Merge pull request #2768 from continuedev/nate/autocomplete-cleaning
Refactor autocomplete
This commit is contained in:
commit
377513ad66
73 changed files with 2641 additions and 1641 deletions
304
core/autocomplete/CompletionProvider.ts
Normal file
304
core/autocomplete/CompletionProvider.ts
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { IDE, ILLM } from "../index.js";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
||||
import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js";
|
||||
import { constructAutocompletePrompt } from "./constructPrompt.js";
|
||||
import { AutocompleteSnippet } from "./context/ranking/index.js";
|
||||
import { postprocessCompletion } from "./postprocessing/index.js";
|
||||
// @prettier-ignore
|
||||
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
|
||||
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
|
||||
import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
|
||||
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
|
||||
import { shouldPrefilter } from "./prefiltering/index.js";
|
||||
import { renderPrompt } from "./templating/index.js";
|
||||
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
|
||||
import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js";
|
||||
import AutocompleteLruCache from "./util/AutocompleteLruCache.js";
|
||||
import { HelperVars } from "./util/HelperVars.js";
|
||||
import { AutocompleteInput, AutocompleteOutcome } from "./util/types.js";
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
|
||||
// Errors that can be expected on occasion even during normal functioning should not be shown.
|
||||
// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
|
||||
const ERRORS_TO_IGNORE = [
|
||||
// From Ollama
|
||||
"unexpected server status",
|
||||
];
|
||||
|
||||
export type GetLspDefinitionsFunction = (
|
||||
filepath: string,
|
||||
contents: string,
|
||||
cursorIndex: number,
|
||||
ide: IDE,
|
||||
lang: AutocompleteLanguageInfo,
|
||||
) => Promise<AutocompleteSnippet[]>;
|
||||
|
||||
export class CompletionProvider {
|
||||
private autocompleteCache = AutocompleteLruCache.get();
|
||||
public errorsShown: Set<string> = new Set();
|
||||
private bracketMatchingService = new BracketMatchingService();
|
||||
private debouncer = new AutocompleteDebouncer();
|
||||
private completionStreamer: CompletionStreamer;
|
||||
private loggingService = new AutocompleteLoggingService();
|
||||
private contextRetrievalService: ContextRetrievalService;
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
|
||||
private readonly _onError: (e: any) => void,
|
||||
private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
|
||||
) {
|
||||
this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
|
||||
this.contextRetrievalService = new ContextRetrievalService(this.ide);
|
||||
}
|
||||
|
||||
private async _prepareLlm(): Promise<ILLM | undefined> {
|
||||
const llm = await this._injectedGetLlm();
|
||||
|
||||
if (!llm) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Ignore empty API keys for Mistral since we currently write
|
||||
// a template provider without one during onboarding
|
||||
if (llm.providerName === "mistral" && llm.apiKey === "") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Set temperature (but don't override)
|
||||
if (llm.completionOptions.temperature === undefined) {
|
||||
llm.completionOptions.temperature = 0.01;
|
||||
}
|
||||
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
} else if (
|
||||
llm.providerName === "free-trial" &&
|
||||
llm.model !== TRIAL_FIM_MODEL
|
||||
) {
|
||||
llm.model = TRIAL_FIM_MODEL;
|
||||
}
|
||||
|
||||
return llm;
|
||||
}
|
||||
|
||||
private onError(e: any) {
|
||||
if (
|
||||
ERRORS_TO_IGNORE.some((err) =>
|
||||
typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.warn("Error generating autocompletion: ", e);
|
||||
if (!this.errorsShown.has(e.message)) {
|
||||
this.errorsShown.add(e.message);
|
||||
this._onError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this.loggingService.cancel();
|
||||
}
|
||||
|
||||
public accept(completionId: string) {
|
||||
const outcome = this.loggingService.accept(completionId);
|
||||
if (!outcome) {
|
||||
return;
|
||||
}
|
||||
this.bracketMatchingService.handleAcceptedCompletion(
|
||||
outcome.completion,
|
||||
outcome.filepath,
|
||||
);
|
||||
}
|
||||
|
||||
public markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
|
||||
this.loggingService.markDisplayed(completionId, outcome);
|
||||
}
|
||||
|
||||
private async _getAutocompleteOptions() {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
const options = {
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
...config.tabAutocompleteOptions,
|
||||
};
|
||||
return options;
|
||||
}
|
||||
|
||||
public async provideInlineCompletionItems(
|
||||
input: AutocompleteInput,
|
||||
token: AbortSignal | undefined,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
const options = await this._getAutocompleteOptions();
|
||||
|
||||
// Debounce
|
||||
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const llm = await this._prepareLlm();
|
||||
if (!llm) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const helper = await HelperVars.create(
|
||||
input,
|
||||
options,
|
||||
llm.model,
|
||||
this.ide,
|
||||
);
|
||||
|
||||
if (await shouldPrefilter(helper, this.ide)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Create abort signal if not given
|
||||
if (!token) {
|
||||
const controller = this.loggingService.createAbortController(
|
||||
input.completionId,
|
||||
);
|
||||
token = controller.signal;
|
||||
}
|
||||
|
||||
//////////
|
||||
|
||||
// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems,
|
||||
// or they might separately track recently edited ranges)
|
||||
const extraSnippets = await this._getExtraSnippets(helper);
|
||||
|
||||
let snippets = await constructAutocompletePrompt(
|
||||
helper,
|
||||
extraSnippets,
|
||||
this.contextRetrievalService,
|
||||
);
|
||||
|
||||
const { prompt, prefix, suffix, completionOptions } = renderPrompt(
|
||||
snippets,
|
||||
await this.ide.getWorkspaceDirs(),
|
||||
helper,
|
||||
);
|
||||
|
||||
// Completion
|
||||
let completion: string | undefined = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cachedCompletion = helper.options.useCache
|
||||
? await cache.get(helper.prunedPrefix)
|
||||
: undefined;
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
} else {
|
||||
const multiline =
|
||||
!helper.options.transform || shouldCompleteMultiline(helper);
|
||||
|
||||
const completionStream =
|
||||
this.completionStreamer.streamCompletionWithFilters(
|
||||
token,
|
||||
llm,
|
||||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
multiline,
|
||||
completionOptions,
|
||||
helper,
|
||||
);
|
||||
|
||||
for await (const update of completionStream) {
|
||||
completion += update;
|
||||
}
|
||||
|
||||
// Don't postprocess if aborted
|
||||
if (token.aborted) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const processedCompletion = helper.options.transform
|
||||
? postprocessCompletion({
|
||||
completion,
|
||||
prefix: helper.prunedPrefix,
|
||||
suffix: helper.prunedSuffix,
|
||||
llm,
|
||||
})
|
||||
: completion;
|
||||
|
||||
completion = processedCompletion;
|
||||
}
|
||||
|
||||
if (!completion) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const outcome: AutocompleteOutcome = {
|
||||
time: Date.now() - startTime,
|
||||
completion,
|
||||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
modelProvider: llm.providerName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
filepath: helper.filepath,
|
||||
completionId: helper.input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(helper.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
...helper.options,
|
||||
};
|
||||
|
||||
//////////
|
||||
|
||||
// Do some stuff later so as not to block return. Latency matters
|
||||
const completionToCache = outcome.completion;
|
||||
setTimeout(async () => {
|
||||
if (!outcome.cacheHit) {
|
||||
(await this.autocompleteCache).put(outcome.prefix, completionToCache);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
return outcome;
|
||||
} catch (e: any) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
this.loggingService.deleteAbortController(input.completionId);
|
||||
}
|
||||
}
|
||||
|
||||
private async _getExtraSnippets(
|
||||
helper: HelperVars,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
let extraSnippets = helper.options.useOtherFiles
|
||||
? ((await Promise.race([
|
||||
this.getDefinitionsFromLsp(
|
||||
helper.input.filepath,
|
||||
helper.fullPrefix + helper.fullSuffix,
|
||||
helper.fullPrefix.length,
|
||||
this.ide,
|
||||
helper.lang,
|
||||
),
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => resolve([]), 100);
|
||||
}),
|
||||
])) as AutocompleteSnippet[])
|
||||
: [];
|
||||
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
if (helper.options.onlyMyCode) {
|
||||
extraSnippets = extraSnippets.filter((snippet) => {
|
||||
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
|
||||
});
|
||||
}
|
||||
|
||||
return extraSnippets;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
import { IDE, Location } from "../index.js";
|
||||
import { LANGUAGES } from "./languages.js";
|
||||
import { getSymbolsForSnippet } from "./ranking.js";
|
||||
|
||||
interface FileInfo {
|
||||
filepath: string;
|
||||
}
|
||||
|
||||
export class NearbyDefinitionsService {
|
||||
static N = 10;
|
||||
|
||||
constructor(private readonly ide: IDE) {}
|
||||
|
||||
async getDefinitionsForLine(filepath: string, line: number) {
|
||||
const lineContent = await this.ide.readRangeInFile(filepath, {
|
||||
start: {
|
||||
line,
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: line + 1,
|
||||
character: 0,
|
||||
},
|
||||
});
|
||||
|
||||
// Remove keywords
|
||||
const lang = LANGUAGES[filepath.split(".").slice(-1)[0]];
|
||||
const symbols = Array.from(getSymbolsForSnippet(lineContent))
|
||||
.filter((s) => s.length > 0)
|
||||
.filter((s) => !(lang && lang?.stopWords?.includes(s)));
|
||||
|
||||
return Promise.all(
|
||||
symbols.map((s) => {
|
||||
const character = lineContent.indexOf(s);
|
||||
const pos: Location = {
|
||||
filepath,
|
||||
position: {
|
||||
line,
|
||||
character,
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
9
core/autocomplete/READEME.md
Normal file
9
core/autocomplete/READEME.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
TODO
|
||||
|
||||
- The generator reuse thing isn't working it seems
|
||||
|
||||
Tests for context:
|
||||
|
||||
- You need a static set of files to test. Ideally you don't have to rewrite the exact same files every time you want to make a new test.
|
||||
- So put some example files in a few folders. There should be a folder for each language I think.
|
||||
- You should definitely test each of the services separately
|
||||
53
core/autocomplete/classification/shouldCompleteMultiline.ts
Normal file
53
core/autocomplete/classification/shouldCompleteMultiline.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
function isMidlineCompletion(prefix: string, suffix: string): boolean {
|
||||
return !suffix.startsWith("\n");
|
||||
}
|
||||
|
||||
function shouldCompleteMultilineBasedOnLanguage(
|
||||
language: AutocompleteLanguageInfo,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
) {
|
||||
return language.useMultiline?.({ prefix, suffix }) ?? true;
|
||||
}
|
||||
|
||||
export function shouldCompleteMultiline(helper: HelperVars) {
|
||||
switch (helper.options.multilineCompletions) {
|
||||
case "always":
|
||||
return true;
|
||||
case "never":
|
||||
return false;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Always single-line if an intellisense option is selected
|
||||
if (helper.input.selectedCompletionInfo) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// // Don't complete multi-line if you are mid-line
|
||||
// if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// Don't complete multi-line for single-line comments
|
||||
if (
|
||||
helper.lang.singleLineComment &&
|
||||
helper.fullPrefix
|
||||
.split("\n")
|
||||
.slice(-1)[0]
|
||||
?.trimStart()
|
||||
.startsWith(helper.lang.singleLineComment)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return shouldCompleteMultilineBasedOnLanguage(
|
||||
helper.lang,
|
||||
helper.prunedPrefix,
|
||||
helper.prunedSuffix,
|
||||
);
|
||||
}
|
||||
|
|
@ -1,811 +0,0 @@
|
|||
import ignore from "ignore";
|
||||
import OpenAI from "openai";
|
||||
import path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
||||
import { streamLines } from "../diff/util.js";
|
||||
import {
|
||||
IDE,
|
||||
ILLM,
|
||||
ModelProvider,
|
||||
Position,
|
||||
Range,
|
||||
TabAutocompleteOptions,
|
||||
} from "../index.js";
|
||||
import { logDevData } from "../util/devdata.js";
|
||||
import { getBasename, getLastNPathParts } from "../util/index.js";
|
||||
import {
|
||||
COUNT_COMPLETION_REJECTED_AFTER,
|
||||
DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
} from "../util/parameters.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { getRangeInString } from "../util/ranges.js";
|
||||
|
||||
import AutocompleteLruCache from "./cache.js";
|
||||
import {
|
||||
constructAutocompletePrompt,
|
||||
languageForFilepath,
|
||||
} from "./constructPrompt.js";
|
||||
import { isOnlyWhitespace } from "./filter.js";
|
||||
import { AutocompleteLanguageInfo } from "./languages.js";
|
||||
import { postprocessCompletion } from "./postprocessing.js";
|
||||
import { AutocompleteSnippet } from "./ranking.js";
|
||||
import { RecentlyEditedRange } from "./recentlyEdited.js";
|
||||
import { RootPathContextService } from "./services/RootPathContextService.js";
|
||||
import {
|
||||
avoidPathLineAndEmptyComments,
|
||||
skipPrefixes,
|
||||
stopAtLines,
|
||||
stopAtRepeatingLines,
|
||||
stopAtSimilarLine,
|
||||
streamWithNewLines,
|
||||
} from "./streamTransforms/lineStream.js";
|
||||
import { getTemplateForModel } from "./templates.js";
|
||||
import { GeneratorReuseManager } from "./util.js";
|
||||
// @prettier-ignore
|
||||
import Handlebars from "handlebars";
|
||||
import { getConfigJsonPath } from "../util/paths.js";
|
||||
import { BracketMatchingService } from "./services/BracketMatchingService.js";
|
||||
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
|
||||
import { stopAtStopTokens } from "./streamTransforms/charStream.js";
|
||||
|
||||
export interface AutocompleteInput {
|
||||
completionId: string;
|
||||
filepath: string;
|
||||
pos: Position;
|
||||
recentlyEditedFiles: RangeInFileWithContents[];
|
||||
recentlyEditedRanges: RecentlyEditedRange[];
|
||||
clipboardText: string;
|
||||
// Used for notebook files
|
||||
manuallyPassFileContents?: string;
|
||||
// Used for VS Code git commit input box
|
||||
manuallyPassPrefix?: string;
|
||||
selectedCompletionInfo?: {
|
||||
text: string;
|
||||
range: Range;
|
||||
};
|
||||
injectDetails?: string;
|
||||
}
|
||||
|
||||
export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
||||
accepted?: boolean;
|
||||
time: number;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
modelProvider: string;
|
||||
modelName: string;
|
||||
completionOptions: any;
|
||||
cacheHit: boolean;
|
||||
filepath: string;
|
||||
gitRepo?: string;
|
||||
completionId: string;
|
||||
uniqueId: string;
|
||||
}
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
|
||||
const DOUBLE_NEWLINE = "\n\n";
|
||||
const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n";
|
||||
// TODO: Do we want to stop completions when reaching a `/src/` string?
|
||||
const SRC_DIRECTORY = "/src/";
|
||||
// Starcoder2 tends to output artifacts starting with the letter "t"
|
||||
const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
|
||||
const PYTHON_ENCODING = "#- coding: utf-8";
|
||||
const CODE_BLOCK_END = "```";
|
||||
|
||||
const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
|
||||
const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END];
|
||||
|
||||
// Errors that can be expected on occasion even during normal functioning should not be shown.
|
||||
// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
|
||||
const ERRORS_TO_IGNORE = [
|
||||
// From Ollama
|
||||
"unexpected server status",
|
||||
];
|
||||
|
||||
const LOCAL_PROVIDERS: ModelProvider[] = [
|
||||
"ollama",
|
||||
"lmstudio",
|
||||
"llama.cpp",
|
||||
"llamafile",
|
||||
"text-gen-webui",
|
||||
];
|
||||
|
||||
function formatExternalSnippet(
|
||||
filepath: string,
|
||||
snippet: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
) {
|
||||
const comment = language.singleLineComment;
|
||||
const lines = [
|
||||
`${comment} Path: ${getBasename(filepath)}`,
|
||||
...snippet
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => `${comment} ${line}`),
|
||||
comment,
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export type GetLspDefinitionsFunction = (
|
||||
filepath: string,
|
||||
contents: string,
|
||||
cursorIndex: number,
|
||||
ide: IDE,
|
||||
lang: AutocompleteLanguageInfo,
|
||||
) => Promise<AutocompleteSnippet[]>;
|
||||
|
||||
export class CompletionProvider {
|
||||
private static debounceTimeout: NodeJS.Timeout | undefined = undefined;
|
||||
private static debouncing = false;
|
||||
private static lastUUID: string | undefined = undefined;
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly getLlm: () => Promise<ILLM | undefined>,
|
||||
private readonly _onError: (e: any) => void,
|
||||
private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
|
||||
) {
|
||||
this.generatorReuseManager = new GeneratorReuseManager(
|
||||
this.onError.bind(this),
|
||||
);
|
||||
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
|
||||
this.rootPathContextService = new RootPathContextService(
|
||||
this.importDefinitionsService,
|
||||
this.ide,
|
||||
);
|
||||
}
|
||||
|
||||
private importDefinitionsService: ImportDefinitionsService;
|
||||
private rootPathContextService: RootPathContextService;
|
||||
private generatorReuseManager: GeneratorReuseManager;
|
||||
private autocompleteCache = AutocompleteLruCache.get();
|
||||
public errorsShown: Set<string> = new Set();
|
||||
private bracketMatchingService = new BracketMatchingService();
|
||||
// private nearbyDefinitionsService = new NearbyDefinitionsService();
|
||||
|
||||
private onError(e: any) {
|
||||
console.warn("Error generating autocompletion: ", e);
|
||||
if (
|
||||
ERRORS_TO_IGNORE.some((err) =>
|
||||
typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!this.errorsShown.has(e.message)) {
|
||||
this.errorsShown.add(e.message);
|
||||
this._onError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this._abortControllers.forEach((abortController, id) => {
|
||||
abortController.abort();
|
||||
});
|
||||
this._abortControllers.clear();
|
||||
}
|
||||
|
||||
// Key is completionId
|
||||
private _abortControllers = new Map<string, AbortController>();
|
||||
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
|
||||
private _outcomes = new Map<string, AutocompleteOutcome>();
|
||||
|
||||
public accept(completionId: string) {
|
||||
if (this._logRejectionTimeouts.has(completionId)) {
|
||||
clearTimeout(this._logRejectionTimeouts.get(completionId));
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
}
|
||||
|
||||
if (this._outcomes.has(completionId)) {
|
||||
const outcome = this._outcomes.get(completionId)!;
|
||||
outcome.accepted = true;
|
||||
logDevData("autocomplete", outcome);
|
||||
void Telemetry.capture(
|
||||
"autocomplete",
|
||||
{
|
||||
accepted: outcome.accepted,
|
||||
modelName: outcome.modelName,
|
||||
modelProvider: outcome.modelProvider,
|
||||
time: outcome.time,
|
||||
cacheHit: outcome.cacheHit,
|
||||
},
|
||||
true,
|
||||
);
|
||||
this._outcomes.delete(completionId);
|
||||
|
||||
this.bracketMatchingService.handleAcceptedCompletion(
|
||||
outcome.completion,
|
||||
outcome.filepath,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public cancelRejectionTimeout(completionId: string) {
|
||||
if (this._logRejectionTimeouts.has(completionId)) {
|
||||
clearTimeout(this._logRejectionTimeouts.get(completionId)!);
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
}
|
||||
|
||||
if (this._outcomes.has(completionId)) {
|
||||
this._outcomes.delete(completionId);
|
||||
}
|
||||
}
|
||||
|
||||
public async provideInlineCompletionItems(
|
||||
input: AutocompleteInput,
|
||||
token: AbortSignal | undefined,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
try {
|
||||
// Debounce
|
||||
const uuid = uuidv4();
|
||||
CompletionProvider.lastUUID = uuid;
|
||||
|
||||
const config = await this.configHandler.loadConfig();
|
||||
const options = {
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
...config.tabAutocompleteOptions,
|
||||
};
|
||||
|
||||
// Check whether we're in the continue config.json file
|
||||
if (input.filepath === getConfigJsonPath()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Check whether autocomplete is disabled for this file
|
||||
if (options.disableInFiles) {
|
||||
// Relative path needed for `ignore`
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
let filepath = input.filepath;
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const relativePath = path.relative(workspaceDir, filepath);
|
||||
const relativePathBase = relativePath.split(path.sep).at(0);
|
||||
const isInWorkspace = !path.isAbsolute(relativePath) && relativePathBase !== "..";
|
||||
if (isInWorkspace) {
|
||||
filepath = path.relative(workspaceDir, filepath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Worst case we can check filetype glob patterns
|
||||
if (filepath === input.filepath) {
|
||||
filepath = getBasename(filepath);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const pattern = ignore.default().add(options.disableInFiles);
|
||||
if (pattern.ignores(filepath)) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Create abort signal if not given
|
||||
if (!token) {
|
||||
const controller = new AbortController();
|
||||
token = controller.signal;
|
||||
this._abortControllers.set(input.completionId, controller);
|
||||
}
|
||||
|
||||
// Allow disabling autocomplete from config.json
|
||||
if (options.disable) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Debounce
|
||||
if (CompletionProvider.debouncing) {
|
||||
CompletionProvider.debounceTimeout?.refresh();
|
||||
const lastUUID = await new Promise((resolve) =>
|
||||
setTimeout(() => {
|
||||
resolve(CompletionProvider.lastUUID);
|
||||
}, options.debounceDelay),
|
||||
);
|
||||
if (uuid !== lastUUID) {
|
||||
return undefined;
|
||||
}
|
||||
} else {
|
||||
CompletionProvider.debouncing = true;
|
||||
CompletionProvider.debounceTimeout = setTimeout(async () => {
|
||||
CompletionProvider.debouncing = false;
|
||||
}, options.debounceDelay);
|
||||
}
|
||||
|
||||
// Get completion
|
||||
const llm = await this.getLlm();
|
||||
|
||||
if (!llm) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Ignore empty API keys for Mistral since we currently write
|
||||
// a template provider without one during onboarding
|
||||
if (llm.providerName === "mistral" && llm.apiKey === "") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Set temperature (but don't overrride)
|
||||
if (llm.completionOptions.temperature === undefined) {
|
||||
llm.completionOptions.temperature = 0.01;
|
||||
}
|
||||
|
||||
if (
|
||||
!config.tabAutocompleteOptions?.maxPromptTokens &&
|
||||
LOCAL_PROVIDERS.includes(llm.providerName)
|
||||
) {
|
||||
options.maxPromptTokens = 500;
|
||||
}
|
||||
|
||||
const outcome = await this.getTabCompletion(token, options, llm, input);
|
||||
|
||||
if (!outcome?.completion) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* This check is most likely not needed because we do trim the LLM output
|
||||
* elsewhere in the code. That said, I'm not yet confident enough to
|
||||
* remove this.
|
||||
*/
|
||||
if (options.transform && isOnlyWhitespace(outcome.completion)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Do some stuff later so as not to block return. Latency matters
|
||||
const completionToCache = outcome.completion;
|
||||
setTimeout(async () => {
|
||||
if (!outcome.cacheHit) {
|
||||
(await this.autocompleteCache).put(outcome.prefix, completionToCache);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
return outcome;
|
||||
} catch (e: any) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
this._abortControllers.delete(input.completionId);
|
||||
}
|
||||
}
|
||||
|
||||
_lastDisplayedCompletion: { id: string; displayedAt: number } | undefined =
|
||||
undefined;
|
||||
|
||||
markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
|
||||
const logRejectionTimeout = setTimeout(() => {
|
||||
// Wait 10 seconds, then assume it wasn't accepted
|
||||
outcome.accepted = false;
|
||||
logDevData("autocomplete", outcome);
|
||||
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
|
||||
void Telemetry.capture(
|
||||
"autocomplete",
|
||||
{
|
||||
accepted: restOfOutcome.accepted,
|
||||
cacheHit: restOfOutcome.cacheHit,
|
||||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0],
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
multilineCompletions: restOfOutcome.multilineCompletions,
|
||||
time: restOfOutcome.time,
|
||||
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
|
||||
useRootPathContext: restOfOutcome.useRootPathContext,
|
||||
},
|
||||
true,
|
||||
);
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
}, COUNT_COMPLETION_REJECTED_AFTER);
|
||||
this._outcomes.set(completionId, outcome);
|
||||
this._logRejectionTimeouts.set(completionId, logRejectionTimeout);
|
||||
|
||||
// If the previously displayed completion is still waiting for rejection,
|
||||
// and this one is a continuation of that (the outcome.completion is the same modulo prefix)
|
||||
// then we should cancel the rejection timeout
|
||||
const previous = this._lastDisplayedCompletion;
|
||||
const now = Date.now();
|
||||
if (previous && this._logRejectionTimeouts.has(previous.id)) {
|
||||
const previousOutcome = this._outcomes.get(previous.id);
|
||||
const c1 = previousOutcome?.completion.split("\n")[0] ?? "";
|
||||
const c2 = outcome.completion.split("\n")[0];
|
||||
if (
|
||||
previousOutcome &&
|
||||
(c1.endsWith(c2) ||
|
||||
c2.endsWith(c1) ||
|
||||
c1.startsWith(c2) ||
|
||||
c2.startsWith(c1))
|
||||
) {
|
||||
this.cancelRejectionTimeout(previous.id);
|
||||
} else if (now - previous.displayedAt < 500) {
|
||||
// If a completion isn't shown for more than
|
||||
this.cancelRejectionTimeout(previous.id);
|
||||
}
|
||||
}
|
||||
|
||||
this._lastDisplayedCompletion = {
|
||||
id: completionId,
|
||||
displayedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
private isMultiline({
|
||||
language,
|
||||
prefix,
|
||||
suffix,
|
||||
selectedCompletionInfo,
|
||||
multilineCompletions,
|
||||
completeMultiline,
|
||||
}: {
|
||||
language: AutocompleteLanguageInfo;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"];
|
||||
multilineCompletions: TabAutocompleteOptions["multilineCompletions"];
|
||||
completeMultiline: boolean;
|
||||
}) {
|
||||
let langMultilineDecision = language.useMultiline?.({ prefix, suffix });
|
||||
if (langMultilineDecision) {
|
||||
return langMultilineDecision;
|
||||
} else {
|
||||
return (
|
||||
!selectedCompletionInfo && // Only ever single-line if using intellisense selected value
|
||||
multilineCompletions !== "never" &&
|
||||
(multilineCompletions === "always" || completeMultiline)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getTabCompletion(
|
||||
token: AbortSignal,
|
||||
options: TabAutocompleteOptions,
|
||||
llm: ILLM,
|
||||
input: AutocompleteInput,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
const startTime = Date.now();
|
||||
|
||||
const {
|
||||
filepath,
|
||||
pos,
|
||||
recentlyEditedFiles,
|
||||
recentlyEditedRanges,
|
||||
clipboardText,
|
||||
manuallyPassFileContents,
|
||||
manuallyPassPrefix,
|
||||
} = input;
|
||||
const fileContents =
|
||||
manuallyPassFileContents ?? (await this.ide.readFile(filepath));
|
||||
const fileLines = fileContents.split("\n");
|
||||
|
||||
// Filter
|
||||
const lang = languageForFilepath(filepath);
|
||||
|
||||
if (options.transform) {
|
||||
const line = fileLines[pos.line] ?? "";
|
||||
for (const endOfLine of lang.endOfLine) {
|
||||
if (line.endsWith(endOfLine) && pos.character >= line.length) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Model
|
||||
if (!llm) {
|
||||
return;
|
||||
}
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
} else if (
|
||||
llm.providerName === "free-trial" &&
|
||||
llm.model !== TRIAL_FIM_MODEL
|
||||
) {
|
||||
llm.model = TRIAL_FIM_MODEL;
|
||||
}
|
||||
|
||||
// Prompt
|
||||
let fullPrefix =
|
||||
getRangeInString(fileContents, {
|
||||
start: { line: 0, character: 0 },
|
||||
end: input.selectedCompletionInfo?.range.start ?? pos,
|
||||
}) + (input.selectedCompletionInfo?.text ?? "");
|
||||
|
||||
if (input.injectDetails) {
|
||||
const lines = fullPrefix.split("\n");
|
||||
fullPrefix = `${lines.slice(0, -1).join("\n")}\n${lang.singleLineComment
|
||||
} ${input.injectDetails
|
||||
.split("\n")
|
||||
.join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`;
|
||||
}
|
||||
|
||||
const fullSuffix = getRangeInString(fileContents, {
|
||||
start: pos,
|
||||
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
|
||||
});
|
||||
|
||||
// First non-whitespace line below the cursor
|
||||
let lineBelowCursor = "";
|
||||
let i = 1;
|
||||
while (
|
||||
lineBelowCursor.trim() === "" &&
|
||||
pos.line + i <= fileLines.length - 1
|
||||
) {
|
||||
lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)];
|
||||
i++;
|
||||
}
|
||||
|
||||
let extrasSnippets = options.useOtherFiles
|
||||
? ((await Promise.race([
|
||||
this.getDefinitionsFromLsp(
|
||||
filepath,
|
||||
fullPrefix + fullSuffix,
|
||||
fullPrefix.length,
|
||||
this.ide,
|
||||
lang,
|
||||
),
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => resolve([]), 100);
|
||||
}),
|
||||
])) as AutocompleteSnippet[])
|
||||
: [];
|
||||
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
if (options.onlyMyCode) {
|
||||
extrasSnippets = extrasSnippets.filter((snippet) => {
|
||||
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
|
||||
});
|
||||
}
|
||||
|
||||
let { prefix, suffix, completeMultiline, snippets } =
|
||||
await constructAutocompletePrompt(
|
||||
filepath,
|
||||
pos.line,
|
||||
fullPrefix,
|
||||
fullSuffix,
|
||||
clipboardText,
|
||||
lang,
|
||||
options,
|
||||
recentlyEditedRanges,
|
||||
recentlyEditedFiles,
|
||||
llm.model,
|
||||
extrasSnippets,
|
||||
this.importDefinitionsService,
|
||||
this.rootPathContextService,
|
||||
);
|
||||
|
||||
// If prefix is manually passed
|
||||
if (manuallyPassPrefix) {
|
||||
prefix = manuallyPassPrefix;
|
||||
suffix = "";
|
||||
}
|
||||
|
||||
// Template prompt
|
||||
const {
|
||||
template,
|
||||
completionOptions,
|
||||
compilePrefixSuffix = undefined,
|
||||
} = options.template
|
||||
? { template: options.template, completionOptions: {} }
|
||||
: getTemplateForModel(llm.model);
|
||||
|
||||
let prompt: string;
|
||||
const filename = getBasename(filepath);
|
||||
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
|
||||
|
||||
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
|
||||
// into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint
|
||||
if (compilePrefixSuffix) {
|
||||
[prefix, suffix] = compilePrefixSuffix(
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof template === "string") {
|
||||
const compiledTemplate = Handlebars.compile(template);
|
||||
|
||||
// Format snippets as comments and prepend to prefix
|
||||
const formattedSnippets = snippets
|
||||
.map((snippet) =>
|
||||
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
|
||||
)
|
||||
.join("\n");
|
||||
if (formattedSnippets.length > 0) {
|
||||
prefix = `${formattedSnippets}\n\n${prefix}`;
|
||||
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
|
||||
// If it's an empty file, include the file name as a comment
|
||||
prefix = `${lang.singleLineComment} ${getLastNPathParts(
|
||||
filepath,
|
||||
2,
|
||||
)}\n${prefix}`;
|
||||
}
|
||||
|
||||
prompt = compiledTemplate({
|
||||
prefix,
|
||||
suffix,
|
||||
filename,
|
||||
reponame,
|
||||
language: lang.name,
|
||||
});
|
||||
} else {
|
||||
// Let the template function format snippets
|
||||
prompt = template(
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
lang.name,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
// Completion
|
||||
let completion = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cachedCompletion = options.useCache
|
||||
? await cache.get(prefix)
|
||||
: undefined;
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
} else {
|
||||
const stop = [
|
||||
...(completionOptions?.stop || []),
|
||||
// ...multilineStops,
|
||||
...commonStops,
|
||||
...(llm.model.toLowerCase().includes("starcoder2")
|
||||
? STARCODER2_T_ARTIFACTS
|
||||
: []),
|
||||
...(lang.stopWords ?? []),
|
||||
// ...lang.topLevelKeywords.map((word) => `\n${word}`),
|
||||
];
|
||||
|
||||
const multiline =
|
||||
!options.transform ||
|
||||
this.isMultiline({
|
||||
multilineCompletions: options.multilineCompletions,
|
||||
language: lang,
|
||||
selectedCompletionInfo: input.selectedCompletionInfo,
|
||||
prefix,
|
||||
suffix,
|
||||
completeMultiline,
|
||||
});
|
||||
|
||||
// Try to reuse pending requests if what the user typed matches start of completion
|
||||
const generator = this.generatorReuseManager.getGenerator(
|
||||
prefix,
|
||||
() =>
|
||||
llm.supportsFim()
|
||||
? llm.streamFim(prefix, suffix, {
|
||||
...completionOptions,
|
||||
stop,
|
||||
})
|
||||
: llm.streamComplete(prompt, {
|
||||
...completionOptions,
|
||||
raw: true,
|
||||
stop,
|
||||
}),
|
||||
multiline,
|
||||
);
|
||||
|
||||
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
|
||||
const fullStop = () =>
|
||||
this.generatorReuseManager.currentGenerator?.cancel();
|
||||
|
||||
// LLM
|
||||
let cancelled = false;
|
||||
const generatorWithCancellation = async function* () {
|
||||
for await (const update of generator) {
|
||||
if (token.aborted) {
|
||||
cancelled = true;
|
||||
return;
|
||||
}
|
||||
yield update;
|
||||
}
|
||||
};
|
||||
let charGenerator = generatorWithCancellation();
|
||||
|
||||
if (options.transform) {
|
||||
// charGenerator = noFirstCharNewline(charGenerator);
|
||||
// charGenerator = onlyWhitespaceAfterEndOfLine(
|
||||
// charGenerator,
|
||||
// lang.endOfLine,
|
||||
// fullStop,
|
||||
// );
|
||||
charGenerator = stopAtStopTokens(charGenerator, stop);
|
||||
charGenerator =
|
||||
this.bracketMatchingService.stopOnUnmatchedClosingBracket(
|
||||
charGenerator,
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
multiline,
|
||||
);
|
||||
}
|
||||
|
||||
let lineGenerator = streamLines(charGenerator);
|
||||
if (options.transform) {
|
||||
lineGenerator = stopAtLines(lineGenerator, fullStop);
|
||||
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
|
||||
lineGenerator = avoidPathLineAndEmptyComments(
|
||||
lineGenerator,
|
||||
lang.singleLineComment,
|
||||
);
|
||||
lineGenerator = skipPrefixes(lineGenerator);
|
||||
|
||||
// lineGenerator = noTopLevelKeywordsMidline(
|
||||
// lineGenerator,
|
||||
// lang.topLevelKeywords,
|
||||
// fullStop,
|
||||
// );
|
||||
for (const lineFilter of lang.lineFilters ?? []) {
|
||||
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
|
||||
}
|
||||
|
||||
lineGenerator = stopAtSimilarLine(
|
||||
lineGenerator,
|
||||
lineBelowCursor,
|
||||
fullStop,
|
||||
);
|
||||
}
|
||||
|
||||
const finalGenerator = streamWithNewLines(lineGenerator);
|
||||
|
||||
try {
|
||||
for await (const update of finalGenerator) {
|
||||
completion += update;
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) {
|
||||
return undefined;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const processedCompletion = options.transform
|
||||
? postprocessCompletion({
|
||||
completion,
|
||||
prefix,
|
||||
suffix,
|
||||
llm,
|
||||
})
|
||||
: completion;
|
||||
|
||||
if (!processedCompletion) {
|
||||
return undefined;
|
||||
}
|
||||
completion = processedCompletion;
|
||||
}
|
||||
|
||||
const time = Date.now() - startTime;
|
||||
return {
|
||||
time,
|
||||
completion,
|
||||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
modelProvider: llm.providerName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
filepath: input.filepath,
|
||||
completionId: input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(input.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
...options,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,18 @@
|
|||
import { LineFilter } from "./streamTransforms/lineStream";
|
||||
import { BracketMatchingService } from "../filtering/BracketMatchingService";
|
||||
import {
|
||||
CharacterFilter,
|
||||
LineFilter,
|
||||
} from "../filtering/streamTransforms/lineStream";
|
||||
|
||||
export interface AutocompleteLanguageInfo {
|
||||
name: string;
|
||||
topLevelKeywords: string[];
|
||||
singleLineComment: string;
|
||||
singleLineComment?: string;
|
||||
endOfLine: string[];
|
||||
stopWords?: string[];
|
||||
lineFilters?: LineFilter[];
|
||||
useMultiline?: (args: {
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
}) => boolean | undefined;
|
||||
charFilters?: CharacterFilter[];
|
||||
useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
|
||||
}
|
||||
|
||||
// TypeScript
|
||||
|
|
@ -256,10 +258,8 @@ export const YAML: AutocompleteLanguageInfo = {
|
|||
} else {
|
||||
seenListItem = true;
|
||||
}
|
||||
yield line;
|
||||
} else {
|
||||
yield line;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
},
|
||||
// Don't allow consecutive lines of same key
|
||||
|
|
@ -268,18 +268,39 @@ export const YAML: AutocompleteLanguageInfo = {
|
|||
for await (const line of lines) {
|
||||
if (line.includes(":")) {
|
||||
const key = line.split(":")[0];
|
||||
if (key !== lastKey) {
|
||||
if (key === lastKey) {
|
||||
break;
|
||||
} else {
|
||||
yield line;
|
||||
lastKey = key;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const Json: AutocompleteLanguageInfo = {
|
||||
name: "JSON",
|
||||
topLevelKeywords: [],
|
||||
singleLineComment: "//",
|
||||
endOfLine: [",", "}", "]"],
|
||||
charFilters: [
|
||||
function matchBrackets({ chars, prefix, suffix, filepath, multiline }) {
|
||||
const bracketMatchingService = new BracketMatchingService();
|
||||
return bracketMatchingService.stopOnUnmatchedClosingBracket(
|
||||
chars,
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
multiline,
|
||||
);
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const Markdown: AutocompleteLanguageInfo = {
|
||||
name: "Markdown",
|
||||
topLevelKeywords: [],
|
||||
|
|
@ -289,7 +310,7 @@ export const Markdown: AutocompleteLanguageInfo = {
|
|||
const singleLineStarters = ["- ", "* ", /^\d+\. /, "> ", "```", /^#{1,6} /];
|
||||
let currentLine = prefix.split("\n").pop();
|
||||
if (!currentLine) {
|
||||
return undefined;
|
||||
return true;
|
||||
}
|
||||
currentLine = currentLine.trim();
|
||||
for (const starter of singleLineStarters) {
|
||||
|
|
@ -301,7 +322,7 @@ export const Markdown: AutocompleteLanguageInfo = {
|
|||
return false;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -309,6 +330,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
ts: Typescript,
|
||||
js: Typescript,
|
||||
tsx: Typescript,
|
||||
json: Json,
|
||||
jsx: Typescript,
|
||||
ipynb: Python,
|
||||
py: Python,
|
||||
|
|
@ -346,3 +368,9 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
yml: YAML,
|
||||
md: Markdown,
|
||||
};
|
||||
|
||||
export function languageForFilepath(
|
||||
filepath: string,
|
||||
): AutocompleteLanguageInfo {
|
||||
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
|
||||
}
|
||||
|
|
@ -1,215 +1,87 @@
|
|||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { TabAutocompleteOptions } from "../index.js";
|
||||
|
||||
import {
|
||||
countTokens,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
} from "../llm/countTokens.js";
|
||||
import { AstPath, getAst, getTreePathAtCursor } from "./ast.js";
|
||||
import {
|
||||
AutocompleteLanguageInfo,
|
||||
LANGUAGES,
|
||||
Typescript,
|
||||
} from "./languages.js";
|
||||
import { Position, Range } from "../index.js";
|
||||
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
|
||||
import {
|
||||
fillPromptWithSnippets,
|
||||
getSymbolsForSnippet,
|
||||
rankSnippets,
|
||||
rankAndOrderSnippets,
|
||||
removeRangeFromSnippets,
|
||||
type AutocompleteSnippet,
|
||||
} from "./ranking.js";
|
||||
import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js";
|
||||
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
|
||||
import { RootPathContextService } from "./services/RootPathContextService.js";
|
||||
import { shouldCompleteMultiline } from "./shouldCompleteMultiline.js";
|
||||
} from "./context/ranking/index.js";
|
||||
import { HelperVars } from "./util/HelperVars.js";
|
||||
|
||||
export function languageForFilepath(
|
||||
filepath: string,
|
||||
): AutocompleteLanguageInfo {
|
||||
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
|
||||
function filterSnippetsAlreadyInCaretWindow(
|
||||
snippets: AutocompleteSnippet[],
|
||||
caretWindow: string,
|
||||
): AutocompleteSnippet[] {
|
||||
return snippets
|
||||
.map((snippet) => ({ ...snippet }))
|
||||
.filter(
|
||||
(s) =>
|
||||
s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()),
|
||||
);
|
||||
}
|
||||
|
||||
function getRangeOfPrefixAndSuffixWithBuffer(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
caretPos: Position,
|
||||
): Range {
|
||||
// Remove prefix range from snippets
|
||||
const prefixLines = prefix.split("\n").length;
|
||||
const suffixLines = suffix.split("\n").length;
|
||||
const buffer = 8;
|
||||
const prefixSuffixRangeWithBuffer = {
|
||||
start: {
|
||||
line: caretPos.line - prefixLines - buffer,
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: caretPos.line + suffixLines + buffer,
|
||||
character: 0,
|
||||
},
|
||||
};
|
||||
|
||||
return prefixSuffixRangeWithBuffer;
|
||||
}
|
||||
|
||||
export async function constructAutocompletePrompt(
|
||||
filepath: string,
|
||||
cursorLine: number,
|
||||
fullPrefix: string,
|
||||
fullSuffix: string,
|
||||
clipboardText: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
options: TabAutocompleteOptions,
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
recentlyEditedFiles: RangeInFileWithContents[],
|
||||
modelName: string,
|
||||
helper: HelperVars,
|
||||
extraSnippets: AutocompleteSnippet[],
|
||||
importDefinitionsService: ImportDefinitionsService,
|
||||
rootPathContextService: RootPathContextService,
|
||||
): Promise<{
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
useFim: boolean;
|
||||
completeMultiline: boolean;
|
||||
snippets: AutocompleteSnippet[];
|
||||
}> {
|
||||
// Construct basic prefix
|
||||
const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage;
|
||||
const prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName);
|
||||
|
||||
// Construct suffix
|
||||
const maxSuffixTokens = Math.min(
|
||||
options.maxPromptTokens - countTokens(prefix, modelName),
|
||||
options.maxSuffixPercentage * options.maxPromptTokens,
|
||||
contextRetrievalService: ContextRetrievalService,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
let snippets = await contextRetrievalService.retrieveCandidateSnippets(
|
||||
helper,
|
||||
extraSnippets,
|
||||
);
|
||||
const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
|
||||
|
||||
// Calculate AST Path
|
||||
let treePath: AstPath | undefined;
|
||||
try {
|
||||
const ast = await getAst(filepath, fullPrefix + fullSuffix);
|
||||
if (ast) {
|
||||
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to parse AST", e);
|
||||
}
|
||||
|
||||
// Find external snippets
|
||||
let snippets: AutocompleteSnippet[] = [];
|
||||
|
||||
if (options.useOtherFiles) {
|
||||
snippets.push(...extraSnippets);
|
||||
|
||||
const windowAroundCursor =
|
||||
fullPrefix.slice(
|
||||
-options.slidingWindowSize * options.slidingWindowPrefixPercentage,
|
||||
) +
|
||||
fullSuffix.slice(
|
||||
options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage),
|
||||
);
|
||||
|
||||
// This was much too slow, and not super useful
|
||||
// const slidingWindowMatches = await slidingWindowMatcher(
|
||||
// recentlyEditedFiles,
|
||||
// windowAroundCursor,
|
||||
// 3,
|
||||
// options.slidingWindowSize,
|
||||
// );
|
||||
// snippets.push(...slidingWindowMatches);
|
||||
|
||||
// snippets.push(
|
||||
// ...recentlyEditedRanges.map((r) => ({
|
||||
// ...r,
|
||||
// contents: r.lines.join("\n"),
|
||||
// })),
|
||||
// );
|
||||
|
||||
if (options.useRecentlyEdited) {
|
||||
const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0];
|
||||
if (currentLinePrefix?.length > options.recentLinePrefixMatchMinLength) {
|
||||
const matchingRange = findMatchingRange(
|
||||
recentlyEditedRanges,
|
||||
currentLinePrefix,
|
||||
);
|
||||
if (matchingRange) {
|
||||
snippets.push({
|
||||
...matchingRange,
|
||||
contents: matchingRange.lines.join("\n"),
|
||||
score: 0.8,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use imports
|
||||
if (options.useImports) {
|
||||
const importSnippets = [];
|
||||
const fileInfo = importDefinitionsService.get(filepath);
|
||||
if (fileInfo) {
|
||||
const { imports } = fileInfo;
|
||||
// Look for imports of any symbols around the current range
|
||||
const textAroundCursor =
|
||||
fullPrefix.split("\n").slice(-5).join("\n") +
|
||||
fullSuffix.split("\n").slice(0, 3).join("\n");
|
||||
const symbols = Array.from(
|
||||
getSymbolsForSnippet(textAroundCursor),
|
||||
).filter((symbol) => !language.topLevelKeywords.includes(symbol));
|
||||
for (const symbol of symbols) {
|
||||
const rifs = imports[symbol];
|
||||
if (Array.isArray(rifs)) {
|
||||
importSnippets.push(...rifs);
|
||||
}
|
||||
}
|
||||
}
|
||||
snippets.push(...importSnippets);
|
||||
}
|
||||
|
||||
if (options.useRootPathContext && treePath) {
|
||||
const ctx = await rootPathContextService.getContextForPath(
|
||||
filepath,
|
||||
treePath,
|
||||
);
|
||||
snippets.push(...ctx);
|
||||
}
|
||||
|
||||
// Filter out empty snippets and ones that are already in the prefix/suffix
|
||||
snippets = snippets
|
||||
.map((snippet) => ({ ...snippet }))
|
||||
.filter(
|
||||
(s) =>
|
||||
s.contents.trim() !== "" &&
|
||||
!(prefix + suffix).includes(s.contents.trim()),
|
||||
);
|
||||
|
||||
// Rank / order the snippets
|
||||
const scoredSnippets = rankSnippets(snippets, windowAroundCursor);
|
||||
|
||||
// Fill maxSnippetTokens with snippets
|
||||
const maxSnippetTokens =
|
||||
options.maxPromptTokens * options.maxSnippetPercentage;
|
||||
|
||||
// Remove prefix range from snippets
|
||||
const prefixLines = prefix.split("\n").length;
|
||||
const suffixLines = suffix.split("\n").length;
|
||||
const buffer = 8;
|
||||
const prefixSuffixRangeWithBuffer = {
|
||||
start: {
|
||||
line: cursorLine - prefixLines - buffer,
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: cursorLine + suffixLines + buffer,
|
||||
character: 0,
|
||||
},
|
||||
};
|
||||
let finalSnippets = removeRangeFromSnippets(
|
||||
scoredSnippets,
|
||||
filepath.split("://").slice(-1)[0],
|
||||
prefixSuffixRangeWithBuffer,
|
||||
);
|
||||
|
||||
// Filter snippets for those with best scores (must be above threshold)
|
||||
finalSnippets = finalSnippets.filter(
|
||||
(snippet) => snippet.score >= options.recentlyEditedSimilarityThreshold,
|
||||
);
|
||||
finalSnippets = fillPromptWithSnippets(
|
||||
scoredSnippets,
|
||||
maxSnippetTokens,
|
||||
modelName,
|
||||
);
|
||||
|
||||
snippets = finalSnippets;
|
||||
}
|
||||
|
||||
return {
|
||||
prefix,
|
||||
suffix,
|
||||
useFim: true,
|
||||
completeMultiline: await shouldCompleteMultiline(
|
||||
treePath,
|
||||
fullPrefix,
|
||||
fullSuffix,
|
||||
language,
|
||||
),
|
||||
snippets = filterSnippetsAlreadyInCaretWindow(
|
||||
snippets,
|
||||
};
|
||||
helper.prunedCaretWindow,
|
||||
);
|
||||
|
||||
const scoredSnippets = rankAndOrderSnippets(snippets, helper);
|
||||
|
||||
// This might be redundant with filterSnippetsAlreadyInCaretWindow
|
||||
let finalSnippets = removeRangeFromSnippets(
|
||||
scoredSnippets,
|
||||
helper.filepath.split("://").slice(-1)[0],
|
||||
getRangeOfPrefixAndSuffixWithBuffer(
|
||||
helper.prunedPrefix,
|
||||
helper.prunedSuffix,
|
||||
helper.pos,
|
||||
),
|
||||
);
|
||||
|
||||
// Filter snippets below similarity threshold
|
||||
finalSnippets = finalSnippets.filter(
|
||||
(snippet) =>
|
||||
snippet.score >= helper.options.recentlyEditedSimilarityThreshold,
|
||||
);
|
||||
|
||||
finalSnippets = fillPromptWithSnippets(
|
||||
scoredSnippets,
|
||||
helper.maxSnippetTokens,
|
||||
helper.modelName,
|
||||
);
|
||||
|
||||
return finalSnippets;
|
||||
}
|
||||
|
|
|
|||
123
core/autocomplete/context/ContextRetrievalService.ts
Normal file
123
core/autocomplete/context/ContextRetrievalService.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { IDE } from "../..";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { RecentlyEditedRange } from "../util/types";
|
||||
import { ImportDefinitionsService } from "./ImportDefinitionsService";
|
||||
import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking";
|
||||
import { RootPathContextService } from "./root-path-context/RootPathContextService";
|
||||
|
||||
export class ContextRetrievalService {
|
||||
private importDefinitionsService: ImportDefinitionsService;
|
||||
private rootPathContextService: RootPathContextService;
|
||||
|
||||
constructor(private readonly ide: IDE) {
|
||||
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
|
||||
this.rootPathContextService = new RootPathContextService(
|
||||
this.importDefinitionsService,
|
||||
this.ide,
|
||||
);
|
||||
}
|
||||
|
||||
public async retrieveCandidateSnippets(
|
||||
helper: HelperVars,
|
||||
extraSnippets: AutocompleteSnippet[],
|
||||
) {
|
||||
if (helper.options.useOtherFiles === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let snippets: AutocompleteSnippet[] = [];
|
||||
|
||||
// Snippets injected by the IDE for IDE-specific reasons
|
||||
snippets.push(...extraSnippets);
|
||||
|
||||
// If a recently edited range has a line that is a perfect match with the start of the current line
|
||||
snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper));
|
||||
|
||||
// Import definitions of any symbols in near range of the caret
|
||||
snippets.push(...(await this.getSnippetsFromImportDefinitions(helper)));
|
||||
|
||||
// Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/
|
||||
if (helper.options.useRootPathContext && helper.treePath) {
|
||||
snippets.push(
|
||||
...(await this.rootPathContextService.getContextForPath(
|
||||
helper.filepath,
|
||||
helper.treePath,
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
return snippets;
|
||||
}
|
||||
|
||||
private getSnippetsFromRecentlyEditedRanges(
|
||||
helper: HelperVars,
|
||||
): AutocompleteSnippet[] {
|
||||
if (helper.options.useRecentlyEdited === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const currentLinePrefix = helper.prunedPrefix
|
||||
.trim()
|
||||
.split("\n")
|
||||
.slice(-1)[0];
|
||||
if (
|
||||
currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength
|
||||
) {
|
||||
const matchingRange = this.findMatchingRange(
|
||||
helper.input.recentlyEditedRanges,
|
||||
currentLinePrefix,
|
||||
);
|
||||
|
||||
if (matchingRange) {
|
||||
return [
|
||||
{
|
||||
...matchingRange,
|
||||
contents: matchingRange.lines.join("\n"),
|
||||
score: 0.8,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private async getSnippetsFromImportDefinitions(
|
||||
helper: HelperVars,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
if (helper.options.useImports === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const importSnippets = [];
|
||||
const fileInfo = this.importDefinitionsService.get(helper.filepath);
|
||||
if (fileInfo) {
|
||||
const { imports } = fileInfo;
|
||||
// Look for imports of any symbols around the current range
|
||||
const textAroundCursor =
|
||||
helper.fullPrefix.split("\n").slice(-5).join("\n") +
|
||||
helper.fullSuffix.split("\n").slice(0, 3).join("\n");
|
||||
const symbols = Array.from(getSymbolsForSnippet(textAroundCursor)).filter(
|
||||
(symbol) => !helper.lang.topLevelKeywords.includes(symbol),
|
||||
);
|
||||
for (const symbol of symbols) {
|
||||
const rifs = imports[symbol];
|
||||
if (Array.isArray(rifs)) {
|
||||
importSnippets.push(...rifs);
|
||||
}
|
||||
}
|
||||
}
|
||||
return importSnippets;
|
||||
}
|
||||
|
||||
findMatchingRange(
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
linePrefix: string,
|
||||
): RecentlyEditedRange | undefined {
|
||||
return recentlyEditedRanges.find((recentlyEditedRange) => {
|
||||
return recentlyEditedRange.lines.some((line) =>
|
||||
line.startsWith(linePrefix),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { IDE, Location } from "../..";
|
||||
import { LANGUAGES } from "../languages";
|
||||
import { getSymbolsForSnippet } from "../ranking";
|
||||
import { LANGUAGES } from "../constants/AutocompleteLanguageInfo";
|
||||
import { getSymbolsForSnippet } from "./ranking";
|
||||
|
||||
interface FileInfo {
|
||||
filepath: string;
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { Range } from "../index.js";
|
||||
import { countTokens } from "../llm/countTokens.js";
|
||||
import { RangeInFileWithContents } from "../../../commands/util.js";
|
||||
import { Range } from "../../../index.js";
|
||||
import { countTokens } from "../../../llm/countTokens.js";
|
||||
import { HelperVars } from "../../util/HelperVars.js";
|
||||
|
||||
export type AutocompleteSnippet = RangeInFileWithContents & {
|
||||
score?: number;
|
||||
|
|
@ -41,10 +42,20 @@ 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(
|
||||
export function rankAndOrderSnippets(
|
||||
ranges: AutocompleteSnippet[],
|
||||
windowAroundCursor: string,
|
||||
helper: HelperVars,
|
||||
): Required<AutocompleteSnippet>[] {
|
||||
const windowAroundCursor =
|
||||
helper.fullPrefix.slice(
|
||||
-helper.options.slidingWindowSize *
|
||||
helper.options.slidingWindowPrefixPercentage,
|
||||
) +
|
||||
helper.fullSuffix.slice(
|
||||
helper.options.slidingWindowSize *
|
||||
(1 - helper.options.slidingWindowPrefixPercentage),
|
||||
);
|
||||
|
||||
const snippets: Required<AutocompleteSnippet>[] = ranges.map((snippet) => ({
|
||||
score:
|
||||
snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor),
|
||||
|
|
@ -119,7 +130,8 @@ function mergeOverlappingRangeContents(
|
|||
}
|
||||
|
||||
/**
|
||||
* Fill the allowed space with snippets
|
||||
* Fill the allowed space with snippets.
|
||||
* It is assumed that the snippets are sorted by score.
|
||||
*/
|
||||
export function fillPromptWithSnippets(
|
||||
snippets: Required<AutocompleteSnippet>[],
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { AutocompleteSnippet, jaccardSimilarity } from "./ranking.js";
|
||||
import { RangeInFileWithContents } from "../../../commands/util.js";
|
||||
import { AutocompleteSnippet, jaccardSimilarity } from "./index.js";
|
||||
|
||||
function* slidingWindow(
|
||||
content: string,
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { Range } from "../../..";
|
||||
import { testIde } from "../../../test/util/fixtures";
|
||||
import { getAst, getTreePathAtCursor } from "../../util/ast";
|
||||
import { ImportDefinitionsService } from "../ImportDefinitionsService";
|
||||
import { RootPathContextService } from "./RootPathContextService";
|
||||
|
||||
function splitTextAtRange(fileContent: string, range: Range): [string, string] {
|
||||
const lines = fileContent.split("\n");
|
||||
let currentPos = 0;
|
||||
|
||||
if (range.start.line === range.end.line) {
|
||||
// If range is on the same line, calculate position once
|
||||
for (let i = 0; i < range.start.line; i++) {
|
||||
currentPos += lines[i].length + 1; // +1 for the newline character
|
||||
}
|
||||
const startPos = currentPos + range.start.character;
|
||||
const endPos = currentPos + range.end.character;
|
||||
return [fileContent.slice(0, startPos), fileContent.slice(endPos)];
|
||||
}
|
||||
|
||||
// Calculate position of range start
|
||||
for (let i = 0; i < range.start.line; i++) {
|
||||
currentPos += lines[i].length + 1;
|
||||
}
|
||||
const startPos = currentPos + range.start.character;
|
||||
|
||||
// Calculate position of range end
|
||||
currentPos = 0;
|
||||
for (let i = 0; i < range.end.line; i++) {
|
||||
currentPos += lines[i].length + 1;
|
||||
}
|
||||
const endPos = currentPos + range.end.character;
|
||||
|
||||
return [fileContent.slice(0, startPos), fileContent.slice(endPos)];
|
||||
}
|
||||
|
||||
export async function testRootPathContext(
|
||||
folderName: string,
|
||||
relativeFilepath: string,
|
||||
rangeToFill: Range,
|
||||
expectedSnippets: string[],
|
||||
) {
|
||||
const ide = testIde;
|
||||
const importDefinitionsService = new ImportDefinitionsService(ide);
|
||||
const service = new RootPathContextService(importDefinitionsService, ide);
|
||||
|
||||
// Copy the folder to the test directory
|
||||
const folderPath = path.join(
|
||||
__dirname,
|
||||
"autocomplete",
|
||||
"context",
|
||||
"root-path-context",
|
||||
"test",
|
||||
folderName,
|
||||
);
|
||||
const workspaceDir = (await ide.getWorkspaceDirs())[0];
|
||||
const testFolderPath = path.join(workspaceDir, folderName);
|
||||
fs.cpSync(folderPath, testFolderPath, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Get results of root path context
|
||||
const startPath = path.join(testFolderPath, relativeFilepath);
|
||||
const [prefix, suffix] = splitTextAtRange(
|
||||
fs.readFileSync(startPath, "utf8"),
|
||||
rangeToFill,
|
||||
);
|
||||
const fileContents = prefix + suffix;
|
||||
const ast = await getAst(startPath, fileContents);
|
||||
if (!ast) {
|
||||
throw new Error("AST is undefined");
|
||||
}
|
||||
|
||||
const treePath = await getTreePathAtCursor(ast, prefix.length);
|
||||
const snippets = await service.getContextForPath(startPath, treePath);
|
||||
|
||||
expectedSnippets.forEach((expectedSnippet) => {
|
||||
const found = snippets.find((snippet) =>
|
||||
snippet.contents.includes(expectedSnippet),
|
||||
);
|
||||
expect(found).toBeDefined();
|
||||
});
|
||||
}
|
||||
|
||||
describe("RootPathContextService", () => {
|
||||
it("should be true", async () => {
|
||||
await testRootPathContext(
|
||||
"typescript",
|
||||
"file1.ts",
|
||||
{ start: { line: 3, character: 2 }, end: { line: 3, character: 24 } },
|
||||
["export interface Person", "export interface Address"],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
import { createHash } from "crypto";
|
||||
import { LRUCache } from "lru-cache";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { IDE } from "../..";
|
||||
import { getQueryForFile, TSQueryType } from "../../util/treeSitter";
|
||||
import { AstPath } from "../ast";
|
||||
import { IDE } from "../../..";
|
||||
import { getQueryForFile, TSQueryType } from "../../../util/treeSitter";
|
||||
import { AstPath } from "../../util/ast";
|
||||
import { ImportDefinitionsService } from "../ImportDefinitionsService";
|
||||
import { AutocompleteSnippet } from "../ranking";
|
||||
import { ImportDefinitionsService } from "./ImportDefinitionsService";
|
||||
|
||||
export class RootPathContextService {
|
||||
private cache = new LRUCache<string, AutocompleteSnippet[]>({
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import { Address, Person } from "./types";
|
||||
|
||||
function getAddress(person: Person): Address {
|
||||
return person.address;
|
||||
}
|
||||
|
||||
class Group {
|
||||
people: Person[];
|
||||
|
||||
constructor(people: Person[]) {
|
||||
this.people = people;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
export interface Person {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
age: number;
|
||||
address: Address;
|
||||
}
|
||||
|
||||
export interface Address {
|
||||
street: string;
|
||||
city: string;
|
||||
}
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
export function isOnlyWhitespace(completion: string): boolean {
|
||||
const whitespaceRegex = /^[\s]+$/;
|
||||
return whitespaceRegex.test(completion);
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
import { streamLines } from "../../../diff/util";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters";
|
||||
import { HelperVars } from "../../util/HelperVars";
|
||||
import { stopAtStopTokens } from "./charStream";
|
||||
import {
|
||||
avoidEmptyComments,
|
||||
avoidPathLine,
|
||||
showWhateverWeHaveAtXMs,
|
||||
skipPrefixes,
|
||||
stopAtLines,
|
||||
stopAtRepeatingLines,
|
||||
stopAtSimilarLine,
|
||||
streamWithNewLines,
|
||||
} from "./lineStream";
|
||||
|
||||
export class StreamTransformPipeline {
|
||||
async *transform(
|
||||
generator: AsyncGenerator<string>,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
multiline: boolean,
|
||||
stopTokens: string[],
|
||||
fullStop: () => void,
|
||||
helper: HelperVars,
|
||||
): AsyncGenerator<string> {
|
||||
let charGenerator = generator;
|
||||
|
||||
charGenerator = stopAtStopTokens(generator, stopTokens);
|
||||
for (const charFilter of helper.lang.charFilters ?? []) {
|
||||
charGenerator = charFilter({
|
||||
chars: charGenerator,
|
||||
prefix,
|
||||
suffix,
|
||||
filepath: helper.filepath,
|
||||
multiline,
|
||||
});
|
||||
}
|
||||
|
||||
let lineGenerator = streamLines(charGenerator);
|
||||
|
||||
lineGenerator = stopAtLines(lineGenerator, fullStop);
|
||||
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
|
||||
lineGenerator = avoidEmptyComments(
|
||||
lineGenerator,
|
||||
helper.lang.singleLineComment,
|
||||
);
|
||||
lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment);
|
||||
lineGenerator = skipPrefixes(lineGenerator);
|
||||
|
||||
for (const lineFilter of helper.lang.lineFilters ?? []) {
|
||||
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
|
||||
}
|
||||
|
||||
lineGenerator = stopAtSimilarLine(
|
||||
lineGenerator,
|
||||
this.getLineBelowCursor(helper),
|
||||
fullStop,
|
||||
);
|
||||
|
||||
lineGenerator = showWhateverWeHaveAtXMs(
|
||||
lineGenerator,
|
||||
helper.options.showWhateverWeHaveAtXMs ??
|
||||
(DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs as number),
|
||||
);
|
||||
|
||||
const finalGenerator = streamWithNewLines(lineGenerator);
|
||||
for await (const update of finalGenerator) {
|
||||
yield update;
|
||||
}
|
||||
}
|
||||
|
||||
private getLineBelowCursor(helper: HelperVars): string {
|
||||
let lineBelowCursor = "";
|
||||
let i = 1;
|
||||
while (
|
||||
lineBelowCursor.trim() === "" &&
|
||||
helper.pos.line + i <= helper.fileLines.length - 1
|
||||
) {
|
||||
lineBelowCursor =
|
||||
helper.fileLines[
|
||||
Math.min(helper.pos.line + i, helper.fileLines.length - 1)
|
||||
];
|
||||
i++;
|
||||
}
|
||||
return lineBelowCursor;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { stopAtStopTokens } from "./streamTransforms/charStream";
|
||||
import { stopAtStopTokens } from "./charStream";
|
||||
|
||||
describe("stopAtStopTokens", () => {
|
||||
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import * as lineStream from "./streamTransforms/lineStream";
|
||||
import * as lineStream from "./lineStream";
|
||||
|
||||
describe("lineStream", () => {
|
||||
let mockFullStop: jest.Mock;
|
||||
|
|
@ -31,21 +31,34 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
describe("avoidPathLine", () => {
|
||||
it("should filter out path lines and empty comments", async () => {
|
||||
it("should filter out path lines", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"// Path: src/index.ts",
|
||||
"const x = 5;",
|
||||
"//",
|
||||
"console.log(x);",
|
||||
]);
|
||||
|
||||
const result = lineStream.avoidPathLineAndEmptyComments(
|
||||
linesGenerator,
|
||||
"//",
|
||||
);
|
||||
const result = lineStream.avoidPathLine(linesGenerator, "//");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]);
|
||||
});
|
||||
});
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "console.log(x);"]);
|
||||
describe("avoidEmptyComments", () => {
|
||||
it("should filter out empty comments", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"// Path: src/index.ts",
|
||||
"const x = 5;",
|
||||
"//",
|
||||
"console.log(x);",
|
||||
]);
|
||||
const result = lineStream.avoidEmptyComments(linesGenerator, "//");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
expect(filteredLines).toEqual([
|
||||
"// Path: src/index.ts",
|
||||
"const x = 5;",
|
||||
"console.log(x);",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -1,12 +1,20 @@
|
|||
import { distance } from "fastest-levenshtein";
|
||||
import { DiffLine } from "../..";
|
||||
import { LineStream } from "../../diff/util";
|
||||
import { DiffLine } from "../../..";
|
||||
import { LineStream } from "../../../diff/util";
|
||||
|
||||
export type LineFilter = (args: {
|
||||
lines: LineStream;
|
||||
fullStop: () => void;
|
||||
}) => LineStream;
|
||||
|
||||
export type CharacterFilter = (args: {
|
||||
chars: AsyncGenerator<string>;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
filepath: string;
|
||||
multiline: boolean;
|
||||
}) => AsyncGenerator<string>;
|
||||
|
||||
function isBracketEnding(line: string): boolean {
|
||||
return line
|
||||
.trim()
|
||||
|
|
@ -14,14 +22,6 @@ function isBracketEnding(line: string): boolean {
|
|||
.some((char) => BRACKET_ENDING_CHARS.includes(char));
|
||||
}
|
||||
|
||||
function commonPrefixLength(a: string, b: string): number {
|
||||
let i = 0;
|
||||
while (i < a.length && i < b.length && a[i] === b[i]) {
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
function isEnglishFirstLine(line: string) {
|
||||
line = line.trim().toLowerCase();
|
||||
|
||||
|
|
@ -122,27 +122,45 @@ export async function* noTopLevelKeywordsMidline(
|
|||
}
|
||||
|
||||
/**
|
||||
* Filters out unwanted lines from a LineStream, specifically those starting with '// Path: <PATH>' or empty comments.
|
||||
* Filters out lines starting with '// Path: <PATH>' from a LineStream.
|
||||
*
|
||||
* @param {LineStream} stream - The input stream of lines to filter.
|
||||
* @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments).
|
||||
* @yields {string} The filtered lines, excluding unwanted path lines and empty comments.
|
||||
* @yields {string} The filtered lines, excluding unwanted path lines.
|
||||
*/
|
||||
export async function* avoidPathLineAndEmptyComments(
|
||||
export async function* avoidPathLine(
|
||||
stream: LineStream,
|
||||
comment: string,
|
||||
comment?: string,
|
||||
): LineStream {
|
||||
// Snippets are inserted as comments with a line at the start '// Path: <PATH>'.
|
||||
// Sometimes the model with copy this pattern, which is unwanted
|
||||
for await (const line of stream) {
|
||||
// Also filter lines that are empty comments
|
||||
if (line.startsWith(`${comment} Path: `) || line.trim() === comment) {
|
||||
if (line.startsWith(`${comment} Path: `)) {
|
||||
continue;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters out empty comment lines from a LineStream.
|
||||
*
|
||||
* @param {LineStream} stream - The input stream of lines to filter.
|
||||
* @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments).
|
||||
* @yields {string} The filtered lines, excluding empty comments.
|
||||
*/
|
||||
export async function* avoidEmptyComments(
|
||||
stream: LineStream,
|
||||
comment?: string,
|
||||
): LineStream {
|
||||
// Filter lines that are empty comments
|
||||
for await (const line of stream) {
|
||||
if (!comment || line.trim() !== comment) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a LineStream by adding newline characters between lines.
|
||||
*
|
||||
|
|
@ -168,9 +186,7 @@ export async function* streamWithNewLines(stream: LineStream): LineStream {
|
|||
* @returns {boolean} True if the lines are considered repeated, false otherwise.
|
||||
*
|
||||
* @description
|
||||
* This function checks if two lines are repeated or very similar based on two criteria:
|
||||
* 1. They have a common prefix longer than 12 characters.
|
||||
* 2. The Levenshtein distance between them is less than 10% of the length of the second line.
|
||||
* This function checks if the Levenshtein distance between them is less than 10% of the length of the second line.
|
||||
* Lines shorter than 5 characters are never considered repeated.
|
||||
*/
|
||||
export function lineIsRepeated(a: string, b: string): boolean {
|
||||
|
|
@ -180,10 +196,7 @@ export function lineIsRepeated(a: string, b: string): boolean {
|
|||
|
||||
const aTrim = a.trim();
|
||||
const bTrim = b.trim();
|
||||
return (
|
||||
commonPrefixLength(aTrim, bTrim) > 12 ||
|
||||
distance(aTrim, bTrim) / bTrim.length < 0.1
|
||||
);
|
||||
return distance(aTrim, bTrim) / bTrim.length < 0.05;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -210,9 +223,9 @@ export async function* stopAtSimilarLine(
|
|||
const lineIsBracketEnding = isBracketEnding(trimmedLine);
|
||||
|
||||
for await (const nextLine of stream) {
|
||||
if (nextLine === line) {
|
||||
fullStop();
|
||||
break;
|
||||
if (trimmedLine === "") {
|
||||
yield nextLine;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lineIsBracketEnding && trimmedLine.trim() === nextLine.trim()) {
|
||||
|
|
@ -220,6 +233,11 @@ export async function* stopAtSimilarLine(
|
|||
continue;
|
||||
}
|
||||
|
||||
if (nextLine === line) {
|
||||
fullStop();
|
||||
break;
|
||||
}
|
||||
|
||||
if (lineIsRepeated(nextLine, trimmedLine)) {
|
||||
fullStop();
|
||||
break;
|
||||
|
|
@ -510,3 +528,19 @@ export async function* logLines(
|
|||
}
|
||||
console.log(`${prefix}:\n${linesToLog.join("\n")}\n\n`);
|
||||
}
|
||||
|
||||
export async function* showWhateverWeHaveAtXMs(
|
||||
lines: LineStream,
|
||||
ms: number,
|
||||
): LineStream {
|
||||
const startTime = Date.now();
|
||||
for await (const line of lines) {
|
||||
// Always get at least one line
|
||||
yield line;
|
||||
|
||||
// But after that, soft break at X ms
|
||||
if (Date.now() - startTime > ms) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
##### Prompt #####
|
||||
{
|
||||
"active": true,
|
||||
"department": "Product Development",
|
||||
"location": {
|
||||
"country": "USA",
|
||||
"state": "California",
|
||||
"city": "San BERNARDINO",
|
||||
"coordinates": {
|
||||
<FIM>
|
||||
}
|
||||
},
|
||||
"employees": [
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"position": "Developer",
|
||||
"skills": ["JavaScript", "React", "Node.js"],
|
||||
"remote": false,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 95000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Jane Smith",
|
||||
"age": 25,
|
||||
"position": "Designer",
|
||||
"skills": ["Photoshop", "Illustrator"],
|
||||
"remote": true,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 70000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Emily Johnson",
|
||||
"age": 35,
|
||||
"position": "Manager",
|
||||
"teamSize": 8,
|
||||
"remote": true,
|
||||
"skills": ["Leadership", "Project Management"],==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
"latitude": 34.10834,
|
||||
"longitude": -117.28977
|
||||
}
|
||||
},
|
||||
"employeeCount": 2,
|
||||
"averageAge": 30,
|
||||
"remoteFriendly": true,
|
||||
"salaryRange": {
|
||||
"min": 70000,
|
||||
"max": 95000,
|
||||
"currency": "USD"
|
||||
},
|
||||
"skills": {
|
||||
"required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"],
|
||||
"optional": ["Photoshop", "Illustrator"]
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
##### Prompt #####
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Vue computed property",
|
||||
filename: "UserComponent.vue",
|
||||
input: `<template>
|
||||
<div>
|
||||
<p>User Full Name: {{ fullName }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
fullName<|fim|>
|
||||
},
|
||||
};
|
||||
</script>
|
||||
`,
|
||||
llmOutput: `() {
|
||||
return this.firstName + ' ' + this.lastName;
|
||||
}`,
|
||||
expectedCompletion: `() {
|
||||
return this.firstName + ' ' + this.lastName;
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Vue method using props",
|
||||
filename: "TodoItem.vue",
|
||||
input: `<template>
|
||||
<li>
|
||||
<p>{{ title }}</p>
|
||||
<button @click="completeTodo">Complete</button>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
title: String,
|
||||
completed: Boolean,
|
||||
},
|
||||
methods: {
|
||||
completeTodo() {
|
||||
<|fim|> = true;
|
||||
}
|
||||
},
|
||||
};
|
||||
</script>
|
||||
`,
|
||||
llmOutput: `this.completed`,
|
||||
expectedCompletion: `this.completed`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Svelte reactive statement",
|
||||
filename: "Counter.svelte",
|
||||
input: `
|
||||
<script>
|
||||
let count = 0;
|
||||
|
||||
$: <|fim|>
|
||||
|
||||
function handleClick() {
|
||||
count += 1;
|
||||
}
|
||||
</script>
|
||||
|
||||
<button on:click={handleClick}>
|
||||
Clicked {count} times
|
||||
</button>
|
||||
`,
|
||||
llmOutput: `doubledCount = count * 2`,
|
||||
expectedCompletion: `doubledCount = count * 2`,
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should autocomplete Svelte component inside HTML",
|
||||
filename: "NestedComponent.svelte",
|
||||
input: `
|
||||
<script>
|
||||
import ChildComponent from './ChildComponent.svelte';
|
||||
</script>
|
||||
|
||||
<main>
|
||||
<h1>Hello Svelte</h1>
|
||||
<ChildComponent <|fim|> />
|
||||
</main>
|
||||
`,
|
||||
llmOutput: `name="World"`,
|
||||
expectedCompletion: `name="World"`,
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should handle autocomplete in Svelte each block",
|
||||
filename: "List.svelte",
|
||||
input: `
|
||||
<script>
|
||||
let items = ["Apple", "Banana", "Cherry"];
|
||||
</script>
|
||||
|
||||
<ul>
|
||||
{#each items as item}
|
||||
<li>{item}</li>
|
||||
{/each<|fim|>
|
||||
</ul>
|
||||
`,
|
||||
llmOutput: `}`,
|
||||
expectedCompletion: `}`,
|
||||
},
|
||||
<FIM>
|
||||
];
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
|
||||
|
||||
export default {
|
||||
components: {
|
||||
ChildComponent,
|
||||
},
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
##### Prompt #####
|
||||
{
|
||||
"employees": [
|
||||
{ "name": "John Doe", "age": 30, "position": "Developer" },
|
||||
{ "name": "Jane Smith", "age": 25, "position": "Designer" },
|
||||
{ "name": "Emily Johnson", "age": 35, "position": "Manager" }<FIM>
|
||||
],
|
||||
"active": true
|
||||
}
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
|
||||
}
|
||||
|
||||
{
|
||||
"employees": [
|
||||
{ "name": "John Doe", "age": 30 },
|
||||
{ "name": "Jane Smith", "age": 25 }
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
##### Prompt #####
|
||||
class Calculator:
|
||||
def __init__(self):
|
||||
self.result = 0
|
||||
|
||||
def add(self, number):
|
||||
self.result += number
|
||||
return self
|
||||
|
||||
def divid<FIM>
|
||||
|
||||
def subtract(self, number):
|
||||
self.result -= number
|
||||
return self
|
||||
|
||||
def reset(self):
|
||||
self.result = 0
|
||||
return self
|
||||
|
||||
def get_result(self):
|
||||
return self.result
|
||||
|
||||
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
self.result /= number
|
||||
return self
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
##### Prompt #####
|
||||
class Calculator
|
||||
attr_accessor :result
|
||||
|
||||
def initialize
|
||||
@result = 0
|
||||
end
|
||||
|
||||
def add(number)
|
||||
@result += number
|
||||
self
|
||||
end
|
||||
|
||||
def subtract(number)
|
||||
@result -= number
|
||||
self
|
||||
end
|
||||
|
||||
def power(ne<FIM>
|
||||
|
||||
def get_result
|
||||
@result
|
||||
end
|
||||
|
||||
def reset
|
||||
@result = 0
|
||||
self
|
||||
end
|
||||
end
|
||||
|
||||
calc = Calculator.new
|
||||
calc.add(5).subtract(3)
|
||||
puts "Result: #{calc.get_result}"
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
|
||||
@result ** number
|
||||
self
|
||||
end
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
##### Prompt #####
|
||||
use std::io;
|
||||
|
||||
fn main() {
|
||||
println!("Welcome to the Calculator!");
|
||||
|
||||
loop {
|
||||
println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
|
||||
let operator = read_input();
|
||||
|
||||
if operator == "q" {
|
||||
break;
|
||||
}
|
||||
|
||||
println!("Please enter the first number:");
|
||||
let num1 = read_input().parse::<f64>().unwrap();
|
||||
|
||||
println!("Please enter the second number:");
|
||||
let num2 = read_input().parse::<f64>().unwrap();
|
||||
|
||||
let result = match operator.as_str() {
|
||||
"+" => num1 + num2,
|
||||
"-" => num1 - num2,
|
||||
"*" => num1 * num2,
|
||||
"/" => num1 / num2,
|
||||
<FIM>
|
||||
_ => {
|
||||
println!("Invalid operator. Please try again.");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
println!("Result: {}", result);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_input() -> String {
|
||||
let mut input = String::new();
|
||||
io::stdin()
|
||||
.read_line(&mut input)
|
||||
.expect("Failed to read input");
|
||||
input.trim().to_string()
|
||||
}
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
=> {
|
||||
println!("Invalid operator. Please try again.");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
println!("Result: {}", result);
|
||||
}
|
||||
|
||||
println!("Goodbye!");
|
||||
}
|
||||
|
||||
|
||||
fn main2() {
|
||||
println!("Welcome to the Calculator!");
|
||||
|
||||
loop {
|
||||
println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
|
||||
let operator = read_input();
|
||||
|
||||
if operator == "q" {
|
||||
break;
|
||||
}
|
||||
|
||||
match operator.as_str() {
|
||||
"+" | "-" | "*" | "/" => (),
|
||||
49
core/autocomplete/filtering/test/filter.test.ts
Normal file
49
core/autocomplete/filtering/test/filter.test.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import {
|
||||
AutocompleteFileringTestInput,
|
||||
testAutocompleteFiltering,
|
||||
} from "./util";
|
||||
import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
|
||||
import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir";
|
||||
|
||||
const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
|
||||
if (tests.some((test) => test.options?.only)) {
|
||||
return tests.filter((test) => test.options?.only);
|
||||
}
|
||||
|
||||
return tests;
|
||||
};
|
||||
|
||||
describe("llms/Mock", () => {
|
||||
beforeAll(async () => {
|
||||
tearDownTestDir();
|
||||
setUpTestDir();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
describe("Autocomplete Filtering Tests", () => {
|
||||
beforeEach(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
});
|
||||
|
||||
describe("Should return unmodified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
|
||||
"$description",
|
||||
async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Should return modified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
|
||||
"$description",
|
||||
async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,7 +1,243 @@
|
|||
import { dedent } from "../../util";
|
||||
import { dedent } from "../../../util";
|
||||
import { AutocompleteFileringTestInput } from "./util";
|
||||
|
||||
export const TEST_CASES: AutocompleteFileringTestInput[] = [
|
||||
export const TEST_CASES_WITH_DIFF: AutocompleteFileringTestInput[] = [
|
||||
{
|
||||
description: "Should handle python multi-line string",
|
||||
filename: "test.py",
|
||||
input: `def create_greeting(name):
|
||||
greeting = """Hello, """ + name + """!
|
||||
Welcome to our community. We hope you have a great time here.
|
||||
If you have any questions, feel free to reach out."""
|
||||
return greeting
|
||||
|
||||
message = create_greeting("Alice")
|
||||
print(message)
|
||||
|
||||
multi_line_message = """<|fim|>
|
||||
print(multi_line_message)
|
||||
`,
|
||||
llmOutput: `This is a multi-line message.
|
||||
It continues across multiple lines,
|
||||
which allows for easy reading and formatting.
|
||||
"""
|
||||
`,
|
||||
expectedCompletion: `This is a multi-line message.
|
||||
It continues across multiple lines,
|
||||
which allows for easy reading and formatting.
|
||||
"""`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Rust match arms",
|
||||
filename: "main.rs",
|
||||
input: `
|
||||
fn get_status_code_description(code: u16) -> &'static str {
|
||||
match code {
|
||||
200 => "OK",
|
||||
404 => "Not Found",
|
||||
500 => "Internal Server Error",
|
||||
<|fim|>
|
||||
}
|
||||
}
|
||||
`,
|
||||
llmOutput: `403 => "Forbidden",
|
||||
401 => "Unauthorized",
|
||||
_ => "Unknown Status",
|
||||
`,
|
||||
expectedCompletion: `403 => "Forbidden",
|
||||
401 => "Unauthorized",
|
||||
_ => "Unknown Status",`,
|
||||
},
|
||||
{
|
||||
description: "Should complete a Markdown code block",
|
||||
filename: "test.md",
|
||||
input: `
|
||||
Here is a sample JavaScript function:
|
||||
|
||||
\`\`\`javascript
|
||||
function sayHello() {
|
||||
console.log("Hello, <|fim|>
|
||||
}
|
||||
\`\`\`
|
||||
`,
|
||||
llmOutput: `world!");
|
||||
`,
|
||||
expectedCompletion: `world!");`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Java when inside a block",
|
||||
filename: "Main.java",
|
||||
input: `
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (i % 2 == 0) {
|
||||
System.out.println("Even: " + i);
|
||||
} else {
|
||||
<|fim|>
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
llmOutput: `
|
||||
System.out.println("Odd: " + i);
|
||||
`,
|
||||
expectedCompletion: `
|
||||
System.out.println("Odd: " + i);`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete a Markdown heading and preserve formatting",
|
||||
filename: "test.md",
|
||||
input: `# My Document
|
||||
|
||||
## Introduction
|
||||
This is a sample document for testing.
|
||||
|
||||
## <|fim|>
|
||||
### Conclusion
|
||||
Thank you for reading.
|
||||
`,
|
||||
llmOutput: `Features
|
||||
Here is a list of features:
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
`,
|
||||
expectedCompletion: `Features
|
||||
Here is a list of features:
|
||||
- Feature 1
|
||||
- Feature 2`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a Java method within a class",
|
||||
filename: "Calculator.java",
|
||||
input: `
|
||||
public class Calculator {
|
||||
private double result;
|
||||
|
||||
public Calculator() {
|
||||
this.result = 0.0;
|
||||
}
|
||||
|
||||
public void add(double number) {
|
||||
result += number;
|
||||
<|fim|>`,
|
||||
llmOutput: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}
|
||||
`,
|
||||
expectedCompletion: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should filter out consecutive, repeated YAML keys",
|
||||
filename: "test.yaml",
|
||||
input: `
|
||||
version: '3'
|
||||
services:
|
||||
db:
|
||||
image: postgres
|
||||
environment:
|
||||
POSTGRES_USER: user
|
||||
POSTGRES_PASSWORD: pass<|fim|>
|
||||
`,
|
||||
llmOutput: `
|
||||
POSTGRES_DB: mydb
|
||||
POSTGRES_DB: mydb
|
||||
`,
|
||||
expectedCompletion: `
|
||||
POSTGRES_DB: mydb
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a Markdown list with nested items",
|
||||
filename: "test.md",
|
||||
input: `
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Subitem 1
|
||||
<|fim|>
|
||||
- Item 3
|
||||
`,
|
||||
llmOutput: ` - Subitem 2
|
||||
- Subitem 3
|
||||
`,
|
||||
expectedCompletion: ` - Subitem 2
|
||||
- Subitem 3`,
|
||||
},
|
||||
{
|
||||
description: "Should enforce bracket matching in JSON files",
|
||||
filename: "test.json",
|
||||
input: `{
|
||||
"active": true,
|
||||
"department": "Product Development",
|
||||
"location": {
|
||||
"country": "USA",
|
||||
"state": "California",
|
||||
"city": "San BERNARDINO",
|
||||
"coordinates": {
|
||||
<FIM>
|
||||
}
|
||||
},
|
||||
"employees": [
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"position": "Developer",
|
||||
"skills": ["JavaScript", "React", "Node.js"],
|
||||
"remote": false,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 95000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Jane Smith",
|
||||
"age": 25,
|
||||
"position": "Designer",
|
||||
"skills": ["Photoshop", "Illustrator"],
|
||||
"remote": true,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 70000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Emily Johnson",
|
||||
"age": 35,
|
||||
"position": "Manager",
|
||||
"teamSize": 8,
|
||||
"remote": true,
|
||||
"skills": ["Leadership", "Project Management"],`,
|
||||
llmOutput: `"latitude": 34.10834,
|
||||
"longitude": -117.28977
|
||||
}
|
||||
},
|
||||
"employeeCount": 2,
|
||||
"averageAge": 30,
|
||||
"remoteFriendly": true,
|
||||
"salaryRange": {
|
||||
"min": 70000,
|
||||
"max": 95000,
|
||||
"currency": "USD"
|
||||
},
|
||||
"skills": {
|
||||
"required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"],
|
||||
"optional": ["Photoshop", "Illustrator"]`,
|
||||
expectedCompletion: `"latitude": 34.10834,
|
||||
"longitude": -117.28977
|
||||
`,
|
||||
},
|
||||
];
|
||||
|
||||
export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [
|
||||
{
|
||||
description: "should pass",
|
||||
filename: "test.js",
|
||||
|
|
@ -412,32 +648,6 @@ print(odd_squares)
|
|||
llmOutput: `x for x in squares if x % 2 != 0`,
|
||||
expectedCompletion: `x for x in squares if x % 2 != 0`,
|
||||
},
|
||||
{
|
||||
description: "Should handle python multi-line string",
|
||||
filename: "test.py",
|
||||
input: `def create_greeting(name):
|
||||
greeting = """Hello, """ + name + """!
|
||||
Welcome to our community. We hope you have a great time here.
|
||||
If you have any questions, feel free to reach out."""
|
||||
return greeting
|
||||
|
||||
message = create_greeting("Alice")
|
||||
print(message)
|
||||
|
||||
multi_line_message = """<|fim|>
|
||||
print(multi_line_message)
|
||||
`,
|
||||
llmOutput: `This is a multi-line message.
|
||||
It continues across multiple lines,
|
||||
which allows for easy reading and formatting.
|
||||
"""
|
||||
`,
|
||||
expectedCompletion: `This is a multi-line message.
|
||||
It continues across multiple lines,
|
||||
which allows for easy reading and formatting.
|
||||
"""
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a simple Go function declaration",
|
||||
filename: "simpleFunction.go",
|
||||
|
|
@ -511,19 +721,6 @@ func main() {
|
|||
expectedCompletion: `
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL query with subquery and alias in SELECT clause",
|
||||
filename: "complex_query.sql",
|
||||
input: `SELECT u.id,
|
||||
u.name,
|
||||
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
|
||||
FROM users u
|
||||
WHERE u.active = 1
|
||||
<|fim|>`,
|
||||
llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
|
||||
expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL query with nested functions and missing bracket",
|
||||
|
|
@ -536,6 +733,49 @@ func main() {
|
|||
llmOutput: `8.5)`,
|
||||
expectedCompletion: `8.5)`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL script with employee and product tables",
|
||||
filename: "database.sql",
|
||||
input: `
|
||||
CREATE TABLE employees (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
age INT NOT NULL,
|
||||
position VARCHAR(100)
|
||||
);
|
||||
|
||||
CREATE TABLE products (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(100),
|
||||
price DECIMAL(8,2) NOT NULL<FIM> '0.00',
|
||||
quantity INT NOT NULL DEFAULT '0'
|
||||
);
|
||||
|
||||
INSERT INTO employees (name, age, position) VALUES ('John Doe', 30, 'Developer');
|
||||
INSERT INTO products (name, price, quantity) VALUES ('Apple', '1.99', '47');
|
||||
|
||||
SELECT * FROM products ORDER BY name DESC LIMIT 3;
|
||||
SELECT * FROM products WHERE price > '0';
|
||||
SELECT * FROM products WHERE quantity > '100';
|
||||
SELECT * FROM employees WHERE age > 25;
|
||||
`,
|
||||
llmOutput: " DEFAULT",
|
||||
expectedCompletion: " DEFAULT",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL query with subquery and alias in SELECT clause",
|
||||
filename: "complex_query.sql",
|
||||
input: `SELECT u.id,
|
||||
u.name,
|
||||
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
|
||||
FROM users u
|
||||
WHERE u.active = 1
|
||||
<|fim|>`,
|
||||
llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
|
||||
expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete multi-line SQL query with CASE statements",
|
||||
|
|
@ -637,57 +877,6 @@ squared_numbers = numbers.<|fim|>
|
|||
expectedCompletion: `map { |n| n ** 2 }`,
|
||||
filename: "array_methods.rb",
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a Java method within a class",
|
||||
filename: "Calculator.java",
|
||||
input: `
|
||||
public class Calculator {
|
||||
private double result;
|
||||
|
||||
public Calculator() {
|
||||
this.result = 0.0;
|
||||
}
|
||||
|
||||
public void add(double number) {
|
||||
result += number;
|
||||
<|fim|>`,
|
||||
llmOutput: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}
|
||||
`,
|
||||
expectedCompletion: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Java when inside a block",
|
||||
filename: "Main.java",
|
||||
input: `
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (i % 2 == 0) {
|
||||
System.out.println("Even: " + i);
|
||||
} else {
|
||||
<|fim|>
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
llmOutput: `
|
||||
System.out.println("Odd: " + i);
|
||||
`,
|
||||
expectedCompletion: `
|
||||
System.out.println("Odd: " + i);
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Java within a string",
|
||||
filename: "App.java",
|
||||
|
|
@ -717,7 +906,6 @@ public class App {
|
|||
llmOutput: " int multiply(int a, int b);",
|
||||
expectedCompletion: " int multiply(int a, int b);",
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should autocomplete C++ for loop syntax",
|
||||
filename: "test.cpp",
|
||||
|
|
@ -730,64 +918,6 @@ public class App {
|
|||
llmOutput: "i++",
|
||||
expectedCompletion: "i++",
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a Markdown list with nested items",
|
||||
filename: "test.md",
|
||||
input: `
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Subitem 1
|
||||
<|fim|>
|
||||
- Item 3
|
||||
`,
|
||||
llmOutput: ` - Subitem 2
|
||||
- Subitem 3
|
||||
`,
|
||||
expectedCompletion: ` - Subitem 2
|
||||
- Subitem 3
|
||||
`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete a Markdown heading and preserve formatting",
|
||||
filename: "test.md",
|
||||
input: `# My Document
|
||||
|
||||
## Introduction
|
||||
This is a sample document for testing.
|
||||
|
||||
## <|fim|>
|
||||
### Conclusion
|
||||
Thank you for reading.
|
||||
`,
|
||||
llmOutput: `Features
|
||||
Here is a list of features:
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
`,
|
||||
expectedCompletion: `Features
|
||||
Here is a list of features:
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should complete a Markdown code block",
|
||||
filename: "test.md",
|
||||
input: `
|
||||
Here is a sample JavaScript function:
|
||||
|
||||
\`\`\`javascript
|
||||
function sayHello() {
|
||||
console.log("Hello, <|fim|>
|
||||
}
|
||||
\`\`\`
|
||||
`,
|
||||
llmOutput: `world!");
|
||||
`,
|
||||
expectedCompletion: `world!");
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete JSON object inside an array",
|
||||
filename: "data.json",
|
||||
|
|
@ -801,40 +931,6 @@ function sayHello() {
|
|||
llmOutput: `, { "id": 3, "name": "Charlie" }`,
|
||||
expectedCompletion: `, { "id": 3, "name": "Charlie" }`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete nested JSON objects",
|
||||
filename: "config.json",
|
||||
input: `{
|
||||
"server": {
|
||||
"host": "localhost",
|
||||
"port": 8080,
|
||||
"features": {
|
||||
"enableLogging": true,
|
||||
"maxConnections": 100
|
||||
<|fim|>
|
||||
}
|
||||
}`,
|
||||
llmOutput: `,
|
||||
"timeout": 5000
|
||||
}`,
|
||||
expectedCompletion: `,
|
||||
"timeout": 5000
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete JSON object with missing bracket",
|
||||
filename: "settings.json",
|
||||
input: `{
|
||||
"theme": "dark",
|
||||
"language": "en"<|fim|>
|
||||
`,
|
||||
llmOutput: `,
|
||||
"notifications": true
|
||||
}`,
|
||||
expectedCompletion: `,
|
||||
"notifications": true
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete within a CSV record",
|
||||
filename: "test.csv",
|
||||
|
|
@ -986,28 +1082,6 @@ impl Calculator {
|
|||
println!("Cannot divide by zero.");
|
||||
}
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Rust match arms",
|
||||
filename: "main.rs",
|
||||
input: `
|
||||
fn get_status_code_description(code: u16) -> &'static str {
|
||||
match code {
|
||||
200 => "OK",
|
||||
404 => "Not Found",
|
||||
500 => "Internal Server Error",
|
||||
<|fim|>
|
||||
}
|
||||
}
|
||||
`,
|
||||
llmOutput: `403 => "Forbidden",
|
||||
401 => "Unauthorized",
|
||||
_ => "Unknown Status",
|
||||
`,
|
||||
expectedCompletion: `403 => "Forbidden",
|
||||
401 => "Unauthorized",
|
||||
_ => "Unknown Status",
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Rust struct definition",
|
||||
|
|
@ -1753,17 +1827,15 @@ let oddSquares = [<|fim|>]`,
|
|||
llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`,
|
||||
expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`,
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should complete an F# recursive function",
|
||||
filename: "recursiveFunctions.fs",
|
||||
input: `let rec factorial n =
|
||||
if n <= 1 then 1
|
||||
else n <|fim|> factorial (n - 1)`,
|
||||
llmOutput: ` * `,
|
||||
expectedCompletion: ` * `,
|
||||
llmOutput: `*`,
|
||||
expectedCompletion: `*`,
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should complete F# member method inside a class type",
|
||||
filename: "bankAccount.fs",
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import Mock from "../../llm/llms/Mock";
|
||||
import { testConfigHandler, testIde } from "../../test/util/fixtures";
|
||||
import { AutocompleteInput, CompletionProvider } from "../completionProvider";
|
||||
import Mock from "../../../llm/llms/Mock";
|
||||
import { testConfigHandler, testIde } from "../../../test/util/fixtures";
|
||||
import { CompletionProvider } from "../../CompletionProvider";
|
||||
import { AutocompleteInput } from "../../util/types";
|
||||
|
||||
const FIM_DELIMITER = "<|fim|>";
|
||||
|
||||
68
core/autocomplete/generation/CompletionStreamer.ts
Normal file
68
core/autocomplete/generation/CompletionStreamer.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { CompletionOptions, ILLM } from "../..";
|
||||
import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { GeneratorReuseManager } from "./GeneratorReuseManager";
|
||||
|
||||
export class CompletionStreamer {
|
||||
private streamTransformPipeline = new StreamTransformPipeline();
|
||||
private generatorReuseManager: GeneratorReuseManager;
|
||||
|
||||
constructor(onError: (err: any) => void) {
|
||||
this.generatorReuseManager = new GeneratorReuseManager(onError);
|
||||
}
|
||||
|
||||
async *streamCompletionWithFilters(
|
||||
token: AbortSignal,
|
||||
llm: ILLM,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
prompt: string,
|
||||
multiline: boolean,
|
||||
completionOptions: Partial<CompletionOptions> | undefined,
|
||||
helper: HelperVars,
|
||||
) {
|
||||
// Try to reuse pending requests if what the user typed matches start of completion
|
||||
const generator = this.generatorReuseManager.getGenerator(
|
||||
prefix,
|
||||
() =>
|
||||
llm.supportsFim()
|
||||
? llm.streamFim(prefix, suffix, completionOptions)
|
||||
: llm.streamComplete(prompt, {
|
||||
...completionOptions,
|
||||
raw: true,
|
||||
}),
|
||||
multiline,
|
||||
);
|
||||
|
||||
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
|
||||
const fullStop = () =>
|
||||
this.generatorReuseManager.currentGenerator?.cancel();
|
||||
|
||||
// LLM
|
||||
const generatorWithCancellation = async function* () {
|
||||
for await (const update of generator) {
|
||||
if (token.aborted) {
|
||||
return;
|
||||
}
|
||||
yield update;
|
||||
}
|
||||
};
|
||||
|
||||
const initialGenerator = generatorWithCancellation();
|
||||
const transformedGenerator = helper.options.transform
|
||||
? this.streamTransformPipeline.transform(
|
||||
initialGenerator,
|
||||
prefix,
|
||||
suffix,
|
||||
multiline,
|
||||
completionOptions?.stop || [],
|
||||
fullStop,
|
||||
helper,
|
||||
)
|
||||
: initialGenerator;
|
||||
|
||||
for await (const update of transformedGenerator) {
|
||||
yield update;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,78 +1,4 @@
|
|||
export class ListenableGenerator<T> {
|
||||
private _source: AsyncGenerator<T>;
|
||||
private _buffer: T[] = [];
|
||||
private _listeners: Set<(value: T) => void> = new Set();
|
||||
private _isEnded = false;
|
||||
|
||||
constructor(
|
||||
source: AsyncGenerator<T>,
|
||||
private readonly onError: (e: any) => void,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.onError(e);
|
||||
} 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 {
|
||||
let i = 0;
|
||||
while (i < this._buffer.length) {
|
||||
yield this._buffer[i++];
|
||||
}
|
||||
while (!this._isEnded) {
|
||||
let resolve: (value: any) => void;
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
this._listeners.add(resolve!);
|
||||
});
|
||||
await promise;
|
||||
this._listeners.delete(resolve!);
|
||||
|
||||
// Possible timing caused something to slip in between
|
||||
// timers so we iterate over the buffer
|
||||
while (i < this._buffer.length) {
|
||||
yield this._buffer[i++];
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// this._listeners.delete(resolve!);
|
||||
}
|
||||
}
|
||||
}
|
||||
import { ListenableGenerator } from "./ListenableGenerator";
|
||||
|
||||
export class GeneratorReuseManager {
|
||||
currentGenerator: ListenableGenerator<string> | undefined;
|
||||
75
core/autocomplete/generation/ListenableGenerator.ts
Normal file
75
core/autocomplete/generation/ListenableGenerator.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
export class ListenableGenerator<T> {
|
||||
private _source: AsyncGenerator<T>;
|
||||
private _buffer: T[] = [];
|
||||
private _listeners: Set<(value: T) => void> = new Set();
|
||||
private _isEnded = false;
|
||||
|
||||
constructor(
|
||||
source: AsyncGenerator<T>,
|
||||
private readonly onError: (e: any) => void,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.onError(e);
|
||||
} 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 {
|
||||
let i = 0;
|
||||
while (i < this._buffer.length) {
|
||||
yield this._buffer[i++];
|
||||
}
|
||||
while (!this._isEnded) {
|
||||
let resolve: (value: any) => void;
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
this._listeners.add(resolve!);
|
||||
});
|
||||
await promise;
|
||||
this._listeners.delete(resolve!);
|
||||
|
||||
// Possible timing caused something to slip in between
|
||||
// timers so we iterate over the buffer
|
||||
while (i < this._buffer.length) {
|
||||
yield this._buffer[i++];
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// this._listeners.delete(resolve!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import type { ILLM } from "../index.js";
|
||||
import { longestCommonSubsequence } from "../util/lcs.js";
|
||||
import { lineIsRepeated } from "./streamTransforms/lineStream.js";
|
||||
import type { ILLM } from "../../index.js";
|
||||
import { longestCommonSubsequence } from "../../util/lcs.js";
|
||||
import { lineIsRepeated } from "../filtering/streamTransforms/lineStream.js";
|
||||
|
||||
function rewritesLineAbove(completion: string, prefix: string): boolean {
|
||||
const lineAbove = prefix
|
||||
|
|
@ -42,6 +42,10 @@ function isExtremeRepetition(completion: string): boolean {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
export function isOnlyWhitespace(completion: string): boolean {
|
||||
const whitespaceRegex = /^[\s]+$/;
|
||||
return whitespaceRegex.test(completion);
|
||||
}
|
||||
|
||||
export function postprocessCompletion({
|
||||
completion,
|
||||
|
|
@ -55,7 +59,7 @@ export function postprocessCompletion({
|
|||
suffix: string;
|
||||
}): string | undefined {
|
||||
// Don't return empty
|
||||
if (completion.trim().length <= 0) {
|
||||
if (isOnlyWhitespace(completion)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
|
@ -69,9 +73,6 @@ export function postprocessCompletion({
|
|||
return undefined;
|
||||
}
|
||||
|
||||
// Remove trailing whitespace
|
||||
completion = completion.trimEnd();
|
||||
|
||||
if (llm.model.includes("codestral")) {
|
||||
// Codestral sometimes starts with an extra space
|
||||
if (completion[0] === " " && completion[1] !== " ") {
|
||||
|
|
@ -81,19 +82,23 @@ export function postprocessCompletion({
|
|||
}
|
||||
}
|
||||
|
||||
// If completion starts with multiple whitespaces, but the cursor is at the end of the line
|
||||
// then it should probably be on a new line
|
||||
if (
|
||||
(completion.startsWith(" ") || completion.startsWith("\t")) &&
|
||||
!prefix.endsWith("\n") &&
|
||||
(suffix.startsWith("\n") || suffix.trim().length === 0)
|
||||
) {
|
||||
// completion = "\n" + completion;
|
||||
return undefined;
|
||||
}
|
||||
// // If completion starts with multiple whitespaces, but the cursor is at the end of the line
|
||||
// // then it should probably be on a new line
|
||||
// if (
|
||||
// (completion.startsWith(" ") || completion.startsWith("\t")) &&
|
||||
// !prefix.endsWith("\n") &&
|
||||
// (suffix.startsWith("\n") || suffix.trim().length === 0)
|
||||
// ) {
|
||||
// completion = "\n" + completion;
|
||||
// }
|
||||
|
||||
// If prefix ends with space and so does completion, then remove the space from completion
|
||||
if (prefix.endsWith(" ") && completion.startsWith(" ")) {
|
||||
if (
|
||||
prefix.split("\n").pop()?.trim() !== "" &&
|
||||
prefix.endsWith(" ") &&
|
||||
completion.startsWith(" ")
|
||||
) {
|
||||
const test = prefix.split("\n").pop()?.trim() !== "";
|
||||
completion = completion.slice(1);
|
||||
}
|
||||
|
||||
78
core/autocomplete/prefiltering/index.ts
Normal file
78
core/autocomplete/prefiltering/index.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import path from "node:path";
|
||||
import { IDE } from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
import { getConfigJsonPath } from "../../util/paths";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
async function isDisabledForFile(
|
||||
currentFilepath: string,
|
||||
disableInFiles: string[] | undefined,
|
||||
ide: IDE,
|
||||
) {
|
||||
if (disableInFiles) {
|
||||
// Relative path needed for `ignore`
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let filepath = currentFilepath;
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const relativePath = path.relative(workspaceDir, filepath);
|
||||
const relativePathBase = relativePath.split(path.sep).at(0);
|
||||
const isInWorkspace =
|
||||
!path.isAbsolute(relativePath) && relativePathBase !== "..";
|
||||
if (isInWorkspace) {
|
||||
filepath = path.relative(workspaceDir, filepath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Worst case we can check filetype glob patterns
|
||||
if (filepath === currentFilepath) {
|
||||
filepath = getBasename(filepath);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const pattern = ignore.default().add(options.disableInFiles);
|
||||
if (pattern.ignores(filepath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function shouldLanguageSpecificPrefilter(helper: HelperVars) {
|
||||
const line = helper.fileLines[helper.pos.line] ?? "";
|
||||
for (const endOfLine of helper.lang.endOfLine) {
|
||||
if (line.endsWith(endOfLine) && helper.pos.character >= line.length) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function shouldPrefilter(
|
||||
helper: HelperVars,
|
||||
ide: IDE,
|
||||
): Promise<boolean> {
|
||||
// Allow disabling autocomplete from config.json
|
||||
if (helper.options.disable) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check whether we're in the continue config.json file
|
||||
if (helper.filepath === getConfigJsonPath()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check whether autocomplete is disabled for this file
|
||||
if (
|
||||
await isDisabledForFile(helper.filepath, helper.options.disableInFiles, ide)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// if (
|
||||
// helper.options.transform &&
|
||||
// (await shouldLanguageSpecificPrefilter(helper))
|
||||
// ) {
|
||||
// return true;
|
||||
// }
|
||||
|
||||
return false;
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
import { RangeInFile } from "../index.js";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFile & {
|
||||
timestamp: number;
|
||||
lines: string[];
|
||||
symbols: Set<string>;
|
||||
};
|
||||
|
||||
export function findMatchingRange(
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
linePrefix: string,
|
||||
): RecentlyEditedRange | undefined {
|
||||
return recentlyEditedRanges.find((recentlyEditedRange) => {
|
||||
return recentlyEditedRange.lines.some((line) =>
|
||||
line.startsWith(linePrefix),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import { BranchAndDir, Chunk } from "../index.js";
|
||||
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js";
|
||||
|
||||
export async function fullTextRetrieve(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
indexTag: BranchAndDir,
|
||||
): 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({
|
||||
tags: [indexTag],
|
||||
text: searchString,
|
||||
n: 3,
|
||||
});
|
||||
results.push(...chunks);
|
||||
});
|
||||
return results;
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
import { AstPath } from "./ast";
|
||||
import { AutocompleteLanguageInfo } from "./languages";
|
||||
|
||||
const BLOCK_TYPES = ["body", "statement_block"];
|
||||
|
||||
function isMidlineCompletion(prefix: string, suffix: string): boolean {
|
||||
return !suffix.startsWith("\n");
|
||||
}
|
||||
|
||||
export async function shouldCompleteMultiline(
|
||||
treePath: AstPath | undefined,
|
||||
fullPrefix: string,
|
||||
fullSuffix: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
): Promise<boolean> {
|
||||
// Don't complete multi-line if you are mid-line
|
||||
if (isMidlineCompletion(fullPrefix, fullSuffix)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't complete multi-line for single-line comments
|
||||
if (
|
||||
fullPrefix
|
||||
.split("\n")
|
||||
.slice(-1)[0]
|
||||
?.trimStart()
|
||||
.startsWith(language.singleLineComment)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
// Fill in the middle prompts
|
||||
|
||||
import { CompletionOptions } from "../index.js";
|
||||
import { getLastNPathParts, shortestRelativePaths } from "../util/index.js";
|
||||
import { AutocompleteSnippet } from "./ranking.js";
|
||||
import { CompletionOptions } from "../../index.js";
|
||||
import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js";
|
||||
import { AutocompleteSnippet } from "../context/ranking/index.js";
|
||||
|
||||
interface AutocompleteTemplate {
|
||||
export interface AutocompleteTemplate {
|
||||
compilePrefixSuffix?: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
44
core/autocomplete/templating/constructPrefixSuffix.ts
Normal file
44
core/autocomplete/templating/constructPrefixSuffix.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { IDE } from "../..";
|
||||
import { getRangeInString } from "../../util/ranges";
|
||||
import { languageForFilepath } from "../constants/AutocompleteLanguageInfo";
|
||||
|
||||
import { AutocompleteInput } from "../util/types";
|
||||
|
||||
/**
|
||||
* We have to handle a few edge cases in getting the entire prefix/suffix for the current file.
|
||||
* This is entirely prior to finding snippets from other files
|
||||
*/
|
||||
export async function constructInitialPrefixSuffix(
|
||||
input: AutocompleteInput,
|
||||
ide: IDE,
|
||||
): Promise<{
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
}> {
|
||||
const lang = languageForFilepath(input.filepath);
|
||||
|
||||
const fileContents =
|
||||
input.manuallyPassFileContents ?? (await ide.readFile(input.filepath));
|
||||
const fileLines = fileContents.split("\n");
|
||||
let prefix =
|
||||
getRangeInString(fileContents, {
|
||||
start: { line: 0, character: 0 },
|
||||
end: input.selectedCompletionInfo?.range.start ?? input.pos,
|
||||
}) + (input.selectedCompletionInfo?.text ?? "");
|
||||
|
||||
if (input.injectDetails) {
|
||||
const lines = prefix.split("\n");
|
||||
prefix = `${lines.slice(0, -1).join("\n")}\n${
|
||||
lang.singleLineComment
|
||||
} ${input.injectDetails
|
||||
.split("\n")
|
||||
.join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`;
|
||||
}
|
||||
|
||||
const suffix = getRangeInString(fileContents, {
|
||||
start: input.pos,
|
||||
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
|
||||
});
|
||||
|
||||
return { prefix, suffix };
|
||||
}
|
||||
33
core/autocomplete/templating/getStopTokens.ts
Normal file
33
core/autocomplete/templating/getStopTokens.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { CompletionOptions } from "../..";
|
||||
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
|
||||
|
||||
const DOUBLE_NEWLINE = "\n\n";
|
||||
const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n";
|
||||
// TODO: Do we want to stop completions when reaching a `/src/` string?
|
||||
const SRC_DIRECTORY = "/src/";
|
||||
// Starcoder2 tends to output artifacts starting with the letter "t"
|
||||
const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
|
||||
const PYTHON_ENCODING = "#- coding: utf-8";
|
||||
const CODE_BLOCK_END = "```";
|
||||
|
||||
const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
|
||||
const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END];
|
||||
|
||||
export function getStopTokens(
|
||||
completionOptions: Partial<CompletionOptions> | undefined,
|
||||
lang: AutocompleteLanguageInfo,
|
||||
model: string,
|
||||
): string[] {
|
||||
const stopTokens = [
|
||||
...(completionOptions?.stop || []),
|
||||
// ...multilineStops,
|
||||
...commonStops,
|
||||
...(model.toLowerCase().includes("starcoder2")
|
||||
? STARCODER2_T_ARTIFACTS
|
||||
: []),
|
||||
...(lang.stopWords ?? []),
|
||||
// ...lang.topLevelKeywords.map((word) => `\n${word}`),
|
||||
];
|
||||
|
||||
return stopTokens;
|
||||
}
|
||||
149
core/autocomplete/templating/index.ts
Normal file
149
core/autocomplete/templating/index.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { CompletionOptions } from "../..";
|
||||
import { getBasename, getLastNPathParts } from "../../util";
|
||||
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
|
||||
import { AutocompleteSnippet } from "../context/ranking";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import {
|
||||
AutocompleteTemplate,
|
||||
getTemplateForModel,
|
||||
} from "./AutocompleteTemplate";
|
||||
import { getStopTokens } from "./getStopTokens";
|
||||
|
||||
export function formatExternalSnippet(
|
||||
filepath: string,
|
||||
snippet: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
) {
|
||||
const comment = language.singleLineComment;
|
||||
const lines = [
|
||||
`${comment} Path: ${getBasename(filepath)}`,
|
||||
...snippet
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => `${comment} ${line}`),
|
||||
comment,
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
function renderStringTemplate(
|
||||
template: string,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
lang: AutocompleteLanguageInfo,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
) {
|
||||
const filename = getBasename(filepath);
|
||||
const compiledTemplate = Handlebars.compile(template);
|
||||
|
||||
// Format snippets as comments and prepend to prefix
|
||||
const formattedSnippets = snippets
|
||||
.map((snippet) =>
|
||||
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
|
||||
)
|
||||
.join("\n");
|
||||
if (formattedSnippets.length > 0) {
|
||||
prefix = `${formattedSnippets}\n\n${prefix}`;
|
||||
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
|
||||
// If it's an empty file, include the file name as a comment
|
||||
prefix = `${lang.singleLineComment} ${getLastNPathParts(
|
||||
filepath,
|
||||
2,
|
||||
)}\n${prefix}`;
|
||||
}
|
||||
|
||||
const prompt = compiledTemplate({
|
||||
prefix,
|
||||
suffix,
|
||||
filename,
|
||||
reponame,
|
||||
language: lang.name,
|
||||
});
|
||||
return prompt;
|
||||
}
|
||||
|
||||
function getTemplate(helper: HelperVars): AutocompleteTemplate {
|
||||
if (helper.options.template) {
|
||||
return {
|
||||
template: helper.options.template,
|
||||
completionOptions: {},
|
||||
compilePrefixSuffix: undefined,
|
||||
};
|
||||
}
|
||||
return getTemplateForModel(helper.modelName);
|
||||
}
|
||||
|
||||
export function renderPrompt(
|
||||
snippets: AutocompleteSnippet[],
|
||||
workspaceDirs: string[],
|
||||
helper: HelperVars,
|
||||
): {
|
||||
prompt: string;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
completionOptions: Partial<CompletionOptions> | undefined;
|
||||
} {
|
||||
// If prefix is manually passed
|
||||
let prefix = helper.prunedPrefix;
|
||||
let suffix = helper.prunedSuffix;
|
||||
|
||||
if (helper.input.manuallyPassPrefix) {
|
||||
prefix = helper.input.manuallyPassPrefix;
|
||||
suffix = "";
|
||||
}
|
||||
|
||||
let prompt: string;
|
||||
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
|
||||
|
||||
let { template, compilePrefixSuffix, completionOptions } =
|
||||
getTemplate(helper);
|
||||
|
||||
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
|
||||
// into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint
|
||||
if (compilePrefixSuffix) {
|
||||
[prefix, suffix] = compilePrefixSuffix(
|
||||
prefix,
|
||||
suffix,
|
||||
helper.filepath,
|
||||
reponame,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
// Templates can be passed as a Handlebars template string or a function
|
||||
if (typeof template === "string") {
|
||||
prompt = renderStringTemplate(
|
||||
template,
|
||||
prefix,
|
||||
suffix,
|
||||
snippets,
|
||||
helper.lang,
|
||||
helper.filepath,
|
||||
reponame,
|
||||
);
|
||||
} else {
|
||||
prompt = template(
|
||||
prefix,
|
||||
suffix,
|
||||
helper.filepath,
|
||||
reponame,
|
||||
helper.lang.name,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
const stopTokens = getStopTokens(
|
||||
completionOptions,
|
||||
helper.lang,
|
||||
helper.modelName,
|
||||
);
|
||||
|
||||
completionOptions = {
|
||||
...completionOptions,
|
||||
stop: stopTokens,
|
||||
};
|
||||
|
||||
return { prompt, prefix, suffix, completionOptions };
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
##### Prompt #####
|
||||
class Calculator {
|
||||
constructor() {
|
||||
this.result = 0;
|
||||
}
|
||||
|
||||
add(number) {
|
||||
this.result += number;
|
||||
return this;
|
||||
}
|
||||
|
||||
subtract(number) {
|
||||
this.result -= number;
|
||||
return this;
|
||||
}
|
||||
|
||||
multiply(number) {
|
||||
this.result *= number;
|
||||
return this;
|
||||
}
|
||||
|
||||
divide(number) {
|
||||
if (number === 0) {
|
||||
throw new Error("Cannot divide by zero");
|
||||
}
|
||||
|
||||
<FIM>
|
||||
|
||||
this.result /= number;
|
||||
return this;
|
||||
}
|
||||
|
||||
getResult() {
|
||||
return this.result;
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
this.result /= number;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Calculator;
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
import {
|
||||
AutocompleteFileringTestInput,
|
||||
testAutocompleteFiltering,
|
||||
} from "./util";
|
||||
import { TEST_CASES } from "./testCases";
|
||||
|
||||
const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
|
||||
if (tests.some((test) => test.options?.only)) {
|
||||
return tests.filter((test) => test.options?.only);
|
||||
}
|
||||
|
||||
return tests;
|
||||
};
|
||||
|
||||
describe("llms/Mock", () => {
|
||||
describe("Autocomplete Filtering Tests", () => {
|
||||
beforeEach(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
});
|
||||
|
||||
describe("Should return unmodified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
});
|
||||
});
|
||||
|
||||
// TODO: Add test cases where modifying LLM output is desirable
|
||||
describe.skip("Should return modified LLM output", () => {});
|
||||
});
|
||||
});
|
||||
32
core/autocomplete/util/AutocompleteDebouncer.ts
Normal file
32
core/autocomplete/util/AutocompleteDebouncer.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
export class AutocompleteDebouncer {
|
||||
private debounceTimeout: NodeJS.Timeout | undefined = undefined;
|
||||
private debouncing = false;
|
||||
private lastUUID: string | undefined = undefined;
|
||||
|
||||
async delayAndShouldDebounce(debounceDelay: number): Promise<boolean> {
|
||||
// Debounce
|
||||
const uuid = uuidv4();
|
||||
this.lastUUID = uuid;
|
||||
|
||||
// Debounce
|
||||
if (this.debouncing) {
|
||||
this.debounceTimeout?.refresh();
|
||||
const lastUUID = await new Promise((resolve) =>
|
||||
setTimeout(() => {
|
||||
resolve(this.lastUUID);
|
||||
}, debounceDelay),
|
||||
);
|
||||
if (uuid !== lastUUID) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
this.debouncing = true;
|
||||
this.debounceTimeout = setTimeout(async () => {
|
||||
this.debouncing = false;
|
||||
}, debounceDelay);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
119
core/autocomplete/util/AutocompleteLoggingService.ts
Normal file
119
core/autocomplete/util/AutocompleteLoggingService.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { logDevData } from "../../util/devdata";
|
||||
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { AutocompleteOutcome } from "./types";
|
||||
|
||||
export class AutocompleteLoggingService {
|
||||
// Key is completionId
|
||||
private _abortControllers = new Map<string, AbortController>();
|
||||
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
|
||||
private _outcomes = new Map<string, AutocompleteOutcome>();
|
||||
_lastDisplayedCompletion: { id: string; displayedAt: number } | undefined =
|
||||
undefined;
|
||||
|
||||
public createAbortController(completionId: string): AbortController {
|
||||
const abortController = new AbortController();
|
||||
this._abortControllers.set(completionId, abortController);
|
||||
return abortController;
|
||||
}
|
||||
|
||||
public deleteAbortController(completionId: string) {
|
||||
this._abortControllers.delete(completionId);
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this._abortControllers.forEach((abortController, id) => {
|
||||
abortController.abort();
|
||||
});
|
||||
this._abortControllers.clear();
|
||||
}
|
||||
|
||||
public accept(completionId: string): AutocompleteOutcome | undefined {
|
||||
if (this._logRejectionTimeouts.has(completionId)) {
|
||||
clearTimeout(this._logRejectionTimeouts.get(completionId));
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
}
|
||||
|
||||
if (this._outcomes.has(completionId)) {
|
||||
const outcome = this._outcomes.get(completionId)!;
|
||||
this.logAutocompleteOutcome(outcome);
|
||||
this._outcomes.delete(completionId);
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
public cancelRejectionTimeout(completionId: string) {
|
||||
if (this._logRejectionTimeouts.has(completionId)) {
|
||||
clearTimeout(this._logRejectionTimeouts.get(completionId)!);
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
}
|
||||
|
||||
if (this._outcomes.has(completionId)) {
|
||||
this._outcomes.delete(completionId);
|
||||
}
|
||||
}
|
||||
|
||||
public markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
|
||||
const logRejectionTimeout = setTimeout(() => {
|
||||
// Wait 10 seconds, then assume it wasn't accepted
|
||||
outcome.accepted = false;
|
||||
this.logAutocompleteOutcome(outcome);
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
}, COUNT_COMPLETION_REJECTED_AFTER);
|
||||
this._outcomes.set(completionId, outcome);
|
||||
this._logRejectionTimeouts.set(completionId, logRejectionTimeout);
|
||||
|
||||
// If the previously displayed completion is still waiting for rejection,
|
||||
// and this one is a continuation of that (the outcome.completion is the same modulo prefix)
|
||||
// then we should cancel the rejection timeout
|
||||
const previous = this._lastDisplayedCompletion;
|
||||
const now = Date.now();
|
||||
if (previous && this._logRejectionTimeouts.has(previous.id)) {
|
||||
const previousOutcome = this._outcomes.get(previous.id);
|
||||
const c1 = previousOutcome?.completion.split("\n")[0] ?? "";
|
||||
const c2 = outcome.completion.split("\n")[0];
|
||||
if (
|
||||
previousOutcome &&
|
||||
(c1.endsWith(c2) ||
|
||||
c2.endsWith(c1) ||
|
||||
c1.startsWith(c2) ||
|
||||
c2.startsWith(c1))
|
||||
) {
|
||||
this.cancelRejectionTimeout(previous.id);
|
||||
} else if (now - previous.displayedAt < 500) {
|
||||
// If a completion isn't shown for more than
|
||||
this.cancelRejectionTimeout(previous.id);
|
||||
}
|
||||
}
|
||||
|
||||
this._lastDisplayedCompletion = {
|
||||
id: completionId,
|
||||
displayedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
private logAutocompleteOutcome(outcome: AutocompleteOutcome) {
|
||||
outcome.accepted = true;
|
||||
logDevData("autocomplete", outcome);
|
||||
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
|
||||
void Telemetry.capture(
|
||||
"autocomplete",
|
||||
{
|
||||
accepted: restOfOutcome.accepted,
|
||||
cacheHit: restOfOutcome.cacheHit,
|
||||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0],
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
multilineCompletions: restOfOutcome.multilineCompletions,
|
||||
time: restOfOutcome.time,
|
||||
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
|
||||
useRootPathContext: restOfOutcome.useRootPathContext,
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,17 @@
|
|||
import { Mutex } from "async-mutex";
|
||||
import { open } from "sqlite";
|
||||
import sqlite3 from "sqlite3";
|
||||
import { DatabaseConnection, truncateSqliteLikePattern } from "../indexing/refreshIndex.js";
|
||||
import { getTabAutocompleteCacheSqlitePath } from "../util/paths.js";
|
||||
import {
|
||||
DatabaseConnection,
|
||||
truncateSqliteLikePattern,
|
||||
} from "../../indexing/refreshIndex.js";
|
||||
import { getTabAutocompleteCacheSqlitePath } from "../../util/paths.js";
|
||||
|
||||
export class AutocompleteLruCache {
|
||||
private static capacity = 1000;
|
||||
private mutex = new Mutex();
|
||||
|
||||
constructor(private db: DatabaseConnection) { }
|
||||
constructor(private db: DatabaseConnection) {}
|
||||
|
||||
static async get(): Promise<AutocompleteLruCache> {
|
||||
const db = await open({
|
||||
175
core/autocomplete/util/HelperVars.ts
Normal file
175
core/autocomplete/util/HelperVars.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import { IDE, TabAutocompleteOptions } from "../..";
|
||||
import {
|
||||
countTokens,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
} from "../../llm/countTokens";
|
||||
import {
|
||||
AutocompleteLanguageInfo,
|
||||
languageForFilepath,
|
||||
} from "../constants/AutocompleteLanguageInfo";
|
||||
import { constructInitialPrefixSuffix } from "../templating/constructPrefixSuffix";
|
||||
import { AstPath, getAst, getTreePathAtCursor } from "./ast";
|
||||
import { AutocompleteInput } from "./types";
|
||||
|
||||
/**
|
||||
* A collection of variables that are often accessed throughout the autocomplete pipeline
|
||||
* It's noisy to re-calculate all the time or inject them into each function
|
||||
*/
|
||||
export class HelperVars {
|
||||
lang: AutocompleteLanguageInfo;
|
||||
treePath: AstPath | undefined;
|
||||
|
||||
private _fileContents: string | undefined;
|
||||
private _fileLines: string[] | undefined;
|
||||
private _fullPrefix: string | undefined;
|
||||
private _fullSuffix: string | undefined;
|
||||
private _prunedPrefix: string | undefined;
|
||||
private _prunedSuffix: string | undefined;
|
||||
|
||||
private constructor(
|
||||
public readonly input: AutocompleteInput,
|
||||
public readonly options: TabAutocompleteOptions,
|
||||
public readonly modelName: string,
|
||||
private readonly ide: IDE,
|
||||
) {
|
||||
this.lang = languageForFilepath(input.filepath);
|
||||
}
|
||||
|
||||
private async init() {
|
||||
// Don't do anything if already initialized
|
||||
if (this._fileContents !== undefined) return;
|
||||
|
||||
this._fileContents =
|
||||
this.input.manuallyPassFileContents ??
|
||||
(await this.ide.readFile(this.filepath));
|
||||
|
||||
this._fileLines = this._fileContents.split("\n");
|
||||
|
||||
// Construct full prefix/suffix (a few edge cases handled in here)
|
||||
const { prefix: fullPrefix, suffix: fullSuffix } =
|
||||
await constructInitialPrefixSuffix(this.input, this.ide);
|
||||
this._fullPrefix = fullPrefix;
|
||||
this._fullSuffix = fullSuffix;
|
||||
|
||||
const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix();
|
||||
this._prunedPrefix = prunedPrefix;
|
||||
this._prunedSuffix = prunedSuffix;
|
||||
|
||||
try {
|
||||
const ast = await getAst(this.filepath, fullPrefix + fullSuffix);
|
||||
if (ast) {
|
||||
this.treePath = await getTreePathAtCursor(ast, fullPrefix.length);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to parse AST", e);
|
||||
}
|
||||
}
|
||||
|
||||
static async create(
|
||||
input: AutocompleteInput,
|
||||
options: TabAutocompleteOptions,
|
||||
modelName: string,
|
||||
ide: IDE,
|
||||
): Promise<HelperVars> {
|
||||
const instance = new HelperVars(input, options, modelName, ide);
|
||||
await instance.init();
|
||||
return instance;
|
||||
}
|
||||
|
||||
prunePrefixSuffix() {
|
||||
// Construct basic prefix
|
||||
const maxPrefixTokens =
|
||||
this.options.maxPromptTokens * this.options.prefixPercentage;
|
||||
const prunedPrefix = pruneLinesFromTop(
|
||||
this.fullPrefix,
|
||||
maxPrefixTokens,
|
||||
this.modelName,
|
||||
);
|
||||
|
||||
// Construct suffix
|
||||
const maxSuffixTokens = Math.min(
|
||||
this.options.maxPromptTokens - countTokens(prunedPrefix, this.modelName),
|
||||
this.options.maxSuffixPercentage * this.options.maxPromptTokens,
|
||||
);
|
||||
const prunedSuffix = pruneLinesFromBottom(
|
||||
this.fullSuffix,
|
||||
maxSuffixTokens,
|
||||
this.modelName,
|
||||
);
|
||||
|
||||
return {
|
||||
prunedPrefix,
|
||||
prunedSuffix,
|
||||
};
|
||||
}
|
||||
|
||||
// Fast access
|
||||
get filepath() {
|
||||
return this.input.filepath;
|
||||
}
|
||||
get pos() {
|
||||
return this.input.pos;
|
||||
}
|
||||
get maxSnippetTokens() {
|
||||
return this.options.maxPromptTokens * this.options.maxSnippetPercentage;
|
||||
}
|
||||
get prunedCaretWindow() {
|
||||
return this.prunedPrefix + this.prunedSuffix;
|
||||
}
|
||||
|
||||
// Getters for lazy access
|
||||
get fileContents(): string {
|
||||
if (this._fileContents === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing fileContents",
|
||||
);
|
||||
}
|
||||
return this._fileContents;
|
||||
}
|
||||
|
||||
get fileLines(): string[] {
|
||||
if (this._fileLines === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing fileLines",
|
||||
);
|
||||
}
|
||||
return this._fileLines;
|
||||
}
|
||||
|
||||
get fullPrefix(): string {
|
||||
if (this._fullPrefix === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing fullPrefix",
|
||||
);
|
||||
}
|
||||
return this._fullPrefix;
|
||||
}
|
||||
|
||||
get fullSuffix(): string {
|
||||
if (this._fullSuffix === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing fullSuffix",
|
||||
);
|
||||
}
|
||||
return this._fullSuffix;
|
||||
}
|
||||
|
||||
get prunedPrefix(): string {
|
||||
if (this._prunedPrefix === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing prunedPrefix",
|
||||
);
|
||||
}
|
||||
return this._prunedPrefix;
|
||||
}
|
||||
|
||||
get prunedSuffix(): string {
|
||||
if (this._prunedSuffix === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing prunedSuffix",
|
||||
);
|
||||
}
|
||||
return this._prunedSuffix;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { getParserForFile } from "../util/treeSitter.js";
|
||||
import { RangeInFileWithContents } from "../../commands/util.js";
|
||||
import { getParserForFile } from "../../util/treeSitter.js";
|
||||
|
||||
export type AstPath = Parser.SyntaxNode[];
|
||||
|
||||
43
core/autocomplete/util/types.ts
Normal file
43
core/autocomplete/util/types.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../..";
|
||||
import { RangeInFileWithContents } from "../../commands/util";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFile & {
|
||||
timestamp: number;
|
||||
lines: string[];
|
||||
symbols: Set<string>;
|
||||
};
|
||||
|
||||
export interface AutocompleteInput {
|
||||
completionId: string;
|
||||
filepath: string;
|
||||
pos: Position;
|
||||
recentlyEditedFiles: RangeInFileWithContents[];
|
||||
recentlyEditedRanges: RecentlyEditedRange[];
|
||||
clipboardText: string;
|
||||
// Used for notebook files
|
||||
manuallyPassFileContents?: string;
|
||||
// Used for VS Code git commit input box
|
||||
manuallyPassPrefix?: string;
|
||||
selectedCompletionInfo?: {
|
||||
text: string;
|
||||
range: Range;
|
||||
};
|
||||
injectDetails?: string;
|
||||
}
|
||||
|
||||
export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
||||
accepted?: boolean;
|
||||
time: number;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
modelProvider: string;
|
||||
modelName: string;
|
||||
completionOptions: any;
|
||||
cacheHit: boolean;
|
||||
filepath: string;
|
||||
gitRepo?: string;
|
||||
completionId: string;
|
||||
uniqueId: string;
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
fixCodeLlamaFirstLineIndentation,
|
||||
stopAtLines,
|
||||
streamWithNewLines,
|
||||
} from "../../autocomplete/streamTransforms/lineStream";
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { stripImages } from "../../llm/images";
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import * as fs from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import path from "path";
|
||||
import { languageForFilepath } from "../../autocomplete/constructPrompt.js";
|
||||
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import ignore from "ignore";
|
|||
import path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
|
||||
import { CompletionProvider } from "./autocomplete/completionProvider";
|
||||
import { CompletionProvider } from "./autocomplete/CompletionProvider";
|
||||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import {
|
||||
setupBestConfig,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { distance } from "fastest-levenshtein";
|
|||
import path from "path";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { DiffLine } from "../..";
|
||||
import { LANGUAGES } from "../../autocomplete/languages";
|
||||
import { LANGUAGES } from "../../autocomplete/constants/AutocompleteLanguageInfo";
|
||||
import { myersDiff } from "../../diff/myers";
|
||||
import { getParserForFile } from "../../util/treeSitter";
|
||||
import { findInAst } from "./findInAst";
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { ILLM } from "../..";
|
|||
import {
|
||||
filterLeadingNewline,
|
||||
stopAtLines,
|
||||
} from "../../autocomplete/streamTransforms/lineStream";
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { dedent } from "../../util";
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import {
|
|||
filterLeadingAndTrailingNewLineInsertion,
|
||||
filterLeadingNewline,
|
||||
stopAtLines,
|
||||
} from "../../autocomplete/streamTransforms/lineStream";
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream.js";
|
||||
import { streamDiff } from "../../diff/streamDiff.js";
|
||||
import { LineStream, streamLines } from "../../diff/util.js";
|
||||
import { DiffLine, ILLM } from "../../index.js";
|
||||
|
|
@ -43,7 +43,7 @@ export async function* streamLazyApply(
|
|||
let lazyCompletionLines = streamLines(lazyCompletion, true);
|
||||
// Process line output
|
||||
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
|
||||
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => { }, ["```"]);
|
||||
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
|
||||
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
|
||||
|
||||
// Fill in unchanged code
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import {
|
|||
filterLeadingAndTrailingNewLineInsertion,
|
||||
skipLines,
|
||||
stopAtLines,
|
||||
} from "../autocomplete/streamTransforms/lineStream.js";
|
||||
} from "../autocomplete/filtering/streamTransforms/lineStream.js";
|
||||
import { streamDiff } from "../diff/streamDiff.js";
|
||||
import { streamLines } from "../diff/util.js";
|
||||
import { ChatMessage, DiffLine, ILLM, Prediction } from "../index.js";
|
||||
|
|
|
|||
13
core/index.d.ts
vendored
13
core/index.d.ts
vendored
|
|
@ -48,9 +48,9 @@ export interface IndexingProgressUpdate {
|
|||
export type PromptTemplate =
|
||||
| string
|
||||
| ((
|
||||
history: ChatMessage[],
|
||||
otherData: Record<string, string>,
|
||||
) => string | ChatMessage[]);
|
||||
history: ChatMessage[],
|
||||
otherData: Record<string, string>,
|
||||
) => string | ChatMessage[]);
|
||||
|
||||
export interface ILLM extends LLMOptions {
|
||||
get providerName(): ModelProvider;
|
||||
|
|
@ -918,6 +918,7 @@ export interface TabAutocompleteOptions {
|
|||
disableInFiles?: string[];
|
||||
useImports?: boolean;
|
||||
useRootPathContext?: boolean;
|
||||
showWhateverWeHaveAtXMs?: number;
|
||||
}
|
||||
|
||||
export interface ContinueUIConfig {
|
||||
|
|
@ -1067,9 +1068,9 @@ export interface Config {
|
|||
embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider;
|
||||
/** The model that Continue will use for tab autocompletions. */
|
||||
tabAutocompleteModel?:
|
||||
| CustomLLM
|
||||
| ModelDescription
|
||||
| (CustomLLM | ModelDescription)[];
|
||||
| CustomLLM
|
||||
| ModelDescription
|
||||
| (CustomLLM | ModelDescription)[];
|
||||
/** Options for tab autocomplete */
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
/** UI styles customization */
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import type {
|
|||
SessionInfo,
|
||||
SiteIndexingConfig,
|
||||
} from "../";
|
||||
import type { AutocompleteInput } from "../autocomplete/completionProvider";
|
||||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
|
||||
export type ProtocolGeneratorType<T> = AsyncGenerator<{
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
|
|||
slidingWindowPrefixPercentage: 0.75,
|
||||
slidingWindowSize: 500,
|
||||
maxSnippetPercentage: 0.6,
|
||||
recentlyEditedSimilarityThreshold: 0.3,
|
||||
recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold.
|
||||
useCache: true,
|
||||
onlyMyCode: true,
|
||||
useOtherFiles: true,
|
||||
|
|
@ -22,6 +22,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
|
|||
useImports: true,
|
||||
useRootPathContext: true,
|
||||
transform: true,
|
||||
showWhateverWeHaveAtXMs: 300,
|
||||
};
|
||||
|
||||
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ export function getRangeInString(content: string, range: Range): string {
|
|||
return (
|
||||
lines[range.start.line]?.substring(
|
||||
range.start.character,
|
||||
range.end.character + 1,
|
||||
range.end.character,
|
||||
) ?? ""
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -115,6 +115,7 @@ export async function getLanguageForFile(
|
|||
return undefined;
|
||||
}
|
||||
let language = nameToLanguage.get(languageName);
|
||||
|
||||
if (!language) {
|
||||
language = await loadLanguageForFileExt(extension);
|
||||
nameToLanguage.set(languageName, language);
|
||||
|
|
@ -149,7 +150,9 @@ export async function getQueryForFile(
|
|||
const sourcePath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
"tree-sitter",
|
||||
...(process.env.NODE_ENV === "test"
|
||||
? ["extensions", "vscode", "tree-sitter"]
|
||||
: ["tree-sitter"]),
|
||||
queryType,
|
||||
`${fullLangName}.scm`,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import type { IDE } from "core";
|
||||
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
|
||||
import {
|
||||
AutocompleteOutcome,
|
||||
CompletionProvider,
|
||||
type AutocompleteInput,
|
||||
} from "core/autocomplete/completionProvider";
|
||||
type AutocompleteOutcome,
|
||||
} from "core/autocomplete/util/types";
|
||||
import { ConfigHandler } from "core/config/ConfigHandler";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import type { IDE, Range, RangeInFile } from "core";
|
||||
import { getAst, getTreePathAtCursor } from "core/autocomplete/ast";
|
||||
import { GetLspDefinitionsFunction } from "core/autocomplete/completionProvider";
|
||||
import { AutocompleteLanguageInfo } from "core/autocomplete/languages";
|
||||
import { AutocompleteSnippet } from "core/autocomplete/ranking";
|
||||
import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider";
|
||||
import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo";
|
||||
import { AutocompleteSnippet } from "core/autocomplete/context/ranking";
|
||||
import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast";
|
||||
import { RangeInFileWithContents } from "core/commands/util";
|
||||
import {
|
||||
FUNCTION_BLOCK_NODE_TYPES,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { getSymbolsForSnippet } from "core/autocomplete/ranking";
|
||||
import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited";
|
||||
import { getSymbolsForSnippet } from "core/autocomplete/context/ranking";
|
||||
import { RecentlyEditedRange } from "core/autocomplete/util/types";
|
||||
import { RangeInFileWithContents } from "core/commands/util";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Chunk, IDE } from "core";
|
||||
import { languageForFilepath } from "core/autocomplete/constructPrompt";
|
||||
import { languageForFilepath } from "core/autocomplete/constants/AutocompleteLanguageInfo";
|
||||
import { DEFAULT_IGNORE_DIRS } from "core/indexing/ignore";
|
||||
import { deduplicateArray } from "core/util";
|
||||
import { getParserForFile } from "core/util/treeSitter";
|
||||
|
|
|
|||
64
manual-testing-sandbox/AdvancedPage.tsx
Normal file
64
manual-testing-sandbox/AdvancedPage.tsx
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import React, { useState } from "react";
|
||||
|
||||
const AdvancedPage = () => {
|
||||
const [isDarkMode, setIsDarkMode] = useState(false);
|
||||
const [counter, setCounter] = useState(0);
|
||||
|
||||
const toggleDarkMode = () => {
|
||||
setIsDarkMode((prevMode) => !prevMode);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`}
|
||||
>
|
||||
<header className="mb-4 flex items-center justify-between border-b-2 pb-4">
|
||||
<h1 className="text-3xl font-bold">Welcome to the Advanced Page</h1>
|
||||
<button
|
||||
className="rounded bg-blue-500 px-4 py-2 text-white"
|
||||
onClick={toggleDarkMode}
|
||||
>
|
||||
Toggle Dark Mode
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<main className="flex flex-col items-center">
|
||||
<div className="mb-4">
|
||||
<p className="text-xl">
|
||||
Counter: <span className="font-bold">{counter}</span>
|
||||
</p>
|
||||
<button
|
||||
className="mt-2 rounded bg-green-500 px-4 py-2 text-white"
|
||||
onClick={() => setCounter(counter + 1)}
|
||||
>
|
||||
Increment
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-2">Some other interactive elements:</p>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Type something here..."
|
||||
className="mb-2 rounded border p-2"
|
||||
/>
|
||||
<div>
|
||||
<select className="rounded border p-2">
|
||||
<option value="option1">Option 1</option>
|
||||
<option value="option2">Option 2</option>
|
||||
<option value="option3">Option 3</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer className="mt-4 border-t-2 pt-4">
|
||||
<p className="text-center">
|
||||
© 2023 Advanced Page. All rights reserved.
|
||||
</p>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdvancedPage;
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
import React from "react";
|
||||
|
||||
export const Button = ({
|
||||
onClick,
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
onClick: () => void;
|
||||
}) => {
|
||||
return (
|
||||
<button className="btn btn-primary" onClick={onClick}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
|
@ -1,8 +1,83 @@
|
|||
{
|
||||
"active": true,
|
||||
"department": "Product Development",
|
||||
"location": {
|
||||
"country": "USA",
|
||||
"state": "California",
|
||||
"city": "San Francisco",
|
||||
"coordinates": {
|
||||
"latitude": 37.7749,
|
||||
"longitude": -122.4194
|
||||
}
|
||||
},
|
||||
"employees": [
|
||||
{ "name": "John Doe", "age": 30, "position": "Developer" },
|
||||
{ "name": "Jane Smith", "age": 25, "position": "Designer" },
|
||||
{ "name": "Emily Johnson", "age": 35, "position": "Manager" }
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"position": "Developer",
|
||||
"skills": ["JavaScript", "React", "Node.js"],
|
||||
"remote": false,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 95000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Jane Smith",
|
||||
"age": 25,
|
||||
"position": "Designer",
|
||||
"skills": ["Photoshop", "Illustrator"],
|
||||
"remote": true,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 70000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Emily Johnson",
|
||||
"age": 35,
|
||||
"position": "Manager",
|
||||
"teamSize": 8,
|
||||
"remote": true,
|
||||
"skills": ["Leadership", "Project Management"],
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 120000
|
||||
},
|
||||
"contact": {
|
||||
"email": "emily.johnson@company.com",
|
||||
"phone": "+1-202-555-0163"
|
||||
}
|
||||
}
|
||||
],
|
||||
"active": true
|
||||
"projects": [
|
||||
{
|
||||
"name": "Project Alpha",
|
||||
"deadline": "2023-12-31",
|
||||
"budget": 150000,
|
||||
"teamMembers": ["John Doe", "Jane Smith"]
|
||||
},
|
||||
{
|
||||
"name": "Project Beta",
|
||||
"deadline": "2024-06-30",
|
||||
"budget": 200000,
|
||||
"teamMembers": ["Emily Johnson"]
|
||||
}
|
||||
],
|
||||
"companyStats": {
|
||||
"founded": 2010,
|
||||
"annualRevenue": 2500000,
|
||||
"clients": [
|
||||
{
|
||||
"name": "Client A",
|
||||
"industry": "Technology",
|
||||
"engagements": ["Consulting", "Development"]
|
||||
},
|
||||
{
|
||||
"name": "Client B",
|
||||
"industry": "Finance",
|
||||
"engagements": ["Design"]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,11 @@
|
|||
</header>
|
||||
<div class="container">
|
||||
<p>This is a sample paragraph.</p>
|
||||
<ol>
|
||||
<li>Item 1</li>
|
||||
<li>Item 2</li>
|
||||
<li>Item 3</li>
|
||||
</ol>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue