Elffuss BraidHub

kikocis/continue public

9d5865e0e05b · 17.0 KiBRawPermalink
1import { myersDiff } from "core/diff/myers";
2import * as URI from "uri-js";
3import * as vscode from "vscode";
4
5import {
6 AddedLineDecorationManager,
7 RemovedLineDecorationManager,
8 belowIndexDecorationType,
9 indexDecorationType,
10} from "./decorations";
11
12import type { ApplyState, DiffLine } from "core";
13import type { VerticalDiffCodeLens } from "./manager";
14
15export interface VerticalDiffHandlerOptions {
16 input?: string;
17 instant?: boolean;
18 onStatusUpdate: (
19 status?: ApplyState["status"],
20 numDiffs?: ApplyState["numDiffs"],
21 fileContent?: ApplyState["fileContent"],
22 ) => void;
23 streamId?: string;
24}
25
26export class VerticalDiffHandler implements vscode.Disposable {
27 public insertedInCurrentBlock = 0;
28 public streamId?: string;
29 disposables: vscode.Disposable[] = [];
30 private currentLineIndex: number;
31 private cancelled = false;
32 private newLinesAdded = 0;
33 private deletionBuffer: string[] = [];
34 private removedLineDecorations: RemovedLineDecorationManager;
35 private addedLineDecorations: AddedLineDecorationManager;
36 private _diffLinesQueue: DiffLine[] = [];
37 private _queueLock = false;
38
39 constructor(
40 private startLine: number,
41 private endLine: number,
42 private editor: vscode.TextEditor,
43 private readonly editorToVerticalDiffCodeLens: Map<
44 string,
45 VerticalDiffCodeLens[]
46 >,
47 private readonly clearForFileUri: (
48 fileUri: string | undefined,
49 accept: boolean,
50 ) => void,
51 private readonly refreshCodeLens: () => void,
52 public options: VerticalDiffHandlerOptions,
53 ) {
54 this.currentLineIndex = startLine;
55 this.streamId = options.streamId;
56
57 this.removedLineDecorations = new RemovedLineDecorationManager(this.editor);
58 this.addedLineDecorations = new AddedLineDecorationManager(this.editor);
59
60 const disposable = vscode.window.onDidChangeActiveTextEditor((editor) => {
61 if (!editor) {
62 return;
63 }
64 // When we switch away and back to this editor, need to re-draw decorations
65 if (URI.equal(editor.document.uri.toString(), this.fileUri)) {
66 this.editor = editor;
67 this.removedLineDecorations.applyToNewEditor(editor);
68 this.addedLineDecorations.applyToNewEditor(editor);
69 this.updateIndexLineDecorations();
70 this.refreshCodeLens();
71
72 // Handle any lines received while editor was closed
73 this.queueDiffLine(undefined);
74 }
75 });
76 this.disposables.push(disposable);
77 }
78
79 public get range(): vscode.Range {
80 const startLine = Math.min(this.startLine, this.endLine);
81 const endLine = Math.max(this.startLine, this.endLine);
82 return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
83 }
84
85 get isCancelled() {
86 return this.cancelled;
87 }
88
89 private get fileUri() {
90 return this.editor.document.uri.toString();
91 }
92
93 async clear(accept: boolean) {
94 vscode.commands.executeCommand(
95 "setContext",
96 "continue.streamingDiff",
97 false,
98 );
99
100 const removedRanges = this.removedLineDecorations.ranges;
101 if (accept) {
102 // Accept all: delete all the red ranges and clear green decorations
103 await this.deleteRangeLines(removedRanges.map((r) => r.range));
104 } else {
105 // Reject all: Re-insert red lines, delete green ones
106 for (const r of removedRanges) {
107 await this.deleteRangeLines([r.range]);
108 await this.insertTextAboveLine(r.range.start.line, r.line);
109 }
110 await this.deleteRangeLines(this.addedLineDecorations.ranges);
111 }
112
113 this.clearDecorations();
114
115 this.options.onStatusUpdate(
116 "closed",
117 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
118 this.editor.document.getText(),
119 );
120
121 this.cancelled = true;
122 this.refreshCodeLens();
123 this.dispose();
124 }
125
126 dispose() {
127 this.disposables.forEach((disposable) => disposable.dispose());
128 }
129
130 async queueDiffLine(diffLine: DiffLine | undefined) {
131 if (diffLine) {
132 this._diffLinesQueue.push(diffLine);
133 }
134
135 if (this._queueLock || this.editor !== vscode.window.activeTextEditor) {
136 return;
137 }
138
139 this._queueLock = true;
140
141 while (this._diffLinesQueue.length) {
142 const line = this._diffLinesQueue.shift();
143 if (!line) {
144 break;
145 }
146
147 try {
148 await this._handleDiffLine(line);
149 } catch (e) {
150 // If editor is switched between calling _handleDiffLine and the edit actually being executed
151 this._diffLinesQueue.push(line);
152 break;
153 }
154 }
155
156 this._queueLock = false;
157 }
158
159 async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
160 let diffLines = [];
161
162 try {
163 // As an indicator of loading
164 this.updateIndexLineDecorations();
165
166 for await (const diffLine of diffLineGenerator) {
167 if (this.isCancelled) {
168 return;
169 }
170 diffLines.push(diffLine);
171 await this.queueDiffLine(diffLine);
172 }
173
174 // Clear deletion buffer
175 await this.insertDeletionBuffer();
176
177 const myersDiffs = await this.reapplyWithMyersDiff(diffLines);
178
179 // Scroll to the first diff
180 const scrollToLine =
181 this.getFirstChangedLine(myersDiffs) ?? this.startLine;
182 const range = new vscode.Range(scrollToLine, 0, scrollToLine, 0);
183 this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
184
185 this.options.onStatusUpdate(
186 "done",
187 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
188 this.editor.document.getText(),
189 );
190
191 // Reject on user typing
192 // const listener = vscode.workspace.onDidChangeTextDocument((e) => {
193 // if (URI.equal(e.document.uri.toString(), this.fileUri)) {
194 // this.clear(false);
195 // listener.dispose();
196 // }
197 // });
198 } catch (e) {
199 this.clearForFileUri(this.fileUri, false);
200 throw e;
201 }
202 return diffLines;
203 }
204
205 async acceptRejectBlock(
206 accept: boolean,
207 startLine: number,
208 numGreen: number,
209 numRed: number,
210 skipStatusUpdate?: boolean,
211 ) {
212 if (numGreen > 0) {
213 // Delete the editor decoration
214 this.addedLineDecorations.deleteRangeStartingAt(startLine + numRed);
215 if (!accept) {
216 // Delete the actual lines
217 await this.deleteLinesAt(startLine + numRed, numGreen);
218 }
219 }
220
221 if (numRed > 0) {
222 const deleted =
223 this.removedLineDecorations.deleteRangesStartingAt(startLine);
224
225 await this.deleteLinesAt(startLine, numRed);
226 if (deleted && !accept) {
227 await this.insertTextAboveLine(
228 startLine,
229 deleted.map((r) => r.line).join("\n"),
230 );
231 }
232 }
233
234 // Shift everything below upward
235 const offset = -(accept ? numRed : numGreen);
236
237 this.removedLineDecorations.shiftDownAfterLine(startLine, offset);
238 this.addedLineDecorations.shiftDownAfterLine(startLine, offset);
239
240 // Shift the codelens objects
241 this.shiftCodeLensObjects(startLine, offset);
242
243 if (!skipStatusUpdate) {
244 const numDiffs =
245 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0;
246
247 const status = numDiffs === 0 ? "closed" : undefined;
248
249 this.options.onStatusUpdate(
250 status,
251 numDiffs,
252 this.editor.document.getText(),
253 );
254 }
255 }
256
257 public updateLineDelta(
258 fileUri: string,
259 startLine: number,
260 lineDelta: number,
261 ) {
262 // Retrieve the diff blocks for the given file
263 const blocks = this.editorToVerticalDiffCodeLens.get(fileUri);
264 if (!blocks) {
265 return;
266 }
267
268 // Update decorations
269 this.removedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
270 this.addedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
271
272 // Update code lens
273 this.shiftCodeLensObjects(startLine, lineDelta);
274 }
275
276 public hasDiffForCurrentFile(): boolean {
277 const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri);
278 return diffBlocks !== undefined && diffBlocks.length > 0;
279 }
280
281 clearDecorations() {
282 this.removedLineDecorations.clear();
283 this.addedLineDecorations.clear();
284 this.clearIndexLineDecorations();
285 this.editorToVerticalDiffCodeLens.delete(this.fileUri);
286 this.refreshCodeLens();
287 }
288
289 /**
290 * This method is used to apply diff decorations after the intiial stream.
291 * This is to handle scenarios where we miscalculate the original diff blocks,
292 * and decide to follow up with a deterministic algorithm like Myers Diff once
293 * we have received all of the diff lines.
294 */
295 async reapplyWithMyersDiff(diffLines: DiffLine[]) {
296 // Diff is messed up without this delay.
297 await new Promise((resolve) => setTimeout(resolve, 100));
298
299 // First, we reset the original diff by rejecting all pending diff blocks
300 const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? [];
301 for (const block of blocks.reverse()) {
302 await this.acceptRejectBlock(
303 false,
304 block.start,
305 block.numGreen,
306 block.numRed,
307 true,
308 );
309 }
310
311 this.clearDecorations();
312
313 // Then, get our old/new file content based on the original lines
314 // We need the input to be "newline terminated" rather than
315 // newline separated, because myersDiff() would consider
316 // ["A"] => "A" and ["A", ""] => "A\n" to be the same single line.
317 // "A\n" and "A\n\n" are unambiguous.
318 const oldContentWithoutTrailingNewline = diffLines
319 .filter((line) => line.type === "same" || line.type === "old")
320 .map((line) => line.line)
321 .join("\n");
322
323 const oldFileContent = oldContentWithoutTrailingNewline + "\n";
324
325 const newFileContent =
326 diffLines
327 .filter((line) => line.type === "same" || line.type === "new")
328 .map((line) => line.line)
329 .join("\n") + "\n";
330
331 const myersDiffs = myersDiff(oldFileContent, newFileContent);
332
333 // Preserve the trailing newline behavior by checking the original document content
334 const originalDocumentContent = this.editor.document.getText(this.range);
335 const originalContentEndsWithNewline =
336 originalDocumentContent.endsWith("\n");
337
338 // Add trailing newline only if the original file had one to prevent line count discrepancies
339 const replaceContent =
340 myersDiffs
341 .map((diff) => (diff.type === "old" ? "" : diff.line))
342 .join("\n") + (originalContentEndsWithNewline ? "\n" : "");
343
344 // Then, we insert our diff lines
345 await this.editor.edit((editBuilder) => {
346 editBuilder.replace(this.range, replaceContent),
347 { undoStopAfter: false, undoStopBefore: false };
348 });
349
350 // Lastly, we apply decorations
351 let numRed = 0;
352 let numGreen = 0;
353
354 const codeLensBlocks: VerticalDiffCodeLens[] = [];
355
356 myersDiffs.forEach((diff, index) => {
357 if (diff.type === "old") {
358 this.removedLineDecorations.addLine(this.startLine + index, diff.line);
359 numRed++;
360 } else if (diff.type === "new") {
361 this.addedLineDecorations.addLine(this.startLine + index);
362 numGreen++;
363 } else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) {
364 codeLensBlocks.push({
365 numRed,
366 numGreen,
367 start: this.startLine + index - numRed - numGreen,
368 });
369 numRed = 0;
370 numGreen = 0;
371 }
372 });
373
374 if (numRed > 0 || numGreen > 0) {
375 codeLensBlocks.push({
376 numGreen,
377 numRed,
378 start: this.startLine + myersDiffs.length - numRed - numGreen,
379 });
380 }
381
382 this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
383 this.refreshCodeLens();
384
385 return myersDiffs;
386 }
387
388 private async insertDeletionBuffer() {
389 if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
390 const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
391
392 blocks.push({
393 start: this.currentLineIndex - this.insertedInCurrentBlock,
394 numRed: this.deletionBuffer.length,
395 numGreen: this.insertedInCurrentBlock,
396 });
397
398 this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
399 }
400
401 if (this.deletionBuffer.length === 0) {
402 this.insertedInCurrentBlock = 0;
403 return;
404 }
405
406 // Insert the block of deleted lines as empty new lines
407 await this.insertTextAboveLine(
408 this.currentLineIndex - this.insertedInCurrentBlock,
409 "\n".repeat(this.deletionBuffer.length - 1),
410 );
411
412 this.removedLineDecorations.addLines(
413 this.currentLineIndex - this.insertedInCurrentBlock,
414 this.deletionBuffer,
415 );
416
417 // Shift green decorations downward
418 this.addedLineDecorations.shiftDownAfterLine(
419 this.currentLineIndex - this.insertedInCurrentBlock,
420 this.deletionBuffer.length,
421 );
422
423 // Update line index, clear buffer
424 for (let i = 0; i < this.deletionBuffer.length; i++) {
425 this.incrementCurrentLineIndex();
426 }
427
428 this.deletionBuffer = [];
429 this.insertedInCurrentBlock = 0;
430 this.refreshCodeLens();
431 }
432
433 private incrementCurrentLineIndex() {
434 this.currentLineIndex++;
435 this.updateIndexLineDecorations();
436 const range = new vscode.Range(
437 this.currentLineIndex,
438 0,
439 this.currentLineIndex,
440 0,
441 );
442 this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
443 }
444
445 private async insertTextAboveLine(index: number, text: string) {
446 await this.editor.edit(
447 (editBuilder) => {
448 const lineCount = this.editor.document.lineCount;
449 if (index >= lineCount) {
450 // Append to end of file
451 editBuilder.insert(
452 new vscode.Position(
453 lineCount,
454 this.editor.document.lineAt(lineCount - 1).text.length,
455 ),
456 `\n${text}`,
457 );
458 } else {
459 editBuilder.insert(new vscode.Position(index, 0), `${text}\n`);
460 }
461 },
462 { undoStopAfter: false, undoStopBefore: false },
463 );
464 }
465
466 private async insertLineAboveIndex(index: number, line: string) {
467 await this.insertTextAboveLine(index, line);
468 this.addedLineDecorations.addLine(index);
469 this.newLinesAdded++;
470 }
471
472 private async deleteLinesAt(index: number, numLines = 1) {
473 const startLine = new vscode.Position(index, 0);
474 await this.editor.edit(
475 (editBuilder) => {
476 editBuilder.delete(
477 new vscode.Range(startLine, startLine.translate(numLines)),
478 );
479 },
480 { undoStopAfter: false, undoStopBefore: false },
481 );
482 }
483
484 private async deleteRangeLines(ranges: vscode.Range[]) {
485 await this.editor.edit(
486 (editBuilder) => {
487 for (const range of ranges) {
488 editBuilder.delete(
489 new vscode.Range(
490 range.start,
491 new vscode.Position(range.end.line + 1, 0),
492 ),
493 );
494 }
495 },
496 { undoStopAfter: false, undoStopBefore: false },
497 );
498 }
499
500 private updateIndexLineDecorations() {
501 if (this.options.instant) {
502 // We don't show progress on instant apply
503 return;
504 }
505
506 // Highlight the line at the currentLineIndex
507 // And lightly highlight all lines between that and endLine
508 if (this.currentLineIndex - this.newLinesAdded >= this.endLine) {
509 this.editor.setDecorations(indexDecorationType, []);
510 this.editor.setDecorations(belowIndexDecorationType, []);
511 } else {
512 const start = new vscode.Position(this.currentLineIndex, 0);
513 this.editor.setDecorations(indexDecorationType, [
514 new vscode.Range(
515 start,
516 new vscode.Position(start.line, Number.MAX_SAFE_INTEGER),
517 ),
518 ]);
519 const end = new vscode.Position(this.endLine, 0);
520 this.editor.setDecorations(belowIndexDecorationType, [
521 new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
522 ]);
523 }
524 }
525
526 private clearIndexLineDecorations() {
527 this.editor.setDecorations(belowIndexDecorationType, []);
528 this.editor.setDecorations(indexDecorationType, []);
529 }
530
531 private async _handleDiffLine(diffLine: DiffLine) {
532 switch (diffLine.type) {
533 case "same":
534 await this.insertDeletionBuffer();
535 this.incrementCurrentLineIndex();
536 break;
537 case "old":
538 // Add to deletion buffer and delete the line for now
539 this.deletionBuffer.push(diffLine.line);
540 await this.deleteLinesAt(this.currentLineIndex);
541 break;
542 case "new":
543 await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
544 this.incrementCurrentLineIndex();
545 this.insertedInCurrentBlock++;
546 break;
547 }
548 }
549
550 private shiftCodeLensObjects(startLine: number, offset: number) {
551 // Shift the codelens objects
552 const blocks =
553 this.editorToVerticalDiffCodeLens
554 .get(this.fileUri)
555 ?.filter((x) => x.start !== startLine)
556 .map((x) => {
557 if (x.start > startLine) {
558 return { ...x, start: x.start + offset };
559 }
560 return x;
561 }) || [];
562 this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
563
564 this.refreshCodeLens();
565 }
566
567 /**
568 * Gets the first line number that was changed in a diff
569 */
570 private getFirstChangedLine(diff: DiffLine[]): number | null {
571 for (let i = 0; i < diff.length; i++) {
572 const item = diff[i];
573 if (item.type === "old" || item.type === "new") {
574 return this.startLine + i;
575 }
576 }
577 return null;
578 }
579}