From 50dafd6c2e5e7bb2a6ce047b1c16efbcf250221b Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 23 Feb 2024 07:30:36 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20organize=20vscode=20autocomplete?= =?UTF-8?q?=20a=20bit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/util.ts | 126 +++++ docs/static/schemas/config.json | 4 +- extensions/vscode/continue_rc_schema.json | 8 +- extensions/vscode/src/activation/activate.ts | 6 +- .../src/autocomplete/completionProvider.ts | 109 ++++ .../src/autocomplete/getTabCompletion.ts | 214 ++++++++ .../vscode/src/autocomplete/statusBar.ts | 51 ++ extensions/vscode/src/commands.ts | 2 +- .../src/lang-server/completionProvider.ts | 486 ------------------ extensions/vscode/yarn.lock | 2 +- 10 files changed, 512 insertions(+), 496 deletions(-) create mode 100644 core/autocomplete/util.ts create mode 100644 extensions/vscode/src/autocomplete/completionProvider.ts create mode 100644 extensions/vscode/src/autocomplete/getTabCompletion.ts create mode 100644 extensions/vscode/src/autocomplete/statusBar.ts delete mode 100644 extensions/vscode/src/lang-server/completionProvider.ts diff --git a/core/autocomplete/util.ts b/core/autocomplete/util.ts new file mode 100644 index 000000000..79560c4de --- /dev/null +++ b/core/autocomplete/util.ts @@ -0,0 +1,126 @@ +export class ListenableGenerator { + private _source: AsyncGenerator; + private _buffer: T[] = []; + private _listeners: Set<(value: T) => void> = new Set(); + private _isEnded: boolean = false; + + constructor(source: AsyncGenerator) { + this._source = source; + this._start(); + } + + public cancel() { + this._isEnded = true; + } + + private async _start() { + try { + for await (const value of this._source) { + if (this._isEnded) { + break; + } + this._buffer.push(value); + for (const listener of this._listeners) { + listener(value); + } + } + } finally { + this._isEnded = true; + for (const listener of this._listeners) { + listener(null as any); + } + } + } + + listen(listener: (value: T) => void) { + this._listeners.add(listener); + for (const value of this._buffer) { + listener(value); + } + if (this._isEnded) { + listener(null as any); + } + } + + async *tee(): AsyncGenerator { + try { + for (const value of this._buffer) { + yield value; + } + while (!this._isEnded) { + let resolve: (value: any) => void; + let promise = new Promise((res) => { + resolve = res; + this._listeners.add(resolve!); + }); + const value = await promise; + this._listeners.delete(resolve!); + + yield value; + } + } finally { + // this._listeners.delete(resolve!); + } + } +} + +export class GeneratorReuseManager { + static currentGenerator: ListenableGenerator | undefined; + static pendingGeneratorPrefix: string | undefined; + static pendingCompletion: string = ""; + + private static _createListenableGenerator( + gen: AsyncGenerator, + prefix: string + ) { + GeneratorReuseManager.currentGenerator?.cancel(); + + const listenableGen = new ListenableGenerator(gen); + listenableGen.listen( + (chunk) => (GeneratorReuseManager.pendingCompletion += chunk ?? "") + ); + + GeneratorReuseManager.pendingGeneratorPrefix = prefix; + GeneratorReuseManager.pendingCompletion = ""; + GeneratorReuseManager.currentGenerator = listenableGen; + } + + static async *getGenerator( + prefix: string, + newGenerator: () => AsyncGenerator + ): AsyncGenerator { + // Check if current can be reused + if ( + !( + GeneratorReuseManager.currentGenerator && + GeneratorReuseManager.pendingGeneratorPrefix && + ( + GeneratorReuseManager.pendingGeneratorPrefix + + GeneratorReuseManager.pendingCompletion + ).startsWith(prefix) && + // for e.g. backspace + GeneratorReuseManager.pendingGeneratorPrefix?.length <= prefix?.length + ) + ) { + // Create a wrapper over the current generator to fix the prompt + GeneratorReuseManager._createListenableGenerator(newGenerator(), prefix); + } + + let alreadyTyped = + prefix.slice(GeneratorReuseManager.pendingGeneratorPrefix?.length) || ""; + for await (let chunk of GeneratorReuseManager.currentGenerator!.tee()) { + if (!chunk) { + continue; + } + while (chunk.length && alreadyTyped.length) { + if (chunk[0] === alreadyTyped[0]) { + alreadyTyped = alreadyTyped.slice(1); + chunk = chunk.slice(1); + } else { + break; + } + } + yield chunk; + } + } +} diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index e37574e2b..832dcbc59 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -1436,8 +1436,8 @@ "type": "string", "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." }, - "disableMultiLineCompletions": { - "type": "boolean", + "multilineCompletions": { + "enum": ["always", "never", "auto"], "description": "If set to true, Continue will only complete a single line at a time." } }, diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 31c78449e..2c732a339 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -1607,8 +1607,12 @@ "type": "string", "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." }, - "disableMultiLineCompletions": { - "type": "boolean", + "multilineCompletions": { + "enum": [ + "always", + "never", + "auto" + ], "description": "If set to true, Continue will only complete a single line at a time." } }, diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 749bc180f..c2c5bcbcc 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -4,15 +4,13 @@ import * as fs from "fs"; import path from "path"; import { v4 } from "uuid"; import * as vscode from "vscode"; +import { ContinueCompletionProvider } from "../autocomplete/completionProvider"; +import { setupStatusBar } from "../autocomplete/statusBar"; import { registerAllCommands } from "../commands"; import IdeProtocolClient from "../continueIdeClient"; import { ContinueGUIWebviewViewProvider } from "../debugPanel"; import registerQuickFixProvider from "../lang-server/codeActions"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; -import { - ContinueCompletionProvider, - setupStatusBar, -} from "../lang-server/completionProvider"; import { vsCodeIndexCodebase } from "../util/indexCodebase"; import { setupRemoteConfigSync } from "../util/remoteConfig"; import { getExtensionVersion } from "../util/util"; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts new file mode 100644 index 000000000..fa1729b50 --- /dev/null +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -0,0 +1,109 @@ +import AutocompleteLruCache from "core/autocomplete/cache"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters"; +import { v4 as uuidv4 } from "uuid"; +import * as vscode from "vscode"; +import { ideProtocolClient } from "../activation/activate"; +import { configHandler } from "../loadConfig"; +import { getTabCompletion } from "./getTabCompletion"; +import { 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 static autocompleteCache = AutocompleteLruCache.get(); + + public static errorsShown: Set = new Set(); + + public async provideInlineCompletionItems( + document: vscode.TextDocument, + position: vscode.Position, + context: vscode.InlineCompletionContext, + token: vscode.CancellationToken + //@ts-ignore + ): ProviderResult { + // Debounce + const uuid = uuidv4(); + ContinueCompletionProvider.lastUUID = uuid; + + const config = await configHandler.loadConfig(); + const options = { + ...config.tabAutocompleteOptions, + ...DEFAULT_AUTOCOMPLETE_OPTS, + }; + + 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") + .get("enableTabAutocomplete") || false; + if (token.isCancellationRequested || !enableTabAutocomplete) { + return []; + } + + try { + const outcome = await getTabCompletion( + document, + position, + token, + options + ); + const completion = outcome?.completion; + + if (!completion) { + return []; + } + + // Do some stuff later so as not to block return. Latency matters + setTimeout(async () => { + if (!outcome.cacheHit) { + (await ContinueCompletionProvider.autocompleteCache).put( + outcome.prompt, + completion + ); + } + }, 100); + + const logRejectionTimeout = setTimeout(() => { + // Wait 10 seconds, then assume it wasn't accepted + outcome.accepted = false; + ideProtocolClient.logDevData("autocomplete", outcome); + }, 10_000); + + return [ + new vscode.InlineCompletionItem( + completion, + new vscode.Range(position, position.translate(0, completion.length)), + { + title: "Log Autocomplete Outcome", + command: "continue.logAutocompleteOutcome", + arguments: [outcome, logRejectionTimeout], + } + ), + ]; + } catch (e: any) { + console.warn("Error getting autocompletion: ", e.message); + } finally { + stopStatusBarLoading(); + } + } +} diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts new file mode 100644 index 000000000..4220772b7 --- /dev/null +++ b/extensions/vscode/src/autocomplete/getTabCompletion.ts @@ -0,0 +1,214 @@ +import { TabAutocompleteOptions } from "core"; +import { AutocompleteLruCache } from "core/autocomplete/cache"; +import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream"; +import { + AutocompleteSnippet, + constructAutocompletePrompt, + languageForFilepath, +} from "core/autocomplete/constructPrompt"; +import { + stopAtSimilarLine, + streamWithNewLines, +} from "core/autocomplete/lineStream"; +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 Handlebars from "handlebars"; +import * as vscode from "vscode"; +import { ideProtocolClient } from "../activation/activate"; +import { TabAutocompleteModel } from "../loadConfig"; +import { ContinueCompletionProvider } from "./completionProvider"; +import { setupStatusBar, stopStatusBarLoading } from "./statusBar"; + +async function getDefinition( + uri: string, + line: number, + character: number +): Promise { + const definitions = (await vscode.commands.executeCommand( + "vscode.executeDefinitionProvider", + vscode.Uri.parse(uri), + new vscode.Position(line, character) + )) as any; + + if (definitions[0]?.targetRange) { + return { + filepath: uri, + content: await ideProtocolClient.readRangeInFile( + definitions[0].targetUri.fsPath, + definitions[0].targetRange + ), + }; + } + + return undefined; +} + +export interface AutocompleteOutcome { + accepted?: boolean; + time: number; + prompt: string; + completion: string; + modelProvider: string; + modelName: string; + completionOptions: any; + cacheHit: boolean; +} + +const autocompleteCache = AutocompleteLruCache.get(); + +export async function getTabCompletion( + document: vscode.TextDocument, + pos: vscode.Position, + token: vscode.CancellationToken, + options: TabAutocompleteOptions +): 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 >= endOfLine.length) { + return undefined; + } + } + + try { + // 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(); + const { prefix, suffix, completeMultiline } = + await constructAutocompletePrompt( + document.uri.toString(), + fullPrefix, + fullSuffix, + clipboardText, + lang, + getDefinition, + options + ); + + const { template, completionOptions } = options.template + ? { template: options.template, completionOptions: {} } + : getTemplateForModel(llm.model); + + const compiledTemplate = Handlebars.compile(template); + const prompt = compiledTemplate({ prefix, suffix }); + + // Completion + let completion = ""; + + const cache = await autocompleteCache; + const cachedCompletion = await cache.get(prompt); + 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", + "```", + ...lang.stopWords, + ]; + if ( + options.multilineCompletions !== "always" && + (options.multilineCompletions === "never" || !completeMultiline) + ) { + stop.unshift("\n"); + } + let generator = GeneratorReuseManager.getGenerator(prefix, () => + llm.streamComplete(prompt, { + ...completionOptions, + temperature: 0, + raw: true, + stop, + }) + ); + + // LLM + let cancelled = false; + const generatorWithCancellation = async function* () { + for await (const update of generator) { + if (token.isCancellationRequested) { + stopStatusBarLoading(); + cancelled = true; + return undefined; + } + yield update; + } + }; + const gen2 = onlyWhitespaceAfterEndOfLine( + generatorWithCancellation(), + lang.endOfLine + ); + const lineGenerator = streamWithNewLines(streamLines(gen2)); + 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, + }; + } catch (e: any) { + console.warn("Error generating autocompletion: ", e); + if (!ContinueCompletionProvider.errorsShown.has(e.message)) { + ContinueCompletionProvider.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" + ) + ); + } + }); + } + return undefined; + } +} diff --git a/extensions/vscode/src/autocomplete/statusBar.ts b/extensions/vscode/src/autocomplete/statusBar.ts new file mode 100644 index 000000000..d9015a833 --- /dev/null +++ b/extensions/vscode/src/autocomplete/statusBar.ts @@ -0,0 +1,51 @@ +import * as vscode from "vscode"; + +const statusBarItemText = (enabled: boolean | undefined) => + enabled ? "$(check) Continue" : "$(circle-slash) Continue"; + +const statusBarItemTooltip = (enabled: boolean | undefined) => + enabled ? "Tab autocomplete is enabled" : "Click to enable tab autocomplete"; + +let lastStatusBar: vscode.StatusBarItem | undefined = undefined; +let statusBarFalseTimeout: NodeJS.Timeout | undefined = undefined; + +export function stopStatusBarLoading() { + statusBarFalseTimeout = setTimeout(() => { + setupStatusBar(true, false); + }, 100); +} + +export function setupStatusBar( + enabled: boolean | undefined, + loading?: boolean +) { + if (loading !== false) { + clearTimeout(statusBarFalseTimeout); + statusBarFalseTimeout = undefined; + } + + const statusBarItem = vscode.window.createStatusBarItem( + vscode.StatusBarAlignment.Right + ); + statusBarItem.text = loading + ? "$(loading~spin) Continue" + : statusBarItemText(enabled); + statusBarItem.tooltip = statusBarItemTooltip(enabled); + statusBarItem.command = "continue.toggleTabAutocompleteEnabled"; + + // Swap out with old status bar + if (lastStatusBar) { + lastStatusBar.dispose(); + } + statusBarItem.show(); + lastStatusBar = statusBarItem; + + vscode.workspace.onDidChangeConfiguration((event) => { + if (event.affectsConfiguration("continue")) { + const config = vscode.workspace.getConfiguration("continue"); + const enabled = config.get("enableTabAutocomplete"); + statusBarItem.dispose(); + setupStatusBar(enabled); + } + }); +} diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index a8484c105..b81c550eb 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -4,6 +4,7 @@ import * as path from "path"; import * as vscode from "vscode"; import { extensionContext, ideProtocolClient } from "./activation/activate"; +import { AutocompleteOutcome } from "./autocomplete/getTabCompletion"; import { debugPanelWebview, getSidebarContent } from "./debugPanel"; import { acceptDiffCommand, rejectDiffCommand } from "./diff/horizontal"; import { @@ -12,7 +13,6 @@ import { verticalPerLineDiffManager, } from "./diff/verticalPerLine/manager"; import { VsCodeIde } from "./ideProtocol"; -import { AutocompleteOutcome } from "./lang-server/completionProvider"; import { configHandler, llmFromTitle } from "./loadConfig"; function addHighlightedCodeToContext(edit: boolean) { diff --git a/extensions/vscode/src/lang-server/completionProvider.ts b/extensions/vscode/src/lang-server/completionProvider.ts deleted file mode 100644 index c78ec8921..000000000 --- a/extensions/vscode/src/lang-server/completionProvider.ts +++ /dev/null @@ -1,486 +0,0 @@ -import { TabAutocompleteOptions } from "core"; -import { AutocompleteLruCache } from "core/autocomplete/cache"; -import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream"; -import { - AutocompleteSnippet, - constructAutocompletePrompt, - languageForFilepath, -} from "core/autocomplete/constructPrompt"; -import { - stopAtSimilarLine, - streamWithNewLines, -} from "core/autocomplete/lineStream"; -import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters"; -import { getTemplateForModel } from "core/autocomplete/templates"; -import { streamLines } from "core/diff/util"; -import OpenAI from "core/llm/llms/OpenAI"; -import Handlebars from "handlebars"; -import { v4 as uuidv4 } from "uuid"; -import * as vscode from "vscode"; -import { ideProtocolClient } from "../activation/activate"; -import { TabAutocompleteModel, configHandler } from "../loadConfig"; - -const statusBarItemText = (enabled: boolean | undefined) => - enabled ? "$(check) Continue" : "$(circle-slash) Continue"; - -const statusBarItemTooltip = (enabled: boolean | undefined) => - enabled ? "Tab autocomplete is enabled" : "Click to enable tab autocomplete"; - -let lastStatusBar: vscode.StatusBarItem | undefined = undefined; -let statusBarFalseTimeout: NodeJS.Timeout | undefined = undefined; - -function stopStatusBarLoading() { - statusBarFalseTimeout = setTimeout(() => { - setupStatusBar(true, false); - }, 100); -} - -export function setupStatusBar( - enabled: boolean | undefined, - loading?: boolean -) { - if (loading !== false) { - clearTimeout(statusBarFalseTimeout); - statusBarFalseTimeout = undefined; - } - - const statusBarItem = vscode.window.createStatusBarItem( - vscode.StatusBarAlignment.Right - ); - statusBarItem.text = loading - ? "$(loading~spin) Continue" - : statusBarItemText(enabled); - statusBarItem.tooltip = statusBarItemTooltip(enabled); - statusBarItem.command = "continue.toggleTabAutocompleteEnabled"; - - // Swap out with old status bar - if (lastStatusBar) { - lastStatusBar.dispose(); - } - statusBarItem.show(); - lastStatusBar = statusBarItem; - - vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("continue")) { - const config = vscode.workspace.getConfiguration("continue"); - const enabled = config.get("enableTabAutocomplete"); - statusBarItem.dispose(); - setupStatusBar(enabled); - } - }); -} - -async function getDefinition( - uri: string, - line: number, - character: number -): Promise { - const definitions = (await vscode.commands.executeCommand( - "vscode.executeDefinitionProvider", - vscode.Uri.parse(uri), - new vscode.Position(line, character) - )) as any; - - if (definitions[0]?.targetRange) { - return { - filepath: uri, - content: await ideProtocolClient.readRangeInFile( - definitions[0].targetUri.fsPath, - definitions[0].targetRange - ), - }; - } - - return undefined; -} - -export interface AutocompleteOutcome { - accepted?: boolean; - time: number; - prompt: string; - completion: string; - modelProvider: string; - modelName: string; - completionOptions: any; - cacheHit: boolean; -} - -const autocompleteCache = AutocompleteLruCache.get(); - -class ListenableGenerator { - private _source: AsyncGenerator; - private _buffer: T[] = []; - private _listeners: Set<(value: T) => void> = new Set(); - private _isEnded: boolean = false; - - constructor(source: AsyncGenerator) { - this._source = source; - this._start(); - } - - public cancel() { - this._isEnded = true; - } - - private async _start() { - try { - for await (const value of this._source) { - if (this._isEnded) { - break; - } - this._buffer.push(value); - for (const listener of this._listeners) { - listener(value); - } - } - } finally { - this._isEnded = true; - for (const listener of this._listeners) { - listener(null as any); - } - } - } - - listen(listener: (value: T) => void) { - this._listeners.add(listener); - for (const value of this._buffer) { - listener(value); - } - if (this._isEnded) { - listener(null as any); - } - } - - async *tee(): AsyncGenerator { - try { - for (const value of this._buffer) { - yield value; - } - while (!this._isEnded) { - let resolve: (value: any) => void; - let promise = new Promise((res) => { - resolve = res; - this._listeners.add(resolve!); - }); - const value = await promise; - this._listeners.delete(resolve!); - - yield value; - } - } finally { - // this._listeners.delete(resolve!); - } - } -} - -class GeneratorReuseManager { - static currentGenerator: ListenableGenerator | undefined; - static pendingGeneratorPrefix: string | undefined; - static pendingCompletion: string = ""; - - private static _createListenableGenerator( - gen: AsyncGenerator, - prefix: string - ) { - GeneratorReuseManager.currentGenerator?.cancel(); - - const listenableGen = new ListenableGenerator(gen); - listenableGen.listen( - (chunk) => (GeneratorReuseManager.pendingCompletion += chunk ?? "") - ); - - GeneratorReuseManager.pendingGeneratorPrefix = prefix; - GeneratorReuseManager.pendingCompletion = ""; - GeneratorReuseManager.currentGenerator = listenableGen; - } - - static async *getGenerator( - prefix: string, - newGenerator: () => AsyncGenerator - ): AsyncGenerator { - // Check if current can be reused - if ( - !( - GeneratorReuseManager.currentGenerator && - GeneratorReuseManager.pendingGeneratorPrefix && - ( - GeneratorReuseManager.pendingGeneratorPrefix + - GeneratorReuseManager.pendingCompletion - ).startsWith(prefix) && - // for e.g. backspace - GeneratorReuseManager.pendingGeneratorPrefix?.length <= prefix?.length - ) - ) { - // Create a wrapper over the current generator to fix the prompt - GeneratorReuseManager._createListenableGenerator(newGenerator(), prefix); - } - - let alreadyTyped = - prefix.slice(GeneratorReuseManager.pendingGeneratorPrefix?.length) || ""; - for await (let chunk of GeneratorReuseManager.currentGenerator!.tee()) { - if (!chunk) { - continue; - } - while (chunk.length && alreadyTyped.length) { - if (chunk[0] === alreadyTyped[0]) { - alreadyTyped = alreadyTyped.slice(1); - chunk = chunk.slice(1); - } else { - break; - } - } - yield chunk; - } - } -} - -async function getTabCompletion( - document: vscode.TextDocument, - pos: vscode.Position, - token: vscode.CancellationToken, - options: TabAutocompleteOptions -): 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 >= endOfLine.length) { - return undefined; - } - } - - try { - // 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(); - const { prefix, suffix, completeMultiline } = - await constructAutocompletePrompt( - document.uri.toString(), - fullPrefix, - fullSuffix, - clipboardText, - lang, - getDefinition, - options - ); - - const { template, completionOptions } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); - - const compiledTemplate = Handlebars.compile(template); - const prompt = compiledTemplate({ prefix, suffix }); - - // Completion - let completion = ""; - - const cache = await autocompleteCache; - const cachedCompletion = await cache.get(prompt); - 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", - "```", - ...lang.stopWords, - ]; - if ( - options.multilineCompletions !== "always" && - (options.multilineCompletions === "never" || !completeMultiline) - ) { - stop.unshift("\n"); - } - let generator = GeneratorReuseManager.getGenerator(prefix, () => - llm.streamComplete(prompt, { - ...completionOptions, - temperature: 0, - raw: true, - stop, - }) - ); - - // LLM - let cancelled = false; - const generatorWithCancellation = async function* () { - for await (const update of generator) { - if (token.isCancellationRequested) { - stopStatusBarLoading(); - cancelled = true; - return undefined; - } - yield update; - } - }; - const gen2 = onlyWhitespaceAfterEndOfLine( - generatorWithCancellation(), - lang.endOfLine - ); - const lineGenerator = streamWithNewLines(streamLines(gen2)); - 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, - }; - } catch (e: any) { - console.warn("Error generating autocompletion: ", e); - if (!ContinueCompletionProvider.errorsShown.has(e.message)) { - ContinueCompletionProvider.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" - ) - ); - } - }); - } - return undefined; - } -} - -export class ContinueCompletionProvider - implements vscode.InlineCompletionItemProvider -{ - private static debounceTimeout: NodeJS.Timeout | undefined = undefined; - private static debouncing: boolean = false; - private static lastUUID: string | undefined = undefined; - - public static errorsShown: Set = new Set(); - - public async provideInlineCompletionItems( - document: vscode.TextDocument, - position: vscode.Position, - context: vscode.InlineCompletionContext, - token: vscode.CancellationToken - //@ts-ignore - ): ProviderResult { - // Debounce - const uuid = uuidv4(); - ContinueCompletionProvider.lastUUID = uuid; - - const config = await configHandler.loadConfig(); - const options = { - ...config.tabAutocompleteOptions, - ...DEFAULT_AUTOCOMPLETE_OPTS, - }; - - 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") - .get("enableTabAutocomplete") || false; - if (token.isCancellationRequested || !enableTabAutocomplete) { - return []; - } - - try { - const outcome = await getTabCompletion( - document, - position, - token, - options - ); - const completion = outcome?.completion; - - if (!completion) { - return []; - } - - // Do some stuff later so as not to block return. Latency matters - setTimeout(async () => { - if (!outcome.cacheHit) { - (await autocompleteCache).put(outcome.prompt, completion); - } - }, 100); - - const logRejectionTimeout = setTimeout(() => { - // Wait 10 seconds, then assume it wasn't accepted - outcome.accepted = false; - ideProtocolClient.logDevData("autocomplete", outcome); - }, 10_000); - - return [ - new vscode.InlineCompletionItem( - completion, - new vscode.Range(position, position.translate(0, completion.length)), - { - title: "Log Autocomplete Outcome", - command: "continue.logAutocompleteOutcome", - arguments: [outcome, logRejectionTimeout], - } - ), - ]; - } catch (e: any) { - console.warn("Error getting autocompletion: ", e.message); - } finally { - stopStatusBarLoading(); - } - } -} diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index 506488bcd..1211ea140 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -696,7 +696,7 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== -"@lancedb/vectordb-darwin-arm64@*", "@lancedb/vectordb-darwin-arm64@0.4.10": +"@lancedb/vectordb-darwin-arm64@0.4.10": version "0.4.10" resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz" integrity sha512-y/uHOGb0g15pvqv5tdTyZ6oN+0QVpBmZDzKFWW6pPbuSZjB2uPqcs+ti0RB+AUdmS21kavVQqaNsw/HLKEGrHA==