🎨 organize vscode autocomplete a bit
This commit is contained in:
parent
598cd40016
commit
50dafd6c2e
10 changed files with 512 additions and 496 deletions
126
core/autocomplete/util.ts
Normal file
126
core/autocomplete/util.ts
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
export class ListenableGenerator<T> {
|
||||
private _source: AsyncGenerator<T>;
|
||||
private _buffer: T[] = [];
|
||||
private _listeners: Set<(value: T) => void> = new Set();
|
||||
private _isEnded: boolean = false;
|
||||
|
||||
constructor(source: AsyncGenerator<T>) {
|
||||
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<T> {
|
||||
try {
|
||||
for (const value of this._buffer) {
|
||||
yield value;
|
||||
}
|
||||
while (!this._isEnded) {
|
||||
let resolve: (value: any) => void;
|
||||
let promise = new Promise<T>((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<string> | undefined;
|
||||
static pendingGeneratorPrefix: string | undefined;
|
||||
static pendingCompletion: string = "";
|
||||
|
||||
private static _createListenableGenerator(
|
||||
gen: AsyncGenerator<string>,
|
||||
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<string>
|
||||
): AsyncGenerator<string> {
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
4
docs/static/schemas/config.json
vendored
4
docs/static/schemas/config.json
vendored
|
|
@ -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."
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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."
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
|
|||
109
extensions/vscode/src/autocomplete/completionProvider.ts
Normal file
109
extensions/vscode/src/autocomplete/completionProvider.ts
Normal file
|
|
@ -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<string> = new Set();
|
||||
|
||||
public async provideInlineCompletionItems(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
context: vscode.InlineCompletionContext,
|
||||
token: vscode.CancellationToken
|
||||
//@ts-ignore
|
||||
): ProviderResult<InlineCompletionItem[] | InlineCompletionList> {
|
||||
// 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<boolean>("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();
|
||||
}
|
||||
}
|
||||
}
|
||||
214
extensions/vscode/src/autocomplete/getTabCompletion.ts
Normal file
214
extensions/vscode/src/autocomplete/getTabCompletion.ts
Normal file
|
|
@ -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<AutocompleteSnippet | undefined> {
|
||||
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<AutocompleteOutcome | undefined> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
51
extensions/vscode/src/autocomplete/statusBar.ts
Normal file
51
extensions/vscode/src/autocomplete/statusBar.ts
Normal file
|
|
@ -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<boolean>("enableTabAutocomplete");
|
||||
statusBarItem.dispose();
|
||||
setupStatusBar(enabled);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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<boolean>("enableTabAutocomplete");
|
||||
statusBarItem.dispose();
|
||||
setupStatusBar(enabled);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function getDefinition(
|
||||
uri: string,
|
||||
line: number,
|
||||
character: number
|
||||
): Promise<AutocompleteSnippet | undefined> {
|
||||
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<T> {
|
||||
private _source: AsyncGenerator<T>;
|
||||
private _buffer: T[] = [];
|
||||
private _listeners: Set<(value: T) => void> = new Set();
|
||||
private _isEnded: boolean = false;
|
||||
|
||||
constructor(source: AsyncGenerator<T>) {
|
||||
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<T> {
|
||||
try {
|
||||
for (const value of this._buffer) {
|
||||
yield value;
|
||||
}
|
||||
while (!this._isEnded) {
|
||||
let resolve: (value: any) => void;
|
||||
let promise = new Promise<T>((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<string> | undefined;
|
||||
static pendingGeneratorPrefix: string | undefined;
|
||||
static pendingCompletion: string = "";
|
||||
|
||||
private static _createListenableGenerator(
|
||||
gen: AsyncGenerator<string>,
|
||||
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<string>
|
||||
): AsyncGenerator<string> {
|
||||
// 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<AutocompleteOutcome | undefined> {
|
||||
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<string> = new Set();
|
||||
|
||||
public async provideInlineCompletionItems(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
context: vscode.InlineCompletionContext,
|
||||
token: vscode.CancellationToken
|
||||
//@ts-ignore
|
||||
): ProviderResult<InlineCompletionItem[] | InlineCompletionList> {
|
||||
// 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<boolean>("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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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==
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue