From 0dafb5240f10daa510f7a0ebf8cdda2e1e950c5b Mon Sep 17 00:00:00 2001 From: lidongming Date: Wed, 20 Nov 2024 14:24:01 +0800 Subject: [PATCH 1/8] Fix deduplication bug in autocomplete. --- .../autocomplete/AutocompleteService.kt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index cddf5769d..777df65ce 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -129,6 +129,13 @@ class AutocompleteService(private val project: Project) { document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength)) } + // Determine the index of a newline character within the text following the cursor. + val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n') + // If a newline character is found and the current line is not empty, truncate the text at that point. + if (newlineIndex > 0) { + textAfterCursor = textAfterCursor.substring(0, newlineIndex) + } + val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor) if (indexOfTextAfterCursorInCompletion > 0) { return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1) From 9dd6284b8e4b1dc09b704bc00d5231af9569b6bc Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 20 Nov 2024 11:22:24 -0800 Subject: [PATCH 2/8] feat: use clipboard content --- core/autocomplete/CompletionProvider.ts | 21 ++++-- core/autocomplete/templating/index.ts | 72 +++++++++++++++---- core/autocomplete/util/HelperVars.ts | 4 ++ core/config/types.ts | 1 + core/index.d.ts | 4 +- core/util/filesystem.ts | 4 ++ core/util/messageIde.ts | 9 ++- core/util/parameters.ts | 1 + extensions/vscode/src/VsCodeIde.ts | 9 +++ extensions/vscode/src/commands.ts | 36 +++++++++- .../vscode/src/extension/VsCodeExtension.ts | 10 ++- packages/config-types/src/index.ts | 1 + 12 files changed, 148 insertions(+), 24 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 3cc1ce65c..f3f5e7791 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -29,7 +29,7 @@ const autocompleteCache = AutocompleteLruCache.get(); const ERRORS_TO_IGNORE = [ // From Ollama "unexpected server status", - "operation was aborted" + "operation was aborted", ]; export type GetLspDefinitionsFunction = ( @@ -176,16 +176,25 @@ export class CompletionProvider { // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); + // debugger; - const [snippets, diff, workspaceDirs] = await Promise.all([ - aggregateSnippets(helper, extraSnippets, this.contextRetrievalService), - this.ide.getDiff(true), - this.ide.getWorkspaceDirs(), - ]); + const [snippets, diff, clipboardContent, workspaceDirs] = + await Promise.all([ + aggregateSnippets( + helper, + extraSnippets, + this.contextRetrievalService, + ), + "", + this.ide.getClipboardContent(), + this.ide.getWorkspaceDirs(), + ]); + // debugger; const { prompt, prefix, suffix, completionOptions } = renderPrompt({ snippets, diff, + clipboardContent, workspaceDirs, helper, }); diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index f847e3b2a..6f95923d1 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -13,21 +13,24 @@ import { import { getStopTokens } from "./getStopTokens"; import { countTokens } from "../../llm/countTokens"; +const addCommentMarks = (text: string, language: AutocompleteLanguageInfo) => { + const comment = language.singleLineComment; + const lines = [ + ...text + .trim() + .split("\n") + .map((line) => `${comment} ${line}`), + ]; + return lines.join("\n"); +}; + export function formatExternalSnippet( filepath: string, snippet: string, language: AutocompleteLanguageInfo, ) { - const comment = language.singleLineComment; - const lines = [ - `${comment} Path: ${getBasename(filepath)}`, - ...snippet - .trim() - .split("\n") - .map((line) => `${comment} ${line}`), - comment, - ]; - return lines.join("\n"); + const filePathString = `Path: ${getBasename(filepath)}\n`; + return addCommentMarks(`${filePathString}${snippet}`, language); } function getContextComments( @@ -35,14 +38,21 @@ function getContextComments( lang: AutocompleteLanguageInfo, filepath: string, ) { + if (snippets.length === 0) { + return ""; + } + + const headerSnipper = `\n\n${lang.singleLineComment} Related code:\n`; const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`; const formattedSnippets = + headerSnipper + snippets .map((snippet) => formatExternalSnippet(snippet.filepath, snippet.contents, lang), ) - .join("\n") + fileNameSnippet; + .join("\n") + + fileNameSnippet; return formattedSnippets; } @@ -90,16 +100,51 @@ const formatDiff = (helper: HelperVars, diff?: string) => { return `${diff}\n\n`; }; +const MAX_CLIPBOARD_AGE = 5 * 60 * 1000; + +const formatClipboardContent = ( + helper: HelperVars, + { text, copiedAt }: { text: string; copiedAt: string }, +) => { + const currDate = new Date(); + + const isTooOld = + currDate.getTime() - new Date(copiedAt).getTime() > MAX_CLIPBOARD_AGE; + + if (isTooOld) { + return ""; + } + + const tokenCount = countTokens(text, helper.modelName); + const isTooLong = tokenCount > helper.maxClipboardTokens; + + if (isTooLong) { + return ""; + } + + return ( + addCommentMarks( + `Recently copied by user:${text.includes("\n") ? "\n" : ""} ${text}`, + helper.lang, + ) + "\n" + ); +}; + export function renderPrompt({ snippets, workspaceDirs, helper, diff, + clipboardContent, }: { snippets: AutocompleteSnippet[]; workspaceDirs: string[]; helper: HelperVars; diff?: string; + clipboardContent: { + text: string; + copiedAt: string; + }; }): { prompt: string; prefix: string; @@ -132,8 +177,11 @@ export function renderPrompt({ helper.filepath, ); const formattedDiff = formatDiff(helper, diff); + const formattedClipboard = formatClipboardContent(helper, clipboardContent); - prefix = `${formattedDiff}${contextComments}${prefix}`; + prefix = [formattedClipboard, formattedDiff, contextComments, prefix].join( + "", + ); } const prompt = diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index 190e9b8ec..c5429fe81 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -122,6 +122,10 @@ export class HelperVars { return this.options.maxPromptTokens * this.options.maxDiffPercentage; } + get maxClipboardTokens() { + return this.options.maxPromptTokens * this.options.maxClipboardPercentage; + } + get prunedCaretWindow() { return this.prunedPrefix + this.prunedSuffix; } diff --git a/core/config/types.ts b/core/config/types.ts index 370689dde..f397b1ed7 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -837,6 +837,7 @@ declare global { slidingWindowSize: number; maxSnippetPercentage: number; maxDiffPercentage: number; + maxClipboardPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/index.d.ts b/core/index.d.ts index ce2e59449..4d50e6e62 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -106,7 +106,7 @@ export interface ILLM extends LLMOptions { complete( prompt: string, signal: AbortSignal, - options?: LLMFullCompletionOptions + options?: LLMFullCompletionOptions, ): Promise; streamComplete( @@ -508,6 +508,7 @@ export interface IDE { getIdeInfo(): Promise; getIdeSettings(): Promise; getDiff(includeUnstaged: boolean): Promise; + getClipboardContent(): Promise<{ text: string; copiedAt: string }>; isTelemetryEnabled(): Promise; getUniqueId(): Promise; getTerminalContents(): Promise; @@ -979,6 +980,7 @@ export interface TabAutocompleteOptions { slidingWindowSize: number; maxSnippetPercentage: number; maxDiffPercentage: number; + maxClipboardPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 42900edb5..23b44eab0 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -129,6 +129,10 @@ class FileSystemIde implements IDE { return Promise.resolve(""); } + getClipboardContent(): Promise<{ text: string; copiedAt: string }> { + return Promise.resolve({ text: "", copiedAt: new Date().toISOString() }); + } + getTerminalContents(): Promise { return Promise.resolve(""); } diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index b157a1078..49d3378b3 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -28,7 +28,7 @@ export class MessageIde implements IDE { messageType: T, callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1], ) => void, - ) { } + ) {} pathSep(): Promise { return this.request("pathSep", undefined); @@ -113,6 +113,13 @@ export class MessageIde implements IDE { return await this.request("getDiff", { includeUnstaged }); } + async getClipboardContent(): Promise<{ text: string; copiedAt: string }> { + return { + text: "", + copiedAt: new Date().toISOString(), + }; + } + async getTerminalContents() { return await this.request("getTerminalContents", undefined); } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 269f3489e..20b96ac47 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -13,6 +13,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { slidingWindowSize: 500, maxSnippetPercentage: 0.5, maxDiffPercentage: 0.5, + maxClipboardPercentage: 0.5, // yes the percentages do not add up useCache: true, onlyMyCode: true, useOtherFiles: true, diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 217f33e6d..1faace46d 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -36,6 +36,7 @@ import type { RangeInFile, Thread, } from "core"; +import { text } from "stream/consumers"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; @@ -43,6 +44,7 @@ class VsCodeIde implements IDE { constructor( private readonly diffManager: DiffManager, private readonly vscodeWebviewProtocolPromise: Promise, + private readonly context: vscode.ExtensionContext, ) { this.ideUtils = new VsCodeIdeUtils(); } @@ -314,6 +316,13 @@ class VsCodeIde implements IDE { return await this.ideUtils.getDiff(includeUnstaged); } + async getClipboardContent() { + return this.context.workspaceState.get("continue.copyBuffer", { + text: "", + copiedAt: new Date("1900-01-01").toISOString(), + }); + } + async getTerminalContents(): Promise { return await this.ideUtils.getTerminalContents(1); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 6847238e3..ac66d0fc4 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -64,6 +64,7 @@ function addCodeToContextFromRange( range: vscode.Range, webviewProtocol: VsCodeWebviewProtocol, prompt?: string, + store: ) { const document = vscode.window.activeTextEditor?.document; @@ -204,7 +205,7 @@ function hideGUI() { } // Copy everything over from extension.ts -const commandsMap: ( +const getCommandsMap: ( ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, @@ -884,6 +885,35 @@ const commandsMap: ( }; }; +const registerCopyBufferSpy = (context: vscode.ExtensionContext) => { + const typeDisposable = vscode.commands.registerCommand( + "editor.action.clipboardCopyAction", + async (arg) => doCopy(typeDisposable), + ); + + async function doCopy(typeDisposable: any) { + typeDisposable.dispose(); // must dispose to avoid endless loops + + await vscode.commands.executeCommand("editor.action.clipboardCopyAction"); + + const clipboardText = await vscode.env.clipboard.readText(); + + await context.workspaceState.update("continue.copyBuffer", { + text: clipboardText, + copiedAt: new Date().toISOString(), + }); + + // re-register to continue intercepting copy commands + typeDisposable = vscode.commands.registerCommand( + "editor.action.clipboardCopyAction", + async () => doCopy(typeDisposable), + ); + context.subscriptions.push(typeDisposable); + } + + context.subscriptions.push(typeDisposable); +}; + export function registerAllCommands( context: vscode.ExtensionContext, ide: VsCodeIde, @@ -898,8 +928,10 @@ export function registerAllCommands( core: Core, editDecorationManager: EditDecorationManager, ) { + registerCopyBufferSpy(context); + for (const [command, callback] of Object.entries( - commandsMap( + getCommandsMap( ide, extensionContext, sidebar, diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 1eb619aa8..1fa8bc6b5 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -73,7 +73,11 @@ export class VsCodeExtension { }, ); this.diffManager = new DiffManager(context); - this.ide = new VsCodeIde(this.diffManager, this.webviewProtocolPromise); + this.ide = new VsCodeIde( + this.diffManager, + this.webviewProtocolPromise, + context, + ); this.extensionContext = context; this.windowId = uuidv4(); @@ -329,7 +333,9 @@ export class VsCodeExtension { // To make sure continue-proxy models and anything else requiring it get updated access token this.configHandler.reloadConfig(); }); - void this.core.invoke("didChangeControlPlaneSessionInfo", { sessionInfo }); + void this.core.invoke("didChangeControlPlaneSessionInfo", { + sessionInfo, + }); } }); diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index a4ba53b8e..876115d11 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -143,6 +143,7 @@ export const tabAutocompleteOptionsSchema = z.object({ slidingWindowSize: z.number(), maxSnippetPercentage: z.number(), maxDiffPercentage: z.number(), + maxClipboardPercentage: z.number(), useCache: z.boolean(), onlyMyCode: z.boolean(), useOtherFiles: z.boolean(), From 9431131f1cbbc5fe742c033a8baf970241c63378 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 20 Nov 2024 16:54:12 -0800 Subject: [PATCH 3/8] fix: getting diff --- core/autocomplete/CompletionProvider.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index f3f5e7791..caa9bd089 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -185,7 +185,7 @@ export class CompletionProvider { extraSnippets, this.contextRetrievalService, ), - "", + this.ide.getDiff(true), this.ide.getClipboardContent(), this.ide.getWorkspaceDirs(), ]); From 580a3c72b58ac72ed7b0526e1fa4e94dcbf33a91 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 20 Nov 2024 17:00:04 -0800 Subject: [PATCH 4/8] chore: clean up --- core/autocomplete/CompletionProvider.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index caa9bd089..b2cfbd9d9 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -176,7 +176,6 @@ export class CompletionProvider { // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - // debugger; const [snippets, diff, clipboardContent, workspaceDirs] = await Promise.all([ @@ -189,7 +188,6 @@ export class CompletionProvider { this.ide.getClipboardContent(), this.ide.getWorkspaceDirs(), ]); - // debugger; const { prompt, prefix, suffix, completionOptions } = renderPrompt({ snippets, From 7dd2c22632d50726271655d5c5d027a8219e6862 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 20 Nov 2024 18:14:29 -0800 Subject: [PATCH 5/8] fix: remove unused argument --- extensions/vscode/src/commands.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index ac66d0fc4..a1c46126e 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -64,7 +64,6 @@ function addCodeToContextFromRange( range: vscode.Range, webviewProtocol: VsCodeWebviewProtocol, prompt?: string, - store: ) { const document = vscode.window.activeTextEditor?.document; From 452b2422d18c05dd28dbfa6fd127f4c3e0b0223c Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 20 Nov 2024 18:21:39 -0800 Subject: [PATCH 6/8] fix: missing arguments --- .../generation/ListenableGenerator.test.ts | 36 +++++++++++++++---- core/test/llm.test.ts | 14 +++++--- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/core/autocomplete/generation/ListenableGenerator.test.ts b/core/autocomplete/generation/ListenableGenerator.test.ts index 69797959e..9dc6cc893 100644 --- a/core/autocomplete/generation/ListenableGenerator.test.ts +++ b/core/autocomplete/generation/ListenableGenerator.test.ts @@ -17,7 +17,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const result: number[] = []; for await (const value of lg.tee()) { @@ -33,7 +37,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const listener = jest.fn(); @@ -57,7 +65,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values, 10); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const initialListener = jest.fn(); @@ -87,7 +99,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values, 10); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const result: number[] = []; const teeIterator = lg.tee(); @@ -116,7 +132,11 @@ describe("ListenableGenerator", () => { const source = errorGenerator(); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const result: number[] = []; for await (const value of lg.tee()) { @@ -133,7 +153,11 @@ describe("ListenableGenerator", () => { const source = asyncGenerator(values); const onError = jest.fn(); - const lg = new ListenableGenerator(source, onError); + const lg = new ListenableGenerator( + source, + onError, + new AbortController(), + ); const listener = jest.fn(); lg.listen(listener); diff --git a/core/test/llm.test.ts b/core/test/llm.test.ts index 2cb81da72..cf42e128a 100644 --- a/core/test/llm.test.ts +++ b/core/test/llm.test.ts @@ -26,9 +26,10 @@ function testLLM(llm: BaseLLM) { describe(llm.providerName, () => { test("Stream Chat works", async () => { let total = ""; - for await (const chunk of llm.streamChat([ - { role: "user", content: "Hi" }, - ])) { + for await (const chunk of llm.streamChat( + [{ role: "user", content: "Hi" }], + new AbortController().signal, + )) { total += chunk.content; } @@ -38,7 +39,10 @@ function testLLM(llm: BaseLLM) { test("Stream Complete works", async () => { let total = ""; - for await (const chunk of llm.streamComplete("Hi")) { + for await (const chunk of llm.streamComplete( + "Hi", + new AbortController().signal, + )) { total += chunk; } @@ -47,7 +51,7 @@ function testLLM(llm: BaseLLM) { }); test("Complete works", async () => { - const completion = await llm.complete("Hi"); + const completion = await llm.complete("Hi", new AbortController().signal); expect(completion.length).toBeGreaterThan(0); return; From c6942998c36b967842b80ecea86abe2eb6bc9280 Mon Sep 17 00:00:00 2001 From: Big Boss Date: Wed, 20 Nov 2024 23:26:53 -0600 Subject: [PATCH 7/8] fix getTheme to respect preferred mode previously the getTheme function would only inspect the workbench.colorTheme. This would not work for users who use window.autoDetectColorScheme. Now, we inspect this value before deciding which color theme to use. --- .../src/ContinueGUIWebviewViewProvider.ts | 12 +++- extensions/vscode/src/util/getTheme.ts | 55 +++++++++++++++++-- 2 files changed, 61 insertions(+), 6 deletions(-) diff --git a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts index 8c8c399a7..610d262fc 100644 --- a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts +++ b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts @@ -168,7 +168,15 @@ export class ContinueGUIWebviewViewProvider const currentTheme = getTheme(); vscode.workspace.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("workbench.colorTheme")) { + if ( + e.affectsConfiguration("workbench.colorTheme") || + e.affectsConfiguration("window.autoDetectColorScheme") || + e.affectsConfiguration("window.autoDetectHighContrast") || + e.affectsConfiguration("workbench.preferredDarkColorTheme") || + e.affectsConfiguration("workbench.preferredLightColorTheme") || + e.affectsConfiguration("workbench.preferredHighContrastColorTheme") || + e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme") + ) { // Send new theme to GUI to update embedded Monaco themes this.webviewProtocol?.request("setTheme", { theme: getTheme() }); } @@ -188,7 +196,7 @@ export class ContinueGUIWebviewViewProvider
- + ${ inDevelopmentMode ? `