Elffuss BraidHub

kikocis/continue public

d1cdc8b8ac2b · 25.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 /**
145 * This is the entry point to the autocomplete and next edit logic.
146 * @param document The text document containing the current cursor position.
147 * @param position The current cursor position.
148 * @param context Contextual information about the inline completion request.
149 */
150 public async provideInlineCompletionItems(
151 document: vscode.TextDocument,
152 position: vscode.Position,
153 context: vscode.InlineCompletionContext,
154 token: vscode.CancellationToken,
155 //@ts-ignore
156 ): ProviderResult<InlineCompletionItem[] | InlineCompletionList> {
157 // This method is triggered on every keystroke, tab keypress, and cursor move.
158 // We need to determine why it was triggered:
159 // 1. Typing (chain doesn't exist)
160 // 2. Jumping (chain exists, jump was taken)
161 // 3. Accepting (chain exists, jump is not taken)
162
163 /* START OF CONTEXT GATHERING BOILERPLATE */
164
165 // The code in this block is meant for gathering context for autocomplete and next edit requests.
166 // e.g. filepath, cursor position, editor, notebook-ness, etc.
167
168 const enableTabAutocomplete =
169 getStatusBarStatus() === StatusBarStatus.Enabled;
170 if (token.isCancellationRequested || !enableTabAutocomplete) {
171 return null;
172 }
173
174 if (document.uri.scheme === "vscode-scm") {
175 return null;
176 }
177
178 const editor = vscode.window.activeTextEditor;
179 if (!editor) {
180 return undefined;
181 }
182 // Don't autocomplete with multi-cursor
183 if (editor && editor.selections.length > 1) {
184 return null;
185 }
186
187 const selectedCompletionInfo = context.selectedCompletionInfo;
188
189 // This code checks if there is a selected completion suggestion in the given context and ensures that it is valid
190 // To improve the accuracy of suggestions it checks if the user has typed at least 4 characters
191 // This helps refine and filter out irrelevant autocomplete options
192 if (selectedCompletionInfo) {
193 const { text, range } = selectedCompletionInfo;
194 const typedText = document.getText(range);
195
196 const typedLength = range.end.character - range.start.character;
197
198 if (typedLength < 4) {
199 return null;
200 }
201
202 if (!text.startsWith(typedText)) {
203 return null;
204 }
205 }
206 let injectDetails: string | undefined = undefined;
207
208 const currCursorPos = editor.selection.active;
209
210 try {
211 const abortController = new AbortController();
212 const signal = abortController.signal;
213 const completionId = uuidv4();
214
215 if (this.isNextEditActive) {
216 this.nextEditLoggingService.trackPendingCompletion(completionId);
217 }
218
219 token.onCancellationRequested(() => {
220 abortController.abort();
221 if (this.isNextEditActive) {
222 this.nextEditLoggingService.handleAbort(completionId);
223 }
224 });
225
226 // Handle notebook cells
227 let pos = {
228 line: position.line,
229 character: position.character,
230 };
231
232 let manuallyPassFileContents: string | undefined = undefined;
233 if (document.uri.scheme === "vscode-notebook-cell") {
234 const notebook = vscode.workspace.notebookDocuments.find((notebook) =>
235 notebook
236 .getCells()
237 .some((cell) =>
238 URI.equal(cell.document.uri.toString(), document.uri.toString()),
239 ),
240 );
241 if (notebook) {
242 const cells = notebook.getCells();
243 manuallyPassFileContents = cells
244 .map((cell) => {
245 const text = cell.document.getText();
246 if (cell.kind === vscode.NotebookCellKind.Markup) {
247 return `"""${text}"""`;
248 } else {
249 return text;
250 }
251 })
252 .join("\n\n");
253 for (const cell of cells) {
254 if (
255 URI.equal(cell.document.uri.toString(), document.uri.toString())
256 ) {
257 break;
258 } else {
259 pos.line += cell.document.getText().split("\n").length + 1;
260 }
261 }
262 }
263 }
264
265 // Manually pass file contents for unsaved, untitled files
266 if (document.isUntitled) {
267 manuallyPassFileContents = document.getText();
268 }
269
270 // Handle commit message input box
271 let manuallyPassPrefix: string | undefined = undefined;
272
273 // handle manual autocompletion trigger
274 const wasManuallyTriggered =
275 context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke;
276
277 // const completionId = uuidv4();
278 const filepath = document.uri.toString();
279 const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets();
280 let recentlyEditedRanges =
281 await this.recentlyEditedTracker.getRecentlyEditedRanges();
282
283 const ctx = {
284 completionId,
285 manuallyPassFileContents,
286 manuallyPassPrefix,
287 selectedCompletionInfo,
288 isUntitledFile: document.isUntitled,
289 recentlyVisitedRanges,
290 recentlyEditedRanges,
291 };
292
293 /* END OF CONTEXT GATHERING BOILERPLATE */
294
295 /* START OF MODEL OUTCOME RECEIVING BLOCK */
296
297 // Throughout this function, we choose whether we want an autocomplete or a next edit request.
298 // The conditional logic below is pretty convoluted, so it would be a good idea to refactor.
299 // The idea was to re-use as much code as possible, but in hindsight I should've just made different functions.
300 // this.isNextEditActive is the boolean that determines whether we use autocomplete vs. next edit.
301
302 // You will also see mentions of this.usingFullFileDiff.
303 // This was initially a flag for whether we should let the model output a full file as an output (or to the best of its abilities).
304 // It ended up becoming a Mercury Coder vs. non-Mercury Coder flag, and is now used to determine whether we should prefetch next edits.
305 // This is a good place to refactor on.
306 // In the future, it will be desirable to have a map where we split models into different next edit requirements and capabilities,
307 // Then use the model's name to retrieve all of its requirements (or better yet, have a model-specific logic inside children class).
308
309 // Prefetching is also a relic of the past.
310 // Before, I envisioned that we should call the model in the background to get next next edits.
311 // Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea.
312
313 let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
314
315 // TODO: We can probably decide here if we want to do the jumping logic.
316 // If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager.
317 // It would simplify the logic quite substantially.
318
319 // Here, we introduce the concept of jumping and chains.
320 // Jump and chain are next edit-specific concepts, and autocomplete has nothing to do with it.
321 // Next edit is rendered to the users in three modes:
322 // 1. Default. This is the case where the user either hasn't seen a next edit suggestion, or has rejected the previous one.
323 // We would render either a ghost text or an SVG with deletion decoration.
324
325 // 2. Jumping. This is the case where the user has just accepted a suggestion, and there are more suggestions in the chain to jump to.
326 // We would render a Jump label suggesting the user to take the jump or reject.
327
328 // 3. Jumped. This is when the user just accepted the jump.
329 // We grab the next edit suggestion from the chain and render that instead of calling the model.
330
331 // Determine why this method was triggered.
332 const isJumping = this.jumpManager.isJumpInProgress();
333 const chainExists = this.nextEditProvider.chainExists();
334 console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
335 this.prefetchQueue.peekThreeProcessed();
336
337 if (isJumping && chainExists) {
338 // Case 2: Jumping (chain exists, jump was taken)
339 console.log("trigger reason: jumping");
340
341 // Reset jump state.
342 this.jumpManager.setJumpInProgress(false);
343
344 // Use the saved completion from JumpManager instead of dequeuing.
345 const savedCompletion = this.jumpManager.completionAfterJump;
346 if (savedCompletion) {
347 outcome = savedCompletion.outcome;
348 this.jumpManager.clearCompletionAfterJump();
349 } else {
350 // Fall back to prefetch queue. This technically should not happen.
351 console.error(
352 "Fell back to prefetch queue even after jump was taken",
353 );
354 outcome = this.prefetchQueue.dequeueProcessed()?.outcome;
355
356 // Fill in the spot after dequeuing.
357 if (!this.usingFullFileDiff) {
358 this.prefetchQueue.process({
359 ...ctx,
360 recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
361 recentlyEditedRanges:
362 await this.recentlyEditedTracker.getRecentlyEditedRanges(),
363 });
364 }
365 }
366 } else if (chainExists) {
367 // Case 3: Accepting next edit outcome (chain exists, jump is not taken).
368 console.log("trigger reason: accepting");
369
370 // Try suggesting jump for each location.
371 let isJumpSuggested = false;
372
373 while (this.prefetchQueue.processedCount > 0 && !isJumpSuggested) {
374 const nextItemInQueue = this.prefetchQueue.dequeueProcessed();
375 if (!nextItemInQueue) continue;
376
377 // Fill in the spot after dequeuing.
378 if (!this.usingFullFileDiff) {
379 this.prefetchQueue.process({
380 ...ctx,
381 recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
382 recentlyEditedRanges:
383 await this.recentlyEditedTracker.getRecentlyEditedRanges(),
384 });
385 }
386
387 const nextLocation = nextItemInQueue.location;
388 outcome = nextItemInQueue.outcome;
389
390 const jumpPosition = new vscode.Position(
391 nextLocation.range.start.line,
392 nextLocation.range.start.character,
393 );
394
395 isJumpSuggested = await this.jumpManager.suggestJump(
396 currCursorPos,
397 jumpPosition,
398 outcome.completion,
399 );
400
401 if (isJumpSuggested) {
402 // Store completion to be rendered after a jump.
403 this.jumpManager.setCompletionAfterJump({
404 completionId: completionId,
405 outcome,
406 currentPosition: jumpPosition,
407 });
408
409 // Don't display anything yet. This will be handled in Case 2.
410 // Recall from above that provideInlineCompletions runs on every cursor movement.
411 return undefined;
412 }
413 }
414
415 if (!isJumpSuggested) {
416 console.log(
417 "No suitable jump location found after trying all positions",
418 );
419 this.nextEditProvider.deleteChain();
420 return undefined;
421 }
422 } else {
423 // Case 1: Typing (chain does not exist).
424 this.nextEditProvider.startChain();
425
426 const input: AutocompleteInput = {
427 pos,
428 filepath,
429 ...ctx,
430 };
431
432 setupStatusBar(undefined, true);
433
434 // Get initial completion.
435 if (this.isNextEditActive) {
436 outcome = await this.nextEditProvider.provideInlineCompletionItems(
437 input,
438 signal,
439 { withChain: false, usingFullFileDiff: this.usingFullFileDiff },
440 );
441
442 // Start prefetching next edits if not using full file diff.
443 // NOTE: this is better off not awaited. fire and forget.
444 if (!this.usingFullFileDiff) {
445 this.prefetchQueue.process(ctx);
446 }
447
448 // If initial outcome is null, suggest a jump instead.
449 // Calling this method again will call it with chain active but jump not suggested yet.
450 if (
451 !outcome ||
452 (!outcome.completion && outcome.diffLines.length === 0)
453 ) {
454 return this.provideInlineCompletionItems(
455 document,
456 position,
457 context,
458 token,
459 );
460 }
461 } else {
462 // Handle regular autocomplete request.
463 outcome = await this.completionProvider.provideInlineCompletionItems(
464 input,
465 signal,
466 wasManuallyTriggered,
467 );
468 }
469 }
470
471 // Return early if no valid outcome was found.
472 if (
473 !outcome ||
474 (!this.isNextEditActive &&
475 !(outcome as AutocompleteOutcome).completion) ||
476 (this.isNextEditActive &&
477 !(outcome as NextEditOutcome).completion &&
478 (outcome as NextEditOutcome).diffLines.length === 0)
479 ) {
480 return null;
481 }
482
483 // VS Code displays dependent on selectedCompletionInfo (their docstring below)
484 // We should first always make sure we have a valid completion, but if it goes wrong we
485 // want telemetry to be correct
486 /**
487 * Provides information about the currently selected item in the autocomplete widget if it is visible.
488 *
489 * If set, provided inline completions must extend the text of the selected item
490 * and use the same range, otherwise they are not shown as preview.
491 * As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document,
492 * the inline completion must also replace `.` and start with `.log`, for example `.log()`.
493 *
494 * Inline completion providers are requested again whenever the selected item changes.
495 */
496 if (selectedCompletionInfo) {
497 outcome.completion = selectedCompletionInfo.text + outcome.completion;
498 }
499 const willDisplay = this.willDisplay(
500 document,
501 selectedCompletionInfo,
502 signal,
503 outcome,
504 );
505 if (!willDisplay) {
506 return null;
507 }
508
509 // Marking the outcome as displayed saves the current outcome as a value of the key completionId.
510 // NOTE: It seems like autocomplete relies on this to be considered accepted.
511 if (this.isNextEditActive) {
512 this.nextEditProvider.markDisplayed(
513 completionId,
514 outcome as NextEditOutcome,
515 );
516 } else {
517 this.completionProvider.markDisplayed(
518 completionId,
519 outcome as AutocompleteOutcome,
520 );
521 }
522 this._lastShownCompletion = outcome;
523
524 /* END OF MODEL OUTCOME RECEIVING BLOCK */
525
526 /* START OF RENDERING BLOCK */
527
528 // Here we determine how to render the outcome received in the previous block.
529 // We check whether the outcome is a FIM completion or not.
530 // If FIM, we render a ghost text, and an SVG + deletion decoration if not.
531 // If we are using autocomplete instead of next edit, we just render a ghost text.
532
533 // Construct the range/text to show
534 const startPos = selectedCompletionInfo?.range.start ?? position;
535 let range = new vscode.Range(startPos, startPos);
536 let completionText = outcome.completion;
537
538 const isSingleLineCompletion = outcome.completion.split("\n").length <= 1;
539
540 if (isSingleLineCompletion) {
541 const lastLineOfCompletionText = completionText.split("\n").pop() || "";
542 const currentText = document
543 .lineAt(startPos)
544 .text.substring(startPos.character);
545
546 const result = processSingleLineCompletion(
547 lastLineOfCompletionText,
548 currentText,
549 startPos.character,
550 );
551
552 if (result === undefined) {
553 return undefined;
554 }
555
556 completionText = result.completionText;
557 if (result.range) {
558 range = new vscode.Range(
559 new vscode.Position(startPos.line, result.range.start),
560 new vscode.Position(startPos.line, result.range.end),
561 );
562 }
563 } else {
564 // Extend the range to the end of the line for multiline completions
565 range = new vscode.Range(startPos, document.lineAt(startPos).range.end);
566 }
567
568 const autocompleteCompletionItem = new vscode.InlineCompletionItem(
569 completionText,
570 range,
571 {
572 title: "Log Autocomplete Outcome",
573 command: "continue.logAutocompleteOutcome",
574 arguments: [completionId, this.completionProvider],
575 },
576 );
577
578 (autocompleteCompletionItem as any).completeBracketPairs = true;
579
580 // Handle autocomplete request.
581 if (!this.isNextEditActive) {
582 return [autocompleteCompletionItem];
583 }
584
585 // Check the diff between old and new editable region.
586 const newEditRangeSlice = completionText;
587
588 // Get the contents of the old (current) editable region.
589 const editableRegionStartLine = (outcome as NextEditOutcome)
590 .editableRegionStartLine;
591 const editableRegionEndLine = (outcome as NextEditOutcome)
592 .editableRegionEndLine;
593 const oldEditRangeSlice = editor.document
594 .getText()
595 .split("\n")
596 .slice(editableRegionStartLine, editableRegionEndLine + 1)
597 .join("\n");
598
599 // We don't need to show the next edit window if the predicted edits are identical to the previous version.
600 if (oldEditRangeSlice === newEditRangeSlice) {
601 this.nextEditLoggingService.cancelRejectionTimeout(completionId);
602 return undefined;
603 }
604
605 // Create a cursor position relative to the edit range slice.
606 const relativeCursorPos = {
607 line: currCursorPos.line - editableRegionStartLine,
608 character: currCursorPos.character,
609 };
610
611 // If the diff is a FIM, render a ghost text.
612 const { isFim, fimText } = checkFim(
613 oldEditRangeSlice,
614 newEditRangeSlice,
615 relativeCursorPos,
616 );
617
618 if (isFim) {
619 if (!fimText) {
620 console.log("deleteChain from completionProvider.ts: !fimText");
621 this.nextEditProvider.deleteChain();
622 return undefined;
623 }
624
625 // Track this ghost text for acceptance detection.
626 // Ghost text acceptance can *technically* be acted upon in the command handler for "continue.logNextEditOutcomeAccept".
627 // However, there is a substantial delay between accepting and logging, which introduces a lot of race conditions with different event handlers.
628 // Plus, separating these concerns seems to make sense logically as well.
629 GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance(
630 document,
631 fimText,
632 new vscode.Position(currCursorPos.line, currCursorPos.character),
633 );
634
635 const nextEditCompletionItem = new vscode.InlineCompletionItem(
636 fimText,
637 new vscode.Range(
638 new vscode.Position(currCursorPos.line, currCursorPos.character),
639 new vscode.Position(currCursorPos.line, currCursorPos.character),
640 ),
641 {
642 title: "Log Next Edit Outcome",
643 command: "continue.logNextEditOutcomeAccept",
644 arguments: [completionId, this.nextEditLoggingService],
645 },
646 );
647 return [nextEditCompletionItem];
648 }
649
650 // Handle non-FIM cases with the NextEditWindowManager.
651 const diffLines = (outcome as NextEditOutcome).diffLines;
652 if (diffLines.length === 0) {
653 // At this point, there is no way that diffLines.length === 0.
654 // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse.
655 // In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place.
656 // In case of initial response, we suggested a jump.
657 console.log(
658 "deleteChain from completionProvider.ts: diffLines.length === 0",
659 );
660 NextEditProvider.getInstance().deleteChain();
661 }
662
663 if (NextEditWindowManager.isInstantiated()) {
664 NextEditWindowManager.getInstance().updateCurrentCompletionId(
665 completionId,
666 );
667
668 await NextEditWindowManager.getInstance().showNextEditWindow(
669 editor,
670 currCursorPos,
671 editableRegionStartLine,
672 editableRegionEndLine,
673 oldEditRangeSlice,
674 newEditRangeSlice,
675 diffLines,
676 );
677 }
678
679 return undefined;
680 } finally {
681 stopStatusBarLoading();
682 }
683
684 /* END OF RENDERING BLOCK */
685 }
686
687 willDisplay(
688 document: vscode.TextDocument,
689 selectedCompletionInfo: vscode.SelectedCompletionInfo | undefined,
690 abortSignal: AbortSignal,
691 outcome: AutocompleteOutcome | NextEditOutcome,
692 ): boolean {
693 if (selectedCompletionInfo) {
694 const { text, range } = selectedCompletionInfo;
695 if (!outcome.completion.startsWith(text)) {
696 console.log(
697 `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`,
698 range,
699 );
700 return false;
701 }
702 }
703
704 if (abortSignal.aborted) {
705 return false;
706 }
707
708 return true;
709 }
710}