| 1 | import { CompletionProvider } from "core/autocomplete/CompletionProvider"; |
| 2 | import { processSingleLineCompletion } from "core/autocomplete/util/processSingleLineCompletion"; |
| 3 | import { |
| 4 | type AutocompleteInput, |
| 5 | type AutocompleteOutcome, |
| 6 | } from "core/autocomplete/util/types"; |
| 7 | import { ConfigHandler } from "core/config/ConfigHandler"; |
| 8 | import * as URI from "uri-js"; |
| 9 | import { v4 as uuidv4 } from "uuid"; |
| 10 | import * as vscode from "vscode"; |
| 11 | |
| 12 | import { handleLLMError } from "../util/errorHandling"; |
| 13 | import { VsCodeIde } from "../VsCodeIde"; |
| 14 | import { VsCodeWebviewProtocol } from "../webviewProtocol"; |
| 15 | |
| 16 | import { checkFim } from "core/nextEdit/diff/diff"; |
| 17 | import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; |
| 18 | import { PrefetchQueue } from "core/nextEdit/NextEditPrefetchQueue"; |
| 19 | import { NextEditProvider } from "core/nextEdit/NextEditProvider"; |
| 20 | import { NextEditOutcome } from "core/nextEdit/types"; |
| 21 | import { JumpManager } from "../activation/JumpManager"; |
| 22 | import { NextEditWindowManager } from "../activation/NextEditWindowManager"; |
| 23 | import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker"; |
| 24 | import { getDefinitionsFromLsp } from "./lsp"; |
| 25 | import { RecentlyEditedTracker } from "./recentlyEdited"; |
| 26 | import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService"; |
| 27 | import { |
| 28 | StatusBarStatus, |
| 29 | getStatusBarStatus, |
| 30 | setupStatusBar, |
| 31 | stopStatusBarLoading, |
| 32 | } from "./statusBar"; |
| 33 | |
| 34 | interface VsCodeCompletionInput { |
| 35 | document: vscode.TextDocument; |
| 36 | position: vscode.Position; |
| 37 | context: vscode.InlineCompletionContext; |
| 38 | } |
| 39 | |
| 40 | export 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 | let chainExists = this.nextEditProvider.chainExists(); |
| 334 | const processedCount = this.prefetchQueue.processedCount; |
| 335 | const unprocessedCount = this.prefetchQueue.unprocessedCount; |
| 336 | console.log("isJumping:", isJumping, "/ chainExists:", chainExists); |
| 337 | this.prefetchQueue.peekThreeProcessed(); |
| 338 | |
| 339 | let resetChainInFullFileDiff = false; |
| 340 | if ( |
| 341 | chainExists && |
| 342 | this.usingFullFileDiff && |
| 343 | processedCount === 0 && |
| 344 | unprocessedCount === 0 |
| 345 | ) { |
| 346 | // Skipping jump logic due to empty queues while using full file diff |
| 347 | await this.nextEditProvider.deleteChain(); |
| 348 | chainExists = false; |
| 349 | resetChainInFullFileDiff = true; |
| 350 | } |
| 351 | |
| 352 | if (isJumping && chainExists) { |
| 353 | // Case 2: Jumping (chain exists, jump was taken) |
| 354 | console.log("trigger reason: jumping"); |
| 355 | |
| 356 | // Reset jump state. |
| 357 | this.jumpManager.setJumpInProgress(false); |
| 358 | |
| 359 | // Use the saved completion from JumpManager instead of dequeuing. |
| 360 | const savedCompletion = this.jumpManager.completionAfterJump; |
| 361 | if (savedCompletion) { |
| 362 | outcome = savedCompletion.outcome; |
| 363 | this.jumpManager.clearCompletionAfterJump(); |
| 364 | } else { |
| 365 | // Fall back to prefetch queue. This technically should not happen. |
| 366 | console.error( |
| 367 | "Fell back to prefetch queue even after jump was taken", |
| 368 | ); |
| 369 | outcome = this.prefetchQueue.dequeueProcessed()?.outcome; |
| 370 | |
| 371 | // Fill in the spot after dequeuing. |
| 372 | if (!this.usingFullFileDiff) { |
| 373 | this.prefetchQueue.process({ |
| 374 | ...ctx, |
| 375 | recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), |
| 376 | recentlyEditedRanges: |
| 377 | await this.recentlyEditedTracker.getRecentlyEditedRanges(), |
| 378 | }); |
| 379 | } |
| 380 | } |
| 381 | } else if (chainExists) { |
| 382 | // Case 3: Accepting next edit outcome (chain exists, jump is not taken). |
| 383 | console.log("trigger reason: accepting"); |
| 384 | |
| 385 | // Try suggesting jump for each location. |
| 386 | let isJumpSuggested = false; |
| 387 | |
| 388 | while (this.prefetchQueue.processedCount > 0 && !isJumpSuggested) { |
| 389 | const nextItemInQueue = this.prefetchQueue.dequeueProcessed(); |
| 390 | if (!nextItemInQueue) continue; |
| 391 | |
| 392 | // Fill in the spot after dequeuing. |
| 393 | if (!this.usingFullFileDiff) { |
| 394 | this.prefetchQueue.process({ |
| 395 | ...ctx, |
| 396 | recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), |
| 397 | recentlyEditedRanges: |
| 398 | await this.recentlyEditedTracker.getRecentlyEditedRanges(), |
| 399 | }); |
| 400 | } |
| 401 | |
| 402 | const nextLocation = nextItemInQueue.location; |
| 403 | outcome = nextItemInQueue.outcome; |
| 404 | |
| 405 | const jumpPosition = new vscode.Position( |
| 406 | nextLocation.range.start.line, |
| 407 | nextLocation.range.start.character, |
| 408 | ); |
| 409 | |
| 410 | isJumpSuggested = await this.jumpManager.suggestJump( |
| 411 | currCursorPos, |
| 412 | jumpPosition, |
| 413 | outcome.completion, |
| 414 | ); |
| 415 | |
| 416 | if (isJumpSuggested) { |
| 417 | // Store completion to be rendered after a jump. |
| 418 | this.jumpManager.setCompletionAfterJump({ |
| 419 | completionId: completionId, |
| 420 | outcome, |
| 421 | currentPosition: jumpPosition, |
| 422 | }); |
| 423 | |
| 424 | // Don't display anything yet. This will be handled in Case 2. |
| 425 | // Recall from above that provideInlineCompletions runs on every cursor movement. |
| 426 | return undefined; |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | if (!isJumpSuggested) { |
| 431 | console.log( |
| 432 | "No suitable jump location found after trying all positions", |
| 433 | ); |
| 434 | this.nextEditProvider.deleteChain(); |
| 435 | return undefined; |
| 436 | } |
| 437 | } else { |
| 438 | // Case 1: Typing (chain does not exist). |
| 439 | // if resetChainInFullFileDiff is true then we are Rebuilding next edit chain after clearing empty queues in full file diff mode |
| 440 | this.nextEditProvider.startChain(); |
| 441 | |
| 442 | const input: AutocompleteInput = { |
| 443 | pos, |
| 444 | filepath, |
| 445 | ...ctx, |
| 446 | }; |
| 447 | |
| 448 | setupStatusBar(undefined, true); |
| 449 | |
| 450 | // Get initial completion. |
| 451 | if (this.isNextEditActive) { |
| 452 | outcome = await this.nextEditProvider.provideInlineCompletionItems( |
| 453 | input, |
| 454 | signal, |
| 455 | { withChain: false, usingFullFileDiff: this.usingFullFileDiff }, |
| 456 | ); |
| 457 | |
| 458 | if ( |
| 459 | resetChainInFullFileDiff && |
| 460 | (!outcome || |
| 461 | (!outcome.completion && outcome.diffLines.length === 0)) |
| 462 | ) { |
| 463 | // No next edit outcome after resetting chain; returning null |
| 464 | return null; |
| 465 | } |
| 466 | |
| 467 | // Start prefetching next edits if not using full file diff. |
| 468 | // NOTE: this is better off not awaited. fire and forget. |
| 469 | if (!this.usingFullFileDiff) { |
| 470 | this.prefetchQueue.process(ctx); |
| 471 | } |
| 472 | |
| 473 | // If initial outcome is null, suggest a jump instead. |
| 474 | // Calling this method again will call it with chain active but jump not suggested yet. |
| 475 | if ( |
| 476 | !outcome || |
| 477 | (!outcome.completion && outcome.diffLines.length === 0) |
| 478 | ) { |
| 479 | return this.provideInlineCompletionItems( |
| 480 | document, |
| 481 | position, |
| 482 | context, |
| 483 | token, |
| 484 | ); |
| 485 | } |
| 486 | } else { |
| 487 | // Handle regular autocomplete request. |
| 488 | outcome = await this.completionProvider.provideInlineCompletionItems( |
| 489 | input, |
| 490 | signal, |
| 491 | wasManuallyTriggered, |
| 492 | ); |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | // Return early if no valid outcome was found. |
| 497 | if ( |
| 498 | !outcome || |
| 499 | (!this.isNextEditActive && |
| 500 | !(outcome as AutocompleteOutcome).completion) || |
| 501 | (this.isNextEditActive && |
| 502 | !(outcome as NextEditOutcome).completion && |
| 503 | (outcome as NextEditOutcome).diffLines.length === 0) |
| 504 | ) { |
| 505 | return null; |
| 506 | } |
| 507 | |
| 508 | // VS Code displays dependent on selectedCompletionInfo (their docstring below) |
| 509 | // We should first always make sure we have a valid completion, but if it goes wrong we |
| 510 | // want telemetry to be correct |
| 511 | /** |
| 512 | * Provides information about the currently selected item in the autocomplete widget if it is visible. |
| 513 | * |
| 514 | * If set, provided inline completions must extend the text of the selected item |
| 515 | * and use the same range, otherwise they are not shown as preview. |
| 516 | * As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document, |
| 517 | * the inline completion must also replace `.` and start with `.log`, for example `.log()`. |
| 518 | * |
| 519 | * Inline completion providers are requested again whenever the selected item changes. |
| 520 | */ |
| 521 | if (selectedCompletionInfo) { |
| 522 | outcome.completion = selectedCompletionInfo.text + outcome.completion; |
| 523 | } |
| 524 | const willDisplay = this.willDisplay( |
| 525 | document, |
| 526 | selectedCompletionInfo, |
| 527 | signal, |
| 528 | outcome, |
| 529 | ); |
| 530 | if (!willDisplay) { |
| 531 | return null; |
| 532 | } |
| 533 | |
| 534 | // Marking the outcome as displayed saves the current outcome as a value of the key completionId. |
| 535 | // NOTE: It seems like autocomplete relies on this to be considered accepted. |
| 536 | if (this.isNextEditActive) { |
| 537 | this.nextEditProvider.markDisplayed( |
| 538 | completionId, |
| 539 | outcome as NextEditOutcome, |
| 540 | ); |
| 541 | } else { |
| 542 | this.completionProvider.markDisplayed( |
| 543 | completionId, |
| 544 | outcome as AutocompleteOutcome, |
| 545 | ); |
| 546 | } |
| 547 | this._lastShownCompletion = outcome; |
| 548 | |
| 549 | /* END OF MODEL OUTCOME RECEIVING BLOCK */ |
| 550 | |
| 551 | /* START OF RENDERING BLOCK */ |
| 552 | |
| 553 | // Here we determine how to render the outcome received in the previous block. |
| 554 | // We check whether the outcome is a FIM completion or not. |
| 555 | // If FIM, we render a ghost text, and an SVG + deletion decoration if not. |
| 556 | // If we are using autocomplete instead of next edit, we just render a ghost text. |
| 557 | |
| 558 | // Construct the range/text to show |
| 559 | const startPos = selectedCompletionInfo?.range.start ?? position; |
| 560 | let range = new vscode.Range(startPos, startPos); |
| 561 | let completionText = outcome.completion; |
| 562 | |
| 563 | const isSingleLineCompletion = outcome.completion.split("\n").length <= 1; |
| 564 | |
| 565 | if (isSingleLineCompletion) { |
| 566 | const lastLineOfCompletionText = completionText.split("\n").pop() || ""; |
| 567 | const currentText = document |
| 568 | .lineAt(startPos) |
| 569 | .text.substring(startPos.character); |
| 570 | |
| 571 | const result = processSingleLineCompletion( |
| 572 | lastLineOfCompletionText, |
| 573 | currentText, |
| 574 | startPos.character, |
| 575 | ); |
| 576 | |
| 577 | if (result === undefined) { |
| 578 | return undefined; |
| 579 | } |
| 580 | |
| 581 | completionText = result.completionText; |
| 582 | if (result.range) { |
| 583 | range = new vscode.Range( |
| 584 | new vscode.Position(startPos.line, result.range.start), |
| 585 | new vscode.Position(startPos.line, result.range.end), |
| 586 | ); |
| 587 | } |
| 588 | } else { |
| 589 | // Extend the range to the end of the line for multiline completions |
| 590 | range = new vscode.Range(startPos, document.lineAt(startPos).range.end); |
| 591 | } |
| 592 | |
| 593 | const autocompleteCompletionItem = new vscode.InlineCompletionItem( |
| 594 | completionText, |
| 595 | range, |
| 596 | { |
| 597 | title: "Log Autocomplete Outcome", |
| 598 | command: "continue.logAutocompleteOutcome", |
| 599 | arguments: [completionId, this.completionProvider], |
| 600 | }, |
| 601 | ); |
| 602 | |
| 603 | (autocompleteCompletionItem as any).completeBracketPairs = true; |
| 604 | |
| 605 | // Handle autocomplete request. |
| 606 | if (!this.isNextEditActive) { |
| 607 | return [autocompleteCompletionItem]; |
| 608 | } |
| 609 | |
| 610 | // Check the diff between old and new editable region. |
| 611 | const newEditRangeSlice = completionText; |
| 612 | |
| 613 | // Get the contents of the old (current) editable region. |
| 614 | const editableRegionStartLine = (outcome as NextEditOutcome) |
| 615 | .editableRegionStartLine; |
| 616 | const editableRegionEndLine = (outcome as NextEditOutcome) |
| 617 | .editableRegionEndLine; |
| 618 | const oldEditRangeSlice = editor.document |
| 619 | .getText() |
| 620 | .split("\n") |
| 621 | .slice(editableRegionStartLine, editableRegionEndLine + 1) |
| 622 | .join("\n"); |
| 623 | |
| 624 | // We don't need to show the next edit window if the predicted edits are identical to the previous version. |
| 625 | if (oldEditRangeSlice === newEditRangeSlice) { |
| 626 | this.nextEditLoggingService.cancelRejectionTimeout(completionId); |
| 627 | return undefined; |
| 628 | } |
| 629 | |
| 630 | // Create a cursor position relative to the edit range slice. |
| 631 | const relativeCursorPos = { |
| 632 | line: currCursorPos.line - editableRegionStartLine, |
| 633 | character: currCursorPos.character, |
| 634 | }; |
| 635 | |
| 636 | // If the diff is a FIM, render a ghost text. |
| 637 | const { isFim, fimText } = checkFim( |
| 638 | oldEditRangeSlice, |
| 639 | newEditRangeSlice, |
| 640 | relativeCursorPos, |
| 641 | ); |
| 642 | |
| 643 | if (isFim) { |
| 644 | if (!fimText) { |
| 645 | console.log("deleteChain from completionProvider.ts: !fimText"); |
| 646 | this.nextEditProvider.deleteChain(); |
| 647 | return undefined; |
| 648 | } |
| 649 | |
| 650 | // Track this ghost text for acceptance detection. |
| 651 | // Ghost text acceptance can *technically* be acted upon in the command handler for "continue.logNextEditOutcomeAccept". |
| 652 | // However, there is a substantial delay between accepting and logging, which introduces a lot of race conditions with different event handlers. |
| 653 | // Plus, separating these concerns seems to make sense logically as well. |
| 654 | GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance( |
| 655 | document, |
| 656 | fimText, |
| 657 | new vscode.Position(currCursorPos.line, currCursorPos.character), |
| 658 | ); |
| 659 | |
| 660 | const nextEditCompletionItem = new vscode.InlineCompletionItem( |
| 661 | fimText, |
| 662 | new vscode.Range( |
| 663 | new vscode.Position(currCursorPos.line, currCursorPos.character), |
| 664 | new vscode.Position(currCursorPos.line, currCursorPos.character), |
| 665 | ), |
| 666 | { |
| 667 | title: "Log Next Edit Outcome", |
| 668 | command: "continue.logNextEditOutcomeAccept", |
| 669 | arguments: [completionId, this.nextEditLoggingService], |
| 670 | }, |
| 671 | ); |
| 672 | return [nextEditCompletionItem]; |
| 673 | } |
| 674 | |
| 675 | // Handle non-FIM cases with the NextEditWindowManager. |
| 676 | const diffLines = (outcome as NextEditOutcome).diffLines; |
| 677 | if (diffLines.length === 0) { |
| 678 | // At this point, there is no way that diffLines.length === 0. |
| 679 | // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse. |
| 680 | // In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place. |
| 681 | // In case of initial response, we suggested a jump. |
| 682 | console.log( |
| 683 | "deleteChain from completionProvider.ts: diffLines.length === 0", |
| 684 | ); |
| 685 | NextEditProvider.getInstance().deleteChain(); |
| 686 | } |
| 687 | |
| 688 | if (NextEditWindowManager.isInstantiated()) { |
| 689 | NextEditWindowManager.getInstance().updateCurrentCompletionId( |
| 690 | completionId, |
| 691 | ); |
| 692 | |
| 693 | await NextEditWindowManager.getInstance().showNextEditWindow( |
| 694 | editor, |
| 695 | currCursorPos, |
| 696 | editableRegionStartLine, |
| 697 | editableRegionEndLine, |
| 698 | oldEditRangeSlice, |
| 699 | newEditRangeSlice, |
| 700 | diffLines, |
| 701 | ); |
| 702 | } |
| 703 | |
| 704 | return undefined; |
| 705 | } finally { |
| 706 | stopStatusBarLoading(); |
| 707 | } |
| 708 | |
| 709 | /* END OF RENDERING BLOCK */ |
| 710 | } |
| 711 | |
| 712 | willDisplay( |
| 713 | document: vscode.TextDocument, |
| 714 | selectedCompletionInfo: vscode.SelectedCompletionInfo | undefined, |
| 715 | abortSignal: AbortSignal, |
| 716 | outcome: AutocompleteOutcome | NextEditOutcome, |
| 717 | ): boolean { |
| 718 | if (selectedCompletionInfo) { |
| 719 | const { text, range } = selectedCompletionInfo; |
| 720 | if (!outcome.completion.startsWith(text)) { |
| 721 | console.log( |
| 722 | `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`, |
| 723 | range, |
| 724 | ); |
| 725 | return false; |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | if (abortSignal.aborted) { |
| 730 | return false; |
| 731 | } |
| 732 | |
| 733 | return true; |
| 734 | } |
| 735 | } |