Elffuss BraidHub

kikocis/continue public

1ff75182e19e · 21.9 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 token.onCancellationRequested(() => abortController.abort());
203
204 // Handle notebook cells
205 let pos = {
206 line: position.line,
207 character: position.character,
208 };
209
210 let manuallyPassFileContents: string | undefined = undefined;
211 if (document.uri.scheme === "vscode-notebook-cell") {
212 const notebook = vscode.workspace.notebookDocuments.find((notebook) =>
213 notebook
214 .getCells()
215 .some((cell) =>
216 URI.equal(cell.document.uri.toString(), document.uri.toString()),
217 ),
218 );
219 if (notebook) {
220 const cells = notebook.getCells();
221 manuallyPassFileContents = cells
222 .map((cell) => {
223 const text = cell.document.getText();
224 if (cell.kind === vscode.NotebookCellKind.Markup) {
225 return `"""${text}"""`;
226 } else {
227 return text;
228 }
229 })
230 .join("\n\n");
231 for (const cell of cells) {
232 if (
233 URI.equal(cell.document.uri.toString(), document.uri.toString())
234 ) {
235 break;
236 } else {
237 pos.line += cell.document.getText().split("\n").length + 1;
238 }
239 }
240 }
241 }
242
243 // Manually pass file contents for unsaved, untitled files
244 if (document.isUntitled) {
245 manuallyPassFileContents = document.getText();
246 }
247
248 // Handle commit message input box
249 let manuallyPassPrefix: string | undefined = undefined;
250
251 // handle manual autocompletion trigger
252 const wasManuallyTriggered =
253 context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke;
254
255 const completionId = uuidv4();
256 const filepath = document.uri.toString();
257 const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets();
258 let recentlyEditedRanges =
259 await this.recentlyEditedTracker.getRecentlyEditedRanges();
260
261 const ctx = {
262 completionId,
263 manuallyPassFileContents,
264 manuallyPassPrefix,
265 selectedCompletionInfo,
266 isUntitledFile: document.isUntitled,
267 recentlyVisitedRanges,
268 recentlyEditedRanges,
269 };
270
271 let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
272
273 // TODO: We can probably decide here if we want to do the jumping logic.
274 // If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager.
275 // It would simplify the logic quite substantially.
276
277 // Determine why this method was triggered.
278 const isJumping = this.jumpManager.isJumpInProgress();
279 const chainExists = this.nextEditProvider.chainExists();
280 console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
281 this.prefetchQueue.peekThreeProcessed();
282
283 if (isJumping && chainExists) {
284 // Case 2: Jumping (chain exists, jump was taken)
285 console.log("trigger reason: jumping");
286
287 // Reset jump state.
288 this.jumpManager.setJumpInProgress(false);
289
290 // Use the saved completion from JumpManager instead of dequeuing.
291 const savedCompletion = this.jumpManager.completionAfterJump;
292 if (savedCompletion) {
293 outcome = savedCompletion.outcome;
294 this.jumpManager.clearCompletionAfterJump();
295 } else {
296 // Fall back to prefetch queue. This technically should not happen.
297 console.error(
298 "Fell back to prefetch queue even after jump was taken",
299 );
300 outcome = this.prefetchQueue.dequeueProcessed()?.outcome;
301
302 // Fill in the spot after dequeuing.
303 if (!this.usingFullFileDiff) {
304 this.prefetchQueue.process({
305 ...ctx,
306 recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
307 recentlyEditedRanges:
308 await this.recentlyEditedTracker.getRecentlyEditedRanges(),
309 });
310 }
311 }
312 } else if (chainExists) {
313 // Case 3: Accepting next edit outcome (chain exists, jump is not taken).
314 console.log("trigger reason: accepting");
315
316 // Try suggesting jump for each location.
317 let isJumpSuggested = false;
318
319 while (this.prefetchQueue.processedCount > 0 && !isJumpSuggested) {
320 const nextItemInQueue = this.prefetchQueue.dequeueProcessed();
321 if (!nextItemInQueue) continue;
322
323 // Fill in the spot after dequeuing.
324 if (!this.usingFullFileDiff) {
325 this.prefetchQueue.process({
326 ...ctx,
327 recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
328 recentlyEditedRanges:
329 await this.recentlyEditedTracker.getRecentlyEditedRanges(),
330 });
331 }
332
333 const nextLocation = nextItemInQueue.location;
334 outcome = nextItemInQueue.outcome;
335
336 const jumpPosition = new vscode.Position(
337 nextLocation.range.start.line,
338 nextLocation.range.start.character,
339 );
340
341 isJumpSuggested = await this.jumpManager.suggestJump(
342 currCursorPos,
343 jumpPosition,
344 outcome.completion,
345 );
346
347 if (isJumpSuggested) {
348 // Store completion to be rendered after a jump.
349 this.jumpManager.setCompletionAfterJump({
350 completionId: completionId,
351 outcome,
352 currentPosition: jumpPosition,
353 });
354
355 // Don't display anything yet.
356 // This will be handled in Case 2.
357 return undefined;
358 }
359 }
360
361 if (!isJumpSuggested) {
362 console.log(
363 "No suitable jump location found after trying all positions",
364 );
365 this.nextEditProvider.deleteChain();
366 return undefined;
367 }
368 } else {
369 // Case 1: Typing (chain does not exist).
370
371 this.nextEditProvider.startChain();
372
373 const input: AutocompleteInput = {
374 pos,
375 filepath,
376 ...ctx,
377 };
378
379 setupStatusBar(undefined, true);
380
381 // Get initial completion.
382 if (this.isNextEditActive) {
383 outcome = await this.nextEditProvider.provideInlineCompletionItems(
384 input,
385 signal,
386 { withChain: false, usingFullFileDiff: this.usingFullFileDiff },
387 );
388
389 // Start prefetching next edits.
390 // NOTE: this might be better off not awaited.
391 if (!this.usingFullFileDiff) {
392 this.prefetchQueue.process(ctx);
393 }
394
395 // If initial outcome is null, suggest a jump instead.
396 // Calling this method again will call it with
397 // chain active but jump not suggested yet.
398 if (
399 !outcome ||
400 (!outcome.completion && outcome.diffLines.length === 0)
401 ) {
402 return this.provideInlineCompletionItems(
403 document,
404 position,
405 context,
406 token,
407 );
408 }
409 } else {
410 // Handle regular autocomplete request.
411 outcome = await this.completionProvider.provideInlineCompletionItems(
412 input,
413 signal,
414 wasManuallyTriggered,
415 );
416 }
417 }
418
419 // Return early if no valid outcome was found.
420 if (
421 !outcome ||
422 (!this.isNextEditActive &&
423 !(outcome as AutocompleteOutcome).completion) ||
424 (this.isNextEditActive &&
425 !(outcome as NextEditOutcome).completion &&
426 (outcome as NextEditOutcome).diffLines.length === 0)
427 ) {
428 return null;
429 }
430
431 // VS Code displays dependent on selectedCompletionInfo (their docstring below)
432 // We should first always make sure we have a valid completion, but if it goes wrong we
433 // want telemetry to be correct
434 /**
435 * Provides information about the currently selected item in the autocomplete widget if it is visible.
436 *
437 * If set, provided inline completions must extend the text of the selected item
438 * and use the same range, otherwise they are not shown as preview.
439 * As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document,
440 * the inline completion must also replace `.` and start with `.log`, for example `.log()`.
441 *
442 * Inline completion providers are requested again whenever the selected item changes.
443 */
444 if (selectedCompletionInfo) {
445 outcome.completion = selectedCompletionInfo.text + outcome.completion;
446 }
447 const willDisplay = this.willDisplay(
448 document,
449 selectedCompletionInfo,
450 signal,
451 outcome,
452 );
453 if (!willDisplay) {
454 return null;
455 }
456
457 // Marking the outcome as displayed saves the current outcome
458 // as a value of the key completionId.
459 if (this.isNextEditActive) {
460 this.nextEditProvider.markDisplayed(
461 completionId,
462 outcome as NextEditOutcome,
463 );
464 } else {
465 this.completionProvider.markDisplayed(
466 completionId,
467 outcome as AutocompleteOutcome,
468 );
469 }
470 this._lastShownCompletion = outcome;
471
472 // Construct the range/text to show
473 const startPos = selectedCompletionInfo?.range.start ?? position;
474 let range = new vscode.Range(startPos, startPos);
475 let completionText = outcome.completion;
476
477 const isSingleLineCompletion = outcome.completion.split("\n").length <= 1;
478
479 if (isSingleLineCompletion) {
480 const lastLineOfCompletionText = completionText.split("\n").pop() || "";
481 const currentText = document
482 .lineAt(startPos)
483 .text.substring(startPos.character);
484
485 const result = processSingleLineCompletion(
486 lastLineOfCompletionText,
487 currentText,
488 startPos.character,
489 );
490
491 if (result === undefined) {
492 return undefined;
493 }
494
495 completionText = result.completionText;
496 if (result.range) {
497 range = new vscode.Range(
498 new vscode.Position(startPos.line, result.range.start),
499 new vscode.Position(startPos.line, result.range.end),
500 );
501 }
502 } else {
503 // Extend the range to the end of the line for multiline completions
504 range = new vscode.Range(startPos, document.lineAt(startPos).range.end);
505 }
506
507 const autocompleteCompletionItem = new vscode.InlineCompletionItem(
508 completionText,
509 range,
510 {
511 title: "Log Autocomplete Outcome",
512 command: "continue.logAutocompleteOutcome",
513 arguments: [completionId, this.completionProvider],
514 },
515 );
516
517 (autocompleteCompletionItem as any).completeBracketPairs = true;
518
519 // Handle autocomplete request.
520 if (!this.isNextEditActive) {
521 return [autocompleteCompletionItem];
522 }
523
524 // Check the diff between old and new editable region.
525 const newEditRangeSlice = completionText;
526
527 // Get the contents of the old (current) editable region.
528 // const editableRegionStartLine = Math.max(
529 // currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
530 // 0,
531 // );
532 // const editableRegionEndLine = Math.min(
533 // currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
534 // editor.document.lineCount - 1,
535 // );
536 const editableRegionStartLine = (outcome as NextEditOutcome)
537 .editableRegionStartLine;
538 const editableRegionEndLine = (outcome as NextEditOutcome)
539 .editableRegionEndLine;
540 const oldEditRangeSlice = editor.document
541 .getText()
542 .split("\n")
543 .slice(editableRegionStartLine, editableRegionEndLine + 1)
544 .join("\n");
545
546 // We don't need to show the next edit window if the predicted edits are identical to the previous version.
547 if (oldEditRangeSlice === newEditRangeSlice) {
548 this.nextEditLoggingService.cancelRejectionTimeout(completionId);
549 return undefined;
550 }
551
552 // Create a cursor position relative to the edit range slice.
553 const relativeCursorPos = {
554 line: currCursorPos.line - editableRegionStartLine,
555 character: currCursorPos.character,
556 };
557
558 // If the diff is a FIM, render a ghost text.
559 const { isFim, fimText } = checkFim(
560 oldEditRangeSlice,
561 newEditRangeSlice,
562 relativeCursorPos,
563 );
564
565 if (isFim) {
566 if (!fimText) {
567 console.log("deleteChain from completionProvider.ts: !fimText");
568 this.nextEditProvider.deleteChain();
569 return undefined;
570 }
571
572 // Track this ghost text for acceptance detection.
573 // Ghost text acceptance can *technically* be acted upon in
574 // the command handler for "continue.logNextEditOutcomeAccept",
575 // but there is a substantial delay between accepting and logging,
576 // which introduces a lot of race conditions with different event handlers.
577 // Plus, separating these concerns seems to make sense logically as well.
578 GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance(
579 document,
580 fimText,
581 new vscode.Position(currCursorPos.line, currCursorPos.character),
582 );
583
584 const nextEditCompletionItem = new vscode.InlineCompletionItem(
585 fimText,
586 new vscode.Range(
587 new vscode.Position(currCursorPos.line, currCursorPos.character),
588 new vscode.Position(currCursorPos.line, currCursorPos.character),
589 ),
590 {
591 title: "Log Next Edit Outcome",
592 command: "continue.logNextEditOutcomeAccept",
593 arguments: [completionId, this.nextEditLoggingService],
594 },
595 );
596 return [nextEditCompletionItem];
597 }
598
599 // Handle non-FIM cases with the NextEditWindowManager.
600 const diffLines = (outcome as NextEditOutcome).diffLines;
601 if (diffLines.length === 0) {
602 // At this point, there is no way that diffLines.length === 0.
603 // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse.
604 // In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place.
605 // In case of initial response, we suggested a jump.
606 console.log(
607 "deleteChain from completionProvider.ts: diffLines.length === 0",
608 );
609 NextEditProvider.getInstance().deleteChain();
610 }
611
612 if (NextEditWindowManager.isInstantiated()) {
613 NextEditWindowManager.getInstance().updateCurrentCompletionId(
614 completionId,
615 );
616
617 await NextEditWindowManager.getInstance().showNextEditWindow(
618 editor,
619 currCursorPos,
620 editableRegionStartLine,
621 editableRegionEndLine,
622 oldEditRangeSlice,
623 newEditRangeSlice,
624 diffLines,
625 );
626 }
627
628 return undefined;
629 } finally {
630 stopStatusBarLoading();
631 }
632 }
633
634 willDisplay(
635 document: vscode.TextDocument,
636 selectedCompletionInfo: vscode.SelectedCompletionInfo | undefined,
637 abortSignal: AbortSignal,
638 outcome: AutocompleteOutcome | NextEditOutcome,
639 ): boolean {
640 if (selectedCompletionInfo) {
641 const { text, range } = selectedCompletionInfo;
642 if (!outcome.completion.startsWith(text)) {
643 console.log(
644 `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`,
645 range,
646 );
647 return false;
648 }
649 }
650
651 if (abortSignal.aborted) {
652 return false;
653 }
654
655 return true;
656 }
657}