diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index c3445498e..c41bbb389 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -5,17 +5,16 @@ import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; -import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { aggregateSnippets } from "./aggregateSnippets"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; // @prettier-ignore -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { AutocompleteSnippetDeprecated } from "./context/ranking/index.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; +import { getAllSnippets, TEMP__Snippets } from "./snippets/index.js"; import { renderPrompt } from "./templating/index.js"; +import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; import AutocompleteLruCache from "./util/AutocompleteLruCache.js"; @@ -32,14 +31,6 @@ const ERRORS_TO_IGNORE = [ "operation was aborted", ]; -export type GetLspDefinitionsFunction = ( - filepath: string, - contents: string, - cursorIndex: number, - ide: IDE, - lang: AutocompleteLanguageInfo, -) => Promise; - export class CompletionProvider { private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); @@ -171,21 +162,14 @@ export class CompletionProvider { 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); - - const [snippets, diff, clipboardContent, workspaceDirs] = + const [{ snippets, diff, clipboardContent }, workspaceDirs] = await Promise.all([ - aggregateSnippets( + getAllSnippets({ helper, - extraSnippets, - this.contextRetrievalService, - ), - this.ide.getDiff(true), - this.ide.getClipboardContent(), + ide: this.ide, + getDefinitionsFromLsp: this.getDefinitionsFromLsp, + contextRetrievalService: this.contextRetrievalService, + }), this.ide.getWorkspaceDirs(), ]); @@ -289,31 +273,31 @@ export class CompletionProvider { } } - private async _getExtraSnippets( - helper: HelperVars, - ): Promise { - 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 AutocompleteSnippetDeprecated[]) - : []; + // private async _getExtraSnippets( + // helper: HelperVars, + // ): Promise { + // 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 AutocompleteSnippetDeprecated[]) + // : []; - const workspaceDirs = await this.ide.getWorkspaceDirs(); - if (helper.options.onlyMyCode) { - extraSnippets = extraSnippets.filter((snippet) => { - return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); - }); - } + // const workspaceDirs = await this.ide.getWorkspaceDirs(); + // if (helper.options.onlyMyCode) { + // extraSnippets = extraSnippets.filter((snippet) => { + // return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); + // }); + // } - return extraSnippets; - } + // return extraSnippets; + // } } diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts deleted file mode 100644 index e6c750a4b..000000000 --- a/core/autocomplete/aggregateSnippets.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { - fillPromptWithSnippets, - rankAndOrderSnippets, - type AutocompleteSnippetDeprecated, -} from "./context/ranking/index.js"; -import { HelperVars } from "./util/HelperVars.js"; - -function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteSnippetDeprecated[], - caretWindow: string, -): AutocompleteSnippetDeprecated[] { - return snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), - ); -} - -export async function aggregateSnippets( - helper: HelperVars, - extraSnippets: AutocompleteSnippetDeprecated[], - contextRetrievalService: ContextRetrievalService, -): Promise { - let snippets = await contextRetrievalService.retrieveCandidateSnippets( - helper, - extraSnippets, - ); - - snippets = filterSnippetsAlreadyInCaretWindow( - snippets, - helper.prunedCaretWindow, - ); - - const scoredSnippets = rankAndOrderSnippets(snippets, helper); - - const finalSnippets = fillPromptWithSnippets( - scoredSnippets, - helper.maxSnippetTokens, - helper.modelName, - ); - - return finalSnippets; -} diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 66b67eec3..72e061fed 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -1,9 +1,12 @@ import { IDE } from "../.."; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; -import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; -import { AutocompleteSnippetDeprecated, getSymbolsForSnippet } from "./ranking"; +import { getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; export class ContextRetrievalService { @@ -18,79 +21,14 @@ export class ContextRetrievalService { ); } - public async retrieveCandidateSnippets( + public async getSnippetsFromImportDefinitions( helper: HelperVars, - extraSnippets: AutocompleteSnippetDeprecated[], - ) { - if (helper.options.useOtherFiles === false) { - return []; - } - - let snippets: AutocompleteSnippetDeprecated[] = []; - - // 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, - ): AutocompleteSnippetDeprecated[] { - 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 { + ): Promise { if (helper.options.useImports === false) { return []; } - const importSnippets = []; + const importSnippets: AutocompleteCodeSnippet[] = []; const fileInfo = this.importDefinitionsService.get(helper.filepath); if (fileInfo) { const { imports } = fileInfo; @@ -104,21 +42,32 @@ export class ContextRetrievalService { for (const symbol of symbols) { const rifs = imports[symbol]; if (Array.isArray(rifs)) { - importSnippets.push(...rifs); + const snippets: AutocompleteCodeSnippet[] = rifs.map((rif) => { + return { + filepath: rif.filepath, + content: rif.contents, + type: AutocompleteSnippetType.Code, + }; + }); + + importSnippets.push(...snippets); } } } + return importSnippets; } - findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, - ): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); + public async getRootPathSnippets( + helper: HelperVars, + ): Promise { + if (!helper.treePath) { + return []; + } + + return this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + ); } } diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 28e9b8112..a11389470 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,17 +1,9 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; import { Range } from "../../../index.js"; import { countTokens } from "../../../llm/countTokens.js"; +import { AutocompleteSnippetDeprecated } from "../../types.js"; import { HelperVars } from "../../util/HelperVars.js"; -/** - * @deprecated This type should be removed in the future or renamed. - * We have a new interface called AutocompleteSnippet which is more - * general. - */ -export type AutocompleteSnippetDeprecated = RangeInFileWithContents & { - score?: number; -}; - const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g; export function getSymbolsForSnippet(snippet: string): Set { const symbols = snippet @@ -24,7 +16,7 @@ export function getSymbolsForSnippet(snippet: string): Set { /** * Calculate similarity as number of shared symbols divided by total number of unique symbols between both. */ -export function jaccardSimilarity(a: string, b: string): number { +function jaccardSimilarity(a: string, b: string): number { const aSet = getSymbolsForSnippet(a); const bSet = getSymbolsForSnippet(b); const union = new Set([...aSet, ...bSet]).size; @@ -76,7 +68,7 @@ export function rankAndOrderSnippets( /** * Deduplicate code snippets by merging overlapping ranges into a single range. */ -export function deduplicateSnippets( +function deduplicateSnippets( snippets: Required[], ): Required[] { // Group by file @@ -166,54 +158,54 @@ export function fillPromptWithSnippets( /** * Remove one range from another range, which may lead to returning two disjoint ranges */ -function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { - if ( - orig.start.line >= remove.start.line && - orig.end.line <= remove.end.line - ) { - // / | | / - return []; - } - if ( - orig.start.line <= remove.start.line && - orig.end.line >= remove.end.line - ) { - // | / / | - // Splits the range - return [ - { - start: orig.start, - end: remove.start, - }, - { - start: remove.end, - end: orig.end, - }, - ]; - } - if ( - orig.start.line >= remove.start.line && - orig.end.line >= remove.end.line - ) { - // \ | / | - return [ - { - start: remove.end, - end: orig.end, - }, - ]; - } - if ( - orig.start.line <= remove.start.line && - orig.end.line <= remove.end.line - ) { - // | / | / - return [ - { - start: orig.start, - end: remove.start, - }, - ]; - } - return [orig]; -} +// function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { +// if ( +// orig.start.line >= remove.start.line && +// orig.end.line <= remove.end.line +// ) { +// // / | | / +// return []; +// } +// if ( +// orig.start.line <= remove.start.line && +// orig.end.line >= remove.end.line +// ) { +// // | / / | +// // Splits the range +// return [ +// { +// start: orig.start, +// end: remove.start, +// }, +// { +// start: remove.end, +// end: orig.end, +// }, +// ]; +// } +// if ( +// orig.start.line >= remove.start.line && +// orig.end.line >= remove.end.line +// ) { +// // \ | / | +// return [ +// { +// start: remove.end, +// end: orig.end, +// }, +// ]; +// } +// if ( +// orig.start.line <= remove.start.line && +// orig.end.line <= remove.end.line +// ) { +// // | / | / +// return [ +// { +// start: orig.start, +// end: remove.start, +// }, +// ]; +// } +// return [orig]; +// } diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts index 3fd3a3f17..88ee2bff3 100644 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,60 +1,61 @@ -import { RangeInFileWithContents } from "../../../commands/util.js"; +// import { RangeInFileWithContents } from "../../../commands/util.js"; +// import { AutocompleteSnippetDeprecated } from "../../types.js"; -import { AutocompleteSnippetDeprecated, jaccardSimilarity } from "./index.js"; +// import { jaccardSimilarity } from "./index.js"; -function* slidingWindow( - content: string, - windowSize: number, -): Generator { - const lines = content.split("\n"); +// function* slidingWindow( +// content: string, +// windowSize: number, +// ): Generator { +// const lines = content.split("\n"); - let charCount = 0; - let currWindowLines: string[] = []; - for (let i = 0; i < lines.length; i++) { - if (charCount + lines[i].length >= windowSize) { - yield currWindowLines.join("\n"); - currWindowLines = [lines[i]]; - charCount = 0; - } else { - currWindowLines.push(lines[i]); - } - charCount += lines[i].length; - } +// let charCount = 0; +// let currWindowLines: string[] = []; +// for (let i = 0; i < lines.length; i++) { +// if (charCount + lines[i].length >= windowSize) { +// yield currWindowLines.join("\n"); +// currWindowLines = [lines[i]]; +// charCount = 0; +// } else { +// currWindowLines.push(lines[i]); +// } +// charCount += lines[i].length; +// } - if (currWindowLines.length > 0) { - yield currWindowLines.join("\n"); - } -} +// if (currWindowLines.length > 0) { +// yield currWindowLines.join("\n"); +// } +// } -/** - * Match by similarity over sliding windows of recent documents. - * @param recentFiles - * @param prefix - * @param suffix - */ -export async function slidingWindowMatcher( - recentFiles: RangeInFileWithContents[], - windowAroundCursor: string, - topN: number, - windowSize: number, -): Promise { - // Sorted lowest similarity to highest - const topMatches: Required[] = []; +// /** +// * Match by similarity over sliding windows of recent documents. +// * @param recentFiles +// * @param prefix +// * @param suffix +// */ +// export async function slidingWindowMatcher( +// recentFiles: RangeInFileWithContents[], +// windowAroundCursor: string, +// topN: number, +// windowSize: number, +// ): Promise { +// // Sorted lowest similarity to highest +// const topMatches: Required[] = []; - for (const { filepath, contents, range } of recentFiles) { - for (const window of slidingWindow(contents, windowSize)) { - const score = jaccardSimilarity(window, windowAroundCursor); +// for (const { filepath, contents, range } of recentFiles) { +// for (const window of slidingWindow(contents, windowSize)) { +// const score = jaccardSimilarity(window, windowAroundCursor); - // Insertion sort - let i = -1; - while (++i < topMatches.length && score > topMatches[i].score) {} - topMatches.splice(i + 1, 0, { filepath, contents, score, range }); - if (topMatches.length > topN) { - topMatches.shift(); - } - } - } +// // Insertion sort +// let i = -1; +// while (++i < topMatches.length && score > topMatches[i].score) {} +// topMatches.splice(i + 1, 0, { filepath, contents, score, range }); +// if (topMatches.length > topN) { +// topMatches.shift(); +// } +// } +// } - // TODO: convert the arbitrary window frame to some whole AST node? - return topMatches; -} +// // TODO: convert the arbitrary window frame to some whole AST node? +// return topMatches; +// } diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 98a947fb1..a94e37e38 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -12,7 +12,11 @@ import { } from "../../../util/treeSitter"; import { AstPath } from "../../util/ast"; import { ImportDefinitionsService } from "../ImportDefinitionsService"; -import { AutocompleteSnippetDeprecated } from "../ranking"; +import { AutocompleteSnippetDeprecated } from "../../types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "../../snippets/types"; function getSyntaxTreeString( node: Parser.SyntaxNode, @@ -153,8 +157,8 @@ export class RootPathContextService { filepath: string, astPath: AstPath, // cursorIndex: number, - ): Promise { - const snippets: AutocompleteSnippetDeprecated[] = []; + ): Promise { + const snippets: AutocompleteCodeSnippet[] = []; let parentKey = filepath; for (const astNode of astPath.filter((node) => @@ -167,7 +171,16 @@ export class RootPathContextService { const foundInCache = this.cache.get(key); const newSnippets = foundInCache ?? (await this.getSnippetsForNode(filepath, astNode)); - snippets.push(...newSnippets); + + const formattedSnippets: AutocompleteCodeSnippet[] = newSnippets.map( + (item) => ({ + filepath: item.filepath, + content: item.contents, + type: AutocompleteSnippetType.Code, + }), + ); + + snippets.push(...formattedSnippets); if (!foundInCache) { this.cache.set(key, newSnippets); diff --git a/core/autocomplete/snippets/aggregateSnippets.ts b/core/autocomplete/snippets/aggregateSnippets.ts new file mode 100644 index 000000000..1562c6f57 --- /dev/null +++ b/core/autocomplete/snippets/aggregateSnippets.ts @@ -0,0 +1,45 @@ +// import { ContextRetrievalService } from "../context/ContextRetrievalService.js"; +// import { +// fillPromptWithSnippets, +// rankAndOrderSnippets, +// } from "../context/ranking/index.js"; +// import { AutocompleteSnippetDeprecated } from "../types.js"; +// import { HelperVars } from "../util/HelperVars.js"; + +// function filterSnippetsAlreadyInCaretWindow( +// snippets: AutocompleteSnippetDeprecated[], +// caretWindow: string, +// ): AutocompleteSnippetDeprecated[] { +// return snippets +// .map((snippet) => ({ ...snippet })) +// .filter( +// (s) => +// s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), +// ); +// } + +// export async function aggregateSnippets( +// helper: HelperVars, +// extraSnippets: AutocompleteSnippetDeprecated[], +// contextRetrievalService: ContextRetrievalService, +// ): Promise { +// let snippets = await contextRetrievalService.retrieveCandidateSnippets( +// helper, +// extraSnippets, +// ); + +// snippets = filterSnippetsAlreadyInCaretWindow( +// snippets, +// helper.prunedCaretWindow, +// ); + +// const scoredSnippets = rankAndOrderSnippets(snippets, helper); + +// const finalSnippets = fillPromptWithSnippets( +// scoredSnippets, +// helper.maxSnippetTokens, +// helper.modelName, +// ); + +// return finalSnippets; +// } diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts new file mode 100644 index 000000000..6f6c79ba3 --- /dev/null +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -0,0 +1,134 @@ +import { IDE } from "../../index"; +import { ContextRetrievalService } from "../context/ContextRetrievalService"; +import { GetLspDefinitionsFunction } from "../types"; +import { HelperVars } from "../util/HelperVars"; +import { + AutocompleteClipboardSnippet, + AutocompleteCodeSnippet, + AutocompleteDiffSnippet, + AutocompleteSnippetType, +} from "./types"; + +// 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) +async function getIdeSnippets( + helper: HelperVars, + ide: IDE, + getDefinitionsFromLsp: GetLspDefinitionsFunction, +): Promise { + const ideSnippets = (await Promise.race([ + getDefinitionsFromLsp( + helper.input.filepath, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, + ide, + helper.lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteCodeSnippet[]; + + if (helper.options.onlyMyCode) { + const workspaceDirs = await ide.getWorkspaceDirs(); + + return ideSnippets.filter((snippet) => + workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)), + ); + } + + return ideSnippets; +} + +function getSnippetsFromRecentlyEditedRanges( + helper: HelperVars, +): AutocompleteCodeSnippet[] { + if (helper.options.useRecentlyEdited === false) { + return []; + } + + return helper.input.recentlyEditedRanges.map((range) => { + return { + filepath: range.filepath, + content: range.lines.join("\n"), + score: 0.8, + type: AutocompleteSnippetType.Code, + }; + }); +} + +export type TEMP__Snippets = { + snippets: AutocompleteCodeSnippet[]; + diff: string | undefined; + clipboardContent: { + text: string; + copiedAt: string; + }; + new: { + rootPathSnippets: AutocompleteCodeSnippet[]; + importDefinitionSnippets: AutocompleteCodeSnippet[]; + ideSnippets: AutocompleteCodeSnippet[]; + recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; + diffSnippets: AutocompleteDiffSnippet[]; + clipboardSnippets: AutocompleteClipboardSnippet[]; + }; +}; + +export const getAllSnippets = async ({ + helper, + ide, + getDefinitionsFromLsp, + contextRetrievalService, +}: { + helper: HelperVars; + ide: IDE; + getDefinitionsFromLsp: GetLspDefinitionsFunction; + contextRetrievalService: ContextRetrievalService; +}): Promise => { + const recentlyEditedRangeSnippets = + getSnippetsFromRecentlyEditedRanges(helper); + + const [ + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + diff, + clipboardContent, + ] = await Promise.all([ + contextRetrievalService.getRootPathSnippets(helper), + contextRetrievalService.getSnippetsFromImportDefinitions(helper), + getIdeSnippets(helper, ide, getDefinitionsFromLsp), + ide.getDiff(true), + ide.getClipboardContent(), + ]); + + return { + snippets: [ + ...rootPathSnippets, + ...importDefinitionSnippets, + ...ideSnippets, + ...recentlyEditedRangeSnippets, + ], + diff, + clipboardContent, + new: { + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + recentlyEditedRangeSnippets, + diffSnippets: [diff].map((item) => { + return { + content: item, + type: AutocompleteSnippetType.Diff, + }; + }), + clipboardSnippets: [clipboardContent].map((item) => { + return { + content: item.text, + copiedAt: item.copiedAt, + type: AutocompleteSnippetType.Clipboard, + }; + }), + }, + }; +}; diff --git a/core/autocomplete/snippets/index.ts b/core/autocomplete/snippets/index.ts new file mode 100644 index 000000000..2a9e1a7ce --- /dev/null +++ b/core/autocomplete/snippets/index.ts @@ -0,0 +1 @@ +export * from "./getAllSnippets"; diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts index e39406b11..b97e07604 100644 --- a/core/autocomplete/snippets/types.ts +++ b/core/autocomplete/snippets/types.ts @@ -1,15 +1,28 @@ +export enum AutocompleteSnippetType { + Code = "code", + Diff = "diff", + Clipboard = "clipboard", +} + interface BaseAutocompleteSnippet { score?: number; content: string; + type: AutocompleteSnippetType; } export interface AutocompleteCodeSnippet extends BaseAutocompleteSnippet { filepath: string; + type: AutocompleteSnippetType.Code; } -export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {} +export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Diff; +} -export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {} +export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Clipboard; + copiedAt: string; +} export type AutocompleteSnippet = | AutocompleteCodeSnippet diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 11fd47333..b84337c0e 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -2,7 +2,8 @@ import { CompletionOptions } from "../../index.js"; import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; -import { AutocompleteSnippetDeprecated } from "../context/ranking/index.js"; +import { AutocompleteCodeSnippet } from "../snippets/types.js"; +import { AutocompleteSnippetDeprecated } from "../types.js"; export interface AutocompleteTemplate { compilePrefixSuffix?: ( @@ -10,7 +11,7 @@ export interface AutocompleteTemplate { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ) => [string, string]; template: | string @@ -20,7 +21,7 @@ export interface AutocompleteTemplate { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ) => string); completionOptions?: Partial; } @@ -73,7 +74,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ): [string, string] => { if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { @@ -86,7 +87,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { filepath, ]); const otherFiles = snippets - .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`) + .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.content}`) .join("\n\n"); return [ `${otherFiles}\n\n+++++ ${ @@ -101,7 +102,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ): string => { return `[SUFFIX]${suffix}[PREFIX]${prefix}`; }, @@ -133,15 +134,14 @@ const starcoder2FimTemplate: AutocompleteTemplate = { filename: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ): string => { const otherFiles = snippets.length === 0 ? "" : `${snippets .map((snippet) => { - return snippet.contents; - // return `${getBasename(snippet.filepath)}\n${snippet.contents}`; + return snippet.content; }) .join("")}`; @@ -187,7 +187,7 @@ const codegeexFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ): string => { const relativePaths = shortestRelativePaths([ ...snippets.map((snippet) => snippet.filepath), @@ -200,7 +200,7 @@ const codegeexFimTemplate: AutocompleteTemplate = { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } const references = `###REFERENCE:\n${snippets - .map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.contents}\n`) + .map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.content}\n`) .join("###REFERENCE:\n")}`; const prompt = `<|user|>\n${references}\n${baseTemplate}<|assistant|>\n`; return prompt; @@ -233,7 +233,7 @@ const holeFillerTemplate: AutocompleteTemplate = { filename: string, reponame: string, language: string, - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], ) => { // From https://github.com/VictorTaelin/AI-scripts const SYSTEM_MSG = `You are a HOLE FILLER. You are provided with a file containing holes, formatted as '{{HOLE_NAME}}'. Your TASK is to complete with a string to replace this hole with, inside a XML tag, including context-aware indentation, if needed. All completions MUST be truthful, accurate, well-written and correct. diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index be2d178d4..2812130c5 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -3,7 +3,6 @@ import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippetDeprecated } from "../context/ranking"; import { HelperVars } from "../util/HelperVars"; import { @@ -12,6 +11,11 @@ import { } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; import { countTokens } from "../../llm/countTokens"; +import { AutocompleteSnippetDeprecated } from "../types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippet, +} from "../snippets/types"; const addCommentMarks = (text: string, language: AutocompleteLanguageInfo) => { const comment = language.singleLineComment; @@ -34,7 +38,7 @@ export function formatExternalSnippet( } function getContextComments( - snippets: AutocompleteSnippetDeprecated[], + snippets: AutocompleteCodeSnippet[], lang: AutocompleteLanguageInfo, filepath: string, ) { @@ -49,7 +53,7 @@ function getContextComments( headerSnipper + snippets .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), + formatExternalSnippet(snippet.filepath, snippet.content, lang), ) .join("\n") + fileNameSnippet; @@ -122,6 +126,11 @@ const formatClipboardContent = ( return ""; } + const isEmpty = text.trim() === ""; + if (isEmpty) { + return ""; + } + return ( addCommentMarks( `Recently copied by user:${text.includes("\n") ? "\n" : ""} ${text}`, @@ -137,7 +146,7 @@ export function renderPrompt({ diff, clipboardContent, }: { - snippets: AutocompleteSnippetDeprecated[]; + snippets: AutocompleteCodeSnippet[]; workspaceDirs: string[]; helper: HelperVars; diff?: string; diff --git a/core/autocomplete/types.ts b/core/autocomplete/types.ts new file mode 100644 index 000000000..9488fb085 --- /dev/null +++ b/core/autocomplete/types.ts @@ -0,0 +1,21 @@ +import { RangeInFileWithContents } from "../commands/util"; +import { IDE } from "../index"; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; +import { AutocompleteCodeSnippet } from "./snippets/types"; + +/** + * @deprecated This type should be removed in the future or renamed. + * We have a new interface called AutocompleteSnippet which is more + * general. + */ +export type AutocompleteSnippetDeprecated = RangeInFileWithContents & { + score?: number; +}; + +export type GetLspDefinitionsFunction = ( + filepath: string, + contents: string, + cursorIndex: number, + ide: IDE, + lang: AutocompleteLanguageInfo, +) => Promise; diff --git a/core/config/types.ts b/core/config/types.ts index f397b1ed7..47c4a5aa7 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -842,7 +842,6 @@ declare global { onlyMyCode: boolean; useOtherFiles: boolean; useRecentlyEdited: boolean; - recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; } diff --git a/core/index.d.ts b/core/index.d.ts index 0646edc54..f96cbd122 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -986,7 +986,6 @@ export interface TabAutocompleteOptions { onlyMyCode: boolean; useOtherFiles: boolean; useRecentlyEdited: boolean; - recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; useRootPathContext?: boolean; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 20b96ac47..7ba828f7a 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -18,7 +18,6 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { onlyMyCode: true, useOtherFiles: true, useRecentlyEdited: true, - recentLinePrefixMatchMinLength: 7, disableInFiles: undefined, useImports: true, useRootPathContext: true, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 940503505..b30a951df 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.232", + "version": "0.9.233", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.232", + "version": "0.9.233", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index de719d3bf..a11aeeead 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,6 +1,4 @@ -import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippetDeprecated } from "core/autocomplete/context/ranking"; import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; import { RangeInFileWithContents } from "core/commands/util"; import { @@ -12,6 +10,14 @@ import * as vscode from "vscode"; import type { IDE, Range, RangeInFile } from "core"; import type Parser from "web-tree-sitter"; +import { + AutocompleteSnippetDeprecated, + GetLspDefinitionsFunction, +} from "core/autocomplete/types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "core/autocomplete/snippets/types"; type GotoProviderName = | "vscode.executeDefinitionProvider" @@ -342,7 +348,7 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( cursorIndex: number, ide: IDE, lang: AutocompleteLanguageInfo, -): Promise => { +): Promise => { try { const ast = await getAst(filepath, contents); if (!ast) { @@ -366,8 +372,10 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( } return results.map((result) => ({ - ...result, + filepath: result.filepath, + content: result.contents, score: 0.8, + type: AutocompleteSnippetType.Code, })); } catch (e) { console.warn("Error getting definitions from LSP: ", e); diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 876115d11..fc53c742f 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -148,7 +148,6 @@ export const tabAutocompleteOptionsSchema = z.object({ onlyMyCode: z.boolean(), useOtherFiles: z.boolean(), useRecentlyEdited: z.boolean(), - recentLinePrefixMatchMinLength: z.number(), disableInFiles: z.array(z.string()).optional(), useImports: z.boolean().optional(), });