Merge branch 'main' into install-guide-mcp

This commit is contained in:
uinstinct 2025-09-18 11:43:58 +05:30
commit ffcb52f7d2
125 changed files with 3698 additions and 844 deletions

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
uses: continuedev/continue/actions/detailed-review@8373ac24010df1110cd00512f925b63813362da1
uses: continuedev/continue/actions/detailed-review@3ebd8232440080aa8891909753f69d75a87b2c86
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@8373ac24010df1110cd00512f925b63813362da1
uses: continuedev/continue/actions/general-review@3ebd8232440080aa8891909753f69d75a87b2c86
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"

View file

@ -84,6 +84,9 @@ jobs:
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
gui-checks:
runs-on: ubuntu-latest
@ -217,6 +220,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest

View file

@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -23,4 +23,7 @@ jobs:
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -32,6 +32,10 @@ on:
required: false
VOYAGE_API_KEY:
required: false
RELACE_API_KEY:
required: false
INCEPTION_API_KEY:
required: false
permissions:
contents: write
@ -77,6 +81,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
- name: Release
env:

View file

@ -56,6 +56,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -215,8 +215,8 @@ function applyRequestOptionsToModels(
// Prepare models
for (const model of models) {
model.requestOptions = {
...model.requestOptions,
...config.requestOptions,
...model.requestOptions,
};
if (roles !== undefined) {
model.roles = model.roles ?? roles;
@ -545,6 +545,7 @@ async function intermediateToFinalConfig({
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
@ -555,6 +556,7 @@ async function intermediateToFinalConfig({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
requestOptions: config.requestOptions,
}),
),
false,

View file

@ -187,7 +187,6 @@ export default async function doLoadConfig(options: {
const mcpManager = MCPManagerSingleton.getInstance();
const mcpServerStatuses = mcpManager.getStatuses();
// Slightly hacky just need connection's client to make slash command for now
const serializableStatuses = mcpServerStatuses.map((server) => {
const { client, ...rest } = server;
return rest;

View file

@ -4,6 +4,7 @@ import {
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
mergeConfigYamlRequestOptions,
mergeUnrolledAssistants,
ModelRole,
PackageIdentifier,
@ -34,10 +35,7 @@ import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
import {
convertYamlMcpToContinueMcp,
convertYamlRuleToContinueRule,
} from "./yamlToContinueConfig";
import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig";
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
@ -155,16 +153,15 @@ async function loadConfigYaml(options: {
};
}
async function configYamlToContinueConfig(options: {
export async function configYamlToContinueConfig(options: {
config: AssistantUnrolled;
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
let { config, ide, ideInfo, uniqueId, llmLogger } = options;
const localErrors: ConfigValidationError[] = [];
@ -192,6 +189,7 @@ async function configYamlToContinueConfig(options: {
summarize: null,
},
rules: [],
requestOptions: { ...config.requestOptions },
};
// Right now, if there are any missing packages in the config, then we will just throw an error
@ -226,7 +224,13 @@ async function configYamlToContinueConfig(options: {
}
}
continueConfig.data = config.data;
continueConfig.data = config.data?.map((d) => ({
...d,
requestOptions: mergeConfigYamlRequestOptions(
d.requestOptions,
continueConfig.requestOptions,
),
}));
continueConfig.docs = config.docs?.map((doc) => ({
title: doc.name,
startUrl: doc.startUrl,
@ -250,12 +254,6 @@ async function configYamlToContinueConfig(options: {
});
});
continueConfig.experimental = {
modelContextProtocolServers: config.mcpServers?.map(
convertYamlMcpToContinueMcp,
),
};
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
@ -307,9 +305,7 @@ async function configYamlToContinueConfig(options: {
try {
const llms = await llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config: continueConfig,
});
@ -394,6 +390,7 @@ async function configYamlToContinueConfig(options: {
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
@ -406,6 +403,10 @@ async function configYamlToContinueConfig(options: {
transport: {
type: "stdio",
args: [],
requestOptions: mergeConfigYamlRequestOptions(
server.requestOptions,
config.requestOptions,
),
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
@ -464,7 +465,6 @@ export async function loadContinueConfigFromYaml(options: {
await configYamlToContinueConfig({
config: configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,

View file

@ -1,12 +1,9 @@
import { ModelConfig } from "@continuedev/config-yaml";
import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
LLMOptions,
} from "../..";
mergeConfigYamlRequestOptions,
ModelConfig,
} from "@continuedev/config-yaml";
import { ContinueConfig, ILLMLogger, LLMOptions } from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
@ -29,14 +26,12 @@ function getModelClass(
async function modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
llmLogger,
config,
isFromAutoDetect,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
isFromAutoDetect?: boolean;
@ -49,6 +44,11 @@ async function modelConfigToBaseLLM({
const { capabilities, ...rest } = model;
const mergedRequestOptions = mergeConfigYamlRequestOptions(
rest.requestOptions,
config.requestOptions,
);
let options: LLMOptions = {
...rest,
contextLength: model.defaultCompletionOptions?.contextLength,
@ -74,6 +74,7 @@ async function modelConfigToBaseLLM({
},
autocompleteOptions: model.autocompleteOptions,
isFromAutoDetect,
requestOptions: mergedRequestOptions,
};
// Model capabilities - need to be undefined if not found
@ -154,17 +155,13 @@ async function modelConfigToBaseLLM({
async function autodetectModels({
llm,
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
llm: BaseLLM;
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
@ -183,7 +180,6 @@ async function autodetectModels({
name: modelName,
},
uniqueId,
ideSettings,
llmLogger,
config,
isFromAutoDetect: true,
@ -199,23 +195,18 @@ async function autodetectModels({
export async function llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
llmLogger,
config,
});
@ -227,9 +218,7 @@ export async function llmsFromModelConfig({
const models = await autodetectModels({
llm: baseLlm,
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
});

View file

@ -0,0 +1,355 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ContinueConfig, ILLMLogger } from "../..";
import { llmsFromModelConfig } from "./models";
// Mock the LLM classes
vi.mock("../../llm/llms", () => ({
LLMClasses: [
class MockOpenAI {
static providerName = "openai";
static defaultOptions = {
completionOptions: {
maxTokens: 2048,
},
};
constructor(options: any) {
Object.assign(this, options);
}
async listModels() {
return ["gpt-4", "gpt-3.5-turbo"];
}
},
class MockAnthropic {
static providerName = "anthropic";
static defaultOptions = {
completionOptions: {
maxTokens: 4096,
},
};
constructor(options: any) {
Object.assign(this, options);
}
async listModels() {
return ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307"];
}
},
],
}));
describe("llmsFromModelConfig requestOptions merging", () => {
let mockLLMLogger: ILLMLogger;
let mockConfig: ContinueConfig;
beforeEach(() => {
mockLLMLogger = { log: vi.fn() } as any;
mockConfig = {
requestOptions: {
timeout: 30000,
headers: {
"User-Agent": "Continue/1.0.0",
},
proxy: "global-proxy",
},
contextProviders: [],
mcpServerStatuses: [],
rules: [],
selectedModelByRole: {
apply: null,
autocomplete: null,
chat: null,
edit: null,
embed: null,
rerank: null,
summarize: null,
},
modelsByRole: {
apply: [],
autocomplete: [],
chat: [],
edit: [],
embed: [],
rerank: [],
summarize: [],
},
slashCommands: [],
tools: [],
allowAnonymousTelemetry: false,
} as ContinueConfig;
vi.clearAllMocks();
});
it("should merge model requestOptions with config requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 60000,
headers: {
Authorization: "Bearer token123",
},
proxy: "model-proxy",
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have merged requestOptions
expect(llm.requestOptions).toEqual({
timeout: 60000, // model-specific takes precedence
headers: {
"User-Agent": "Continue/1.0.0", // from global request options
Authorization: "Bearer token123", // from model
},
proxy: "model-proxy", // model-specific takes precedence
});
});
it("should use config requestOptions when model has no requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
// no requestOptions
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have config requestOptions
expect(llm.requestOptions).toEqual(mockConfig.requestOptions);
});
it("should use model requestOptions when config has no requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 45000,
headers: {
"API-Key": "secret",
},
},
};
const configWithoutOptions = { ...mockConfig };
delete configWithoutOptions.requestOptions;
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithoutOptions,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have model requestOptions
expect(llm.requestOptions).toEqual(model.requestOptions);
});
it("should handle empty headers correctly in merge", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 60000,
headers: {},
},
};
const configWithEmptyHeaders = {
...mockConfig,
requestOptions: {
...mockConfig.requestOptions!,
headers: {},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithEmptyHeaders,
});
expect(result).toHaveLength(1);
const llm = result[0];
// When headers merge to empty object, they should be undefined
expect(llm.requestOptions).toEqual({
timeout: 60000,
proxy: "global-proxy",
headers: undefined,
});
});
it("should handle autodetect models with merged requestOptions", async () => {
const model: ModelConfig = {
name: "autodetect-openai",
provider: "openai",
model: "AUTODETECT",
requestOptions: {
timeout: 120000,
headers: {
"X-Custom": "autodetect",
},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
// Should return multiple models from listModels()
expect(result.length).toBeGreaterThan(0);
// Each detected model should have the merged requestOptions
result.forEach((llm) => {
expect(llm.requestOptions).toEqual({
timeout: 120000, // model-specific takes precedence
headers: {
"User-Agent": "Continue/1.0.0", // from global request options
"X-Custom": "autodetect", // from model
},
proxy: "global-proxy", // from global request options
});
});
});
it("should handle unknown provider gracefully", async () => {
const model: ModelConfig = {
name: "unknown-provider",
provider: "unknown",
model: "unknown-model",
requestOptions: {
timeout: 60000,
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
// Should return empty array for unknown provider
expect(result).toHaveLength(0);
});
it("should preserve other model properties while merging requestOptions", async () => {
const model: ModelConfig = {
name: "test-anthropic",
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
roles: ["chat", "summarize"],
capabilities: ["tool_use", "image_input"],
defaultCompletionOptions: {
temperature: 0.7,
maxTokens: 1000,
},
requestOptions: {
timeout: 90000,
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// Should preserve model properties
expect(llm.title).toBe("test-anthropic");
expect(llm.completionOptions?.temperature).toBe(0.7);
expect(llm.completionOptions?.maxTokens).toBe(1000);
expect(llm.capabilities?.tools).toBe(true);
expect(llm.capabilities?.uploadImage).toBe(true);
// Should have merged requestOptions
expect(llm.requestOptions).toEqual({
timeout: 90000,
headers: {
"User-Agent": "Continue/1.0.0",
},
proxy: "global-proxy",
});
});
it("should handle complex header merging scenarios", async () => {
const model: ModelConfig = {
name: "complex-headers",
provider: "openai",
model: "gpt-4",
requestOptions: {
headers: {
Authorization: "Bearer model-token",
Accept: "application/json", // Should override config Accept
"X-Model-Specific": "true",
},
},
};
const configWithMoreHeaders = {
...mockConfig,
requestOptions: {
...mockConfig.requestOptions!,
headers: {
...mockConfig.requestOptions!.headers,
Accept: "text/plain", // Should be overridden by model
"Cache-Control": "no-cache",
},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithMoreHeaders,
});
expect(result).toHaveLength(1);
const llm = result[0];
expect(llm.requestOptions?.headers).toEqual({
"User-Agent": "Continue/1.0.0", // from global request options
"Cache-Control": "no-cache", // from global request options
Authorization: "Bearer model-token", // from model
Accept: "application/json", // from model (overrides config)
"X-Model-Specific": "true", // from model
});
});
});

View file

@ -18,6 +18,7 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
import Lemonade from "./llm/llms/Lemonade";
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
import { callTool } from "./tools/callTool";
@ -1263,6 +1264,9 @@ export class Core {
if (msg.data.title === "Ollama") {
const models = await new Ollama({ model: "" }).listModels();
return models;
} else if (msg.data.title === "Lemonade") {
const models = await new Lemonade({ model: "" }).listModels();
return models;
} else {
return undefined;
}
@ -1348,6 +1352,8 @@ export class Core {
selectedCode,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
// Important note: context providers fetch uses global request options not LLM request options
// Because LLM calls are handled separately
fetchwithRequestOptions(url, init, config.requestOptions),
isInAgentMode: msg.data.isInAgentMode,
});

2
core/index.d.ts vendored
View file

@ -1099,6 +1099,7 @@ export interface Tool {
exampleArgs?: Array<[string, string | number]>;
};
defaultToolPolicy?: ToolPolicy;
toolCallIcon?: string;
evaluateToolCallPolicy?: (
basePolicy: ToolPolicy,
parsedArgs: Record<string, unknown>,
@ -1281,6 +1282,7 @@ export interface MCPOptions {
transport: TransportOptions;
faviconUrl?: string;
timeout?: number;
requestOptions?: RequestOptions;
}
export type MCPConnectionStatus =

View file

@ -203,6 +203,13 @@ export const DEFAULT_IGNORE_DIRS = [
...ADDITIONAL_INDEXING_IGNORE_DIRS,
];
export const DEFAULT_IGNORES = [
...DEFAULT_IGNORE_FILETYPES,
...DEFAULT_IGNORE_DIRS,
];
export const defaultIgnoresGlob = `!{${DEFAULT_IGNORES.join(",")}}`;
// Create ignore instances
export const defaultSecurityIgnoreFile = ignore().add(
DEFAULT_SECURITY_IGNORE_FILETYPES,

View file

@ -45,6 +45,7 @@ import {
const PROVIDER_HANDLES_TEMPLATING: string[] = [
"lmstudio",
"lemonade",
"openai",
"nvidia",
"ollama",
@ -67,6 +68,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
const PROVIDER_SUPPORTS_IMAGES: string[] = [
"openai",
"ollama",
"lemonade",
"cohere",
"gemini",
"msty",

View file

@ -85,7 +85,7 @@ function encodingForModel(modelName: string): Encoding {
function countImageTokens(content: MessagePart): number {
if (content.type === "imageUrl") {
return 85;
return 1024;
}
throw new Error("Non-image content type");
}

View file

@ -30,6 +30,7 @@ import {
TemplateType,
Usage,
} from "../index.js";
import { isLemonadeInstalled } from "../util/lemonadeHelper.js";
import { Logger } from "../util/Logger.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
@ -503,6 +504,24 @@ export abstract class BaseLLM implements ILLM {
: "Unable to connect to local Ollama instance. Ollama may not be installed or may not running.";
throw new Error(message);
}
if (
e.code === "ECONNREFUSED" &&
e.message.includes("http://localhost:8000")
) {
const isInstalled = await isLemonadeInstalled();
let message: string;
if (process.platform === "linux") {
// On Linux, isLemonadeInstalled checks if it's running (via health endpoint)
message =
"Unable to connect to local Lemonade instance. Please ensure Lemonade is running. Visit http://lemonade-server.ai for setup instructions.";
} else {
// On Windows, we can check if it's installed
message = isInstalled
? "Unable to connect to local Lemonade instance. Lemonade server may not be running."
: "Unable to connect to local Lemonade instance. Lemonade may not be installed or may not be running.";
}
throw new Error(message);
}
}
throw e;
}
@ -537,18 +556,14 @@ export abstract class BaseLLM implements ILLM {
}
private _formatChatMessage(msg: ChatMessage): string {
let contentToShow = "";
if (msg.role === "tool") {
contentToShow = msg.content;
} else if (msg.role === "assistant" && msg.toolCalls?.length) {
contentToShow = msg.toolCalls
let contentToShow = renderChatMessage(msg);
if (msg.role === "assistant" && msg.toolCalls?.length) {
contentToShow += msg.toolCalls
?.map(
(toolCall) =>
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
)
.join("\n");
} else if ("content" in msg) {
contentToShow = renderChatMessage(msg);
}
return `<${msg.role}>\n${contentToShow}\n\n`;

View file

@ -68,6 +68,17 @@ class Anthropic extends BaseLLM {
return finalOptions;
}
private buildTextPart(text: string, addCaching: boolean) {
const part: any = {
type: "text",
text,
};
if (addCaching) {
part.cache_control = { type: "ephemeral" };
}
return part;
}
private convertMessage(message: ChatMessage, addCaching: boolean): any {
if (message.role === "tool") {
return {
@ -81,14 +92,30 @@ class Anthropic extends BaseLLM {
],
};
} else if (message.role === "assistant" && message.toolCalls) {
return {
role: "assistant",
content: message.toolCalls.map((toolCall) => ({
const parts: any[] = [];
if (message.content) {
if (typeof message.content === "string") {
parts.push(this.buildTextPart(message.content, addCaching));
} else if (message.content.length > 0) {
const textContent = message.content.filter((p) => p.type === "text");
const textParts = textContent.map((part, idx) => {
const cache = idx === textContent.length - 1 && addCaching;
return this.buildTextPart(part.text, cache);
});
parts.push(...textParts);
}
}
parts.push(
...message.toolCalls.map((toolCall) => ({
type: "tool_use",
id: toolCall.id,
name: toolCall.function?.name,
input: safeParseToolCallArgs(toolCall),
})),
);
return {
role: "assistant",
content: parts,
};
} else if (message.role === "thinking" && !message.redactedThinking) {
return {
@ -154,9 +181,7 @@ class Anthropic extends BaseLLM {
public convertMessages(msgs: ChatMessage[]): any[] {
// should be public for use within VertexAI
const filteredmessages = msgs.filter(
(m) => m.role !== "system" && !!m.content,
);
const filteredmessages = msgs.filter((m) => m.role !== "system");
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1)

12
core/llm/llms/Lemonade.ts Normal file
View file

@ -0,0 +1,12 @@
import { LLMOptions } from "../../index.js";
import OpenAI from "./OpenAI.js";
class Lemonade extends OpenAI {
static providerName = "lemonade";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:8000/api/v1/",
};
}
export default Lemonade;

View file

@ -269,6 +269,11 @@ class Ollama extends BaseLLM implements ModelInstaller {
return this.modelMap[this.model] ?? this.model;
}
get contextLength() {
const DEFAULT_OLLAMA_CONTEXT_LENGTH = 8192; // twice of https://github.com/ollama/ollama/blob/29ddfc2cab7f5a83a96c3133094f67b22e4f27d1/envconfig/config.go#L185
return this._contextLength ?? DEFAULT_OLLAMA_CONTEXT_LENGTH;
}
private _getModelFileParams(
options: CompletionOptions,
): OllamaModelFileParams {

View file

@ -174,7 +174,7 @@ class OpenAI extends BaseLLM {
protected _getHeaders() {
return {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
...(this.apiKey && { Authorization: `Bearer ${this.apiKey}` }),
"api-key": this.apiKey ?? "", // For Azure
};
}

View file

@ -33,6 +33,7 @@ import Kindo from "./Kindo";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import LlamaStack from "./LlamaStack";
import Lemonade from "./Lemonade";
import LMStudio from "./LMStudio";
import Mistral from "./Mistral";
import MockLLM from "./Mock";
@ -82,6 +83,7 @@ export const LLMClasses = [
LlamaCpp,
OpenAI,
OVHcloud,
Lemonade,
LMStudio,
Mistral,
Bedrock,

View file

@ -95,7 +95,7 @@ export async function* llmStreamChat(
...init,
signal: abortController.signal,
},
config.requestOptions,
model.requestOptions,
),
completionOptions,
abortController,

View file

@ -374,9 +374,8 @@ export function isRecommendedAgentModel(modelName: string): boolean {
[/o[134]/],
[/deepseek/, /r1|reasoner/],
[/gemini/, /2\.5/, /pro/],
[/gpt/, /4/],
[/gpt-5/],
[/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
[/claude/, /sonnet/, /3\.7|3-7|-4/],
[/claude/, /opus/, /-4/],
];
for (const combo of recs) {

24
core/package-lock.json generated
View file

@ -152,10 +152,10 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.96",
"version": "1.14.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
@ -179,17 +179,22 @@
},
"../packages/fetch": {
"name": "@continuedev/fetch",
"version": "1.0.16",
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/follow-redirects": "^1.14.4",
"semantic-release": "^21.1.2",
"typescript": "^5.0.0",
"vitest": "^3.2.0"
}
@ -199,20 +204,25 @@
"version": "1.0.9",
"license": "Apache-2.0",
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/node": "^22.15.29",
"semantic-release": "^21.1.2",
"typescript": "^5.5.2"
}
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
"version": "1.5.1",
"version": "1.14.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.14",
"@continuedev/config-yaml": "^1.8.0",
"@continuedev/fetch": "^1.0.16",
"@continuedev/config-yaml": "^1.14.0",
"@continuedev/fetch": "^1.1.0",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",

View file

@ -84,4 +84,5 @@ For example:`,
["alwaysApply", "false"],
],
},
toolCallIcon: "PencilIcon",
};

View file

@ -30,4 +30,5 @@ export const fetchUrlContentTool: Tool = {
prefix: `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,
exampleArgs: [["url", "https://example.com"]],
},
toolCallIcon: "GlobeAltIcon",
};

View file

@ -13,7 +13,7 @@ export const globSearchTool: Tool = {
function: {
name: BuiltInToolNames.FileGlobSearch,
description:
"Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns",
"Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Will not show many build, cache, secrets dirs/files (can use ls tool instead). Output may be truncated; use targeted patterns",
parameters: {
type: "object",
required: ["pattern"],
@ -30,4 +30,5 @@ export const globSearchTool: Tool = {
prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
exampleArgs: [["pattern", "*.py"]],
},
toolCallIcon: "MagnifyingGlassIcon",
};

View file

@ -13,7 +13,7 @@ export const grepSearchTool: Tool = {
function: {
name: BuiltInToolNames.GrepSearch,
description:
"Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries",
"Perform a search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries",
parameters: {
type: "object",
required: ["query"],
@ -31,4 +31,5 @@ export const grepSearchTool: Tool = {
prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
exampleArgs: [["query", ".*main_services.*"]],
},
toolCallIcon: "MagnifyingGlassIcon",
};

View file

@ -38,4 +38,5 @@ export const lsTool: Tool = {
["recursive", "false"],
],
},
toolCallIcon: "FolderIcon",
};

View file

@ -24,4 +24,5 @@ export const readCurrentlyOpenFileTool: Tool = {
prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
If the user is asking about a file and you don't see any code, use this to check the current file`,
},
toolCallIcon: "DocumentTextIcon",
};

View file

@ -31,4 +31,5 @@ export const readFileTool: Tool = {
exampleArgs: [["filepath", "path/to/the_file.txt"]],
},
defaultToolPolicy: "allowedWithoutPermission",
toolCallIcon: "DocumentIcon",
};

View file

@ -48,4 +48,5 @@ export const readFileRangeTool: Tool = {
],
},
defaultToolPolicy: "allowedWithoutPermission",
toolCallIcon: "DocumentIcon",
};

View file

@ -30,4 +30,5 @@ export const searchWebTool: Tool = {
prefix: `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,
exampleArgs: [["query", "What is the current weather in San Francisco?"]],
},
toolCallIcon: "GlobeAltIcon",
};

View file

@ -23,4 +23,5 @@ export const viewDiffTool: Tool = {
prefix: `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,
},
defaultToolPolicy: "allowedWithoutPermission",
toolCallIcon: "CodeBracketIcon",
};

View file

@ -23,4 +23,5 @@ export const viewRepoMapTool: Tool = {
prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
},
defaultToolPolicy: "allowedWithPermission",
toolCallIcon: "MapIcon",
};

View file

@ -30,4 +30,5 @@ export const viewSubdirectoryTool: Tool = {
exampleArgs: [["directory_path", "path/to/subdirectory"]],
},
defaultToolPolicy: "allowedWithPermission",
toolCallIcon: "FolderOpenIcon",
};

View file

@ -1,10 +1,10 @@
import { ConfigDependentToolParams, Tool } from "..";
import { isRecommendedAgentModel } from "../llm/toolSupport";
import * as toolDefinitions from "./definitions";
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
export const getBaseToolDefinitions = () => [
toolDefinitions.readFileTool,
toolDefinitions.createNewFileTool,
toolDefinitions.runTerminalCommandTool,
toolDefinitions.globSearchTool,
@ -13,7 +13,6 @@ export const getBaseToolDefinitions = () => [
toolDefinitions.lsTool,
toolDefinitions.createRuleBlock,
toolDefinitions.fetchUrlContentTool,
toolDefinitions.singleFindAndReplaceTool,
];
export const getConfigDependentToolDefinitions = (
@ -38,10 +37,11 @@ export const getConfigDependentToolDefinitions = (
);
}
if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
if (modelName && isRecommendedAgentModel(modelName)) {
tools.push(toolDefinitions.multiEditTool);
} else {
tools.push(toolDefinitions.editFileTool);
tools.push(toolDefinitions.singleFindAndReplaceTool);
}
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269

View file

@ -44,9 +44,8 @@ export type GlobalContextType = {
isSupportedLanceDbCpuTargetForLinux: boolean;
sharedConfig: SharedConfigSchema;
failedDocs: SiteIndexingConfig[];
shownDeprecatedProviderWarnings: {
[providerTitle: string]: boolean;
};
shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean };
autoUpdateCli: boolean;
mcpOauthStorage: {
[serverUrl: string]: {
clientInformation?: OAuthClientInformationFull;
@ -66,16 +65,7 @@ export class GlobalContext {
) {
const filepath = getGlobalContextFilePath();
if (!fs.existsSync(filepath)) {
fs.writeFileSync(
filepath,
JSON.stringify(
{
[key]: value,
},
null,
2,
),
);
fs.writeFileSync(filepath, JSON.stringify({ [key]: value }, null, 2));
} else {
const data = fs.readFileSync(filepath, "utf-8");
@ -113,10 +103,7 @@ export class GlobalContext {
}
// Recreate the file with salvaged values plus the new value
const newData = {
...salvaged,
[key]: value,
};
const newData = { ...salvaged, [key]: value };
fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
return;
@ -174,10 +161,7 @@ export class GlobalContext {
newValues: Partial<SharedConfigSchema>,
): SharedConfigSchema {
const currentSharedConfig = this.getSharedConfig();
const updatedSharedConfig = {
...currentSharedConfig,
...newValues,
};
const updatedSharedConfig = { ...currentSharedConfig, ...newValues };
this.update("sharedConfig", updatedSharedConfig);
return updatedSharedConfig;
}
@ -189,10 +173,7 @@ export class GlobalContext {
): GlobalContextModelSelections {
const currentSelections = this.get("selectedModelsByProfileId") ?? {};
const forProfile = currentSelections[profileId] ?? {};
const newSelections = {
...forProfile,
[role]: title,
};
const newSelections = { ...forProfile, [role]: title };
this.update("selectedModelsByProfileId", {
...currentSelections,

View file

@ -0,0 +1,59 @@
import { exec } from "node:child_process";
import { IDE } from "..";
export async function isLemonadeInstalled(): Promise<boolean> {
// On Windows, check if lemonade-server command exists
if (process.platform === "win32") {
return new Promise((resolve, _reject) => {
exec("where.exe lemonade-server", (error, _stdout, _stderr) => {
resolve(!error);
});
});
}
// On Linux, check if the health endpoint is accessible
try {
const response = await fetch("http://localhost:8000/api/v1/health", {
method: "GET",
signal: AbortSignal.timeout(3000), // 3 second timeout
});
if (response.ok) {
const data = await response.json();
return data.status === "ok";
}
return false;
} catch {
return false;
}
}
export async function startLocalLemonade(ide: IDE): Promise<any> {
let startCommand: string | undefined;
switch (process.platform) {
case "linux": // Linux
// On Linux, direct users to start Lemonade manually
return ide.showToast(
"info",
"Please start Lemonade manually. Visit https://lemonade-server.ai for instructions.",
);
case "win32": // Windows
startCommand = "lemonade-server serve\n";
break;
default:
return ide.showToast(
"error",
"Cannot start Lemonade: platform not supported!",
);
}
if (startCommand) {
return ide.runCommand(startCommand, {
reuseTerminal: true,
terminalName: "Start Lemonade",
});
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 144 KiB

After

Width:  |  Height:  |  Size: 265 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

View file

@ -0,0 +1,81 @@
---
title: "Lemonade Server"
description: "Configure Lemonade Server with Continue for refreshingly fast local LLM inference on GPUs and NPUs"
---
<Info>
Get started with [Lemonade Server](https://lemonade-server.ai/) - Refreshingly fast LLMs on GPUs and NPUs with seamless Continue integration
</Info>
## Overview
Lemonade Server provides optimized local LLM inference with support for GPU and NPU hardware acceleration. It offers an OpenAI-compatible API that seamlessly integrates with Continue and other open-source platforms.
## Installation
Download and install Lemonade Server from [lemonade-server.ai](https://lemonade-server.ai/).
## Configuration
Lemonade Server is available directly in the Continue UI as a provider. You can select it from the model provider dropdown without manual configuration.
### Option 1: Using the Continue UI (Recommended)
1. Click on the model selector dropdown in Continue
2. Select "Add Model"
3. Choose "Lemonade Server" from the provider list
4. Continue will automatically configure the connection
### Option 2: Manual Configuration
If you need custom settings, you can manually configure Lemonade:
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Lemonade
provider: lemonade
model: <MODEL_NAME>
apiBase: http://localhost:8000/api/v1/
```
</Tab>
<Tab title="JSON (Deprecated)">
```json title="config.json"
{
"models": [
{
"title": "Lemonade",
"provider": "lemonade",
"model": "<MODEL_NAME>",
"apiBase": "http://localhost:8000/api/v1/"
}
]
}
```
</Tab>
</Tabs>
## Getting Started
1. **Install Lemonade Server**: Download from [lemonade-server.ai](https://lemonade-server.ai/)
2. **Start the server**: Launch Lemonade Server (runs on `http://localhost:8000/api/v1/` by default)
3. **Add to Continue**: Select Lemonade Server from the model provider dropdown in Continue
4. **Load a model**: Choose your preferred model through the interface
## Hardware Support
Lemonade Server automatically detects and optimizes for available hardware:
- **NPU**: Neural Processing Unit acceleration for efficient inference
- **GPU**: Full GPU acceleration support
- **CPU**: Optimized CPU fallback when accelerators are unavailable
## Key Features
- OpenAI-compatible API for seamless integration
- Support for popular model formats
- Automatic hardware detection and optimization
- Integration with Continue, Open WebUI, Gaia, and AnythingLLM
- Active open-source community
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Lemonade.ts)

View file

@ -3,81 +3,250 @@ title: "Tetrate Agent Router Service"
sidebarTitle: "Tetrate Agent Router Service"
slug: ../tetrate-agent-router-service
---
The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities as well as embedding services.
The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities.
This gateway acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization.
## Getting Started
<Tip>
Want to get started quickly? Sign up for the [Tetrate Agent Router Service](https://router.tetrate.ai/) to get an API key, then use [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) to get started fast.
</Tip>
1. Obtain an API key from the [Agent Router Service portal](https://api.router.tetrate.ai/)
2. Configure Continue to use Agent Router Service as your model provider
## Setup
## Configuring Models
<Steps>
<Step title="Sign in or sign up">
Visit the [Agent Router Service portal](https://router.tetrate.ai/) and create an account to get your API key
<img src="../assets/tetrate-sign-in.png" alt="Tetrate sign in page" style={{width: '250px', maxWidth: '100%'}} />
</Step>
You can also quickly use models from Tetrate on the Cotninue Hub by visiting Tetrate on the Continue Hub [here](https://hub.continue.dev/tetrate). The easiest way if you don't see the model you want to use is to remix one of the models on the Tetrate page and change the model to the one you want to use.
<Step title="Get your API key">
Go to the [API keys page](https://router.tetrate.ai/api-keys) to get your key
<img src="../assets/tetrate-get-api-key.png" alt="Tetrate get API key" style={{width: '250px', maxWidth: '100%'}} />
</Step>
<Step title="Configure Continue">
- Choose a configuration method below.
- If you use the Continue VS Code extension, install version `>=1.2.3`.
</Step>
</Steps>
### Quickstart with Continue Hub
Fastest way: use preconfigured models from Tetrate on Continue Hub
<Steps>
<Step title="Browse models">
Open [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) and pick a model (e.g., [Claude Sonnet 4](https://hub.continue.dev/tetrate/claude-sonnet-4))
</Step>
<Step title="Use or remix">
Click "Use Model", or "Remix" to change the model ID if needed
</Step>
<Step title="Add your API key">
Add your API key to Continue. See [adding secrets in Continue Hub](/hub/secrets/secret-types) and [managing local secrets in the FAQ](/faqs#managing-local-secrets-and-environment-variables)
<Tip>
Add it as a Continue Hub secret named `TETRATE_API_KEY` to reuse across projects.
</Tip>
</Step>
</Steps>
![Remix a model from Tetrate on Continue Hub](../assets/tetrate-remix.png)
### Available Models
<Info>
If a model is missing, remix a similar one and set the `model` field to the target ID.
</Info>
Agent Router Service supports routing to various models.
Go to the [Agent Router Service model catalog](https://router.tetrate.ai/models) for a full list of supported models.
### Configuration Methods
## Configuration Options
<CardGroup cols={1}>
<Card title="In Local Agent Configuration" icon="folder" vertical>
Use a Tetrate model block from the Hub or define it directly in your local agent configuration.
</Card>
<Card title="Continue Hub" icon="cloud" vertical>
Use a Tetrate model block from the Hub or define your own on the Hub.
</Card>
<Card title="Using Local Model Blocks" icon="file-lines" vertical>
Create a local model block for reuse across agents without publishing it to the Hub.
</Card>
</CardGroup>
As Agent Router Service is an OpenAI API compatible provider, you can configure it like any other OpenAI API compatible provider. Therefore you will be setting `provider: openai` and `apiBase: https://api.router.tetrate.ai/v1`.
Update your Continue configuration file (`~/.continue/config.yaml`) with your Agent Router Service API key:
### Configuration Examples
<Info>
**Click a tab** to see an example.
</Info>
<Tabs>
<Tab title="In Local Agent Configuration">
### On your local machine
**When to use**: Simple local setups (like using the VS Code extension) when you don't need shared or published blocks.
#### In your config.yaml
Use a Tetrate model block from the Hub in your local agent configuration:
```yaml title="config.yaml"
```yaml title="~/.continue/config.yaml"
name: Local Agent
version: 1.0.0
schema: v1
models:
- name: <MODEL_NAME>
provider: openai
model: <MODEL_ID>
apiKey: <TETRATE_API_KEY>
apiBase: https://api.router.tetrate.ai/v1
- uses: tetrate/claude-sonnet-4
with:
TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
context:
- provider: code
- provider: docs
- provider: diff
- provider: terminal
- provider: problems
- provider: folder
- provider: codebase
```
#### As a local model block
Or define the model directly:
Review the configuration reference for [model blocks](/reference#models) and using [local blocks](/reference#local-blocks). Ensure you look at the roles and capabilities section and review the [model capabilities guide](/customize/deep-dives/model-capabilities).
```yaml title="~/.continue/config.yaml"
name: Local Agent
version: 1.0.0
schema: v1
models:
- name: Claude Sonnet 4
provider: tars
model: claude-4-sonnet-20250514
apiKey: ${{ secrets.TETRATE_API_KEY }}
roles:
- chat
- edit
- apply
capabilities:
- tool_use
context:
- provider: code
- provider: docs
- provider: diff
- provider: terminal
- provider: problems
- provider: folder
- provider: codebase
```
</Tab>
<Tab title="Continue Hub">
**When to use**: Share configurations across teams or contribute to the community.
```yaml title="model_name.yaml"
name: <MODEL_NAME>
models:
- name: <MODEL_NAME>
provider: openai
model: <MODEL_ID>
apiKey: ${{ inputs.TETRATE_API_KEY }}
apiBase: https://api.router.tetrate.ai/v1
roles:
- chat
- edit
- apply
capabilities:
- tool_use
**The Model Block:**
```yaml title="tetrate/claude-sonnet-4"
name: Claude Sonnet 4
version: 1.0.14
schema: v1
models:
- name: Claude Sonnet 4 - Tetrate
provider: tars
model: claude-4-sonnet-20250514
apiKey: ${{ inputs.TETRATE_API_KEY }}
roles:
- chat
- edit
- apply
capabilities:
- tool_use
```
View the model block `tetrate/claude-sonnet-4` on the [Continue Hub](https://hub.continue.dev/tetrate/claude-sonnet-4).
**Reference it in your Agent configuration:**
```yaml title="my-agent"
name: My Agent
version: 1.0.0
schema: v1
models:
- uses: tetrate/claude-sonnet-4
with:
TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
context:
- uses: continuedev/diff-context
- uses: continuedev/terminal-context
- uses: continuedev/file-context
```
<Tip>
To customize, see the [model block creation guide](/hub/blocks/create-a-block).
</Tip>
</Tab>
<Tab title="Using Local Model Blocks">
**When to use**: Reuse configurations across agents and keep them local or in GitHub (not on Continue Hub).
**The Local Model Block:**
<Info>
Name the file `my-claude-4-model.yaml` so you can reference it in the Agent.
</Info>
```yaml title="~/.continue/models/my-claude-4-model.yaml"
name: Claude Sonnet 4
version: 1.0.1
schema: v1
models:
- name: Claude Sonnet 4
provider: tars
model: claude-4-sonnet-20250514
apiKey: ${{ inputs.TETRATE_API_KEY }}
roles:
- chat
- edit
- apply
capabilities:
- tool_use
```
Reference it as `my-claude-4-model` in your Agent configuration:
```yaml title="~/.continue/agents/simple-agent.yaml"
name: Simple Agent
version: 1.0.0
schema: v1
models:
- uses: my-claude-4-model
with:
TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
context:
- uses: continuedev/diff-context
- uses: continuedev/terminal-context
- uses: continuedev/file-context
```
### On Model Block on Continue Hub
Learn how to use model blocks on Continue Hub [here](/hub/blocks/create-a-block).
<Tip>
Learn more about [model blocks](/reference#models) and [local blocks](/reference#local-blocks).
</Tip>
```yaml title="model_name.yaml"
name: <MODEL_NAME>
models:
- name: <MODEL_NAME>
provider: openai
model: <MODEL_ID>
apiKey: ${{ inputs.TETRATE_API_KEY }}
apiBase: https://api.router.tetrate.ai/v1
roles:
- chat
- edit
- apply
capabilities:
- tool_use
```
</Tab>
</Tabs>
---
## Troubleshooting Common Issues
<CardGroup cols={2}>
<Card title="Invalid API key" icon="key" vertical>
Verify your API key is active and has no extra spaces.
</Card>
<Card title="Model not found" icon="ban" href="https://router.tetrate.ai/models" vertical>
Confirm the model ID matches the Tetrate catalog.
</Card>
<Card title="Slow responses" icon="code" vertical>
Check your network or try a less-loaded model. Contact Tetrate support if issues persist.
</Card>
<Card title="Configuration not loading" icon="file-lines" vertical>
Validate YAML syntax and review error messages in Continue. If using Hub, ensure the block is published.
</Card>
</CardGroup>
---
## Join the Community
Connect with Tetrate and other builders for help and discussion.
<CardGroup cols={1}>
<Card title="Join the Tetrate Community" icon="slack" href="https://join.slack.com/t/tetrate-agent-router/shared_invite/zt-399tv7hjm-6YMXztGywTOQrMIolvEBNg">
Get answers, insights, and best practices for secure, scalable infrastructure
</Card>
</CardGroup>

View file

@ -233,6 +233,7 @@
"guides/codebase-documentation-awareness",
"guides/cli",
"guides/continuous-ai",
"guides/posthog-github-continuous-ai",
"guides/continuous-ai-readiness-assessment",
"guides/plan-mode-guide",
"guides/ollama-guide",
@ -354,10 +355,6 @@
"source": "/hub/blocks",
"destination": "/hub/blocks/intro"
},
{
"source": "/hub/agents/intro",
"destination": "/hub/agents/intro"
},
{
"source": "/customize",
"destination": "/customization/overview"

View file

@ -14,6 +14,7 @@ description: "Comprehensive collection of practical guides for Continue includin
- [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows
- [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue
- [Continuous AI Readiness Assessment](/guides/continuous-ai-readiness-assessment) - Evaluate team readiness for Continuous AI adoption
- [PostHog Session Analysis with Continue CLI](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation
## What Advanced Tutorials Are Available

View file

@ -0,0 +1,496 @@
---
title: "Building a Continuous AI Workflow with PostHog and GitHub"
description: "Build an automated system that continuously monitors PostHog session recordings, analyzes UX issues using Continue CLI, and creates GitHub issues automatically."
sidebarTitle: "PostHog Session Analysis with Continue CLI"
---
<Card title="What You'll Build" icon="robot">
A fully automated workflow that uses Continue CLI to fetch PostHog session
data, analyze user experience issues with AI, and automatically create GitHub
issues with specific technical recommendations
</Card>
## Prerequisites
Before starting, ensure you have:
- GitHub repository where you want to create issues
- PostHog account with **[session recordings enabled and collecting data](https://posthog.com/docs/session-replay/installation)**
- Node.js 18+ installed locally
- Continue CLI account with **active credits** (required for API usage)
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
</Step>
<Step title="Set up Continue CLI Account & API Key">
1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations)
2. Sign up or log in to your Continue account
3. Navigate to your organization settings
4. Click **"API Keys"** and then **"+ New API Key"**
5. Copy the API key immediately (you won't see it again!)
6. Login to the CLI: `cn login`
</Step>
<Step title="Add Required Secrets to Continue CLI">
Continue CLI will securely store your API keys as secrets that can be referenced in prompts.
</Step>
</Steps>
<Tip>
Continue CLI handles all the complex API interactions - you just need to
provide the right prompts!
</Tip>
## Step 1: Set Up Your Credentials
First, you'll need to gather your API credentials and add them as secrets in Continue CLI.
### Get Your PostHog API Credentials
You need a **Personal API Key** (not a Project API key) to access session recordings:
1. Go to [Personal API Keys](https://app.posthog.com/settings/user-api-keys) in PostHog
2. Click **+ Create a personal API Key**
3. Name it "Continue CLI Session Analysis"
4. Select these scopes:
- `session_recording:read` - **Required** for accessing session data
- `insight:read` - Optional, for additional analytics
5. Copy the key immediately (you won't see it again!)
<Tip>
**Find Your Project Details**: Your Project ID is in your PostHog URL:
`https://app.posthog.com/project/YOUR_PROJECT_ID`
</Tip>
### Get Your GitHub Personal Access Token
1. Go to [GitHub Personal Access Tokens](https://github.com/settings/personal-access-tokens/new)
2. Click **"Generate new token (classic)"**
3. Name it "Continue CLI PostHog Analysis"
4. Select these scopes:
- `repo` (or just `public_repo` if your repository is public)
- `issues:write` - **Required** for creating issues
5. Copy the token immediately
### Add Secrets to Continue CLI
Use Continue CLI's built-in environment setup helper:
```bash
cn -p "Help me set up my environment for PostHog session analysis. Please:
1. Check if I have the required secrets configured in Continue CLI:
- POSTHOG_API_KEY
- POSTHOG_PROJECT_ID
- POSTHOG_HOST
- GITHUB_PAT
2. If any are missing, guide me through:
- How to get PostHog Personal API Key from PostHog settings
- How to find my PostHog Project ID from the URL
- How to create a GitHub Personal Access Token with issues:write permission
- How to add these as secrets in Continue CLI
3. Help me identify my GitHub repository owner and name by:
- Checking git remote origin URL
- Or asking me to provide them
4. Test the API connections by making a simple API call to both PostHog and GitHub to verify the credentials work.
Please walk me through this setup process step by step."
```
<Info>
Continue CLI will guide you through adding secrets and testing your API
connections. Follow the prompts to add: - `POSTHOG_API_KEY`: Your PostHog
Personal API Key - `POSTHOG_PROJECT_ID`: Your PostHog Project ID -
`POSTHOG_HOST`: `https://us.posthog.com` (or your custom PostHog host) -
`GITHUB_PAT`: Your GitHub Personal Access Token
</Info>
## Step 2: Analyze PostHog Sessions with Continue CLI
Now you'll use Continue CLI to fetch PostHog session data and analyze it for UX issues. Continue CLI handles all the API calls and analysis automatically.
### Run the Analysis
Use this prompt with Continue CLI to fetch and analyze your PostHog sessions:
```bash
cn -p "I need you to help me analyze PostHog session recordings to identify UX issues. Please:
1. First, fetch session recordings from PostHog using these details:
- Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from my secrets
- API endpoint: {POSTHOG_HOST}/api/projects/{POSTHOG_PROJECT_ID}/session_recordings/?limit=20
- Include Authorization header: 'Bearer {POSTHOG_API_KEY}'
2. Filter the sessions to find problematic ones with either:
- console_error_count > 0 (JavaScript errors)
- recording_duration > 300 (sessions longer than 5 minutes)
3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems.
4. Format each issue like this:
### 1. **Issue Title Here**
**Problem**: One sentence describing the user problem
**Technical Causes**: Brief technical explanation
**Affected Pages**: List the URLs
**Recommended Fix**:
- Specific action item 1
- Specific action item 2
**Priority**: **HIGH** or **MEDIUM** or **LOW**
**Impact**: Quantify the impact (e.g., 'Affects 80% of sessions')
Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data."
```
<Info>
**What Continue CLI Does:** - Makes authenticated API calls to PostHog using
your stored secrets - Fetches and filters session recordings automatically -
Analyzes patterns in the data using AI - Generates structured issue
descriptions ready for GitHub
</Info>
<Tip>
Save the analysis output to a file by adding `> analysis-results.txt` to the
command if you want to review it later.
</Tip>
## Step 3: Create GitHub Issues Automatically
Now use Continue CLI to create GitHub issues from your analysis results:
```bash
cn -p "I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API.
Use these details from my secrets:
- GITHUB_PAT: My GitHub Personal Access Token
- Repository: Extract from git remote or ask me to specify
For each issue in my analysis:
1. Parse the issue title, body content, and priority level
2. Create a GitHub issue via API POST to: https://api.github.com/repos/{owner}/{repo}/issues
3. Use these headers:
- Authorization: token {GITHUB_PAT}
- Accept: application/vnd.github.v3+json
- Content-Type: application/json
4. Set labels based on priority:
- HIGH: [\"bug\", \"high-priority\", \"user-experience\", \"automated\"]
- MEDIUM: [\"enhancement\", \"medium-priority\", \"user-experience\", \"automated\"]
- LOW: [\"low-priority\", \"user-experience\", \"automated\"]
5. Format the issue title as: \"🔍 UX Issue: {original title}\"
Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs.
"
```
<Warning>
**Repository Labels Required**: Make sure your GitHub repository has these labels:
- `bug`, `enhancement`
- `high-priority`, `medium-priority`, `low-priority`
- `user-experience`, `automated`
Create missing labels in your repo at: **Settings → Labels → New label**
</Warning>
<Info>
**What Continue CLI Does:** - Parses your analysis results automatically -
Makes authenticated GitHub API calls using your stored token - Creates
properly formatted issues with appropriate labels - Checks for duplicate
issues to avoid spam - Provides confirmation with issue URLs
</Info>
## Step 4: Set Up Automated GitHub Actions Workflow
Create a GitHub Actions workflow that runs your Continue CLI analysis automatically on a schedule.
### Add GitHub Secrets
First, add these secrets to your GitHub repository:
1. Go to **Repository Settings → Secrets and variables → Actions**
2. Click **"New repository secret"** and add:
- `CONTINUE_API_KEY`: Your Continue API key from hub.continue.dev
- `POSTHOG_API_KEY`: Your PostHog Personal API Key
- `POSTHOG_PROJECT_ID`: Your PostHog Project ID
- `POSTHOG_HOST`: `https://us.posthog.com` (or your custom PostHog host)
- `GITHUB_PAT`: Your GitHub Personal Access Token
### Create GitHub Actions Workflow
Create `.github/workflows/posthog-analysis.yml` in your repository:
```yaml
name: PostHog Session Analysis with Continue CLI
on:
schedule:
- cron: "0 6 * * *" # Run at 6 AM UTC daily
workflow_dispatch: # Allow manual triggering
jobs:
analyze:
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "18"
- name: Install Continue CLI
run: |
npm install -g @continuedev/cli
echo "✅ Continue CLI installed"
cn --version
- name: Set up environment variables
run: |
echo "POSTHOG_API_KEY=${{ secrets.POSTHOG_API_KEY }}" >> $GITHUB_ENV
echo "POSTHOG_PROJECT_ID=${{ secrets.POSTHOG_PROJECT_ID }}" >> $GITHUB_ENV
echo "POSTHOG_HOST=${{ secrets.POSTHOG_HOST || 'https://us.posthog.com' }}" >> $GITHUB_ENV
echo "GITHUB_PAT=${{ secrets.GITHUB_PAT }}" >> $GITHUB_ENV
echo "GITHUB_OWNER=${{ github.repository_owner }}" >> $GITHUB_ENV
echo "GITHUB_REPO=$(echo ${{ github.repository }} | cut -d'/' -f2)" >> $GITHUB_ENV
- name: Authenticate with Continue CLI
run: |
# Set Continue API key
export CONTINUE_API_KEY="${{ secrets.CONTINUE_API_KEY }}"
# Login to Continue CLI
if ! cn auth login --api-key "$CONTINUE_API_KEY"; then
echo "❌ Failed to authenticate with Continue CLI"
exit 1
fi
echo "✅ Continue CLI authenticated"
- name: Run PostHog Session Analysis
run: |
echo "🎬 Starting PostHog session analysis..."
# Create the analysis prompt
cat > analysis_prompt.txt << 'EOF'
I need you to help me analyze PostHog session recordings to identify UX issues. Please:
1. First, fetch session recordings from PostHog using these details:
- Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from environment variables
- API endpoint: $POSTHOG_HOST/api/projects/$POSTHOG_PROJECT_ID/session_recordings/?limit=20
- Include Authorization header: "Bearer $POSTHOG_API_KEY"
2. Filter the sessions to find problematic ones with either:
- console_error_count > 0 (JavaScript errors)
- recording_duration > 300 (sessions longer than 5 minutes)
3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems.
4. Format each issue like this:
### 1. **Issue Title Here**
**Problem**: One sentence describing the user problem
**Technical Causes**: Brief technical explanation
**Affected Pages**: List the URLs
**Recommended Fix**:
- Specific action item 1
- Specific action item 2
**Priority**: **HIGH** or **MEDIUM** or **LOW**
**Impact**: Quantify the impact (e.g., 'Affects 80% of sessions')
Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data.
Environment context:
- POSTHOG_API_KEY: $POSTHOG_API_KEY
- POSTHOG_PROJECT_ID: $POSTHOG_PROJECT_ID
- POSTHOG_HOST: $POSTHOG_HOST
- GitHub Repo: $GITHUB_OWNER/$GITHUB_REPO
EOF
# Run the analysis
cn < analysis_prompt.txt > analysis-results.txt 2>&1
# Check if analysis completed
if [ ! -s analysis-results.txt ]; then
echo "❌ Analysis failed or produced no output"
exit 1
fi
echo "✅ Analysis completed"
echo "📄 Analysis results preview:"
head -20 analysis-results.txt
- name: Create GitHub Issues from Analysis
run: |
echo "📝 Creating GitHub issues from analysis..."
# Create the issue creation prompt
cat > issue_prompt.txt << 'EOF'
I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API.
Use these details from environment variables:
- GITHUB_PAT: My GitHub Personal Access Token
- Repository: $GITHUB_OWNER/$GITHUB_REPO
For each issue in my analysis:
1. Parse the issue title, body content, and priority level
2. Create a GitHub issue via API POST to: https://api.github.com/repos/$GITHUB_OWNER/$GITHUB_REPO/issues
3. Use these headers:
- Authorization: token $GITHUB_PAT
- Accept: application/vnd.github.v3+json
- Content-Type: application/json
4. Set labels based on priority:
- HIGH: ["bug", "high-priority", "user-experience", "automated"]
- MEDIUM: ["enhancement", "medium-priority", "user-experience", "automated"]
- LOW: ["low-priority", "user-experience", "automated"]
5. Format the issue title as: "🔍 UX Issue: {original title}"
Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs.
Here's my analysis to process:
EOF
# Append the analysis results to the prompt
cat analysis-results.txt >> issue_prompt.txt
# Run the issue creation
cn < issue_prompt.txt > issue-creation-results.txt 2>&1
echo "✅ Issue creation completed"
echo "📄 Issue creation results:"
cat issue-creation-results.txt
- name: Upload Analysis Artifacts
uses: actions/upload-artifact@v4
if: always()
with:
name: analysis-results-${{ github.run_number }}
path: |
analysis-results.txt
issue-creation-results.txt
retention-days: 30
- name: Summary
run: |
echo "✅ PostHog analysis workflow completed!"
echo "📊 Check the artifacts for detailed analysis results"
echo "🐛 Check your repository issues for newly created UX issues"
```
## Step 5: Testing Your Workflow
### Test Locally First
Before setting up automation, test the workflow locally:
**Test 1: Session Analysis**
```bash
cn -p "[Paste the PostHog analysis prompt from Step 2]"
```
Expected: Analysis output with 3 formatted GitHub issues
**Test 2: Issue Creation**
```bash
cn -p "[Paste the GitHub issue creation prompt from Step 3 with your analysis results]"
```
Expected: Confirmation of GitHub issues created with URLs
### Test the GitHub Actions Workflow
1. **Manual Trigger**: Go to **Actions** tab in your repository and manually trigger the workflow
2. **Check Artifacts**: Download the analysis results from the workflow run
3. **Verify Issues**: Check that GitHub issues were created in your repository
<Check>
**Success Indicators:** - PostHog API returns session data (not empty) -
Continue CLI generates analysis with identified issues - GitHub issues are
created with proper labels and formatting - Workflow completes without errors
</Check>
## Troubleshooting
If you encounter issues, use this helpful prompt to diagnose problems:
```bash
cn -p "Help me set up my environment for PostHog session analysis. Please:
1. Check if I have the required secrets configured in Continue CLI:
- POSTHOG_API_KEY
- POSTHOG_PROJECT_ID
- POSTHOG_HOST
- GITHUB_PAT
2. If any are missing, guide me through:
- How to get PostHog Personal API Key from PostHog settings
- How to find my PostHog Project ID from the URL
- How to create a GitHub Personal Access Token with issues:write permission
- How to add these as secrets in Continue CLI
3. Help me identify my GitHub repository owner and name by:
- Checking git remote origin URL
- Or asking me to provide them
4. Test the API connections by making a simple API call to both PostHog and GitHub to verify the credentials work.
Please walk me through this setup process step by step."
```
## What You've Built
After completing this guide, you have a complete **Continuous AI system** that:
✅ **Monitors user experience** - Automatically fetches and analyzes PostHog session data
✅ **Identifies problems intelligently** - Uses AI to spot patterns and technical issues
✅ **Creates actionable tasks** - Generates GitHub issues with specific recommendations
✅ **Runs autonomously** - Operates daily without manual intervention using GitHub Actions
✅ **Scales with your team** - Handles growing amounts of session data automatically
<Card title="Continuous AI" icon="rocket">
Your system now operates at **[Level 2 Continuous
AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
AI handles routine analysis tasks with human oversight through GitHub issue
review and prioritization.
</Card>
## Security Best Practices
<Warning>
**Protect Your API Keys:** - Store all credentials as GitHub Secrets, never in
code - Use Continue CLI's secure secret storage - Limit token scopes to
minimum required permissions - Rotate API keys regularly (every 90 days
recommended) - Monitor token usage for unusual activity
</Warning>
## Advanced Prompts
Consider enhancing your workflow with these advanced Continue CLI prompts:
<CardGroup cols={2}>
<Card title="Performance Analysis" icon="chart-line">
"Analyze PostHog performance metrics alongside session recordings to
identify slow page loads affecting user experience"
</Card>
<Card title="Error Correlation" icon="bug">
"Cross-reference JavaScript console errors with user actions to identify the
root cause of UX issues"
</Card>
<Card title="Feature Flag Analysis" icon="flag">
"Analyze how PostHog feature flags impact user behavior in session
recordings"
</Card>
<Card title="Custom Slack Alerts" icon="slack">
"Create Slack alerts when critical UX issues are detected in PostHog
sessions"
</Card>
</CardGroup>
## Next Steps
1. **Monitor your first issues** - Review the GitHub issues created and implement fixes
2. **Measure impact** - Track how resolved issues improve PostHog metrics
3. **Refine prompts** - Adjust the Continue CLI prompts based on issue quality
4. **Scale the system** - Add more data sources or create specialized analysis workflows

View file

@ -403,6 +403,7 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
- `env`: An optional map of environment variables for the server process.
- `cwd`: An optional working directory to run the command in. Can be absolute or relative path.
- `connectionTimeout`: An optional connection timeout number to the server in milliseconds.
- `requestOptions`: Optional request options for `sse` and `streamable-http` servers. Same format as [model requestOptions](#models).
**Example:**

View file

@ -37,7 +37,7 @@
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/cli.git"
"url": "https://github.com/continuedev/continue.git"
},
"bugs": {
"url": "https://github.com/continuedev/continue/issues"

View file

@ -40,6 +40,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Sign out of your current session",
category: "system",
},
{
name: "update",
description: "Update the Continue CLI",
category: "system",
},
{
name: "whoami",
description: "Check who you're currently logged in as",

View file

@ -9,13 +9,10 @@ import {
} from "./auth/workos.js";
import { services } from "./services/index.js";
import { getCurrentSession, getSessionFilePath } from "./session.js";
import { posthogService } from "./telemetry/posthogService.js";
import { logger } from "./util/logger.js";
import { getVersion } from "./version.js";
export async function handleInfoSlashCommand() {
posthogService.capture("useSlashCommand", { name: "info" });
const infoLines = [];
// Version and working directory info

View file

@ -0,0 +1,241 @@
import { exec, spawn } from "child_process";
import { promisify } from "util";
import { GlobalContext } from "core/util/GlobalContext.js";
import { logger } from "src/util/logger.js";
import { compareVersions, getLatestVersion, getVersion } from "../version.js";
import { BaseService } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { UpdateServiceState, UpdateStatus } from "./types.js";
const execAsync = promisify(exec);
/**
* Service for checking and performing CLI updates
*/
export class UpdateService extends BaseService<UpdateServiceState> {
constructor() {
super("update", {
autoUpdate: true,
isAutoUpdate: true,
status: UpdateStatus.IDLE,
message: "",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: getVersion(),
});
}
/**
* Initialize the update service
*/
async doInitialize(headless?: boolean) {
// Don't automatically check in tests/headless
if (!headless && process.env.NODE_ENV !== "test") {
void this.checkAndAutoUpdate();
}
return this.currentState;
}
private async checkAndAutoUpdate() {
// First get auto update setting from global context
const globalContext = new GlobalContext();
const autoUpdate = globalContext.get("autoUpdateCli") ?? true;
this.setState({
autoUpdate,
});
try {
// Check for updates
this.setState({
status: UpdateStatus.CHECKING,
message: "Checking for updates",
});
const latestVersion = await getLatestVersion();
this.setState({
latestVersion,
});
if (!latestVersion) {
this.setState({
status: UpdateStatus.IDLE,
message: "Continue CLI",
isUpdateAvailable: false,
});
return;
}
const comparison = compareVersions(
this.currentState.currentVersion,
latestVersion,
);
const isUpdateAvailable = comparison === "older";
this.setState({
isUpdateAvailable,
});
if (this.currentState.currentVersion === "0.0.0-dev") {
this.setState({
status: UpdateStatus.IDLE,
message: `Continue CLI`,
isUpdateAvailable,
latestVersion,
});
return; // Uncomment to test auto-update behavior in dev
}
// If update is available, automatically update
if (
autoUpdate &&
isUpdateAvailable &&
this.currentState.status !== "updating" &&
!process.env.CONTINUE_CLI_AUTO_UPDATED //Already auto updated, preventing sequential auto-update
) {
await this.performUpdate(true);
} else {
this.setState({
status: UpdateStatus.IDLE,
message: isUpdateAvailable
? `Update available: v${latestVersion}`
: `Continue CLI v${this.currentState.currentVersion}`,
isUpdateAvailable,
latestVersion,
});
}
} catch (error: any) {
logger.error("Error checking for updates:", error);
this.setState({
status: UpdateStatus.ERROR,
message: `Continue CLI v${this.currentState.currentVersion}`,
error,
});
}
}
public async setAutoUpdate(value: boolean) {
const globalContext = new GlobalContext();
globalContext.update("autoUpdateCli", value);
this.setState({
autoUpdate: value,
});
}
// TODO this is a hack because our service state update code is broken
// Currently all things that need update use serviceContainer.set manually
// Rather than actually using the stateChanged event
setState(newState: Partial<UpdateServiceState>): void {
super.setState(newState);
serviceContainer.set("update", this.currentState);
}
async performUpdate(isAutoUpdate?: boolean) {
if (this.currentState.status === "updating") {
return;
}
try {
this.setState({
isAutoUpdate,
status: UpdateStatus.UPDATING,
message: `${isAutoUpdate ? "Auto-updating" : "Updating"} to v${this.currentState.latestVersion}`,
});
// Install the update
const { stdout, stderr } = await execAsync("npm i -g @continuedev/cli");
logger.debug("Update output:", { stdout, stderr });
if (stderr) {
const errLines = stderr.split("\n");
for (const line of errLines) {
const lower = line.toLowerCase().trim();
if (
!line ||
lower.includes("debugger") ||
lower.includes("npm warn")
) {
continue;
}
this.setState({
status: UpdateStatus.ERROR,
message: `Error updating to v${this.currentState.latestVersion}`,
error: new Error(stderr),
});
return;
}
}
this.setState({
status: UpdateStatus.UPDATED,
message: `${isAutoUpdate ? "Auto-updated to" : "Restart for"} v${this.currentState.latestVersion}`,
isUpdateAvailable: false,
});
if (isAutoUpdate) {
this.restartCLI();
}
} catch (error: any) {
logger.error("Error updating CLI:", error);
this.setState({
status: UpdateStatus.ERROR,
message: isAutoUpdate ? "Auto-update failed" : "Update failed",
error,
});
setTimeout(() => {
this.setState({
status: UpdateStatus.IDLE,
message: `/update to v${this.currentState.latestVersion}`,
});
}, 4000);
}
}
private restartCLI(): void {
try {
const entryPoint = process.argv[1];
const cliArgs = process.argv.slice(2);
const nodeExecutable = process.execPath;
logger.debug(
`Preparing for CLI restart with: ${nodeExecutable} ${entryPoint} ${cliArgs.join(
" ",
)}`,
);
// Halt/clean up parent cn process
try {
// Remove all input listeners
global.clearTimeout = () => {};
global.clearInterval = () => {};
process.stdin.removeAllListeners();
process.stdin.pause();
// console.clear(); // Don't want to clear things that were in console before cn started
} catch (e) {
logger.debug("Error cleaning up terminal:", e);
}
// Spawn a new detached cn process
const child = spawn(nodeExecutable, [entryPoint, ...cliArgs], {
detached: true,
stdio: "inherit",
env: {
...process.env,
CONTINUE_CLI_AUTO_UPDATED: "true",
},
});
// I did not find a way on existing to avoid a bug where next process has input glitches without leaving parent in place
// So instead of existing, parent will exit when child exits
// process.exit(0);
child.on("exit", (code) => {
process.exit(code);
});
child.unref();
} catch (error) {
logger.error("Failed to restart CLI:", error);
}
}
}

View file

@ -21,6 +21,7 @@ import {
ServiceInitOptions,
ServiceInitResult,
} from "./types.js";
import { UpdateService } from "./UpdateService.js";
// Service instances
const authService = new AuthService();
@ -31,6 +32,7 @@ const mcpService = new MCPService();
const fileIndexService = new FileIndexService();
const resourceMonitoringService = new ResourceMonitoringService();
const chatHistoryService = new ChatHistoryService();
const updateService = new UpdateService();
/**
* Initialize all services and register them with the service container
@ -132,6 +134,12 @@ export async function initializeServices(
[], // No dependencies
);
serviceContainer.register(
SERVICE_NAMES.UPDATE,
() => updateService.initialize(),
[], // No dependencies
);
serviceContainer.register(
SERVICE_NAMES.API_CLIENT,
async () => {
@ -283,17 +291,9 @@ export function reloadService(serviceName: string) {
* Check if all core services are ready
*/
export function areServicesReady(): boolean {
return [
SERVICE_NAMES.TOOL_PERMISSIONS,
SERVICE_NAMES.AUTH,
SERVICE_NAMES.API_CLIENT,
SERVICE_NAMES.CONFIG,
SERVICE_NAMES.MODEL,
SERVICE_NAMES.MCP,
SERVICE_NAMES.FILE_INDEX,
SERVICE_NAMES.RESOURCE_MONITORING,
SERVICE_NAMES.CHAT_HISTORY,
].every((name) => serviceContainer.isReady(name));
return Object.values(SERVICE_NAMES).every((name) =>
serviceContainer.isReady(name),
);
}
/**
@ -317,6 +317,7 @@ export const services = {
resourceMonitoring: resourceMonitoringService,
systemMessage: systemMessageService,
chatHistory: chatHistoryService,
updateService: updateService,
} as const;
// Export the service container for advanced usage

View file

@ -81,6 +81,25 @@ export interface MCPServiceState {
prompts: MCPPrompt[];
}
export enum UpdateStatus {
IDLE = "idle",
CHECKING = "checking",
UPDATING = "updating",
UPDATED = "updated",
ERROR = "error",
}
export interface UpdateServiceState {
autoUpdate: boolean;
isAutoUpdate: boolean;
status: UpdateStatus;
message: string;
error?: Error | null;
isUpdateAvailable: boolean;
latestVersion: string | null;
currentVersion: string;
}
export interface ApiClientServiceState {
apiClient: DefaultApiInterface | null;
}
@ -92,8 +111,8 @@ export interface ToolPermissionServiceState {
originalPolicies?: ToolPermissions;
}
export type { FileIndexServiceState } from "./FileIndexService.js";
export type { ChatHistoryState } from "./ChatHistoryService.js";
export type { FileIndexServiceState } from "./FileIndexService.js";
/**
* Service names as constants to prevent typos
@ -109,6 +128,7 @@ export const SERVICE_NAMES = {
RESOURCE_MONITORING: "resourceMonitoring",
SYSTEM_MESSAGE: "systemMessage",
CHAT_HISTORY: "chatHistory",
UPDATE: "update",
} as const;
/**

View file

@ -48,12 +48,10 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
` Type ${chalk.cyan("/")} to see available slash commands`,
` Type ${chalk.cyan("!")} followed by a command to execute bash directly`,
].join("\n");
posthogService.capture("useSlashCommand", { name: "help" });
return { output: helpMessage };
}
async function handleLogin() {
posthogService.capture("useSlashCommand", { name: "login" });
try {
const newAuthState = await services.auth.login();
await reloadService(SERVICE_NAMES.AUTH);
@ -79,7 +77,6 @@ async function handleLogin() {
}
async function handleLogout() {
posthogService.capture("useSlashCommand", { name: "logout" });
try {
await services.auth.logout();
return {
@ -95,7 +92,6 @@ async function handleLogout() {
}
function handleWhoami() {
posthogService.capture("useSlashCommand", { name: "whoami" });
if (isAuthenticated()) {
const config = loadAuthConfig();
if (config && isAuthenticatedConfig(config)) {
@ -118,8 +114,6 @@ function handleWhoami() {
}
async function handleFork() {
posthogService.capture("useSlashCommand", { name: "fork" });
try {
const currentSession = getCurrentSession();
const forkCommand = `cn --fork ${currentSession.sessionId}`;
@ -148,15 +142,12 @@ async function handleFork() {
const commandHandlers: Record<string, CommandHandler> = {
help: handleHelp,
clear: () => {
posthogService.capture("useSlashCommand", { name: "clear" });
return { clear: true, output: "Chat history cleared" };
},
exit: () => {
posthogService.capture("useSlashCommand", { name: "exit" });
return { exit: true, output: "Goodbye!" };
},
config: () => {
posthogService.capture("useSlashCommand", { name: "config" });
return { openConfigSelector: true };
},
login: handleLogin,
@ -165,38 +156,25 @@ const commandHandlers: Record<string, CommandHandler> = {
info: handleInfoSlashCommand,
model: () => ({ openModelSelector: true }),
compact: () => {
posthogService.capture("useSlashCommand", { name: "compact" });
return { compact: true };
},
mcp: () => {
posthogService.capture("useSlashCommand", { name: "mcp" });
return { openMcpSelector: true };
},
resume: () => {
posthogService.capture("useSlashCommand", { name: "resume" });
return { openSessionSelector: true };
},
fork: handleFork,
init: (args, assistant) => {
posthogService.capture("useSlashCommand", { name: "init" });
return handleInit(args, assistant);
init: handleInit,
update: () => {
return { openUpdateSelector: true };
},
};
export async function handleSlashCommands(
input: string,
assistant: AssistantConfig,
): Promise<{
output?: string;
exit?: boolean;
newInput?: string;
clear?: boolean;
openConfigSelector?: boolean;
openModelSelector?: boolean;
openMCPSelector?: boolean;
openSessionSelector?: boolean;
compact?: boolean;
} | null> {
): Promise<SlashCommandResult | null> {
// Only trigger slash commands if slash is the very first character
if (!input.startsWith("/") || !input.trim().startsWith("/")) {
return null;

View file

@ -16,9 +16,11 @@ import { telemetryService } from "../telemetry/telemetryService.js";
import { ToolCall } from "../tools/index.js";
import {
chatCompletionStreamWithBackoff,
isContextLengthError,
withExponentialBackoff,
} from "../util/exponentialBackoff.js";
import { logger } from "../util/logger.js";
import { validateContextLength } from "../util/tokenizer.js";
import { getAllTools, handleToolCalls } from "./handleToolCalls.js";
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
@ -148,6 +150,12 @@ export async function processStreamingResponse(
tools,
} = options;
// Validate context length before making the request
const validation = validateContextLength(chatHistory, model);
if (!validation.isValid) {
throw new Error(`Context length validation failed: ${validation.error}`);
}
// Get fresh system message and inject it
const systemMessage = await systemMessageService.getSystemMessage();
const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
@ -277,6 +285,13 @@ export async function processStreamingResponse(
shouldContinue: false,
};
}
// Handle context length errors with helpful message
if (isContextLengthError(error)) {
logger.debug(`Context length exceeded: ${error}`);
throw new Error(`Context length exceeded: ${error}`);
}
throw error;
}

View file

@ -6,8 +6,10 @@ import {
serviceContainer,
} from "../services/index.js";
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
import type { ModelServiceState } from "../services/types.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { logger } from "../util/logger.js";
import { isModelCapable } from "../utils/index.js";
import { editTool } from "./edit.js";
import { exitTool } from "./exit.js";
@ -66,9 +68,53 @@ function getDynamicTools(): Tool[] {
return dynamicTools;
}
// Get all builtin tools including dynamic ones
// Check if the current model is capable and should exclude Edit tool
function shouldExcludeEditTool(): boolean {
try {
const modelServiceResult = getServiceSync<ModelServiceState>(
SERVICE_NAMES.MODEL,
);
if (
modelServiceResult.state === "ready" &&
modelServiceResult.value?.model
) {
const { name, provider, model } = modelServiceResult.value.model;
// Check if model is capable
const isCapable = isModelCapable(provider, name, model);
logger.debug("Capability-based tool filtering", {
provider,
name,
isCapable,
willExcludeEdit: isCapable,
});
return isCapable;
}
} catch (error) {
logger.debug("Error checking model capability for tool filtering", {
error,
});
}
return false;
}
// Get all builtin tools including dynamic ones, with capability-based filtering
export function getAllBuiltinTools(): Tool[] {
return [...BUILTIN_TOOLS, ...getDynamicTools()];
let builtinTools = [...BUILTIN_TOOLS];
// Apply capability-based filtering for edit tools
// If model is capable, exclude editTool in favor of multiEditTool
if (shouldExcludeEditTool()) {
builtinTools = builtinTools.filter((tool) => tool.name !== editTool.name);
logger.debug(
"Excluded Edit tool for capable model - MultiEdit will be used instead",
);
}
return [...builtinTools, ...getDynamicTools()];
}
export function getToolDisplayName(toolName: string): string {

View file

@ -9,7 +9,6 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { editTool } from "./edit.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
@ -133,8 +132,8 @@ export const multiEditTool: Tool = {
displayName: "MultiEdit",
readonly: false,
isBuiltIn: true,
description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${editTool.name} tool and allows you to perform multiple find-and-replace operations efficiently.
Prefer this tool over the ${editTool.name} tool when you need to make multiple edits to the same file.
description: `This is a tool for making multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently.
This tool is ideal when you need to make multiple edits to the same file.
To make multiple edits to a file, provide the following:
1. file_path: The absolute path to the file to modify (must be absolute, not relative)

View file

@ -0,0 +1,33 @@
import { Text } from "ink";
import React, { useEffect, useState } from "react";
interface LoadingTextProps {
text: string;
color?: string;
interval?: number;
}
export const LoadingText: React.FC<LoadingTextProps> = ({
text,
color = "gray",
interval = 300,
}) => {
const [dotsCount, setDotsCount] = useState(1);
useEffect(() => {
const timer = setInterval(() => {
setDotsCount((current) => (current % 3) + 1);
}, interval);
return () => clearInterval(timer);
}, [interval]);
const dots = ".".repeat(dotsCount);
return (
<Text color={color}>
{text}
{dots}
</Text>
);
};

View file

@ -14,6 +14,7 @@ import {
ConfigServiceState,
MCPServiceState,
ModelServiceState,
UpdateServiceState,
} from "../services/types.js";
import { logger } from "../util/logger.js";
@ -93,7 +94,8 @@ function useTUIChatServices(remoteUrl?: string) {
model: ModelServiceState;
mcp: MCPServiceState;
apiClient: ApiClientServiceState;
}>(["auth", "config", "model", "mcp", "apiClient"]);
update: UpdateServiceState;
}>(["auth", "config", "model", "mcp", "apiClient", "update"]);
return { services, allServicesReady, isRemoteMode };
}
@ -207,6 +209,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
onShowConfigSelector: () => navigateTo("config"),
onShowModelSelector: () => navigateTo("model"),
onShowMCPSelector: () => navigateTo("mcp"),
onShowUpdateSelector: () => navigateTo("update"),
onShowSessionSelector: () => navigateTo("session"),
onLoginPrompt: handleLoginPrompt,
onReload: handleReload,

View file

@ -1,10 +1,3 @@
// Mock the version module before any other imports
vi.mock("../version.js", () => ({
getVersion: vi.fn(),
getLatestVersion: vi.fn(),
compareVersions: vi.fn(),
}));
// Mock useTerminalSize hook
vi.mock("./hooks/useTerminalSize.js", () => ({
useTerminalSize: () => ({ columns: 80, rows: 24 }),
@ -30,93 +23,202 @@ import { render } from "ink-testing-library";
import React from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as versionModule from "../version.js";
import { UpdateStatus } from "../services/types.js";
import { UpdateNotification } from "./UpdateNotification.js";
const mockVersionModule = vi.mocked(versionModule);
// Mock useServices hook
const mockUseServices = vi.fn();
vi.mock("../hooks/useService.js", () => ({
useServices: () => mockUseServices(),
}));
describe("UpdateNotification", () => {
let originalNodeEnv: string | undefined;
beforeEach(() => {
vi.clearAllMocks();
originalNodeEnv = process.env.NODE_ENV;
// Default mock implementations
mockVersionModule.getLatestVersion.mockResolvedValue("1.0.1");
mockVersionModule.compareVersions.mockReturnValue("older");
// Default mock implementation - no update available
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "Continue CLI v1.0.0",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: "1.0.0",
},
},
});
});
afterEach(() => {
// Restore original NODE_ENV
if (originalNodeEnv === undefined) {
delete process.env.NODE_ENV;
} else {
process.env.NODE_ENV = originalNodeEnv;
}
vi.clearAllMocks();
});
it("should not check for updates when version ends with -dev", async () => {
// Set NODE_ENV to non-test value to enable update checks
process.env.NODE_ENV = "development";
mockVersionModule.getVersion.mockReturnValue("1.0.0-dev");
it("should show default message when no update is available", () => {
const { lastFrame } = render(<UpdateNotification />);
render(<UpdateNotification />);
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
// getLatestVersion should not have been called for dev versions
expect(mockVersionModule.getLatestVersion).not.toHaveBeenCalled();
expect(lastFrame()).toContain("◉ Continue CLI v1.0.0");
});
it("should check for updates when version does not end with -dev", async () => {
// Set NODE_ENV to non-test value to enable update checks
process.env.NODE_ENV = "development";
mockVersionModule.getVersion.mockReturnValue("1.0.0");
it("should show update available message when update is available", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "Update available: v1.0.1",
error: null,
isUpdateAvailable: true,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
render(<UpdateNotification />);
const { lastFrame } = render(<UpdateNotification />);
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
// getLatestVersion should have been called for non-dev versions
expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
expect(lastFrame()).toContain("◉ Update available: v1.0.1");
});
it("should handle various dev version formats", async () => {
// Set NODE_ENV to non-test value to enable update checks
process.env.NODE_ENV = "development";
const devVersions = ["1.0.0-dev", "2.1.3-dev", "0.5.0-dev"];
it("should show checking message when checking for updates", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.CHECKING,
message: "Checking for updates",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: "1.0.0",
},
},
});
for (const version of devVersions) {
vi.clearAllMocks();
mockVersionModule.getVersion.mockReturnValue(version);
const { lastFrame } = render(<UpdateNotification />);
render(<UpdateNotification />);
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
expect(mockVersionModule.getLatestVersion).not.toHaveBeenCalled();
}
expect(lastFrame()).toContain("◉ Checking for updates");
});
it("should still check for updates with other version suffixes", async () => {
// Set NODE_ENV to non-test value to enable update checks
process.env.NODE_ENV = "development";
const nonDevVersions = ["1.0.0-beta", "1.0.0-alpha", "1.0.0-rc1"];
it("should show updating message when updating", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.UPDATING,
message: "Updating to v1.0.1",
error: null,
isUpdateAvailable: false,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
for (const version of nonDevVersions) {
vi.clearAllMocks();
mockVersionModule.getVersion.mockReturnValue(version);
const { lastFrame } = render(<UpdateNotification />);
render(<UpdateNotification />);
expect(lastFrame()).toContain("◉ Updating to v1.0.1");
});
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
it("should show updated message when update completes", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.UPDATED,
message: "Auto-updated to v1.0.1",
error: null,
isUpdateAvailable: false,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
}
const { lastFrame } = render(<UpdateNotification />);
expect(lastFrame()).toContain("◉ Auto-updated to v1.0.1");
});
it("should show error message when update fails", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.ERROR,
message: "Update failed",
error: new Error("Update error"),
isUpdateAvailable: true,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
const { lastFrame } = render(<UpdateNotification />);
expect(lastFrame()).toContain("◉ Update failed");
});
it("should show remote mode when in remote mode and no update available", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "Continue CLI v1.0.0",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: "1.0.0",
},
},
});
const { lastFrame } = render(<UpdateNotification isRemoteMode={true} />);
expect(lastFrame()).toContain("◉ Remote Mode");
});
it("should show update message even in remote mode when update is available", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "Update available: v1.0.1",
error: null,
isUpdateAvailable: true,
latestVersion: "1.0.1",
currentVersion: "1.0.0",
},
},
});
const { lastFrame } = render(<UpdateNotification isRemoteMode={true} />);
expect(lastFrame()).toContain("◉ Update available: v1.0.1");
});
it("should show default message when update service has no message", () => {
mockUseServices.mockReturnValue({
services: {
update: {
autoUpdate: true,
status: UpdateStatus.IDLE,
message: "",
error: null,
isUpdateAvailable: false,
latestVersion: null,
currentVersion: "1.0.0",
},
},
});
const { lastFrame } = render(<UpdateNotification />);
expect(lastFrame()).toContain("◉ Continue CLI");
});
});

View file

@ -1,79 +1,54 @@
import { Text } from "ink";
import React, { useEffect, useMemo, useState } from "react";
import React, { useMemo } from "react";
import { compareVersions, getLatestVersion, getVersion } from "../version.js";
import { useServices } from "../hooks/useService.js";
import {
SERVICE_NAMES,
UpdateServiceState,
UpdateStatus,
} from "../services/types.js";
import { useTerminalSize } from "./hooks/useTerminalSize.js";
interface UpdateNotificationProps {
isRemoteMode?: boolean;
}
const UpdateNotification: React.FC<UpdateNotificationProps> = ({
isRemoteMode = false,
}) => {
const [updateAvailable, setUpdateAvailable] = useState(false);
const [latestVersion, setLatestVersion] = useState<string>("");
const [currentVersion] = useState(getVersion());
const { columns } = useTerminalSize();
useEffect(() => {
// Skip update check in test environment
if (process.env.NODE_ENV === "test") {
return;
const { services } = useServices<{
update: UpdateServiceState;
}>([SERVICE_NAMES.UPDATE]);
const color = useMemo(() => {
switch (services.update?.status) {
case UpdateStatus.UPDATING:
case UpdateStatus.CHECKING:
return "yellow";
case UpdateStatus.UPDATED:
return "green";
case UpdateStatus.ERROR:
return "red";
default:
return "dim";
}
// Skip update check for development versions
if (currentVersion.endsWith("-dev")) {
return;
}
const abortController = new AbortController();
const checkForUpdate = async () => {
try {
const latest = await getLatestVersion(abortController.signal);
if (latest) {
setLatestVersion(latest);
const comparison = compareVersions(currentVersion, latest);
setUpdateAvailable(comparison === "older");
}
} catch (error) {
// Silently fail - we don't want to interrupt the user experience
if (error instanceof Error && error.name !== "AbortError") {
console.debug("Failed to check for updates:", error);
}
}
};
// Check for updates but don't block
checkForUpdate();
// Cleanup function to abort the request when component unmounts
return () => {
abortController.abort();
};
}, [currentVersion]);
}, [services.update?.status]);
const text = useMemo(() => {
if (columns < 75) {
return `v${latestVersion} available`;
if (!services.update?.message) {
return "Continue CLI";
}
return `Update available: v${latestVersion} (npm i -g @continuedev/cli)`;
}, [columns, latestVersion]);
if (!updateAvailable) {
if (isRemoteMode) {
return <Text color="cyan">◉ Remote Mode</Text>;
}
return (
<Text wrap="truncate-end" color="gray">
● Continue CLI
</Text>
);
return services.update.message;
}, [columns, services.update?.message]);
if (!services.update?.isUpdateAvailable && isRemoteMode) {
return <Text color="cyan">◉ Remote Mode</Text>;
}
return <Text color="dim">{text}</Text>;
return <Text color={color}>{`◉ ${text}`}</Text>;
};
export { UpdateNotification };

View file

@ -0,0 +1,93 @@
import React, { useMemo, useState } from "react";
import { useService } from "../hooks/useService.js";
import { services } from "../services/index.js";
import type { UpdateServiceState } from "../services/types.js";
import { SERVICE_NAMES } from "../services/types.js";
import { Selector, SelectorOption } from "./Selector.js";
interface UpdateSelectorProps {
onCancel: () => void;
}
interface UpdateOption extends SelectorOption {
action: "run" | "toggle-auto" | "back";
}
export const UpdateSelector: React.FC<UpdateSelectorProps> = ({ onCancel }) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const updateServiceState = useService<UpdateServiceState>(
SERVICE_NAMES.UPDATE,
);
const updateState = updateServiceState.value;
const isWorking =
updateServiceState.state === "loading" ||
updateState?.status === "checking" ||
updateState?.status === "updating";
const error: string | null = useMemo(() => {
if (updateServiceState.state === "error") {
return updateServiceState.error?.message || "Update service error";
}
if (updateState?.status === "error") {
return updateState.message || "Update failed";
}
return null;
}, [updateServiceState.state, updateServiceState.error, updateState]);
const loadingMessage = useMemo(() => {
if (!updateState) return "Preparing update...";
return updateState.message || "Working...";
}, [updateState]);
const options: UpdateOption[] = useMemo(() => {
const runLabel = updateState?.latestVersion
? `Run update to v${updateState.latestVersion}`
: "Run update";
const autoUpdateLabel = updateState?.autoUpdate
? "Turn off auto-updates"
: "Turn on auto-updates";
return [
{ id: "run-update", name: runLabel, action: "run" },
{ id: "toggle-auto", name: autoUpdateLabel, action: "toggle-auto" },
{ id: "back", name: "Back", action: "back" },
];
}, [updateState?.latestVersion, updateState?.autoUpdate]);
const handleSelect = async (option: UpdateOption) => {
switch (option.action) {
case "run":
// Perform a manual update (not auto-update)
await services.updateService.performUpdate(false);
return; // Keep selector open to show status changes
case "toggle-auto":
// Toggle auto-update setting
const newValue = !updateState?.autoUpdate;
await services.updateService.setAutoUpdate(newValue);
return; // Keep selector open to show updated label
case "back":
onCancel();
return;
}
};
return (
<Selector
title="Update Continue CLI"
options={options}
selectedIndex={selectedIndex}
loading={!!isWorking}
error={error}
loadingMessage={loadingMessage}
currentId={null}
onSelect={handleSelect}
onCancel={onCancel}
onNavigate={setSelectedIndex}
/>
);
};

View file

@ -1,6 +1,8 @@
import { Box, Text } from "ink";
import React from "react";
import { UpdateServiceState } from "src/services/types.js";
import { listSessions } from "../../session.js";
import { ConfigSelector } from "../ConfigSelector.js";
import type { NavigationScreen } from "../context/NavigationContext.js";
@ -9,6 +11,7 @@ import { MCPSelector } from "../MCPSelector.js";
import { ModelSelector } from "../ModelSelector.js";
import { SessionSelector } from "../SessionSelector.js";
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
import { UpdateSelector } from "../UpdateSelector.js";
import { UserInput } from "../UserInput.js";
import { ToolPermissionSelector } from "./ToolPermissionSelector.js";
@ -42,6 +45,14 @@ interface ScreenContentProps {
onImageInClipboardChange?: (hasImage: boolean) => void;
}
function hideScreenContent(state?: UpdateServiceState) {
return (
(state?.status === "checking" && state?.autoUpdate) ||
(state?.isAutoUpdate &&
(state?.status === "updating" || state?.status === "updated"))
);
}
export const ScreenContent: React.FC<ScreenContentProps> = ({
isScreenActive,
navState,
@ -65,6 +76,10 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
isRemoteMode,
onImageInClipboardChange,
}) => {
if (hideScreenContent(services.update)) {
return null;
}
// Login prompt
if (isScreenActive("login") && navState.screenData) {
return (
@ -106,6 +121,10 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
return <MCPSelector onCancel={closeCurrentScreen} />;
}
if (isScreenActive("update")) {
return <UpdateSelector onCancel={closeCurrentScreen} />;
}
// Model selector
if (isScreenActive("model")) {
return (

View file

@ -1,9 +1,9 @@
import React, {
createContext,
ReactNode,
useCallback,
useContext,
useReducer,
useCallback,
ReactNode,
} from "react";
/**
@ -17,6 +17,7 @@ export type NavigationScreen =
| "free-trial" // Free trial transition UI
| "login" // Login prompt
| "mcp" // MCP selector
| "update" // Update selector
| "session"; // Session selector
interface NavigationState {

View file

@ -48,6 +48,7 @@ interface ProcessSlashCommandResultOptions {
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
onShowConfigSelector: () => void;
onShowModelSelector?: () => void;
onShowUpdateSelector?: () => void;
onShowMCPSelector?: () => void;
onShowSessionSelector?: () => void;
onClear?: () => void;
@ -61,6 +62,7 @@ export function processSlashCommandResult({
chatHistory,
setChatHistory,
onShowConfigSelector,
onShowUpdateSelector,
onShowModelSelector,
onShowMCPSelector,
onShowSessionSelector,
@ -75,6 +77,11 @@ export function processSlashCommandResult({
return null;
}
if (result.openUpdateSelector) {
onShowUpdateSelector?.();
return null;
}
if (result.openConfigSelector) {
onShowConfigSelector();
return null;

View file

@ -55,6 +55,7 @@ export function useChat({
additionalPrompts,
onShowConfigSelector,
onShowModelSelector,
onShowUpdateSelector,
onShowMCPSelector,
onShowSessionSelector,
onLoginPrompt: _onLoginPrompt,
@ -419,6 +420,7 @@ export function useChat({
onShowModelSelector,
onShowMCPSelector,
onShowSessionSelector,
onShowUpdateSelector,
onClear,
});

View file

@ -15,6 +15,7 @@ export interface UseChatProps {
additionalPrompts?: string[];
onShowConfigSelector: () => void;
onShowMCPSelector: () => void;
onShowUpdateSelector: () => void;
onShowModelSelector?: () => void;
onShowSessionSelector?: () => void;
onLoginPrompt?: (promptText: string) => Promise<string>;
@ -57,6 +58,7 @@ export interface SlashCommandResult {
openConfigSelector?: boolean;
openModelSelector?: boolean;
openMcpSelector?: boolean;
openUpdateSelector?: boolean;
openSessionSelector?: boolean;
compact?: boolean;
}

View file

@ -77,10 +77,40 @@ function isConnectionError(errorMessage: string): boolean {
);
}
/**
* Checks if the error indicates a context length issue (non-retryable)
*/
export function isContextLengthError(error: any): boolean {
const errorMessage = error.message?.toLowerCase() || "";
const contextLengthPatterns = [
// Anthropic Claude
"input length and max_tokens exceed context limit",
"decrease input length or max_tokens",
// OpenAI
"maximum context length",
"reduce the length of the messages",
// Mistral
"tokens in the prompt exceeds",
"use a shorter prompt",
// Generic patterns
"context_length_exceeded",
"invalid_request_error",
];
return contextLengthPatterns.some((pattern) =>
errorMessage.includes(pattern),
);
}
/**
* Determines if an error is retryable based on the error type and status code
*/
function isRetryableError(error: any): boolean {
// Context length errors are never retryable - they need user intervention
if (isContextLengthError(error)) {
return false;
}
// Network errors are retryable
if (isNetworkError(error)) {
return true;

View file

@ -0,0 +1,62 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { describe, expect, it } from "vitest";
import { validateContextLength } from "./tokenizer.js";
describe("validateContextLength", () => {
const createMockModel = (
contextLength: number,
maxTokens?: number,
): ModelConfig => ({
name: "test-model",
model: "test",
provider: "openai",
defaultCompletionOptions: {
contextLength,
maxTokens,
},
});
const createMockHistory = (messageCount: number, contentLength = 100) => {
return Array.from({ length: messageCount }, (_, i) => ({
message: {
role: "user" as const,
content: "x".repeat(contentLength), // Roughly contentLength/4 tokens
},
contextItems: [],
}));
};
it("should pass validation when within context limits", () => {
const model = createMockModel(1000, 200);
const chatHistory = createMockHistory(5, 40); // ~50 tokens total
const result = validateContextLength(chatHistory, model);
expect(result.isValid).toBe(true);
expect(result.error).toBeUndefined();
});
it("should fail validation when input + maxTokens exceeds context limit", () => {
const model = createMockModel(1000, 800);
const chatHistory = createMockHistory(20, 100); // ~500+ tokens
const result = validateContextLength(chatHistory, model);
expect(result.isValid).toBe(false);
expect(result.error).toContain("Context length exceeded");
expect(result.error).toContain("input");
expect(result.error).toContain("max_tokens");
expect(result.error).toContain("context_limit");
});
it("should handle large models with appropriate scaling", () => {
const model = createMockModel(200_000, 64_000); // Claude-like model
const chatHistory = createMockHistory(100, 1000); // Large conversation
const result = validateContextLength(chatHistory, model);
expect(result.contextLimit).toBe(200_000);
expect(result.maxTokens).toBe(64_000);
});
});

View file

@ -78,14 +78,14 @@ describe("tokenizer", () => {
role: "user",
content: [
{ type: "text", text: "Hello" }, // 5 chars -> ~2 tokens
{ type: "imageUrl", imageUrl: { url: "test.jpg" } }, // +85 tokens
{ type: "imageUrl", imageUrl: { url: "test.jpg" } }, // +1024 tokens
],
},
contextItems: [],
};
const tokenCount = countChatHistoryItemTokens(historyItem);
expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens
expect(tokenCount).toBe(1028); // 2 + 1024 + 2 role tokens
});
it("should count tokens for tool calls", () => {

View file

@ -47,7 +47,7 @@ export function countChatHistoryItemTokens(
// Images and other content types have their own token costs
// but we'll use a rough estimate for now
if (part.type === "imageUrl") {
tokenCount += 85; // Rough estimate for image tokens
tokenCount += 1024; // Rough estimate for image tokens
}
}
}
@ -192,3 +192,46 @@ export function getAutoCompactMessage(model: ModelConfig): string {
const limit = getModelContextLimit(model);
return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`;
}
/**
* Validates that the input tokens + max_tokens don't exceed context limit
* @param chatHistory The chat history to validate
* @param model The model configuration
* @returns Validation result with error details if invalid
*/
export function validateContextLength(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
): {
isValid: boolean;
error?: string;
inputTokens?: number;
contextLimit?: number;
maxTokens?: number;
} {
const inputTokens = countChatHistoryTokens(chatHistory);
const contextLimit = getModelContextLimit(model);
const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;
// If maxTokens is not set, use 35% default reservation for output
const reservedForOutput =
maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35);
const totalRequired = inputTokens + reservedForOutput;
if (totalRequired > contextLimit) {
return {
isValid: false,
error: `Context length exceeded: input (${inputTokens.toLocaleString()}) + max_tokens (${reservedForOutput.toLocaleString()}) = ${totalRequired.toLocaleString()} > context_limit (${contextLimit.toLocaleString()})`,
inputTokens,
contextLimit,
maxTokens: reservedForOutput,
};
}
return {
isValid: true,
inputTokens,
contextLimit,
maxTokens: reservedForOutput,
};
}

View file

@ -45,6 +45,76 @@ class IntelliJIDE(
private val continuePluginService: ContinuePluginService,
) : IDE {
// Security-focused ignore patterns - should always be excluded for security reasons
private val DEFAULT_SECURITY_IGNORE_FILETYPES = listOf(
// Environment and configuration files with secrets
"*.env", "*.env.*", ".env*", "config.json", "config.yaml", "config.yml",
"settings.json", "appsettings.json", "appsettings.*.json",
// Certificate and key files
"*.key", "*.pem", "*.p12", "*.pfx", "*.crt", "*.cer", "*.jks",
"*.keystore", "*.truststore",
// Database files that may contain sensitive data
"*.db", "*.sqlite", "*.sqlite3", "*.mdb", "*.accdb",
// Credential and secret files
"*.secret", "*.secrets", "credentials", "credentials.*", "auth.json",
"token", "token.*", "*.token",
// Backup files that might contain sensitive data
"*.bak", "*.backup", "*.old", "*.orig",
// Docker secrets
"docker-compose.override.yml", "docker-compose.override.yaml",
// SSH and GPG
"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "*.ppk", "*.gpg"
)
private val DEFAULT_SECURITY_IGNORE_DIRS = listOf(
// Environment and configuration directories
".env/", "env/",
// Cloud provider credential directories
".aws/", ".gcp/", ".azure/", ".kube/", ".docker/",
// Secret directories
"secrets/", ".secrets/", "private/", ".private/", "certs/",
"certificates/", "keys/", ".ssh/", ".gnupg/", ".gpg/",
// Temporary directories that might contain sensitive data
"tmp/secrets/", "temp/secrets/", ".tmp/"
)
// Additional non-security patterns for general indexing exclusion
private val ADDITIONAL_SEARCH_IGNORE_FILETYPES = listOf(
"*.DS_Store", "*-lock.json", "*.lock", "*.log", "*.ttf", "*.png",
"*.jpg", "*.jpeg", "*.gif", "*.mp4", "*.svg", "*.ico", "*.pdf",
"*.zip", "*.gz", "*.tar", "*.dmg", "*.tgz", "*.rar", "*.7z",
"*.exe", "*.dll", "*.obj", "*.o", "*.o.d", "*.a", "*.lib",
"*.so", "*.dylib", "*.ncb", "*.sdf", "*.woff", "*.woff2",
"*.eot", "*.cur", "*.avi", "*.mpg", "*.mpeg", "*.mov", "*.mp3",
"*.mkv", "*.webm", "*.jar", "*.onnx", "*.parquet", "*.pqt",
"*.wav", "*.webp", "*.wasm", "*.plist", "*.profraw", "*.gcda",
"*.gcno", "go.sum", "*.gitignore", "*.gitkeep", "*.continueignore",
"*.csv", "*.uasset", "*.pdb", "*.bin", "*.pag", "*.swp", "*.jsonl"
)
private val ADDITIONAL_SEARCH_IGNORE_DIRS = listOf(
".git/", ".svn/", "node_modules/", "dist/", "build/", "Build/",
"target/", "out/", "bin/", ".pytest_cache/", ".vscode-test/",
"__pycache__/", "site-packages/", ".gradle/", ".mvn/", ".cache/",
"gems/", "vendor/", ".venv/", "venv/", ".vscode/", ".idea/", ".vs/",
".continue/"
)
// Combined patterns for use in ripgrep
private val DEFAULT_IGNORES = DEFAULT_SECURITY_IGNORE_FILETYPES +
DEFAULT_SECURITY_IGNORE_DIRS +
ADDITIONAL_SEARCH_IGNORE_FILETYPES +
ADDITIONAL_SEARCH_IGNORE_DIRS
private val gitService = GitService(project, continuePluginService)
private val fileUtils = FileUtils(project)
@ -335,6 +405,9 @@ class IntelliJIDE(
val ideInfo = this.getIdeInfo()
if (ideInfo.remoteName == "local") {
try {
// Create a single combined ignore pattern using glob brace expansion
val defaultIgnorePattern = DEFAULT_IGNORES.joinToString(",") { it }
var commandArgs = mutableListOf<String>(
ripgrep,
"--files",
@ -343,7 +416,9 @@ class IntelliJIDE(
"--ignore-file",
".continueignore",
"--ignore-file",
".gitignore"
".gitignore",
"--glob",
"!{${defaultIgnorePattern}}"
)
if (maxResults != null) {
commandArgs.add("--max-count")
@ -370,6 +445,9 @@ class IntelliJIDE(
val ideInfo = this.getIdeInfo()
if (ideInfo.remoteName == "local") {
try {
// Create a single combined ignore pattern for ripgrep
val defaultIgnorePattern = DEFAULT_IGNORES.joinToString(",") { it }
val commandArgs = mutableListOf(
ripgrep,
"-i",
@ -379,7 +457,9 @@ class IntelliJIDE(
".gitignore",
"-C",
"2",
"--heading"
"--heading",
"--glob",
"!{${defaultIgnorePattern}}" // Exclude all default ignores using brace expansion
)
// Conditionally add maxResults flag

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.3.3",
"version": "1.3.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.3.3",
"version": "1.3.10",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../../packages/config-types",
@ -231,17 +231,22 @@
},
"../../packages/fetch": {
"name": "@continuedev/fetch",
"version": "1.0.16",
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/follow-redirects": "^1.14.4",
"semantic-release": "^21.1.2",
"typescript": "^5.0.0",
"vitest": "^3.2.0"
}

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.3.9",
"version": "1.3.10",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -3,6 +3,7 @@ import { exec } from "node:child_process";
import { Range } from "core";
import { EXTENSION_NAME } from "core/control-plane/env";
import { DEFAULT_IGNORES, defaultIgnoresGlob } from "core/indexing/ignore";
import * as URI from "uri-js";
import * as vscode from "vscode";
@ -452,7 +453,9 @@ class VsCodeIde implements IDE {
resolve(output);
} else if (code === 1) {
// No matches
resolve("No matches found");
resolve(
"No matches found. Build, secrets, etc. dirs and files are not included.",
);
} else {
reject(new Error(`Process exited with code ${code}`));
}
@ -464,6 +467,8 @@ class VsCodeIde implements IDE {
pattern: string,
maxResults?: number,
): Promise<string[]> {
// Create a single combined ignore pattern for ripgrep (calculated once)
if (vscode.env.remoteName) {
// TODO better tests for this remote search implementation
// throw new Error("Ripgrep not supported, this workspace is remote");
@ -475,6 +480,11 @@ class VsCodeIde implements IDE {
);
const ignoreGlobs: Set<string> = new Set();
// Add default ignores from core
for (const pattern of DEFAULT_IGNORES) {
ignoreGlobs.add(pattern);
}
for (const file of ignoreFiles) {
const content = await this.ideUtils.readFile(file);
if (content === null) {
@ -535,6 +545,7 @@ class VsCodeIde implements IDE {
return results.map((result) => vscode.workspace.asRelativePath(result));
} else {
const results: string[] = [];
// Create a single combined ignore pattern using glob brace expansion
for (const dir of await this.getWorkspaceDirs()) {
const dirResults = await this.runRipgrepQuery(dir, [
"--files",
@ -544,6 +555,8 @@ class VsCodeIde implements IDE {
".continueignore",
"--ignore-file",
".gitignore",
"--glob",
defaultIgnoresGlob,
...(maxResults ? ["--max-count", String(maxResults)] : []),
]);
@ -566,6 +579,7 @@ class VsCodeIde implements IDE {
throw new Error("Ripgrep not supported, this workspace is remote");
}
const results: string[] = [];
for (const dir of await this.getWorkspaceDirs()) {
const dirResults = await this.runRipgrepQuery(dir, [
"-i", // Case-insensitive search
@ -576,6 +590,9 @@ class VsCodeIde implements IDE {
"-C",
"2", // Show 2 lines of context
"--heading", // Only show filepath once per result
// Use a single glob with all default ignores
"--glob",
defaultIgnoresGlob,
...(maxResults ? ["-m", maxResults.toString()] : []),
"-e",
query, // Pattern to search for

View file

@ -9,6 +9,7 @@ import { Core } from "core/core";
import { walkDirAsync } from "core/indexing/walkDir";
import { isModelInstaller } from "core/llm";
import { startLocalOllama } from "core/util/ollamaHelper";
import { startLocalLemonade } from "core/util/lemonadeHelper";
import { getConfigJsonPath, getConfigYamlPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
@ -620,6 +621,9 @@ const getCommandsMap: (
"continue.startLocalOllama": () => {
startLocalOllama(ide);
},
"continue.startLocalLemonade": () => {
startLocalLemonade(ide);
},
"continue.installModel": async (
modelName: string,
llmProvider: ILLM | undefined,

View file

@ -76,6 +76,39 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.disposables.push(disposable);
}
/** ensures the current target file is open and focused before performing edits*/
private async ensureCurrentFileIsFocused() {
const targetUri = this.editor.document.uri;
const active = vscode.window.activeTextEditor;
if (
active &&
URI.equal(active.document.uri.toString(), targetUri.toString())
) {
this.editor = active;
return;
}
const visible = vscode.window.visibleTextEditors.find((foundEditor) =>
URI.equal(foundEditor.document.uri.toString(), targetUri.toString()),
);
if (visible) {
await vscode.window.showTextDocument(visible.document, {
preview: false,
preserveFocus: false,
viewColumn: visible.viewColumn,
});
this.editor = vscode.window.activeTextEditor ?? visible;
return;
}
const doc = await vscode.workspace.openTextDocument(targetUri);
const editor = await vscode.window.showTextDocument(doc, {
preview: false,
preserveFocus: false,
});
this.editor = editor;
}
public get range(): vscode.Range {
const startLine = Math.min(this.startLine, this.endLine);
const endLine = Math.max(this.startLine, this.endLine);
@ -296,6 +329,8 @@ export class VerticalDiffHandler implements vscode.Disposable {
// Diff is messed up without this delay.
await new Promise((resolve) => setTimeout(resolve, 100));
await this.ensureCurrentFileIsFocused();
// First, we reset the original diff by rejecting all pending diff blocks
const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? [];
for (const block of blocks.reverse()) {
@ -443,6 +478,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
private async insertTextAboveLine(index: number, text: string) {
await this.ensureCurrentFileIsFocused();
await this.editor.edit(
(editBuilder) => {
const lineCount = this.editor.document.lineCount;
@ -471,6 +507,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
private async deleteLinesAt(index: number, numLines = 1) {
const startLine = new vscode.Position(index, 0);
await this.ensureCurrentFileIsFocused();
await this.editor.edit(
(editBuilder) => {
editBuilder.delete(
@ -482,6 +519,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
private async deleteRangeLines(ranges: vscode.Range[]) {
await this.ensureCurrentFileIsFocused();
await this.editor.edit(
(editBuilder) => {
for (const range of ranges) {

View file

@ -51,7 +51,7 @@ export class VerticalDiffManager {
this.fileUriToHandler.get(fileUri)?.clear(false);
this.fileUriToHandler.delete(fileUri);
}
const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files
const editor = vscode.window.activeTextEditor;
if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
const handler = new VerticalDiffHandler(
startLine,

View file

@ -3,13 +3,41 @@ import { isModelInstaller } from "core/llm";
import * as vscode from "vscode";
/**
* @param error Handles common LLM errors. Currently only handles Ollama-related errors.
* @param error Handles common LLM errors. Currently handles Ollama and Lemonade-related errors.
* @returns true if error is handled, false otherwise
*/
export async function handleLLMError(error: unknown): Promise<boolean> {
if (!error || !(error instanceof Error) || !error.message) {
return false;
}
// Handle Lemonade errors
if (error.message.toLowerCase().includes("lemonade")) {
let message: string = error.message;
let options: string[] | undefined;
// For Windows, offer to start Lemonade if it's installed but not running
if (
process.platform === "win32" &&
message.includes("Lemonade server may not be running")
) {
options = ["Start Lemonade", "Setup Instructions"];
} else {
// For all other cases (Linux, not installed, etc.), direct to setup instructions
options = ["Setup Instructions"];
}
vscode.window.showErrorMessage(message, ...options).then((val) => {
if (val === "Setup Instructions") {
vscode.env.openExternal(vscode.Uri.parse("https://lemonade-server.ai"));
} else if (val === "Start Lemonade") {
vscode.commands.executeCommand("continue.startLocalLemonade");
}
});
return true;
}
// Handle Ollama errors
if (!error.message.toLowerCase().includes("ollama")) {
return false;
}

View file

@ -107,7 +107,7 @@ export class VsCodeWebviewProtocol
if (e.cause) {
if (e.cause.name === "ConnectTimeoutError") {
message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://docs.continue.dev/reference/config`;
message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in your config by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://docs.continue.dev/reference/config`;
} else if (e.cause.code === "ECONNREFUSED") {
message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://docs.continue.dev/reference/Model%20Providers/openai#openai-compatible-servers--apis`;
} else {

8
gui/package-lock.json generated
View file

@ -234,10 +234,11 @@
}
},
"../packages/config-yaml": {
"version": "1.0.96",
"name": "@continuedev/config-yaml",
"version": "1.14.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
@ -260,6 +261,7 @@
}
},
"../packages/terminal-security": {
"name": "@continuedev/terminal-security",
"version": "1.0.0",
"license": "Apache-2.0",
"dependencies": {
@ -269,7 +271,7 @@
"@types/node": "^20.11.19",
"@types/shell-quote": "^1.7.5",
"typescript": "^5.5.2",
"vitest": "^1.6.0"
"vitest": "^3.2.4"
}
},
"node_modules/@adobe/css-tools": {

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View file

@ -1,4 +1,7 @@
import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
import {
Cog6ToothIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import { useContext, useMemo } from "react";
import { useNavigate } from "react-router-dom";
@ -48,7 +51,7 @@ export function AssistantOption({
disabled={hasFatalErrors}
onClick={!hasFatalErrors ? handleOptionClick : undefined}
fontSizeModifier={-2}
className={selected ? "bg-list-active text-list-active-foreground" : ""}
className={`group ${selected ? "bg-list-active text-list-active-foreground" : ""}`}
>
<div className="flex w-full items-center justify-between gap-10 py-0.5">
<div className="flex w-full items-center gap-3">
@ -62,6 +65,20 @@ export function AssistantOption({
</span>
</div>
<div className="flex flex-row items-center gap-1.5">
<Button
variant="ghost"
size="sm"
className="text-description-muted hover:enabled:text-foreground my-0 h-4 w-4 p-0 opacity-0 transition-opacity group-hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
ideMessenger.post("config/openProfile", {
profileId: profile.id,
});
onClick(); // Close the listbox
}}
>
<Cog6ToothIcon className="h-3.5 w-3.5" />
</Button>
{profile.errors && profile.errors?.length > 0 && (
<ToolTip content="View errors">
<Button

View file

@ -1,14 +1,16 @@
import { CheckIcon } from "@heroicons/react/24/outline";
import { Cog6ToothIcon } from "@heroicons/react/24/outline";
import {
BuildingOfficeIcon,
UserCircleIcon,
UserIcon,
} from "@heroicons/react/24/solid";
import { useContext } from "react";
import { useNavigate } from "react-router-dom";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { setSelectedOrgId } from "../../redux/slices/profilesSlice";
import { ListboxOption } from "../ui";
import { CONFIG_ROUTES } from "../../util/navigation";
import { Button, ListboxOption } from "../ui";
interface OrganizationOptionProps {
organization: { id: string; name: string; iconUrl?: string | null };
@ -45,6 +47,7 @@ export function OrganizationOption({
onClose,
}: OrganizationOptionProps) {
const dispatch = useAppDispatch();
const navigate = useNavigate();
const ideMessenger = useContext(IdeMessengerContext);
const selectedOrgId = useAppSelector(
(state) => state.profiles.selectedOrganizationId,
@ -64,7 +67,7 @@ export function OrganizationOption({
value={organization.id}
onClick={handleOptionClick}
fontSizeModifier={-2}
className={isSelected ? "bg-list-active text-list-active-foreground" : ""}
className={`group ${isSelected ? "bg-list-active text-list-active-foreground" : ""}`}
>
<div className="flex w-full items-center justify-between gap-10 py-0.5">
<div className="flex w-full items-center gap-3">
@ -78,7 +81,18 @@ export function OrganizationOption({
</span>
</div>
<div className="flex flex-row items-center gap-1.5">
{isSelected && <CheckIcon className="h-3.5 w-3.5 flex-shrink-0" />}
<Button
variant="ghost"
size="sm"
className="text-description-muted hover:enabled:text-foreground my-0 h-4 w-4 p-0 opacity-0 transition-opacity group-hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
navigate(CONFIG_ROUTES.ORGANIZATIONS);
onClose(); // Close the listbox
}}
>
<Cog6ToothIcon className="h-3.5 w-3.5" />
</Button>
</div>
</div>
</ListboxOption>

View file

@ -2,9 +2,7 @@ import {
ArrowPathIcon,
ArrowRightStartOnRectangleIcon,
Cog6ToothIcon,
PencilIcon,
PlusIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { isOnPremSession } from "core/control-plane/AuthTypes";
import { useContext, useEffect, useRef } from "react";
@ -155,7 +153,7 @@ export function AssistantAndOrgListbox({
className="max-h-32 -translate-x-1.5 overflow-y-auto pb-0"
style={{ zIndex: 200 }}
>
<div className="flex items-center justify-between p-2">
<div className="flex items-center justify-between px-1.5 py-1">
<span className="text-description text-xs font-medium">
Agents
</span>
@ -193,7 +191,7 @@ export function AssistantAndOrgListbox({
{shouldRenderOrgInfo && (
<>
<Divider className="!mb-0.5 !mt-0" />
<div className="flex items-center justify-between p-2">
<div className="flex items-center justify-between px-1.5 py-1">
<span className="text-description text-xs font-medium">
Organizations
</span>
@ -232,34 +230,6 @@ export function AssistantAndOrgListbox({
{/* Settings Section */}
{variant !== "sidebar" && (
<div>
<Button
onClick={(e) => {
e.stopPropagation();
onRulesConfig();
}}
variant="ghost"
size="sm"
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
>
<div className="flex w-full items-center">
<PencilIcon className="ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0" />
<span className="text-2xs">Rules</span>
</div>
</Button>
<Button
onClick={(e) => {
e.stopPropagation();
onToolsConfig();
}}
variant="ghost"
size="sm"
className="text-description hover:bg-input my-0 w-full justify-start py-1.5 pl-1 text-left"
>
<div className="flex w-full items-center">
<WrenchScrewdriverIcon className="ml-1.5 mr-2 h-3.5 w-3.5 flex-shrink-0" />
<span className="text-2xs">Tools</span>
</div>
</Button>
<Button
onClick={(e) => {
e.stopPropagation();

View file

@ -1,6 +1,6 @@
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers, RuleWithSource } from "core";
import { useMemo } from "react";
import { memo, useMemo } from "react";
import { defaultBorderRadius, vscBackground } from "..";
import { useAppSelector } from "../../redux/hooks";
import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
@ -69,16 +69,20 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const historyKey = isInEdit ? "edit" : "chat";
const placeholder = isInEdit ? "Edit selected code" : undefined;
const toolbarOptions: ToolbarOptions = isInEdit
? {
const toolbarOptions: ToolbarOptions = useMemo(() => {
if (isInEdit) {
return {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
enterText:
editModeState.applyState.status === "done" ? "Retry" : "Edit",
}
: {};
} as ToolbarOptions;
}
// Stable empty object to avoid re-renders from identity changes
return {} as ToolbarOptions;
}, [isInEdit, editModeState.applyState.status]);
const { appliedRules = [], contextItems = [] } = props;
@ -123,4 +127,4 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
);
}
export default ContinueInputBox;
export default memo(ContinueInputBox);

View file

@ -9,7 +9,7 @@ import {
modelSupportsImages,
modelSupportsReasoning,
} from "core/llm/autodetect";
import { useContext, useRef } from "react";
import { memo, useContext, useRef } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
@ -242,4 +242,24 @@ function InputToolbar(props: InputToolbarProps) {
);
}
export default InputToolbar;
function shallowToolbarOptionsEqual(a?: ToolbarOptions, b?: ToolbarOptions) {
if (a === b) return true;
if (!a || !b) return false;
return (
a.hideAddContext === b.hideAddContext &&
a.hideImageUpload === b.hideImageUpload &&
a.hideUseCodebase === b.hideUseCodebase &&
a.hideSelectModel === b.hideSelectModel &&
a.enterText === b.enterText
);
}
export default memo(
InputToolbar,
(prev, next) =>
prev.hidden === next.hidden &&
prev.disabled === next.disabled &&
prev.isMainInput === next.isMainInput &&
prev.activeKey === next.activeKey &&
shallowToolbarOptionsEqual(prev.toolbarOptions, next.toolbarOptions),
);

View file

@ -6,7 +6,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger";
type SectionKey = Exclude<
keyof ConfigYaml,
"name" | "version" | "schema" | "metadata" | "env"
"name" | "version" | "schema" | "metadata" | "env" | "requestOptions"
>;
interface EditBlockButtonProps<T extends SectionKey> {

View file

@ -1,24 +1,45 @@
import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
import {
CubeIcon,
ExclamationTriangleIcon,
PencilIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppSelector } from "../../../../redux/hooks";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import {
selectPendingToolCalls,
selectToolCallsByStatus,
} from "../../../../redux/selectors/selectToolCalls";
import { setSelectedProfile } from "../../../../redux/slices/profilesSlice";
import FreeTrialButton from "../../../FreeTrialButton";
import { ToolTip } from "../../../gui/Tooltip";
import HoverItem from "../../InputToolbar/HoverItem";
import { usesFreeTrialApiKey } from "core/config/usesFreeTrialApiKey";
import type { FreeTrialStatus } from "core/control-plane/client";
import { useAuth } from "../../../../context/Auth";
import { getLocalStorage } from "../../../../util/localStorage";
import { CONFIG_ROUTES } from "../../../../util/navigation";
import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox";
export function BlockSettingsTopToolbar() {
const navigate = useNavigate();
const dispatch = useAppDispatch();
const { selectedProfile } = useAuth();
const configError = useAppSelector((store) => store.config.configError);
const config = useAppSelector((state) => state.config.config);
const ideMessenger = useContext(IdeMessengerContext);
const pendingToolCalls = useAppSelector(selectPendingToolCalls);
const callingToolCalls = useAppSelector((state) =>
selectToolCallsByStatus(state, "calling"),
);
const hasActiveContent =
pendingToolCalls.length > 0 || callingToolCalls.length > 0;
const [freeTrialStatus, setFreeTrialStatus] =
useState<FreeTrialStatus | null>(null);
const hasExitedFreeTrial = getLocalStorage("hasExitedFreeTrial");
@ -53,9 +74,39 @@ export function BlockSettingsTopToolbar() {
const shouldShowError = configError && configError?.length > 0;
const handleRulesClick = () => {
if (selectedProfile) {
dispatch(setSelectedProfile(selectedProfile.id));
ideMessenger.post("didChangeSelectedProfile", {
id: selectedProfile.id,
});
}
navigate(CONFIG_ROUTES.RULES);
};
const handleToolsClick = () => {
if (selectedProfile) {
dispatch(setSelectedProfile(selectedProfile.id));
ideMessenger.post("didChangeSelectedProfile", {
id: selectedProfile.id,
});
}
navigate(CONFIG_ROUTES.TOOLS);
};
const handleModelsClick = () => {
if (selectedProfile) {
dispatch(setSelectedProfile(selectedProfile.id));
ideMessenger.post("didChangeSelectedProfile", {
id: selectedProfile.id,
});
}
navigate(CONFIG_ROUTES.MODELS);
};
return (
<div className="flex flex-1 items-center justify-between gap-1.5">
<div>
<div className="flex items-center gap-1">
{shouldShowError && (
<ToolTip delayShow={700} content="View configuration errors">
<div
@ -78,7 +129,30 @@ export function BlockSettingsTopToolbar() {
</div>
</ToolTip>
)}
{!hasActiveContent && (
<div className="flex items-center gap-1.5">
<ToolTip content="Configure rules">
<HoverItem onClick={handleRulesClick} px={2}>
<PencilIcon className="text-description-muted h-3 w-3 hover:brightness-125" />
</HoverItem>
</ToolTip>
<ToolTip content="Configure tools">
<HoverItem onClick={handleToolsClick} px={2}>
<WrenchScrewdriverIcon className="text-description-muted h-3 w-3 hover:brightness-125" />
</HoverItem>
</ToolTip>
<ToolTip content="Configure models">
<HoverItem onClick={handleModelsClick} px={2}>
<CubeIcon className="text-description-muted h-3 w-3 hover:brightness-125" />
</HoverItem>
</ToolTip>
</div>
)}
</div>
<ToolTip
place="top"
content={isUsingFreeTrial ? "View free trial usage" : "Select Agent"}

View file

@ -1,7 +1,14 @@
import { Editor, EditorContent, JSONContent } from "@tiptap/react";
import { ContextProviderDescription, InputModifiers } from "core";
import { modelSupportsImages } from "core/llm/autodetect";
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import {
memo,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import useIsOSREnabled from "../../../hooks/useIsOSREnabled";
import useUpdatingRef from "../../../hooks/useUpdatingRef";
@ -38,7 +45,7 @@ export interface TipTapEditorProps {
export const TIPPY_DIV_ID = "tippy-js-div";
export function TipTapEditor(props: TipTapEditorProps) {
function TipTapEditorInner(props: TipTapEditorProps) {
const dispatch = useAppDispatch();
const mainEditorContext = useMainEditor();
@ -72,12 +79,13 @@ export function TipTapEditor(props: TipTapEditorProps) {
return;
}
const placeholder = getPlaceholderText(props.placeholder, historyLength);
editor.extensionManager.extensions.filter(
(extension) => extension.name === "placeholder",
)[0].options["placeholder"] = placeholder;
editor.view.dispatch(editor.state.tr);
const placeholderExt = editor.extensionManager.extensions.find(
(e) => e.name === "placeholder",
) as any;
if (placeholderExt) {
placeholderExt.options["placeholder"] = placeholder;
editor.view.dispatch(editor.state.tr);
}
}, [editor, props.placeholder, historyLength]);
useEffect(() => {
@ -112,6 +120,23 @@ export function TipTapEditor(props: TipTapEditorProps) {
}
}, [props.isMainInput, isStreaming, editor]);
// Recovery mechanism: ensure historical inputs regain editability when streaming ends
useEffect(() => {
if (!isStreaming && !props.isMainInput && editor) {
// Small delay to ensure editor state has settled after streaming transition
const timeoutId = setTimeout(() => {
if (editor && !editor.isDestroyed) {
// Force re-enable the editor
editor.setOptions({ editable: true });
// Trigger view update to refresh editor state
editor.view.dispatch(editor.state.tr);
}
}, 100);
return () => clearTimeout(timeoutId);
}
}, [isStreaming, props.isMainInput]);
const [showDragOverMsg, setShowDragOverMsg] = useState(false);
const [activeKey, setActiveKey] = useState<string | null>(null);
@ -281,3 +306,37 @@ export function TipTapEditor(props: TipTapEditorProps) {
</InputBoxDiv>
);
}
function toolbarOptionsEqual(a?: ToolbarOptions, b?: ToolbarOptions) {
if (a === b) return true;
if (!a || !b) return false;
return (
a.hideAddContext === b.hideAddContext &&
a.hideImageUpload === b.hideImageUpload &&
a.hideUseCodebase === b.hideUseCodebase &&
a.hideSelectModel === b.hideSelectModel &&
a.enterText === b.enterText
);
}
const MemoInner = memo(
TipTapEditorInner,
(prev, next) =>
prev.isMainInput === next.isMainInput &&
prev.placeholder === next.placeholder &&
prev.historyKey === next.historyKey &&
prev.inputId === next.inputId &&
toolbarOptionsEqual(prev.toolbarOptions, next.toolbarOptions) &&
(prev.availableContextProviders?.length || 0) ===
(next.availableContextProviders?.length || 0) &&
(prev.availableSlashCommands?.length || 0) ===
(next.availableSlashCommands?.length || 0),
);
export function TipTapEditor(props: TipTapEditorProps) {
return (
<div className="relative w-full">
<MemoInner {...props} />
</div>
);
}

View file

@ -1,5 +1,5 @@
import { Editor } from "@tiptap/react";
import { KeyboardEvent } from "react";
import { KeyboardEvent, useRef } from "react";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../../util";
import {
handleJetBrainsOSRMetaKeyIssues,
@ -13,6 +13,7 @@ export function useEditorEventHandlers(options: {
setActiveKey: (key: string | null) => void;
}) {
const { editor, isOSREnabled, editorFocusedRef, setActiveKey } = options;
const metaActiveRef = useRef(false);
/**
* This handles various issues with meta key actions
@ -31,10 +32,14 @@ export function useEditorEventHandlers(options: {
return;
}
setActiveKey(e.key);
if (!editorFocusedRef?.current || !isMetaEquivalentKeyPressed(e)) return;
// Only set activeKey for Meta/Control/Alt to drive toolbar highlighting
if (e.key === "Meta" || e.key === "Control" || e.key === "Alt") {
setActiveKey(e.key);
metaActiveRef.current = true;
}
if (isOSREnabled) {
handleJetBrainsOSRMetaKeyIssues(e, editor);
} else if (!isJetBrains()) {
@ -42,7 +47,12 @@ export function useEditorEventHandlers(options: {
}
};
const handleKeyUp = () => setActiveKey(null);
const handleKeyUp = () => {
if (metaActiveRef.current) {
setActiveKey(null);
metaActiveRef.current = false;
}
};
return { handleKeyDown, handleKeyUp };
}

View file

@ -1,6 +1,5 @@
import {
ArrowPathIcon,
CheckIcon,
ChevronDownIcon,
Cog6ToothIcon,
CubeIcon,
@ -16,7 +15,9 @@ import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { updateSelectedModelByRole } from "../../redux/thunks/updateSelectedModelByRole";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { CONFIG_ROUTES } from "../../util/navigation";
import { ToolTip } from "../gui/Tooltip";
import {
Button,
Listbox,
ListboxButton,
ListboxOption,
@ -57,6 +58,8 @@ function ModelOption({
showMissingApiKeyMsg,
isSelected,
}: ModelOptionProps) {
const navigate = useNavigate();
function handleOptionClick(e: any) {
if (showMissingApiKeyMsg) {
e.preventDefault();
@ -64,12 +67,18 @@ function ModelOption({
}
}
function handleConfigureClick(e: React.MouseEvent) {
e.stopPropagation();
navigate(CONFIG_ROUTES.MODELS);
}
return (
<ListboxOption
key={idx}
disabled={showMissingApiKeyMsg}
value={option.value}
onClick={handleOptionClick}
className={`group ${isSelected ? "bg-list-active text-list-active-foreground" : ""}`}
>
<div className="flex w-full items-center justify-between gap-5">
<div className="flex items-center gap-2 py-0.5">
@ -88,9 +97,14 @@ function ModelOption({
)}
</span>
</div>
<CheckIcon
className={`h-3 w-3 flex-shrink-0 ${isSelected ? "" : "invisible"}`}
/>
<Button
variant="ghost"
size="sm"
className="text-description-muted hover:enabled:text-foreground my-0 h-4 w-4 p-0 opacity-0 transition-opacity group-hover:opacity-100"
onClick={handleConfigureClick}
>
<Cog6ToothIcon className="h-3.5 w-3.5" />
</Button>
</div>
</ListboxOption>
);
@ -245,8 +259,21 @@ function ModelSelect() {
/>
</ListboxButton>
<ListboxOptions className="min-w-[160px]">
<div className="flex items-center justify-between gap-1 px-2 py-1">
<span className="text-description font-semibold">Models</span>
<div className="flex items-center justify-between px-1.5 py-1">
<span className="text-description text-xs font-medium">Models</span>
<div className="flex items-center gap-0.5">
<Button
onClick={(e) => {
e.stopPropagation();
onClickConfigureModels(e);
}}
variant="ghost"
size="sm"
className="my-0 h-5 w-5 p-0"
>
<Cog6ToothIcon className="text-description h-3.5 w-3.5" />
</Button>
</div>
</div>
<div className="no-scrollbar max-h-[300px] overflow-y-auto">
@ -274,36 +301,26 @@ function ModelSelect() {
{!isConfigLoading && (
<>
<Divider className="!mb-0" />
{selectedProfile?.profileType === "local" && (
<ListboxOption
key={options.length}
onClick={onClickAddModel}
value={"addModel" as any}
fontSizeModifier={-2}
className="px-2 py-2"
>
<span className="text-description text-2xs flex flex-row items-center">
<PlusIcon className="mr-1.5 h-3.5 w-3.5" />
Add Chat model
</span>
</ListboxOption>
<>
<Divider className="!mb-0" />
<ListboxOption
key={options.length}
onClick={onClickAddModel}
value={"addModel" as any}
fontSizeModifier={-2}
className="px-2 py-2"
>
<span className="text-description text-2xs flex flex-row items-center">
<PlusIcon className="mr-1.5 h-3.5 w-3.5" />
Add Chat model
</span>
</ListboxOption>
</>
)}
<ListboxOption
value="configure-models"
fontSizeModifier={-2}
className="px-2 py-2"
onClick={onClickConfigureModels}
>
<span className="text-description text-2xs flex flex-row items-center">
<Cog6ToothIcon className="mr-1.5 h-3.5 w-3.5" />
Configure models
</span>
</ListboxOption>
<Divider className="!my-0" />
<div className="text-description flex items-center justify-between gap-1.5 px-2 py-2">
<div className="text-description flex items-center justify-start p-2">
<span className="block" style={{ fontSize: tinyFont }}>
<code>{getMetaKeyLabel()}'</code> to toggle model
</span>

View file

@ -1,57 +0,0 @@
import styled from "styled-components";
import {
defaultBorderRadius,
lightGray,
vscInputBackground,
vscListActiveBackground,
vscListActiveForeground,
} from "..";
const TopDiv = styled.div`
display: flex;
align-items: center;
text-align: center;
margin: auto;
width: fit-content;
cursor: pointer;
border: 1px solid ${lightGray};
background-color: ${vscInputBackground};
border-radius: ${defaultBorderRadius};
&:hover {
background-color: ${lightGray}55;
}
`;
const SubDiv = styled.div<{ selected: boolean }>`
text-align: center;
padding: 8px 12px;
border-radius: ${defaultBorderRadius};
transition: all 0.2s ease-in-out;
${(props) =>
props.selected &&
`
background-color: ${vscListActiveBackground};
color: ${vscListActiveForeground};
`}
`;
function Toggle(props: {
optionOne: string;
optionTwo: string;
selected: boolean;
onClick: () => void;
}) {
return (
<TopDiv onClick={props.onClick}>
<SubDiv selected={props.selected}>{props.optionOne}</SubDiv>
<SubDiv selected={!props.selected}>{props.optionTwo}</SubDiv>
</TopDiv>
);
}
export default Toggle;

View file

@ -0,0 +1,70 @@
import { CSSProperties, useEffect, useRef } from "react";
/**
* useRenderDebug
*
* Developer utility to visualize component re-renders.
*
* - Returns a `ref` to attach to a container element and a `count` that
* increments on every render of the component using this hook.
* - On each render, it briefly adds a CSS class (default: `rerender-flash`)
* to the element for a quick visual flash.
* - Use together with <RenderCountBadge /> to show the render count inline.
*
* Options:
* - enabled: boolean to toggle the effect (default true)
* - flashClassName: class added on each render (default `rerender-flash`)
* - flashDurationMs: duration of the flash animation in ms (default 180)
*/
export function useRenderDebug(options?: {
enabled?: boolean;
flashClassName?: string;
flashDurationMs?: number;
}) {
const {
enabled = true,
flashClassName = "rerender-flash",
flashDurationMs = 180,
} = options || {};
const ref = useRef<HTMLElement | null>(null);
const countRef = useRef(0);
countRef.current += 1;
useEffect(() => {
if (!enabled || !ref.current) return;
const el = ref.current;
el.classList.add(flashClassName);
const t = setTimeout(
() => el.classList.remove(flashClassName),
flashDurationMs,
);
return () => {
clearTimeout(t);
// Ensure we don't leave the flash class applied on cleanup
el.classList.remove(flashClassName);
};
});
return { ref, count: countRef.current, countRef } as const;
}
export function RenderCountBadge(props: {
count: number;
title?: string;
style?: CSSProperties;
className?: string;
}) {
// Simple badge for use with useRenderDebug; keep lightweight.
const { count, title = `Renders: ${count}`, style, className } = props;
return (
<span
className={`render-count ${className || ""}`}
title={title}
style={style}
>
R{count}
</span>
);
}

View file

@ -119,3 +119,28 @@ body {
.scroll-container:is(:hover, :focus)::-webkit-scrollbar {
display: block; /* Show scrollbar only on hover or focus */
}
/* Debug: visible flash when component re-renders */
@keyframes rerenderFlash {
0% {
box-shadow: 0 0 0 2px rgba(255, 0, 0, 0.9) inset;
}
100% {
box-shadow: 0 0 0 0 rgba(255, 0, 0, 0) inset;
}
}
.rerender-flash {
animation: rerenderFlash 180ms ease-out;
}
.render-count {
display: inline-block;
margin-right: 6px;
padding: 0 4px;
border-radius: 3px;
background: rgba(255, 0, 0, 0.15);
color: rgba(255, 0, 0, 0.9);
font-weight: 600;
letter-spacing: 0.02em;
}

Some files were not shown because too many files have changed in this diff Show more