From ac0fb0d388eb82e3187d33e681be5f8084315f31 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 13 May 2025 10:54:35 +0530 Subject: [PATCH 001/104] instructions to clean reset --- docs/docs/troubleshooting.mdx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index 71eac9d9b..dcb619f76 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -162,6 +162,10 @@ Most Continue features will work normally, including autocomplete and chat. Howe For more details about this requirement, see the [LanceDB issue #2195](https://github.com/lancedb/lance/issues/2195). +### Resetting the entire plugin + +In cases when you like to clean reset the plugin, you would need to delete the `~/.continue` directory (or `%USERPROFILE%\.continue` on Windows). This will remove all your local settings, sessions, and other customizations. After this you may want to reinstall the plugin. + ## Still having trouble? You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly. From d837f9215662b77ff45f0e2cab34a4c5cc89905a Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 13 May 2025 11:24:05 +0530 Subject: [PATCH 002/104] rename "apply" to "Apply Role" in sidebar --- docs/docs/customize/model-roles/apply.mdx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index 6cce4acbc..d1ee7609b 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -1,3 +1,10 @@ +--- +title: Apply Role +description: Apply model role +keywords: [apply, model, role] +sidebar_position: 4 +--- + When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file. ## Recommended Apply models From 952d13b22acf9217be032f22f818bc1eedc95df1 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 13 May 2025 10:00:10 -0700 Subject: [PATCH 003/104] Update docs/docs/troubleshooting.mdx --- docs/docs/troubleshooting.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index dcb619f76..b6df0dd22 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -162,7 +162,7 @@ Most Continue features will work normally, including autocomplete and chat. Howe For more details about this requirement, see the [LanceDB issue #2195](https://github.com/lancedb/lance/issues/2195). -### Resetting the entire plugin +### How do I reset the state of the extension? In cases when you like to clean reset the plugin, you would need to delete the `~/.continue` directory (or `%USERPROFILE%\.continue` on Windows). This will remove all your local settings, sessions, and other customizations. After this you may want to reinstall the plugin. From 7c4cd8313aa2f52a2b49445d6f1dc0e644046cbf Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 13 May 2025 10:02:09 -0700 Subject: [PATCH 004/104] Update docs/docs/troubleshooting.mdx --- docs/docs/troubleshooting.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index b6df0dd22..f6836e78c 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -164,7 +164,9 @@ For more details about this requirement, see the [LanceDB issue #2195](https://g ### How do I reset the state of the extension? -In cases when you like to clean reset the plugin, you would need to delete the `~/.continue` directory (or `%USERPROFILE%\.continue` on Windows). This will remove all your local settings, sessions, and other customizations. After this you may want to reinstall the plugin. +Continue stores it's data in the `~/.continue` directory (%USERPROFILE%\.continue` on Windows). + +If you'd like to perform a clean reset of the extension, including removing all configuration files, indices, etc, you can remove this directory, uninstall, and then reinstall. ## Still having trouble? From 971c4de33e1a3f117eafe9d64bf175c0d2a849ef Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 23 May 2025 11:27:15 +0530 Subject: [PATCH 005/104] feat: add agentinteraction dev data --- gui/src/redux/thunks/streamNormalInput.ts | 2 +- packages/config-yaml/src/schemas/data/index.ts | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 43e431271..a4ce0007d 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -75,7 +75,7 @@ export const streamNormalInput = createAsyncThunk< try { if (state.session.mode === "chat" || state.session.mode === "agent") { extra.ideMessenger.post("devdata/log", { - name: "chatInteraction", + name: state.session.mode === 'chat' ? "chatInteraction" : "agentInteraction", data: { prompt: next.value.prompt, completion: next.value.completion, diff --git a/packages/config-yaml/src/schemas/data/index.ts b/packages/config-yaml/src/schemas/data/index.ts index 7251e12a7..1d8b59547 100644 --- a/packages/config-yaml/src/schemas/data/index.ts +++ b/packages/config-yaml/src/schemas/data/index.ts @@ -72,6 +72,7 @@ const devEventAllVersionDataSchemas = z.object({ tokensGenerated: tokensGeneratedEventAllSchema, chatInteraction: chatInteractionEventAllSchema, editInteraction: editInteractionEventAllSchema, + agentInteraction: chatInteractionEventAllSchema }); // Version and level specific schemas are organized here @@ -97,6 +98,7 @@ export const devDataVersionedSchemas = { tokensGenerated: tokensGeneratedEventSchema_0_2_0, chatInteraction: chatInteractionEventSchema_0_2_0, editInteraction: editInteractionEventSchema_0_2_0, + agentInteraction: chatInteractionEventSchema_0_2_0, }, noCode: { autocomplete: autocompleteEventSchema_0_2_0_noCode, @@ -104,6 +106,7 @@ export const devDataVersionedSchemas = { tokensGenerated: tokensGeneratedEventSchema_0_2_0_noCode, chatInteraction: chatInteractionEventSchema_0_2_0_noCode, editInteraction: editInteractionEventSchema_0_2_0_noCode, + agentInteraction: chatInteractionEventSchema_0_2_0_noCode, }, }, }; From f09ada8d897b201baed917a048a1b2af9d5850b1 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 23 May 2025 11:40:09 +0530 Subject: [PATCH 006/104] added tests --- core/data/log.test.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/core/data/log.test.ts b/core/data/log.test.ts index e2471b6bd..5e9bcce5f 100644 --- a/core/data/log.test.ts +++ b/core/data/log.test.ts @@ -18,6 +18,18 @@ const TEST_EVENT: DevDataLogEvent = { provider: "openai", }, }; + +const TEST_AGENT_INTERACTION_EVENT: DevDataLogEvent = { + name: 'agentInteraction', + data: { + prompt: "Hello, world!", + completion: "Hello, world!", + modelProvider: "openai", + modelTitle: "gpt-4", + sessionId: "1234", + }, +} + const SCHEMA = "0.2.0"; describe("DataLogger", () => { @@ -157,6 +169,21 @@ describe("DataLogger", () => { expect(fileContent).toContain('"model":"gpt-4"'); expect(fileContent).toContain('"eventName":"tokensGenerated"'); }); + + it('should write agent interaction data to local file', async () => { + // Call the method to log data locally + await dataLogger.logLocalData(TEST_AGENT_INTERACTION_EVENT); + + // Verify the file was created + const filepath = getDevDataFilePath(TEST_AGENT_INTERACTION_EVENT.name, SCHEMA); + expect(fs.existsSync(filepath)).toBe(true); + + // Read file contents and verify + const fileContent = fs.readFileSync(filepath, "utf8"); + expect(fileContent).toContain('"eventName":"agentInteraction"'); + expect(fileContent).toContain('"prompt":"Hello, world!"'); + expect(fileContent).toContain('"completion":"Hello, world!"'); + }) }); describe("logDevData", () => { From cdfc1ff54211a2eeb872a1a09fc98de2a40a4043 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 26 May 2025 18:33:14 +0530 Subject: [PATCH 007/104] add `tools` key in chatInteraction --- core/data/log.test.ts | 7 +++++-- gui/src/redux/thunks/streamNormalInput.ts | 6 +++++- .../config-yaml/src/schemas/data/chatInteraction/index.ts | 1 + .../config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts | 1 + packages/config-yaml/src/schemas/data/index.ts | 3 --- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/core/data/log.test.ts b/core/data/log.test.ts index 5e9bcce5f..a7d664518 100644 --- a/core/data/log.test.ts +++ b/core/data/log.test.ts @@ -20,13 +20,14 @@ const TEST_EVENT: DevDataLogEvent = { }; const TEST_AGENT_INTERACTION_EVENT: DevDataLogEvent = { - name: 'agentInteraction', + name: 'chatInteraction', data: { prompt: "Hello, world!", completion: "Hello, world!", modelProvider: "openai", modelTitle: "gpt-4", sessionId: "1234", + tools: ['test-tool1'] }, } @@ -180,9 +181,11 @@ describe("DataLogger", () => { // Read file contents and verify const fileContent = fs.readFileSync(filepath, "utf8"); - expect(fileContent).toContain('"eventName":"agentInteraction"'); + console.log('debug1 filecontent', fileContent) + expect(fileContent).toContain('"eventName":"chatInteraction"'); expect(fileContent).toContain('"prompt":"Hello, world!"'); expect(fileContent).toContain('"completion":"Hello, world!"'); + expect(fileContent).toContain('"tools":["test-tool1"]'); }) }); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index ec12627c0..b7e39490e 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -36,6 +36,7 @@ export const streamNormalInput = createAsyncThunk< throw new Error("Default model not defined"); } + const isInEdit = state.session.isInEdit; let completionOptions: LLMFullCompletionOptions = {}; const activeTools = selectActiveTools(state); const toolsSupported = modelSupportsTools(selectedChatModel); @@ -75,13 +76,16 @@ export const streamNormalInput = createAsyncThunk< try { if (state.session.mode === "chat" || state.session.mode === "agent") { extra.ideMessenger.post("devdata/log", { - name: state.session.mode === 'chat' ? "chatInteraction" : "agentInteraction", + name: "chatInteraction", data: { prompt: next.value.prompt, completion: next.value.completion, modelProvider: selectedChatModel.underlyingProviderName, modelTitle: selectedChatModel.title, sessionId: state.session.id, + ...(isInEdit && { + tools: activeTools.map((tool) => tool.function.name), + }), }, }); } diff --git a/packages/config-yaml/src/schemas/data/chatInteraction/index.ts b/packages/config-yaml/src/schemas/data/chatInteraction/index.ts index fd10fa72c..1afb558b0 100644 --- a/packages/config-yaml/src/schemas/data/chatInteraction/index.ts +++ b/packages/config-yaml/src/schemas/data/chatInteraction/index.ts @@ -7,4 +7,5 @@ export const chatInteractionEventAllSchema = baseDevDataAllSchema.extend({ prompt: z.string(), completion: z.string(), sessionId: z.string(), + tools: z.array(z.string()).optional() }); diff --git a/packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts b/packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts index 206791c22..cb424c9b2 100644 --- a/packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts +++ b/packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts @@ -16,6 +16,7 @@ export const chatInteractionEventSchema_0_2_0 = modelTitle: true, modelProvider: true, sessionId: true, + tools: true }); export const chatInteractionEventSchema_0_2_0_noCode = diff --git a/packages/config-yaml/src/schemas/data/index.ts b/packages/config-yaml/src/schemas/data/index.ts index 1d8b59547..7251e12a7 100644 --- a/packages/config-yaml/src/schemas/data/index.ts +++ b/packages/config-yaml/src/schemas/data/index.ts @@ -72,7 +72,6 @@ const devEventAllVersionDataSchemas = z.object({ tokensGenerated: tokensGeneratedEventAllSchema, chatInteraction: chatInteractionEventAllSchema, editInteraction: editInteractionEventAllSchema, - agentInteraction: chatInteractionEventAllSchema }); // Version and level specific schemas are organized here @@ -98,7 +97,6 @@ export const devDataVersionedSchemas = { tokensGenerated: tokensGeneratedEventSchema_0_2_0, chatInteraction: chatInteractionEventSchema_0_2_0, editInteraction: editInteractionEventSchema_0_2_0, - agentInteraction: chatInteractionEventSchema_0_2_0, }, noCode: { autocomplete: autocompleteEventSchema_0_2_0_noCode, @@ -106,7 +104,6 @@ export const devDataVersionedSchemas = { tokensGenerated: tokensGeneratedEventSchema_0_2_0_noCode, chatInteraction: chatInteractionEventSchema_0_2_0_noCode, editInteraction: editInteractionEventSchema_0_2_0_noCode, - agentInteraction: chatInteractionEventSchema_0_2_0_noCode, }, }, }; From 04109e62d144b80d7b0b719c48e83445787b4b7a Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 26 May 2025 18:42:36 +0530 Subject: [PATCH 008/104] correction --- gui/src/redux/thunks/streamNormalInput.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index b7e39490e..6be602ca0 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -36,7 +36,6 @@ export const streamNormalInput = createAsyncThunk< throw new Error("Default model not defined"); } - const isInEdit = state.session.isInEdit; let completionOptions: LLMFullCompletionOptions = {}; const activeTools = selectActiveTools(state); const toolsSupported = modelSupportsTools(selectedChatModel); @@ -83,7 +82,7 @@ export const streamNormalInput = createAsyncThunk< modelProvider: selectedChatModel.underlyingProviderName, modelTitle: selectedChatModel.title, sessionId: state.session.id, - ...(isInEdit && { + ...(state.session.mode === 'agent' && { tools: activeTools.map((tool) => tool.function.name), }), }, From ad95e61ec0744bf1ce879d6c2313fe4a8a798aaa Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 3 Jun 2025 13:47:07 -0700 Subject: [PATCH 009/104] defining cache for opened files + making change in active editor update cache element recency --- core/autocomplete/util/openedFilesLruCache.ts | 14 ++++++++++++++ core/core.ts | 4 ++++ extensions/vscode/package-lock.json | 3 ++- extensions/vscode/src/VsCodeIde.ts | 2 -- gui/package-lock.json | 3 ++- 5 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 core/autocomplete/util/openedFilesLruCache.ts diff --git a/core/autocomplete/util/openedFilesLruCache.ts b/core/autocomplete/util/openedFilesLruCache.ts new file mode 100644 index 000000000..4e7ea9b2c --- /dev/null +++ b/core/autocomplete/util/openedFilesLruCache.ts @@ -0,0 +1,14 @@ +import QuickLRU from "quick-lru"; + +// The cache key and value are both a filepath string +type cacheElementType = string; + +// maximum number of open files that can be cached +const MAX_NUM_OPEN_CONTEXT_FILES = 10; + +export const openedFilesLruCache = new QuickLRU< + cacheElementType, + cacheElementType +>({ + maxSize: MAX_NUM_OPEN_CONTEXT_FILES, +}); diff --git a/core/core.ts b/core/core.ts index 2c13fd6a7..cd1fb4f99 100644 --- a/core/core.ts +++ b/core/core.ts @@ -3,6 +3,7 @@ import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import { CompletionProvider } from "./autocomplete/CompletionProvider"; +import { openedFilesLruCache } from "./autocomplete/util/openedFilesLruCache"; import { ConfigHandler } from "./config/ConfigHandler"; import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; import { addModel, deleteModel } from "./config/util"; @@ -692,7 +693,10 @@ export class Core { try { const ignore = await shouldIgnore(filepath, this.ide); if (!ignore) { + // Update the recently edited files cache recentlyEditedFilesCache.set(filepath, filepath); + // Update the cache for opened files as well + openedFilesLruCache.set(filepath, filepath); } } catch (e) { console.error( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 78fa03df8..e516f171e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -199,7 +199,8 @@ "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", "ts-jest": "^29.1.1", - "typescript": "^5.6.3" + "typescript": "^5.6.3", + "vitest": "^3.1.4" }, "engines": { "node": ">=20.19.0" diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 5ca51d183..dcc17d179 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -3,8 +3,6 @@ import { exec } from "node:child_process"; import { Range } from "core"; import { EXTENSION_NAME } from "core/control-plane/env"; -import { GetGhTokenArgs } from "core/protocol/ide"; -import { editConfigFile, getConfigJsonPath } from "core/util/paths"; import * as URI from "uri-js"; import * as vscode from "vscode"; diff --git a/gui/package-lock.json b/gui/package-lock.json index 17f6b1514..1fb8463d7 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -203,7 +203,8 @@ "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", "ts-jest": "^29.1.1", - "typescript": "^5.6.3" + "typescript": "^5.6.3", + "vitest": "^3.1.4" }, "engines": { "node": ">=20.19.0" From ceee1831e38142af9c94aeb4296ffe8770527fd4 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 3 Jun 2025 14:24:15 -0700 Subject: [PATCH 010/104] general outline of which files will be modified for update 2; short break from this branch to test changeVisibleTextEditors --- core/autocomplete/util/openedFilesLruCache.ts | 5 ++++- core/core.ts | 14 ++++++++++++-- core/index.d.ts | 2 ++ core/protocol/ide.ts | 1 + extensions/vscode/src/VsCodeIde.ts | 8 ++++++++ extensions/vscode/src/extension/VsCodeExtension.ts | 4 ++++ 6 files changed, 31 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/util/openedFilesLruCache.ts b/core/autocomplete/util/openedFilesLruCache.ts index 4e7ea9b2c..07df57b56 100644 --- a/core/autocomplete/util/openedFilesLruCache.ts +++ b/core/autocomplete/util/openedFilesLruCache.ts @@ -1,7 +1,10 @@ import QuickLRU from "quick-lru"; +import { ToWebviewOrCoreFromIdeProtocol } from "../../protocol/ide.js"; + // The cache key and value are both a filepath string -type cacheElementType = string; +export type cacheElementType = + ToWebviewOrCoreFromIdeProtocol["didChangeActiveTextEditor"][0]["filepath"]; // maximum number of open files that can be cached const MAX_NUM_OPEN_CONTEXT_FILES = 10; diff --git a/core/core.ts b/core/core.ts index cd1fb4f99..7ad19ed48 100644 --- a/core/core.ts +++ b/core/core.ts @@ -693,9 +693,9 @@ export class Core { try { const ignore = await shouldIgnore(filepath, this.ide); if (!ignore) { - // Update the recently edited files cache recentlyEditedFilesCache.set(filepath, filepath); - // Update the cache for opened files as well + + // Update the cache for opened files openedFilesLruCache.set(filepath, filepath); } } catch (e) { @@ -705,6 +705,16 @@ export class Core { } }); + on("didChangeVisibleTextEditors", async ({ data: { filepaths } }) => { + try { + // LOGIC FOR DEALING WITH FILEPATHS HERE (UPDATE #2) + } catch (e) { + console.error( + `didChangeVisibleTextEditors: failed to update openedFilesLruCache`, + ); + } + }); + on("tools/call", async ({ data: { toolCall } }) => { const { config } = await this.configHandler.loadConfig(); if (!config) { diff --git a/core/index.d.ts b/core/index.d.ts index ad778d3d8..1ced5227c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -813,6 +813,8 @@ export interface IDE { // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; + + onDidChangeVisibleTextEditors(callback: (fileUris: string[]) => void): void; } // Slash Commands diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index fda1b84fe..08b867850 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -103,4 +103,5 @@ export type ToIdeFromWebviewOrCoreProtocol = { export type ToWebviewOrCoreFromIdeProtocol = { didChangeActiveTextEditor: [{ filepath: string }, void]; + didChangeVisibleTextEditors: [{ filepaths: string[] }, void]; }; diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index dcc17d179..9752556d3 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -94,6 +94,14 @@ class VsCodeIde implements IDE { }); } + onDidChangeVisibleTextEditors(callback: (uris: string[]) => void): void { + vscode.window.onDidChangeActiveTextEditor((editor) => { + if (editor) { + // extract list of opened files + } + }); + } + showToast: IDE["showToast"] = async (...params) => { const [type, message, ...otherParams] = params; const { showErrorMessage, showWarningMessage, showInformationMessage } = diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index b15d4420c..be4359656 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -386,6 +386,10 @@ export class VsCodeExtension { void this.core.invoke("didChangeActiveTextEditor", { filepath }); }); + this.ide.onDidChangeVisibleTextEditors((filepaths) => { + void this.core.invoke("didChangeVisibleTextEditors", { filepaths }); + }); + vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { const settings = await this.ide.getIdeSettings(); From 78c86d1e597fba7d91a9f623bb24c116e50d6bb0 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 3 Jun 2025 15:41:27 -0700 Subject: [PATCH 011/104] temp experiment finished. figured out how to catch when files close. --- core/autocomplete/util/openedFilesLruCache.ts | 7 ++----- core/core.ts | 8 +++++--- core/index.d.ts | 2 +- core/protocol/ide.ts | 2 +- extensions/vscode/src/VsCodeIde.ts | 13 +++++++++---- extensions/vscode/src/extension/VsCodeExtension.ts | 4 ++-- 6 files changed, 20 insertions(+), 16 deletions(-) diff --git a/core/autocomplete/util/openedFilesLruCache.ts b/core/autocomplete/util/openedFilesLruCache.ts index 07df57b56..2ef27d276 100644 --- a/core/autocomplete/util/openedFilesLruCache.ts +++ b/core/autocomplete/util/openedFilesLruCache.ts @@ -1,13 +1,10 @@ import QuickLRU from "quick-lru"; -import { ToWebviewOrCoreFromIdeProtocol } from "../../protocol/ide.js"; - // The cache key and value are both a filepath string -export type cacheElementType = - ToWebviewOrCoreFromIdeProtocol["didChangeActiveTextEditor"][0]["filepath"]; +export type cacheElementType = string; // maximum number of open files that can be cached -const MAX_NUM_OPEN_CONTEXT_FILES = 10; +const MAX_NUM_OPEN_CONTEXT_FILES = 20; export const openedFilesLruCache = new QuickLRU< cacheElementType, diff --git a/core/core.ts b/core/core.ts index 7ad19ed48..c34da634c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -695,7 +695,7 @@ export class Core { if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); - // Update the cache for opened files + // Set the active filepath as most recently used in the opened files cache openedFilesLruCache.set(filepath, filepath); } } catch (e) { @@ -705,9 +705,11 @@ export class Core { } }); - on("didChangeVisibleTextEditors", async ({ data: { filepaths } }) => { + on("didCloseTextDocument", async ({ data: { filepaths } }) => { try { - // LOGIC FOR DEALING WITH FILEPATHS HERE (UPDATE #2) + console.log("Visible", filepaths.length); + + // Remove the closed files from the opened files cache: TODO, UPDATE #2 } catch (e) { console.error( `didChangeVisibleTextEditors: failed to update openedFilesLruCache`, diff --git a/core/index.d.ts b/core/index.d.ts index 1ced5227c..9dec0ac51 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -814,7 +814,7 @@ export interface IDE { // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; - onDidChangeVisibleTextEditors(callback: (fileUris: string[]) => void): void; + onDidCloseTextDocument(callback: (fileUris: string[]) => void): void; } // Slash Commands diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 08b867850..cb8e15aa4 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -103,5 +103,5 @@ export type ToIdeFromWebviewOrCoreProtocol = { export type ToWebviewOrCoreFromIdeProtocol = { didChangeActiveTextEditor: [{ filepath: string }, void]; - didChangeVisibleTextEditors: [{ filepaths: string[] }, void]; + didCloseTextDocument: [{ filepaths: string[] }, void]; }; diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 9752556d3..5e2784891 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -94,10 +94,15 @@ class VsCodeIde implements IDE { }); } - onDidChangeVisibleTextEditors(callback: (uris: string[]) => void): void { - vscode.window.onDidChangeActiveTextEditor((editor) => { - if (editor) { - // extract list of opened files + onDidCloseTextDocument(callback: (uris: string[]) => void): void { + vscode.workspace.onDidCloseTextDocument((document) => { + if (document) { + let openFilePaths = vscode.window.tabGroups.all // get tab groups + .flatMap((group) => group.tabs) // extract tabs from tab groups + .filter((tab) => tab.input instanceof vscode.TabInputText) // filter irrelevant tabs (settings, etc.) + .map((tab) => (tab.input as vscode.TabInputText).uri.fsPath); // get filepaths + + callback(openFilePaths); } }); } diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index be4359656..7705f9a5c 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -386,8 +386,8 @@ export class VsCodeExtension { void this.core.invoke("didChangeActiveTextEditor", { filepath }); }); - this.ide.onDidChangeVisibleTextEditors((filepaths) => { - void this.core.invoke("didChangeVisibleTextEditors", { filepaths }); + this.ide.onDidCloseTextDocument((filepaths) => { + void this.core.invoke("didCloseTextDocument", { filepaths }); }); vscode.workspace.onDidChangeConfiguration(async (event) => { From 6a542a2d9310fd23009c8e5b42cebd2b084b3bab Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 3 Jun 2025 16:31:57 -0700 Subject: [PATCH 012/104] good detection of changing active view and closing tabs now --- core/autocomplete/util/openedFilesLruCache.ts | 4 +++ core/core.ts | 34 ++++++++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/core/autocomplete/util/openedFilesLruCache.ts b/core/autocomplete/util/openedFilesLruCache.ts index 2ef27d276..b38222813 100644 --- a/core/autocomplete/util/openedFilesLruCache.ts +++ b/core/autocomplete/util/openedFilesLruCache.ts @@ -12,3 +12,7 @@ export const openedFilesLruCache = new QuickLRU< >({ maxSize: MAX_NUM_OPEN_CONTEXT_FILES, }); + +export const prevFilepaths = { + filepaths: [] as string[], +}; diff --git a/core/core.ts b/core/core.ts index c34da634c..7a0e7b4f6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -3,7 +3,10 @@ import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import { CompletionProvider } from "./autocomplete/CompletionProvider"; -import { openedFilesLruCache } from "./autocomplete/util/openedFilesLruCache"; +import { + openedFilesLruCache, + prevFilepaths, +} from "./autocomplete/util/openedFilesLruCache"; import { ConfigHandler } from "./config/ConfigHandler"; import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; import { addModel, deleteModel } from "./config/util"; @@ -695,8 +698,17 @@ export class Core { if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); - // Set the active filepath as most recently used in the opened files cache + // Set the active file as most recently used (need to force recency update by deleting and re-adding) + if (openedFilesLruCache.has(filepath)) { + openedFilesLruCache.delete(filepath); + } openedFilesLruCache.set(filepath, filepath); + + console.log("ACTIVE TEXT EDITOR CHANGED"); + for (const [key, value] of openedFilesLruCache.entriesDescending()) { + console.log(`${key}`); + } + console.log("\n"); } } catch (e) { console.error( @@ -705,11 +717,25 @@ export class Core { } }); + // function sleep(ms: number): Promise { + // return new Promise((resolve) => setTimeout(resolve, ms)); + // } + on("didCloseTextDocument", async ({ data: { filepaths } }) => { try { - console.log("Visible", filepaths.length); + if (!prevFilepaths.filepaths.length) { + } - // Remove the closed files from the opened files cache: TODO, UPDATE #2 + if (filepaths.length < prevFilepaths.filepaths.length) { + // Remove the closed files from the opened files cache: TODO, UPDATE #2 + console.log("close-text-doc"); + for (const [key, value] of openedFilesLruCache.entriesDescending()) { + console.log(`${key}`); + } + console.log("\n"); + } + + prevFilepaths.filepaths = filepaths; } catch (e) { console.error( `didChangeVisibleTextEditors: failed to update openedFilesLruCache`, From 192c22a4a6b836caff9ace9ae68a21717e7bf525 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 3 Jun 2025 17:07:24 -0700 Subject: [PATCH 013/104] cache updates properly now for opening files, changing views, and closing files. --- core/core.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/core/core.ts b/core/core.ts index 7a0e7b4f6..a19e8d50b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -717,17 +717,22 @@ export class Core { } }); - // function sleep(ms: number): Promise { - // return new Promise((resolve) => setTimeout(resolve, ms)); - // } - on("didCloseTextDocument", async ({ data: { filepaths } }) => { try { if (!prevFilepaths.filepaths.length) { + prevFilepaths.filepaths = filepaths; } - if (filepaths.length < prevFilepaths.filepaths.length) { - // Remove the closed files from the opened files cache: TODO, UPDATE #2 + // If there is a removal, including if the number of tabs is the same (which can happen with temp tabs) + if (filepaths.length <= prevFilepaths.filepaths.length) { + // Remove files from cache that are no longer open (i.e. in the cache but not in the list of opened tabs) + for (const [key, value] of openedFilesLruCache.entriesDescending()) { + let trimmedKey = key.slice(7); // uri -> filepath + if (!filepaths.includes(trimmedKey)) { + openedFilesLruCache.delete(key); + } + } + console.log("close-text-doc"); for (const [key, value] of openedFilesLruCache.entriesDescending()) { console.log(`${key}`); From 4f9c7a3974e6590c1088894f47027fa854b2c0ac Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 3 Jun 2025 17:12:05 -0700 Subject: [PATCH 014/104] testing console logs removed, this is good to go --- core/autocomplete/util/openedFilesLruCache.ts | 2 ++ core/core.ts | 12 ------------ 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/core/autocomplete/util/openedFilesLruCache.ts b/core/autocomplete/util/openedFilesLruCache.ts index b38222813..102e0704f 100644 --- a/core/autocomplete/util/openedFilesLruCache.ts +++ b/core/autocomplete/util/openedFilesLruCache.ts @@ -6,6 +6,7 @@ export type cacheElementType = string; // maximum number of open files that can be cached const MAX_NUM_OPEN_CONTEXT_FILES = 20; +// stores which files are currently open in the IDE, in viewing order export const openedFilesLruCache = new QuickLRU< cacheElementType, cacheElementType @@ -13,6 +14,7 @@ export const openedFilesLruCache = new QuickLRU< maxSize: MAX_NUM_OPEN_CONTEXT_FILES, }); +// used in core/core.ts to handle removals from the cache export const prevFilepaths = { filepaths: [] as string[], }; diff --git a/core/core.ts b/core/core.ts index a19e8d50b..2a02b5ee1 100644 --- a/core/core.ts +++ b/core/core.ts @@ -703,12 +703,6 @@ export class Core { openedFilesLruCache.delete(filepath); } openedFilesLruCache.set(filepath, filepath); - - console.log("ACTIVE TEXT EDITOR CHANGED"); - for (const [key, value] of openedFilesLruCache.entriesDescending()) { - console.log(`${key}`); - } - console.log("\n"); } } catch (e) { console.error( @@ -732,12 +726,6 @@ export class Core { openedFilesLruCache.delete(key); } } - - console.log("close-text-doc"); - for (const [key, value] of openedFilesLruCache.entriesDescending()) { - console.log(`${key}`); - } - console.log("\n"); } prevFilepaths.filepaths = filepaths; From e9c1ad7e0386cbd3efdc8c17cdd5cb3558d9f961 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 3 Jun 2025 17:55:40 -0700 Subject: [PATCH 015/104] caching of context with initialization, ordering, addition, and removal is good to go --- core/core.ts | 16 ++++++++++++++++ core/protocol/ide.ts | 1 + .../vscode/src/extension/VsCodeExtension.ts | 7 +++++++ 3 files changed, 24 insertions(+) diff --git a/core/core.ts b/core/core.ts index 2a02b5ee1..4d97093bd 100644 --- a/core/core.ts +++ b/core/core.ts @@ -736,6 +736,22 @@ export class Core { } }); + on( + "initializeOpenedFileCache", + async ({ data: { initialOpenedFilePaths } }) => { + try { + for (const filepath of initialOpenedFilePaths) { + openedFilesLruCache.set(`file://${filepath}`, `file://${filepath}`); + } + } catch (e) { + console.error( + `initializeOpenedFileCache: failed to update openedFilesLruCache`, + e, + ); + } + }, + ); + on("tools/call", async ({ data: { toolCall } }) => { const { config } = await this.configHandler.loadConfig(); if (!config) { diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index cb8e15aa4..37072cc05 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -104,4 +104,5 @@ export type ToIdeFromWebviewOrCoreProtocol = { export type ToWebviewOrCoreFromIdeProtocol = { didChangeActiveTextEditor: [{ filepath: string }, void]; didCloseTextDocument: [{ filepaths: string[] }, void]; + initializeOpenedFileCache: [{ initialOpenedFilePaths: string[] }, void]; }; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 7705f9a5c..16d9d8b41 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -390,6 +390,13 @@ export class VsCodeExtension { void this.core.invoke("didCloseTextDocument", { filepaths }); }); + // initializes openedFileLruCache with files that are already open when the extension is activated + let initialOpenedFilePaths = vscode.window.tabGroups.all + .flatMap((group) => group.tabs) + .filter((tab) => tab.input instanceof vscode.TabInputText) + .map((tab) => (tab.input as vscode.TabInputText).uri.fsPath); + this.core.invoke("initializeOpenedFileCache", { initialOpenedFilePaths }); + vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { const settings = await this.ide.getIdeSettings(); From 0a632b5401970e4d1e5321576b82bb22a4bd2768 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Wed, 4 Jun 2025 15:20:16 -0700 Subject: [PATCH 016/104] open files context works :) refinements to come as to how they are loaded into context --- core/autocomplete/snippets/getAllSnippets.ts | 48 +++++++++++++++++++ core/autocomplete/templating/filtering.ts | 13 +++-- core/autocomplete/templating/index.ts | 2 +- core/index.d.ts | 1 + core/util/parameters.ts | 7 +-- .../calculator_test/Calculator.java | 21 ++++++++ .../calculator_test/Main.java | 7 +++ manual-testing-sandbox/test.py | 2 +- manual-testing-sandbox/test.ts | 2 +- 9 files changed, 94 insertions(+), 9 deletions(-) create mode 100644 manual-testing-sandbox/calculator_test/Calculator.java create mode 100644 manual-testing-sandbox/calculator_test/Main.java diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index eaf287587..c4c89a59c 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -3,6 +3,7 @@ import { findUriInDirs } from "../../util/uri"; import { ContextRetrievalService } from "../context/ContextRetrievalService"; import { GetLspDefinitionsFunction } from "../types"; import { HelperVars } from "../util/HelperVars"; +import { openedFilesLruCache } from "../util/openedFilesLruCache"; import { getDiffsFromCache } from "./gitDiffCache"; import { @@ -22,6 +23,7 @@ export interface SnippetPayload { recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[]; diffSnippets: AutocompleteDiffSnippet[]; clipboardSnippets: AutocompleteClipboardSnippet[]; + recentlyOpenedFileSnippets: AutocompleteCodeSnippet[]; } function racePromise(promise: Promise, timeout = 100): Promise { @@ -103,6 +105,49 @@ const getDiffSnippets = async ( }); }; +const getSnippetsFromRecentlyOpenedFiles = async ( + helper: HelperVars, + ide: IDE, +): Promise => { + if (helper.options.useRecentlyOpened === false) { + return []; + } + + // stores snippets from cache + const snippets: AutocompleteCodeSnippet[] = []; + + try { + const currentFileUri = `${helper.filepath}`; + + // converts cache file URIs to autocomplete snippets + for (const [fileUri, _] of openedFilesLruCache.entriesDescending()) { + if (fileUri === currentFileUri) { + continue; + } + + try { + const fileContent = await ide.readFile(fileUri); + + if (!fileContent || fileContent.trim() === "") { + continue; + } + + snippets.push({ + filepath: fileUri, + content: fileContent, + type: AutocompleteSnippetType.Code, + }); + } catch (e) { + console.error(`Failed to read file ${fileUri}:`, e); + } + } + } catch (e) { + console.error("Error processing opened files cache:", e); + } + + return snippets; +}; + export const getAllSnippets = async ({ helper, ide, @@ -123,6 +168,7 @@ export const getAllSnippets = async ({ ideSnippets, diffSnippets, clipboardSnippets, + recentlyOpenedFileSnippets, ] = await Promise.all([ racePromise(contextRetrievalService.getRootPathSnippets(helper)), racePromise( @@ -133,6 +179,7 @@ export const getAllSnippets = async ({ : [], [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, racePromise(getClipboardSnippets(ide)), + racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide), 500), // giving this one a little more time to complete ]); return { @@ -143,5 +190,6 @@ export const getAllSnippets = async ({ diffSnippets, clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, + recentlyOpenedFileSnippets, }; }; diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index 7f69398c6..da1d12233 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -47,6 +47,7 @@ export const getSnippets = ( recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets, recentlyEditedRanges: payload.recentlyEditedRangeSnippets, diff: payload.diffSnippets, + recentlyOpenedFiles: payload.recentlyOpenedFileSnippets, base: shuffleArray( filterSnippetsAlreadyInCaretWindow( [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], @@ -68,11 +69,17 @@ export const getSnippets = ( defaultPriority: 1, snippets: payload.clipboardSnippets, }, + { + key: "recentlyOpenedFiles", + enabledOrPriority: helper.options.useRecentlyOpened, + defaultPriority: 2, + snippets: payload.recentlyOpenedFileSnippets, + }, { key: "recentlyVisitedRanges", enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges, - defaultPriority: 2, + defaultPriority: 3, snippets: payload.recentlyVisitedRangesSnippets, /* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output if they are visible. We should handle them separately so that we can control their priority @@ -82,13 +89,13 @@ export const getSnippets = ( key: "recentlyEditedRanges", enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges, - defaultPriority: 3, + defaultPriority: 4, snippets: payload.recentlyEditedRangeSnippets, }, { key: "diff", enabledOrPriority: helper.options.experimental_includeDiff, - defaultPriority: 4, + defaultPriority: 5, snippets: payload.diffSnippets, // TODO: diff is commonly too large, thus anything lower in priority is not included. }, diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 9722ee328..55fb086c4 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -4,13 +4,13 @@ import { CompletionOptions } from "../.."; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { HelperVars } from "../util/HelperVars"; +import { getUriPathBasename } from "../../util/uri"; import { SnippetPayload } from "../snippets"; import { AutocompleteTemplate, getTemplateForModel, } from "./AutocompleteTemplate"; import { getSnippets } from "./filtering"; -import { getUriPathBasename } from "../../util/uri"; import { formatSnippets } from "./formatting"; import { getStopTokens } from "./getStopTokens"; diff --git a/core/index.d.ts b/core/index.d.ts index 9dec0ac51..065785ce1 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1107,6 +1107,7 @@ export interface TabAutocompleteOptions { useCache: boolean; onlyMyCode: boolean; useRecentlyEdited: boolean; + useRecentlyOpened: boolean; disableInFiles?: string[]; useImports?: boolean; showWhateverWeHaveAtXMs?: number; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index aa50de122..e6fd93189 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -2,9 +2,9 @@ import { TabAutocompleteOptions } from "../index.js"; export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disable: false, - maxPromptTokens: 1024, - prefixPercentage: 0.3, - maxSuffixPercentage: 0.2, + maxPromptTokens: 2048, // doubled from default to fit opened files + prefixPercentage: 0.15, // halved as a result + maxSuffixPercentage: 0.1, // halved as a result debounceDelay: 350, modelTimeout: 150, multilineCompletions: "auto", @@ -15,6 +15,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { useCache: true, onlyMyCode: true, useRecentlyEdited: true, + useRecentlyOpened: true, disableInFiles: undefined, useImports: true, transform: true, diff --git a/manual-testing-sandbox/calculator_test/Calculator.java b/manual-testing-sandbox/calculator_test/Calculator.java new file mode 100644 index 000000000..6aef8409e --- /dev/null +++ b/manual-testing-sandbox/calculator_test/Calculator.java @@ -0,0 +1,21 @@ +public class Calculator { + public int myAddition(int a, int b, int c) { + return a + b + c; + } + + public int subtract(int a, int b) { + return a - b; + } + + public int multiply(int a, int b) { + return a * b; + } + + public double divide(int a, int b) { + if (b != 0) { + return (double) a / b; + } else { + throw new IllegalArgumentException("Division by zero is not allowed."); + } + } +} diff --git a/manual-testing-sandbox/calculator_test/Main.java b/manual-testing-sandbox/calculator_test/Main.java new file mode 100644 index 000000000..4c8489359 --- /dev/null +++ b/manual-testing-sandbox/calculator_test/Main.java @@ -0,0 +1,7 @@ +public class Main { + public static void main(String[] args) { + Calculator calculator = new Calculator(); + calculator.myAddition(1, 2, 3); + + } +} diff --git a/manual-testing-sandbox/test.py b/manual-testing-sandbox/test.py index 4478e7b3d..df0f203cc 100644 --- a/manual-testing-sandbox/test.py +++ b/manual-testing-sandbox/test.py @@ -15,4 +15,4 @@ class Calculator: return self def get_result(self): - return self.result + return self.result \ No newline at end of file diff --git a/manual-testing-sandbox/test.ts b/manual-testing-sandbox/test.ts index 0f25987c2..21aa32018 100644 --- a/manual-testing-sandbox/test.ts +++ b/manual-testing-sandbox/test.ts @@ -14,7 +14,7 @@ class Calculator { this.result -= number; return this; } - + multiply(number: number): Calculator { this.result *= number; return this; From 062abb689d3eeb30aa5c5bff650eb002cf6cd0cd Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Wed, 4 Jun 2025 15:21:18 -0700 Subject: [PATCH 017/104] branch feature/view-context-make-context-experiment-greedy terminated here. --- core/autocomplete/snippets/getAllSnippets.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index c4c89a59c..ce1c762ab 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -113,7 +113,6 @@ const getSnippetsFromRecentlyOpenedFiles = async ( return []; } - // stores snippets from cache const snippets: AutocompleteCodeSnippet[] = []; try { From 7bbd9b000db7d269f2447d157c8a3d330060f408 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Wed, 4 Jun 2025 15:51:44 -0700 Subject: [PATCH 018/104] ok branch finished now. made time limit for open file context same as other contexts --- core/autocomplete/snippets/getAllSnippets.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index ce1c762ab..6ad16e49d 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -178,7 +178,7 @@ export const getAllSnippets = async ({ : [], [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, racePromise(getClipboardSnippets(ide)), - racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide), 500), // giving this one a little more time to complete + racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete ]); return { From 2d3bdbe256871c219f7abfa252141a002691cd3f Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Wed, 4 Jun 2025 22:23:39 -0700 Subject: [PATCH 019/104] refactor: :recycle: Updates to code to remove negative cases first (linting) --- .../implementations/runTerminalCommand.ts | 90 +++++++++---------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 785f4ee30..4f0596535 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -130,26 +130,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { return; } - if (!waitForCompletion) { - // Already resolved, just update the UI with final output - if (extras.onPartialOutput) { - const status = - code === 0 || !code - ? "\nBackground command completed" - : `\nBackground command failed with exit code ${code}`; - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ], - }); - } - } else { + if (waitForCompletion) { // Normal completion, resolve now if (code === 0) { const status = "Command completed"; @@ -172,6 +153,25 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }, ]); } + } else { + // Already resolved, just update the UI with final output + if (extras.onPartialOutput) { + const status = + code === 0 || !code + ? "\nBackground command completed" + : `\nBackground command failed with exit code ${code}`; + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ], + }); + } } }); @@ -197,7 +197,31 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { const workspaceDirs = await extras.ide.getWorkspaceDirs(); const cwd = fileURLToPath(workspaceDirs[0]); - if (!waitForCompletion) { + if (waitForCompletion) { + // Standard execution, waiting for completion + try { + const output = await asyncExec(args.command, { cwd }); + const status = "Command completed"; + return [ + { + name: "Terminal", + description: "Terminal command output", + content: output.stdout ?? "", + status: status, + }, + ]; + } catch (error: any) { + const status = `Command failed with: ${error.message || error.toString()}`; + return [ + { + name: "Terminal", + description: "Terminal command output", + content: error.stderr ?? error.toString(), + status: status, + }, + ]; + } + } else { // For non-streaming but also not waiting for completion, use spawn // but don't attach any listeners other than error try { @@ -246,30 +270,6 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }, ]; } - } else { - // Standard execution, waiting for completion - try { - const output = await asyncExec(args.command, { cwd }); - const status = "Command completed"; - return [ - { - name: "Terminal", - description: "Terminal command output", - content: output.stdout ?? "", - status: status, - }, - ]; - } catch (error: any) { - const status = `Command failed with: ${error.message || error.toString()}`; - return [ - { - name: "Terminal", - description: "Terminal command output", - content: error.stderr ?? error.toString(), - status: status, - }, - ]; - } } } } From e83290bd3a921929052b0c0c91751800e7e9fd2c Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Thu, 5 Jun 2025 01:13:26 -0700 Subject: [PATCH 020/104] feat: :sparkles: Give the terminal color and ansi escape rendering --- .../implementations/runTerminalCommand.ts | 22 +- gui/package-lock.json | 16 +- gui/package.json | 2 + gui/src/components/ansiTerminal/Ansi.tsx | 279 ++++++++++++++++++ .../gui/ToolCallDiv/RunTerminalCommand.tsx | 64 ++-- 5 files changed, 358 insertions(+), 25 deletions(-) create mode 100644 gui/src/components/ansiTerminal/Ansi.tsx diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 4f0596535..3d3ac85cb 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -10,6 +10,16 @@ import { const asyncExec = util.promisify(childProcess.exec); +// Add color-supporting environment variables +const getColorEnv = () => ({ + ...process.env, + FORCE_COLOR: "1", + COLORTERM: "truecolor", + TERM: "xterm-256color", + CLICOLOR: "1", + CLICOLOR_FORCE: "1", +}); + const ENABLED_FOR_REMOTES = [ "", "local", @@ -56,10 +66,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { } } - // Use spawn instead of exec to get streaming output + // Use spawn with color environment const childProc = childProcess.spawn(args.command, { cwd, shell: true, + env: getColorEnv(), // Add enhanced environment for colors }); childProc.stdout?.on("data", (data) => { @@ -200,7 +211,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { if (waitForCompletion) { // Standard execution, waiting for completion try { - const output = await asyncExec(args.command, { cwd }); + // Use color environment for exec as well + const output = await asyncExec(args.command, { + cwd, + env: getColorEnv(), + }); const status = "Command completed"; return [ { @@ -225,10 +240,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // For non-streaming but also not waiting for completion, use spawn // but don't attach any listeners other than error try { - // Use spawn instead of exec but don't wait + // Use spawn with color environment const childProc = childProcess.spawn(args.command, { cwd, shell: true, + env: getColorEnv(), // Add color environment // Detach the process so it's not tied to the parent detached: true, // Redirect to /dev/null equivalent (works cross-platform) diff --git a/gui/package-lock.json b/gui/package-lock.json index 020586519..96d91cee6 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -25,10 +25,12 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", + "anser": "^2.3.2", "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", "downshift": "^7.6.0", + "escape-carriage": "^1.3.1", "lodash": "^4.17.21", "lowlight": "^3.3.0", "minisearch": "^7.0.2", @@ -111,7 +113,7 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.13", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.25", "@modelcontextprotocol/sdk": "^1.12.0", @@ -3727,6 +3729,12 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/anser": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/anser/-/anser-2.3.2.tgz", + "integrity": "sha512-PMqBCBvrOVDRqLGooQb+z+t1Q0PiPyurUQeZRR5uHBOVZcW8B04KMmnT12USnhpNX2wCPagWzLVppQMUG3u0Dw==", + "license": "MIT" + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -5190,6 +5198,12 @@ "node": ">=6" } }, + "node_modules/escape-carriage": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/escape-carriage/-/escape-carriage-1.3.1.tgz", + "integrity": "sha512-GwBr6yViW3ttx1kb7/Oh+gKQ1/TrhYwxKqVmg5gS+BK+Qe2KrOa/Vh7w3HPBvgGf0LfcDGoY9I6NHKoA5Hozhw==", + "license": "MIT" + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", diff --git a/gui/package.json b/gui/package.json index de6da1959..1f137f19b 100644 --- a/gui/package.json +++ b/gui/package.json @@ -34,10 +34,12 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", + "anser": "^2.3.2", "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", "downshift": "^7.6.0", + "escape-carriage": "^1.3.1", "lodash": "^4.17.21", "lowlight": "^3.3.0", "minisearch": "^7.0.2", diff --git a/gui/src/components/ansiTerminal/Ansi.tsx b/gui/src/components/ansiTerminal/Ansi.tsx new file mode 100644 index 000000000..35d4b0a43 --- /dev/null +++ b/gui/src/components/ansiTerminal/Ansi.tsx @@ -0,0 +1,279 @@ +import Anser, { AnserJsonEntry } from "anser"; +import { escapeCarriageReturn } from "escape-carriage"; +import * as React from "react"; +import styled from "styled-components"; +import { + defaultBorderRadius, + vscBackground, + vscEditorBackground, + vscForeground, +} from "../../components"; +import { getFontSize } from "../../util"; + +const AnsiSpan = styled.span<{ + bg?: string; + fg?: string; + decoration?: string; +}>` + ${({ bg }) => bg && `background-color: rgb(${bg});`} + ${({ fg }) => fg && `color: rgb(${fg});`} + ${({ decoration }) => { + switch (decoration) { + case "bold": + return "font-weight: bold;"; + case "dim": + return "opacity: 0.5;"; + case "italic": + return "font-style: italic;"; + case "hidden": + return "visibility: hidden;"; + case "strikethrough": + return "text-decoration: line-through;"; + case "underline": + return "text-decoration: underline;"; + case "blink": + return "text-decoration: blink;"; + default: + return ""; + } + }} +`; + +const AnsiLink = styled.a` + color: var(--vscode-textLink-foreground, #3794ff); + text-decoration: none; + &:hover { + text-decoration: underline; + } +`; + +// Using the same styled component structure as StyledMarkdown +const StyledAnsi = styled.div<{ + fontSize?: number; + whiteSpace: string; + bgColor: string; +}>` + pre { + white-space: ${(props) => props.whiteSpace}; + background-color: ${vscEditorBackground}; + border-radius: ${defaultBorderRadius}; + border: 1px solid + var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3)); + max-width: calc(100vw - 24px); + overflow-x: scroll; + overflow-y: hidden; + padding: 8px; + } + + code { + span.line:empty { + display: none; + } + word-wrap: break-word; + border-radius: ${defaultBorderRadius}; + background-color: ${vscEditorBackground}; + font-size: ${getFontSize() - 2}px; + font-family: var(--vscode-editor-font-family); + } + + code:not(pre > code) { + font-family: var(--vscode-editor-font-family); + color: var(--vscode-input-placeholderForeground); + } + + background-color: ${(props) => props.bgColor}; + font-family: + var(--vscode-font-family), + system-ui, + -apple-system, + BlinkMacSystemFont, + "Segoe UI", + Roboto, + Oxygen, + Ubuntu, + Cantarell, + "Open Sans", + "Helvetica Neue", + sans-serif; + font-size: ${(props) => props.fontSize || getFontSize()}px; + padding-left: 8px; + padding-right: 8px; + color: ${vscForeground}; + line-height: 1.5; + + > *:last-child { + margin-bottom: 0; + } +`; + +/** + * Converts ANSI strings into JSON output. + * @name ansiToJSON + * @function + * @param {String} input The input string. + * @param {boolean} use_classes If `true`, HTML classes will be appended + * to the HTML output. + * @return {Array} The parsed input. + */ +function ansiToJSON( + input: string, + use_classes: boolean = false, +): AnserJsonEntry[] { + input = escapeCarriageReturn(fixBackspace(input)); + return Anser.ansiToJson(input, { + json: true, + remove_empty: true, + use_classes, + }); +} + +/** + * Create a class string. + * @name createClass + * @function + * @param {AnserJsonEntry} bundle + * @return {String} class name(s) + */ +function createClass(bundle: AnserJsonEntry): string | null { + let classNames: string = ""; + + if (bundle.bg) { + classNames += `${bundle.bg}-bg `; + } + if (bundle.fg) { + classNames += `${bundle.fg}-fg `; + } + if (bundle.decoration) { + classNames += `ansi-${bundle.decoration} `; + } + + if (classNames === "") { + return null; + } + + classNames = classNames.substring(0, classNames.length - 1); + return classNames; +} + +/** + * Converts an Anser bundle into a React Node. + * @param linkify whether links should be converting into clickable anchor tags. + * @param useClasses should render the span with a class instead of style. + * @param bundle Anser output. + * @param key + */ + +function convertBundleIntoReact( + linkify: boolean, + useClasses: boolean, + bundle: AnserJsonEntry, + key: number, +): JSX.Element { + const className = useClasses ? createClass(bundle) : null; + // Convert bundle.decoration to string or undefined (not null) to match the prop type + const decorationProp = bundle.decoration + ? String(bundle.decoration) + : undefined; + + if (!linkify) { + return ( + + {bundle.content} + + ); + } + + const content: React.ReactNode[] = []; + const linkRegex = + /(\s|^)(https?:\/\/(?:www\.|(?!www))[^\s.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/g; + + let index = 0; + let match: RegExpExecArray | null; + while ((match = linkRegex.exec(bundle.content)) !== null) { + const [, pre, url] = match; + + const startIndex = match.index + pre.length; + if (startIndex > index) { + content.push(bundle.content.substring(index, startIndex)); + } + + // Make sure the href we generate from the link is fully qualified. We assume http + // if it starts with a www because many sites don't support https + const href = url.startsWith("www.") ? `http://${url}` : url; + + content.push( + + {url} + , + ); + + index = linkRegex.lastIndex; + } + + if (index < bundle.content.length) { + content.push(bundle.content.substring(index)); + } + + return ( + + {content} + + ); +} + +declare interface Props { + children?: string; + linkify?: boolean; + className?: string; + useClasses?: boolean; +} + +export default function Ansi(props: Props): JSX.Element { + const { className, useClasses, children, linkify } = props; + + // Create the ANSI content + const ansiContent = ansiToJSON(children ?? "", useClasses ?? false).map( + (bundle, i) => + convertBundleIntoReact(linkify ?? false, useClasses ?? false, bundle, i), + ); + + return ( + +
+        {ansiContent}
+      
+
+ ); +} + +// This is copied from the Jupyter Classic source code +// notebook/static/base/js/utils.js to handle \b in a way +// that is **compatible with Jupyter classic**. One can +// argue that this behavior is questionable: +// https://stackoverflow.com/questions/55440152/multiple-b-doesnt-work-as-expected-in-jupyter# +function fixBackspace(txt: string) { + let tmp = txt; + do { + txt = tmp; + // Cancel out anything-but-newline followed by backspace + tmp = txt.replace(/[^\n]\x08/gm, ""); + } while (tmp.length < txt.length); + return txt; +} diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index c78ec3495..0b3bf1b9d 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,11 +1,10 @@ -import { AnyAction, ThunkDispatch } from "@reduxjs/toolkit"; import { ToolCallState } from "core"; -import { Fragment } from "react"; -import { useDispatch } from "react-redux"; import styled from "styled-components"; +import { vscForeground } from "../../../components"; +import Ansi from "../../../components/ansiTerminal/Ansi"; import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; -import { moveTerminalProcessToBackground } from "../../../redux/thunks/moveTerminalProcessToBackground"; import { useAppDispatch } from "../../../redux/hooks"; +import { moveTerminalProcessToBackground } from "../../../redux/thunks/moveTerminalProcessToBackground"; interface RunTerminalCommandToolCallProps { command: string; @@ -15,13 +14,12 @@ interface RunTerminalCommandToolCallProps { const CommandStatus = styled.div` font-size: 12px; - color: #666; + color: var(--vscode-descriptionForeground, ${vscForeground}88); margin-top: 8px; - padding-left: 8px; - padding-right: 8px; - padding-bottom: 8px; display: flex; align-items: center; + padding-left: 8px; + padding-right: 8px; `; const StatusIcon = styled.span<{ @@ -33,21 +31,32 @@ const StatusIcon = styled.span<{ margin-right: 8px; background-color: ${(props) => props.status === "running" - ? "#4caf50" + ? "var(--vscode-testing-runAction, #4caf50)" : props.status === "completed" - ? "#4caf50" + ? "var(--vscode-testing-iconPassed, #4caf50)" : props.status === "background" - ? "#2196f3" - : "#f44336"}; + ? "var(--vscode-statusBarItem-prominentBackground, #2196f3)" + : "var(--vscode-testing-iconFailed, #f44336)"}; ${(props) => props.status === "running" ? "animation: pulse 1.5s infinite;" : ""} `; -// Removed unused styled components +// Waiting message styled for consistency +const WaitingMessage = styled.div` + padding: 8px; + padding-left: 16px; + padding-right: 16px; + margin-top: 8px; +`; + +// For consistency with the rest of the styled components +const AnsiWrapper = styled.div` + margin-top: 8px; +`; const BackgroundLink = styled.a` font-size: 12px; - color: #0077cc; + color: var(--vscode-textLink-foreground, #3794ff); margin-left: 12px; cursor: pointer; text-decoration: none; @@ -57,6 +66,11 @@ const BackgroundLink = styled.a` } `; +// Just spacing between terminal components and the next toolcall +const TerminalContainer = styled.div` + margin-bottom: 16px; +`; + export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { const dispatch = useAppDispatch(); @@ -82,16 +96,24 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { } return ( - + + {/* Command */} + {/* Terminal output with ANSI support */} + {isRunning && !hasOutput && ( + Waiting for output... + )} + {hasOutput && ( + + {terminalContent} + + )} + + {/* Status information */} {(statusMessage || isRunning) && ( @@ -112,6 +134,6 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { )} )} - + ); } From 5fbc64156147b1f7b3aaa8574e1141b556b7e62d Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Thu, 5 Jun 2025 15:12:14 -0700 Subject: [PATCH 022/104] wrote adaptive trimmer for autocomplete opened file context --- core/autocomplete/templating/filtering.ts | 95 ++++++---- .../templating/formatOpenedFilesContext.ts | 172 ++++++++++++++++++ 2 files changed, 232 insertions(+), 35 deletions(-) create mode 100644 core/autocomplete/templating/formatOpenedFilesContext.ts diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index da1d12233..6d321aba7 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -5,6 +5,7 @@ import { AutocompleteSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; +import { formatOpenedFilesContext } from "./formatOpenedFilesContext"; import { isValidSnippet } from "./validation"; @@ -126,46 +127,70 @@ export const getSnippets = ( })) .sort((a, b) => a.priority - b.priority); - // Log the snippet order for debugging - uncomment if needed - /* console.log( - 'Snippet processing order:', - snippetOrder - .map(({ key, priority }) => `${key} (priority: ${priority})`).join("\n") - ); */ - - // Convert configs to prioritized snippets - let prioritizedSnippets = snippetOrder - .flatMap(({ key, priority }) => - snippets[key].map((snippet) => ({ snippet, priority })), - ) - .sort((a, b) => a.priority - b.priority) - .map(({ snippet }) => snippet); - - // Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature - // while looking at the prompts in the Continue's output - prioritizedSnippets = prioritizedSnippets.filter( - (snippet) => - !(snippet as AutocompleteCodeSnippet).filepath?.startsWith( - "output:extension-output-Continue.continue", - ), - ); - const finalSnippets = []; let remainingTokenCount = getRemainingTokenCount(helper); - while (remainingTokenCount > 0 && prioritizedSnippets.length > 0) { - const snippet = prioritizedSnippets.shift(); - if (!snippet || !isValidSnippet(snippet)) { - continue; + // Process snippets in priority order + for (const { key } of snippetOrder) { + // Special handling for recentlyOpenedFiles + if (key === "recentlyOpenedFiles" && helper.options.useRecentlyOpened) { + const recentlyOpenedFilesSnippets = + payload.recentlyOpenedFileSnippets.filter( + (snippet) => + !(snippet as AutocompleteCodeSnippet).filepath?.startsWith( + "output:extension-output-Continue.continue", + ), + ); + + // Custom trimming + const processedSnippets = formatOpenedFilesContext( + recentlyOpenedFilesSnippets, + remainingTokenCount, + helper, + finalSnippets, + TOKEN_BUFFER, + ); + + // Add processed snippets to finalSnippets respecting token limits + for (const snippet of processedSnippets) { + if (!isValidSnippet(snippet)) continue; + + const snippetSize = + countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; + + if (remainingTokenCount >= snippetSize) { + finalSnippets.push(snippet); + remainingTokenCount -= snippetSize; + } else { + break; // Out of tokens + } + } + } else { + // Normal processing for other snippet types + const snippetsToProcess = snippets[key].filter( + (snippet) => + !(snippet as AutocompleteCodeSnippet).filepath?.startsWith( + "output:extension-output-Continue.continue", + ), + ); + + for (const snippet of snippetsToProcess) { + if (!isValidSnippet(snippet)) continue; + + const snippetSize = + countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; + + if (remainingTokenCount >= snippetSize) { + finalSnippets.push(snippet); + remainingTokenCount -= snippetSize; + } else { + break; // Out of tokens + } + } } - const snippetSize = - countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; - - if (remainingTokenCount >= snippetSize) { - finalSnippets.push(snippet); - remainingTokenCount -= snippetSize; - } + // If we're out of tokens, no need to process more snippet types + if (remainingTokenCount <= 0) break; } return finalSnippets; diff --git a/core/autocomplete/templating/formatOpenedFilesContext.ts b/core/autocomplete/templating/formatOpenedFilesContext.ts new file mode 100644 index 000000000..cc8505ec5 --- /dev/null +++ b/core/autocomplete/templating/formatOpenedFilesContext.ts @@ -0,0 +1,172 @@ +import { countTokens, pruneStringFromBottom } from "../../llm/countTokens"; +import { AutocompleteSnippet } from "../snippets/types"; +import { HelperVars } from "../util/HelperVars"; + +let logMin: number; +let logMax: number; + +// when ranking files according to scores +const numFilesConsidered = 10; +const defaultNumFilesUsed = 5; + +// for scores +const recencyWeight = 0.5; +const sizeWeight = 0.5; + +const minSize = 10; // for numerical stability in log computations + +const minTokensInSnippet = 125; + +// Reduces opened file snippets to fit within the remaining amount of tokens +export function formatOpenedFilesContext( + recentlyOpenedFilesSnippets: AutocompleteSnippet[], + remainingTokenCount: number, + helper: HelperVars, + alreadyAddedSnippets: AutocompleteSnippet[], // TODO use this to deduplicate context + TOKEN_BUFFER: number, +): AutocompleteSnippet[] { + if (recentlyOpenedFilesSnippets.length === 0) { + return []; + } + + // Calculate how many full snippets would fit within the remaining token count + let numSnippetsThatFit = 0; + let totalTokens = 0; + + const numFilesUsed = Math.min( + defaultNumFilesUsed, + recentlyOpenedFilesSnippets.length, + ); + + for (let i = 0; i < recentlyOpenedFilesSnippets.length; i++) { + const snippetTokens = countTokens( + recentlyOpenedFilesSnippets[i].content, + helper.modelName, + ); + if (totalTokens + snippetTokens < remainingTokenCount - TOKEN_BUFFER) { + totalTokens += snippetTokens; + numSnippetsThatFit++; + } else { + break; + } + } + + // if we can fit all untrimmed snippets, or more than some default value, return the untrimmed snippets + if (numSnippetsThatFit >= numFilesUsed) { + return recentlyOpenedFilesSnippets.slice(0, numSnippetsThatFit); + } + + // If we can't fit all these, we need to adaptively trim them. + setLogStats(recentlyOpenedFilesSnippets); + const topScoredSnippets = rankByScore(recentlyOpenedFilesSnippets); + let N = topScoredSnippets.length; + while (remainingTokenCount - TOKEN_BUFFER < N * minTokensInSnippet) { + topScoredSnippets.pop(); + N = topScoredSnippets.length; + if (N === 0) break; + } + + let trimmedSnippets = new Array(); + + while (N > 0) { + let W = 2 / (N + 1); + let snippetTokenLimit = Math.floor( + minTokensInSnippet + + W * (remainingTokenCount - TOKEN_BUFFER - N * minTokensInSnippet), + ); + + let trimmedSnippetAndTokenCount = trimSnippetForContext( + topScoredSnippets[0], + snippetTokenLimit, + helper.modelName, + ); + trimmedSnippets.push(trimmedSnippetAndTokenCount.newSnippet); + remainingTokenCount -= trimmedSnippetAndTokenCount.newTokens; + topScoredSnippets.shift(); + N = topScoredSnippets.length; + } + + return trimmedSnippets; +} + +// Rank snippets by recency and size +const rankByScore = ( + snippets: AutocompleteSnippet[], +): AutocompleteSnippet[] => { + if (snippets.length === 0) return []; + + // Keep only the top numFilesConsidered elements (or all if fewer) + const topSnippets = snippets.slice(0, numFilesConsidered); + + // Sort by score (using original index for recency calculation) + const scoredSnippets = topSnippets.map((snippet, i) => ({ + snippet, + originalIndex: i, + score: getRecencyAndSizeScore(i, snippet), + })); + + scoredSnippets.sort((a, b) => b.score - a.score); + + // Return the top defaultNumFilesUsed (or all if fewer) + return scoredSnippets + .slice(0, Math.min(defaultNumFilesUsed, scoredSnippets.length)) + .map((item) => item.snippet); +}; + +// returns linear combination of recency and size scores +// recency score is exponential decay over recency; log normalized score is used for size +const getRecencyAndSizeScore = ( + index: number, + snippet: AutocompleteSnippet, +): number => { + const recencyScore = Math.pow(1.15, -1 * index); + + const logCurrent = Math.log(Math.max(snippet.content.length, minSize)); + const sizeScore = + logMax === logMin ? 0.5 : 1 - (logCurrent - logMax) / (logMax - logMin); + + return recencyWeight * recencyScore + sizeWeight * sizeScore; +}; + +// Utility to set logMin and logMax +const setLogStats = (snippets: AutocompleteSnippet[]): void => { + let contentSizes = snippets + .slice(0, 10) + .map((snippet) => snippet.content.length); + logMin = Math.log(Math.max(Math.min(...contentSizes), minSize)); + logMax = Math.log(Math.max(Math.max(...contentSizes), minSize)); + return; +}; + +function trimSnippetForContext( + snippet: AutocompleteSnippet, + maxTokens: number, + modelName: string, +): { newSnippet: AutocompleteSnippet; newTokens: number } { + // If the code is already under the token limit, return it as is + let numTokensInSnippet = countTokens(snippet.content, modelName); + if (numTokensInSnippet <= maxTokens) { + return { newSnippet: snippet, newTokens: numTokensInSnippet }; + } + + // Else trim from bottom + let trimmedCode = pruneStringFromBottom( + modelName, + maxTokens, + snippet.content, + ); + + // Add an indicator that the code has been trimmed + if (trimmedCode !== snippet.content) { + const lastNewline = trimmedCode.lastIndexOf("\n"); + if (lastNewline !== -1) { + trimmedCode = + trimmedCode.substring(0, lastNewline) + "\n// remaining code trimmed"; + } + } + + return { + newSnippet: { ...snippet, content: trimmedCode }, + newTokens: countTokens(trimmedCode, modelName), + }; +} From 8fc3a35e930f73c3361a60ada16d925c95920ebb Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Thu, 5 Jun 2025 16:21:32 -0700 Subject: [PATCH 023/104] branch ends here; debugged, optimized, and set up for good open file context provision --- .../templating/formatOpenedFilesContext.ts | 62 ++++++++----------- core/util/parameters.ts | 6 +- 2 files changed, 30 insertions(+), 38 deletions(-) diff --git a/core/autocomplete/templating/formatOpenedFilesContext.ts b/core/autocomplete/templating/formatOpenedFilesContext.ts index cc8505ec5..c114e63d1 100644 --- a/core/autocomplete/templating/formatOpenedFilesContext.ts +++ b/core/autocomplete/templating/formatOpenedFilesContext.ts @@ -1,30 +1,28 @@ import { countTokens, pruneStringFromBottom } from "../../llm/countTokens"; -import { AutocompleteSnippet } from "../snippets/types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippet, +} from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; let logMin: number; let logMax: number; -// when ranking files according to scores const numFilesConsidered = 10; const defaultNumFilesUsed = 5; - -// for scores -const recencyWeight = 0.5; -const sizeWeight = 0.5; - -const minSize = 10; // for numerical stability in log computations - +const recencyWeight = 0.6; +const sizeWeight = 0.4; +const minSize = 10; const minTokensInSnippet = 125; -// Reduces opened file snippets to fit within the remaining amount of tokens +// Fits opened-file snippets into the remaining amount of prompt tokens export function formatOpenedFilesContext( - recentlyOpenedFilesSnippets: AutocompleteSnippet[], + recentlyOpenedFilesSnippets: AutocompleteCodeSnippet[], remainingTokenCount: number, helper: HelperVars, alreadyAddedSnippets: AutocompleteSnippet[], // TODO use this to deduplicate context TOKEN_BUFFER: number, -): AutocompleteSnippet[] { +): AutocompleteCodeSnippet[] { if (recentlyOpenedFilesSnippets.length === 0) { return []; } @@ -51,12 +49,12 @@ export function formatOpenedFilesContext( } } - // if we can fit all untrimmed snippets, or more than some default value, return the untrimmed snippets + // if all the untrimmed snippets, or more than a default value, fit, return the untrimmed snippets if (numSnippetsThatFit >= numFilesUsed) { return recentlyOpenedFilesSnippets.slice(0, numSnippetsThatFit); } - // If we can't fit all these, we need to adaptively trim them. + // If they don't fit, adaptively trim them. setLogStats(recentlyOpenedFilesSnippets); const topScoredSnippets = rankByScore(recentlyOpenedFilesSnippets); let N = topScoredSnippets.length; @@ -66,7 +64,7 @@ export function formatOpenedFilesContext( if (N === 0) break; } - let trimmedSnippets = new Array(); + let trimmedSnippets = new Array(); while (N > 0) { let W = 2 / (N + 1); @@ -91,11 +89,10 @@ export function formatOpenedFilesContext( // Rank snippets by recency and size const rankByScore = ( - snippets: AutocompleteSnippet[], -): AutocompleteSnippet[] => { + snippets: AutocompleteCodeSnippet[], +): AutocompleteCodeSnippet[] => { if (snippets.length === 0) return []; - // Keep only the top numFilesConsidered elements (or all if fewer) const topSnippets = snippets.slice(0, numFilesConsidered); // Sort by score (using original index for recency calculation) @@ -105,15 +102,22 @@ const rankByScore = ( score: getRecencyAndSizeScore(i, snippet), })); + // Uncomment to debug. Logs the table of snippets with their scores (in order of recency). + /* console.table( + topSnippets.map((snippet, i) => ({ + filepath: "filepath" in snippet ? snippet.filepath : "unknown", + recencyAndSizeScore: getRecencyAndSizeScore(i, snippet), + })), + ); */ + scoredSnippets.sort((a, b) => b.score - a.score); - // Return the top defaultNumFilesUsed (or all if fewer) return scoredSnippets .slice(0, Math.min(defaultNumFilesUsed, scoredSnippets.length)) .map((item) => item.snippet); }; -// returns linear combination of recency and size scores +// Returns linear combination of recency and size scores // recency score is exponential decay over recency; log normalized score is used for size const getRecencyAndSizeScore = ( index: number, @@ -123,12 +127,11 @@ const getRecencyAndSizeScore = ( const logCurrent = Math.log(Math.max(snippet.content.length, minSize)); const sizeScore = - logMax === logMin ? 0.5 : 1 - (logCurrent - logMax) / (logMax - logMin); + logMax === logMin ? 0.5 : 1 - (logCurrent - logMin) / (logMax - logMin); return recencyWeight * recencyScore + sizeWeight * sizeScore; }; -// Utility to set logMin and logMax const setLogStats = (snippets: AutocompleteSnippet[]): void => { let contentSizes = snippets .slice(0, 10) @@ -139,32 +142,21 @@ const setLogStats = (snippets: AutocompleteSnippet[]): void => { }; function trimSnippetForContext( - snippet: AutocompleteSnippet, + snippet: AutocompleteCodeSnippet, maxTokens: number, modelName: string, -): { newSnippet: AutocompleteSnippet; newTokens: number } { - // If the code is already under the token limit, return it as is +): { newSnippet: AutocompleteCodeSnippet; newTokens: number } { let numTokensInSnippet = countTokens(snippet.content, modelName); if (numTokensInSnippet <= maxTokens) { return { newSnippet: snippet, newTokens: numTokensInSnippet }; } - // Else trim from bottom let trimmedCode = pruneStringFromBottom( modelName, maxTokens, snippet.content, ); - // Add an indicator that the code has been trimmed - if (trimmedCode !== snippet.content) { - const lastNewline = trimmedCode.lastIndexOf("\n"); - if (lastNewline !== -1) { - trimmedCode = - trimmedCode.substring(0, lastNewline) + "\n// remaining code trimmed"; - } - } - return { newSnippet: { ...snippet, content: trimmedCode }, newTokens: countTokens(trimmedCode, modelName), diff --git a/core/util/parameters.ts b/core/util/parameters.ts index e6fd93189..cadbe9a47 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -2,9 +2,9 @@ import { TabAutocompleteOptions } from "../index.js"; export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disable: false, - maxPromptTokens: 2048, // doubled from default to fit opened files - prefixPercentage: 0.15, // halved as a result - maxSuffixPercentage: 0.1, // halved as a result + maxPromptTokens: 1024, + prefixPercentage: 0.3, + maxSuffixPercentage: 0.2, debounceDelay: 350, modelTimeout: 150, multilineCompletions: "auto", From 029b0cabc25bb682f85d17c76a750c67b3cce933 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Thu, 5 Jun 2025 16:40:52 -0700 Subject: [PATCH 024/104] updated MessageIDE and FileSystemIDE to include necessary methods for open file viewing --- core/protocol/messenger/messageIde.ts | 9 +++++++++ core/util/filesystem.ts | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index b3af976f2..f6a2e8738 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -40,22 +40,30 @@ export class MessageIde implements IDE { fileExists(fileUri: string): Promise { return this.request("fileExists", { filepath: fileUri }); } + async gotoDefinition(location: Location): Promise { return this.request("gotoDefinition", { location }); } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } + onDidCloseTextDocument(callback: (fileUris: string[]) => void): void { + this.on("didCloseTextDocument", (data) => callback(data.filepaths)); + } + getIdeSettings(): Promise { return this.request("getIdeSettings", undefined); } + getFileStats(files: string[]): Promise { return this.request("getFileStats", { files }); } getGitRootPath(dir: string): Promise { return this.request("getGitRootPath", { dir }); } + listDir(dir: string): Promise<[string, FileType][]> { return this.request("listDir", { dir }); } @@ -164,6 +172,7 @@ export class MessageIde implements IDE { async saveFile(fileUri: string): Promise { await this.request("saveFile", { filepath: fileUri }); } + async readFile(fileUri: string): Promise { return await this.request("readFile", { filepath: fileUri }); } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index ccb97ed8f..78620bf71 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -34,6 +34,7 @@ class FileSystemIde implements IDE { ): Promise { return Promise.resolve(); } + fileExists(fileUri: string): Promise { const filepath = fileURLToPath(fileUri); return Promise.resolve(fs.existsSync(filepath)); @@ -42,10 +43,15 @@ class FileSystemIde implements IDE { gotoDefinition(location: Location): Promise { return Promise.resolve([]); } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } + onDidCloseTextDocument(callback: (fileUris: string[]) => void): void { + return; + } + async getIdeSettings(): Promise { return { remoteConfigServerUrl: undefined, @@ -55,6 +61,7 @@ class FileSystemIde implements IDE { pauseCodebaseIndexOnStart: false, }; } + async getFileStats(fileUris: string[]): Promise { const result: FileStatsMap = {}; for (const uri of fileUris) { @@ -71,9 +78,11 @@ class FileSystemIde implements IDE { } return result; } + getGitRootPath(dir: string): Promise { return Promise.resolve(dir); } + async listDir(dir: string): Promise<[string, FileType][]> { const filepath = fileURLToPath(dir); const all: [string, FileType][] = fs From 1513f5dd48f9f0d64484e33ded67a710e06e2921 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Thu, 5 Jun 2025 16:59:51 -0700 Subject: [PATCH 025/104] miscellaneous cleanup --- .continue/prompts/update-llm-info.prompt | 79 ++++ .../config/yaml/LocalPlatformClient.vitest.ts | 233 +++++++++++ core/control-plane/mdm/mdm.test.ts | 210 ++++++++++ core/control-plane/mdm/mdm.ts | 364 ++++++++++++++++++ .../promptFiles/v2/renderPromptFile.vitest.ts | 175 +++++++++ core/protocol/messenger/messageIde.ts | 4 + core/util/filesystem.ts | 3 + packages/fetch/src/getAgentOptions.test.ts | 122 ++++++ packages/fetch/vitest.config.ts | 17 + 9 files changed, 1207 insertions(+) create mode 100644 .continue/prompts/update-llm-info.prompt create mode 100644 core/config/yaml/LocalPlatformClient.vitest.ts create mode 100644 core/control-plane/mdm/mdm.test.ts create mode 100644 core/control-plane/mdm/mdm.ts create mode 100644 core/promptFiles/v2/renderPromptFile.vitest.ts create mode 100644 packages/fetch/src/getAgentOptions.test.ts create mode 100644 packages/fetch/vitest.config.ts diff --git a/.continue/prompts/update-llm-info.prompt b/.continue/prompts/update-llm-info.prompt new file mode 100644 index 000000000..7264ebf38 --- /dev/null +++ b/.continue/prompts/update-llm-info.prompt @@ -0,0 +1,79 @@ +name: Update LLM Info +description: Updates Gemini blocks with latest information +version: 2 +--- +I need you to update this repo with the latest information about large language models from certain providers. +The information is stored in the `packages/llm-info` directory, which operates as its own npm package. +Information is stored in a simple JSON format, with one file of models per "provider" (e.g. gemini, ollama, openai, etc). +For example, Gemini model information is stored in `packages/llm-info/src/providers/gemini.ts`. + +To make these updates for a given provider, perform the following steps one at a time: + +1. VIEW CURRENT INFORMATION + +To view the current llm info, read the file (e.g. `packages/llm-info/src/providers/gemini.ts`) using the read_file tool. +If you do not see a tool for reading files, let me know. + +For reference, here is the LLMInfo interface used to store the information: + +```typescript +export interface LlmInfo { + model: string; // the model name used to distinguish the model at the API layer, e.g. "gemini-2.5-pro-preview-05-06" + displayName?: string; // A fitting display name, e.g. "Gemini 2.5 Pro Preview" + description?: string; // A short description of the model, as similar as possible to descriptions found on the provider's website + contextLength?: number; // The size of the context window in tokens, often called "max input tokens" or "context length" + maxCompletionTokens?: number; // The maximum number of tokens the model can output + regex?: RegExp; // A regex expression to uniquely match the model name if it had some slight modifications/upgrades, e.g. /gemini-2\.5-pro-preview/i + mediaTypes?: MediaType[]; // Input/output types supported by the model, e.g. [MediaType.Text, MediaType.Image] +} + +export enum MediaType { + Text = "text", + Image = "image", + Audio = "audio", + Video = "video", +} + +export const AllMediaTypes = [ + MediaType.Text, + MediaType.Image, + MediaType.Audio, + MediaType.Video, +]; +``` + +2. EXTRACT NEW INFORMATION + +New information will be pulled from the internet. +If you do not see a web search tool, let me know. + +Retrieve the following sites per these providers, and consider these notes on how to extract the information: +- "gemini": https://ai.google.dev/gemini-api/docs/models - maxCompletionTokens is called "Output token limit", contextLength is called "Input token limit" +// TODO: add info for openai, ollama, etc + +For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement. +Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored. +Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained. + +3. UPDATE THE INFORMATION + +Use the edit file tool to submit updates to the relevant provider file (e.g. `packages/llm-info/src/providers/gemini.ts`). +Let me know if you do not see a tool for editing files. + +Generally, avoid making changes to existing information, as it is probably up to date. +Primarily, focus on adding new models or adding missing information to existing models. +NEVER delete any existing models, but let me know if you think one should be removed. +Stop to ask me if you are unsure about any changes, and let me know if there are updates that seem nuanced, complex, or extremely notable. +Provide a summary of changes after the fact. + +4. ASK IF I WANT TO PUBLISH TO NPM +After you are done updating everything, remind me that I need to publish the changes to npm. + +// TODO too sensitive for now +// If yes, update `packages/llm-info/package.json` with the new version number and then +// - use the terminal tool to commit the changes +// - use the terminal tool to publish changes to npm +// If you do not see a tool for running terminal commands, let me know. + +// User input +Please update LLM Info for the following providers. If "all", update all providers mentioned above: diff --git a/core/config/yaml/LocalPlatformClient.vitest.ts b/core/config/yaml/LocalPlatformClient.vitest.ts new file mode 100644 index 000000000..a91017ed2 --- /dev/null +++ b/core/config/yaml/LocalPlatformClient.vitest.ts @@ -0,0 +1,233 @@ +import { FQSN, SecretResult, SecretType } from "@continuedev/config-yaml"; +import { + afterEach, + beforeEach, + describe, + expect, + Mock, + test, + vi, +} from "vitest"; +import { IDE } from "../.."; +import { ControlPlaneClient } from "../../control-plane/client"; +import { LocalPlatformClient } from "./LocalPlatformClient"; + +vi.mock("../../util/paths", { spy: true }); + +describe("LocalPlatformClient", () => { + const testFQSN: FQSN = { + packageSlugs: [ + { + ownerSlug: "test-owner-slug", + packageSlug: "test-package-slug", + }, + ], + secretName: "TEST_CONTINUE_SECRET_KEY", + }; + const testFQSN2: FQSN = { + packageSlugs: [ + { + ownerSlug: "test-owner-slug-2", + packageSlug: "test-package-slug-2", + }, + ], + secretName: "TEST_WORKSPACE_SECRET_KEY", + }; + + const testResolvedFQSN: SecretResult = { + found: true, + fqsn: testFQSN, + secretLocation: { + secretName: testFQSN.secretName, + secretType: SecretType.Organization, + orgSlug: "test-org-slug", + }, + }; + + let testControlPlaneClient: ControlPlaneClient; + let testIde: IDE; + beforeEach( + /**dynamic import before each test for test isolation */ + async () => { + const testFixtures = await import("../../test/fixtures"); + testControlPlaneClient = testFixtures.testControlPlaneClient; + testIde = testFixtures.testIde; + }, + ); + + let secretValue: string; + let envKeyValues: Record; + let envKeyValuesString: string; + beforeEach( + /**generate unique env key value pairs for each test */ + () => { + secretValue = Math.floor(Math.random() * 100) + ""; + envKeyValues = { + TEST_CONTINUE_SECRET_KEY: secretValue, + TEST_WORKSPACE_SECRET_KEY: secretValue + "-workspace", + }; + envKeyValuesString = Object.entries(envKeyValues) + .map(([key, value]) => `${key}=${value}`) + .join("\n"); + }, + ); + + afterEach(() => { + vi.resetAllMocks(); + vi.restoreAllMocks(); + vi.resetModules(); // clear dynamic imported module cache + }); + + test("should not be able to resolve FQSNs if they do not exist", async () => { + const localPlatformClient = new LocalPlatformClient( + null, + testControlPlaneClient, + testIde, + ); + const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]); + + expect(resolvedFQSNs.length).toBeGreaterThan(0); + expect(resolvedFQSNs[0]?.found).toBe(false); + }); + + test("should be able to resolve FQSNs if they exist", async () => { + testControlPlaneClient.resolveFQSNs = vi.fn(async () => [testResolvedFQSN]); + const localPlatformClient = new LocalPlatformClient( + null, + testControlPlaneClient, + testIde, + ); + const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]); + expect(testControlPlaneClient.resolveFQSNs).toHaveBeenCalled(); + expect(resolvedFQSNs).toEqual([testResolvedFQSN]); + expect(resolvedFQSNs[0]?.found).toBe(true); + }); + + describe("searches for secrets in local .env files", () => { + let getContinueDotEnv: Mock; + beforeEach(async () => { + const utilPaths = await import("../../util/paths"); + getContinueDotEnv = vi.fn(() => envKeyValues); + utilPaths.getContinueDotEnv = getContinueDotEnv; + }); + + test("should be able to get secrets from ~/.continue/.env files", async () => { + const localPlatformClient = new LocalPlatformClient( + null, + testControlPlaneClient, + testIde, + ); + const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]); + expect(getContinueDotEnv).toHaveBeenCalled(); + expect(resolvedFQSNs.length).toBe(1); + expect( + (resolvedFQSNs[0] as SecretResult & { value: unknown })?.value, + ).toBe(secretValue); + console.log("debug1 resolved fqsn", resolvedFQSNs); + }); + }); + + describe("should be able to get secrets from workspace .env files", () => { + test("should get secrets from /.continue/.env and /.env", async () => { + const originalIdeFileExists = testIde.fileExists; + testIde.fileExists = vi.fn(async (fileUri: string) => + fileUri.includes(".env") ? true : originalIdeFileExists(fileUri), + ); + + const originalIdeReadFile = testIde.readFile; + const randomValueForContinueDirDotEnv = + "continue-dir-" + Math.floor(Math.random() * 100); + const randomValueForWorkspaceDotEnv = + "dotenv-" + Math.floor(Math.random() * 100); + + testIde.readFile = vi.fn(async (fileUri: string) => { + // fileUri should contain .continue/.env and not .env + if (fileUri.match(/.*\.continue\/\.env.*/gi)?.length) { + return ( + envKeyValuesString.split("\n")[0] + randomValueForContinueDirDotEnv + ); + } + // filUri should contain .env and not .continue/.env + else if (fileUri.match(/.*(?/.continue/.env and then /.env", async () => { + const originalIdeFileExists = testIde.fileExists; + testIde.fileExists = vi.fn(async (fileUri: string) => + fileUri.includes(".env") ? true : originalIdeFileExists(fileUri), + ); + + const randomValueForContinueDirDotEnv = + "continue-dir-" + Math.floor(Math.random() * 100); + const randomValueForWorkspaceDotEnv = + "dotenv-" + Math.floor(Math.random() * 100); + + const originalIdeReadFile = testIde.readFile; + testIde.readFile = vi.fn(async (fileUri: string) => { + // fileUri should contain .continue/.env and not .env + if (fileUri.match(/.*\.continue\/\.env.*/gi)?.length) { + return ( + envKeyValuesString.split("\n")[0] + randomValueForContinueDirDotEnv + ); + } + // filUri should contain .env and not .continue/.env + else if (fileUri.match(/.*(?.continue/.env does not override the /.env secret + expect( + (resolvedFQSNs[0] as SecretResult & { value: unknown })?.value, + ).toContain(randomValueForContinueDirDotEnv); + expect( + (resolvedFQSNs[0] as SecretResult & { value: unknown })?.value, + ).not.toContain(randomValueForWorkspaceDotEnv); + }); + }); +}); diff --git a/core/control-plane/mdm/mdm.test.ts b/core/control-plane/mdm/mdm.test.ts new file mode 100644 index 000000000..ca4f5f0ec --- /dev/null +++ b/core/control-plane/mdm/mdm.test.ts @@ -0,0 +1,210 @@ +import * as crypto from "crypto"; +import { LicenseKeyData, validateLicenseKey } from "./mdm"; + +// We'll create a real key pair once for all tests +const testKeyPair = crypto.generateKeyPairSync("rsa", { + modulusLength: 2048, + publicKeyEncoding: { + type: "spki", + format: "pem", + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem", + }, +}); + +// Custom function to create test licenses with the new structure including unsignedData +function createTestLicense( + licenseData: LicenseKeyData, + apiUrl: string = "https://api.continue.dev", + useValidSignature: boolean = true, +): string { + // Convert license data to a string + const licenseDataStr = JSON.stringify(licenseData); + + // Create a signature with our generated private key + const sign = crypto.createSign("SHA256"); + sign.update(licenseDataStr); + sign.end(); + + let signature: string; + if (useValidSignature) { + signature = sign.sign(testKeyPair.privateKey, "base64"); + } else { + // For invalid tests, create an intentionally wrong signature by signing different data + const wrongSign = crypto.createSign("SHA256"); + wrongSign.update(licenseDataStr + "tampered"); + wrongSign.end(); + signature = wrongSign.sign(testKeyPair.privateKey, "base64"); + } + + // Combine data, signature, and unsigned data into a license key + const licenseKeyObj = { + data: licenseDataStr, + signature: signature, + unsignedData: { + apiUrl: apiUrl, + }, + }; + + return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64"); +} + +// We need to test the actual implementation - which we can't mock with ESM +// Instead, we'll have tests that bypass validation or are expected to fail +// depending on what we're testing + +test("validateLicenseKey returns false for malformed license key", () => { + // Test with a completely invalid license key + const invalidLicenseKey = "not-a-valid-license-key"; + + // Test - no mocks, real validation + const result = validateLicenseKey(invalidLicenseKey); + + // Assert + expect(result.isValid).toBe(false); + expect(result.licenseKeyData).toBeUndefined(); +}); + +test("validateLicenseKey returns false for invalid JSON in license key", () => { + // Create a malformed but base64-encoded string + const malformedLicenseKey = Buffer.from("this is not valid JSON").toString( + "base64", + ); + + // Test - no mocks, real validation + const result = validateLicenseKey(malformedLicenseKey); + + // Assert + expect(result.isValid).toBe(false); + expect(result.licenseKeyData).toBeUndefined(); +}); + +test("validateLicenseKey returns false for expired license", () => { + // Without mocking, we expect this to fail signature verification + // We're testing the date logic by itself + const licenseData: LicenseKeyData = { + customerId: "customer123", + createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago + expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago + }; + + // Create a license key with apiUrl in unsignedData - will fail verification but test logic still works + const expiredLicenseKey = createTestLicense( + licenseData, + "https://api.continue.dev", + ); + + // Test - expect false, either due to signature or expiration - both are valid test cases + const result = validateLicenseKey(expiredLicenseKey); + + // Assert + expect(result.isValid).toBe(false); + expect(result.licenseKeyData).toBeUndefined(); +}); + +test("validateLicenseKey returns false for invalid signature", () => { + // Create license data with valid dates + const licenseData: LicenseKeyData = { + customerId: "customer123", + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day + }; + + // Create a license with an invalid signature but valid unsignedData structure + const invalidSignatureKey = createTestLicense( + licenseData, + "https://api.continue.dev", + false, + ); + + // Test - no mocks, real validation + const result = validateLicenseKey(invalidSignatureKey); + + // Assert + expect(result.isValid).toBe(false); + expect(result.licenseKeyData).toBeUndefined(); +}); + +test("validateLicenseKey handles JSON parsing errors gracefully", () => { + // Create a base64 string that decodes to valid JSON but lacks required fields + const invalidStructureKey = Buffer.from( + JSON.stringify({ + notTheRightField: "wrong structure", + }), + ).toString("base64"); + + // Test - no mocks, real validation + const result = validateLicenseKey(invalidStructureKey); + + // Assert + expect(result.isValid).toBe(false); + expect(result.licenseKeyData).toBeUndefined(); +}); + +test("validateLicenseKey handles missing unsignedData gracefully", () => { + // Create a license key structure without unsignedData field + const licenseData: LicenseKeyData = { + customerId: "customer123", + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), + }; + + const licenseDataStr = JSON.stringify(licenseData); + const sign = crypto.createSign("SHA256"); + sign.update(licenseDataStr); + sign.end(); + const signature = sign.sign(testKeyPair.privateKey, "base64"); + + // Create license key without unsignedData + const licenseKeyObj = { + data: licenseDataStr, + signature: signature, + // Missing unsignedData field + }; + + const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString( + "base64", + ); + + // Test - no mocks, real validation + const result = validateLicenseKey(licenseKey); + + // Assert - should fail due to signature verification with wrong public key + expect(result.isValid).toBe(false); + expect(result.licenseKeyData).toBeUndefined(); +}); + +test("validateLicenseKey handles invalid unsignedData structure", () => { + // Create license data with valid dates + const licenseData: LicenseKeyData = { + customerId: "customer123", + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), + }; + + const licenseDataStr = JSON.stringify(licenseData); + const sign = crypto.createSign("SHA256"); + sign.update(licenseDataStr); + sign.end(); + const signature = sign.sign(testKeyPair.privateKey, "base64"); + + // Create license key with invalid unsignedData structure + const licenseKeyObj = { + data: licenseDataStr, + signature: signature, + unsignedData: "not an object", // Should be an object with apiUrl + }; + + const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString( + "base64", + ); + + // Test - no mocks, real validation + const result = validateLicenseKey(licenseKey); + + // Assert - should fail due to signature verification with wrong public key + expect(result.isValid).toBe(false); + expect(result.licenseKeyData).toBeUndefined(); +}); diff --git a/core/control-plane/mdm/mdm.ts b/core/control-plane/mdm/mdm.ts new file mode 100644 index 000000000..c782105ed --- /dev/null +++ b/core/control-plane/mdm/mdm.ts @@ -0,0 +1,364 @@ +import * as crypto from "crypto"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import * as plist from "plist"; + +export interface MdmKeys { + licenseKey: string; +} + +const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp +93QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7 +HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA +zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn +U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP +LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar +FQIDAQAB +-----END PUBLIC KEY-----`; + +interface LicenseKeyUnsignedData { + apiUrl: string; +} + +export interface LicenseKey { + signature: string; + data: string; + unsignedData: LicenseKeyUnsignedData; +} + +export interface LicenseKeyData { + customerId: string; + createdAt: string; + expiresAt: string; +} + +export function validateLicenseKey(licenseKey: string): { + isValid: boolean; + licenseKeyData?: LicenseKey; +} { + try { + // Decode the base64 license key + const decodedString = Buffer.from(licenseKey, "base64").toString("utf8"); + const { data, signature, unsignedData } = JSON.parse(decodedString); + + // Verify the signature + const verify = crypto.createVerify("SHA256"); + verify.update(data); + verify.end(); + + const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64"); + + if (!isValid) return { isValid: false }; + + // Check license expiration + const licenseData: LicenseKeyData = JSON.parse(data); + const expirationDate = new Date(licenseData.expiresAt); + const now = new Date(); + + const isNotExpired = expirationDate > now; + + if (!isNotExpired) return { isValid: false }; + + // Return both validation result and license key data + const licenseKeyData: LicenseKey = { + signature, + data, + unsignedData, + }; + + return { isValid: true, licenseKeyData }; + } catch (error) { + console.error("License validation error:", error); + return { isValid: false }; + } +} + +const MACOS_MDM_PATHS = [ + // Organization-specific MDM plist + "/Library/Managed Preferences/dev.continue.app.plist", + // User-specific MDM plist + path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"), +]; + +function readMdmKeysMacOS(): MdmKeys | undefined { + try { + // MDM configuration is typically stored in /Library/Managed Preferences/ on macOS + // The filename is often the bundle identifier of the application + + // Try to find a valid MDM configuration file + for (const mdmPath of MACOS_MDM_PATHS) { + if (fs.existsSync(mdmPath)) { + // Read the file content + const fileContent = fs.readFileSync(mdmPath, "utf8"); + + try { + // Parse the plist file using the plist package + const config = plist.parse(fileContent) as + | { licenseKey: string | undefined } + | undefined; + + if (config && config?.licenseKey) { + // Extract the license key from the configuration + return { licenseKey: config?.licenseKey }; + } else { + console.error("Invalid MDM configuration format"); + } + } catch (parseError) { + console.error(`Error parsing MDM configuration: ${parseError}`); + } + } + } + + return undefined; + } catch (error) { + console.error("Error reading macOS MDM keys:", error); + return undefined; + } +} + +function readMdmKeysWindows(): MdmKeys | undefined { + try { + // For Windows, we need to read from the registry + // Using regedit or another synchronous registry access module + const { execSync } = require("child_process"); + + // Path to the registry where MDM configuration is stored + const regPath = "HKLM\\Software\\Continue\\MDM"; + const userRegPath = "HKCU\\Software\\Continue\\MDM"; + + // Try to read from HKEY_LOCAL_MACHINE first + try { + // Use REG QUERY command to read registry values + const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`; + const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" }); + // Extract values from command output + const licenseKey = extractRegValue(licenseKeyOutput); + if (licenseKey) { + return { licenseKey }; + } + } catch (error) { + // Registry key might not exist, fallback to HKEY_CURRENT_USER + } + + // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE + try { + const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`; + const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" }); + // Extract values from command output + const licenseKey = extractRegValue(licenseKeyOutput); + if (licenseKey) { + return { licenseKey }; + } + } catch (error) { + // Registry key might not exist in HKCU either + } + + return undefined; + } catch (error) { + console.error("Error reading Windows MDM keys:", error); + return undefined; + } +} + +// Helper function to extract registry values from reg query output +function extractRegValue(output: string): string | undefined { + const match = output.match(/REG_SZ\s+(.+)$/m); + return match ? match[1].trim() : undefined; +} + +// Common locations for MDM configurations in Linux systems +const LINUX_MDM_PATHS = [ + // System-wide configuration + "/etc/continue/mdm.json", + "/var/lib/continue/mdm.json", + // User-specific configuration + path.join(os.homedir(), ".config/continue/mdm.json"), +]; + +function readMdmKeysLinux(): MdmKeys | undefined { + try { + // Try to find a valid MDM configuration file + for (const mdmPath of LINUX_MDM_PATHS) { + if (fs.existsSync(mdmPath)) { + // Read the file content + const fileContent = fs.readFileSync(mdmPath, "utf8"); + + try { + // Parse the JSON configuration file + const config = JSON.parse(fileContent); + + // Check if required key is present + if (config.licenseKey) { + return { + licenseKey: config.licenseKey, + }; + } + } catch (parseError) { + console.error(`Error parsing Linux MDM configuration: ${parseError}`); + } + } + } + + return undefined; + } catch (error) { + console.error("Error reading Linux MDM keys:", error); + return undefined; + } +} + +function readMdmKeys(): MdmKeys | undefined { + const platform = os.platform(); + + switch (platform) { + case "darwin": + return readMdmKeysMacOS(); + + case "win32": + return readMdmKeysWindows(); + + case "linux": + return readMdmKeysLinux(); + + default: + console.error(`MDM keys not supported on platform: ${platform}`); + return undefined; + } +} + +/** + * Read and validate MDM keys from the operating system's configuration files or registry. + */ +export function getLicenseKeyData(): LicenseKey | undefined { + try { + const mdmKeys = readMdmKeys(); + + if (mdmKeys) { + const { isValid, licenseKeyData } = validateLicenseKey( + mdmKeys.licenseKey, + ); + if (!isValid) { + console.error("Invalid license key found: ", mdmKeys.licenseKey); + return undefined; + } + + return licenseKeyData; + } + + return undefined; + } catch (e) { + console.warn("Error reading MDM keys: ", e); + return undefined; + } +} + +function writeMdmKeysMacOS(licenseKey: string): boolean { + try { + // Write to user-specific MDM plist + const userMdmPath = path.join( + os.homedir(), + "Library/Managed Preferences/dev.continue.app.plist", + ); + + const config = { + licenseKey, + }; + + // Ensure directory exists + fs.mkdirSync(path.dirname(userMdmPath), { recursive: true }); + + // Write the plist file + const plistContent = plist.build(config); + fs.writeFileSync(userMdmPath, plistContent, "utf8"); + + return true; + } catch (error) { + console.error("Error writing macOS MDM keys:", error); + return false; + } +} + +function writeMdmKeysWindows(licenseKey: string): boolean { + try { + const { execSync } = require("child_process"); + + // Use HKEY_CURRENT_USER to avoid needing admin privileges + const userRegPath = "HKCU\\Software\\Continue\\MDM"; + + // Create the registry key if it doesn't exist + try { + execSync(`reg add "${userRegPath}" /f`); + } catch (error) { + // Key might already exist + } + + // Set the license key and API URL + execSync( + `reg add "${userRegPath}" /v licenseKey /t REG_SZ /d "${licenseKey}" /f`, + ); + + return true; + } catch (error) { + console.error("Error writing Windows MDM keys:", error); + return false; + } +} + +function writeMdmKeysLinux(licenseKey: string): boolean { + try { + // Write to user-specific configuration + const userMdmPath = path.join(os.homedir(), ".config/continue/mdm.json"); + + const config = { + licenseKey, + }; + + // Ensure directory exists + fs.mkdirSync(path.dirname(userMdmPath), { recursive: true }); + + // Write the JSON configuration file + fs.writeFileSync(userMdmPath, JSON.stringify(config, null, 2), "utf8"); + + return true; + } catch (error) { + console.error("Error writing Linux MDM keys:", error); + return false; + } +} + +/** + * Store the license key in the appropriate OS-specific location. + * For now, we'll use a default API URL since it's not provided in the command. + */ +export function setMdmLicenseKey(licenseKey: string): boolean { + try { + // Validate the license key first + const { isValid } = validateLicenseKey(licenseKey); + if (!isValid) { + return false; + } + + const platform = os.platform(); + + switch (platform) { + case "darwin": + return writeMdmKeysMacOS(licenseKey); + + case "win32": + return writeMdmKeysWindows(licenseKey); + + case "linux": + return writeMdmKeysLinux(licenseKey); + + default: + console.error( + `Setting MDM keys not supported on platform: ${platform}`, + ); + return false; + } + } catch (error) { + console.error("Error setting MDM license key:", error); + return false; + } +} diff --git a/core/promptFiles/v2/renderPromptFile.vitest.ts b/core/promptFiles/v2/renderPromptFile.vitest.ts new file mode 100644 index 000000000..1d72bc85a --- /dev/null +++ b/core/promptFiles/v2/renderPromptFile.vitest.ts @@ -0,0 +1,175 @@ +import { ContextProviderExtras, ILLM, RangeInFile } from "../.."; +import { testConfigHandler, testIde } from "../../test/fixtures"; +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, +} from "../../test/testDir"; +import { renderPromptFileV2 } from "./renderPromptFile"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock( + import("../../context/providers/URLContextProvider"), + async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + getUrlContextItems: vi.fn().mockResolvedValue([ + { + description: "https://example.com", + content: "Example Content", + name: "Example site", + uri: { + type: "url", + value: "https://example.com", + }, + }, + ]), + }; + }, +); + +describe("renderPromptFileV2", () => { + let extras: ContextProviderExtras; + const mockGetContextItems = vi.fn().mockResolvedValue([ + { + name: "custom", + content: "Custom provider content", + description: "Custom provider", + }, + ]); + beforeEach(async () => { + const { config } = await testConfigHandler.loadConfig(); + + // Setup mock extras + extras = { + config: { + ...config!, + contextProviders: [ + { + description: { + type: "normal", + title: "CustomProvider", + displayTitle: "Custom Provider", + description: "A custom context provider", + }, + loadSubmenuItems: vi.fn().mockResolvedValue([]), + getContextItems: mockGetContextItems, + }, + ], + }, + fullInput: "User input", + embeddingsProvider: null, + reranker: null, + llm: {} as ILLM, + ide: testIde, + selectedCode: [] as RangeInFile[], + fetch: vi.fn(), + }; + + // Clear all mocks + vi.clearAllMocks(); + setUpTestDir(); + }); + + afterEach(() => { + tearDownTestDir(); + }); + + it("should render a prompt file with no attachments", async () => { + const rawContent = "Simple prompt with no attachments"; + const [contextItems, renderedPrompt] = await renderPromptFileV2( + rawContent, + extras, + ); + + expect(contextItems).toHaveLength(0); + expect(renderedPrompt).toBe( + "Simple prompt with no attachments\n\nUser input", + ); + }); + + it("should handle URL attachments", async () => { + const rawContent = "Content with URL @https://example.com"; + + const [contextItems, renderedPrompt] = await renderPromptFileV2( + rawContent, + extras, + ); + + expect(contextItems).toHaveLength(1); + expect(renderedPrompt).toContain("Example Content"); + }); + + it("should resolve file attachments", async () => { + const rawContent = "Content with file attachment @test.txt"; + + addToTestDir([["test.txt", "File content"]]); + + const [contextItems, renderedPrompt] = await renderPromptFileV2( + rawContent, + extras, + ); + + expect(contextItems).toHaveLength(1); + expect(renderedPrompt).toContain("```test.txt\nFile content\n```"); + expect(renderedPrompt).toContain("Content with file attachment @test.txt"); + }); + + it("should handle nested prompt files", async () => { + const rawContent = "Main prompt with nested @nested.prompt"; + addToTestDir([ + ["nested.prompt", "Nested prompt content with @CustomProvider"], + ]); + + const [contextItems, renderedPrompt] = await renderPromptFileV2( + rawContent, + extras, + ); + + expect(renderedPrompt).toContain("Custom provider content"); + }); + + it("should handle custom context providers", async () => { + const rawContent = "Content with custom provider @CustomProvider"; + + const [contextItems, renderedPrompt] = await renderPromptFileV2( + rawContent, + extras, + ); + + expect(contextItems).toHaveLength(1); + expect(renderedPrompt).toContain("Custom provider content"); + expect(mockGetContextItems).toHaveBeenCalled(); + }); + + it("should handle multiple attachments", async () => { + const rawContent = "Content with @file1.txt and @file2.txt"; + addToTestDir([ + ["file1.txt", "Content 1"], + ["file2.txt", "Content 2"], + ]); + + const [contextItems, renderedPrompt] = await renderPromptFileV2( + rawContent, + extras, + ); + + expect(contextItems).toHaveLength(2); + expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```"); + expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```"); + }); + + it("should handle failed attachment resolutions gracefully", async () => { + const rawContent = "Content with @nonexistent"; + + const [contextItems, renderedPrompt] = await renderPromptFileV2( + rawContent, + extras, + ); + + expect(contextItems).toHaveLength(0); + expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input"); + }); +}); diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index b3af976f2..8bd1d3e80 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -47,6 +47,10 @@ export class MessageIde implements IDE { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } + onDidCloseTextDocument(callback: (fileUris: string[]) => void): void { + this.on("didCloseTextDocument", (data) => callback(data.filepaths)); + } + getIdeSettings(): Promise { return this.request("getIdeSettings", undefined); } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index ccb97ed8f..f6f0b5d66 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -45,6 +45,9 @@ class FileSystemIde implements IDE { onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } + onDidCloseTextDocument(callback: (fileUris: string[]) => void): void { + return; + } async getIdeSettings(): Promise { return { diff --git a/packages/fetch/src/getAgentOptions.test.ts b/packages/fetch/src/getAgentOptions.test.ts new file mode 100644 index 000000000..5b589ea85 --- /dev/null +++ b/packages/fetch/src/getAgentOptions.test.ts @@ -0,0 +1,122 @@ +import * as fs from "node:fs"; +import { expect, test, vi } from "vitest"; + +// Mock fs module +vi.mock("node:fs", () => ({ + readFileSync: vi.fn(), +})); + +const mockReadFileSync = vi.mocked(fs.readFileSync); + +// We need to access the private getCertificateContent function for testing +// Since it's not exported, we'll test it indirectly through scenarios or mock the module +const getCertificateContent = (input: string): string => { + if (input.startsWith("data:")) { + // Parse data URI: data:[][;base64], + const [header, data] = input.split(","); + if (header.includes("base64")) { + return Buffer.from(data, "base64").toString("utf8"); + } else { + return decodeURIComponent(data); + } + } else { + // Assume it's a file path + return fs.readFileSync(input, "utf8"); + } +}; + +test("getCertificateContent should decode base64 data URI correctly", () => { + const testCert = + "-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----"; + const base64Data = Buffer.from(testCert, "utf8").toString("base64"); + const dataUri = `data:application/x-pem-file;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testCert); +}); + +test("getCertificateContent should decode URL-encoded data URI correctly", () => { + const testCert = + "-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----"; + const encodedData = encodeURIComponent(testCert); + const dataUri = `data:text/plain,${encodedData}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testCert); +}); + +test("getCertificateContent should handle plain text data URI correctly", () => { + const testCert = "simple-cert-content"; + const dataUri = `data:text/plain,${testCert}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testCert); +}); + +test("getCertificateContent should read file when input is a file path", () => { + const filePath = "/path/to/cert.pem"; + const expectedContent = + "-----BEGIN CERTIFICATE-----\nfile content\n-----END CERTIFICATE-----"; + + mockReadFileSync.mockReturnValue(expectedContent); + + const result = getCertificateContent(filePath); + + expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8"); + expect(result).toBe(expectedContent); +}); + +test("getCertificateContent should handle data URI with different media types", () => { + const testData = "certificate-data"; + const base64Data = Buffer.from(testData, "utf8").toString("base64"); + const dataUri = `data:application/x-x509-ca-cert;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testData); +}); + +test("getCertificateContent should handle data URI without media type", () => { + const testData = "simple-data"; + const base64Data = Buffer.from(testData, "utf8").toString("base64"); + const dataUri = `data:;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testData); +}); + +test("getCertificateContent should handle data URI without media type or encoding", () => { + const testData = "simple-data"; + const base64Data = Buffer.from(testData, "utf8").toString("base64"); + const dataUri = `data:;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testData); +}); + +test("getCertificateContent should handle relative file paths", () => { + const filePath = "./certs/ca.pem"; + const expectedContent = "certificate from relative path"; + + mockReadFileSync.mockReturnValue(expectedContent); + + const result = getCertificateContent(filePath); + + expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8"); + expect(result).toBe(expectedContent); +}); + +test("getCertificateContent should handle data URI with special characters in URL encoding", () => { + const testCert = "cert with spaces and special chars: !@#$%"; + const encodedData = encodeURIComponent(testCert); + const dataUri = `data:text/plain,${encodedData}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testCert); +}); diff --git a/packages/fetch/vitest.config.ts b/packages/fetch/vitest.config.ts new file mode 100644 index 000000000..50f824200 --- /dev/null +++ b/packages/fetch/vitest.config.ts @@ -0,0 +1,17 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + environment: "node", + timeout: 10000, + globals: true, + }, + resolve: { + alias: { + // Handle .js imports for TypeScript files + "./getAgentOptions.js": "./getAgentOptions.ts", + "./stream.js": "./stream.ts", + "./util.js": "./util.ts", + }, + }, +}); From a995da46d199363bc1d92e41d7d7b1ef27438e9e Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Thu, 5 Jun 2025 17:12:05 -0700 Subject: [PATCH 026/104] removed duplicate function in filesystem --- core/util/filesystem.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 617ad93da..fe882ba90 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -51,10 +51,6 @@ class FileSystemIde implements IDE { return; } - onDidCloseTextDocument(callback: (fileUris: string[]) => void): void { - return; - } - async getIdeSettings(): Promise { return { remoteConfigServerUrl: undefined, From 91a45507c8ea160b1793ae1a7091d64d095f289f Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Thu, 5 Jun 2025 17:18:10 -0700 Subject: [PATCH 027/104] changed test.ts for prettier formatting test --- manual-testing-sandbox/test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/manual-testing-sandbox/test.ts b/manual-testing-sandbox/test.ts index 21aa32018..0f25987c2 100644 --- a/manual-testing-sandbox/test.ts +++ b/manual-testing-sandbox/test.ts @@ -14,7 +14,7 @@ class Calculator { this.result -= number; return this; } - + multiply(number: number): Calculator { this.result *= number; return this; From 45e39ed50925d72ade246c55c69df59f5e96a0dc Mon Sep 17 00:00:00 2001 From: Lucas Shamanic Date: Sat, 7 Jun 2025 02:19:07 +0100 Subject: [PATCH 028/104] bump dependencies and update package versions in package-lock files --- binary/package-lock.json | 5 +++-- core/package-lock.json | 4 ++-- extensions/vscode/package-lock.json | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/binary/package-lock.json b/binary/package-lock.json index abb11ce8e..2d84672f0 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -52,7 +52,7 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.13", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.25", "@modelcontextprotocol/sdk": "^1.12.0", @@ -144,7 +144,8 @@ "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", "ts-jest": "^29.1.1", - "typescript": "^5.6.3" + "typescript": "^5.6.3", + "vitest": "^3.1.4" }, "engines": { "node": ">=20.19.0" diff --git a/core/package-lock.json b/core/package-lock.json index f6eabcae4..20b1d0870 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -113,10 +113,10 @@ "node": ">=20.19.0" } }, - "../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": { + "../../../dallin/documents/code/continuedev/continue/packages/config-yaml": { "extraneous": true }, - "../../../../documents/code/continuedev/continue/packages/config-yaml": { + "../../../documents/code/continuedev/continue/packages/config-yaml": { "version": "1.0.78", "extraneous": true, "license": "Apache-2.0", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 38efaa08a..349212a6a 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.44", + "version": "1.1.45", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.44", + "version": "1.1.45", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", From 77a723cdea62e281e28bb13e85b45f21f2d8585d Mon Sep 17 00:00:00 2001 From: Lucas Shamanic Date: Sat, 7 Jun 2025 04:00:30 +0100 Subject: [PATCH 029/104] Add force autocomplete command and update inline completion handling - Introduced a new command `continue.forceAutocomplete` to trigger autocompletion manually. - Updated `CompletionProvider` to accept a `force` parameter for inline completion. - Enhanced `ContinueCompletionProvider` to handle manual autocompletion triggers. --- core/autocomplete/CompletionProvider.ts | 9 +++++++-- extensions/vscode/package.json | 16 ++++++++++++++++ .../src/autocomplete/completionProvider.ts | 5 +++++ extensions/vscode/src/commands.ts | 5 +++++ 4 files changed, 33 insertions(+), 2 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 8a579c231..749b44e25 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -127,6 +127,7 @@ export class CompletionProvider { public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, + force?: boolean, ): Promise { try { // Create abort signal if not given @@ -146,8 +147,12 @@ export class CompletionProvider { const options = await this._getAutocompleteOptions(llm); // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; + if (!force) { + if ( + await this.debouncer.delayAndShouldDebounce(options.debounceDelay) + ) { + return undefined; + } } if (llm.promptTemplates?.autocomplete) { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 54f93c509..8a265c903 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -225,6 +225,11 @@ "title": "Toggle Autocomplete Enabled", "group": "Continue" }, + { + "command": "continue.forceAutocomplete", + "title": "Continue: Force Autocomplete", + "category": "Continue" + }, { "command": "continue.selectFilesAsContext", "category": "Continue", @@ -411,6 +416,17 @@ "key": "ctrl+k ctrl+a", "when": "!terminalFocus" }, + { + "command": "continue.forceAutocomplete", + "key": "ctrl+alt+space", + "when": "editorTextFocus && !editorHasSelection && !editorReadOnly && !inSnippetMode" + }, + { + "command": "continue.forceAutocomplete", + "key": "cmd+alt+space", + "mac": "cmd+alt+space", + "when": "editorTextFocus && !editorHasSelection && !editorReadOnly && !inSnippetMode" + }, { "command": "continue.applyCodeFromChat", "mac": "alt+a", diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index c15897883..963dcedeb 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -189,6 +189,10 @@ export class ContinueCompletionProvider // Handle commit message input box let manuallyPassPrefix: string | undefined = undefined; + // handle manual autocompletion trigger + const wasManuallyTriggered = + context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke; + const input: AutocompleteInput = { pos, manuallyPassFileContents, @@ -208,6 +212,7 @@ export class ContinueCompletionProvider await this.completionProvider.provideInlineCompletionItems( input, signal, + wasManuallyTriggered, ); if (!outcome || !outcome.completion) { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 3aadfadb9..351c3a33c 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -624,6 +624,11 @@ const getCommandsMap: ( } } }, + "continue.forceAutocomplete": () => { + captureCommandTelemetry("forceAutocomplete"); + vscode.commands.executeCommand("editor.action.inlineSuggest.trigger"); + }, + "continue.openTabAutocompleteConfigMenu": async () => { captureCommandTelemetry("openTabAutocompleteConfigMenu"); From cc507687eb36be5b7fd59eac433a9a908c1ee07e Mon Sep 17 00:00:00 2001 From: shamanic Date: Sat, 7 Jun 2025 04:17:02 +0100 Subject: [PATCH 030/104] fix(vscode): improve forceAutocomplete command reliability Modified the `forceAutocomplete` command to first hide any existing inline suggestion before triggering a new one. This ensures VS Code's suggestion cache is cleared, forcing it to call the provider for a fresh suggestion. --- extensions/vscode/src/commands.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 351c3a33c..2162b1fca 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -624,9 +624,16 @@ const getCommandsMap: ( } } }, - "continue.forceAutocomplete": () => { + "continue.forceAutocomplete": async () => { captureCommandTelemetry("forceAutocomplete"); - vscode.commands.executeCommand("editor.action.inlineSuggest.trigger"); + + // 1. Explicitly hide any existing suggestion. This clears VS Code's cache for the current position. + await vscode.commands.executeCommand("editor.action.inlineSuggest.hide"); + + // 2. Now trigger a new one. VS Code has no cached suggestion, so it's forced to call our provider. + await vscode.commands.executeCommand( + "editor.action.inlineSuggest.trigger", + ); }, "continue.openTabAutocompleteConfigMenu": async () => { From dcffd3529ff8583c3ddb429928af82aeb25c8436 Mon Sep 17 00:00:00 2001 From: shamanic Date: Sat, 7 Jun 2025 05:03:12 +0100 Subject: [PATCH 031/104] test: add force autocomplete test case - Adds `forceCompletion` method to `AutocompleteActions` to trigger autocomplete via command. - Includes new test case to verify forced autocomplete functionality. - Attempted to test these tests to the best of my ability` --- .../vscode/e2e/actions/Autocomplete.actions.ts | 15 ++++++++++++++- extensions/vscode/e2e/tests/Autocomplete.test.ts | 5 +++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/e2e/actions/Autocomplete.actions.ts b/extensions/vscode/e2e/actions/Autocomplete.actions.ts index c35c47a29..9e91355fd 100644 --- a/extensions/vscode/e2e/actions/Autocomplete.actions.ts +++ b/extensions/vscode/e2e/actions/Autocomplete.actions.ts @@ -1,5 +1,5 @@ import { expect } from "chai"; -import { TextEditor } from "vscode-extension-tester"; +import { TextEditor, VSBrowser, Workbench } from "vscode-extension-tester"; import { DEFAULT_TIMEOUT } from "../constants"; import { AutocompleteSelectors } from "../selectors/Autocomplete.selectors"; @@ -29,4 +29,17 @@ export class AutocompleteActions { ); expect(ghostText1).to.equal(messagePair1.llmResponse); } + + public static async forceCompletion(editor: TextEditor): Promise { + await editor.setText("def main():\n "); + await editor.moveCursor(2, 5); + + await new Workbench().executeCommand("Continue: Force Autocomplete"); + + const ghostText = await TestUtils.waitForSuccess(() => + AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver) + ); + + return ghostText; + } } diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index 836c2c60e..7685d52ae 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -1,3 +1,4 @@ +import { expect } from "chai"; import { EditorView, TextEditor } from "vscode-extension-tester"; import { AutocompleteActions } from "../actions/Autocomplete.actions"; @@ -23,4 +24,8 @@ describe("Autocomplete", () => { it("Should display completions", async () => { await AutocompleteActions.testCompletions(editor); }).timeout(DEFAULT_TIMEOUT.XL); + it("Should force a completion using the command", async () => { + const ghostText = await AutocompleteActions.forceCompletion(editor); + expect(ghostText).to.not.be.empty; + }).timeout(DEFAULT_TIMEOUT.XL); }); From 4952c1696491dc6418790313393e8c3bf5705c7c Mon Sep 17 00:00:00 2001 From: shamanic Date: Sat, 7 Jun 2025 05:15:57 +0100 Subject: [PATCH 032/104] docs: add section on forcing autocomplete suggestions Includes details on triggering autocomplete suggestions immediately using the `cmd/ctrl + alt + space` keyboard shortcut. --- docs/docs/autocomplete/how-to-use-it.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/docs/autocomplete/how-to-use-it.md b/docs/docs/autocomplete/how-to-use-it.md index b9b3c19d2..93a1ce507 100644 --- a/docs/docs/autocomplete/how-to-use-it.md +++ b/docs/docs/autocomplete/how-to-use-it.md @@ -23,3 +23,7 @@ Reject a full suggestion with Esc ### Partially accepting a suggestion For more granular control, use cmd/ctrl + → to accept parts of the suggestion word-by-word. + +### Forcing a suggestion + +If you want to trigger a suggestion immediately without waiting, or if you've dismissed a suggestion and want a new one, you can force it by using the keyboard shortcut **cmd/ctrl + alt + space**. From 41bc0e922b333ee404ddb17e5bdcf7c83b7a6ca0 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 9 Jun 2025 10:10:05 -0700 Subject: [PATCH 033/104] feat: onboarding card upgrade tab --- core/control-plane/client.ts | 22 +++- core/core.ts | 6 ++ core/llm/streamChat.ts | 21 ++++ core/protocol/core.ts | 6 ++ core/protocol/ideWebview.ts | 2 +- core/protocol/passThrough.ts | 2 + core/protocol/webview.ts | 1 + extensions/vscode/src/webviewProtocol.ts | 2 +- gui/src/components/Layout.tsx | 32 ++++-- .../OnboardingCard/OnboardingCard.tsx | 29 ++++- .../components/OnboardingCardLanding.tsx | 2 +- .../components/OnboardingCardTabs.tsx | 102 +++++++++++++----- .../components/OnboardingModelsAddOnTab.tsx | 84 +++++++++++++++ .../components/OnboardingProvidersTab.tsx | 2 +- .../OnboardingCard/components/index.ts | 1 + .../dialogs/FreeTrialOverDialog.tsx | 25 ----- .../components/{gui => svg}/ContinueLogo.tsx | 0 gui/src/components/svg/ContinueSignet.tsx | 35 ++++++ gui/src/components/svg/OllamaLogo.tsx | 51 +++++++++ gui/src/pages/config/ScopeSelect.tsx | 2 +- gui/src/pages/gui/Chat.tsx | 2 - 21 files changed, 359 insertions(+), 70 deletions(-) create mode 100644 gui/src/components/OnboardingCard/components/OnboardingModelsAddOnTab.tsx delete mode 100644 gui/src/components/dialogs/FreeTrialOverDialog.tsx rename gui/src/components/{gui => svg}/ContinueLogo.tsx (100%) create mode 100644 gui/src/components/svg/ContinueSignet.tsx create mode 100644 gui/src/components/svg/OllamaLogo.tsx diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 72523aa08..5a045f4b3 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -10,7 +10,7 @@ import { import fetch, { RequestInit, Response } from "node-fetch"; import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; -import { IdeSettings, ModelDescription } from "../index.js"; +import { IdeSettings, IdeType, ModelDescription } from "../index.js"; import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js"; import { getControlPlaneEnv } from "./env.js"; @@ -182,4 +182,24 @@ export class ControlPlaneClient { return null; } } + + public async getModelsAddOnUpgradeUrl( + ide: IdeType, + ): Promise<{ url: string } | null> { + if (!(await this.isSignedIn())) { + return null; + } + + try { + const resp = await this.request( + `ide/get-models-add-on-upgrade-url?ide=${encodeURIComponent(ide)}`, + { + method: "GET", + }, + ); + return (await resp.json()) as { url: string }; + } catch (e) { + return null; + } + } } diff --git a/core/core.ts b/core/core.ts index dfa91e1f7..dc03537a8 100644 --- a/core/core.ts +++ b/core/core.ts @@ -342,6 +342,12 @@ export class Core { return this.configHandler.controlPlaneClient.getFreeTrialStatus(); }); + on("controlPlane/getModelsAddOnUpgradeUrl", async (msg) => { + return this.configHandler.controlPlaneClient.getModelsAddOnUpgradeUrl( + msg.data.ide, + ); + }); + on("mcp/reloadServer", async (msg) => { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); }); diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index c899e437f..e56e321a3 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -135,6 +135,8 @@ export async function* llmStreamChat( true, ); + void checkForFreeTrialExceeded(configHandler, messenger); + if (!next.done) { throw new Error("Will never happen"); } @@ -142,3 +144,22 @@ export async function* llmStreamChat( return next.value; } } + +async function checkForFreeTrialExceeded( + configHandler: ConfigHandler, + messenger: IMessenger, +) { + try { + const freeTrialStatus = + await configHandler.controlPlaneClient.getFreeTrialStatus(); + if ( + freeTrialStatus && + freeTrialStatus.chatCount && + freeTrialStatus.chatCount > freeTrialStatus.chatLimit + ) { + void messenger.request("freeTrialExceeded", undefined); + } + } catch (error) { + console.error("Error checking free trial status:", error); + } +} diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 1358e0a3a..7251a8497 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -21,6 +21,7 @@ import { ExperimentalModelRoles, FileSymbolMap, IdeSettings, + IdeType, LLMFullCompletionOptions, ModelDescription, PromptLog, @@ -40,6 +41,7 @@ import { FreeTrialStatus } from "../control-plane/client"; export enum OnboardingModes { PROVIDERS = "Providers", LOCAL = "Local", + MODELS_ADD_ON = "Models Add-On", } export interface ListHistoryOptions { @@ -199,6 +201,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; "controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null]; + "controlPlane/getModelsAddOnUpgradeUrl": [ + { ide: IdeType }, + { url: string } | null, + ]; isItemTooBig: [{ item: ContextItemWithId }, boolean]; didChangeControlPlaneSessionInfo: [ { sessionInfo: ControlPlaneSessionInfo | undefined }, diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 39ae205a5..074e3837f 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -76,7 +76,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setColors: [{ [key: string]: string }, void]; "jetbrains/editorInsetRefresh": [undefined, void]; "jetbrains/isOSREnabled": [boolean, void]; - addApiKey: [undefined, void]; + setupApiKey: [undefined, void]; setupLocalConfig: [undefined, void]; incrementFtc: [undefined, void]; openOnboardingCard: [undefined, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index d1e1a0e8f..622b4e6f5 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -61,6 +61,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", + "controlPlane/getModelsAddOnUpgradeUrl", "isItemTooBig", "process/markAsBackgrounded", "process/isBackgrounded", @@ -83,4 +84,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "sessionUpdate", "didCloseFiles", "toolCallPartialOutput", + "freeTrialExceeded", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 5ba47e3d4..1a8d40313 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -43,4 +43,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { "jetbrains/setColors": [Record, void]; sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; + freeTrialExceeded: [undefined, void]; }; diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 5778371a3..013e10d03 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -129,7 +129,7 @@ export class VsCodeWebviewProtocol .showInformationMessage(message, "Add API Key", "Use Local Model") .then((selection) => { if (selection === "Add API Key") { - this.request("addApiKey", undefined); + this.request("setupApiKey", undefined); } else if (selection === "Use Local Model") { this.request("setupLocalConfig", undefined); } diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 811297e81..a046d33ef 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -9,7 +9,7 @@ import { LocalStorageProvider } from "../context/LocalStorage"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setCodeToEdit } from "../redux/slices/editState"; -import { setShowDialog } from "../redux/slices/uiSlice"; +import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { enterEdit, exitEdit } from "../redux/thunks/edit"; import { saveCurrentSession } from "../redux/thunks/session"; import { fontSize, isMetaEquivalentKeyPressed } from "../util"; @@ -20,7 +20,11 @@ import TextDialog from "./dialogs"; import Footer from "./Footer"; import { LumpProvider } from "./mainInput/Lump/LumpContext"; import { useMainEditor } from "./mainInput/TipTapEditor"; -import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; +import { + isNewUserOnboarding, + OnboardingCard, + useOnboardingCard, +} from "./OnboardingCard"; import OSRContextMenu from "./OSRContextMenu"; import PostHogPageView from "./PosthogPageView"; @@ -130,17 +134,33 @@ const Layout = () => { ); useWebviewListener( - "openOnboardingCard", + "setupLocalConfig", async () => { - onboardingCard.open(OnboardingModes.PROVIDERS); + onboardingCard.open(OnboardingModes.LOCAL); }, [], ); useWebviewListener( - "setupLocalConfig", + "freeTrialExceeded", async () => { - onboardingCard.open(OnboardingModes.LOCAL); + dispatch(setShowDialog(true)); + onboardingCard.setActiveTab(OnboardingModes.MODELS_ADD_ON); + dispatch( + setDialogMessage( +
+ +
, + ), + ); + }, + [], + ); + + useWebviewListener( + "setupApiKey", + async () => { + onboardingCard.open(OnboardingModes.PROVIDERS); }, [], ); diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index 1c0569c80..855b1f0e5 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -1,11 +1,13 @@ import { OnboardingModes } from "core/protocol/core"; import { useAppSelector } from "../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import Alert from "../gui/Alert"; import { ReusableCard } from "../ReusableCard"; import { OnboardingCardLanding, OnboardingCardTabs, OnboardingLocalTab, + OnboardingModelsAddOnTab, OnboardingProvidersTab, } from "./components"; import { useOnboardingCard } from "./hooks"; @@ -17,9 +19,13 @@ export interface OnboardingCardState { interface OnboardingCardProps { isDialog?: boolean; + showFreeTrialExceededAlert?: boolean; } -export function OnboardingCard({ isDialog }: OnboardingCardProps) { +export function OnboardingCard({ + isDialog, + showFreeTrialExceededAlert, +}: OnboardingCardProps) { const { activeTab, close, setActiveTab } = useOnboardingCard(); const config = useAppSelector((store) => store.config.config); @@ -33,6 +39,8 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { return ; case OnboardingModes.LOCAL: return ; + case OnboardingModes.MODELS_ADD_ON: + return ; default: return ; } @@ -45,7 +53,24 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { onClose={close} testId="onboarding-card" > - + {showFreeTrialExceededAlert && ( +
+ +

+ Free trial completed +

+ + To keep using Continue, select an option below to setup your + models + +
+
+ )} + {renderTabContent()} ); diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx index efef32934..3af954188 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx @@ -5,8 +5,8 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { selectCurrentOrg } from "../../../redux"; import { useAppSelector } from "../../../redux/hooks"; import { hasPassedFTL } from "../../../util/freeTrial"; -import ContinueLogo from "../../gui/ContinueLogo"; import { ToolTip } from "../../gui/Tooltip"; +import ContinueLogo from "../../svg/ContinueLogo"; import { useOnboardingCard } from "../hooks"; export function OnboardingCardLanding({ diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx index 07de1e42e..5c3eb4829 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx @@ -1,26 +1,64 @@ import { KeyIcon } from "@heroicons/react/24/outline"; import { OnboardingModes } from "core/protocol/core"; +import ContinueSignet from "../../svg/ContinueSignet"; +import OllamaLogo from "../../svg/OllamaLogo"; interface OnboardingCardTabsProps { - /** The currently active tab */ activeTab: OnboardingModes; - /** Callback function called when a tab is clicked */ onTabClick: (tabName: OnboardingModes) => void; + showFreeTrialExceededAlert?: boolean; } -const getTabIcon = (tabTitle: OnboardingModes) => { +const renderTabButton = ( + tabTitle: OnboardingModes, + index: number, + activeTab: OnboardingModes, + onTabClick: (tabName: OnboardingModes) => void, +) => { + const baseButtonClass = `text-foreground -mb-px cursor-pointer rounded-t-sm border-none bg-transparent py-2 font-medium hover:brightness-125 focus:outline-none ${index === 0 ? "pl-1.5 pr-3" : "px-3"} ${activeTab === tabTitle ? "brightness-125" : "brightness-75"}`; + if (tabTitle === OnboardingModes.PROVIDERS) { - return ; - } - if (tabTitle === OnboardingModes.LOCAL) { return ( - Ollama + ); } + + if (tabTitle === OnboardingModes.LOCAL) { + return ( + + ); + } + + if (tabTitle === OnboardingModes.MODELS_ADD_ON) { + return ( + + ); + } + return null; }; @@ -30,28 +68,34 @@ const getTabIcon = (tabTitle: OnboardingModes) => { export function OnboardingCardTabs({ activeTab, onTabClick, + showFreeTrialExceededAlert, }: OnboardingCardTabsProps) { + /** + * When users initially install, we only render these tabs after they've + * declined the free trial, so we show the upgrade tab last since they've + * indicated they want don't want to use the Hub. + * + * If `showFreeTrialExceededAlert` is true, they've used the Hub, so show + * upgrade first. + */ + const tabs = showFreeTrialExceededAlert + ? [ + OnboardingModes.MODELS_ADD_ON, + OnboardingModes.PROVIDERS, + OnboardingModes.LOCAL, + ] + : [ + OnboardingModes.PROVIDERS, + OnboardingModes.LOCAL, + OnboardingModes.MODELS_ADD_ON, + ]; return (
- {Object.values(OnboardingModes).map((tabTitle) => { - const isActive = activeTab === tabTitle; - - return ( - - ); - })} + {tabs.map((tabTitle, index) => + renderTabButton(tabTitle, index, activeTab, onTabClick), + )}
@@ -61,7 +105,7 @@ export function OnboardingCardTabs({ value={activeTab} onChange={(e) => onTabClick(e.target.value as OnboardingModes)} > - {Object.values(OnboardingModes).map((tabTitle) => { + {tabs.map((tabTitle) => { return (