improved edit logging behavior, working on optimizing performance now

This commit is contained in:
adarshramiyer 2025-06-17 15:43:37 -07:00
parent 7ec4bc25a0
commit 3202b2d34d
6 changed files with 805 additions and 338 deletions

View file

@ -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,
};
};

View file

@ -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

View file

@ -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<void>>;
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<string, FileState> = 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<EditClusterConfig> = {},
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
if (this.config.verbose) {
console.log("Finalizing all active clusters");
@ -361,7 +266,6 @@ export class EditAggregator {
const filePromises: Promise<void>[] = [];
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<string> {
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<void> {
// 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<number>();
let removedLines = new Set<number>();
// 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();
}
}

View file

@ -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<void>>;
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<string, FileState> = new Map();
private config: EditClusterConfig;
private onComparisonFinalized: (
filePath: string,
beforeState: string[],
beforeAfterComparison: string,
contextComparisons: string[],
) => void;
constructor(
config: Partial<EditClusterConfig> = {},
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
if (this.config.verbose) {
console.log("Finalizing all active clusters");
}
const filePromises: Promise<void>[] = [];
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<string> {
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<void> {
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();
}
}

View file

@ -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",

View file

@ -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) => {