Elffuss BraidHub

kikocis/continue public

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