From ec910c7047755c2ffa004b5f855f313be955088a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 14 Jul 2025 16:41:13 -0700 Subject: [PATCH 01/88] feat: add getReferences --- core/config/types.ts | 1 + core/index.d.ts | 1 + core/protocol/ide.ts | 1 + core/protocol/messenger/messageIde.ts | 4 ++++ core/util/filesystem.ts | 4 ++++ .../continueintellijextension/continue/IntelliJIde.kt | 6 +++++- .../continuedev/continueintellijextension/types.kt | 3 ++- extensions/vscode/src/VsCodeIde.ts | 11 +++++++++++ extensions/vscode/src/extension/VsCodeMessenger.ts | 4 ++++ 9 files changed, 33 insertions(+), 2 deletions(-) diff --git a/core/config/types.ts b/core/config/types.ts index 406f40ddd..25ae3247a 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -745,6 +745,7 @@ declare global { // LSP gotoDefinition(location: Location): Promise; + getReferences(location: Location): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (filepath: string) => void): void; diff --git a/core/index.d.ts b/core/index.d.ts index e211c824e..8c7b2c1a6 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -836,6 +836,7 @@ export interface IDE { // LSP gotoDefinition(location: Location): Promise; + getReferences(location: Location): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index ba4cf4f88..ed108ba9b 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -82,6 +82,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { getFileStats: [{ files: string[] }, FileStatsMap]; gotoDefinition: [{ location: Location }, RangeInFile[]]; + getReferences: [{ location: Location }, RangeInFile[]]; getControlPlaneSessionInfo: [ { silent: boolean; useOnboarding: boolean }, diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 30d9b8177..de1ed3ecc 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -45,6 +45,10 @@ export class MessageIde implements IDE { return this.request("gotoDefinition", { location }); } + async getReferences(location: Location): Promise { + return this.request("getReferences", { location }); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index f415e5e86..254bbe28a 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -44,6 +44,10 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } + getReferences(location: Location): Promise { + return Promise.resolve([]); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 2dfc3e3e1..1ce14b3fd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -592,6 +592,10 @@ class IntelliJIDE( throw NotImplementedError("gotoDefinition not implemented yet") } + override suspend fun getReferences(location: Location): List { + throw NotImplementedError("getReferences not implemented yet") + } + override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) { throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet") } @@ -622,4 +626,4 @@ class IntelliJIDE( return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() } -} \ No newline at end of file +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 5ff9e9454..4e6c6c771 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -191,6 +191,7 @@ interface IDE { // LSP suspend fun gotoDefinition(location: Location): List + suspend fun getReferences(location: Location): List // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) @@ -247,4 +248,4 @@ data class AcceptOrRejectDiffPayload( data class ShowFilePayload( val filepath: String -) \ No newline at end of file +) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 91fb6154b..97c48f174 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -86,6 +86,17 @@ class VsCodeIde implements IDE { return result; } + async getReferences(location: Location): Promise { + const result = await executeGotoProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeReferenceProvider", + }); + + return result; + } + onDidChangeActiveTextEditor(callback: (uri: string) => void): void { vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor) { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 430c4fff1..7f9158da5 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -390,6 +390,10 @@ export class VsCodeMessenger { return await ide.gotoDefinition(msg.data.location); }); + this.onWebviewOrCore("getReferences", async (msg) => { + return await ide.getReferences(msg.data.location); + }); + this.onWebviewOrCore("getFileStats", async (msg) => { return await ide.getFileStats(msg.data.files); }); From 1f8d667bf861894ffd7458244334861ac88b19bf Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 15 Jul 2025 17:43:38 -0700 Subject: [PATCH 02/88] feat: create prefetch queue data structure --- core/util/PrefetchQueue.ts | 90 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 core/util/PrefetchQueue.ts diff --git a/core/util/PrefetchQueue.ts b/core/util/PrefetchQueue.ts new file mode 100644 index 000000000..36b55ff10 --- /dev/null +++ b/core/util/PrefetchQueue.ts @@ -0,0 +1,90 @@ +import { NextEditProvider } from "../nextEdit/NextEditProvider"; + +export class PrefetchQueue { + private currentPromise: Promise | null = null; + private nextPromise: Promise | null = null; + private resourceQueue: R[]; + private other: O | undefined; + private fetchFunction: ( + previousData: T | undefined, + resource: R | undefined, + other: O | undefined, + ) => Promise; + + constructor( + fetchFunction: ( + previousData: T | undefined, + resource: R | undefined, + other: O | undefined, + ) => Promise, + resources: R[], + other: O | undefined, + ) { + this.fetchFunction = fetchFunction; + this.resourceQueue = [...resources]; + this.other = other; + } + + loadResource(resources: R[]) { + // if (this.resourceQueue.length > 0) { + // throw new Error("Queue already initialized"); + // } + this.resourceQueue = [...this.resourceQueue, ...resources]; + } + + loadOther(other: O) { + this.other = other; + } + + async initialize(): Promise { + // Get the first response (no resource needed). + this.currentPromise = this.fetchFunction(undefined, undefined, this.other); + const firstData = await this.currentPromise; + // TODO: cleanse editable_region_start and trailing newline. + + // Create the next promise based on the first response and first resource. + // if (this.resourceQueue.length > 0) { + const resource = this.resourceQueue.shift()!; + this.nextPromise = this.fetchFunction(firstData, resource, this.other); + // } + } + + async pop(): Promise { + if (!this.currentPromise) { + // throw new Error("Queue not initialized"); + return undefined; + } + + const currentData = await this.currentPromise; + + // Move next promise to current (if it exists). + if (this.nextPromise) { + this.currentPromise = this.nextPromise; + + // Create new next promise if we have resources left. + const resource = this.resourceQueue.shift()!; + this.nextPromise = this.currentPromise.then((data) => + this.fetchFunction(data, resource, this.other), + ); + // if (this.resourceQueue.length > 0) { + // } else { + // this.nextPromise = null; + // } + } else { + NextEditProvider.currentEditChainId = null; + // throw new Error("No more items in queue"); + return undefined; + } + + console.log("currentData:", currentData); + return currentData; + } + + hasNext(): boolean { + return this.nextPromise !== null; + } + + getRemainingResourceCount(): number { + return this.resourceQueue.length; + } +} From e3b61b989022642297b25698d93c4d2867cef756 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 15 Jul 2025 17:44:03 -0700 Subject: [PATCH 03/88] refactor: factor out final cursor position calculation --- core/nextEdit/diff/diff.ts | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index bca4a6d08..b89d638a4 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -1,4 +1,6 @@ +import { Position } from "shiki"; import { DiffLine } from "../.."; +import { myersDiff } from "../../diff/myers"; /** * Given a diff of two editable regions, get the offset position at the last new line inside the editable region. @@ -192,3 +194,34 @@ export function checkFim( return { isFim, fimText: null }; } } + +export function calculateFinalCursorPosition( + currCursorPos: Position, + editableRegionStartLine: number, + oldEditRangeSlice: string, + newEditRangeSlice: string, +) { + // How far away is the current line from the start of the editable region? + const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine; + + // How long is the line at the current cursor position? + const lineContentAtCursorPos = + newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; + + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + + const offset = getOffsetPositionAtLastNewLine( + diffLines, + lineContentAtCursorPos, + lineOffsetAtCursorPos, + ); + + // Calculate the actual line number in the editor by adding the startPos offset + // to the line number from the diff calculation. + const finalCursorPos: Position = { + line: editableRegionStartLine + offset.line, + character: offset.character, + }; + + return finalCursorPos; +} From 263e340d07be4a9591ce78ab443b97bc2834120d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 15 Jul 2025 17:44:31 -0700 Subject: [PATCH 04/88] feat: extend NextEditOutcome type to include final cursor position and the editable region start and end lines --- core/nextEdit/types.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 0837c5494..26e2b156a 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -53,7 +53,10 @@ export interface NextEditOutcome extends TabAutocompleteOptions { originalEditableRange: string; completion: string; cursorPosition: { line: number; character: number }; + finalCursorPosition: { line: number; character: number }; accepted?: boolean; + editableRegionStartLine: number; + editableRegionEndLine: number; } export interface PromptMetadata { From 90cdcafee2ce8ff034846ed70a94667d789ce579 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 15 Jul 2025 17:44:56 -0700 Subject: [PATCH 05/88] feat: use prefetch queue to prefetch inference results --- core/nextEdit/NextEditProvider.ts | 253 +++++++++++++++++- .../templating/NextEditPromptEngine.ts | 59 +++- 2 files changed, 306 insertions(+), 6 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index fba86df33..9ae8a635e 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,11 +1,12 @@ import * as path from "path"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { ChatMessage, IDE, ILLM } from "../index.js"; +import { ChatMessage, IDE, ILLM, Position, RangeInFile } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js"; +import { randomUUID } from "crypto"; import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; @@ -15,11 +16,17 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; +import { myersDiff } from "../diff/myers.js"; +import { PrefetchQueue } from "../util/PrefetchQueue.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; +import { + calculateFinalCursorPosition, + getOffsetPositionAtLastNewLine, +} from "./diff/diff.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; import { renderDefaultSystemPrompt, @@ -52,6 +59,21 @@ export class NextEditProvider { private endpointType: "default" | "fineTuned"; private diffContext: string = ""; private promptMetadata: PromptMetadata | null = null; + private prefetchQueue: PrefetchQueue< + NextEditOutcome, + RangeInFile, + { + helper: HelperVars; + diffContext: string; + llm: ILLM; + token: AbortSignal; + startTime: number; + newCursorPos: Position; + } + >; + // private refQueue: RangeInFile[] = []; + // TODO: This needs to be cleared globally on cancel. + public static currentEditChainId: string | null = null; private constructor( private readonly configHandler: ConfigHandler, @@ -65,6 +87,121 @@ export class NextEditProvider { this.contextRetrievalService = new ContextRetrievalService(this.ide); this.endpointType = endpointType; this.loggingService = NextEditLoggingService.getInstance(); + + const fetchFunction = async ( + previousData: NextEditOutcome | undefined, + resource: RangeInFile | undefined, + other?: { + helper: HelperVars; + diffContext: string; + llm: ILLM; + token: AbortSignal; + startTime: number; + newCursorPos: Position; + }, + ) => { + if (!other) return undefined; + // render prompt + // TODO: this has to set the editable region properly. + console.log("fetchfunction - previousData:", previousData?.completion); + const promptMetadata = renderPrompt( + other.helper, + other.diffContext, + previousData, + resource, + ); + this.promptMetadata = promptMetadata; + // call llm.chat + const msg = await other.llm.chat([promptMetadata.prompt], other.token); + // built and return outcome + if (typeof msg.content === "string") { + if (msg.content === "") return undefined; + // TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined + const nextCompletion = replaceEscapedCharacters( + msg.content.split("<|editable_region_start|>\n")[1], + ).replace(/\n$/, ""); + + const currCursorPos = other.helper.pos; + const editableRegionStartLine = Math.max( + currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + const editableRegionEndLine = Math.min( + currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + other.helper.fileLines.length - 1, + ); + const oldEditRangeSlice = other.helper.fileContents + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + // How far away is the current line from the start of the editable region? + const lineOffsetAtCursorPos = + currCursorPos.line - editableRegionStartLine; + + // How long is the line at the current cursor position? + const newEditRangeSlice = nextCompletion; + const lineContentAtCursorPos = + newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; + + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + + const offset = getOffsetPositionAtLastNewLine( + diffLines, + lineContentAtCursorPos, + lineOffsetAtCursorPos, + ); + + // Calculate the actual line number in the editor by adding the startPos offset + // to the line number from the diff calculation. + const finalCursorPos: Position = { + line: editableRegionStartLine + offset.line, + character: offset.character, + }; + + const outcomeNext: NextEditOutcome = { + elapsed: Date.now() - other.startTime, + modelProvider: other.llm.underlyingProviderName, + modelName: other.llm.model + ":zetaDataset", + completionOptions: null, + // filepath: helper.filepath, + completionId: other.helper.input.completionId, + gitRepo: await this.ide.getRepoName(other.helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + fileUri: other.helper.filepath, + workspaceDirUri: + other.helper.workspaceUris[0] ?? + path.dirname(other.helper.filepath), + prompt: this.promptMetadata!.prompt.content, + userEdits: this.promptMetadata!.userEdits, + userExcerpts: this.promptMetadata!.userExcerpts, + originalEditableRange: oldEditRangeSlice, + completion: nextCompletion, + cursorPosition: other.helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine, + editableRegionEndLine, + ...other.helper.options, + }; + return outcomeNext; + } else { + return undefined; + } + }; + + this.prefetchQueue = new PrefetchQueue< + NextEditOutcome, + RangeInFile, + { + helper: HelperVars; + diffContext: string; + llm: ILLM; + token: AbortSignal; + startTime: number; + newCursorPos: Position; + } + >(fetchFunction, [], undefined); } public static initialize( @@ -247,6 +384,26 @@ export class NextEditProvider { prompts.push(promptMetadata.prompt); } + const editableRegionStartLine = Math.max( + helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + const editableRegionEndLine = Math.min( + helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + helper.fileLines.length - 1, + ); + const oldEditRangeSlice = helper.fileContents + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + "", + ); + if (this.endpointType === "default") { const msg: ChatMessage = await llm.chat(prompts, token); if (typeof msg.content === "string") { @@ -270,6 +427,9 @@ export class NextEditProvider { originalEditableRange: "", completion: nextCompletion, cursorPosition: helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine: 0, + editableRegionEndLine: 0, ...helper.options, }; return outcomeNext; @@ -298,6 +458,13 @@ export class NextEditProvider { .slice(editableRegionStartLine, editableRegionEndLine + 1) .join("\n"); + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + "", + ); + const outcomeNext: NextEditOutcome = { elapsed: Date.now() - startTime, modelProvider: llm.underlyingProviderName, @@ -317,6 +484,9 @@ export class NextEditProvider { originalEditableRange: oldEditRangeSlice, completion: nextCompletion, cursorPosition: helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine, + editableRegionEndLine, ...helper.options, }; return outcomeNext; @@ -330,4 +500,85 @@ export class NextEditProvider { this.loggingService.deleteAbortController(input.completionId); } } + + public async provideNextEditPrediction( + input: AutocompleteInput, + token: AbortSignal | undefined, + ) { + try { + if (NextEditProvider.currentEditChainId) { + return await this.prefetchQueue.pop(); + } + + // Create abort signal if not given + if (!token) { + const controller = this.loggingService.createAbortController( + input.completionId, + ); + token = controller.signal; + } + 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; + } + + if (llm.promptTemplates?.autocomplete) { + options.template = llm.promptTemplates.autocomplete as string; + } + + const helper = await HelperVars.create( + input, + options, + llm.model, + this.ide, + ); + + if (await shouldPrefilter(helper, this.ide)) { + return undefined; + } + + NextEditProvider.currentEditChainId = randomUUID(); + + this.prefetchQueue.loadOther({ + helper, + diffContext: this.diffContext, + llm, + token, + startTime, + newCursorPos: helper.pos, + }); + + const [snippetPayload, workspaceDirs] = await Promise.all([ + getAllSnippetsWithoutRace({ + helper, + ide: this.ide, + getDefinitionsFromLsp: this.getDefinitionsFromLsp, + contextRetrievalService: this.contextRetrievalService, + }), + this.ide.getWorkspaceDirs(), + ]); + + // TODO: Get the references. + const refQueue = await this.ide.getReferences({ + filepath: helper.filepath, + position: helper.pos, + }); + + this.prefetchQueue.loadResource(refQueue); + await this.prefetchQueue.initialize(); + return await this.prefetchQueue.pop(); + } catch (e: any) { + this.onError(e); + } finally { + this.loggingService.deleteAbortController(input.completionId); + } + } } diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 93f794a63..a257f0621 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -1,5 +1,5 @@ import Handlebars from "handlebars"; -import { Position } from "../.."; +import { Position, RangeInFile } from "../.."; import { SnippetPayload } from "../../autocomplete/snippets"; import { HelperVars } from "../../autocomplete/util/HelperVars"; import { @@ -9,7 +9,9 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; +import { createDiff, DiffFormatType } from "../context/diffFormatting"; import { + NextEditOutcome, NextEditTemplate, PromptMetadata, SystemPrompt, @@ -49,6 +51,8 @@ function templateRendererOfModel( export function renderPrompt( helper: HelperVars, userEdits: string, + prevOutcome?: NextEditOutcome, + toApply?: RangeInFile, ): PromptMetadata { let modelName = helper.modelName as NextEditModelName; @@ -80,10 +84,55 @@ export function renderPrompt( } const renderer = templateRendererOfModel(modelName); - const editedCodeWithTokens = insertTokens( - helper.fileContents.split("\n"), - helper.pos, - ); + let editedCodeWithTokens = ""; + + // TODO: apply prevOutcome to existing content. we will need the line range. + // Also display the diff between existing content and applied content. + if (prevOutcome) { + console.log( + "beforeInsert:", + helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), + ); + console.log("toInsert: ", prevOutcome?.completion.split("\n")); + console.log( + "afterInsert:", + helper.fileLines.slice(prevOutcome?.editableRegionEndLine), + ); + let appliedContent = [ + ...helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), + ...(prevOutcome?.completion.split("\n") ?? []), + ...helper.fileLines.slice(prevOutcome?.editableRegionEndLine), + ]; + // console.log("helper.fileContents:", helper.fileContents); + // TODO: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. + // The individual parts don't contain this. + console.log("appliedContent:", appliedContent); + appliedContent = appliedContent.filter( + (line) => !line.includes(USER_CURSOR_IS_HERE_TOKEN), + ); + // TODO: helper.pos is outdated. + // Given a previous response, we need to calculate where the cursor would be. + // I think it's a good idea to calculate this in the response. + editedCodeWithTokens = insertTokens( + appliedContent, + prevOutcome.finalCursorPosition, + ); + console.log("new editedCodeWithTokens:", editedCodeWithTokens); + userEdits = createDiff({ + beforeContent: helper.fileContents, + afterContent: appliedContent.join("\n"), + filePath: helper.filepath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }); + userEdits = userEdits.replace(USER_CURSOR_IS_HERE_TOKEN, ""); + console.log("new userDiff:", userEdits); + } else { + editedCodeWithTokens = insertTokens( + helper.fileContents.split("\n"), + helper.pos, + ); + } const tv: TemplateVars = { userEdits, From 51818bffee9a9c76f921e4d3c4cd62040eda8500 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 15 Jul 2025 17:45:12 -0700 Subject: [PATCH 06/88] feat: reset edit chain id to null --- .../vscode/src/activation/NextEditWindowManager.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 58d03239d..25171c935 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -12,6 +12,7 @@ import { } from "core/nextEdit/constants"; import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { getThemeString } from "../util/getTheme"; export interface TextApplier { @@ -199,10 +200,10 @@ export class NextEditWindowManager { await NextEditWindowManager.freeTabAndEsc(); // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. - this.registerCommandSafely( - HIDE_NEXT_EDIT_SUGGESTION_COMMAND, - async () => await this.hideAllNextEditWindowsAndResetCompletionId(), - ); + this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => { + NextEditProvider.currentEditChainId = null; + await this.hideAllNextEditWindowsAndResetCompletionId(); + }); this.registerCommandSafely( ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, async () => await this.acceptNextEdit(), @@ -317,6 +318,8 @@ export class NextEditWindowManager { * Hide all tooltips in all editors. */ public async hideAllNextEditWindows() { + NextEditProvider.currentEditChainId = null; + if (this.currentDecoration) { vscode.window.visibleTextEditors.forEach((editor) => { editor.setDecorations(this.currentDecoration!, []); From 3d0ef7afbc7f0f040352f44c1ca61a484523399e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 15 Jul 2025 17:45:18 -0700 Subject: [PATCH 07/88] feat: reset edit chain id to null --- extensions/vscode/src/extension/VsCodeExtension.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 0bc47f90d..802c5f28a 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -42,6 +42,7 @@ import { VsCodeIde } from "../VsCodeIde"; import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import setupNextEditWindowManager, { NextEditWindowManager, } from "../activation/NextEditWindowManager"; @@ -368,6 +369,19 @@ export class VsCodeExtension { } }); + // TODO: check if next edit provider's chain id is cleared properly. + // Listen for editor changes to clean up decorations when editor closes. + vscode.window.onDidChangeVisibleTextEditors(async () => { + // If our active editor is no longer visible, clear decorations. + NextEditProvider.currentEditChainId = null; + }); + + // Listen for selection changes to hide tooltip when cursor moves. + vscode.window.onDidChangeTextEditorSelection(async (e) => { + // If the selection changed in our active editor, hide the tooltip. + NextEditProvider.currentEditChainId = null; + }); + // Refresh index when branch is changed void this.ide.getWorkspaceDirs().then((dirs) => dirs.forEach(async (dir) => { From 007f40948ef27cce2d66113c3c781c8227afd564 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 15 Jul 2025 17:45:30 -0700 Subject: [PATCH 08/88] feat: use the new prefetch method --- .../src/autocomplete/completionProvider.ts | 43 ++++++++++++++----- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 88131a3e8..2237c68a4 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -236,23 +236,44 @@ export class ContinueCompletionProvider setupStatusBar(undefined, true); + // TODO: Consume next edit generator. + let outcome: AutocompleteOutcome | NextEditOutcome | undefined; + + // Check if editChainId exists or needs to be refreshed. + if (this.isNextEditActive) { + outcome = await this.nextEditProvider.provideNextEditPrediction( + input, + signal, + ); + } else { + outcome = await this.completionProvider.provideInlineCompletionItems( + input, + signal, + wasManuallyTriggered, + ); + } + // TODO: fix type of outcome to be a union between NextEditOutcome and AutocompleteOutcome. - const outcome: AutocompleteOutcome | NextEditOutcome | undefined = this - .isNextEditActive - ? await this.nextEditProvider.provideInlineCompletionItems( - input, - signal, - ) - : await this.completionProvider.provideInlineCompletionItems( - input, - signal, - wasManuallyTriggered, - ); + // const outcome: AutocompleteOutcome | NextEditOutcome | undefined = this + // .isNextEditActive + // ? await this.nextEditProvider.provideInlineCompletionItems( + // input, + // signal, + // ) + // : await this.completionProvider.provideInlineCompletionItems( + // input, + // signal, + // wasManuallyTriggered, + // ); if (!outcome || !outcome.completion) { return null; } + console.log("======"); + console.log(outcome.completion); + console.log("======"); + // VS Code displays dependent on selectedCompletionInfo (their docstring below) // We should first always make sure we have a valid completion, but if it goes wrong we // want telemetry to be correct From 4f7ec0dc13b119aeed0e0caf288d78fc2f329bf5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 15 Jul 2025 19:55:20 -0700 Subject: [PATCH 09/88] chore: remove console logs and add timer --- core/nextEdit/NextEditProvider.ts | 2 +- .../templating/NextEditPromptEngine.ts | 24 +++++++++---------- .../src/autocomplete/completionProvider.ts | 7 +++--- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 9ae8a635e..9d30741be 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -103,7 +103,7 @@ export class NextEditProvider { if (!other) return undefined; // render prompt // TODO: this has to set the editable region properly. - console.log("fetchfunction - previousData:", previousData?.completion); + // console.log("fetchfunction - previousData:", previousData?.completion); const promptMetadata = renderPrompt( other.helper, other.diffContext, diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index a257f0621..98f382126 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -89,15 +89,15 @@ export function renderPrompt( // TODO: apply prevOutcome to existing content. we will need the line range. // Also display the diff between existing content and applied content. if (prevOutcome) { - console.log( - "beforeInsert:", - helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), - ); - console.log("toInsert: ", prevOutcome?.completion.split("\n")); - console.log( - "afterInsert:", - helper.fileLines.slice(prevOutcome?.editableRegionEndLine), - ); + // console.log( + // "beforeInsert:", + // helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), + // ); + // console.log("toInsert: ", prevOutcome?.completion.split("\n")); + // console.log( + // "afterInsert:", + // helper.fileLines.slice(prevOutcome?.editableRegionEndLine), + // ); let appliedContent = [ ...helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), ...(prevOutcome?.completion.split("\n") ?? []), @@ -106,7 +106,7 @@ export function renderPrompt( // console.log("helper.fileContents:", helper.fileContents); // TODO: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. // The individual parts don't contain this. - console.log("appliedContent:", appliedContent); + // console.log("appliedContent:", appliedContent); appliedContent = appliedContent.filter( (line) => !line.includes(USER_CURSOR_IS_HERE_TOKEN), ); @@ -117,7 +117,7 @@ export function renderPrompt( appliedContent, prevOutcome.finalCursorPosition, ); - console.log("new editedCodeWithTokens:", editedCodeWithTokens); + // console.log("new editedCodeWithTokens:", editedCodeWithTokens); userEdits = createDiff({ beforeContent: helper.fileContents, afterContent: appliedContent.join("\n"), @@ -126,7 +126,7 @@ export function renderPrompt( contextLines: 3, }); userEdits = userEdits.replace(USER_CURSOR_IS_HERE_TOKEN, ""); - console.log("new userDiff:", userEdits); + // console.log("new userDiff:", userEdits); } else { editedCodeWithTokens = insertTokens( helper.fileContents.split("\n"), diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 2237c68a4..4e401f72b 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -241,10 +241,13 @@ export class ContinueCompletionProvider // Check if editChainId exists or needs to be refreshed. if (this.isNextEditActive) { + const st = performance.now(); outcome = await this.nextEditProvider.provideNextEditPrediction( input, signal, ); + console.log(performance.now() - st); + console.log(outcome?.elapsed); } else { outcome = await this.completionProvider.provideInlineCompletionItems( input, @@ -270,10 +273,6 @@ export class ContinueCompletionProvider return null; } - console.log("======"); - console.log(outcome.completion); - console.log("======"); - // VS Code displays dependent on selectedCompletionInfo (their docstring below) // We should first always make sure we have a valid completion, but if it goes wrong we // want telemetry to be correct From c8c0472d8105239a28a2f331ed3c4b1d60e99ce0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 16 Jul 2025 15:36:57 -0700 Subject: [PATCH 10/88] feat: retrieve five most relevant code chunks given a code snippet --- .../pipelines/BaseRetrievalPipeline.ts | 24 ++++- .../pipelines/NextEditRetrievalPipeline.ts | 99 +++++++++++++++++++ core/nextEdit/NextEditProvider.ts | 14 +++ 3 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 5089678c1..33789da6e 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -77,6 +77,21 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } + // Add this to BaseRetrievalPipeline.ts + protected async ensureLanceDbInitialized(): Promise { + if (!this.lanceDbIndex) { + // Re-run the initialization logic + const embedModel = this.options.config.selectedModelByRole.embed; + if (!embedModel) { + return false; + } + this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) => + this.options.ide.readFile(uri), + ); + } + return this.lanceDbIndex !== null; + } + private getCleanedTrigrams( query: RetrievalPipelineRunArguments["query"], ): string[] { @@ -163,12 +178,19 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { input: string, n: number, ): Promise { - if (!this.lanceDbIndex) { + const initialized = await this.ensureLanceDbInitialized(); + if (!initialized || !this.lanceDbIndex) { console.warn( "LanceDB index not available, skipping embeddings retrieval", ); return []; } + // if (!this.lanceDbIndex) { + // console.warn( + // "LanceDB index not available, skipping embeddings retrieval", + // ); + // return []; + // } return this.lanceDbIndex.retrieve( input, diff --git a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts new file mode 100644 index 000000000..bbf5d8350 --- /dev/null +++ b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts @@ -0,0 +1,99 @@ +import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../.."; +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; + +export default class NextEditRetrievalPipeline extends BaseRetrievalPipeline { + async run(args: RetrievalPipelineRunArguments): Promise { + if (args.includeEmbeddings) { + await this.ensureLanceDbInitialized(); + } + // Collect chunks from multiple sources. + const [embeddingChunks, ftsChunks, recentChunks, toolChunks] = + await Promise.all([ + // Get chunks using embeddings similarity (vector search). + args.includeEmbeddings + ? this.retrieveEmbeddings(args.query, this.options.nRetrieve) + : Promise.resolve([]), + + // Get chunks using full-text search. + this.retrieveFts(args, this.options.nRetrieve), + + // Get chunks from recently edited files. + this.retrieveAndChunkRecentlyEditedFiles(this.options.nRetrieve), + + // Get chunks using LLM-guided tool selection. + this.retrieveWithTools(args.query), + ]); + + // Combine all chunks. + let allChunks = [ + ...embeddingChunks, + ...ftsChunks, + ...recentChunks, + ...toolChunks, + ]; + + // Remove duplicates by digest. + const uniqueDigests = new Set(); + const uniqueChunks = allChunks.filter((chunk) => { + if (uniqueDigests.has(chunk.digest)) { + return false; + } + uniqueDigests.add(chunk.digest); + return true; + }); + + // If we have too many chunks and embedding retrieval is available, + // prioritize chunks from embedding search as they're likely more semantically relevant. + if (uniqueChunks.length > this.options.nFinal) { + // First include embedding chunks (most semantically relevant). + const result: Chunk[] = [...embeddingChunks]; + + // Then add unique chunks from other sources until we reach nFinal. + const remainingChunks = uniqueChunks.filter( + (chunk) => !embeddingChunks.some((ec) => ec.digest === chunk.digest), + ); + + result.push( + ...remainingChunks.slice(0, this.options.nFinal - result.length), + ); + + return result.slice(0, this.options.nFinal); + } + + // Otherwise just return the unique chunks up to nFinal. + return uniqueChunks.slice(0, this.options.nFinal); + } +} + +export async function getTopRelevantCodeChunks( + codeSnippet: string, + options: { + ide: IDE; + llm: ILLM; + config: ContinueConfig; + tags: BranchAndDir[]; + filterDirectory?: string; + }, +): Promise { + const retrievalPipeline = new NextEditRetrievalPipeline({ + llm: options.llm, + config: options.config, + ide: options.ide, + input: codeSnippet, + nRetrieve: 10, // retrieve more initially for better filtering + nFinal: 5, // return top 5 + tags: options.tags, + filterDirectory: options.filterDirectory, + }); + + const chunks = await retrievalPipeline.run({ + query: codeSnippet, + tags: options.tags, + filterDirectory: options.filterDirectory, + includeEmbeddings: true, + }); + + return chunks; +} diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 9d30741be..df47476ff 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -16,6 +16,7 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; +import { getTopRelevantCodeChunks } from "../context/retrieval/pipelines/NextEditRetrievalPipeline.js"; import { myersDiff } from "../diff/myers.js"; import { PrefetchQueue } from "../util/PrefetchQueue.js"; import { replaceEscapedCharacters } from "../util/text.js"; @@ -572,6 +573,19 @@ export class NextEditProvider { position: helper.pos, }); + const { config } = await this.configHandler.loadConfig(); + const chunks = await getTopRelevantCodeChunks( + "pow(number, exponent) {\n return number ** exponent;\n}", + { + ide: this.ide, + llm: llm, + config: config!, + tags: [], + // filterDirectory: getUriPathBasename(helper.workspaceUris[0]), + }, + ); + console.log("chunks:", JSON.stringify(chunks)); + this.prefetchQueue.loadResource(refQueue); await this.prefetchQueue.initialize(); return await this.prefetchQueue.pop(); From fdde91b13865f788d601910bd2f7b508ee67eb2a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 16 Jul 2025 18:16:53 -0700 Subject: [PATCH 11/88] feat: wrap each retrieval methods in try catches --- .../pipelines/NextEditRetrievalPipeline.ts | 111 ++++++++++++------ core/nextEdit/NextEditProvider.ts | 25 +++- 2 files changed, 99 insertions(+), 37 deletions(-) diff --git a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts index bbf5d8350..2c18a407d 100644 --- a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts @@ -8,25 +8,62 @@ export default class NextEditRetrievalPipeline extends BaseRetrievalPipeline { if (args.includeEmbeddings) { await this.ensureLanceDbInitialized(); } - // Collect chunks from multiple sources. + + // Try each retrieval method. + // Embeddings can fail if query.execute() goes wrong. + const embeddingPromise = async () => { + if (!args.includeEmbeddings) return []; + try { + return await this.retrieveEmbeddings( + args.query, + this.options.nRetrieve, + ); + } catch (error) { + console.error("Error retrieving embeddings:", error); + return []; + } + }; + + const ftsPromise = async () => { + try { + return await this.retrieveFts(args, this.options.nRetrieve); + } catch (error) { + console.error("Error retrieving from full-text search:", error); + return []; + } + }; + + const recentFilesPromise = async () => { + try { + return await this.retrieveAndChunkRecentlyEditedFiles( + this.options.nRetrieve, + ); + } catch (error) { + console.error("Error retrieving recently edited files:", error); + return []; + } + }; + + const toolsPromise = async () => { + try { + return await this.retrieveWithTools(args.query); + } catch (error) { + console.error("Error retrieving with tools:", error); + return []; + } + }; + const [embeddingChunks, ftsChunks, recentChunks, toolChunks] = await Promise.all([ - // Get chunks using embeddings similarity (vector search). - args.includeEmbeddings - ? this.retrieveEmbeddings(args.query, this.options.nRetrieve) - : Promise.resolve([]), - - // Get chunks using full-text search. - this.retrieveFts(args, this.options.nRetrieve), - - // Get chunks from recently edited files. - this.retrieveAndChunkRecentlyEditedFiles(this.options.nRetrieve), - - // Get chunks using LLM-guided tool selection. - this.retrieveWithTools(args.query), + embeddingPromise(), + ftsPromise(), + recentFilesPromise(), + toolsPromise(), ]); - // Combine all chunks. + // console.log(`Retrieved chunks: ${embeddingChunks.length} from embeddings, ${ftsChunks.length} from FTS, ${recentChunks.length} from recent + // files, ${toolChunks.length} from tools`); + let allChunks = [ ...embeddingChunks, ...ftsChunks, @@ -46,7 +83,10 @@ export default class NextEditRetrievalPipeline extends BaseRetrievalPipeline { // If we have too many chunks and embedding retrieval is available, // prioritize chunks from embedding search as they're likely more semantically relevant. - if (uniqueChunks.length > this.options.nFinal) { + if ( + uniqueChunks.length > this.options.nFinal && + embeddingChunks.length > 0 + ) { // First include embedding chunks (most semantically relevant). const result: Chunk[] = [...embeddingChunks]; @@ -77,23 +117,28 @@ export async function getTopRelevantCodeChunks( filterDirectory?: string; }, ): Promise { - const retrievalPipeline = new NextEditRetrievalPipeline({ - llm: options.llm, - config: options.config, - ide: options.ide, - input: codeSnippet, - nRetrieve: 10, // retrieve more initially for better filtering - nFinal: 5, // return top 5 - tags: options.tags, - filterDirectory: options.filterDirectory, - }); + try { + const retrievalPipeline = new NextEditRetrievalPipeline({ + llm: options.llm, + config: options.config, + ide: options.ide, + input: codeSnippet, + nRetrieve: 10, // retrieve more initially for better filtering + nFinal: 5, // return top 5 + tags: options.tags, + filterDirectory: options.filterDirectory, + }); - const chunks = await retrievalPipeline.run({ - query: codeSnippet, - tags: options.tags, - filterDirectory: options.filterDirectory, - includeEmbeddings: true, - }); + const chunks = await retrievalPipeline.run({ + query: codeSnippet, + tags: options.tags, + filterDirectory: options.filterDirectory, + includeEmbeddings: !options.config.experimental?.codebaseToolCallingOnly, + }); - return chunks; + return chunks; + } catch (error) { + console.error("Error getting relevant code chunks:", error); + return []; + } } diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index df47476ff..3bc5f80ea 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,6 +1,13 @@ import * as path from "path"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { ChatMessage, IDE, ILLM, Position, RangeInFile } from "../index.js"; +import { + BranchAndDir, + ChatMessage, + IDE, + ILLM, + Position, + RangeInFile, +} from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; @@ -574,17 +581,27 @@ export class NextEditProvider { }); const { config } = await this.configHandler.loadConfig(); + const branches = await Promise.all( + workspaceDirs.map((dir) => this.ide.getBranch(dir)), + ); + const tags: BranchAndDir[] = workspaceDirs.map((directory, i) => ({ + directory, + branch: branches[i], + })); const chunks = await getTopRelevantCodeChunks( - "pow(number, exponent) {\n return number ** exponent;\n}", + ` add(number) { + this.result += number; + return this; + }`, { ide: this.ide, llm: llm, config: config!, - tags: [], + tags: tags, // filterDirectory: getUriPathBasename(helper.workspaceUris[0]), }, ); - console.log("chunks:", JSON.stringify(chunks)); + console.log("chunks:", JSON.stringify(chunks, null, 2)); this.prefetchQueue.loadResource(refQueue); await this.prefetchQueue.initialize(); From 0001645b7efd2f75e9f761cb1051acf928be9756 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 16 Jul 2025 20:02:02 -0700 Subject: [PATCH 12/88] feat: add jump-specific chunking --- .../pipelines/NextEditRetrievalPipeline.ts | 109 +++++++++++++++++- 1 file changed, 108 insertions(+), 1 deletion(-) diff --git a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts index 2c18a407d..515eb9bc8 100644 --- a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts @@ -1,4 +1,11 @@ -import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../.."; +import { + BranchAndDir, + Chunk, + ContinueConfig, + IDE, + ILLM, + Position, +} from "../../.."; import BaseRetrievalPipeline, { RetrievalPipelineRunArguments, } from "./BaseRetrievalPipeline"; @@ -142,3 +149,103 @@ export async function getTopRelevantCodeChunks( return []; } } + +export async function retrieveRelevantSnippetsInFile( + query: string, + filepath: string, + cursorPosition: Position, + maxSnippets: number = 5, + snippetSize: number = 10, // lines per snippet + ide: IDE, +): Promise { + try { + const fileContent = await ide.readFile(filepath); + const lines = fileContent.split("\n"); + + // Create smaller overlapping chunks around the cursor position. + const chunks: Chunk[] = []; + const totalLines = lines.length; + + // If file is too small, skip chunking. + // Ideally we want to keep the chunk size smaller for jump purposes. + if (totalLines <= snippetSize * 2) { + return []; + } + + // Use sliding window to create chunks in the file. + // Make sure to overlap the window while sliding. + for ( + let startLine = 0; + startLine < totalLines - snippetSize; + startLine += Math.floor(snippetSize / 2) + ) { + // Skip the chunk that contains the cursor. + // NOTE: We might just include it. + if ( + startLine <= cursorPosition.line && + cursorPosition.line < startLine + snippetSize + ) { + continue; + } + + const endLine = Math.min(startLine + snippetSize - 1, totalLines - 1); + const content = lines.slice(startLine, endLine + 1).join("\n"); + + chunks.push({ + content, + startLine, + endLine, + digest: `${filepath}:${startLine}-${endLine}`, + filepath, + index: chunks.length, + }); + } + + // Calculate relevance score for each chunk. + // For now, we use simple keyword matching + // In the future we should use embeddings or cosine similarity. + const keywords = query + .toLowerCase() + .split(/\s+/) + .filter((k) => k.length > 2); + + const scoredChunks = chunks.map((chunk) => { + const lowerContent = chunk.content.toLowerCase(); + const score = keywords.reduce((sum, keyword) => { + return sum + (lowerContent.includes(keyword) ? 1 : 0); + }, 0); + + return { chunk, score }; + }); + + // Sort by score desc. + return scoredChunks + .sort((a, b) => b.score - a.score) + .slice(0, maxSnippets) + .map((sc) => sc.chunk); + } catch (error) { + console.error("Error finding relevant in-file snippets:", error); + return []; + } +} + +export function cosineSimilarity(a: number[], b: number[]): number { + let dotProduct = 0; + let normA = 0; + let normB = 0; + + for (let i = 0; i < a.length; i++) { + dotProduct += a[i] * b[i]; + normA += a[i] * a[i]; + normB += b[i] * b[i]; + } + + return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)); +} + +// export async function getJumpDestinations( +// codeSnippet: string, +// cursorPosition: Position, +// filepath: string, +// ): Promise { +// } From 57fceb53a54b7d933b92bac462fa6b24a1674983 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 14:14:51 -0700 Subject: [PATCH 13/88] feat: add a jump manager to handle jumps --- .../vscode/src/activation/JumpManager.ts | 162 ++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 extensions/vscode/src/activation/JumpManager.ts diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts new file mode 100644 index 000000000..cf3c83290 --- /dev/null +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -0,0 +1,162 @@ +import * as vscode from "vscode"; +// TODO: +// Checks for current viewport range. +// Creates and saves the Tab to Jump SVG decoration. +// Given the range to replace, determines whether to display the SVG or not. +// When SVG is displayed, reserve Tab and Esc for jumping. + +export class JumpManager { + private static _instance: JumpManager | undefined; + + // Decoration state. + private _jumpDecoration: vscode.TextEditorDecorationType | undefined; + private _jumpDecorationVisible = false; + private _disposables: vscode.Disposable[] = []; + + private constructor() {} + + initialize() {} + + public static getInstance(): JumpManager { + if (!JumpManager._instance) { + JumpManager._instance = new JumpManager(); + } + return JumpManager._instance; + } + + public static clearInstance() { + if (JumpManager._instance) { + JumpManager._instance.dispose(); + JumpManager._instance = undefined; + } + } + + public dispose() { + // Dispose current decoration. + this._disposables.forEach((d) => d.dispose()); + this._disposables = []; + } + + private async suggestJump(nextJumpLocation: vscode.Position) { + const editor = vscode.window.activeTextEditor; + + if (editor) { + const visibleRanges = editor.visibleRanges; + + if (visibleRanges.length > 0) { + const visibleRange = visibleRanges[0]; + const topLineNumber = visibleRange.start.line; + const bottomLineNumber = visibleRange.end.line; + + const decorationLine = nextJumpLocation.line; + + // Check if jump location is outside the visible range. + if (decorationLine < topLineNumber) { + await this.renderTabToJumpDecoration( + editor, + topLineNumber, + nextJumpLocation, + ); + } else if (decorationLine > bottomLineNumber) { + await this.renderTabToJumpDecoration( + editor, + bottomLineNumber, + nextJumpLocation, + ); + } else { + // No suggestion is made when the decoration is within visibleRange. + return; + } + + // Scroll to show the jump location. + editor.revealRange( + new vscode.Range(decorationLine, 0, decorationLine, 0), + vscode.TextEditorRevealType.InCenter, + ); + } + } + } + + private async renderTabToJumpDecoration( + editor: vscode.TextEditor, + lineToRenderOn: number, + jumpPosition: vscode.Position, + ) { + // Clean up any existing decoration beforehand. + await this.clearJumpDecoration(); + + // Create a decoration for jump. + this._jumpDecoration = vscode.window.createTextEditorDecorationType({ + before: { + contentText: "📌 Press Tab to jump, Esc to cancel", + color: new vscode.ThemeColor("editorInfo.foreground"), + backgroundColor: new vscode.ThemeColor("editorInfo.background"), + margin: "0 0 0 0", + }, + isWholeLine: true, + }); + + // Apply the decoration. + editor.setDecorations(this._jumpDecoration, [ + new vscode.Range(lineToRenderOn, 0, lineToRenderOn, 0), + ]); + + // Set the context key to enable tab/esc shortcuts. + await vscode.commands.executeCommand( + "setContext", + "continue.jumpDecorationVisible", + true, + ); + this._jumpDecorationVisible = true; + + // Register the key listeners. + await this.registerKeyListeners(editor, jumpPosition); + } + + private async clearJumpDecoration() { + if (this._jumpDecoration) { + this._jumpDecoration.dispose(); + this._jumpDecoration = undefined; + } + + // Dispose any active listeners. + this._disposables.forEach((d) => d.dispose()); + this._disposables = []; + + // Reset the context. + await vscode.commands.executeCommand( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + this._jumpDecorationVisible = false; + } + + private async registerKeyListeners( + editor: vscode.TextEditor, + jumpPosition: vscode.Position, + ) { + const acceptJumpCommand = vscode.commands.registerCommand( + "continue.acceptJump", + async () => { + if (this._jumpDecorationVisible) { + // Move cursor to the jump position. + editor.selection = new vscode.Selection(jumpPosition, jumpPosition); + await this.clearJumpDecoration(); + } + }, + ); + + const rejectJumpCommand = vscode.commands.registerCommand( + "continue.rejectJump", + async () => { + if (this._jumpDecorationVisible) { + await this.clearJumpDecoration(); + } + }, + ); + + // This allows us to dispose the command after a jump is completed. + this._disposables.push(acceptJumpCommand, rejectJumpCommand); + } +} From dd162c889d5bf69ca07e690a56951722072f92d4 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 14:15:00 -0700 Subject: [PATCH 14/88] feat: add jump commands --- extensions/vscode/package.json | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index f7c6b6ea5..923343624 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -350,6 +350,16 @@ "category": "Continue", "title": "Continue: Force Next Edit" }, + { + "command": "continue.acceptJump", + "category": "Continue", + "title": "Continue: Accept Jump Suggestion" + }, + { + "command": "continue.rejectJump", + "category": "Continue", + "title": "Continue: Reject Jump Suggestion" + }, { "command": "continue.generateRule", "category": "Continue", @@ -451,12 +461,22 @@ { "command": "continue.nextEditWindow.hideNextEditSuggestion", "key": "escape", - "when": "editorTextFocus && nextEditWindowActive" + "when": "editorTextFocus && nextEditWindowActive && !continue.jumpDecorationVisible" }, { "command": "continue.nextEditWindow.acceptNextEditSuggestion", "key": "tab", - "when": "editorTextFocus && nextEditWindowActive" + "when": "editorTextFocus && nextEditWindowActive && !continue.jumpDecorationVisible" + }, + { + "command": "continue.acceptJump", + "key": "tab", + "when": "editorTextFocus && continue.jumpDecorationVisible" + }, + { + "command": "continue.rejectJump", + "key": "escape", + "when": "editorTextFocus && continue.jumpDecorationVisible" } ], "submenus": [ From 9d62771da8fe77dd6a081836c8fd338d4a4a89dc Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 14:15:16 -0700 Subject: [PATCH 15/88] feat: activate and clear jump manager singleton --- extensions/vscode/src/extension/VsCodeExtension.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 802c5f28a..bf703606f 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -49,6 +49,7 @@ import setupNextEditWindowManager, { import { getDefinitionsFromLsp } from "../autocomplete/lsp"; import { handleTextDocumentChange } from "../util/editLoggingUtils"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { JumpManager } from "../activation/JumpManager"; export class VsCodeExtension { // Currently some of these are public so they can be used in testing (test/test-suites) @@ -171,10 +172,14 @@ export class VsCodeExtension { this.activateNextEdit(); await NextEditWindowManager.freeTabAndEsc(); + + JumpManager.getInstance(); } else { NextEditWindowManager.clearInstance(); this.deactivateNextEdit(); await NextEditWindowManager.freeTabAndEsc(); + + JumpManager.clearInstance(); } if (configLoadInterrupted) { From 0264db58072347799eb323f10634d4b47d1abb41 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 21:28:19 -0700 Subject: [PATCH 16/88] feat: add a class to find next editable region --- core/nextEdit/NextEditEditableRegionCarver.ts | 302 ++++++++++++++++++ 1 file changed, 302 insertions(+) create mode 100644 core/nextEdit/NextEditEditableRegionCarver.ts diff --git a/core/nextEdit/NextEditEditableRegionCarver.ts b/core/nextEdit/NextEditEditableRegionCarver.ts new file mode 100644 index 000000000..0576a714b --- /dev/null +++ b/core/nextEdit/NextEditEditableRegionCarver.ts @@ -0,0 +1,302 @@ +import { RangeInFile } from ".."; +import { cosineSimilarity } from "../context/retrieval/pipelines/NextEditRetrievalPipeline"; + +export enum EditableRegionStrategy { + Naive = "naive", + Model = "model", + Sliding = "sliding", +} + +export function getNextEditableRegion( + strategy: EditableRegionStrategy, + ctx: any, +): RangeInFile | null { + switch (strategy) { + case EditableRegionStrategy.Naive: + return naiveJump(ctx); + case EditableRegionStrategy.Model: + return modelJump(ctx); + case EditableRegionStrategy.Sliding: + return slidingJump(ctx); + default: + return null; + } +} + +// Naive assumes that the entire file is editable. +function naiveJump(ctx: any): RangeInFile | null { + const { fileLines, filepath } = ctx; + if (!fileLines || !filepath) { + console.warn("Missing required context for naive jump"); + return null; + } + + return { + filepath, + range: { + start: { line: 0, character: 0 }, + end: { + line: fileLines.length - 1, + character: fileLines.at(-1).length, + }, + }, + }; +} + +// A naive jump uses the next edit model to predict edits for the entire file. +// Then it calculates the diff between that and the original to get the jump location. +function modelJump(ctx: any): RangeInFile | null { + try { + const { fileContent, predictedContent, filepath } = ctx; + + if (!fileContent || !predictedContent || !filepath) { + console.warn("Missing required context for model jump"); + return null; + } + + const originalLines = fileContent.split("\n"); + const predictedLines = predictedContent.split("\n"); + + // Find the first line that differs. + for ( + let i = 0; + i < Math.min(originalLines.length, predictedLines.length); + i++ + ) { + if (originalLines[i] !== predictedLines[i]) { + // Calculate the end of the differing section (find where they align again). + let endLine = i; + while ( + endLine < Math.min(originalLines.length, predictedLines.length) && + originalLines[endLine] !== predictedLines[endLine] + ) { + endLine++; + } + + // Return a range that covers the differences. + return { + filepath, + range: { + start: { line: i, character: 0 }, + end: { + line: Math.min(endLine, originalLines.length - 1), + character: + originalLines[Math.min(endLine, originalLines.length - 1)] + .length, + }, + }, + }; + } + } + + // If no difference found but files have different lengths, + if (originalLines.length !== predictedLines.length) { + const diffStartLine = Math.min( + originalLines.length, + predictedLines.length, + ); + return { + filepath, + range: { + start: { line: diffStartLine, character: 0 }, + end: { + line: originalLines.length - 1, + character: originalLines.at(-1).length, + }, + }, + }; + } + + // No differences found. + return null; + } catch (error) { + console.error("Error in model jump:", error); + return null; + } +} + +// A sliding jump uses a sliding window to split the current file into zones. +// Then each zone is ranked on how similar it is to the model's next edit prediction. +function slidingJump(ctx: any): RangeInFile | null { + try { + const { fileContent, predictedContent, filepath, windowSize = 5 } = ctx; + + if (!fileContent || !predictedContent || !filepath) { + console.warn("Missing required context for sliding jump"); + return null; + } + + const originalLines = fileContent.split("\n"); + const predictedLines = predictedContent.split("\n"); + + // Create sliding windows/zones from the file. + const zones: Array<{ + startLine: number; + endLine: number; + similarity: number; + }> = []; + + for ( + let i = 0; + i <= originalLines.length - windowSize; + i += Math.floor(windowSize / 2) + ) { + const originalWindow = originalLines.slice(i, i + windowSize).join("\n"); + + // For each zone, find the most similar section in the predicted content. + let highestSimilarity = 0; + + for ( + let j = 0; + j <= predictedLines.length - windowSize; + j += Math.floor(windowSize / 2) + ) { + const predictedWindow = predictedLines + .slice(j, j + windowSize) + .join("\n"); + + // Convert to simple vector representation for similarity calculation. + const originalVector = createSimpleVector(originalWindow); + const predictedVector = createSimpleVector(predictedWindow); + + const similarity = cosineSimilarity(originalVector, predictedVector); + + if (similarity > highestSimilarity) { + highestSimilarity = similarity; + } + } + + zones.push({ + startLine: i, + endLine: Math.min(i + windowSize - 1, originalLines.length - 1), + similarity: highestSimilarity, + }); + } + + // Find the zone with the highest similarity score. + const mostSimilarZone = zones.reduce((prev, current) => + prev.similarity > current.similarity ? prev : current, + ); + + // Return the range of the most similar zone. + return { + filepath, + range: { + start: { line: mostSimilarZone.startLine, character: 0 }, + end: { + line: mostSimilarZone.endLine, + character: originalLines[mostSimilarZone.endLine].length, + }, + }, + }; + } catch (error) { + console.error("Error in sliding jump:", error); + return null; + } +} + +// A rerank jump splits the current file into chunks. +// Then it uses a rerank model to get the most relevant chunks and their positions. +function rerankJump(ctx: any): RangeInFile | null { + try { + const { fileContent, query, filepath, reranker, chunkSize = 10 } = ctx; + + if (!fileContent || !query || !filepath || !reranker) { + console.warn("Missing required context for rerank jump"); + return null; + } + + const lines = fileContent.split("\n"); + const chunks: Array<{ + content: string; + startLine: number; + endLine: number; + }> = []; + + // Create chunks from the file + for (let i = 0; i < lines.length; i += Math.floor(chunkSize / 2)) { + const endLine = Math.min(i + chunkSize - 1, lines.length - 1); + const chunkContent = lines.slice(i, endLine + 1).join("\n"); + chunks.push({ + content: chunkContent, + startLine: i, + endLine: endLine, + }); + } + + // Use the reranker to score each chunk against the query + const scoredChunks = chunks.map((chunk) => ({ + ...chunk, + score: reranker.rerank(query, [{ content: chunk.content }])[0], + })); + + // Sort by score in descending order and get the highest scoring chunk + const mostRelevantChunk = scoredChunks.sort((a, b) => b.score - a.score)[0]; + + if (!mostRelevantChunk) { + return null; + } + + // Return the range of the most relevant chunk + return { + filepath, + range: { + start: { line: mostRelevantChunk.startLine, character: 0 }, + end: { + line: mostRelevantChunk.endLine, + character: lines[mostRelevantChunk.endLine].length, + }, + }, + }; + } catch (error) { + console.error("Error in rerank jump:", error); + return null; + } +} + +// Helper method to create a simple vector representation of a text string. +function createSimpleVector(text: string): number[] { + const tokenFrequency: Record = {}; + + // Split text into tokens. + const tokens = text + .toLowerCase() + .split(/[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g) + .map((s) => s.trim()) + .filter((s) => s.length > 0); + + // Count frequency of each token. + for (const token of tokens) { + tokenFrequency[token] = (tokenFrequency[token] || 0) + 1; + } + + // Create a fixed-dimension vector (using common programming keywords as dimensions). + const dimensions = [ + "function", + "return", + "if", + "else", + "for", + "while", + "const", + "let", + "var", + "class", + "import", + "export", + "interface", + "type", + "new", + "this", + "try", + "catch", + "async", + "await", + "true", + "false", + "null", + "undefined", + ]; + + return dimensions.map((dim) => tokenFrequency[dim] || 0); +} From 2a4ad72aa3a74f7c219243688cf6cab9cd6b09e1 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 21:28:36 -0700 Subject: [PATCH 17/88] feat: add some helpful diff functions --- core/diff/myers.ts | 135 +++++++++++++++++++++++++++++++++++++ core/nextEdit/diff/diff.ts | 34 ++++++++++ 2 files changed, 169 insertions(+) diff --git a/core/diff/myers.ts b/core/diff/myers.ts index b39ddccf3..9d4ea1740 100644 --- a/core/diff/myers.ts +++ b/core/diff/myers.ts @@ -209,3 +209,138 @@ export function myersCharDiff( return result; } + +export interface ChangeRange { + startLine: number; + endLine: number; + changeType: "deletion" | "addition" | "modification"; +} + +export function findChangedLineRanges( + diffLines: DiffLine[], + // oldCodeBlock: string, + // newCodeBlock: string, +): ChangeRange[] { + const changes: ChangeRange[] = []; + let oldLineNumber = 0; + let newLineNumber = 0; + let currentChangeStart: number | null = null; + let currentChangeType: "deletion" | "addition" | "modification" | null = null; + + for (let i = 0; i < diffLines.length; i++) { + const line = diffLines[i]; + + if (line.type === "same") { + // If we were tracking a change, close it + if (currentChangeStart !== null) { + changes.push({ + startLine: currentChangeStart, + endLine: oldLineNumber - 1, + changeType: currentChangeType!, + }); + currentChangeStart = null; + currentChangeType = null; + } + + // Both old and new advance for 'same' lines + oldLineNumber++; + newLineNumber++; + } else if (line.type === "old") { + // Start tracking change if not already + if (currentChangeStart === null) { + currentChangeStart = oldLineNumber; + currentChangeType = "deletion"; + } + + // Check if this is part of a modification (old followed by new) + if (currentChangeType === "deletion") { + // Look ahead to see if there are 'new' lines following + let hasNewLines = false; + for (let j = i + 1; j < diffLines.length; j++) { + if (diffLines[j].type === "new") { + hasNewLines = true; + break; + } else if (diffLines[j].type === "same") { + break; + } + } + if (hasNewLines) { + currentChangeType = "modification"; + } + } + + oldLineNumber++; + } else if (line.type === "new") { + // Start tracking change if not already + if (currentChangeStart === null) { + currentChangeStart = oldLineNumber; + currentChangeType = "addition"; + } + + // If we were tracking deletions, this becomes a modification + if (currentChangeType === "deletion") { + currentChangeType = "modification"; + } + + newLineNumber++; + } + } + + // Close any remaining change + if (currentChangeStart !== null) { + changes.push({ + startLine: currentChangeStart, + endLine: oldLineNumber - 1, + changeType: currentChangeType!, + }); + } + + return changes; +} + +// Alternative simpler approach if you just want deletion/modification ranges +export function findChangedLineRangesSimple( + diffLines: DiffLine[], +): ChangeRange[] { + const changes: ChangeRange[] = []; + let oldLineNumber = 0; + let currentChangeStart: number | null = null; + + for (const line of diffLines) { + if (line.type === "same") { + // Close any current change + if (currentChangeStart !== null) { + changes.push({ + startLine: currentChangeStart, + endLine: oldLineNumber - 1, + changeType: "modification", + }); + currentChangeStart = null; + } + oldLineNumber++; + } else if (line.type === "old") { + // Start change if not already started + if (currentChangeStart === null) { + currentChangeStart = oldLineNumber; + } + oldLineNumber++; + } else if (line.type === "new") { + // Start change if not already started (for pure additions) + if (currentChangeStart === null) { + currentChangeStart = oldLineNumber; + } + // Don't increment oldLineNumber for 'new' lines + } + } + + // Close any remaining change + if (currentChangeStart !== null) { + changes.push({ + startLine: currentChangeStart, + endLine: oldLineNumber - 1, + changeType: "modification", + }); + } + + return changes; +} diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index b89d638a4..cc6908690 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -136,6 +136,8 @@ export function checkFim( isFim: false; fimText: null; } { + console.log("oldEditRange", oldEditRange); + console.log("newEditRange", newEditRange); // Find the common prefix. let prefixLength = 0; while ( @@ -225,3 +227,35 @@ export function calculateFinalCursorPosition( return finalCursorPos; } + +/** + * Applies a completion to file content by replacing lines starting from a specific line number + * + * @param fileContent The original file content + * @param completion The completion text to apply + * @param startLineNumber The line number (0-based) where replacement should start + * @param linesToReplace Optional number of lines to replace; if not provided, will replace the same number of lines as in the completion + * @returns The file content with the completion applied + */ +export function applyCompletionToFile( + fileContent: string, + completion: string, + startLineNumber: number, + linesToReplace?: number, +): string { + const lines = fileContent.split("\n"); + const completionLines = completion.split("\n"); + + // Determine how many lines to replace + const numLinesToReplace = + linesToReplace !== undefined ? linesToReplace : completionLines.length; + + // Replace the lines + const newLines = [ + ...lines.slice(0, startLineNumber), + ...completionLines, + ...lines.slice(startLineNumber + numLinesToReplace), + ]; + + return newLines.join("\n"); +} From 6b848298b894ef61567bc9ef8d85c89017d7c4cf Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 21:28:47 -0700 Subject: [PATCH 18/88] feat: prefetch queue for next edit --- core/nextEdit/NextEditPrefetchQueue.ts | 136 +++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 core/nextEdit/NextEditPrefetchQueue.ts diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts new file mode 100644 index 000000000..99fff2b35 --- /dev/null +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -0,0 +1,136 @@ +import { ILLM, Position, RangeInFile } from ".."; +import { HelperVars } from "../autocomplete/util/HelperVars"; +import { findChangedLineRanges, myersDiff } from "../diff/myers"; +import { PrefetchQueue } from "../util/PrefetchQueue"; +import { applyCompletionToFile } from "./diff/diff"; +import { EditableRegionStrategy } from "./NextEditEditableRegionCarver"; +import { NextEditProvider } from "./NextEditProvider"; +import { NextEditOutcome } from "./types"; + +export class NextEditPrefetchQueue extends PrefetchQueue< + NextEditOutcome, + RangeInFile, + { + helper: HelperVars; + diffContext: string; + llm: ILLM; + token: AbortSignal; + startTime: number; + newCursorPos: Position; + editableRegionStrategy: EditableRegionStrategy; + } +> { + async initialize(): Promise { + const firstPromise = this.fetchFunction(undefined, undefined, this.other); + this.promiseQueue.push(firstPromise); + + const firstData = await firstPromise; + if (this.resourceQueue.length > 0) { + const resource = this.resourceQueue.shift()!; + const nextPromise = this.fetchFunction(firstData, resource, this.other); + this.promiseQueue.push(nextPromise); + } + + if (this.other?.editableRegionStrategy === EditableRegionStrategy.Naive) { + // Get the response from fetchFunction and compare with firstData to identify changed regions + const resource = + this.resourceQueue.length > 0 ? this.resourceQueue[0] : undefined; + const secondPromise = this.fetchFunction(firstData, resource, this.other); + const secondData = await secondPromise; + // console.log(secondData?.completion); + + // if (secondPromise) { + // Process this in the background + // secondPromise + // .then((secondData) => { + + if (firstData && secondData) { + // Use myersDiff to find differences between the two completions + // const firstCompletionLines = firstData.completion.split("\n"); + // const secondCompletionLines = secondData.completion.split("\n"); + + // TODO: this should be comparing old file and new file, not the completions. + // Compare the file after first completion is merged, + // and compare the file after first and second completion is merged. + const appliedFirst = applyCompletionToFile( + this.other.helper.fileContents, + firstData.completion, + firstData.editableRegionStartLine, + ); + // const appliedFirstAndSecond = applyCompletionToFile( + // appliedFirst, + // secondData.completion, + // secondData.editableRegionStartLine, + // ); + const diffLines = myersDiff(appliedFirst, secondData.completion); + + // Track chunks of differences + console.log(diffLines, appliedFirst, secondData.completion); + const changedLineRanges = findChangedLineRanges(diffLines); + changedLineRanges.forEach((change) => { + // Inclusive, zero-based line numbers. + const chunk = { + startLine: change.startLine, + endLine: change.endLine, + }; + console.log("chunk:", chunk); + const chunkOutcome: NextEditOutcome = { + ...firstData, + uniqueId: `${firstData.uniqueId}-chunk-${chunk.startLine}-${chunk.endLine}`, + editableRegionStartLine: chunk.startLine, + editableRegionEndLine: chunk.endLine, + }; + + this.promiseQueue.push(Promise.resolve(chunkOutcome)); + }); + } + } + } + + async pop(): Promise { + if (this.promiseQueue.length === 0) { + return undefined; + } + + if (this.other?.editableRegionStrategy === EditableRegionStrategy.Naive) { + // The queue should already be preloaded. + // We don't need to make extra calls to the model + // because we assume that the items already in the queue + // are the only items in this chain of edit. + const currentPromise = this.promiseQueue.shift()!; + + if (this.promiseQueue.length === 0) { + NextEditProvider.currentEditChainId = null; + } + + return await currentPromise; + } + + // Get and remove the first promise from the queue + const currentPromise = this.promiseQueue.shift()!; + const currentData = await currentPromise; + + // If we have resources left, prefetch the next item + if (this.resourceQueue.length > 0) { + // Get the most recently added promise (now at the end of the queue) + const previousPromise = + this.promiseQueue.length > 0 + ? this.promiseQueue[this.promiseQueue.length - 1] + : Promise.resolve(currentData); + + // Create new promise based on the previous one and next resource + const resource = this.resourceQueue.shift()!; + const nextPromise = previousPromise.then((data) => + this.fetchFunction(data, resource, this.other), + ); + + this.promiseQueue.push(nextPromise); + } else if (this.promiseQueue.length === 0) { + // No more items in the queue and no more resources + NextEditProvider.currentEditChainId = null; + } + + // console.log("currentData:", currentData); + return currentData; + } +} From 4f087fb8cfdf68b2a371b1214574fcefea6b6dd9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 21:29:02 -0700 Subject: [PATCH 19/88] refactor: use the next edit prefetch queue --- core/nextEdit/NextEditProvider.ts | 77 ++++++++++++++----------------- 1 file changed, 35 insertions(+), 42 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 3bc5f80ea..6265f06db 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -23,9 +23,7 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; -import { getTopRelevantCodeChunks } from "../context/retrieval/pipelines/NextEditRetrievalPipeline.js"; import { myersDiff } from "../diff/myers.js"; -import { PrefetchQueue } from "../util/PrefetchQueue.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, @@ -35,7 +33,9 @@ import { calculateFinalCursorPosition, getOffsetPositionAtLastNewLine, } from "./diff/diff.js"; +import { EditableRegionStrategy } from "./NextEditEditableRegionCarver.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; +import { NextEditPrefetchQueue } from "./NextEditPrefetchQueue.js"; import { renderDefaultSystemPrompt, renderDefaultUserPrompt, @@ -67,18 +67,7 @@ export class NextEditProvider { private endpointType: "default" | "fineTuned"; private diffContext: string = ""; private promptMetadata: PromptMetadata | null = null; - private prefetchQueue: PrefetchQueue< - NextEditOutcome, - RangeInFile, - { - helper: HelperVars; - diffContext: string; - llm: ILLM; - token: AbortSignal; - startTime: number; - newCursorPos: Position; - } - >; + private prefetchQueue: NextEditPrefetchQueue; // private refQueue: RangeInFile[] = []; // TODO: This needs to be cleared globally on cancel. public static currentEditChainId: string | null = null; @@ -106,25 +95,29 @@ export class NextEditProvider { token: AbortSignal; startTime: number; newCursorPos: Position; + editableRegionStrategy: EditableRegionStrategy; }, ) => { if (!other) return undefined; + // console.log("previousData:", previousData?.completion); // render prompt // TODO: this has to set the editable region properly. // console.log("fetchfunction - previousData:", previousData?.completion); const promptMetadata = renderPrompt( other.helper, other.diffContext, + other.editableRegionStrategy, previousData, resource, ); this.promptMetadata = promptMetadata; + // console.log("prompt:", promptMetadata.prompt); // call llm.chat const msg = await other.llm.chat([promptMetadata.prompt], other.token); // built and return outcome if (typeof msg.content === "string") { if (msg.content === "") return undefined; - // TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined + // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined const nextCompletion = replaceEscapedCharacters( msg.content.split("<|editable_region_start|>\n")[1], ).replace(/\n$/, ""); @@ -167,6 +160,8 @@ export class NextEditProvider { character: offset.character, }; + // TODO: if editable region strategy is naive, then we need to split the prediction up into regions. Also potentially filling up the prefetch queue. + const outcomeNext: NextEditOutcome = { elapsed: Date.now() - other.startTime, modelProvider: other.llm.underlyingProviderName, @@ -198,18 +193,11 @@ export class NextEditProvider { } }; - this.prefetchQueue = new PrefetchQueue< - NextEditOutcome, - RangeInFile, - { - helper: HelperVars; - diffContext: string; - llm: ILLM; - token: AbortSignal; - startTime: number; - newCursorPos: Position; - } - >(fetchFunction, [], undefined); + this.prefetchQueue = new NextEditPrefetchQueue( + fetchFunction, + [], + undefined, + ); } public static initialize( @@ -387,7 +375,11 @@ export class NextEditProvider { prompts.push(renderDefaultSystemPrompt()); prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); } else { - const promptMetadata = renderPrompt(helper, this.diffContext); + const promptMetadata = renderPrompt( + helper, + this.diffContext, + EditableRegionStrategy.Naive, + ); this.promptMetadata = promptMetadata; prompts.push(promptMetadata.prompt); } @@ -562,6 +554,7 @@ export class NextEditProvider { token, startTime, newCursorPos: helper.pos, + editableRegionStrategy: EditableRegionStrategy.Naive, }); const [snippetPayload, workspaceDirs] = await Promise.all([ @@ -588,20 +581,20 @@ export class NextEditProvider { directory, branch: branches[i], })); - const chunks = await getTopRelevantCodeChunks( - ` add(number) { - this.result += number; - return this; - }`, - { - ide: this.ide, - llm: llm, - config: config!, - tags: tags, - // filterDirectory: getUriPathBasename(helper.workspaceUris[0]), - }, - ); - console.log("chunks:", JSON.stringify(chunks, null, 2)); + // const chunks = await getTopRelevantCodeChunks( + // ` add(number) { + // this.result += number; + // return this; + // }`, + // { + // ide: this.ide, + // llm: llm, + // config: config!, + // tags: tags, + // // filterDirectory: getUriPathBasename(helper.workspaceUris[0]), + // }, + // ); + // console.log("chunks:", JSON.stringify(chunks, null, 2)); this.prefetchQueue.loadResource(refQueue); await this.prefetchQueue.initialize(); From 1ca57b1c5ef1a11acdb17941a18181384555cb0b Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 21:29:23 -0700 Subject: [PATCH 20/88] feat: use an actual queue data type instead of a two pointer --- core/util/PrefetchQueue.ts | 67 +++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/core/util/PrefetchQueue.ts b/core/util/PrefetchQueue.ts index 36b55ff10..360c6bf82 100644 --- a/core/util/PrefetchQueue.ts +++ b/core/util/PrefetchQueue.ts @@ -1,11 +1,10 @@ import { NextEditProvider } from "../nextEdit/NextEditProvider"; export class PrefetchQueue { - private currentPromise: Promise | null = null; - private nextPromise: Promise | null = null; - private resourceQueue: R[]; - private other: O | undefined; - private fetchFunction: ( + protected promiseQueue: Promise[] = []; + protected resourceQueue: R[]; + protected other: O | undefined; + protected fetchFunction: ( previousData: T | undefined, resource: R | undefined, other: O | undefined, @@ -26,9 +25,6 @@ export class PrefetchQueue { } loadResource(resources: R[]) { - // if (this.resourceQueue.length > 0) { - // throw new Error("Queue already initialized"); - // } this.resourceQueue = [...this.resourceQueue, ...resources]; } @@ -37,43 +33,45 @@ export class PrefetchQueue { } async initialize(): Promise { - // Get the first response (no resource needed). - this.currentPromise = this.fetchFunction(undefined, undefined, this.other); - const firstData = await this.currentPromise; - // TODO: cleanse editable_region_start and trailing newline. + // Get the first response (no resource needed) + const firstPromise = this.fetchFunction(undefined, undefined, this.other); + this.promiseQueue.push(firstPromise); - // Create the next promise based on the first response and first resource. - // if (this.resourceQueue.length > 0) { - const resource = this.resourceQueue.shift()!; - this.nextPromise = this.fetchFunction(firstData, resource, this.other); - // } + // Prefetch the next item using the first resource + const firstData = await firstPromise; + if (this.resourceQueue.length > 0) { + const resource = this.resourceQueue.shift()!; + const nextPromise = this.fetchFunction(firstData, resource, this.other); + this.promiseQueue.push(nextPromise); + } } async pop(): Promise { - if (!this.currentPromise) { - // throw new Error("Queue not initialized"); + if (this.promiseQueue.length === 0) { return undefined; } - const currentData = await this.currentPromise; + // Get and remove the first promise from the queue + const currentPromise = this.promiseQueue.shift()!; + const currentData = await currentPromise; - // Move next promise to current (if it exists). - if (this.nextPromise) { - this.currentPromise = this.nextPromise; + // If we have resources left, prefetch the next item + if (this.resourceQueue.length > 0) { + // Get the most recently added promise (now at the end of the queue) + const previousPromise = + this.promiseQueue.length > 0 + ? this.promiseQueue[this.promiseQueue.length - 1] + : Promise.resolve(currentData); - // Create new next promise if we have resources left. + // Create new promise based on the previous one and next resource const resource = this.resourceQueue.shift()!; - this.nextPromise = this.currentPromise.then((data) => + const nextPromise = previousPromise.then((data) => this.fetchFunction(data, resource, this.other), ); - // if (this.resourceQueue.length > 0) { - // } else { - // this.nextPromise = null; - // } - } else { - NextEditProvider.currentEditChainId = null; - // throw new Error("No more items in queue"); - return undefined; + + this.promiseQueue.push(nextPromise); + } else if (this.promiseQueue.length === 0) { + // No more items in the queue and no more resources } console.log("currentData:", currentData); @@ -81,10 +79,11 @@ export class PrefetchQueue { } hasNext(): boolean { - return this.nextPromise !== null; + return this.promiseQueue.length > 0; } getRemainingResourceCount(): number { return this.resourceQueue.length; } } + From 0363bb63c14df653fe2f666a2523365b697e3a6d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 21:29:34 -0700 Subject: [PATCH 21/88] feat: use strategies --- .../templating/NextEditPromptEngine.ts | 57 +++++++++++++++---- 1 file changed, 45 insertions(+), 12 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 98f382126..8b02ad401 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -10,6 +10,10 @@ import { USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; import { createDiff, DiffFormatType } from "../context/diffFormatting"; +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "../NextEditEditableRegionCarver"; import { NextEditOutcome, NextEditTemplate, @@ -51,6 +55,7 @@ function templateRendererOfModel( export function renderPrompt( helper: HelperVars, userEdits: string, + editableRegionStrategy: EditableRegionStrategy, prevOutcome?: NextEditOutcome, toApply?: RangeInFile, ): PromptMetadata { @@ -89,6 +94,7 @@ export function renderPrompt( // TODO: apply prevOutcome to existing content. we will need the line range. // Also display the diff between existing content and applied content. if (prevOutcome) { + // console.log("renderPrompt prevOutcome:", prevOutcome.completion); // console.log( // "beforeInsert:", // helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), @@ -104,18 +110,27 @@ export function renderPrompt( ...helper.fileLines.slice(prevOutcome?.editableRegionEndLine), ]; // console.log("helper.fileContents:", helper.fileContents); - // TODO: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. + // NOTE: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. // The individual parts don't contain this. // console.log("appliedContent:", appliedContent); appliedContent = appliedContent.filter( (line) => !line.includes(USER_CURSOR_IS_HERE_TOKEN), ); - // TODO: helper.pos is outdated. // Given a previous response, we need to calculate where the cursor would be. // I think it's a good idea to calculate this in the response. + + const editableRegion = getNextEditableRegion(editableRegionStrategy, { + fileLines: appliedContent, + filepath: helper.filepath, + }); + + // console.log("appliedContent:", appliedContent); + // console.log("startLine:", editableRegion?.range.start.line); editedCodeWithTokens = insertTokens( appliedContent, prevOutcome.finalCursorPosition, + editableRegion?.range.start.line ?? undefined, + editableRegion?.range.end.line ?? undefined, ); // console.log("new editedCodeWithTokens:", editedCodeWithTokens); userEdits = createDiff({ @@ -313,9 +328,19 @@ export function renderDefaultUserPrompt( // } // } -function insertTokens(lines: string[], cursorPos: Position) { +function insertTokens( + lines: string[], + cursorPos: Position, + editableRegionStart?: number, + editableRegionEnd?: number, +) { const a = insertCursorToken(lines, cursorPos); - const b = insertEditableRegionTokensWithStaticRange(a, cursorPos); + const b = insertEditableRegionTokensWithStaticRange( + a, + cursorPos, + editableRegionStart, + editableRegionEnd, + ); return b.join("\n"); } @@ -339,20 +364,28 @@ function insertCursorToken(lines: string[], cursorPos: Position) { function insertEditableRegionTokensWithStaticRange( lines: string[], cursorPos: Position, + editableRegionStart?: number, + editableRegionEnd?: number, ) { if (cursorPos.line < 0 || cursorPos.line >= lines.length) { return lines; } // Ensure editable regions are within bounds. - const editableRegionStart = Math.max( - cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - 0, - ); - const editableRegionEnd = Math.min( - cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - lines.length - 1, // Line numbers should be zero-indexed. - ); + if (editableRegionStart === undefined) { + editableRegionStart = Math.max( + cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + } + if (editableRegionEnd === undefined) { + editableRegionEnd = Math.min( + cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + lines.length - 1, // Line numbers should be zero-indexed. + ); + } + + // console.log("editableRegionStart:", editableRegionStart); const instrumentedLines = [ ...lines.slice(0, editableRegionStart), From 00a996c1f9e7b28937d7260b80258cb16ced2fe2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 21:35:40 -0700 Subject: [PATCH 22/88] feat: add a jump manager --- extensions/vscode/src/activation/JumpManager.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index cf3c83290..66036ae08 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -1,9 +1,4 @@ import * as vscode from "vscode"; -// TODO: -// Checks for current viewport range. -// Creates and saves the Tab to Jump SVG decoration. -// Given the range to replace, determines whether to display the SVG or not. -// When SVG is displayed, reserve Tab and Esc for jumping. export class JumpManager { private static _instance: JumpManager | undefined; @@ -37,7 +32,7 @@ export class JumpManager { this._disposables = []; } - private async suggestJump(nextJumpLocation: vscode.Position) { + public async suggestJump(nextJumpLocation: vscode.Position) { const editor = vscode.window.activeTextEditor; if (editor) { From ef5986367ec0f9c5abeff07a55f2a73f0261fabf Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 17 Jul 2025 21:36:30 -0700 Subject: [PATCH 23/88] feat: use the jump manager --- .../vscode/src/autocomplete/completionProvider.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 4e401f72b..231c480e9 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -24,6 +24,7 @@ import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { NextEditOutcome } from "core/nextEdit/types"; +import { JumpManager } from "../activation/JumpManager"; import { NextEditWindowManager } from "../activation/NextEditWindowManager"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; @@ -66,6 +67,7 @@ export class ContinueCompletionProvider private completionProvider: CompletionProvider; private nextEditProvider: NextEditProvider; private nextEditLoggingService: NextEditLoggingService; + private jumpManager: JumpManager; public recentlyVisitedRanges: RecentlyVisitedRangesService; public recentlyEditedTracker: RecentlyEditedTracker; @@ -112,6 +114,8 @@ export class ContinueCompletionProvider "fineTuned", ); + this.jumpManager = JumpManager.getInstance(); + this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide); } @@ -366,6 +370,12 @@ export class ContinueCompletionProvider (autocompleteCompletionItem as any).completeBracketPairs = true; if (this.isNextEditActive) { + this.jumpManager.suggestJump( + new vscode.Position( + (outcome as NextEditOutcome).editableRegionStartLine, + 0, + ), + ); const editor = vscode.window.activeTextEditor; if (!editor) { return undefined; From 72533b6169e1eeba0f0842e41d5c43145d141694 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 09:35:27 -0700 Subject: [PATCH 24/88] fix: reranker jump --- core/nextEdit/NextEditEditableRegionCarver.ts | 130 +++++++++--------- 1 file changed, 68 insertions(+), 62 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCarver.ts b/core/nextEdit/NextEditEditableRegionCarver.ts index 0576a714b..dbe906814 100644 --- a/core/nextEdit/NextEditEditableRegionCarver.ts +++ b/core/nextEdit/NextEditEditableRegionCarver.ts @@ -1,19 +1,22 @@ -import { RangeInFile } from ".."; +import { Chunk, ChunkWithoutID, ILLM, RangeInFile } from ".."; import { cosineSimilarity } from "../context/retrieval/pipelines/NextEditRetrievalPipeline"; export enum EditableRegionStrategy { Naive = "naive", + Rerank = "rerank", Model = "model", Sliding = "sliding", } -export function getNextEditableRegion( +export async function getNextEditableRegion( strategy: EditableRegionStrategy, ctx: any, -): RangeInFile | null { +): Promise { switch (strategy) { case EditableRegionStrategy.Naive: return naiveJump(ctx); + case EditableRegionStrategy.Rerank: + return await rerankJump(ctx); case EditableRegionStrategy.Model: return modelJump(ctx); case EditableRegionStrategy.Sliding: @@ -24,6 +27,7 @@ export function getNextEditableRegion( } // Naive assumes that the entire file is editable. +// This relies on the next edit model to figure out where to jump next. function naiveJump(ctx: any): RangeInFile | null { const { fileLines, filepath } = ctx; if (!fileLines || !filepath) { @@ -43,6 +47,67 @@ function naiveJump(ctx: any): RangeInFile | null { }; } +// A rerank jump splits the current file into chunks. +// Then it uses a rerank model to get the most relevant chunks and their positions. +async function rerankJump(ctx: { + fileContent: string; + query: string; + filepath: string; + reranker: ILLM; + chunkSize: number; +}): Promise { + try { + const { fileContent, query, filepath, reranker, chunkSize = 5 } = ctx; + + if (!fileContent || !query || !filepath || !reranker) { + console.warn("Missing required context for rerank jump"); + return null; + } + + const lines = fileContent.split("\n"); + const chunks: Array = []; + + // Create chunks from the file. + for (let i = 0; i < lines.length; i += Math.floor(chunkSize / 2)) { + const endLine = Math.min(i + chunkSize - 1, lines.length - 1); + const chunkContent = lines.slice(i, endLine + 1).join("\n"); + chunks.push({ + content: chunkContent, + startLine: i, + endLine: endLine, + digest: `chunk-${i}-${endLine}`, + filepath: filepath, + index: i, + }); + } + + // Use the reranker to score each chunk against the query. + const scores = await reranker.rerank(query, chunks); + + // Sort by score in descending order and get the highest scoring chunk. + chunks.sort( + (a, b) => scores[chunks.indexOf(b)] - scores[chunks.indexOf(a)], + ); + + const mostRelevantChunk = chunks[0]; + + // Return the range of the most relevant chunk. + return { + filepath, + range: { + start: { line: mostRelevantChunk.startLine, character: 0 }, + end: { + line: mostRelevantChunk.endLine, + character: lines[mostRelevantChunk.endLine].length, + }, + }, + }; + } catch (error) { + console.error("Error in rerank jump:", error); + return null; + } +} + // A naive jump uses the next edit model to predict edits for the entire file. // Then it calculates the diff between that and the original to get the jump location. function modelJump(ctx: any): RangeInFile | null { @@ -195,65 +260,6 @@ function slidingJump(ctx: any): RangeInFile | null { } } -// A rerank jump splits the current file into chunks. -// Then it uses a rerank model to get the most relevant chunks and their positions. -function rerankJump(ctx: any): RangeInFile | null { - try { - const { fileContent, query, filepath, reranker, chunkSize = 10 } = ctx; - - if (!fileContent || !query || !filepath || !reranker) { - console.warn("Missing required context for rerank jump"); - return null; - } - - const lines = fileContent.split("\n"); - const chunks: Array<{ - content: string; - startLine: number; - endLine: number; - }> = []; - - // Create chunks from the file - for (let i = 0; i < lines.length; i += Math.floor(chunkSize / 2)) { - const endLine = Math.min(i + chunkSize - 1, lines.length - 1); - const chunkContent = lines.slice(i, endLine + 1).join("\n"); - chunks.push({ - content: chunkContent, - startLine: i, - endLine: endLine, - }); - } - - // Use the reranker to score each chunk against the query - const scoredChunks = chunks.map((chunk) => ({ - ...chunk, - score: reranker.rerank(query, [{ content: chunk.content }])[0], - })); - - // Sort by score in descending order and get the highest scoring chunk - const mostRelevantChunk = scoredChunks.sort((a, b) => b.score - a.score)[0]; - - if (!mostRelevantChunk) { - return null; - } - - // Return the range of the most relevant chunk - return { - filepath, - range: { - start: { line: mostRelevantChunk.startLine, character: 0 }, - end: { - line: mostRelevantChunk.endLine, - character: lines[mostRelevantChunk.endLine].length, - }, - }, - }; - } catch (error) { - console.error("Error in rerank jump:", error); - return null; - } -} - // Helper method to create a simple vector representation of a text string. function createSimpleVector(text: string): number[] { const tokenFrequency: Record = {}; From bfbce53f3a5c367a98558f6e0ef9e6b94251f465 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 09:35:48 -0700 Subject: [PATCH 25/88] fix: ditch the prefetch queue for now --- extensions/vscode/src/autocomplete/completionProvider.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 231c480e9..63d175df8 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -240,18 +240,17 @@ export class ContinueCompletionProvider setupStatusBar(undefined, true); - // TODO: Consume next edit generator. let outcome: AutocompleteOutcome | NextEditOutcome | undefined; // Check if editChainId exists or needs to be refreshed. if (this.isNextEditActive) { const st = performance.now(); - outcome = await this.nextEditProvider.provideNextEditPrediction( + outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, ); - console.log(performance.now() - st); - console.log(outcome?.elapsed); + // console.log(performance.now() - st); + // console.log(outcome?.elapsed); } else { outcome = await this.completionProvider.provideInlineCompletionItems( input, From ae36095a89531a98fd97c71560a178d163cab163 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 12:32:39 -0700 Subject: [PATCH 26/88] chore: remove console.logs --- core/nextEdit/diff/diff.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index cc6908690..91d2eae41 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -136,8 +136,8 @@ export function checkFim( isFim: false; fimText: null; } { - console.log("oldEditRange", oldEditRange); - console.log("newEditRange", newEditRange); + // console.log("oldEditRange", oldEditRange); + // console.log("newEditRange", newEditRange); // Find the common prefix. let prefixLength = 0; while ( From deae3c66d3ed28d9de4b818dbc5ad4e7e93d0f54 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 12:33:20 -0700 Subject: [PATCH 27/88] feat: render jump suggestion at the location of the next decoration when the decoration should be rendered inside the viewport --- extensions/vscode/src/activation/JumpManager.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 66036ae08..b459f1002 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -60,7 +60,12 @@ export class JumpManager { ); } else { // No suggestion is made when the decoration is within visibleRange. - return; + await this.renderTabToJumpDecoration( + editor, + decorationLine, + nextJumpLocation, + ); + // return; } // Scroll to show the jump location. @@ -92,8 +97,14 @@ export class JumpManager { }); // Apply the decoration. + const lastIndexOfLine = editor.document.lineAt(lineToRenderOn).text.length; editor.setDecorations(this._jumpDecoration, [ - new vscode.Range(lineToRenderOn, 0, lineToRenderOn, 0), + new vscode.Range( + lineToRenderOn, + lastIndexOfLine, + lineToRenderOn, + lastIndexOfLine, + ), ]); // Set the context key to enable tab/esc shortcuts. From 39cc73f3a2c835ed5cce4e33b235b6de71ef28a2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 12:33:47 -0700 Subject: [PATCH 28/88] fix: reranker expects non-empty chunk contents --- core/nextEdit/NextEditEditableRegionCarver.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCarver.ts b/core/nextEdit/NextEditEditableRegionCarver.ts index dbe906814..85cbb30ee 100644 --- a/core/nextEdit/NextEditEditableRegionCarver.ts +++ b/core/nextEdit/NextEditEditableRegionCarver.ts @@ -1,4 +1,4 @@ -import { Chunk, ChunkWithoutID, ILLM, RangeInFile } from ".."; +import { Chunk, ILLM, RangeInFile } from ".."; import { cosineSimilarity } from "../context/retrieval/pipelines/NextEditRetrievalPipeline"; export enum EditableRegionStrategy { @@ -60,17 +60,26 @@ async function rerankJump(ctx: { const { fileContent, query, filepath, reranker, chunkSize = 5 } = ctx; if (!fileContent || !query || !filepath || !reranker) { - console.warn("Missing required context for rerank jump"); + console.warn( + "Missing required context for rerank jump:", + !fileContent, + !query, + !filepath, + !reranker, + ); return null; } + console.log("reranker", reranker); + const lines = fileContent.split("\n"); - const chunks: Array = []; + const chunks: Chunk[] = []; // Create chunks from the file. for (let i = 0; i < lines.length; i += Math.floor(chunkSize / 2)) { const endLine = Math.min(i + chunkSize - 1, lines.length - 1); const chunkContent = lines.slice(i, endLine + 1).join("\n"); + if (chunkContent === "") continue; // Voyager throws an error if there are empty strings in its document field in the body. chunks.push({ content: chunkContent, startLine: i, @@ -92,6 +101,9 @@ async function rerankJump(ctx: { const mostRelevantChunk = chunks[0]; // Return the range of the most relevant chunk. + // NOTE: It might be better to return a list of chunks, + // because it's very difficult to gauge when to stop the model. + // We could argue that we should always try to jump until the user says no. return { filepath, range: { From 8e867fa362bc819a49405df46e8efa682ee3e165 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 12:34:00 -0700 Subject: [PATCH 29/88] feat: add chain-related methods --- core/nextEdit/NextEditProvider.ts | 36 +++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 6265f06db..88906b056 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,4 +1,5 @@ import * as path from "path"; +import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { BranchAndDir, @@ -13,7 +14,6 @@ import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js"; -import { randomUUID } from "crypto"; import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; @@ -69,8 +69,8 @@ export class NextEditProvider { private promptMetadata: PromptMetadata | null = null; private prefetchQueue: NextEditPrefetchQueue; // private refQueue: RangeInFile[] = []; - // TODO: This needs to be cleared globally on cancel. - public static currentEditChainId: string | null = null; + private currentEditChainId: string | null = null; + private previousCompletions: string[] = []; private constructor( private readonly configHandler: ConfigHandler, @@ -318,6 +318,27 @@ export class NextEditProvider { return options; } + public chainExists(): boolean { + return this.currentEditChainId !== null; + } + + public getPreviousCompletion(): string | null { + return this.previousCompletions[0]; + } + + public deleteChain(): void { + this.currentEditChainId = null; + this.previousCompletions = []; + } + + public startChain(id?: string) { + this.currentEditChainId = id ?? uuidv4(); + } + + public isStartOfChain() { + return this.previousCompletions.length === 1; + } + public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, @@ -444,6 +465,8 @@ export class NextEditProvider { msg.content.split("<|editable_region_start|>\n")[1], ).replace(/\n$/, ""); + this.previousCompletions.push(nextCompletion); + const currCursorPos = helper.pos; const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, @@ -462,7 +485,8 @@ export class NextEditProvider { helper.pos, editableRegionStartLine, oldEditRangeSlice, - "", + // "", + nextCompletion, ); const outcomeNext: NextEditOutcome = { @@ -506,7 +530,7 @@ export class NextEditProvider { token: AbortSignal | undefined, ) { try { - if (NextEditProvider.currentEditChainId) { + if (this.currentEditChainId) { return await this.prefetchQueue.pop(); } @@ -545,7 +569,7 @@ export class NextEditProvider { return undefined; } - NextEditProvider.currentEditChainId = randomUUID(); + // this.currentEditChainId = randomUUID(); this.prefetchQueue.loadOther({ helper, From c7b182f5f3e5f1a85c83d64b97421667fd009b08 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 12:34:14 -0700 Subject: [PATCH 30/88] feat: display jump decoration --- .../src/autocomplete/completionProvider.ts | 66 ++++++++++++++----- 1 file changed, 49 insertions(+), 17 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 63d175df8..9f7eab8eb 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -21,9 +21,14 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "core/nextEdit/constants"; import { checkFim } from "core/nextEdit/diff/diff"; +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "core/nextEdit/NextEditEditableRegionCarver"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { NextEditOutcome } from "core/nextEdit/types"; +import { localPathOrUriToPath } from "core/util/pathToUri"; import { JumpManager } from "../activation/JumpManager"; import { NextEditWindowManager } from "../activation/NextEditWindowManager"; import { getDefinitionsFromLsp } from "./lsp"; @@ -95,6 +100,7 @@ export class ContinueCompletionProvider } return config.selectedModelByRole.autocomplete ?? undefined; } + this.completionProvider = new CompletionProvider( this.configHandler, this.ide, @@ -121,6 +127,14 @@ export class ContinueCompletionProvider _lastShownCompletion: AutocompleteOutcome | NextEditOutcome | undefined; + private async getRerankModel() { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return; + } + return config.selectedModelByRole.rerank ?? undefined; + } + public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, @@ -171,14 +185,36 @@ export class ContinueCompletionProvider token.onCancellationRequested(() => abortController.abort()); // Handle notebook cells - const pos = { + let pos = { line: position.line, character: position.character, }; - // const pos = { - // line: 0, - // character: 0, - // }; + + if (this.nextEditProvider.chainExists()) { + // If the user has accepted the previous completion, the chain of edits is alive. + // Get the next editable region and set the pos to be within that range. + const nextEditableRegion = await getNextEditableRegion( + EditableRegionStrategy.Rerank, + { + fileContent: document.getText(), + query: this.nextEditProvider.getPreviousCompletion(), // previous completion in the chain + filepath: localPathOrUriToPath(document.uri.toString()), + reranker: await this.getRerankModel(), + chunkSize: 5, + }, + ); + + if (nextEditableRegion) { + pos = { + line: nextEditableRegion.range.start.line, + character: nextEditableRegion.range.start.character, + }; + } + } else { + // If the user has rejected, then we start a new chain of edits. + this.nextEditProvider.startChain(); + } + let manuallyPassFileContents: string | undefined = undefined; if (document.uri.scheme === "vscode-notebook-cell") { const notebook = vscode.workspace.notebookDocuments.find((notebook) => @@ -244,13 +280,10 @@ export class ContinueCompletionProvider // Check if editChainId exists or needs to be refreshed. if (this.isNextEditActive) { - const st = performance.now(); outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, ); - // console.log(performance.now() - st); - // console.log(outcome?.elapsed); } else { outcome = await this.completionProvider.provideInlineCompletionItems( input, @@ -319,10 +352,7 @@ export class ContinueCompletionProvider // Construct the range/text to show const startPos = selectedCompletionInfo?.range.start ?? position; - // const startPos = new vscode.Position(0, 0); - // const endPos = new vscode.Position(0, 5); let range = new vscode.Range(startPos, startPos); - // let range = new vscode.Range(startPos, endPos); let completionText = outcome.completion; // NOTE: This seems like an autocomplete logic. @@ -369,12 +399,14 @@ export class ContinueCompletionProvider (autocompleteCompletionItem as any).completeBracketPairs = true; if (this.isNextEditActive) { - this.jumpManager.suggestJump( - new vscode.Position( - (outcome as NextEditOutcome).editableRegionStartLine, - 0, - ), - ); + if (!this.nextEditProvider.isStartOfChain()) { + await this.jumpManager.suggestJump( + new vscode.Position( + (outcome as NextEditOutcome).editableRegionStartLine, + 0, + ), + ); + } const editor = vscode.window.activeTextEditor; if (!editor) { return undefined; From 4c15e87b86a75e46460acd0fd0fc9d89ea446d87 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 13:32:33 -0700 Subject: [PATCH 31/88] feat: feat --- .../vscode/src/activation/JumpManager.ts | 34 ++++++++++++++++++- .../src/autocomplete/completionProvider.ts | 14 +++++--- extensions/vscode/src/commands.ts | 9 +++++ 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index b459f1002..d0da8faa2 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -32,7 +32,10 @@ export class JumpManager { this._disposables = []; } - public async suggestJump(nextJumpLocation: vscode.Position) { + public async suggestJump( + nextJumpLocation: vscode.Position, + nextEditData?: any, + ) { const editor = vscode.window.activeTextEditor; if (editor) { @@ -75,6 +78,35 @@ export class JumpManager { ); } } + + if (nextEditData) { + this.pendingNextEditData = nextEditData; + + const disposable = vscode.window.onDidChangeTextEditorSelection((e) => { + const editor = vscode.window.activeTextEditor; + if (editor && e.textEditor === editor) { + const currentPosition = editor.selection.active; + + if (Math.abs(currentPosition.line - nextJumpLocation.line) <= 1) { + disposable.dispose(); + + vscode.commands.executeCommand("continue.showNextEditAfterJump", { + ...this.pendingNextEditData, + currentPosition, + }); + + this.pendingNextEditData = undefined; + } + } + }); + + setTimeout(() => { + if (this.pendingNextEditData) { + disposable.dispose(); + this.pendingNextEditData = undefined; + } + }, 10000); + } } private async renderTabToJumpDecoration( diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 9f7eab8eb..d9883f928 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -400,12 +400,16 @@ export class ContinueCompletionProvider if (this.isNextEditActive) { if (!this.nextEditProvider.isStartOfChain()) { - await this.jumpManager.suggestJump( - new vscode.Position( - (outcome as NextEditOutcome).editableRegionStartLine, - 0, - ), + const jumpPosition = new vscode.Position( + (outcome as NextEditOutcome).editableRegionStartLine, + 0, ); + await this.jumpManager.suggestJump(jumpPosition, { + completionId: input.completionId, + outcome: outcome as NextEditOutcome, + }); + + return undefined; } const editor = vscode.window.activeTextEditor; if (!editor) { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 3b247f88b..c4a1e4d9e 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -805,6 +805,15 @@ const getCommandsMap: ( "editor.action.inlineSuggest.trigger", ); }, + "continue.showNextEditAfterJump": async (data) => { + const { completionId, outcome, currCursorPos } = data; + const editor = vscode.window.activeTextEditor; + if (!editor) return; + + // This would be the same logic as in the renderNextEditSuggestion method + // from my first suggestion + // ... + }, }; }; From 9dce2baa8faaec876575a9755e58d257e7f9384d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 15:06:44 -0700 Subject: [PATCH 32/88] feat: delay the next edit decoration until the jump is complete --- .../vscode/src/activation/JumpManager.ts | 64 ++++++++++--------- .../src/autocomplete/completionProvider.ts | 18 ++++-- 2 files changed, 47 insertions(+), 35 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index d0da8faa2..b6704fd8f 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -8,6 +8,9 @@ export class JumpManager { private _jumpDecorationVisible = false; private _disposables: vscode.Disposable[] = []; + private _jumpInProgress: boolean = false; + private _completionAfterJump: any = null; + private constructor() {} initialize() {} @@ -32,10 +35,9 @@ export class JumpManager { this._disposables = []; } - public async suggestJump( - nextJumpLocation: vscode.Position, - nextEditData?: any, - ) { + public async suggestJump(nextJumpLocation: vscode.Position) { + this._jumpInProgress = true; + const editor = vscode.window.activeTextEditor; if (editor) { @@ -68,7 +70,6 @@ export class JumpManager { decorationLine, nextJumpLocation, ); - // return; } // Scroll to show the jump location. @@ -79,34 +80,27 @@ export class JumpManager { } } - if (nextEditData) { - this.pendingNextEditData = nextEditData; + // Set up a way to detect when the jump is complete. + const disposable = vscode.window.onDidChangeTextEditorSelection(() => { + this._jumpInProgress = false; + disposable.dispose(); - const disposable = vscode.window.onDidChangeTextEditorSelection((e) => { - const editor = vscode.window.activeTextEditor; - if (editor && e.textEditor === editor) { - const currentPosition = editor.selection.active; + // If there's a completion waiting to be shown after the jump, + // execute the command to show it. + if (this._completionAfterJump) { + vscode.commands.executeCommand( + "continue.showNextEditAfterJump", + this._completionAfterJump, + ); + this._completionAfterJump = null; + } + }); - if (Math.abs(currentPosition.line - nextJumpLocation.line) <= 1) { - disposable.dispose(); - - vscode.commands.executeCommand("continue.showNextEditAfterJump", { - ...this.pendingNextEditData, - currentPosition, - }); - - this.pendingNextEditData = undefined; - } - } - }); - - setTimeout(() => { - if (this.pendingNextEditData) { - disposable.dispose(); - this.pendingNextEditData = undefined; - } - }, 10000); - } + // Clean up after timeout if no jump has been made. + setTimeout(() => { + this._jumpInProgress = false; + disposable.dispose(); + }, 5000); } private async renderTabToJumpDecoration( @@ -197,4 +191,12 @@ export class JumpManager { // This allows us to dispose the command after a jump is completed. this._disposables.push(acceptJumpCommand, rejectJumpCommand); } + + isJumpInProgress(): boolean { + return this._jumpInProgress; + } + + setCompletionAfterJump(completionData: any): void { + this._completionAfterJump = completionData; + } } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d9883f928..294e09dd5 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -404,13 +404,23 @@ export class ContinueCompletionProvider (outcome as NextEditOutcome).editableRegionStartLine, 0, ); - await this.jumpManager.suggestJump(jumpPosition, { - completionId: input.completionId, - outcome: outcome as NextEditOutcome, - }); + + await this.jumpManager.suggestJump(jumpPosition); + + // If a jump was just suggested, don't show ghost text yet. + if (this.jumpManager.isJumpInProgress()) { + // Store this completion for later use when jump is complete. + this.jumpManager.setCompletionAfterJump({ + completionId: input.completionId, + outcome: outcome as NextEditOutcome, + }); + + return undefined; // Don't show anything yet! + } return undefined; } + const editor = vscode.window.activeTextEditor; if (!editor) { return undefined; From 07c7371ba53cd9bc42645be3a3894439fae77969 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 15:07:07 -0700 Subject: [PATCH 33/88] feat: add a display after jump command --- extensions/vscode/src/commands.ts | 113 ++++++++++++++++++++++++++++-- 1 file changed, 107 insertions(+), 6 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index c4a1e4d9e..d7f23f3d0 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -17,7 +17,14 @@ import * as YAML from "yaml"; import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist"; +import { myersDiff } from "core/diff/myers"; +import { + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, +} from "core/nextEdit/constants"; +import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; +import { NextEditWindowManager } from "./activation/NextEditWindowManager"; import { getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, @@ -806,13 +813,107 @@ const getCommandsMap: ( ); }, "continue.showNextEditAfterJump": async (data) => { - const { completionId, outcome, currCursorPos } = data; - const editor = vscode.window.activeTextEditor; - if (!editor) return; + // NOTE: This could use some cleanup or abstraction. + // The logic is largely similar to that of completionProvider.ts + // but we don't have access to the class. - // This would be the same logic as in the renderNextEditSuggestion method - // from my first suggestion - // ... + const { completionId, outcome, currentPosition } = data; + + const editor = vscode.window.activeTextEditor; + if (!editor) { + console.log("No active editor when trying to show next edit"); + return; + } + + // Calculate the editable region boundaries around the current cursor position/ + const editableRegionStartLine = Math.max( + currentPosition.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + const editableRegionEndLine = Math.min( + currentPosition.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + editor.document.lineCount - 1, + ); + + // Get the current text in the editable region. + const oldEditRangeSlice = editor.document + .getText() + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + // Get the suggested new text from the completion outcome. + const newEditRangeSlice = outcome.completion; + + // Skip showing edit if the suggestion is empty. + if (newEditRangeSlice === "") { + const loggingService = NextEditLoggingService.getInstance(); + loggingService.cancelRejectionTimeout(completionId); + return; + } + + // Skip showing edit if the suggestion is identical to current text. + if (oldEditRangeSlice === newEditRangeSlice) { + const loggingService = NextEditLoggingService.getInstance(); + loggingService.cancelRejectionTimeout(completionId); + return; + } + + // Check if this is a simple "fill in middle" (FIM) type edit. + const { isFim, fimText } = checkFim( + oldEditRangeSlice, + newEditRangeSlice, + currentPosition, + ); + + if (isFim) { + // For FIM edits, create an inline completion item. + const nextEditCompletionItem = new vscode.InlineCompletionItem( + fimText, + new vscode.Range( + new vscode.Position( + currentPosition.line, + currentPosition.character, + ), + new vscode.Position( + currentPosition.line, + currentPosition.character, + ), + ), + { + title: "Log Next Edit Outcome", + command: "continue.logNextEditOutcomeAccept", + arguments: [completionId, NextEditLoggingService.getInstance()], + }, + ); + + // Show the ghost text using VS Code's inline completion API. + // We need to trigger this manually since we're not in the completion provider. + await vscode.commands.executeCommand( + "editor.action.inlineCompletions.showNext", + { + completions: [nextEditCompletionItem], + position: currentPosition, + }, + ); + } else { + // For more complex edits, we display a diff inside a window. + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + + if (NextEditWindowManager.isInstantiated()) { + const windowManager = NextEditWindowManager.getInstance(); + windowManager.updateCurrentCompletionId(completionId); + + await windowManager.showNextEditWindow( + editor, + currentPosition, + editableRegionStartLine, + oldEditRangeSlice, + newEditRangeSlice, + diffLines, + ); + } + } }, }; }; From 2488df36fcd35a3294d8aa33d1451fd7fa4c4182 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:05:17 -0700 Subject: [PATCH 34/88] feat: jump only when necessary --- .../vscode/src/activation/JumpManager.ts | 130 +++++++++++++++++- 1 file changed, 123 insertions(+), 7 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index b6704fd8f..1d180c072 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -1,5 +1,13 @@ +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { NextEditOutcome } from "core/nextEdit/types"; import * as vscode from "vscode"; +export interface CompletionDataForAfterJump { + completionId: string; + outcome: NextEditOutcome; + currentPosition: vscode.Position; +} + export class JumpManager { private static _instance: JumpManager | undefined; @@ -9,7 +17,8 @@ export class JumpManager { private _disposables: vscode.Disposable[] = []; private _jumpInProgress: boolean = false; - private _completionAfterJump: any = null; + private _completionAfterJump: CompletionDataForAfterJump | null = null; + private _oldCursorPosition: vscode.Position | undefined; private constructor() {} @@ -35,8 +44,84 @@ export class JumpManager { this._disposables = []; } - public async suggestJump(nextJumpLocation: vscode.Position) { + public async suggestJump( + currentPosition: vscode.Position, + nextJumpLocation: vscode.Position, + completionContent?: string, + ) { + // Deduplication logic. + // If the content at the next jump location is + // identical to the completion content, + // then we don't have to jump. + if (completionContent !== undefined) { + const editor = vscode.window.activeTextEditor; + if (editor) { + try { + const completionLines = completionContent.split("\n"); + + // Get document content at jump location spanning multiple lines. + const document = editor.document; + const startLine = nextJumpLocation.line; + const endLine = Math.min( + startLine + completionLines.length - 1, + document.lineCount - 1, + ); + + // Check if we have enough lines in the document to compare. + if (endLine - startLine + 1 < completionLines.length) { + // Not enough lines in document, so content can't be identical. + // Proceed to jump! + } else { + // Check the first line first for early exit. + const firstLineText = document.lineAt(startLine).text; + const firstLineSubstring = firstLineText.substring( + nextJumpLocation.character, + ); + const firstCompletionLine = completionLines[0]; + + if (!firstLineSubstring.startsWith(firstCompletionLine)) { + // First line doesn't match, so proceed to jump. + } else { + // Check remaining lines if there are any. + if (completionLines.length > 1) { + let fullMatch = true; + + // Process remaining lines. + for (let i = 1; i < completionLines.length; i++) { + const documentLine = startLine + i; + if (documentLine <= endLine) { + const lineText = document.lineAt(documentLine).text; + if (lineText !== completionLines[i]) { + fullMatch = false; + break; + } + } + } + + if (fullMatch) { + console.log( + "Skipping jump as content is identical at jump location", + ); + return; // Exit early, don't suggest jump. + } + } else { + // Only one line and it matches. + console.log( + "Skipping jump as content is identical at jump location", + ); + return; // Exit early, don't suggest jump. + } + } + } + } catch (error) { + console.error("Error checking content at jump location:", error); + // Continue with jump even if there's an error checking content. + } + } + } + this._jumpInProgress = true; + this._oldCursorPosition = currentPosition; const editor = vscode.window.activeTextEditor; @@ -114,12 +199,11 @@ export class JumpManager { // Create a decoration for jump. this._jumpDecoration = vscode.window.createTextEditorDecorationType({ before: { - contentText: "📌 Press Tab to jump, Esc to cancel", + contentText: "🦘 Press Tab to jump, Esc to cancel", color: new vscode.ThemeColor("editorInfo.foreground"), backgroundColor: new vscode.ThemeColor("editorInfo.background"), - margin: "0 0 0 0", + margin: `0 0 0 4px`, }, - isWholeLine: true, }); // Apply the decoration. @@ -183,20 +267,52 @@ export class JumpManager { "continue.rejectJump", async () => { if (this._jumpDecorationVisible) { + console.log( + "deleteChain from JumpManager.ts: rejectJump and decoration visible", + ); + NextEditProvider.getInstance().deleteChain(); await this.clearJumpDecoration(); } }, ); + // Add a selection change listener to the editor to reject jump when cursor moves. + const selectionChangeListener = + vscode.window.onDidChangeTextEditorSelection((e) => { + // If jump decoration isn't visible, nothing to do. + if (!this._jumpDecorationVisible) { + return; + } + + const currentPosition = e.selections[0].active; + + // If cursor moved to jump position, this is likely the result of acceptJump. + if (currentPosition.isEqual(jumpPosition)) { + return; + } + + // If cursor position changed for any other reason, reject the jump. + if ( + this._oldCursorPosition && + !currentPosition.isEqual(this._oldCursorPosition) + ) { + vscode.commands.executeCommand("continue.rejectJump"); + } + }); + // This allows us to dispose the command after a jump is completed. - this._disposables.push(acceptJumpCommand, rejectJumpCommand); + this._disposables.push( + acceptJumpCommand, + rejectJumpCommand, + selectionChangeListener, + ); } isJumpInProgress(): boolean { return this._jumpInProgress; } - setCompletionAfterJump(completionData: any): void { + setCompletionAfterJump(completionData: CompletionDataForAfterJump): void { this._completionAfterJump = completionData; } } From f137cc3d9a618d156e4e30588812cc99f2cdfdcf Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:06:04 -0700 Subject: [PATCH 35/88] chore: remove console.log --- core/nextEdit/NextEditEditableRegionCarver.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCarver.ts b/core/nextEdit/NextEditEditableRegionCarver.ts index 85cbb30ee..69a6708e7 100644 --- a/core/nextEdit/NextEditEditableRegionCarver.ts +++ b/core/nextEdit/NextEditEditableRegionCarver.ts @@ -70,8 +70,6 @@ async function rerankJump(ctx: { return null; } - console.log("reranker", reranker); - const lines = fileContent.split("\n"); const chunks: Chunk[] = []; From b6ab6e3585bf0713fe105c28d4932118670a8675 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:06:21 -0700 Subject: [PATCH 36/88] feat: await renderPrompt --- core/nextEdit/NextEditProvider.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 88906b056..ad969a84f 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -103,7 +103,7 @@ export class NextEditProvider { // render prompt // TODO: this has to set the editable region properly. // console.log("fetchfunction - previousData:", previousData?.completion); - const promptMetadata = renderPrompt( + const promptMetadata = await renderPrompt( other.helper, other.diffContext, other.editableRegionStrategy, @@ -335,6 +335,10 @@ export class NextEditProvider { this.currentEditChainId = id ?? uuidv4(); } + public getChain() { + return this.previousCompletions; + } + public isStartOfChain() { return this.previousCompletions.length === 1; } @@ -396,7 +400,7 @@ export class NextEditProvider { prompts.push(renderDefaultSystemPrompt()); prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); } else { - const promptMetadata = renderPrompt( + const promptMetadata = await renderPrompt( helper, this.diffContext, EditableRegionStrategy.Naive, From d3c250ff85fd0215756c1fe62a8e4e9a8dbf12f3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:06:34 -0700 Subject: [PATCH 37/88] feat: await for other functions --- core/nextEdit/templating/NextEditPromptEngine.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 8b02ad401..5efb341ce 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -52,13 +52,13 @@ function templateRendererOfModel( }; } -export function renderPrompt( +export async function renderPrompt( helper: HelperVars, userEdits: string, editableRegionStrategy: EditableRegionStrategy, prevOutcome?: NextEditOutcome, toApply?: RangeInFile, -): PromptMetadata { +): Promise { let modelName = helper.modelName as NextEditModelName; if (modelName === "this field is not used") { @@ -119,7 +119,7 @@ export function renderPrompt( // Given a previous response, we need to calculate where the cursor would be. // I think it's a good idea to calculate this in the response. - const editableRegion = getNextEditableRegion(editableRegionStrategy, { + const editableRegion = await getNextEditableRegion(editableRegionStrategy, { fileLines: appliedContent, filepath: helper.filepath, }); From 6e36bc89ef4ad990f19d6c35741446a7d9ad9fd6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:07:41 -0700 Subject: [PATCH 38/88] feat: pass data for rendering completion after jump --- extensions/vscode/src/commands.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index d7f23f3d0..693fbd9aa 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -24,6 +24,8 @@ import { } from "core/nextEdit/constants"; import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { CompletionDataForAfterJump } from "./activation/JumpManager"; import { NextEditWindowManager } from "./activation/NextEditWindowManager"; import { getAutocompleteStatusBarDescription, @@ -812,7 +814,9 @@ const getCommandsMap: ( "editor.action.inlineSuggest.trigger", ); }, - "continue.showNextEditAfterJump": async (data) => { + "continue.showNextEditAfterJump": async ( + data: CompletionDataForAfterJump, + ) => { // NOTE: This could use some cleanup or abstraction. // The logic is largely similar to that of completionProvider.ts // but we don't have access to the class. @@ -867,6 +871,10 @@ const getCommandsMap: ( ); if (isFim) { + if (!fimText) { + console.log("deleteChain from commands.ts: !fimText"); + NextEditProvider.getInstance().deleteChain(); + } // For FIM edits, create an inline completion item. const nextEditCompletionItem = new vscode.InlineCompletionItem( fimText, @@ -899,6 +907,11 @@ const getCommandsMap: ( } else { // For more complex edits, we display a diff inside a window. const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + if (diffLines.length === 0) { + console.log("deleteChain from commands.ts: diffLines.length === 0"); + NextEditProvider.getInstance().deleteChain(); + } + console.log("number of difflines:", diffLines.length); if (NextEditWindowManager.isInstantiated()) { const windowManager = NextEditWindowManager.getInstance(); From 1e02676ff13354298393b83847b9f5ab9ca12a84 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:08:10 -0700 Subject: [PATCH 39/88] feat: remove static member, add hasAccepted method --- .../vscode/src/activation/NextEditWindowManager.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 25171c935..37414830e 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -201,7 +201,10 @@ export class NextEditWindowManager { // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => { - NextEditProvider.currentEditChainId = null; + console.log( + "deleteChain from NextEditWindowManager.ts: hide next edit command", + ); + NextEditProvider.getInstance().deleteChain(); await this.hideAllNextEditWindowsAndResetCompletionId(); }); this.registerCommandSafely( @@ -318,8 +321,6 @@ export class NextEditWindowManager { * Hide all tooltips in all editors. */ public async hideAllNextEditWindows() { - NextEditProvider.currentEditChainId = null; - if (this.currentDecoration) { vscode.window.visibleTextEditors.forEach((editor) => { editor.setDecorations(this.currentDecoration!, []); @@ -848,6 +849,10 @@ export class NextEditWindowManager { // If all else fails, return a reasonable default return SVG_CONFIG.fontSize * 0.6; } + + public hasAccepted() { + return this.accepted; + } } export default async function setupNextEditWindowManager( From adfa2a8b59a70b99fc2b8e5bf69642b0b8a83562 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:09:11 -0700 Subject: [PATCH 40/88] feat: use new jump manager methods --- .../src/autocomplete/completionProvider.ts | 44 ++++++++++++++++--- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 294e09dd5..eae812873 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -31,6 +31,7 @@ import { NextEditOutcome } from "core/nextEdit/types"; import { localPathOrUriToPath } from "core/util/pathToUri"; import { JumpManager } from "../activation/JumpManager"; import { NextEditWindowManager } from "../activation/NextEditWindowManager"; +import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService"; @@ -398,14 +399,27 @@ export class ContinueCompletionProvider (autocompleteCompletionItem as any).completeBracketPairs = true; + const editor = vscode.window.activeTextEditor; + if (!editor) { + return undefined; + } + + const currCursorPos = editor.selection.active; + if (this.isNextEditActive) { + console.log(this.nextEditProvider.getChain().length); + if (!this.nextEditProvider.isStartOfChain()) { const jumpPosition = new vscode.Position( (outcome as NextEditOutcome).editableRegionStartLine, 0, ); - await this.jumpManager.suggestJump(jumpPosition); + await this.jumpManager.suggestJump( + currCursorPos, + jumpPosition, + outcome.completion, + ); // If a jump was just suggested, don't show ghost text yet. if (this.jumpManager.isJumpInProgress()) { @@ -413,6 +427,7 @@ export class ContinueCompletionProvider this.jumpManager.setCompletionAfterJump({ completionId: input.completionId, outcome: outcome as NextEditOutcome, + currentPosition: jumpPosition, }); return undefined; // Don't show anything yet! @@ -421,11 +436,6 @@ export class ContinueCompletionProvider return undefined; } - const editor = vscode.window.activeTextEditor; - if (!editor) { - return undefined; - } - // Check the diff between old and new editable region. const newEditRangeSlice = completionText; @@ -438,7 +448,6 @@ export class ContinueCompletionProvider } // Get the contents of the old (current) editable region. - const currCursorPos = editor.selection.active; const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0, @@ -468,6 +477,21 @@ export class ContinueCompletionProvider currCursorPos, ); if (isFim) { + if (!fimText) { + console.log("deleteChain from completionProvider.ts: !fimText"); + this.nextEditProvider.deleteChain(); + return undefined; + } + + // const completionId = input.completionId; + + // Track this ghost text for acceptance detection. + GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance( + document, + fimText, + new vscode.Position(currCursorPos.line, currCursorPos.character), + ); + const nextEditCompletionItem = new vscode.InlineCompletionItem( fimText, new vscode.Range( @@ -485,6 +509,12 @@ export class ContinueCompletionProvider // Else, render a next edit window. const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + if (diffLines.length === 0) { + console.log( + "deleteChain from completionProvider.ts: diffLines.length === 0", + ); + NextEditProvider.getInstance().deleteChain(); + } if (NextEditWindowManager.isInstantiated()) { NextEditWindowManager.getInstance().updateCurrentCompletionId( From 0b4bd55da32227ac09b8ad5a237e81773552cfec Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:09:34 -0700 Subject: [PATCH 41/88] feat: create a ghost text acceptance tracker to quickly check if a completion has been accepted --- .../GhostTextAcceptanceTracker.ts | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts new file mode 100644 index 000000000..610a3c7fe --- /dev/null +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -0,0 +1,188 @@ +// export class CompletionAcceptanceTracker { +// private static instance: CompletionAcceptanceTracker; +// private acceptedCompletionIds: Set = new Set(); + +// static getInstance(): CompletionAcceptanceTracker { +// if (!CompletionAcceptanceTracker.instance) { +// CompletionAcceptanceTracker.instance = new CompletionAcceptanceTracker(); +// } +// return CompletionAcceptanceTracker.instance; +// } + +// markGhostTextAccepted(completionId: string) { +// this.acceptedCompletionIds.add(completionId); + +// // Keep a reasonable history size +// if (this.acceptedCompletionIds.size > 1) { +// // Remove the oldest item (using the fact that Sets maintain insertion order) +// const oldestId = this.acceptedCompletionIds.values().next().value; +// if (oldestId) { +// this.acceptedCompletionIds.delete(oldestId); +// } +// } +// } + +// wasCompletionAccepted(completionId: string): boolean { +// return this.acceptedCompletionIds.has(completionId); +// } + +// // Add a method to check if the most recent completion was accepted +// wasRecentCompletionAccepted(): boolean { +// return this.acceptedCompletionIds.size > 0; +// } +// } +// In completionAcceptanceTracker.ts +// export class CompletionAcceptanceTracker { +// private static instance: CompletionAcceptanceTracker; +// private acceptedCompletionIds: Set = new Set(); +// private currentCompletionId: string | null = null; + +// static getInstance(): CompletionAcceptanceTracker { +// if (!CompletionAcceptanceTracker.instance) { +// CompletionAcceptanceTracker.instance = new CompletionAcceptanceTracker(); +// } +// return CompletionAcceptanceTracker.instance; +// } + +// setCurrentCompletionId(completionId: string) { +// this.currentCompletionId = completionId; +// } + +// markGhostTextAccepted(completionId: string) { +// console.log("mark"); +// this.acceptedCompletionIds.add(completionId); + +// // Keep a reasonable history size +// if (this.acceptedCompletionIds.size > 1) { +// // Remove the oldest item (using the fact that Sets maintain insertion order) +// const oldestId = this.acceptedCompletionIds.values().next().value; +// if (oldestId) { +// this.acceptedCompletionIds.delete(oldestId); +// } +// } +// } + +// wasCompletionAccepted(completionId: string): boolean { +// return this.acceptedCompletionIds.has(completionId); +// } + +// isCurrentCompletionAccepted(): boolean { +// return ( +// this.currentCompletionId !== null && +// this.acceptedCompletionIds.has(this.currentCompletionId) +// ); +// } + +// clearCurrentCompletionId() { +// this.currentCompletionId = null; +// } +// } +// New file: extensions/vscode/src/activation/GhostTextAcceptanceTracker.ts +import * as vscode from "vscode"; + +export interface ExpectedGhostTextAcceptance { + documentUri: string; + documentVersion: number; + text: string; + startLine: number; + startCharacter: number; + endLine: number; + endCharacter: number; +} + +export class GhostTextAcceptanceTracker { + private static instance: GhostTextAcceptanceTracker | undefined; + private expectedAcceptance: ExpectedGhostTextAcceptance | null = null; + + private constructor() {} + + public static getInstance(): GhostTextAcceptanceTracker { + if (!GhostTextAcceptanceTracker.instance) { + GhostTextAcceptanceTracker.instance = new GhostTextAcceptanceTracker(); + } + return GhostTextAcceptanceTracker.instance; + } + + public static clearInstance() { + GhostTextAcceptanceTracker.instance = undefined; + } + + public setExpectedGhostTextAcceptance( + document: vscode.TextDocument, + text: string, + startPosition: vscode.Position, + ) { + // Calculate end position + const lines = text.split("\n"); + let endLine: number; + let endCharacter: number; + + if (lines.length > 1) { + endLine = startPosition.line + lines.length - 1; + endCharacter = lines[lines.length - 1].length; + } else { + endLine = startPosition.line; + endCharacter = startPosition.character + text.length; + } + + this.expectedAcceptance = { + documentUri: document.uri.toString(), + documentVersion: document.version, + text, + startLine: startPosition.line, + startCharacter: startPosition.character, + endLine, + endCharacter, + }; + } + + public checkGhostTextWasAccepted( + document: vscode.TextDocument, + newPosition: vscode.Position, + ): boolean { + if (!this.expectedAcceptance) return false; + + // Check document match + if (this.expectedAcceptance.documentUri !== document.uri.toString()) { + return false; + } + + // Check document version (must be newer) + if (document.version <= this.expectedAcceptance.documentVersion) { + return false; + } + + // Check if cursor is at expected end position + const expectedEndPos = new vscode.Position( + this.expectedAcceptance.endLine, + this.expectedAcceptance.endCharacter, + ); + + if (newPosition.isEqual(expectedEndPos)) { + // The cursor is where we'd expect after accepting the ghost text + + // Verify text was inserted (optional additional check) + const startPos = new vscode.Position( + this.expectedAcceptance.startLine, + this.expectedAcceptance.startCharacter, + ); + const expectedText = this.expectedAcceptance.text; + + try { + const actualRange = new vscode.Range(startPos, expectedEndPos); + + const actualText = document.getText(actualRange); + + if (actualText === expectedText) { + // Clear the expectation + this.expectedAcceptance = null; + return true; + } + } catch (error) { + // Range might be invalid, just fall through + } + } + + return false; + } +} From 3d08b80666e61f4ee1ab00eba1d3f24d85ee5279 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 19:10:40 -0700 Subject: [PATCH 42/88] feat: clear chain of edits in cursor movement, but not when part of next edit or jump --- .../vscode/src/extension/VsCodeExtension.ts | 46 +++++++++++++++++-- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index bf703606f..3efbd6bf4 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -43,13 +43,14 @@ import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider import { VsCodeMessenger } from "./VsCodeMessenger"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { JumpManager } from "../activation/JumpManager"; import setupNextEditWindowManager, { NextEditWindowManager, } from "../activation/NextEditWindowManager"; +import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker"; import { getDefinitionsFromLsp } from "../autocomplete/lsp"; import { handleTextDocumentChange } from "../util/editLoggingUtils"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { JumpManager } from "../activation/JumpManager"; export class VsCodeExtension { // Currently some of these are public so they can be used in testing (test/test-suites) @@ -174,12 +175,14 @@ export class VsCodeExtension { await NextEditWindowManager.freeTabAndEsc(); JumpManager.getInstance(); + GhostTextAcceptanceTracker.getInstance(); } else { NextEditWindowManager.clearInstance(); this.deactivateNextEdit(); await NextEditWindowManager.freeTabAndEsc(); JumpManager.clearInstance(); + GhostTextAcceptanceTracker.clearInstance(); } if (configLoadInterrupted) { @@ -378,13 +381,48 @@ export class VsCodeExtension { // Listen for editor changes to clean up decorations when editor closes. vscode.window.onDidChangeVisibleTextEditors(async () => { // If our active editor is no longer visible, clear decorations. - NextEditProvider.currentEditChainId = null; + console.log( + "deleteChain from VsCodeExtension.ts: onDidChangeVisibleTextEditors", + ); + NextEditProvider.getInstance().deleteChain(); }); // Listen for selection changes to hide tooltip when cursor moves. vscode.window.onDidChangeTextEditorSelection(async (e) => { - // If the selection changed in our active editor, hide the tooltip. - NextEditProvider.currentEditChainId = null; + console.log("move detected"); + // Don't delete the chain if: + + // 1. A next edit window was just accepted. + if ( + NextEditWindowManager.isInstantiated() && + NextEditWindowManager.getInstance().hasAccepted() + ) { + return; + } + + // 2. A jump is in progress. + if (JumpManager.getInstance().isJumpInProgress()) { + return; + } + + // 3. A ghost text was just accepted. + // Check if this selection change matches our expected ghost text acceptance. + const wasGhostTextAccepted = + GhostTextAcceptanceTracker.getInstance().checkGhostTextWasAccepted( + e.textEditor.document, + e.selections[0].active, + ); + + if (wasGhostTextAccepted) { + // Ghost text was accepted - don't delete the chain. + return; + } + + // Otherwise, delete the chain (for rejection or unrelated movement). + console.log( + "deleteChain from VsCodeExtension.ts: onDidChangeTextEditorSelection", + ); + NextEditProvider.getInstance().deleteChain(); }); // Refresh index when branch is changed From a08b4ae3114ff18f65996b143607bd50f660472d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 18 Jul 2025 20:59:04 -0700 Subject: [PATCH 43/88] chore: test around with rerank --- core/nextEdit/NextEditEditableRegionCarver.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/NextEditEditableRegionCarver.ts b/core/nextEdit/NextEditEditableRegionCarver.ts index 69a6708e7..d6c831923 100644 --- a/core/nextEdit/NextEditEditableRegionCarver.ts +++ b/core/nextEdit/NextEditEditableRegionCarver.ts @@ -96,7 +96,11 @@ async function rerankJump(ctx: { (a, b) => scores[chunks.indexOf(b)] - scores[chunks.indexOf(a)], ); - const mostRelevantChunk = chunks[0]; + // const mostRelevantChunk = chunks[0]; + // Get the third most relevant chunk if there are enough chunks, + // otherwise fallback to second or first. + const chunkIndex = Math.min(2, chunks.length - 1); + const mostRelevantChunk = chunks[chunkIndex]; // Return the range of the most relevant chunk. // NOTE: It might be better to return a list of chunks, From c3240f898dfcc92389d873348f2704398797aec0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 21 Jul 2025 15:03:23 -0700 Subject: [PATCH 44/88] fix: use relative cursor position instead of absolute --- core/nextEdit/diff/diff.ts | 17 +++++--- core/nextEdit/diff/diff.vitest.ts | 40 +++++++++++++++++++ .../src/autocomplete/completionProvider.ts | 10 ++++- extensions/vscode/src/commands.ts | 12 ++++-- 4 files changed, 69 insertions(+), 10 deletions(-) diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index 91d2eae41..fdcb78fb4 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -172,12 +172,19 @@ export function checkFim( // Convert cursor position to an offset in the string. // For simplicity, we need to calculate the cursor's position in the string. // This requires knowledge of line endings in the oldEditRange. - const lines = oldEditRange.substring(0, prefixLength).split("\n"); + // const lines = oldEditRange.substring(0, prefixLength).split("\n"); + // const lines = oldEditRange.split("\n"); + // const cursorOffset = + // lines.length > 1 + // ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) + + // cursorPosition.character + // : cursorPosition.character; + const oldEditLines = oldEditRange.split("\n"); const cursorOffset = - lines.length > 1 - ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) + - cursorPosition.character - : cursorPosition.character; + oldEditLines + .slice(0, cursorPosition.line) + .reduce((sum, line) => sum + line.length + 1, 0) + + cursorPosition.character; // Check if the cursor is positioned between the prefix and suffix. const cursorBetweenPrefixAndSuffix = diff --git a/core/nextEdit/diff/diff.vitest.ts b/core/nextEdit/diff/diff.vitest.ts index fa161d49c..706fed14c 100644 --- a/core/nextEdit/diff/diff.vitest.ts +++ b/core/nextEdit/diff/diff.vitest.ts @@ -79,6 +79,46 @@ describe("checkFim", () => { "const data = fetchData();\n const result = processData(data);", }, }, + { + name: "interesting case", + oldEditRange: [" }", "}", ""].join("\n"), + newEditRange: [" }", "}", "", "module.exports = Calculator;"].join("\n"), + cursorPosition: { line: 0, character: 0 }, + expected: { + isFim: false, + fimText: null, + }, + }, + { + name: "calculator.js divide", + oldEditRange: [ + " ", + " if (number === 0) {", + ' throw new Error("Cannot divide by zero");', + " }", + " this.result /= number;", + " return this;", + ].join("\n"), + newEditRange: [ + " if (typeof number !== 'number') {", + ' throw new Error("Invalid input: must be a number");', + " }", + " if (number === 0) {", + ' throw new Error("Cannot divide by zero");', + " }", + " this.result /= number;", + " return this;", + ].join("\n"), + cursorPosition: { line: 0, character: 4 }, + expected: { + isFim: true, + fimText: [ + "if (typeof number !== 'number') {", + ' throw new Error("Invalid input: must be a number");', + " }", + ].join("\n"), + }, + }, ]; testCases.forEach( diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index eae812873..862ea83d7 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -470,12 +470,19 @@ export class ContinueCompletionProvider return undefined; } + // Create a cursor position relative to the edit range slice. + const relativeCursorPos = { + line: currCursorPos.line - editableRegionStartLine, + character: currCursorPos.character, + }; + // If the diff is a FIM, render a ghost text. const { isFim, fimText } = checkFim( oldEditRangeSlice, newEditRangeSlice, - currCursorPos, + relativeCursorPos, ); + if (isFim) { if (!fimText) { console.log("deleteChain from completionProvider.ts: !fimText"); @@ -504,6 +511,7 @@ export class ContinueCompletionProvider arguments: [input.completionId, this.nextEditLoggingService], // TODO: this may have to be this.completionProvider. }, ); + console.log(nextEditCompletionItem); return [nextEditCompletionItem]; } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 693fbd9aa..25f5f0487 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -820,7 +820,7 @@ const getCommandsMap: ( // NOTE: This could use some cleanup or abstraction. // The logic is largely similar to that of completionProvider.ts // but we don't have access to the class. - + console.log("continue.showNextEditAfterJump"); const { completionId, outcome, currentPosition } = data; const editor = vscode.window.activeTextEditor; @@ -863,11 +863,15 @@ const getCommandsMap: ( return; } - // Check if this is a simple "fill in middle" (FIM) type edit. + // Create a cursor position relative to the edit range slice + const relativeCursorPos = { + line: currentPosition.line - editableRegionStartLine, + character: currentPosition.character, + }; const { isFim, fimText } = checkFim( oldEditRangeSlice, newEditRangeSlice, - currentPosition, + relativeCursorPos, ); if (isFim) { @@ -898,7 +902,7 @@ const getCommandsMap: ( // Show the ghost text using VS Code's inline completion API. // We need to trigger this manually since we're not in the completion provider. await vscode.commands.executeCommand( - "editor.action.inlineCompletions.showNext", + "editor.action.inlineSuggest.trigger", { completions: [nextEditCompletionItem], position: currentPosition, From 281a79a1fc8a907ffb30037984d9a55a8f2df462 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 21 Jul 2025 15:03:37 -0700 Subject: [PATCH 45/88] chore: remove print --- extensions/vscode/src/commands.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 25f5f0487..70a602a0f 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -820,7 +820,7 @@ const getCommandsMap: ( // NOTE: This could use some cleanup or abstraction. // The logic is largely similar to that of completionProvider.ts // but we don't have access to the class. - console.log("continue.showNextEditAfterJump"); + const { completionId, outcome, currentPosition } = data; const editor = vscode.window.activeTextEditor; From f9c4baa91f900bc96a36e0027afefc84fd5bae70 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 21 Jul 2025 16:07:30 -0700 Subject: [PATCH 46/88] refactor: rename file and update imports --- ...bleRegionCarver.ts => NextEditEditableRegionCalculator.ts} | 3 +++ core/nextEdit/NextEditPrefetchQueue.ts | 2 +- core/nextEdit/NextEditProvider.ts | 2 +- core/nextEdit/templating/NextEditPromptEngine.ts | 2 +- extensions/vscode/src/activation/JumpManager.ts | 4 ++++ 5 files changed, 10 insertions(+), 3 deletions(-) rename core/nextEdit/{NextEditEditableRegionCarver.ts => NextEditEditableRegionCalculator.ts} (98%) diff --git a/core/nextEdit/NextEditEditableRegionCarver.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts similarity index 98% rename from core/nextEdit/NextEditEditableRegionCarver.ts rename to core/nextEdit/NextEditEditableRegionCalculator.ts index d6c831923..18aa52c0e 100644 --- a/core/nextEdit/NextEditEditableRegionCarver.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -99,6 +99,9 @@ async function rerankJump(ctx: { // const mostRelevantChunk = chunks[0]; // Get the third most relevant chunk if there are enough chunks, // otherwise fallback to second or first. + // The most relevant chunk seems to be the one that + // is similar enough lexically, + // but different enough to still justify making an edit. const chunkIndex = Math.min(2, chunks.length - 1); const mostRelevantChunk = chunks[chunkIndex]; diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 99fff2b35..43b8697e4 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -3,7 +3,7 @@ import { HelperVars } from "../autocomplete/util/HelperVars"; import { findChangedLineRanges, myersDiff } from "../diff/myers"; import { PrefetchQueue } from "../util/PrefetchQueue"; import { applyCompletionToFile } from "./diff/diff"; -import { EditableRegionStrategy } from "./NextEditEditableRegionCarver"; +import { EditableRegionStrategy } from "./NextEditEditableRegionCalculator"; import { NextEditProvider } from "./NextEditProvider"; import { NextEditOutcome } from "./types"; diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 29a91c62d..a1163aaf9 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -33,7 +33,7 @@ import { calculateFinalCursorPosition, getOffsetPositionAtLastNewLine, } from "./diff/diff.js"; -import { EditableRegionStrategy } from "./NextEditEditableRegionCarver.js"; +import { EditableRegionStrategy } from "./NextEditEditableRegionCalculator.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; import { NextEditPrefetchQueue } from "./NextEditPrefetchQueue.js"; import { diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 5efb341ce..98ae5db3e 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -13,7 +13,7 @@ import { createDiff, DiffFormatType } from "../context/diffFormatting"; import { EditableRegionStrategy, getNextEditableRegion, -} from "../NextEditEditableRegionCarver"; +} from "../NextEditEditableRegionCalculator"; import { NextEditOutcome, NextEditTemplate, diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 1d180c072..9ed09851c 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -314,5 +314,9 @@ export class JumpManager { setCompletionAfterJump(completionData: CompletionDataForAfterJump): void { this._completionAfterJump = completionData; + console.log( + "setCompletionAfterJump: saved", + JSON.stringify(completionData, null, 2), + ); } } From 8fa0bfaea63761bab4eb9c999f07b6d10b6e8221 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 21 Jul 2025 16:08:38 -0700 Subject: [PATCH 47/88] refactor: remove unused methods --- .../NextEditEditableRegionCalculator.ts | 206 ------------------ 1 file changed, 206 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 18aa52c0e..b5d9fa634 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -1,11 +1,8 @@ import { Chunk, ILLM, RangeInFile } from ".."; -import { cosineSimilarity } from "../context/retrieval/pipelines/NextEditRetrievalPipeline"; export enum EditableRegionStrategy { Naive = "naive", Rerank = "rerank", - Model = "model", - Sliding = "sliding", } export async function getNextEditableRegion( @@ -17,10 +14,6 @@ export async function getNextEditableRegion( return naiveJump(ctx); case EditableRegionStrategy.Rerank: return await rerankJump(ctx); - case EditableRegionStrategy.Model: - return modelJump(ctx); - case EditableRegionStrategy.Sliding: - return slidingJump(ctx); default: return null; } @@ -124,202 +117,3 @@ async function rerankJump(ctx: { return null; } } - -// A naive jump uses the next edit model to predict edits for the entire file. -// Then it calculates the diff between that and the original to get the jump location. -function modelJump(ctx: any): RangeInFile | null { - try { - const { fileContent, predictedContent, filepath } = ctx; - - if (!fileContent || !predictedContent || !filepath) { - console.warn("Missing required context for model jump"); - return null; - } - - const originalLines = fileContent.split("\n"); - const predictedLines = predictedContent.split("\n"); - - // Find the first line that differs. - for ( - let i = 0; - i < Math.min(originalLines.length, predictedLines.length); - i++ - ) { - if (originalLines[i] !== predictedLines[i]) { - // Calculate the end of the differing section (find where they align again). - let endLine = i; - while ( - endLine < Math.min(originalLines.length, predictedLines.length) && - originalLines[endLine] !== predictedLines[endLine] - ) { - endLine++; - } - - // Return a range that covers the differences. - return { - filepath, - range: { - start: { line: i, character: 0 }, - end: { - line: Math.min(endLine, originalLines.length - 1), - character: - originalLines[Math.min(endLine, originalLines.length - 1)] - .length, - }, - }, - }; - } - } - - // If no difference found but files have different lengths, - if (originalLines.length !== predictedLines.length) { - const diffStartLine = Math.min( - originalLines.length, - predictedLines.length, - ); - return { - filepath, - range: { - start: { line: diffStartLine, character: 0 }, - end: { - line: originalLines.length - 1, - character: originalLines.at(-1).length, - }, - }, - }; - } - - // No differences found. - return null; - } catch (error) { - console.error("Error in model jump:", error); - return null; - } -} - -// A sliding jump uses a sliding window to split the current file into zones. -// Then each zone is ranked on how similar it is to the model's next edit prediction. -function slidingJump(ctx: any): RangeInFile | null { - try { - const { fileContent, predictedContent, filepath, windowSize = 5 } = ctx; - - if (!fileContent || !predictedContent || !filepath) { - console.warn("Missing required context for sliding jump"); - return null; - } - - const originalLines = fileContent.split("\n"); - const predictedLines = predictedContent.split("\n"); - - // Create sliding windows/zones from the file. - const zones: Array<{ - startLine: number; - endLine: number; - similarity: number; - }> = []; - - for ( - let i = 0; - i <= originalLines.length - windowSize; - i += Math.floor(windowSize / 2) - ) { - const originalWindow = originalLines.slice(i, i + windowSize).join("\n"); - - // For each zone, find the most similar section in the predicted content. - let highestSimilarity = 0; - - for ( - let j = 0; - j <= predictedLines.length - windowSize; - j += Math.floor(windowSize / 2) - ) { - const predictedWindow = predictedLines - .slice(j, j + windowSize) - .join("\n"); - - // Convert to simple vector representation for similarity calculation. - const originalVector = createSimpleVector(originalWindow); - const predictedVector = createSimpleVector(predictedWindow); - - const similarity = cosineSimilarity(originalVector, predictedVector); - - if (similarity > highestSimilarity) { - highestSimilarity = similarity; - } - } - - zones.push({ - startLine: i, - endLine: Math.min(i + windowSize - 1, originalLines.length - 1), - similarity: highestSimilarity, - }); - } - - // Find the zone with the highest similarity score. - const mostSimilarZone = zones.reduce((prev, current) => - prev.similarity > current.similarity ? prev : current, - ); - - // Return the range of the most similar zone. - return { - filepath, - range: { - start: { line: mostSimilarZone.startLine, character: 0 }, - end: { - line: mostSimilarZone.endLine, - character: originalLines[mostSimilarZone.endLine].length, - }, - }, - }; - } catch (error) { - console.error("Error in sliding jump:", error); - return null; - } -} - -// Helper method to create a simple vector representation of a text string. -function createSimpleVector(text: string): number[] { - const tokenFrequency: Record = {}; - - // Split text into tokens. - const tokens = text - .toLowerCase() - .split(/[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g) - .map((s) => s.trim()) - .filter((s) => s.length > 0); - - // Count frequency of each token. - for (const token of tokens) { - tokenFrequency[token] = (tokenFrequency[token] || 0) + 1; - } - - // Create a fixed-dimension vector (using common programming keywords as dimensions). - const dimensions = [ - "function", - "return", - "if", - "else", - "for", - "while", - "const", - "let", - "var", - "class", - "import", - "export", - "interface", - "type", - "new", - "this", - "try", - "catch", - "async", - "await", - "true", - "false", - "null", - "undefined", - ]; - - return dimensions.map((dim) => tokenFrequency[dim] || 0); -} From 3651d626a8e7a6f63dc6ddfe971753408ba01d1a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 21 Jul 2025 16:12:43 -0700 Subject: [PATCH 48/88] fix: prettier --- core/util/PrefetchQueue.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/core/util/PrefetchQueue.ts b/core/util/PrefetchQueue.ts index 360c6bf82..91a240dcc 100644 --- a/core/util/PrefetchQueue.ts +++ b/core/util/PrefetchQueue.ts @@ -1,5 +1,3 @@ -import { NextEditProvider } from "../nextEdit/NextEditProvider"; - export class PrefetchQueue { protected promiseQueue: Promise[] = []; protected resourceQueue: R[]; @@ -86,4 +84,3 @@ export class PrefetchQueue { return this.resourceQueue.length; } } - From 153e97458ea7dd21f696a414edbe360a8acd8eea Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 21 Jul 2025 16:28:18 -0700 Subject: [PATCH 49/88] fix: undefined field error --- core/nextEdit/NextEditPrefetchQueue.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 43b8697e4..54a43bc29 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -4,7 +4,6 @@ import { findChangedLineRanges, myersDiff } from "../diff/myers"; import { PrefetchQueue } from "../util/PrefetchQueue"; import { applyCompletionToFile } from "./diff/diff"; import { EditableRegionStrategy } from "./NextEditEditableRegionCalculator"; -import { NextEditProvider } from "./NextEditProvider"; import { NextEditOutcome } from "./types"; export class NextEditPrefetchQueue extends PrefetchQueue< @@ -100,7 +99,7 @@ export class NextEditPrefetchQueue extends PrefetchQueue< const currentPromise = this.promiseQueue.shift()!; if (this.promiseQueue.length === 0) { - NextEditProvider.currentEditChainId = null; + // NextEditProvider.currentEditChainId = null; } return await currentPromise; @@ -127,7 +126,7 @@ export class NextEditPrefetchQueue extends PrefetchQueue< this.promiseQueue.push(nextPromise); } else if (this.promiseQueue.length === 0) { // No more items in the queue and no more resources - NextEditProvider.currentEditChainId = null; + // NextEditProvider.currentEditChainId = null; } // console.log("currentData:", currentData); From 4af947dd250bb229ed0f87fe237c63a4860c4815 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 21 Jul 2025 16:33:08 -0700 Subject: [PATCH 50/88] refactor: update package imports --- extensions/vscode/src/autocomplete/completionProvider.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 862ea83d7..1ea7fa29c 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -24,7 +24,7 @@ import { checkFim } from "core/nextEdit/diff/diff"; import { EditableRegionStrategy, getNextEditableRegion, -} from "core/nextEdit/NextEditEditableRegionCarver"; +} from "core/nextEdit/NextEditEditableRegionCalculator"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { NextEditOutcome } from "core/nextEdit/types"; From 98e41cdccc302cf5fa419b62d50fbedb012d71d1 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 22 Jul 2025 13:12:11 -0700 Subject: [PATCH 51/88] feat: add getDocumentSymbols LSP method --- core/config/types.ts | 1 + core/index.d.ts | 54 +++++++++++ core/protocol/ide.ts | 2 + core/protocol/messenger/messageIde.ts | 7 ++ core/util/filesystem.ts | 5 + .../continue/IntelliJIde.kt | 4 + .../continueintellijextension/types.kt | 8 ++ extensions/vscode/src/VsCodeIde.ts | 14 ++- extensions/vscode/src/autocomplete/lsp.ts | 95 ++++++++++++++++++- .../vscode/src/extension/VsCodeMessenger.ts | 4 + 10 files changed, 192 insertions(+), 2 deletions(-) diff --git a/core/config/types.ts b/core/config/types.ts index 25ae3247a..9fd2720f1 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -746,6 +746,7 @@ declare global { // LSP gotoDefinition(location: Location): Promise; getReferences(location: Location): Promise; + getDocumentSymbols(textDocumentIdentifier: string): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (filepath: string) => void): void; diff --git a/core/index.d.ts b/core/index.d.ts index 99f1cd6cd..f026c17c2 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -872,6 +872,7 @@ export interface IDE { // LSP gotoDefinition(location: Location): Promise; getReferences(location: Location): Promise; + getDocumentSymbols(textDocumentIdentifier: string): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; @@ -1722,3 +1723,56 @@ export interface CompiledMessagesResult { export interface MessageOption { precompiled: boolean; } + +/* LSP-specific interfaces. */ + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolKind. +// We shift this one index down to match vscode.SymbolKind. +export enum SymbolKind { + File = 0, + Module = 1, + Namespace = 2, + Package = 3, + Class = 4, + Method = 5, + Property = 6, + Field = 7, + Constructor = 8, + Enum = 9, + Interface = 10, + Function = 11, + Variable = 12, + Constant = 13, + String = 14, + Number = 15, + Boolean = 16, + Array = 17, + Object = 18, + Key = 19, + Null = 20, + EnumMember = 21, + Struct = 22, + Event = 23, + Operator = 24, + TypeParameter = 25, +} + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolTag. +export namespace SymbolTag { + export const Deprecated: 1 = 1; +} + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolTag. +export type SymbolTag = 1; + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#documentSymbol. +export interface DocumentSymbol { + name: string; + detail?: string; + kind: SymbolKind; + tags?: SymbolTag[]; + deprecated?: boolean; + range: Range; + selectionRange: Range; + children?: DocumentSymbol[]; +} diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index ed108ba9b..49030e8a5 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -1,5 +1,6 @@ import type { ContinueRcJson, + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -83,6 +84,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { gotoDefinition: [{ location: Location }, RangeInFile[]]; getReferences: [{ location: Location }, RangeInFile[]]; + getDocumentSymbols: [{ textDocumentIdentifier: string }, DocumentSymbol[]]; getControlPlaneSessionInfo: [ { silent: boolean; useOnboarding: boolean }, diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index de1ed3ecc..bb72b8d63 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -3,6 +3,7 @@ import { ToIdeFromWebviewOrCoreProtocol } from "../ide"; import type { ContinueRcJson, + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -49,6 +50,12 @@ export class MessageIde implements IDE { return this.request("getReferences", { location }); } + async getDocumentSymbols( + textDocumentIdentifier: string, + ): Promise { + return this.request("getDocumentSymbols", { textDocumentIdentifier }); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 7a9a08f8c..b0fa43f78 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -3,6 +3,7 @@ import * as fs from "node:fs"; import { fileURLToPath } from "node:url"; import { ContinueRcJson, + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -48,6 +49,10 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } + getDocumentSymbols(fileUri: string): Promise { + return Promise.resolve([]); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 58b8de1a9..5a3778d30 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -598,6 +598,10 @@ class IntelliJIDE( throw NotImplementedError("getReferences not implemented yet") } + override suspend fun getDocumentSymbols(textDocumentIdentifier: String): List { + throw NotImplementedError("getDocumentSymbols not implemented yet") + } + override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) { throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 6d16351cf..3566bf345 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -64,6 +64,13 @@ data class RangeInFileWithContents( val contents: String ) +data class DocumentSymbol( + val name: String, + val kind: String, + val range: Range, + val selectionRange: Range +) + data class ControlPlaneSessionInfo( val accessToken: String, val account: Account @@ -193,6 +200,7 @@ interface IDE { // LSP suspend fun gotoDefinition(location: Location): List suspend fun getReferences(location: Location): List + suspend fun getDocumentSymbols(textDocumentIdentifier: String): List // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index b6f1cea7d..43be229e3 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -6,7 +6,7 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import { executeGotoProvider } from "./autocomplete/lsp"; +import { executeGotoProvider, executeSymbolProvider } from "./autocomplete/lsp"; import { Repository } from "./otherExtensions/git"; import { SecretStorage } from "./stubs/SecretStorage"; import { VsCodeIdeUtils } from "./util/ideUtils"; @@ -15,6 +15,7 @@ import { VsCodeWebviewProtocol } from "./webviewProtocol"; import type { ContinueRcJson, + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -98,6 +99,17 @@ class VsCodeIde implements IDE { return result; } + async getDocumentSymbols( + textDocumentIdentifier: string, // uri + ): Promise { + const result = await executeSymbolProvider({ + uri: vscode.Uri.parse(textDocumentIdentifier), + name: "vscode.executeDocumentSymbolProvider" + }); + + return result; + } + onDidChangeActiveTextEditor(callback: (uri: string) => void): void { vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor) { diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index a6900291a..fbf69932d 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -13,7 +13,13 @@ import { intersection } from "core/util/ranges"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core"; +import type { + DocumentSymbol, + IDE, + Range, + RangeInFile, + RangeInFileWithContents, +} from "core"; import type Parser from "web-tree-sitter"; type GotoProviderName = @@ -382,3 +388,90 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( return []; } }; + +type SymbolProviderName = "vscode.executeDocumentSymbolProvider"; + +interface SymbolInput { + uri: vscode.Uri; + name: SymbolProviderName; +} + +function symbolInputKey(input: SymbolInput) { + return `${input.name}${input.uri.toString()}`; +} + +const MAX_SYMBOL_CACHE_SIZE = 100; +const symbolCache = new Map(); + +export async function executeSymbolProvider( + input: SymbolInput, +): Promise { + const cacheKey = symbolInputKey(input); + const cached = symbolCache.get(cacheKey); + if (cached) { + return cached; + } + + try { + const symbols = (await vscode.commands.executeCommand( + input.name, + input.uri, + // )) as vscode.DocumentSymbol[] | vscode.SymbolInformation[]; + )) as vscode.DocumentSymbol[]; + + const results: DocumentSymbol[] = []; + + // Handle both possible return types from the symbol provider + if (symbols.length > 0) { + // if ("location" in symbols[0]) { + // // SymbolInformation type + // results.push( + // ...symbols.map((s: vscode.SymbolInformation) => ({ + // filepath: s.location.uri.toString(), + // range: s.location.range, + // })), + // ); + // } else { + // DocumentSymbol type - collect symbols recursively + function collectSymbols( + symbols: vscode.DocumentSymbol[], + uri: vscode.Uri, + ): DocumentSymbol[] { + const result: DocumentSymbol[] = []; + for (const symbol of symbols) { + result.push({ + name: symbol.name, + range: symbol.range, + selectionRange: symbol.selectionRange, + kind: symbol.kind, + }); + + if (symbol.children && symbol.children.length > 0) { + result.push(...collectSymbols(symbol.children, uri)); + } + } + return result; + } + + results.push( + ...collectSymbols(symbols as vscode.DocumentSymbol[], input.uri), + ); + // } + } + + // Add to cache + if (symbolCache.size >= MAX_SYMBOL_CACHE_SIZE) { + // Remove the oldest item from the cache + const oldestKey = symbolCache.keys().next().value; + if (oldestKey) { + symbolCache.delete(oldestKey); + } + } + symbolCache.set(cacheKey, results); + + return results; + } catch (e) { + console.warn(`Error executing ${input.name}:`, e); + return []; + } +} diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 7f9158da5..a114a542c 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -394,6 +394,10 @@ export class VsCodeMessenger { return await ide.getReferences(msg.data.location); }); + this.onWebviewOrCore("getDocumentSymbols", async (msg) => { + return await ide.getDocumentSymbols(msg.data.textDocumentIdentifier); + }); + this.onWebviewOrCore("getFileStats", async (msg) => { return await ide.getFileStats(msg.data.files); }); From b1946329aebcf7b322435b112db4b6a01ba3df30 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 22 Jul 2025 13:12:24 -0700 Subject: [PATCH 52/88] feat: save NextEditOutcome instead of string --- core/nextEdit/NextEditProvider.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index a1163aaf9..c84a76bba 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -70,7 +70,7 @@ export class NextEditProvider { private prefetchQueue: NextEditPrefetchQueue; // private refQueue: RangeInFile[] = []; private currentEditChainId: string | null = null; - private previousCompletions: string[] = []; + private previousCompletions: NextEditOutcome[] = []; private constructor( private readonly configHandler: ConfigHandler, @@ -322,7 +322,7 @@ export class NextEditProvider { return this.currentEditChainId !== null; } - public getPreviousCompletion(): string | null { + public getPreviousCompletion(): NextEditOutcome | null { return this.previousCompletions[0]; } @@ -481,7 +481,7 @@ export class NextEditProvider { ).replace(/\n$/, "") : ""; - this.previousCompletions.push(nextCompletion); + // this.previousCompletions.push(nextCompletion); const currCursorPos = helper.pos; const editableRegionStartLine = Math.max( @@ -530,6 +530,8 @@ export class NextEditProvider { ...helper.options, }; + this.previousCompletions.push(outcomeNext); + // When using the JetBrains extension, mark as displayed. // This helps us not need to make additional network calls just to mark as displayed. const ideType = (await this.ide.getIdeInfo()).ideType; From b4b126ca082d55ebc52f89e5e99585235ea16fbf Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 22 Jul 2025 13:12:37 -0700 Subject: [PATCH 53/88] chore: remove console.logs --- extensions/vscode/src/extension/VsCodeExtension.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 2cb2faeee..4983583ab 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -386,15 +386,15 @@ export class VsCodeExtension { // Listen for editor changes to clean up decorations when editor closes. vscode.window.onDidChangeVisibleTextEditors(async () => { // If our active editor is no longer visible, clear decorations. - console.log( - "deleteChain from VsCodeExtension.ts: onDidChangeVisibleTextEditors", - ); + // console.log( + // "deleteChain from VsCodeExtension.ts: onDidChangeVisibleTextEditors", + // ); NextEditProvider.getInstance().deleteChain(); }); // Listen for selection changes to hide tooltip when cursor moves. vscode.window.onDidChangeTextEditorSelection(async (e) => { - console.log("move detected"); + // console.log("move detected"); // Don't delete the chain if: // 1. A next edit window was just accepted. From 517837226fa78d3eb9f44280d247ca9b118727d2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 22 Jul 2025 13:13:06 -0700 Subject: [PATCH 54/88] feat: add a static-based jump method --- .../NextEditEditableRegionCalculator.ts | 428 +++++++++++++++++- .../src/autocomplete/completionProvider.ts | 42 +- 2 files changed, 465 insertions(+), 5 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index b5d9fa634..9d159f74b 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -1,8 +1,11 @@ -import { Chunk, ILLM, RangeInFile } from ".."; +import Parser from "web-tree-sitter"; +import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; +import { getAst } from "../autocomplete/util/ast"; export enum EditableRegionStrategy { Naive = "naive", Rerank = "rerank", + Static = "static", } export async function getNextEditableRegion( @@ -14,6 +17,8 @@ export async function getNextEditableRegion( return naiveJump(ctx); case EditableRegionStrategy.Rerank: return await rerankJump(ctx); + case EditableRegionStrategy.Static: + return await staticJump(ctx); default: return null; } @@ -117,3 +122,424 @@ async function rerankJump(ctx: { return null; } } + +// A static jump runs a lightweight static analysis on the file +// to jump to relevant locations. +async function staticJump(ctx: { + oldFileContent: string; + newFileContent: string; + completionRange: Range; + filepath: string; + ide: IDE; + reranker?: ILLM; + chunkSize?: number; +}): Promise { + try { + const { oldFileContent, newFileContent, completionRange, filepath, ide } = + ctx; + + if ( + !oldFileContent || + !newFileContent || + !completionRange || + !filepath || + !ide + ) { + console.warn( + "Missing required context for static jump:", + !oldFileContent, + !newFileContent, + !completionRange, + !filepath, + !ide, + ); + return null; + } + + // TODO: + // Parse the old file contents into an AST. + // Parse the new file contents into an AST. + // Compare the two trees and find which nodes have changed. + // Save the queue of changed nodes. The queue should contain the old node and the new node. Each of them can be null if the change is a deletion or insertion. + // Rank the queue by node depth (decreasing order because we want granular edits). + // Pop front until we find a queue item with an old node != null. + // Search the codebase for the old node's expression. For this, either use ide.getReferences(some_location), or other methods you see fit. If you can utilize the strategy pattern, even better. + // For now, filter out results from outside files. We only want to keep the results in the current file. + // Return the first result from this filtered list of results. + + // Parse the old file contents into an AST. + const oldAst = await getAst(filepath, oldFileContent); + if (!oldAst) return null; + + // Parse the new file contents into an AST. + const newAst = await getAst(filepath, newFileContent); + if (!newAst) return null; + + // Compare the two trees and find which nodes have changed. + const changedNodes = compareAsts(oldAst, newAst); + if (!changedNodes || changedNodes.length === 0) return null; + + // Save the queue of changed nodes. + // The queue should contain the old node and the new node. + // Each can be null if the change is a deletion or insertion. + // const nodeQueue = changedNodes.map((change) => ({ + // oldNode: change.oldNode, + // newNode: change.newNode, + // depth: change.depth, + // })); + + // Rank the queue by node depth. + // Decreasing order for granular edits. + // Increasing order for larger definition-based searches. + // Making it decreasing has issues when the deepest node is a string_fragment. + const nodeQueue = changedNodes.sort((a, b) => a.depth - b.depth); + console.log( + "nodeQueue:", + nodeQueue.map((node) => ({ + oldText: node.oldNode?.text || "", + newText: node.newNode?.text || "", + oldType: node.oldNode?.type || "", + newType: node.newNode?.type || "", + depth: node.depth, + })), + ); + + // Find the first item with a non-null old node. + let targetNode = null; + while (nodeQueue.length > 0 && !targetNode) { + const candidate = nodeQueue.shift(); + if ( + candidate && + candidate.oldNode && + candidate.oldNode.type !== "program" + ) { + targetNode = candidate.oldNode; + } + } + + if (!targetNode) return null; + + // Get the text representation of the old node's expression. + const nodeText = getNodeText(targetNode); + if (!nodeText || nodeText.trim() === "") return null; + + // Search for similar code in the file. + let references: RangeInFile[] = []; + + // Try to use IDE's reference finding capabilities if available. + try { + // Get the position of the target node in the old file. + const nodePosition = getNodePosition(targetNode); + if (nodePosition) { + // Use IDE to find references. + + // TODO: + // Get the list of document symbols using await ide.getDocumentSymbols. + // Each document symbol will be our query. + // Use the rerank model to rank the nodeText against the query. + // Get the highest scoring query and its location. + + // Get the list of document symbols using await ide.getDocumentSymbols. + // Filter out symbols that are directly inside the completion range. + const symbols = await ide.getDocumentSymbols(filepath); + + // Filter out symbols that are directly inside the completion range + const filteredSymbols = symbols.filter((symbol) => { + // Check if the symbol's range is outside of the completion range + return !doRangesOverlap(symbol.range, completionRange); + }); + + // Use the reranker to rank the filtered symbols against the node text. + if (!ctx.reranker) { + console.warn("No reranker available for static jump symbol ranking"); + return null; + } + + const symbolChunks: Chunk[] = filteredSymbols.map((symbol) => ({ + content: symbol.name, + startLine: symbol.range.start.line, + endLine: symbol.range.end.line, + digest: `symbol-${symbol.name}-${symbol.range.start.line}`, + filepath: filepath, + index: symbol.range.start.line, + })); + + if (symbolChunks.length === 0) { + console.warn("No symbols found for ranking"); + return null; + } + + const scores = await ctx.reranker.rerank(nodeText, symbolChunks); + symbolChunks.sort( + (a, b) => + scores[symbolChunks.indexOf(b)] - scores[symbolChunks.indexOf(a)], + ); + + const mostRelevantSymbol = symbolChunks[0]; + const originalSymbol = filteredSymbols.find( + (symbol) => + symbol.range.start.line === mostRelevantSymbol.startLine && + symbol.range.end.line === mostRelevantSymbol.endLine, + ); + + if (originalSymbol) { + references = [ + { + filepath, + range: originalSymbol.range, + }, + ]; + } + + // const foundReferences = await ide.getReferences({ + // filepath, + // position: nodePosition, + // }); + + // if (foundReferences && foundReferences.length > 0) { + // references = foundReferences; + // } + } + } catch (e) { + console.warn( + "Failed to use IDE references, falling back to text search:", + e, + ); + } + + // If IDE reference finding failed or returned no results, fall back to text search. + if (references.length === 0) { + references = findTextOccurrences(oldFileContent, nodeText).map( + (range) => ({ filepath, range }), + ); + } + + // Filter out results from outside the current file. + const currentFileReferences = references.filter( + (ref) => ref.filepath === filepath, + ); + + // Return the first reference if any found. + if (currentFileReferences.length > 0) { + return currentFileReferences[0]; + } + + return null; + } catch (error) { + console.error("Error in static jump:", error); + return null; + } +} + +// Helper function to compare ASTs and find changed nodes. +function compareAsts(oldAst: Parser.Tree, newAst: Parser.Tree) { + const changedNodes: { + oldNode: Parser.SyntaxNode | null; + newNode: Parser.SyntaxNode | null; + depth: number; + }[] = []; + + // This is a simplified implementation. + // In practice, you would traverse both ASTs in parallel + // and identify nodes that differ. + + function traverse( + oldNode: Parser.SyntaxNode | null, + newNode: Parser.SyntaxNode | null, + depth: number = 0, + ) { + if (!oldNode && !newNode) return; + + // If one node exists and the other doesn't, or they're different types. + if ( + (!oldNode && newNode) || + (oldNode && !newNode) || + oldNode?.type !== newNode?.type + ) { + changedNodes.push({ oldNode, newNode, depth }); + return; + } + + // Compare properties. + if (oldNode?.text !== newNode?.text) { + changedNodes.push({ oldNode, newNode, depth }); + } + + // Recursively compare children. + const oldChildCount = oldNode?.childCount || 0; + const newChildCount = newNode?.childCount || 0; + + const maxLength = Math.max(oldChildCount, newChildCount); + for (let i = 0; i < maxLength; i++) { + const oldChild = i < oldChildCount ? oldNode?.child(i) || null : null; + const newChild = i < newChildCount ? newNode?.child(i) || null : null; + traverse(oldChild, newChild, depth + 1); + } + } + + traverse(oldAst.rootNode, newAst.rootNode); + return changedNodes; +} + +// Helper function to get a node's text. +function getNodeText(node: Parser.SyntaxNode): string { + if (!node) return ""; + + return node.text; +} + +// Helper function to get a node's position. +function getNodePosition(node: Parser.SyntaxNode): Position | null { + if (!node) return null; + + // Tree-sitter nodes have startPosition property that contains row and column. + return { + line: node.startPosition.row, + character: node.startPosition.column, + }; +} + +// Helper function to find all occurrences of text in a string. +function findTextOccurrences(text: string, searchText: string): Range[] { + const results: Range[] = []; + const lines = text.split("\n"); + + for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { + const line = lines[lineIndex]; + let charIndex = 0; + + while (charIndex < line.length) { + const foundIndex = line.indexOf(searchText, charIndex); + if (foundIndex === -1) break; + + results.push({ + start: { line: lineIndex, character: foundIndex }, + end: { line: lineIndex, character: foundIndex + searchText.length }, + }); + + charIndex = foundIndex + 1; + } + } + + return results; +} + +// Helper function to check if a range is within another range. +function isRangeWithin(innerRange: Range, outerRange: Range): boolean { + // Check if the inner range's start position is after or equal to the outer range's start. + const startWithin = + innerRange.start.line > outerRange.start.line || + (innerRange.start.line === outerRange.start.line && + innerRange.start.character >= outerRange.start.character); + + // Check if the inner range's end position is before or equal to the outer range's end. + const endWithin = + innerRange.end.line < outerRange.end.line || + (innerRange.end.line === outerRange.end.line && + innerRange.end.character <= outerRange.end.character); + + return startWithin && endWithin; +} + +// Helper function to check if two ranges overlap. +function doRangesOverlap(range1: Range, range2: Range): boolean { + // Check if one range starts after the other ends + const range1StartsAfterRange2Ends = + range1.start.line > range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character > range2.end.character); + + const range2StartsAfterRange1Ends = + range2.start.line > range1.end.line || + (range2.start.line === range1.end.line && + range2.start.character > range1.end.character); + + // If either condition is true, the ranges don't overlap + return !(range1StartsAfterRange2Ends || range2StartsAfterRange1Ends); +} + +// Helper function to check if the upper part of range1 overlaps with range2. +function doesUpperPartOverlap(range1: Range, range2: Range): boolean { + // Check if range1 starts before range2 ends + const range1StartsBeforeRange2Ends = + range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character <= range2.end.character); + + // Check if range1 starts before range2 starts (meaning it's "upper" than range2) + const range1StartsBeforeRange2Starts = + range1.start.line < range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character < range2.start.character); + + // The upper part overlaps if range1 starts before range2 ends + // AND range1 starts before range2 starts + return range1StartsBeforeRange2Ends && range1StartsBeforeRange2Starts; +} + +// Helper function to check if the lower part of range1 overlaps with range2. +function doesLowerPartOverlap(range1: Range, range2: Range): boolean { + // Check if range1 starts inside range2 + const range1StartsInsideRange2 = + (range1.start.line > range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character >= range2.start.character)) && + (range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character < range2.end.character)); + + // Check if range1 ends after range2 ends + const range1EndsAfterRange2 = + range1.end.line > range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character > range2.end.character); + + // The lower part overlaps if range1 starts inside range2 + // AND range1 ends after range2 ends + return range1StartsInsideRange2 && range1EndsAfterRange2; +} + +// Helper function to check if a range overlaps with another range from either end +function doesRangePartiallyOverlap(range1: Range, range2: Range): boolean { + // Upper part overlap: range1 starts before range2 starts but ends inside range2 + const upperPartOverlap = + (range1.start.line < range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character < range2.start.character)) && + (range1.end.line > range2.start.line || + (range1.end.line === range2.start.line && + range1.end.character > range2.start.character)) && + (range1.end.line < range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character <= range2.end.character)); + + // Lower part overlap: range1 starts inside range2 but ends after range2 ends + const lowerPartOverlap = + (range1.start.line > range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character >= range2.start.character)) && + (range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character < range2.end.character)) && + (range1.end.line > range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character > range2.end.character)); + + return upperPartOverlap || lowerPartOverlap; +} + +// Utility function to print chunks. +function printChunks(chunks: Chunk[]) { + console.log( + "chunks:", + JSON.stringify( + chunks.map((chunk) => ({ + content: chunk.content, + startLine: chunk.startLine, + endLine: chunk.endLine, + })), + null, + 2, + ), + ); +} diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 1ea7fa29c..7d4a186d4 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -77,6 +77,8 @@ export class ContinueCompletionProvider public recentlyVisitedRanges: RecentlyVisitedRangesService; public recentlyEditedTracker: RecentlyEditedTracker; + private oldFileContent: string = ""; + private isNextEditActive: boolean = false; public activateNextEdit() { @@ -194,17 +196,47 @@ export class ContinueCompletionProvider if (this.nextEditProvider.chainExists()) { // If the user has accepted the previous completion, the chain of edits is alive. // Get the next editable region and set the pos to be within that range. + // const nextEditableRegion = await getNextEditableRegion( + // EditableRegionStrategy.Rerank, + // { + // fileContent: document.getText(), + // query: this.nextEditProvider.getPreviousCompletion(), // previous completion in the chain + // filepath: localPathOrUriToPath(document.uri.toString()), + // reranker: await this.getRerankModel(), + // chunkSize: 5, + // }, + // ); + const newFileContent = document.getText(); const nextEditableRegion = await getNextEditableRegion( - EditableRegionStrategy.Rerank, + EditableRegionStrategy.Static, { - fileContent: document.getText(), - query: this.nextEditProvider.getPreviousCompletion(), // previous completion in the chain + oldFileContent: this.oldFileContent, + newFileContent, + completionRange: { + start: { + line: + this.nextEditProvider.getPreviousCompletion() + ?.editableRegionStartLine ?? 0, + character: 0, + }, + end: { + line: + this.nextEditProvider.getPreviousCompletion() + ?.editableRegionEndLine ?? document.lineCount - 1, + character: 0, + }, + }, filepath: localPathOrUriToPath(document.uri.toString()), + ide: this.ide, reranker: await this.getRerankModel(), - chunkSize: 5, }, ); + console.log( + "nextEditableRegion:", + JSON.stringify(nextEditableRegion, null, 2), + ); + if (nextEditableRegion) { pos = { line: nextEditableRegion.range.start.line, @@ -277,6 +309,8 @@ export class ContinueCompletionProvider setupStatusBar(undefined, true); + this.oldFileContent = document.getText(); + let outcome: AutocompleteOutcome | NextEditOutcome | undefined; // Check if editChainId exists or needs to be refreshed. From 24f4918c982246691c96d582d036cc4da161774e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 22 Jul 2025 13:13:31 -0700 Subject: [PATCH 55/88] chore: remove console.logs --- extensions/vscode/src/activation/JumpManager.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 9ed09851c..1d180c072 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -314,9 +314,5 @@ export class JumpManager { setCompletionAfterJump(completionData: CompletionDataForAfterJump): void { this._completionAfterJump = completionData; - console.log( - "setCompletionAfterJump: saved", - JSON.stringify(completionData, null, 2), - ); } } From 92f956a654bd26bf0552fc0b28f987c482de67ea Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 23 Jul 2025 15:51:18 -0700 Subject: [PATCH 56/88] feat: add a truly static strategy --- .../NextEditEditableRegionCalculator.ts | 234 ++++++++++++++++-- 1 file changed, 209 insertions(+), 25 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 9d159f74b..c6353b0c5 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -5,18 +5,21 @@ import { getAst } from "../autocomplete/util/ast"; export enum EditableRegionStrategy { Naive = "naive", Rerank = "rerank", + StaticRerank = "staticRerank", Static = "static", } export async function getNextEditableRegion( strategy: EditableRegionStrategy, ctx: any, -): Promise { +): Promise { switch (strategy) { case EditableRegionStrategy.Naive: return naiveJump(ctx); case EditableRegionStrategy.Rerank: return await rerankJump(ctx); + case EditableRegionStrategy.StaticRerank: + return await staticRerankJump(ctx); case EditableRegionStrategy.Static: return await staticJump(ctx); default: @@ -26,23 +29,25 @@ export async function getNextEditableRegion( // Naive assumes that the entire file is editable. // This relies on the next edit model to figure out where to jump next. -function naiveJump(ctx: any): RangeInFile | null { +function naiveJump(ctx: any): RangeInFile[] | null { const { fileLines, filepath } = ctx; if (!fileLines || !filepath) { console.warn("Missing required context for naive jump"); return null; } - return { - filepath, - range: { - start: { line: 0, character: 0 }, - end: { - line: fileLines.length - 1, - character: fileLines.at(-1).length, + return [ + { + filepath, + range: { + start: { line: 0, character: 0 }, + end: { + line: fileLines.length - 1, + character: fileLines.at(-1).length, + }, }, }, - }; + ]; } // A rerank jump splits the current file into chunks. @@ -53,7 +58,7 @@ async function rerankJump(ctx: { filepath: string; reranker: ILLM; chunkSize: number; -}): Promise { +}): Promise { try { const { fileContent, query, filepath, reranker, chunkSize = 5 } = ctx; @@ -107,25 +112,27 @@ async function rerankJump(ctx: { // NOTE: It might be better to return a list of chunks, // because it's very difficult to gauge when to stop the model. // We could argue that we should always try to jump until the user says no. - return { - filepath, - range: { - start: { line: mostRelevantChunk.startLine, character: 0 }, - end: { - line: mostRelevantChunk.endLine, - character: lines[mostRelevantChunk.endLine].length, + return [ + { + filepath, + range: { + start: { line: mostRelevantChunk.startLine, character: 0 }, + end: { + line: mostRelevantChunk.endLine, + character: lines[mostRelevantChunk.endLine].length, + }, }, }, - }; + ]; } catch (error) { console.error("Error in rerank jump:", error); return null; } } -// A static jump runs a lightweight static analysis on the file -// to jump to relevant locations. -async function staticJump(ctx: { +// A static rerank jump runs a lightweight static analysis on the file +// and uses the reranker to jump to relevant locations. +async function staticRerankJump(ctx: { oldFileContent: string; newFileContent: string; completionRange: Range; @@ -133,7 +140,7 @@ async function staticJump(ctx: { ide: IDE; reranker?: ILLM; chunkSize?: number; -}): Promise { +}): Promise { try { const { oldFileContent, newFileContent, completionRange, filepath, ide } = ctx; @@ -146,7 +153,7 @@ async function staticJump(ctx: { !ide ) { console.warn( - "Missing required context for static jump:", + "Missing required context for static rerank jump:", !oldFileContent, !newFileContent, !completionRange, @@ -321,7 +328,8 @@ async function staticJump(ctx: { // Return the first reference if any found. if (currentFileReferences.length > 0) { - return currentFileReferences[0]; + return [currentFileReferences[0]]; + // return currentFileReferences; } return null; @@ -331,6 +339,180 @@ async function staticJump(ctx: { } } +// Static jump relies purely on static analysis +// to determine where to edit next. +async function staticJump(ctx: { + fileContent: string; + cursorPosition: { line: number; character: number }; + filepath: string; + ide: IDE; +}): Promise { + try { + const { fileContent, cursorPosition, filepath, ide } = ctx; + if (!fileContent || !cursorPosition || !filepath || !ide) { + console.warn( + "Missing required context for static jump:", + !fileContent, + !cursorPosition, + !filepath, + !ide, + ); + return null; + } + + // Get the file's AST. + // Getting this once helps us live-track the current node. + const tree = await getAst(filepath, fileContent); + if (!tree) return null; + + // Convert cursor position to tree-sitter point format (0-based). + const point = { + row: cursorPosition.line, + column: cursorPosition.character, + }; + + // Find the node at the cursor position. + const nodeAtCursor = tree.rootNode.descendantForPosition(point); + if (!nodeAtCursor) { + console.log("No node found at cursor position"); + return null; + } + + // Find the closest identifier node. + const identifierNode = findClosestIdentifierNode(nodeAtCursor); + if (!identifierNode) { + console.log("No identifier node found near cursor position"); + return null; + } + + // Get all references to this identifier using the IDE's API + const references = await ide.getReferences({ + filepath, + position: { + line: identifierNode.startPosition.row, + character: identifierNode.startPosition.column, + }, + }); + + if (!references || references.length === 0) { + console.log(`No references found for identifier: ${identifierNode.text}`); + return null; + } + + return references; + } catch (error) { + console.error("Error in staticJump:", error); + return null; + } +} + +/* AST HELPER FUNCTIONS */ + +// Helper function to find the closest identifier node. +function findClosestIdentifierNode( + node: Parser.SyntaxNode | null, +): Parser.SyntaxNode | null { + if (!node) return null; + + if (isIdentifierNode(node)) return node; + + // Check if the parent is an identifier. + // NOTE: This will probably never get triggered. + // Most identifiers are leaf nodes. + const parent = node.parent; + if (parent && isIdentifierNode(parent)) { + return parent; + } + + if (parent) { + // Check if one of the siblings is an identifier. + for (let i = 0; i < parent.childCount; ++i) { + const sibling = node.child(i); + if (sibling && isIdentifierNode(sibling)) { + // Get the leftmost identifier sibling. + return sibling; + } + } + } + + return findClosestIdentifierNode(parent); +} + +// Helper function to check if a node is an identifier. +function isIdentifierNode(node: Parser.SyntaxNode) { + const nodeType = node.type; + + if (nodeType === "identifier") return true; + if (nodeType.includes("identifier")) return true; + + // Most language grammars will use the term "identifier". + // However some might not. + // Update this as they come. + const specialIdentifiers = ["name", "constant"]; + return specialIdentifiers.includes(nodeType); +} + +// // Helper function to find the closest identifier node. +// function findClosestIdentifierNode( +// node: Parser.SyntaxNode | undefined, +// ): Parser.SyntaxNode | undefined { +// if (!node) return undefined; + +// // Check if the current node is an identifier +// if (isIdentifierLike(node)) { +// return node; +// } + +// // Check if the parent is an identifier +// const parent = node.parent; +// if (parent && isIdentifierLike(parent)) { +// return parent; +// } + +// // Check if any of the node's children are identifiers +// // Return the leftmost identifier child if found +// for (let i = 0; i < node.childCount; i++) { +// const child = node.child(i); +// if (child && isIdentifierLike(child)) { +// return child; +// } +// } + +// // Check if any of the parent's children are identifiers +// if (parent) { +// for (let i = 0; i < parent.childCount; i++) { +// const sibling = parent.child(i); +// if (sibling && isIdentifierLike(sibling)) { +// return sibling; +// } +// } +// } + +// // Recurse on the parent if we haven't found anything yet +// return findClosestIdentifierNode(parent); +// } + +// // Helper function to determine if a node is identifier-like +// function isIdentifierLike(node: Parser.SyntaxNode): boolean { +// // Common identifier node types across languages +// const commonIdentifierTypes = [ +// "identifier", +// "property_identifier", +// "type_identifier", +// "field_identifier", +// "variable_identifier", +// "constant", +// "symbol", +// ]; + +// if (commonIdentifierTypes.includes(node.type)) { +// return true; +// } + +// // Check for common identifier patterns in node types +// return /identifier$|^identifier|_identifier/.test(node.type); +// } + // Helper function to compare ASTs and find changed nodes. function compareAsts(oldAst: Parser.Tree, newAst: Parser.Tree) { const changedNodes: { @@ -399,6 +581,8 @@ function getNodePosition(node: Parser.SyntaxNode): Position | null { }; } +/* OTHER HELPER FUNCTIONS */ + // Helper function to find all occurrences of text in a string. function findTextOccurrences(text: string, searchText: string): Range[] { const results: Range[] = []; From 34ebf350c94c6d35785f1a7854476b17d613e114 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 23 Jul 2025 15:51:43 -0700 Subject: [PATCH 57/88] refactor: update to use RangeInFile[] instead of RangeInFile --- .../templating/NextEditPromptEngine.ts | 11 +++- .../src/autocomplete/completionProvider.ts | 51 +++++++++++-------- 2 files changed, 40 insertions(+), 22 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 98ae5db3e..01a18ac7f 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -93,6 +93,7 @@ export async function renderPrompt( // TODO: apply prevOutcome to existing content. we will need the line range. // Also display the diff between existing content and applied content. + // NOTE: This only runs in fetchFunction. if (prevOutcome) { // console.log("renderPrompt prevOutcome:", prevOutcome.completion); // console.log( @@ -119,6 +120,8 @@ export async function renderPrompt( // Given a previous response, we need to calculate where the cursor would be. // I think it's a good idea to calculate this in the response. + // TODO: handle cases where there are more than one next editable region. + // NOTE: we might set it so that we receive the next editable region as an argument. const editableRegion = await getNextEditableRegion(editableRegionStrategy, { fileLines: appliedContent, filepath: helper.filepath, @@ -129,8 +132,12 @@ export async function renderPrompt( editedCodeWithTokens = insertTokens( appliedContent, prevOutcome.finalCursorPosition, - editableRegion?.range.start.line ?? undefined, - editableRegion?.range.end.line ?? undefined, + editableRegion && editableRegion[0]?.range.start.line !== undefined + ? editableRegion[0].range.start.line + : undefined, + editableRegion && editableRegion[0]?.range.end.line !== undefined + ? editableRegion[0].range.end.line + : undefined, ); // console.log("new editedCodeWithTokens:", editedCodeWithTokens); userEdits = createDiff({ diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 7d4a186d4..495e68da0 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -206,29 +206,39 @@ export class ContinueCompletionProvider // chunkSize: 5, // }, // ); - const newFileContent = document.getText(); + // const newFileContent = document.getText(); + // const nextEditableRegion = await getNextEditableRegion( + // EditableRegionStrategy.StaticRerank, + // { + // oldFileContent: this.oldFileContent, + // newFileContent, + // completionRange: { + // start: { + // line: + // this.nextEditProvider.getPreviousCompletion() + // ?.editableRegionStartLine ?? 0, + // character: 0, + // }, + // end: { + // line: + // this.nextEditProvider.getPreviousCompletion() + // ?.editableRegionEndLine ?? document.lineCount - 1, + // character: 0, + // }, + // }, + // filepath: localPathOrUriToPath(document.uri.toString()), + // ide: this.ide, + // reranker: await this.getRerankModel(), + // }, + // ); const nextEditableRegion = await getNextEditableRegion( EditableRegionStrategy.Static, { - oldFileContent: this.oldFileContent, - newFileContent, - completionRange: { - start: { - line: - this.nextEditProvider.getPreviousCompletion() - ?.editableRegionStartLine ?? 0, - character: 0, - }, - end: { - line: - this.nextEditProvider.getPreviousCompletion() - ?.editableRegionEndLine ?? document.lineCount - 1, - character: 0, - }, - }, + fileContent: this.oldFileContent, + cursorPosition: + this.nextEditProvider.getPreviousCompletion()?.cursorPosition, filepath: localPathOrUriToPath(document.uri.toString()), ide: this.ide, - reranker: await this.getRerankModel(), }, ); @@ -237,10 +247,11 @@ export class ContinueCompletionProvider JSON.stringify(nextEditableRegion, null, 2), ); + // TODO: handle cases where there are more than one next editable region. if (nextEditableRegion) { pos = { - line: nextEditableRegion.range.start.line, - character: nextEditableRegion.range.start.character, + line: nextEditableRegion[0].range.start.line, + character: nextEditableRegion[0].range.start.character, }; } } else { From 44bb9aa0b82a4569da6666bd4a567c9fa137e432 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:17:24 -0700 Subject: [PATCH 58/88] feat: add a a document ast tracker to cache ASTs --- core/nextEdit/DocumentAstTracker.ts | 207 ++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 core/nextEdit/DocumentAstTracker.ts diff --git a/core/nextEdit/DocumentAstTracker.ts b/core/nextEdit/DocumentAstTracker.ts new file mode 100644 index 000000000..1bbdc98b7 --- /dev/null +++ b/core/nextEdit/DocumentAstTracker.ts @@ -0,0 +1,207 @@ +// TODO: +// Create a DocumentAstTracker singleton class that keeps track of a map of document paths to their history of ASTs. +// There should be a map from document path to history of ASTs (a LIFO stack of ASTs where the newest AST is at the front) +// We want to expose these methods: +// add document and its first AST +// push to an existing document's AST history stack +// get the most recent AST of an existing document's AST +// The AST and nodes will be using web-tree-sitter types. +// save map to file as a documentAstTracker.json inside the user's global continue path +// delete document from map +// clear map +import * as fs from "fs"; +import * as path from "path"; +import Parser from "web-tree-sitter"; +import { getContinueGlobalPath } from "../util/paths"; + +/** + * Singleton class that keeps track of a map of document paths to their history of ASTs. + */ +export class DocumentAstTracker { + private static instance: DocumentAstTracker | null = null; + + // Map from document path to history of ASTs (LIFO stack where newest AST is at the front). + private documentAstMap: Map; + private documentContentHistoryMap: Map; + + // Path to save the AST tracker data. + private readonly savePath: string; + + private constructor() { + this.documentAstMap = new Map(); + this.documentContentHistoryMap = new Map(); + this.savePath = path.join( + getContinueGlobalPath(), + "documentAstTracker.jsonl", + ); + + // Try to load existing data. + // this.loadFromFile(); + } + + /** + * Get the singleton instance of DocumentAstTracker. + */ + public static getInstance(): DocumentAstTracker { + if (!DocumentAstTracker.instance) { + DocumentAstTracker.instance = new DocumentAstTracker(); + } + + return DocumentAstTracker.instance; + } + + /** + * Add a document and its first AST to the tracker. + * + * @param documentPath The path of the document. + * @param ast The first AST of the document. + */ + public addDocument( + documentPath: string, + documentContent: string, + ast: Parser.Tree, + ): void { + this.documentAstMap.set(documentPath, [ast]); + this.documentContentHistoryMap.set(documentPath, [documentContent]); + // this.saveToFile(); + } + + /** + * Push a new AST to an existing document's history stack. + * + * @param documentPath The path of the document. + * @param ast The new AST to push to the document's history stack. + * @throws Error if the document doesn't exist in the tracker. + */ + public pushAst( + documentPath: string, + documentContent: string, + ast: Parser.Tree, + ): void { + const astHistory = this.documentAstMap.get(documentPath); + const documentHistory = this.documentContentHistoryMap.get(documentPath); + + if (!astHistory || !documentHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + this.addDocument(documentPath, documentContent, ast); + } + + console.log("same AST:", this.getMostRecentAst(documentPath) !== ast); + + // Add the new AST to the front of the array (LIFO stack). + astHistory!.unshift(ast); + documentHistory!.unshift(documentContent); + // this.saveToFile(); + } + + /** + * Get the most recent AST of a document. + * + * @param documentPath The path of the document. + * @returns The most recent AST of the document. + * @throws Error if the document doesn't exist in the tracker. + */ + public getMostRecentAst(documentPath: string): Parser.Tree | null { + const astHistory = this.documentAstMap.get(documentPath); + + if (!astHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + return null; + } + if (astHistory.length === 0) { + console.error(`Document ${documentPath} has no ASTs`); + return null; + } + + // Return the first element (most recent AST). + return astHistory[0]; + } + + /** + * Get the most recent AST of a document. + * + * @param documentPath The path of the document. + * @returns The most recent document history of the document. + * @throws Error if the document doesn't exist in the tracker. + */ + public getMostRecentDocumentHistory(documentPath: string): string | null { + const documentHistory = this.documentContentHistoryMap.get(documentPath); + + if (!documentHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + return null; + } + if (documentHistory.length === 0) { + console.error(`Document ${documentPath} has no history`); + return null; + } + + // Return the first element (most recent doc history). + return documentHistory[0]; + } + + /** + * Delete a document from the tracker. + * + * @param documentPath The path of the document to delete. + */ + public deleteDocument(documentPath: string): void { + this.documentAstMap.delete(documentPath); + this.documentContentHistoryMap.delete(documentPath); + // this.saveToFile(); + } + + /** + * Clear all documents from the tracker. + */ + public clearMap(): void { + this.documentAstMap.clear(); + this.documentContentHistoryMap.clear(); + // this.saveToFile(); + } + + /** + * Save the current state of the tracker to a file. + */ + private saveToFile(): void { + try { + // We can't directly serialize Tree objects to JSON. + // So we'll just save the paths - this serves as a record of which documents we're tracking. + // The actual ASTs will need to be recreated when needed. + const documentPaths = Array.from(this.documentAstMap.keys()); + const serializableData = { documentPaths }; + + fs.writeFileSync( + this.savePath, + JSON.stringify(serializableData, null, 2), + ); + } catch (error) { + console.error("Error saving AST tracker data to file:", error); + } + } + + /** + * Load the tracker state from a file. + */ + private loadFromFile(): void { + try { + if (fs.existsSync(this.savePath)) { + const fileContent = fs.readFileSync(this.savePath, "utf-8"); + const data = JSON.parse(fileContent); + + // We only saved the paths, not the actual Trees. + // The Trees need to be reparsed when the documents are loaded again. + if (data && data.documentPaths) { + // Initialize empty arrays for each document. + data.documentPaths.forEach((path: string) => { + this.documentAstMap.set(path, []); + }); + } + } + } catch (error) { + console.error("Error loading AST tracker data from file:", error); + // If loading fails, we'll start with an empty map. + this.documentAstMap = new Map(); + } + } +} From d5ce1aec0ab946fc3af83277b8016b9f66e23564 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:19:20 -0700 Subject: [PATCH 59/88] feat: use the document ast tracker --- .../NextEditEditableRegionCalculator.ts | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index c6353b0c5..74dc011ba 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -1,6 +1,7 @@ import Parser from "web-tree-sitter"; import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; import { getAst } from "../autocomplete/util/ast"; +import { DocumentAstTracker } from "./DocumentAstTracker"; export enum EditableRegionStrategy { Naive = "naive", @@ -362,7 +363,9 @@ async function staticJump(ctx: { // Get the file's AST. // Getting this once helps us live-track the current node. - const tree = await getAst(filepath, fileContent); + const tree = + await DocumentAstTracker.getInstance().getMostRecentAst(filepath); + // const tree = await getAst(filepath, fileContent); if (!tree) return null; // Convert cursor position to tree-sitter point format (0-based). @@ -384,6 +387,7 @@ async function staticJump(ctx: { console.log("No identifier node found near cursor position"); return null; } + console.log("closest identifier:", identifierNode.text); // Get all references to this identifier using the IDE's API const references = await ide.getReferences({ @@ -399,7 +403,19 @@ async function staticJump(ctx: { return null; } - return references; + console.log( + "references:", + JSON.stringify( + references.map((ref) => ({ + line: ref.range.start.line, + character: ref.range.start.character, + })), + null, + 2, + ), + ); + + return references.length > 1 ? references.slice(1) : null; } catch (error) { console.error("Error in staticJump:", error); return null; From 04868195e37b61d56b28057fbf586a8ca144e011 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:19:33 -0700 Subject: [PATCH 60/88] feat: add fileContentsBeforeAccept field --- core/nextEdit/types.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 26e2b156a..e4ae1f328 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -47,9 +47,10 @@ export interface NextEditOutcome extends TabAutocompleteOptions { // New for Next Edit. fileUri: string; workspaceDirUri: string; + fileContentsBeforeAccept: string; prompt: string; userEdits: string; - userExcerpts: string; + userExcerpts: string; // For now, this is the same as fileContentsBeforeAccept, but that assumption should not be relied on. originalEditableRange: string; completion: string; cursorPosition: { line: number; character: number }; From c172170569a5d10a4311a41074ff076e0f23fe8c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:20:43 -0700 Subject: [PATCH 61/88] feat: add a method to request the model within a given chain --- core/nextEdit/NextEditProvider.ts | 161 +++++++++++++++++++++++++++++- 1 file changed, 157 insertions(+), 4 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index c84a76bba..851572ce7 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -7,6 +7,7 @@ import { IDE, ILLM, Position, + Range, RangeInFile, } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; @@ -18,22 +19,30 @@ import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchin import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; +import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; +import { getAst } from "../autocomplete/util/ast.js"; import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js"; import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; import { myersDiff } from "../diff/myers.js"; +import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; +import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { calculateFinalCursorPosition, getOffsetPositionAtLastNewLine, } from "./diff/diff.js"; -import { EditableRegionStrategy } from "./NextEditEditableRegionCalculator.js"; +import { DocumentAstTracker } from "./DocumentAstTracker.js"; +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "./NextEditEditableRegionCalculator.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; import { NextEditPrefetchQueue } from "./NextEditPrefetchQueue.js"; import { @@ -41,7 +50,12 @@ import { renderDefaultUserPrompt, renderPrompt, } from "./templating/NextEditPromptEngine.js"; -import { NextEditOutcome, Prompt, PromptMetadata } from "./types.js"; +import { + NextEditOutcome, + Prompt, + PromptMetadata, + RecentlyEditedRange, +} from "./types.js"; // import { renderPrompt } from "./templating/NextEditPromptEngine.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -70,7 +84,10 @@ export class NextEditProvider { private prefetchQueue: NextEditPrefetchQueue; // private refQueue: RangeInFile[] = []; private currentEditChainId: string | null = null; + private previousRequest: AutocompleteInput | null = null; private previousCompletions: NextEditOutcome[] = []; + private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; + // TODO: keep track of the last completion request (at least the file path it came from) private constructor( private readonly configHandler: ConfigHandler, @@ -176,6 +193,7 @@ export class NextEditProvider { workspaceDirUri: other.helper.workspaceUris[0] ?? path.dirname(other.helper.filepath), + fileContentsBeforeAccept: other.helper.fileContents, prompt: this.promptMetadata!.prompt.content, userEdits: this.promptMetadata!.userEdits, userExcerpts: this.promptMetadata!.userExcerpts, @@ -326,9 +344,24 @@ export class NextEditProvider { return this.previousCompletions[0]; } - public deleteChain(): void { + public async deleteChain(): Promise { this.currentEditChainId = null; this.previousCompletions = []; + this.nextEditableRegionsInTheCurrentChain = []; + + if (this.previousRequest) { + const fileContent = + // await fs.readFile(localPathOrUriToPath(this.previousRequest.filepath) + (await this.ide.readFile(this.previousRequest.filepath)).toString(); + const ast = await getAst(this.previousRequest.filepath, fileContent); + if (ast) { + DocumentAstTracker.getInstance().pushAst( + localPathOrUriToPath(this.previousRequest.filepath), + fileContent, + ast, + ); + } + } } public startChain(id?: string) { @@ -348,6 +381,7 @@ export class NextEditProvider { token: AbortSignal | undefined, ): Promise { try { + this.previousRequest = input; // Create abort signal if not given if (!token) { const controller = this.loggingService.createAbortController( @@ -399,12 +433,34 @@ export class NextEditProvider { prompts.push(renderDefaultSystemPrompt()); prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); } else { + const historyDiff = createDiff({ + beforeContent: + DocumentAstTracker.getInstance().getMostRecentDocumentHistory( + localPathOrUriToPath(helper.filepath), + ) ?? "", + afterContent: helper.fileContents, + filePath: helper.filepath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }); const promptMetadata = await renderPrompt( helper, - this.diffContext, + // this.diffContext, + historyDiff ?? this.diffContext, EditableRegionStrategy.Naive, + // input.recentlyEditedRanges, ); this.promptMetadata = promptMetadata; + prompts.push({ + role: "system", + content: [ + "When the user deletes or replaces over previous code, you should respect that decision.", + "Respect the new code the user is writing, and complete it.", + "For example, if the user is changing a field name, try to autocomplete the new field name. Don't suggest the previous field name.", + "Do not roll back to previous content.", + "If the user has made a change, make sure you respect that and try to apply it to other parts of the code that used to use the old content.", + ].join("\n"), + }); prompts.push(promptMetadata.prompt); } @@ -445,6 +501,7 @@ export class NextEditProvider { fileUri: helper.filepath, workspaceDirUri: helper.workspaceUris[0] ?? path.dirname(helper.filepath), + fileContentsBeforeAccept: helper.fileContents, prompt: prompts.join("\n"), userEdits: "", userExcerpts: "", @@ -518,6 +575,7 @@ export class NextEditProvider { fileUri: helper.filepath, workspaceDirUri: helper.workspaceUris[0] ?? path.dirname(helper.filepath), + fileContentsBeforeAccept: helper.fileContents, prompt: this.promptMetadata!.prompt.content, userEdits: this.promptMetadata!.userEdits, userExcerpts: this.promptMetadata!.userExcerpts, @@ -551,6 +609,101 @@ export class NextEditProvider { } } + public async provideInlineCompletionItemsWithChain( + ctx: { + completionId: string; + manuallyPassFileContents?: string; + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + isUntitledFile: boolean; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }, + token: AbortSignal | undefined, + ) { + // TODO: + // If we don't have a precomputed list of next editable regions already, compute it. + // Store this list as a class attribute. + // Pop the frontmost RangeInFile and use that to build an input. + try { + const previousOutcome = this.getPreviousCompletion(); + if (!previousOutcome) { + return undefined; + } + // TODO: This is actually getting the contents after the user typed something. + // we need the file before the user has typed anything. + // console.log("previousOutcome:", previousOutcome.fileContentsBeforeAccept); + // console.log("previousCursorPosition:", previousOutcome.cursorPosition); + + const fileContent = previousOutcome.fileContentsBeforeAccept; + const filepath = localPathOrUriToPath(previousOutcome.fileUri); + + if (this.nextEditableRegionsInTheCurrentChain.length === 0) { + this.loadNextEditableRegionsInTheCurrentChain( + (await getNextEditableRegion(EditableRegionStrategy.Static, { + fileContent, + cursorPosition: previousOutcome.cursorPosition, + filepath, + ide: this.ide, + })) ?? [], + ); + + if (this.nextEditableRegionsInTheCurrentChain.length === 0) { + await this.deleteChain(); + return undefined; + } + } + + const input = await this.buildAutocompleteInputFromChain( + previousOutcome, + this.nextEditableRegionsInTheCurrentChain[0], + ctx, + ); + if (!input) { + return undefined; + } + + return await this.provideInlineCompletionItems(input, token); + } catch (e: any) { + this.onError(e); + } + } + + private buildAutocompleteInputFromChain( + previousOutcome: NextEditOutcome, + nextEditableRegion: RangeInFile, + ctx: { + completionId: string; + manuallyPassFileContents?: string; + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + isUntitledFile: boolean; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }, + ): AutocompleteInput | undefined { + const input: AutocompleteInput = { + pos: { + line: nextEditableRegion.range.start.line, + character: nextEditableRegion.range.start.character, + }, + filepath: previousOutcome.fileUri, + ...ctx, + }; + + return input; + } + + public loadNextEditableRegionsInTheCurrentChain(regions: RangeInFile[]) { + this.nextEditableRegionsInTheCurrentChain = regions; + } + public async provideNextEditPrediction( input: AutocompleteInput, token: AbortSignal | undefined, From f319a40c6424100e7d50fc35a3b6fac0bb4338c3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:21:16 -0700 Subject: [PATCH 62/88] refactor: calculate document content separately --- extensions/vscode/src/commands.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 70a602a0f..4c00fee06 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -829,6 +829,8 @@ const getCommandsMap: ( return; } + const documentContent = editor.document.getText(); + // Calculate the editable region boundaries around the current cursor position/ const editableRegionStartLine = Math.max( currentPosition.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, @@ -840,8 +842,7 @@ const getCommandsMap: ( ); // Get the current text in the editable region. - const oldEditRangeSlice = editor.document - .getText() + const oldEditRangeSlice = documentContent .split("\n") .slice(editableRegionStartLine, editableRegionEndLine + 1) .join("\n"); From 333757f003c1c0223dbd1340425168ab1304808f Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:22:07 -0700 Subject: [PATCH 63/88] feat: handle cases where there are existing edit chains --- .../src/autocomplete/completionProvider.ts | 205 ++++++++---------- 1 file changed, 91 insertions(+), 114 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 495e68da0..26a7b1308 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -21,14 +21,9 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "core/nextEdit/constants"; import { checkFim } from "core/nextEdit/diff/diff"; -import { - EditableRegionStrategy, - getNextEditableRegion, -} from "core/nextEdit/NextEditEditableRegionCalculator"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { NextEditOutcome } from "core/nextEdit/types"; -import { localPathOrUriToPath } from "core/util/pathToUri"; import { JumpManager } from "../activation/JumpManager"; import { NextEditWindowManager } from "../activation/NextEditWindowManager"; import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker"; @@ -193,72 +188,6 @@ export class ContinueCompletionProvider character: position.character, }; - if (this.nextEditProvider.chainExists()) { - // If the user has accepted the previous completion, the chain of edits is alive. - // Get the next editable region and set the pos to be within that range. - // const nextEditableRegion = await getNextEditableRegion( - // EditableRegionStrategy.Rerank, - // { - // fileContent: document.getText(), - // query: this.nextEditProvider.getPreviousCompletion(), // previous completion in the chain - // filepath: localPathOrUriToPath(document.uri.toString()), - // reranker: await this.getRerankModel(), - // chunkSize: 5, - // }, - // ); - // const newFileContent = document.getText(); - // const nextEditableRegion = await getNextEditableRegion( - // EditableRegionStrategy.StaticRerank, - // { - // oldFileContent: this.oldFileContent, - // newFileContent, - // completionRange: { - // start: { - // line: - // this.nextEditProvider.getPreviousCompletion() - // ?.editableRegionStartLine ?? 0, - // character: 0, - // }, - // end: { - // line: - // this.nextEditProvider.getPreviousCompletion() - // ?.editableRegionEndLine ?? document.lineCount - 1, - // character: 0, - // }, - // }, - // filepath: localPathOrUriToPath(document.uri.toString()), - // ide: this.ide, - // reranker: await this.getRerankModel(), - // }, - // ); - const nextEditableRegion = await getNextEditableRegion( - EditableRegionStrategy.Static, - { - fileContent: this.oldFileContent, - cursorPosition: - this.nextEditProvider.getPreviousCompletion()?.cursorPosition, - filepath: localPathOrUriToPath(document.uri.toString()), - ide: this.ide, - }, - ); - - console.log( - "nextEditableRegion:", - JSON.stringify(nextEditableRegion, null, 2), - ); - - // TODO: handle cases where there are more than one next editable region. - if (nextEditableRegion) { - pos = { - line: nextEditableRegion[0].range.start.line, - character: nextEditableRegion[0].range.start.character, - }; - } - } else { - // If the user has rejected, then we start a new chain of edits. - this.nextEditProvider.startChain(); - } - let manuallyPassFileContents: string | undefined = undefined; if (document.uri.scheme === "vscode-notebook-cell") { const notebook = vscode.workspace.notebookDocuments.find((notebook) => @@ -304,40 +233,67 @@ export class ContinueCompletionProvider const wasManuallyTriggered = context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke; - const input: AutocompleteInput = { - pos, - manuallyPassFileContents, - manuallyPassPrefix, - selectedCompletionInfo, - injectDetails, - isUntitledFile: document.isUntitled, - completionId: uuidv4(), - filepath: document.uri.toString(), - recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), - recentlyEditedRanges: - await this.recentlyEditedTracker.getRecentlyEditedRanges(), - }; + let outcome: AutocompleteOutcome | NextEditOutcome | undefined; + const completionId = uuidv4(); + const filepath = document.uri.toString(); + const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets(); + let recentlyEditedRanges = + await this.recentlyEditedTracker.getRecentlyEditedRanges(); + console.log("one:", JSON.stringify(recentlyEditedRanges, null, 2)); - setupStatusBar(undefined, true); + if (this.nextEditProvider.chainExists()) { + // If the user has accepted the previous completion, the chain of edits is alive. + // Get the next editable region and set the pos to be within that range. + outcome = + await this.nextEditProvider.provideInlineCompletionItemsWithChain( + { + completionId, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + isUntitledFile: document.isUntitled, + recentlyVisitedRanges, + recentlyEditedRanges, + }, + signal, + ); + } else { + // If the user has rejected, then we start a new chain of edits. + this.nextEditProvider.startChain(); + + const input: AutocompleteInput = { + pos, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + injectDetails, + isUntitledFile: document.isUntitled, + completionId, + filepath, + recentlyVisitedRanges, + recentlyEditedRanges, + }; + + setupStatusBar(undefined, true); + // Check if editChainId exists or needs to be refreshed. + if (this.isNextEditActive) { + outcome = await this.nextEditProvider.provideInlineCompletionItems( + input, + signal, + ); + console.log("outcome.completion:"); + console.log(outcome?.completion); + } else { + outcome = await this.completionProvider.provideInlineCompletionItems( + input, + signal, + wasManuallyTriggered, + ); + } + } this.oldFileContent = document.getText(); - let outcome: AutocompleteOutcome | NextEditOutcome | undefined; - - // Check if editChainId exists or needs to be refreshed. - if (this.isNextEditActive) { - outcome = await this.nextEditProvider.provideInlineCompletionItems( - input, - signal, - ); - } else { - outcome = await this.completionProvider.provideInlineCompletionItems( - input, - signal, - wasManuallyTriggered, - ); - } - // TODO: fix type of outcome to be a union between NextEditOutcome and AutocompleteOutcome. // const outcome: AutocompleteOutcome | NextEditOutcome | undefined = this // .isNextEditActive @@ -352,7 +308,30 @@ export class ContinueCompletionProvider // ); if (!outcome || !outcome.completion) { - return null; + // TODO: At this point we assume that the user typed something "whole". + // AKA, the user's edit was good enough to start an edit chain. + // We actually started the chain before getting the outcome. This makes logical sense. + // Then all we need to do is to calculate next editable region. + // We also need to use the user's edits to create a user edits section in renderPrompt. + recentlyEditedRanges = + await this.recentlyEditedTracker.getRecentlyEditedRanges(); + console.log("two:", JSON.stringify(recentlyEditedRanges, null, 2)); + outcome = + await this.nextEditProvider.provideInlineCompletionItemsWithChain( + { + completionId, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + isUntitledFile: document.isUntitled, + recentlyVisitedRanges, + recentlyEditedRanges, + }, + signal, + ); + if (!outcome || !outcome.completion) { + return null; + } } // VS Code displays dependent on selectedCompletionInfo (their docstring below) @@ -385,12 +364,12 @@ export class ContinueCompletionProvider // the current outcome as a value of the key completionId. if (this.isNextEditActive) { this.nextEditProvider.markDisplayed( - input.completionId, + completionId, outcome as NextEditOutcome, ); } else { this.completionProvider.markDisplayed( - input.completionId, + completionId, outcome as AutocompleteOutcome, ); } @@ -438,7 +417,7 @@ export class ContinueCompletionProvider { title: "Log Autocomplete Outcome", command: "continue.logAutocompleteOutcome", - arguments: [input.completionId, this.completionProvider], + arguments: [completionId, this.completionProvider], }, ); @@ -470,7 +449,7 @@ export class ContinueCompletionProvider if (this.jumpManager.isJumpInProgress()) { // Store this completion for later use when jump is complete. this.jumpManager.setCompletionAfterJump({ - completionId: input.completionId, + completionId: completionId, outcome: outcome as NextEditOutcome, currentPosition: jumpPosition, }); @@ -486,9 +465,7 @@ export class ContinueCompletionProvider // We don't need to show the next edit window if the predicted edits is empty. if (newEditRangeSlice === "") { - this.nextEditLoggingService.cancelRejectionTimeout( - input.completionId, - ); + this.nextEditLoggingService.cancelRejectionTimeout(completionId); return undefined; } @@ -509,9 +486,7 @@ export class ContinueCompletionProvider // We don't need to show the next edit window if the predicted edits are identical to the previous version. if (oldEditRangeSlice === newEditRangeSlice) { - this.nextEditLoggingService.cancelRejectionTimeout( - input.completionId, - ); + this.nextEditLoggingService.cancelRejectionTimeout(completionId); return undefined; } @@ -527,6 +502,8 @@ export class ContinueCompletionProvider newEditRangeSlice, relativeCursorPos, ); + console.log("isFim:", isFim); + console.log("fimText:", fimText); if (isFim) { if (!fimText) { @@ -553,7 +530,7 @@ export class ContinueCompletionProvider { title: "Log Next Edit Outcome", command: "continue.logNextEditOutcomeAccept", - arguments: [input.completionId, this.nextEditLoggingService], // TODO: this may have to be this.completionProvider. + arguments: [completionId, this.nextEditLoggingService], // TODO: this may have to be this.completionProvider. }, ); console.log(nextEditCompletionItem); @@ -571,7 +548,7 @@ export class ContinueCompletionProvider if (NextEditWindowManager.isInstantiated()) { NextEditWindowManager.getInstance().updateCurrentCompletionId( - input.completionId, + completionId, ); await NextEditWindowManager.getInstance().showNextEditWindow( From 895c2855145d1f33fcde3f57f2337d1a171c1c4a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:22:24 -0700 Subject: [PATCH 64/88] fix: actually update the recently edited ranges --- extensions/vscode/src/autocomplete/recentlyEdited.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 9fa48cd98..fc4eab517 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -67,6 +67,7 @@ export class RecentlyEditedTracker { lines: contents.split("\n"), symbols: getSymbolsForSnippet(contents), }; + this.recentlyEditedRanges[i] = range; return; } } From 00efd382a825546b1801040606d8c96cf2371f6e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:22:48 -0700 Subject: [PATCH 65/88] feat: handle typing sessions separately from cursor movements --- .../vscode/src/extension/VsCodeExtension.ts | 58 ++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 4983583ab..d0c4fdd5b 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -42,7 +42,14 @@ import { VsCodeIde } from "../VsCodeIde"; import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; +import { getAst } from "core/autocomplete/util/ast"; +import { DocumentAstTracker } from "core/nextEdit/DocumentAstTracker"; +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "core/nextEdit/NextEditEditableRegionCalculator"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { localPathOrUriToPath } from "core/util/pathToUri"; import { JumpManager } from "../activation/JumpManager"; import setupNextEditWindowManager, { NextEditWindowManager, @@ -71,6 +78,18 @@ export class VsCodeExtension { private fileSearch: FileSearch; private uriHandler = new UriEventHandler(); private completionProvider: ContinueCompletionProvider; + // Track whether the user is currently typing + private isTypingSession = false; + private typingTimer: NodeJS.Timeout | null = null; + private lastDocumentChangeTime = 0; + + // Reset typing session after a delay + resetTypingSession = () => { + if (this.typingTimer) clearTimeout(this.typingTimer); + this.typingTimer = setTimeout(() => { + this.isTypingSession = false; + }, 2000); // Typing session considered over after 2 seconds of inactivity + }; constructor(context: vscode.ExtensionContext) { // Register auth provider @@ -320,6 +339,12 @@ export class VsCodeExtension { }); vscode.workspace.onDidChangeTextDocument(async (event) => { + if (event.contentChanges.length > 0) { + this.isTypingSession = true; + this.lastDocumentChangeTime = Date.now(); + this.resetTypingSession(); + } + const editInfo = await handleTextDocumentChange( event, this.configHandler, @@ -355,6 +380,19 @@ export class VsCodeExtension { }); }); + vscode.workspace.onDidOpenTextDocument(async (event) => { + console.log("onDidOpenTextDocument"); + const ast = await getAst(event.fileName, event.getText()); + console.log(ast === undefined); + if (ast) { + DocumentAstTracker.getInstance().addDocument( + localPathOrUriToPath(event.fileName), + event.getText(), + ast, + ); + } + }); + // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); @@ -389,7 +427,7 @@ export class VsCodeExtension { // console.log( // "deleteChain from VsCodeExtension.ts: onDidChangeVisibleTextEditors", // ); - NextEditProvider.getInstance().deleteChain(); + await NextEditProvider.getInstance().deleteChain(); }); // Listen for selection changes to hide tooltip when cursor moves. @@ -423,11 +461,27 @@ export class VsCodeExtension { return; } + // 4. The selection change is part of a typing session + // Check if this selection change is close enough to a document change to be considered typing + const timeSinceLastDocChange = Date.now() - this.lastDocumentChangeTime; + if (this.isTypingSession && timeSinceLastDocChange < 500) { + // This selection change is likely due to typing, don't delete the chain + return; + } + // Otherwise, delete the chain (for rejection or unrelated movement). console.log( "deleteChain from VsCodeExtension.ts: onDidChangeTextEditorSelection", ); - NextEditProvider.getInstance().deleteChain(); + await NextEditProvider.getInstance().deleteChain(); + NextEditProvider.getInstance().loadNextEditableRegionsInTheCurrentChain( + (await getNextEditableRegion(EditableRegionStrategy.Static, { + fileContent: e.textEditor.document.getText(), + cursorPosition: e.selections[0].anchor, + filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), + ide: this.ide, + })) ?? [], + ); }); // Refresh index when branch is changed From 3413cf563304a0781e05915b4ba785872b52c0ba Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 10:23:15 -0700 Subject: [PATCH 66/88] feat: get the editor contents instead of file contents --- extensions/vscode/src/util/ideUtils.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 6f213b302..d8593f7d0 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -111,6 +111,7 @@ export class VsCodeIdeUtils { /** * Read the entire contents of a file from the given URI. + * If there are unsaved changes in an open editor, returns those instead of the file on disk. * * @param uri - The URI of the file to read. * @param ignoreMissingProviders - Optional flag to ignore missing file system providers for unsupported schemes. @@ -124,6 +125,18 @@ export class VsCodeIdeUtils { uri: vscode.Uri, ignoreMissingProviders: boolean = true, ): Promise { + // First check if there's an open document with this URI that might have unsaved changes. + const openDocuments = vscode.workspace.textDocuments; + for (const document of openDocuments) { + if (document.uri.toString() === uri.toString()) { + // Found an open document with this URI. + // Return its current content (including any unsaved changes) as Uint8Array. + const docText = document.getText(); + return Buffer.from(docText, "utf8"); + } + } + + // If no open document found or if it's not dirty, fall back to reading from disk. return await this.fsOperation( uri, async (u) => { From 7030eb80af7a35c5b204e5f4e9ed19e2562e4dc4 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 15:16:44 -0700 Subject: [PATCH 67/88] refactor: rename file --- .../nextEdit/{DocumentAstTracker.ts => DocumentHistoryTracker.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename core/nextEdit/{DocumentAstTracker.ts => DocumentHistoryTracker.ts} (100%) diff --git a/core/nextEdit/DocumentAstTracker.ts b/core/nextEdit/DocumentHistoryTracker.ts similarity index 100% rename from core/nextEdit/DocumentAstTracker.ts rename to core/nextEdit/DocumentHistoryTracker.ts From 1480e1b0bdedad995346ab9a765a1493f235d017 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 15:17:53 -0700 Subject: [PATCH 68/88] feat: check if the completion request is within a chain, and shift the next editable region accordingly --- core/nextEdit/NextEditProvider.ts | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 851572ce7..b8512cd4e 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -38,7 +38,7 @@ import { calculateFinalCursorPosition, getOffsetPositionAtLastNewLine, } from "./diff/diff.js"; -import { DocumentAstTracker } from "./DocumentAstTracker.js"; +import { DocumentAstTracker } from "./DocumentHistoryTracker.js"; import { EditableRegionStrategy, getNextEditableRegion, @@ -379,6 +379,7 @@ export class NextEditProvider { public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, + withChain: boolean, ): Promise { try { this.previousRequest = input; @@ -397,6 +398,12 @@ export class NextEditProvider { return undefined; } + // Depending on whether this method is called from provideInlineCompletionItemsWithChain, + // shift the next editable regions. + if (withChain) { + this.shiftNextEditableRegionsInTheCurrentChain(); + } + const llm = await this._prepareLlm(); if (!llm) { return undefined; @@ -451,6 +458,7 @@ export class NextEditProvider { // input.recentlyEditedRanges, ); this.promptMetadata = promptMetadata; + prompts.push({ role: "system", content: [ @@ -640,8 +648,13 @@ export class NextEditProvider { const fileContent = previousOutcome.fileContentsBeforeAccept; const filepath = localPathOrUriToPath(previousOutcome.fileUri); + console.log( + "number of next editable regions:", + this.nextEditableRegionsInTheCurrentChain.length, + ); if (this.nextEditableRegionsInTheCurrentChain.length === 0) { + console.log("empty next editable regions list"); this.loadNextEditableRegionsInTheCurrentChain( (await getNextEditableRegion(EditableRegionStrategy.Static, { fileContent, @@ -659,14 +672,15 @@ export class NextEditProvider { const input = await this.buildAutocompleteInputFromChain( previousOutcome, - this.nextEditableRegionsInTheCurrentChain[0], + this.nextEditableRegionsInTheCurrentChain[0], // this will be shifted after debouncer check ctx, ); if (!input) { return undefined; } - return await this.provideInlineCompletionItems(input, token); + const WITH_CHAIN = true; + return await this.provideInlineCompletionItems(input, token, WITH_CHAIN); } catch (e: any) { this.onError(e); } @@ -701,9 +715,15 @@ export class NextEditProvider { } public loadNextEditableRegionsInTheCurrentChain(regions: RangeInFile[]) { + console.log("regions after load:", regions.length); this.nextEditableRegionsInTheCurrentChain = regions; } + public shiftNextEditableRegionsInTheCurrentChain() { + console.log("shift", this.nextEditableRegionsInTheCurrentChain.length); + this.nextEditableRegionsInTheCurrentChain.shift(); + } + public async provideNextEditPrediction( input: AutocompleteInput, token: AbortSignal | undefined, From e454ede427e532b0d0d9f5ca415f12c4bad99fba Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 15:18:23 -0700 Subject: [PATCH 69/88] chore: remove console.logs --- extensions/vscode/src/commands.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 4c00fee06..ce69ea87b 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -916,7 +916,6 @@ const getCommandsMap: ( console.log("deleteChain from commands.ts: diffLines.length === 0"); NextEditProvider.getInstance().deleteChain(); } - console.log("number of difflines:", diffLines.length); if (NextEditWindowManager.isInstantiated()) { const windowManager = NextEditWindowManager.getInstance(); From c9acabe58ff5161c6a058ff13cf15398fd9cae7e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 15:18:45 -0700 Subject: [PATCH 70/88] fix: we don't need to set inlineSuggest manually anymore --- .../vscode/src/activation/NextEditWindowManager.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 37414830e..00e340e17 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -404,9 +404,9 @@ export class NextEditWindowManager { // Disable inline suggestions temporarily. // This prevents the race condition between vscode's inline completion provider // and the next edit window manager's cursor repositioning logic. - await vscode.workspace - .getConfiguration() - .update("editor.inlineSuggest.enabled", false, true); + // await vscode.workspace + // .getConfiguration() + // .update("editor.inlineSuggest.enabled", false, true); } if (success) { @@ -418,9 +418,9 @@ export class NextEditWindowManager { ); // Reenable inline suggestions after we move the cursor. - await vscode.workspace - .getConfiguration() - .update("editor.inlineSuggest.enabled", true, true); + // await vscode.workspace + // .getConfiguration() + // .update("editor.inlineSuggest.enabled", true, true); await this.hideAllNextEditWindows(); } From a14c1bf397c75912cd8de58407ae58c90bf331e5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 15:19:41 -0700 Subject: [PATCH 71/88] refactor: pass withChain boolean and remove console.logs --- core/core.ts | 1 + .../src/autocomplete/completionProvider.ts | 64 +++++++++++-------- .../vscode/src/extension/VsCodeExtension.ts | 3 +- 3 files changed, 41 insertions(+), 27 deletions(-) diff --git a/core/core.ts b/core/core.ts index a3fe4cab5..c97837fde 100644 --- a/core/core.ts +++ b/core/core.ts @@ -593,6 +593,7 @@ export class Core { const outcome = await this.nextEditProvider.provideInlineCompletionItems( msg.data, undefined, + false, ); return outcome ? [outcome.completion, outcome.originalEditableRange] : []; }); diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 26a7b1308..4919377c9 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -140,6 +140,14 @@ export class ContinueCompletionProvider token: vscode.CancellationToken, //@ts-ignore ): ProviderResult { + console.log("================================================"); + console.log( + "editor.inlineSuggest.enabled:", + vscode.workspace + .getConfiguration() + .get("editor.inlineSuggest.enabled"), + ); + // console.log("trigger!!", token.isCancellationRequested); const enableTabAutocomplete = getStatusBarStatus() === StatusBarStatus.Enabled; if (token.isCancellationRequested || !enableTabAutocomplete) { @@ -239,7 +247,12 @@ export class ContinueCompletionProvider const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets(); let recentlyEditedRanges = await this.recentlyEditedTracker.getRecentlyEditedRanges(); - console.log("one:", JSON.stringify(recentlyEditedRanges, null, 2)); + // console.log("one:", JSON.stringify(recentlyEditedRanges, null, 2)); + console.log( + this.nextEditProvider.chainExists() + ? "chain is alive" + : "chain is not alive", + ); if (this.nextEditProvider.chainExists()) { // If the user has accepted the previous completion, the chain of edits is alive. @@ -280,9 +293,33 @@ export class ContinueCompletionProvider outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, + false, ); console.log("outcome.completion:"); console.log(outcome?.completion); + if (!outcome || !outcome.completion) { + // TODO: At this point we assume that the user typed something "whole". + // AKA, the user's edit was good enough to start an edit chain. + // We actually started the chain before getting the outcome. This makes logical sense. + // Then all we need to do is to calculate next editable region. + // We also need to use the user's edits to create a user edits section in renderPrompt. + recentlyEditedRanges = + await this.recentlyEditedTracker.getRecentlyEditedRanges(); + // console.log("two:", JSON.stringify(recentlyEditedRanges, null, 2)); + outcome = + await this.nextEditProvider.provideInlineCompletionItemsWithChain( + { + completionId, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + isUntitledFile: document.isUntitled, + recentlyVisitedRanges, + recentlyEditedRanges, + }, + signal, + ); + } } else { outcome = await this.completionProvider.provideInlineCompletionItems( input, @@ -308,30 +345,7 @@ export class ContinueCompletionProvider // ); if (!outcome || !outcome.completion) { - // TODO: At this point we assume that the user typed something "whole". - // AKA, the user's edit was good enough to start an edit chain. - // We actually started the chain before getting the outcome. This makes logical sense. - // Then all we need to do is to calculate next editable region. - // We also need to use the user's edits to create a user edits section in renderPrompt. - recentlyEditedRanges = - await this.recentlyEditedTracker.getRecentlyEditedRanges(); - console.log("two:", JSON.stringify(recentlyEditedRanges, null, 2)); - outcome = - await this.nextEditProvider.provideInlineCompletionItemsWithChain( - { - completionId, - manuallyPassFileContents, - manuallyPassPrefix, - selectedCompletionInfo, - isUntitledFile: document.isUntitled, - recentlyVisitedRanges, - recentlyEditedRanges, - }, - signal, - ); - if (!outcome || !outcome.completion) { - return null; - } + return null; } // VS Code displays dependent on selectedCompletionInfo (their docstring below) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index d0c4fdd5b..776c59843 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -43,7 +43,7 @@ import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider import { VsCodeMessenger } from "./VsCodeMessenger"; import { getAst } from "core/autocomplete/util/ast"; -import { DocumentAstTracker } from "core/nextEdit/DocumentAstTracker"; +import { DocumentAstTracker } from "core/nextEdit/DocumentHistoryTracker"; import { EditableRegionStrategy, getNextEditableRegion, @@ -383,7 +383,6 @@ export class VsCodeExtension { vscode.workspace.onDidOpenTextDocument(async (event) => { console.log("onDidOpenTextDocument"); const ast = await getAst(event.fileName, event.getText()); - console.log(ast === undefined); if (ast) { DocumentAstTracker.getInstance().addDocument( localPathOrUriToPath(event.fileName), From bc7ae7c7c74c7d709dee2f370643f50ec6374819 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 15:20:07 -0700 Subject: [PATCH 72/88] feat: handle declaration nodes separately --- .../NextEditEditableRegionCalculator.ts | 61 ++++++++++++++++++- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 74dc011ba..04c5247c3 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -1,7 +1,7 @@ import Parser from "web-tree-sitter"; import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; import { getAst } from "../autocomplete/util/ast"; -import { DocumentAstTracker } from "./DocumentAstTracker"; +import { DocumentAstTracker } from "./DocumentHistoryTracker"; export enum EditableRegionStrategy { Naive = "naive", @@ -431,6 +431,7 @@ function findClosestIdentifierNode( if (!node) return null; if (isIdentifierNode(node)) return node; + if (isDeclarationNode(node)) return findLeftmostIdentifier(node); // Check if the parent is an identifier. // NOTE: This will probably never get triggered. @@ -441,9 +442,12 @@ function findClosestIdentifierNode( } if (parent) { + if (isDeclarationNode(parent)) return findLeftmostIdentifier(parent); + // Check if one of the siblings is an identifier. for (let i = 0; i < parent.childCount; ++i) { - const sibling = node.child(i); + // const sibling = node.child(i); + const sibling = parent.child(i); if (sibling && isIdentifierNode(sibling)) { // Get the leftmost identifier sibling. return sibling; @@ -454,6 +458,22 @@ function findClosestIdentifierNode( return findClosestIdentifierNode(parent); } +function findLeftmostIdentifier( + node: Parser.SyntaxNode, +): Parser.SyntaxNode | null { + if (isIdentifierNode(node)) return node; + + for (let i = 0; i < node.childCount; ++i) { + const child = node.child(i); + if (child) { + const result = findLeftmostIdentifier(child); + if (result) return result; + } + } + + return null; +} + // Helper function to check if a node is an identifier. function isIdentifierNode(node: Parser.SyntaxNode) { const nodeType = node.type; @@ -468,6 +488,43 @@ function isIdentifierNode(node: Parser.SyntaxNode) { return specialIdentifiers.includes(nodeType); } +// Helper function to check if a node is a declaration. +function isDeclarationNode(node: Parser.SyntaxNode) { + const nodeType = node.type; + + // Common declaration patterns. + if (nodeType.endsWith("_declaration")) return true; + if (nodeType.endsWith("_definition")) return true; + if (nodeType.endsWith("_item")) return true; // Rust. + + // Language-specific patterns. + const declarationTypes = [ + // Python. + "function_definition", + "class_definition", + "async_function_definition", + "decorated_definition", + + // Ruby. + "method", + "class", + "module", + "singleton_method", + + // Java. + "variable_declarator", + "local_variable_declaration", + + // Go. + "short_var_declaration", + + // General + "method_definition", + ]; + + return declarationTypes.includes(nodeType); +} + // // Helper function to find the closest identifier node. // function findClosestIdentifierNode( // node: Parser.SyntaxNode | undefined, From cd8450f9d586c940a528e13ef711932b5de53963 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 25 Jul 2025 15:23:14 -0700 Subject: [PATCH 73/88] feat: await for deleteChain --- extensions/vscode/src/commands.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index ce69ea87b..01db39411 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -878,7 +878,7 @@ const getCommandsMap: ( if (isFim) { if (!fimText) { console.log("deleteChain from commands.ts: !fimText"); - NextEditProvider.getInstance().deleteChain(); + await NextEditProvider.getInstance().deleteChain(); } // For FIM edits, create an inline completion item. const nextEditCompletionItem = new vscode.InlineCompletionItem( @@ -914,7 +914,7 @@ const getCommandsMap: ( const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); if (diffLines.length === 0) { console.log("deleteChain from commands.ts: diffLines.length === 0"); - NextEditProvider.getInstance().deleteChain(); + await NextEditProvider.getInstance().deleteChain(); } if (NextEditWindowManager.isInstantiated()) { From e5708fcb822946ed3f1f2af025f20482c4e6f6eb Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 15:08:54 -0700 Subject: [PATCH 74/88] refactor: clean up --- .../NextEditEditableRegionCalculator.ts | 6 +- core/nextEdit/NextEditPrefetchQueue.ts | 135 --------- core/nextEdit/NextEditProvider.ts | 272 +----------------- .../templating/NextEditPromptEngine.ts | 124 ++++---- core/nextEdit/types.ts | 3 +- core/util/PrefetchQueue.ts | 86 ------ .../GhostTextAcceptanceTracker.ts | 94 +----- .../src/autocomplete/completionProvider.ts | 75 ++--- .../vscode/src/extension/VsCodeExtension.ts | 22 +- 9 files changed, 108 insertions(+), 709 deletions(-) delete mode 100644 core/nextEdit/NextEditPrefetchQueue.ts delete mode 100644 core/util/PrefetchQueue.ts diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 04c5247c3..a4dc04794 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -343,17 +343,15 @@ async function staticRerankJump(ctx: { // Static jump relies purely on static analysis // to determine where to edit next. async function staticJump(ctx: { - fileContent: string; cursorPosition: { line: number; character: number }; filepath: string; ide: IDE; }): Promise { try { - const { fileContent, cursorPosition, filepath, ide } = ctx; - if (!fileContent || !cursorPosition || !filepath || !ide) { + const { cursorPosition, filepath, ide } = ctx; + if (!cursorPosition || !filepath || !ide) { console.warn( "Missing required context for static jump:", - !fileContent, !cursorPosition, !filepath, !ide, diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts deleted file mode 100644 index 54a43bc29..000000000 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { ILLM, Position, RangeInFile } from ".."; -import { HelperVars } from "../autocomplete/util/HelperVars"; -import { findChangedLineRanges, myersDiff } from "../diff/myers"; -import { PrefetchQueue } from "../util/PrefetchQueue"; -import { applyCompletionToFile } from "./diff/diff"; -import { EditableRegionStrategy } from "./NextEditEditableRegionCalculator"; -import { NextEditOutcome } from "./types"; - -export class NextEditPrefetchQueue extends PrefetchQueue< - NextEditOutcome, - RangeInFile, - { - helper: HelperVars; - diffContext: string; - llm: ILLM; - token: AbortSignal; - startTime: number; - newCursorPos: Position; - editableRegionStrategy: EditableRegionStrategy; - } -> { - async initialize(): Promise { - const firstPromise = this.fetchFunction(undefined, undefined, this.other); - this.promiseQueue.push(firstPromise); - - const firstData = await firstPromise; - if (this.resourceQueue.length > 0) { - const resource = this.resourceQueue.shift()!; - const nextPromise = this.fetchFunction(firstData, resource, this.other); - this.promiseQueue.push(nextPromise); - } - - if (this.other?.editableRegionStrategy === EditableRegionStrategy.Naive) { - // Get the response from fetchFunction and compare with firstData to identify changed regions - const resource = - this.resourceQueue.length > 0 ? this.resourceQueue[0] : undefined; - const secondPromise = this.fetchFunction(firstData, resource, this.other); - const secondData = await secondPromise; - // console.log(secondData?.completion); - - // if (secondPromise) { - // Process this in the background - // secondPromise - // .then((secondData) => { - - if (firstData && secondData) { - // Use myersDiff to find differences between the two completions - // const firstCompletionLines = firstData.completion.split("\n"); - // const secondCompletionLines = secondData.completion.split("\n"); - - // TODO: this should be comparing old file and new file, not the completions. - // Compare the file after first completion is merged, - // and compare the file after first and second completion is merged. - const appliedFirst = applyCompletionToFile( - this.other.helper.fileContents, - firstData.completion, - firstData.editableRegionStartLine, - ); - // const appliedFirstAndSecond = applyCompletionToFile( - // appliedFirst, - // secondData.completion, - // secondData.editableRegionStartLine, - // ); - const diffLines = myersDiff(appliedFirst, secondData.completion); - - // Track chunks of differences - console.log(diffLines, appliedFirst, secondData.completion); - const changedLineRanges = findChangedLineRanges(diffLines); - changedLineRanges.forEach((change) => { - // Inclusive, zero-based line numbers. - const chunk = { - startLine: change.startLine, - endLine: change.endLine, - }; - console.log("chunk:", chunk); - const chunkOutcome: NextEditOutcome = { - ...firstData, - uniqueId: `${firstData.uniqueId}-chunk-${chunk.startLine}-${chunk.endLine}`, - editableRegionStartLine: chunk.startLine, - editableRegionEndLine: chunk.endLine, - }; - - this.promiseQueue.push(Promise.resolve(chunkOutcome)); - }); - } - } - } - - async pop(): Promise { - if (this.promiseQueue.length === 0) { - return undefined; - } - - if (this.other?.editableRegionStrategy === EditableRegionStrategy.Naive) { - // The queue should already be preloaded. - // We don't need to make extra calls to the model - // because we assume that the items already in the queue - // are the only items in this chain of edit. - const currentPromise = this.promiseQueue.shift()!; - - if (this.promiseQueue.length === 0) { - // NextEditProvider.currentEditChainId = null; - } - - return await currentPromise; - } - - // Get and remove the first promise from the queue - const currentPromise = this.promiseQueue.shift()!; - const currentData = await currentPromise; - - // If we have resources left, prefetch the next item - if (this.resourceQueue.length > 0) { - // Get the most recently added promise (now at the end of the queue) - const previousPromise = - this.promiseQueue.length > 0 - ? this.promiseQueue[this.promiseQueue.length - 1] - : Promise.resolve(currentData); - - // Create new promise based on the previous one and next resource - const resource = this.resourceQueue.shift()!; - const nextPromise = previousPromise.then((data) => - this.fetchFunction(data, resource, this.other), - ); - - this.promiseQueue.push(nextPromise); - } else if (this.promiseQueue.length === 0) { - // No more items in the queue and no more resources - // NextEditProvider.currentEditChainId = null; - } - - // console.log("currentData:", currentData); - return currentData; - } -} diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index b8512cd4e..f266b27bf 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,15 +1,7 @@ import * as path from "path"; import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { - BranchAndDir, - ChatMessage, - IDE, - ILLM, - Position, - Range, - RangeInFile, -} from "../index.js"; +import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; @@ -26,7 +18,6 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; -import { myersDiff } from "../diff/myers.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { @@ -34,17 +25,13 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; -import { - calculateFinalCursorPosition, - getOffsetPositionAtLastNewLine, -} from "./diff/diff.js"; +import { calculateFinalCursorPosition } from "./diff/diff.js"; import { DocumentAstTracker } from "./DocumentHistoryTracker.js"; import { EditableRegionStrategy, getNextEditableRegion, } from "./NextEditEditableRegionCalculator.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; -import { NextEditPrefetchQueue } from "./NextEditPrefetchQueue.js"; import { renderDefaultSystemPrompt, renderDefaultUserPrompt, @@ -56,7 +43,6 @@ import { PromptMetadata, RecentlyEditedRange, } from "./types.js"; -// import { renderPrompt } from "./templating/NextEditPromptEngine.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -81,8 +67,6 @@ export class NextEditProvider { private endpointType: "default" | "fineTuned"; private diffContext: string = ""; private promptMetadata: PromptMetadata | null = null; - private prefetchQueue: NextEditPrefetchQueue; - // private refQueue: RangeInFile[] = []; private currentEditChainId: string | null = null; private previousRequest: AutocompleteInput | null = null; private previousCompletions: NextEditOutcome[] = []; @@ -101,121 +85,6 @@ export class NextEditProvider { this.contextRetrievalService = new ContextRetrievalService(this.ide); this.endpointType = endpointType; this.loggingService = NextEditLoggingService.getInstance(); - - const fetchFunction = async ( - previousData: NextEditOutcome | undefined, - resource: RangeInFile | undefined, - other?: { - helper: HelperVars; - diffContext: string; - llm: ILLM; - token: AbortSignal; - startTime: number; - newCursorPos: Position; - editableRegionStrategy: EditableRegionStrategy; - }, - ) => { - if (!other) return undefined; - // console.log("previousData:", previousData?.completion); - // render prompt - // TODO: this has to set the editable region properly. - // console.log("fetchfunction - previousData:", previousData?.completion); - const promptMetadata = await renderPrompt( - other.helper, - other.diffContext, - other.editableRegionStrategy, - previousData, - resource, - ); - this.promptMetadata = promptMetadata; - // console.log("prompt:", promptMetadata.prompt); - // call llm.chat - const msg = await other.llm.chat([promptMetadata.prompt], other.token); - // built and return outcome - if (typeof msg.content === "string") { - if (msg.content === "") return undefined; - // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined - const nextCompletion = replaceEscapedCharacters( - msg.content.split("<|editable_region_start|>\n")[1], - ).replace(/\n$/, ""); - - const currCursorPos = other.helper.pos; - const editableRegionStartLine = Math.max( - currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - 0, - ); - const editableRegionEndLine = Math.min( - currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - other.helper.fileLines.length - 1, - ); - const oldEditRangeSlice = other.helper.fileContents - .split("\n") - .slice(editableRegionStartLine, editableRegionEndLine + 1) - .join("\n"); - - // How far away is the current line from the start of the editable region? - const lineOffsetAtCursorPos = - currCursorPos.line - editableRegionStartLine; - - // How long is the line at the current cursor position? - const newEditRangeSlice = nextCompletion; - const lineContentAtCursorPos = - newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; - - const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); - - const offset = getOffsetPositionAtLastNewLine( - diffLines, - lineContentAtCursorPos, - lineOffsetAtCursorPos, - ); - - // Calculate the actual line number in the editor by adding the startPos offset - // to the line number from the diff calculation. - const finalCursorPos: Position = { - line: editableRegionStartLine + offset.line, - character: offset.character, - }; - - // TODO: if editable region strategy is naive, then we need to split the prediction up into regions. Also potentially filling up the prefetch queue. - - const outcomeNext: NextEditOutcome = { - elapsed: Date.now() - other.startTime, - modelProvider: other.llm.underlyingProviderName, - modelName: other.llm.model + ":zetaDataset", - completionOptions: null, - // filepath: helper.filepath, - completionId: other.helper.input.completionId, - gitRepo: await this.ide.getRepoName(other.helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: other.helper.filepath, - workspaceDirUri: - other.helper.workspaceUris[0] ?? - path.dirname(other.helper.filepath), - fileContentsBeforeAccept: other.helper.fileContents, - prompt: this.promptMetadata!.prompt.content, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: oldEditRangeSlice, - completion: nextCompletion, - cursorPosition: other.helper.pos, - finalCursorPosition: finalCursorPos, - editableRegionStartLine, - editableRegionEndLine, - ...other.helper.options, - }; - return outcomeNext; - } else { - return undefined; - } - }; - - this.prefetchQueue = new NextEditPrefetchQueue( - fetchFunction, - [], - undefined, - ); } public static initialize( @@ -350,9 +219,9 @@ export class NextEditProvider { this.nextEditableRegionsInTheCurrentChain = []; if (this.previousRequest) { - const fileContent = - // await fs.readFile(localPathOrUriToPath(this.previousRequest.filepath) - (await this.ide.readFile(this.previousRequest.filepath)).toString(); + const fileContent = ( + await this.ide.readFile(this.previousRequest.filepath) + ).toString(); const ast = await getAst(this.previousRequest.filepath, fileContent); if (ast) { DocumentAstTracker.getInstance().pushAst( @@ -452,10 +321,8 @@ export class NextEditProvider { }); const promptMetadata = await renderPrompt( helper, - // this.diffContext, historyDiff ?? this.diffContext, EditableRegionStrategy.Naive, - // input.recentlyEditedRanges, ); this.promptMetadata = promptMetadata; @@ -509,7 +376,6 @@ export class NextEditProvider { fileUri: helper.filepath, workspaceDirUri: helper.workspaceUris[0] ?? path.dirname(helper.filepath), - fileContentsBeforeAccept: helper.fileContents, prompt: prompts.join("\n"), userEdits: "", userExcerpts: "", @@ -546,8 +412,6 @@ export class NextEditProvider { ).replace(/\n$/, "") : ""; - // this.previousCompletions.push(nextCompletion); - const currCursorPos = helper.pos; const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, @@ -566,7 +430,6 @@ export class NextEditProvider { helper.pos, editableRegionStartLine, oldEditRangeSlice, - // "", nextCompletion, ); @@ -583,7 +446,6 @@ export class NextEditProvider { fileUri: helper.filepath, workspaceDirUri: helper.workspaceUris[0] ?? path.dirname(helper.filepath), - fileContentsBeforeAccept: helper.fileContents, prompt: this.promptMetadata!.prompt.content, userEdits: this.promptMetadata!.userEdits, userExcerpts: this.promptMetadata!.userExcerpts, @@ -632,32 +494,18 @@ export class NextEditProvider { }, token: AbortSignal | undefined, ) { - // TODO: - // If we don't have a precomputed list of next editable regions already, compute it. - // Store this list as a class attribute. - // Pop the frontmost RangeInFile and use that to build an input. try { const previousOutcome = this.getPreviousCompletion(); if (!previousOutcome) { return undefined; } - // TODO: This is actually getting the contents after the user typed something. - // we need the file before the user has typed anything. - // console.log("previousOutcome:", previousOutcome.fileContentsBeforeAccept); - // console.log("previousCursorPosition:", previousOutcome.cursorPosition); - const fileContent = previousOutcome.fileContentsBeforeAccept; const filepath = localPathOrUriToPath(previousOutcome.fileUri); - console.log( - "number of next editable regions:", - this.nextEditableRegionsInTheCurrentChain.length, - ); + // If we don't have a precomputed list of next editable regions already, compute and load it. if (this.nextEditableRegionsInTheCurrentChain.length === 0) { - console.log("empty next editable regions list"); this.loadNextEditableRegionsInTheCurrentChain( (await getNextEditableRegion(EditableRegionStrategy.Static, { - fileContent, cursorPosition: previousOutcome.cursorPosition, filepath, ide: this.ide, @@ -670,6 +518,7 @@ export class NextEditProvider { } } + // Use the frontmost RangeInFile to build an input. const input = await this.buildAutocompleteInputFromChain( previousOutcome, this.nextEditableRegionsInTheCurrentChain[0], // this will be shifted after debouncer check @@ -715,117 +564,10 @@ export class NextEditProvider { } public loadNextEditableRegionsInTheCurrentChain(regions: RangeInFile[]) { - console.log("regions after load:", regions.length); this.nextEditableRegionsInTheCurrentChain = regions; } public shiftNextEditableRegionsInTheCurrentChain() { - console.log("shift", this.nextEditableRegionsInTheCurrentChain.length); this.nextEditableRegionsInTheCurrentChain.shift(); } - - public async provideNextEditPrediction( - input: AutocompleteInput, - token: AbortSignal | undefined, - ) { - try { - if (this.currentEditChainId) { - return await this.prefetchQueue.pop(); - } - - // Create abort signal if not given - if (!token) { - const controller = this.loggingService.createAbortController( - input.completionId, - ); - token = controller.signal; - } - 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; - } - - if (llm.promptTemplates?.autocomplete) { - options.template = llm.promptTemplates.autocomplete as string; - } - - const helper = await HelperVars.create( - input, - options, - llm.model, - this.ide, - ); - - if (await shouldPrefilter(helper, this.ide)) { - return undefined; - } - - // this.currentEditChainId = randomUUID(); - - this.prefetchQueue.loadOther({ - helper, - diffContext: this.diffContext, - llm, - token, - startTime, - newCursorPos: helper.pos, - editableRegionStrategy: EditableRegionStrategy.Naive, - }); - - const [snippetPayload, workspaceDirs] = await Promise.all([ - getAllSnippetsWithoutRace({ - helper, - ide: this.ide, - getDefinitionsFromLsp: this.getDefinitionsFromLsp, - contextRetrievalService: this.contextRetrievalService, - }), - this.ide.getWorkspaceDirs(), - ]); - - // TODO: Get the references. - const refQueue = await this.ide.getReferences({ - filepath: helper.filepath, - position: helper.pos, - }); - - const { config } = await this.configHandler.loadConfig(); - const branches = await Promise.all( - workspaceDirs.map((dir) => this.ide.getBranch(dir)), - ); - const tags: BranchAndDir[] = workspaceDirs.map((directory, i) => ({ - directory, - branch: branches[i], - })); - // const chunks = await getTopRelevantCodeChunks( - // ` add(number) { - // this.result += number; - // return this; - // }`, - // { - // ide: this.ide, - // llm: llm, - // config: config!, - // tags: tags, - // // filterDirectory: getUriPathBasename(helper.workspaceUris[0]), - // }, - // ); - // console.log("chunks:", JSON.stringify(chunks, null, 2)); - - this.prefetchQueue.loadResource(refQueue); - await this.prefetchQueue.initialize(); - return await this.prefetchQueue.pop(); - } catch (e: any) { - this.onError(e); - } finally { - this.loggingService.deleteAbortController(input.completionId); - } - } } diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 01a18ac7f..d6cd8dacf 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -9,11 +9,7 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; -import { createDiff, DiffFormatType } from "../context/diffFormatting"; -import { - EditableRegionStrategy, - getNextEditableRegion, -} from "../NextEditEditableRegionCalculator"; +import { EditableRegionStrategy } from "../NextEditEditableRegionCalculator"; import { NextEditOutcome, NextEditTemplate, @@ -94,67 +90,67 @@ export async function renderPrompt( // TODO: apply prevOutcome to existing content. we will need the line range. // Also display the diff between existing content and applied content. // NOTE: This only runs in fetchFunction. - if (prevOutcome) { - // console.log("renderPrompt prevOutcome:", prevOutcome.completion); - // console.log( - // "beforeInsert:", - // helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), - // ); - // console.log("toInsert: ", prevOutcome?.completion.split("\n")); - // console.log( - // "afterInsert:", - // helper.fileLines.slice(prevOutcome?.editableRegionEndLine), - // ); - let appliedContent = [ - ...helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), - ...(prevOutcome?.completion.split("\n") ?? []), - ...helper.fileLines.slice(prevOutcome?.editableRegionEndLine), - ]; - // console.log("helper.fileContents:", helper.fileContents); - // NOTE: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. - // The individual parts don't contain this. - // console.log("appliedContent:", appliedContent); - appliedContent = appliedContent.filter( - (line) => !line.includes(USER_CURSOR_IS_HERE_TOKEN), - ); - // Given a previous response, we need to calculate where the cursor would be. - // I think it's a good idea to calculate this in the response. + // if (prevOutcome) { + // // console.log("renderPrompt prevOutcome:", prevOutcome.completion); + // // console.log( + // // "beforeInsert:", + // // helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), + // // ); + // // console.log("toInsert: ", prevOutcome?.completion.split("\n")); + // // console.log( + // // "afterInsert:", + // // helper.fileLines.slice(prevOutcome?.editableRegionEndLine), + // // ); + // let appliedContent = [ + // ...helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), + // ...(prevOutcome?.completion.split("\n") ?? []), + // ...helper.fileLines.slice(prevOutcome?.editableRegionEndLine), + // ]; + // // console.log("helper.fileContents:", helper.fileContents); + // // NOTE: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. + // // The individual parts don't contain this. + // // console.log("appliedContent:", appliedContent); + // appliedContent = appliedContent.filter( + // (line) => !line.includes(USER_CURSOR_IS_HERE_TOKEN), + // ); + // // Given a previous response, we need to calculate where the cursor would be. + // // I think it's a good idea to calculate this in the response. - // TODO: handle cases where there are more than one next editable region. - // NOTE: we might set it so that we receive the next editable region as an argument. - const editableRegion = await getNextEditableRegion(editableRegionStrategy, { - fileLines: appliedContent, - filepath: helper.filepath, - }); + // // TODO: handle cases where there are more than one next editable region. + // // NOTE: we might set it so that we receive the next editable region as an argument. + // const editableRegion = await getNextEditableRegion(editableRegionStrategy, { + // fileLines: appliedContent, + // filepath: helper.filepath, + // }); - // console.log("appliedContent:", appliedContent); - // console.log("startLine:", editableRegion?.range.start.line); - editedCodeWithTokens = insertTokens( - appliedContent, - prevOutcome.finalCursorPosition, - editableRegion && editableRegion[0]?.range.start.line !== undefined - ? editableRegion[0].range.start.line - : undefined, - editableRegion && editableRegion[0]?.range.end.line !== undefined - ? editableRegion[0].range.end.line - : undefined, - ); - // console.log("new editedCodeWithTokens:", editedCodeWithTokens); - userEdits = createDiff({ - beforeContent: helper.fileContents, - afterContent: appliedContent.join("\n"), - filePath: helper.filepath, - diffType: DiffFormatType.Unified, - contextLines: 3, - }); - userEdits = userEdits.replace(USER_CURSOR_IS_HERE_TOKEN, ""); - // console.log("new userDiff:", userEdits); - } else { - editedCodeWithTokens = insertTokens( - helper.fileContents.split("\n"), - helper.pos, - ); - } + // // console.log("appliedContent:", appliedContent); + // // console.log("startLine:", editableRegion?.range.start.line); + // editedCodeWithTokens = insertTokens( + // appliedContent, + // prevOutcome.finalCursorPosition, + // editableRegion && editableRegion[0]?.range.start.line !== undefined + // ? editableRegion[0].range.start.line + // : undefined, + // editableRegion && editableRegion[0]?.range.end.line !== undefined + // ? editableRegion[0].range.end.line + // : undefined, + // ); + // // console.log("new editedCodeWithTokens:", editedCodeWithTokens); + // userEdits = createDiff({ + // beforeContent: helper.fileContents, + // afterContent: appliedContent.join("\n"), + // filePath: helper.filepath, + // diffType: DiffFormatType.Unified, + // contextLines: 3, + // }); + // userEdits = userEdits.replace(USER_CURSOR_IS_HERE_TOKEN, ""); + // // console.log("new userDiff:", userEdits); + // } else { + editedCodeWithTokens = insertTokens( + helper.fileContents.split("\n"), + helper.pos, + ); + // } const tv: TemplateVars = { userEdits, diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index e4ae1f328..26e2b156a 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -47,10 +47,9 @@ export interface NextEditOutcome extends TabAutocompleteOptions { // New for Next Edit. fileUri: string; workspaceDirUri: string; - fileContentsBeforeAccept: string; prompt: string; userEdits: string; - userExcerpts: string; // For now, this is the same as fileContentsBeforeAccept, but that assumption should not be relied on. + userExcerpts: string; originalEditableRange: string; completion: string; cursorPosition: { line: number; character: number }; diff --git a/core/util/PrefetchQueue.ts b/core/util/PrefetchQueue.ts deleted file mode 100644 index 91a240dcc..000000000 --- a/core/util/PrefetchQueue.ts +++ /dev/null @@ -1,86 +0,0 @@ -export class PrefetchQueue { - protected promiseQueue: Promise[] = []; - protected resourceQueue: R[]; - protected other: O | undefined; - protected fetchFunction: ( - previousData: T | undefined, - resource: R | undefined, - other: O | undefined, - ) => Promise; - - constructor( - fetchFunction: ( - previousData: T | undefined, - resource: R | undefined, - other: O | undefined, - ) => Promise, - resources: R[], - other: O | undefined, - ) { - this.fetchFunction = fetchFunction; - this.resourceQueue = [...resources]; - this.other = other; - } - - loadResource(resources: R[]) { - this.resourceQueue = [...this.resourceQueue, ...resources]; - } - - loadOther(other: O) { - this.other = other; - } - - async initialize(): Promise { - // Get the first response (no resource needed) - const firstPromise = this.fetchFunction(undefined, undefined, this.other); - this.promiseQueue.push(firstPromise); - - // Prefetch the next item using the first resource - const firstData = await firstPromise; - if (this.resourceQueue.length > 0) { - const resource = this.resourceQueue.shift()!; - const nextPromise = this.fetchFunction(firstData, resource, this.other); - this.promiseQueue.push(nextPromise); - } - } - - async pop(): Promise { - if (this.promiseQueue.length === 0) { - return undefined; - } - - // Get and remove the first promise from the queue - const currentPromise = this.promiseQueue.shift()!; - const currentData = await currentPromise; - - // If we have resources left, prefetch the next item - if (this.resourceQueue.length > 0) { - // Get the most recently added promise (now at the end of the queue) - const previousPromise = - this.promiseQueue.length > 0 - ? this.promiseQueue[this.promiseQueue.length - 1] - : Promise.resolve(currentData); - - // Create new promise based on the previous one and next resource - const resource = this.resourceQueue.shift()!; - const nextPromise = previousPromise.then((data) => - this.fetchFunction(data, resource, this.other), - ); - - this.promiseQueue.push(nextPromise); - } else if (this.promiseQueue.length === 0) { - // No more items in the queue and no more resources - } - - console.log("currentData:", currentData); - return currentData; - } - - hasNext(): boolean { - return this.promiseQueue.length > 0; - } - - getRemainingResourceCount(): number { - return this.resourceQueue.length; - } -} diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts index 610a3c7fe..f40047c4f 100644 --- a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -1,83 +1,3 @@ -// export class CompletionAcceptanceTracker { -// private static instance: CompletionAcceptanceTracker; -// private acceptedCompletionIds: Set = new Set(); - -// static getInstance(): CompletionAcceptanceTracker { -// if (!CompletionAcceptanceTracker.instance) { -// CompletionAcceptanceTracker.instance = new CompletionAcceptanceTracker(); -// } -// return CompletionAcceptanceTracker.instance; -// } - -// markGhostTextAccepted(completionId: string) { -// this.acceptedCompletionIds.add(completionId); - -// // Keep a reasonable history size -// if (this.acceptedCompletionIds.size > 1) { -// // Remove the oldest item (using the fact that Sets maintain insertion order) -// const oldestId = this.acceptedCompletionIds.values().next().value; -// if (oldestId) { -// this.acceptedCompletionIds.delete(oldestId); -// } -// } -// } - -// wasCompletionAccepted(completionId: string): boolean { -// return this.acceptedCompletionIds.has(completionId); -// } - -// // Add a method to check if the most recent completion was accepted -// wasRecentCompletionAccepted(): boolean { -// return this.acceptedCompletionIds.size > 0; -// } -// } -// In completionAcceptanceTracker.ts -// export class CompletionAcceptanceTracker { -// private static instance: CompletionAcceptanceTracker; -// private acceptedCompletionIds: Set = new Set(); -// private currentCompletionId: string | null = null; - -// static getInstance(): CompletionAcceptanceTracker { -// if (!CompletionAcceptanceTracker.instance) { -// CompletionAcceptanceTracker.instance = new CompletionAcceptanceTracker(); -// } -// return CompletionAcceptanceTracker.instance; -// } - -// setCurrentCompletionId(completionId: string) { -// this.currentCompletionId = completionId; -// } - -// markGhostTextAccepted(completionId: string) { -// console.log("mark"); -// this.acceptedCompletionIds.add(completionId); - -// // Keep a reasonable history size -// if (this.acceptedCompletionIds.size > 1) { -// // Remove the oldest item (using the fact that Sets maintain insertion order) -// const oldestId = this.acceptedCompletionIds.values().next().value; -// if (oldestId) { -// this.acceptedCompletionIds.delete(oldestId); -// } -// } -// } - -// wasCompletionAccepted(completionId: string): boolean { -// return this.acceptedCompletionIds.has(completionId); -// } - -// isCurrentCompletionAccepted(): boolean { -// return ( -// this.currentCompletionId !== null && -// this.acceptedCompletionIds.has(this.currentCompletionId) -// ); -// } - -// clearCurrentCompletionId() { -// this.currentCompletionId = null; -// } -// } -// New file: extensions/vscode/src/activation/GhostTextAcceptanceTracker.ts import * as vscode from "vscode"; export interface ExpectedGhostTextAcceptance { @@ -142,26 +62,26 @@ export class GhostTextAcceptanceTracker { ): boolean { if (!this.expectedAcceptance) return false; - // Check document match + // Check document match. if (this.expectedAcceptance.documentUri !== document.uri.toString()) { return false; } - // Check document version (must be newer) + // Check document version (must be newer). if (document.version <= this.expectedAcceptance.documentVersion) { return false; } - // Check if cursor is at expected end position + // Check if cursor is at expected end position. const expectedEndPos = new vscode.Position( this.expectedAcceptance.endLine, this.expectedAcceptance.endCharacter, ); if (newPosition.isEqual(expectedEndPos)) { - // The cursor is where we'd expect after accepting the ghost text + // The cursor is where we'd expect after accepting the ghost text. - // Verify text was inserted (optional additional check) + // Verify text was inserted (optional additional check). const startPos = new vscode.Position( this.expectedAcceptance.startLine, this.expectedAcceptance.startCharacter, @@ -174,12 +94,12 @@ export class GhostTextAcceptanceTracker { const actualText = document.getText(actualRange); if (actualText === expectedText) { - // Clear the expectation + // Clear the expectation. this.expectedAcceptance = null; return true; } } catch (error) { - // Range might be invalid, just fall through + // Range might be invalid, just fall through. } } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 4919377c9..5e22b5c7e 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -5,8 +5,6 @@ import { type AutocompleteOutcome, } from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; -// import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants"; -// import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -72,8 +70,6 @@ export class ContinueCompletionProvider public recentlyVisitedRanges: RecentlyVisitedRangesService; public recentlyEditedTracker: RecentlyEditedTracker; - private oldFileContent: string = ""; - private isNextEditActive: boolean = false; public activateNextEdit() { @@ -140,14 +136,6 @@ export class ContinueCompletionProvider token: vscode.CancellationToken, //@ts-ignore ): ProviderResult { - console.log("================================================"); - console.log( - "editor.inlineSuggest.enabled:", - vscode.workspace - .getConfiguration() - .get("editor.inlineSuggest.enabled"), - ); - // console.log("trigger!!", token.isCancellationRequested); const enableTabAutocomplete = getStatusBarStatus() === StatusBarStatus.Enabled; if (token.isCancellationRequested || !enableTabAutocomplete) { @@ -247,15 +235,9 @@ export class ContinueCompletionProvider const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets(); let recentlyEditedRanges = await this.recentlyEditedTracker.getRecentlyEditedRanges(); - // console.log("one:", JSON.stringify(recentlyEditedRanges, null, 2)); - console.log( - this.nextEditProvider.chainExists() - ? "chain is alive" - : "chain is not alive", - ); if (this.nextEditProvider.chainExists()) { - // If the user has accepted the previous completion, the chain of edits is alive. + // The chain of edits is alive because the user has accepted the previous completion. // Get the next editable region and set the pos to be within that range. outcome = await this.nextEditProvider.provideInlineCompletionItemsWithChain( @@ -288,6 +270,7 @@ export class ContinueCompletionProvider }; setupStatusBar(undefined, true); + // Check if editChainId exists or needs to be refreshed. if (this.isNextEditActive) { outcome = await this.nextEditProvider.provideInlineCompletionItems( @@ -295,17 +278,16 @@ export class ContinueCompletionProvider signal, false, ); - console.log("outcome.completion:"); - console.log(outcome?.completion); + if (!outcome || !outcome.completion) { - // TODO: At this point we assume that the user typed something "whole". - // AKA, the user's edit was good enough to start an edit chain. - // We actually started the chain before getting the outcome. This makes logical sense. - // Then all we need to do is to calculate next editable region. + // Hitting this condition means that the model could not predict a next edit action. + // That happens when the user's recent edit is good enough, or if the model is totally lost. + // At this point we assume that the user typed something good enough to maintain a chain of edits. + // All we need to do here is to calculate next editable region. // We also need to use the user's edits to create a user edits section in renderPrompt. recentlyEditedRanges = await this.recentlyEditedTracker.getRecentlyEditedRanges(); - // console.log("two:", JSON.stringify(recentlyEditedRanges, null, 2)); + outcome = await this.nextEditProvider.provideInlineCompletionItemsWithChain( { @@ -321,6 +303,7 @@ export class ContinueCompletionProvider ); } } else { + // Handle autocomplete request. outcome = await this.completionProvider.provideInlineCompletionItems( input, signal, @@ -329,21 +312,8 @@ export class ContinueCompletionProvider } } - this.oldFileContent = document.getText(); - - // TODO: fix type of outcome to be a union between NextEditOutcome and AutocompleteOutcome. - // const outcome: AutocompleteOutcome | NextEditOutcome | undefined = this - // .isNextEditActive - // ? await this.nextEditProvider.provideInlineCompletionItems( - // input, - // signal, - // ) - // : await this.completionProvider.provideInlineCompletionItems( - // input, - // signal, - // wasManuallyTriggered, - // ); - + // If the model cannot predict a completion or a next edit, + // then it's safe to assume that there are no more changes to be made. if (!outcome || !outcome.completion) { return null; } @@ -374,8 +344,8 @@ export class ContinueCompletionProvider return null; } - // Marking the outcome as displayed saves - // the current outcome as a value of the key completionId. + // Marking the outcome as displayed saves the current outcome + // as a value of the key completionId. if (this.isNextEditActive) { this.nextEditProvider.markDisplayed( completionId, @@ -394,7 +364,6 @@ export class ContinueCompletionProvider let range = new vscode.Range(startPos, startPos); let completionText = outcome.completion; - // NOTE: This seems like an autocomplete logic. const isSingleLineCompletion = outcome.completion.split("\n").length <= 1; if (isSingleLineCompletion) { @@ -445,14 +414,14 @@ export class ContinueCompletionProvider const currCursorPos = editor.selection.active; if (this.isNextEditActive) { - console.log(this.nextEditProvider.getChain().length); - if (!this.nextEditProvider.isStartOfChain()) { const jumpPosition = new vscode.Position( (outcome as NextEditOutcome).editableRegionStartLine, 0, ); + // Suggest a jump if there is a valid next location. + // This will set isJumpInProgress if a jump is suggested. await this.jumpManager.suggestJump( currCursorPos, jumpPosition, @@ -461,7 +430,7 @@ export class ContinueCompletionProvider // If a jump was just suggested, don't show ghost text yet. if (this.jumpManager.isJumpInProgress()) { - // Store this completion for later use when jump is complete. + // Store this completion to be rendered after jump is complete. this.jumpManager.setCompletionAfterJump({ completionId: completionId, outcome: outcome as NextEditOutcome, @@ -516,8 +485,6 @@ export class ContinueCompletionProvider newEditRangeSlice, relativeCursorPos, ); - console.log("isFim:", isFim); - console.log("fimText:", fimText); if (isFim) { if (!fimText) { @@ -526,9 +493,12 @@ export class ContinueCompletionProvider return undefined; } - // const completionId = input.completionId; - // Track this ghost text for acceptance detection. + // Ghost text acceptance can *technically* be acted upon in + // the command handler for "continue.logNextEditOutcomeAccept", + // but there is a substantial delay between accepting and logging, + // which introduces a lot of race conditions with different event handlers. + // Plus, separating these concerns seems to make sense logically as well. GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance( document, fimText, @@ -544,10 +514,9 @@ export class ContinueCompletionProvider { title: "Log Next Edit Outcome", command: "continue.logNextEditOutcomeAccept", - arguments: [completionId, this.nextEditLoggingService], // TODO: this may have to be this.completionProvider. + arguments: [completionId, this.nextEditLoggingService], }, ); - console.log(nextEditCompletionItem); return [nextEditCompletionItem]; } diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 776c59843..94bf619df 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -419,20 +419,15 @@ export class VsCodeExtension { } }); - // TODO: check if next edit provider's chain id is cleared properly. // Listen for editor changes to clean up decorations when editor closes. vscode.window.onDidChangeVisibleTextEditors(async () => { // If our active editor is no longer visible, clear decorations. - // console.log( - // "deleteChain from VsCodeExtension.ts: onDidChangeVisibleTextEditors", - // ); await NextEditProvider.getInstance().deleteChain(); }); // Listen for selection changes to hide tooltip when cursor moves. vscode.window.onDidChangeTextEditorSelection(async (e) => { - // console.log("move detected"); - // Don't delete the chain if: + // Don't delete the chain of edits if: // 1. A next edit window was just accepted. if ( @@ -461,21 +456,22 @@ export class VsCodeExtension { } // 4. The selection change is part of a typing session - // Check if this selection change is close enough to a document change to be considered typing + // Check if this selection change is close enough to a document change to be considered typing. const timeSinceLastDocChange = Date.now() - this.lastDocumentChangeTime; - if (this.isTypingSession && timeSinceLastDocChange < 500) { - // This selection change is likely due to typing, don't delete the chain + const ARBITRARY_TYPING_DELAY = 500; + if ( + this.isTypingSession && + timeSinceLastDocChange < ARBITRARY_TYPING_DELAY + ) { + // This selection change is likely due to typing, don't delete the chain. return; } // Otherwise, delete the chain (for rejection or unrelated movement). - console.log( - "deleteChain from VsCodeExtension.ts: onDidChangeTextEditorSelection", - ); await NextEditProvider.getInstance().deleteChain(); + NextEditProvider.getInstance().loadNextEditableRegionsInTheCurrentChain( (await getNextEditableRegion(EditableRegionStrategy.Static, { - fileContent: e.textEditor.document.getText(), cursorPosition: e.selections[0].anchor, filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), ide: this.ide, From f68bf5759ff9d2bc4ed49392c66bae2f5bf47543 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 15:34:51 -0700 Subject: [PATCH 75/88] refactor: clean up --- .../pipelines/BaseRetrievalPipeline.ts | 6 - .../pipelines/NextEditRetrievalPipeline.ts | 7 -- core/nextEdit/DocumentHistoryTracker.ts | 103 +++--------------- .../NextEditEditableRegionCalculator.ts | 4 +- core/nextEdit/NextEditProvider.ts | 6 +- .../GhostTextAcceptanceTracker.ts | 9 ++ .../vscode/src/extension/VsCodeExtension.ts | 4 +- 7 files changed, 32 insertions(+), 107 deletions(-) diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 617240410..f5d8a89f6 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -189,12 +189,6 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); return []; } - // if (!this.lanceDbIndex) { - // console.warn( - // "LanceDB index not available, skipping embeddings retrieval", - // ); - // return []; - // } return this.lanceDbIndex.retrieve( input, diff --git a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts index 515eb9bc8..b95aa0a6b 100644 --- a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts @@ -242,10 +242,3 @@ export function cosineSimilarity(a: number[], b: number[]): number { return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)); } - -// export async function getJumpDestinations( -// codeSnippet: string, -// cursorPosition: Position, -// filepath: string, -// ): Promise { -// } diff --git a/core/nextEdit/DocumentHistoryTracker.ts b/core/nextEdit/DocumentHistoryTracker.ts index 1bbdc98b7..34ea763bf 100644 --- a/core/nextEdit/DocumentHistoryTracker.ts +++ b/core/nextEdit/DocumentHistoryTracker.ts @@ -1,59 +1,38 @@ -// TODO: -// Create a DocumentAstTracker singleton class that keeps track of a map of document paths to their history of ASTs. -// There should be a map from document path to history of ASTs (a LIFO stack of ASTs where the newest AST is at the front) -// We want to expose these methods: -// add document and its first AST -// push to an existing document's AST history stack -// get the most recent AST of an existing document's AST -// The AST and nodes will be using web-tree-sitter types. -// save map to file as a documentAstTracker.json inside the user's global continue path -// delete document from map -// clear map -import * as fs from "fs"; -import * as path from "path"; import Parser from "web-tree-sitter"; -import { getContinueGlobalPath } from "../util/paths"; /** - * Singleton class that keeps track of a map of document paths to their history of ASTs. + * Singleton class that keeps track of a map of document paths to their history. + * The point here is to prevent re-calculating the AST, + * and to preserve an older, original state of the document before any user edits. */ -export class DocumentAstTracker { - private static instance: DocumentAstTracker | null = null; +export class DocumentHistoryTracker { + private static instance: DocumentHistoryTracker | null = null; - // Map from document path to history of ASTs (LIFO stack where newest AST is at the front). + // Map from document path to history (LIFO stack where newest representation is at the front). private documentAstMap: Map; private documentContentHistoryMap: Map; - // Path to save the AST tracker data. - private readonly savePath: string; - private constructor() { this.documentAstMap = new Map(); this.documentContentHistoryMap = new Map(); - this.savePath = path.join( - getContinueGlobalPath(), - "documentAstTracker.jsonl", - ); - - // Try to load existing data. - // this.loadFromFile(); } /** - * Get the singleton instance of DocumentAstTracker. + * Get the singleton instance of DocumentHistoryTracker. */ - public static getInstance(): DocumentAstTracker { - if (!DocumentAstTracker.instance) { - DocumentAstTracker.instance = new DocumentAstTracker(); + public static getInstance(): DocumentHistoryTracker { + if (!DocumentHistoryTracker.instance) { + DocumentHistoryTracker.instance = new DocumentHistoryTracker(); } - return DocumentAstTracker.instance; + return DocumentHistoryTracker.instance; } /** - * Add a document and its first AST to the tracker. + * Add a document and its first state to the tracker. * * @param documentPath The path of the document. + * @param documentContent The first content of the document. * @param ast The first AST of the document. */ public addDocument( @@ -63,17 +42,17 @@ export class DocumentAstTracker { ): void { this.documentAstMap.set(documentPath, [ast]); this.documentContentHistoryMap.set(documentPath, [documentContent]); - // this.saveToFile(); } /** * Push a new AST to an existing document's history stack. * * @param documentPath The path of the document. + * @param documentContent The new content to push to the document's history stack. * @param ast The new AST to push to the document's history stack. * @throws Error if the document doesn't exist in the tracker. */ - public pushAst( + public push( documentPath: string, documentContent: string, ast: Parser.Tree, @@ -86,12 +65,9 @@ export class DocumentAstTracker { this.addDocument(documentPath, documentContent, ast); } - console.log("same AST:", this.getMostRecentAst(documentPath) !== ast); - - // Add the new AST to the front of the array (LIFO stack). + // Push to top (LIFO). astHistory!.unshift(ast); documentHistory!.unshift(documentContent); - // this.saveToFile(); } /** @@ -148,7 +124,6 @@ export class DocumentAstTracker { public deleteDocument(documentPath: string): void { this.documentAstMap.delete(documentPath); this.documentContentHistoryMap.delete(documentPath); - // this.saveToFile(); } /** @@ -157,51 +132,5 @@ export class DocumentAstTracker { public clearMap(): void { this.documentAstMap.clear(); this.documentContentHistoryMap.clear(); - // this.saveToFile(); - } - - /** - * Save the current state of the tracker to a file. - */ - private saveToFile(): void { - try { - // We can't directly serialize Tree objects to JSON. - // So we'll just save the paths - this serves as a record of which documents we're tracking. - // The actual ASTs will need to be recreated when needed. - const documentPaths = Array.from(this.documentAstMap.keys()); - const serializableData = { documentPaths }; - - fs.writeFileSync( - this.savePath, - JSON.stringify(serializableData, null, 2), - ); - } catch (error) { - console.error("Error saving AST tracker data to file:", error); - } - } - - /** - * Load the tracker state from a file. - */ - private loadFromFile(): void { - try { - if (fs.existsSync(this.savePath)) { - const fileContent = fs.readFileSync(this.savePath, "utf-8"); - const data = JSON.parse(fileContent); - - // We only saved the paths, not the actual Trees. - // The Trees need to be reparsed when the documents are loaded again. - if (data && data.documentPaths) { - // Initialize empty arrays for each document. - data.documentPaths.forEach((path: string) => { - this.documentAstMap.set(path, []); - }); - } - } - } catch (error) { - console.error("Error loading AST tracker data from file:", error); - // If loading fails, we'll start with an empty map. - this.documentAstMap = new Map(); - } } } diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index a4dc04794..7f5d13b66 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -1,7 +1,7 @@ import Parser from "web-tree-sitter"; import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; import { getAst } from "../autocomplete/util/ast"; -import { DocumentAstTracker } from "./DocumentHistoryTracker"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; export enum EditableRegionStrategy { Naive = "naive", @@ -362,7 +362,7 @@ async function staticJump(ctx: { // Get the file's AST. // Getting this once helps us live-track the current node. const tree = - await DocumentAstTracker.getInstance().getMostRecentAst(filepath); + await DocumentHistoryTracker.getInstance().getMostRecentAst(filepath); // const tree = await getAst(filepath, fileContent); if (!tree) return null; diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index f266b27bf..3af145859 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -26,7 +26,7 @@ import { } from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { calculateFinalCursorPosition } from "./diff/diff.js"; -import { DocumentAstTracker } from "./DocumentHistoryTracker.js"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; import { EditableRegionStrategy, getNextEditableRegion, @@ -224,7 +224,7 @@ export class NextEditProvider { ).toString(); const ast = await getAst(this.previousRequest.filepath, fileContent); if (ast) { - DocumentAstTracker.getInstance().pushAst( + DocumentHistoryTracker.getInstance().push( localPathOrUriToPath(this.previousRequest.filepath), fileContent, ast, @@ -311,7 +311,7 @@ export class NextEditProvider { } else { const historyDiff = createDiff({ beforeContent: - DocumentAstTracker.getInstance().getMostRecentDocumentHistory( + DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( localPathOrUriToPath(helper.filepath), ) ?? "", afterContent: helper.fileContents, diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts index f40047c4f..a72c67202 100644 --- a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -10,6 +10,15 @@ export interface ExpectedGhostTextAcceptance { endCharacter: number; } +/** + * This singleton tracks whether a given ghost text is accepted or not. + * We need this because there is no clean way of determining if a ghost text has been accepted outside of vscode command callback. + * The above mentioned callback is not viable because it's too slow. + * We need a way to reject model predictions on cursor movement, but cursor can move due to many reasons -- one being accepting a ghost text. + * We need to differentiate the ghost text acceptance from a deliberate cursor movement to reject the completion. + * The cursor movement event listener fires much before the vscode command callback, so the chain of edits often breaks when cursor moves due to accepting a ghost text. + * This is not what we want, as we want to keep the current chain of edits alive when the user accepts the completion. + */ export class GhostTextAcceptanceTracker { private static instance: GhostTextAcceptanceTracker | undefined; private expectedAcceptance: ExpectedGhostTextAcceptance | null = null; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 94bf619df..c32ecfc9c 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -43,7 +43,7 @@ import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider import { VsCodeMessenger } from "./VsCodeMessenger"; import { getAst } from "core/autocomplete/util/ast"; -import { DocumentAstTracker } from "core/nextEdit/DocumentHistoryTracker"; +import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker"; import { EditableRegionStrategy, getNextEditableRegion, @@ -384,7 +384,7 @@ export class VsCodeExtension { console.log("onDidOpenTextDocument"); const ast = await getAst(event.fileName, event.getText()); if (ast) { - DocumentAstTracker.getInstance().addDocument( + DocumentHistoryTracker.getInstance().addDocument( localPathOrUriToPath(event.fileName), event.getText(), ast, From 4c94fd84464b2bc1b7ff22ba298f256c34ebf62a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 15:42:16 -0700 Subject: [PATCH 76/88] refactor: cleanup --- core/nextEdit/NextEditProvider.ts | 14 ++-- .../templating/NextEditPromptEngine.ts | 67 +------------------ 2 files changed, 11 insertions(+), 70 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 3af145859..b431f0503 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -71,7 +71,6 @@ export class NextEditProvider { private previousRequest: AutocompleteInput | null = null; private previousCompletions: NextEditOutcome[] = []; private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; - // TODO: keep track of the last completion request (at least the file path it came from) private constructor( private readonly configHandler: ConfigHandler, @@ -305,6 +304,7 @@ export class NextEditProvider { // TODO: Toggle between the default endpoint and the finetuned endpoint. const prompts: Prompt[] = []; + if (this.endpointType === "default") { prompts.push(renderDefaultSystemPrompt()); prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); @@ -319,11 +319,12 @@ export class NextEditProvider { diffType: DiffFormatType.Unified, contextLines: 3, }); + const promptMetadata = await renderPrompt( helper, historyDiff ?? this.diffContext, - EditableRegionStrategy.Naive, ); + this.promptMetadata = promptMetadata; prompts.push({ @@ -336,6 +337,7 @@ export class NextEditProvider { "If the user has made a change, make sure you respect that and try to apply it to other parts of the code that used to use the old content.", ].join("\n"), }); + prompts.push(promptMetadata.prompt); } @@ -343,10 +345,12 @@ export class NextEditProvider { helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0, ); + const editableRegionEndLine = Math.min( helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, helper.fileLines.length - 1, ); + const oldEditRangeSlice = helper.fileContents .split("\n") .slice(editableRegionStartLine, editableRegionEndLine + 1) @@ -361,6 +365,7 @@ export class NextEditProvider { if (this.endpointType === "default") { const msg: ChatMessage = await llm.chat(prompts, token); + if (typeof msg.content === "string") { const nextCompletion = JSON.parse(msg.content).newCode; const outcomeNext: NextEditOutcome = { @@ -368,7 +373,6 @@ export class NextEditProvider { modelProvider: llm.underlyingProviderName, modelName: llm.model + ":zetaDataset", completionOptions: null, - // filepath: helper.filepath, completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), @@ -413,14 +417,17 @@ export class NextEditProvider { : ""; const currCursorPos = helper.pos; + const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0, ); + const editableRegionEndLine = Math.min( currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, helper.fileLines.length - 1, ); + const oldEditRangeSlice = helper.fileContents .split("\n") .slice(editableRegionStartLine, editableRegionEndLine + 1) @@ -438,7 +445,6 @@ export class NextEditProvider { modelProvider: llm.underlyingProviderName, modelName: llm.model + ":zetaDataset", completionOptions: null, - // filepath: helper.filepath, completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index d6cd8dacf..bad3f5166 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -1,5 +1,5 @@ import Handlebars from "handlebars"; -import { Position, RangeInFile } from "../.."; +import { Position } from "../.."; import { SnippetPayload } from "../../autocomplete/snippets"; import { HelperVars } from "../../autocomplete/util/HelperVars"; import { @@ -9,9 +9,7 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; -import { EditableRegionStrategy } from "../NextEditEditableRegionCalculator"; import { - NextEditOutcome, NextEditTemplate, PromptMetadata, SystemPrompt, @@ -51,9 +49,6 @@ function templateRendererOfModel( export async function renderPrompt( helper: HelperVars, userEdits: string, - editableRegionStrategy: EditableRegionStrategy, - prevOutcome?: NextEditOutcome, - toApply?: RangeInFile, ): Promise { let modelName = helper.modelName as NextEditModelName; @@ -87,70 +82,10 @@ export async function renderPrompt( const renderer = templateRendererOfModel(modelName); let editedCodeWithTokens = ""; - // TODO: apply prevOutcome to existing content. we will need the line range. - // Also display the diff between existing content and applied content. - // NOTE: This only runs in fetchFunction. - // if (prevOutcome) { - // // console.log("renderPrompt prevOutcome:", prevOutcome.completion); - // // console.log( - // // "beforeInsert:", - // // helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), - // // ); - // // console.log("toInsert: ", prevOutcome?.completion.split("\n")); - // // console.log( - // // "afterInsert:", - // // helper.fileLines.slice(prevOutcome?.editableRegionEndLine), - // // ); - // let appliedContent = [ - // ...helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), - // ...(prevOutcome?.completion.split("\n") ?? []), - // ...helper.fileLines.slice(prevOutcome?.editableRegionEndLine), - // ]; - // // console.log("helper.fileContents:", helper.fileContents); - // // NOTE: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. - // // The individual parts don't contain this. - // // console.log("appliedContent:", appliedContent); - // appliedContent = appliedContent.filter( - // (line) => !line.includes(USER_CURSOR_IS_HERE_TOKEN), - // ); - // // Given a previous response, we need to calculate where the cursor would be. - // // I think it's a good idea to calculate this in the response. - - // // TODO: handle cases where there are more than one next editable region. - // // NOTE: we might set it so that we receive the next editable region as an argument. - // const editableRegion = await getNextEditableRegion(editableRegionStrategy, { - // fileLines: appliedContent, - // filepath: helper.filepath, - // }); - - // // console.log("appliedContent:", appliedContent); - // // console.log("startLine:", editableRegion?.range.start.line); - // editedCodeWithTokens = insertTokens( - // appliedContent, - // prevOutcome.finalCursorPosition, - // editableRegion && editableRegion[0]?.range.start.line !== undefined - // ? editableRegion[0].range.start.line - // : undefined, - // editableRegion && editableRegion[0]?.range.end.line !== undefined - // ? editableRegion[0].range.end.line - // : undefined, - // ); - // // console.log("new editedCodeWithTokens:", editedCodeWithTokens); - // userEdits = createDiff({ - // beforeContent: helper.fileContents, - // afterContent: appliedContent.join("\n"), - // filePath: helper.filepath, - // diffType: DiffFormatType.Unified, - // contextLines: 3, - // }); - // userEdits = userEdits.replace(USER_CURSOR_IS_HERE_TOKEN, ""); - // // console.log("new userDiff:", userEdits); - // } else { editedCodeWithTokens = insertTokens( helper.fileContents.split("\n"), helper.pos, ); - // } const tv: TemplateVars = { userEdits, From 885654ede28c53dc89701044d38febe1ade761f3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 15:53:14 -0700 Subject: [PATCH 77/88] test: add vitest for GhostTextAcceptanceTracker --- .../GhostTextAcceptanceTracker.vitest.ts | 246 ++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts new file mode 100644 index 000000000..18a1b80ff --- /dev/null +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts @@ -0,0 +1,246 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; +import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker"; + +// Mock the vscode module +vi.mock("vscode", () => ({ + Position: vi.fn((line: number, character: number) => ({ + line, + character, + isEqual: vi.fn( + (other: any) => other.line === line && other.character === character, + ), + })), + Range: vi.fn((start: any, end: any) => ({ start, end })), +})); + +describe("GhostTextAcceptanceTracker", () => { + let tracker: GhostTextAcceptanceTracker; + let mockDocument: vscode.TextDocument; + + beforeEach(() => { + // Clear any existing instance + GhostTextAcceptanceTracker.clearInstance(); + tracker = GhostTextAcceptanceTracker.getInstance(); + + // Create mock document + mockDocument = { + uri: { + toString: () => "file:///test.ts", + }, + version: 1, + getText: vi.fn(), + } as any; + }); + + describe("getInstance", () => { + it("should return the same instance when called multiple times", () => { + const instance1 = GhostTextAcceptanceTracker.getInstance(); + const instance2 = GhostTextAcceptanceTracker.getInstance(); + expect(instance1).toBe(instance2); + }); + + it("should create a new instance after clearInstance is called", () => { + const instance1 = GhostTextAcceptanceTracker.getInstance(); + GhostTextAcceptanceTracker.clearInstance(); + const instance2 = GhostTextAcceptanceTracker.getInstance(); + expect(instance1).not.toBe(instance2); + }); + }); + + describe("setExpectedGhostTextAcceptance", () => { + it("should set expected acceptance for single line text", () => { + const startPosition = new vscode.Position(5, 10); + const text = "console.log('hello')"; + + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + + // Verify internal state by testing checkGhostTextWasAccepted. + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(text), + } as any; + const endPosition = new vscode.Position(5, 30); // 10 in startPosition + 20 characters in text + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + + it("should set expected acceptance for multi-line text", () => { + const startPosition = new vscode.Position(5, 10); + const text = "function test() {\n return 'hello';\n}"; + + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + + // For multi-line, end position should be at line 7 (5 + 3 lines - 1), character 1 (length of last line). + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(text), + } as any; + const endPosition = new vscode.Position(7, 1); + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + }); + + describe("checkGhostTextWasAccepted", () => { + beforeEach(() => { + const startPosition = new vscode.Position(5, 10); + const text = "console.log('test')"; + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + }); + + it("should return false when no expected acceptance is set", () => { + GhostTextAcceptanceTracker.clearInstance(); + const newTracker = GhostTextAcceptanceTracker.getInstance(); + + const newDocument = { ...mockDocument, version: 2 } as any; + const position = new vscode.Position(5, 29); + + expect(newTracker.checkGhostTextWasAccepted(newDocument, position)).toBe( + false, + ); + }); + + it("should return false when document URI doesn't match", () => { + const differentDocument = { + ...mockDocument, + uri: { toString: () => "file:///different.ts" }, + version: 2, + } as any; + const position = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(differentDocument, position), + ).toBe(false); + }); + + it("should return false when document version is not newer", () => { + const sameVersionDocument = { + ...mockDocument, + version: 1, // same version + } as any; + const position = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(sameVersionDocument, position), + ).toBe(false); + + const olderVersionDocument = { + ...mockDocument, + version: 0, // older version + } as any; + + expect( + tracker.checkGhostTextWasAccepted(olderVersionDocument, position), + ).toBe(false); + }); + + it("should return false when cursor position doesn't match expected end position", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue("console.log('test')"), + } as any; + const wrongPosition = new vscode.Position(5, 20); // wrong position + + expect( + tracker.checkGhostTextWasAccepted(newDocument, wrongPosition), + ).toBe(false); + }); + + it("should return false when text content doesn't match", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue("different text"), // wrong text + } as any; + const correctPosition = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should return true when all conditions match and clear expectation", () => { + const expectedText = "console.log('test')"; + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(expectedText), + } as any; + const correctPosition = new vscode.Position(5, 29); // 10 + 19 characters + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(true); + + // Check for clearing logic. + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should handle getText throwing an error gracefully", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockImplementation(() => { + throw new Error("Range invalid"); + }), + } as any; + const correctPosition = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should work with multi-line ghost text acceptance", () => { + const startPosition = new vscode.Position(0, 0); + const multiLineText = "if (condition) {\n doSomething();\n}"; + tracker.setExpectedGhostTextAcceptance( + mockDocument, + multiLineText, + startPosition, + ); + + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(multiLineText), + } as any; + const endPosition = new vscode.Position(2, 1); // line 2, character 1 (length of "}") + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + + it("should handle empty text", () => { + const startPosition = new vscode.Position(10, 5); + const emptyText = ""; + tracker.setExpectedGhostTextAcceptance( + mockDocument, + emptyText, + startPosition, + ); + + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(""), + } as any; + const samePosition = new vscode.Position(10, 5); // should be same as start for empty text + + expect(tracker.checkGhostTextWasAccepted(newDocument, samePosition)).toBe( + true, + ); + }); + }); +}); From f93a18e390b0c7302844f46f14697ff5d556eba3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 16:46:22 -0700 Subject: [PATCH 78/88] feat: pass end line --- extensions/vscode/src/commands.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 01db39411..2ffd24418 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -925,6 +925,7 @@ const getCommandsMap: ( editor, currentPosition, editableRegionStartLine, + editableRegionEndLine, oldEditRangeSlice, newEditRangeSlice, diffLines, From a265cbd5cbf9767adcf035e1373cc33df7baaea6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 16:47:41 -0700 Subject: [PATCH 79/88] chore: bump version --- binary/package-lock.json | 3 ++- core/package-lock.json | 15 ++++++++++++--- extensions/vscode/package-lock.json | 4 ++-- package-lock.json | 2 +- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/binary/package-lock.json b/binary/package-lock.json index 11dd6505b..85ce515a1 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -77,6 +77,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -90,7 +91,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.76.0", + "openai": "^4.104.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", diff --git a/core/package-lock.json b/core/package-lock.json index d2afa4b76..8dfc3a735 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -38,6 +38,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -169,15 +170,16 @@ }, "../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.0.45", + "version": "1.1.1", "license": "Apache-2.0", "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.15", + "@continuedev/fetch": "^1.0.16", "dotenv": "^16.5.0", + "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.104.0", @@ -185,13 +187,20 @@ "zod": "^3.24.2" }, "devDependencies": { + "@semantic-release/changelog": "^6.0.3", + "@semantic-release/commit-analyzer": "^13.0.1", + "@semantic-release/git": "^10.0.1", + "@semantic-release/github": "^11.0.3", + "@semantic-release/npm": "^12.0.2", + "@semantic-release/release-notes-generator": "^14.0.3", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.14", "@types/json-schema": "^7.0.15", "cross-env": "^7.0.3", + "semantic-release": "^24.2.7", "ts-jest": "^29.2.3", "ts-node": "^10.9.2", - "vitest": "^1.6.1" + "vitest": "^3.2.4" } }, "node_modules/@75lb/deep-merge": { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 0f419444a..7b50769d1 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.68", + "version": "1.1.69", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.68", + "version": "1.1.69", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/package-lock.json b/package-lock.json index 0a2538840..b4289d422 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "wt-openai-adapters-tests", + "name": "continue", "lockfileVersion": 3, "requires": true, "packages": { From 0d8bd09d86adb1e754de00124fb851f9a7da0e8f Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 17:06:30 -0700 Subject: [PATCH 80/88] feat: add lsp method types --- core/config/types.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/config/types.ts b/core/config/types.ts index b880d1157..b9be2b209 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -743,6 +743,8 @@ declare global { // LSP gotoDefinition(location: Location): Promise; + gotoTypeDefinition(location: Location): Promise; + getSignatureHelp(location: Location): Promise; getReferences(location: Location): Promise; getDocumentSymbols(textDocumentIdentifier: string): Promise; From 182bd11f6be021d0d8b5eaf14a9567416d182cac Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 17:09:26 -0700 Subject: [PATCH 81/88] refactor: remove unused code --- .../pipelines/NextEditRetrievalPipeline.ts | 244 ------------------ 1 file changed, 244 deletions(-) delete mode 100644 core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts diff --git a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts b/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts deleted file mode 100644 index b95aa0a6b..000000000 --- a/core/context/retrieval/pipelines/NextEditRetrievalPipeline.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { - BranchAndDir, - Chunk, - ContinueConfig, - IDE, - ILLM, - Position, -} from "../../.."; -import BaseRetrievalPipeline, { - RetrievalPipelineRunArguments, -} from "./BaseRetrievalPipeline"; - -export default class NextEditRetrievalPipeline extends BaseRetrievalPipeline { - async run(args: RetrievalPipelineRunArguments): Promise { - if (args.includeEmbeddings) { - await this.ensureLanceDbInitialized(); - } - - // Try each retrieval method. - // Embeddings can fail if query.execute() goes wrong. - const embeddingPromise = async () => { - if (!args.includeEmbeddings) return []; - try { - return await this.retrieveEmbeddings( - args.query, - this.options.nRetrieve, - ); - } catch (error) { - console.error("Error retrieving embeddings:", error); - return []; - } - }; - - const ftsPromise = async () => { - try { - return await this.retrieveFts(args, this.options.nRetrieve); - } catch (error) { - console.error("Error retrieving from full-text search:", error); - return []; - } - }; - - const recentFilesPromise = async () => { - try { - return await this.retrieveAndChunkRecentlyEditedFiles( - this.options.nRetrieve, - ); - } catch (error) { - console.error("Error retrieving recently edited files:", error); - return []; - } - }; - - const toolsPromise = async () => { - try { - return await this.retrieveWithTools(args.query); - } catch (error) { - console.error("Error retrieving with tools:", error); - return []; - } - }; - - const [embeddingChunks, ftsChunks, recentChunks, toolChunks] = - await Promise.all([ - embeddingPromise(), - ftsPromise(), - recentFilesPromise(), - toolsPromise(), - ]); - - // console.log(`Retrieved chunks: ${embeddingChunks.length} from embeddings, ${ftsChunks.length} from FTS, ${recentChunks.length} from recent - // files, ${toolChunks.length} from tools`); - - let allChunks = [ - ...embeddingChunks, - ...ftsChunks, - ...recentChunks, - ...toolChunks, - ]; - - // Remove duplicates by digest. - const uniqueDigests = new Set(); - const uniqueChunks = allChunks.filter((chunk) => { - if (uniqueDigests.has(chunk.digest)) { - return false; - } - uniqueDigests.add(chunk.digest); - return true; - }); - - // If we have too many chunks and embedding retrieval is available, - // prioritize chunks from embedding search as they're likely more semantically relevant. - if ( - uniqueChunks.length > this.options.nFinal && - embeddingChunks.length > 0 - ) { - // First include embedding chunks (most semantically relevant). - const result: Chunk[] = [...embeddingChunks]; - - // Then add unique chunks from other sources until we reach nFinal. - const remainingChunks = uniqueChunks.filter( - (chunk) => !embeddingChunks.some((ec) => ec.digest === chunk.digest), - ); - - result.push( - ...remainingChunks.slice(0, this.options.nFinal - result.length), - ); - - return result.slice(0, this.options.nFinal); - } - - // Otherwise just return the unique chunks up to nFinal. - return uniqueChunks.slice(0, this.options.nFinal); - } -} - -export async function getTopRelevantCodeChunks( - codeSnippet: string, - options: { - ide: IDE; - llm: ILLM; - config: ContinueConfig; - tags: BranchAndDir[]; - filterDirectory?: string; - }, -): Promise { - try { - const retrievalPipeline = new NextEditRetrievalPipeline({ - llm: options.llm, - config: options.config, - ide: options.ide, - input: codeSnippet, - nRetrieve: 10, // retrieve more initially for better filtering - nFinal: 5, // return top 5 - tags: options.tags, - filterDirectory: options.filterDirectory, - }); - - const chunks = await retrievalPipeline.run({ - query: codeSnippet, - tags: options.tags, - filterDirectory: options.filterDirectory, - includeEmbeddings: !options.config.experimental?.codebaseToolCallingOnly, - }); - - return chunks; - } catch (error) { - console.error("Error getting relevant code chunks:", error); - return []; - } -} - -export async function retrieveRelevantSnippetsInFile( - query: string, - filepath: string, - cursorPosition: Position, - maxSnippets: number = 5, - snippetSize: number = 10, // lines per snippet - ide: IDE, -): Promise { - try { - const fileContent = await ide.readFile(filepath); - const lines = fileContent.split("\n"); - - // Create smaller overlapping chunks around the cursor position. - const chunks: Chunk[] = []; - const totalLines = lines.length; - - // If file is too small, skip chunking. - // Ideally we want to keep the chunk size smaller for jump purposes. - if (totalLines <= snippetSize * 2) { - return []; - } - - // Use sliding window to create chunks in the file. - // Make sure to overlap the window while sliding. - for ( - let startLine = 0; - startLine < totalLines - snippetSize; - startLine += Math.floor(snippetSize / 2) - ) { - // Skip the chunk that contains the cursor. - // NOTE: We might just include it. - if ( - startLine <= cursorPosition.line && - cursorPosition.line < startLine + snippetSize - ) { - continue; - } - - const endLine = Math.min(startLine + snippetSize - 1, totalLines - 1); - const content = lines.slice(startLine, endLine + 1).join("\n"); - - chunks.push({ - content, - startLine, - endLine, - digest: `${filepath}:${startLine}-${endLine}`, - filepath, - index: chunks.length, - }); - } - - // Calculate relevance score for each chunk. - // For now, we use simple keyword matching - // In the future we should use embeddings or cosine similarity. - const keywords = query - .toLowerCase() - .split(/\s+/) - .filter((k) => k.length > 2); - - const scoredChunks = chunks.map((chunk) => { - const lowerContent = chunk.content.toLowerCase(); - const score = keywords.reduce((sum, keyword) => { - return sum + (lowerContent.includes(keyword) ? 1 : 0); - }, 0); - - return { chunk, score }; - }); - - // Sort by score desc. - return scoredChunks - .sort((a, b) => b.score - a.score) - .slice(0, maxSnippets) - .map((sc) => sc.chunk); - } catch (error) { - console.error("Error finding relevant in-file snippets:", error); - return []; - } -} - -export function cosineSimilarity(a: number[], b: number[]): number { - let dotProduct = 0; - let normA = 0; - let normB = 0; - - for (let i = 0; i < a.length; i++) { - dotProduct += a[i] * b[i]; - normA += a[i] * a[i]; - normB += b[i] * b[i]; - } - - return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)); -} From 526deee862d81dddf43a0bb40ff2a3e987de21e3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 17:10:45 -0700 Subject: [PATCH 82/88] refactor: remove unused code --- core/diff/myers.ts | 135 --------------------------------------------- 1 file changed, 135 deletions(-) diff --git a/core/diff/myers.ts b/core/diff/myers.ts index 9d4ea1740..b39ddccf3 100644 --- a/core/diff/myers.ts +++ b/core/diff/myers.ts @@ -209,138 +209,3 @@ export function myersCharDiff( return result; } - -export interface ChangeRange { - startLine: number; - endLine: number; - changeType: "deletion" | "addition" | "modification"; -} - -export function findChangedLineRanges( - diffLines: DiffLine[], - // oldCodeBlock: string, - // newCodeBlock: string, -): ChangeRange[] { - const changes: ChangeRange[] = []; - let oldLineNumber = 0; - let newLineNumber = 0; - let currentChangeStart: number | null = null; - let currentChangeType: "deletion" | "addition" | "modification" | null = null; - - for (let i = 0; i < diffLines.length; i++) { - const line = diffLines[i]; - - if (line.type === "same") { - // If we were tracking a change, close it - if (currentChangeStart !== null) { - changes.push({ - startLine: currentChangeStart, - endLine: oldLineNumber - 1, - changeType: currentChangeType!, - }); - currentChangeStart = null; - currentChangeType = null; - } - - // Both old and new advance for 'same' lines - oldLineNumber++; - newLineNumber++; - } else if (line.type === "old") { - // Start tracking change if not already - if (currentChangeStart === null) { - currentChangeStart = oldLineNumber; - currentChangeType = "deletion"; - } - - // Check if this is part of a modification (old followed by new) - if (currentChangeType === "deletion") { - // Look ahead to see if there are 'new' lines following - let hasNewLines = false; - for (let j = i + 1; j < diffLines.length; j++) { - if (diffLines[j].type === "new") { - hasNewLines = true; - break; - } else if (diffLines[j].type === "same") { - break; - } - } - if (hasNewLines) { - currentChangeType = "modification"; - } - } - - oldLineNumber++; - } else if (line.type === "new") { - // Start tracking change if not already - if (currentChangeStart === null) { - currentChangeStart = oldLineNumber; - currentChangeType = "addition"; - } - - // If we were tracking deletions, this becomes a modification - if (currentChangeType === "deletion") { - currentChangeType = "modification"; - } - - newLineNumber++; - } - } - - // Close any remaining change - if (currentChangeStart !== null) { - changes.push({ - startLine: currentChangeStart, - endLine: oldLineNumber - 1, - changeType: currentChangeType!, - }); - } - - return changes; -} - -// Alternative simpler approach if you just want deletion/modification ranges -export function findChangedLineRangesSimple( - diffLines: DiffLine[], -): ChangeRange[] { - const changes: ChangeRange[] = []; - let oldLineNumber = 0; - let currentChangeStart: number | null = null; - - for (const line of diffLines) { - if (line.type === "same") { - // Close any current change - if (currentChangeStart !== null) { - changes.push({ - startLine: currentChangeStart, - endLine: oldLineNumber - 1, - changeType: "modification", - }); - currentChangeStart = null; - } - oldLineNumber++; - } else if (line.type === "old") { - // Start change if not already started - if (currentChangeStart === null) { - currentChangeStart = oldLineNumber; - } - oldLineNumber++; - } else if (line.type === "new") { - // Start change if not already started (for pure additions) - if (currentChangeStart === null) { - currentChangeStart = oldLineNumber; - } - // Don't increment oldLineNumber for 'new' lines - } - } - - // Close any remaining change - if (currentChangeStart !== null) { - changes.push({ - startLine: currentChangeStart, - endLine: oldLineNumber - 1, - changeType: "modification", - }); - } - - return changes; -} From 2011603e93912d00c278c377a68de1dc6f071028 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 19:35:12 -0700 Subject: [PATCH 83/88] fix: skip next edit e2e for now --- .../vscode/e2e/tests/{NextEdit.test.ts => NextEdit.test.skip.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename extensions/vscode/e2e/tests/{NextEdit.test.ts => NextEdit.test.skip.ts} (100%) diff --git a/extensions/vscode/e2e/tests/NextEdit.test.ts b/extensions/vscode/e2e/tests/NextEdit.test.skip.ts similarity index 100% rename from extensions/vscode/e2e/tests/NextEdit.test.ts rename to extensions/vscode/e2e/tests/NextEdit.test.skip.ts From 0485aa1f287cbeb61103f63dd9504970b1f89f56 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 09:52:45 -0700 Subject: [PATCH 84/88] fix: merge --- .../vscode/e2e/tests/NextEdit.test.skip.ts | 124 ------------------ 1 file changed, 124 deletions(-) diff --git a/extensions/vscode/e2e/tests/NextEdit.test.skip.ts b/extensions/vscode/e2e/tests/NextEdit.test.skip.ts index cff31239a..e33767fd9 100644 --- a/extensions/vscode/e2e/tests/NextEdit.test.skip.ts +++ b/extensions/vscode/e2e/tests/NextEdit.test.skip.ts @@ -1,125 +1,14 @@ import { expect } from "chai"; -<<<<<<< HEAD -import * as fs from "fs/promises"; -======= ->>>>>>> 3592cd40b2ab16b4d066503e7d42c0672b19a9ae import { EditorView, TextEditor } from "vscode-extension-tester"; import { GlobalActions } from "../actions/Global.actions"; import { NextEditActions } from "../actions/NextEdit.actions"; import { DEFAULT_TIMEOUT } from "../constants"; -<<<<<<< HEAD -import { TestUtils } from "../TestUtils"; -======= ->>>>>>> 3592cd40b2ab16b4d066503e7d42c0672b19a9ae describe("Next Edit", () => { let editor: TextEditor; before(async function () { -<<<<<<< HEAD - // this.timeout(DEFAULT_TIMEOUT.XL); - - const globalContextPath = TestUtils.getGlobalContextFilePath(); - - // Update config.json to add optInNextEditFeature. - // globalContext.json does not exist in CI before this test runs. - if (await TestUtils.fileExists(globalContextPath)) { - const globalContext = await fs.readFile(globalContextPath, "utf8"); - const sharedConfig = JSON.parse(globalContext).sharedConfig; - - const sharedConfigWithNextEditEnabled = { - ...sharedConfig, - optInNextEditFeature: true, - }; - - const globalContextWithNextEditEnabled = { - ...JSON.parse(globalContext), - sharedConfig: sharedConfigWithNextEditEnabled, - }; - - await fs.writeFile( - globalContextPath, - JSON.stringify(globalContextWithNextEditEnabled, null, 2), - "utf8", - ); - } else { - await fs.writeFile( - globalContextPath, - JSON.stringify( - { - sharedConfig: { - optInNextEditFeature: true, - }, - selectedModelsByProfileId: { - local: { - chat: "TEST LLM", - edit: "TEST LLM", - apply: "TEST LLM", - embed: "Transformers.js (Built-In)", - autocomplete: "TEST LLM", - rerank: null, - summarize: null, - }, - }, - }, - null, - 2, - ), - ); - } - - await NextEditActions.reload(); - }).timeout(DEFAULT_TIMEOUT.XL); - - beforeEach(async function () { - // this.timeout(DEFAULT_TIMEOUT.XL); - - await GlobalActions.openTestWorkspace(); - ({ editor } = await GlobalActions.createAndOpenNewTextFile()); - }).timeout(DEFAULT_TIMEOUT.XL); - - afterEach(async function () { - // this.timeout(DEFAULT_TIMEOUT.XL); - - await editor.clearText(); - await new EditorView().closeAllEditors(); - }).timeout(DEFAULT_TIMEOUT.XL); - - after(async function () { - // this.timeout(DEFAULT_TIMEOUT.XL); - - // Update config.json to delete optInNextEditFeature. - const globalContext = await fs.readFile( - TestUtils.getGlobalContextFilePath(), - "utf8", - ); - const sharedConfig = JSON.parse(globalContext).sharedConfig; - - const sharedConfigWithoutNextEdit = { ...sharedConfig }; - delete sharedConfigWithoutNextEdit.optInNextEditFeature; - - const globalContextWithNextEditEnabled = { - ...JSON.parse(globalContext), - sharedConfig: sharedConfigWithoutNextEdit, - }; - - await fs.writeFile( - TestUtils.getGlobalContextFilePath(), - JSON.stringify(globalContextWithNextEditEnabled, null, 2), - "utf8", - ); - await NextEditActions.reload(); - }).timeout(DEFAULT_TIMEOUT.XL); - - // it("Should enable Next Edit feature in settings", async () => { - // expect(false).to.be.true; - // }).timeout(DEFAULT_TIMEOUT.XL); - - // it("Should check that autocomplete is disabled when next edit is enabled", async () => { - // expect(false).to.be.true; - // }).timeout(DEFAULT_TIMEOUT.XL); -======= process.env.NEXT_EDIT_TEST_ENABLED = "true"; }); @@ -140,32 +29,19 @@ describe("Next Edit", () => { after(async function () { process.env.NEXT_EDIT_TEST_ENABLED = "false"; }); ->>>>>>> 3592cd40b2ab16b4d066503e7d42c0672b19a9ae it("Should force a Next Edit", async () => { const hasDecoration = await NextEditActions.forceNextEdit(editor); expect(hasDecoration).to.be.true; -<<<<<<< HEAD - }).timeout(DEFAULT_TIMEOUT.XXL); -======= }).timeout(DEFAULT_TIMEOUT.XL); ->>>>>>> 3592cd40b2ab16b4d066503e7d42c0672b19a9ae it("Should accept Next Edit suggestion with Tab", async () => { const accepted = await NextEditActions.acceptNextEditSuggestion(editor); expect(accepted).to.be.true; -<<<<<<< HEAD - }).timeout(DEFAULT_TIMEOUT.XXL); -======= }).timeout(DEFAULT_TIMEOUT.XL); ->>>>>>> 3592cd40b2ab16b4d066503e7d42c0672b19a9ae it("Should reject Next Edit suggestion with Esc", async () => { const rejected = await NextEditActions.rejectNextEditSuggestion(editor); expect(rejected).to.be.true; -<<<<<<< HEAD - }).timeout(DEFAULT_TIMEOUT.XXL); -======= }).timeout(DEFAULT_TIMEOUT.XL); ->>>>>>> 3592cd40b2ab16b4d066503e7d42c0672b19a9ae }); From 87d35f175137212dfc8d8500514a4c9b7d4434c8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 14:47:18 -0700 Subject: [PATCH 85/88] test: add vitest for JumpManager --- .../src/activation/JumpManager.vitest.ts | 458 ++++++++++++++++++ 1 file changed, 458 insertions(+) create mode 100644 extensions/vscode/src/activation/JumpManager.vitest.ts diff --git a/extensions/vscode/src/activation/JumpManager.vitest.ts b/extensions/vscode/src/activation/JumpManager.vitest.ts new file mode 100644 index 000000000..3a74f479b --- /dev/null +++ b/extensions/vscode/src/activation/JumpManager.vitest.ts @@ -0,0 +1,458 @@ +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { NextEditOutcome } from "core/nextEdit/types"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; +import { CompletionDataForAfterJump, JumpManager } from "./JumpManager"; + +// Mock VSCode API +vi.mock("vscode", () => { + return { + window: { + createTextEditorDecorationType: vi.fn(() => ({ + dispose: vi.fn(), + })), + activeTextEditor: { + document: { + lineAt: vi.fn((line) => ({ + text: "Test line content", + lineNumber: line, + })), + lineCount: 10, + }, + setDecorations: vi.fn(), + selection: { active: { line: 0, character: 0 } }, + revealRange: vi.fn(), + visibleRanges: [{ start: { line: 0 }, end: { line: 5 } }], + }, + onDidChangeTextEditorSelection: vi.fn(() => ({ + dispose: vi.fn(), + })), + }, + commands: { + executeCommand: vi.fn(), + registerCommand: vi.fn(() => ({ + dispose: vi.fn(), + })), + }, + Position: class { + line: number; + character: number; + constructor(line: number, character: number) { + this.line = line; + this.character = character; + } + isEqual(other: any): boolean { + return this.line === other.line && this.character === other.character; + } + }, + Range: class { + start: any; + end: any; + constructor( + startLine: number, + startChar: number, + endLine: number, + endChar: number, + ) { + this.start = { line: startLine, character: startChar }; + this.end = { line: endLine, character: endChar }; + } + }, + Selection: class { + anchor: any; + active: any; + constructor(anchor: any, active: any) { + this.anchor = anchor; + this.active = active; + } + }, + TextEditorDecorationType: class { + dispose: () => void; + constructor() { + this.dispose = vi.fn(); + } + }, + TextEditorRevealType: { + InCenter: "inCenter", + }, + ThemeColor: class { + id: string; + constructor(id: string) { + this.id = id; + } + }, + }; +}); + +// Mock NextEditProvider +vi.mock("core/nextEdit/NextEditProvider", () => { + const mockDeleteChain = vi.fn(); + const mockGetInstance = vi.fn(() => ({ + deleteChain: mockDeleteChain, + })); + + return { + NextEditProvider: { + getInstance: mockGetInstance, + }, + }; +}); + +const createMockNextEditOutcome = ( + overrides: Partial = {}, +): NextEditOutcome => { + return { + // TabAutocompleteOptions properties + disable: false, + maxPromptTokens: 2048, + debounceDelay: 300, + modelTimeout: 5000, + maxSuffixPercentage: 0.5, + prefixPercentage: 0.8, + transform: true, + template: "default", + multilineCompletions: "auto", + slidingWindowPrefixPercentage: 0.5, + slidingWindowSize: 100, + useCache: true, + onlyMyCode: false, + useRecentlyEdited: true, + useRecentlyOpened: true, + disableInFiles: [".env", "node_modules/**"], + useImports: true, + showWhateverWeHaveAtXMs: 2000, + experimental_includeClipboard: true, + experimental_includeRecentlyVisitedRanges: true, + experimental_includeRecentlyEditedRanges: true, + experimental_includeDiff: true, + experimental_enableStaticContextualization: false, + // Base properties + elapsed: 1500, + modelProvider: "openai", + modelName: "gpt-4", + completionOptions: { + temperature: 0.7, + max_tokens: 1000, + }, + completionId: "comp_12345abcde", + uniqueId: "ne_67890fghij", + timestamp: Date.now(), + gitRepo: "continuedev/continue", + + // NextEdit specific properties + fileUri: "file:///workspace/project/src/main.ts", + workspaceDirUri: "file:///workspace/project", + prompt: "Add error handling to this function", + userEdits: "// I added a try/catch block", + userExcerpts: "function example() { ... }", + originalEditableRange: "function example() {\n return fetch(url);\n}", + completion: + "function example() {\n try {\n return fetch(url);\n } catch (error) {\n console.error('Fetch failed:', error);\n throw error;\n }\n}", + cursorPosition: { line: 2, character: 10 }, + finalCursorPosition: { line: 4, character: 5 }, + accepted: true, + editableRegionStartLine: 1, + editableRegionEndLine: 3, + + // Apply any overrides + ...overrides, + }; +}; + +describe("JumpManager", () => { + let jumpManager: JumpManager; + + beforeEach(() => { + // Reset mocks + vi.resetAllMocks(); + + // Clear any existing instance + JumpManager.clearInstance(); + + // Get a fresh instance + jumpManager = JumpManager.getInstance(); + }); + + afterEach(() => { + jumpManager.dispose(); + }); + + describe("getInstance", () => { + it("should return the same instance on multiple calls", () => { + const instance1 = JumpManager.getInstance(); + const instance2 = JumpManager.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("clearInstance", () => { + it("should dispose the current instance and clear it", () => { + const instance = JumpManager.getInstance(); + const disposeSpy = vi.spyOn(instance, "dispose"); + + JumpManager.clearInstance(); + + expect(disposeSpy).toHaveBeenCalled(); + + // Get a new instance + const newInstance = JumpManager.getInstance(); + expect(newInstance).not.toBe(instance); + }); + }); + + describe("suggestJump", () => { + it("should set jumpInProgress to true", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(3, 0); + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + expect(jumpManager.isJumpInProgress()).toBe(true); + }); + + it("should not suggest jump if completion content matches document content", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(3, 0); + const completionContent = "Test line content"; + + // Mock document content to match the completion content + vscode.window.activeTextEditor!.document.lineAt = vi.fn(() => ({ + text: "Test line content", + lineNumber: 3, + })) as any; + + await jumpManager.suggestJump( + currentPosition, + nextJumpLocation, + completionContent, + ); + + // Jump should not be suggested, so decorations should not be created + expect( + vscode.window.createTextEditorDecorationType, + ).not.toHaveBeenCalled(); + }); + + it("should render decoration for jump location outside visible range (below)", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(8, 0); // Outside visible range (below) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + // Should set context + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + true, + ); + // Should register key listeners + expect(vscode.commands.registerCommand).toHaveBeenCalledWith( + "continue.acceptJump", + expect.any(Function), + ); + expect(vscode.commands.registerCommand).toHaveBeenCalledWith( + "continue.rejectJump", + expect.any(Function), + ); + }); + + it("should render decoration for jump location outside visible range (above)", async () => { + // Set visible range to be below the jump target + // @ts-ignore + vscode.window.activeTextEditor!.visibleRanges = [ + { start: { line: 5 }, end: { line: 10 } }, + ]; + + const currentPosition = new vscode.Position(6, 0); + const nextJumpLocation = new vscode.Position(2, 0); // Outside visible range (above) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + }); + }); + + describe("registerKeyListeners", () => { + it("should register acceptJump command that moves cursor", async () => { + // Setup private method access (this is a bit of a hack for testing private methods) + const privateJumpManager = jumpManager as any; + + // Mock context + privateJumpManager._jumpDecorationVisible = true; + + // Create editor mock + const editor = { + selection: null, + setSelection: vi.fn(), + }; + + // Create jump position + const jumpPosition = new vscode.Position(3, 5); + + // Call the private method + await privateJumpManager.registerKeyListeners(editor, jumpPosition); + + // Find the command handler + //@ts-ignore + const commandArgs = vscode.commands.registerCommand.mock.calls.find( + (call: any) => call[0] === "continue.acceptJump", + ); + const acceptJumpHandler = commandArgs[1]; + + // Call the handler + await acceptJumpHandler(); + + // Expect selection to be updated + expect(editor.selection).toEqual( + new vscode.Selection(jumpPosition, jumpPosition), + ); + // Expect decoration to be cleared + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + + it("should register rejectJump command that deletes the chain", async () => { + // Setup private method access + const privateJumpManager = jumpManager as any; + + // Mock context + privateJumpManager._jumpDecorationVisible = true; + + // Get a reference to the mocked deleteChain + const mockDeleteChain = vi.mocked( + NextEditProvider.getInstance().deleteChain, + ); + mockDeleteChain.mockClear(); + + // Call the private method + await privateJumpManager.registerKeyListeners( + {} as vscode.TextEditor, + new vscode.Position(0, 0), + ); + + // Find the command handler + //@ts-ignore + const commandArgs = vscode.commands.registerCommand.mock.calls.find( + (call: any) => call[0] === "continue.rejectJump", + ); + expect(commandArgs).toBeDefined(); + const rejectJumpHandler = commandArgs?.[1]; + expect(rejectJumpHandler).toBeDefined(); + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the handler + await rejectJumpHandler(); + + // Debug: Log state after calling handler + console.log("mockDeleteChain called:", mockDeleteChain.mock.calls.length); + + // Expect NextEditProvider.deleteChain to be called + expect(mockDeleteChain).toHaveBeenCalled(); + + // Expect decoration to be cleared + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + }); + + describe("setCompletionAfterJump", () => { + it("should store completion data", () => { + const completionData: CompletionDataForAfterJump = { + completionId: "test-id", + outcome: createMockNextEditOutcome(), + currentPosition: new vscode.Position(1, 0), + }; + + // Set the completion data + jumpManager.setCompletionAfterJump(completionData); + + // Verify the completion data was stored correctly + expect((jumpManager as any)._completionAfterJump).toEqual(completionData); + }); + + it("should process completion data when jump is completed", async () => { + const completionData: CompletionDataForAfterJump = { + completionId: "test-id", + outcome: createMockNextEditOutcome(), + currentPosition: new vscode.Position(1, 0), + }; + + // Set the completion data + jumpManager.setCompletionAfterJump(completionData); + + // Verify the completion data was set correctly + expect((jumpManager as any)._completionAfterJump).toEqual(completionData); + + // Reset executeCommand mock to clear previous calls + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Directly simulate what happens when a jump is completed + // by manipulating the internal state + (jumpManager as any)._jumpInProgress = false; + + // Now directly call the method that would show the completion + // We need to manually implement what the callback would do + if ((jumpManager as any)._completionAfterJump) { + vscode.commands.executeCommand( + "continue.showNextEditAfterJump", + (jumpManager as any)._completionAfterJump, + ); + (jumpManager as any)._completionAfterJump = null; + } + + // Verify that the command was called with the completion data + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "continue.showNextEditAfterJump", + completionData, + ); + + // Verify that _completionAfterJump was reset to null + expect((jumpManager as any)._completionAfterJump).toBeNull(); + }); + }); + + describe("clearJumpDecoration", () => { + it("should dispose decoration and reset state", async () => { + // Setup private method access + const privateJumpManager = jumpManager as any; + + // Create a mock decoration with a spy on dispose + const mockDispose = vi.fn(); + privateJumpManager._jumpDecoration = { + dispose: mockDispose, + }; + privateJumpManager._jumpDecorationVisible = true; + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the method + await privateJumpManager.clearJumpDecoration(); + + // Expect dispose to have been called + expect(mockDispose).toHaveBeenCalled(); + + // Expect decoration to be undefined after clearing + expect(privateJumpManager._jumpDecoration).toBeUndefined(); + expect(privateJumpManager._jumpDecorationVisible).toBe(false); + + // Expect context to be reset + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + }); +}); From de5450376bc3000bd82a4041643e2db268651100 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 14:56:31 -0700 Subject: [PATCH 86/88] fix: handle empty map cases properly --- core/nextEdit/DocumentHistoryTracker.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/DocumentHistoryTracker.ts b/core/nextEdit/DocumentHistoryTracker.ts index 34ea763bf..7cca91f56 100644 --- a/core/nextEdit/DocumentHistoryTracker.ts +++ b/core/nextEdit/DocumentHistoryTracker.ts @@ -63,11 +63,12 @@ export class DocumentHistoryTracker { if (!astHistory || !documentHistory) { console.error(`Document ${documentPath} not found in AST tracker`); this.addDocument(documentPath, documentContent, ast); + return; // Early return - document was added with initial state } - // Push to top (LIFO). - astHistory!.unshift(ast); - documentHistory!.unshift(documentContent); + // Only execute this if the arrays already existed + astHistory.unshift(ast); + documentHistory.unshift(documentContent); } /** From 88d9b6f1908d2dbfc2d2c6c99218dc40d9d4d67d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 14:56:39 -0700 Subject: [PATCH 87/88] test: add vitest for DocumentHistoryTracker --- .../nextEdit/DocumentHistoryTracker.vitest.ts | 228 ++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 core/nextEdit/DocumentHistoryTracker.vitest.ts diff --git a/core/nextEdit/DocumentHistoryTracker.vitest.ts b/core/nextEdit/DocumentHistoryTracker.vitest.ts new file mode 100644 index 000000000..f6c9b2dd4 --- /dev/null +++ b/core/nextEdit/DocumentHistoryTracker.vitest.ts @@ -0,0 +1,228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import Parser from "web-tree-sitter"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; + +// Mock the Parser.Tree class +vi.mock("web-tree-sitter", () => { + return { + default: { + Tree: class MockTree { + constructor() { + // Mock implementation + } + }, + }, + }; +}); + +describe("DocumentHistoryTracker", () => { + let tracker: DocumentHistoryTracker; + let mockAst1: Parser.Tree; + let mockAst2: Parser.Tree; + const testDocPath = "/test/document.ts"; + const testContent1 = "const x = 1;"; + const testContent2 = "const x = 2;"; + + beforeEach(() => { + // Reset singleton instance for each test + // @ts-ignore - accessing private static property for testing + DocumentHistoryTracker.instance = null; + tracker = DocumentHistoryTracker.getInstance(); + + // Create mock ASTs + //@ts-ignore + mockAst1 = new Parser.Tree() as Parser.Tree; + //@ts-ignore + mockAst2 = new Parser.Tree() as Parser.Tree; + }); + + afterEach(() => { + // Clear the tracker after each test + tracker.clearMap(); + }); + + describe("getInstance", () => { + it("should return a singleton instance", () => { + const instance1 = DocumentHistoryTracker.getInstance(); + const instance2 = DocumentHistoryTracker.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("addDocument", () => { + it("should add a document to the tracker", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBe(mockAst1); + expect(content).toBe(testContent1); + }); + }); + + describe("push", () => { + it("should push a new AST to an existing document's history stack", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBe(mockAst2); + expect(content).toBe(testContent2); + }); + + it("should add a document if it doesn't exist when pushing", () => { + tracker.push(testDocPath, testContent1, mockAst1); + + // Check if document was actually added + const ast = tracker.getMostRecentAst(testDocPath); + expect(ast).toBe(mockAst1); + }); + }); + + describe("getMostRecentAst", () => { + it("should return the most recent AST of a document", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const ast = tracker.getMostRecentAst(testDocPath); + + expect(ast).toBe(mockAst2); + }); + + it("should return null if the document doesn't exist", () => { + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst("nonexistent-path"); + + expect(ast).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Document nonexistent-path not found in AST tracker", + ); + + consoleErrorSpy.mockRestore(); + }); + + it("should return null if the document has no ASTs", () => { + // This test would require modifying private properties + // So we'll mock an empty array situation + tracker.addDocument(testDocPath, testContent1, mockAst1); + + // @ts-ignore - accessing private property for testing + tracker.documentAstMap.set(testDocPath, []); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst(testDocPath); + + expect(ast).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} has no ASTs`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("getMostRecentDocumentHistory", () => { + it("should return the most recent document history", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(content).toBe(testContent2); + }); + + it("should return null if the document doesn't exist", () => { + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const content = tracker.getMostRecentDocumentHistory("nonexistent-path"); + + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Document nonexistent-path not found in AST tracker", + ); + + consoleErrorSpy.mockRestore(); + }); + + it("should return null if the document has no history", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + + // @ts-ignore - accessing private property for testing + tracker.documentContentHistoryMap.set(testDocPath, []); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} has no history`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("deleteDocument", () => { + it("should delete a document from the tracker", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.deleteDocument(testDocPath); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBeNull(); + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} not found in AST tracker`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("clearMap", () => { + it("should clear all documents from the tracker", () => { + const anotherDocPath = "/test/another-document.ts"; + + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.addDocument(anotherDocPath, testContent1, mockAst1); + + tracker.clearMap(); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + expect(tracker.getMostRecentAst(testDocPath)).toBeNull(); + expect(tracker.getMostRecentAst(anotherDocPath)).toBeNull(); + expect(tracker.getMostRecentDocumentHistory(testDocPath)).toBeNull(); + expect(tracker.getMostRecentDocumentHistory(anotherDocPath)).toBeNull(); + + consoleErrorSpy.mockRestore(); + }); + }); +}); From 5ffcaaa2e22c52bcffe9e80fbc2bc7b21aac8bed Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 15:03:15 -0700 Subject: [PATCH 88/88] refactor: use named argument --- core/core.ts | 2 +- core/nextEdit/NextEditProvider.ts | 13 +++++++++---- .../vscode/src/autocomplete/completionProvider.ts | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/core/core.ts b/core/core.ts index 0a561f0fa..7cf6dd6e1 100644 --- a/core/core.ts +++ b/core/core.ts @@ -603,7 +603,7 @@ export class Core { const outcome = await this.nextEditProvider.provideInlineCompletionItems( msg.data, undefined, - false, + { withChain: false }, ); return outcome ? [outcome.completion, outcome.originalEditableRange] : []; }); diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index b431f0503..a001df3b0 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -247,7 +247,9 @@ export class NextEditProvider { public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, - withChain: boolean, + opts?: { + withChain: boolean; + }, ): Promise { try { this.previousRequest = input; @@ -268,7 +270,9 @@ export class NextEditProvider { // Depending on whether this method is called from provideInlineCompletionItemsWithChain, // shift the next editable regions. - if (withChain) { + // This is handled here because this must run after the debouncer + // to prevent excessive shifts. + if (opts?.withChain) { this.shiftNextEditableRegionsInTheCurrentChain(); } @@ -534,8 +538,9 @@ export class NextEditProvider { return undefined; } - const WITH_CHAIN = true; - return await this.provideInlineCompletionItems(input, token, WITH_CHAIN); + return await this.provideInlineCompletionItems(input, token, { + withChain: true, + }); } catch (e: any) { this.onError(e); } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 4be4b7cef..966a048b5 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -276,7 +276,7 @@ export class ContinueCompletionProvider outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, - false, + { withChain: false }, ); if (!outcome || !outcome.completion) {