From 598cd40016020482b318466e9f84be704e6beaa9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 23 Feb 2024 07:23:44 -0800 Subject: [PATCH 01/11] =?UTF-8?q?=F0=9F=94=A7=20add=20option=20to=20always?= =?UTF-8?q?=20enable=20multiline=20completions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/index.d.ts | 2 +- docs/docs/walkthroughs/tab-autocomplete.md | 1 + extensions/vscode/config_schema.json | 4 ++-- extensions/vscode/src/lang-server/completionProvider.ts | 5 ++++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 261081593..9882b8d55 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -581,7 +581,7 @@ export interface TabAutocompleteOptions { maxSuffixPercentage: number; prefixPercentage: number; template?: string; - disableMultiLineCompletions?: boolean; + multilineCompletions?: "always" | "never" | "auto"; } export interface SerializedContinueConfig { diff --git a/docs/docs/walkthroughs/tab-autocomplete.md b/docs/docs/walkthroughs/tab-autocomplete.md index 6579a21a1..ea4f6f36f 100644 --- a/docs/docs/walkthroughs/tab-autocomplete.md +++ b/docs/docs/walkthroughs/tab-autocomplete.md @@ -49,6 +49,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa - `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) - `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) - `template`: 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. (String) +- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". ### Full example diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index e37574e2b..832dcbc59 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.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/src/lang-server/completionProvider.ts b/extensions/vscode/src/lang-server/completionProvider.ts index bf6d22ccc..c78ec8921 100644 --- a/extensions/vscode/src/lang-server/completionProvider.ts +++ b/extensions/vscode/src/lang-server/completionProvider.ts @@ -311,7 +311,10 @@ async function getTabCompletion( "```", ...lang.stopWords, ]; - if (options.disableMultiLineCompletions || !completeMultiline) { + if ( + options.multilineCompletions !== "always" && + (options.multilineCompletions === "never" || !completeMultiline) + ) { stop.unshift("\n"); } let generator = GeneratorReuseManager.getGenerator(prefix, () => From 50dafd6c2e5e7bb2a6ce047b1c16efbcf250221b Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 23 Feb 2024 07:30:36 -0800 Subject: [PATCH 02/11] =?UTF-8?q?=F0=9F=8E=A8=20organize=20vscode=20autoco?= =?UTF-8?q?mplete=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== From ac2e8056f4553eb573cd1b7d11f728f6b9392fca Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 23 Feb 2024 08:12:42 -0800 Subject: [PATCH 03/11] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20recently=20edited=20?= =?UTF-8?q?snippets=20for=20autocomplete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/ast.ts | 76 +++++++++++++++++++ core/autocomplete/constructPrompt.ts | 58 +++++--------- core/autocomplete/recentlyEdited.ts | 5 ++ core/autocomplete/retrieval.ts | 24 ++++++ .../src/autocomplete/getTabCompletion.ts | 5 +- .../vscode/src/autocomplete/recentlyEdited.ts | 65 ++++++++++++++++ 6 files changed, 192 insertions(+), 41 deletions(-) create mode 100644 core/autocomplete/ast.ts create mode 100644 core/autocomplete/recentlyEdited.ts create mode 100644 core/autocomplete/retrieval.ts create mode 100644 extensions/vscode/src/autocomplete/recentlyEdited.ts diff --git a/core/autocomplete/ast.ts b/core/autocomplete/ast.ts new file mode 100644 index 000000000..223a5ae5d --- /dev/null +++ b/core/autocomplete/ast.ts @@ -0,0 +1,76 @@ +import Parser from "web-tree-sitter"; +import { RangeInFileWithContents } from "../commands/util"; +import { getParserForFile } from "../util/treeSitter"; + +export async function getAst( + filepath: string, + fileContents: string +): Promise { + const parser = await getParserForFile(filepath); + + if (!parser) { + return undefined; + } + + const ast = parser.parse(fileContents); + return ast; +} + +export async function getTreePathAtCursor( + ast: Parser.Tree, + cursorIndex: number +): Promise { + const path = [ast.rootNode]; + while (path[path.length - 1].childCount > 0) { + let foundChild = false; + for (let child of path[path.length - 1].children) { + if (child.startIndex <= cursorIndex && child.endIndex >= cursorIndex) { + path.push(child); + foundChild = true; + break; + } + } + + if (!foundChild) { + break; + } + } + + return path; +} + +export async function getScopeAroundRange( + range: RangeInFileWithContents +): Promise { + const ast = await getAst(range.filepath, range.contents); + if (!ast) { + return undefined; + } + + const { start: s, end: e } = range.range; + const lines = range.contents.split("\n"); + const startIndex = + lines.slice(0, s.line).join("\n").length + + lines[s.line].slice(s.character).length; + const endIndex = + lines.slice(0, e.line).join("\n").length + + lines[e.line].slice(0, e.character).length; + + let node = ast.rootNode; + while (node.childCount > 0) { + let foundChild = false; + for (let child of node.children) { + if (child.startIndex < startIndex && child.endIndex > endIndex) { + node = child; + foundChild = true; + break; + } + } + + if (!foundChild) { + break; + } + } + + return node.text; +} diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index f9f28704c..71a3b5168 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,12 +1,14 @@ import Parser from "web-tree-sitter"; import { TabAutocompleteOptions } from ".."; +import { RangeInFileWithContents } from "../commands/util"; import { countTokens, pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens"; import { getBasename } from "../util"; -import { getParserForFile } from "../util/treeSitter"; + +import { getAst, getScopeAroundRange, getTreePathAtCursor } from "./ast"; import { AutocompleteLanguageInfo, LANGUAGES, Typescript } from "./languages"; export function languageForFilepath( @@ -29,43 +31,6 @@ function formatExternalSnippet( return lines.join("\n"); } -async function getAst( - filepath: string, - fileContents: string -): Promise { - const parser = await getParserForFile(filepath); - - if (!parser) { - return undefined; - } - - const ast = parser.parse(fileContents); - return ast; -} - -async function getTreePathAtCursor( - ast: Parser.Tree, - cursorIndex: number -): Promise { - const path = [ast.rootNode]; - while (path[path.length - 1].childCount > 0) { - let foundChild = false; - for (let child of path[path.length - 1].children) { - if (child.startIndex <= cursorIndex && child.endIndex >= cursorIndex) { - path.push(child); - foundChild = true; - break; - } - } - - if (!foundChild) { - break; - } - } - - return path; -} - export interface AutocompleteSnippet { filepath: string; content: string; @@ -111,7 +76,8 @@ export async function constructAutocompletePrompt( line: number, character: number ) => Promise, - options: TabAutocompleteOptions + options: TabAutocompleteOptions, + recentlyEditedRanges: RangeInFileWithContents[] ): Promise<{ prefix: string; suffix: string; @@ -119,7 +85,19 @@ export async function constructAutocompletePrompt( completeMultiline: boolean; }> { // Find external snippets - const snippets: AutocompleteSnippet[] = []; + const snippets: AutocompleteSnippet[] = (await Promise.all( + recentlyEditedRanges + .map(async (r) => { + const scope = await getScopeAroundRange(r); + if (!scope) return null; + + return { + filepath: r.filepath, + content: r.contents, + }; + }) + .filter((s) => !!s) + )) as any; let treePath: Parser.SyntaxNode[] | undefined; try { diff --git a/core/autocomplete/recentlyEdited.ts b/core/autocomplete/recentlyEdited.ts new file mode 100644 index 000000000..d809066a4 --- /dev/null +++ b/core/autocomplete/recentlyEdited.ts @@ -0,0 +1,5 @@ +import { RangeInFileWithContents } from "../commands/util"; + +export type RecentlyEditedRange = RangeInFileWithContents & { + timestamp: number; +}; diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts new file mode 100644 index 000000000..2beb3b44d --- /dev/null +++ b/core/autocomplete/retrieval.ts @@ -0,0 +1,24 @@ +import { Chunk } from ".."; +import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch"; +import { IndexTag } from "../indexing/types"; + +export async function fullTextRetrieve( + prefix: string, + suffix: string, + indexTag: IndexTag +): Promise { + const index = new FullTextSearchCodebaseIndex(); + const searchStrings = prefix.split("\n").slice(-3); + const results: Chunk[] = []; + searchStrings.forEach(async (searchString) => { + const chunks = await index.retrieve( + [indexTag], + searchString, + 3, + undefined, + undefined + ); + results.push(...chunks); + }); + return results; +} diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts index 4220772b7..b729cbdc8 100644 --- a/extensions/vscode/src/autocomplete/getTabCompletion.ts +++ b/extensions/vscode/src/autocomplete/getTabCompletion.ts @@ -19,6 +19,7 @@ import * as vscode from "vscode"; import { ideProtocolClient } from "../activation/activate"; import { TabAutocompleteModel } from "../loadConfig"; import { ContinueCompletionProvider } from "./completionProvider"; +import { RecentlyEditedTracker } from "./recentlyEdited"; import { setupStatusBar, stopStatusBarLoading } from "./statusBar"; async function getDefinition( @@ -57,6 +58,7 @@ export interface AutocompleteOutcome { } const autocompleteCache = AutocompleteLruCache.get(); +const recentlyEditedTracker = new RecentlyEditedTracker(); export async function getTabCompletion( document: vscode.TextDocument, @@ -105,7 +107,8 @@ export async function getTabCompletion( clipboardText, lang, getDefinition, - options + options, + await recentlyEditedTracker.getRecentlyEditedRanges() ); const { template, completionOptions } = options.template diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts new file mode 100644 index 000000000..f66f26d55 --- /dev/null +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -0,0 +1,65 @@ +import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited"; +import * as vscode from "vscode"; + +interface VsCodeRecentlyEditedRange { + timestamp: number; + uri: vscode.Uri; + range: vscode.Range; +} + +export class RecentlyEditedTracker { + private static staleTime = 1000 * 60 * 2; + private static maxRecentlyEditedRanges = 3; + private recentlyEditedRanges: VsCodeRecentlyEditedRange[] = []; + + constructor() { + vscode.workspace.onDidChangeTextDocument((event) => { + event.contentChanges.forEach((change) => { + const editedRange = { + uri: event.document.uri, + range: change.range, + timestamp: Date.now(), + }; + const newLength = this.recentlyEditedRanges.unshift(editedRange); + if (newLength >= RecentlyEditedTracker.maxRecentlyEditedRanges) { + this.recentlyEditedRanges = this.recentlyEditedRanges.slice( + 0, + RecentlyEditedTracker.maxRecentlyEditedRanges + ); + } + }); + }); + + setInterval(() => { + this.removeOldEntries(); + }, 1000 * 15); + } + + private removeOldEntries() { + this.recentlyEditedRanges = this.recentlyEditedRanges.filter( + (entry) => entry.timestamp > Date.now() - RecentlyEditedTracker.staleTime + ); + } + + public async getRecentlyEditedRanges(): Promise { + return Promise.all( + this.recentlyEditedRanges.map(async (entry) => ({ + timestamp: entry.timestamp, + filepath: entry.uri.fsPath, + contents: await vscode.workspace.fs + .readFile(entry.uri) + .then((content) => content.toString()), + range: { + start: { + line: entry.range.start.line, + character: entry.range.start.character, + }, + end: { + line: entry.range.end.line, + character: entry.range.end.character, + }, + }, + })) + ); + } +} From 9c9835009143d11ecdc6b65c03facc647169938e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 23 Feb 2024 08:52:29 -0800 Subject: [PATCH 04/11] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20sliding=20window=20s?= =?UTF-8?q?imilarity=20over=20recent=20documents?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/constructPrompt.ts | 28 +++-- core/autocomplete/parameters.ts | 4 +- core/autocomplete/slidingWindow.ts | 101 ++++++++++++++++++ core/index.d.ts | 7 ++ .../src/autocomplete/getTabCompletion.ts | 10 +- .../vscode/src/autocomplete/recentlyEdited.ts | 31 ++++++ 6 files changed, 165 insertions(+), 16 deletions(-) create mode 100644 core/autocomplete/slidingWindow.ts diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 71a3b5168..39dcd7952 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,5 +1,5 @@ import Parser from "web-tree-sitter"; -import { TabAutocompleteOptions } from ".."; +import { FileWithContents, TabAutocompleteOptions } from ".."; import { RangeInFileWithContents } from "../commands/util"; import { countTokens, @@ -10,6 +10,7 @@ import { getBasename } from "../util"; import { getAst, getScopeAroundRange, getTreePathAtCursor } from "./ast"; import { AutocompleteLanguageInfo, LANGUAGES, Typescript } from "./languages"; +import { slidingWindowMatcher } from "./slidingWindow"; export function languageForFilepath( filepath: string @@ -31,11 +32,6 @@ function formatExternalSnippet( return lines.join("\n"); } -export interface AutocompleteSnippet { - filepath: string; - content: string; -} - const BLOCK_TYPES = ["body", "statement_block"]; function shouldCompleteMultiline( @@ -75,9 +71,10 @@ export async function constructAutocompletePrompt( filepath: string, line: number, character: number - ) => Promise, + ) => Promise, options: TabAutocompleteOptions, - recentlyEditedRanges: RangeInFileWithContents[] + recentlyEditedRanges: RangeInFileWithContents[], + recentlyEditedDocuments: FileWithContents[] ): Promise<{ prefix: string; suffix: string; @@ -85,7 +82,7 @@ export async function constructAutocompletePrompt( completeMultiline: boolean; }> { // Find external snippets - const snippets: AutocompleteSnippet[] = (await Promise.all( + const snippets: FileWithContents[] = (await Promise.all( recentlyEditedRanges .map(async (r) => { const scope = await getScopeAroundRange(r); @@ -99,6 +96,17 @@ export async function constructAutocompletePrompt( .filter((s) => !!s) )) as any; + snippets.push( + ...(await slidingWindowMatcher( + recentlyEditedDocuments, + fullPrefix, + fullSuffix, + 3, + options.slidingWindowPrefixPercentage, + options.slidingWindowSize + )) + ); + let treePath: Parser.SyntaxNode[] | undefined; try { const ast = await getAst(filepath, fullPrefix + fullSuffix); @@ -140,7 +148,7 @@ export async function constructAutocompletePrompt( // Construct basic prefix / suffix const formattedSnippets = snippets .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.content, language) + formatExternalSnippet(snippet.filepath, snippet.contents, language) ) .join("\n"); const maxPrefixTokens = diff --git a/core/autocomplete/parameters.ts b/core/autocomplete/parameters.ts index ae70787ef..c2268e073 100644 --- a/core/autocomplete/parameters.ts +++ b/core/autocomplete/parameters.ts @@ -3,8 +3,10 @@ import { TabAutocompleteOptions } from ".."; export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { useCopyBuffer: true, useSuffix: true, - maxPromptTokens: 650, + maxPromptTokens: 500, prefixPercentage: 0.85, maxSuffixPercentage: 0.25, debounceDelay: 350, + slidingWindowPrefixPercentage: 0.75, + slidingWindowSize: 100, }; diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/slidingWindow.ts new file mode 100644 index 000000000..5d4b99812 --- /dev/null +++ b/core/autocomplete/slidingWindow.ts @@ -0,0 +1,101 @@ +import { FileWithContents } from ".."; + +function* slidingWindow( + content: string, + windowSize: number +): Generator { + const lines = content.split("\n"); + + let charCount = 0; + let currWindowLines: string[] = []; + for (let i = 0; i < lines.length; i++) { + if (charCount + lines[i].length >= windowSize) { + yield currWindowLines.join("\n"); + currWindowLines = [lines[i]]; + charCount = 0; + } else { + currWindowLines.push(lines[i]); + } + charCount += lines[i].length; + } + + if (currWindowLines.length > 0) { + yield currWindowLines.join("\n"); + } +} + +function getSymbolsForSnippet(snippet: string): Set { + const symbols = snippet + .split( + new RegExp( + `[s\.\:\'\,\;\"\*\&\^\|\\\#\@\$\!\%\(\)\[\]\{\}\<\>\/\?\+\-\/]`, + "g" + ) + ) + .map((s) => s.trim()); + return new Set(symbols); +} + +/** + * Calculate similarity as number of shared symbols divided by total number of unique symbols between both. + */ +function slidingWindowSimilarity(a: string, b: string): number { + const aSet = getSymbolsForSnippet(a); + const bSet = getSymbolsForSnippet(b); + const totalSet = new Set([...aSet, ...bSet]); + + // Avoid division by zero + if (totalSet.size === 0) { + return 0; + } + + let intersection = 0; + for (const symbol of aSet) { + if (bSet.has(symbol)) { + intersection++; + } + } + + return intersection / totalSet.size; +} + +/** + * Match by similarity over sliding windows of recent documents. + * @param recentDocuments + * @param prefix + * @param suffix + */ +export async function slidingWindowMatcher( + recentDocuments: FileWithContents[], + prefix: string, + suffix: string, + topN: number, + slidingWindowPrefixPercentage: number, + windowSize: number +): Promise { + // Sorted lowest similarity to highest + const topMatches: (FileWithContents & { similarity: number })[] = []; + + for (const { filepath, contents } of recentDocuments) { + for (const window of slidingWindow(contents, windowSize)) { + const similarity = slidingWindowSimilarity( + window, + prefix.slice(-windowSize * slidingWindowPrefixPercentage) + + suffix.slice(windowSize * (1 - slidingWindowPrefixPercentage)) + ); + + // Insertion sort + let i = -1; + while ( + ++i < topMatches.length && + similarity > topMatches[i].similarity + ) {} + topMatches.splice(i + 1, 0, { filepath, contents, similarity }); + if (topMatches.length > topN) { + topMatches.shift(); + } + } + } + + return topMatches; +} diff --git a/core/index.d.ts b/core/index.d.ts index 9882b8d55..8b5dc6444 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -162,6 +162,11 @@ export interface RangeInFile { range: Range; } +export interface FileWithContents { + filepath: string; + contents: string; +} + export interface Range { start: Position; end: Position; @@ -582,6 +587,8 @@ export interface TabAutocompleteOptions { prefixPercentage: number; template?: string; multilineCompletions?: "always" | "never" | "auto"; + slidingWindowPrefixPercentage?: number; + slidingWindowSize?: number; } export interface SerializedContinueConfig { diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts index b729cbdc8..14c0242b0 100644 --- a/extensions/vscode/src/autocomplete/getTabCompletion.ts +++ b/extensions/vscode/src/autocomplete/getTabCompletion.ts @@ -1,8 +1,7 @@ -import { TabAutocompleteOptions } from "core"; +import { FileWithContents, TabAutocompleteOptions } from "core"; import { AutocompleteLruCache } from "core/autocomplete/cache"; import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream"; import { - AutocompleteSnippet, constructAutocompletePrompt, languageForFilepath, } from "core/autocomplete/constructPrompt"; @@ -26,7 +25,7 @@ async function getDefinition( uri: string, line: number, character: number -): Promise { +): Promise { const definitions = (await vscode.commands.executeCommand( "vscode.executeDefinitionProvider", vscode.Uri.parse(uri), @@ -36,7 +35,7 @@ async function getDefinition( if (definitions[0]?.targetRange) { return { filepath: uri, - content: await ideProtocolClient.readRangeInFile( + contents: await ideProtocolClient.readRangeInFile( definitions[0].targetUri.fsPath, definitions[0].targetRange ), @@ -108,7 +107,8 @@ export async function getTabCompletion( lang, getDefinition, options, - await recentlyEditedTracker.getRecentlyEditedRanges() + await recentlyEditedTracker.getRecentlyEditedRanges(), + await recentlyEditedTracker.getRecentlyEditedDocuments() ); const { template, completionOptions } = options.template diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index f66f26d55..d8c4cf80d 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -1,3 +1,4 @@ +import { FileWithContents } from "core"; import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited"; import * as vscode from "vscode"; @@ -7,11 +8,19 @@ interface VsCodeRecentlyEditedRange { range: vscode.Range; } +interface VsCodeRecentlyEditedDocument { + timestamp: number; + uri: vscode.Uri; +} + export class RecentlyEditedTracker { private static staleTime = 1000 * 60 * 2; private static maxRecentlyEditedRanges = 3; private recentlyEditedRanges: VsCodeRecentlyEditedRange[] = []; + private recentlyEditedDocuments: VsCodeRecentlyEditedDocument[] = []; + private static maxRecentlyEditedDocuments = 10; + constructor() { vscode.workspace.onDidChangeTextDocument((event) => { event.contentChanges.forEach((change) => { @@ -28,6 +37,17 @@ export class RecentlyEditedTracker { ); } }); + + const newLength = this.recentlyEditedDocuments.unshift({ + uri: event.document.uri, + timestamp: Date.now(), + }); + if (newLength >= RecentlyEditedTracker.maxRecentlyEditedDocuments) { + this.recentlyEditedDocuments = this.recentlyEditedDocuments.slice( + 0, + RecentlyEditedTracker.maxRecentlyEditedDocuments + ); + } }); setInterval(() => { @@ -62,4 +82,15 @@ export class RecentlyEditedTracker { })) ); } + + public async getRecentlyEditedDocuments(): Promise { + return Promise.all( + this.recentlyEditedDocuments.map(async (entry) => ({ + filepath: entry.uri.fsPath, + contents: await vscode.workspace.fs + .readFile(entry.uri) + .then((content) => content.toString()), + })) + ); + } } From da6470762adb4f48fcdd48f867d257e671b4931d Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 23 Feb 2024 08:53:15 -0800 Subject: [PATCH 05/11] =?UTF-8?q?=F0=9F=90=9B=20fix=20autocomplete=20optio?= =?UTF-8?q?ns=20type?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/parameters.ts | 1 + core/index.d.ts | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/parameters.ts b/core/autocomplete/parameters.ts index c2268e073..63cb1d4eb 100644 --- a/core/autocomplete/parameters.ts +++ b/core/autocomplete/parameters.ts @@ -7,6 +7,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { prefixPercentage: 0.85, maxSuffixPercentage: 0.25, debounceDelay: 350, + multilineCompletions: "auto", slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 100, }; diff --git a/core/index.d.ts b/core/index.d.ts index 8b5dc6444..0ceea8899 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -586,9 +586,9 @@ export interface TabAutocompleteOptions { maxSuffixPercentage: number; prefixPercentage: number; template?: string; - multilineCompletions?: "always" | "never" | "auto"; - slidingWindowPrefixPercentage?: number; - slidingWindowSize?: number; + multilineCompletions: "always" | "never" | "auto"; + slidingWindowPrefixPercentage: number; + slidingWindowSize: number; } export interface SerializedContinueConfig { From 64a346dcac2c5a1fd17bb6cf2d07d633f69b7f44 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 23 Feb 2024 10:38:34 -0800 Subject: [PATCH 06/11] =?UTF-8?q?=F0=9F=9A=A7=20basic=20ranking=20by=20sym?= =?UTF-8?q?bol=20intersection=20similarity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/constructPrompt.ts | 14 ++++++- core/autocomplete/ranking.ts | 59 ++++++++++++++++++++++++++++ core/autocomplete/slidingWindow.ts | 38 +----------------- 3 files changed, 74 insertions(+), 37 deletions(-) create mode 100644 core/autocomplete/ranking.ts diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 39dcd7952..794cb7585 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -10,6 +10,7 @@ import { getBasename } from "../util"; import { getAst, getScopeAroundRange, getTreePathAtCursor } from "./ast"; import { AutocompleteLanguageInfo, LANGUAGES, Typescript } from "./languages"; +import { rankSnippets } from "./ranking"; import { slidingWindowMatcher } from "./slidingWindow"; export function languageForFilepath( @@ -82,7 +83,7 @@ export async function constructAutocompletePrompt( completeMultiline: boolean; }> { // Find external snippets - const snippets: FileWithContents[] = (await Promise.all( + let snippets: FileWithContents[] = (await Promise.all( recentlyEditedRanges .map(async (r) => { const scope = await getScopeAroundRange(r); @@ -145,6 +146,17 @@ export async function constructAutocompletePrompt( completeMultiline = shouldCompleteMultiline(treePath, cursorLine); } + // Rank / order the snippets + snippets = rankSnippets( + snippets, + fullPrefix, + fullSuffix, + options.slidingWindowPrefixPercentage, + options.slidingWindowSize + ); + + // How to add snippets to the prefix? Count separately? Always keep some of the prefix?? + // Construct basic prefix / suffix const formattedSnippets = snippets .map((snippet) => diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/ranking.ts new file mode 100644 index 000000000..399df39ab --- /dev/null +++ b/core/autocomplete/ranking.ts @@ -0,0 +1,59 @@ +import { FileWithContents } from ".."; + +function getSymbolsForSnippet(snippet: string): Set { + const symbols = snippet + .split( + new RegExp( + `[s\.\:\'\,\;\"\*\&\^\|\\\#\@\$\!\%\(\)\[\]\{\}\<\>\/\?\+\-\/]`, + "g" + ) + ) + .map((s) => s.trim()); + return new Set(symbols); +} + +/** + * Calculate similarity as number of shared symbols divided by total number of unique symbols between both. + */ +export function symbolSimilarity(a: string, b: string): number { + const aSet = getSymbolsForSnippet(a); + const bSet = getSymbolsForSnippet(b); + const totalSet = new Set([...aSet, ...bSet]); + + // Avoid division by zero + if (totalSet.size === 0) { + return 0; + } + + let intersection = 0; + for (const symbol of aSet) { + if (bSet.has(symbol)) { + intersection++; + } + } + + return intersection / totalSet.size; +} + +/** + * Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array. + */ +export function rankSnippets( + snippets: FileWithContents[], + prefix: string, + suffix: string, + slidingWindowPrefixPercentage: number, + windowSize: number +): FileWithContents[] { + const scores = snippets.map((snippet) => { + const b = + prefix.slice(-windowSize * slidingWindowPrefixPercentage) + + suffix.slice(0, windowSize * (1 - slidingWindowPrefixPercentage)); + + return { + score: symbolSimilarity(snippet.contents, b), + snippet, + }; + }); + return scores.sort((a, b) => a.score - b.score).map((s) => s.snippet); +} diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/slidingWindow.ts index 5d4b99812..af483ec0a 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/slidingWindow.ts @@ -1,4 +1,5 @@ import { FileWithContents } from ".."; +import { symbolSimilarity } from "./ranking"; function* slidingWindow( content: string, @@ -24,41 +25,6 @@ function* slidingWindow( } } -function getSymbolsForSnippet(snippet: string): Set { - const symbols = snippet - .split( - new RegExp( - `[s\.\:\'\,\;\"\*\&\^\|\\\#\@\$\!\%\(\)\[\]\{\}\<\>\/\?\+\-\/]`, - "g" - ) - ) - .map((s) => s.trim()); - return new Set(symbols); -} - -/** - * Calculate similarity as number of shared symbols divided by total number of unique symbols between both. - */ -function slidingWindowSimilarity(a: string, b: string): number { - const aSet = getSymbolsForSnippet(a); - const bSet = getSymbolsForSnippet(b); - const totalSet = new Set([...aSet, ...bSet]); - - // Avoid division by zero - if (totalSet.size === 0) { - return 0; - } - - let intersection = 0; - for (const symbol of aSet) { - if (bSet.has(symbol)) { - intersection++; - } - } - - return intersection / totalSet.size; -} - /** * Match by similarity over sliding windows of recent documents. * @param recentDocuments @@ -78,7 +44,7 @@ export async function slidingWindowMatcher( for (const { filepath, contents } of recentDocuments) { for (const window of slidingWindow(contents, windowSize)) { - const similarity = slidingWindowSimilarity( + const similarity = symbolSimilarity( window, prefix.slice(-windowSize * slidingWindowPrefixPercentage) + suffix.slice(windowSize * (1 - slidingWindowPrefixPercentage)) From 28a8e81cb96ab26214f15c52a459890adb43a118 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 24 Feb 2024 19:15:07 -0500 Subject: [PATCH 07/11] =?UTF-8?q?=F0=9F=9A=A7=20jaccard=20similarity=20to?= =?UTF-8?q?=20rank=20snippets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/ast.ts | 4 +- core/autocomplete/constructPrompt.ts | 42 ++++++------ core/autocomplete/lsp.ts | 49 ++++++++++++++ core/autocomplete/parameters.ts | 2 +- core/autocomplete/ranking.ts | 38 ++++------- core/autocomplete/slidingWindow.ts | 13 ++-- .../vscode/src/autocomplete/recentlyEdited.ts | 65 ++++++++++++++----- extensions/vscode/yarn.lock | 5 ++ 8 files changed, 143 insertions(+), 75 deletions(-) create mode 100644 core/autocomplete/lsp.ts diff --git a/core/autocomplete/ast.ts b/core/autocomplete/ast.ts index 223a5ae5d..910dc36fe 100644 --- a/core/autocomplete/ast.ts +++ b/core/autocomplete/ast.ts @@ -51,10 +51,10 @@ export async function getScopeAroundRange( const lines = range.contents.split("\n"); const startIndex = lines.slice(0, s.line).join("\n").length + - lines[s.line].slice(s.character).length; + lines[s.line]?.slice(s.character).length ?? 0; const endIndex = lines.slice(0, e.line).join("\n").length + - lines[e.line].slice(0, e.character).length; + lines[e.line]?.slice(0, e.character).length ?? 0; let node = ast.rootNode; while (node.childCount > 0) { diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 794cb7585..7b731c509 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -83,7 +83,25 @@ export async function constructAutocompletePrompt( completeMultiline: boolean; }> { // Find external snippets - let snippets: FileWithContents[] = (await Promise.all( + let snippets: FileWithContents[] = []; + + const windowAroundCursor = + fullPrefix.slice( + -options.slidingWindowSize * options.slidingWindowPrefixPercentage + ) + + fullSuffix.slice( + options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage) + ); + + const slidingWindowMatches = await slidingWindowMatcher( + recentlyEditedDocuments, + windowAroundCursor, + 3, + options.slidingWindowSize + ); + snippets.push(...slidingWindowMatches); + + const recentlyEdited = await Promise.all( recentlyEditedRanges .map(async (r) => { const scope = await getScopeAroundRange(r); @@ -91,22 +109,12 @@ export async function constructAutocompletePrompt( return { filepath: r.filepath, - content: r.contents, + contents: r.contents, }; }) .filter((s) => !!s) - )) as any; - - snippets.push( - ...(await slidingWindowMatcher( - recentlyEditedDocuments, - fullPrefix, - fullSuffix, - 3, - options.slidingWindowPrefixPercentage, - options.slidingWindowSize - )) ); + snippets.push(...(recentlyEdited as any)); let treePath: Parser.SyntaxNode[] | undefined; try { @@ -147,13 +155,7 @@ export async function constructAutocompletePrompt( } // Rank / order the snippets - snippets = rankSnippets( - snippets, - fullPrefix, - fullSuffix, - options.slidingWindowPrefixPercentage, - options.slidingWindowSize - ); + snippets = rankSnippets(snippets, windowAroundCursor); // How to add snippets to the prefix? Count separately? Always keep some of the prefix?? diff --git a/core/autocomplete/lsp.ts b/core/autocomplete/lsp.ts new file mode 100644 index 000000000..4b8e76a76 --- /dev/null +++ b/core/autocomplete/lsp.ts @@ -0,0 +1,49 @@ +import Parser from "web-tree-sitter"; +import { FileWithContents } from ".."; +import { RangeInFileWithContents } from "../commands/util"; +import { getAst, getTreePathAtCursor } from "./ast"; + +async function getDefinitionForNode( + node: Parser.SyntaxNode +): Promise { + switch (node.type) { + case "call_expression": + // function call -> function definition + break; + case "": + // variable assignment -> variable definition/type + break; + case "": + // impl of trait -> trait definition + break; + case "": + // + break; + } + return []; +} + +/** + * and other stuff not directly on the path: + * - variables defined on line above + * ...etc... + */ + +async function getDefinitionsFromLsp( + document: FileWithContents, + cursorIndex: number +): Promise { + const ast = await getAst(document.filepath, document.contents); + if (!ast) return []; + + const treePath = await getTreePathAtCursor(ast, cursorIndex); + if (!treePath) return []; + + const results: RangeInFileWithContents[] = []; + for (const node of treePath.reverse()) { + const definitions = await getDefinitionForNode(node); + results.push(...definitions); + } + + return results; +} diff --git a/core/autocomplete/parameters.ts b/core/autocomplete/parameters.ts index 63cb1d4eb..f41184088 100644 --- a/core/autocomplete/parameters.ts +++ b/core/autocomplete/parameters.ts @@ -9,5 +9,5 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { debounceDelay: 350, multilineCompletions: "auto", slidingWindowPrefixPercentage: 0.75, - slidingWindowSize: 100, + slidingWindowSize: 500, }; diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/ranking.ts index 399df39ab..a5d9abbe0 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/ranking.ts @@ -1,27 +1,24 @@ import { FileWithContents } from ".."; +const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g; function getSymbolsForSnippet(snippet: string): Set { const symbols = snippet - .split( - new RegExp( - `[s\.\:\'\,\;\"\*\&\^\|\\\#\@\$\!\%\(\)\[\]\{\}\<\>\/\?\+\-\/]`, - "g" - ) - ) - .map((s) => s.trim()); + .split(rx) + .map((s) => s.trim()) + .filter((s) => s !== ""); return new Set(symbols); } /** * Calculate similarity as number of shared symbols divided by total number of unique symbols between both. */ -export function symbolSimilarity(a: string, b: string): number { +export function jaccardSimilarity(a: string, b: string): number { const aSet = getSymbolsForSnippet(a); const bSet = getSymbolsForSnippet(b); - const totalSet = new Set([...aSet, ...bSet]); + const union = new Set([...aSet, ...bSet]).size; // Avoid division by zero - if (totalSet.size === 0) { + if (union === 0) { return 0; } @@ -32,7 +29,7 @@ export function symbolSimilarity(a: string, b: string): number { } } - return intersection / totalSet.size; + return intersection / union; } /** @@ -40,20 +37,11 @@ export function symbolSimilarity(a: string, b: string): number { */ export function rankSnippets( snippets: FileWithContents[], - prefix: string, - suffix: string, - slidingWindowPrefixPercentage: number, - windowSize: number + windowAroundCursor: string ): FileWithContents[] { - const scores = snippets.map((snippet) => { - const b = - prefix.slice(-windowSize * slidingWindowPrefixPercentage) + - suffix.slice(0, windowSize * (1 - slidingWindowPrefixPercentage)); - - return { - score: symbolSimilarity(snippet.contents, b), - snippet, - }; - }); + const scores = snippets.map((snippet) => ({ + score: jaccardSimilarity(snippet.contents, windowAroundCursor), + snippet, + })); return scores.sort((a, b) => a.score - b.score).map((s) => s.snippet); } diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/slidingWindow.ts index af483ec0a..1a1e1935a 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/slidingWindow.ts @@ -1,5 +1,5 @@ import { FileWithContents } from ".."; -import { symbolSimilarity } from "./ranking"; +import { jaccardSimilarity } from "./ranking"; function* slidingWindow( content: string, @@ -33,10 +33,8 @@ function* slidingWindow( */ export async function slidingWindowMatcher( recentDocuments: FileWithContents[], - prefix: string, - suffix: string, + windowAroundCursor: string, topN: number, - slidingWindowPrefixPercentage: number, windowSize: number ): Promise { // Sorted lowest similarity to highest @@ -44,11 +42,7 @@ export async function slidingWindowMatcher( for (const { filepath, contents } of recentDocuments) { for (const window of slidingWindow(contents, windowSize)) { - const similarity = symbolSimilarity( - window, - prefix.slice(-windowSize * slidingWindowPrefixPercentage) + - suffix.slice(windowSize * (1 - slidingWindowPrefixPercentage)) - ); + const similarity = jaccardSimilarity(window, windowAroundCursor); // Insertion sort let i = -1; @@ -63,5 +57,6 @@ export async function slidingWindowMatcher( } } + // TODO: convert the arbitrary window frame to some whole AST node? return topMatches; } diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index d8c4cf80d..4e942cb9f 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -26,28 +26,16 @@ export class RecentlyEditedTracker { event.contentChanges.forEach((change) => { const editedRange = { uri: event.document.uri, - range: change.range, + range: new vscode.Range( + new vscode.Position(change.range.start.line, 0), + new vscode.Position(change.range.end.line + 1, 0) + ), timestamp: Date.now(), }; - const newLength = this.recentlyEditedRanges.unshift(editedRange); - if (newLength >= RecentlyEditedTracker.maxRecentlyEditedRanges) { - this.recentlyEditedRanges = this.recentlyEditedRanges.slice( - 0, - RecentlyEditedTracker.maxRecentlyEditedRanges - ); - } + this.insertRange(editedRange); }); - const newLength = this.recentlyEditedDocuments.unshift({ - uri: event.document.uri, - timestamp: Date.now(), - }); - if (newLength >= RecentlyEditedTracker.maxRecentlyEditedDocuments) { - this.recentlyEditedDocuments = this.recentlyEditedDocuments.slice( - 0, - RecentlyEditedTracker.maxRecentlyEditedDocuments - ); - } + this.insertDocument(event.document.uri); }); setInterval(() => { @@ -55,6 +43,47 @@ export class RecentlyEditedTracker { }, 1000 * 15); } + private insertRange(editedRange: VsCodeRecentlyEditedRange): void { + // Check for overlap with any existing ranges + for (let i = 0; i < this.recentlyEditedRanges.length; i++) { + let range = this.recentlyEditedRanges[i]; + if (range.range.intersection(editedRange.range)) { + range = { + ...range, + range: range.range.union(editedRange.range), + }; + return; + } + } + + // Otherwise, just add the new and maintain max size + const newLength = this.recentlyEditedRanges.unshift(editedRange); + if (newLength >= RecentlyEditedTracker.maxRecentlyEditedRanges) { + this.recentlyEditedRanges = this.recentlyEditedRanges.slice( + 0, + RecentlyEditedTracker.maxRecentlyEditedRanges + ); + } + } + + private insertDocument(uri: vscode.Uri): void { + // Don't add a duplicate + if (this.recentlyEditedDocuments.some((doc) => doc.uri === uri)) { + return; + } + + const newLength = this.recentlyEditedDocuments.unshift({ + uri, + timestamp: Date.now(), + }); + if (newLength >= RecentlyEditedTracker.maxRecentlyEditedDocuments) { + this.recentlyEditedDocuments = this.recentlyEditedDocuments.slice( + 0, + RecentlyEditedTracker.maxRecentlyEditedDocuments + ); + } + } + private removeOldEntries() { this.recentlyEditedRanges = this.recentlyEditedRanges.filter( (entry) => entry.timestamp > Date.now() - RecentlyEditedTracker.staleTime diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index 1211ea140..d7fbcf227 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -696,6 +696,11 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== +"@lancedb/vectordb-darwin-arm64@*": + version "0.4.11" + resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.11.tgz" + integrity sha512-JDOKmFnuJPFkA7ZmrzBJolROwSjWr7yMvAbi40uLBc25YbbVezodd30u2EFtIwWwtk1GqNYRZ49FZOElKYeC/Q== + "@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" From e147b5abfec0eb2fdcca8332091eb944e2a1ee56 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 24 Feb 2024 23:35:34 -0500 Subject: [PATCH 08/11] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20deduplicate=20autoco?= =?UTF-8?q?mplete=20snippets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/constructPrompt.ts | 18 ++--- core/autocomplete/ranking.ts | 77 +++++++++++++++++-- core/autocomplete/slidingWindow.ts | 21 +++-- .../src/autocomplete/getTabCompletion.ts | 6 +- .../vscode/src/autocomplete/recentlyEdited.ts | 28 +++++-- 5 files changed, 114 insertions(+), 36 deletions(-) diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 7b731c509..c25228d97 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,5 +1,5 @@ import Parser from "web-tree-sitter"; -import { FileWithContents, TabAutocompleteOptions } from ".."; +import { TabAutocompleteOptions } from ".."; import { RangeInFileWithContents } from "../commands/util"; import { countTokens, @@ -72,10 +72,10 @@ export async function constructAutocompletePrompt( filepath: string, line: number, character: number - ) => Promise, + ) => Promise, options: TabAutocompleteOptions, recentlyEditedRanges: RangeInFileWithContents[], - recentlyEditedDocuments: FileWithContents[] + recentlyEditedDocuments: RangeInFileWithContents[] ): Promise<{ prefix: string; suffix: string; @@ -83,7 +83,7 @@ export async function constructAutocompletePrompt( completeMultiline: boolean; }> { // Find external snippets - let snippets: FileWithContents[] = []; + let snippets: RangeInFileWithContents[] = []; const windowAroundCursor = fullPrefix.slice( @@ -107,10 +107,7 @@ export async function constructAutocompletePrompt( const scope = await getScopeAroundRange(r); if (!scope) return null; - return { - filepath: r.filepath, - contents: r.contents, - }; + return r; }) .filter((s) => !!s) ); @@ -155,7 +152,10 @@ export async function constructAutocompletePrompt( } // Rank / order the snippets - snippets = rankSnippets(snippets, windowAroundCursor); + snippets = rankSnippets(snippets, windowAroundCursor).filter( + // Filter out snippets that are already in prefix + (snippet) => snippet.score < 0.98 + ); // How to add snippets to the prefix? Count separately? Always keep some of the prefix?? diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/ranking.ts index a5d9abbe0..81da512eb 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/ranking.ts @@ -1,4 +1,8 @@ -import { FileWithContents } from ".."; +import { RangeInFileWithContents } from "../commands/util"; + +export type AutocompleteSnippet = RangeInFileWithContents & { + score: number; +}; const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g; function getSymbolsForSnippet(snippet: string): Set { @@ -36,12 +40,73 @@ export function jaccardSimilarity(a: string, b: string): number { * Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array. */ export function rankSnippets( - snippets: FileWithContents[], + ranges: RangeInFileWithContents[], windowAroundCursor: string -): FileWithContents[] { - const scores = snippets.map((snippet) => ({ +): AutocompleteSnippet[] { + const snippets = ranges.map((snippet) => ({ score: jaccardSimilarity(snippet.contents, windowAroundCursor), - snippet, + ...snippet, })); - return scores.sort((a, b) => a.score - b.score).map((s) => s.snippet); + const uniqueSnippets = deduplicateSnippets(snippets); + return uniqueSnippets.sort((a, b) => a.score - b.score); +} + +/** + * Deduplicate code snippets by merging overlapping ranges into a single range. + */ +export function deduplicateSnippets( + snippets: AutocompleteSnippet[] +): AutocompleteSnippet[] { + // Group by file + const fileGroups: { [key: string]: AutocompleteSnippet[] } = {}; + for (const snippet of snippets) { + if (!fileGroups[snippet.filepath]) { + fileGroups[snippet.filepath] = []; + } + fileGroups[snippet.filepath].push(snippet); + } + + // Merge overlapping ranges + const allRanges = []; + for (const file of Object.keys(fileGroups)) { + allRanges.push(...mergeSnippetsByRange(fileGroups[file])); + } + return allRanges; +} + +function mergeSnippetsByRange( + snippets: AutocompleteSnippet[] +): AutocompleteSnippet[] { + if (snippets.length === 0) { + return snippets; + } + + const sorted = snippets.sort( + (a, b) => a.range.start.line - b.range.start.line + ); + const merged: AutocompleteSnippet[] = []; + + while (sorted.length > 0) { + const next = sorted.shift()!; + const last = merged[merged.length - 1]; + if (merged.length > 0 && last.range.end.line >= next.range.start.line) { + // Merge with previous snippet + last.score = Math.max(last.score, next.score); + last.range.end = next.range.end; + last.contents = mergeOverlappingRangeContents(last, next); + } else { + merged.push(next); + } + } + + return merged; +} + +function mergeOverlappingRangeContents( + first: RangeInFileWithContents, + second: RangeInFileWithContents +): string { + const firstLines = first.contents.split("\n"); + const numOverlapping = first.range.end.line - second.range.start.line; + return firstLines.slice(-numOverlapping).join("\n") + "\n" + second.contents; } diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/slidingWindow.ts index 1a1e1935a..cfcdbb340 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/slidingWindow.ts @@ -1,5 +1,5 @@ -import { FileWithContents } from ".."; -import { jaccardSimilarity } from "./ranking"; +import { RangeInFileWithContents } from "../commands/util"; +import { AutocompleteSnippet, jaccardSimilarity } from "./ranking"; function* slidingWindow( content: string, @@ -32,25 +32,22 @@ function* slidingWindow( * @param suffix */ export async function slidingWindowMatcher( - recentDocuments: FileWithContents[], + recentDocuments: RangeInFileWithContents[], windowAroundCursor: string, topN: number, windowSize: number -): Promise { +): Promise { // Sorted lowest similarity to highest - const topMatches: (FileWithContents & { similarity: number })[] = []; + const topMatches: AutocompleteSnippet[] = []; - for (const { filepath, contents } of recentDocuments) { + for (const { filepath, contents, range } of recentDocuments) { for (const window of slidingWindow(contents, windowSize)) { - const similarity = jaccardSimilarity(window, windowAroundCursor); + const score = jaccardSimilarity(window, windowAroundCursor); // Insertion sort let i = -1; - while ( - ++i < topMatches.length && - similarity > topMatches[i].similarity - ) {} - topMatches.splice(i + 1, 0, { filepath, contents, similarity }); + while (++i < topMatches.length && score > topMatches[i].score) {} + topMatches.splice(i + 1, 0, { filepath, contents, score, range }); if (topMatches.length > topN) { topMatches.shift(); } diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts index 14c0242b0..b277cc611 100644 --- a/extensions/vscode/src/autocomplete/getTabCompletion.ts +++ b/extensions/vscode/src/autocomplete/getTabCompletion.ts @@ -1,4 +1,4 @@ -import { FileWithContents, TabAutocompleteOptions } from "core"; +import { TabAutocompleteOptions } from "core"; import { AutocompleteLruCache } from "core/autocomplete/cache"; import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream"; import { @@ -11,6 +11,7 @@ import { } from "core/autocomplete/lineStream"; import { getTemplateForModel } from "core/autocomplete/templates"; import { GeneratorReuseManager } from "core/autocomplete/util"; +import { RangeInFileWithContents } from "core/commands/util"; import { streamLines } from "core/diff/util"; import OpenAI from "core/llm/llms/OpenAI"; import Handlebars from "handlebars"; @@ -25,7 +26,7 @@ async function getDefinition( uri: string, line: number, character: number -): Promise { +): Promise { const definitions = (await vscode.commands.executeCommand( "vscode.executeDefinitionProvider", vscode.Uri.parse(uri), @@ -39,6 +40,7 @@ async function getDefinition( definitions[0].targetUri.fsPath, definitions[0].targetRange ), + range: definitions[0].targetRange, }; } diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 4e942cb9f..3e5847efc 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -1,5 +1,5 @@ -import { FileWithContents } from "core"; import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited"; +import { RangeInFileWithContents } from "core/commands/util"; import * as vscode from "vscode"; interface VsCodeRecentlyEditedRange { @@ -112,14 +112,28 @@ export class RecentlyEditedTracker { ); } - public async getRecentlyEditedDocuments(): Promise { + public async getRecentlyEditedDocuments(): Promise< + RangeInFileWithContents[] + > { return Promise.all( - this.recentlyEditedDocuments.map(async (entry) => ({ - filepath: entry.uri.fsPath, - contents: await vscode.workspace.fs + this.recentlyEditedDocuments.map(async (entry) => { + const contents = await vscode.workspace.fs .readFile(entry.uri) - .then((content) => content.toString()), - })) + .then((content) => content.toString()); + const lines = contents.split("\n"); + + return { + filepath: entry.uri.fsPath, + contents, + range: { + start: { line: 0, character: 0 }, + end: { + line: lines.length - 1, + character: lines[lines.length - 1].length, + }, + }, + }; + }) ); } } From 52942824a123ca218fb3a0ad16fcce6e1b770b05 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 25 Feb 2024 10:10:39 -0500 Subject: [PATCH 09/11] =?UTF-8?q?=F0=9F=8E=A8=20update=20LSP=20usage=20for?= =?UTF-8?q?=20autocomplete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/constructPrompt.ts | 86 +++++++-------- core/autocomplete/lsp.ts | 49 --------- .../src/autocomplete/getTabCompletion.ts | 30 +----- extensions/vscode/src/autocomplete/lsp.ts | 101 ++++++++++++++++++ 4 files changed, 144 insertions(+), 122 deletions(-) delete mode 100644 core/autocomplete/lsp.ts create mode 100644 extensions/vscode/src/autocomplete/lsp.ts diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index c25228d97..f44a207e7 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -35,7 +35,7 @@ function formatExternalSnippet( const BLOCK_TYPES = ["body", "statement_block"]; -function shouldCompleteMultiline( +function shouldCompleteMultilineAst( treePath: Parser.SyntaxNode[], cursorLine: number ): boolean { @@ -62,17 +62,42 @@ function shouldCompleteMultiline( return false; } +async function shouldCompleteMultiline( + filepath: string, + fullPrefix: string, + fullSuffix: string +): Promise { + // Use AST to determine whether to complete multiline + let treePath: Parser.SyntaxNode[] | undefined; + try { + const ast = await getAst(filepath, fullPrefix + fullSuffix); + if (!ast) { + throw new Error(`AST undefined for ${filepath}`); + } + + treePath = await getTreePathAtCursor(ast, fullPrefix.length); + } catch (e) { + console.error("Failed to parse AST", e); + } + + let completeMultiline = false; + if (treePath) { + let cursorLine = fullPrefix.split("\n").length - 1; + completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine); + } + return completeMultiline; +} + export async function constructAutocompletePrompt( filepath: string, fullPrefix: string, fullSuffix: string, clipboardText: string, language: AutocompleteLanguageInfo, - getDefinition: ( - filepath: string, - line: number, - character: number - ) => Promise, + getDefinitions: ( + document: RangeInFileWithContents, + cursorIndex: number + ) => Promise, options: TabAutocompleteOptions, recentlyEditedRanges: RangeInFileWithContents[], recentlyEditedDocuments: RangeInFileWithContents[] @@ -113,44 +138,6 @@ export async function constructAutocompletePrompt( ); snippets.push(...(recentlyEdited as any)); - let treePath: Parser.SyntaxNode[] | undefined; - try { - const ast = await getAst(filepath, fullPrefix + fullSuffix); - if (!ast) { - throw new Error(`AST undefined for ${filepath}`); - } - - treePath = await getTreePathAtCursor(ast, fullPrefix.length); - } catch (e) { - console.error("Failed to parse AST", e); - } - - let completeMultiline = false; - if (treePath) { - // Get function def when inside call expression - let callExpression = undefined; - for (let node of treePath.reverse()) { - if (node.type === "call_expression") { - callExpression = node; - break; - } - } - if (callExpression) { - const definition = await getDefinition( - filepath, - callExpression.startPosition.row, - callExpression.startPosition.column - ); - if (definition) { - snippets.push(definition); - } - } - - // Use AST to determine whether to complete multiline - let cursorLine = fullPrefix.split("\n").length - 1; - completeMultiline = shouldCompleteMultiline(treePath, cursorLine); - } - // Rank / order the snippets snippets = rankSnippets(snippets, windowAroundCursor).filter( // Filter out snippets that are already in prefix @@ -179,5 +166,14 @@ export async function constructAutocompletePrompt( ); let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens); - return { prefix, suffix, useFim: true, completeMultiline }; + return { + prefix, + suffix, + useFim: true, + completeMultiline: await shouldCompleteMultiline( + filepath, + fullPrefix, + fullSuffix + ), + }; } diff --git a/core/autocomplete/lsp.ts b/core/autocomplete/lsp.ts deleted file mode 100644 index 4b8e76a76..000000000 --- a/core/autocomplete/lsp.ts +++ /dev/null @@ -1,49 +0,0 @@ -import Parser from "web-tree-sitter"; -import { FileWithContents } from ".."; -import { RangeInFileWithContents } from "../commands/util"; -import { getAst, getTreePathAtCursor } from "./ast"; - -async function getDefinitionForNode( - node: Parser.SyntaxNode -): Promise { - switch (node.type) { - case "call_expression": - // function call -> function definition - break; - case "": - // variable assignment -> variable definition/type - break; - case "": - // impl of trait -> trait definition - break; - case "": - // - break; - } - return []; -} - -/** - * and other stuff not directly on the path: - * - variables defined on line above - * ...etc... - */ - -async function getDefinitionsFromLsp( - document: FileWithContents, - cursorIndex: number -): Promise { - const ast = await getAst(document.filepath, document.contents); - if (!ast) return []; - - const treePath = await getTreePathAtCursor(ast, cursorIndex); - if (!treePath) return []; - - const results: RangeInFileWithContents[] = []; - for (const node of treePath.reverse()) { - const definitions = await getDefinitionForNode(node); - results.push(...definitions); - } - - return results; -} diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts index b277cc611..862bea0ef 100644 --- a/extensions/vscode/src/autocomplete/getTabCompletion.ts +++ b/extensions/vscode/src/autocomplete/getTabCompletion.ts @@ -11,42 +11,16 @@ import { } from "core/autocomplete/lineStream"; import { getTemplateForModel } from "core/autocomplete/templates"; import { GeneratorReuseManager } from "core/autocomplete/util"; -import { RangeInFileWithContents } from "core/commands/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 { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; 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, - contents: await ideProtocolClient.readRangeInFile( - definitions[0].targetUri.fsPath, - definitions[0].targetRange - ), - range: definitions[0].targetRange, - }; - } - - return undefined; -} - export interface AutocompleteOutcome { accepted?: boolean; time: number; @@ -107,7 +81,7 @@ export async function getTabCompletion( fullSuffix, clipboardText, lang, - getDefinition, + getDefinitionsFromLsp, options, await recentlyEditedTracker.getRecentlyEditedRanges(), await recentlyEditedTracker.getRecentlyEditedDocuments() diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts new file mode 100644 index 000000000..1a0d8514d --- /dev/null +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -0,0 +1,101 @@ +import { RangeInFile } from "core"; +import { getAst, getTreePathAtCursor } from "core/autocomplete/ast"; +import { RangeInFileWithContents } from "core/commands/util"; +import * as vscode from "vscode"; +import Parser from "web-tree-sitter"; +import { ideProtocolClient } from "../activation/activate"; + +type GotoProviderName = + | "vscode.executeDefinitionProvider" + | "vscode.executeTypeDefinitionProvider" + | "vscode.executeDeclarationProvider" + | "vscode.executeImplementationProvider" + | "vscode.executeReferenceProvider"; +async function executeGotoProvider( + uri: string, + line: number, + character: number, + name: GotoProviderName +): Promise { + const definitions = (await vscode.commands.executeCommand( + name, + vscode.Uri.parse(uri), + new vscode.Position(line, character) + )) as any; + + return definitions.map((d: any) => ({ + filepath: uri, + range: d.targetRange, + })); +} + +async function getDefinitionsForNode( + uri: string, + node: Parser.SyntaxNode +): Promise { + const ranges: RangeInFile[] = []; + switch (node.type) { + case "call_expression": + // function call -> function definition + const defs = await executeGotoProvider( + uri, + node.startPosition.row, + node.startPosition.column, + "vscode.executeDefinitionProvider" + ); + ranges.push(...defs); + break; + case "variable_declarator": + // variable assignment -> variable definition/type + // usages of the var that appear after the declaration + break; + case "impl_item": + // impl of trait -> trait definition + break; + case "": + // function definition -> implementations? + break; + } + return ranges; +} + +/** + * and other stuff not directly on the path: + * - variables defined on line above + * ...etc... + */ + +export async function getDefinitionsFromLsp( + document: RangeInFileWithContents, + cursorIndex: number +): Promise { + const ast = await getAst(document.filepath, document.contents); + if (!ast) return []; + + const treePath = await getTreePathAtCursor(ast, cursorIndex); + if (!treePath) return []; + + const results: RangeInFileWithContents[] = []; + for (const node of treePath.reverse()) { + const definitions = await getDefinitionsForNode(document.filepath, node); + results.push( + ...(await Promise.all( + definitions.map(async (def) => ({ + ...def, + contents: await ideProtocolClient.readRangeInFile( + def.filepath, + new vscode.Range( + new vscode.Position( + def.range.start.line, + def.range.start.character + ), + new vscode.Position(def.range.end.line, def.range.end.character) + ) + ), + })) + )) + ); + } + + return results; +} From a7cc1f32e565741447892930cd150c26162c56a1 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 27 Feb 2024 23:23:37 -0500 Subject: [PATCH 10/11] =?UTF-8?q?=F0=9F=9A=A7=20working=20on=20fixing=20up?= =?UTF-8?q?=20after=20merging=20preview=20to=20tab-auto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/constructPrompt.ts | 27 +++++-------------- .../src/main/resources/config_schema.json | 4 +-- extensions/vscode/package-lock.json | 4 +-- .../src/autocomplete/completionProvider.ts | 12 ++++++--- .../vscode/src/extension/vscodeExtension.ts | 8 +++--- extensions/vscode/src/util/remoteConfig.ts | 2 +- 6 files changed, 23 insertions(+), 34 deletions(-) diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 7597b0560..8c608ba71 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -10,7 +10,7 @@ import { getBasename } from "../util"; import { getAst, getScopeAroundRange, getTreePathAtCursor } from "./ast"; import { AutocompleteLanguageInfo, LANGUAGES, Typescript } from "./languages"; -import { AutocompleteSnippet, rankSnippets } from "./ranking"; +import { rankSnippets } from "./ranking"; import { slidingWindowMatcher } from "./slidingWindow"; export function languageForFilepath( @@ -65,25 +65,9 @@ function shouldCompleteMultilineAst( async function shouldCompleteMultiline( filepath: string, fullPrefix: string, - fullSuffix: string, - clipboardText: string, - language: AutocompleteLanguageInfo, - getDefinition: ( - filepath: string, - line: number, - character: number - ) => Promise, - options: TabAutocompleteOptions, - modelName: string -): Promise<{ - prefix: string; - suffix: string; - useFim: boolean; - completeMultiline: boolean; -}> { - // Find external snippets - const snippets: AutocompleteSnippet[] = []; - + fullSuffix: string +): Promise { + // Use AST to determine whether to complete multiline let treePath: Parser.SyntaxNode[] | undefined; try { const ast = await getAst(filepath, fullPrefix + fullSuffix); @@ -116,7 +100,8 @@ export async function constructAutocompletePrompt( ) => Promise, options: TabAutocompleteOptions, recentlyEditedRanges: RangeInFileWithContents[], - recentlyEditedDocuments: RangeInFileWithContents[] + recentlyEditedDocuments: RangeInFileWithContents[], + modelName: string ): Promise<{ prefix: string; suffix: string; diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index f693f46a2..7cc6e3c2f 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -1558,8 +1558,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/package-lock.json b/extensions/vscode/package-lock.json index ab7886c46..8b8837ae8 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.72", + "version": "0.9.73", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.72", + "version": "0.9.73", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index fa1729b50..30900ee9c 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -1,9 +1,11 @@ +import { IDE } from "core"; import AutocompleteLruCache from "core/autocomplete/cache"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters"; +import { ConfigHandler } from "core/config/handler"; +import { logDevData } from "core/util/devdata"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; -import { ideProtocolClient } from "../activation/activate"; -import { configHandler } from "../loadConfig"; +import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { getTabCompletion } from "./getTabCompletion"; import { stopStatusBarLoading } from "./statusBar"; @@ -18,6 +20,8 @@ export class ContinueCompletionProvider public static errorsShown: Set = new Set(); + constructor(private readonly configHandler: ConfigHandler, private readonly ide: IDE, private readonly tabAutocompleteModel: TabAutocompleteModel) {} + public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, @@ -29,7 +33,7 @@ export class ContinueCompletionProvider const uuid = uuidv4(); ContinueCompletionProvider.lastUUID = uuid; - const config = await configHandler.loadConfig(); + const config = await this.configHandler.loadConfig(); const options = { ...config.tabAutocompleteOptions, ...DEFAULT_AUTOCOMPLETE_OPTS, @@ -86,7 +90,7 @@ export class ContinueCompletionProvider const logRejectionTimeout = setTimeout(() => { // Wait 10 seconds, then assume it wasn't accepted outcome.accepted = false; - ideProtocolClient.logDevData("autocomplete", outcome); + logDevData("autocomplete", outcome); }, 10_000); return [ diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts index 0ba7a327c..a0359453f 100644 --- a/extensions/vscode/src/extension/vscodeExtension.ts +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -2,16 +2,16 @@ import { ConfigHandler } from "core/config/handler"; import { CodebaseIndexer, PauseToken } from "core/indexing/indexCodebase"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; +import { + ContinueCompletionProvider, +} from "../autocomplete/completionProvider"; +import { setupStatusBar } from "../autocomplete/statusBar"; import { registerAllCommands } from "../commands"; import { ContinueGUIWebviewViewProvider } from "../debugPanel"; import { DiffManager } from "../diff/horizontal"; import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; import { VsCodeIde } from "../ideProtocol"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; -import { - ContinueCompletionProvider, - setupStatusBar, -} from "../lang-server/completionProvider"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { RemoteConfigSync } from "../util/remoteConfig"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; diff --git a/extensions/vscode/src/util/remoteConfig.ts b/extensions/vscode/src/util/remoteConfig.ts index a18b04ce8..2f27664a4 100644 --- a/extensions/vscode/src/util/remoteConfig.ts +++ b/extensions/vscode/src/util/remoteConfig.ts @@ -88,7 +88,7 @@ export class RemoteConfigSync { this.syncInterval = setInterval(() => { if (!this.userToken || !this.remoteConfigServerUrl) return; this.sync(this.userToken, new URL(this.remoteConfigServerUrl)); - }, this.remoteConfigSyncPeriod * 1000); + }, this.remoteConfigSyncPeriod * 1000 * 60); } async sync(userToken: string, remoteConfigServerUrl: URL) { From 76116764e132705161ee61624afab604aa12aadb Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 28 Feb 2024 00:01:23 -0500 Subject: [PATCH 11/11] =?UTF-8?q?=F0=9F=8E=A8=20clean=20up=20tab-auto=20af?= =?UTF-8?q?ter=20merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vscode/src/autocomplete/completionProvider.ts | 4 +++- .../vscode/src/autocomplete/getTabCompletion.ts | 15 +++++++++------ extensions/vscode/src/autocomplete/lsp.ts | 8 ++++---- .../src/lang-server/autocompletePromptBuilder.ts | 6 ++++-- 4 files changed, 20 insertions(+), 13 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 30900ee9c..afd2a2dc7 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -69,7 +69,9 @@ export class ContinueCompletionProvider document, position, token, - options + options, + this.tabAutocompleteModel, + this.ide ); const completion = outcome?.completion; diff --git a/extensions/vscode/src/autocomplete/getTabCompletion.ts b/extensions/vscode/src/autocomplete/getTabCompletion.ts index 862bea0ef..dda474b44 100644 --- a/extensions/vscode/src/autocomplete/getTabCompletion.ts +++ b/extensions/vscode/src/autocomplete/getTabCompletion.ts @@ -1,4 +1,4 @@ -import { TabAutocompleteOptions } from "core"; +import { IDE, TabAutocompleteOptions } from "core"; import { AutocompleteLruCache } from "core/autocomplete/cache"; import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream"; import { @@ -15,7 +15,7 @@ import { streamLines } from "core/diff/util"; import OpenAI from "core/llm/llms/OpenAI"; import Handlebars from "handlebars"; import * as vscode from "vscode"; -import { TabAutocompleteModel } from "../loadConfig"; +import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { ContinueCompletionProvider } from "./completionProvider"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; @@ -39,7 +39,9 @@ export async function getTabCompletion( document: vscode.TextDocument, pos: vscode.Position, token: vscode.CancellationToken, - options: TabAutocompleteOptions + options: TabAutocompleteOptions, + tabAutocompleteModel: TabAutocompleteModel, + ide: IDE ): Promise { const startTime = Date.now(); @@ -54,7 +56,7 @@ export async function getTabCompletion( try { // Model - const llm = await TabAutocompleteModel.get(); + const llm = await tabAutocompleteModel.get() if (llm instanceof OpenAI) { llm.useLegacyCompletionsEndpoint = true; } @@ -81,10 +83,11 @@ export async function getTabCompletion( fullSuffix, clipboardText, lang, - getDefinitionsFromLsp, + (document, cursorIndex) => getDefinitionsFromLsp(document, cursorIndex, ide), options, await recentlyEditedTracker.getRecentlyEditedRanges(), - await recentlyEditedTracker.getRecentlyEditedDocuments() + await recentlyEditedTracker.getRecentlyEditedDocuments(), + llm.model ); const { template, completionOptions } = options.template diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index 1a0d8514d..d21763424 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,9 +1,8 @@ -import { RangeInFile } from "core"; +import { IDE, RangeInFile } from "core"; import { getAst, getTreePathAtCursor } from "core/autocomplete/ast"; import { RangeInFileWithContents } from "core/commands/util"; import * as vscode from "vscode"; import Parser from "web-tree-sitter"; -import { ideProtocolClient } from "../activation/activate"; type GotoProviderName = | "vscode.executeDefinitionProvider" @@ -67,7 +66,8 @@ async function getDefinitionsForNode( export async function getDefinitionsFromLsp( document: RangeInFileWithContents, - cursorIndex: number + cursorIndex: number, + ide: IDE ): Promise { const ast = await getAst(document.filepath, document.contents); if (!ast) return []; @@ -82,7 +82,7 @@ export async function getDefinitionsFromLsp( ...(await Promise.all( definitions.map(async (def) => ({ ...def, - contents: await ideProtocolClient.readRangeInFile( + contents: await ide.readRangeInFile( def.filepath, new vscode.Range( new vscode.Position( diff --git a/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts b/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts index eab90c80e..8a8895f55 100644 --- a/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts +++ b/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts @@ -1,5 +1,5 @@ import { IDE } from "core"; -import { AutocompleteSnippet } from "core/autocomplete/constructPrompt"; +import { AutocompleteSnippet } from "core/autocomplete/ranking"; import * as vscode from "vscode"; export class AutocompletePromptBuilder { @@ -19,10 +19,12 @@ export class AutocompletePromptBuilder { if (definitions[0]?.targetRange) { return { filepath: uri, - content: await this.ide.readRangeInFile( + contents: await this.ide.readRangeInFile( definitions[0].targetUri.fsPath, definitions[0].targetRange ), + range: definitions[0].targetRange, + score: 0.8 }; }