diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 671c52d3b..702356198 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -230,7 +230,7 @@ export const getAllSnippetsWithoutRace = async ({ ideSnippets, diffSnippets, clipboardSnippets, - recentlyOpenedFileSnippets + recentlyOpenedFileSnippets, ] = await Promise.all([ contextRetrievalService.getRootPathSnippets(helper), contextRetrievalService.getSnippetsFromImportDefinitions(helper), @@ -239,7 +239,7 @@ export const getAllSnippetsWithoutRace = async ({ : [], [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, getClipboardSnippets(ide), - getSnippetsFromRecentlyOpenedFiles(helper, ide) + getSnippetsFromRecentlyOpenedFiles(helper, ide), ]); return { @@ -250,6 +250,6 @@ export const getAllSnippetsWithoutRace = async ({ diffSnippets, clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, - recentlyOpenedFileSnippets + recentlyOpenedFileSnippets, }; }; diff --git a/core/core.ts b/core/core.ts index 4c79f18d1..26c460fc8 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,32 @@ export class Core { } }); + on("files/smallEdit", async ({ data }) => { + const EDIT_AGGREGATION_OPTIONS = { + deltaT: 1.0, + deltaL: 5, + maxEdits: 250, + maxDuration: 100.0, + contextSize: 5, + maxEditSize: 1000, + }; + + if (!global._editAggregator) { + global._editAggregator = new EditAggregator( + EDIT_AGGREGATION_OPTIONS, + (diff: string) => { + console.log(diff, "\n"); + // TODO handle devData logging here + }, + ); + } + + // queueMicrotask prevents blocking the UI thread during typing + queueMicrotask(() => { + void 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..4db65569a --- /dev/null +++ b/core/nextEdit/context/aggregateEdits.ts @@ -0,0 +1,457 @@ +import { RangeInFileWithContentsAndEdit } from "../.."; +import { DiffFormatType, createDiff } from "./diffFormatting"; + +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: (diff: string) => void; + + constructor( + config: Partial = {}, + onComparisonFinalized: (diff: string) => void = () => {}, + ) { + this.config = { + 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; + } + + 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; + + // Process chunks of (5) edits instead of one at a time + while (fileState.processingQueue.length > 0) { + const tasks = fileState.processingQueue.splice(0, 5); + if (tasks.length > 0) { + try { + await Promise.all(tasks.map((task) => task())); + } catch (error) { + console.error(`Error processing edits in ${filePath}:`, error); + } + + // Yield to the event loop to prevent blocking + await new Promise((resolve) => setTimeout(resolve, 0)); + } + } + + fileState.isProcessing = false; + } + + private async _processEditInternal( + edit: RangeInFileWithContentsAndEdit, + timestamp: number, + fileState: FileState, + ): Promise { + const filePath = edit.filepath; + + const editSize = edit.editText.length; + if (editSize > 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); + } + } + } + + 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(); + + // Only process the last edit during rapid typing + if (this.getProcessingQueueSize() > 15) { + if (edits.length > 0) { + await this.processEdit(edits[edits.length - 1], timestamp); + } + return; + } + + for (const edit of edits) { + await this.processEdit(edit, timestamp); + } + } + + async finalizeAllClusters(): Promise { + 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 { + 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; + + // Only consider the line changed if it's a DIFFERENT line + const isOnDifferentLine = cluster.lastLine !== editLine; + + // 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); + } + }); + + return clustersToFinalize; + } + + private async finalizeCluster( + filePath: string, + cluster: ClusterState, + fileState: FileState, + ): Promise { + const beforeContent = cluster.beforeState; + const afterContent = fileState.currentContent; + + // Skip whitespace-only diffs + const isWhitespaceOnlyDiff = + beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, ""); + + if (isWhitespaceOnlyDiff) { + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + return; + } + + const diff = createDiff( + beforeContent, + afterContent, + filePath, + DiffFormatType.Unified, + ); + + // Skip diffs with too many changed lines + const changedLineCount = this.countChangedLines(diff); + if (changedLineCount > this.config.deltaL * 2) { + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + return; + } + + fileState.priorComparisons.push(diff); + if (fileState.priorComparisons.length > this.config.contextSize) { + fileState.priorComparisons.shift(); + } + + fileState.activeClusters = fileState.activeClusters.filter( + (c) => c !== cluster, + ); + + 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("+")) { + addedLines.add(count); + count++; + } else if (line.startsWith("-")) { + removedLines.add(count); + count++; + } + } + + 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/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 ""; +}; 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/package-lock.json b/extensions/vscode/package-lock.json index ce706126c..199c669c7 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/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 9194c909d..8a2605a95 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -308,11 +308,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..1292e44bb 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"; @@ -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 @@ -283,6 +284,38 @@ export class VsCodeExtension { this.configHandler.reloadConfig(); }); + vscode.workspace.onDidChangeTextDocument(async (event) => { + const changes = event.contentChanges; + + if (event.contentChanges.length === 0) { + return; + } + + // OPTIMIZATION: Debounce rapid keystrokes + // This prevents sending too many edit events during fast typing + if (this._editDebounceTimer) { + clearTimeout(this._editDebounceTimer); + } + + 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) => { this.core.invoke("files/changed", { uris: [event.uri.toString()],