Elffuss BraidHub

kikocis/continue public

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