Elffuss BraidHub

kikocis/continue public

600fc58ca200 · 15.3 KiBRawPermalink
1import { ChatMessage, DiffLine, IDE, ILLM, RuleWithSource } from "core";
2import { streamDiffLines } from "core/edit/streamDiffLines";
3import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
4import { getMarkdownLanguageTagForFile } from "core/util";
5import * as URI from "uri-js";
6import * as vscode from "vscode";
7
8import { isFastApplyModel } from "../../apply/utils";
9import EditDecorationManager from "../../quickEdit/EditDecorationManager";
10import { handleLLMError } from "../../util/errorHandling";
11import { VsCodeWebviewProtocol } from "../../webviewProtocol";
12
13import { ApplyAbortManager } from "core/edit/applyAbortManager";
14import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
15import { stripImages } from "core/util/messageContent";
16import { editOutcomeTracker } from "../../extension/EditOutcomeTracker";
17import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
18
19export interface VerticalDiffCodeLens {
20 start: number;
21 numRed: number;
22 numGreen: number;
23}
24
25export class VerticalDiffManager {
26 public refreshCodeLens: () => void = () => {};
27
28 private fileUriToHandler: Map<string, VerticalDiffHandler> = new Map();
29 fileUriToCodeLens: Map<string, VerticalDiffCodeLens[]> = new Map();
30
31 private userChangeListener: vscode.Disposable | undefined;
32
33 logDiffs: DiffLine[] | undefined;
34
35 constructor(
36 private readonly webviewProtocol: VsCodeWebviewProtocol,
37 private readonly editDecorationManager: EditDecorationManager,
38 private readonly ide: IDE,
39 ) {
40 this.userChangeListener = undefined;
41 }
42
43 createVerticalDiffHandler(
44 fileUri: string,
45 startLine: number,
46 endLine: number,
47 options: VerticalDiffHandlerOptions,
48 ): VerticalDiffHandler | undefined {
49 if (this.fileUriToHandler.has(fileUri)) {
50 this.fileUriToHandler.get(fileUri)?.clear(false);
51 this.fileUriToHandler.delete(fileUri);
52 }
53 const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files
54 if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
55 const handler = new VerticalDiffHandler(
56 startLine,
57 endLine,
58 editor,
59 this.fileUriToCodeLens,
60 this.clearForfileUri.bind(this),
61 this.refreshCodeLens,
62 options,
63 );
64 this.fileUriToHandler.set(fileUri, handler);
65 return handler;
66 } else {
67 return undefined;
68 }
69 }
70
71 getHandlerForFile(fileUri: string) {
72 return this.fileUriToHandler.get(fileUri);
73 }
74
75 getStreamIdForFile(fileUri: string): string | undefined {
76 return this.fileUriToHandler.get(fileUri)?.streamId;
77 }
78
79 // Creates a listener for document changes by user.
80 private enableDocumentChangeListener(): vscode.Disposable | undefined {
81 if (this.userChangeListener) {
82 //Only create one listener per file
83 return;
84 }
85
86 this.userChangeListener = vscode.workspace.onDidChangeTextDocument(
87 (event) => {
88 // Check if there is an active handler for the affected file
89 const fileUri = event.document.uri.toString();
90 const handler = this.getHandlerForFile(fileUri);
91 if (handler) {
92 // If there is an active diff for that file, handle the document change
93 this.handleDocumentChange(event, handler);
94 }
95 },
96 );
97 }
98
99 // Listener for user doc changes is disabled during updates to the text document by continue
100 public disableDocumentChangeListener() {
101 if (this.userChangeListener) {
102 this.userChangeListener.dispose();
103 this.userChangeListener = undefined;
104 }
105 }
106
107 private handleDocumentChange(
108 event: vscode.TextDocumentChangeEvent,
109 handler: VerticalDiffHandler,
110 ) {
111 // Loop through each change in the event
112 event.contentChanges.forEach((change) => {
113 // Calculate the number of lines added or removed
114 const linesAdded = change.text.split("\n").length - 1;
115 const linesDeleted = change.range.end.line - change.range.start.line;
116 const lineDelta = linesAdded - linesDeleted;
117
118 // Update the diff handler with the new line delta
119 handler.updateLineDelta(
120 event.document.uri.toString(),
121 change.range.start.line,
122 lineDelta,
123 );
124 });
125 }
126
127 clearForfileUri(fileUri: string | undefined, accept: boolean) {
128 if (!fileUri) {
129 const activeEditor = vscode.window.activeTextEditor;
130 if (!activeEditor) {
131 return;
132 }
133 fileUri = activeEditor.document.uri.toString();
134 }
135
136 const handler = this.fileUriToHandler.get(fileUri);
137 if (handler) {
138 handler.clear(accept);
139 this.fileUriToHandler.delete(fileUri);
140 }
141
142 this.disableDocumentChangeListener();
143
144 vscode.commands.executeCommand("setContext", "continue.diffVisible", false);
145 }
146
147 async acceptRejectVerticalDiffBlock(
148 accept: boolean,
149 fileUri?: string,
150 index?: number,
151 ) {
152 if (!fileUri) {
153 const activeEditor = vscode.window.activeTextEditor;
154 if (!activeEditor) {
155 return;
156 }
157 fileUri = activeEditor.document.uri.toString();
158 }
159
160 if (typeof index === "undefined") {
161 index = 0;
162 }
163
164 const blocks = this.fileUriToCodeLens.get(fileUri);
165 const block = blocks?.[index];
166 if (!blocks || !block) {
167 return;
168 }
169
170 const handler = this.getHandlerForFile(fileUri);
171 if (!handler) {
172 return;
173 }
174
175 // Disable listening to file changes while continue makes changes
176 this.disableDocumentChangeListener();
177
178 // CodeLens object removed from editorToVerticalDiffCodeLens here
179 await handler.acceptRejectBlock(
180 accept,
181 block.start,
182 block.numGreen,
183 block.numRed,
184 );
185
186 if (blocks.length === 1) {
187 this.clearForfileUri(fileUri, true);
188 } else {
189 // Re-enable listener for user changes to file
190 this.enableDocumentChangeListener();
191 }
192
193 this.refreshCodeLens();
194 }
195
196 async streamDiffLines(
197 diffStream: AsyncGenerator<DiffLine>,
198 instant: boolean,
199 streamId: string,
200 toolCallId?: string,
201 ) {
202 vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
203
204 // Get the current editor fileUri/range
205 let editor = vscode.window.activeTextEditor;
206 if (!editor) {
207 return;
208 }
209 const fileUri = editor.document.uri.toString();
210 const startLine = 0;
211 const endLine = editor.document.lineCount - 1;
212
213 // Check for existing handlers in the same file the new one will be created in
214 const existingHandler = this.getHandlerForFile(fileUri);
215 if (existingHandler) {
216 existingHandler.clear(false);
217 }
218
219 await new Promise((resolve) => {
220 setTimeout(resolve, 200);
221 });
222
223 // Create new handler with determined start/end
224 const diffHandler = this.createVerticalDiffHandler(
225 fileUri,
226 startLine,
227 endLine,
228 {
229 instant,
230 onStatusUpdate: (status, numDiffs, fileContent) =>
231 void this.webviewProtocol.request("updateApplyState", {
232 streamId,
233 status,
234 numDiffs,
235 fileContent,
236 filepath: fileUri,
237 toolCallId,
238 }),
239 streamId,
240 },
241 );
242
243 if (!diffHandler) {
244 console.warn("Issue occurred while creating new vertical diff handler");
245 return;
246 }
247
248 if (editor.selection) {
249 // Unselect the range
250 editor.selection = new vscode.Selection(
251 editor.selection.active,
252 editor.selection.active,
253 );
254 }
255
256 vscode.commands.executeCommand(
257 "setContext",
258 "continue.streamingDiff",
259 true,
260 );
261
262 try {
263 this.logDiffs = await diffHandler.run(diffStream);
264
265 // enable a listener for user edits to file while diff is open
266 this.enableDocumentChangeListener();
267 } catch (e) {
268 this.disableDocumentChangeListener();
269 const handled = await handleLLMError(e);
270 if (!handled) {
271 let message = "Error streaming diffs";
272 if (e instanceof Error) {
273 message += `: ${e.message}`;
274 }
275 throw new Error(message);
276 }
277 } finally {
278 vscode.commands.executeCommand(
279 "setContext",
280 "continue.streamingDiff",
281 false,
282 );
283 }
284 }
285
286 async streamEdit({
287 input,
288 llm,
289 streamId,
290 onlyOneInsertion,
291 quickEdit,
292 range,
293 newCode,
294 toolCallId,
295 rulesToInclude,
296 }: {
297 input: string;
298 llm: ILLM;
299 streamId?: string;
300 onlyOneInsertion?: boolean;
301 quickEdit?: string;
302 range?: vscode.Range;
303 newCode?: string;
304 toolCallId?: string;
305 rulesToInclude: undefined | RuleWithSource[];
306 }): Promise<string | undefined> {
307 void vscode.commands.executeCommand(
308 "setContext",
309 "continue.diffVisible",
310 true,
311 );
312
313 let editor = vscode.window.activeTextEditor;
314
315 if (!editor) {
316 return undefined;
317 }
318
319 const fileUri = editor.document.uri.toString();
320
321 let startLine, endLine: number;
322
323 if (range) {
324 startLine = range.start.line;
325 endLine = range.end.line;
326 } else {
327 startLine = editor.selection.start.line;
328 endLine = editor.selection.end.line;
329 }
330
331 // Check for existing handlers in the same file the new one will be created in
332 const existingHandler = this.getHandlerForFile(fileUri);
333
334 if (existingHandler) {
335 if (quickEdit) {
336 // Previous diff was a quickEdit
337 // Check if user has highlighted a range
338 let rangeBool =
339 startLine !== endLine ||
340 editor.selection.start.character !== editor.selection.end.character;
341
342 // Check if the range is different from the previous range
343 let newRangeBool =
344 startLine !== existingHandler.range.start.line ||
345 endLine !== existingHandler.range.end.line;
346
347 if (!rangeBool || !newRangeBool) {
348 // User did not highlight a new range -> use start/end from the previous quickEdit
349 startLine = existingHandler.range.start.line;
350 endLine = existingHandler.range.end.line;
351 }
352 }
353
354 // Clear the previous handler
355 // This allows the user to edit above the changed area,
356 // but extra delta was added for each line generated by Continue
357 // Before adding this back, we need to distinguish between human and Continue
358 // let effectiveLineDelta =
359 // existingHandler.getLineDeltaBeforeLine(startLine);
360 // startLine += effectiveLineDelta;
361 // endLine += effectiveLineDelta;
362
363 await existingHandler.clear(false);
364 }
365
366 await new Promise((resolve) => {
367 setTimeout(resolve, 150);
368 });
369
370 // Create new handler with determined start/end
371 const diffHandler = this.createVerticalDiffHandler(
372 fileUri,
373 startLine,
374 endLine,
375 {
376 instant: isFastApplyModel(llm),
377 input,
378 onStatusUpdate: (status, numDiffs, fileContent) =>
379 streamId &&
380 void this.webviewProtocol.request("updateApplyState", {
381 streamId,
382 status,
383 numDiffs,
384 fileContent,
385 filepath: fileUri,
386 toolCallId,
387 }),
388 streamId,
389 },
390 );
391
392 if (!diffHandler) {
393 console.warn("Issue occurred while creating new vertical diff handler");
394 return undefined;
395 }
396
397 let selectedRange = diffHandler.range;
398
399 // Only if the selection is empty, use exact prefix/suffix instead of by line
400 if (selectedRange.isEmpty) {
401 selectedRange = new vscode.Range(
402 editor.selection.start.with(undefined, 0),
403 editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER),
404 );
405 }
406
407 const rangeContent = editor.document.getText(selectedRange);
408 const prefix = pruneLinesFromTop(
409 editor.document.getText(
410 new vscode.Range(new vscode.Position(0, 0), selectedRange.start),
411 ),
412 llm.contextLength / 4,
413 llm.model,
414 );
415 const suffix = pruneLinesFromBottom(
416 editor.document.getText(
417 new vscode.Range(
418 selectedRange.end,
419 new vscode.Position(editor.document.lineCount, 0),
420 ),
421 ),
422 llm.contextLength / 4,
423 llm.model,
424 );
425
426 let overridePrompt: ChatMessage[] | undefined;
427 if (llm.promptTemplates?.apply) {
428 const rendered = llm.renderPromptTemplate(llm.promptTemplates.apply, [], {
429 original_code: rangeContent,
430 new_code: newCode ?? "",
431 });
432 overridePrompt =
433 typeof rendered === "string"
434 ? [{ role: "user", content: rendered }]
435 : rendered;
436 }
437
438 if (editor.selection) {
439 // Unselect the range
440 editor.selection = new vscode.Selection(
441 editor.selection.active,
442 editor.selection.active,
443 );
444 }
445
446 void vscode.commands.executeCommand(
447 "setContext",
448 "continue.streamingDiff",
449 true,
450 );
451
452 this.editDecorationManager.clear();
453
454 const abortManager = ApplyAbortManager.getInstance();
455 const abortController = abortManager.get(fileUri);
456
457 try {
458 const streamedLines: string[] = [];
459
460 async function* recordedStream() {
461 const stream = streamDiffLines({
462 highlighted: rangeContent,
463 prefix,
464 suffix,
465 llm,
466 rulesToInclude,
467 input,
468 language: getMarkdownLanguageTagForFile(fileUri),
469 onlyOneInsertion: !!onlyOneInsertion,
470 overridePrompt,
471 abortController,
472 });
473
474 for await (const line of stream) {
475 if (line.type === "new" || line.type === "same") {
476 streamedLines.push(line.line);
477 }
478 yield line;
479 }
480 }
481
482 this.logDiffs = await diffHandler.run(recordedStream());
483
484 // enable a listener for user edits to file while diff is open
485 this.enableDocumentChangeListener();
486
487 if (abortController.signal.aborted) {
488 void vscode.commands.executeCommand("continue.rejectDiff");
489 }
490
491 const fileAfterEdit = `${prefix}${streamedLines.join("\n")}${suffix}`;
492 await this.trackEditInteraction({
493 model: llm,
494 filepath: fileUri,
495 prompt: input,
496 fileAfterEdit,
497 });
498
499 return fileAfterEdit;
500 } catch (e) {
501 this.disableDocumentChangeListener();
502 const handled = await handleLLMError(e);
503 if (!handled) {
504 let message = "Error streaming edit diffs";
505 if (e instanceof Error) {
506 message += `: ${e.message}`;
507 }
508 throw new Error(message);
509 }
510 } finally {
511 void vscode.commands.executeCommand(
512 "setContext",
513 "continue.streamingDiff",
514 false,
515 );
516 }
517 }
518
519 async trackEditInteraction({
520 model,
521 filepath,
522 prompt,
523 fileAfterEdit,
524 }: {
525 model: ILLM;
526 filepath: string;
527 prompt: string;
528 fileAfterEdit: string | undefined;
529 }) {
530 // Get previous code content for outcome tracking
531 const previousCode = await this.ide.readFile(filepath);
532 const newCode = fileAfterEdit ?? "";
533 const previousCodeLines = previousCode.split("\n").length;
534 const newCodeLines = newCode.split("\n").length;
535 const lineChange = newCodeLines - previousCodeLines;
536
537 // Store pending edit data for outcome tracking
538 editOutcomeTracker.trackEditInteraction({
539 streamId: EDIT_MODE_STREAM_ID,
540 timestamp: new Date().toISOString(),
541 modelProvider: model.underlyingProviderName,
542 modelTitle: model.title ?? "",
543 prompt: stripImages(prompt),
544 completion: newCode,
545 previousCode,
546 newCode,
547 filepath: filepath,
548 previousCodeLines,
549 newCodeLines,
550 lineChange,
551 });
552 }
553}