From 7ec4bc25a06fce67e2f9e52482a6bf0e20c91a3b Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 17 Jun 2025 12:15:43 -0700 Subject: [PATCH 1/5] basic action chunking in place for edit diff logging --- core/core.ts | 30 + core/index.d.ts | 12 + core/nextEdit/context/aggregateEdits.ts | 611 ++++++++++++++++++ core/protocol/core.ts | 2 + .../src/autocomplete/completionProvider.ts | 4 +- .../vscode/src/extension/VsCodeExtension.ts | 24 +- 6 files changed, 680 insertions(+), 3 deletions(-) create mode 100644 core/nextEdit/context/aggregateEdits.ts diff --git a/core/core.ts b/core/core.ts index 4c79f18d1..558a681e4 100644 --- a/core/core.ts +++ b/core/core.ts @@ -21,6 +21,7 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { countTokens } from "./llm/countTokens"; import Ollama from "./llm/llms/Ollama"; +import { EditAggregator } from "./nextEdit/context/aggregateEdits"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; import { ChatDescriber } from "./util/chatDescriber"; @@ -684,6 +685,35 @@ export class Core { } }); + on("files/smallEdit", async ({ data }) => { + // console.log(JSON.stringify(data.actions)); + + const DEFAULT_EDIT_AGGREGATION_OPTIONS = { + delta_t: 1.0, + delta_l: 5, + max_edits: 50, + max_duration: 100.0, + context_size: 5, + max_edit_size: 1000, + }; + + // Create global EditAggregator + if (!global._editAggregator) { + global._editAggregator = new EditAggregator( + DEFAULT_EDIT_AGGREGATION_OPTIONS, + (filePath, beforeState, diff, contextDiffs) => { + // This callback is called when a diff is finalized + // console.log(`\nFinalized diff for ${filePath}:`); + // console.log(diff); + // console.log("\n"); + }, + ); + } + + // Process the incoming edits + global._editAggregator.processEdits(data.actions); + }); + // Docs, etc. indexing on("indexing/reindex", async (msg) => { if (msg.data.type === "docs") { diff --git a/core/index.d.ts b/core/index.d.ts index ce78a8d82..3bd354245 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -28,6 +28,8 @@ declare global { messageIde: string, ) => void; } + + var _editAggregator: EditAggregator | undefined; } export interface ChunkWithoutID { @@ -1297,6 +1299,16 @@ export interface RangeInFileWithContents { contents: string; } +export interface RangeInFileWithContentsAndEdit { + filepath: string; + range: { + start: { line: number; character: number }; + end: { line: number; character: number }; + }; + fileContents: string; + editText: string; +} + export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents; /** diff --git a/core/nextEdit/context/aggregateEdits.ts b/core/nextEdit/context/aggregateEdits.ts new file mode 100644 index 000000000..39ce70603 --- /dev/null +++ b/core/nextEdit/context/aggregateEdits.ts @@ -0,0 +1,611 @@ +import { RangeInFileWithContentsAndEdit } from "../.."; + +/** + * Represents the state of an edit cluster + */ +interface ClusterState { + before_state: string; // Full file content before the cluster started + start_range: { + min_line: number; + max_line: number; + }; + current_range: { + min_line: number; + max_line: number; + }; + edits: RangeInFileWithContentsAndEdit[]; + first_timestamp: number; + last_timestamp: number; + last_line: number; +} + +/** + * Represents the state of a file being edited + */ +interface FileState { + activeClusters: ClusterState[]; + currentContent: string; // Current full file content + priorComparisons: string[]; + processingQueue: Array<() => Promise>; + isProcessing: boolean; +} + +/** + * Configuration for the edit clustering process + */ +export interface EditClusterConfig { + /** Maximum time gap (seconds) between edits to consider them part of the same cluster (unless on the same line) */ + delta_t: number; + /** Maximum line distance between edits in a cluster */ + delta_l: number; + /** Maximum number of edits in a cluster before finalization */ + max_edits: number; + /** Maximum duration (seconds) a cluster can remain active */ + max_duration: number; + /** Number of prior comparisons to include as context */ + context_size: number; + /** Maximum size of a single edit to process (larger edits are discarded) */ + max_edit_size: number; + /** Number of unchanged lines to include as context */ + context_lines: number; + /** Whether to log detailed information to console */ + verbose: boolean; +} + +/** + * Class that aggregates granular file edits into logical edit sequences + * based on temporal, spatial, and line-based criteria. + */ +export class EditAggregator { + private fileStates: Map = new Map(); + private config: EditClusterConfig; + private onComparisonFinalized: ( + filePath: string, + beforeState: string[], + beforeAfterComparison: string, + contextComparisons: string[], + ) => void; + + /** + * Creates a new EditAggregator instance + * + * @param config Configuration options for edit clustering + * @param onComparisonFinalized Callback function when a comparison is finalized + */ + constructor( + config: Partial = {}, + onComparisonFinalized: ( + filePath: string, + beforeState: string[], + diff: string, + contextDiffs: string[], + ) => void = () => {}, + ) { + this.config = { + delta_t: config.delta_t ?? 1.0, + delta_l: config.delta_l ?? 5, + max_edits: config.max_edits ?? 50, + max_duration: config.max_duration ?? 10.0, + context_size: config.context_size ?? 5, + max_edit_size: config.max_edit_size ?? 1000, + context_lines: config.context_lines ?? 3, + verbose: config.verbose ?? false, + }; + this.onComparisonFinalized = onComparisonFinalized; + } + + /** + * Queues an edit to be processed asynchronously + * + * @param edit The edit to process + * @param timestamp Timestamp of the edit + */ + async processEdit( + edit: RangeInFileWithContentsAndEdit, + timestamp: number = Date.now(), + ): Promise { + const filePath = edit.filepath; + + // Initialize file state if needed + if (!this.fileStates.has(filePath)) { + this.fileStates.set(filePath, { + activeClusters: [], + currentContent: edit.fileContents, + priorComparisons: [], + processingQueue: [], + isProcessing: false, + }); + } + + const fileState = this.fileStates.get(filePath)!; + + // Create a task for processing this edit + const task = async () => { + await this._processEditInternal(edit, timestamp, fileState); + }; + + // Add task to queue + fileState.processingQueue.push(task); + + // Start processing if not already in progress + if (!fileState.isProcessing) { + void this._processQueue(filePath); + } + } + + /** + * Process the queue of edits for a file + */ + private async _processQueue(filePath: string): Promise { + const fileState = this.fileStates.get(filePath); + if (!fileState) return; + + fileState.isProcessing = true; + + while (fileState.processingQueue.length > 0) { + // Get the next task + const nextTask = fileState.processingQueue.shift(); + if (nextTask) { + try { + // Execute the task + await nextTask(); + } catch (error) { + console.error(`Error processing edit in ${filePath}:`, error); + } + + // Small delay to allow UI updates + await new Promise((resolve) => setTimeout(resolve, 0)); + } + } + + fileState.isProcessing = false; + } + + /** + * Internal method to process a single edit + */ + private async _processEditInternal( + edit: RangeInFileWithContentsAndEdit, + timestamp: number, + fileState: FileState, + ): Promise { + const filePath = edit.filepath; + const editSize = edit.editText.length; + + // Discard oversized edits + if (editSize > this.config.max_edit_size) { + if (this.config.verbose) { + console.log( + `Edit discarded: size ${editSize} exceeds max_edit_size ${this.config.max_edit_size}`, + ); + } + return; + } + + const editLine = edit.range.start.line; + const currentFileLines = fileState.currentContent.split("\n"); + + // First finalize any existing clusters that meet criteria + const clustersToFinalize = this.identifyClustersToFinalize( + fileState, + editLine, + timestamp, + false, + ); + + for (const cluster of clustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + + // Find or create suitable cluster for this edit + let suitableCluster = this.findSuitableCluster( + fileState, + editLine, + timestamp, + ); + + if (!suitableCluster) { + // Create a new cluster with the current file state + suitableCluster = { + before_state: fileState.currentContent, + start_range: { + min_line: Math.max(0, editLine - this.config.context_lines), + max_line: Math.min( + currentFileLines.length - 1, + editLine + this.config.context_lines, + ), + }, + current_range: { + min_line: Math.max(0, editLine - this.config.context_lines), + max_line: Math.min( + currentFileLines.length - 1, + editLine + this.config.context_lines, + ), + }, + edits: [], + first_timestamp: timestamp, + last_timestamp: timestamp, + last_line: editLine, + }; + fileState.activeClusters.push(suitableCluster); + } + + // Add edit to cluster and update cluster metadata + suitableCluster.edits.push(edit); + suitableCluster.last_timestamp = timestamp; + suitableCluster.last_line = editLine; + + // Check if this is a meaningful edit or just whitespace + const isWhitespaceOnly = this.isWhitespaceOnlyEdit( + edit, + fileState.currentContent, + ); + + // Only update the range for meaningful edits + if (!isWhitespaceOnly) { + // Update the current range to include this edit + suitableCluster.current_range.min_line = Math.min( + suitableCluster.current_range.min_line, + Math.max(0, editLine - this.config.context_lines), + ); + suitableCluster.current_range.max_line = Math.max( + suitableCluster.current_range.max_line, + Math.min( + currentFileLines.length - 1, + editLine + this.config.context_lines, + ), + ); + } + + // Update the current file content based on the edit + fileState.currentContent = edit.fileContents; + + // Check for structural edits that might affect other clusters + const isStructuralEdit = + edit.editText.includes("\n") || + edit.range.start.line !== edit.range.end.line; + + if (isStructuralEdit) { + // Find other clusters that might be affected by this structural edit + const additionalClustersToFinalize = fileState.activeClusters.filter( + (c) => + c !== suitableCluster && this.clustersOverlap(c, suitableCluster), + ); + + for (const cluster of additionalClustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + } + + if (this.config.verbose) { + console.log( + `Processed edit in ${filePath} at line ${editLine}: "${edit.editText.substring(0, 30)}${edit.editText.length > 30 ? "..." : ""}"`, + ); + } + } + + /** + * Check if an edit only changes whitespace + */ + private isWhitespaceOnlyEdit( + edit: RangeInFileWithContentsAndEdit, + currentContent: string, + ): boolean { + // Get the line before the edit + const lines = currentContent.split("\n"); + const line = edit.range.start.line; + + if (line >= lines.length) return false; + + // For edits within a single line + if (edit.range.start.line === edit.range.end.line) { + const beforeEdit = lines[line]; + + // Apply the edit to get the after state + const afterEdit = + beforeEdit.substring(0, edit.range.start.character) + + edit.editText + + beforeEdit.substring(edit.range.end.character); + + // Compare normalized versions + return beforeEdit.trim() === afterEdit.trim(); + } + + return false; // Multi-line edits are considered meaningful + } + + /** + * Check if two clusters overlap or are close enough to affect each other + */ + private clustersOverlap( + cluster1: ClusterState, + cluster2: ClusterState, + ): boolean { + const c1MinLine = cluster1.current_range.min_line; + const c1MaxLine = cluster1.current_range.max_line; + const c2MinLine = cluster2.current_range.min_line; + const c2MaxLine = cluster2.current_range.max_line; + + // Check if the ranges overlap or are within delta_l lines of each other + return ( + c1MinLine <= c2MaxLine + this.config.delta_l && + c1MaxLine >= c2MinLine - this.config.delta_l + ); + } + + /** + * Process multiple edits at once + * + * @param edits Array of edits to process + */ + async processEdits(edits: RangeInFileWithContentsAndEdit[]): Promise { + const timestamp = Date.now(); + if (this.config.verbose) { + console.log(`Queueing batch of ${edits.length} edits`); + } + + // Queue all edits to be processed + for (const edit of edits) { + await this.processEdit(edit, timestamp); + } + } + + /** + * Finalize all active clusters across all files + */ + async finalizeAllClusters(): Promise { + if (this.config.verbose) { + console.log("Finalizing all active clusters"); + } + + const filePromises: Promise[] = []; + + this.fileStates.forEach((fileState, filePath) => { + // Create a finalization task for each file + const filePromise = (async () => { + const clustersToFinalize = [...fileState.activeClusters]; + for (const cluster of clustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + })(); + + filePromises.push(filePromise); + }); + + // Wait for all files to be processed + await Promise.all(filePromises); + } + + /** + * Find a suitable cluster for a new edit based on temporal and spatial proximity + * + * @param fileState Current state of the file + * @param editLine Line number of the edit + * @param timestamp Timestamp of the edit + * @returns A suitable cluster or null if none found + */ + private findSuitableCluster( + fileState: FileState, + editLine: number, + timestamp: number, + ): ClusterState | null { + for (const cluster of fileState.activeClusters) { + // Edit is on the same line as the last edit in the cluster + const isOnSameLine = editLine === cluster.last_line; + + // Edit is within time window of the last edit in the cluster + const isWithinTimeWindow = + (timestamp - cluster.last_timestamp) / 1000 <= this.config.delta_t; + + // Edit is within line range of the cluster + const isWithinLineRange = + editLine >= cluster.current_range.min_line - this.config.delta_l && + editLine <= cluster.current_range.max_line + this.config.delta_l; + + // Cluster hasn't reached max edits + const isWithinEditLimit = cluster.edits.length < this.config.max_edits; + + // Cluster hasn't reached max duration + const isWithinDurationLimit = + (timestamp - cluster.first_timestamp) / 1000 <= + this.config.max_duration; + + if ( + (isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) && + isWithinEditLimit && + isWithinDurationLimit + ) { + return cluster; + } + } + return null; + } + + /** + * Identify clusters that should be finalized based on clustering rules + * + * @param fileState Current state of the file + * @param editLine Line number of the current edit + * @param timestamp Timestamp of the current edit + * @param isStructuralEdit Whether the edit changes line structure + * @returns Array of clusters to finalize + */ + private identifyClustersToFinalize( + fileState: FileState, + editLine: number, + timestamp: number, + isStructuralEdit: boolean, + ): ClusterState[] { + const clustersToFinalize: ClusterState[] = []; + + fileState.activeClusters.forEach((cluster) => { + const timeSinceLastEdit = (timestamp - cluster.last_timestamp) / 1000; + + // Important fix: Only consider the line changed if it's a DIFFERENT line + // This way, continuing to edit the same line won't finalize the cluster + const isOnDifferentLine = cluster.last_line !== editLine; + + // Only finalize if we moved to a different line AND the time gap exceeds delta_t + const shouldFinalizeByTime = + isOnDifferentLine && timeSinceLastEdit > this.config.delta_t; + + // Finalize if cluster reached max edits + const shouldFinalizeByCount = + cluster.edits.length >= this.config.max_edits; + + // Finalize if cluster reached max duration + const shouldFinalizeByDuration = + (timestamp - cluster.first_timestamp) / 1000 > this.config.max_duration; + + // Structural edits should only finalize other clusters, not their own + const shouldFinalizeByStructuralEdit = + isStructuralEdit && isOnDifferentLine; + + if ( + shouldFinalizeByTime || + shouldFinalizeByCount || + shouldFinalizeByDuration || + shouldFinalizeByStructuralEdit + ) { + clustersToFinalize.push(cluster); + } + }); + + return clustersToFinalize; + } + + /** + * Create a console-friendly side-by-side comparison of the edited region with context + */ + private async createConsoleComparison( + beforeContent: string, + afterContent: string, + filePath: string, + ): Promise { + return new Promise((resolve) => { + setTimeout(() => { + const beforeLines = beforeContent.split("\n"); + const afterLines = afterContent.split("\n"); + + // Find the first and last lines that differ + const maxLines = Math.max(beforeLines.length, afterLines.length); + let firstDiffLine = maxLines; + let lastDiffLine = 0; + + for (let i = 0; i < maxLines; i++) { + const beforeLine = i < beforeLines.length ? beforeLines[i] : ""; + const afterLine = i < afterLines.length ? afterLines[i] : ""; + + if (beforeLine !== afterLine) { + firstDiffLine = Math.min(firstDiffLine, i); + lastDiffLine = Math.max(lastDiffLine, i); + } + } + + // If no differences found, show a small section from the beginning + if (firstDiffLine > lastDiffLine) { + firstDiffLine = 0; + lastDiffLine = Math.min(5, maxLines - 1); + } + + // Add context lines (3 lines on either side) + const contextLines = 3; + const startLine = Math.max(0, firstDiffLine - contextLines); + const endLine = Math.min(maxLines - 1, lastDiffLine + contextLines); + + let result = `\n=== File: ${filePath} ===\n`; + result += `=== Diff view of lines ${startLine}-${endLine} ===\n\n`; + + // Calculate width for line numbers + const lineNumWidth = String(endLine).length; + + // Max width for content columns (adjust based on your terminal width) + const contentWidth = 60; + + // Table header + result += `${"LINE".padEnd(lineNumWidth + 2)} | ${"BEFORE".padEnd(contentWidth)} | ${"AFTER".padEnd(contentWidth)}\n`; + result += `${"-".repeat(lineNumWidth + 2)}-|-${"-".repeat(contentWidth)}-|-${"-".repeat(contentWidth)}\n`; + + // Generate the comparison for the specified range + for (let i = startLine; i <= endLine; i++) { + const beforeLine = i < beforeLines.length ? beforeLines[i] : ""; + const afterLine = i < afterLines.length ? afterLines[i] : ""; + + // Truncate long lines + const truncatedBeforeLine = + beforeLine.length > contentWidth - 3 + ? beforeLine.substring(0, contentWidth - 3) + "..." + : beforeLine; + + const truncatedAfterLine = + afterLine.length > contentWidth - 3 + ? afterLine.substring(0, contentWidth - 3) + "..." + : afterLine; + + // Mark changed lines with asterisk + const changed = beforeLine !== afterLine ? "* " : " "; + const lineNum = String(i).padStart(lineNumWidth); + + result += `${changed}${lineNum} | ${truncatedBeforeLine.padEnd(contentWidth)} | ${truncatedAfterLine.padEnd(contentWidth)}\n`; + } + + result += "\n"; + resolve(result); + }, 0); + }); + } + + /** + * Finalize a cluster, generating a comparison and removing it from active clusters + */ + private async finalizeCluster( + filePath: string, + cluster: ClusterState, + fileState: FileState, + ): Promise { + // Create a console-friendly comparison of the before and after states + const beforeContent = cluster.before_state; + const afterContent = fileState.currentContent; + + // Generate comparison asynchronously + const comparison = await this.createConsoleComparison( + beforeContent, + afterContent, + filePath, + ); + + // Add to prior comparisons and maintain context size limit + fileState.priorComparisons.push(comparison); + if (fileState.priorComparisons.length > this.config.context_size) { + fileState.priorComparisons.shift(); + } + + // Convert before state to array for callback + const beforeStateArray = cluster.before_state.split("\n"); + + // Log the finalized comparison + console.log("\n========== FINALIZED EDIT CLUSTER =========="); + console.log(`File: ${filePath}`); + console.log(`Number of edits: ${cluster.edits.length}`); + console.log(`First edit at line: ${cluster.edits[0]?.range.start.line}`); + console.log( + `Last edit at line: ${cluster.edits[cluster.edits.length - 1]?.range.start.line}`, + ); + console.log( + `Duration: ${((cluster.last_timestamp - cluster.first_timestamp) / 1000).toFixed(2)}s`, + ); + console.log(comparison); + console.log("===========================================\n"); + + // Call the finalization callback with the generated comparison and context + this.onComparisonFinalized(filePath, beforeStateArray, comparison, [ + ...fileState.priorComparisons, + ]); + + // Remove cluster from active clusters + const clusterIndex = fileState.activeClusters.indexOf(cluster); + if (clusterIndex !== -1) { + fileState.activeClusters.splice(clusterIndex, 1); + } + } +} diff --git a/core/protocol/core.ts b/core/protocol/core.ts index dfc0d87d6..885710138 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -25,6 +25,7 @@ import { ModelDescription, PromptLog, RangeInFile, + RangeInFileWithContentsAndEdit, SerializedContinueConfig, Session, SessionMetadata, @@ -182,6 +183,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "files/created": [{ uris?: string[] }, void]; "files/deleted": [{ uris?: string[] }, void]; "files/closed": [{ uris?: string[] }, void]; + "files/smallEdit": [{ actions: RangeInFileWithContentsAndEdit[] }, void]; // Docs etc. Indexing. TODO move codebase to this "indexing/reindex": [{ type: string; id: string }, void]; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 12eb8a881..d4ee9063e 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -303,11 +303,11 @@ export class ContinueCompletionProvider new vscode.Position(startPos.line, result.range.end), ); } - console.log("range", range.start, range.end); + // console.log("range", range.start, range.end); } else { // Extend the range to the end of the line for multiline completions range = new vscode.Range(startPos, document.lineAt(startPos).range.end); - console.log("range", range.start, range.end); + // console.log("range", range.start, range.end); } const completionItem = new vscode.InlineCompletionItem( diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 20bde355d..7a2a5fa48 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -1,6 +1,6 @@ import fs from "fs"; -import { IContextProvider } from "core"; +import { IContextProvider, RangeInFileWithContentsAndEdit } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { EXTENSION_NAME, getControlPlaneEnv } from "core/control-plane/env"; import { Core } from "core/core"; @@ -283,6 +283,28 @@ export class VsCodeExtension { this.configHandler.reloadConfig(); }); + vscode.workspace.onDidChangeTextDocument(async (event) => { + const changes = event.contentChanges; + + if (event.contentChanges.length === 0) { + return; + } + + let editActions: RangeInFileWithContentsAndEdit[] = changes.map( + (change) => ({ + filepath: event.document.uri.toString(), + range: { + start: change.range.start, + end: change.range.end, + }, + fileContents: event.document.getText(), + editText: change.text, + }), + ); + + this.core.invoke("files/smallEdit", { actions: editActions }); + }); + vscode.workspace.onDidSaveTextDocument(async (event) => { this.core.invoke("files/changed", { uris: [event.uri.toString()], From 3202b2d34d7b2bfb68059d1537139c503d70aefb Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 17 Jun 2025 15:43:37 -0700 Subject: [PATCH 2/5] improved edit logging behavior, working on optimizing performance now --- core/autocomplete/snippets/getAllSnippets.ts | 3 + core/core.ts | 33 +- core/nextEdit/context/aggregateEdits.ts | 545 ++++++++---------- .../context/aggregateEditsWorkingCopy.ts | 524 +++++++++++++++++ extensions/vscode/package-lock.json | 4 +- .../vscode/src/extension/VsCodeExtension.ts | 34 +- 6 files changed, 805 insertions(+), 338 deletions(-) create mode 100644 core/nextEdit/context/aggregateEditsWorkingCopy.ts diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index bb3a9dbc3..702356198 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -230,6 +230,7 @@ export const getAllSnippetsWithoutRace = async ({ ideSnippets, diffSnippets, clipboardSnippets, + recentlyOpenedFileSnippets, ] = await Promise.all([ contextRetrievalService.getRootPathSnippets(helper), contextRetrievalService.getSnippetsFromImportDefinitions(helper), @@ -238,6 +239,7 @@ export const getAllSnippetsWithoutRace = async ({ : [], [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, getClipboardSnippets(ide), + getSnippetsFromRecentlyOpenedFiles(helper, ide), ]); return { @@ -248,5 +250,6 @@ export const getAllSnippetsWithoutRace = async ({ diffSnippets, clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, + recentlyOpenedFileSnippets, }; }; diff --git a/core/core.ts b/core/core.ts index 558a681e4..48d69ae21 100644 --- a/core/core.ts +++ b/core/core.ts @@ -686,32 +686,29 @@ export class Core { }); on("files/smallEdit", async ({ data }) => { - // console.log(JSON.stringify(data.actions)); - - const DEFAULT_EDIT_AGGREGATION_OPTIONS = { - delta_t: 1.0, - delta_l: 5, - max_edits: 50, - max_duration: 100.0, - context_size: 5, - max_edit_size: 1000, + const EDIT_AGGREGATION_OPTIONS = { + deltaT: 1.0, + deltaL: 5, + maxEdits: 250, + maxDuration: 100.0, + contextSize: 5, + maxEditSize: 1000, }; - // Create global EditAggregator if (!global._editAggregator) { global._editAggregator = new EditAggregator( - DEFAULT_EDIT_AGGREGATION_OPTIONS, - (filePath, beforeState, diff, contextDiffs) => { - // This callback is called when a diff is finalized - // console.log(`\nFinalized diff for ${filePath}:`); - // console.log(diff); - // console.log("\n"); + EDIT_AGGREGATION_OPTIONS, + (diff: string) => { + // callback for when a diff is finalized + // TODO: add the diff to devData from here }, ); } - // Process the incoming edits - global._editAggregator.processEdits(data.actions); + // queueMicrotask prevents blocking the UI thread during typing + queueMicrotask(() => { + void global._editAggregator.processEdits(data.actions); + }); }); // Docs, etc. indexing diff --git a/core/nextEdit/context/aggregateEdits.ts b/core/nextEdit/context/aggregateEdits.ts index 39ce70603..c4d636cf3 100644 --- a/core/nextEdit/context/aggregateEdits.ts +++ b/core/nextEdit/context/aggregateEdits.ts @@ -1,112 +1,63 @@ +import { createPatch } from "diff"; import { RangeInFileWithContentsAndEdit } from "../.."; -/** - * Represents the state of an edit cluster - */ interface ClusterState { - before_state: string; // Full file content before the cluster started - start_range: { - min_line: number; - max_line: number; - }; - current_range: { - min_line: number; - max_line: number; - }; + beforeState: string; + startRange: { minLine: number; maxLine: number }; + currentRange: { minLine: number; maxLine: number }; edits: RangeInFileWithContentsAndEdit[]; - first_timestamp: number; - last_timestamp: number; - last_line: number; + firstTimestamp: number; + lastTimestamp: number; + lastLine: number; } -/** - * Represents the state of a file being edited - */ interface FileState { activeClusters: ClusterState[]; - currentContent: string; // Current full file content + currentContent: string; priorComparisons: string[]; processingQueue: Array<() => Promise>; isProcessing: boolean; } -/** - * Configuration for the edit clustering process - */ export interface EditClusterConfig { - /** Maximum time gap (seconds) between edits to consider them part of the same cluster (unless on the same line) */ - delta_t: number; - /** Maximum line distance between edits in a cluster */ - delta_l: number; - /** Maximum number of edits in a cluster before finalization */ - max_edits: number; - /** Maximum duration (seconds) a cluster can remain active */ - max_duration: number; - /** Number of prior comparisons to include as context */ - context_size: number; - /** Maximum size of a single edit to process (larger edits are discarded) */ - max_edit_size: number; - /** Number of unchanged lines to include as context */ - context_lines: number; - /** Whether to log detailed information to console */ + deltaT: number; + deltaL: number; + maxEdits: number; + maxDuration: number; + contextSize: number; + maxEditSize: number; + contextLines: number; verbose: boolean; } -/** - * Class that aggregates granular file edits into logical edit sequences - * based on temporal, spatial, and line-based criteria. - */ export class EditAggregator { private fileStates: Map = new Map(); private config: EditClusterConfig; - private onComparisonFinalized: ( - filePath: string, - beforeState: string[], - beforeAfterComparison: string, - contextComparisons: string[], - ) => void; + private onComparisonFinalized: (diff: string) => void; - /** - * Creates a new EditAggregator instance - * - * @param config Configuration options for edit clustering - * @param onComparisonFinalized Callback function when a comparison is finalized - */ constructor( config: Partial = {}, - onComparisonFinalized: ( - filePath: string, - beforeState: string[], - diff: string, - contextDiffs: string[], - ) => void = () => {}, + onComparisonFinalized: (diff: string) => void = () => {}, ) { this.config = { - delta_t: config.delta_t ?? 1.0, - delta_l: config.delta_l ?? 5, - max_edits: config.max_edits ?? 50, - max_duration: config.max_duration ?? 10.0, - context_size: config.context_size ?? 5, - max_edit_size: config.max_edit_size ?? 1000, - context_lines: config.context_lines ?? 3, + deltaT: config.deltaT ?? 1.0, + deltaL: config.deltaL ?? 5, + maxEdits: config.maxEdits ?? 500, + maxDuration: config.maxDuration ?? 10.0, + contextSize: config.contextSize ?? 5, + maxEditSize: config.maxEditSize ?? 1000, + contextLines: config.contextLines ?? 3, verbose: config.verbose ?? false, }; this.onComparisonFinalized = onComparisonFinalized; } - /** - * Queues an edit to be processed asynchronously - * - * @param edit The edit to process - * @param timestamp Timestamp of the edit - */ async processEdit( edit: RangeInFileWithContentsAndEdit, timestamp: number = Date.now(), ): Promise { const filePath = edit.filepath; - // Initialize file state if needed if (!this.fileStates.has(filePath)) { this.fileStates.set(filePath, { activeClusters: [], @@ -118,24 +69,17 @@ export class EditAggregator { } const fileState = this.fileStates.get(filePath)!; - - // Create a task for processing this edit const task = async () => { await this._processEditInternal(edit, timestamp, fileState); }; - // Add task to queue fileState.processingQueue.push(task); - // Start processing if not already in progress if (!fileState.isProcessing) { void this._processQueue(filePath); } } - /** - * Process the queue of edits for a file - */ private async _processQueue(filePath: string): Promise { const fileState = this.fileStates.get(filePath); if (!fileState) return; @@ -143,17 +87,13 @@ export class EditAggregator { fileState.isProcessing = true; while (fileState.processingQueue.length > 0) { - // Get the next task const nextTask = fileState.processingQueue.shift(); if (nextTask) { try { - // Execute the task await nextTask(); } catch (error) { console.error(`Error processing edit in ${filePath}:`, error); } - - // Small delay to allow UI updates await new Promise((resolve) => setTimeout(resolve, 0)); } } @@ -161,31 +101,29 @@ export class EditAggregator { fileState.isProcessing = false; } - /** - * Internal method to process a single edit - */ private async _processEditInternal( edit: RangeInFileWithContentsAndEdit, timestamp: number, fileState: FileState, ): Promise { const filePath = edit.filepath; + + // Correctly calculate the edit size const editSize = edit.editText.length; - // Discard oversized edits - if (editSize > this.config.max_edit_size) { - if (this.config.verbose) { - console.log( - `Edit discarded: size ${editSize} exceeds max_edit_size ${this.config.max_edit_size}`, - ); - } - return; + // Strictly enforce the max edit size limit + // TODO: This prevents large edits from being processes, but they still show up in the output diff + // since that is a comparison. We need to fix that in the diff generation (downstream) + if (editSize > this.config.maxEditSize) { + console.log( + `Large edit discarded: size ${editSize} characters exceeds max_edit_size ${this.config.maxEditSize}`, + ); + return; // Exit early without processing this edit } const editLine = edit.range.start.line; const currentFileLines = fileState.currentContent.split("\n"); - // First finalize any existing clusters that meet criteria const clustersToFinalize = this.identifyClustersToFinalize( fileState, editLine, @@ -197,7 +135,6 @@ export class EditAggregator { await this.finalizeCluster(filePath, cluster, fileState); } - // Find or create suitable cluster for this edit let suitableCluster = this.findSuitableCluster( fileState, editLine, @@ -205,68 +142,60 @@ export class EditAggregator { ); if (!suitableCluster) { - // Create a new cluster with the current file state suitableCluster = { - before_state: fileState.currentContent, - start_range: { - min_line: Math.max(0, editLine - this.config.context_lines), - max_line: Math.min( + beforeState: fileState.currentContent, + startRange: { + minLine: Math.max(0, editLine - this.config.contextLines), + maxLine: Math.min( currentFileLines.length - 1, - editLine + this.config.context_lines, + editLine + this.config.contextLines, ), }, - current_range: { - min_line: Math.max(0, editLine - this.config.context_lines), - max_line: Math.min( + currentRange: { + minLine: Math.max(0, editLine - this.config.contextLines), + maxLine: Math.min( currentFileLines.length - 1, - editLine + this.config.context_lines, + editLine + this.config.contextLines, ), }, edits: [], - first_timestamp: timestamp, - last_timestamp: timestamp, - last_line: editLine, + firstTimestamp: timestamp, + lastTimestamp: timestamp, + lastLine: editLine, }; fileState.activeClusters.push(suitableCluster); } - // Add edit to cluster and update cluster metadata suitableCluster.edits.push(edit); - suitableCluster.last_timestamp = timestamp; - suitableCluster.last_line = editLine; + suitableCluster.lastTimestamp = timestamp; + suitableCluster.lastLine = editLine; - // Check if this is a meaningful edit or just whitespace const isWhitespaceOnly = this.isWhitespaceOnlyEdit( edit, fileState.currentContent, ); - // Only update the range for meaningful edits if (!isWhitespaceOnly) { - // Update the current range to include this edit - suitableCluster.current_range.min_line = Math.min( - suitableCluster.current_range.min_line, - Math.max(0, editLine - this.config.context_lines), + suitableCluster.currentRange.minLine = Math.min( + suitableCluster.currentRange.minLine, + Math.max(0, editLine - this.config.contextLines), ); - suitableCluster.current_range.max_line = Math.max( - suitableCluster.current_range.max_line, + suitableCluster.currentRange.maxLine = Math.max( + suitableCluster.currentRange.maxLine, Math.min( currentFileLines.length - 1, - editLine + this.config.context_lines, + editLine + this.config.contextLines, ), ); } - // Update the current file content based on the edit fileState.currentContent = edit.fileContents; - // Check for structural edits that might affect other clusters const isStructuralEdit = edit.editText.includes("\n") || edit.range.start.line !== edit.range.end.line; if (isStructuralEdit) { - // Find other clusters that might be affected by this structural edit const additionalClustersToFinalize = fileState.activeClusters.filter( (c) => c !== suitableCluster && this.clustersOverlap(c, suitableCluster), @@ -284,75 +213,51 @@ export class EditAggregator { } } - /** - * Check if an edit only changes whitespace - */ private isWhitespaceOnlyEdit( edit: RangeInFileWithContentsAndEdit, currentContent: string, ): boolean { - // Get the line before the edit const lines = currentContent.split("\n"); const line = edit.range.start.line; if (line >= lines.length) return false; - // For edits within a single line if (edit.range.start.line === edit.range.end.line) { const beforeEdit = lines[line]; - - // Apply the edit to get the after state const afterEdit = beforeEdit.substring(0, edit.range.start.character) + edit.editText + beforeEdit.substring(edit.range.end.character); - // Compare normalized versions return beforeEdit.trim() === afterEdit.trim(); } - return false; // Multi-line edits are considered meaningful + return false; } - /** - * Check if two clusters overlap or are close enough to affect each other - */ private clustersOverlap( cluster1: ClusterState, cluster2: ClusterState, ): boolean { - const c1MinLine = cluster1.current_range.min_line; - const c1MaxLine = cluster1.current_range.max_line; - const c2MinLine = cluster2.current_range.min_line; - const c2MaxLine = cluster2.current_range.max_line; - - // Check if the ranges overlap or are within delta_l lines of each other return ( - c1MinLine <= c2MaxLine + this.config.delta_l && - c1MaxLine >= c2MinLine - this.config.delta_l + cluster1.currentRange.minLine <= + cluster2.currentRange.maxLine + this.config.deltaL && + cluster1.currentRange.maxLine >= + cluster2.currentRange.minLine - this.config.deltaL ); } - /** - * Process multiple edits at once - * - * @param edits Array of edits to process - */ async processEdits(edits: RangeInFileWithContentsAndEdit[]): Promise { const timestamp = Date.now(); if (this.config.verbose) { console.log(`Queueing batch of ${edits.length} edits`); } - // Queue all edits to be processed for (const edit of edits) { await this.processEdit(edit, timestamp); } } - /** - * Finalize all active clusters across all files - */ async finalizeAllClusters(): Promise { if (this.config.verbose) { console.log("Finalizing all active clusters"); @@ -361,7 +266,6 @@ export class EditAggregator { const filePromises: Promise[] = []; this.fileStates.forEach((fileState, filePath) => { - // Create a finalization task for each file const filePromise = (async () => { const clustersToFinalize = [...fileState.activeClusters]; for (const cluster of clustersToFinalize) { @@ -372,43 +276,48 @@ export class EditAggregator { filePromises.push(filePromise); }); - // Wait for all files to be processed await Promise.all(filePromises); } - /** - * Find a suitable cluster for a new edit based on temporal and spatial proximity - * - * @param fileState Current state of the file - * @param editLine Line number of the edit - * @param timestamp Timestamp of the edit - * @returns A suitable cluster or null if none found - */ private findSuitableCluster( fileState: FileState, editLine: number, timestamp: number, ): ClusterState | null { - for (const cluster of fileState.activeClusters) { - // Edit is on the same line as the last edit in the cluster - const isOnSameLine = editLine === cluster.last_line; + // First check if we need to finalize any clusters due to line jumps + const activeClusters = [...fileState.activeClusters]; + + for (const cluster of activeClusters) { + // If we're outside the line range but within the time window, + // we should finalize the current cluster + const isOutsideLineRange = + editLine < cluster.currentRange.minLine - this.config.deltaL || + editLine > cluster.currentRange.maxLine + this.config.deltaL; - // Edit is within time window of the last edit in the cluster const isWithinTimeWindow = - (timestamp - cluster.last_timestamp) / 1000 <= this.config.delta_t; + (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT; - // Edit is within line range of the cluster + // If user quickly jumped far away, finalize this cluster before continuing + if (isOutsideLineRange && isWithinTimeWindow) { + void this.finalizeCluster( + cluster.edits[0].filepath, + cluster, + fileState, + ); + } + } + + // Now look for a suitable cluster for the new edit + for (const cluster of fileState.activeClusters) { + const isOnSameLine = editLine === cluster.lastLine; + const isWithinTimeWindow = + (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT; const isWithinLineRange = - editLine >= cluster.current_range.min_line - this.config.delta_l && - editLine <= cluster.current_range.max_line + this.config.delta_l; - - // Cluster hasn't reached max edits - const isWithinEditLimit = cluster.edits.length < this.config.max_edits; - - // Cluster hasn't reached max duration + editLine >= cluster.currentRange.minLine - this.config.deltaL && + editLine <= cluster.currentRange.maxLine + this.config.deltaL; + const isWithinEditLimit = cluster.edits.length < this.config.maxEdits; const isWithinDurationLimit = - (timestamp - cluster.first_timestamp) / 1000 <= - this.config.max_duration; + (timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration; if ( (isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) && @@ -421,15 +330,6 @@ export class EditAggregator { return null; } - /** - * Identify clusters that should be finalized based on clustering rules - * - * @param fileState Current state of the file - * @param editLine Line number of the current edit - * @param timestamp Timestamp of the current edit - * @param isStructuralEdit Whether the edit changes line structure - * @returns Array of clusters to finalize - */ private identifyClustersToFinalize( fileState: FileState, editLine: number, @@ -439,23 +339,21 @@ export class EditAggregator { const clustersToFinalize: ClusterState[] = []; fileState.activeClusters.forEach((cluster) => { - const timeSinceLastEdit = (timestamp - cluster.last_timestamp) / 1000; + const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000; // Important fix: Only consider the line changed if it's a DIFFERENT line // This way, continuing to edit the same line won't finalize the cluster - const isOnDifferentLine = cluster.last_line !== editLine; + const isOnDifferentLine = cluster.lastLine !== editLine; - // Only finalize if we moved to a different line AND the time gap exceeds delta_t + // Only finalize if we moved to a different line AND the time gap exceeds deltaT const shouldFinalizeByTime = - isOnDifferentLine && timeSinceLastEdit > this.config.delta_t; + isOnDifferentLine && timeSinceLastEdit > this.config.deltaT; - // Finalize if cluster reached max edits const shouldFinalizeByCount = - cluster.edits.length >= this.config.max_edits; + cluster.edits.length >= this.config.maxEdits; - // Finalize if cluster reached max duration const shouldFinalizeByDuration = - (timestamp - cluster.first_timestamp) / 1000 > this.config.max_duration; + (timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration; // Structural edits should only finalize other clusters, not their own const shouldFinalizeByStructuralEdit = @@ -468,144 +366,179 @@ export class EditAggregator { shouldFinalizeByStructuralEdit ) { clustersToFinalize.push(cluster); + + if (this.config.verbose || true) { + const reasons = []; + if (shouldFinalizeByTime) + reasons.push( + `time gap (${timeSinceLastEdit.toFixed(2)}s > ${this.config.deltaT}s)`, + ); + if (shouldFinalizeByCount) + reasons.push( + `edit count (${cluster.edits.length} >= ${this.config.maxEdits})`, + ); + if (shouldFinalizeByDuration) + reasons.push( + `duration (${((timestamp - cluster.firstTimestamp) / 1000).toFixed(2)}s > ${this.config.maxDuration}s)`, + ); + if (shouldFinalizeByStructuralEdit) + reasons.push("structural edit on different line"); + console.log( + // `Finalizing cluster in ${cluster.edits[0].filepath} due to: ${reasons.join(", ")}`, + `Finalizing cluster due to: ${reasons.join(", ")}`, + ); + } } }); return clustersToFinalize; } - /** - * Create a console-friendly side-by-side comparison of the edited region with context - */ - private async createConsoleComparison( + private createStandardDiff( beforeContent: string, afterContent: string, filePath: string, - ): Promise { - return new Promise((resolve) => { - setTimeout(() => { - const beforeLines = beforeContent.split("\n"); - const afterLines = afterContent.split("\n"); + ): string { + // Ensure both strings end with a newline + const normalizedBefore = beforeContent.endsWith("\n") + ? beforeContent + : beforeContent + "\n"; + const normalizedAfter = afterContent.endsWith("\n") + ? afterContent + : afterContent + "\n"; - // Find the first and last lines that differ - const maxLines = Math.max(beforeLines.length, afterLines.length); - let firstDiffLine = maxLines; - let lastDiffLine = 0; + // Create standard unified diff + const patch = createPatch( + filePath, + normalizedBefore, + normalizedAfter, + "before", + "after", + { context: 3 }, + ); - for (let i = 0; i < maxLines; i++) { - const beforeLine = i < beforeLines.length ? beforeLines[i] : ""; - const afterLine = i < afterLines.length ? afterLines[i] : ""; - - if (beforeLine !== afterLine) { - firstDiffLine = Math.min(firstDiffLine, i); - lastDiffLine = Math.max(lastDiffLine, i); - } - } - - // If no differences found, show a small section from the beginning - if (firstDiffLine > lastDiffLine) { - firstDiffLine = 0; - lastDiffLine = Math.min(5, maxLines - 1); - } - - // Add context lines (3 lines on either side) - const contextLines = 3; - const startLine = Math.max(0, firstDiffLine - contextLines); - const endLine = Math.min(maxLines - 1, lastDiffLine + contextLines); - - let result = `\n=== File: ${filePath} ===\n`; - result += `=== Diff view of lines ${startLine}-${endLine} ===\n\n`; - - // Calculate width for line numbers - const lineNumWidth = String(endLine).length; - - // Max width for content columns (adjust based on your terminal width) - const contentWidth = 60; - - // Table header - result += `${"LINE".padEnd(lineNumWidth + 2)} | ${"BEFORE".padEnd(contentWidth)} | ${"AFTER".padEnd(contentWidth)}\n`; - result += `${"-".repeat(lineNumWidth + 2)}-|-${"-".repeat(contentWidth)}-|-${"-".repeat(contentWidth)}\n`; - - // Generate the comparison for the specified range - for (let i = startLine; i <= endLine; i++) { - const beforeLine = i < beforeLines.length ? beforeLines[i] : ""; - const afterLine = i < afterLines.length ? afterLines[i] : ""; - - // Truncate long lines - const truncatedBeforeLine = - beforeLine.length > contentWidth - 3 - ? beforeLine.substring(0, contentWidth - 3) + "..." - : beforeLine; - - const truncatedAfterLine = - afterLine.length > contentWidth - 3 - ? afterLine.substring(0, contentWidth - 3) + "..." - : afterLine; - - // Mark changed lines with asterisk - const changed = beforeLine !== afterLine ? "* " : " "; - const lineNum = String(i).padStart(lineNumWidth); - - result += `${changed}${lineNum} | ${truncatedBeforeLine.padEnd(contentWidth)} | ${truncatedAfterLine.padEnd(contentWidth)}\n`; - } - - result += "\n"; - resolve(result); - }, 0); - }); + return patch; } - /** - * Finalize a cluster, generating a comparison and removing it from active clusters - */ private async finalizeCluster( filePath: string, cluster: ClusterState, fileState: FileState, ): Promise { - // Create a console-friendly comparison of the before and after states - const beforeContent = cluster.before_state; + const beforeContent = cluster.beforeState; const afterContent = fileState.currentContent; - // Generate comparison asynchronously - const comparison = await this.createConsoleComparison( - beforeContent, - afterContent, - filePath, - ); + // Check if this diff is whitespace-only by comparing trimmed content + const isWhitespaceOnlyDiff = + beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, ""); - // Add to prior comparisons and maintain context size limit - fileState.priorComparisons.push(comparison); - if (fileState.priorComparisons.length > this.config.context_size) { + // Skip whitespace-only diffs + if (isWhitespaceOnlyDiff) { + if (this.config.verbose) { + console.log(`Skipping W H I T E S P A C E -only diff in ${filePath}`); + } + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + return; + } + + // Use standard diff + const diff = this.createStandardDiff(beforeContent, afterContent, filePath); + + // Count changed lines in the diff + const changedLineCount = this.countChangedLines(diff); + + // Skip diffs with too many changed lines + if (changedLineCount > this.config.deltaL * 2) { + if (this.config.verbose) { + console.log( + `Skipping diff with ${changedLineCount} changed lines (> ${this.config.deltaL}) in ${filePath}`, + ); + } + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + return; + } + + fileState.priorComparisons.push(diff); + if (fileState.priorComparisons.length > this.config.contextSize) { fileState.priorComparisons.shift(); } - // Convert before state to array for callback - const beforeStateArray = cluster.before_state.split("\n"); - - // Log the finalized comparison console.log("\n========== FINALIZED EDIT CLUSTER =========="); - console.log(`File: ${filePath}`); - console.log(`Number of edits: ${cluster.edits.length}`); - console.log(`First edit at line: ${cluster.edits[0]?.range.start.line}`); - console.log( - `Last edit at line: ${cluster.edits[cluster.edits.length - 1]?.range.start.line}`, - ); - console.log( - `Duration: ${((cluster.last_timestamp - cluster.first_timestamp) / 1000).toFixed(2)}s`, - ); - console.log(comparison); + // console.log(`File: ${filePath}`); + // console.log(`Number of edits: ${cluster.edits.length}`); + // console.log(`First edit at line: ${cluster.edits[0]?.range.start.line}`); + // console.log( + // `Last edit at line: ${cluster.edits[cluster.edits.length - 1]?.range.start.line}`, + // ); + // console.log( + // `Duration: ${(cluster.lastTimestamp - cluster.firstTimestamp) / 1000}s`, + // ); + console.log(diff); console.log("===========================================\n"); - // Call the finalization callback with the generated comparison and context - this.onComparisonFinalized(filePath, beforeStateArray, comparison, [ - ...fileState.priorComparisons, - ]); + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); - // Remove cluster from active clusters - const clusterIndex = fileState.activeClusters.indexOf(cluster); - if (clusterIndex !== -1) { - fileState.activeClusters.splice(clusterIndex, 1); + // Call the callback with just the diff + this.onComparisonFinalized(diff); + } + + private countChangedLines(diff: string): number { + let count = 0; + let addedLines = new Set(); + let removedLines = new Set(); + + // Parse the diff lines + const lines = diff.split("\n"); + for (const line of lines) { + if ( + line.startsWith("+++ ") || + line.startsWith("--- ") || + line.startsWith("@@") + ) { + continue; // Skip header lines + } + + if (line.startsWith("+")) { + // Extract line number if possible (depends on diff format) + addedLines.add(count); + count++; + } else if (line.startsWith("-")) { + // Extract line number if possible + removedLines.add(count); + count++; + } } + + // Count replacements as one line (lines that were both added and removed) + const replacementCount = Math.min(addedLines.size, removedLines.size); + + // Total changed lines is the max of added and removed lines + return Math.max(addedLines.size, removedLines.size); + } + + getActiveClusterCount(): number { + let count = 0; + this.fileStates.forEach((fileState) => { + count += fileState.activeClusters.length; + }); + return count; + } + + getProcessingQueueSize(): number { + let count = 0; + this.fileStates.forEach((fileState) => { + count += fileState.processingQueue.length; + }); + return count; + } + + resetState(): void { + this.fileStates.clear(); } } diff --git a/core/nextEdit/context/aggregateEditsWorkingCopy.ts b/core/nextEdit/context/aggregateEditsWorkingCopy.ts new file mode 100644 index 000000000..df26c806d --- /dev/null +++ b/core/nextEdit/context/aggregateEditsWorkingCopy.ts @@ -0,0 +1,524 @@ +import { RangeInFileWithContentsAndEdit } from "../.."; + +interface ClusterState { + beforeState: string; + startRange: { minLine: number; maxLine: number }; + currentRange: { minLine: number; maxLine: number }; + edits: RangeInFileWithContentsAndEdit[]; + firstTimestamp: number; + lastTimestamp: number; + lastLine: number; +} + +interface FileState { + activeClusters: ClusterState[]; + currentContent: string; + priorComparisons: string[]; + processingQueue: Array<() => Promise>; + isProcessing: boolean; +} + +export interface EditClusterConfig { + deltaT: number; + deltaL: number; + maxEdits: number; + maxDuration: number; + contextSize: number; + maxEditSize: number; + contextLines: number; + verbose: boolean; +} + +export class EditAggregator { + private fileStates: Map = new Map(); + private config: EditClusterConfig; + private onComparisonFinalized: ( + filePath: string, + beforeState: string[], + beforeAfterComparison: string, + contextComparisons: string[], + ) => void; + + constructor( + config: Partial = {}, + onComparisonFinalized: ( + filePath: string, + beforeState: string[], + diff: string, + contextDiffs: string[], + ) => void = () => {}, + ) { + this.config = { + deltaT: config.deltaT ?? 1.0, + deltaL: config.deltaL ?? 5, + maxEdits: config.maxEdits ?? 200, + maxDuration: config.maxDuration ?? 20.0, + contextSize: config.contextSize ?? 5, + maxEditSize: config.maxEditSize ?? 1000, + contextLines: config.contextLines ?? 3, + verbose: config.verbose ?? false, + }; + this.onComparisonFinalized = onComparisonFinalized; + } + + async processEdit( + edit: RangeInFileWithContentsAndEdit, + timestamp: number = Date.now(), + ): Promise { + const filePath = edit.filepath; + + if (!this.fileStates.has(filePath)) { + this.fileStates.set(filePath, { + activeClusters: [], + currentContent: edit.fileContents, + priorComparisons: [], + processingQueue: [], + isProcessing: false, + }); + } + + const fileState = this.fileStates.get(filePath)!; + const task = async () => { + await this._processEditInternal(edit, timestamp, fileState); + }; + + fileState.processingQueue.push(task); + + if (!fileState.isProcessing) { + void this._processQueue(filePath); + } + } + + private async _processQueue(filePath: string): Promise { + const fileState = this.fileStates.get(filePath); + if (!fileState) return; + + fileState.isProcessing = true; + + while (fileState.processingQueue.length > 0) { + const nextTask = fileState.processingQueue.shift(); + if (nextTask) { + try { + await nextTask(); + } catch (error) { + console.error(`Error processing edit in ${filePath}:`, error); + } + await new Promise((resolve) => setTimeout(resolve, 0)); + } + } + + fileState.isProcessing = false; + } + + private async _processEditInternal( + edit: RangeInFileWithContentsAndEdit, + timestamp: number, + fileState: FileState, + ): Promise { + const filePath = edit.filepath; + + if (edit.editText.length > this.config.maxEditSize) { + if (this.config.verbose) { + console.log( + `Edit discarded: size ${edit.editText.length} exceeds max_edit_size ${this.config.maxEditSize}`, + ); + } + return; + } + + const editLine = edit.range.start.line; + const currentFileLines = fileState.currentContent.split("\n"); + + const clustersToFinalize = this.identifyClustersToFinalize( + fileState, + editLine, + timestamp, + false, + ); + + for (const cluster of clustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + + let suitableCluster = this.findSuitableCluster( + fileState, + editLine, + timestamp, + ); + + if (!suitableCluster) { + suitableCluster = { + beforeState: fileState.currentContent, + startRange: { + minLine: Math.max(0, editLine - this.config.contextLines), + maxLine: Math.min( + currentFileLines.length - 1, + editLine + this.config.contextLines, + ), + }, + currentRange: { + minLine: Math.max(0, editLine - this.config.contextLines), + maxLine: Math.min( + currentFileLines.length - 1, + editLine + this.config.contextLines, + ), + }, + edits: [], + firstTimestamp: timestamp, + lastTimestamp: timestamp, + lastLine: editLine, + }; + fileState.activeClusters.push(suitableCluster); + } + + suitableCluster.edits.push(edit); + suitableCluster.lastTimestamp = timestamp; + suitableCluster.lastLine = editLine; + + const isWhitespaceOnly = this.isWhitespaceOnlyEdit( + edit, + fileState.currentContent, + ); + + if (!isWhitespaceOnly) { + suitableCluster.currentRange.minLine = Math.min( + suitableCluster.currentRange.minLine, + Math.max(0, editLine - this.config.contextLines), + ); + suitableCluster.currentRange.maxLine = Math.max( + suitableCluster.currentRange.maxLine, + Math.min( + currentFileLines.length - 1, + editLine + this.config.contextLines, + ), + ); + } + + fileState.currentContent = edit.fileContents; + + const isStructuralEdit = + edit.editText.includes("\n") || + edit.range.start.line !== edit.range.end.line; + + if (isStructuralEdit) { + const additionalClustersToFinalize = fileState.activeClusters.filter( + (c) => + c !== suitableCluster && this.clustersOverlap(c, suitableCluster), + ); + + for (const cluster of additionalClustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + } + + if (this.config.verbose) { + console.log( + `Processed edit in ${filePath} at line ${editLine}: "${edit.editText.substring(0, 30)}${edit.editText.length > 30 ? "..." : ""}"`, + ); + } + } + + private isWhitespaceOnlyEdit( + edit: RangeInFileWithContentsAndEdit, + currentContent: string, + ): boolean { + const lines = currentContent.split("\n"); + const line = edit.range.start.line; + + if (line >= lines.length) return false; + + if (edit.range.start.line === edit.range.end.line) { + const beforeEdit = lines[line]; + const afterEdit = + beforeEdit.substring(0, edit.range.start.character) + + edit.editText + + beforeEdit.substring(edit.range.end.character); + + return beforeEdit.trim() === afterEdit.trim(); + } + + return false; + } + + private clustersOverlap( + cluster1: ClusterState, + cluster2: ClusterState, + ): boolean { + return ( + cluster1.currentRange.minLine <= + cluster2.currentRange.maxLine + this.config.deltaL && + cluster1.currentRange.maxLine >= + cluster2.currentRange.minLine - this.config.deltaL + ); + } + + async processEdits(edits: RangeInFileWithContentsAndEdit[]): Promise { + const timestamp = Date.now(); + if (this.config.verbose) { + console.log(`Queueing batch of ${edits.length} edits`); + } + + for (const edit of edits) { + await this.processEdit(edit, timestamp); + } + } + + async finalizeAllClusters(): Promise { + if (this.config.verbose) { + console.log("Finalizing all active clusters"); + } + + const filePromises: Promise[] = []; + + this.fileStates.forEach((fileState, filePath) => { + const filePromise = (async () => { + const clustersToFinalize = [...fileState.activeClusters]; + for (const cluster of clustersToFinalize) { + await this.finalizeCluster(filePath, cluster, fileState); + } + })(); + + filePromises.push(filePromise); + }); + + await Promise.all(filePromises); + } + + private findSuitableCluster( + fileState: FileState, + editLine: number, + timestamp: number, + ): ClusterState | null { + // First check if we need to finalize any clusters due to line jumps + const activeClusters = [...fileState.activeClusters]; + + for (const cluster of activeClusters) { + // If we're outside the line range but within the time window, + // we should finalize the current cluster + const isOutsideLineRange = + editLine < cluster.currentRange.minLine - this.config.deltaL || + editLine > cluster.currentRange.maxLine + this.config.deltaL; + + const isWithinTimeWindow = + (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT; + + // If user quickly jumped far away, finalize this cluster before continuing + if (isOutsideLineRange && isWithinTimeWindow) { + void this.finalizeCluster( + cluster.edits[0].filepath, + cluster, + fileState, + ); + } + } + + // Now look for a suitable cluster for the new edit + for (const cluster of fileState.activeClusters) { + const isOnSameLine = editLine === cluster.lastLine; + const isWithinTimeWindow = + (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT; + const isWithinLineRange = + editLine >= cluster.currentRange.minLine - this.config.deltaL && + editLine <= cluster.currentRange.maxLine + this.config.deltaL; + const isWithinEditLimit = cluster.edits.length < this.config.maxEdits; + const isWithinDurationLimit = + (timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration; + + if ( + (isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) && + isWithinEditLimit && + isWithinDurationLimit + ) { + return cluster; + } + } + return null; + } + + private identifyClustersToFinalize( + fileState: FileState, + editLine: number, + timestamp: number, + isStructuralEdit: boolean, + ): ClusterState[] { + const clustersToFinalize: ClusterState[] = []; + + fileState.activeClusters.forEach((cluster) => { + const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000; + + // Important fix: Only consider the line changed if it's a DIFFERENT line + // This way, continuing to edit the same line won't finalize the cluster + const isOnDifferentLine = cluster.lastLine !== editLine; + + // Only finalize if we moved to a different line AND the time gap exceeds deltaT + const shouldFinalizeByTime = + isOnDifferentLine && timeSinceLastEdit > this.config.deltaT; + + const shouldFinalizeByCount = + cluster.edits.length >= this.config.maxEdits; + + const shouldFinalizeByDuration = + (timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration; + + // Structural edits should only finalize other clusters, not their own + const shouldFinalizeByStructuralEdit = + isStructuralEdit && isOnDifferentLine; + + if ( + shouldFinalizeByTime || + shouldFinalizeByCount || + shouldFinalizeByDuration || + shouldFinalizeByStructuralEdit + ) { + clustersToFinalize.push(cluster); + + if (this.config.verbose || true) { + const reasons = []; + if (shouldFinalizeByTime) + reasons.push( + `time gap (${timeSinceLastEdit.toFixed(2)}s > ${this.config.deltaT}s)`, + ); + if (shouldFinalizeByCount) + reasons.push( + `edit count (${cluster.edits.length} >= ${this.config.maxEdits})`, + ); + if (shouldFinalizeByDuration) + reasons.push( + `duration (${((timestamp - cluster.firstTimestamp) / 1000).toFixed(2)}s > ${this.config.maxDuration}s)`, + ); + if (shouldFinalizeByStructuralEdit) + reasons.push("structural edit on different line"); + console.log( + `Finalizing cluster in ${cluster.edits[0].filepath} due to: ${reasons.join(", ")}`, + ); + } + } + }); + + return clustersToFinalize; + } + + private async createConsoleComparison( + beforeContent: string, + afterContent: string, + filePath: string, + ): Promise { + return new Promise((resolve) => { + setTimeout(() => { + const beforeLines = beforeContent.split("\n"); + const afterLines = afterContent.split("\n"); + const maxLines = Math.max(beforeLines.length, afterLines.length); + let firstDiffLine = maxLines; + let lastDiffLine = 0; + + for (let i = 0; i < maxLines; i++) { + const beforeLine = i < beforeLines.length ? beforeLines[i] : ""; + const afterLine = i < afterLines.length ? afterLines[i] : ""; + + if (beforeLine !== afterLine) { + firstDiffLine = Math.min(firstDiffLine, i); + lastDiffLine = Math.max(lastDiffLine, i); + } + } + + if (firstDiffLine > lastDiffLine) { + firstDiffLine = 0; + lastDiffLine = Math.min(5, maxLines - 1); + } + + const contextLines = 3; + const startLine = Math.max(0, firstDiffLine - contextLines); + const endLine = Math.min(maxLines - 1, lastDiffLine + contextLines); + const lineNumWidth = String(endLine).length; + const contentWidth = 60; + + let result = `\n=== File: ${filePath} ===\n`; + result += `=== Diff view of lines ${startLine}-${endLine} ===\n\n`; + result += `${"LINE".padEnd(lineNumWidth + 2)} | ${"BEFORE".padEnd(contentWidth)} | ${"AFTER".padEnd(contentWidth)}\n`; + result += `${"-".repeat(lineNumWidth + 2)}-|-${"-".repeat(contentWidth)}-|-${"-".repeat(contentWidth)}\n`; + + for (let i = startLine; i <= endLine; i++) { + const beforeLine = i < beforeLines.length ? beforeLines[i] : ""; + const afterLine = i < afterLines.length ? afterLines[i] : ""; + const truncatedBeforeLine = + beforeLine.length > contentWidth - 3 + ? beforeLine.substring(0, contentWidth - 3) + "..." + : beforeLine; + const truncatedAfterLine = + afterLine.length > contentWidth - 3 + ? afterLine.substring(0, contentWidth - 3) + "..." + : afterLine; + const changed = beforeLine === afterLine ? " " : "* "; + const lineNum = String(i).padStart(lineNumWidth); + + result += `${changed}${lineNum} | ${truncatedBeforeLine.padEnd(contentWidth)} | ${truncatedAfterLine.padEnd(contentWidth)}\n`; + } + + result += "\n"; + resolve(result); + }, 0); + }); + } + + private async finalizeCluster( + filePath: string, + cluster: ClusterState, + fileState: FileState, + ): Promise { + const beforeContent = cluster.beforeState; + const afterContent = fileState.currentContent; + const comparison = await this.createConsoleComparison( + beforeContent, + afterContent, + filePath, + ); + + fileState.priorComparisons.push(comparison); + if (fileState.priorComparisons.length > this.config.contextSize) { + fileState.priorComparisons.shift(); + } + + const beforeStateArray = cluster.beforeState.split("\n"); + + console.log("\n========== FINALIZED EDIT CLUSTER =========="); + console.log(`File: ${filePath}`); + console.log(`Number of edits: ${cluster.edits.length}`); + console.log(`First edit at line: ${cluster.edits[0]?.range.start.line}`); + console.log( + `Last edit at line: ${cluster.edits[cluster.edits.length - 1]?.range.start.line}`, + ); + console.log( + `Duration: ${(cluster.lastTimestamp - cluster.firstTimestamp) / 1000}s`, + ); + console.log(comparison); + console.log("===========================================\n"); + + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + + this.onComparisonFinalized(filePath, beforeStateArray, comparison, [ + ...fileState.priorComparisons, + ]); + } + + getActiveClusterCount(): number { + let count = 0; + this.fileStates.forEach((fileState) => { + count += fileState.activeClusters.length; + }); + return count; + } + + getProcessingQueueSize(): number { + let count = 0; + this.fileStates.forEach((fileState) => { + count += fileState.processingQueue.length; + }); + return count; + } + + resetState(): void { + this.fileStates.clear(); + } +} diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index c6d421c03..033c2391e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.47", + "version": "1.1.48", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.47", + "version": "1.1.48", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 7a2a5fa48..e6cb61eed 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -290,19 +290,29 @@ export class VsCodeExtension { return; } - let editActions: RangeInFileWithContentsAndEdit[] = changes.map( - (change) => ({ - filepath: event.document.uri.toString(), - range: { - start: change.range.start, - end: change.range.end, - }, - fileContents: event.document.getText(), - editText: change.text, - }), - ); + // OPTIMIZATION: Debounce rapid keystrokes + // This prevents sending too many edit events during fast typing + if (this._editDebounceTimer) { + clearTimeout(this._editDebounceTimer); + } - this.core.invoke("files/smallEdit", { actions: editActions }); + this._editDebounceTimer = setTimeout(() => { + const editActions: RangeInFileWithContentsAndEdit[] = changes.map( + (change) => ({ + filepath: event.document.uri.toString(), + range: { + start: change.range.start, + end: change.range.end, + }, + // OPTIMIZATION: Only get document text once + fileContents: event.document.getText(), + editText: change.text, + }), + ); + + // Use invoke without awaiting to prevent blocking + this.core.invoke("files/smallEdit", { actions: editActions }); + }, 10); // Small delay to batch rapid edits }); vscode.workspace.onDidSaveTextDocument(async (event) => { From 2630d89a79b683b339932c3a22590d896b567349 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 17 Jun 2025 16:00:53 -0700 Subject: [PATCH 3/5] completed some performance optimizations that make edit logging less laggy --- core/core.ts | 2 +- core/nextEdit/context/aggregateEdits.ts | 50 ++++++++----------- .../vscode/src/extension/VsCodeExtension.ts | 1 + 3 files changed, 22 insertions(+), 31 deletions(-) diff --git a/core/core.ts b/core/core.ts index 48d69ae21..aa2bc4226 100644 --- a/core/core.ts +++ b/core/core.ts @@ -687,7 +687,7 @@ export class Core { on("files/smallEdit", async ({ data }) => { const EDIT_AGGREGATION_OPTIONS = { - deltaT: 1.0, + deltaT: 0.75, deltaL: 5, maxEdits: 250, maxDuration: 100.0, diff --git a/core/nextEdit/context/aggregateEdits.ts b/core/nextEdit/context/aggregateEdits.ts index c4d636cf3..227453baf 100644 --- a/core/nextEdit/context/aggregateEdits.ts +++ b/core/nextEdit/context/aggregateEdits.ts @@ -86,14 +86,17 @@ export class EditAggregator { fileState.isProcessing = true; + // Process chunks of (5) edits instead of one at a time while (fileState.processingQueue.length > 0) { - const nextTask = fileState.processingQueue.shift(); - if (nextTask) { + const tasks = fileState.processingQueue.splice(0, 5); + if (tasks.length > 0) { try { - await nextTask(); + await Promise.all(tasks.map((task) => task())); } catch (error) { - console.error(`Error processing edit in ${filePath}:`, error); + console.error(`Error processing edits in ${filePath}:`, error); } + + // Yield to the event loop to prevent blocking await new Promise((resolve) => setTimeout(resolve, 0)); } } @@ -108,12 +111,7 @@ export class EditAggregator { ): Promise { const filePath = edit.filepath; - // Correctly calculate the edit size const editSize = edit.editText.length; - - // Strictly enforce the max edit size limit - // TODO: This prevents large edits from being processes, but they still show up in the output diff - // since that is a comparison. We need to fix that in the diff generation (downstream) if (editSize > this.config.maxEditSize) { console.log( `Large edit discarded: size ${editSize} characters exceeds max_edit_size ${this.config.maxEditSize}`, @@ -249,6 +247,16 @@ export class EditAggregator { async processEdits(edits: RangeInFileWithContentsAndEdit[]): Promise { const timestamp = Date.now(); + + // Skip processing during rapid typing + if (this.getProcessingQueueSize() > 15) { + // Only process the last edit + if (edits.length > 0) { + await this.processEdit(edits[edits.length - 1], timestamp); + } + return; + } + if (this.config.verbose) { console.log(`Queueing batch of ${edits.length} edits`); } @@ -284,7 +292,6 @@ export class EditAggregator { editLine: number, timestamp: number, ): ClusterState | null { - // First check if we need to finalize any clusters due to line jumps const activeClusters = [...fileState.activeClusters]; for (const cluster of activeClusters) { @@ -342,7 +349,6 @@ export class EditAggregator { const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000; // Important fix: Only consider the line changed if it's a DIFFERENT line - // This way, continuing to edit the same line won't finalize the cluster const isOnDifferentLine = cluster.lastLine !== editLine; // Only finalize if we moved to a different line AND the time gap exceeds deltaT @@ -383,10 +389,7 @@ export class EditAggregator { ); if (shouldFinalizeByStructuralEdit) reasons.push("structural edit on different line"); - console.log( - // `Finalizing cluster in ${cluster.edits[0].filepath} due to: ${reasons.join(", ")}`, - `Finalizing cluster due to: ${reasons.join(", ")}`, - ); + console.log(`Finalizing cluster due to: ${reasons.join(", ")}`); } } }); @@ -399,7 +402,6 @@ export class EditAggregator { afterContent: string, filePath: string, ): string { - // Ensure both strings end with a newline const normalizedBefore = beforeContent.endsWith("\n") ? beforeContent : beforeContent + "\n"; @@ -407,7 +409,6 @@ export class EditAggregator { ? afterContent : afterContent + "\n"; - // Create standard unified diff const patch = createPatch( filePath, normalizedBefore, @@ -428,11 +429,10 @@ export class EditAggregator { const beforeContent = cluster.beforeState; const afterContent = fileState.currentContent; - // Check if this diff is whitespace-only by comparing trimmed content + // Skip whitespace-only diffs const isWhitespaceOnlyDiff = beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, ""); - // Skip whitespace-only diffs if (isWhitespaceOnlyDiff) { if (this.config.verbose) { console.log(`Skipping W H I T E S P A C E -only diff in ${filePath}`); @@ -443,13 +443,10 @@ export class EditAggregator { return; } - // Use standard diff const diff = this.createStandardDiff(beforeContent, afterContent, filePath); - // Count changed lines in the diff - const changedLineCount = this.countChangedLines(diff); - // Skip diffs with too many changed lines + const changedLineCount = this.countChangedLines(diff); if (changedLineCount > this.config.deltaL * 2) { if (this.config.verbose) { console.log( @@ -484,7 +481,6 @@ export class EditAggregator { (c) => c !== cluster, ); - // Call the callback with just the diff this.onComparisonFinalized(diff); } @@ -505,20 +501,14 @@ export class EditAggregator { } if (line.startsWith("+")) { - // Extract line number if possible (depends on diff format) addedLines.add(count); count++; } else if (line.startsWith("-")) { - // Extract line number if possible removedLines.add(count); count++; } } - // Count replacements as one line (lines that were both added and removed) - const replacementCount = Math.min(addedLines.size, removedLines.size); - - // Total changed lines is the max of added and removed lines return Math.max(addedLines.size, removedLines.size); } diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index e6cb61eed..1292e44bb 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -62,6 +62,7 @@ export class VsCodeExtension { private workOsAuthProvider: WorkOsAuthProvider; private fileSearch: FileSearch; private uriHandler = new UriEventHandler(); + private _editDebounceTimer: NodeJS.Timeout | null = null; constructor(context: vscode.ExtensionContext) { // Register auth provider From 3d851d1fa324dfec9b981835fb88c7f87bbbacb5 Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 17 Jun 2025 16:20:02 -0700 Subject: [PATCH 4/5] cleanup in prep for devData logging --- core/core.ts | 6 +-- core/nextEdit/context/aggregateEdits.ts | 66 ++----------------------- 2 files changed, 7 insertions(+), 65 deletions(-) diff --git a/core/core.ts b/core/core.ts index aa2bc4226..26c460fc8 100644 --- a/core/core.ts +++ b/core/core.ts @@ -687,7 +687,7 @@ export class Core { on("files/smallEdit", async ({ data }) => { const EDIT_AGGREGATION_OPTIONS = { - deltaT: 0.75, + deltaT: 1.0, deltaL: 5, maxEdits: 250, maxDuration: 100.0, @@ -699,8 +699,8 @@ export class Core { global._editAggregator = new EditAggregator( EDIT_AGGREGATION_OPTIONS, (diff: string) => { - // callback for when a diff is finalized - // TODO: add the diff to devData from here + console.log(diff, "\n"); + // TODO handle devData logging here }, ); } diff --git a/core/nextEdit/context/aggregateEdits.ts b/core/nextEdit/context/aggregateEdits.ts index 227453baf..c2111a3e7 100644 --- a/core/nextEdit/context/aggregateEdits.ts +++ b/core/nextEdit/context/aggregateEdits.ts @@ -113,10 +113,7 @@ export class EditAggregator { const editSize = edit.editText.length; if (editSize > this.config.maxEditSize) { - console.log( - `Large edit discarded: size ${editSize} characters exceeds max_edit_size ${this.config.maxEditSize}`, - ); - return; // Exit early without processing this edit + return; } const editLine = edit.range.start.line; @@ -203,12 +200,6 @@ export class EditAggregator { await this.finalizeCluster(filePath, cluster, fileState); } } - - if (this.config.verbose) { - console.log( - `Processed edit in ${filePath} at line ${editLine}: "${edit.editText.substring(0, 30)}${edit.editText.length > 30 ? "..." : ""}"`, - ); - } } private isWhitespaceOnlyEdit( @@ -248,29 +239,20 @@ export class EditAggregator { async processEdits(edits: RangeInFileWithContentsAndEdit[]): Promise { const timestamp = Date.now(); - // Skip processing during rapid typing + // Only process the last edit during rapid typing if (this.getProcessingQueueSize() > 15) { - // Only process the last edit if (edits.length > 0) { await this.processEdit(edits[edits.length - 1], timestamp); } return; } - if (this.config.verbose) { - console.log(`Queueing batch of ${edits.length} edits`); - } - for (const edit of edits) { await this.processEdit(edit, timestamp); } } async finalizeAllClusters(): Promise { - if (this.config.verbose) { - console.log("Finalizing all active clusters"); - } - const filePromises: Promise[] = []; this.fileStates.forEach((fileState, filePath) => { @@ -348,10 +330,10 @@ export class EditAggregator { fileState.activeClusters.forEach((cluster) => { const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000; - // Important fix: Only consider the line changed if it's a DIFFERENT line + // Only consider the line changed if it's a DIFFERENT line const isOnDifferentLine = cluster.lastLine !== editLine; - // Only finalize if we moved to a different line AND the time gap exceeds deltaT + // Finalize if we moved to a different line AND the time gap exceeds deltaT const shouldFinalizeByTime = isOnDifferentLine && timeSinceLastEdit > this.config.deltaT; @@ -372,25 +354,6 @@ export class EditAggregator { shouldFinalizeByStructuralEdit ) { clustersToFinalize.push(cluster); - - if (this.config.verbose || true) { - const reasons = []; - if (shouldFinalizeByTime) - reasons.push( - `time gap (${timeSinceLastEdit.toFixed(2)}s > ${this.config.deltaT}s)`, - ); - if (shouldFinalizeByCount) - reasons.push( - `edit count (${cluster.edits.length} >= ${this.config.maxEdits})`, - ); - if (shouldFinalizeByDuration) - reasons.push( - `duration (${((timestamp - cluster.firstTimestamp) / 1000).toFixed(2)}s > ${this.config.maxDuration}s)`, - ); - if (shouldFinalizeByStructuralEdit) - reasons.push("structural edit on different line"); - console.log(`Finalizing cluster due to: ${reasons.join(", ")}`); - } } }); @@ -434,9 +397,6 @@ export class EditAggregator { beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, ""); if (isWhitespaceOnlyDiff) { - if (this.config.verbose) { - console.log(`Skipping W H I T E S P A C E -only diff in ${filePath}`); - } fileState.activeClusters = fileState.activeClusters.filter( (c) => c !== cluster, ); @@ -448,11 +408,6 @@ export class EditAggregator { // Skip diffs with too many changed lines const changedLineCount = this.countChangedLines(diff); if (changedLineCount > this.config.deltaL * 2) { - if (this.config.verbose) { - console.log( - `Skipping diff with ${changedLineCount} changed lines (> ${this.config.deltaL}) in ${filePath}`, - ); - } fileState.activeClusters = fileState.activeClusters.filter( (c) => c !== cluster, ); @@ -464,19 +419,6 @@ export class EditAggregator { fileState.priorComparisons.shift(); } - console.log("\n========== FINALIZED EDIT CLUSTER =========="); - // console.log(`File: ${filePath}`); - // console.log(`Number of edits: ${cluster.edits.length}`); - // console.log(`First edit at line: ${cluster.edits[0]?.range.start.line}`); - // console.log( - // `Last edit at line: ${cluster.edits[cluster.edits.length - 1]?.range.start.line}`, - // ); - // console.log( - // `Duration: ${(cluster.lastTimestamp - cluster.firstTimestamp) / 1000}s`, - // ); - console.log(diff); - console.log("===========================================\n"); - fileState.activeClusters = fileState.activeClusters.filter( (c) => c !== cluster, ); From b0a5c783efc99e7bddb98220ef2c77ba01ea89cb Mon Sep 17 00:00:00 2001 From: adarshramiyer Date: Tue, 17 Jun 2025 17:07:52 -0700 Subject: [PATCH 5/5] created diff formatting utils for later --- core/nextEdit/context/aggregateEdits.ts | 33 +- .../context/aggregateEditsWorkingCopy.ts | 524 ------------------ core/nextEdit/context/diffFormatting.ts | 65 +++ 3 files changed, 72 insertions(+), 550 deletions(-) delete mode 100644 core/nextEdit/context/aggregateEditsWorkingCopy.ts create mode 100644 core/nextEdit/context/diffFormatting.ts diff --git a/core/nextEdit/context/aggregateEdits.ts b/core/nextEdit/context/aggregateEdits.ts index c2111a3e7..4db65569a 100644 --- a/core/nextEdit/context/aggregateEdits.ts +++ b/core/nextEdit/context/aggregateEdits.ts @@ -1,5 +1,5 @@ -import { createPatch } from "diff"; import { RangeInFileWithContentsAndEdit } from "../.."; +import { DiffFormatType, createDiff } from "./diffFormatting"; interface ClusterState { beforeState: string; @@ -360,30 +360,6 @@ export class EditAggregator { return clustersToFinalize; } - private createStandardDiff( - beforeContent: string, - afterContent: string, - filePath: string, - ): string { - const normalizedBefore = beforeContent.endsWith("\n") - ? beforeContent - : beforeContent + "\n"; - const normalizedAfter = afterContent.endsWith("\n") - ? afterContent - : afterContent + "\n"; - - const patch = createPatch( - filePath, - normalizedBefore, - normalizedAfter, - "before", - "after", - { context: 3 }, - ); - - return patch; - } - private async finalizeCluster( filePath: string, cluster: ClusterState, @@ -403,7 +379,12 @@ export class EditAggregator { return; } - const diff = this.createStandardDiff(beforeContent, afterContent, filePath); + const diff = createDiff( + beforeContent, + afterContent, + filePath, + DiffFormatType.Unified, + ); // Skip diffs with too many changed lines const changedLineCount = this.countChangedLines(diff); diff --git a/core/nextEdit/context/aggregateEditsWorkingCopy.ts b/core/nextEdit/context/aggregateEditsWorkingCopy.ts deleted file mode 100644 index df26c806d..000000000 --- a/core/nextEdit/context/aggregateEditsWorkingCopy.ts +++ /dev/null @@ -1,524 +0,0 @@ -import { RangeInFileWithContentsAndEdit } from "../.."; - -interface ClusterState { - beforeState: string; - startRange: { minLine: number; maxLine: number }; - currentRange: { minLine: number; maxLine: number }; - edits: RangeInFileWithContentsAndEdit[]; - firstTimestamp: number; - lastTimestamp: number; - lastLine: number; -} - -interface FileState { - activeClusters: ClusterState[]; - currentContent: string; - priorComparisons: string[]; - processingQueue: Array<() => Promise>; - isProcessing: boolean; -} - -export interface EditClusterConfig { - deltaT: number; - deltaL: number; - maxEdits: number; - maxDuration: number; - contextSize: number; - maxEditSize: number; - contextLines: number; - verbose: boolean; -} - -export class EditAggregator { - private fileStates: Map = new Map(); - private config: EditClusterConfig; - private onComparisonFinalized: ( - filePath: string, - beforeState: string[], - beforeAfterComparison: string, - contextComparisons: string[], - ) => void; - - constructor( - config: Partial = {}, - onComparisonFinalized: ( - filePath: string, - beforeState: string[], - diff: string, - contextDiffs: string[], - ) => void = () => {}, - ) { - this.config = { - deltaT: config.deltaT ?? 1.0, - deltaL: config.deltaL ?? 5, - maxEdits: config.maxEdits ?? 200, - maxDuration: config.maxDuration ?? 20.0, - contextSize: config.contextSize ?? 5, - maxEditSize: config.maxEditSize ?? 1000, - contextLines: config.contextLines ?? 3, - verbose: config.verbose ?? false, - }; - this.onComparisonFinalized = onComparisonFinalized; - } - - async processEdit( - edit: RangeInFileWithContentsAndEdit, - timestamp: number = Date.now(), - ): Promise { - const filePath = edit.filepath; - - if (!this.fileStates.has(filePath)) { - this.fileStates.set(filePath, { - activeClusters: [], - currentContent: edit.fileContents, - priorComparisons: [], - processingQueue: [], - isProcessing: false, - }); - } - - const fileState = this.fileStates.get(filePath)!; - const task = async () => { - await this._processEditInternal(edit, timestamp, fileState); - }; - - fileState.processingQueue.push(task); - - if (!fileState.isProcessing) { - void this._processQueue(filePath); - } - } - - private async _processQueue(filePath: string): Promise { - const fileState = this.fileStates.get(filePath); - if (!fileState) return; - - fileState.isProcessing = true; - - while (fileState.processingQueue.length > 0) { - const nextTask = fileState.processingQueue.shift(); - if (nextTask) { - try { - await nextTask(); - } catch (error) { - console.error(`Error processing edit in ${filePath}:`, error); - } - await new Promise((resolve) => setTimeout(resolve, 0)); - } - } - - fileState.isProcessing = false; - } - - private async _processEditInternal( - edit: RangeInFileWithContentsAndEdit, - timestamp: number, - fileState: FileState, - ): Promise { - const filePath = edit.filepath; - - if (edit.editText.length > this.config.maxEditSize) { - if (this.config.verbose) { - console.log( - `Edit discarded: size ${edit.editText.length} exceeds max_edit_size ${this.config.maxEditSize}`, - ); - } - return; - } - - const editLine = edit.range.start.line; - const currentFileLines = fileState.currentContent.split("\n"); - - const clustersToFinalize = this.identifyClustersToFinalize( - fileState, - editLine, - timestamp, - false, - ); - - for (const cluster of clustersToFinalize) { - await this.finalizeCluster(filePath, cluster, fileState); - } - - let suitableCluster = this.findSuitableCluster( - fileState, - editLine, - timestamp, - ); - - if (!suitableCluster) { - suitableCluster = { - beforeState: fileState.currentContent, - startRange: { - minLine: Math.max(0, editLine - this.config.contextLines), - maxLine: Math.min( - currentFileLines.length - 1, - editLine + this.config.contextLines, - ), - }, - currentRange: { - minLine: Math.max(0, editLine - this.config.contextLines), - maxLine: Math.min( - currentFileLines.length - 1, - editLine + this.config.contextLines, - ), - }, - edits: [], - firstTimestamp: timestamp, - lastTimestamp: timestamp, - lastLine: editLine, - }; - fileState.activeClusters.push(suitableCluster); - } - - suitableCluster.edits.push(edit); - suitableCluster.lastTimestamp = timestamp; - suitableCluster.lastLine = editLine; - - const isWhitespaceOnly = this.isWhitespaceOnlyEdit( - edit, - fileState.currentContent, - ); - - if (!isWhitespaceOnly) { - suitableCluster.currentRange.minLine = Math.min( - suitableCluster.currentRange.minLine, - Math.max(0, editLine - this.config.contextLines), - ); - suitableCluster.currentRange.maxLine = Math.max( - suitableCluster.currentRange.maxLine, - Math.min( - currentFileLines.length - 1, - editLine + this.config.contextLines, - ), - ); - } - - fileState.currentContent = edit.fileContents; - - const isStructuralEdit = - edit.editText.includes("\n") || - edit.range.start.line !== edit.range.end.line; - - if (isStructuralEdit) { - const additionalClustersToFinalize = fileState.activeClusters.filter( - (c) => - c !== suitableCluster && this.clustersOverlap(c, suitableCluster), - ); - - for (const cluster of additionalClustersToFinalize) { - await this.finalizeCluster(filePath, cluster, fileState); - } - } - - if (this.config.verbose) { - console.log( - `Processed edit in ${filePath} at line ${editLine}: "${edit.editText.substring(0, 30)}${edit.editText.length > 30 ? "..." : ""}"`, - ); - } - } - - private isWhitespaceOnlyEdit( - edit: RangeInFileWithContentsAndEdit, - currentContent: string, - ): boolean { - const lines = currentContent.split("\n"); - const line = edit.range.start.line; - - if (line >= lines.length) return false; - - if (edit.range.start.line === edit.range.end.line) { - const beforeEdit = lines[line]; - const afterEdit = - beforeEdit.substring(0, edit.range.start.character) + - edit.editText + - beforeEdit.substring(edit.range.end.character); - - return beforeEdit.trim() === afterEdit.trim(); - } - - return false; - } - - private clustersOverlap( - cluster1: ClusterState, - cluster2: ClusterState, - ): boolean { - return ( - cluster1.currentRange.minLine <= - cluster2.currentRange.maxLine + this.config.deltaL && - cluster1.currentRange.maxLine >= - cluster2.currentRange.minLine - this.config.deltaL - ); - } - - async processEdits(edits: RangeInFileWithContentsAndEdit[]): Promise { - const timestamp = Date.now(); - if (this.config.verbose) { - console.log(`Queueing batch of ${edits.length} edits`); - } - - for (const edit of edits) { - await this.processEdit(edit, timestamp); - } - } - - async finalizeAllClusters(): Promise { - if (this.config.verbose) { - console.log("Finalizing all active clusters"); - } - - const filePromises: Promise[] = []; - - this.fileStates.forEach((fileState, filePath) => { - const filePromise = (async () => { - const clustersToFinalize = [...fileState.activeClusters]; - for (const cluster of clustersToFinalize) { - await this.finalizeCluster(filePath, cluster, fileState); - } - })(); - - filePromises.push(filePromise); - }); - - await Promise.all(filePromises); - } - - private findSuitableCluster( - fileState: FileState, - editLine: number, - timestamp: number, - ): ClusterState | null { - // First check if we need to finalize any clusters due to line jumps - const activeClusters = [...fileState.activeClusters]; - - for (const cluster of activeClusters) { - // If we're outside the line range but within the time window, - // we should finalize the current cluster - const isOutsideLineRange = - editLine < cluster.currentRange.minLine - this.config.deltaL || - editLine > cluster.currentRange.maxLine + this.config.deltaL; - - const isWithinTimeWindow = - (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT; - - // If user quickly jumped far away, finalize this cluster before continuing - if (isOutsideLineRange && isWithinTimeWindow) { - void this.finalizeCluster( - cluster.edits[0].filepath, - cluster, - fileState, - ); - } - } - - // Now look for a suitable cluster for the new edit - for (const cluster of fileState.activeClusters) { - const isOnSameLine = editLine === cluster.lastLine; - const isWithinTimeWindow = - (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT; - const isWithinLineRange = - editLine >= cluster.currentRange.minLine - this.config.deltaL && - editLine <= cluster.currentRange.maxLine + this.config.deltaL; - const isWithinEditLimit = cluster.edits.length < this.config.maxEdits; - const isWithinDurationLimit = - (timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration; - - if ( - (isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) && - isWithinEditLimit && - isWithinDurationLimit - ) { - return cluster; - } - } - return null; - } - - private identifyClustersToFinalize( - fileState: FileState, - editLine: number, - timestamp: number, - isStructuralEdit: boolean, - ): ClusterState[] { - const clustersToFinalize: ClusterState[] = []; - - fileState.activeClusters.forEach((cluster) => { - const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000; - - // Important fix: Only consider the line changed if it's a DIFFERENT line - // This way, continuing to edit the same line won't finalize the cluster - const isOnDifferentLine = cluster.lastLine !== editLine; - - // Only finalize if we moved to a different line AND the time gap exceeds deltaT - const shouldFinalizeByTime = - isOnDifferentLine && timeSinceLastEdit > this.config.deltaT; - - const shouldFinalizeByCount = - cluster.edits.length >= this.config.maxEdits; - - const shouldFinalizeByDuration = - (timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration; - - // Structural edits should only finalize other clusters, not their own - const shouldFinalizeByStructuralEdit = - isStructuralEdit && isOnDifferentLine; - - if ( - shouldFinalizeByTime || - shouldFinalizeByCount || - shouldFinalizeByDuration || - shouldFinalizeByStructuralEdit - ) { - clustersToFinalize.push(cluster); - - if (this.config.verbose || true) { - const reasons = []; - if (shouldFinalizeByTime) - reasons.push( - `time gap (${timeSinceLastEdit.toFixed(2)}s > ${this.config.deltaT}s)`, - ); - if (shouldFinalizeByCount) - reasons.push( - `edit count (${cluster.edits.length} >= ${this.config.maxEdits})`, - ); - if (shouldFinalizeByDuration) - reasons.push( - `duration (${((timestamp - cluster.firstTimestamp) / 1000).toFixed(2)}s > ${this.config.maxDuration}s)`, - ); - if (shouldFinalizeByStructuralEdit) - reasons.push("structural edit on different line"); - console.log( - `Finalizing cluster in ${cluster.edits[0].filepath} due to: ${reasons.join(", ")}`, - ); - } - } - }); - - return clustersToFinalize; - } - - private async createConsoleComparison( - beforeContent: string, - afterContent: string, - filePath: string, - ): Promise { - return new Promise((resolve) => { - setTimeout(() => { - const beforeLines = beforeContent.split("\n"); - const afterLines = afterContent.split("\n"); - const maxLines = Math.max(beforeLines.length, afterLines.length); - let firstDiffLine = maxLines; - let lastDiffLine = 0; - - for (let i = 0; i < maxLines; i++) { - const beforeLine = i < beforeLines.length ? beforeLines[i] : ""; - const afterLine = i < afterLines.length ? afterLines[i] : ""; - - if (beforeLine !== afterLine) { - firstDiffLine = Math.min(firstDiffLine, i); - lastDiffLine = Math.max(lastDiffLine, i); - } - } - - if (firstDiffLine > lastDiffLine) { - firstDiffLine = 0; - lastDiffLine = Math.min(5, maxLines - 1); - } - - const contextLines = 3; - const startLine = Math.max(0, firstDiffLine - contextLines); - const endLine = Math.min(maxLines - 1, lastDiffLine + contextLines); - const lineNumWidth = String(endLine).length; - const contentWidth = 60; - - let result = `\n=== File: ${filePath} ===\n`; - result += `=== Diff view of lines ${startLine}-${endLine} ===\n\n`; - result += `${"LINE".padEnd(lineNumWidth + 2)} | ${"BEFORE".padEnd(contentWidth)} | ${"AFTER".padEnd(contentWidth)}\n`; - result += `${"-".repeat(lineNumWidth + 2)}-|-${"-".repeat(contentWidth)}-|-${"-".repeat(contentWidth)}\n`; - - for (let i = startLine; i <= endLine; i++) { - const beforeLine = i < beforeLines.length ? beforeLines[i] : ""; - const afterLine = i < afterLines.length ? afterLines[i] : ""; - const truncatedBeforeLine = - beforeLine.length > contentWidth - 3 - ? beforeLine.substring(0, contentWidth - 3) + "..." - : beforeLine; - const truncatedAfterLine = - afterLine.length > contentWidth - 3 - ? afterLine.substring(0, contentWidth - 3) + "..." - : afterLine; - const changed = beforeLine === afterLine ? " " : "* "; - const lineNum = String(i).padStart(lineNumWidth); - - result += `${changed}${lineNum} | ${truncatedBeforeLine.padEnd(contentWidth)} | ${truncatedAfterLine.padEnd(contentWidth)}\n`; - } - - result += "\n"; - resolve(result); - }, 0); - }); - } - - private async finalizeCluster( - filePath: string, - cluster: ClusterState, - fileState: FileState, - ): Promise { - const beforeContent = cluster.beforeState; - const afterContent = fileState.currentContent; - const comparison = await this.createConsoleComparison( - beforeContent, - afterContent, - filePath, - ); - - fileState.priorComparisons.push(comparison); - if (fileState.priorComparisons.length > this.config.contextSize) { - fileState.priorComparisons.shift(); - } - - const beforeStateArray = cluster.beforeState.split("\n"); - - console.log("\n========== FINALIZED EDIT CLUSTER =========="); - console.log(`File: ${filePath}`); - console.log(`Number of edits: ${cluster.edits.length}`); - console.log(`First edit at line: ${cluster.edits[0]?.range.start.line}`); - console.log( - `Last edit at line: ${cluster.edits[cluster.edits.length - 1]?.range.start.line}`, - ); - console.log( - `Duration: ${(cluster.lastTimestamp - cluster.firstTimestamp) / 1000}s`, - ); - console.log(comparison); - console.log("===========================================\n"); - - fileState.activeClusters = fileState.activeClusters.filter( - (c) => c !== cluster, - ); - - this.onComparisonFinalized(filePath, beforeStateArray, comparison, [ - ...fileState.priorComparisons, - ]); - } - - getActiveClusterCount(): number { - let count = 0; - this.fileStates.forEach((fileState) => { - count += fileState.activeClusters.length; - }); - return count; - } - - getProcessingQueueSize(): number { - let count = 0; - this.fileStates.forEach((fileState) => { - count += fileState.processingQueue.length; - }); - return count; - } - - resetState(): void { - this.fileStates.clear(); - } -} diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts new file mode 100644 index 000000000..51aaef7ce --- /dev/null +++ b/core/nextEdit/context/diffFormatting.ts @@ -0,0 +1,65 @@ +import { createPatch } from "diff"; + +export enum DiffFormatType { + Unified = "unified", + Minimal = "minimal", + TokenLineDiff = "linediff", +} + +export const createDiff = ( + beforeContent: string, + afterContent: string, + filePath: string, + diffType: DiffFormatType, +) => { + switch (diffType) { + case DiffFormatType.Unified: + return createUnifiedDiff(beforeContent, afterContent, filePath); + case DiffFormatType.Minimal: + return createMinimalDiff(beforeContent, afterContent, filePath); + case DiffFormatType.TokenLineDiff: + return createTokenLineDiff(beforeContent, afterContent, filePath); + } +}; + +const createUnifiedDiff = ( + beforeContent: string, + afterContent: string, + filePath: string, +) => { + const normalizedBefore = beforeContent.endsWith("\n") + ? beforeContent + : beforeContent + "\n"; + const normalizedAfter = afterContent.endsWith("\n") + ? afterContent + : afterContent + "\n"; + + const patch = createPatch( + filePath, + normalizedBefore, + normalizedAfter, + "before", + "after", + { context: 3 }, + ); + + return patch; +}; + +const createMinimalDiff = ( + beforeContent: string, + afterContent: string, + filePath: string, +) => { + // TODO: Implement minimal diff + return ""; +}; + +const createTokenLineDiff = ( + beforeContent: string, + afterContent: string, + filePath: string, +) => { + // TODO: Implement token line diff + return ""; +};