Merge branch 'nate/flight-tab-auto' into preview

This commit is contained in:
Nate Sesti 2024-02-28 00:01:42 -05:00
commit 08ac136089
24 changed files with 1122 additions and 581 deletions

76
core/autocomplete/ast.ts Normal file
View file

@ -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<Parser.Tree | undefined> {
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<Parser.SyntaxNode[] | undefined> {
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<string | undefined> {
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 ?? 0;
const endIndex =
lines.slice(0, e.line).join("\n").length +
lines[e.line]?.slice(0, e.character).length ?? 0;
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;
}

View file

@ -1,13 +1,17 @@
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";
import { rankSnippets } from "./ranking";
import { slidingWindowMatcher } from "./slidingWindow";
export function languageForFilepath(
filepath: string
@ -29,51 +33,9 @@ function formatExternalSnippet(
return lines.join("\n");
}
async function getAst(
filepath: string,
fileContents: string
): Promise<Parser.Tree | undefined> {
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<Parser.SyntaxNode[] | undefined> {
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;
}
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultiline(
function shouldCompleteMultilineAst(
treePath: Parser.SyntaxNode[],
cursorLine: number
): boolean {
@ -100,28 +62,12 @@ function shouldCompleteMultiline(
return false;
}
export async function constructAutocompletePrompt(
async function shouldCompleteMultiline(
filepath: string,
fullPrefix: string,
fullSuffix: string,
clipboardText: string,
language: AutocompleteLanguageInfo,
getDefinition: (
filepath: string,
line: number,
character: number
) => Promise<AutocompleteSnippet | undefined>,
options: TabAutocompleteOptions,
modelName: string
): Promise<{
prefix: string;
suffix: string;
useFim: boolean;
completeMultiline: boolean;
}> {
// Find external snippets
const snippets: AutocompleteSnippet[] = [];
fullSuffix: string
): Promise<boolean> {
// Use AST to determine whether to complete multiline
let treePath: Parser.SyntaxNode[] | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
@ -136,34 +82,75 @@ export async function constructAutocompletePrompt(
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);
completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine);
}
return completeMultiline;
}
export async function constructAutocompletePrompt(
filepath: string,
fullPrefix: string,
fullSuffix: string,
clipboardText: string,
language: AutocompleteLanguageInfo,
getDefinitions: (
document: RangeInFileWithContents,
cursorIndex: number
) => Promise<RangeInFileWithContents[]>,
options: TabAutocompleteOptions,
recentlyEditedRanges: RangeInFileWithContents[],
recentlyEditedDocuments: RangeInFileWithContents[],
modelName: string
): Promise<{
prefix: string;
suffix: string;
useFim: boolean;
completeMultiline: boolean;
}> {
// Find external snippets
let snippets: RangeInFileWithContents[] = [];
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);
if (!scope) return null;
return r;
})
.filter((s) => !!s)
);
snippets.push(...(recentlyEdited as any));
// Rank / order the snippets
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??
// 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 =
@ -180,5 +167,14 @@ export async function constructAutocompletePrompt(
);
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
return { prefix, suffix, useFim: true, completeMultiline };
return {
prefix,
suffix,
useFim: true,
completeMultiline: await shouldCompleteMultiline(
filepath,
fullPrefix,
fullSuffix
),
};
}

View file

@ -3,8 +3,11 @@ 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,
multilineCompletions: "auto",
slidingWindowPrefixPercentage: 0.75,
slidingWindowSize: 500,
};

View file

@ -0,0 +1,112 @@
import { RangeInFileWithContents } from "../commands/util";
export type AutocompleteSnippet = RangeInFileWithContents & {
score: number;
};
const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g;
function getSymbolsForSnippet(snippet: string): Set<string> {
const symbols = snippet
.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 jaccardSimilarity(a: string, b: string): number {
const aSet = getSymbolsForSnippet(a);
const bSet = getSymbolsForSnippet(b);
const union = new Set([...aSet, ...bSet]).size;
// Avoid division by zero
if (union === 0) {
return 0;
}
let intersection = 0;
for (const symbol of aSet) {
if (bSet.has(symbol)) {
intersection++;
}
}
return intersection / union;
}
/**
* Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array.
*/
export function rankSnippets(
ranges: RangeInFileWithContents[],
windowAroundCursor: string
): AutocompleteSnippet[] {
const snippets = ranges.map((snippet) => ({
score: jaccardSimilarity(snippet.contents, windowAroundCursor),
...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;
}

View file

@ -0,0 +1,5 @@
import { RangeInFileWithContents } from "../commands/util";
export type RecentlyEditedRange = RangeInFileWithContents & {
timestamp: number;
};

View file

@ -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<Chunk[]> {
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;
}

View file

@ -0,0 +1,59 @@
import { RangeInFileWithContents } from "../commands/util";
import { AutocompleteSnippet, jaccardSimilarity } from "./ranking";
function* slidingWindow(
content: string,
windowSize: number
): Generator<string> {
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");
}
}
/**
* Match by similarity over sliding windows of recent documents.
* @param recentDocuments
* @param prefix
* @param suffix
*/
export async function slidingWindowMatcher(
recentDocuments: RangeInFileWithContents[],
windowAroundCursor: string,
topN: number,
windowSize: number
): Promise<AutocompleteSnippet[]> {
// Sorted lowest similarity to highest
const topMatches: AutocompleteSnippet[] = [];
for (const { filepath, contents, range } of recentDocuments) {
for (const window of slidingWindow(contents, windowSize)) {
const score = jaccardSimilarity(window, windowAroundCursor);
// Insertion sort
let i = -1;
while (++i < topMatches.length && score > topMatches[i].score) {}
topMatches.splice(i + 1, 0, { filepath, contents, score, range });
if (topMatches.length > topN) {
topMatches.shift();
}
}
}
// TODO: convert the arbitrary window frame to some whole AST node?
return topMatches;
}

126
core/autocomplete/util.ts Normal file
View 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;
}
}
}

9
core/index.d.ts vendored
View file

@ -166,6 +166,11 @@ export interface RangeInFile {
range: Range;
}
export interface FileWithContents {
filepath: string;
contents: string;
}
export interface Range {
start: Position;
end: Position;
@ -580,7 +585,9 @@ export interface TabAutocompleteOptions {
maxSuffixPercentage: number;
prefixPercentage: number;
template?: string;
disableMultiLineCompletions?: boolean;
multilineCompletions: "always" | "never" | "auto";
slidingWindowPrefixPercentage: number;
slidingWindowSize: number;
}
export interface SerializedContinueConfig {

View file

@ -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

View file

@ -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."
}
},

View file

@ -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."
}
},

View file

@ -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."
}
},

View file

@ -1749,8 +1749,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."
}
},

View file

@ -0,0 +1,115 @@
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 { TabAutocompleteModel } from "../util/loadAutocompleteModel";
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();
constructor(private readonly configHandler: ConfigHandler, private readonly ide: IDE, private readonly tabAutocompleteModel: TabAutocompleteModel) {}
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 this.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,
this.tabAutocompleteModel,
this.ide
);
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;
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();
}
}
}

View file

@ -0,0 +1,196 @@
import { IDE, TabAutocompleteOptions } from "core";
import { AutocompleteLruCache } from "core/autocomplete/cache";
import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream";
import {
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 { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { ContinueCompletionProvider } from "./completionProvider";
import { getDefinitionsFromLsp } from "./lsp";
import { RecentlyEditedTracker } from "./recentlyEdited";
import { setupStatusBar, stopStatusBarLoading } from "./statusBar";
export interface AutocompleteOutcome {
accepted?: boolean;
time: number;
prompt: string;
completion: string;
modelProvider: string;
modelName: string;
completionOptions: any;
cacheHit: boolean;
}
const autocompleteCache = AutocompleteLruCache.get();
const recentlyEditedTracker = new RecentlyEditedTracker();
export async function getTabCompletion(
document: vscode.TextDocument,
pos: vscode.Position,
token: vscode.CancellationToken,
options: TabAutocompleteOptions,
tabAutocompleteModel: TabAutocompleteModel,
ide: IDE
): 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,
(document, cursorIndex) => getDefinitionsFromLsp(document, cursorIndex, ide),
options,
await recentlyEditedTracker.getRecentlyEditedRanges(),
await recentlyEditedTracker.getRecentlyEditedDocuments(),
llm.model
);
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;
}
}

View file

@ -0,0 +1,101 @@
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";
type GotoProviderName =
| "vscode.executeDefinitionProvider"
| "vscode.executeTypeDefinitionProvider"
| "vscode.executeDeclarationProvider"
| "vscode.executeImplementationProvider"
| "vscode.executeReferenceProvider";
async function executeGotoProvider(
uri: string,
line: number,
character: number,
name: GotoProviderName
): Promise<RangeInFile[]> {
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<RangeInFile[]> {
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,
ide: IDE
): Promise<RangeInFileWithContents[]> {
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 ide.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;
}

View file

@ -0,0 +1,139 @@
import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited";
import { RangeInFileWithContents } from "core/commands/util";
import * as vscode from "vscode";
interface VsCodeRecentlyEditedRange {
timestamp: number;
uri: vscode.Uri;
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) => {
const editedRange = {
uri: event.document.uri,
range: new vscode.Range(
new vscode.Position(change.range.start.line, 0),
new vscode.Position(change.range.end.line + 1, 0)
),
timestamp: Date.now(),
};
this.insertRange(editedRange);
});
this.insertDocument(event.document.uri);
});
setInterval(() => {
this.removeOldEntries();
}, 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
);
}
public async getRecentlyEditedRanges(): Promise<RecentlyEditedRange[]> {
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,
},
},
}))
);
}
public async getRecentlyEditedDocuments(): Promise<
RangeInFileWithContents[]
> {
return Promise.all(
this.recentlyEditedDocuments.map(async (entry) => {
const contents = await vscode.workspace.fs
.readFile(entry.uri)
.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,
},
},
};
})
);
}
}

View 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);
}
});
}

View file

@ -6,10 +6,10 @@ import * as vscode from "vscode";
import { IDE } from "core";
import { ConfigHandler } from "core/config/handler";
import { logDevData } from "core/util/devdata";
import { AutocompleteOutcome } from "./autocomplete/getTabCompletion";
import { ContinueGUIWebviewViewProvider } from "./debugPanel";
import { DiffManager } from "./diff/horizontal";
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
import { AutocompleteOutcome } from "./lang-server/completionProvider";
import { VsCodeWebviewProtocol } from "./webviewProtocol";
function getFullScreenTab() {

View file

@ -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";

View file

@ -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
};
}

View file

@ -1,476 +0,0 @@
import { IDE, TabAutocompleteOptions } from "core";
import { AutocompleteLruCache } from "core/autocomplete/cache";
import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream";
import {
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 { ConfigHandler } from "core/config/handler";
import { streamLines } from "core/diff/util";
import OpenAI from "core/llm/llms/OpenAI";
import { logDevData } from "core/util/devdata";
import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { AutocompletePromptBuilder } from "./autocompletePromptBuilder";
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);
}
});
}
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;
}
}
}
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();
private readonly promptBuilder: AutocompletePromptBuilder;
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly tabAutocompleteModel: TabAutocompleteModel
) {
this.promptBuilder = new AutocompletePromptBuilder(ide);
}
async 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 this.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,
this.promptBuilder.getDefinition.bind(this.promptBuilder),
options,
llm.model
);
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.disableMultiLineCompletions || !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;
}
}
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 this.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 this.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;
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();
}
}
}

View file

@ -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) {