Elffuss BraidHub

kikocis/continue public

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