Elffuss BraidHub

kikocis/continue public

86e71fea71da · 22.2 KiBRawPermalink
1import { CompletionProvider } from "core/autocomplete/CompletionProvider";
2import { processSingleLineCompletion } from "core/autocomplete/util/processSingleLineCompletion";
3import {
4 type AutocompleteInput,
5 type AutocompleteOutcome,
6} from "core/autocomplete/util/types";
7import { ConfigHandler } from "core/config/ConfigHandler";
8import * as URI from "uri-js";
9import { v4 as uuidv4 } from "uuid";
10import * as vscode from "vscode";
11
12import { handleLLMError } from "../util/errorHandling";
13import { VsCodeIde } from "../VsCodeIde";
14import { VsCodeWebviewProtocol } from "../webviewProtocol";
15
16import { checkFim } from "core/nextEdit/diff/diff";
17import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService";
18import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue";
19import { NextEditProvider } from "core/nextEdit/NextEditProvider";
20import { NextEditOutcome } from "core/nextEdit/types";
21import { JumpManager } from "../activation/JumpManager";
22import { NextEditWindowManager } from "../activation/NextEditWindowManager";
23import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker";
24import { getDefinitionsFromLsp } from "./lsp";
25import { RecentlyEditedTracker } from "./recentlyEdited";
26import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService";
27import {
28 StatusBarStatus,
29 getStatusBarStatus,
30 setupStatusBar,
31 stopStatusBarLoading,
32} from "./statusBar";
33
34interface VsCodeCompletionInput {
35 document: vscode.TextDocument;
36 position: vscode.Position;
37 context: vscode.InlineCompletionContext;
38}
39
40export class ContinueCompletionProvider
41 implements vscode.InlineCompletionItemProvider
42{
43 private async onError(e: unknown) {
44 if (await handleLLMError(e)) {
45 return;
46 }
47 let message = "Continue Autocomplete Error";
48 if (e instanceof Error) {
49 message += `: ${e.message}`;
50 }
51 vscode.window.showErrorMessage(message, "Documentation").then((val) => {
52 if (val === "Documentation") {
53 vscode.env.openExternal(
54 vscode.Uri.parse(
55 "https://docs.continue.dev/features/tab-autocomplete",
56 ),
57 );
58 }
59 });
60 }
61
62 private completionProvider: CompletionProvider;
63 private nextEditProvider: NextEditProvider;
64 private nextEditLoggingService: NextEditLoggingService;
65 private jumpManager: JumpManager;
66 private prefetchQueue: PrefetchQueue;
67
68 public recentlyVisitedRanges: RecentlyVisitedRangesService;
69 public recentlyEditedTracker: RecentlyEditedTracker;
70
71 private isNextEditActive: boolean = false;
72 private usingFullFileDiff: boolean = true;
73
74 public activateNextEdit() {
75 this.isNextEditActive = true;
76 }
77
78 public deactivateNextEdit() {
79 this.isNextEditActive = false;
80 }
81
82 constructor(
83 private readonly configHandler: ConfigHandler,
84 private readonly ide: VsCodeIde,
85 private readonly webviewProtocol: VsCodeWebviewProtocol,
86 usingFullFileDiff: boolean,
87 ) {
88 this.usingFullFileDiff = usingFullFileDiff;
89 this.recentlyEditedTracker = new RecentlyEditedTracker(ide.ideUtils);
90
91 async function getAutocompleteModel() {
92 const { config } = await configHandler.loadConfig();
93 if (!config) {
94 return;
95 }
96 return config.selectedModelByRole.autocomplete ?? undefined;
97 }
98
99 this.completionProvider = new CompletionProvider(
100 this.configHandler,
101 this.ide,
102 getAutocompleteModel,
103 this.onError.bind(this),
104 getDefinitionsFromLsp,
105 );
106
107 // Logging service must be created first.
108 this.nextEditLoggingService = NextEditLoggingService.getInstance();
109 this.nextEditProvider = NextEditProvider.initialize(
110 this.configHandler,
111 this.ide,
112 getAutocompleteModel,
113 this.onError.bind(this),
114 getDefinitionsFromLsp,
115 "fineTuned",
116 );
117
118 this.jumpManager = JumpManager.getInstance();
119 this.prefetchQueue = PrefetchQueue.getInstance();
120 this.prefetchQueue.initialize(this.usingFullFileDiff);
121
122 this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide);
123 }
124
125 _lastShownCompletion: AutocompleteOutcome | NextEditOutcome | undefined;
126
127 private async getRerankModel() {
128 const { config } = await this.configHandler.loadConfig();
129 if (!config) {
130 return;
131 }
132 return config.selectedModelByRole.rerank ?? undefined;
133 }
134
135 /**
136 * Updates this class and the prefetch queue's usingFullFileDiff flag.
137 * @param usingFullFileDiff New value to set.
138 */
139 public updateUsingFullFileDiff(usingFullFileDiff: boolean) {
140 this.usingFullFileDiff = usingFullFileDiff;
141 this.prefetchQueue.initialize(this.usingFullFileDiff);
142 }
143
144 public async provideInlineCompletionItems(
145 document: vscode.TextDocument,
146 position: vscode.Position,
147 context: vscode.InlineCompletionContext,
148 token: vscode.CancellationToken,
149 //@ts-ignore
150 ): ProviderResult<InlineCompletionItem[] | InlineCompletionList> {
151 // This method is triggered on every keystroke, tab keypress, and cursor move.
152 // We need to determine why it was triggered:
153 // 1. Typing (chain doesn't exist)
154 // 2. Jumping (chain exists, jump was taken)
155 // 3. Accepting (chain exists, jump is not taken)
156
157 const enableTabAutocomplete =
158 getStatusBarStatus() === StatusBarStatus.Enabled;
159 if (token.isCancellationRequested || !enableTabAutocomplete) {
160 return null;
161 }
162
163 if (document.uri.scheme === "vscode-scm") {
164 return null;
165 }
166
167 const editor = vscode.window.activeTextEditor;
168 if (!editor) {
169 return undefined;
170 }
171 // Don't autocomplete with multi-cursor
172 if (editor && editor.selections.length > 1) {
173 return null;
174 }
175
176 const selectedCompletionInfo = context.selectedCompletionInfo;
177
178 // This code checks if there is a selected completion suggestion in the given context and ensures that it is valid
179 // To improve the accuracy of suggestions it checks if the user has typed at least 4 characters
180 // This helps refine and filter out irrelevant autocomplete options
181 if (selectedCompletionInfo) {
182 const { text, range } = selectedCompletionInfo;
183 const typedText = document.getText(range);
184
185 const typedLength = range.end.character - range.start.character;
186
187 if (typedLength < 4) {
188 return null;
189 }
190
191 if (!text.startsWith(typedText)) {
192 return null;
193 }
194 }
195 let injectDetails: string | undefined = undefined;
196
197 const currCursorPos = editor.selection.active;
198
199 try {
200 const abortController = new AbortController();
201 const signal = abortController.signal;
202 const completionId = uuidv4();
203
204 if (this.isNextEditActive) {
205 this.nextEditLoggingService.trackPendingCompletion(completionId);
206 }
207
208 token.onCancellationRequested(() => {
209 abortController.abort();
210 if (this.isNextEditActive) {
211 this.nextEditLoggingService.handleAbort(completionId);
212 }
213 });
214
215 // Handle notebook cells
216 let pos = {
217 line: position.line,
218 character: position.character,
219 };
220
221 let manuallyPassFileContents: string | undefined = undefined;
222 if (document.uri.scheme === "vscode-notebook-cell") {
223 const notebook = vscode.workspace.notebookDocuments.find((notebook) =>
224 notebook
225 .getCells()
226 .some((cell) =>
227 URI.equal(cell.document.uri.toString(), document.uri.toString()),
228 ),
229 );
230 if (notebook) {
231 const cells = notebook.getCells();
232 manuallyPassFileContents = cells
233 .map((cell) => {
234 const text = cell.document.getText();
235 if (cell.kind === vscode.NotebookCellKind.Markup) {
236 return `"""${text}"""`;
237 } else {
238 return text;
239 }
240 })
241 .join("\n\n");
242 for (const cell of cells) {
243 if (
244 URI.equal(cell.document.uri.toString(), document.uri.toString())
245 ) {
246 break;
247 } else {
248 pos.line += cell.document.getText().split("\n").length + 1;
249 }
250 }
251 }
252 }
253
254 // Manually pass file contents for unsaved, untitled files
255 if (document.isUntitled) {
256 manuallyPassFileContents = document.getText();
257 }
258
259 // Handle commit message input box
260 let manuallyPassPrefix: string | undefined = undefined;
261
262 // handle manual autocompletion trigger
263 const wasManuallyTriggered =
264 context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke;
265
266 // const completionId = uuidv4();
267 const filepath = document.uri.toString();
268 const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets();
269 let recentlyEditedRanges =
270 await this.recentlyEditedTracker.getRecentlyEditedRanges();
271
272 const ctx = {
273 completionId,
274 manuallyPassFileContents,
275 manuallyPassPrefix,
276 selectedCompletionInfo,
277 isUntitledFile: document.isUntitled,
278 recentlyVisitedRanges,
279 recentlyEditedRanges,
280 };
281
282 let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
283
284 // TODO: We can probably decide here if we want to do the jumping logic.
285 // If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager.
286 // It would simplify the logic quite substantially.
287
288 // Determine why this method was triggered.
289 const isJumping = this.jumpManager.isJumpInProgress();
290 const chainExists = this.nextEditProvider.chainExists();
291 console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
292 this.prefetchQueue.peekThreeProcessed();
293
294 if (isJumping && chainExists) {
295 // Case 2: Jumping (chain exists, jump was taken)
296 console.log("trigger reason: jumping");
297
298 // Reset jump state.
299 this.jumpManager.setJumpInProgress(false);
300
301 // Use the saved completion from JumpManager instead of dequeuing.
302 const savedCompletion = this.jumpManager.completionAfterJump;
303 if (savedCompletion) {
304 outcome = savedCompletion.outcome;
305 this.jumpManager.clearCompletionAfterJump();
306 } else {
307 // Fall back to prefetch queue. This technically should not happen.
308 console.error(
309 "Fell back to prefetch queue even after jump was taken",
310 );
311 outcome = this.prefetchQueue.dequeueProcessed()?.outcome;
312
313 // Fill in the spot after dequeuing.
314 if (!this.usingFullFileDiff) {
315 this.prefetchQueue.process({
316 ...ctx,
317 recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
318 recentlyEditedRanges:
319 await this.recentlyEditedTracker.getRecentlyEditedRanges(),
320 });
321 }
322 }
323 } else if (chainExists) {
324 // Case 3: Accepting next edit outcome (chain exists, jump is not taken).
325 console.log("trigger reason: accepting");
326
327 // Try suggesting jump for each location.
328 let isJumpSuggested = false;
329
330 while (this.prefetchQueue.processedCount > 0 && !isJumpSuggested) {
331 const nextItemInQueue = this.prefetchQueue.dequeueProcessed();
332 if (!nextItemInQueue) continue;
333
334 // Fill in the spot after dequeuing.
335 if (!this.usingFullFileDiff) {
336 this.prefetchQueue.process({
337 ...ctx,
338 recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
339 recentlyEditedRanges:
340 await this.recentlyEditedTracker.getRecentlyEditedRanges(),
341 });
342 }
343
344 const nextLocation = nextItemInQueue.location;
345 outcome = nextItemInQueue.outcome;
346
347 const jumpPosition = new vscode.Position(
348 nextLocation.range.start.line,
349 nextLocation.range.start.character,
350 );
351
352 isJumpSuggested = await this.jumpManager.suggestJump(
353 currCursorPos,
354 jumpPosition,
355 outcome.completion,
356 );
357
358 if (isJumpSuggested) {
359 // Store completion to be rendered after a jump.
360 this.jumpManager.setCompletionAfterJump({
361 completionId: completionId,
362 outcome,
363 currentPosition: jumpPosition,
364 });
365
366 // Don't display anything yet.
367 // This will be handled in Case 2.
368 return undefined;
369 }
370 }
371
372 if (!isJumpSuggested) {
373 console.log(
374 "No suitable jump location found after trying all positions",
375 );
376 this.nextEditProvider.deleteChain();
377 return undefined;
378 }
379 } else {
380 // Case 1: Typing (chain does not exist).
381
382 this.nextEditProvider.startChain();
383
384 const input: AutocompleteInput = {
385 pos,
386 filepath,
387 ...ctx,
388 };
389
390 setupStatusBar(undefined, true);
391
392 // Get initial completion.
393 if (this.isNextEditActive) {
394 outcome = await this.nextEditProvider.provideInlineCompletionItems(
395 input,
396 signal,
397 { withChain: false, usingFullFileDiff: this.usingFullFileDiff },
398 );
399
400 // Start prefetching next edits.
401 // NOTE: this might be better off not awaited.
402 if (!this.usingFullFileDiff) {
403 this.prefetchQueue.process(ctx);
404 }
405
406 // If initial outcome is null, suggest a jump instead.
407 // Calling this method again will call it with
408 // chain active but jump not suggested yet.
409 if (
410 !outcome ||
411 (!outcome.completion && outcome.diffLines.length === 0)
412 ) {
413 return this.provideInlineCompletionItems(
414 document,
415 position,
416 context,
417 token,
418 );
419 }
420 } else {
421 // Handle regular autocomplete request.
422 outcome = await this.completionProvider.provideInlineCompletionItems(
423 input,
424 signal,
425 wasManuallyTriggered,
426 );
427 }
428 }
429
430 // Return early if no valid outcome was found.
431 if (
432 !outcome ||
433 (!this.isNextEditActive &&
434 !(outcome as AutocompleteOutcome).completion) ||
435 (this.isNextEditActive &&
436 !(outcome as NextEditOutcome).completion &&
437 (outcome as NextEditOutcome).diffLines.length === 0)
438 ) {
439 return null;
440 }
441
442 // VS Code displays dependent on selectedCompletionInfo (their docstring below)
443 // We should first always make sure we have a valid completion, but if it goes wrong we
444 // want telemetry to be correct
445 /**
446 * Provides information about the currently selected item in the autocomplete widget if it is visible.
447 *
448 * If set, provided inline completions must extend the text of the selected item
449 * and use the same range, otherwise they are not shown as preview.
450 * As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document,
451 * the inline completion must also replace `.` and start with `.log`, for example `.log()`.
452 *
453 * Inline completion providers are requested again whenever the selected item changes.
454 */
455 if (selectedCompletionInfo) {
456 outcome.completion = selectedCompletionInfo.text + outcome.completion;
457 }
458 const willDisplay = this.willDisplay(
459 document,
460 selectedCompletionInfo,
461 signal,
462 outcome,
463 );
464 if (!willDisplay) {
465 return null;
466 }
467
468 // Marking the outcome as displayed saves the current outcome
469 // as a value of the key completionId.
470 if (this.isNextEditActive) {
471 this.nextEditProvider.markDisplayed(
472 completionId,
473 outcome as NextEditOutcome,
474 );
475 } else {
476 this.completionProvider.markDisplayed(
477 completionId,
478 outcome as AutocompleteOutcome,
479 );
480 }
481 this._lastShownCompletion = outcome;
482
483 // Construct the range/text to show
484 const startPos = selectedCompletionInfo?.range.start ?? position;
485 let range = new vscode.Range(startPos, startPos);
486 let completionText = outcome.completion;
487
488 const isSingleLineCompletion = outcome.completion.split("\n").length <= 1;
489
490 if (isSingleLineCompletion) {
491 const lastLineOfCompletionText = completionText.split("\n").pop() || "";
492 const currentText = document
493 .lineAt(startPos)
494 .text.substring(startPos.character);
495
496 const result = processSingleLineCompletion(
497 lastLineOfCompletionText,
498 currentText,
499 startPos.character,
500 );
501
502 if (result === undefined) {
503 return undefined;
504 }
505
506 completionText = result.completionText;
507 if (result.range) {
508 range = new vscode.Range(
509 new vscode.Position(startPos.line, result.range.start),
510 new vscode.Position(startPos.line, result.range.end),
511 );
512 }
513 } else {
514 // Extend the range to the end of the line for multiline completions
515 range = new vscode.Range(startPos, document.lineAt(startPos).range.end);
516 }
517
518 const autocompleteCompletionItem = new vscode.InlineCompletionItem(
519 completionText,
520 range,
521 {
522 title: "Log Autocomplete Outcome",
523 command: "continue.logAutocompleteOutcome",
524 arguments: [completionId, this.completionProvider],
525 },
526 );
527
528 (autocompleteCompletionItem as any).completeBracketPairs = true;
529
530 // Handle autocomplete request.
531 if (!this.isNextEditActive) {
532 return [autocompleteCompletionItem];
533 }
534
535 // Check the diff between old and new editable region.
536 const newEditRangeSlice = completionText;
537
538 // Get the contents of the old (current) editable region.
539 // const editableRegionStartLine = Math.max(
540 // currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
541 // 0,
542 // );
543 // const editableRegionEndLine = Math.min(
544 // currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
545 // editor.document.lineCount - 1,
546 // );
547 const editableRegionStartLine = (outcome as NextEditOutcome)
548 .editableRegionStartLine;
549 const editableRegionEndLine = (outcome as NextEditOutcome)
550 .editableRegionEndLine;
551 const oldEditRangeSlice = editor.document
552 .getText()
553 .split("\n")
554 .slice(editableRegionStartLine, editableRegionEndLine + 1)
555 .join("\n");
556
557 // We don't need to show the next edit window if the predicted edits are identical to the previous version.
558 if (oldEditRangeSlice === newEditRangeSlice) {
559 this.nextEditLoggingService.cancelRejectionTimeout(completionId);
560 return undefined;
561 }
562
563 // Create a cursor position relative to the edit range slice.
564 const relativeCursorPos = {
565 line: currCursorPos.line - editableRegionStartLine,
566 character: currCursorPos.character,
567 };
568
569 // If the diff is a FIM, render a ghost text.
570 const { isFim, fimText } = checkFim(
571 oldEditRangeSlice,
572 newEditRangeSlice,
573 relativeCursorPos,
574 );
575
576 if (isFim) {
577 if (!fimText) {
578 console.log("deleteChain from completionProvider.ts: !fimText");
579 this.nextEditProvider.deleteChain();
580 return undefined;
581 }
582
583 // Track this ghost text for acceptance detection.
584 // Ghost text acceptance can *technically* be acted upon in
585 // the command handler for "continue.logNextEditOutcomeAccept",
586 // but there is a substantial delay between accepting and logging,
587 // which introduces a lot of race conditions with different event handlers.
588 // Plus, separating these concerns seems to make sense logically as well.
589 GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance(
590 document,
591 fimText,
592 new vscode.Position(currCursorPos.line, currCursorPos.character),
593 );
594
595 const nextEditCompletionItem = new vscode.InlineCompletionItem(
596 fimText,
597 new vscode.Range(
598 new vscode.Position(currCursorPos.line, currCursorPos.character),
599 new vscode.Position(currCursorPos.line, currCursorPos.character),
600 ),
601 {
602 title: "Log Next Edit Outcome",
603 command: "continue.logNextEditOutcomeAccept",
604 arguments: [completionId, this.nextEditLoggingService],
605 },
606 );
607 return [nextEditCompletionItem];
608 }
609
610 // Handle non-FIM cases with the NextEditWindowManager.
611 const diffLines = (outcome as NextEditOutcome).diffLines;
612 if (diffLines.length === 0) {
613 // At this point, there is no way that diffLines.length === 0.
614 // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse.
615 // In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place.
616 // In case of initial response, we suggested a jump.
617 console.log(
618 "deleteChain from completionProvider.ts: diffLines.length === 0",
619 );
620 NextEditProvider.getInstance().deleteChain();
621 }
622
623 if (NextEditWindowManager.isInstantiated()) {
624 NextEditWindowManager.getInstance().updateCurrentCompletionId(
625 completionId,
626 );
627
628 await NextEditWindowManager.getInstance().showNextEditWindow(
629 editor,
630 currCursorPos,
631 editableRegionStartLine,
632 editableRegionEndLine,
633 oldEditRangeSlice,
634 newEditRangeSlice,
635 diffLines,
636 );
637 }
638
639 return undefined;
640 } finally {
641 stopStatusBarLoading();
642 }
643 }
644
645 willDisplay(
646 document: vscode.TextDocument,
647 selectedCompletionInfo: vscode.SelectedCompletionInfo | undefined,
648 abortSignal: AbortSignal,
649 outcome: AutocompleteOutcome | NextEditOutcome,
650 ): boolean {
651 if (selectedCompletionInfo) {
652 const { text, range } = selectedCompletionInfo;
653 if (!outcome.completion.startsWith(text)) {
654 console.log(
655 `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`,
656 range,
657 );
658 return false;
659 }
660 }
661
662 if (abortSignal.aborted) {
663 return false;
664 }
665
666 return true;
667 }
668}