Elffuss BraidHub

kikocis/continue public

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