| 1 | import * as path from "path"; |
| 2 | import { v4 as uuidv4 } from "uuid"; |
| 3 | import { ConfigHandler } from "../config/ConfigHandler.js"; |
| 4 | import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js"; |
| 5 | import OpenAI from "../llm/llms/OpenAI.js"; |
| 6 | import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; |
| 7 | |
| 8 | import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js"; |
| 9 | |
| 10 | import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; |
| 11 | import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; |
| 12 | import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; |
| 13 | import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; |
| 14 | import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; |
| 15 | import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; |
| 16 | import { getAst } from "../autocomplete/util/ast.js"; |
| 17 | import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js"; |
| 18 | import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; |
| 19 | import { HelperVars } from "../autocomplete/util/HelperVars.js"; |
| 20 | import { AutocompleteInput } from "../autocomplete/util/types.js"; |
| 21 | import { localPathOrUriToPath } from "../util/pathToUri.js"; |
| 22 | import { replaceEscapedCharacters } from "../util/text.js"; |
| 23 | import { |
| 24 | CODE_TO_EDIT_OPEN, |
| 25 | NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, |
| 26 | NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, |
| 27 | } from "./constants.js"; |
| 28 | import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; |
| 29 | import { calculateFinalCursorPosition } from "./diff/diff.js"; |
| 30 | import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; |
| 31 | import { |
| 32 | EditableRegionStrategy, |
| 33 | getNextEditableRegion, |
| 34 | } from "./NextEditEditableRegionCalculator.js"; |
| 35 | import { NextEditLoggingService } from "./NextEditLoggingService.js"; |
| 36 | import { |
| 37 | renderDefaultSystemPrompt, |
| 38 | renderDefaultUserPrompt, |
| 39 | renderPrompt, |
| 40 | } from "./templating/NextEditPromptEngine.js"; |
| 41 | import { |
| 42 | NextEditOutcome, |
| 43 | Prompt, |
| 44 | PromptMetadata, |
| 45 | RecentlyEditedRange, |
| 46 | } from "./types.js"; |
| 47 | |
| 48 | const autocompleteCache = AutocompleteLruCache.get(); |
| 49 | |
| 50 | // Errors that can be expected on occasion even during normal functioning should not be shown. |
| 51 | // Not worth disrupting the user to tell them that a single autocomplete request didn't go through |
| 52 | const ERRORS_TO_IGNORE = [ |
| 53 | // From Ollama |
| 54 | "unexpected server status", |
| 55 | "operation was aborted", |
| 56 | ]; |
| 57 | |
| 58 | export class NextEditProvider { |
| 59 | private static instance: NextEditProvider | null = null; |
| 60 | |
| 61 | private autocompleteCache = AutocompleteLruCache.get(); |
| 62 | public errorsShown: Set<string> = new Set(); |
| 63 | private bracketMatchingService = new BracketMatchingService(); |
| 64 | private debouncer = new AutocompleteDebouncer(); |
| 65 | private completionStreamer: CompletionStreamer; |
| 66 | private loggingService: NextEditLoggingService; |
| 67 | private contextRetrievalService: ContextRetrievalService; |
| 68 | private endpointType: "default" | "fineTuned"; |
| 69 | private diffContext: string = ""; |
| 70 | private promptMetadata: PromptMetadata | null = null; |
| 71 | private currentEditChainId: string | null = null; |
| 72 | private previousRequest: AutocompleteInput | null = null; |
| 73 | private previousCompletions: NextEditOutcome[] = []; |
| 74 | private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; |
| 75 | |
| 76 | private constructor( |
| 77 | private readonly configHandler: ConfigHandler, |
| 78 | private readonly ide: IDE, |
| 79 | private readonly _injectedGetLlm: () => Promise<ILLM | undefined>, |
| 80 | private readonly _onError: (e: any) => void, |
| 81 | private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, |
| 82 | endpointType: "default" | "fineTuned", |
| 83 | ) { |
| 84 | this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); |
| 85 | this.contextRetrievalService = new ContextRetrievalService(this.ide); |
| 86 | this.endpointType = endpointType; |
| 87 | this.loggingService = NextEditLoggingService.getInstance(); |
| 88 | } |
| 89 | |
| 90 | public static initialize( |
| 91 | configHandler: ConfigHandler, |
| 92 | ide: IDE, |
| 93 | injectedGetLlm: () => Promise<ILLM | undefined>, |
| 94 | onError: (e: any) => void, |
| 95 | getDefinitionsFromLsp: GetLspDefinitionsFunction, |
| 96 | endpointType: "default" | "fineTuned", |
| 97 | ): NextEditProvider { |
| 98 | if (!NextEditProvider.instance) { |
| 99 | NextEditProvider.instance = new NextEditProvider( |
| 100 | configHandler, |
| 101 | ide, |
| 102 | injectedGetLlm, |
| 103 | onError, |
| 104 | getDefinitionsFromLsp, |
| 105 | endpointType, |
| 106 | ); |
| 107 | } |
| 108 | return NextEditProvider.instance; |
| 109 | } |
| 110 | |
| 111 | public static getInstance(): NextEditProvider { |
| 112 | if (!NextEditProvider.instance) { |
| 113 | throw new Error( |
| 114 | "NextEditProvider has not been initialized. Call initialize() first.", |
| 115 | ); |
| 116 | } |
| 117 | return NextEditProvider.instance; |
| 118 | } |
| 119 | |
| 120 | public addDiffToContext(diff: string): void { |
| 121 | this.diffContext = diff; |
| 122 | } |
| 123 | |
| 124 | private async _prepareLlm(): Promise<ILLM | undefined> { |
| 125 | const llm = await this._injectedGetLlm(); |
| 126 | |
| 127 | if (!llm) { |
| 128 | return undefined; |
| 129 | } |
| 130 | |
| 131 | // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022 |
| 132 | if (llm.model === undefined && llm.completionOptions?.model !== undefined) { |
| 133 | llm.model = llm.completionOptions.model; |
| 134 | } |
| 135 | |
| 136 | // Ignore empty API keys for Mistral since we currently write |
| 137 | // a template provider without one during onboarding |
| 138 | if (llm.providerName === "mistral" && llm.apiKey === "") { |
| 139 | return undefined; |
| 140 | } |
| 141 | |
| 142 | // Set temperature (but don't override) |
| 143 | if (llm.completionOptions.temperature === undefined) { |
| 144 | llm.completionOptions.temperature = 0.01; |
| 145 | } |
| 146 | |
| 147 | if (llm instanceof OpenAI) { |
| 148 | llm.useLegacyCompletionsEndpoint = true; |
| 149 | } |
| 150 | // TODO: Resolve import error with TRIAL_FIM_MODEL |
| 151 | // else if ( |
| 152 | // llm.providerName === "free-trial" && |
| 153 | // llm.model !== TRIAL_FIM_MODEL |
| 154 | // ) { |
| 155 | // llm.model = TRIAL_FIM_MODEL; |
| 156 | // } |
| 157 | |
| 158 | return llm; |
| 159 | } |
| 160 | |
| 161 | private onError(e: any) { |
| 162 | if ( |
| 163 | ERRORS_TO_IGNORE.some((err) => |
| 164 | typeof e === "string" ? e.includes(err) : e?.message?.includes(err), |
| 165 | ) |
| 166 | ) { |
| 167 | return; |
| 168 | } |
| 169 | |
| 170 | console.warn("Error generating autocompletion: ", e); |
| 171 | if (!this.errorsShown.has(e.message)) { |
| 172 | this.errorsShown.add(e.message); |
| 173 | this._onError(e); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | public cancel() { |
| 178 | this.loggingService.cancel(); |
| 179 | } |
| 180 | |
| 181 | public accept(completionId: string) { |
| 182 | const outcome = this.loggingService.accept(completionId); |
| 183 | if (!outcome) { |
| 184 | return; |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | public reject(completionId: string) { |
| 189 | const outcome = this.loggingService.reject(completionId); |
| 190 | if (!outcome) { |
| 191 | return; |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | public markDisplayed(completionId: string, outcome: NextEditOutcome) { |
| 196 | this.loggingService.markDisplayed(completionId, outcome); |
| 197 | } |
| 198 | |
| 199 | private async _getAutocompleteOptions() { |
| 200 | const { config } = await this.configHandler.loadConfig(); |
| 201 | const options = { |
| 202 | ...DEFAULT_AUTOCOMPLETE_OPTS, |
| 203 | ...config?.tabAutocompleteOptions, |
| 204 | }; |
| 205 | return options; |
| 206 | } |
| 207 | |
| 208 | public chainExists(): boolean { |
| 209 | return this.currentEditChainId !== null; |
| 210 | } |
| 211 | |
| 212 | public getChainLength(): number { |
| 213 | return this.previousCompletions.length; |
| 214 | } |
| 215 | |
| 216 | public getPreviousCompletion(): NextEditOutcome | null { |
| 217 | return this.previousCompletions[0]; |
| 218 | } |
| 219 | |
| 220 | public async deleteChain(): Promise<void> { |
| 221 | this.currentEditChainId = null; |
| 222 | this.previousCompletions = []; |
| 223 | this.nextEditableRegionsInTheCurrentChain = []; |
| 224 | |
| 225 | if (this.previousRequest) { |
| 226 | const fileContent = ( |
| 227 | await this.ide.readFile(this.previousRequest.filepath) |
| 228 | ).toString(); |
| 229 | const ast = await getAst(this.previousRequest.filepath, fileContent); |
| 230 | if (ast) { |
| 231 | DocumentHistoryTracker.getInstance().push( |
| 232 | localPathOrUriToPath(this.previousRequest.filepath), |
| 233 | fileContent, |
| 234 | ast, |
| 235 | ); |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | public startChain(id?: string) { |
| 241 | this.currentEditChainId = id ?? uuidv4(); |
| 242 | } |
| 243 | |
| 244 | public getChain() { |
| 245 | return this.previousCompletions; |
| 246 | } |
| 247 | |
| 248 | public isStartOfChain() { |
| 249 | return this.previousCompletions.length === 1; |
| 250 | } |
| 251 | |
| 252 | public async provideInlineCompletionItems( |
| 253 | input: AutocompleteInput, |
| 254 | token: AbortSignal | undefined, |
| 255 | opts?: { |
| 256 | withChain: boolean; |
| 257 | }, |
| 258 | ): Promise<NextEditOutcome | undefined> { |
| 259 | try { |
| 260 | this.previousRequest = input; |
| 261 | // Create abort signal if not given |
| 262 | if (!token) { |
| 263 | const controller = this.loggingService.createAbortController( |
| 264 | input.completionId, |
| 265 | ); |
| 266 | token = controller.signal; |
| 267 | } |
| 268 | const startTime = Date.now(); |
| 269 | const options = await this._getAutocompleteOptions(); |
| 270 | |
| 271 | // Debounce |
| 272 | if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { |
| 273 | return undefined; |
| 274 | } |
| 275 | |
| 276 | // Depending on whether this method is called from provideInlineCompletionItemsWithChain, |
| 277 | // shift the next editable regions. |
| 278 | // This is handled here because this must run after the debouncer |
| 279 | // to prevent excessive shifts. |
| 280 | if (opts?.withChain) { |
| 281 | this.shiftNextEditableRegionsInTheCurrentChain(); |
| 282 | } |
| 283 | |
| 284 | const llm = await this._prepareLlm(); |
| 285 | if (!llm) { |
| 286 | return undefined; |
| 287 | } |
| 288 | |
| 289 | if (llm.promptTemplates?.autocomplete) { |
| 290 | options.template = llm.promptTemplates.autocomplete as string; |
| 291 | } |
| 292 | |
| 293 | const helper = await HelperVars.create( |
| 294 | input, |
| 295 | options, |
| 296 | llm.model, |
| 297 | this.ide, |
| 298 | ); |
| 299 | |
| 300 | if (await shouldPrefilter(helper, this.ide)) { |
| 301 | return undefined; |
| 302 | } |
| 303 | |
| 304 | const [snippetPayload, workspaceDirs] = await Promise.all([ |
| 305 | getAllSnippetsWithoutRace({ |
| 306 | helper, |
| 307 | ide: this.ide, |
| 308 | getDefinitionsFromLsp: this.getDefinitionsFromLsp, |
| 309 | contextRetrievalService: this.contextRetrievalService, |
| 310 | }), |
| 311 | this.ide.getWorkspaceDirs(), |
| 312 | ]); |
| 313 | |
| 314 | const editableRegionStartLine = Math.max( |
| 315 | helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, |
| 316 | 0, |
| 317 | ); |
| 318 | |
| 319 | const editableRegionEndLine = Math.min( |
| 320 | helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, |
| 321 | helper.fileLines.length - 1, |
| 322 | ); |
| 323 | |
| 324 | // TODO: Toggle between the default endpoint and the finetuned endpoint. |
| 325 | const prompts: Prompt[] = []; |
| 326 | |
| 327 | if (this.endpointType === "default") { |
| 328 | prompts.push(renderDefaultSystemPrompt()); |
| 329 | prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); |
| 330 | } else { |
| 331 | const historyDiff = createDiff({ |
| 332 | beforeContent: |
| 333 | DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( |
| 334 | localPathOrUriToPath(helper.filepath), |
| 335 | ) ?? "", |
| 336 | afterContent: helper.fileContents, |
| 337 | filePath: helper.filepath, |
| 338 | diffType: DiffFormatType.Unified, |
| 339 | contextLines: 3, |
| 340 | }); |
| 341 | |
| 342 | const modelName = helper.modelName; |
| 343 | let ctx: any; |
| 344 | |
| 345 | if (modelName.includes("mercury-coder-nextedit")) { |
| 346 | ctx = { |
| 347 | recentlyViewedCodeSnippets: |
| 348 | snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ |
| 349 | filepath: snip.filepath, |
| 350 | content: snip.content, |
| 351 | })) ?? [], |
| 352 | currentFileContent: helper.fileContents, |
| 353 | editableRegionStartLine, |
| 354 | editableRegionEndLine, |
| 355 | editDiffHistory: historyDiff, |
| 356 | }; |
| 357 | } else if (modelName.includes("model-1")) { |
| 358 | ctx = { |
| 359 | userEdits: historyDiff ?? this.diffContext, |
| 360 | languageShorthand: helper.lang.name, |
| 361 | userExcerpts: helper.fileContents, |
| 362 | }; |
| 363 | } else { |
| 364 | ctx = {}; |
| 365 | } |
| 366 | |
| 367 | const promptMetadata = await renderPrompt(helper, ctx); |
| 368 | |
| 369 | this.promptMetadata = promptMetadata; |
| 370 | |
| 371 | // prompts.push({ |
| 372 | // role: "system", |
| 373 | // content: [ |
| 374 | // "When the user deletes or replaces over previous code, you should respect that decision.", |
| 375 | // "Respect the new code the user is writing, and complete it.", |
| 376 | // "For example, if the user is changing a field name, try to autocomplete the new field name. Don't suggest the previous field name.", |
| 377 | // "Do not roll back to previous content.", |
| 378 | // "If the user has made a change, make sure you respect that and try to apply it to other parts of the code that used to use the old content.", |
| 379 | // ].join("\n"), |
| 380 | // }); |
| 381 | |
| 382 | prompts.push(promptMetadata.prompt); |
| 383 | } |
| 384 | |
| 385 | const oldEditRangeSlice = helper.fileContents |
| 386 | .split("\n") |
| 387 | .slice(editableRegionStartLine, editableRegionEndLine + 1) |
| 388 | .join("\n"); |
| 389 | |
| 390 | const finalCursorPos = calculateFinalCursorPosition( |
| 391 | helper.pos, |
| 392 | editableRegionStartLine, |
| 393 | oldEditRangeSlice, |
| 394 | "", |
| 395 | ); |
| 396 | |
| 397 | if (this.endpointType === "default") { |
| 398 | const msg: ChatMessage = await llm.chat(prompts, token); |
| 399 | |
| 400 | if (typeof msg.content === "string") { |
| 401 | const nextCompletion = JSON.parse(msg.content).newCode; |
| 402 | const outcomeNext: NextEditOutcome = { |
| 403 | elapsed: Date.now() - startTime, |
| 404 | modelProvider: llm.underlyingProviderName, |
| 405 | modelName: llm.model + ":zetaDataset", |
| 406 | completionOptions: null, |
| 407 | completionId: helper.input.completionId, |
| 408 | gitRepo: await this.ide.getRepoName(helper.filepath), |
| 409 | uniqueId: await this.ide.getUniqueId(), |
| 410 | timestamp: Date.now(), |
| 411 | fileUri: helper.filepath, |
| 412 | workspaceDirUri: |
| 413 | helper.workspaceUris[0] ?? path.dirname(helper.filepath), |
| 414 | prompt: prompts.join("\n"), |
| 415 | userEdits: "", |
| 416 | userExcerpts: "", |
| 417 | originalEditableRange: "", |
| 418 | completion: nextCompletion, |
| 419 | cursorPosition: helper.pos, |
| 420 | finalCursorPosition: finalCursorPos, |
| 421 | editableRegionStartLine: 0, |
| 422 | editableRegionEndLine: 0, |
| 423 | ...helper.options, |
| 424 | }; |
| 425 | |
| 426 | // When using the JetBrains extension, mark as displayed. |
| 427 | // This helps us not need to make additional network calls just to mark as displayed. |
| 428 | const ideType = (await this.ide.getIdeInfo()).ideType; |
| 429 | if (ideType === "jetbrains") { |
| 430 | this.markDisplayed(input.completionId, outcomeNext); |
| 431 | } |
| 432 | |
| 433 | return outcomeNext; |
| 434 | } else { |
| 435 | return undefined; |
| 436 | } |
| 437 | } else { |
| 438 | const msg: ChatMessage = await llm.chat(prompts, token); |
| 439 | |
| 440 | if (typeof msg.content === "string") { |
| 441 | // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined |
| 442 | const nextCompletion = msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1] |
| 443 | ? replaceEscapedCharacters( |
| 444 | msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1], |
| 445 | ).replace(/\n$/, "") |
| 446 | : ""; |
| 447 | |
| 448 | const currCursorPos = helper.pos; |
| 449 | |
| 450 | const editableRegionStartLine = Math.max( |
| 451 | currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, |
| 452 | 0, |
| 453 | ); |
| 454 | |
| 455 | const editableRegionEndLine = Math.min( |
| 456 | currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, |
| 457 | helper.fileLines.length - 1, |
| 458 | ); |
| 459 | |
| 460 | const oldEditRangeSlice = helper.fileContents |
| 461 | .split("\n") |
| 462 | .slice(editableRegionStartLine, editableRegionEndLine + 1) |
| 463 | .join("\n"); |
| 464 | |
| 465 | const finalCursorPos = calculateFinalCursorPosition( |
| 466 | helper.pos, |
| 467 | editableRegionStartLine, |
| 468 | oldEditRangeSlice, |
| 469 | nextCompletion, |
| 470 | ); |
| 471 | |
| 472 | const outcomeNext: NextEditOutcome = { |
| 473 | elapsed: Date.now() - startTime, |
| 474 | modelProvider: llm.underlyingProviderName, |
| 475 | modelName: llm.model + ":zetaDataset", |
| 476 | completionOptions: null, |
| 477 | completionId: helper.input.completionId, |
| 478 | gitRepo: await this.ide.getRepoName(helper.filepath), |
| 479 | uniqueId: await this.ide.getUniqueId(), |
| 480 | timestamp: Date.now(), |
| 481 | fileUri: helper.filepath, |
| 482 | workspaceDirUri: |
| 483 | helper.workspaceUris[0] ?? path.dirname(helper.filepath), |
| 484 | prompt: this.promptMetadata!.prompt.content, |
| 485 | userEdits: this.promptMetadata!.userEdits, |
| 486 | userExcerpts: this.promptMetadata!.userExcerpts, |
| 487 | originalEditableRange: oldEditRangeSlice, |
| 488 | completion: nextCompletion, |
| 489 | cursorPosition: helper.pos, |
| 490 | finalCursorPosition: finalCursorPos, |
| 491 | editableRegionStartLine, |
| 492 | editableRegionEndLine, |
| 493 | ...helper.options, |
| 494 | }; |
| 495 | |
| 496 | this.previousCompletions.push(outcomeNext); |
| 497 | |
| 498 | // When using the JetBrains extension, mark as displayed. |
| 499 | // This helps us not need to make additional network calls just to mark as displayed. |
| 500 | const ideType = (await this.ide.getIdeInfo()).ideType; |
| 501 | if (ideType === "jetbrains") { |
| 502 | this.markDisplayed(input.completionId, outcomeNext); |
| 503 | } |
| 504 | |
| 505 | return outcomeNext; |
| 506 | } else { |
| 507 | return undefined; |
| 508 | } |
| 509 | } |
| 510 | } catch (e: any) { |
| 511 | this.onError(e); |
| 512 | } finally { |
| 513 | this.loggingService.deleteAbortController(input.completionId); |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | public async provideInlineCompletionItemsWithChain( |
| 518 | ctx: { |
| 519 | completionId: string; |
| 520 | manuallyPassFileContents?: string; |
| 521 | manuallyPassPrefix?: string; |
| 522 | selectedCompletionInfo?: { |
| 523 | text: string; |
| 524 | range: Range; |
| 525 | }; |
| 526 | isUntitledFile: boolean; |
| 527 | recentlyVisitedRanges: AutocompleteCodeSnippet[]; |
| 528 | recentlyEditedRanges: RecentlyEditedRange[]; |
| 529 | }, |
| 530 | token: AbortSignal | undefined, |
| 531 | ) { |
| 532 | try { |
| 533 | const previousOutcome = this.getPreviousCompletion(); |
| 534 | if (!previousOutcome) { |
| 535 | return undefined; |
| 536 | } |
| 537 | |
| 538 | const filepath = localPathOrUriToPath(previousOutcome.fileUri); |
| 539 | |
| 540 | // If we don't have a precomputed list of next editable regions already, compute and load it. |
| 541 | if (this.nextEditableRegionsInTheCurrentChain.length === 0) { |
| 542 | this.loadNextEditableRegionsInTheCurrentChain( |
| 543 | (await getNextEditableRegion(EditableRegionStrategy.Static, { |
| 544 | cursorPosition: previousOutcome.cursorPosition, |
| 545 | filepath, |
| 546 | ide: this.ide, |
| 547 | })) ?? [], |
| 548 | ); |
| 549 | |
| 550 | if (this.nextEditableRegionsInTheCurrentChain.length === 0) { |
| 551 | console.log( |
| 552 | "deleteChain called from provideInlineCompletionItemsWithChain", |
| 553 | ); |
| 554 | await this.deleteChain(); |
| 555 | return undefined; |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | // Use the frontmost RangeInFile to build an input. |
| 560 | const input = await this.buildAutocompleteInputFromChain( |
| 561 | previousOutcome, |
| 562 | this.nextEditableRegionsInTheCurrentChain[0], // this will be shifted after debouncer check |
| 563 | ctx, |
| 564 | ); |
| 565 | if (!input) { |
| 566 | return undefined; |
| 567 | } |
| 568 | |
| 569 | return await this.provideInlineCompletionItems(input, token, { |
| 570 | withChain: true, |
| 571 | }); |
| 572 | } catch (e: any) { |
| 573 | this.onError(e); |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | private buildAutocompleteInputFromChain( |
| 578 | previousOutcome: NextEditOutcome, |
| 579 | nextEditableRegion: RangeInFile, |
| 580 | ctx: { |
| 581 | completionId: string; |
| 582 | manuallyPassFileContents?: string; |
| 583 | manuallyPassPrefix?: string; |
| 584 | selectedCompletionInfo?: { |
| 585 | text: string; |
| 586 | range: Range; |
| 587 | }; |
| 588 | isUntitledFile: boolean; |
| 589 | recentlyVisitedRanges: AutocompleteCodeSnippet[]; |
| 590 | recentlyEditedRanges: RecentlyEditedRange[]; |
| 591 | }, |
| 592 | ): AutocompleteInput | undefined { |
| 593 | const input: AutocompleteInput = { |
| 594 | pos: { |
| 595 | line: nextEditableRegion.range.start.line, |
| 596 | character: nextEditableRegion.range.start.character, |
| 597 | }, |
| 598 | filepath: previousOutcome.fileUri, |
| 599 | ...ctx, |
| 600 | }; |
| 601 | |
| 602 | return input; |
| 603 | } |
| 604 | |
| 605 | public loadNextEditableRegionsInTheCurrentChain(regions: RangeInFile[]) { |
| 606 | this.nextEditableRegionsInTheCurrentChain = regions; |
| 607 | } |
| 608 | |
| 609 | public shiftNextEditableRegionsInTheCurrentChain() { |
| 610 | return this.nextEditableRegionsInTheCurrentChain.shift(); |
| 611 | } |
| 612 | |
| 613 | public getNextEditableRegionsInTheCurrentChainLength() { |
| 614 | return this.nextEditableRegionsInTheCurrentChain.length; |
| 615 | } |
| 616 | |
| 617 | public getNextEditableRegionsInTheCurrentChain(): RangeInFile[] { |
| 618 | return [...this.nextEditableRegionsInTheCurrentChain]; // Return a copy to prevent external modification |
| 619 | } |
| 620 | } |