Elffuss BraidHub

kikocis/continue public

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