Elffuss BraidHub

kikocis/continue public

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