diff --git a/core/index.d.ts b/core/index.d.ts index f31b62ed7..7086a98e5 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1510,6 +1510,7 @@ export interface RangeInFileWithNextEditInfo { filepath: string; range: Range; fileContents: string; + fileContentsBefore: string; editText: string; afterCursorPos: Position; beforeCursorPos: Position; diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 6f96cd3b8..f92804a6c 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -21,6 +21,7 @@ import { AutocompleteInput } from "../autocomplete/util/types.js"; import { isSecurityConcern } from "../indexing/ignore.js"; import { modelSupportsNextEdit } from "../llm/autodetect.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; +import { EditAggregator } from "./context/aggregateEdits.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; @@ -399,13 +400,28 @@ export class NextEditProvider { opts?.usingFullFileDiff ?? false, ); + // Build diffContext including in-progress edits + // The finalized diffs are in this.diffContext, but we also need to include + // any in-progress edits that haven't been finalized yet (the user's most recent typing) + const combinedDiffContext = [...this.diffContext]; + try { + const inProgressDiff = EditAggregator.getInstance().getInProgressDiff( + helper.filepath, + ); + if (inProgressDiff) { + combinedDiffContext.push(inProgressDiff); + } + } catch (e) { + // EditAggregator may not be initialized yet, ignore + } + // Build context for model-specific prompt generation. const context: ModelSpecificContext = { helper, snippetPayload, editableRegionStartLine, editableRegionEndLine, - diffContext: this.diffContext, + diffContext: combinedDiffContext, autocompleteContext: this.autocompleteContext, historyDiff: createDiff({ beforeContent: diff --git a/core/nextEdit/context/aggregateEdits.ts b/core/nextEdit/context/aggregateEdits.ts index b4a9bbd9e..e8df57960 100644 --- a/core/nextEdit/context/aggregateEdits.ts +++ b/core/nextEdit/context/aggregateEdits.ts @@ -124,7 +124,7 @@ export class EditAggregator { if (!this.fileStates.has(filePath)) { this.fileStates.set(filePath, { activeClusters: [], - currentContent: edit.fileContents, + currentContent: edit.fileContents, // Post-edit content (will be updated correctly by _processEditInternal) priorComparisons: [], processingQueue: [], isProcessing: false, @@ -218,8 +218,12 @@ export class EditAggregator { // initialize a cluster if (!suitableCluster) { + // Use fileContentsBefore if available (tracked by VS Code extension), + // otherwise fall back to current content + const beforeState = edit.fileContentsBefore ?? fileState.currentContent; + suitableCluster = { - beforeState: fileState.currentContent, + beforeState, startRange: { minLine: Math.max(0, editLine - this.config.contextLines), maxLine: Math.min( @@ -573,4 +577,52 @@ export class EditAggregator { this.fileStates.clear(); this.lastProcessedFilePath = null; } + + /** + * Gets the in-progress diff for a file by comparing the earliest active cluster's + * beforeState with the current file content. + * This captures edits that haven't been finalized yet. + * + * @param filePath The file path to get the in-progress diff for + * @returns The unified diff string if there are active clusters, or null otherwise + */ + getInProgressDiff(filePath: string): string | null { + const fileState = this.fileStates.get(filePath); + if (!fileState || fileState.activeClusters.length === 0) { + return null; + } + + // Get the earliest active cluster (first edit that started this batch of typing) + const earliestCluster = fileState.activeClusters.reduce( + (earliest, cluster) => + cluster.firstTimestamp < earliest.firstTimestamp ? cluster : earliest, + ); + + const beforeContent = earliestCluster.beforeState; + const afterContent = fileState.currentContent; + + // Skip if the content is the same + if (beforeContent === afterContent) { + return null; + } + + // Skip whitespace-only diffs + if ( + beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, "") + ) { + return null; + } + + // Get workspaceDir from the first edit in the cluster (for consistent path formatting) + const workspaceDir = earliestCluster.edits[0]?.workspaceDir; + + return createDiff({ + beforeContent, + afterContent, + filePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + workspaceDir, + }); + } } diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 22f1aaad8..962c4ec01 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -58,7 +58,11 @@ import { } from "../activation/SelectionChangeManager"; import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker"; import { getDefinitionsFromLsp } from "../autocomplete/lsp"; -import { handleTextDocumentChange } from "../util/editLoggingUtils"; +import { + clearDocumentContentCache, + handleTextDocumentChange, + initDocumentContentCache, +} from "../util/editLoggingUtils"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; export class VsCodeExtension { @@ -476,6 +480,16 @@ export class VsCodeExtension { }); } + // Initialize document content cache for tracking pre-edit content + vscode.workspace.onDidOpenTextDocument((document) => { + initDocumentContentCache(document); + }); + + // Initialize cache for all currently open documents + for (const document of vscode.workspace.textDocuments) { + initDocumentContentCache(document); + } + vscode.workspace.onDidChangeTextDocument(async (event) => { if (event.contentChanges.length > 0) { selectionManager.documentChanged(); @@ -505,6 +519,7 @@ export class VsCodeExtension { }); vscode.workspace.onDidCloseTextDocument(async (event) => { + clearDocumentContentCache(event.uri.toString()); this.core.invoke("files/closed", { uris: [event.uri.toString()], }); diff --git a/extensions/vscode/src/util/editLoggingUtils.ts b/extensions/vscode/src/util/editLoggingUtils.ts index 467ab4f0f..7938ca391 100644 --- a/extensions/vscode/src/util/editLoggingUtils.ts +++ b/extensions/vscode/src/util/editLoggingUtils.ts @@ -6,6 +6,51 @@ import { RecentlyEditedRange } from "core/nextEdit/types"; import * as vscode from "vscode"; import { ContinueCompletionProvider } from "../autocomplete/completionProvider"; +// Cache to store the last known content for each file (before edits) +const documentContentCache = new Map(); + +/** + * Gets the cached content for a document, or reads the current content if not cached. + * This should be called BEFORE processing the edit to get the pre-edit state. + */ +export const getPreEditContent = (document: vscode.TextDocument): string => { + const uri = document.uri.toString(); + const cached = documentContentCache.get(uri); + if (cached !== undefined) { + return cached; + } + // If not cached, this is the first edit we're seeing - the document's current state + // in the event is already post-edit, so we can't get the true pre-edit content. + // Return empty string to indicate no prior content was tracked. + return ""; +}; + +/** + * Updates the cache with the current document content. + * This should be called AFTER processing the edit. + */ +export const updateDocumentContentCache = ( + document: vscode.TextDocument, +): void => { + documentContentCache.set(document.uri.toString(), document.getText()); +}; + +/** + * Initializes the cache for a document when it's opened. + */ +export const initDocumentContentCache = ( + document: vscode.TextDocument, +): void => { + documentContentCache.set(document.uri.toString(), document.getText()); +}; + +/** + * Removes a document from the cache when it's closed. + */ +export const clearDocumentContentCache = (uri: string): void => { + documentContentCache.delete(uri); +}; + export const getBeforeCursorPos = (range: Range, activePos: Position) => { // whichever side of the range isn't active is the before position if ( @@ -49,6 +94,9 @@ export const handleTextDocumentChange = async ( const workspaceDirUri = await getWorkspaceDirUri(event); if (!workspaceDirUri) return; + // Get the pre-edit content from our cache BEFORE updating it + const fileContentsBefore = getPreEditContent(event.document); + const activeCursorPos = editor.selection.active; const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({ filepath: event.document.uri.toString(), @@ -57,12 +105,16 @@ export const handleTextDocumentChange = async ( end: change.range.end as Position, }, fileContents: event.document.getText(), + fileContentsBefore, editText: change.text, beforeCursorPos: getBeforeCursorPos(change.range, activeCursorPos), afterCursorPos: activeCursorPos as Position, workspaceDir: workspaceDirUri, })); + // Update the cache with the new content AFTER capturing the edit + updateDocumentContentCache(event.document); + let recentlyEditedRanges: RecentlyEditedRange[] = []; let recentlyVisitedRanges: AutocompleteCodeSnippet[] = [];