Elffuss BraidHub

kikocis/continue public

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