Elffuss BraidHub

kikocis/continue public

94f7b85f6068 · 31.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 {
37 INSTINCT_SYSTEM_PROMPT,
38 MERCURY_CODE_TO_EDIT_OPEN,
39 MERCURY_SYSTEM_PROMPT,
40 MODEL_WINDOW_SIZES,
41} from "./constants.js";
42import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
43import {
44 calculateFinalCursorPosition,
45 DiffGroup,
46 groupDiffLines,
47} from "./diff/diff.js";
48import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
49import { NextEditLoggingService } from "./NextEditLoggingService.js";
50import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
51import {
52 renderDefaultSystemPrompt,
53 renderDefaultUserPrompt,
54 renderPrompt,
55} from "./templating/NextEditPromptEngine.js";
56import {
57 NextEditOutcome,
58 Prompt,
59 PromptMetadata,
60 RecentlyEditedRange,
61} from "./types.js";
62import { isWhitespaceOnlyDeletion } from "./utils.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 const nextCompletion =
696 msg.content
697 .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
698 .replace(/\n$/, "") ?? msg.content;
699
700 if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
701 return await this._handlePartialFileDiff(
702 // we could use fillFileDiff
703 helper,
704 editableRegionStartLine,
705 editableRegionEndLine,
706 startTime,
707 llm,
708 nextCompletion,
709 );
710 } else {
711 return await this._handleFullFileDiff(
712 helper,
713 editableRegionStartLine,
714 editableRegionEndLine,
715 startTime,
716 llm,
717 nextCompletion,
718 );
719 }
720 }
721
722 private async _handlePartialFileDiff(
723 helper: HelperVars,
724 editableRegionStartLine: number,
725 editableRegionEndLine: number,
726 startTime: number,
727 llm: ILLM,
728 nextCompletion: string,
729 ): Promise<NextEditOutcome | undefined> {
730 const oldEditRangeSlice = helper.fileContents
731 .split("\n")
732 .slice(editableRegionStartLine, editableRegionEndLine + 1)
733 .join("\n");
734
735 const finalCursorPos = calculateFinalCursorPosition(
736 helper.pos,
737 editableRegionStartLine,
738 oldEditRangeSlice,
739 nextCompletion,
740 );
741
742 const outcomeNext = await this._createNextEditOutcome({
743 helper,
744 startTime,
745 llm,
746 promptContent: this.promptMetadata!.prompt.content,
747 completion: nextCompletion,
748 finalCursorPosition: finalCursorPos,
749 editableRegionStartLine,
750 editableRegionEndLine,
751 userEdits: this.promptMetadata!.userEdits,
752 userExcerpts: this.promptMetadata!.userExcerpts,
753 originalEditableRange: oldEditRangeSlice,
754 diffLines: [],
755 });
756
757 this.previousCompletions.push(outcomeNext);
758
759 // Mark as displayed for JetBrains extension
760 await this._markDisplayedIfJetBrains(
761 helper.input.completionId,
762 outcomeNext,
763 );
764
765 return outcomeNext;
766 }
767
768 private async _handleFullFileDiff(
769 helper: HelperVars,
770 editableRegionStartLine: number,
771 editableRegionEndLine: number,
772 startTime: number,
773 llm: ILLM,
774 nextCompletion: string,
775 ): Promise<NextEditOutcome | undefined> {
776 const fileSlice = helper.fileLines
777 .slice(editableRegionStartLine, editableRegionEndLine + 1)
778 .join("\n");
779 const diffLines = myersDiff(fileSlice, nextCompletion);
780 const diffGroups = groupDiffLines(
781 diffLines,
782 editableRegionStartLine,
783 5,
784 ).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
785 const currentLine = helper.pos.line;
786 const prefetchQueue = PrefetchQueue.getInstance();
787
788 // Process diff groups and find the one containing the cursor
789 const cursorLocalDiffGroup = await this._processDiffGroups(
790 diffGroups,
791 currentLine,
792 helper,
793 startTime,
794 llm,
795 prefetchQueue,
796 );
797
798 // Handle the diff group containing the cursor if found
799 if (cursorLocalDiffGroup) {
800 return await this._createOutcomeFromDiffGroup(
801 cursorLocalDiffGroup,
802 helper,
803 startTime,
804 llm,
805 helper.input.completionId,
806 true,
807 );
808 // } else if (diffGroups.length > 0) {
809 // // Fallback to first diff group if cursor's group not found
810 // return await this._createOutcomeFromDiffGroup(
811 // diffGroups[0],
812 // helper,
813 // startTime,
814 // llm,
815 // helper.input.completionId,
816 // false,
817 // );
818 }
819
820 return undefined;
821 }
822
823 private async _processDiffGroups(
824 diffGroups: DiffGroup[],
825 currentLine: number,
826 helper: HelperVars,
827 startTime: number,
828 llm: ILLM,
829 prefetchQueue: PrefetchQueue,
830 ): Promise<DiffGroup | undefined> {
831 let cursorGroup: DiffGroup | undefined;
832
833 console.log("diffGroups:");
834 console.log(diffGroups);
835
836 for (const group of diffGroups) {
837 if (currentLine >= group.startLine && currentLine <= group.endLine) {
838 cursorGroup = group;
839 } else {
840 // Add non-cursor groups to prefetch queue
841 await this._addDiffGroupToPrefetchQueue(
842 group,
843 helper,
844 startTime,
845 llm,
846 prefetchQueue,
847 );
848 }
849 }
850
851 return cursorGroup;
852 }
853
854 private async _addDiffGroupToPrefetchQueue(
855 group: DiffGroup,
856 helper: HelperVars,
857 startTime: number,
858 llm: ILLM,
859 prefetchQueue: PrefetchQueue,
860 ): Promise<void> {
861 const groupContent = group.lines
862 .filter((l) => l.type !== "old")
863 .map((l) => l.line)
864 .join("\n");
865
866 // Create a range for this diff group
867 const rangeInFile: RangeInFile = {
868 filepath: helper.filepath,
869 range: {
870 start: { line: group.startLine, character: 0 },
871 end: {
872 line: group.endLine,
873 character: group.lines[group.lines.length - 1].line.length,
874 },
875 },
876 };
877
878 const originalContent = group.lines
879 .filter((l) => l.type !== "new")
880 .map((l) => l.line)
881 .join("\n");
882
883 // Build outcome for this diff group
884 const groupOutcome = await this._createNextEditOutcome({
885 helper,
886 startTime,
887 llm,
888 promptContent: this.promptMetadata!.prompt.content,
889 completion: groupContent,
890 finalCursorPosition: {
891 line: group.endLine,
892 character: group.lines[group.lines.length - 1].line.length,
893 },
894 editableRegionStartLine: group.startLine,
895 editableRegionEndLine: group.endLine,
896 userEdits: this.promptMetadata!.userEdits,
897 userExcerpts: this.promptMetadata!.userExcerpts,
898 originalEditableRange: originalContent,
899 cursorPosition: { line: group.startLine, character: 0 },
900 completionId: uuidv4(), // Generate a new ID for this prefetched item
901 diffLines: group.lines,
902 });
903
904 // Add to prefetch queue
905 prefetchQueue.enqueueProcessed({
906 location: rangeInFile,
907 outcome: groupOutcome,
908 });
909 }
910
911 private async _createOutcomeFromDiffGroup(
912 diffGroup: DiffGroup,
913 helper: HelperVars,
914 startTime: number,
915 llm: ILLM,
916 completionId: string,
917 isCurrentCursorGroup: boolean,
918 ): Promise<NextEditOutcome> {
919 const groupContent = diffGroup.lines
920 .filter((l) => l.type !== "old")
921 .map((line) => line.line)
922 .join("\n");
923
924 const originalContent = diffGroup.lines
925 .filter((l) => l.type !== "new")
926 .map((l) => l.line)
927 .join("\n");
928
929 // Use the actual cursor position if this is the group containing the cursor
930 // Otherwise use the start of the diff group
931 const cursorPos = isCurrentCursorGroup
932 ? helper.pos
933 : { line: diffGroup.startLine, character: 0 };
934
935 const finalCursorPos = calculateFinalCursorPosition(
936 cursorPos,
937 diffGroup.startLine,
938 originalContent,
939 groupContent,
940 );
941
942 const outcomeNext = await this._createNextEditOutcome({
943 helper,
944 startTime,
945 llm,
946 promptContent: this.promptMetadata!.prompt.content,
947 completion: groupContent,
948 finalCursorPosition: finalCursorPos,
949 editableRegionStartLine: diffGroup.startLine,
950 editableRegionEndLine: diffGroup.endLine,
951 userEdits: this.promptMetadata!.userEdits,
952 userExcerpts: this.promptMetadata!.userExcerpts,
953 originalEditableRange: originalContent,
954 cursorPosition: cursorPos,
955 completionId,
956 diffLines: diffGroup.lines,
957 });
958
959 this.previousCompletions.push(outcomeNext);
960
961 // Mark as displayed for JetBrains
962 await this._markDisplayedIfJetBrains(completionId, outcomeNext);
963
964 return outcomeNext;
965 }
966
967 private async _createNextEditOutcome(outcomeCtx: {
968 helper: HelperVars;
969 startTime: number;
970 llm: ILLM;
971 promptContent: string;
972 completion: string;
973 finalCursorPosition: Position;
974 editableRegionStartLine: number;
975 editableRegionEndLine: number;
976 userEdits: string;
977 userExcerpts: string;
978 originalEditableRange: string;
979 cursorPosition?: Position;
980 completionId?: string;
981 diffLines: DiffLine[];
982 }): Promise<NextEditOutcome> {
983 return {
984 elapsed: Date.now() - outcomeCtx.startTime,
985 modelProvider: outcomeCtx.llm.underlyingProviderName,
986 modelName: outcomeCtx.llm.model + ":zetaDataset",
987 completionOptions: null,
988 completionId:
989 outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
990 gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath),
991 uniqueId: await this.ide.getUniqueId(),
992 timestamp: Date.now(),
993 fileUri: outcomeCtx.helper.filepath,
994 workspaceDirUri:
995 outcomeCtx.helper.workspaceUris[0] ??
996 path.dirname(outcomeCtx.helper.filepath),
997 prompt: outcomeCtx.promptContent,
998 userEdits: outcomeCtx.userEdits ?? "",
999 userExcerpts: outcomeCtx.userExcerpts ?? "",
1000 originalEditableRange: outcomeCtx.originalEditableRange ?? "",
1001 completion: outcomeCtx.completion,
1002 cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
1003 finalCursorPosition: outcomeCtx.finalCursorPosition,
1004 editableRegionStartLine: outcomeCtx.editableRegionStartLine,
1005 editableRegionEndLine: outcomeCtx.editableRegionEndLine,
1006 diffLines: outcomeCtx.diffLines,
1007 ...outcomeCtx.helper.options,
1008 };
1009 }
1010
1011 private async _markDisplayedIfJetBrains(
1012 completionId: string,
1013 outcome: NextEditOutcome,
1014 ): Promise<void> {
1015 const ideType = (await this.ide.getIdeInfo()).ideType;
1016 if (ideType === "jetbrains") {
1017 this.markDisplayed(completionId, outcome);
1018 }
1019 }
1020
1021 public async provideInlineCompletionItemsWithChain(
1022 ctx: {
1023 completionId: string;
1024 manuallyPassFileContents?: string;
1025 manuallyPassPrefix?: string;
1026 selectedCompletionInfo?: {
1027 text: string;
1028 range: Range;
1029 };
1030 isUntitledFile: boolean;
1031 recentlyVisitedRanges: AutocompleteCodeSnippet[];
1032 recentlyEditedRanges: RecentlyEditedRange[];
1033 },
1034 nextEditLocation: RangeInFile,
1035 token: AbortSignal | undefined,
1036 usingFullFileDiff: boolean,
1037 ) {
1038 try {
1039 const previousOutcome = this.getPreviousCompletion();
1040 if (!previousOutcome) {
1041 console.log("previousOutcome is undefined");
1042 return undefined;
1043 }
1044
1045 // Use the frontmost RangeInFile to build an input.
1046 const input = this.buildAutocompleteInputFromChain(
1047 previousOutcome,
1048 nextEditLocation,
1049 ctx,
1050 );
1051 if (!input) {
1052 console.log("input is undefined");
1053 return undefined;
1054 }
1055
1056 return await this.provideInlineCompletionItems(input, token, {
1057 withChain: true,
1058 usingFullFileDiff,
1059 });
1060 } catch (e: any) {
1061 this.onError(e);
1062 }
1063 }
1064
1065 private buildAutocompleteInputFromChain(
1066 previousOutcome: NextEditOutcome,
1067 nextEditableRegion: RangeInFile,
1068 ctx: {
1069 completionId: string;
1070 manuallyPassFileContents?: string;
1071 manuallyPassPrefix?: string;
1072 selectedCompletionInfo?: {
1073 text: string;
1074 range: Range;
1075 };
1076 isUntitledFile: boolean;
1077 recentlyVisitedRanges: AutocompleteCodeSnippet[];
1078 recentlyEditedRanges: RecentlyEditedRange[];
1079 },
1080 ): AutocompleteInput | undefined {
1081 const input: AutocompleteInput = {
1082 pos: {
1083 line: nextEditableRegion.range.start.line,
1084 character: nextEditableRegion.range.start.character,
1085 },
1086 filepath: previousOutcome.fileUri,
1087 ...ctx,
1088 };
1089
1090 return input;
1091 }
1092}