continue-custom/core/nextEdit/providers/BaseNextEditProvider.ts
Jacob Kim f27e7c71de
feat: add user-friendly way to toggle between FIM and next edit (#7355)
* feat: don't format when model is not mercury

* chore: bump

* fix: remove mercury-coder-nextedit

* refactor: remove refs to mercury-coder-nextedit

* feat: add util function for converting model name to enum

* refactor: add new types

* refactor: create an abstract base class for providers

* refactor: add child provider for instinct

* refactor: add provider for mercury coder

* refactor: provider factory

* refactor: use factory to create model providers based on helper.modelName

* refactor: clean up redundant logic to be more provider-friendly

* add buildPromptMetadata as an abstract method

* refactor: use handlebars and provider-specific template renderers

* refactor: use this.modelProvider instead of prompt engine

* refactor: remove redundant helper

* fix: update vitest after refactor

* feat: add test for convertNextEditModelNameToEnum

* fix: add isSecurityConcern imports

* feat: add functions to return next edit menu items and update config

* fix: get rid of callbacks

* feat: render next edit menu items

* fix: get rid of redundant completion request

* feat: update next edit status on vscode workspace config update, refactor out common logic

* feat: add continue.enableNextEdit

* feat: add aborted field to check for false positives

* fix: remove zetaDataset suffix

* feat: make sure that we are tracking completions

* feat: log aborts and move id generation to the top

* feat: all requests are tracked. when request is aborted, log as aborted with zero-value data. else, graduate it from pending completion and set aborted to false

* feat: add aborted to schema

* feat: add a toggleNextEditEnabled command

* feat: show (NE) in the status bar when next edit is enabled, add keymap

* feat: add command definitions for toggleNextEditEnabled

* refactor: handle validation in VsCodeExtension

* feat: check if model does not support next edit

* feat: use better menu item labels

* fix: casing

* chore: bump

* feat: add a function to disable next edit

* feat: disable next edit before e2e tests

* chore: bump

* fix: add a small delay to wait for UI loading

* fix: NE is shown for all statuses

* fix: wait for the NE to pop up

* fix: wait longer for disableNextEdit, clear potential next edit notifications

* fix: roll back clearAllNotifications

* fix: try disabling next edit before each

* fix: revert

* feat: add sane defaults when no workspace settings are set

* fix: fall back to false

* fix: debugging

* chore: change name

* fix: try waiting for text

* debug: more debug logs

* fix: clear notifs

* fix: suppress warning

* fix: string matching

* fix: jump label overlapping with the inline tip label (#7399)

* feat: add methods to temporarily hide and show tooltip

* feat: hide the inline tooltip when the jumpmanager's tooltip is shown

* feat: focus on chat input after apply

* revert

* fix: HOTFIX local assistant loading (#7354)

* fix: local assistant loading

* fix: no need for excluding .continue/.continue

* test: cases for config.yml and config.yaml names

* feat: remove hide/show logic for creating a new svgbuilder instance

* feat: use a new svgBuilder istance

* chore: update package-lock.json

---------

Co-authored-by: uinstinct <61635505+uinstinct@users.noreply.github.com>
Co-authored-by: Dallin Romney <dallinromney@gmail.com>
Co-authored-by: Ting-Wai <40179554+tingwai@users.noreply.github.com>

---------

Co-authored-by: uinstinct <61635505+uinstinct@users.noreply.github.com>
Co-authored-by: Dallin Romney <dallinromney@gmail.com>
Co-authored-by: Ting-Wai <40179554+tingwai@users.noreply.github.com>
2025-08-26 21:54:29 -04:00

415 lines
12 KiB
TypeScript

import * as path from "path";
import { v4 as uuidv4 } from "uuid";
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
import { myersDiff } from "../../diff/myers.js";
import { DiffLine, IDE, ILLM, Position, RangeInFile } from "../../index.js";
import { countTokens } from "../../llm/countTokens.js";
import {
calculateFinalCursorPosition,
DiffGroup,
groupDiffLines,
} from "../diff/diff.js";
import { PrefetchQueue } from "../NextEditPrefetchQueue.js";
import {
ModelSpecificContext,
NextEditOutcome,
Prompt,
PromptMetadata,
} from "../types.js";
import { isWhitespaceOnlyDeletion } from "../utils.js";
export abstract class BaseNextEditProvider {
protected readonly modelName: string;
constructor(modelName: string) {
this.modelName = modelName;
}
// Leave methods as abstract when you must have the models implement their own versions.
abstract getSystemPrompt(): string;
abstract generatePrompts(context: ModelSpecificContext): Promise<Prompt[]>;
abstract extractCompletion(message: string): string;
abstract buildPromptContext(context: ModelSpecificContext): any;
abstract buildPromptMetadata(context: ModelSpecificContext): PromptMetadata;
abstract getWindowSize(): { topMargin: number; bottomMargin: number };
abstract calculateEditableRegion(
helper: HelperVars,
usingFullFileDiff: boolean,
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
};
// Methods that can be used as default fallback.
public async handlePartialFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome> {
const oldEditRangeSlice = helper.fileContents
.split("\n")
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const finalCursorPos = calculateFinalCursorPosition(
helper.pos,
editableRegionStartLine,
oldEditRangeSlice,
nextCompletion,
);
const outcome = await this.createNextEditOutcome({
helper,
startTime,
llm,
promptContent: promptMetadata.prompt.content,
completion: nextCompletion,
finalCursorPosition: finalCursorPos,
editableRegionStartLine,
editableRegionEndLine,
userEdits: promptMetadata.userEdits,
userExcerpts: promptMetadata.userExcerpts,
originalEditableRange: oldEditRangeSlice,
diffLines: [],
ide,
});
return outcome;
}
public async handleFullFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome | undefined> {
const fileSlice = helper.fileLines
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const diffLines = myersDiff(fileSlice, nextCompletion);
const diffGroups = groupDiffLines(
diffLines,
editableRegionStartLine,
5,
).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
const currentLine = helper.pos.line;
const prefetchQueue = PrefetchQueue.getInstance();
const cursorLocalDiffGroup = await this.processDiffGroups(
diffGroups,
currentLine,
helper,
startTime,
llm,
prefetchQueue,
promptMetadata,
ide,
);
if (cursorLocalDiffGroup) {
return await this.createOutcomeFromDiffGroup(
cursorLocalDiffGroup,
helper,
startTime,
llm,
helper.input.completionId,
true,
promptMetadata,
ide,
);
}
return undefined;
}
/**
* Process diff groups and find the one containing the cursor.
*/
private async processDiffGroups(
diffGroups: DiffGroup[],
currentLine: number,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<DiffGroup | undefined> {
let cursorGroup: DiffGroup | undefined;
for (const group of diffGroups) {
if (currentLine >= group.startLine && currentLine <= group.endLine) {
cursorGroup = group;
} else {
await this.addDiffGroupToPrefetchQueue(
group,
helper,
startTime,
llm,
prefetchQueue,
promptMetadata,
ide,
);
}
}
return cursorGroup;
}
private async addDiffGroupToPrefetchQueue(
group: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<void> {
// Extract lines that are not old.
const groupContent = group.lines
.filter((l) => l.type !== "old")
.map((l) => l.line)
.join("\n");
const rangeInFile: RangeInFile = {
filepath: helper.filepath,
range: {
start: { line: group.startLine, character: 0 },
end: {
line: group.endLine,
character: group.lines[group.lines.length - 1].line.length,
},
},
};
// Extract lines that are not new.
const originalContent = group.lines
.filter((l) => l.type !== "new")
.map((l) => l.line)
.join("\n");
const groupOutcome = await this.createNextEditOutcome({
helper,
startTime,
llm,
promptContent: promptMetadata.prompt.content,
completion: groupContent,
finalCursorPosition: {
line: group.endLine,
character: group.lines[group.lines.length - 1].line.length,
},
editableRegionStartLine: group.startLine,
editableRegionEndLine: group.endLine,
userEdits: promptMetadata.userEdits,
userExcerpts: promptMetadata.userExcerpts,
originalEditableRange: originalContent,
cursorPosition: { line: group.startLine, character: 0 },
completionId: uuidv4(), // Generate a new ID for this prefetched item.
diffLines: group.lines,
ide,
});
prefetchQueue.enqueueProcessed({
location: rangeInFile,
outcome: groupOutcome,
});
}
private async createOutcomeFromDiffGroup(
diffGroup: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
completionId: string,
isCurrentCursorGroup: boolean,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome> {
const groupContent = diffGroup.lines
.filter((l) => l.type !== "old")
.map((l) => l.line)
.join("\n");
const originalContent = diffGroup.lines
.filter((l) => l.type !== "new")
.map((l) => l.line)
.join("\n");
const cursorPos = isCurrentCursorGroup
? helper.pos
: { line: diffGroup.startLine, character: 0 };
const finalCursorPos = calculateFinalCursorPosition(
cursorPos,
diffGroup.startLine,
originalContent,
groupContent,
);
const outcomeNext = await this.createNextEditOutcome({
helper,
startTime,
llm,
promptContent: promptMetadata.prompt.content,
completion: groupContent,
finalCursorPosition: finalCursorPos,
editableRegionStartLine: diffGroup.startLine,
editableRegionEndLine: diffGroup.endLine,
userEdits: promptMetadata.userEdits,
userExcerpts: promptMetadata.userExcerpts,
originalEditableRange: originalContent,
cursorPosition: cursorPos,
completionId,
diffLines: diffGroup.lines,
ide,
});
return outcomeNext;
}
protected async createNextEditOutcome(outcomeCtx: {
helper: HelperVars;
startTime: number;
llm: ILLM;
promptContent: string;
completion: string;
finalCursorPosition: Position;
editableRegionStartLine: number;
editableRegionEndLine: number;
userEdits: string;
userExcerpts: string;
originalEditableRange: string;
cursorPosition?: Position;
completionId?: string;
diffLines: DiffLine[];
ide: IDE;
}): Promise<NextEditOutcome> {
return {
elapsed: Date.now() - outcomeCtx.startTime,
modelProvider: outcomeCtx.llm.underlyingProviderName,
modelName: outcomeCtx.llm.model,
completionOptions: null,
completionId:
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath),
uniqueId: await outcomeCtx.ide.getUniqueId(),
timestamp: Date.now(),
fileUri: outcomeCtx.helper.filepath,
workspaceDirUri:
outcomeCtx.helper.workspaceUris[0] ??
path.dirname(outcomeCtx.helper.filepath),
prompt: outcomeCtx.promptContent,
userEdits: outcomeCtx.userEdits ?? "",
userExcerpts: outcomeCtx.userExcerpts ?? "",
originalEditableRange: outcomeCtx.originalEditableRange ?? "",
completion: outcomeCtx.completion,
cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
finalCursorPosition: outcomeCtx.finalCursorPosition,
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
diffLines: outcomeCtx.diffLines,
...outcomeCtx.helper.options,
};
}
// Shared utility for calculating editable regions.
protected calculateOptimalEditableRegion(
helper: HelperVars,
maxTokens: number = 512,
heuristic: "fourChars" | "tokenizer" = "tokenizer",
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
} {
const cursorLine = helper.pos.line;
const fileLines = helper.fileLines;
let editableRegionStartLine = cursorLine;
let editableRegionEndLine = cursorLine;
let currentContent = fileLines[cursorLine];
let totalTokens =
heuristic === "tokenizer"
? countTokens(currentContent, helper.modelName)
: Math.ceil(currentContent.length / 4);
let addingAbove = true;
while (totalTokens < maxTokens) {
let addedLine = false;
if (addingAbove) {
if (editableRegionStartLine > 0) {
editableRegionStartLine--;
const lineContent = fileLines[editableRegionStartLine];
const lineTokens =
heuristic === "tokenizer"
? countTokens(lineContent, helper.modelName)
: Math.ceil(lineContent.length / 4);
totalTokens += lineTokens;
addedLine = true;
}
} else {
if (editableRegionEndLine < fileLines.length - 1) {
editableRegionEndLine++;
const lineContent = fileLines[editableRegionEndLine];
const lineTokens =
heuristic === "tokenizer"
? countTokens(lineContent, helper.modelName)
: Math.ceil(lineContent.length / 4);
totalTokens += lineTokens;
addedLine = true;
}
}
if (!addedLine) {
if (
editableRegionStartLine === 0 &&
editableRegionEndLine === fileLines.length - 1
) {
break;
}
addingAbove = !addingAbove;
continue;
}
if (totalTokens > maxTokens) {
if (addingAbove) {
editableRegionStartLine++;
} else {
editableRegionEndLine--;
}
break;
}
addingAbove = !addingAbove;
}
return {
editableRegionStartLine,
editableRegionEndLine,
};
}
// Optional methods with defaults.
shouldInjectUniqueToken(): boolean {
return false;
}
getUniqueToken(): string | null {
return null;
}
}