From f6e5198cfae166ec72eddc93b3ce79c2ad0d8103 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 18:06:02 -0700 Subject: [PATCH 01/48] feat: add a prefetch queue class --- core/nextEdit/NextEditPrefetchQueue.ts | 91 ++++++++++++++++++++++++++ 1 file changed, 91 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..056d0d0ee --- /dev/null +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -0,0 +1,91 @@ +import { Position } from ".."; +import { NextEditOutcome } from "./types"; + +export interface PrefetchQueueItem { + editableRegionStartLine: number; + editableRegionEndLine: number; + cursorPosition: Position; + outcome?: NextEditOutcome; + completionId?: string; + inProgress: boolean; +} + +export class NextEditPrefetchQueue { + private static _instance: NextEditPrefetchQueue; + private queue: PrefetchQueueItem[] = []; + private maxQueueSize: number = 3; // Limit queue size to prevent too many requests. We don't need to be too eager. + + private constructor() {} + + public static getInstance(): NextEditPrefetchQueue { + if (!NextEditPrefetchQueue._instance) { + NextEditPrefetchQueue._instance = new NextEditPrefetchQueue(); + } + return NextEditPrefetchQueue._instance; + } + + public enqueue(item: PrefetchQueueItem): void { + // Deduplication logic. + if ( + this.queue.some( + (queueItem) => + queueItem.editableRegionStartLine === item.editableRegionStartLine, + ) + ) { + return; + } + + // Shift off oldest item in the queue. + while (this.queue.length >= this.maxQueueSize) { + this.queue.shift(); + } + + this.queue.push(item); + } + + public dequeue(): PrefetchQueueItem | undefined { + return this.queue.shift(); + } + + public getNextUnprocessedItem(): PrefetchQueueItem | undefined { + return this.queue.find((item) => !item.inProgress && !item.outcome); + } + + public updateItemWithOutcome( + startLine: number, + outcome: NextEditOutcome, + completionId: string, + ): void { + const item = this.queue.find( + (item) => item.editableRegionStartLine === startLine, + ); + if (item) { + item.outcome = outcome; + item.completionId = completionId; + item.inProgress = false; + } + } + + public markItemInProgress(startLine: number): void { + const item = this.queue.find( + (item) => item.editableRegionStartLine === startLine, + ); + if (item) { + item.inProgress = true; + } + } + + public getItemByStartLine(startLine: number): PrefetchQueueItem | undefined { + return this.queue.find( + (item) => item.editableRegionStartLine === startLine, + ); + } + + public clear(): void { + this.queue = []; + } + + public size(): number { + return this.queue.length; + } +} From 375b19a70c3516573b40580f99004a6ebf0655da Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 31 Jul 2025 14:56:27 -0700 Subject: [PATCH 02/48] feat: create prefetch queue --- core/nextEdit/NextEditPrefetchQueue.ts | 154 +++++++++++++------------ 1 file changed, 78 insertions(+), 76 deletions(-) diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 056d0d0ee..66e680835 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -1,91 +1,93 @@ -import { Position } from ".."; -import { NextEditOutcome } from "./types"; +import { NextEditProvider } from "./NextEditProvider"; -export interface PrefetchQueueItem { - editableRegionStartLine: number; - editableRegionEndLine: number; - cursorPosition: Position; - outcome?: NextEditOutcome; - completionId?: string; - inProgress: boolean; -} +export class PrefetchQueue { + private unprocessedQueue: EditLocation[] = []; + private processedQueue: ProcessedItem[] = []; + private prefetchLimit: number; + private abortController: AbortController; -export class NextEditPrefetchQueue { - private static _instance: NextEditPrefetchQueue; - private queue: PrefetchQueueItem[] = []; - private maxQueueSize: number = 3; // Limit queue size to prevent too many requests. We don't need to be too eager. - - private constructor() {} - - public static getInstance(): NextEditPrefetchQueue { - if (!NextEditPrefetchQueue._instance) { - NextEditPrefetchQueue._instance = new NextEditPrefetchQueue(); - } - return NextEditPrefetchQueue._instance; + constructor(prefetchLimit: number = 3) { + this.prefetchLimit = prefetchLimit; + this.abortController = new AbortController(); } - public enqueue(item: PrefetchQueueItem): void { - // Deduplication logic. - if ( - this.queue.some( - (queueItem) => - queueItem.editableRegionStartLine === item.editableRegionStartLine, - ) + // Queue management methods + enqueueUnprocessed(location: EditLocation): void { + this.unprocessedQueue.push(location); + } + + dequeueUnprocessed(): EditLocation | undefined { + return this.unprocessedQueue.shift(); + } + + enqueueProcessed(item: ProcessedItem): void { + this.processedQueue.push(item); + } + + dequeueProcessed(): ProcessedItem | undefined { + return this.processedQueue.shift(); + } + + // Process items from unprocessed queue + async process(ctx: any): Promise { + let processCount = 0; + + while ( + this.unprocessedQueue.length > 0 && + processCount < this.prefetchLimit && + !this.abortController.signal.aborted ) { - return; - } + const location = this.dequeueUnprocessed(); + if (!location) break; - // Shift off oldest item in the queue. - while (this.queue.length >= this.maxQueueSize) { - this.queue.shift(); - } + try { + const outcome = + await NextEditProvider.getInstance().provideInlineCompletionItemsWithChain( + ctx, + location, + this.abortController.signal, + ); - this.queue.push(item); - } + this.enqueueProcessed({ + location, + outcome, + }); - public dequeue(): PrefetchQueueItem | undefined { - return this.queue.shift(); - } - - public getNextUnprocessedItem(): PrefetchQueueItem | undefined { - return this.queue.find((item) => !item.inProgress && !item.outcome); - } - - public updateItemWithOutcome( - startLine: number, - outcome: NextEditOutcome, - completionId: string, - ): void { - const item = this.queue.find( - (item) => item.editableRegionStartLine === startLine, - ); - if (item) { - item.outcome = outcome; - item.completionId = completionId; - item.inProgress = false; + processCount++; + } catch (error) { + if (!this.abortController.signal.aborted) { + // Handle error + console.error("Error processing item:", error); + } + // If aborted, we just stop processing + break; + } } } - public markItemInProgress(startLine: number): void { - const item = this.queue.find( - (item) => item.editableRegionStartLine === startLine, - ); - if (item) { - item.inProgress = true; - } + // Abort all operations + abort(): void { + this.abortController.abort(); + this.clear(); + + // Create a new AbortController for future operations + this.abortController = new AbortController(); } - public getItemByStartLine(startLine: number): PrefetchQueueItem | undefined { - return this.queue.find( - (item) => item.editableRegionStartLine === startLine, - ); - } - - public clear(): void { - this.queue = []; - } - - public size(): number { - return this.queue.length; + // Clear all queues + clear(): void { + this.unprocessedQueue = []; + this.processedQueue = []; } } + +// Types +interface EditLocation { + // Define properties for edit location + // e.g., file, position, etc. +} + +interface ProcessedItem { + location: EditLocation; + outcome: any; // Result from the model +} From 90d07b4b4a4baccc6d06c9316c69eb03674728a8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 31 Jul 2025 17:45:59 -0700 Subject: [PATCH 03/48] feat: integrate prefetch queue and refactor --- .../src/autocomplete/completionProvider.ts | 487 +++++++++--------- 1 file changed, 249 insertions(+), 238 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 55214732b..d50d5c838 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -20,6 +20,7 @@ import { } from "core/nextEdit/constants"; import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; +import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { NextEditOutcome } from "core/nextEdit/types"; import { JumpManager } from "../activation/JumpManager"; @@ -67,6 +68,8 @@ export class ContinueCompletionProvider private nextEditProvider: NextEditProvider; private nextEditLoggingService: NextEditLoggingService; private jumpManager: JumpManager; + private prefetchQueue: PrefetchQueue; + public recentlyVisitedRanges: RecentlyVisitedRangesService; public recentlyEditedTracker: RecentlyEditedTracker; @@ -115,6 +118,7 @@ export class ContinueCompletionProvider ); this.jumpManager = JumpManager.getInstance(); + this.prefetchQueue = PrefetchQueue.getInstance(); this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide); } @@ -136,6 +140,12 @@ export class ContinueCompletionProvider token: vscode.CancellationToken, //@ts-ignore ): ProviderResult { + // This method is triggered on every keystroke, tab keypress, and cursor move. + // We need to determine why it was triggered: + // 1. Typing (chain doesn't exist) + // 2. Jumping (chain exists, jump was taken) + // 3. Accepting (chain exists, jump is not taken) + const enableTabAutocomplete = getStatusBarStatus() === StatusBarStatus.Enabled; if (token.isCancellationRequested || !enableTabAutocomplete) { @@ -146,8 +156,11 @@ export class ContinueCompletionProvider return null; } - // Don't autocomplete with multi-cursor const editor = vscode.window.activeTextEditor; + if (!editor) { + return undefined; + } + // Don't autocomplete with multi-cursor if (editor && editor.selections.length > 1) { return null; } @@ -173,6 +186,8 @@ export class ContinueCompletionProvider } let injectDetails: string | undefined = undefined; + const currCursorPos = editor.selection.active; + try { const abortController = new AbortController(); const signal = abortController.signal; @@ -229,58 +244,131 @@ export class ContinueCompletionProvider const wasManuallyTriggered = context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke; - 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( - "chain exists?", - this.nextEditProvider.chainExists(), - ", length:", - this.nextEditProvider.getChainLength(), - ", next regions queue:", - this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(), - ); + const ctx = { + completionId, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + isUntitledFile: document.isUntitled, + recentlyVisitedRanges, + recentlyEditedRanges, + }; - if (this.nextEditProvider.chainExists()) { - // 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( - { - completionId, - manuallyPassFileContents, - manuallyPassPrefix, - selectedCompletionInfo, - isUntitledFile: document.isUntitled, - recentlyVisitedRanges, - recentlyEditedRanges, - }, - signal, + let outcome: AutocompleteOutcome | NextEditOutcome | undefined; + + // console.log( + // "chain exists?", + // this.nextEditProvider.chainExists(), + // ", length:", + // this.nextEditProvider.getChainLength(), + // ", next regions queue:", + // this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(), + // ); + + // Determine why this method was triggered. + const isJumping = this.jumpManager.isJumpInProgress(); + const chainExists = this.nextEditProvider.chainExists(); + + if (isJumping && chainExists) { + // Case 2: Jumping (chain exists, jump was taken) + console.log("trigger reason: jumping"); + + // Reset jump state. + this.jumpManager.setJumpInProgress(false); + + // Use the saved completion from JumpManager instead of dequeuing. + const savedCompletion = this.jumpManager.completionAfterJump; + if (savedCompletion) { + outcome = savedCompletion.outcome; + this.jumpManager.clearCompletionAfterJump(); + } else { + // Fall back to prefetch queue. This technically should not happen. + console.error( + "Fell back to prefetch queue even after jump was taken", ); + outcome = this.prefetchQueue.dequeueProcessed()?.outcome; + + // Fill in the spot after dequeuing. + this.prefetchQueue.process({ + ...ctx, + recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), + recentlyEditedRanges: + await this.recentlyEditedTracker.getRecentlyEditedRanges(), + }); + } + } else if (chainExists) { + // Case 3: Accepting next edit outcome (chain exists, jump is not taken). + console.log("trigger reason: accepting"); + + // Try suggesting jump for each location. + let isJumpSuggested = false; + + while (this.prefetchQueue.processedCount > 0 && !isJumpSuggested) { + const nextItemInQueue = this.prefetchQueue.dequeueProcessed(); + if (!nextItemInQueue) continue; + + // Fill in the spot after dequeuing. + this.prefetchQueue.process({ + ...ctx, + recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), + recentlyEditedRanges: + await this.recentlyEditedTracker.getRecentlyEditedRanges(), + }); + + const nextLocation = nextItemInQueue.location; + outcome = nextItemInQueue.outcome; + + const jumpPosition = new vscode.Position( + nextLocation.range.start.line, + nextLocation.range.start.character, + ); + + isJumpSuggested = await this.jumpManager.suggestJump( + currCursorPos, + jumpPosition, + outcome.completion, + ); + + if (isJumpSuggested) { + // Store completion to be rendered after a jump. + this.jumpManager.setCompletionAfterJump({ + completionId: completionId, + outcome, + currentPosition: jumpPosition, + }); + + // Don't display anything yet. + // This will be handled in Case 2. + return undefined; + } + } + + if (!isJumpSuggested) { + console.log( + "No suitable jump location found after trying all positions", + ); + return undefined; + } } else { - // If the user has rejected, then we start a new chain of edits. + // Case 1: Typing (chain does not exist). + this.nextEditProvider.startChain(); const input: AutocompleteInput = { pos, - manuallyPassFileContents, - manuallyPassPrefix, - selectedCompletionInfo, - injectDetails, - isUntitledFile: document.isUntitled, - completionId, filepath, - recentlyVisitedRanges, - recentlyEditedRanges, + ...ctx, }; setupStatusBar(undefined, true); - // Check if editChainId exists or needs to be refreshed. + // Get initial completion. if (this.isNextEditActive) { outcome = await this.nextEditProvider.provideInlineCompletionItems( input, @@ -288,31 +376,21 @@ export class ContinueCompletionProvider { withChain: false }, ); - if (!outcome || !outcome.completion) { - // 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(); + // Start prefetching next edits. + // NOTE: this might be better off not awaited. + await this.prefetchQueue.process(ctx); - outcome = - await this.nextEditProvider.provideInlineCompletionItemsWithChain( - { - completionId, - manuallyPassFileContents, - manuallyPassPrefix, - selectedCompletionInfo, - isUntitledFile: document.isUntitled, - recentlyVisitedRanges, - recentlyEditedRanges, - }, - signal, - ); - } + // If initial outcome is null, suggest a jump instead. + // Calling this method again will call it with + // chain active but jump not suggested yet. + return this.provideInlineCompletionItems( + document, + position, + context, + token, + ); } else { - // Handle autocomplete request. + // Handle regular autocomplete request. outcome = await this.completionProvider.provideInlineCompletionItems( input, signal, @@ -321,8 +399,7 @@ export class ContinueCompletionProvider } } - // 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. + // Return early if no valid outcome was found. if (!outcome || !outcome.completion) { return null; } @@ -415,186 +492,120 @@ 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) { - if (!this.nextEditProvider.isStartOfChain()) { - // Try suggesting jumps for each location in the queue. - let jumpSuccessful = false; - - while ( - this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength() > - 0 && - !jumpSuccessful - ) { - // NOTE: Outcome has to be re-computed for each next editable location. - const nextRegion = - this.nextEditProvider.getNextEditableRegionsInTheCurrentChain()[0]; - if (!nextRegion) continue; - - // Getting the outcome shifts the next editable region queue, - // deleting the item denoted by nextRegion above. - outcome = - await this.nextEditProvider.provideInlineCompletionItemsWithChain( - { - completionId, - manuallyPassFileContents, - manuallyPassPrefix, - selectedCompletionInfo, - isUntitledFile: document.isUntitled, - recentlyVisitedRanges, - recentlyEditedRanges, - }, - signal, - ); - - if (!outcome) continue; - - const jumpPosition = new vscode.Position( - nextRegion.range.start.line, - nextRegion.range.start.character, - ); - - // Try to suggest a jump to this location. - jumpSuccessful = await this.jumpManager.suggestJump( - currCursorPos, - jumpPosition, - outcome.completion, - ); - - if (jumpSuccessful) { - // Store completion to be rendered after jump. - this.jumpManager.setCompletionAfterJump({ - completionId: completionId, - outcome: outcome as NextEditOutcome, - currentPosition: jumpPosition, - }); - - return undefined; // Don't show anything yet! - } - } - - // If no jump was successful after trying multiple locations, - // proceed with other completion display logic or return undefined. - if (!jumpSuccessful) { - console.log( - "No suitable jump location found after trying multiple positions", - ); - return undefined; - } - } - - // Check the diff between old and new editable region. - const newEditRangeSlice = completionText; - - // We don't need to show the next edit window if the predicted edits is empty. - if (newEditRangeSlice === "") { - this.nextEditLoggingService.cancelRejectionTimeout(completionId); - return undefined; - } - - // Get the contents of the old (current) editable region. - 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, - editor.document.lineCount - 1, - ); - const oldEditRangeSlice = editor.document - .getText() - .split("\n") - .slice(editableRegionStartLine, editableRegionEndLine + 1) - .join("\n"); - - // 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(completionId); - 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, - relativeCursorPos, - ); - - if (isFim) { - if (!fimText) { - console.log("deleteChain from completionProvider.ts: !fimText"); - this.nextEditProvider.deleteChain(); - return undefined; - } - - // 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, - new vscode.Position(currCursorPos.line, currCursorPos.character), - ); - - const nextEditCompletionItem = new vscode.InlineCompletionItem( - fimText, - new vscode.Range( - new vscode.Position(currCursorPos.line, currCursorPos.character), - new vscode.Position(currCursorPos.line, currCursorPos.character), - ), - { - title: "Log Next Edit Outcome", - command: "continue.logNextEditOutcomeAccept", - arguments: [completionId, this.nextEditLoggingService], - }, - ); - return [nextEditCompletionItem]; - } - - // 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( - completionId, - ); - - await NextEditWindowManager.getInstance().showNextEditWindow( - editor, - currCursorPos, - editableRegionStartLine, - editableRegionEndLine, - oldEditRangeSlice, - newEditRangeSlice, - diffLines, - ); - } - - return undefined; - } else { + // Handle autocomplete request. + if (!this.isNextEditActive) { return [autocompleteCompletionItem]; } + + // Check the diff between old and new editable region. + const newEditRangeSlice = completionText; + + // We don't need to show the next edit window if the predicted edits is empty. + if (newEditRangeSlice === "") { + this.nextEditLoggingService.cancelRejectionTimeout(completionId); + return undefined; + } + + // Get the contents of the old (current) editable region. + 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, + editor.document.lineCount - 1, + ); + const oldEditRangeSlice = editor.document + .getText() + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + // 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(completionId); + 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, + relativeCursorPos, + ); + + if (isFim) { + if (!fimText) { + console.log("deleteChain from completionProvider.ts: !fimText"); + this.nextEditProvider.deleteChain(); + return undefined; + } + + // 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, + new vscode.Position(currCursorPos.line, currCursorPos.character), + ); + + const nextEditCompletionItem = new vscode.InlineCompletionItem( + fimText, + new vscode.Range( + new vscode.Position(currCursorPos.line, currCursorPos.character), + new vscode.Position(currCursorPos.line, currCursorPos.character), + ), + { + title: "Log Next Edit Outcome", + command: "continue.logNextEditOutcomeAccept", + arguments: [completionId, this.nextEditLoggingService], + }, + ); + return [nextEditCompletionItem]; + } + + // Handle non-FIM cases with the NextEditWindowManager. + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + if (diffLines.length === 0) { + // At this point, there is no way that diffLines.length === 0. + // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse. + // In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place. + // In case of initial response, this could actually happen. + // We just suggest a jump at this point. + // If this were to be true, we wouldn't have even + console.log( + "deleteChain from completionProvider.ts: diffLines.length === 0", + ); + NextEditProvider.getInstance().deleteChain(); + } + + if (NextEditWindowManager.isInstantiated()) { + NextEditWindowManager.getInstance().updateCurrentCompletionId( + completionId, + ); + + await NextEditWindowManager.getInstance().showNextEditWindow( + editor, + currCursorPos, + editableRegionStartLine, + editableRegionEndLine, + oldEditRangeSlice, + newEditRangeSlice, + diffLines, + ); + } + + return undefined; } finally { stopStatusBarLoading(); } From 68beae55b5aa925188af01429a349e239a7f43c3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 31 Jul 2025 17:46:28 -0700 Subject: [PATCH 04/48] refactor: move the next editable region list to prefetch queue --- core/nextEdit/NextEditPrefetchQueue.ts | 59 +++++++++++++++++--------- core/nextEdit/NextEditProvider.ts | 59 +++----------------------- 2 files changed, 46 insertions(+), 72 deletions(-) diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 66e680835..38b5589c6 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -1,26 +1,43 @@ +import { RangeInFile } from ".."; import { NextEditProvider } from "./NextEditProvider"; +import { NextEditOutcome } from "./types"; + +interface ProcessedItem { + location: RangeInFile; + outcome: NextEditOutcome; // Result from the model +} export class PrefetchQueue { - private unprocessedQueue: EditLocation[] = []; + private static instance: PrefetchQueue | null = null; + + private unprocessedQueue: RangeInFile[] = []; private processedQueue: ProcessedItem[] = []; private prefetchLimit: number; private abortController: AbortController; - constructor(prefetchLimit: number = 3) { + private constructor(prefetchLimit: number = 3) { this.prefetchLimit = prefetchLimit; this.abortController = new AbortController(); } + public static getInstance(prefetchLimit: number = 3): PrefetchQueue { + if (!PrefetchQueue.instance) { + PrefetchQueue.instance = new PrefetchQueue(prefetchLimit); + } + + return PrefetchQueue.instance; + } + // Queue management methods - enqueueUnprocessed(location: EditLocation): void { + enqueueUnprocessed(location: RangeInFile): void { this.unprocessedQueue.push(location); } - dequeueUnprocessed(): EditLocation | undefined { + private dequeueUnprocessed(): RangeInFile | undefined { return this.unprocessedQueue.shift(); } - enqueueProcessed(item: ProcessedItem): void { + private enqueueProcessed(item: ProcessedItem): void { this.processedQueue.push(item); } @@ -30,11 +47,9 @@ export class PrefetchQueue { // Process items from unprocessed queue async process(ctx: any): Promise { - let processCount = 0; - while ( this.unprocessedQueue.length > 0 && - processCount < this.prefetchLimit && + this.processedQueue.length < this.prefetchLimit && !this.abortController.signal.aborted ) { const location = this.dequeueUnprocessed(); @@ -48,12 +63,12 @@ export class PrefetchQueue { this.abortController.signal, ); + if (!outcome) continue; + this.enqueueProcessed({ location, outcome, }); - - processCount++; } catch (error) { if (!this.abortController.signal.aborted) { // Handle error @@ -79,15 +94,21 @@ export class PrefetchQueue { this.unprocessedQueue = []; this.processedQueue = []; } -} -// Types -interface EditLocation { - // Define properties for edit location - // e.g., file, position, etc. -} + // Additional helper methods + get unprocessedCount(): number { + return this.unprocessedQueue.length; + } -interface ProcessedItem { - location: EditLocation; - outcome: any; // Result from the model + get processedCount(): number { + return this.processedQueue.length; + } + + peekProcessed(): ProcessedItem | undefined { + return this.processedQueue[0]; + } + + setPreetchLimit(limit: number): void { + this.prefetchLimit = limit; + } } diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 1ae21c152..cfb44a950 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -28,10 +28,6 @@ import { import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { calculateFinalCursorPosition } from "./diff/diff.js"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; -import { - EditableRegionStrategy, - getNextEditableRegion, -} from "./NextEditEditableRegionCalculator.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; import { renderDefaultSystemPrompt, @@ -71,7 +67,7 @@ export class NextEditProvider { private currentEditChainId: string | null = null; private previousRequest: AutocompleteInput | null = null; private previousCompletions: NextEditOutcome[] = []; - private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; + // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; private constructor( private readonly configHandler: ConfigHandler, @@ -220,7 +216,8 @@ export class NextEditProvider { public async deleteChain(): Promise { this.currentEditChainId = null; this.previousCompletions = []; - this.nextEditableRegionsInTheCurrentChain = []; + // TODO: this should be cleaned up in the prefetch queue. + // this.nextEditableRegionsInTheCurrentChain = []; if (this.previousRequest) { const fileContent = ( @@ -273,14 +270,6 @@ export class NextEditProvider { return undefined; } - // Depending on whether this method is called from provideInlineCompletionItemsWithChain, - // shift the next editable regions. - // This is handled here because this must run after the debouncer - // to prevent excessive shifts. - if (opts?.withChain) { - this.shiftNextEditableRegionsInTheCurrentChain(); - } - const llm = await this._prepareLlm(); if (!llm) { return undefined; @@ -527,6 +516,7 @@ export class NextEditProvider { recentlyVisitedRanges: AutocompleteCodeSnippet[]; recentlyEditedRanges: RecentlyEditedRange[]; }, + nextEditLocation: RangeInFile, token: AbortSignal | undefined, ) { try { @@ -535,31 +525,10 @@ export class NextEditProvider { return undefined; } - const filepath = localPathOrUriToPath(previousOutcome.fileUri); - - // If we don't have a precomputed list of next editable regions already, compute and load it. - if (this.nextEditableRegionsInTheCurrentChain.length === 0) { - this.loadNextEditableRegionsInTheCurrentChain( - (await getNextEditableRegion(EditableRegionStrategy.Static, { - cursorPosition: previousOutcome.cursorPosition, - filepath, - ide: this.ide, - })) ?? [], - ); - - if (this.nextEditableRegionsInTheCurrentChain.length === 0) { - console.log( - "deleteChain called from provideInlineCompletionItemsWithChain", - ); - await this.deleteChain(); - return undefined; - } - } - // Use the frontmost RangeInFile to build an input. - const input = await this.buildAutocompleteInputFromChain( + const input = this.buildAutocompleteInputFromChain( previousOutcome, - this.nextEditableRegionsInTheCurrentChain[0], // this will be shifted after debouncer check + nextEditLocation, ctx, ); if (!input) { @@ -601,20 +570,4 @@ export class NextEditProvider { return input; } - - public loadNextEditableRegionsInTheCurrentChain(regions: RangeInFile[]) { - this.nextEditableRegionsInTheCurrentChain = regions; - } - - public shiftNextEditableRegionsInTheCurrentChain() { - return this.nextEditableRegionsInTheCurrentChain.shift(); - } - - public getNextEditableRegionsInTheCurrentChainLength() { - return this.nextEditableRegionsInTheCurrentChain.length; - } - - public getNextEditableRegionsInTheCurrentChain(): RangeInFile[] { - return [...this.nextEditableRegionsInTheCurrentChain]; // Return a copy to prevent external modification - } } From 300377eaf3b832b11a60576a4542f6eea76086dd Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 31 Jul 2025 17:46:44 -0700 Subject: [PATCH 05/48] feat: add more helper functions to JumpManager --- extensions/vscode/src/activation/JumpManager.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 48797f007..0f0e64e12 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -328,6 +328,10 @@ export class JumpManager { return this._jumpInProgress; } + setJumpInProgress(jumpInProgress: boolean) { + this._jumpInProgress = jumpInProgress; + } + wasJumpJustAccepted(): boolean { return this._jumpAccepted; } @@ -335,4 +339,12 @@ export class JumpManager { setCompletionAfterJump(completionData: CompletionDataForAfterJump): void { this._completionAfterJump = completionData; } + + clearCompletionAfterJump(): void { + this._completionAfterJump = null; + } + + get completionAfterJump() { + return this._completionAfterJump; + } } From 201e34c0ebca3415587dfa7fa1f1a98365dea798 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 31 Jul 2025 19:24:01 -0700 Subject: [PATCH 06/48] feat: add a global selection change manager to handle text selection events in an event bus --- .../src/activation/SelectionChangeManager.ts | 264 ++++++++++++++++++ 1 file changed, 264 insertions(+) create mode 100644 extensions/vscode/src/activation/SelectionChangeManager.ts diff --git a/extensions/vscode/src/activation/SelectionChangeManager.ts b/extensions/vscode/src/activation/SelectionChangeManager.ts new file mode 100644 index 000000000..7c09046ee --- /dev/null +++ b/extensions/vscode/src/activation/SelectionChangeManager.ts @@ -0,0 +1,264 @@ +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "core/nextEdit/NextEditEditableRegionCalculator"; +import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { localPathOrUriToPath } from "core/util/pathToUri"; +import * as vscode from "vscode"; +import { VsCodeIde } from "../VsCodeIde"; +import { JumpManager } from "./JumpManager"; +import { NextEditWindowManager } from "./NextEditWindowManager"; + +export enum HandlerPriority { + CRITICAL = 1000, + HIGH = 800, + NORMAL = 500, + LOW = 200, + FALLBACK = 100, +} + +interface StateSnapshot { + nextEditWindowAccepted: boolean; + jumpInProgress: boolean; + jumpJustAccepted: boolean; + lastDocumentChangeTime: number; + isTypingSession: boolean; +} + +type SelectionChangeHandler = ( + e: vscode.TextEditorSelectionChangeEvent, + state: StateSnapshot, +) => Promise; + +interface HandlerRegistration { + id: string; + priority: number; + handler: SelectionChangeHandler; +} + +export class SelectionChangeManager { + private static instance: SelectionChangeManager; + private listeners: HandlerRegistration[] = []; + private ide: VsCodeIde | null = null; + + // Event bus-related attributes. + private eventQueue: vscode.TextEditorSelectionChangeEvent[] = []; + private lastEventTime = 0; + private isProcessingEvent = false; + private processingTimeout: NodeJS.Timeout | null = null; + + // Debounce settings. + private readonly DEBOUNCE_DELAY = 50; + private readonly PROCESSING_TIMEOUT = 500; + + // Track typing session state. + private isTypingSession = false; + private typingTimer: NodeJS.Timeout | null = null; + private lastDocumentChangeTime = 0; + private readonly TYPING_SESSION_TIMEOUT = 2000; // ms + private readonly TYPING_DELAY = 500; // ms + + private constructor() {} + + public static getInstance() { + if (!SelectionChangeManager.instance) { + SelectionChangeManager.instance = new SelectionChangeManager(); + } + return SelectionChangeManager.instance; + } + + public initialize(ide: VsCodeIde): void { + this.ide = ide; + + // After handling all other listeners, this will delete the chain. + this.registerListener( + "defaultFallbackHandler", + this.defaultFallbackHandler.bind(this), + HandlerPriority.FALLBACK, + ); + } + + public documentChanged(): void { + this.isTypingSession = true; + this.lastDocumentChangeTime = Date.now(); + this.resetTypingSession(); + } + + private resetTypingSession(): void { + if (this.typingTimer) { + clearTimeout(this.typingTimer); + } + this.typingTimer = setTimeout(() => { + this.isTypingSession = false; + }, this.TYPING_SESSION_TIMEOUT); + } + + /** + * Register a listener for the selection change event. + * @param id Unique id for this handler. + * @param handler Function to handle the event. + * @param priority Higher priority runs first. + * @returns Function to unregister this listener. + */ + public registerListener( + id: string, + handler: SelectionChangeHandler, + priority: HandlerPriority = HandlerPriority.NORMAL, + ): () => void { + // Remove any existing handler with the same id. + this.listeners = this.listeners.filter((l) => l.id !== id); + + // Add the new handler. + this.listeners.push({ id, priority, handler }); + + // Sort by desc priority. + this.listeners.sort((a, b) => b.priority - a.priority); + + // Return the unregister function. + return () => { + this.listeners = this.listeners.filter((l) => l.id !== id); + }; + } + + /** + * Handle a given selection change event. + * @param e THe selection change event. + */ + public async handleSelectionChange( + e: vscode.TextEditorSelectionChangeEvent, + ): Promise { + const now = Date.now(); + + // Simple debouncing logic. + // Ignore events that come too quickly after the previous one. + // TODO: test this. + if (now - this.lastEventTime < this.DEBOUNCE_DELAY) { + // Replace the queued event with the most recent one. + if (this.eventQueue.length > 0) { + this.eventQueue[this.eventQueue.length - 1] = e; + } else { + this.eventQueue.push(e); + } + + return; + } + + this.lastEventTime = now; + + // Queue this event for later if the manager is already processing an event. + if (this.isProcessingEvent) { + this.eventQueue.push(e); + return; + } + + try { + // Process this event first. + await this.processEventWithTimeout(e); + + // Process remaining queued events sequentially. + while (this.eventQueue.length > 0) { + const nextEvent = this.eventQueue.shift()!; + await this.processEventWithTimeout(nextEvent); + } + } catch (err) { + console.error("Error processing selection change event:", err); + this.isProcessingEvent = false; + if (this.processingTimeout) { + clearTimeout(this.processingTimeout); + this.processingTimeout = null; + } + } + } + + /** + * Process a given event with a timeout. + * This is in attempt to prevent deadlocks between events. + * @param e The selection change event. + */ + private async processEventWithTimeout( + e: vscode.TextEditorSelectionChangeEvent, + ): Promise { + this.isProcessingEvent = true; + + // Set up a timeout to prevent deadlocks. + const timeoutPromise = new Promise((_, reject) => { + this.processingTimeout = setTimeout(() => { + reject(new Error("Selection change event processing timed out")); + }, this.PROCESSING_TIMEOUT); + }); + + try { + await Promise.race([this.processEvent(e), timeoutPromise]); + } finally { + // Clean up. + if (this.processingTimeout) { + clearTimeout(this.processingTimeout); + this.processingTimeout = null; + } + + this.isProcessingEvent = false; + } + } + + /** + * Core event processing logic. + * @param e The selection change event. + */ + private async processEvent( + e: vscode.TextEditorSelectionChangeEvent, + ): Promise { + const snapshot = this.captureState(); + + for (const { handler } of this.listeners) { + try { + if (await handler(e, snapshot)) { + return; + } + } catch (err) { + console.error("Error in selection change handler:", err); + // Don't break just yet -- go to next handler. + } + } + } + + private captureState(): StateSnapshot { + return { + nextEditWindowAccepted: + NextEditWindowManager.isInstantiated() && + NextEditWindowManager.getInstance().hasAccepted(), + jumpInProgress: JumpManager.getInstance().isJumpInProgress(), + jumpJustAccepted: JumpManager.getInstance().wasJumpJustAccepted(), + lastDocumentChangeTime: this.lastDocumentChangeTime, + isTypingSession: this.isTypingSession, + }; + } + + private async defaultFallbackHandler( + e: vscode.TextEditorSelectionChangeEvent, + state: StateSnapshot, + ): Promise { + if (!this.ide) { + console.error("IDE not initialized in SelectionChangeManager"); + return false; + } + + console.log( + "defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection", + ); + await NextEditProvider.getInstance().deleteChain(); + + const nextEditableRegions = + (await getNextEditableRegion(EditableRegionStrategy.Static, { + cursorPosition: e.selections[0].anchor, + filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), + ide: this.ide, + })) ?? []; + + nextEditableRegions.forEach((region) => { + PrefetchQueue.getInstance().enqueueUnprocessed(region); + }); + + return true; + } +} From b324391e358f2328c5cdcfda8cb8b51ec874fe3e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 31 Jul 2025 19:24:18 -0700 Subject: [PATCH 07/48] feat: add event registration methods --- .../vscode/src/activation/JumpManager.ts | 23 +++++++++++++++ .../src/activation/NextEditWindowManager.ts | 22 +++++++++++++++ .../GhostTextAcceptanceTracker.ts | 28 +++++++++++++++++++ 3 files changed, 73 insertions(+) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 0f0e64e12..8f39fb8eb 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -1,6 +1,10 @@ import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { NextEditOutcome } from "core/nextEdit/types"; import * as vscode from "vscode"; +import { + HandlerPriority, + SelectionChangeManager, +} from "./SelectionChangeManager"; export interface CompletionDataForAfterJump { completionId: string; @@ -347,4 +351,23 @@ export class JumpManager { get completionAfterJump() { return this._completionAfterJump; } + + public registerSelectionChangeHandler(): void { + const manager = SelectionChangeManager.getInstance(); + + manager.registerListener( + "jumpManager", + async (e, state) => { + if (state.jumpInProgress || state.jumpJustAccepted) { + console.log( + "JumpManager: jump in progress or just accepted, preserving chain", + ); + return true; + } + + return false; + }, + HandlerPriority.HIGH, + ); + } } diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 89a43f765..4a2b29870 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -10,6 +10,10 @@ import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { getThemeString } from "../util/getTheme"; +import { + HandlerPriority, + SelectionChangeManager, +} from "./SelectionChangeManager"; export interface TextApplier { applyText( @@ -848,6 +852,24 @@ export class NextEditWindowManager { public hasAccepted() { return this.accepted; } + + public registerSelectionChangeHandler(): void { + const manager = SelectionChangeManager.getInstance(); + + manager.registerListener( + "nextEditWindowManager", + async (e, state) => { + if (state.nextEditWindowAccepted) { + console.log( + "NextEditWindowManager: Edit was just accepted, preserving chain", + ); + return true; + } + return false; + }, + HandlerPriority.CRITICAL, + ); + } } export default async function setupNextEditWindowManager( diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts index a72c67202..30110a341 100644 --- a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -1,4 +1,8 @@ import * as vscode from "vscode"; +import { + HandlerPriority, + SelectionChangeManager, +} from "../activation/SelectionChangeManager"; export interface ExpectedGhostTextAcceptance { documentUri: string; @@ -114,4 +118,28 @@ export class GhostTextAcceptanceTracker { return false; } + + public registerSelectionChangeHandler(): void { + const manager = SelectionChangeManager.getInstance(); + + manager.registerListener( + "ghostTextTracker", + async (e, state) => { + const wasGhostTextAccepted = this.checkGhostTextWasAccepted( + e.textEditor.document, + e.selections[0].active, + ); + + if (wasGhostTextAccepted) { + console.log( + "GhostTextAcceptanceTracker: ghost text was accepted, preserving chain", + ); + return true; + } + + return false; + }, + HandlerPriority.HIGH, + ); + } } From 878fb9474f7dcc06e489b7f96e5ecf191b9bb4f0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 31 Jul 2025 19:24:35 -0700 Subject: [PATCH 08/48] feat: set up event handler for selection changes --- .../vscode/src/extension/VsCodeExtension.ts | 117 +++++++----------- 1 file changed, 43 insertions(+), 74 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index d5b0766ae..90d017628 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -44,10 +44,6 @@ import { VsCodeMessenger } from "./VsCodeMessenger"; import { getAst } from "core/autocomplete/util/ast"; import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker"; -import { - EditableRegionStrategy, - getNextEditableRegion, -} from "core/nextEdit/NextEditEditableRegionCalculator"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { isModelCapableOfNextEdit } from "core/nextEdit/utils"; import { localPathOrUriToPath } from "core/util/pathToUri"; @@ -55,6 +51,10 @@ import { JumpManager } from "../activation/JumpManager"; import setupNextEditWindowManager, { NextEditWindowManager, } from "../activation/NextEditWindowManager"; +import { + HandlerPriority, + SelectionChangeManager, +} from "../activation/SelectionChangeManager"; import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker"; import { getDefinitionsFromLsp } from "../autocomplete/lsp"; import { handleTextDocumentChange } from "../util/editLoggingUtils"; @@ -79,18 +79,8 @@ 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 - }; + private ARBITRARY_TYPING_DELAY = 2000; constructor(context: vscode.ExtensionContext) { // Register auth provider @@ -111,6 +101,27 @@ export class VsCodeExtension { this.extensionContext = context; this.windowId = uuidv4(); + const selectionManager = SelectionChangeManager.getInstance(); + selectionManager.initialize(this.ide); + + selectionManager.registerListener( + "typing", + async (e, state) => { + const timeSinceLastDocChange = + Date.now() - state.lastDocumentChangeTime; + if ( + state.isTypingSession && + timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY + ) { + console.log("VsCodeExtension: typing in progress, preserving chain"); + return true; + } + + return false; + }, + HandlerPriority.NORMAL, + ); + // Dependencies of core let resolveVerticalDiffManager: any = undefined; const verticalDiffManagerPromise = new Promise( @@ -198,8 +209,15 @@ export class VsCodeExtension { this.activateNextEdit(); await NextEditWindowManager.freeTabAndEsc(); - JumpManager.getInstance(); - GhostTextAcceptanceTracker.getInstance(); + const jumpManager = JumpManager.getInstance(); + jumpManager.registerSelectionChangeHandler(); + + const ghostTextAcceptanceTracker = + GhostTextAcceptanceTracker.getInstance(); + ghostTextAcceptanceTracker.registerSelectionChangeHandler(); + + const nextEditWindowManager = NextEditWindowManager.getInstance(); + nextEditWindowManager.registerSelectionChangeHandler(); } else { NextEditWindowManager.clearInstance(); this.deactivateNextEdit(); @@ -344,11 +362,15 @@ export class VsCodeExtension { vscode.workspace.onDidChangeTextDocument(async (event) => { if (event.contentChanges.length > 0) { - this.isTypingSession = true; - this.lastDocumentChangeTime = Date.now(); - this.resetTypingSession(); + selectionManager.documentChanged(); } + // if (event.contentChanges.length > 0) { + // this.isTypingSession = true; + // this.lastDocumentChangeTime = Date.now(); + // this.resetTypingSession(); + // } + const editInfo = await handleTextDocumentChange( event, this.configHandler, @@ -432,60 +454,7 @@ export class VsCodeExtension { // Listen for selection changes to hide tooltip when cursor moves. vscode.window.onDidChangeTextEditorSelection(async (e) => { - // Don't delete the chain of edits 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() || - JumpManager.getInstance().wasJumpJustAccepted() - ) { - 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; - } - - // 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; - 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 called from onDidChangeTextEditorSelection"); - await NextEditProvider.getInstance().deleteChain(); - - NextEditProvider.getInstance().loadNextEditableRegionsInTheCurrentChain( - (await getNextEditableRegion(EditableRegionStrategy.Static, { - cursorPosition: e.selections[0].anchor, - filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), - ide: this.ide, - })) ?? [], - ); + await selectionManager.handleSelectionChange(e); }); // Refresh index when branch is changed From 03fbf74160644b683bdf5ffa96e3449415c1d8dd Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 1 Aug 2025 10:32:33 -0700 Subject: [PATCH 09/48] refactor: clean up jump manager logic --- .../vscode/src/activation/JumpManager.ts | 28 ++++--------------- 1 file changed, 5 insertions(+), 23 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 8f39fb8eb..82724405c 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -178,28 +178,10 @@ export class JumpManager { vscode.TextEditorRevealType.InCenter, ); - // Set up a way to detect when the jump is complete. - const disposable = vscode.window.onDidChangeTextEditorSelection(() => { - console.log("_jumpInProgress is false"); - this._jumpInProgress = false; - disposable.dispose(); - - // 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; - } - }); - // Clean up after timeout if no jump has been made. - setTimeout(() => { - this._jumpInProgress = false; - disposable.dispose(); - }, 10000); + // setTimeout(() => { + // this._jumpInProgress = false; + // }, 10000); return true; } @@ -215,8 +197,8 @@ export class JumpManager { // 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"), + contentText: "📍 Press Tab to jump, Esc to cancel", + color: new vscode.ThemeColor("editor.foreground"), backgroundColor: new vscode.ThemeColor("editorInfo.background"), margin: `0 0 0 4px`, }, From 65685335e2252b970dd98d23109553fd894beab4 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 1 Aug 2025 10:33:18 -0700 Subject: [PATCH 10/48] refactor: remove unused command --- extensions/vscode/src/commands.ts | 128 ------------------------------ 1 file changed, 128 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 2ffd24418..3b247f88b 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -17,16 +17,7 @@ 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 { NextEditProvider } from "core/nextEdit/NextEditProvider"; -import { CompletionDataForAfterJump } from "./activation/JumpManager"; -import { NextEditWindowManager } from "./activation/NextEditWindowManager"; import { getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, @@ -814,125 +805,6 @@ const getCommandsMap: ( "editor.action.inlineSuggest.trigger", ); }, - "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. - - const { completionId, outcome, currentPosition } = data; - - const editor = vscode.window.activeTextEditor; - if (!editor) { - console.log("No active editor when trying to show next edit"); - 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, - 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 = documentContent - .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; - } - - // 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, - relativeCursorPos, - ); - - if (isFim) { - if (!fimText) { - console.log("deleteChain from commands.ts: !fimText"); - await NextEditProvider.getInstance().deleteChain(); - } - // 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.inlineSuggest.trigger", - { - completions: [nextEditCompletionItem], - position: currentPosition, - }, - ); - } 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"); - await NextEditProvider.getInstance().deleteChain(); - } - - if (NextEditWindowManager.isInstantiated()) { - const windowManager = NextEditWindowManager.getInstance(); - windowManager.updateCurrentCompletionId(completionId); - - await windowManager.showNextEditWindow( - editor, - currentPosition, - editableRegionStartLine, - editableRegionEndLine, - oldEditRangeSlice, - newEditRangeSlice, - diffLines, - ); - } - } - }, }; }; From 562dddd08ad5b5db14e85a5e5cc838868280cd96 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 1 Aug 2025 10:33:37 -0700 Subject: [PATCH 11/48] refactor: add lots of docs --- .../src/activation/SelectionChangeManager.ts | 91 +++++++++++++++++-- 1 file changed, 83 insertions(+), 8 deletions(-) diff --git a/extensions/vscode/src/activation/SelectionChangeManager.ts b/extensions/vscode/src/activation/SelectionChangeManager.ts index 7c09046ee..964b5fadf 100644 --- a/extensions/vscode/src/activation/SelectionChangeManager.ts +++ b/extensions/vscode/src/activation/SelectionChangeManager.ts @@ -11,11 +11,11 @@ import { JumpManager } from "./JumpManager"; import { NextEditWindowManager } from "./NextEditWindowManager"; export enum HandlerPriority { - CRITICAL = 1000, - HIGH = 800, - NORMAL = 500, - LOW = 200, - FALLBACK = 100, + CRITICAL = 5, + HIGH = 4, + NORMAL = 3, + LOW = 2, + FALLBACK = 1, } interface StateSnapshot { @@ -24,6 +24,8 @@ interface StateSnapshot { jumpJustAccepted: boolean; lastDocumentChangeTime: number; isTypingSession: boolean; + document?: vscode.TextDocument; + cursorPosition?: vscode.Position; } type SelectionChangeHandler = ( @@ -37,6 +39,74 @@ interface HandlerRegistration { handler: SelectionChangeHandler; } +/** + * SelectionChangeManager handles cursor movement events in a coordinated way + * to prevent race conditions and ensure consistent behavior across features. + * + * Case 1: User just moves the cursor around. + * - vscode fires onDidChangeTextEditorSelection. + * - State is captured. All fields in StateSnapshot are false. + * - All registered handlers return false. + * - Fallback handler runs, deleting the chain. + * + * Case 2: User accepts a next edit suggestion from a window. + * - vscode fires onDidChangeTextEditorSelection. + * - State is captured. nextEditWindowAccepted is true. + * - NextEditWindowManager's handler returns true. + * - No other handlers run, and edit chain is preserved. + * + * Case 3: User accepts a next edit suggestion from a ghost text. + * - vscode fires onDidChangeTextEditorSelection. + * - State is captured with document and cursorPosition. + * - GhostTextTracker's handler checks if ghost text was accepted at that position. + * - If accepted, handler returns true and edit chain is preserved. + * + * Case 4: User is actively typing code. + * - Each keystroke triggers documentChanged() to update lastDocumentChangeTime. + * - When cursor moves due to typing, onDidChangeTextEditorSelection fires. + * - State is captured with isTypingSession=true and recent lastDocumentChangeTime. + * - Typing session handler detects time since last edit is < TYPING_DELAY. + * - Handler returns true, preserving the edit chain during typing. + * + * Case 5: User performs a jump operation. + * - Jump is initiated, setting jumpInProgress to true. + * - When cursor position changes due to jump, onDidChangeTextEditorSelection fires. + * - State is captured with jumpInProgress=true. + * - JumpManager's handler returns true, preserving the edit chain. + * + * Case 6: User just completed a jump operation. + * - Jump completes, setting jumpJustAccepted to true. + * - onDidChangeTextEditorSelection fires for the final position. + * - State is captured with jumpJustAccepted=true. + * - JumpManager's handler returns true, preserving the edit chain. + * + * Case 7: Rapid cursor movements (debouncing). + * - User rapidly moves cursor (e.g., holding an arrow key). + * - Multiple onDidChangeTextEditorSelection events fire in quick succession. + * - Events within DEBOUNCE_DELAY of each other are queued. + * - Only the most recent event in a rapid sequence gets processed. + * - Prevents performance issues from too many events. + * + * Case 8: Event processing timeout. + * - An event handler takes longer than PROCESSING_TIMEOUT. + * - The timeout promise resolves first, throwing an error. + * - Error is caught, processing state is reset to prevent deadlocks. + * - System can continue processing the next event. + * - NOTE: At the current moment, there should not be any deadlocks, but I'm just making sure. + * + * Case 9: Error in handler. + * - One of the handlers throws an exception. + * - The error is caught and logged. + * - Processing continues with the next handler rather than failing completely. + * - Ensures stability even when individual handlers have problems. + * + * Case 10: Multiple queued events. + * - An event is being processed when new events arrive. + * - New events are added to eventQueue. + * - After current event is processed, queued events are handled sequentially. + * - Ensures all events are processed in the order they were received. + * - NOTE: I'm not sure if we even want to queue these events... + */ export class SelectionChangeManager { private static instance: SelectionChangeManager; private listeners: HandlerRegistration[] = []; @@ -57,7 +127,6 @@ export class SelectionChangeManager { private typingTimer: NodeJS.Timeout | null = null; private lastDocumentChangeTime = 0; private readonly TYPING_SESSION_TIMEOUT = 2000; // ms - private readonly TYPING_DELAY = 500; // ms private constructor() {} @@ -147,6 +216,7 @@ export class SelectionChangeManager { this.lastEventTime = now; // Queue this event for later if the manager is already processing an event. + // NOTE: Depending on if we want an event bus or not, do an early return instead. if (this.isProcessingEvent) { this.eventQueue.push(e); return; @@ -157,6 +227,7 @@ export class SelectionChangeManager { await this.processEventWithTimeout(e); // Process remaining queued events sequentially. + // NOTE: Depending on if we want an event bus or not, skip this. while (this.eventQueue.length > 0) { const nextEvent = this.eventQueue.shift()!; await this.processEventWithTimeout(nextEvent); @@ -208,7 +279,7 @@ export class SelectionChangeManager { private async processEvent( e: vscode.TextEditorSelectionChangeEvent, ): Promise { - const snapshot = this.captureState(); + const snapshot = this.captureState(e); for (const { handler } of this.listeners) { try { @@ -222,7 +293,9 @@ export class SelectionChangeManager { } } - private captureState(): StateSnapshot { + private captureState( + e: vscode.TextEditorSelectionChangeEvent, + ): StateSnapshot { return { nextEditWindowAccepted: NextEditWindowManager.isInstantiated() && @@ -231,6 +304,8 @@ export class SelectionChangeManager { jumpJustAccepted: JumpManager.getInstance().wasJumpJustAccepted(), lastDocumentChangeTime: this.lastDocumentChangeTime, isTypingSession: this.isTypingSession, + document: e.textEditor.document, + cursorPosition: e.selections[0].active, }; } From b784a2913a11563a2ceb532b35f4551dbac60ba0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 1 Aug 2025 10:34:50 -0700 Subject: [PATCH 12/48] chore: fix comments --- extensions/vscode/src/autocomplete/completionProvider.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d50d5c838..33e6f1412 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -580,9 +580,7 @@ export class ContinueCompletionProvider // At this point, there is no way that diffLines.length === 0. // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse. // In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place. - // In case of initial response, this could actually happen. - // We just suggest a jump at this point. - // If this were to be true, we wouldn't have even + // In case of initial response, we suggested a jump. console.log( "deleteChain from completionProvider.ts: diffLines.length === 0", ); From 6a0eaa472c2b82477e01ed9c2bf688179b016d91 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 1 Aug 2025 10:37:14 -0700 Subject: [PATCH 13/48] refactor: move event to selection change manager --- .../vscode/src/autocomplete/GhostTextAcceptanceTracker.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts index 30110a341..fbb4ac8ae 100644 --- a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -125,9 +125,13 @@ export class GhostTextAcceptanceTracker { manager.registerListener( "ghostTextTracker", async (e, state) => { + if (!state.document || !state.cursorPosition) { + return false; + } + const wasGhostTextAccepted = this.checkGhostTextWasAccepted( - e.textEditor.document, - e.selections[0].active, + state.document, + state.cursorPosition, ); if (wasGhostTextAccepted) { From da3876adc0da737fd5b2d458a5f05994ec600aa0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 1 Aug 2025 11:11:46 -0700 Subject: [PATCH 14/48] feat: abort prefetch queue --- core/nextEdit/NextEditProvider.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index cfb44a950..0632596ef 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -29,6 +29,7 @@ import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { calculateFinalCursorPosition } from "./diff/diff.js"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; +import { PrefetchQueue } from "./NextEditPrefetchQueue.js"; import { renderDefaultSystemPrompt, renderDefaultUserPrompt, @@ -214,6 +215,8 @@ export class NextEditProvider { } public async deleteChain(): Promise { + PrefetchQueue.getInstance().abort(); + this.currentEditChainId = null; this.previousCompletions = []; // TODO: this should be cleaned up in the prefetch queue. From 2f97143333975ae231a467ad0067ed6c05b3b927 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:51:06 -0700 Subject: [PATCH 15/48] feat: add a sliding window strategy --- .../NextEditEditableRegionCalculator.ts | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 0bb9537d7..57818271d 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -2,9 +2,14 @@ import Parser from "web-tree-sitter"; import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; import { getAst } from "../autocomplete/util/ast"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; +import { + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, +} from "./constants"; export enum EditableRegionStrategy { Naive = "naive", + Sliding = "sliding", Rerank = "rerank", StaticRerank = "staticRerank", Static = "static", @@ -17,6 +22,8 @@ export async function getNextEditableRegion( switch (strategy) { case EditableRegionStrategy.Naive: return naiveJump(ctx); + case EditableRegionStrategy.Sliding: + return slidingJump(ctx); case EditableRegionStrategy.Rerank: return await rerankJump(ctx); case EditableRegionStrategy.StaticRerank: @@ -51,6 +58,64 @@ function naiveJump(ctx: any): RangeInFile[] | null { ]; } +// Sliding splits the file using into sliding window. +function slidingJump(ctx: any): RangeInFile[] | null { + const { fileLines, filepath } = ctx; + if (!fileLines || !filepath) { + console.warn("Missing required context for naive jump"); + return null; + } + + const windowSize = + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN + + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN + + 1; // 1 for current line; + + if (fileLines.length <= windowSize) { + return [ + { + filepath, + range: { + start: { line: 0, character: 0 }, + end: { + line: fileLines.length - 1, + character: fileLines[fileLines.length - 1].length, + }, + }, + }, + ]; + } + + const slidingStep = Math.max(1, Math.floor(windowSize / 2)); + const ranges: RangeInFile[] = []; + + for ( + let startLine = 0; + startLine < fileLines.length; + startLine += slidingStep + ) { + const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1); + + ranges.push({ + filepath, + range: { + start: { line: startLine, character: 0 }, + end: { + line: endLine, + character: fileLines[endLine].length, + }, + }, + }); + + if (endLine >= fileLines.length - 1) { + break; + } + } + + console.log("ranges:", ranges.length); + return ranges; +} + // 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: { From 3c66709ae8e202c3b7780bfdc903de029ac0d3b9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:51:20 -0700 Subject: [PATCH 16/48] chore: remove console.log --- core/nextEdit/NextEditEditableRegionCalculator.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 57818271d..7ced3b435 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -112,7 +112,6 @@ function slidingJump(ctx: any): RangeInFile[] | null { } } - console.log("ranges:", ranges.length); return ranges; } From 61d27c530ca82508033b34a956a42179a8973538 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:51:48 -0700 Subject: [PATCH 17/48] fix: pass the current file path and a system prompt --- core/nextEdit/NextEditProvider.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0632596ef..28839f1ab 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -344,7 +344,8 @@ export class NextEditProvider { currentFileContent: helper.fileContents, editableRegionStartLine, editableRegionEndLine, - editDiffHistory: historyDiff, + editDiffHistory: this.diffContext, + currentFilePath: helper.filepath, }; } else if (modelName.includes("model-1")) { ctx = { @@ -360,15 +361,20 @@ export class NextEditProvider { this.promptMetadata = promptMetadata; + prompts.push({ + role: "system", + content: + "You are Mercury, created by Inception Labs. You are an AI Assistant and an expert at coding. Your role as an AI assistant is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'\''s possible these are entirely irrelevant to the developer'\''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'\''s intentions. These changes are listed from oldest to latest. It'\''s possible a lot of old edit diff history is entirely irrelevant to the developer'\''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'\''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'\''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'\''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'\''s last change unless there are obvious typos or errors.\n- Don'\''t include the line numbers of the form #| in your response.", + }); + // 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"), + // "Respect the user's changes and predict a next edit based on the user's changes.", + // "Don't revert the user's edits. The user has made that edit intentionally.", + // "Whenever you think that reverting the change is a good idea, stop and think one more time.", + // "The user made this change -- what would be the logical next change that the user would make?", + // ].join(" "), // }); prompts.push(promptMetadata.prompt); @@ -437,6 +443,10 @@ export class NextEditProvider { ).replace(/\n$/, "") : ""; + // console.log("outcome is null?", nextCompletion === null); + + // console.log("metadata:", msg.content, prompts[0]); + const currCursorPos = helper.pos; const editableRegionStartLine = Math.max( From f404a4d5ffde09a65f262f3d0c0c1bbde0b9023a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:52:00 -0700 Subject: [PATCH 18/48] feat: add currentFilePath field --- core/nextEdit/types.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 5b3d96eee..8c28bc5f9 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -93,4 +93,5 @@ export interface MercuryTemplateVars extends TemplateVars { recentlyViewedCodeSnippets: string; currentFileContent: string; editDiffHistory: string; // could be a singe large unified diff + currentFilePath: string; } From 1579375550f505ddbbb9b10998f9824fbb64b291 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:52:16 -0700 Subject: [PATCH 19/48] fix: remove the first two lines generated by createDiff --- core/nextEdit/templating/mercuryCoderNextEdit.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.ts b/core/nextEdit/templating/mercuryCoderNextEdit.ts index 616700b17..d87923969 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.ts @@ -48,7 +48,10 @@ export function currentFileContentBlock( export function editHistoryBlock( editDiffHistory: string, // could be a singe large unified diff ) { - return editDiffHistory; + // diffHistory is made from createDiff. + // This uses createPatch from npm diff library, which includes an index line and a separator. + // We get rid of these first two lines. + return editDiffHistory.split("\n").slice(2).join("\n"); } function mercuryNextEditTemplateBuilder( From eba4e0b1370fc98a41819c29649e80f72e0440b9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:52:48 -0700 Subject: [PATCH 20/48] fix: update prompt template --- core/nextEdit/templating/NextEditPromptEngine.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 1369ebbc6..5b8e93f14 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -40,7 +40,7 @@ export type NextEditModelName = const NEXT_EDIT_MODEL_TEMPLATES: Record = { "mercury-coder-nextedit": { - template: `${RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${CURRENT_FILE_CONTENT_CLOSE}\n\n${EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at [CURRENT FILE PATH].\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, + template: `${RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${CURRENT_FILE_CONTENT_CLOSE}\n\n${EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, "model-1": { template: @@ -125,6 +125,7 @@ export async function renderPrompt( helper.pos, ), editDiffHistory: editHistoryBlock(ctx.editDiffHistory), + currentFilePath: ctx.currentFilePath, }; tv = mercuryCtx; From c3dcacf1a361dab24b1d169681937b4f74d00230 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:53:00 -0700 Subject: [PATCH 21/48] fix: simplify logic --- .../vscode/src/activation/JumpManager.ts | 68 ++++++++----------- 1 file changed, 30 insertions(+), 38 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 82724405c..7d3adb73c 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -59,11 +59,13 @@ export class JumpManager { // identical to the completion content, // then we don't have to jump. if (completionContent !== undefined) { + console.log("completionContent is not null"); const editor = vscode.window.activeTextEditor; if (editor) { try { const completionLines = completionContent.split("\n"); + console.log("completionLines:", completionLines); // Get document content at jump location spanning multiple lines. const document = editor.document; @@ -73,51 +75,40 @@ export class JumpManager { document.lineCount - 1, ); - // Check if we have enough lines in the document to compare. + console.log( + "editor lines:", + document + .getText() + .split("\n") + .slice(startLine, endLine + 1), + ); + + // First check if we have enough lines in the document 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, + console.log( + "Not enough lines in document to match completion content", ); - const firstCompletionLine = completionLines[0]; + } else { + let contentMatches = true; - 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 false; // 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 false; // Exit early, don't suggest jump. + // Check all lines for match. + for (let i = 0; i < completionLines.length && contentMatches; i++) { + const documentLine = startLine + i; + const lineText = document.lineAt(documentLine).text; + if (lineText !== completionLines[i]) { + contentMatches = false; + console.log(`Line ${i + 1} doesn't match`); } } + + if (contentMatches) { + console.log( + "Skipping jump as content is identical at jump location", + ); + return false; // Exit early, don't suggest jump. + } } } catch (error) { console.error("Error checking content at jump location:", error); @@ -261,6 +252,7 @@ export class JumpManager { await this.clearJumpDecoration(); this._jumpAccepted = false; + vscode.commands.executeCommand("editor.action.inlineSuggest.trigger"); } }, ); From d93e5a2e1b1a199d360ffee874a205946d4d34e0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:53:15 -0700 Subject: [PATCH 22/48] feat: try using sliding strategy --- .../vscode/src/activation/SelectionChangeManager.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/activation/SelectionChangeManager.ts b/extensions/vscode/src/activation/SelectionChangeManager.ts index 964b5fadf..150f630d4 100644 --- a/extensions/vscode/src/activation/SelectionChangeManager.ts +++ b/extensions/vscode/src/activation/SelectionChangeManager.ts @@ -324,10 +324,14 @@ export class SelectionChangeManager { await NextEditProvider.getInstance().deleteChain(); const nextEditableRegions = - (await getNextEditableRegion(EditableRegionStrategy.Static, { - cursorPosition: e.selections[0].anchor, + // (await getNextEditableRegion(EditableRegionStrategy.Static, { + // cursorPosition: e.selections[0].anchor, + // filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), + // ide: this.ide, + // })) ?? []; + (await getNextEditableRegion(EditableRegionStrategy.Sliding, { filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), - ide: this.ide, + fileLines: e.textEditor.document.getText().split("\n"), })) ?? []; nextEditableRegions.forEach((region) => { From 022d202c787b7e52819c487156572623ad1d328b Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 18:53:40 -0700 Subject: [PATCH 23/48] fix: only make a recursive call when outcome is null --- .../src/autocomplete/completionProvider.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 33e6f1412..59b70b625 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -337,6 +337,7 @@ export class ContinueCompletionProvider if (isJumpSuggested) { // Store completion to be rendered after a jump. + // TODO: setCompletionAfterJump must have a 1-1 correspondence to the jump location. this.jumpManager.setCompletionAfterJump({ completionId: completionId, outcome, @@ -378,17 +379,19 @@ export class ContinueCompletionProvider // Start prefetching next edits. // NOTE: this might be better off not awaited. - await this.prefetchQueue.process(ctx); + this.prefetchQueue.process(ctx); // If initial outcome is null, suggest a jump instead. // Calling this method again will call it with // chain active but jump not suggested yet. - return this.provideInlineCompletionItems( - document, - position, - context, - token, - ); + if (!outcome || !outcome.completion) { + return this.provideInlineCompletionItems( + document, + position, + context, + token, + ); + } } else { // Handle regular autocomplete request. outcome = await this.completionProvider.provideInlineCompletionItems( From 863f187aa433a26466c325fdccaea9fcf5e51045 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 2 Aug 2025 22:43:52 -0700 Subject: [PATCH 24/48] feat: add a new diff group creator --- core/nextEdit/diff/diff.ts | 59 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index fdcb78fb4..34c894e20 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -266,3 +266,62 @@ export function applyCompletionToFile( return newLines.join("\n"); } + +export interface DiffGroup { + startLine: number; + endLine: number; + lines: DiffLine[]; + type?: string; // Optional classification of the group +} + +export function groupDiffLines( + diffLines: DiffLine[], + maxGap: number = 3, +): DiffGroup[] { + const groups: DiffGroup[] = []; + let currentGroup: DiffGroup | null = null; + let lineNumber = 0; + + for (let i = 0; i < diffLines.length; i++) { + const line = diffLines[i]; + + // If it's a changed line and we don't have a current group, start one + if (line.type !== "same" && !currentGroup) { + currentGroup = { + startLine: lineNumber, + endLine: lineNumber, + lines: [line], + }; + } + // If it's a changed line and we have a current group, add to it + else if (line.type !== "same" && currentGroup) { + currentGroup.lines.push(line); + currentGroup.endLine = lineNumber; + } + // If it's an unchanged line and we have a current group + else if (line.type === "same" && currentGroup) { + // Check if we've seen too many unchanged lines in a row + const unchangedCount = currentGroup.lines.filter( + (l) => l.type === "same", + ).length; + + if (unchangedCount >= maxGap) { + // Finalize this group and start a new one + groups.push(currentGroup); + currentGroup = null; + } else { + // Add this unchanged line to the current group + currentGroup.lines.push(line); + } + } + + lineNumber++; + } + + // Don't forget the last group if there is one + if (currentGroup) { + groups.push(currentGroup); + } + + return groups; +} From bc66ca8a58e386dc0bbbb208d40ab7a693b2cff8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 3 Aug 2025 13:10:37 -0700 Subject: [PATCH 25/48] feat: pass the fullFileDiff flag --- core/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index 2db7856d1..b91c8318d 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, - { withChain: false }, + { withChain: false, fullFileDiff: true }, ); return outcome ? [outcome.completion, outcome.originalEditableRange] : []; }); From 9a460bf5d90dc524f7770a5b037ca6d4fd7478b8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 3 Aug 2025 13:11:25 -0700 Subject: [PATCH 26/48] refactor: make enqueueProcessed public --- core/nextEdit/NextEditPrefetchQueue.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 38b5589c6..8581e6d5a 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -37,7 +37,7 @@ export class PrefetchQueue { return this.unprocessedQueue.shift(); } - private enqueueProcessed(item: ProcessedItem): void { + enqueueProcessed(item: ProcessedItem): void { this.processedQueue.push(item); } @@ -61,6 +61,7 @@ export class PrefetchQueue { ctx, location, this.abortController.signal, + true, ); if (!outcome) continue; From b92aa3209001c014db7542e373abe46eccb839f8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 3 Aug 2025 13:11:56 -0700 Subject: [PATCH 27/48] fix: properly handle diff groups to use maxGroupSize instead of maxGap --- core/nextEdit/diff/diff.ts | 97 ++++++++++++++++++++++++-------------- 1 file changed, 62 insertions(+), 35 deletions(-) diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index 34c894e20..f0316d56d 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -276,51 +276,78 @@ export interface DiffGroup { export function groupDiffLines( diffLines: DiffLine[], - maxGap: number = 3, + maxGroupSize: number = 5, ): DiffGroup[] { const groups: DiffGroup[] = []; - let currentGroup: DiffGroup | null = null; - let lineNumber = 0; + + // First pass: find areas where changes occur + let changedAreaStart = -1; for (let i = 0; i < diffLines.length; i++) { - const line = diffLines[i]; - - // If it's a changed line and we don't have a current group, start one - if (line.type !== "same" && !currentGroup) { - currentGroup = { - startLine: lineNumber, - endLine: lineNumber, - lines: [line], - }; + if (diffLines[i].type !== "same" && changedAreaStart === -1) { + changedAreaStart = i; + } else if (diffLines[i].type === "same" && changedAreaStart !== -1) { + // We've found the end of a changed area, process it + processChangedArea(changedAreaStart, i - 1); + changedAreaStart = -1; } - // If it's a changed line and we have a current group, add to it - else if (line.type !== "same" && currentGroup) { - currentGroup.lines.push(line); - currentGroup.endLine = lineNumber; - } - // If it's an unchanged line and we have a current group - else if (line.type === "same" && currentGroup) { - // Check if we've seen too many unchanged lines in a row - const unchangedCount = currentGroup.lines.filter( - (l) => l.type === "same", - ).length; + } - if (unchangedCount >= maxGap) { - // Finalize this group and start a new one - groups.push(currentGroup); - currentGroup = null; - } else { - // Add this unchanged line to the current group - currentGroup.lines.push(line); + // Handle the last changed area if it extends to the end + if (changedAreaStart !== -1) { + processChangedArea(changedAreaStart, diffLines.length - 1); + } + + function processChangedArea(start: number, end: number) { + // Calculate result line numbers + let resultLineStart = 0; + + // Count how many result lines appear before the start + for (let i = 0; i < start; i++) { + if (diffLines[i].type !== "old") { + resultLineStart++; } } - lineNumber++; - } + // Create a group from the change area + const changedLines = diffLines.slice(start, end + 1); - // Don't forget the last group if there is one - if (currentGroup) { - groups.push(currentGroup); + // Count how many additional lines we can include + const changedResultLineCount = changedLines.filter( + (l) => l.type !== "old", + ).length; + const additionalLinesNeeded = maxGroupSize - changedResultLineCount; + + // Add additional context lines after the change + let additionalLines: DiffLine[] = []; + let additionalResultLineCount = 0; + + for ( + let i = end + 1; + i < diffLines.length && additionalResultLineCount < additionalLinesNeeded; + i++ + ) { + additionalLines.push(diffLines[i]); + if (diffLines[i].type !== "old") { + additionalResultLineCount++; + } + } + + // Calculate the ending result line number + let resultLineEnd = resultLineStart; + for (const line of [...changedLines, ...additionalLines]) { + if (line.type !== "old") { + resultLineEnd++; + } + } + resultLineEnd--; // Adjust because we incremented one too many times + + // Create the group + groups.push({ + startLine: resultLineStart, + endLine: resultLineEnd, + lines: [...changedLines, ...additionalLines], + }); } return groups; From da3230eef75a568837ab3728c9b50e65a30c35b9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 3 Aug 2025 13:12:35 -0700 Subject: [PATCH 28/48] feat: handle cases where fullFileDiff is true --- core/nextEdit/NextEditProvider.ts | 354 ++++++++++++++++++++++++------ 1 file changed, 288 insertions(+), 66 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 28839f1ab..4aa378b81 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,7 +1,14 @@ import * as path from "path"; import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js"; +import { + ChatMessage, + IDE, + ILLM, + Position, + Range, + RangeInFile, +} from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; @@ -18,6 +25,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 { myersDiff } from "../diff/myers.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { @@ -26,7 +34,11 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; -import { calculateFinalCursorPosition } from "./diff/diff.js"; +import { + calculateFinalCursorPosition, + DiffGroup, + groupDiffLines, +} from "./diff/diff.js"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; import { PrefetchQueue } from "./NextEditPrefetchQueue.js"; @@ -254,6 +266,7 @@ export class NextEditProvider { token: AbortSignal | undefined, opts?: { withChain: boolean; + fullFileDiff: boolean; }, ): Promise { try { @@ -303,15 +316,18 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); - const editableRegionStartLine = Math.max( - helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - 0, - ); + // 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 editableRegionEndLine = Math.min( + // helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + // helper.fileLines.length - 1, + // ); + + const editableRegionStartLine = 0; + const editableRegionEndLine = helper.fileLines.length - 1; // TODO: Toggle between the default endpoint and the finetuned endpoint. const prompts: Prompt[] = []; @@ -385,12 +401,16 @@ export class NextEditProvider { .slice(editableRegionStartLine, editableRegionEndLine + 1) .join("\n"); - const finalCursorPos = calculateFinalCursorPosition( - helper.pos, - editableRegionStartLine, - oldEditRangeSlice, - "", - ); + // const finalCursorPos = calculateFinalCursorPosition( + // helper.pos, + // editableRegionStartLine, + // oldEditRangeSlice, + // "", + // ); + const finalCursorPos: Position = { + line: editableRegionEndLine, + character: 0, + }; if (this.endpointType === "default") { const msg: ChatMessage = await llm.chat(prompts, token); @@ -447,64 +467,264 @@ export class NextEditProvider { // console.log("metadata:", msg.content, prompts[0]); - const currCursorPos = helper.pos; + if (opts?.fullFileDiff === false || !opts?.fullFileDiff) { + const currCursorPos = helper.pos; - const editableRegionStartLine = Math.max( - currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - 0, - ); + 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 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) - .join("\n"); + const oldEditRangeSlice = helper.fileContents + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); - const finalCursorPos = calculateFinalCursorPosition( - helper.pos, - editableRegionStartLine, - oldEditRangeSlice, - nextCompletion, - ); + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + nextCompletion, + ); - const outcomeNext: NextEditOutcome = { - elapsed: Date.now() - startTime, - modelProvider: llm.underlyingProviderName, - modelName: llm.model + ":zetaDataset", - completionOptions: null, - completionId: helper.input.completionId, - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: helper.filepath, - workspaceDirUri: - helper.workspaceUris[0] ?? path.dirname(helper.filepath), - prompt: this.promptMetadata!.prompt.content, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: oldEditRangeSlice, - completion: nextCompletion, - cursorPosition: helper.pos, - finalCursorPosition: finalCursorPos, - editableRegionStartLine, - editableRegionEndLine, - ...helper.options, - }; + const outcomeNext: NextEditOutcome = { + elapsed: Date.now() - startTime, + modelProvider: llm.underlyingProviderName, + modelName: llm.model + ":zetaDataset", + completionOptions: null, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + fileUri: helper.filepath, + workspaceDirUri: + helper.workspaceUris[0] ?? path.dirname(helper.filepath), + prompt: this.promptMetadata!.prompt.content, + userEdits: this.promptMetadata!.userEdits, + userExcerpts: this.promptMetadata!.userExcerpts, + originalEditableRange: oldEditRangeSlice, + completion: nextCompletion, + cursorPosition: helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine, + editableRegionEndLine, + ...helper.options, + }; - this.previousCompletions.push(outcomeNext); + 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; - if (ideType === "jetbrains") { - this.markDisplayed(input.completionId, 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; + if (ideType === "jetbrains") { + this.markDisplayed(input.completionId, outcomeNext); + } + + return outcomeNext; + } else { + // At this point, the model outputted an new file, basically. + // We run a myersDiff on the input file content and the model's output. + // Run the DiffLines through groupDiffLines and get a list of DiffGroup. + // Extract out the DiffGroup containing the current cursor position. + // Insert the remaining DiffGroups into Prefetch Queue's processedQueue. + // When pushing, make sure to build a ProcessedItem by building a RangeInFile and NextEditOutcome based on the DiffGroup's position and contents. + // Build a NextEditOutcome based on the extracted DiffGroup, and return it. + + // At this point, the model outputted an new file, basically. + // We run a myersDiff on the input file content and the model's output. + const diffLines = myersDiff(helper.fileContents, nextCompletion); + + // Run the DiffLines through groupDiffLines and get a list of DiffGroup. + const diffGroups = groupDiffLines(diffLines); + + // Extract out the DiffGroup containing the current cursor position. + const currentLine = helper.pos.line; + let cursorLocalDiffGroup: DiffGroup | undefined; + const prefetchQueue = PrefetchQueue.getInstance(); + + // Find the diff group containing the cursor position and queue others for prefetch + console.log("diffGroups:"); + console.log(diffGroups); + for (const group of diffGroups) { + if ( + currentLine >= group.startLine && + currentLine <= group.endLine + ) { + cursorLocalDiffGroup = group; + } else { + // Insert the remaining DiffGroups into Prefetch Queue's processedQueue. + const groupContent = group.lines + .filter((l) => l.type !== "old") + .map((l) => l.line) + .join("\n"); + + // Create a range for this diff group + const rangeInFile: RangeInFile = { + filepath: helper.filepath, + range: { + start: { line: group.startLine, character: 0 }, + end: { + line: group.endLine, + character: + group.lines[group.lines.length - 1].line.length, + }, + }, + }; + + // Build outcome for this diff group + const groupOutcome: NextEditOutcome = { + elapsed: Date.now() - startTime, + modelProvider: llm.underlyingProviderName, + modelName: llm.model + ":zetaDataset", + completionOptions: null, + completionId: uuidv4(), // Generate a new ID for this prefetched item + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + fileUri: helper.filepath, + workspaceDirUri: + helper.workspaceUris[0] ?? path.dirname(helper.filepath), + prompt: this.promptMetadata!.prompt.content, + userEdits: this.promptMetadata!.userEdits, + userExcerpts: this.promptMetadata!.userExcerpts, + originalEditableRange: group.lines + .filter((l) => l.type !== "new") + .map((l) => l.line) + .join("\n"), + completion: groupContent, + cursorPosition: { line: group.startLine, character: 0 }, + finalCursorPosition: { + line: group.endLine, + character: group.lines[group.lines.length - 1].line.length, + }, + editableRegionStartLine: group.startLine, + editableRegionEndLine: group.endLine, + ...helper.options, + }; + + // Add to prefetch queue + prefetchQueue.enqueueProcessed({ + location: rangeInFile, + outcome: groupOutcome, + }); + } + } + + // If we found a diff group containing the cursor, create an outcome for it + if (cursorLocalDiffGroup) { + const currentGroupContent = cursorLocalDiffGroup.lines + .filter((l) => l.type !== "old") + .map((line) => line.line) + .join("\n"); + const originalContent = cursorLocalDiffGroup.lines + .filter((l) => l.type !== "new") + .map((l) => l.line) + .join("\n"); + + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + cursorLocalDiffGroup.startLine, + originalContent, + currentGroupContent, + ); + + const outcomeNext: NextEditOutcome = { + elapsed: Date.now() - startTime, + modelProvider: llm.underlyingProviderName, + modelName: llm.model + ":zetaDataset", + completionOptions: null, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + fileUri: helper.filepath, + workspaceDirUri: + helper.workspaceUris[0] ?? path.dirname(helper.filepath), + prompt: this.promptMetadata!.prompt.content, + userEdits: this.promptMetadata!.userEdits, + userExcerpts: this.promptMetadata!.userExcerpts, + originalEditableRange: originalContent, + completion: currentGroupContent, + cursorPosition: helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine: cursorLocalDiffGroup.startLine, + editableRegionEndLine: cursorLocalDiffGroup.endLine, + ...helper.options, + }; + + this.previousCompletions.push(outcomeNext); + + // When using the JetBrains extension, mark as displayed. + const ideType = (await this.ide.getIdeInfo()).ideType; + if (ideType === "jetbrains") { + this.markDisplayed(input.completionId, outcomeNext); + } + + return outcomeNext; + } else { + // If we couldn't find a diff group containing the cursor position, + // use the first diff group as a fallback + if (diffGroups.length > 0) { + const firstGroup = diffGroups[0]; + const groupContent = firstGroup.lines + .filter((l) => l.type !== "old") + .map((line) => line.line) + .join("\n"); + const originalContent = firstGroup.lines + .filter((l) => l.type !== "new") + .map((l) => l.line) + .join("\n"); + + const finalCursorPos = calculateFinalCursorPosition( + { line: firstGroup.startLine, character: 0 }, + firstGroup.startLine, + originalContent, + groupContent, + ); + + const outcomeNext: NextEditOutcome = { + elapsed: Date.now() - startTime, + modelProvider: llm.underlyingProviderName, + modelName: llm.model + ":zetaDataset", + completionOptions: null, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + fileUri: helper.filepath, + workspaceDirUri: + helper.workspaceUris[0] ?? path.dirname(helper.filepath), + prompt: this.promptMetadata!.prompt.content, + userEdits: this.promptMetadata!.userEdits, + userExcerpts: this.promptMetadata!.userExcerpts, + originalEditableRange: originalContent, + completion: groupContent, + cursorPosition: { line: firstGroup.startLine, character: 0 }, + finalCursorPosition: finalCursorPos, + editableRegionStartLine: firstGroup.startLine, + editableRegionEndLine: firstGroup.endLine, + ...helper.options, + }; + + this.previousCompletions.push(outcomeNext); + + // When using the JetBrains extension, mark as displayed. + const ideType = (await this.ide.getIdeInfo()).ideType; + if (ideType === "jetbrains") { + this.markDisplayed(input.completionId, outcomeNext); + } + + return outcomeNext; + } + + return undefined; + } } - - return outcomeNext; } else { return undefined; } @@ -531,6 +751,7 @@ export class NextEditProvider { }, nextEditLocation: RangeInFile, token: AbortSignal | undefined, + fullFileDiff: boolean, ) { try { const previousOutcome = this.getPreviousCompletion(); @@ -550,6 +771,7 @@ export class NextEditProvider { return await this.provideInlineCompletionItems(input, token, { withChain: true, + fullFileDiff, }); } catch (e: any) { this.onError(e); From a5506b1af12a81fea74fd750c0b85ff58db1261e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 3 Aug 2025 13:13:35 -0700 Subject: [PATCH 29/48] feat: use full file diff --- .../src/autocomplete/completionProvider.ts | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 59b70b625..de94ede49 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -14,10 +14,6 @@ import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; 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 { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue"; @@ -295,12 +291,12 @@ export class ContinueCompletionProvider outcome = this.prefetchQueue.dequeueProcessed()?.outcome; // Fill in the spot after dequeuing. - this.prefetchQueue.process({ - ...ctx, - recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), - recentlyEditedRanges: - await this.recentlyEditedTracker.getRecentlyEditedRanges(), - }); + // this.prefetchQueue.process({ + // ...ctx, + // recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), + // recentlyEditedRanges: + // await this.recentlyEditedTracker.getRecentlyEditedRanges(), + // }); } } else if (chainExists) { // Case 3: Accepting next edit outcome (chain exists, jump is not taken). @@ -314,12 +310,12 @@ export class ContinueCompletionProvider if (!nextItemInQueue) continue; // Fill in the spot after dequeuing. - this.prefetchQueue.process({ - ...ctx, - recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), - recentlyEditedRanges: - await this.recentlyEditedTracker.getRecentlyEditedRanges(), - }); + // this.prefetchQueue.process({ + // ...ctx, + // recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), + // recentlyEditedRanges: + // await this.recentlyEditedTracker.getRecentlyEditedRanges(), + // }); const nextLocation = nextItemInQueue.location; outcome = nextItemInQueue.outcome; @@ -374,12 +370,12 @@ export class ContinueCompletionProvider outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, - { withChain: false }, + { withChain: false, fullFileDiff: true }, ); // Start prefetching next edits. // NOTE: this might be better off not awaited. - this.prefetchQueue.process(ctx); + // this.prefetchQueue.process(ctx); // If initial outcome is null, suggest a jump instead. // Calling this method again will call it with @@ -510,14 +506,18 @@ export class ContinueCompletionProvider } // Get the contents of the old (current) editable region. - 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, - editor.document.lineCount - 1, - ); + // 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, + // editor.document.lineCount - 1, + // ); + const editableRegionStartLine = (outcome as NextEditOutcome) + .editableRegionStartLine; + const editableRegionEndLine = (outcome as NextEditOutcome) + .editableRegionEndLine; const oldEditRangeSlice = editor.document .getText() .split("\n") From a49e8cbbd5dea589c3fdc10b1b38f04a75506aa1 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 3 Aug 2025 13:25:45 -0700 Subject: [PATCH 30/48] feat: toggle given fullFileDiff --- core/nextEdit/NextEditProvider.ts | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 4aa378b81..19ec5040a 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -316,18 +316,16 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); - // const editableRegionStartLine = Math.max( - // helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - // 0, - // ); + const editableRegionStartLine = opts?.fullFileDiff + ? 0 + : 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 editableRegionStartLine = 0; - const editableRegionEndLine = helper.fileLines.length - 1; + const editableRegionEndLine = opts?.fullFileDiff + ? helper.fileLines.length - 1 + : Math.min( + helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + helper.fileLines.length - 1, + ); // TODO: Toggle between the default endpoint and the finetuned endpoint. const prompts: Prompt[] = []; From bdcfa85df19d0a8ff8526664d3419ec3f7dd566b Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 3 Aug 2025 13:43:15 -0700 Subject: [PATCH 31/48] refactor: initialize usingFullFileDiff once --- core/core.ts | 2 +- core/nextEdit/NextEditPrefetchQueue.ts | 8 +++- core/nextEdit/NextEditProvider.ts | 12 +++--- .../src/activation/SelectionChangeManager.ts | 28 ++++++++------ .../src/autocomplete/completionProvider.ts | 38 ++++++++++++------- .../vscode/src/extension/VsCodeExtension.ts | 4 +- 6 files changed, 57 insertions(+), 35 deletions(-) diff --git a/core/core.ts b/core/core.ts index b91c8318d..46e0f245c 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, - { withChain: false, fullFileDiff: true }, + { withChain: false, usingFullFileDiff: true }, ); return outcome ? [outcome.completion, outcome.originalEditableRange] : []; }); diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 8581e6d5a..5cbb7ddc8 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -15,6 +15,8 @@ export class PrefetchQueue { private prefetchLimit: number; private abortController: AbortController; + private usingFullFileDiff: boolean = true; + private constructor(prefetchLimit: number = 3) { this.prefetchLimit = prefetchLimit; this.abortController = new AbortController(); @@ -28,6 +30,10 @@ export class PrefetchQueue { return PrefetchQueue.instance; } + initialize(usingFullFileDiff: boolean) { + this.usingFullFileDiff = usingFullFileDiff; + } + // Queue management methods enqueueUnprocessed(location: RangeInFile): void { this.unprocessedQueue.push(location); @@ -61,7 +67,7 @@ export class PrefetchQueue { ctx, location, this.abortController.signal, - true, + this.usingFullFileDiff, ); if (!outcome) continue; diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 19ec5040a..c4ddb8714 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -266,7 +266,7 @@ export class NextEditProvider { token: AbortSignal | undefined, opts?: { withChain: boolean; - fullFileDiff: boolean; + usingFullFileDiff: boolean; }, ): Promise { try { @@ -316,11 +316,11 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); - const editableRegionStartLine = opts?.fullFileDiff + const editableRegionStartLine = opts?.usingFullFileDiff ? 0 : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); - const editableRegionEndLine = opts?.fullFileDiff + const editableRegionEndLine = opts?.usingFullFileDiff ? helper.fileLines.length - 1 : Math.min( helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, @@ -465,7 +465,7 @@ export class NextEditProvider { // console.log("metadata:", msg.content, prompts[0]); - if (opts?.fullFileDiff === false || !opts?.fullFileDiff) { + if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { const currCursorPos = helper.pos; const editableRegionStartLine = Math.max( @@ -749,7 +749,7 @@ export class NextEditProvider { }, nextEditLocation: RangeInFile, token: AbortSignal | undefined, - fullFileDiff: boolean, + usingFullFileDiff: boolean, ) { try { const previousOutcome = this.getPreviousCompletion(); @@ -769,7 +769,7 @@ export class NextEditProvider { return await this.provideInlineCompletionItems(input, token, { withChain: true, - fullFileDiff, + usingFullFileDiff, }); } catch (e: any) { this.onError(e); diff --git a/extensions/vscode/src/activation/SelectionChangeManager.ts b/extensions/vscode/src/activation/SelectionChangeManager.ts index 150f630d4..d8851ce52 100644 --- a/extensions/vscode/src/activation/SelectionChangeManager.ts +++ b/extensions/vscode/src/activation/SelectionChangeManager.ts @@ -111,6 +111,7 @@ export class SelectionChangeManager { private static instance: SelectionChangeManager; private listeners: HandlerRegistration[] = []; private ide: VsCodeIde | null = null; + private usingFullFileDiff: boolean = true; // Event bus-related attributes. private eventQueue: vscode.TextEditorSelectionChangeEvent[] = []; @@ -137,8 +138,9 @@ export class SelectionChangeManager { return SelectionChangeManager.instance; } - public initialize(ide: VsCodeIde): void { + public initialize(ide: VsCodeIde, usingFullFileDiff: boolean): void { this.ide = ide; + this.usingFullFileDiff = usingFullFileDiff; // After handling all other listeners, this will delete the chain. this.registerListener( @@ -323,20 +325,22 @@ export class SelectionChangeManager { ); await NextEditProvider.getInstance().deleteChain(); - const nextEditableRegions = - // (await getNextEditableRegion(EditableRegionStrategy.Static, { - // cursorPosition: e.selections[0].anchor, + if (!this.usingFullFileDiff) { + const nextEditableRegions = + (await getNextEditableRegion(EditableRegionStrategy.Static, { + cursorPosition: e.selections[0].anchor, + filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), + ide: this.ide, + })) ?? []; + // (await getNextEditableRegion(EditableRegionStrategy.Sliding, { // filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), - // ide: this.ide, + // fileLines: e.textEditor.document.getText().split("\n"), // })) ?? []; - (await getNextEditableRegion(EditableRegionStrategy.Sliding, { - filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), - fileLines: e.textEditor.document.getText().split("\n"), - })) ?? []; - nextEditableRegions.forEach((region) => { - PrefetchQueue.getInstance().enqueueUnprocessed(region); - }); + nextEditableRegions.forEach((region) => { + PrefetchQueue.getInstance().enqueueUnprocessed(region); + }); + } return true; } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index de94ede49..d30930748 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -70,6 +70,7 @@ export class ContinueCompletionProvider public recentlyEditedTracker: RecentlyEditedTracker; private isNextEditActive: boolean = false; + private usingFullFileDiff: boolean = true; public activateNextEdit() { this.isNextEditActive = true; @@ -83,7 +84,9 @@ export class ContinueCompletionProvider private readonly configHandler: ConfigHandler, private readonly ide: VsCodeIde, private readonly webviewProtocol: VsCodeWebviewProtocol, + usingFullFileDiff: boolean, ) { + this.usingFullFileDiff = usingFullFileDiff; this.recentlyEditedTracker = new RecentlyEditedTracker(ide.ideUtils); async function getAutocompleteModel() { @@ -115,6 +118,7 @@ export class ContinueCompletionProvider this.jumpManager = JumpManager.getInstance(); this.prefetchQueue = PrefetchQueue.getInstance(); + this.prefetchQueue.initialize(this.usingFullFileDiff); this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide); } @@ -291,12 +295,14 @@ export class ContinueCompletionProvider outcome = this.prefetchQueue.dequeueProcessed()?.outcome; // Fill in the spot after dequeuing. - // this.prefetchQueue.process({ - // ...ctx, - // recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), - // recentlyEditedRanges: - // await this.recentlyEditedTracker.getRecentlyEditedRanges(), - // }); + if (!this.usingFullFileDiff) { + this.prefetchQueue.process({ + ...ctx, + recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), + recentlyEditedRanges: + await this.recentlyEditedTracker.getRecentlyEditedRanges(), + }); + } } } else if (chainExists) { // Case 3: Accepting next edit outcome (chain exists, jump is not taken). @@ -310,12 +316,14 @@ export class ContinueCompletionProvider if (!nextItemInQueue) continue; // Fill in the spot after dequeuing. - // this.prefetchQueue.process({ - // ...ctx, - // recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), - // recentlyEditedRanges: - // await this.recentlyEditedTracker.getRecentlyEditedRanges(), - // }); + if (!this.usingFullFileDiff) { + this.prefetchQueue.process({ + ...ctx, + recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), + recentlyEditedRanges: + await this.recentlyEditedTracker.getRecentlyEditedRanges(), + }); + } const nextLocation = nextItemInQueue.location; outcome = nextItemInQueue.outcome; @@ -370,12 +378,14 @@ export class ContinueCompletionProvider outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, - { withChain: false, fullFileDiff: true }, + { withChain: false, usingFullFileDiff: this.usingFullFileDiff }, ); // Start prefetching next edits. // NOTE: this might be better off not awaited. - // this.prefetchQueue.process(ctx); + if (!this.usingFullFileDiff) { + this.prefetchQueue.process(ctx); + } // If initial outcome is null, suggest a jump instead. // Calling this method again will call it with diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 90d017628..1e5fe8254 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -101,8 +101,9 @@ export class VsCodeExtension { this.extensionContext = context; this.windowId = uuidv4(); + const usingFullFileDiff = true; const selectionManager = SelectionChangeManager.getInstance(); - selectionManager.initialize(this.ide); + selectionManager.initialize(this.ide, usingFullFileDiff); selectionManager.registerListener( "typing", @@ -254,6 +255,7 @@ export class VsCodeExtension { this.configHandler, this.ide, this.sidebar.webviewProtocol, + usingFullFileDiff, ); context.subscriptions.push( vscode.languages.registerInlineCompletionItemProvider( From 24428b97d21b859e87271cedda64c8cc9b700bec Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 3 Aug 2025 14:44:53 -0700 Subject: [PATCH 32/48] refactor: clean up provideInlineCompletionItems method --- core/nextEdit/NextEditProvider.ts | 1004 ++++++++++++++++------------- 1 file changed, 552 insertions(+), 452 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index c4ddb8714..3f268675b 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -17,7 +17,10 @@ import { ContextRetrievalService } from "../autocomplete/context/ContextRetrieva import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; -import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; +import { + getAllSnippetsWithoutRace, + SnippetPayload, +} 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"; @@ -271,461 +274,34 @@ export class NextEditProvider { ): Promise { try { this.previousRequest = input; - // 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(); + const { + token: abortToken, + startTime, + helper, + } = await this._initializeCompletionRequest(input, token); + if (!helper) return undefined; - // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; - } + const { editableRegionStartLine, editableRegionEndLine, prompts } = + await this._generatePrompts(helper, opts); - 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; - } - - const [snippetPayload, workspaceDirs] = await Promise.all([ - getAllSnippetsWithoutRace({ + if (this.endpointType === "default") { + return await this._handleDefaultEndpointCompletion( helper, - ide: this.ide, - getDefinitionsFromLsp: this.getDefinitionsFromLsp, - contextRetrievalService: this.contextRetrievalService, - }), - this.ide.getWorkspaceDirs(), - ]); - - const editableRegionStartLine = opts?.usingFullFileDiff - ? 0 - : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); - - const editableRegionEndLine = opts?.usingFullFileDiff - ? helper.fileLines.length - 1 - : Math.min( - helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - helper.fileLines.length - 1, - ); - - // 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)); + prompts, + abortToken, + startTime, + editableRegionEndLine, + ); } else { - const historyDiff = createDiff({ - beforeContent: - DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( - localPathOrUriToPath(helper.filepath), - ) ?? "", - afterContent: helper.fileContents, - filePath: helper.filepath, - diffType: DiffFormatType.Unified, - contextLines: 3, - }); - - const modelName = helper.modelName; - let ctx: any; - - if (modelName.includes("mercury-coder-nextedit")) { - ctx = { - recentlyViewedCodeSnippets: - snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ - filepath: snip.filepath, - content: snip.content, - })) ?? [], - currentFileContent: helper.fileContents, - editableRegionStartLine, - editableRegionEndLine, - editDiffHistory: this.diffContext, - currentFilePath: helper.filepath, - }; - } else if (modelName.includes("model-1")) { - ctx = { - userEdits: historyDiff ?? this.diffContext, - languageShorthand: helper.lang.name, - userExcerpts: helper.fileContents, - }; - } else { - ctx = {}; - } - - const promptMetadata = await renderPrompt(helper, ctx); - - this.promptMetadata = promptMetadata; - - prompts.push({ - role: "system", - content: - "You are Mercury, created by Inception Labs. You are an AI Assistant and an expert at coding. Your role as an AI assistant is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'\''s possible these are entirely irrelevant to the developer'\''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'\''s intentions. These changes are listed from oldest to latest. It'\''s possible a lot of old edit diff history is entirely irrelevant to the developer'\''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'\''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'\''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'\''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'\''s last change unless there are obvious typos or errors.\n- Don'\''t include the line numbers of the form #| in your response.", - }); - - // prompts.push({ - // role: "system", - // content: [ - // "Respect the user's changes and predict a next edit based on the user's changes.", - // "Don't revert the user's edits. The user has made that edit intentionally.", - // "Whenever you think that reverting the change is a good idea, stop and think one more time.", - // "The user made this change -- what would be the logical next change that the user would make?", - // ].join(" "), - // }); - - prompts.push(promptMetadata.prompt); - } - - const oldEditRangeSlice = helper.fileContents - .split("\n") - .slice(editableRegionStartLine, editableRegionEndLine + 1) - .join("\n"); - - // const finalCursorPos = calculateFinalCursorPosition( - // helper.pos, - // editableRegionStartLine, - // oldEditRangeSlice, - // "", - // ); - const finalCursorPos: Position = { - line: editableRegionEndLine, - character: 0, - }; - - 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 = { - elapsed: Date.now() - startTime, - modelProvider: llm.underlyingProviderName, - modelName: llm.model + ":zetaDataset", - completionOptions: null, - completionId: helper.input.completionId, - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: helper.filepath, - workspaceDirUri: - helper.workspaceUris[0] ?? path.dirname(helper.filepath), - prompt: prompts.join("\n"), - userEdits: "", - userExcerpts: "", - originalEditableRange: "", - completion: nextCompletion, - cursorPosition: helper.pos, - finalCursorPosition: finalCursorPos, - editableRegionStartLine: 0, - editableRegionEndLine: 0, - ...helper.options, - }; - - // 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; - if (ideType === "jetbrains") { - this.markDisplayed(input.completionId, outcomeNext); - } - - return outcomeNext; - } else { - return undefined; - } - } else { - const msg: ChatMessage = await llm.chat(prompts, token); - - if (typeof msg.content === "string") { - // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined - const nextCompletion = msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1] - ? replaceEscapedCharacters( - msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1], - ).replace(/\n$/, "") - : ""; - - // console.log("outcome is null?", nextCompletion === null); - - // console.log("metadata:", msg.content, prompts[0]); - - if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { - 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) - .join("\n"); - - const finalCursorPos = calculateFinalCursorPosition( - helper.pos, - editableRegionStartLine, - oldEditRangeSlice, - nextCompletion, - ); - - const outcomeNext: NextEditOutcome = { - elapsed: Date.now() - startTime, - modelProvider: llm.underlyingProviderName, - modelName: llm.model + ":zetaDataset", - completionOptions: null, - completionId: helper.input.completionId, - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: helper.filepath, - workspaceDirUri: - helper.workspaceUris[0] ?? path.dirname(helper.filepath), - prompt: this.promptMetadata!.prompt.content, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: oldEditRangeSlice, - completion: nextCompletion, - cursorPosition: helper.pos, - finalCursorPosition: finalCursorPos, - editableRegionStartLine, - editableRegionEndLine, - ...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; - if (ideType === "jetbrains") { - this.markDisplayed(input.completionId, outcomeNext); - } - - return outcomeNext; - } else { - // At this point, the model outputted an new file, basically. - // We run a myersDiff on the input file content and the model's output. - // Run the DiffLines through groupDiffLines and get a list of DiffGroup. - // Extract out the DiffGroup containing the current cursor position. - // Insert the remaining DiffGroups into Prefetch Queue's processedQueue. - // When pushing, make sure to build a ProcessedItem by building a RangeInFile and NextEditOutcome based on the DiffGroup's position and contents. - // Build a NextEditOutcome based on the extracted DiffGroup, and return it. - - // At this point, the model outputted an new file, basically. - // We run a myersDiff on the input file content and the model's output. - const diffLines = myersDiff(helper.fileContents, nextCompletion); - - // Run the DiffLines through groupDiffLines and get a list of DiffGroup. - const diffGroups = groupDiffLines(diffLines); - - // Extract out the DiffGroup containing the current cursor position. - const currentLine = helper.pos.line; - let cursorLocalDiffGroup: DiffGroup | undefined; - const prefetchQueue = PrefetchQueue.getInstance(); - - // Find the diff group containing the cursor position and queue others for prefetch - console.log("diffGroups:"); - console.log(diffGroups); - for (const group of diffGroups) { - if ( - currentLine >= group.startLine && - currentLine <= group.endLine - ) { - cursorLocalDiffGroup = group; - } else { - // Insert the remaining DiffGroups into Prefetch Queue's processedQueue. - const groupContent = group.lines - .filter((l) => l.type !== "old") - .map((l) => l.line) - .join("\n"); - - // Create a range for this diff group - const rangeInFile: RangeInFile = { - filepath: helper.filepath, - range: { - start: { line: group.startLine, character: 0 }, - end: { - line: group.endLine, - character: - group.lines[group.lines.length - 1].line.length, - }, - }, - }; - - // Build outcome for this diff group - const groupOutcome: NextEditOutcome = { - elapsed: Date.now() - startTime, - modelProvider: llm.underlyingProviderName, - modelName: llm.model + ":zetaDataset", - completionOptions: null, - completionId: uuidv4(), // Generate a new ID for this prefetched item - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: helper.filepath, - workspaceDirUri: - helper.workspaceUris[0] ?? path.dirname(helper.filepath), - prompt: this.promptMetadata!.prompt.content, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: group.lines - .filter((l) => l.type !== "new") - .map((l) => l.line) - .join("\n"), - completion: groupContent, - cursorPosition: { line: group.startLine, character: 0 }, - finalCursorPosition: { - line: group.endLine, - character: group.lines[group.lines.length - 1].line.length, - }, - editableRegionStartLine: group.startLine, - editableRegionEndLine: group.endLine, - ...helper.options, - }; - - // Add to prefetch queue - prefetchQueue.enqueueProcessed({ - location: rangeInFile, - outcome: groupOutcome, - }); - } - } - - // If we found a diff group containing the cursor, create an outcome for it - if (cursorLocalDiffGroup) { - const currentGroupContent = cursorLocalDiffGroup.lines - .filter((l) => l.type !== "old") - .map((line) => line.line) - .join("\n"); - const originalContent = cursorLocalDiffGroup.lines - .filter((l) => l.type !== "new") - .map((l) => l.line) - .join("\n"); - - const finalCursorPos = calculateFinalCursorPosition( - helper.pos, - cursorLocalDiffGroup.startLine, - originalContent, - currentGroupContent, - ); - - const outcomeNext: NextEditOutcome = { - elapsed: Date.now() - startTime, - modelProvider: llm.underlyingProviderName, - modelName: llm.model + ":zetaDataset", - completionOptions: null, - completionId: helper.input.completionId, - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: helper.filepath, - workspaceDirUri: - helper.workspaceUris[0] ?? path.dirname(helper.filepath), - prompt: this.promptMetadata!.prompt.content, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: originalContent, - completion: currentGroupContent, - cursorPosition: helper.pos, - finalCursorPosition: finalCursorPos, - editableRegionStartLine: cursorLocalDiffGroup.startLine, - editableRegionEndLine: cursorLocalDiffGroup.endLine, - ...helper.options, - }; - - this.previousCompletions.push(outcomeNext); - - // When using the JetBrains extension, mark as displayed. - const ideType = (await this.ide.getIdeInfo()).ideType; - if (ideType === "jetbrains") { - this.markDisplayed(input.completionId, outcomeNext); - } - - return outcomeNext; - } else { - // If we couldn't find a diff group containing the cursor position, - // use the first diff group as a fallback - if (diffGroups.length > 0) { - const firstGroup = diffGroups[0]; - const groupContent = firstGroup.lines - .filter((l) => l.type !== "old") - .map((line) => line.line) - .join("\n"); - const originalContent = firstGroup.lines - .filter((l) => l.type !== "new") - .map((l) => l.line) - .join("\n"); - - const finalCursorPos = calculateFinalCursorPosition( - { line: firstGroup.startLine, character: 0 }, - firstGroup.startLine, - originalContent, - groupContent, - ); - - const outcomeNext: NextEditOutcome = { - elapsed: Date.now() - startTime, - modelProvider: llm.underlyingProviderName, - modelName: llm.model + ":zetaDataset", - completionOptions: null, - completionId: helper.input.completionId, - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: helper.filepath, - workspaceDirUri: - helper.workspaceUris[0] ?? path.dirname(helper.filepath), - prompt: this.promptMetadata!.prompt.content, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: originalContent, - completion: groupContent, - cursorPosition: { line: firstGroup.startLine, character: 0 }, - finalCursorPosition: finalCursorPos, - editableRegionStartLine: firstGroup.startLine, - editableRegionEndLine: firstGroup.endLine, - ...helper.options, - }; - - this.previousCompletions.push(outcomeNext); - - // When using the JetBrains extension, mark as displayed. - const ideType = (await this.ide.getIdeInfo()).ideType; - if (ideType === "jetbrains") { - this.markDisplayed(input.completionId, outcomeNext); - } - - return outcomeNext; - } - - return undefined; - } - } - } else { - return undefined; - } + return await this._handleFineTunedEndpointCompletion( + helper, + prompts, + abortToken, + startTime, + editableRegionStartLine, + editableRegionEndLine, + opts, + ); } } catch (e: any) { this.onError(e); @@ -734,6 +310,530 @@ export class NextEditProvider { } } + private async _initializeCompletionRequest( + input: AutocompleteInput, + token: AbortSignal | undefined, + ): Promise<{ + token: AbortSignal; + startTime: number; + helper: HelperVars | undefined; + }> { + // 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 { token, startTime, helper: undefined }; + } + + const llm = await this._prepareLlm(); + if (!llm) { + return { token, startTime, helper: 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 { token, startTime, helper: undefined }; + } + + return { token, startTime, helper }; + } + + private async _generatePrompts( + helper: HelperVars, + opts?: { + withChain: boolean; + usingFullFileDiff: boolean; + }, + ): Promise<{ + editableRegionStartLine: number; + editableRegionEndLine: number; + prompts: Prompt[]; + }> { + const [snippetPayload, workspaceDirs] = await Promise.all([ + getAllSnippetsWithoutRace({ + helper, + ide: this.ide, + getDefinitionsFromLsp: this.getDefinitionsFromLsp, + contextRetrievalService: this.contextRetrievalService, + }), + this.ide.getWorkspaceDirs(), + ]); + + const editableRegionStartLine = opts?.usingFullFileDiff + ? 0 + : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); + + const editableRegionEndLine = opts?.usingFullFileDiff + ? helper.fileLines.length - 1 + : Math.min( + helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + helper.fileLines.length - 1, + ); + + const prompts: Prompt[] = []; + + if (this.endpointType === "default") { + prompts.push(renderDefaultSystemPrompt()); + prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); + } else { + prompts.push( + ...(await this._generateFineTunedPrompts( + helper, + snippetPayload, + editableRegionStartLine, + editableRegionEndLine, + )), + ); + } + + return { editableRegionStartLine, editableRegionEndLine, prompts }; + } + + private async _generateFineTunedPrompts( + helper: HelperVars, + snippetPayload: SnippetPayload, + editableRegionStartLine: number, + editableRegionEndLine: number, + ): Promise { + const historyDiff = createDiff({ + beforeContent: + DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( + localPathOrUriToPath(helper.filepath), + ) ?? "", + afterContent: helper.fileContents, + filePath: helper.filepath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }); + + const modelName = helper.modelName; + let ctx: any; + + if (modelName.includes("mercury-coder-nextedit")) { + ctx = { + recentlyViewedCodeSnippets: + snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ + filepath: snip.filepath, + content: snip.content, + })) ?? [], + currentFileContent: helper.fileContents, + editableRegionStartLine, + editableRegionEndLine, + editDiffHistory: this.diffContext, + currentFilePath: helper.filepath, + }; + } else if (modelName.includes("model-1")) { + ctx = { + userEdits: historyDiff ?? this.diffContext, + languageShorthand: helper.lang.name, + userExcerpts: helper.fileContents, + }; + } else { + ctx = {}; + } + + const promptMetadata = await renderPrompt(helper, ctx); + this.promptMetadata = promptMetadata; + + const systemPrompt: Prompt = { + role: "system", + content: + "You are Mercury, created by Inception Labs. You are an AI Assistant and an expert at coding. Your role as an AI assistant is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'\''s possible these are entirely irrelevant to the developer'\''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'\''s intentions. These changes are listed from oldest to latest. It'\''s possible a lot of old edit diff history is entirely irrelevant to the developer'\''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'\''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'\''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'\''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'\''s last change unless there are obvious typos or errors.\n- Don'\''t include the line numbers of the form #| in your response.", + }; + + return [systemPrompt, promptMetadata.prompt]; + } + + private async _handleDefaultEndpointCompletion( + helper: HelperVars, + prompts: Prompt[], + token: AbortSignal, + startTime: number, + editableRegionEndLine: number, + ): Promise { + const llm = await this._prepareLlm(); + if (!llm) return undefined; + + const msg: ChatMessage = await llm.chat(prompts, token); + + if (typeof msg.content === "string") { + const nextCompletion = JSON.parse(msg.content).newCode; + const finalCursorPos: Position = { + line: editableRegionEndLine, + character: 0, + }; + + const outcomeNext = await this._createNextEditOutcome({ + helper, + startTime, + llm, + promptContent: prompts.join("\n"), + completion: nextCompletion, + finalCursorPosition: finalCursorPos, + editableRegionStartLine: 0, + editableRegionEndLine: 0, + userEdits: "", + userExcerpts: "", + originalEditableRange: "", + }); + + // Mark as displayed for JetBrains extension + await this._markDisplayedIfJetBrains( + helper.input.completionId, + outcomeNext, + ); + + return outcomeNext; + } + + return undefined; + } + + private async _handleFineTunedEndpointCompletion( + helper: HelperVars, + prompts: Prompt[], + token: AbortSignal, + startTime: number, + editableRegionStartLine: number, + editableRegionEndLine: number, + opts?: { + withChain: boolean; + usingFullFileDiff: boolean; + }, + ): Promise { + const llm = await this._prepareLlm(); + if (!llm) return undefined; + + const msg: ChatMessage = await llm.chat(prompts, token); + + if (typeof msg.content !== "string") { + return undefined; + } + + const nextCompletion = msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1] + ? replaceEscapedCharacters( + msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1], + ).replace(/\n$/, "") + : ""; + + if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { + return await this._handlePartialFileDiff( + helper, + startTime, + llm, + nextCompletion, + editableRegionStartLine, + editableRegionEndLine, + ); + } else { + return await this._handleFullFileDiff( + helper, + startTime, + llm, + nextCompletion, + ); + } + } + + private async _handlePartialFileDiff( + helper: HelperVars, + startTime: number, + llm: ILLM, + nextCompletion: string, + editableRegionStartLine: number, + editableRegionEndLine: number, + ): Promise { + const oldEditRangeSlice = helper.fileContents + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + nextCompletion, + ); + + const outcomeNext = await this._createNextEditOutcome({ + helper, + startTime, + llm, + promptContent: this.promptMetadata!.prompt.content, + completion: nextCompletion, + finalCursorPosition: finalCursorPos, + editableRegionStartLine, + editableRegionEndLine, + userEdits: this.promptMetadata!.userEdits, + userExcerpts: this.promptMetadata!.userExcerpts, + originalEditableRange: oldEditRangeSlice, + }); + + this.previousCompletions.push(outcomeNext); + + // Mark as displayed for JetBrains extension + await this._markDisplayedIfJetBrains( + helper.input.completionId, + outcomeNext, + ); + + return outcomeNext; + } + + private async _handleFullFileDiff( + helper: HelperVars, + startTime: number, + llm: ILLM, + nextCompletion: string, + ): Promise { + const diffLines = myersDiff(helper.fileContents, nextCompletion); + const diffGroups = groupDiffLines(diffLines); + const currentLine = helper.pos.line; + let cursorLocalDiffGroup: DiffGroup | undefined; + const prefetchQueue = PrefetchQueue.getInstance(); + + // Process diff groups and find the one containing the cursor + await this._processDiffGroups( + diffGroups, + currentLine, + helper, + startTime, + llm, + prefetchQueue, + ); + + // Handle the diff group containing the cursor if found + if (cursorLocalDiffGroup) { + return await this._createOutcomeFromDiffGroup( + cursorLocalDiffGroup, + helper, + startTime, + llm, + helper.input.completionId, + true, + ); + } else if (diffGroups.length > 0) { + // Fallback to first diff group if cursor's group not found + return await this._createOutcomeFromDiffGroup( + diffGroups[0], + helper, + startTime, + llm, + helper.input.completionId, + false, + ); + } + + return undefined; + } + + private async _processDiffGroups( + diffGroups: DiffGroup[], + currentLine: number, + helper: HelperVars, + startTime: number, + llm: ILLM, + prefetchQueue: PrefetchQueue, + ): Promise { + let cursorGroup: DiffGroup | undefined; + + console.log("diffGroups:"); + console.log(diffGroups); + + for (const group of diffGroups) { + if (currentLine >= group.startLine && currentLine <= group.endLine) { + cursorGroup = group; + } else { + // Add non-cursor groups to prefetch queue + await this._addDiffGroupToPrefetchQueue( + group, + helper, + startTime, + llm, + prefetchQueue, + ); + } + } + + return cursorGroup; + } + + private async _addDiffGroupToPrefetchQueue( + group: DiffGroup, + helper: HelperVars, + startTime: number, + llm: ILLM, + prefetchQueue: PrefetchQueue, + ): Promise { + const groupContent = group.lines + .filter((l) => l.type !== "old") + .map((l) => l.line) + .join("\n"); + + // Create a range for this diff group + const rangeInFile: RangeInFile = { + filepath: helper.filepath, + range: { + start: { line: group.startLine, character: 0 }, + end: { + line: group.endLine, + character: group.lines[group.lines.length - 1].line.length, + }, + }, + }; + + const originalContent = group.lines + .filter((l) => l.type !== "new") + .map((l) => l.line) + .join("\n"); + + // Build outcome for this diff group + const groupOutcome = await this._createNextEditOutcome({ + helper, + startTime, + llm, + promptContent: this.promptMetadata!.prompt.content, + completion: groupContent, + finalCursorPosition: { + line: group.endLine, + character: group.lines[group.lines.length - 1].line.length, + }, + editableRegionStartLine: group.startLine, + editableRegionEndLine: group.endLine, + userEdits: this.promptMetadata!.userEdits, + userExcerpts: this.promptMetadata!.userExcerpts, + originalEditableRange: originalContent, + cursorPosition: { line: group.startLine, character: 0 }, + completionId: uuidv4(), // Generate a new ID for this prefetched item + }); + + // Add to prefetch queue + prefetchQueue.enqueueProcessed({ + location: rangeInFile, + outcome: groupOutcome, + }); + } + + private async _createOutcomeFromDiffGroup( + diffGroup: DiffGroup, + helper: HelperVars, + startTime: number, + llm: ILLM, + completionId: string, + isCurrentCursorGroup: boolean, + ): Promise { + const groupContent = diffGroup.lines + .filter((l) => l.type !== "old") + .map((line) => line.line) + .join("\n"); + + const originalContent = diffGroup.lines + .filter((l) => l.type !== "new") + .map((l) => l.line) + .join("\n"); + + // Use the actual cursor position if this is the group containing the cursor + // Otherwise use the start of the diff group + const cursorPos = isCurrentCursorGroup + ? helper.pos + : { line: diffGroup.startLine, character: 0 }; + + const finalCursorPos = calculateFinalCursorPosition( + cursorPos, + diffGroup.startLine, + originalContent, + groupContent, + ); + + const outcomeNext = await this._createNextEditOutcome({ + helper, + startTime, + llm, + promptContent: this.promptMetadata!.prompt.content, + completion: groupContent, + finalCursorPosition: finalCursorPos, + editableRegionStartLine: diffGroup.startLine, + editableRegionEndLine: diffGroup.endLine, + userEdits: this.promptMetadata!.userEdits, + userExcerpts: this.promptMetadata!.userExcerpts, + originalEditableRange: originalContent, + cursorPosition: cursorPos, + completionId, + }); + + this.previousCompletions.push(outcomeNext); + + // Mark as displayed for JetBrains + await this._markDisplayedIfJetBrains(completionId, outcomeNext); + + return outcomeNext; + } + + private async _createNextEditOutcome(outcomeCtx: { + helper: HelperVars; + startTime: number; + llm: ILLM; + promptContent: string; + completion: string; + finalCursorPosition: Position; + editableRegionStartLine: number; + editableRegionEndLine: number; + userEdits: string; + userExcerpts: string; + originalEditableRange: string; + cursorPosition?: Position; + completionId?: string; + }): Promise { + return { + elapsed: Date.now() - outcomeCtx.startTime, + modelProvider: outcomeCtx.llm.underlyingProviderName, + modelName: outcomeCtx.llm.model + ":zetaDataset", + completionOptions: null, + completionId: + outcomeCtx.completionId || outcomeCtx.helper.input.completionId, + gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + fileUri: outcomeCtx.helper.filepath, + workspaceDirUri: + outcomeCtx.helper.workspaceUris[0] ?? + path.dirname(outcomeCtx.helper.filepath), + prompt: outcomeCtx.promptContent, + userEdits: outcomeCtx.userEdits ?? "", + userExcerpts: outcomeCtx.userExcerpts ?? "", + originalEditableRange: outcomeCtx.originalEditableRange ?? "", + completion: outcomeCtx.completion, + cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos, + finalCursorPosition: outcomeCtx.finalCursorPosition, + editableRegionStartLine: outcomeCtx.editableRegionStartLine, + editableRegionEndLine: outcomeCtx.editableRegionEndLine, + ...outcomeCtx.helper.options, + }; + } + + private async _markDisplayedIfJetBrains( + completionId: string, + outcome: NextEditOutcome, + ): Promise { + const ideType = (await this.ide.getIdeInfo()).ideType; + if (ideType === "jetbrains") { + this.markDisplayed(completionId, outcome); + } + } + public async provideInlineCompletionItemsWithChain( ctx: { completionId: string; From 8e79ce3587877b89357ccc709c3d294e8f18d5d8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 4 Aug 2025 09:53:07 -0700 Subject: [PATCH 33/48] refactor: rename constants to be model-specific --- core/nextEdit/NextEditProvider.ts | 12 ++++--- core/nextEdit/constants.ts | 33 ++++++++++-------- .../templating/NextEditPromptEngine.ts | 22 ++++++------ .../templating/NextEditPromptEngine.vitest.ts | 34 +++++++++---------- .../templating/mercuryCoderNextEdit.ts | 12 ++++--- .../templating/mercuryCoderNextEdit.vitest.ts | 20 ++++++----- core/nextEdit/templating/utils.ts | 8 ++--- core/nextEdit/templating/utils.vitest.ts | 12 +++---- .../vscode/src/extension/VsCodeExtension.ts | 6 ---- 9 files changed, 84 insertions(+), 75 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 3f268675b..5b8d487e0 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -32,7 +32,8 @@ import { myersDiff } from "../diff/myers.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { - CODE_TO_EDIT_OPEN, + MERCURY_CODE_TO_EDIT_OPEN, + MERCURY_SYSTEM_PROMPT, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; @@ -450,8 +451,7 @@ export class NextEditProvider { const systemPrompt: Prompt = { role: "system", - content: - "You are Mercury, created by Inception Labs. You are an AI Assistant and an expert at coding. Your role as an AI assistant is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'\''s possible these are entirely irrelevant to the developer'\''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'\''s intentions. These changes are listed from oldest to latest. It'\''s possible a lot of old edit diff history is entirely irrelevant to the developer'\''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'\''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'\''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'\''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'\''s last change unless there are obvious typos or errors.\n- Don'\''t include the line numbers of the form #| in your response.", + content: MERCURY_SYSTEM_PROMPT, }; return [systemPrompt, promptMetadata.prompt]; @@ -523,9 +523,11 @@ export class NextEditProvider { return undefined; } - const nextCompletion = msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1] + const nextCompletion = msg.content.split( + `${MERCURY_CODE_TO_EDIT_OPEN}\n`, + )[1] ? replaceEscapedCharacters( - msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1], + msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1], ).replace(/\n$/, "") : ""; diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 05ac1caa3..153563d11 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -1,22 +1,27 @@ export const IS_NEXT_EDIT_ACTIVE = false; export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0; export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5; -export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; -export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; -export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; -export const RECENTLY_VIEWED_CODE_SNIPPETS_OPEN = +// Model 1-specific tokens. +export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; +export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; +export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; + +// Mercury Coder Next Edit-specific tokens. +export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN = "<|recently_viewed_code_snippets|>"; -export const RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE = +export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE = "<|/recently_viewed_code_snippets|>"; -export const RECENTLY_VIEWED_CODE_SNIPPET_OPEN = +export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN = "<|recently_viewed_code_snippet|>"; -export const RECENTLY_VIEWED_CODE_SNIPPET_CLOSE = +export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE = "<|/recently_viewed_code_snippet|>"; -export const CURRENT_FILE_CONTENT_OPEN = "<|current_file_content|>"; -export const CURRENT_FILE_CONTENT_CLOSE = "<|/current_file_content|>"; -export const CODE_TO_EDIT_OPEN = "<|code_to_edit|>"; -export const CODE_TO_EDIT_CLOSE = "<|/code_to_edit|>"; -export const EDIT_DIFF_HISTORY_OPEN = "<|edit_diff_history|>"; -export const EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>"; -export const CURSOR = "<|cursor|>"; +export const MERCURY_CURRENT_FILE_CONTENT_OPEN = "<|current_file_content|>"; +export const MERCURY_CURRENT_FILE_CONTENT_CLOSE = "<|/current_file_content|>"; +export const MERCURY_CODE_TO_EDIT_OPEN = "<|code_to_edit|>"; +export const MERCURY_CODE_TO_EDIT_CLOSE = "<|/code_to_edit|>"; +export const MERCURY_EDIT_DIFF_HISTORY_OPEN = "<|edit_diff_history|>"; +export const MERCURY_EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>"; +export const MERCURY_CURSOR = "<|cursor|>"; +export const MERCURY_SYSTEM_PROMPT = + "You are Mercury, created by Inception Labs. You are an AI Assistant and an expert at coding. Your role as an AI assistant is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'\''s possible these are entirely irrelevant to the developer'\''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'\''s intentions. These changes are listed from oldest to latest. It'\''s possible a lot of old edit diff history is entirely irrelevant to the developer'\''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'\''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'\''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'\''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'\''s last change unless there are obvious typos or errors.\n- Don'\''t include the line numbers of the form #| in your response."; diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 5b8e93f14..24f16e681 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -3,14 +3,14 @@ import { Position } from "../.."; import { SnippetPayload } from "../../autocomplete/snippets"; import { HelperVars } from "../../autocomplete/util/HelperVars"; import { - CURRENT_FILE_CONTENT_CLOSE, - CURRENT_FILE_CONTENT_OPEN, - CURSOR, - EDIT_DIFF_HISTORY_CLOSE, - EDIT_DIFF_HISTORY_OPEN, - RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, - RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, - USER_CURSOR_IS_HERE_TOKEN, + MERCURY_CURRENT_FILE_CONTENT_CLOSE, + MERCURY_CURRENT_FILE_CONTENT_OPEN, + MERCURY_CURSOR, + MERCURY_EDIT_DIFF_HISTORY_CLOSE, + MERCURY_EDIT_DIFF_HISTORY_OPEN, + MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, + MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, + MODEL_1_USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; import { MercuryTemplateVars, @@ -40,7 +40,7 @@ export type NextEditModelName = const NEXT_EDIT_MODEL_TEMPLATES: Record = { "mercury-coder-nextedit": { - template: `${RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${CURRENT_FILE_CONTENT_CLOSE}\n\n${EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, + template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, "model-1": { template: @@ -111,7 +111,7 @@ export async function renderPrompt( editedCodeWithTokens = insertTokens( helper.fileContents.split("\n"), helper.pos, - CURSOR, + MERCURY_CURSOR, ); const mercuryCtx: MercuryTemplateVars = { @@ -138,7 +138,7 @@ export async function renderPrompt( editedCodeWithTokens = insertTokens( helper.fileContents.split("\n"), helper.pos, - USER_CURSOR_IS_HERE_TOKEN, + MODEL_1_USER_CURSOR_IS_HERE_TOKEN, ); const model1Ctx: Model1TemplateVars = { diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index aa3fad6a6..03ffd26e8 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -4,14 +4,14 @@ import { SnippetPayload } from "../../autocomplete/snippets"; import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; import { HelperVars } from "../../autocomplete/util/HelperVars"; import { - CURRENT_FILE_CONTENT_CLOSE, - CURRENT_FILE_CONTENT_OPEN, - CURSOR, - EDIT_DIFF_HISTORY_CLOSE, - EDIT_DIFF_HISTORY_OPEN, - RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, - RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, - USER_CURSOR_IS_HERE_TOKEN, + MERCURY_CURRENT_FILE_CONTENT_CLOSE, + MERCURY_CURRENT_FILE_CONTENT_OPEN, + MERCURY_CURSOR, + MERCURY_EDIT_DIFF_HISTORY_CLOSE, + MERCURY_EDIT_DIFF_HISTORY_OPEN, + MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, + MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, + MODEL_1_USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; import { NextEditModelName, @@ -75,15 +75,15 @@ describe("NextEditPromptEngine", () => { expect(result.prompt.role).toBe("user"); const content = result.prompt.content; - expect(content).toContain(RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); - expect(content).toContain(RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); - expect(content).toContain(CURRENT_FILE_CONTENT_OPEN); - expect(content).toContain(CURRENT_FILE_CONTENT_CLOSE); - expect(content).toContain(EDIT_DIFF_HISTORY_OPEN); - expect(content).toContain(EDIT_DIFF_HISTORY_CLOSE); + expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); + expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); + expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN); + expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE); + expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN); + expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE); expect(result.userEdits).toBe(ctx.editDiffHistory); - expect(result.userExcerpts).toContain(CURSOR); + expect(result.userExcerpts).toContain(MERCURY_CURSOR); }); it("should render model-1 prompt correctly", async () => { @@ -96,7 +96,7 @@ describe("NextEditPromptEngine", () => { expect(result.prompt.content).toContain("```ts"); expect(result.userEdits).toBe(ctx.userEdits); - expect(result.userExcerpts).toContain(USER_CURSOR_IS_HERE_TOKEN); + expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN); }); it("should handle 'this field is not used' model name", async () => { @@ -229,7 +229,7 @@ describe("NextEditPromptEngine", () => { }; return renderPrompt(mercuryHelper, ctx).then((result) => { - expect(result.userExcerpts).toContain(CURSOR); + expect(result.userExcerpts).toContain(MERCURY_CURSOR); }); }); }); diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.ts b/core/nextEdit/templating/mercuryCoderNextEdit.ts index d87923969..1d7950e96 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.ts @@ -1,5 +1,9 @@ import { Position, Range } from "../.."; -import { CODE_TO_EDIT_CLOSE, CODE_TO_EDIT_OPEN, CURSOR } from "../constants"; +import { + MERCURY_CODE_TO_EDIT_CLOSE, + MERCURY_CODE_TO_EDIT_OPEN, + MERCURY_CURSOR, +} from "../constants"; import { insertCursorToken } from "./utils"; export function recentlyViewedCodeSnippetsBlock( @@ -28,17 +32,17 @@ export function currentFileContentBlock( const insertedCursorLines = insertCursorToken( currentFileContentLines, cursorPosition, - CURSOR, + MERCURY_CURSOR, ); const instrumentedLines = [ ...insertedCursorLines.slice(0, editableRegionStartLine), - CODE_TO_EDIT_OPEN, + MERCURY_CODE_TO_EDIT_OPEN, ...insertedCursorLines.slice( editableRegionStartLine, editableRegionEndLine + 1, ), - CODE_TO_EDIT_CLOSE, + MERCURY_CODE_TO_EDIT_CLOSE, ...insertedCursorLines.slice(editableRegionEndLine + 1), ]; diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts index 2849082b7..8fefb5e7b 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vitest"; import { Position } from "../.."; -import { CODE_TO_EDIT_CLOSE, CODE_TO_EDIT_OPEN, CURSOR } from "../constants"; +import { + MERCURY_CODE_TO_EDIT_CLOSE, + MERCURY_CODE_TO_EDIT_OPEN, + MERCURY_CURSOR, +} from "../constants"; import { currentFileContentBlock, editHistoryBlock, @@ -51,14 +55,14 @@ describe("mercuryCoderNextEdit", () => { const expected = "line 1\n" + - CODE_TO_EDIT_OPEN + + MERCURY_CODE_TO_EDIT_OPEN + "\n" + "line 2\n" + "lin" + - CURSOR + + MERCURY_CURSOR + "e 3\n" + "line 4\n" + - CODE_TO_EDIT_CLOSE + + MERCURY_CODE_TO_EDIT_CLOSE + "\n" + "line 5"; @@ -78,9 +82,9 @@ describe("mercuryCoderNextEdit", () => { cursorPosition, ); - expect(result).toContain(CODE_TO_EDIT_OPEN); - expect(result).toContain(CURSOR + "line 2"); - expect(result).toContain(CODE_TO_EDIT_CLOSE); + expect(result).toContain(MERCURY_CODE_TO_EDIT_OPEN); + expect(result).toContain(MERCURY_CURSOR + "line 2"); + expect(result).toContain(MERCURY_CODE_TO_EDIT_CLOSE); }); it("should handle cursor at the end of a line", () => { @@ -96,7 +100,7 @@ describe("mercuryCoderNextEdit", () => { cursorPosition, ); - expect(result).toContain("line 2" + CURSOR); + expect(result).toContain("line 2" + MERCURY_CURSOR); }); }); diff --git a/core/nextEdit/templating/utils.ts b/core/nextEdit/templating/utils.ts index a75712689..586fd1795 100644 --- a/core/nextEdit/templating/utils.ts +++ b/core/nextEdit/templating/utils.ts @@ -1,7 +1,7 @@ import { Position } from "../.."; import { - EDITABLE_REGION_END_TOKEN, - EDITABLE_REGION_START_TOKEN, + MODEL_1_EDITABLE_REGION_END_TOKEN, + MODEL_1_EDITABLE_REGION_START_TOKEN, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "../constants"; @@ -53,9 +53,9 @@ export function insertEditableRegionTokensWithStaticRange( const instrumentedLines = [ ...lines.slice(0, editableRegionStart), - EDITABLE_REGION_START_TOKEN, + MODEL_1_EDITABLE_REGION_START_TOKEN, ...lines.slice(editableRegionStart, editableRegionEnd + 1), - EDITABLE_REGION_END_TOKEN, + MODEL_1_EDITABLE_REGION_END_TOKEN, ...lines.slice(editableRegionEnd + 1), ]; diff --git a/core/nextEdit/templating/utils.vitest.ts b/core/nextEdit/templating/utils.vitest.ts index a2f8772ba..f60a26d7d 100644 --- a/core/nextEdit/templating/utils.vitest.ts +++ b/core/nextEdit/templating/utils.vitest.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; import { Position } from "../.."; import { - EDITABLE_REGION_END_TOKEN, - EDITABLE_REGION_START_TOKEN, + MODEL_1_EDITABLE_REGION_END_TOKEN, + MODEL_1_EDITABLE_REGION_START_TOKEN, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "../constants"; @@ -88,9 +88,9 @@ describe("insertEditableRegionTokensWithStaticRange", () => { const expected = [ ...lines.slice(0, expectedStart), - EDITABLE_REGION_START_TOKEN, + MODEL_1_EDITABLE_REGION_START_TOKEN, ...lines.slice(expectedStart, expectedEnd + 1), - EDITABLE_REGION_END_TOKEN, + MODEL_1_EDITABLE_REGION_END_TOKEN, ...lines.slice(expectedEnd + 1), ]; @@ -112,11 +112,11 @@ describe("insertEditableRegionTokensWithStaticRange", () => { const expected = [ "line 0", - EDITABLE_REGION_START_TOKEN, + MODEL_1_EDITABLE_REGION_START_TOKEN, "line 1", "line 2", "line 3", - EDITABLE_REGION_END_TOKEN, + MODEL_1_EDITABLE_REGION_END_TOKEN, "line 4", ]; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 1e5fe8254..f28b375b2 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -367,12 +367,6 @@ export class VsCodeExtension { selectionManager.documentChanged(); } - // if (event.contentChanges.length > 0) { - // this.isTypingSession = true; - // this.lastDocumentChangeTime = Date.now(); - // this.resetTypingSession(); - // } - const editInfo = await handleTextDocumentChange( event, this.configHandler, From 5aaa4912da3f492774693db59aff452127691c92 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 4 Aug 2025 11:41:44 -0700 Subject: [PATCH 34/48] feat: respect token limits --- core/nextEdit/NextEditProvider.ts | 124 +++++++++++++++++++++++++++--- 1 file changed, 115 insertions(+), 9 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 5b8d487e0..a334cdda2 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -29,6 +29,7 @@ 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 { countTokens } from "../llm/countTokens.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { @@ -373,16 +374,30 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); - const editableRegionStartLine = opts?.usingFullFileDiff - ? 0 - : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); + const { editableRegionStartLine, editableRegionEndLine } = + opts?.usingFullFileDiff + ? this._calculateOptimalEditableRegion(helper, "tokenizer") + : { + editableRegionStartLine: Math.max( + helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ), + editableRegionEndLine: Math.min( + helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + helper.fileLines.length - 1, + ), + }; - const editableRegionEndLine = opts?.usingFullFileDiff - ? helper.fileLines.length - 1 - : Math.min( - helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - helper.fileLines.length - 1, - ); + // const editableRegionStartLine = opts?.usingFullFileDiff + // ? 0 + // : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); + + // const editableRegionEndLine = opts?.usingFullFileDiff + // ? helper.fileLines.length - 1 + // : Math.min( + // helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + // helper.fileLines.length - 1, + // ); const prompts: Prompt[] = []; @@ -403,6 +418,97 @@ export class NextEditProvider { return { editableRegionStartLine, editableRegionEndLine, prompts }; } + private _calculateOptimalEditableRegion( + helper: HelperVars, + heuristic: "fourChars" | "tokenizer" = "tokenizer", + ): { + editableRegionStartLine: number; + editableRegionEndLine: number; + } { + const cursorLine = helper.pos.line; + const fileLines = helper.fileLines; + const MAX_TOKENS = 500; + + // Initialize with cursor line. + let editableRegionStartLine = cursorLine; + let editableRegionEndLine = cursorLine; + + // Get initial content and token count. + let currentContent = fileLines[cursorLine]; + let totalTokens = + heuristic === "tokenizer" + ? countTokens(currentContent, helper.modelName) + : Math.ceil(currentContent.length / 4); + + // Expand outward alternating between adding lines above and below. + let addingAbove = true; + + while (totalTokens < MAX_TOKENS) { + let addedLine = false; + + if (addingAbove) { + // Try to add a line above. + if (editableRegionStartLine > 0) { + editableRegionStartLine--; + const lineContent = fileLines[editableRegionStartLine]; + const lineTokens = + heuristic === "tokenizer" + ? countTokens(lineContent, helper.modelName) + : Math.ceil(lineContent.length / 4); + + totalTokens += lineTokens; + addedLine = true; + } + } else { + // Try to add a line below. + if (editableRegionEndLine < fileLines.length - 1) { + editableRegionEndLine++; + const lineContent = fileLines[editableRegionEndLine]; + const lineTokens = + heuristic === "tokenizer" + ? countTokens(lineContent, helper.modelName) + : Math.ceil(lineContent.length / 4); + + totalTokens += lineTokens; + addedLine = true; + } + } + + // If we can't add in the current direction, try the other. + if (!addedLine) { + // If we're already at both file boundaries, we're done. + if ( + editableRegionStartLine === 0 && + editableRegionEndLine === fileLines.length - 1 + ) { + break; + } + + // If we couldn't add in one direction, force the next attempt in the other direction. + addingAbove = !addingAbove; + continue; + } + + // If we exceeded the token limit, revert the last addition. + if (totalTokens > MAX_TOKENS) { + if (addingAbove) { + editableRegionStartLine++; + } else { + editableRegionEndLine--; + } + break; + } + + // Alternate between adding above and below for balanced context. + addingAbove = !addingAbove; + } + + return { + editableRegionStartLine, + editableRegionEndLine, + }; + } + private async _generateFineTunedPrompts( helper: HelperVars, snippetPayload: SnippetPayload, From 58f400144fa22acd39b160c15d53b12e380f1d92 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 4 Aug 2025 11:42:00 -0700 Subject: [PATCH 35/48] test: add test for _calculateOptimalEditableRegion --- core/nextEdit/NextEditProvider.vitest.ts | 259 +++++++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 core/nextEdit/NextEditProvider.vitest.ts diff --git a/core/nextEdit/NextEditProvider.vitest.ts b/core/nextEdit/NextEditProvider.vitest.ts new file mode 100644 index 000000000..99a9045bb --- /dev/null +++ b/core/nextEdit/NextEditProvider.vitest.ts @@ -0,0 +1,259 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; +import { HelperVars } from "../autocomplete/util/HelperVars.js"; +import { ConfigHandler } from "../config/ConfigHandler.js"; +import { IDE, ILLM } from "../index.js"; +import { NextEditProvider } from "./NextEditProvider.js"; + +// Mock the countTokens function +vi.mock("../llm/countTokens.js", () => ({ + countTokens: (text: string) => { + // Simple mock that counts 1 token per character for predictable tests + return text.length; + }, +})); + +// Create a helper function to set up the test context +function createMockHelper( + fileContents: string, + cursorLine: number, +): HelperVars { + const fileLines = fileContents.split("\n"); + + return { + fileLines, + fileContents, + pos: { line: cursorLine, character: 0 }, + modelName: "gpt-4", + lang: { name: "typescript" }, + filepath: "test/file.ts", + workspaceUris: ["test/workspace"], + options: {}, + input: { completionId: "test-completion-id" }, + } as unknown as HelperVars; +} + +// TODO: Add more tests for other methods. +describe("_calculateOptimalEditableRegion", () => { + let nextEditProvider: NextEditProvider; + let mockConfigHandler: ConfigHandler; + let mockIde: IDE; + let mockGetLlm: () => Promise; + let mockOnError: (e: any) => void; + let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction; + + beforeEach(() => { + // Create comprehensive mocks for all dependencies + mockConfigHandler = { + loadConfig: vi.fn().mockResolvedValue({ config: {} }), + } as unknown as ConfigHandler; + + mockIde = { + readFile: vi.fn().mockResolvedValue(""), + getWorkspaceDirs: vi.fn().mockResolvedValue([]), + getRepoName: vi.fn().mockResolvedValue("test-repo"), + getUniqueId: vi.fn().mockResolvedValue("test-id"), + getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }), + onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => { + // Return a disposable object that does nothing when disposed + return { + dispose: () => {}, + }; + }), + } as unknown as IDE; + + mockGetLlm = vi.fn().mockResolvedValue({ + model: "gpt-4", + providerName: "openai", + underlyingProviderName: "openai", + completionOptions: {}, + chat: vi.fn(), + }); + + mockOnError = vi.fn(); + mockGetDefinitionsFromLsp = vi.fn(); + + // Initialize NextEditProvider with mocked dependencies + nextEditProvider = NextEditProvider.initialize( + mockConfigHandler, + mockIde, + mockGetLlm, + mockOnError, + mockGetDefinitionsFromLsp, + "default", + ); + + // Expose the private method for testing + // This is a bit of a hack, but necessary for testing private methods + (nextEditProvider as any)._calculateOptimalEditableRegion = ( + NextEditProvider.prototype as any + )._calculateOptimalEditableRegion.bind(nextEditProvider); + }); + + // Test cases remain the same as before... + it("should include only the cursor line when it already exceeds token limit", () => { + // Create a mock helper with a very long cursor line (>500 characters) + const longLine = "X".repeat(600); + const helper = createMockHelper(longLine, 0); + + //@ts-ignore + const result = nextEditProvider._calculateOptimalEditableRegion( + helper, + "tokenizer", + ); + + expect(result.editableRegionStartLine).toBe(0); + expect(result.editableRegionEndLine).toBe(0); + }); + + it("should expand symmetrically when possible", () => { + // Create content with identical lines and cursor in the middle + const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each + const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5) + + //@ts-ignore + const result = nextEditProvider._calculateOptimalEditableRegion( + helper, + "tokenizer", + ); + + // Should expand 5 lines in each direction (total 11 lines) for symmetry + expect(result.editableRegionStartLine).toBe(0); + expect(result.editableRegionEndLine).toBe(10); + }); + + it("should expand asymmetrically when hitting a file boundary", () => { + // Create content with cursor near the top + const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each + const helper = createMockHelper(lines, 1); // Cursor near the top (line 1) + + //@ts-ignore + const result = nextEditProvider._calculateOptimalEditableRegion( + helper, + "tokenizer", + ); + + // Should include more lines below since it can't expand much above + expect(result.editableRegionStartLine).toBe(0); + // Should include many more lines below to reach token limit + expect(result.editableRegionEndLine).toBeGreaterThan(10); + }); + + it("should handle files with varying line lengths", () => { + // Create content with varying line lengths + const fileContents = [ + "Short line", // 10 chars + "A".repeat(100), // 100 chars + "Medium length line here", // 24 chars + "B".repeat(200), // 200 chars + "Another typical line of code", // 28 chars + ].join("\n"); + + const helper = createMockHelper(fileContents, 2); // Cursor on the medium line + + //@ts-ignore + const result = nextEditProvider._calculateOptimalEditableRegion( + helper, + "tokenizer", + ); + + // Should include all lines since total tokens < 500 + expect(result.editableRegionStartLine).toBe(0); + expect(result.editableRegionEndLine).toBe(4); + }); + + it("should respect the token limit and not include too many lines", () => { + // Create content with many small lines (10 chars each) + const lines = Array(600).fill("C".repeat(10)).join("\n"); + const helper = createMockHelper(lines, 300); // Cursor in the middle + + //@ts-ignore + const result = nextEditProvider._calculateOptimalEditableRegion( + helper, + "tokenizer", + ); + + // Each line is 10 chars = 10 tokens per line with our mock + // So with 500 token limit, we should get ~45 lines total + const totalLines = + result.editableRegionEndLine - result.editableRegionStartLine + 1; + const expectedMaxLines = Math.floor(500 / 10); + expect(totalLines).toBe(expectedMaxLines); // Not more than 50 lines + }); + + it("should use character approximation when using fourChars heuristic", () => { + // In this test, we're setting up a situation where tiktoken and fourChars would give different results + // Creating 5 lines, each 100 characters + const lines = Array(10).fill("D".repeat(100)).join("\n"); + const helper = createMockHelper(lines, 2); // Cursor in the middle + + // Mock for tiktoken counting (1 char = 1 token) + //@ts-ignore + const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion( + helper, + "tokenizer", + ); + + // Mock for fourChars counting (1 token = 4 chars) + // This should include more lines since each line is counted as 25 tokens instead of 100 + //@ts-ignore + const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion( + helper, + "fourChars", + ); + + // The fourChars approach should include more lines since it estimates fewer tokens per line + expect( + fourCharsResult.editableRegionEndLine - + fourCharsResult.editableRegionStartLine, + ).toBeGreaterThan( + tokenizerResult.editableRegionEndLine - + tokenizerResult.editableRegionStartLine, + ); + }); + + it("should include the entire file if it's within token limit", () => { + // Create a small file + const smallFile = "Small file\nwith just\na few lines\nof text"; + const helper = createMockHelper(smallFile, 1); + + //@ts-ignore + const result = nextEditProvider._calculateOptimalEditableRegion( + helper, + "tokenizer", + ); + + // Should include all lines + expect(result.editableRegionStartLine).toBe(0); + expect(result.editableRegionEndLine).toBe(3); + }); + + it("should prioritize balanced context when token limit allows", () => { + // Create content with alternating long and short lines + const fileContents = [ + "Short", // 5 chars + "E".repeat(80), // 80 chars + "Also short", // 10 chars + "F".repeat(80), // 80 chars + "Another short one", // 17 chars + "G".repeat(80), // 80 chars + "Final short line", // 16 chars + ].join("\n"); + + const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3) + + //@ts-ignore + const result = nextEditProvider._calculateOptimalEditableRegion( + helper, + "tokenizer", + ); + + // Should try to include equal number of lines above and below cursor + const linesAbove = result.editableRegionStartLine; + const linesBelow = + helper.fileLines.length - 1 - result.editableRegionEndLine; + + // Difference between lines above and below should be minimal + expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1); + }); +}); From fa5323f626b57a197015071a9171c4aae68c26ee Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 13:20:57 -0700 Subject: [PATCH 36/48] feat: pass difflines --- core/nextEdit/NextEditProvider.ts | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index a334cdda2..0b97c4491 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -3,6 +3,7 @@ import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { ChatMessage, + DiffLine, IDE, ILLM, Position, @@ -427,7 +428,7 @@ export class NextEditProvider { } { const cursorLine = helper.pos.line; const fileLines = helper.fileLines; - const MAX_TOKENS = 500; + const MAX_TOKENS = 512; // Initialize with cursor line. let editableRegionStartLine = cursorLine; @@ -594,6 +595,7 @@ export class NextEditProvider { userEdits: "", userExcerpts: "", originalEditableRange: "", + diffLines: [], }); // Mark as displayed for JetBrains extension @@ -649,6 +651,8 @@ export class NextEditProvider { } else { return await this._handleFullFileDiff( helper, + editableRegionStartLine, + editableRegionEndLine, startTime, llm, nextCompletion, @@ -688,6 +692,7 @@ export class NextEditProvider { userEdits: this.promptMetadata!.userEdits, userExcerpts: this.promptMetadata!.userExcerpts, originalEditableRange: oldEditRangeSlice, + diffLines: [], }); this.previousCompletions.push(outcomeNext); @@ -703,12 +708,17 @@ export class NextEditProvider { private async _handleFullFileDiff( helper: HelperVars, + editableRegionStartLine: number, + editableRegionEndLine: number, startTime: number, llm: ILLM, nextCompletion: string, ): Promise { - const diffLines = myersDiff(helper.fileContents, nextCompletion); - const diffGroups = groupDiffLines(diffLines); + const fileSlice = helper.fileLines + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + const diffLines = myersDiff(fileSlice, nextCompletion); + const diffGroups = groupDiffLines(diffLines, editableRegionStartLine, 5); const currentLine = helper.pos.line; let cursorLocalDiffGroup: DiffGroup | undefined; const prefetchQueue = PrefetchQueue.getInstance(); @@ -826,6 +836,7 @@ export class NextEditProvider { originalEditableRange: originalContent, cursorPosition: { line: group.startLine, character: 0 }, completionId: uuidv4(), // Generate a new ID for this prefetched item + diffLines: group.lines, }); // Add to prefetch queue @@ -880,6 +891,7 @@ export class NextEditProvider { originalEditableRange: originalContent, cursorPosition: cursorPos, completionId, + diffLines: diffGroup.lines, }); this.previousCompletions.push(outcomeNext); @@ -904,6 +916,7 @@ export class NextEditProvider { originalEditableRange: string; cursorPosition?: Position; completionId?: string; + diffLines: DiffLine[]; }): Promise { return { elapsed: Date.now() - outcomeCtx.startTime, @@ -928,6 +941,7 @@ export class NextEditProvider { finalCursorPosition: outcomeCtx.finalCursorPosition, editableRegionStartLine: outcomeCtx.editableRegionStartLine, editableRegionEndLine: outcomeCtx.editableRegionEndLine, + diffLines: outcomeCtx.diffLines, ...outcomeCtx.helper.options, }; } From 04f238afc83f0a5a8e5655cbf191a93554bb8af2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 13:21:09 -0700 Subject: [PATCH 37/48] feat: add diffLines field --- core/nextEdit/types.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 8c28bc5f9..49a4c0862 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -1,4 +1,10 @@ -import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../"; +import { + DiffLine, + Position, + Range, + RangeInFile, + TabAutocompleteOptions, +} from "../"; import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types"; export type RecentlyEditedRange = RangeInFile & { @@ -57,6 +63,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions { accepted?: boolean; editableRegionStartLine: number; editableRegionEndLine: number; + diffLines: DiffLine[]; } export interface PromptMetadata { From 9f0baeae4284733220df1fd620fece66c5eb8b3c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 13:23:17 -0700 Subject: [PATCH 38/48] fix: properly calculate diff group --- core/nextEdit/diff/diff.ts | 203 ++++++++++++++++++++++++++----------- 1 file changed, 144 insertions(+), 59 deletions(-) diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index f0316d56d..0a06bd1eb 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -210,6 +210,9 @@ export function calculateFinalCursorPosition( oldEditRangeSlice: string, newEditRangeSlice: string, ) { + if (newEditRangeSlice === "") { + return currCursorPos; + } // How far away is the current line from the start of the editable region? const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine; @@ -274,81 +277,163 @@ export interface DiffGroup { type?: string; // Optional classification of the group } +/** + * Group diff lines into meaningful sections based on changes + * @param diffLines The diff lines to group + * @param offset Optional line offset to apply to the resulting line numbers + * @param maxGroupSize Optional maximum group size constraint (Mode 2) + * @returns Array of DiffGroup objects representing the changes + */ export function groupDiffLines( diffLines: DiffLine[], - maxGroupSize: number = 5, + offset: number = 0, + maxGroupSize?: number, ): DiffGroup[] { const groups: DiffGroup[] = []; + const changedAreas = findChangedAreas(diffLines); - // First pass: find areas where changes occur + for (const area of changedAreas) { + if (maxGroupSize === undefined) { + // Mode 1: Flexible group size. + groups.push( + processFlexibleSizeGroup(diffLines, area.start, area.end, offset), + ); + } else { + // Mode 2: Limited group size. + groups.push( + processLimitedSizeGroup( + diffLines, + area.start, + area.end, + maxGroupSize, + offset, + ), + ); + } + } + + return groups; +} + +/** + * Find areas of change in the diff lines. + */ +function findChangedAreas( + diffLines: DiffLine[], +): { start: number; end: number }[] { + const changedAreas: { start: number; end: number }[] = []; let changedAreaStart = -1; for (let i = 0; i < diffLines.length; i++) { if (diffLines[i].type !== "same" && changedAreaStart === -1) { changedAreaStart = i; } else if (diffLines[i].type === "same" && changedAreaStart !== -1) { - // We've found the end of a changed area, process it - processChangedArea(changedAreaStart, i - 1); + // We've found the end of a changed area. + changedAreas.push({ start: changedAreaStart, end: i - 1 }); changedAreaStart = -1; } } - // Handle the last changed area if it extends to the end + // Handle the last changed area if it extends to the end. if (changedAreaStart !== -1) { - processChangedArea(changedAreaStart, diffLines.length - 1); + changedAreas.push({ start: changedAreaStart, end: diffLines.length - 1 }); } - function processChangedArea(start: number, end: number) { - // Calculate result line numbers - let resultLineStart = 0; - - // Count how many result lines appear before the start - for (let i = 0; i < start; i++) { - if (diffLines[i].type !== "old") { - resultLineStart++; - } - } - - // Create a group from the change area - const changedLines = diffLines.slice(start, end + 1); - - // Count how many additional lines we can include - const changedResultLineCount = changedLines.filter( - (l) => l.type !== "old", - ).length; - const additionalLinesNeeded = maxGroupSize - changedResultLineCount; - - // Add additional context lines after the change - let additionalLines: DiffLine[] = []; - let additionalResultLineCount = 0; - - for ( - let i = end + 1; - i < diffLines.length && additionalResultLineCount < additionalLinesNeeded; - i++ - ) { - additionalLines.push(diffLines[i]); - if (diffLines[i].type !== "old") { - additionalResultLineCount++; - } - } - - // Calculate the ending result line number - let resultLineEnd = resultLineStart; - for (const line of [...changedLines, ...additionalLines]) { - if (line.type !== "old") { - resultLineEnd++; - } - } - resultLineEnd--; // Adjust because we incremented one too many times - - // Create the group - groups.push({ - startLine: resultLineStart, - endLine: resultLineEnd, - lines: [...changedLines, ...additionalLines], - }); - } - - return groups; + return changedAreas; +} + +/** + * Count the number of lines in the old content (excluding "new" lines). + */ +function countOldContentLines( + diffLines: DiffLine[], + startIdx: number, + endIdx: number, +): number { + let count = 0; + for (let i = startIdx; i <= endIdx; i++) { + if (diffLines[i].type !== "new") { + count++; + } + } + return count; +} + +/** + * Process a changed area with a limited group size. + */ +function processLimitedSizeGroup( + diffLines: DiffLine[], + start: number, + end: number, + maxGroupSize: number, + offset: number, +): DiffGroup { + // Calculate the starting line in old content. + let oldContentLineStart = countOldContentLines(diffLines, 0, start - 1); + + // Track how many lines we have left in our group size budget. + let remainingGroupSize = maxGroupSize; + let currentLine = start; + const lines: DiffLine[] = []; + + // Process lines until we hit our size limit or reach the end. + while (currentLine <= end && remainingGroupSize > 0) { + // Add current line to results if we haven't seen it yet. + if ( + lines.length === 0 || + (lines.length > 0 && + lines[lines.length - 1].line !== diffLines[currentLine].line) + ) { + lines.push(diffLines[currentLine]); + } + + if (diffLines[currentLine].type === "old") { + currentLine++; + } else if (diffLines[currentLine].type === "same") { + remainingGroupSize--; + currentLine++; + } else if (diffLines[currentLine].type === "new") { + remainingGroupSize--; + currentLine++; + } + } + + // Adjust for the last increment. + currentLine--; + + // Calculate the end line in old content. + let oldContentLineEnd = + oldContentLineStart + + countOldContentLines(diffLines, start, currentLine) - + 1; + + return { + startLine: oldContentLineStart + offset, + endLine: oldContentLineEnd + offset, + lines, + }; +} + +/** + * Process a changed area with flexible sizing. + */ +function processFlexibleSizeGroup( + diffLines: DiffLine[], + start: number, + end: number, + offset: number, +): DiffGroup { + // Calculate the starting line in old content. + let oldContentLineStart = countOldContentLines(diffLines, 0, start - 1); + + // Calculate the end line in old content. + let oldContentLineEnd = + oldContentLineStart + countOldContentLines(diffLines, start, end) - 1; + + return { + startLine: oldContentLineStart + offset, + endLine: oldContentLineEnd + offset, + lines: diffLines.slice(start, end + 1), + }; } From 7af923137e763035dda899f1b927c533e7bec4b7 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 13:23:27 -0700 Subject: [PATCH 39/48] refactor: add diffLines --- extensions/vscode/src/activation/JumpManager.vitest.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/vscode/src/activation/JumpManager.vitest.ts b/extensions/vscode/src/activation/JumpManager.vitest.ts index 3a74f479b..457918857 100644 --- a/extensions/vscode/src/activation/JumpManager.vitest.ts +++ b/extensions/vscode/src/activation/JumpManager.vitest.ts @@ -153,6 +153,7 @@ const createMockNextEditOutcome = ( accepted: true, editableRegionStartLine: 1, editableRegionEndLine: 3, + diffLines: [], // Apply any overrides ...overrides, From 5dd17da77416411f86e7ed4dcec90daa6e197445 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 13:25:00 -0700 Subject: [PATCH 40/48] fix: proper finalcursorpos setting and disposal of decorations --- .../src/activation/NextEditWindowManager.ts | 123 +++++++++++++----- 1 file changed, 89 insertions(+), 34 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 4a2b29870..970494d33 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -129,6 +129,8 @@ export class NextEditWindowManager { private finalCursorPos: vscode.Position | null = null; + private isLineDelete: boolean = false; + private context: vscode.ExtensionContext | null = null; public static getInstance(): NextEditWindowManager { @@ -273,19 +275,45 @@ export class NextEditWindowManager { newEditRangeSlice: string, diffLines: DiffLine[], ) { - if (!newEditRangeSlice || !this.shouldRenderTip(editor.document.uri)) { + if (!this.shouldRenderTip(editor.document.uri)) { return; } // Clear any existing decorations first (very important to prevent overlapping). await this.hideAllNextEditWindows(); + this.activeEditor = editor; + this.editableRegionStartLine = editableRegionStartLine; this.editableRegionEndLine = editableRegionEndLine; // Store the current tooltip text for accepting later. this.currentTooltipText = newEditRangeSlice; + // Determine if this is a line deletion case + // NOTE: A simpler approach might be to just delete the line when newEditRangeSlice is "". + // But we opt for the below in case the above note is too naive. + this.isLineDelete = false; + if ( + newEditRangeSlice === "" && + editableRegionStartLine === editableRegionEndLine + ) { + // Check if diffLines contains only deletions (no additions). + const onlyDeletions = diffLines.every( + (diff) => diff.type === "old" || diff.type === "same", + ); + const hasDeletedLine = diffLines.some((diff) => diff.type === "old"); + + if (onlyDeletions && hasDeletedLine) { + // Check if the entire line is being deleted (not just characters). + const line = editor.document.lineAt(editableRegionStartLine).text; + const oldLine = oldEditRangeSlice.trim(); + if (line.trim() === oldLine || line.trim() === "") { + this.isLineDelete = true; + } + } + } + // How far away is the current line from the start of the editable region? const lineOffsetAtCursorPos = currCursorPos.line - this.editableRegionStartLine; @@ -300,22 +328,40 @@ export class NextEditWindowManager { lineOffsetAtCursorPos, ); - // Calculate the actual line number in the editor by adding the startPos offset - // to the line number from the diff calculation. - this.finalCursorPos = new vscode.Position( - this.editableRegionStartLine + offset.line, - offset.character, - ); + // Calculate the final cursor position. + if (this.isLineDelete) { + // For line deletion, position cursor at the end of the previous line. + if (this.editableRegionStartLine > 0) { + const prevLine = editor.document.lineAt( + this.editableRegionStartLine - 1, + ); + this.finalCursorPos = new vscode.Position( + this.editableRegionStartLine - 1, + prevLine.text.length, + ); + } else { + // If we're deleting the first line, position at the start of the document. + this.finalCursorPos = new vscode.Position(0, 0); + } + } else { + // For normal edits, use the standard calculation. + this.finalCursorPos = new vscode.Position( + this.editableRegionStartLine + offset.line, + offset.character, + ); + } // Create and apply decoration with the text. - await this.renderWindow( - editor, - currCursorPos, - oldEditRangeSlice, - newEditRangeSlice, - this.editableRegionStartLine, - diffLines, - ); + if (newEditRangeSlice !== "") { + await this.renderWindow( + editor, + currCursorPos, + oldEditRangeSlice, + newEditRangeSlice, + this.editableRegionStartLine, + diffLines, + ); + } const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); @@ -347,12 +393,14 @@ export class NextEditWindowManager { this.currentDecoration.dispose(); this.currentDecoration = null; - this.disposables.forEach((d) => d.dispose()); - this.disposables = []; - // Clear the current tooltip text. this.currentTooltipText = null; } + + if (this.disposables.length > 0) { + this.disposables.forEach((d) => d.dispose()); + this.disposables = []; + } } public async hideAllNextEditWindowsAndResetCompletionId() { @@ -368,11 +416,14 @@ export class NextEditWindowManager { this.mostRecentCompletionId = null; } + /** + * Accept the current next edit suggestion by inserting it at cursor position. + */ /** * Accept the current next edit suggestion by inserting it at cursor position. */ private async acceptNextEdit() { - if (!this.activeEditor || !this.currentTooltipText) { + if (this.activeEditor === null || this.currentTooltipText === null) { return; } this.accepted = true; @@ -405,16 +456,26 @@ export class NextEditWindowManager { ); const editRange = new vscode.Range(startPos, endPos); - success = await editor.edit((editBuilder) => { - editBuilder.replace(editRange, text); - }); + if (this.isLineDelete) { + // Handle line deletion - extend the range to include the newline. + let lineDeleteRange = editRange; - // 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); + // If this isn't the last line, extend to include the newline character. + if (this.editableRegionStartLine < editor.document.lineCount - 1) { + lineDeleteRange = new vscode.Range( + startPos, + new vscode.Position(this.editableRegionStartLine + 1, 0), + ); + } + + success = await editor.edit((editBuilder) => { + editBuilder.delete(lineDeleteRange); + }); + } else { + success = await editor.edit((editBuilder) => { + editBuilder.replace(editRange, text); + }); + } } if (success && this.finalCursorPos) { @@ -425,11 +486,6 @@ export class NextEditWindowManager { ); } - // Reenable inline suggestions after we move the cursor. - // await vscode.workspace - // .getConfiguration() - // .update("editor.inlineSuggest.enabled", true, true); - // Log with accept = true. await vscode.commands.executeCommand( "continue.logNextEditOutcomeAccept", @@ -759,7 +815,6 @@ export class NextEditWindowManager { // Store the decoration and editor. this.currentDecoration = decoration; // TODO: This might be redundant. this.disposables.push(decoration); - this.activeEditor = editor; // Calculate how far off to the right of the cursor the decoration should be. const decorationOffsetPosition = this.getDecorationOffsetPosition( From bdf9544fa92a55e347d23d0e5fe13b6f9d37d0ea Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 13:26:02 -0700 Subject: [PATCH 41/48] fix: still render empty completions in case they are oure deletions --- .../src/autocomplete/completionProvider.ts | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d30930748..b81111e81 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -13,7 +13,6 @@ import { handleLLMError } from "../util/errorHandling"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { myersDiff } from "core/diff/myers"; import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue"; @@ -358,6 +357,7 @@ export class ContinueCompletionProvider console.log( "No suitable jump location found after trying all positions", ); + this.nextEditProvider.deleteChain(); return undefined; } } else { @@ -390,7 +390,10 @@ export class ContinueCompletionProvider // If initial outcome is null, suggest a jump instead. // Calling this method again will call it with // chain active but jump not suggested yet. - if (!outcome || !outcome.completion) { + if ( + !outcome || + (!outcome.completion && outcome.diffLines.length === 0) + ) { return this.provideInlineCompletionItems( document, position, @@ -409,7 +412,14 @@ export class ContinueCompletionProvider } // Return early if no valid outcome was found. - if (!outcome || !outcome.completion) { + if ( + !outcome || + (!this.isNextEditActive && + !(outcome as AutocompleteOutcome).completion) || + (this.isNextEditActive && + !(outcome as NextEditOutcome).completion && + (outcome as NextEditOutcome).diffLines.length === 0) + ) { return null; } @@ -509,12 +519,6 @@ export class ContinueCompletionProvider // Check the diff between old and new editable region. const newEditRangeSlice = completionText; - // We don't need to show the next edit window if the predicted edits is empty. - if (newEditRangeSlice === "") { - this.nextEditLoggingService.cancelRejectionTimeout(completionId); - return undefined; - } - // Get the contents of the old (current) editable region. // const editableRegionStartLine = Math.max( // currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, @@ -588,7 +592,7 @@ export class ContinueCompletionProvider } // Handle non-FIM cases with the NextEditWindowManager. - const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + const diffLines = (outcome as NextEditOutcome).diffLines; if (diffLines.length === 0) { // At this point, there is no way that diffLines.length === 0. // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse. From 7cc714106297b6ec615b4f3f3c22e4af06012aee Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 13:27:05 -0700 Subject: [PATCH 42/48] chore: bump version --- binary/package-lock.json | 4 ++-- core/package-lock.json | 4 ++-- extensions/vscode/package-lock.json | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/binary/package-lock.json b/binary/package-lock.json index 85ce515a1..83a78d4d2 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -53,8 +53,8 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.14", - "@continuedev/llm-info": "^1.0.8", + "@continuedev/fetch": "file:../packages/fetch", + "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", diff --git a/core/package-lock.json b/core/package-lock.json index a864be394..bb018d8f9 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -170,7 +170,7 @@ }, "../packages/fetch": { "name": "@continuedev/fetch", - "version": "1.0.15", + "version": "1.0.16", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "file:../config-types", @@ -196,7 +196,7 @@ }, "../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.0.46", + "version": "1.1.1", "license": "Apache-2.0", "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.842.0", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 9483160c6..76e958b38 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.67", + "version": "1.1.71", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.67", + "version": "1.1.71", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "file:../../packages/config-types", @@ -222,7 +222,7 @@ }, "../../packages/fetch": { "name": "@continuedev/fetch", - "version": "1.0.15", + "version": "1.0.16", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "file:../config-types", From 1374574f30403bf1a2515e4fae8e414003019af2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 16:18:31 -0700 Subject: [PATCH 43/48] fix: stale tests --- core/nextEdit/NextEditProvider.vitest.ts | 8 +- .../templating/mercuryCoderNextEdit.vitest.ts | 5 +- .../src/activation/JumpManager.vitest.ts | 222 +++++++++++------- 3 files changed, 148 insertions(+), 87 deletions(-) diff --git a/core/nextEdit/NextEditProvider.vitest.ts b/core/nextEdit/NextEditProvider.vitest.ts index 99a9045bb..a86cc8a34 100644 --- a/core/nextEdit/NextEditProvider.vitest.ts +++ b/core/nextEdit/NextEditProvider.vitest.ts @@ -173,12 +173,12 @@ describe("_calculateOptimalEditableRegion", () => { "tokenizer", ); - // Each line is 10 chars = 10 tokens per line with our mock - // So with 500 token limit, we should get ~45 lines total + // Each line is 10 chars = 10 tokens per line with our mock. + // So with 500 token limit, we should get 50 lines total. + // 25 above, 25 below, +1 current const totalLines = result.editableRegionEndLine - result.editableRegionStartLine + 1; - const expectedMaxLines = Math.floor(500 / 10); - expect(totalLines).toBe(expectedMaxLines); // Not more than 50 lines + expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line) }); it("should use character approximation when using fourChars heuristic", () => { diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts index 8fefb5e7b..6a1c35c74 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts @@ -106,9 +106,10 @@ describe("mercuryCoderNextEdit", () => { describe("editHistoryBlock", () => { it("should return the edit diff history unchanged", () => { - const diffHistory = "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"; + const diffHistory = + "diff --git a/file.ts b/file.ts\n==============================\n@@ -1,3 +1,4 @@"; const result = editHistoryBlock(diffHistory); - expect(result).toBe(diffHistory); + expect(result).toBe("@@ -1,3 +1,4 @@"); }); it("should handle empty diff history", () => { diff --git a/extensions/vscode/src/activation/JumpManager.vitest.ts b/extensions/vscode/src/activation/JumpManager.vitest.ts index 457918857..796ab225f 100644 --- a/extensions/vscode/src/activation/JumpManager.vitest.ts +++ b/extensions/vscode/src/activation/JumpManager.vitest.ts @@ -8,78 +8,66 @@ import { CompletionDataForAfterJump, JumpManager } from "./JumpManager"; 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, + lineAt: vi.fn().mockReturnValue({ + text: "Sample line text", + lineNumber: 0, + }), + getText: vi.fn().mockReturnValue("Sample document text"), + lineCount: 5, + }, + selection: { + active: { line: 0, character: 0 }, }, setDecorations: vi.fn(), - selection: { active: { line: 0, character: 0 } }, revealRange: vi.fn(), - visibleRanges: [{ start: { line: 0 }, end: { line: 5 } }], + visibleRanges: [ + { + start: { line: 0, character: 0 }, + end: { line: 4, character: 0 }, // Changed to be within document bounds + }, + ], }, - onDidChangeTextEditorSelection: vi.fn(() => ({ + createTextEditorDecorationType: vi.fn().mockReturnValue({ dispose: vi.fn(), - })), - }, - commands: { - executeCommand: vi.fn(), - registerCommand: vi.fn(() => ({ + }), + onDidChangeTextEditorSelection: vi.fn().mockReturnValue({ dispose: vi.fn(), - })), + }), }, Position: class { - line: number; - character: number; - constructor(line: number, character: number) { - this.line = line; - this.character = character; - } - isEqual(other: any): boolean { + constructor( + public line: number, + public character: number, + ) {} + isEqual(other: any) { 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; - } + constructor( + public anchor: any, + public active: any, + ) {} }, - TextEditorDecorationType: class { - dispose: () => void; - constructor() { - this.dispose = vi.fn(); - } + Range: class { + constructor( + public start: any, + public end: any, + ) {} }, TextEditorRevealType: { - InCenter: "inCenter", + InCenter: 2, }, ThemeColor: class { - id: string; - constructor(id: string) { - this.id = id; - } + constructor(public id: string) {} + }, + commands: { + executeCommand: vi.fn(), + registerCommand: vi.fn().mockReturnValue({ + dispose: vi.fn(), + }), }, }; }); @@ -167,6 +155,19 @@ describe("JumpManager", () => { // Reset mocks vi.resetAllMocks(); + // Re-setup the lineAt mock after reset + const mockLineAt = vi.fn().mockReturnValue({ + text: "Sample line text", + lineNumber: 0, + }); + + // Ensure our mock is properly set up after reset + if (vscode.window.activeTextEditor?.document) { + vi.mocked( + vscode.window.activeTextEditor.document.lineAt, + ).mockImplementation(mockLineAt); + } + // Clear any existing instance JumpManager.clearInstance(); @@ -217,18 +218,26 @@ describe("JumpManager", () => { const completionContent = "Test line content"; // Mock document content to match the completion content - vscode.window.activeTextEditor!.document.lineAt = vi.fn(() => ({ + const mockLineAt = vi.fn().mockReturnValue({ text: "Test line content", lineNumber: 3, - })) as any; + }); - await jumpManager.suggestJump( + // Override the mock for this specific test + vi.mocked( + vscode.window.activeTextEditor!.document.lineAt, + ).mockImplementation(mockLineAt); + + const result = await jumpManager.suggestJump( currentPosition, nextJumpLocation, completionContent, ); - // Jump should not be suggested, so decorations should not be created + // Jump should not be suggested + expect(result).toBe(false); + expect(jumpManager.isJumpInProgress()).toBe(false); + // Decorations should not be created expect( vscode.window.createTextEditorDecorationType, ).not.toHaveBeenCalled(); @@ -261,10 +270,11 @@ describe("JumpManager", () => { 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 mockEditor = vscode.window.activeTextEditor!; + Object.defineProperty(mockEditor, "visibleRanges", { + value: [{ start: { line: 5 }, end: { line: 10 } }], + writable: true, + }); const currentPosition = new vscode.Position(6, 0); const nextJumpLocation = new vscode.Position(2, 0); // Outside visible range (above) @@ -274,21 +284,30 @@ describe("JumpManager", () => { // Should create decoration expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); }); + + it("should render decoration for jump location within visible range", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(2, 0); // Within visible range (0-4) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + // Should reveal range + expect(vscode.window.activeTextEditor!.revealRange).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) + // Setup private method access const privateJumpManager = jumpManager as any; // Mock context privateJumpManager._jumpDecorationVisible = true; - // Create editor mock - const editor = { - selection: null, - setSelection: vi.fn(), - }; + // Create editor mock that matches the expected interface + const editor = vscode.window.activeTextEditor!; // Create jump position const jumpPosition = new vscode.Position(3, 5); @@ -297,11 +316,14 @@ describe("JumpManager", () => { 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]; + const commandArgs = vi + .mocked(vscode.commands.registerCommand) + .mock.calls.find((call: any) => call[0] === "continue.acceptJump"); + expect(commandArgs).toBeDefined(); + const acceptJumpHandler = commandArgs![1]; + + // Clear previous executeCommand calls + vi.mocked(vscode.commands.executeCommand).mockClear(); // Call the handler await acceptJumpHandler(); @@ -316,6 +338,10 @@ describe("JumpManager", () => { "continue.jumpDecorationVisible", false, ); + // Expect inline suggest to be triggered + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "editor.action.inlineSuggest.trigger", + ); }); it("should register rejectJump command that deletes the chain", async () => { @@ -333,17 +359,16 @@ describe("JumpManager", () => { // Call the private method await privateJumpManager.registerKeyListeners( - {} as vscode.TextEditor, + vscode.window.activeTextEditor!, 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", - ); + const commandArgs = vi + .mocked(vscode.commands.registerCommand) + .mock.calls.find((call: any) => call[0] === "continue.rejectJump"); expect(commandArgs).toBeDefined(); - const rejectJumpHandler = commandArgs?.[1]; + const rejectJumpHandler = commandArgs![1]; expect(rejectJumpHandler).toBeDefined(); // Reset executeCommand mock @@ -352,9 +377,6 @@ describe("JumpManager", () => { // 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(); @@ -365,6 +387,44 @@ describe("JumpManager", () => { false, ); }); + + it("should register selection change listener that rejects jump on cursor movement", async () => { + const privateJumpManager = jumpManager as any; + privateJumpManager._jumpDecorationVisible = true; + privateJumpManager._oldCursorPosition = new vscode.Position(1, 0); + + const jumpPosition = new vscode.Position(3, 0); + + await privateJumpManager.registerKeyListeners( + vscode.window.activeTextEditor!, + jumpPosition, + ); + + // Find the selection change listener + expect(vscode.window.onDidChangeTextEditorSelection).toHaveBeenCalled(); + const selectionChangeListener = vi.mocked( + vscode.window.onDidChangeTextEditorSelection, + ).mock.calls[0][0]; + + // Mock a selection change event that moves cursor away from both old and jump positions + const newPosition = new vscode.Position(5, 0); + const mockEvent = { + textEditor: vscode.window.activeTextEditor!, + kind: undefined, // Can be undefined according to VSCode API + selections: [new vscode.Selection(newPosition, newPosition)], // Use proper Selection object + }; + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the selection change listener + selectionChangeListener(mockEvent); + + // Should trigger reject jump + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "continue.rejectJump", + ); + }); }); describe("setCompletionAfterJump", () => { From 9924e868e0cd01d046a4ef8e80cdb3cf72f6ea3d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 16:18:44 -0700 Subject: [PATCH 44/48] fix: handle undefined disposables --- extensions/vscode/src/activation/JumpManager.ts | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 7d3adb73c..65bffaa0a 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -45,7 +45,9 @@ export class JumpManager { public dispose() { // Dispose current decoration. - this._disposables.forEach((d) => d.dispose()); + this._disposables.forEach((d) => { + if (d) d.dispose(); + }); this._disposables = []; } @@ -75,14 +77,6 @@ export class JumpManager { document.lineCount - 1, ); - console.log( - "editor lines:", - document - .getText() - .split("\n") - .slice(startLine, endLine + 1), - ); - // First check if we have enough lines in the document if (endLine - startLine + 1 < completionLines.length) { // Not enough lines in document, so content can't be identical. @@ -225,8 +219,7 @@ export class JumpManager { } // Dispose any active listeners. - this._disposables.forEach((d) => d.dispose()); - this._disposables = []; + this.dispose(); // Reset the context. await vscode.commands.executeCommand( From ea5859b3daeafee4c79fb13d4a17d832360942f0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 17:46:42 -0700 Subject: [PATCH 45/48] fix: bug where newlines aren't escaped properly --- core/util/text.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/util/text.ts b/core/util/text.ts index 9e948f415..434436c40 100644 --- a/core/util/text.ts +++ b/core/util/text.ts @@ -32,7 +32,10 @@ export function escapeForSVG(text: string): string { .replace(//g, ">") .replace(/"/g, """) - .replace(/'/g, "'"); + .replace(/'/g, "'") + .replace(/\n/g, "\\n") // newlines + .replace(/\t/g, "\\t") // tabs + .replace(/\r/g, "\\r"); // carriage returns } export function kebabOfStr(str: string): string { From 404cce0047b2e665c7c7092a993a891d1bfae055 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 17:47:07 -0700 Subject: [PATCH 46/48] fix: handle numbers as well --- core/util/text.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/util/text.ts b/core/util/text.ts index 434436c40..297bfd5c1 100644 --- a/core/util/text.ts +++ b/core/util/text.ts @@ -40,7 +40,7 @@ export function escapeForSVG(text: string): string { export function kebabOfStr(str: string): string { return str - .replace(/([a-z])([A-Z])/g, "$1-$2") // handle camelCase and PascalCase + .replace(/([a-z0-9])([A-Z])/g, "$1-$2") // handle camelCase, PascalCase, and numbers followed by uppercase .replace(/[\s_]+/g, "-") // replace spaces and underscores with hyphens .toLowerCase(); } From 63d938e53a5bf136f432253c99868640f68a44d0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 5 Aug 2025 17:47:15 -0700 Subject: [PATCH 47/48] test: add vitest for text.ts --- core/util/text.vitest.ts | 186 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 core/util/text.vitest.ts diff --git a/core/util/text.vitest.ts b/core/util/text.vitest.ts new file mode 100644 index 000000000..d69ffa781 --- /dev/null +++ b/core/util/text.vitest.ts @@ -0,0 +1,186 @@ +import { describe, expect, it } from "vitest"; +import { + capitalizeFirstLetter, + escapeForSVG, + kebabOfStr, + replaceEscapedCharacters, +} from "./text"; + +describe("capitalizeFirstLetter", () => { + it("should capitalize the first letter of a string", () => { + expect(capitalizeFirstLetter("hello")).toBe("Hello"); + expect(capitalizeFirstLetter("world")).toBe("World"); + }); + + it("should handle already capitalized strings", () => { + expect(capitalizeFirstLetter("Hello")).toBe("Hello"); + }); + + it("should handle single character strings", () => { + expect(capitalizeFirstLetter("a")).toBe("A"); + expect(capitalizeFirstLetter("A")).toBe("A"); + }); + + it("should handle empty strings", () => { + expect(capitalizeFirstLetter("")).toBe(""); + }); + + it("should handle strings with numbers", () => { + expect(capitalizeFirstLetter("123abc")).toBe("123abc"); + }); + + it("should handle strings with special characters", () => { + expect(capitalizeFirstLetter("@hello")).toBe("@hello"); + expect(capitalizeFirstLetter("!world")).toBe("!world"); + }); +}); + +describe("replaceEscapedCharacters", () => { + it("should replace escaped newlines with actual newlines", () => { + expect(replaceEscapedCharacters("Hello\\nWorld")).toBe("Hello\nWorld"); + }); + + it("should replace escaped tabs with actual tabs", () => { + expect(replaceEscapedCharacters("Hello\\tWorld")).toBe("Hello\tWorld"); + }); + + it("should replace escaped carriage returns with actual carriage returns", () => { + expect(replaceEscapedCharacters("Hello\\rWorld")).toBe("Hello\rWorld"); + }); + + it("should replace escaped backslashes with actual backslashes", () => { + expect(replaceEscapedCharacters("Hello\\\\World")).toBe("Hello\\World"); + }); + + it("should replace escaped double quotes with actual double quotes", () => { + expect(replaceEscapedCharacters('Hello\\"World')).toBe('Hello"World'); + }); + + it("should replace escaped single quotes with actual single quotes", () => { + expect(replaceEscapedCharacters("Hello\\'World")).toBe("Hello'World"); + }); + + it("should handle multiple escaped characters", () => { + expect( + replaceEscapedCharacters("Line1\\nLine2\\tTabbed\\\\Backslash"), + ).toBe("Line1\nLine2\tTabbed\\Backslash"); + }); + + it("should handle strings without escaped characters", () => { + expect(replaceEscapedCharacters("Hello World")).toBe("Hello World"); + }); + + it("should handle empty strings", () => { + expect(replaceEscapedCharacters("")).toBe(""); + }); + + it("should not replace invalid escape sequences", () => { + expect(replaceEscapedCharacters("Hello\\xWorld")).toBe("Hello\\xWorld"); + }); +}); + +describe("escapeForSVG", () => { + it("should escape XML entities", () => { + expect(escapeForSVG("Hello & World")).toBe("Hello & World"); + expect(escapeForSVG("Hello < World")).toBe("Hello < World"); + expect(escapeForSVG("Hello > World")).toBe("Hello > World"); + expect(escapeForSVG('Hello "World"')).toBe("Hello "World""); + expect(escapeForSVG("Hello 'World'")).toBe("Hello 'World'"); + }); + + it("should escape whitespace characters as literal escape sequences", () => { + expect(escapeForSVG("Hello\nWorld")).toBe("Hello\\nWorld"); + expect(escapeForSVG("Hello\tWorld")).toBe("Hello\\tWorld"); + expect(escapeForSVG("Hello\rWorld")).toBe("Hello\\rWorld"); + }); + + it("should handle multiple types of characters together", () => { + expect(escapeForSVG("Line1\nLine2&<>\"'Tab\tHere")).toBe( + "Line1\\nLine2&<>"'Tab\\tHere", + ); + }); + + it("should handle empty strings", () => { + expect(escapeForSVG("")).toBe(""); + }); + + it("should handle strings with only whitespace characters", () => { + expect(escapeForSVG("\n\t\r")).toBe("\\n\\t\\r"); + }); + + it("should handle strings without special characters", () => { + expect(escapeForSVG("Hello World 123")).toBe("Hello World 123"); + }); + + it("should handle complex multiline code examples", () => { + const codeExample = `function test() { + console.log("Hello & World"); + return true; +}`; + const expected = `function test() {\\n console.log("Hello & World");\\n return true;\\n}`; + expect(escapeForSVG(codeExample)).toBe(expected); + }); + + it("should handle edge case with all escape types", () => { + expect(escapeForSVG("&<>\"'\n\t\r")).toBe( + "&<>"'\\n\\t\\r", + ); + }); +}); + +describe("kebabOfStr", () => { + it("should convert camelCase to kebab-case", () => { + expect(kebabOfStr("camelCase")).toBe("camel-case"); + expect(kebabOfStr("someVariableName")).toBe("some-variable-name"); + }); + + it("should convert PascalCase to kebab-case", () => { + expect(kebabOfStr("PascalCase")).toBe("pascal-case"); + expect(kebabOfStr("SomeClassName")).toBe("some-class-name"); + }); + + it("should convert spaces to hyphens", () => { + expect(kebabOfStr("hello world")).toBe("hello-world"); + expect(kebabOfStr("multiple spaces")).toBe("multiple-spaces"); + }); + + it("should convert underscores to hyphens", () => { + expect(kebabOfStr("snake_case")).toBe("snake-case"); + expect(kebabOfStr("multiple___underscores")).toBe("multiple-underscores"); + }); + + it("should convert mixed formats", () => { + expect(kebabOfStr("mixedCase_with spaces")).toBe("mixed-case-with-spaces"); + expect(kebabOfStr("PascalCase_Snake SPACE")).toBe( + "pascal-case-snake-space", + ); + }); + + it("should handle already kebab-case strings", () => { + expect(kebabOfStr("already-kebab")).toBe("already-kebab"); + }); + + it("should handle strings with numbers", () => { + expect(kebabOfStr("version2Beta")).toBe("version2-beta"); + expect(kebabOfStr("test123Case")).toBe("test123-case"); + }); + + it("should handle empty strings", () => { + expect(kebabOfStr("")).toBe(""); + }); + + it("should handle single characters", () => { + expect(kebabOfStr("A")).toBe("a"); + expect(kebabOfStr("a")).toBe("a"); + }); + + it("should handle special characters", () => { + expect(kebabOfStr("hello@world")).toBe("hello@world"); + expect(kebabOfStr("test.file.name")).toBe("test.file.name"); + }); + + it("should convert to lowercase", () => { + expect(kebabOfStr("UPPERCASE")).toBe("uppercase"); + expect(kebabOfStr("MiXeD cAsE")).toBe("mi-xe-d-c-as-e"); + }); +}); From f7ab325fed7c8113d88ab7081a12b30155bf507c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 14:25:34 -0700 Subject: [PATCH 48/48] test: add vitest for SelectionChangeManager --- .../SelectionChangeManager.vitest.ts | 899 ++++++++++++++++++ 1 file changed, 899 insertions(+) create mode 100644 extensions/vscode/src/activation/SelectionChangeManager.vitest.ts diff --git a/extensions/vscode/src/activation/SelectionChangeManager.vitest.ts b/extensions/vscode/src/activation/SelectionChangeManager.vitest.ts new file mode 100644 index 000000000..941ef5c24 --- /dev/null +++ b/extensions/vscode/src/activation/SelectionChangeManager.vitest.ts @@ -0,0 +1,899 @@ +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "core/nextEdit/NextEditEditableRegionCalculator"; +import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; +import { VsCodeIde } from "../VsCodeIde"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { JumpManager } from "./JumpManager"; +import { NextEditWindowManager } from "./NextEditWindowManager"; +import { + HandlerPriority, + SelectionChangeManager, +} from "./SelectionChangeManager"; + +// Mock VSCode API +vi.mock("vscode", () => ({ + window: { + activeTextEditor: { + document: { + uri: { + toString: vi.fn().mockReturnValue("file:///test/file.ts"), + }, + getText: vi.fn().mockReturnValue("Sample document text"), + lineCount: 10, + lineAt: vi.fn((line) => ({ + text: "sample line text", + range: { + start: { line, character: 0 }, + end: { line, character: 16 }, + }, + })), + }, + selections: [ + { + active: { line: 2, character: 5 }, + anchor: { line: 2, character: 5 }, + }, + ], + }, + }, + Position: class { + constructor( + public line: number, + public character: number, + ) {} + }, + Selection: class { + constructor( + public anchor: any, + public active: any, + ) {} + }, +})); + +// Mock core dependencies +vi.mock("core/nextEdit/NextEditProvider", () => ({ + NextEditProvider: { + getInstance: vi.fn(() => ({ + deleteChain: vi.fn(), + })), + }, +})); + +vi.mock("core/nextEdit/NextEditEditableRegionCalculator", () => ({ + EditableRegionStrategy: { + Static: "static", + Sliding: "sliding", + }, + getNextEditableRegion: vi.fn(), +})); + +vi.mock("core/nextEdit/NextEditPrefetchQueue", () => ({ + PrefetchQueue: { + getInstance: vi.fn(() => ({ + enqueueUnprocessed: vi.fn(), + })), + }, +})); + +vi.mock("core/util/pathToUri", () => ({ + localPathOrUriToPath: vi.fn((uri) => uri.replace("file://", "")), +})); + +vi.mock("../VsCodeIde", () => ({ + VsCodeIde: vi.fn(), +})); + +vi.mock("./JumpManager", () => ({ + JumpManager: { + getInstance: vi.fn(() => ({ + isJumpInProgress: vi.fn().mockReturnValue(false), + wasJumpJustAccepted: vi.fn().mockReturnValue(false), + })), + }, +})); + +vi.mock("./NextEditWindowManager", () => ({ + NextEditWindowManager: { + isInstantiated: vi.fn().mockReturnValue(false), + getInstance: vi.fn(() => ({ + hasAccepted: vi.fn().mockReturnValue(false), + })), + }, +})); + +describe("SelectionChangeManager", () => { + let selectionChangeManager: SelectionChangeManager; + let mockIde: VsCodeIde; + let mockDeleteChain: ReturnType; + let mockEnqueueUnprocessed: ReturnType; + + beforeEach(() => { + vi.resetAllMocks(); + + // Setup mock implementations + mockDeleteChain = vi.fn(); + mockEnqueueUnprocessed = vi.fn(); + + vi.mocked(NextEditProvider.getInstance).mockReturnValue({ + deleteChain: mockDeleteChain, + } as any); + + vi.mocked(PrefetchQueue.getInstance).mockReturnValue({ + enqueueUnprocessed: mockEnqueueUnprocessed, + } as any); + + vi.mocked(getNextEditableRegion).mockResolvedValue([ + { + filepath: "/test/file.ts", + range: { + start: { line: 0, character: 0 }, + end: { line: 10, character: 0 }, + }, + // content: "test content", + // cursorPosition: { line: 2, character: 5 }, + }, + ]); + + // Create mock context and webview protocol promise + const mockContext = { + subscriptions: [], + workspaceState: { + get: vi.fn(), + update: vi.fn(), + keys: vi.fn().mockReturnValue([]), + }, + globalState: { + get: vi.fn(), + update: vi.fn(), + keys: vi.fn().mockReturnValue([]), + setKeysForSync: vi.fn(), + }, + secrets: { + get: vi.fn(), + store: vi.fn(), + delete: vi.fn(), + onDidChange: vi.fn(), + }, + extensionUri: { fsPath: "/mock/extension/path" } as any, + extensionPath: "/mock/extension/path", + environmentVariableCollection: {} as any, + asAbsolutePath: vi.fn(), + storageUri: undefined, + storagePath: undefined, + globalStorageUri: { fsPath: "/mock/global/storage" } as any, + globalStoragePath: "/mock/global/storage", + logUri: { fsPath: "/mock/log" } as any, + logPath: "/mock/log", + extensionMode: 1, // Production mode + extension: {} as any, + } as vscode.ExtensionContext; + let resolveWebviewProtocol: any = undefined; + const webviewProtocolPromise = new Promise( + (resolve) => { + resolveWebviewProtocol = resolve; + }, + ); + + // Create VsCodeIde instance with proper constructor arguments + mockIde = new VsCodeIde(webviewProtocolPromise, mockContext); + + // Get a fresh instance + selectionChangeManager = SelectionChangeManager.getInstance(); + + // Clear any existing listeners from previous tests + const privateManager = selectionChangeManager as any; + privateManager.listeners = []; + + selectionChangeManager.initialize(mockIde, false); + }); + + afterEach(() => { + // Clear any timers + vi.clearAllTimers(); + + // Reset all private state to prevent test interference + const privateManager = selectionChangeManager as any; + privateManager.listeners = []; + privateManager.eventQueue = []; + privateManager.lastEventTime = 0; + privateManager.isProcessingEvent = false; + if (privateManager.processingTimeout) { + clearTimeout(privateManager.processingTimeout); + privateManager.processingTimeout = null; + } + privateManager.isTypingSession = false; + if (privateManager.typingTimer) { + clearTimeout(privateManager.typingTimer); + privateManager.typingTimer = null; + } + privateManager.lastDocumentChangeTime = 0; + }); + + describe("getInstance", () => { + it("should return the same instance on multiple calls", () => { + const instance1 = SelectionChangeManager.getInstance(); + const instance2 = SelectionChangeManager.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("initialize", () => { + it("should set up IDE and register default fallback handler", () => { + const newManager = new (SelectionChangeManager as any)(); + const registerSpy = vi.spyOn(newManager, "registerListener"); + + newManager.initialize(mockIde, true); + + expect(registerSpy).toHaveBeenCalledWith( + "defaultFallbackHandler", + expect.any(Function), + HandlerPriority.FALLBACK, + ); + }); + }); + + describe("documentChanged", () => { + it("should set typing session to true and update last document change time", () => { + const beforeTime = Date.now(); + selectionChangeManager.documentChanged(); + const afterTime = Date.now(); + + // Access private properties for testing + const privateManager = selectionChangeManager as any; + expect(privateManager.isTypingSession).toBe(true); + expect(privateManager.lastDocumentChangeTime).toBeGreaterThanOrEqual( + beforeTime, + ); + expect(privateManager.lastDocumentChangeTime).toBeLessThanOrEqual( + afterTime, + ); + }); + + it("should reset typing session timer", () => { + vi.useFakeTimers(); + + selectionChangeManager.documentChanged(); + const privateManager = selectionChangeManager as any; + + expect(privateManager.isTypingSession).toBe(true); + + // Fast-forward past the typing session timeout + vi.advanceTimersByTime(2100); // TYPING_SESSION_TIMEOUT is 2000ms + + expect(privateManager.isTypingSession).toBe(false); + + vi.useRealTimers(); + }); + }); + + describe("registerListener", () => { + it("should register a handler with correct priority", () => { + const mockHandler = vi.fn(); + const unregister = selectionChangeManager.registerListener( + "testHandler", + mockHandler, + HandlerPriority.HIGH, + ); + + // Access private listeners array + const privateManager = selectionChangeManager as any; + const testHandler = privateManager.listeners.find( + (l: any) => l.id === "testHandler", + ); + + expect(testHandler).toBeDefined(); + expect(testHandler.priority).toBe(HandlerPriority.HIGH); + expect(testHandler.handler).toBe(mockHandler); + + // Test unregister function + unregister(); + const afterUnregister = privateManager.listeners.find( + (l: any) => l.id === "testHandler", + ); + expect(afterUnregister).toBeUndefined(); + }); + + it("should replace existing handler with same id", () => { + const firstHandler = vi.fn(); + const secondHandler = vi.fn(); + + selectionChangeManager.registerListener( + "testHandler", + firstHandler, + HandlerPriority.NORMAL, + ); + + selectionChangeManager.registerListener( + "testHandler", + secondHandler, + HandlerPriority.HIGH, + ); + + const privateManager = selectionChangeManager as any; + const handlers = privateManager.listeners.filter( + (l: any) => l.id === "testHandler", + ); + + expect(handlers).toHaveLength(1); + expect(handlers[0].handler).toBe(secondHandler); + expect(handlers[0].priority).toBe(HandlerPriority.HIGH); + }); + + it("should sort handlers by priority in descending order", () => { + selectionChangeManager.registerListener( + "low", + vi.fn(), + HandlerPriority.LOW, + ); + selectionChangeManager.registerListener( + "critical", + vi.fn(), + HandlerPriority.CRITICAL, + ); + selectionChangeManager.registerListener( + "normal", + vi.fn(), + HandlerPriority.NORMAL, + ); + + const privateManager = selectionChangeManager as any; + const priorities = privateManager.listeners.map((l: any) => l.priority); + + // Should be sorted in descending order (CRITICAL=5, NORMAL=3, LOW=2, FALLBACK=1) + expect(priorities[0]).toBe(HandlerPriority.CRITICAL); + expect(priorities[1]).toBe(HandlerPriority.NORMAL); + expect(priorities[2]).toBe(HandlerPriority.LOW); + expect(priorities[3]).toBe(HandlerPriority.FALLBACK); + }); + }); + + describe("handleSelectionChange", () => { + let mockEvent: vscode.TextEditorSelectionChangeEvent; + let mockEvent1: vscode.TextEditorSelectionChangeEvent; + let mockEvent2: vscode.TextEditorSelectionChangeEvent; + let mockEvent3: vscode.TextEditorSelectionChangeEvent; + + beforeEach(() => { + mockEvent = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + mockEvent1 = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(0, 0), + new vscode.Position(0, 1), + ), + ], + kind: undefined, + }; + + mockEvent2 = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(1, 0), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + mockEvent3 = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(2, 0), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + }); + + it("should queue event if already processing", async () => { + vi.useFakeTimers(); + + // Mock Date.now to work with fake timers + const mockDateNow = vi.spyOn(Date, "now"); + let currentTime = 1000; // Start at some arbitrary time + mockDateNow.mockImplementation(() => currentTime); + + let firstHandlerResolve: (value: boolean) => void; + let handlerCallCount = 0; + + const slowHandler = vi.fn().mockImplementation(() => { + handlerCallCount++; + if (handlerCallCount === 1) { + return new Promise((resolve) => { + firstHandlerResolve = resolve; + }); + } else { + return Promise.resolve(true); + } + }); + + selectionChangeManager.registerListener( + "slowHandler", + slowHandler, + HandlerPriority.HIGH, + ); + + // First event - should bypass debouncing and start processing immediately + const firstEventPromise = + selectionChangeManager.handleSelectionChange(mockEvent1); + + // Advance time to simulate the first event being processed + currentTime += 10; // Small increment to simulate processing start + vi.advanceTimersByTime(10); + + expect(slowHandler).toHaveBeenCalledTimes(1); + + // Second event comes quickly (within DEBOUNCE_DELAY of 50ms) + currentTime += 10; // Total elapsed: 10ms (< 50ms DEBOUNCE_DELAY) + const secondEventPromise = + selectionChangeManager.handleSelectionChange(mockEvent2); + + // The second event should be queued due to isProcessingEvent = true, not debouncing + expect(slowHandler).toHaveBeenCalledTimes(1); // Still only called once + + // Third event comes within debounce window, replacing the second event. + currentTime += 10; // Total elapsed: 30ms (< 50ms DEBOUNCE_DELAY) + const thirdEventPromise = + selectionChangeManager.handleSelectionChange(mockEvent3); + + // Still should only be called once + expect(slowHandler).toHaveBeenCalledTimes(1); + + // Now resolve the first handler to allow queued events to process + firstHandlerResolve!(true); + + // Advance time to allow any pending timers to resolve + vi.advanceTimersByTime(100); + + // Wait for all events to complete + await Promise.all([ + firstEventPromise, + secondEventPromise, + thirdEventPromise, + ]); + + // Should have been called twice total: + // - Once for the first event + // - Once for the last queued event (debouncing replaces earlier queued events) + expect(slowHandler).toHaveBeenCalledTimes(2); + + mockDateNow.mockRestore(); + vi.useRealTimers(); + }); + + it("should implement debouncing for rapid events", async () => { + vi.useFakeTimers(); + + const mockHandler = vi.fn().mockResolvedValue(true); + selectionChangeManager.registerListener( + "testHandler", + mockHandler, + HandlerPriority.HIGH, + ); + + // Fire multiple events rapidly + selectionChangeManager.handleSelectionChange(mockEvent); + selectionChangeManager.handleSelectionChange(mockEvent); + selectionChangeManager.handleSelectionChange(mockEvent); + + // Only the last event should be queued due to debouncing + const privateManager = selectionChangeManager as any; + expect(privateManager.eventQueue).toHaveLength(1); + + vi.useRealTimers(); + }); + + it("should handle timeout for slow processing", async () => { + vi.useFakeTimers(); + + const slowHandler = vi.fn().mockImplementation( + () => + new Promise((resolve) => + setTimeout(() => { + console.log("Slow handler resolving"); + resolve(true); + }, 1000), + ), + ); + + selectionChangeManager.registerListener( + "slowHandler", + slowHandler, + HandlerPriority.HIGH, + ); + + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + // Start processing and advance past timeout + console.log("Starting event processing"); + const eventPromise = + selectionChangeManager.handleSelectionChange(mockEvent); + + console.log("Advancing timers by 600ms"); + vi.advanceTimersByTime(700); // PROCESSING_TIMEOUT is 500ms + + try { + await eventPromise; + console.log("Event promise resolved successfully"); + } catch (error) { + console.log("Event promise rejected:", error); + } + + console.log("Console error calls:", consoleErrorSpy.mock.calls); + expect(consoleErrorSpy).toHaveBeenCalled(); + + consoleErrorSpy.mockRestore(); + vi.useRealTimers(); + }); + + it("should handle errors in handlers gracefully", async () => { + const errorHandler = vi + .fn() + .mockRejectedValue(new Error("Handler error")); + const goodHandler = vi.fn().mockResolvedValue(true); + + selectionChangeManager.registerListener( + "errorHandler", + errorHandler, + HandlerPriority.HIGH, + ); + selectionChangeManager.registerListener( + "goodHandler", + goodHandler, + HandlerPriority.NORMAL, + ); + + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + await selectionChangeManager.handleSelectionChange(mockEvent); + + expect(errorHandler).toHaveBeenCalled(); + expect(goodHandler).toHaveBeenCalled(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Error in selection change handler:", + expect.any(Error), + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("captureState", () => { + beforeEach(() => { + vi.resetAllMocks(); + + // Explicitly set up the mocks. For some reason the toplevel mock leaves these as undefined. + vi.mocked(NextEditWindowManager.isInstantiated).mockReturnValue(false); + vi.mocked(NextEditWindowManager.getInstance).mockReturnValue({ + hasAccepted: vi.fn().mockReturnValue(false), + } as any); + + vi.mocked(JumpManager.getInstance).mockReturnValue({ + isJumpInProgress: vi.fn().mockReturnValue(false), + wasJumpJustAccepted: vi.fn().mockReturnValue(false), + } as any); + }); + + it("should capture current state snapshot", () => { + const mockEvent: vscode.TextEditorSelectionChangeEvent = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + // Setup some state + selectionChangeManager.documentChanged(); + + const privateManager = selectionChangeManager as any; + const state = privateManager.captureState(mockEvent); + + expect(state).toEqual({ + nextEditWindowAccepted: false, + jumpInProgress: false, + jumpJustAccepted: false, + lastDocumentChangeTime: expect.any(Number), + isTypingSession: true, + document: mockEvent.textEditor.document, + cursorPosition: mockEvent.selections[0].active, + }); + }); + + it("should reflect NextEditWindowManager acceptance state", () => { + vi.mocked(NextEditWindowManager.isInstantiated).mockReturnValue(true); + vi.mocked(NextEditWindowManager.getInstance).mockReturnValue({ + hasAccepted: vi.fn().mockReturnValue(true), + } as any); + + const mockEvent: vscode.TextEditorSelectionChangeEvent = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + const privateManager = selectionChangeManager as any; + const state = privateManager.captureState(mockEvent); + + expect(state.nextEditWindowAccepted).toBe(true); + }); + + it("should reflect JumpManager state", () => { + vi.mocked(JumpManager.getInstance).mockReturnValue({ + isJumpInProgress: vi.fn().mockReturnValue(true), + wasJumpJustAccepted: vi.fn().mockReturnValue(true), + } as any); + + const mockEvent: vscode.TextEditorSelectionChangeEvent = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + const privateManager = selectionChangeManager as any; + const state = privateManager.captureState(mockEvent); + + expect(state.jumpInProgress).toBe(true); + expect(state.jumpJustAccepted).toBe(true); + }); + }); + + describe("defaultFallbackHandler", () => { + it("should call deleteChain on NextEditProvider", async () => { + const mockEvent: vscode.TextEditorSelectionChangeEvent = { + textEditor: { + ...vscode.window.activeTextEditor!, + document: { + //@ts-ignore + uri: { + toString: vi.fn().mockReturnValue("file:///test/file.ts"), + }, + }, + }, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + const mockState = { + nextEditWindowAccepted: false, + jumpInProgress: false, + jumpJustAccepted: false, + lastDocumentChangeTime: Date.now(), + isTypingSession: false, + document: mockEvent.textEditor.document, + cursorPosition: mockEvent.selections[0].active, + }; + + const privateManager = selectionChangeManager as any; + const result = await privateManager.defaultFallbackHandler( + mockEvent, + mockState, + ); + + expect(mockDeleteChain).toHaveBeenCalled(); + expect(result).toBe(true); + }); + + it("should handle missing IDE gracefully", async () => { + const mockEvent: vscode.TextEditorSelectionChangeEvent = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + const mockState = { + nextEditWindowAccepted: false, + jumpInProgress: false, + jumpJustAccepted: false, + lastDocumentChangeTime: Date.now(), + isTypingSession: false, + document: mockEvent.textEditor.document, + cursorPosition: mockEvent.selections[0].active, + }; + + const privateManager = selectionChangeManager as any; + privateManager.ide = null; + + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const result = await privateManager.defaultFallbackHandler( + mockEvent, + mockState, + ); + + expect(consoleErrorSpy).toHaveBeenCalledWith( + "IDE not initialized in SelectionChangeManager", + ); + expect(result).toBe(false); + + consoleErrorSpy.mockRestore(); + }); + + it("should prefetch editable regions when not using full file diff", async () => { + // Initialize with usingFullFileDiff = false + const newManager = SelectionChangeManager.getInstance(); + newManager.initialize(mockIde, false); + + const mockEvent: vscode.TextEditorSelectionChangeEvent = { + textEditor: { + ...vscode.window.activeTextEditor!, + document: { + //@ts-ignore + uri: { + toString: vi.fn().mockReturnValue("file:///test/file.ts"), + }, + }, + }, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + const mockState = { + nextEditWindowAccepted: false, + jumpInProgress: false, + jumpJustAccepted: false, + lastDocumentChangeTime: Date.now(), + isTypingSession: false, + document: mockEvent.textEditor.document, + cursorPosition: mockEvent.selections[0].active, + }; + + const mockRegions = [ + { + filepath: "/test/file.ts", + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + // content: "test content", + // cursorPosition: { line: 2, character: 5 }, + }, + ]; + + vi.mocked(getNextEditableRegion).mockResolvedValue(mockRegions); + + const privateManager = newManager as any; + await privateManager.defaultFallbackHandler(mockEvent, mockState); + + expect(getNextEditableRegion).toHaveBeenCalledWith( + EditableRegionStrategy.Static, + { + cursorPosition: mockEvent.selections[0].anchor, + filepath: "/test/file.ts", + ide: mockIde, + }, + ); + + expect(mockEnqueueUnprocessed).toHaveBeenCalledWith(mockRegions[0]); + }); + + it("should skip prefetching when using full file diff", async () => { + // Initialize with usingFullFileDiff = true + const newManager = SelectionChangeManager.getInstance(); + newManager.initialize(mockIde, true); + + const mockEvent: vscode.TextEditorSelectionChangeEvent = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + const mockState = { + nextEditWindowAccepted: false, + jumpInProgress: false, + jumpJustAccepted: false, + lastDocumentChangeTime: Date.now(), + isTypingSession: false, + document: mockEvent.textEditor.document, + cursorPosition: mockEvent.selections[0].active, + }; + + const privateManager = newManager as any; + await privateManager.defaultFallbackHandler(mockEvent, mockState); + + expect(getNextEditableRegion).not.toHaveBeenCalled(); + expect(mockEnqueueUnprocessed).not.toHaveBeenCalled(); + }); + }); + + describe("handler execution order", () => { + it("should execute handlers in priority order and stop on first true return", async () => { + const handler1 = vi.fn().mockResolvedValue(false); + const handler2 = vi.fn().mockResolvedValue(true); + const handler3 = vi.fn().mockResolvedValue(false); + const fallbackHandler = vi.fn().mockResolvedValue(true); + + selectionChangeManager.registerListener( + "handler1", + handler1, + HandlerPriority.CRITICAL, + ); + selectionChangeManager.registerListener( + "handler2", + handler2, + HandlerPriority.HIGH, + ); + selectionChangeManager.registerListener( + "handler3", + handler3, + HandlerPriority.NORMAL, + ); + + const mockEvent: vscode.TextEditorSelectionChangeEvent = { + textEditor: vscode.window.activeTextEditor!, + selections: [ + new vscode.Selection( + new vscode.Position(2, 5), + new vscode.Position(2, 5), + ), + ], + kind: undefined, + }; + + await selectionChangeManager.handleSelectionChange(mockEvent); + + expect(handler1).toHaveBeenCalled(); + expect(handler2).toHaveBeenCalled(); + expect(handler3).not.toHaveBeenCalled(); // Should not be called because handler2 returned true + expect(mockDeleteChain).not.toHaveBeenCalled(); // Fallback should not run + }); + }); +});