Elffuss BraidHub

kikocis/continue public

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