Elffuss BraidHub

kikocis/continue public

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