Elffuss BraidHub

kikocis/continue public

main · 17.7 KiBRawPermalink
1import { Position, RangeInFileWithNextEditInfo } from "../..";
2import {
3 BeforeAfterDiff,
4 DiffFormatType,
5 createBeforeAfterDiff,
6 createDiff,
7} from "./diffFormatting";
8
9interface ClusterState {
10 beforeState: string; // stores content of cluster before edit
11 startRange: { minLine: number; maxLine: number };
12 currentRange: { minLine: number; maxLine: number };
13 edits: RangeInFileWithNextEditInfo[]; // store small edits that form the cluster
14 firstTimestamp: number;
15 lastTimestamp: number;
16 lastLine: number;
17 firstEditBeforeCursor: { line: number; character: number }; // cursor position before the first edit in the cluster
18 lastEditAfterCursor: { line: number; character: number }; // cursor position after the last edit in the previous cluster
19}
20
21interface FileState {
22 activeClusters: ClusterState[]; // Stores active clusters for the file
23 currentContent: string; // Stores the current content of the file
24 priorComparisons: string[]; // Stores prior comparisons for the file (not currently used, but kept for future use)
25 processingQueue: Array<() => Promise<void>>; // Stores a queue of small edits to be processed into clusters
26 isProcessing: boolean;
27}
28
29export interface EditClusterConfig {
30 deltaT: number; // Time threshold in seconds; if exceeded, a new cluster is created
31 deltaL: number; // Line threshold; if the user jumps more than this many lines, a new cluster is created
32 maxEdits: number; // Maximum number of edits in a cluster
33 maxDuration: number; // Maximum total duration of an edit in seconds
34 contextSize: number; // Number of previous edits to store; not currently used but kept for future use
35 contextLines: number; // Used for computations involving deltaL
36}
37
38export class EditAggregator {
39 private fileStates: Map<string, FileState> = new Map();
40 public config: EditClusterConfig;
41 private previousEditFinalCursorPosition: Position;
42 private lastProcessedFilePath: string | null = null;
43 public onComparisonFinalized: (
44 diff: BeforeAfterDiff,
45 beforeCursorPos: Position,
46 afterPrevEditCursorPos: Position,
47 ) => void;
48
49 private static _instance: EditAggregator | null = null;
50
51 public static getInstance(
52 config?: Partial<EditClusterConfig>,
53 onComparisonFinalized?: (
54 diff: BeforeAfterDiff,
55 beforeCursorPos: Position,
56 afterPrevEditCursorPos: Position,
57 ) => void,
58 ): EditAggregator {
59 // Create instance if it doesn't exist
60 if (!EditAggregator._instance) {
61 EditAggregator._instance = new EditAggregator(
62 config,
63 onComparisonFinalized,
64 );
65 }
66 // Update instance if new parameters are provided
67 else if (config || onComparisonFinalized) {
68 if (config) {
69 EditAggregator._instance.config = {
70 deltaT: config.deltaT ?? EditAggregator._instance.config.deltaT,
71 deltaL: config.deltaL ?? EditAggregator._instance.config.deltaL,
72 maxEdits: config.maxEdits ?? EditAggregator._instance.config.maxEdits,
73 maxDuration:
74 config.maxDuration ?? EditAggregator._instance.config.maxDuration,
75 contextSize:
76 config.contextSize ?? EditAggregator._instance.config.contextSize,
77 contextLines:
78 config.contextLines ?? EditAggregator._instance.config.contextLines,
79 };
80 }
81
82 if (onComparisonFinalized) {
83 EditAggregator._instance.onComparisonFinalized = onComparisonFinalized;
84 }
85 }
86
87 return EditAggregator._instance;
88 }
89
90 constructor(
91 config: Partial<EditClusterConfig> = {},
92 onComparisonFinalized: (
93 diff: BeforeAfterDiff,
94 beforeCursorPos: Position,
95 afterPrevEditCursorPos: Position,
96 ) => void = () => {},
97 ) {
98 this.config = {
99 deltaT: config.deltaT ?? 1.0,
100 deltaL: config.deltaL ?? 5,
101 maxEdits: config.maxEdits ?? 500,
102 maxDuration: config.maxDuration ?? 100.0,
103 contextSize: config.contextSize ?? 5,
104 contextLines: config.contextLines ?? 3,
105 };
106 this.onComparisonFinalized = onComparisonFinalized;
107 this.previousEditFinalCursorPosition = { line: 0, character: 0 };
108 }
109
110 async processEdit(
111 edit: RangeInFileWithNextEditInfo,
112 timestamp: number = Date.now(),
113 ): Promise<void> {
114 const filePath = edit.filepath;
115
116 // If we're switching to a different file, finalize all clusters from the previous file
117 if (this.lastProcessedFilePath && this.lastProcessedFilePath !== filePath) {
118 await this.finalizeClustersForFile(this.lastProcessedFilePath);
119 }
120
121 // Update the last processed file path
122 this.lastProcessedFilePath = filePath;
123
124 if (!this.fileStates.has(filePath)) {
125 this.fileStates.set(filePath, {
126 activeClusters: [],
127 currentContent: edit.fileContents,
128 priorComparisons: [],
129 processingQueue: [],
130 isProcessing: false,
131 });
132 }
133
134 const fileState = this.fileStates.get(filePath)!;
135 const task = async () => {
136 await this._processEditInternal(edit, timestamp, fileState);
137 };
138
139 fileState.processingQueue.push(task);
140
141 if (!fileState.isProcessing) {
142 void this._processQueue(filePath);
143 }
144 }
145
146 private async _processQueue(filePath: string): Promise<void> {
147 const fileState = this.fileStates.get(filePath);
148 if (!fileState) return;
149
150 fileState.isProcessing = true;
151
152 // Process chunks of (5) edits instead of one at a time
153 while (fileState.processingQueue.length > 0) {
154 const tasks = fileState.processingQueue.splice(0, 5);
155 if (tasks.length > 0) {
156 try {
157 await Promise.all(tasks.map((task) => task()));
158 } catch (error) {
159 console.error(`Error processing edits in ${filePath}:`, error);
160 }
161
162 // Yield to the event loop to prevent blocking
163 await new Promise((resolve) => setTimeout(resolve, 0));
164 }
165 }
166
167 fileState.isProcessing = false;
168 }
169
170 private async _processEditInternal(
171 edit: RangeInFileWithNextEditInfo,
172 timestamp: number,
173 fileState: FileState,
174 ): Promise<void> {
175 const filePath = edit.filepath;
176
177 const editLine = edit.range.start.line;
178 const currentFileLines = fileState.currentContent.split("\n");
179
180 const clustersToFinalize = this.identifyClustersToFinalize(
181 fileState,
182 edit,
183 timestamp,
184 false,
185 );
186
187 for (const cluster of clustersToFinalize) {
188 await this.finalizeCluster(filePath, cluster, fileState);
189 }
190
191 let suitableCluster = this.findSuitableCluster(
192 fileState,
193 editLine,
194 timestamp,
195 );
196
197 // Check if adding this edit would exceed deltaL lines for the cluster
198 if (suitableCluster) {
199 const potentialMinLine = Math.min(
200 suitableCluster.currentRange.minLine,
201 Math.max(0, editLine - this.config.contextLines),
202 );
203 const potentialMaxLine = Math.max(
204 suitableCluster.currentRange.maxLine,
205 Math.min(
206 currentFileLines.length - 1,
207 editLine + this.config.contextLines,
208 ),
209 );
210 const potentialLineSpan = potentialMaxLine - potentialMinLine + 1;
211
212 if (potentialLineSpan > this.config.deltaL * 2) {
213 // Auto-finalize the current cluster before creating a new one
214 await this.finalizeCluster(filePath, suitableCluster, fileState);
215 suitableCluster = null;
216 }
217 }
218
219 // initialize a cluster
220 if (!suitableCluster) {
221 suitableCluster = {
222 beforeState: fileState.currentContent,
223 startRange: {
224 minLine: Math.max(0, editLine - this.config.contextLines),
225 maxLine: Math.min(
226 currentFileLines.length - 1,
227 editLine + this.config.contextLines,
228 ),
229 },
230 currentRange: {
231 minLine: Math.max(0, editLine - this.config.contextLines),
232 maxLine: Math.min(
233 currentFileLines.length - 1,
234 editLine + this.config.contextLines,
235 ),
236 },
237 edits: [],
238 firstTimestamp: timestamp,
239 lastTimestamp: timestamp,
240 lastLine: editLine,
241 firstEditBeforeCursor: edit.beforeCursorPos,
242 lastEditAfterCursor: edit.afterCursorPos,
243 };
244 fileState.activeClusters.push(suitableCluster);
245 }
246
247 suitableCluster.edits.push(edit);
248 suitableCluster.lastTimestamp = timestamp;
249 suitableCluster.lastLine = editLine;
250 suitableCluster.lastEditAfterCursor = edit.afterCursorPos;
251
252 const isWhitespaceOnly = this.isWhitespaceOnlyEdit(
253 edit,
254 fileState.currentContent,
255 );
256
257 if (!isWhitespaceOnly) {
258 suitableCluster.currentRange.minLine = Math.min(
259 suitableCluster.currentRange.minLine,
260 Math.max(0, editLine - this.config.contextLines),
261 );
262 suitableCluster.currentRange.maxLine = Math.max(
263 suitableCluster.currentRange.maxLine,
264 Math.min(
265 currentFileLines.length - 1,
266 editLine + this.config.contextLines,
267 ),
268 );
269 }
270
271 fileState.currentContent = edit.fileContents;
272
273 const isStructuralEdit =
274 edit.editText.includes("\n") ||
275 edit.range.start.line !== edit.range.end.line;
276
277 if (isStructuralEdit) {
278 const additionalClustersToFinalize = fileState.activeClusters.filter(
279 (c) =>
280 c !== suitableCluster && this.clustersOverlap(c, suitableCluster),
281 );
282
283 for (const cluster of additionalClustersToFinalize) {
284 await this.finalizeCluster(filePath, cluster, fileState);
285 }
286 }
287 }
288
289 private isWhitespaceOnlyEdit(
290 edit: RangeInFileWithNextEditInfo,
291 currentContent: string,
292 ): boolean {
293 const lines = currentContent.split("\n");
294 const line = edit.range.start.line;
295
296 if (line >= lines.length) return false;
297
298 if (edit.range.start.line === edit.range.end.line) {
299 const beforeEdit = lines[line];
300 const afterEdit =
301 beforeEdit.substring(0, edit.range.start.character) +
302 edit.editText +
303 beforeEdit.substring(edit.range.end.character);
304
305 return beforeEdit.trim() === afterEdit.trim();
306 }
307
308 return false;
309 }
310
311 private clustersOverlap(
312 cluster1: ClusterState,
313 cluster2: ClusterState,
314 ): boolean {
315 return (
316 cluster1.currentRange.minLine <=
317 cluster2.currentRange.maxLine + this.config.deltaL &&
318 cluster1.currentRange.maxLine >=
319 cluster2.currentRange.minLine - this.config.deltaL
320 );
321 }
322
323 async processEdits(edits: RangeInFileWithNextEditInfo[]): Promise<void> {
324 const timestamp = Date.now();
325
326 // Only process the last edit during rapid typing
327 if (this.getProcessingQueueSize() > 50) {
328 if (edits.length > 0) {
329 await this.processEdit(edits[edits.length - 1], timestamp);
330 }
331 return;
332 }
333
334 for (const edit of edits) {
335 await this.processEdit(edit, timestamp);
336 }
337 }
338
339 /**
340 * Finalizes all clusters for a specific file
341 */
342 private async finalizeClustersForFile(filePath: string): Promise<void> {
343 const fileState = this.fileStates.get(filePath);
344 if (!fileState) return;
345
346 // Create a copy of the clusters to finalize to avoid modifying array during iteration
347 const clustersToFinalize = [...fileState.activeClusters];
348
349 for (const cluster of clustersToFinalize) {
350 await this.finalizeCluster(filePath, cluster, fileState);
351 }
352 }
353
354 async finalizeAllClusters(): Promise<void> {
355 const filePromises: Promise<void>[] = [];
356
357 this.fileStates.forEach((fileState, filePath) => {
358 const filePromise = this.finalizeClustersForFile(filePath);
359 filePromises.push(filePromise);
360 });
361
362 await Promise.all(filePromises);
363 }
364
365 private findSuitableCluster(
366 fileState: FileState,
367 editLine: number,
368 timestamp: number,
369 ): ClusterState | null {
370 const activeClusters = [...fileState.activeClusters];
371
372 for (const cluster of activeClusters) {
373 // If we're outside the line range but within the time window,
374 // we should finalize the current cluster
375 const isOutsideLineRange =
376 editLine < cluster.currentRange.minLine - this.config.deltaL ||
377 editLine > cluster.currentRange.maxLine + this.config.deltaL;
378
379 const isWithinTimeWindow =
380 (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
381
382 // If user quickly jumped far away, finalize this cluster before continuing
383 if (isOutsideLineRange && isWithinTimeWindow) {
384 void this.finalizeCluster(
385 cluster.edits[0].filepath,
386 cluster,
387 fileState,
388 );
389 }
390 }
391
392 // Now look for a suitable cluster for the new edit
393 for (const cluster of fileState.activeClusters) {
394 const isOnSameLine = editLine === cluster.lastLine;
395 const isWithinTimeWindow =
396 (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
397 const isWithinLineRange =
398 editLine >= cluster.currentRange.minLine - this.config.deltaL &&
399 editLine <= cluster.currentRange.maxLine + this.config.deltaL;
400 const isWithinEditLimit = cluster.edits.length < this.config.maxEdits;
401 const isWithinDurationLimit =
402 (timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration;
403
404 if (
405 (isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) &&
406 isWithinEditLimit &&
407 isWithinDurationLimit
408 ) {
409 return cluster;
410 }
411 }
412 return null;
413 }
414
415 private identifyClustersToFinalize(
416 fileState: FileState,
417 edit: RangeInFileWithNextEditInfo,
418 timestamp: number,
419 isStructuralEdit: boolean,
420 ): ClusterState[] {
421 const clustersToFinalize: ClusterState[] = [];
422 const editLine = edit.range.start.line;
423
424 fileState.activeClusters.forEach((cluster) => {
425 const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000;
426
427 const isOnDifferentLineByNumber = cluster.lastLine !== editLine;
428
429 const isOnDifferentLineByNewline = edit.editText.includes("\n");
430
431 // Use different time thresholds for different types of line change detection
432 const shouldFinalizeByLineNumber =
433 isOnDifferentLineByNumber && timeSinceLastEdit > this.config.deltaT;
434
435 const shouldFinalizeByNewline =
436 isOnDifferentLineByNewline &&
437 timeSinceLastEdit > this.config.deltaT * 1.5;
438
439 // Finalize if we moved to a different line AND the time gap exceeds the respective threshold
440 const shouldFinalizeByTime =
441 shouldFinalizeByLineNumber || shouldFinalizeByNewline;
442 const shouldFinalizeByCount =
443 cluster.edits.length >= this.config.maxEdits;
444 const shouldFinalizeByDuration =
445 (timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration;
446
447 // For structural edits, use the combined line detection
448 const isOnDifferentLine =
449 isOnDifferentLineByNumber || isOnDifferentLineByNewline;
450 const shouldFinalizeByStructuralEdit =
451 isStructuralEdit && isOnDifferentLine;
452
453 if (
454 shouldFinalizeByTime ||
455 shouldFinalizeByCount ||
456 shouldFinalizeByDuration ||
457 shouldFinalizeByStructuralEdit
458 ) {
459 clustersToFinalize.push(cluster);
460 }
461 });
462
463 return clustersToFinalize;
464 }
465
466 private async finalizeCluster(
467 filePath: string,
468 cluster: ClusterState,
469 fileState: FileState,
470 ): Promise<void> {
471 const beforeContent = cluster.beforeState;
472 const afterContent = fileState.currentContent;
473
474 // Skip whitespace-only diffs
475 const isWhitespaceOnlyDiff =
476 beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, "");
477
478 if (isWhitespaceOnlyDiff) {
479 fileState.activeClusters = fileState.activeClusters.filter(
480 (c) => c !== cluster,
481 );
482 return;
483 }
484
485 const diff = createDiff({
486 beforeContent: beforeContent,
487 afterContent: afterContent,
488 filePath: filePath,
489 diffType: DiffFormatType.Unified,
490 contextLines: 3,
491 }); // Used for checks, not for final output
492
493 // Skip diffs with too many changed lines
494 const changedLineCount = this.countChangedLines(diff);
495 if (changedLineCount > this.config.deltaL * 2) {
496 fileState.activeClusters = fileState.activeClusters.filter(
497 (c) => c !== cluster,
498 );
499 return;
500 }
501
502 fileState.priorComparisons.push(diff);
503 if (fileState.priorComparisons.length > this.config.contextSize) {
504 fileState.priorComparisons.shift();
505 }
506
507 fileState.activeClusters = fileState.activeClusters.filter(
508 (c) => c !== cluster,
509 );
510
511 // Give format-agnostic diff to the callback
512 const fullFileVersionsDiff = createBeforeAfterDiff(
513 beforeContent,
514 afterContent,
515 filePath,
516 );
517
518 // Store this cluster's final cursor position for future reference
519 this.previousEditFinalCursorPosition = cluster.lastEditAfterCursor;
520
521 this.onComparisonFinalized(
522 fullFileVersionsDiff,
523 cluster.firstEditBeforeCursor,
524 this.previousEditFinalCursorPosition,
525 );
526 }
527
528 private countChangedLines(diff: string): number {
529 let count = 0;
530 let addedLines = new Set<number>();
531 let removedLines = new Set<number>();
532
533 // Parse the diff lines
534 const lines = diff.split("\n");
535 for (const line of lines) {
536 if (
537 line.startsWith("+++ ") ||
538 line.startsWith("--- ") ||
539 line.startsWith("@@")
540 ) {
541 continue; // Skip header lines
542 }
543
544 if (line.startsWith("+")) {
545 addedLines.add(count);
546 count++;
547 } else if (line.startsWith("-")) {
548 removedLines.add(count);
549 count++;
550 }
551 }
552
553 return Math.max(addedLines.size, removedLines.size);
554 }
555
556 getActiveClusterCount(): number {
557 let count = 0;
558 this.fileStates.forEach((fileState) => {
559 count += fileState.activeClusters.length;
560 });
561 return count;
562 }
563
564 getProcessingQueueSize(): number {
565 let count = 0;
566 this.fileStates.forEach((fileState) => {
567 count += fileState.processingQueue.length;
568 });
569 return count;
570 }
571
572 resetState(): void {
573 this.fileStates.clear();
574 this.lastProcessedFilePath = null;
575 }
576}