Elffuss BraidHub

kikocis/continue public

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