Elffuss BraidHub

kikocis/continue public

736b2a5165fa · 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 { 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 void vscode.commands.executeCommand(
145 "setContext",
146 "continue.diffVisible",
147 false,
148 );
149
150 void this.webviewProtocol.request(
151 "focusContinueInputWithoutClear",
152 undefined,
153 );
154 }
155
156 async acceptRejectVerticalDiffBlock(
157 accept: boolean,
158 fileUri?: string,
159 index?: number,
160 ) {
161 if (!fileUri) {
162 const activeEditor = vscode.window.activeTextEditor;
163 if (!activeEditor) {
164 return;
165 }
166 fileUri = activeEditor.document.uri.toString();
167 }
168
169 if (typeof index === "undefined") {
170 index = 0;
171 }
172
173 const blocks = this.fileUriToCodeLens.get(fileUri);
174 const block = blocks?.[index];
175 if (!blocks || !block) {
176 return;
177 }
178
179 const handler = this.getHandlerForFile(fileUri);
180 if (!handler) {
181 return;
182 }
183
184 // Disable listening to file changes while continue makes changes
185 this.disableDocumentChangeListener();
186
187 // CodeLens object removed from editorToVerticalDiffCodeLens here
188 await handler.acceptRejectBlock(
189 accept,
190 block.start,
191 block.numGreen,
192 block.numRed,
193 );
194
195 if (blocks.length === 1) {
196 this.clearForfileUri(fileUri, true);
197 } else {
198 // Re-enable listener for user changes to file
199 this.enableDocumentChangeListener();
200 }
201
202 this.refreshCodeLens();
203 }
204
205 async streamDiffLines(
206 diffStream: AsyncGenerator<DiffLine>,
207 instant: boolean,
208 streamId: string,
209 toolCallId?: string,
210 ) {
211 vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
212
213 // Get the current editor fileUri/range
214 let editor = vscode.window.activeTextEditor;
215 if (!editor) {
216 return;
217 }
218 const fileUri = editor.document.uri.toString();
219 const startLine = 0;
220 const endLine = editor.document.lineCount - 1;
221
222 // Check for existing handlers in the same file the new one will be created in
223 const existingHandler = this.getHandlerForFile(fileUri);
224 if (existingHandler) {
225 existingHandler.clear(false);
226 }
227
228 await new Promise((resolve) => {
229 setTimeout(resolve, 200);
230 });
231
232 // Create new handler with determined start/end
233 const diffHandler = this.createVerticalDiffHandler(
234 fileUri,
235 startLine,
236 endLine,
237 {
238 instant,
239 onStatusUpdate: (status, numDiffs, fileContent) =>
240 void this.webviewProtocol.request("updateApplyState", {
241 streamId,
242 status,
243 numDiffs,
244 fileContent,
245 filepath: fileUri,
246 toolCallId,
247 }),
248 streamId,
249 },
250 );
251
252 if (!diffHandler) {
253 console.warn("Issue occurred while creating new vertical diff handler");
254 return;
255 }
256
257 if (editor.selection) {
258 // Unselect the range
259 editor.selection = new vscode.Selection(
260 editor.selection.active,
261 editor.selection.active,
262 );
263 }
264
265 vscode.commands.executeCommand(
266 "setContext",
267 "continue.streamingDiff",
268 true,
269 );
270
271 try {
272 this.logDiffs = await diffHandler.run(diffStream);
273
274 // enable a listener for user edits to file while diff is open
275 this.enableDocumentChangeListener();
276 } catch (e) {
277 this.disableDocumentChangeListener();
278 const handled = await handleLLMError(e);
279 if (!handled) {
280 let message = "Error streaming diffs";
281 if (e instanceof Error) {
282 message += `: ${e.message}`;
283 }
284 throw new Error(message);
285 }
286 } finally {
287 vscode.commands.executeCommand(
288 "setContext",
289 "continue.streamingDiff",
290 false,
291 );
292 }
293 }
294
295 async streamEdit({
296 input,
297 llm,
298 streamId,
299 quickEdit,
300 range,
301 newCode,
302 toolCallId,
303 rulesToInclude,
304 }: {
305 input: string;
306 llm: ILLM;
307 streamId?: string;
308 quickEdit?: string;
309 range?: vscode.Range;
310 newCode?: string;
311 toolCallId?: string;
312 rulesToInclude: undefined | RuleWithSource[];
313 }): Promise<string | undefined> {
314 void vscode.commands.executeCommand(
315 "setContext",
316 "continue.diffVisible",
317 true,
318 );
319
320 let editor = vscode.window.activeTextEditor;
321
322 if (!editor) {
323 return undefined;
324 }
325
326 const fileUri = editor.document.uri.toString();
327
328 let startLine, endLine: number;
329
330 if (range) {
331 startLine = range.start.line;
332 endLine = range.end.line;
333 } else {
334 startLine = editor.selection.start.line;
335 endLine = editor.selection.end.line;
336 }
337
338 // Check for existing handlers in the same file the new one will be created in
339 const existingHandler = this.getHandlerForFile(fileUri);
340
341 if (existingHandler) {
342 if (quickEdit) {
343 // Previous diff was a quickEdit
344 // Check if user has highlighted a range
345 let rangeBool =
346 startLine !== endLine ||
347 editor.selection.start.character !== editor.selection.end.character;
348
349 // Check if the range is different from the previous range
350 let newRangeBool =
351 startLine !== existingHandler.range.start.line ||
352 endLine !== existingHandler.range.end.line;
353
354 if (!rangeBool || !newRangeBool) {
355 // User did not highlight a new range -> use start/end from the previous quickEdit
356 startLine = existingHandler.range.start.line;
357 endLine = existingHandler.range.end.line;
358 }
359 }
360
361 // Clear the previous handler
362 // This allows the user to edit above the changed area,
363 // but extra delta was added for each line generated by Continue
364 // Before adding this back, we need to distinguish between human and Continue
365 // let effectiveLineDelta =
366 // existingHandler.getLineDeltaBeforeLine(startLine);
367 // startLine += effectiveLineDelta;
368 // endLine += effectiveLineDelta;
369
370 await existingHandler.clear(false);
371 }
372
373 await new Promise((resolve) => {
374 setTimeout(resolve, 150);
375 });
376
377 // Create new handler with determined start/end
378 const diffHandler = this.createVerticalDiffHandler(
379 fileUri,
380 startLine,
381 endLine,
382 {
383 instant: isFastApplyModel(llm),
384 input,
385 onStatusUpdate: (status, numDiffs, fileContent) =>
386 streamId &&
387 void this.webviewProtocol.request("updateApplyState", {
388 streamId,
389 status,
390 numDiffs,
391 fileContent,
392 filepath: fileUri,
393 toolCallId,
394 }),
395 streamId,
396 },
397 );
398
399 if (!diffHandler) {
400 console.warn("Issue occurred while creating new vertical diff handler");
401 return undefined;
402 }
403
404 let selectedRange = diffHandler.range;
405
406 // Only if the selection is empty, use exact prefix/suffix instead of by line
407 if (selectedRange.isEmpty) {
408 selectedRange = new vscode.Range(
409 editor.selection.start.with(undefined, 0),
410 editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER),
411 );
412 }
413
414 const rangeContent = editor.document.getText(selectedRange);
415 const prefix = pruneLinesFromTop(
416 editor.document.getText(
417 new vscode.Range(new vscode.Position(0, 0), selectedRange.start),
418 ),
419 llm.contextLength / 4,
420 llm.model,
421 );
422 const suffix = pruneLinesFromBottom(
423 editor.document.getText(
424 new vscode.Range(
425 selectedRange.end,
426 new vscode.Position(editor.document.lineCount, 0),
427 ),
428 ),
429 llm.contextLength / 4,
430 llm.model,
431 );
432
433 let overridePrompt: ChatMessage[] | undefined;
434 if (llm.promptTemplates?.apply) {
435 const rendered = llm.renderPromptTemplate(llm.promptTemplates.apply, [], {
436 original_code: rangeContent,
437 new_code: newCode ?? "",
438 });
439 overridePrompt =
440 typeof rendered === "string"
441 ? [{ role: "user", content: rendered }]
442 : rendered;
443 }
444
445 if (editor.selection) {
446 // Unselect the range
447 editor.selection = new vscode.Selection(
448 editor.selection.active,
449 editor.selection.active,
450 );
451 }
452
453 void vscode.commands.executeCommand(
454 "setContext",
455 "continue.streamingDiff",
456 true,
457 );
458
459 this.editDecorationManager.clear();
460
461 const abortManager = ApplyAbortManager.getInstance();
462 const abortController = abortManager.get(fileUri);
463
464 try {
465 const streamedLines: string[] = [];
466
467 async function* recordedStream() {
468 const stream = streamDiffLines({
469 highlighted: rangeContent,
470 prefix,
471 suffix,
472 llm,
473 rulesToInclude,
474 input,
475 language: getMarkdownLanguageTagForFile(fileUri),
476 overridePrompt,
477 abortController,
478 });
479
480 for await (const line of stream) {
481 if (line.type === "new" || line.type === "same") {
482 streamedLines.push(line.line);
483 }
484 yield line;
485 }
486 }
487
488 this.logDiffs = await diffHandler.run(recordedStream());
489
490 // enable a listener for user edits to file while diff is open
491 this.enableDocumentChangeListener();
492
493 if (abortController.signal.aborted) {
494 void vscode.commands.executeCommand("continue.rejectDiff");
495 }
496
497 const fileAfterEdit = `${prefix}${streamedLines.join("\n")}${suffix}`;
498 await this.trackEditInteraction({
499 model: llm,
500 filepath: fileUri,
501 prompt: input,
502 fileAfterEdit,
503 });
504
505 return fileAfterEdit;
506 } catch (e) {
507 this.disableDocumentChangeListener();
508 const handled = await handleLLMError(e);
509 if (!handled) {
510 let message = "Error streaming edit diffs";
511 if (e instanceof Error) {
512 message += `: ${e.message}`;
513 }
514 throw new Error(message);
515 }
516 } finally {
517 void vscode.commands.executeCommand(
518 "setContext",
519 "continue.streamingDiff",
520 false,
521 );
522 }
523 }
524
525 async trackEditInteraction({
526 model,
527 filepath,
528 prompt,
529 fileAfterEdit,
530 }: {
531 model: ILLM;
532 filepath: string;
533 prompt: string;
534 fileAfterEdit: string | undefined;
535 }) {
536 // Get previous code content for outcome tracking
537 const previousCode = await this.ide.readFile(filepath);
538 const newCode = fileAfterEdit ?? "";
539 const previousCodeLines = previousCode.split("\n").length;
540 const newCodeLines = newCode.split("\n").length;
541 const lineChange = newCodeLines - previousCodeLines;
542
543 // Store pending edit data for outcome tracking
544 editOutcomeTracker.trackEditInteraction({
545 streamId: EDIT_MODE_STREAM_ID,
546 timestamp: new Date().toISOString(),
547 modelProvider: model.underlyingProviderName,
548 modelName: model.title ?? "",
549 modelTitle: model.title ?? "",
550 prompt: stripImages(prompt),
551 completion: newCode,
552 previousCode,
553 newCode,
554 filepath: filepath,
555 previousCodeLines,
556 newCodeLines,
557 lineChange,
558 });
559 }
560}