From 805e002fc701e7850ab63a89c30f0d8b2d6f341a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 12 Mar 2024 19:40:57 -0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20decouple=20autocomplete=20from?= =?UTF-8?q?=20VS=20Code=20extension?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/completionProvider.ts | 385 ++++++++++++++++++ core/autocomplete/constructPrompt.ts | 4 +- core/autocomplete/slidingWindow.ts | 6 +- core/protocol.ts | 2 + core/util/ranges.ts | 25 ++ .../src/autocomplete/completionProvider.ts | 124 +++--- .../src/autocomplete/getTabCompletion.ts | 262 ------------ extensions/vscode/src/commands.ts | 2 +- extensions/vscode/src/util/ideUtils.ts | 49 ++- gui/src/util/ide.ts | 18 +- 10 files changed, 502 insertions(+), 375 deletions(-) create mode 100644 core/autocomplete/completionProvider.ts create mode 100644 core/util/ranges.ts delete mode 100644 extensions/vscode/src/autocomplete/getTabCompletion.ts diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts new file mode 100644 index 000000000..fb23ebf12 --- /dev/null +++ b/core/autocomplete/completionProvider.ts @@ -0,0 +1,385 @@ +import Handlebars from "handlebars"; +import { v4 as uuidv4 } from "uuid"; +import { IDE, ILLM, Position, TabAutocompleteOptions } from ".."; +import { RangeInFileWithContents } from "../commands/util"; +import { ConfigHandler } from "../config/handler"; +import { streamLines } from "../diff/util"; +import OpenAI from "../llm/llms/OpenAI"; +import { getBasename } from "../util"; +import { logDevData } from "../util/devdata"; +import { Telemetry } from "../util/posthog"; +import { getRangeInString } from "../util/ranges"; +import AutocompleteLruCache from "./cache"; +import { noFirstCharNewline, onlyWhitespaceAfterEndOfLine } from "./charStream"; +import { + constructAutocompletePrompt, + languageForFilepath, +} from "./constructPrompt"; +import { AutocompleteLanguageInfo } from "./languages"; +import { + avoidPathLine, + stopAtLines, + stopAtRepeatingLines, + stopAtSimilarLine, + streamWithNewLines, +} from "./lineStream"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "./parameters"; +import { AutocompleteSnippet } from "./ranking"; +import { getTemplateForModel } from "./templates"; +import { GeneratorReuseManager } from "./util"; + +export interface AutocompleteInput { + filepath: string; + pos: Position; + recentlyEditedFiles: RangeInFileWithContents[]; + recentlyEditedRanges: RangeInFileWithContents[]; + clipboardText: string; +} + +export interface AutocompleteOutcome { + accepted?: boolean; + time: number; + prompt: string; + completion: string; + modelProvider: string; + modelName: string; + completionOptions: any; + cacheHit: boolean; +} + +const autocompleteCache = AutocompleteLruCache.get(); + +function formatExternalSnippet( + filepath: string, + snippet: string, + language: AutocompleteLanguageInfo, +) { + const comment = language.comment; + const lines = [ + comment + " Path: " + getBasename(filepath), + ...snippet + .trim() + .split("\n") + .map((line) => comment + " " + line), + comment, + ]; + return lines.join("\n"); +} + +export async function getTabCompletion( + token: AbortSignal, + options: TabAutocompleteOptions, + llm: ILLM, + ide: IDE, + generatorReuseManager: GeneratorReuseManager, + input: AutocompleteInput, + getDefinitionsFromLsp: ( + filepath: string, + contents: string, + cursorIndex: number, + ide: IDE, + ) => Promise, +): Promise { + const startTime = Date.now(); + + const { + filepath, + pos, + recentlyEditedFiles, + recentlyEditedRanges, + clipboardText, + } = input; + const fileContents = await ide.readFile(filepath); + const fileLines = fileContents.split("\n"); + + // Filter + const lang = languageForFilepath(filepath); + const line = fileLines[pos.line] ?? ""; + for (const endOfLine of lang.endOfLine) { + if (line.endsWith(endOfLine) && pos.character >= line.length) { + return undefined; + } + } + + // Model + if (llm instanceof OpenAI) { + llm.useLegacyCompletionsEndpoint = true; + } + if (!llm) return; + + // Prompt + const fullPrefix = getRangeInString(fileContents, { + start: { line: 0, character: 0 }, + end: pos, + }); + const fullSuffix = getRangeInString(fileContents, { + start: pos, + end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, + }); + const lineBelowCursor = + fileLines[Math.min(pos.line + 1, fileLines.length - 1)]; + + let extrasSnippets = (await Promise.race([ + getDefinitionsFromLsp( + filepath, + fullPrefix + fullSuffix, + fullPrefix.length, + ide, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteSnippet[]; + + const workspaceDirs = await ide.getWorkspaceDirs(); + if (options.onlyMyCode) { + extrasSnippets = extrasSnippets.filter((snippet) => { + return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); + }); + } + + let { prefix, suffix, completeMultiline, snippets } = + await constructAutocompletePrompt( + filepath, + pos.line, + fullPrefix, + fullSuffix, + clipboardText, + lang, + options, + recentlyEditedRanges, + recentlyEditedFiles, + llm.model, + extrasSnippets, + ); + + // Template prompt + const { template, completionOptions } = options.template + ? { template: options.template, completionOptions: {} } + : getTemplateForModel(llm.model); + + let prompt: string; + const filename = getBasename(filepath); + const reponame = getBasename(workspaceDirs[0] ?? "myproject"); + if (typeof template === "string") { + const compiledTemplate = Handlebars.compile(template); + + // Format snippets as comments and prepend to prefix + const formattedSnippets = snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n"); + if (formattedSnippets.length > 0) { + prefix = formattedSnippets + "\n\n" + prefix; + } + + prompt = compiledTemplate({ + prefix, + suffix, + filename, + reponame, + }); + } else { + // Let the template function format snippets + prompt = template(prefix, suffix, filename, reponame, snippets); + } + + // Completion + let completion = ""; + + const cache = await autocompleteCache; + const cachedCompletion = options.useCache + ? await cache.get(prompt) + : undefined; + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + // Try to reuse pending requests if what the user typed matches start of completion + let stop = [ + ...(completionOptions?.stop || []), + "\n\n", + "/src/", + "```", + ...lang.stopWords, + ]; + + const multiline = + options.multilineCompletions !== "never" && + (options.multilineCompletions === "always" || completeMultiline); + + let generator = generatorReuseManager.getGenerator( + prefix, + () => + llm.streamComplete(prompt, { + ...completionOptions, + temperature: 0, + raw: true, + stop, + }), + multiline, + ); + + // LLM + let cancelled = false; + const generatorWithCancellation = async function* () { + for await (const update of generator) { + if (token.aborted) { + cancelled = true; + return undefined; + } + yield update; + } + }; + let chars = generatorWithCancellation(); + const gen2 = onlyWhitespaceAfterEndOfLine( + noFirstCharNewline(chars), + lang.endOfLine, + ); + const lineGenerator = streamWithNewLines( + avoidPathLine( + stopAtRepeatingLines(stopAtLines(streamLines(gen2))), + lang.comment, + ), + ); + const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor); + for await (const update of finalGenerator) { + completion += update; + } + + if (cancelled) { + return undefined; + } + + // Don't return empty + if (completion.trim().length <= 0) { + return undefined; + } + + // Post-processing + completion = completion.trimEnd(); + } + + const time = Date.now() - startTime; + return { + time, + completion, + prompt, + modelProvider: llm.providerName, + modelName: llm.model, + completionOptions, + cacheHit, + }; +} + +export class CompletionProvider { + private static debounceTimeout: NodeJS.Timeout | undefined = undefined; + private static debouncing: boolean = false; + private static lastUUID: string | undefined = undefined; + + constructor( + private readonly configHandler: ConfigHandler, + private readonly ide: IDE, + private readonly getLlm: () => Promise, + private readonly _onError: (e: any) => void, + private readonly getDefinitionsFromLsp: ( + filepath: string, + contents: string, + cursorIndex: number, + ide: IDE, + ) => Promise, + ) { + this.generatorReuseManager = new GeneratorReuseManager( + this.onError.bind(this), + ); + } + + private generatorReuseManager: GeneratorReuseManager; + private autocompleteCache = AutocompleteLruCache.get(); + public errorsShown: Set = new Set(); + + private onError(e: any) { + console.warn("Error generating autocompletion: ", e); + if (!this.errorsShown.has(e.message)) { + this.errorsShown.add(e.message); + this._onError(e); + } + } + + public async provideInlineCompletionItems( + input: AutocompleteInput, + token: AbortSignal, + ): Promise { + // Debounce + const uuid = uuidv4(); + CompletionProvider.lastUUID = uuid; + + const config = await this.configHandler.loadConfig(); + const options = { + ...DEFAULT_AUTOCOMPLETE_OPTS, + ...config.tabAutocompleteOptions, + }; + + if (CompletionProvider.debouncing) { + CompletionProvider.debounceTimeout?.refresh(); + const lastUUID = await new Promise((resolve) => + setTimeout(() => { + resolve(CompletionProvider.lastUUID); + }, options.debounceDelay), + ); + if (uuid !== lastUUID) { + return undefined; + } + } else { + CompletionProvider.debouncing = true; + CompletionProvider.debounceTimeout = setTimeout(async () => { + CompletionProvider.debouncing = false; + }, options.debounceDelay); + } + + // Get completion + const llm = await this.getLlm(); + if (!llm) { + return undefined; + } + const outcome = await getTabCompletion( + token, + options, + llm, + this.ide, + this.generatorReuseManager, + input, + this.getDefinitionsFromLsp, + ); + const completion = outcome?.completion; + + if (!completion) { + return undefined; + } + + // Do some stuff later so as not to block return. Latency matters + setTimeout(async () => { + if (!outcome.cacheHit) { + (await this.autocompleteCache).put(outcome.prompt, completion); + } + }, 100); + + const logRejectionTimeout = setTimeout(() => { + // Wait 10 seconds, then assume it wasn't accepted + outcome.accepted = false; + logDevData("autocomplete", outcome); + Telemetry.capture("autocomplete", { + accepted: outcome.accepted, + modelName: outcome.modelName, + modelProvider: outcome.modelProvider, + time: outcome.time, + cacheHit: outcome.cacheHit, + }); + }, 10_000); + + return outcome; + } +} diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 3e3f00b01..996283e42 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -87,7 +87,7 @@ export async function constructAutocompletePrompt( language: AutocompleteLanguageInfo, options: TabAutocompleteOptions, recentlyEditedRanges: RangeInFileWithContents[], - recentlyEditedDocuments: RangeInFileWithContents[], + recentlyEditedFiles: RangeInFileWithContents[], modelName: string, extraSnippets: AutocompleteSnippet[], ): Promise<{ @@ -123,7 +123,7 @@ export async function constructAutocompletePrompt( ); const slidingWindowMatches = await slidingWindowMatcher( - recentlyEditedDocuments, + recentlyEditedFiles, windowAroundCursor, 3, options.slidingWindowSize, diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/slidingWindow.ts index 253860925..27537b3d9 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/slidingWindow.ts @@ -27,12 +27,12 @@ function* slidingWindow( /** * Match by similarity over sliding windows of recent documents. - * @param recentDocuments + * @param recentFiles * @param prefix * @param suffix */ export async function slidingWindowMatcher( - recentDocuments: RangeInFileWithContents[], + recentFiles: RangeInFileWithContents[], windowAroundCursor: string, topN: number, windowSize: number, @@ -40,7 +40,7 @@ export async function slidingWindowMatcher( // Sorted lowest similarity to highest const topMatches: AutocompleteSnippet[] = []; - for (const { filepath, contents, range } of recentDocuments) { + for (const { filepath, contents, range } of recentFiles) { for (const window of slidingWindow(contents, windowSize)) { const score = jaccardSimilarity(window, windowAroundCursor); diff --git a/core/protocol.ts b/core/protocol.ts index 961b80c3a..a37209532 100644 --- a/core/protocol.ts +++ b/core/protocol.ts @@ -60,6 +60,8 @@ export type Protocol = { { filepath: string; line: number; column: number }, string[], ]; + "autocomplete/cancel": [undefined, void]; + "autocomplete/accept": [{ completionId: string }, void]; "command/run": [ { input: string; diff --git a/core/util/ranges.ts b/core/util/ranges.ts new file mode 100644 index 000000000..25e4c4916 --- /dev/null +++ b/core/util/ranges.ts @@ -0,0 +1,25 @@ +import { Range } from ".."; + +export function getRangeInString(content: string, range: Range): string { + const lines = content.split("\n"); + + if (range.start.line === range.end.line) { + return ( + lines[range.start.line]?.substring( + range.start.character, + range.end.character + 1, + ) ?? "" + ); + } + + const firstLine = + lines[range.start.line]?.substring( + range.start.character, + lines[range.start.line].length, + ) ?? ""; + const middleLines = lines.slice(range.start.line + 1, range.end.line); + const lastLine = + lines[range.end.line]?.substring(0, range.end.character) ?? ""; + + return [firstLine, ...middleLines, lastLine].join("\n"); +} diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 9ce3cd548..f6198b654 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -1,50 +1,46 @@ import { IDE } from "core"; -import AutocompleteLruCache from "core/autocomplete/cache"; -import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters"; -import { GeneratorReuseManager } from "core/autocomplete/util"; +import { + AutocompleteInput, + CompletionProvider, +} from "core/autocomplete/completionProvider"; import { ConfigHandler } from "core/config/handler"; import { logDevData } from "core/util/devdata"; import { Telemetry } from "core/util/posthog"; -import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; -import { getTabCompletion } from "./getTabCompletion"; -import { stopStatusBarLoading } from "./statusBar"; +import { getDefinitionsFromLsp } from "./lsp"; +import { setupStatusBar, stopStatusBarLoading } from "./statusBar"; export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { - private static debounceTimeout: NodeJS.Timeout | undefined = undefined; - private static debouncing: boolean = false; - private static lastUUID: string | undefined = undefined; - private onError(e: any) { - console.warn("Error generating autocompletion: ", e); - if (!this.errorsShown.has(e.message)) { - this.errorsShown.add(e.message); - vscode.window.showErrorMessage(e.message, "Documentation").then((val) => { - if (val === "Documentation") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete", - ), - ); - } - }); - } + vscode.window.showErrorMessage(e.message, "Documentation").then((val) => { + if (val === "Documentation") { + vscode.env.openExternal( + vscode.Uri.parse( + "https://continue.dev/docs/walkthroughs/tab-autocomplete", + ), + ); + } + }); } - private generatorReuseManager = new GeneratorReuseManager( - this.onError.bind(this), - ); - private autocompleteCache = AutocompleteLruCache.get(); - public errorsShown: Set = new Set(); + private completionProvider: CompletionProvider; constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, private readonly tabAutocompleteModel: TabAutocompleteModel, - ) {} + ) { + this.completionProvider = new CompletionProvider( + this.configHandler, + this.ide, + this.tabAutocompleteModel.get, + this.onError.bind(this), + getDefinitionsFromLsp, + ); + } public async provideInlineCompletionItems( document: vscode.TextDocument, @@ -53,33 +49,6 @@ export class ContinueCompletionProvider token: vscode.CancellationToken, //@ts-ignore ): ProviderResult { - // Debounce - const uuid = uuidv4(); - ContinueCompletionProvider.lastUUID = uuid; - - const config = await this.configHandler.loadConfig(); - const options = { - ...DEFAULT_AUTOCOMPLETE_OPTS, - ...config.tabAutocompleteOptions, - }; - - if (ContinueCompletionProvider.debouncing) { - ContinueCompletionProvider.debounceTimeout?.refresh(); - const lastUUID = await new Promise((resolve) => - setTimeout(() => { - resolve(ContinueCompletionProvider.lastUUID); - }, options.debounceDelay), - ); - if (uuid !== lastUUID) { - return []; - } - } else { - ContinueCompletionProvider.debouncing = true; - ContinueCompletionProvider.debounceTimeout = setTimeout(async () => { - ContinueCompletionProvider.debouncing = false; - }, options.debounceDelay); - } - const enableTabAutocomplete = vscode.workspace .getConfiguration("continue") @@ -89,28 +58,28 @@ export class ContinueCompletionProvider } try { - const outcome = await getTabCompletion( - document, - position, - token, - options, - this.tabAutocompleteModel, - this.ide, - this.generatorReuseManager, - ); - const completion = outcome?.completion; + const abortController = new AbortController(); + const signal = abortController.signal; + token.onCancellationRequested(() => abortController.abort()); + const input: AutocompleteInput = { + filepath: document.uri.fsPath, + pos: { line: position.line, character: position.character }, + recentlyEditedFiles: [], + recentlyEditedRanges: [], + clipboardText: await vscode.env.clipboard.readText(), + }; - if (!completion) { + setupStatusBar(true, true); + const outcome = + await this.completionProvider.provideInlineCompletionItems( + input, + signal, + ); + + if (!outcome || !outcome.completion) { return []; } - // Do some stuff later so as not to block return. Latency matters - setTimeout(async () => { - if (!outcome.cacheHit) { - (await this.autocompleteCache).put(outcome.prompt, completion); - } - }, 100); - const logRejectionTimeout = setTimeout(() => { // Wait 10 seconds, then assume it wasn't accepted outcome.accepted = false; @@ -126,8 +95,11 @@ export class ContinueCompletionProvider return [ new vscode.InlineCompletionItem( - completion, - new vscode.Range(position, position.translate(0, completion.length)), + outcome.completion, + new vscode.Range( + position, + position.translate(0, outcome.completion.length), + ), { title: "Log Autocomplete Outcome", command: "continue.logAutocompleteOutcome", diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts deleted file mode 100644 index e947cbc5e..000000000 --- a/extensions/vscode/src/autocomplete/getTabCompletion.ts +++ /dev/null @@ -1,262 +0,0 @@ -import { IDE, TabAutocompleteOptions } from "core"; -import { AutocompleteLruCache } from "core/autocomplete/cache"; -import { - noFirstCharNewline, - onlyWhitespaceAfterEndOfLine, -} from "core/autocomplete/charStream"; -import { - constructAutocompletePrompt, - languageForFilepath, -} from "core/autocomplete/constructPrompt"; -import { AutocompleteLanguageInfo } from "core/autocomplete/languages"; -import { - avoidPathLine, - stopAtLines, - stopAtRepeatingLines, - stopAtSimilarLine, - streamWithNewLines, -} from "core/autocomplete/lineStream"; -import { AutocompleteSnippet } from "core/autocomplete/ranking"; -import { getTemplateForModel } from "core/autocomplete/templates"; -import { GeneratorReuseManager } from "core/autocomplete/util"; -import { streamLines } from "core/diff/util"; -import OpenAI from "core/llm/llms/OpenAI"; -import { getBasename } from "core/util"; -import Handlebars from "handlebars"; -import * as vscode from "vscode"; -import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; -import { getDefinitionsFromLsp } from "./lsp"; -import { RecentlyEditedTracker } from "./recentlyEdited"; -import { setupStatusBar, stopStatusBarLoading } from "./statusBar"; - -export interface AutocompleteOutcome { - accepted?: boolean; - time: number; - prompt: string; - completion: string; - modelProvider: string; - modelName: string; - completionOptions: any; - cacheHit: boolean; -} - -const autocompleteCache = AutocompleteLruCache.get(); -const recentlyEditedTracker = new RecentlyEditedTracker(); - -function formatExternalSnippet( - filepath: string, - snippet: string, - language: AutocompleteLanguageInfo, -) { - const comment = language.comment; - const lines = [ - comment + " Path: " + getBasename(filepath), - ...snippet - .trim() - .split("\n") - .map((line) => comment + " " + line), - comment, - ]; - return lines.join("\n"); -} - -export async function getTabCompletion( - document: vscode.TextDocument, - pos: vscode.Position, - token: vscode.CancellationToken, - options: TabAutocompleteOptions, - tabAutocompleteModel: TabAutocompleteModel, - ide: IDE, - generatorReuseManager: GeneratorReuseManager, -): Promise { - const startTime = Date.now(); - - // Filter - const lang = languageForFilepath(document.fileName); - const line = document.lineAt(pos).text; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= line.length) { - return undefined; - } - } - - // Model - const llm = await tabAutocompleteModel.get(); - if (llm instanceof OpenAI) { - llm.useLegacyCompletionsEndpoint = true; - } - if (!llm) return; - - // Prompt - const fullPrefix = document.getText( - new vscode.Range(new vscode.Position(0, 0), pos), - ); - const fullSuffix = document.getText( - new vscode.Range( - pos, - new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER), - ), - ); - const lineBelowCursor = document.lineAt( - Math.min(pos.line + 1, document.lineCount - 1), - ).text; - const clipboardText = await vscode.env.clipboard.readText(); - - let extrasSnippets = (await Promise.race([ - getDefinitionsFromLsp( - document.uri.fsPath, - fullPrefix + fullSuffix, - fullPrefix.length, - ide, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]; - - const workspaceDirs = await ide.getWorkspaceDirs(); - if (options.onlyMyCode) { - extrasSnippets = extrasSnippets.filter((snippet) => { - return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); - }); - } - - let { prefix, suffix, completeMultiline, snippets } = - await constructAutocompletePrompt( - document.uri.toString(), - pos.line, - fullPrefix, - fullSuffix, - clipboardText, - lang, - options, - await recentlyEditedTracker.getRecentlyEditedRanges(), - await recentlyEditedTracker.getRecentlyEditedDocuments(), - llm.model, - extrasSnippets, - ); - - // Template prompt - const { template, completionOptions } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); - - let prompt: string; - const filename = getBasename(document.uri.fsPath); - const reponame = getBasename(workspaceDirs[0] ?? "myproject"); - if (typeof template === "string") { - const compiledTemplate = Handlebars.compile(template); - - // Format snippets as comments and prepend to prefix - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - prefix = formattedSnippets + "\n\n" + prefix; - } - - prompt = compiledTemplate({ - prefix, - suffix, - filename, - reponame, - }); - } else { - // Let the template function format snippets - prompt = template(prefix, suffix, filename, reponame, snippets); - } - - // Completion - let completion = ""; - - const cache = await autocompleteCache; - const cachedCompletion = options.useCache - ? await cache.get(prompt) - : undefined; - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; - } else { - setupStatusBar(true, true); - - // Try to reuse pending requests if what the user typed matches start of completion - let stop = [ - ...(completionOptions?.stop || []), - "\n\n", - "/src/", - "```", - ...lang.stopWords, - ]; - - const multiline = - options.multilineCompletions !== "never" && - (options.multilineCompletions === "always" || completeMultiline); - - let generator = generatorReuseManager.getGenerator( - prefix, - () => - llm.streamComplete(prompt, { - ...completionOptions, - temperature: 0, - raw: true, - stop, - }), - multiline, - ); - - // LLM - let cancelled = false; - const generatorWithCancellation = async function* () { - for await (const update of generator) { - if (token.isCancellationRequested) { - stopStatusBarLoading(); - cancelled = true; - return undefined; - } - yield update; - } - }; - let chars = generatorWithCancellation(); - const gen2 = onlyWhitespaceAfterEndOfLine( - noFirstCharNewline(chars), - lang.endOfLine, - ); - const lineGenerator = streamWithNewLines( - avoidPathLine( - stopAtRepeatingLines(stopAtLines(streamLines(gen2))), - lang.comment, - ), - ); - const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor); - for await (const update of finalGenerator) { - completion += update; - } - - if (cancelled) { - return undefined; - } - - // Don't return empty - if (completion.trim().length <= 0) { - return undefined; - } - - // Post-processing - completion = completion.trimEnd(); - } - - const time = Date.now() - startTime; - return { - time, - completion, - prompt, - modelProvider: llm.providerName, - modelName: llm.model, - completionOptions, - cacheHit, - }; -} diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 3e3fe41bc..5d38dd9d6 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -4,10 +4,10 @@ import * as path from "path"; import * as vscode from "vscode"; import { IDE } from "core"; +import { AutocompleteOutcome } from "core/autocomplete/completionProvider"; import { ConfigHandler } from "core/config/handler"; import { logDevData } from "core/util/devdata"; import { Telemetry } from "core/util/posthog"; -import { AutocompleteOutcome } from "./autocomplete/getTabCompletion"; import { ContinueGUIWebviewViewProvider } from "./debugPanel"; import { DiffManager } from "./diff/horizontal"; import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 86fd41aea..cf47c7e19 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -287,32 +287,37 @@ export class VsCodeIdeUtils { } } + private static MAX_BYTES = 100000; + async readFile(filepath: string): Promise { - filepath = this.getAbsolutePath(filepath); + try { + filepath = this.getAbsolutePath(filepath); + const uri = uriFromFilePath(filepath); - const MAX_BYTES = 100000; - let contents: string | undefined; - if (typeof contents === "undefined") { - try { - const fileStats = await vscode.workspace.fs.stat( - uriFromFilePath(filepath), - ); - if (fileStats.size > 10 * MAX_BYTES) { - return ""; - } - - const bytes = await vscode.workspace.fs.readFile( - uriFromFilePath(filepath), - ); - - // Truncate the buffer to the first MAX_BYTES - const truncatedBytes = bytes.slice(0, MAX_BYTES); - contents = new TextDecoder().decode(truncatedBytes); - } catch { - contents = ""; + // Check first whether it's an open document + const openTextDocument = vscode.workspace.textDocuments.find( + (doc) => doc.uri.toString() === uri.toString(), + ); + if (openTextDocument !== undefined) { + return openTextDocument.getText(); } + + const fileStats = await vscode.workspace.fs.stat( + uriFromFilePath(filepath), + ); + if (fileStats.size > 10 * VsCodeIdeUtils.MAX_BYTES) { + return ""; + } + + const bytes = await vscode.workspace.fs.readFile(uri); + + // Truncate the buffer to the first MAX_BYTES + const truncatedBytes = bytes.slice(0, VsCodeIdeUtils.MAX_BYTES); + const contents = new TextDecoder().decode(truncatedBytes); + return contents; + } catch { + return ""; } - return contents; } async readRangeInFile( diff --git a/gui/src/util/ide.ts b/gui/src/util/ide.ts index e445f6db8..912a3dfbf 100644 --- a/gui/src/util/ide.ts +++ b/gui/src/util/ide.ts @@ -19,7 +19,7 @@ function _postToIde(messageType: string, data: any, messageId?: string) { console.log( "Unable to send message: postIntellijMessage is undefined. ", messageType, - data + data, ); throw new Error("postIntellijMessage is undefined"); } @@ -30,7 +30,7 @@ function _postToIde(messageType: string, data: any, messageId?: string) { console.log( "Unable to send message: vscode is undefined. ", messageType, - data + data, ); return; } @@ -47,7 +47,7 @@ export function postToIde( messageType: T, data: WebviewProtocol[T][0], messageId?: string, - attempt: number = 0 + attempt: number = 0, ) { try { _postToIde(messageType, data, messageId); @@ -56,7 +56,7 @@ export function postToIde( console.log(`Attempt ${attempt} failed. Retrying...`); setTimeout( () => postToIde(messageType, data, messageId, attempt + 1), - Math.pow(2, attempt) * 1000 + Math.pow(2, attempt) * 1000, ); } else { console.error("Max attempts reached. Message could not be sent.", error); @@ -67,7 +67,7 @@ export function postToIde( export function respondToIde( messageType: T, data: ReverseWebviewProtocol[T][1], - messageId: string + messageId: string, ) { _postToIde(messageType, data, messageId); } @@ -82,7 +82,7 @@ function safeParseResponse(data: any) { export async function ideRequest( messageType: T, - data: WebviewProtocol[T][0] + data: WebviewProtocol[T][0], ): Promise { const messageId = uuidv4(); @@ -102,7 +102,7 @@ export async function ideRequest( export async function* ideStreamRequest( messageType: T, data: WebviewProtocol[T][0], - cancelToken?: AbortSignal + cancelToken?: AbortSignal, ): WebviewProtocol[T][1] { const messageId = uuidv4(); @@ -153,7 +153,7 @@ export async function* llmStreamChat( modelTitle: string, cancelToken: AbortSignal | undefined, messages: ChatMessage[], - options: LLMFullCompletionOptions = {} + options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const gen = ideStreamRequest( "llm/streamChat", @@ -162,7 +162,7 @@ export async function* llmStreamChat( title: modelTitle, completionOptions: options, }, - cancelToken + cancelToken, ); let next = await gen.next();