Elffuss BraidHub

kikocis/continue public

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