Elffuss BraidHub

kikocis/continue public

245005345e6e · 29.9 KiBRawPermalink
1import * as path from "path";
2import { v4 as uuidv4 } from "uuid";
3import { ConfigHandler } from "../config/ConfigHandler.js";
4import {
5 ChatMessage,
6 DiffLine,
7 IDE,
8 ILLM,
9 Position,
10 Range,
11 RangeInFile,
12} from "../index.js";
13import OpenAI from "../llm/llms/OpenAI.js";
14import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
15
16import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
17
18import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
19import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
20import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
21import {
22 getAllSnippetsWithoutRace,
23 SnippetPayload,
24} from "../autocomplete/snippets/index.js";
25import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
26import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
27import { getAst } from "../autocomplete/util/ast.js";
28import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
29import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
30import { HelperVars } from "../autocomplete/util/HelperVars.js";
31import { AutocompleteInput } from "../autocomplete/util/types.js";
32import { myersDiff } from "../diff/myers.js";
33import { modelSupportsNextEdit } from "../llm/autodetect.js";
34import { countTokens } from "../llm/countTokens.js";
35import { localPathOrUriToPath } from "../util/pathToUri.js";
36import { replaceEscapedCharacters } from "../util/text.js";
37import {
38 MERCURY_CODE_TO_EDIT_OPEN,
39 MERCURY_SYSTEM_PROMPT,
40 NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
41 NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
42} from "./constants.js";
43import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
44import {
45 calculateFinalCursorPosition,
46 DiffGroup,
47 groupDiffLines,
48} from "./diff/diff.js";
49import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
50import { NextEditLoggingService } from "./NextEditLoggingService.js";
51import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
52import {
53 renderDefaultSystemPrompt,
54 renderDefaultUserPrompt,
55 renderPrompt,
56} from "./templating/NextEditPromptEngine.js";
57import {
58 NextEditOutcome,
59 Prompt,
60 PromptMetadata,
61 RecentlyEditedRange,
62} from "./types.js";
63
64const autocompleteCache = AutocompleteLruCache.get();
65
66// Errors that can be expected on occasion even during normal functioning should not be shown.
67// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
68const ERRORS_TO_IGNORE = [
69 // From Ollama
70 "unexpected server status",
71 "operation was aborted",
72];
73
74export class NextEditProvider {
75 private static instance: NextEditProvider | null = null;
76
77 private autocompleteCache = AutocompleteLruCache.get();
78 public errorsShown: Set<string> = new Set();
79 private bracketMatchingService = new BracketMatchingService();
80 private debouncer = new AutocompleteDebouncer();
81 private completionStreamer: CompletionStreamer;
82 private loggingService: NextEditLoggingService;
83 private contextRetrievalService: ContextRetrievalService;
84 private endpointType: "default" | "fineTuned";
85 private diffContext: string = "";
86 private promptMetadata: PromptMetadata | null = null;
87 private currentEditChainId: string | null = null;
88 private previousRequest: AutocompleteInput | null = null;
89 private previousCompletions: NextEditOutcome[] = [];
90 // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
91
92 private constructor(
93 private readonly configHandler: ConfigHandler,
94 private readonly ide: IDE,
95 private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
96 private readonly _onError: (e: any) => void,
97 private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
98 endpointType: "default" | "fineTuned",
99 ) {
100 this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
101 this.contextRetrievalService = new ContextRetrievalService(this.ide);
102 this.endpointType = endpointType;
103 this.loggingService = NextEditLoggingService.getInstance();
104 }
105
106 public static initialize(
107 configHandler: ConfigHandler,
108 ide: IDE,
109 injectedGetLlm: () => Promise<ILLM | undefined>,
110 onError: (e: any) => void,
111 getDefinitionsFromLsp: GetLspDefinitionsFunction,
112 endpointType: "default" | "fineTuned",
113 ): NextEditProvider {
114 if (!NextEditProvider.instance) {
115 NextEditProvider.instance = new NextEditProvider(
116 configHandler,
117 ide,
118 injectedGetLlm,
119 onError,
120 getDefinitionsFromLsp,
121 endpointType,
122 );
123 }
124 return NextEditProvider.instance;
125 }
126
127 public static getInstance(): NextEditProvider {
128 if (!NextEditProvider.instance) {
129 throw new Error(
130 "NextEditProvider has not been initialized. Call initialize() first.",
131 );
132 }
133 return NextEditProvider.instance;
134 }
135
136 public addDiffToContext(diff: string): void {
137 this.diffContext = diff;
138 }
139
140 private async _prepareLlm(): Promise<ILLM | undefined> {
141 const llm = await this._injectedGetLlm();
142
143 if (!llm) {
144 return undefined;
145 }
146
147 // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022
148 if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
149 llm.model = llm.completionOptions.model;
150 }
151
152 // Ignore empty API keys for Mistral since we currently write
153 // a template provider without one during onboarding
154 if (llm.providerName === "mistral" && llm.apiKey === "") {
155 return undefined;
156 }
157
158 // Set temperature (but don't override)
159 if (llm.completionOptions.temperature === undefined) {
160 llm.completionOptions.temperature = 0.01;
161 }
162
163 if (llm instanceof OpenAI) {
164 llm.useLegacyCompletionsEndpoint = true;
165 }
166 // TODO: Resolve import error with TRIAL_FIM_MODEL
167 // else if (
168 // llm.providerName === "free-trial" &&
169 // llm.model !== TRIAL_FIM_MODEL
170 // ) {
171 // llm.model = TRIAL_FIM_MODEL;
172 // }
173
174 return llm;
175 }
176
177 private onError(e: any) {
178 if (
179 ERRORS_TO_IGNORE.some((err) =>
180 typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
181 )
182 ) {
183 return;
184 }
185
186 console.warn("Error generating autocompletion: ", e);
187 if (!this.errorsShown.has(e.message)) {
188 this.errorsShown.add(e.message);
189 this._onError(e);
190 }
191 }
192
193 public cancel() {
194 this.loggingService.cancel();
195 }
196
197 public accept(completionId: string) {
198 const outcome = this.loggingService.accept(completionId);
199 if (!outcome) {
200 return;
201 }
202 }
203
204 public reject(completionId: string) {
205 const outcome = this.loggingService.reject(completionId);
206 if (!outcome) {
207 return;
208 }
209 }
210
211 public markDisplayed(completionId: string, outcome: NextEditOutcome) {
212 this.loggingService.markDisplayed(completionId, outcome);
213 }
214
215 private async _getAutocompleteOptions() {
216 const { config } = await this.configHandler.loadConfig();
217 const options = {
218 ...DEFAULT_AUTOCOMPLETE_OPTS,
219 ...config?.tabAutocompleteOptions,
220 };
221 return options;
222 }
223
224 public chainExists(): boolean {
225 return this.currentEditChainId !== null;
226 }
227
228 public getChainLength(): number {
229 return this.previousCompletions.length;
230 }
231
232 public getPreviousCompletion(): NextEditOutcome | null {
233 return this.previousCompletions[0];
234 }
235
236 public async deleteChain(): Promise<void> {
237 PrefetchQueue.getInstance().abort();
238
239 this.currentEditChainId = null;
240 this.previousCompletions = [];
241 // TODO: this should be cleaned up in the prefetch queue.
242 // this.nextEditableRegionsInTheCurrentChain = [];
243
244 if (this.previousRequest) {
245 const fileContent = (
246 await this.ide.readFile(this.previousRequest.filepath)
247 ).toString();
248 const ast = await getAst(this.previousRequest.filepath, fileContent);
249 if (ast) {
250 DocumentHistoryTracker.getInstance().push(
251 localPathOrUriToPath(this.previousRequest.filepath),
252 fileContent,
253 ast,
254 );
255 }
256 }
257 }
258
259 public startChain(id?: string) {
260 this.currentEditChainId = id ?? uuidv4();
261 }
262
263 public getChain() {
264 return this.previousCompletions;
265 }
266
267 public isStartOfChain() {
268 return this.previousCompletions.length === 1;
269 }
270
271 public async provideInlineCompletionItems(
272 input: AutocompleteInput,
273 token: AbortSignal | undefined,
274 opts?: {
275 withChain: boolean;
276 usingFullFileDiff: boolean;
277 },
278 ): Promise<NextEditOutcome | undefined> {
279 try {
280 this.previousRequest = input;
281 const {
282 token: abortToken,
283 startTime,
284 helper,
285 } = await this._initializeCompletionRequest(input, token);
286 if (!helper) return undefined;
287
288 const { editableRegionStartLine, editableRegionEndLine, prompts } =
289 await this._generatePrompts(helper, opts);
290
291 if (this.endpointType === "default") {
292 return await this._handleDefaultEndpointCompletion(
293 helper,
294 prompts,
295 abortToken,
296 startTime,
297 editableRegionEndLine,
298 );
299 } else {
300 return await this._handleFineTunedEndpointCompletion(
301 helper,
302 prompts,
303 abortToken,
304 startTime,
305 editableRegionStartLine,
306 editableRegionEndLine,
307 opts,
308 );
309 }
310 } catch (e: any) {
311 this.onError(e);
312 } finally {
313 this.loggingService.deleteAbortController(input.completionId);
314 }
315 }
316
317 private async _initializeCompletionRequest(
318 input: AutocompleteInput,
319 token: AbortSignal | undefined,
320 ): Promise<{
321 token: AbortSignal;
322 startTime: number;
323 helper: HelperVars | undefined;
324 }> {
325 // Create abort signal if not given.
326 if (!token) {
327 const controller = this.loggingService.createAbortController(
328 input.completionId,
329 );
330 token = controller.signal;
331 }
332 const startTime = Date.now();
333 const options = await this._getAutocompleteOptions();
334
335 // Debounce.
336 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
337 return { token, startTime, helper: undefined };
338 }
339
340 const llm = await this._prepareLlm();
341 if (!llm) {
342 return { token, startTime, helper: undefined };
343 }
344
345 // In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts.
346 // For other editors, this check should be done in their respective config reloaders.
347 // This is left for a final check.
348 if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
349 console.error(`${llm.model} is not capable of next edit.`);
350 return { token, startTime, helper: undefined };
351 }
352
353 if (llm.promptTemplates?.autocomplete) {
354 options.template = llm.promptTemplates.autocomplete as string;
355 }
356
357 const helper = await HelperVars.create(input, options, llm.model, this.ide);
358
359 if (await shouldPrefilter(helper, this.ide)) {
360 return { token, startTime, helper: undefined };
361 }
362
363 return { token, startTime, helper };
364 }
365
366 private async _generatePrompts(
367 helper: HelperVars,
368 opts?: {
369 withChain: boolean;
370 usingFullFileDiff: boolean;
371 },
372 ): Promise<{
373 editableRegionStartLine: number;
374 editableRegionEndLine: number;
375 prompts: Prompt[];
376 }> {
377 const [snippetPayload, workspaceDirs] = await Promise.all([
378 getAllSnippetsWithoutRace({
379 helper,
380 ide: this.ide,
381 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
382 contextRetrievalService: this.contextRetrievalService,
383 }),
384 this.ide.getWorkspaceDirs(),
385 ]);
386
387 const { editableRegionStartLine, editableRegionEndLine } =
388 opts?.usingFullFileDiff
389 ? this._calculateOptimalEditableRegion(helper, "tokenizer")
390 : {
391 editableRegionStartLine: Math.max(
392 helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
393 0,
394 ),
395 editableRegionEndLine: Math.min(
396 helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
397 helper.fileLines.length - 1,
398 ),
399 };
400
401 // const editableRegionStartLine = opts?.usingFullFileDiff
402 // ? 0
403 // : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0);
404
405 // const editableRegionEndLine = opts?.usingFullFileDiff
406 // ? helper.fileLines.length - 1
407 // : Math.min(
408 // helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
409 // helper.fileLines.length - 1,
410 // );
411
412 const prompts: Prompt[] = [];
413
414 if (this.endpointType === "default") {
415 prompts.push(renderDefaultSystemPrompt());
416 prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
417 } else {
418 prompts.push(
419 ...(await this._generateFineTunedPrompts(
420 helper,
421 snippetPayload,
422 editableRegionStartLine,
423 editableRegionEndLine,
424 )),
425 );
426 }
427
428 return { editableRegionStartLine, editableRegionEndLine, prompts };
429 }
430
431 private _calculateOptimalEditableRegion(
432 helper: HelperVars,
433 heuristic: "fourChars" | "tokenizer" = "tokenizer",
434 ): {
435 editableRegionStartLine: number;
436 editableRegionEndLine: number;
437 } {
438 const cursorLine = helper.pos.line;
439 const fileLines = helper.fileLines;
440 const MAX_TOKENS = 512;
441
442 // Initialize with cursor line.
443 let editableRegionStartLine = cursorLine;
444 let editableRegionEndLine = cursorLine;
445
446 // Get initial content and token count.
447 let currentContent = fileLines[cursorLine];
448 let totalTokens =
449 heuristic === "tokenizer"
450 ? countTokens(currentContent, helper.modelName)
451 : Math.ceil(currentContent.length / 4);
452
453 // Expand outward alternating between adding lines above and below.
454 let addingAbove = true;
455
456 while (totalTokens < MAX_TOKENS) {
457 let addedLine = false;
458
459 if (addingAbove) {
460 // Try to add a line above.
461 if (editableRegionStartLine > 0) {
462 editableRegionStartLine--;
463 const lineContent = fileLines[editableRegionStartLine];
464 const lineTokens =
465 heuristic === "tokenizer"
466 ? countTokens(lineContent, helper.modelName)
467 : Math.ceil(lineContent.length / 4);
468
469 totalTokens += lineTokens;
470 addedLine = true;
471 }
472 } else {
473 // Try to add a line below.
474 if (editableRegionEndLine < fileLines.length - 1) {
475 editableRegionEndLine++;
476 const lineContent = fileLines[editableRegionEndLine];
477 const lineTokens =
478 heuristic === "tokenizer"
479 ? countTokens(lineContent, helper.modelName)
480 : Math.ceil(lineContent.length / 4);
481
482 totalTokens += lineTokens;
483 addedLine = true;
484 }
485 }
486
487 // If we can't add in the current direction, try the other.
488 if (!addedLine) {
489 // If we're already at both file boundaries, we're done.
490 if (
491 editableRegionStartLine === 0 &&
492 editableRegionEndLine === fileLines.length - 1
493 ) {
494 break;
495 }
496
497 // If we couldn't add in one direction, force the next attempt in the other direction.
498 addingAbove = !addingAbove;
499 continue;
500 }
501
502 // If we exceeded the token limit, revert the last addition.
503 if (totalTokens > MAX_TOKENS) {
504 if (addingAbove) {
505 editableRegionStartLine++;
506 } else {
507 editableRegionEndLine--;
508 }
509 break;
510 }
511
512 // Alternate between adding above and below for balanced context.
513 addingAbove = !addingAbove;
514 }
515
516 return {
517 editableRegionStartLine,
518 editableRegionEndLine,
519 };
520 }
521
522 private async _generateFineTunedPrompts(
523 helper: HelperVars,
524 snippetPayload: SnippetPayload,
525 editableRegionStartLine: number,
526 editableRegionEndLine: number,
527 ): Promise<Prompt[]> {
528 const historyDiff = createDiff({
529 beforeContent:
530 DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
531 localPathOrUriToPath(helper.filepath),
532 ) ?? "",
533 afterContent: helper.fileContents,
534 filePath: helper.filepath,
535 diffType: DiffFormatType.Unified,
536 contextLines: 3,
537 });
538
539 const modelName = helper.modelName;
540 let ctx: any;
541
542 if (modelName.includes("mercury-coder-nextedit")) {
543 ctx = {
544 recentlyViewedCodeSnippets:
545 snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
546 filepath: snip.filepath,
547 content: snip.content,
548 })) ?? [],
549 currentFileContent: helper.fileContents,
550 editableRegionStartLine,
551 editableRegionEndLine,
552 editDiffHistory: this.diffContext,
553 currentFilePath: helper.filepath,
554 };
555 } else if (modelName.includes("model-1")) {
556 ctx = {
557 userEdits: historyDiff ?? this.diffContext,
558 languageShorthand: helper.lang.name,
559 userExcerpts: helper.fileContents,
560 };
561 } else {
562 ctx = {};
563 }
564
565 const promptMetadata = await renderPrompt(helper, ctx);
566 this.promptMetadata = promptMetadata;
567
568 const systemPrompt: Prompt = {
569 role: "system",
570 content: MERCURY_SYSTEM_PROMPT,
571 };
572
573 return [systemPrompt, promptMetadata.prompt];
574 }
575
576 private async _handleDefaultEndpointCompletion(
577 helper: HelperVars,
578 prompts: Prompt[],
579 token: AbortSignal,
580 startTime: number,
581 editableRegionEndLine: number,
582 ): Promise<NextEditOutcome | undefined> {
583 const llm = await this._prepareLlm();
584 if (!llm) return undefined;
585
586 const msg: ChatMessage = await llm.chat(prompts, token);
587
588 if (typeof msg.content === "string") {
589 const nextCompletion = JSON.parse(msg.content).newCode;
590 const finalCursorPos: Position = {
591 line: editableRegionEndLine,
592 character: 0,
593 };
594
595 const outcomeNext = await this._createNextEditOutcome({
596 helper,
597 startTime,
598 llm,
599 promptContent: prompts.join("\n"),
600 completion: nextCompletion,
601 finalCursorPosition: finalCursorPos,
602 editableRegionStartLine: 0,
603 editableRegionEndLine: 0,
604 userEdits: "",
605 userExcerpts: "",
606 originalEditableRange: "",
607 diffLines: [],
608 });
609
610 // Mark as displayed for JetBrains extension
611 await this._markDisplayedIfJetBrains(
612 helper.input.completionId,
613 outcomeNext,
614 );
615
616 return outcomeNext;
617 }
618
619 return undefined;
620 }
621
622 private async _handleFineTunedEndpointCompletion(
623 helper: HelperVars,
624 prompts: Prompt[],
625 token: AbortSignal,
626 startTime: number,
627 editableRegionStartLine: number,
628 editableRegionEndLine: number,
629 opts?: {
630 withChain: boolean;
631 usingFullFileDiff: boolean;
632 },
633 ): Promise<NextEditOutcome | undefined> {
634 const llm = await this._prepareLlm();
635 if (!llm) return undefined;
636
637 const msg: ChatMessage = await llm.chat(prompts, token);
638
639 if (typeof msg.content !== "string") {
640 return undefined;
641 }
642
643 const nextCompletion = msg.content.split(
644 `${MERCURY_CODE_TO_EDIT_OPEN}\n`,
645 )[1]
646 ? replaceEscapedCharacters(
647 msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1],
648 ).replace(/\n$/, "")
649 : "";
650
651 if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
652 return await this._handlePartialFileDiff(
653 helper,
654 startTime,
655 llm,
656 nextCompletion,
657 editableRegionStartLine,
658 editableRegionEndLine,
659 );
660 } else {
661 return await this._handleFullFileDiff(
662 helper,
663 editableRegionStartLine,
664 editableRegionEndLine,
665 startTime,
666 llm,
667 nextCompletion,
668 );
669 }
670 }
671
672 private async _handlePartialFileDiff(
673 helper: HelperVars,
674 startTime: number,
675 llm: ILLM,
676 nextCompletion: string,
677 editableRegionStartLine: number,
678 editableRegionEndLine: number,
679 ): Promise<NextEditOutcome | undefined> {
680 const oldEditRangeSlice = helper.fileContents
681 .split("\n")
682 .slice(editableRegionStartLine, editableRegionEndLine + 1)
683 .join("\n");
684
685 const finalCursorPos = calculateFinalCursorPosition(
686 helper.pos,
687 editableRegionStartLine,
688 oldEditRangeSlice,
689 nextCompletion,
690 );
691
692 const outcomeNext = await this._createNextEditOutcome({
693 helper,
694 startTime,
695 llm,
696 promptContent: this.promptMetadata!.prompt.content,
697 completion: nextCompletion,
698 finalCursorPosition: finalCursorPos,
699 editableRegionStartLine,
700 editableRegionEndLine,
701 userEdits: this.promptMetadata!.userEdits,
702 userExcerpts: this.promptMetadata!.userExcerpts,
703 originalEditableRange: oldEditRangeSlice,
704 diffLines: [],
705 });
706
707 this.previousCompletions.push(outcomeNext);
708
709 // Mark as displayed for JetBrains extension
710 await this._markDisplayedIfJetBrains(
711 helper.input.completionId,
712 outcomeNext,
713 );
714
715 return outcomeNext;
716 }
717
718 private async _handleFullFileDiff(
719 helper: HelperVars,
720 editableRegionStartLine: number,
721 editableRegionEndLine: number,
722 startTime: number,
723 llm: ILLM,
724 nextCompletion: string,
725 ): Promise<NextEditOutcome | undefined> {
726 const fileSlice = helper.fileLines
727 .slice(editableRegionStartLine, editableRegionEndLine + 1)
728 .join("\n");
729 const diffLines = myersDiff(fileSlice, nextCompletion);
730 const diffGroups = groupDiffLines(diffLines, editableRegionStartLine, 5);
731 const currentLine = helper.pos.line;
732 let cursorLocalDiffGroup: DiffGroup | undefined;
733 const prefetchQueue = PrefetchQueue.getInstance();
734
735 // Process diff groups and find the one containing the cursor
736 await this._processDiffGroups(
737 diffGroups,
738 currentLine,
739 helper,
740 startTime,
741 llm,
742 prefetchQueue,
743 );
744
745 // Handle the diff group containing the cursor if found
746 if (cursorLocalDiffGroup) {
747 return await this._createOutcomeFromDiffGroup(
748 cursorLocalDiffGroup,
749 helper,
750 startTime,
751 llm,
752 helper.input.completionId,
753 true,
754 );
755 } else if (diffGroups.length > 0) {
756 // Fallback to first diff group if cursor's group not found
757 return await this._createOutcomeFromDiffGroup(
758 diffGroups[0],
759 helper,
760 startTime,
761 llm,
762 helper.input.completionId,
763 false,
764 );
765 }
766
767 return undefined;
768 }
769
770 private async _processDiffGroups(
771 diffGroups: DiffGroup[],
772 currentLine: number,
773 helper: HelperVars,
774 startTime: number,
775 llm: ILLM,
776 prefetchQueue: PrefetchQueue,
777 ): Promise<DiffGroup | undefined> {
778 let cursorGroup: DiffGroup | undefined;
779
780 console.log("diffGroups:");
781 console.log(diffGroups);
782
783 for (const group of diffGroups) {
784 if (currentLine >= group.startLine && currentLine <= group.endLine) {
785 cursorGroup = group;
786 } else {
787 // Add non-cursor groups to prefetch queue
788 await this._addDiffGroupToPrefetchQueue(
789 group,
790 helper,
791 startTime,
792 llm,
793 prefetchQueue,
794 );
795 }
796 }
797
798 return cursorGroup;
799 }
800
801 private async _addDiffGroupToPrefetchQueue(
802 group: DiffGroup,
803 helper: HelperVars,
804 startTime: number,
805 llm: ILLM,
806 prefetchQueue: PrefetchQueue,
807 ): Promise<void> {
808 const groupContent = group.lines
809 .filter((l) => l.type !== "old")
810 .map((l) => l.line)
811 .join("\n");
812
813 // Create a range for this diff group
814 const rangeInFile: RangeInFile = {
815 filepath: helper.filepath,
816 range: {
817 start: { line: group.startLine, character: 0 },
818 end: {
819 line: group.endLine,
820 character: group.lines[group.lines.length - 1].line.length,
821 },
822 },
823 };
824
825 const originalContent = group.lines
826 .filter((l) => l.type !== "new")
827 .map((l) => l.line)
828 .join("\n");
829
830 // Build outcome for this diff group
831 const groupOutcome = await this._createNextEditOutcome({
832 helper,
833 startTime,
834 llm,
835 promptContent: this.promptMetadata!.prompt.content,
836 completion: groupContent,
837 finalCursorPosition: {
838 line: group.endLine,
839 character: group.lines[group.lines.length - 1].line.length,
840 },
841 editableRegionStartLine: group.startLine,
842 editableRegionEndLine: group.endLine,
843 userEdits: this.promptMetadata!.userEdits,
844 userExcerpts: this.promptMetadata!.userExcerpts,
845 originalEditableRange: originalContent,
846 cursorPosition: { line: group.startLine, character: 0 },
847 completionId: uuidv4(), // Generate a new ID for this prefetched item
848 diffLines: group.lines,
849 });
850
851 // Add to prefetch queue
852 prefetchQueue.enqueueProcessed({
853 location: rangeInFile,
854 outcome: groupOutcome,
855 });
856 }
857
858 private async _createOutcomeFromDiffGroup(
859 diffGroup: DiffGroup,
860 helper: HelperVars,
861 startTime: number,
862 llm: ILLM,
863 completionId: string,
864 isCurrentCursorGroup: boolean,
865 ): Promise<NextEditOutcome> {
866 const groupContent = diffGroup.lines
867 .filter((l) => l.type !== "old")
868 .map((line) => line.line)
869 .join("\n");
870
871 const originalContent = diffGroup.lines
872 .filter((l) => l.type !== "new")
873 .map((l) => l.line)
874 .join("\n");
875
876 // Use the actual cursor position if this is the group containing the cursor
877 // Otherwise use the start of the diff group
878 const cursorPos = isCurrentCursorGroup
879 ? helper.pos
880 : { line: diffGroup.startLine, character: 0 };
881
882 const finalCursorPos = calculateFinalCursorPosition(
883 cursorPos,
884 diffGroup.startLine,
885 originalContent,
886 groupContent,
887 );
888
889 const outcomeNext = await this._createNextEditOutcome({
890 helper,
891 startTime,
892 llm,
893 promptContent: this.promptMetadata!.prompt.content,
894 completion: groupContent,
895 finalCursorPosition: finalCursorPos,
896 editableRegionStartLine: diffGroup.startLine,
897 editableRegionEndLine: diffGroup.endLine,
898 userEdits: this.promptMetadata!.userEdits,
899 userExcerpts: this.promptMetadata!.userExcerpts,
900 originalEditableRange: originalContent,
901 cursorPosition: cursorPos,
902 completionId,
903 diffLines: diffGroup.lines,
904 });
905
906 this.previousCompletions.push(outcomeNext);
907
908 // Mark as displayed for JetBrains
909 await this._markDisplayedIfJetBrains(completionId, outcomeNext);
910
911 return outcomeNext;
912 }
913
914 private async _createNextEditOutcome(outcomeCtx: {
915 helper: HelperVars;
916 startTime: number;
917 llm: ILLM;
918 promptContent: string;
919 completion: string;
920 finalCursorPosition: Position;
921 editableRegionStartLine: number;
922 editableRegionEndLine: number;
923 userEdits: string;
924 userExcerpts: string;
925 originalEditableRange: string;
926 cursorPosition?: Position;
927 completionId?: string;
928 diffLines: DiffLine[];
929 }): Promise<NextEditOutcome> {
930 return {
931 elapsed: Date.now() - outcomeCtx.startTime,
932 modelProvider: outcomeCtx.llm.underlyingProviderName,
933 modelName: outcomeCtx.llm.model + ":zetaDataset",
934 completionOptions: null,
935 completionId:
936 outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
937 gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath),
938 uniqueId: await this.ide.getUniqueId(),
939 timestamp: Date.now(),
940 fileUri: outcomeCtx.helper.filepath,
941 workspaceDirUri:
942 outcomeCtx.helper.workspaceUris[0] ??
943 path.dirname(outcomeCtx.helper.filepath),
944 prompt: outcomeCtx.promptContent,
945 userEdits: outcomeCtx.userEdits ?? "",
946 userExcerpts: outcomeCtx.userExcerpts ?? "",
947 originalEditableRange: outcomeCtx.originalEditableRange ?? "",
948 completion: outcomeCtx.completion,
949 cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
950 finalCursorPosition: outcomeCtx.finalCursorPosition,
951 editableRegionStartLine: outcomeCtx.editableRegionStartLine,
952 editableRegionEndLine: outcomeCtx.editableRegionEndLine,
953 diffLines: outcomeCtx.diffLines,
954 ...outcomeCtx.helper.options,
955 };
956 }
957
958 private async _markDisplayedIfJetBrains(
959 completionId: string,
960 outcome: NextEditOutcome,
961 ): Promise<void> {
962 const ideType = (await this.ide.getIdeInfo()).ideType;
963 if (ideType === "jetbrains") {
964 this.markDisplayed(completionId, outcome);
965 }
966 }
967
968 public async provideInlineCompletionItemsWithChain(
969 ctx: {
970 completionId: string;
971 manuallyPassFileContents?: string;
972 manuallyPassPrefix?: string;
973 selectedCompletionInfo?: {
974 text: string;
975 range: Range;
976 };
977 isUntitledFile: boolean;
978 recentlyVisitedRanges: AutocompleteCodeSnippet[];
979 recentlyEditedRanges: RecentlyEditedRange[];
980 },
981 nextEditLocation: RangeInFile,
982 token: AbortSignal | undefined,
983 usingFullFileDiff: boolean,
984 ) {
985 try {
986 const previousOutcome = this.getPreviousCompletion();
987 if (!previousOutcome) {
988 return undefined;
989 }
990
991 // Use the frontmost RangeInFile to build an input.
992 const input = this.buildAutocompleteInputFromChain(
993 previousOutcome,
994 nextEditLocation,
995 ctx,
996 );
997 if (!input) {
998 return undefined;
999 }
1000
1001 return await this.provideInlineCompletionItems(input, token, {
1002 withChain: true,
1003 usingFullFileDiff,
1004 });
1005 } catch (e: any) {
1006 this.onError(e);
1007 }
1008 }
1009
1010 private buildAutocompleteInputFromChain(
1011 previousOutcome: NextEditOutcome,
1012 nextEditableRegion: RangeInFile,
1013 ctx: {
1014 completionId: string;
1015 manuallyPassFileContents?: string;
1016 manuallyPassPrefix?: string;
1017 selectedCompletionInfo?: {
1018 text: string;
1019 range: Range;
1020 };
1021 isUntitledFile: boolean;
1022 recentlyVisitedRanges: AutocompleteCodeSnippet[];
1023 recentlyEditedRanges: RecentlyEditedRange[];
1024 },
1025 ): AutocompleteInput | undefined {
1026 const input: AutocompleteInput = {
1027 pos: {
1028 line: nextEditableRegion.range.start.line,
1029 character: nextEditableRegion.range.start.character,
1030 },
1031 filepath: previousOutcome.fileUri,
1032 ...ctx,
1033 };
1034
1035 return input;
1036 }
1037}