Elffuss BraidHub

kikocis/continue public

main · 15.7 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 isApply,
306 }: {
307 input: string;
308 llm: ILLM;
309 streamId?: string;
310 quickEdit?: string;
311 range?: vscode.Range;
312 newCode?: string;
313 toolCallId?: string;
314 rulesToInclude: undefined | RuleWithSource[];
315 isApply: boolean;
316 }): Promise<string | undefined> {
317 void vscode.commands.executeCommand(
318 "setContext",
319 "continue.diffVisible",
320 true,
321 );
322
323 let editor = vscode.window.activeTextEditor;
324
325 if (!editor) {
326 return undefined;
327 }
328
329 const fileUri = editor.document.uri.toString();
330
331 let startLine, endLine: number;
332
333 if (range) {
334 startLine = range.start.line;
335 endLine = range.end.line;
336 } else {
337 startLine = editor.selection.start.line;
338 endLine = editor.selection.end.line;
339 }
340
341 // Check for existing handlers in the same file the new one will be created in
342 const existingHandler = this.getHandlerForFile(fileUri);
343
344 if (existingHandler) {
345 if (quickEdit) {
346 // Previous diff was a quickEdit
347 // Check if user has highlighted a range
348 let rangeBool =
349 startLine !== endLine ||
350 editor.selection.start.character !== editor.selection.end.character;
351
352 // Check if the range is different from the previous range
353 let newRangeBool =
354 startLine !== existingHandler.range.start.line ||
355 endLine !== existingHandler.range.end.line;
356
357 if (!rangeBool || !newRangeBool) {
358 // User did not highlight a new range -> use start/end from the previous quickEdit
359 startLine = existingHandler.range.start.line;
360 endLine = existingHandler.range.end.line;
361 }
362 }
363
364 // Clear the previous handler
365 // This allows the user to edit above the changed area,
366 // but extra delta was added for each line generated by Continue
367 // Before adding this back, we need to distinguish between human and Continue
368 // let effectiveLineDelta =
369 // existingHandler.getLineDeltaBeforeLine(startLine);
370 // startLine += effectiveLineDelta;
371 // endLine += effectiveLineDelta;
372
373 await existingHandler.clear(false);
374 }
375
376 await new Promise((resolve) => {
377 setTimeout(resolve, 150);
378 });
379
380 // Create new handler with determined start/end
381 const diffHandler = this.createVerticalDiffHandler(
382 fileUri,
383 startLine,
384 endLine,
385 {
386 instant: isFastApplyModel(llm),
387 input,
388 onStatusUpdate: (status, numDiffs, fileContent) =>
389 streamId &&
390 void this.webviewProtocol.request("updateApplyState", {
391 streamId,
392 status,
393 numDiffs,
394 fileContent,
395 filepath: fileUri,
396 toolCallId,
397 }),
398 streamId,
399 },
400 );
401
402 if (!diffHandler) {
403 console.warn("Issue occurred while creating new vertical diff handler");
404 return undefined;
405 }
406
407 let selectedRange = diffHandler.range;
408
409 // Only if the selection is empty, use exact prefix/suffix instead of by line
410 if (selectedRange.isEmpty) {
411 selectedRange = new vscode.Range(
412 editor.selection.start.with(undefined, 0),
413 editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER),
414 );
415 }
416
417 const rangeContent = editor.document.getText(selectedRange);
418 const prefix = pruneLinesFromTop(
419 editor.document.getText(
420 new vscode.Range(new vscode.Position(0, 0), selectedRange.start),
421 ),
422 llm.contextLength / 4,
423 llm.model,
424 );
425 const suffix = pruneLinesFromBottom(
426 editor.document.getText(
427 new vscode.Range(
428 selectedRange.end,
429 new vscode.Position(editor.document.lineCount, 0),
430 ),
431 ),
432 llm.contextLength / 4,
433 llm.model,
434 );
435
436 let overridePrompt: ChatMessage[] | undefined;
437 if (llm.promptTemplates?.apply) {
438 const filepath = getLastNPathParts(fileUri, 1);
439 const rendered = llm.renderPromptTemplate(llm.promptTemplates.apply, [], {
440 original_code: rangeContent,
441 new_code: newCode ?? "",
442 filepath,
443 });
444 overridePrompt =
445 typeof rendered === "string"
446 ? [{ role: "user", content: rendered }]
447 : rendered;
448 }
449
450 if (editor.selection) {
451 // Unselect the range
452 editor.selection = new vscode.Selection(
453 editor.selection.active,
454 editor.selection.active,
455 );
456 }
457
458 void vscode.commands.executeCommand(
459 "setContext",
460 "continue.streamingDiff",
461 true,
462 );
463
464 this.editDecorationManager.clear();
465
466 const abortManager = ApplyAbortManager.getInstance();
467 const abortController = abortManager.get(fileUri);
468
469 try {
470 const streamedLines: string[] = [];
471
472 async function* recordedStream() {
473 const stream = streamDiffLines(
474 {
475 highlighted: rangeContent,
476 prefix,
477 suffix,
478 input,
479 language: getMarkdownLanguageTagForFile(fileUri),
480 type: isApply ? "apply" : "edit",
481 newCode: newCode ?? "",
482 includeRulesInSystemMessage: !!rulesToInclude && !isApply,
483 modelTitle: llm.title ?? llm.model,
484 },
485 llm,
486 abortController,
487 overridePrompt,
488 rulesToInclude,
489 );
490
491 for await (const line of stream) {
492 if (line.type === "new" || line.type === "same") {
493 streamedLines.push(line.line);
494 }
495 yield line;
496 }
497 }
498
499 this.logDiffs = await diffHandler.run(recordedStream());
500
501 // enable a listener for user edits to file while diff is open
502 this.enableDocumentChangeListener();
503
504 if (abortController.signal.aborted) {
505 void vscode.commands.executeCommand("continue.rejectDiff");
506 }
507
508 const fileAfterEdit = `${prefix}${streamedLines.join("\n")}${suffix}`;
509 await this.trackEditInteraction({
510 model: llm,
511 filepath: fileUri,
512 prompt: input,
513 fileAfterEdit,
514 });
515
516 return fileAfterEdit;
517 } catch (e) {
518 this.disableDocumentChangeListener();
519 const handled = await handleLLMError(e);
520 if (!handled) {
521 let message = "Error streaming edit diffs";
522 if (e instanceof Error) {
523 message += `: ${e.message}`;
524 }
525 throw new Error(message);
526 }
527 } finally {
528 void vscode.commands.executeCommand(
529 "setContext",
530 "continue.streamingDiff",
531 false,
532 );
533 }
534 }
535
536 async trackEditInteraction({
537 model,
538 filepath,
539 prompt,
540 fileAfterEdit,
541 }: {
542 model: ILLM;
543 filepath: string;
544 prompt: string;
545 fileAfterEdit: string | undefined;
546 }) {
547 // Get previous code content for outcome tracking
548 const previousCode = await this.ide.readFile(filepath);
549 const newCode = fileAfterEdit ?? "";
550 const previousCodeLines = previousCode.split("\n").length;
551 const newCodeLines = newCode.split("\n").length;
552 const lineChange = newCodeLines - previousCodeLines;
553
554 // Store pending edit data for outcome tracking
555 editOutcomeTracker.trackEditInteraction({
556 streamId: EDIT_MODE_STREAM_ID,
557 timestamp: new Date().toISOString(),
558 modelProvider: model.underlyingProviderName,
559 modelName: model.title ?? "",
560 modelTitle: model.title ?? "",
561 prompt: stripImages(prompt),
562 completion: newCode,
563 previousCode,
564 newCode,
565 filepath: filepath,
566 previousCodeLines,
567 newCodeLines,
568 lineChange,
569 });
570 }
571}