Merge pull request #6896 from continuedev/jacob/con-3081
feat: handle more next edit models
This commit is contained in:
commit
09cbcdba55
16 changed files with 915 additions and 292 deletions
4
.vscode/launch.json
vendored
4
.vscode/launch.json
vendored
|
|
@ -12,8 +12,8 @@
|
|||
"cwd": "${workspaceFolder}/extensions/vscode",
|
||||
"args": [
|
||||
// Pass a directory to manually test in
|
||||
"${workspaceFolder}/core",
|
||||
"${workspaceFolder}/package.json",
|
||||
"${workspaceFolder}/manual-testing-sandbox",
|
||||
"${workspaceFolder}/manual-testing-sandbox/test.js",
|
||||
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
|
||||
],
|
||||
"pauseForSourceMap": false,
|
||||
|
|
|
|||
|
|
@ -761,6 +761,9 @@ export class Core {
|
|||
});
|
||||
|
||||
on("files/closed", async ({ data }) => {
|
||||
console.log("deleteChain called from files/closed");
|
||||
await NextEditProvider.getInstance().deleteChain();
|
||||
|
||||
try {
|
||||
const fileUris = await this.ide.getOpenFiles();
|
||||
if (fileUris) {
|
||||
|
|
|
|||
|
|
@ -385,7 +385,7 @@ async function staticJump(ctx: {
|
|||
console.log("No identifier node found near cursor position");
|
||||
return null;
|
||||
}
|
||||
console.log("closest identifier:", identifierNode.text);
|
||||
// console.log("closest identifier:", identifierNode.text);
|
||||
|
||||
// Get all references to this identifier using the IDE's API
|
||||
const references = await ide.getReferences({
|
||||
|
|
@ -401,17 +401,17 @@ async function staticJump(ctx: {
|
|||
return null;
|
||||
}
|
||||
|
||||
console.log(
|
||||
"references:",
|
||||
JSON.stringify(
|
||||
references.map((ref) => ({
|
||||
line: ref.range.start.line,
|
||||
character: ref.range.start.character,
|
||||
})),
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
// console.log(
|
||||
// "references:",
|
||||
// JSON.stringify(
|
||||
// references.map((ref) => ({
|
||||
// line: ref.range.start.line,
|
||||
// character: ref.range.start.character,
|
||||
// })),
|
||||
// null,
|
||||
// 2,
|
||||
// ),
|
||||
// );
|
||||
|
||||
return references.length > 1 ? references.slice(1) : null;
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import { AutocompleteInput } from "../autocomplete/util/types.js";
|
|||
import { localPathOrUriToPath } from "../util/pathToUri.js";
|
||||
import { replaceEscapedCharacters } from "../util/text.js";
|
||||
import {
|
||||
CODE_TO_EDIT_OPEN,
|
||||
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
} from "./constants.js";
|
||||
|
|
@ -208,6 +209,10 @@ export class NextEditProvider {
|
|||
return this.currentEditChainId !== null;
|
||||
}
|
||||
|
||||
public getChainLength(): number {
|
||||
return this.previousCompletions.length;
|
||||
}
|
||||
|
||||
public getPreviousCompletion(): NextEditOutcome | null {
|
||||
return this.previousCompletions[0];
|
||||
}
|
||||
|
|
@ -306,6 +311,16 @@ export class NextEditProvider {
|
|||
this.ide.getWorkspaceDirs(),
|
||||
]);
|
||||
|
||||
const editableRegionStartLine = Math.max(
|
||||
helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
0,
|
||||
);
|
||||
|
||||
const editableRegionEndLine = Math.min(
|
||||
helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
helper.fileLines.length - 1,
|
||||
);
|
||||
|
||||
// TODO: Toggle between the default endpoint and the finetuned endpoint.
|
||||
const prompts: Prompt[] = [];
|
||||
|
||||
|
|
@ -324,37 +339,49 @@ export class NextEditProvider {
|
|||
contextLines: 3,
|
||||
});
|
||||
|
||||
const promptMetadata = await renderPrompt(
|
||||
helper,
|
||||
historyDiff ?? this.diffContext,
|
||||
);
|
||||
const modelName = helper.modelName;
|
||||
let ctx: any;
|
||||
|
||||
if (modelName.includes("mercury-coder-nextedit")) {
|
||||
ctx = {
|
||||
recentlyViewedCodeSnippets:
|
||||
snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
|
||||
filepath: snip.filepath,
|
||||
content: snip.content,
|
||||
})) ?? [],
|
||||
currentFileContent: helper.fileContents,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
editDiffHistory: historyDiff,
|
||||
};
|
||||
} else if (modelName.includes("model-1")) {
|
||||
ctx = {
|
||||
userEdits: historyDiff ?? this.diffContext,
|
||||
languageShorthand: helper.lang.name,
|
||||
userExcerpts: helper.fileContents,
|
||||
};
|
||||
} else {
|
||||
ctx = {};
|
||||
}
|
||||
|
||||
const promptMetadata = await renderPrompt(helper, ctx);
|
||||
|
||||
this.promptMetadata = promptMetadata;
|
||||
|
||||
prompts.push({
|
||||
role: "system",
|
||||
content: [
|
||||
"When the user deletes or replaces over previous code, you should respect that decision.",
|
||||
"Respect the new code the user is writing, and complete it.",
|
||||
"For example, if the user is changing a field name, try to autocomplete the new field name. Don't suggest the previous field name.",
|
||||
"Do not roll back to previous content.",
|
||||
"If the user has made a change, make sure you respect that and try to apply it to other parts of the code that used to use the old content.",
|
||||
].join("\n"),
|
||||
});
|
||||
// prompts.push({
|
||||
// role: "system",
|
||||
// content: [
|
||||
// "When the user deletes or replaces over previous code, you should respect that decision.",
|
||||
// "Respect the new code the user is writing, and complete it.",
|
||||
// "For example, if the user is changing a field name, try to autocomplete the new field name. Don't suggest the previous field name.",
|
||||
// "Do not roll back to previous content.",
|
||||
// "If the user has made a change, make sure you respect that and try to apply it to other parts of the code that used to use the old content.",
|
||||
// ].join("\n"),
|
||||
// });
|
||||
|
||||
prompts.push(promptMetadata.prompt);
|
||||
}
|
||||
|
||||
const editableRegionStartLine = Math.max(
|
||||
helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
0,
|
||||
);
|
||||
|
||||
const editableRegionEndLine = Math.min(
|
||||
helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
helper.fileLines.length - 1,
|
||||
);
|
||||
|
||||
const oldEditRangeSlice = helper.fileContents
|
||||
.split("\n")
|
||||
.slice(editableRegionStartLine, editableRegionEndLine + 1)
|
||||
|
|
@ -412,11 +439,9 @@ export class NextEditProvider {
|
|||
|
||||
if (typeof msg.content === "string") {
|
||||
// NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
|
||||
const nextCompletion = msg.content.split(
|
||||
"<|editable_region_start|>\n",
|
||||
)[1]
|
||||
const nextCompletion = msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1]
|
||||
? replaceEscapedCharacters(
|
||||
msg.content.split("<|editable_region_start|>\n")[1],
|
||||
msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1],
|
||||
).replace(/\n$/, "")
|
||||
: "";
|
||||
|
||||
|
|
@ -523,6 +548,9 @@ export class NextEditProvider {
|
|||
);
|
||||
|
||||
if (this.nextEditableRegionsInTheCurrentChain.length === 0) {
|
||||
console.log(
|
||||
"deleteChain called from provideInlineCompletionItemsWithChain",
|
||||
);
|
||||
await this.deleteChain();
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -579,6 +607,14 @@ export class NextEditProvider {
|
|||
}
|
||||
|
||||
public shiftNextEditableRegionsInTheCurrentChain() {
|
||||
this.nextEditableRegionsInTheCurrentChain.shift();
|
||||
return this.nextEditableRegionsInTheCurrentChain.shift();
|
||||
}
|
||||
|
||||
public getNextEditableRegionsInTheCurrentChainLength() {
|
||||
return this.nextEditableRegionsInTheCurrentChain.length;
|
||||
}
|
||||
|
||||
public getNextEditableRegionsInTheCurrentChain(): RangeInFile[] {
|
||||
return [...this.nextEditableRegionsInTheCurrentChain]; // Return a copy to prevent external modification
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,3 +4,19 @@ export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
|
|||
export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
|
||||
export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
|
||||
export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
|
||||
|
||||
export const RECENTLY_VIEWED_CODE_SNIPPETS_OPEN =
|
||||
"<|recently_viewed_code_snippets|>";
|
||||
export const RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE =
|
||||
"<|/recently_viewed_code_snippets|>";
|
||||
export const RECENTLY_VIEWED_CODE_SNIPPET_OPEN =
|
||||
"<|recently_viewed_code_snippet|>";
|
||||
export const RECENTLY_VIEWED_CODE_SNIPPET_CLOSE =
|
||||
"<|/recently_viewed_code_snippet|>";
|
||||
export const CURRENT_FILE_CONTENT_OPEN = "<|current_file_content|>";
|
||||
export const CURRENT_FILE_CONTENT_CLOSE = "<|/current_file_content|>";
|
||||
export const CODE_TO_EDIT_OPEN = "<|code_to_edit|>";
|
||||
export const CODE_TO_EDIT_CLOSE = "<|/code_to_edit|>";
|
||||
export const EDIT_DIFF_HISTORY_OPEN = "<|edit_diff_history|>";
|
||||
export const EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>";
|
||||
export const CURSOR = "<|cursor|>";
|
||||
|
|
|
|||
|
|
@ -3,26 +3,46 @@ import { Position } from "../..";
|
|||
import { SnippetPayload } from "../../autocomplete/snippets";
|
||||
import { HelperVars } from "../../autocomplete/util/HelperVars";
|
||||
import {
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
CURRENT_FILE_CONTENT_CLOSE,
|
||||
CURRENT_FILE_CONTENT_OPEN,
|
||||
CURSOR,
|
||||
EDIT_DIFF_HISTORY_CLOSE,
|
||||
EDIT_DIFF_HISTORY_OPEN,
|
||||
RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
|
||||
RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
|
||||
USER_CURSOR_IS_HERE_TOKEN,
|
||||
} from "../constants";
|
||||
import {
|
||||
MercuryTemplateVars,
|
||||
Model1TemplateVars,
|
||||
NextEditTemplate,
|
||||
PromptMetadata,
|
||||
SystemPrompt,
|
||||
TemplateVars,
|
||||
UserPrompt,
|
||||
} from "../types";
|
||||
import {
|
||||
currentFileContentBlock,
|
||||
editHistoryBlock,
|
||||
recentlyViewedCodeSnippetsBlock,
|
||||
} from "./mercuryCoderNextEdit";
|
||||
import {
|
||||
insertCursorToken,
|
||||
insertEditableRegionTokensWithStaticRange,
|
||||
} from "./utils";
|
||||
|
||||
type TemplateRenderer = (vars: TemplateVars) => string;
|
||||
|
||||
type NextEditModelName = "mercury-coder-nextedit" | "this field is not used";
|
||||
export type NextEditModelName =
|
||||
| "mercury-coder-nextedit"
|
||||
| "model-1"
|
||||
| "this field is not used";
|
||||
|
||||
const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
|
||||
"mercury-coder-nextedit": {
|
||||
template: `${RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${CURRENT_FILE_CONTENT_CLOSE}\n\n${EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at [CURRENT FILE PATH].\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
|
||||
},
|
||||
"model-1": {
|
||||
template:
|
||||
"### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
|
||||
},
|
||||
|
|
@ -48,7 +68,7 @@ function templateRendererOfModel(
|
|||
|
||||
export async function renderPrompt(
|
||||
helper: HelperVars,
|
||||
userEdits: string,
|
||||
ctx: any,
|
||||
): Promise<PromptMetadata> {
|
||||
let modelName = helper.modelName as NextEditModelName;
|
||||
|
||||
|
|
@ -58,7 +78,7 @@ export async function renderPrompt(
|
|||
role: "user",
|
||||
content: "NEXT_EDIT",
|
||||
},
|
||||
userEdits,
|
||||
userEdits: "",
|
||||
userExcerpts: helper.fileContents,
|
||||
};
|
||||
}
|
||||
|
|
@ -80,18 +100,60 @@ export async function renderPrompt(
|
|||
}
|
||||
|
||||
const renderer = templateRendererOfModel(modelName);
|
||||
let userEdits = "";
|
||||
let editedCodeWithTokens = "";
|
||||
let tv: TemplateVars;
|
||||
|
||||
editedCodeWithTokens = insertTokens(
|
||||
helper.fileContents.split("\n"),
|
||||
helper.pos,
|
||||
);
|
||||
switch (modelName) {
|
||||
case "mercury-coder-nextedit": {
|
||||
userEdits = ctx.editDiffHistory;
|
||||
|
||||
const tv: TemplateVars = {
|
||||
userEdits,
|
||||
languageShorthand: helper.lang.name,
|
||||
userExcerpts: editedCodeWithTokens,
|
||||
};
|
||||
editedCodeWithTokens = insertTokens(
|
||||
helper.fileContents.split("\n"),
|
||||
helper.pos,
|
||||
CURSOR,
|
||||
);
|
||||
|
||||
const mercuryCtx: MercuryTemplateVars = {
|
||||
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
|
||||
ctx.recentlyViewedCodeSnippets,
|
||||
),
|
||||
currentFileContent: currentFileContentBlock(
|
||||
ctx.currentFileContent,
|
||||
ctx.editableRegionStartLine,
|
||||
ctx.editableRegionEndLine,
|
||||
helper.pos,
|
||||
),
|
||||
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
|
||||
};
|
||||
|
||||
tv = mercuryCtx;
|
||||
|
||||
break;
|
||||
}
|
||||
case "model-1": {
|
||||
userEdits = ctx.userEdits;
|
||||
|
||||
editedCodeWithTokens = insertTokens(
|
||||
helper.fileContents.split("\n"),
|
||||
helper.pos,
|
||||
USER_CURSOR_IS_HERE_TOKEN,
|
||||
);
|
||||
|
||||
const model1Ctx: Model1TemplateVars = {
|
||||
userEdits: ctx.userEdits,
|
||||
languageShorthand: ctx.languageShorthand,
|
||||
userExcerpts: ctx.userExcerpts,
|
||||
};
|
||||
|
||||
tv = model1Ctx;
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
tv = {};
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
prompt: {
|
||||
|
|
@ -174,105 +236,14 @@ export function renderDefaultUserPrompt(
|
|||
};
|
||||
}
|
||||
|
||||
// export async function renderFineTunedUserPrompt(
|
||||
// snippets: SnippetPayload,
|
||||
// ide: IDE,
|
||||
// helper: HelperVars,
|
||||
// ): Promise<UserPrompt> {
|
||||
// const ideInfo = await ide.getIdeInfo();
|
||||
// switch (ideInfo.ideType) {
|
||||
// case "vscode":
|
||||
// const editedCodeWithPins = insertTokens(
|
||||
// helper.fileContents.split("\n"),
|
||||
// helper.pos,
|
||||
// );
|
||||
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: renderStringTemplate(
|
||||
// mercuryCoderTemplate,
|
||||
// snippets.diffSnippets.join("\n"),
|
||||
// helper.lang.name,
|
||||
// editedCodeWithPins,
|
||||
// ),
|
||||
// };
|
||||
|
||||
// case "jetbrains":
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: "",
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
// export async function renderDefaultBasicUserPrompt(
|
||||
// snippets: SnippetPayload,
|
||||
// ide: IDE,
|
||||
// helper: HelperVars,
|
||||
// ): Promise<UserPrompt> {
|
||||
// const ideInfo = await ide.getIdeInfo();
|
||||
// switch (ideInfo.ideType) {
|
||||
// case "vscode":
|
||||
// const editedCodeWithPins = insertTokens(
|
||||
// helper.fileContents.split("\n"),
|
||||
// helper.pos,
|
||||
// );
|
||||
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: renderStringTemplate(
|
||||
// mercuryCoderTemplate,
|
||||
// JSON.stringify(snippets),
|
||||
// helper.lang.name,
|
||||
// editedCodeWithPins,
|
||||
// ),
|
||||
// };
|
||||
|
||||
// case "jetbrains":
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: "",
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
// export async function renderFineTunedBasicUserPrompt(
|
||||
// snippets: SnippetPayload,
|
||||
// ide: IDE,
|
||||
// helper: HelperVars,
|
||||
// diffContext: string,
|
||||
// ): Promise<UserPrompt> {
|
||||
// const ideInfo = await ide.getIdeInfo();
|
||||
// switch (ideInfo.ideType) {
|
||||
// case "vscode":
|
||||
// const lines = helper.fileContents.split("\n");
|
||||
// const editedCodeWithPins = insertTokens(lines, helper.pos);
|
||||
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: renderStringTemplate(
|
||||
// mercuryCoderTemplate,
|
||||
// diffContext,
|
||||
// helper.lang.name,
|
||||
// editedCodeWithPins,
|
||||
// ),
|
||||
// };
|
||||
|
||||
// case "jetbrains":
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: "",
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
function insertTokens(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
cursorToken: string,
|
||||
editableRegionStart?: number,
|
||||
editableRegionEnd?: number,
|
||||
) {
|
||||
const a = insertCursorToken(lines, cursorPos);
|
||||
const a = insertCursorToken(lines, cursorPos, cursorToken);
|
||||
const b = insertEditableRegionTokensWithStaticRange(
|
||||
a,
|
||||
cursorPos,
|
||||
|
|
@ -281,76 +252,3 @@ function insertTokens(
|
|||
);
|
||||
return b.join("\n");
|
||||
}
|
||||
|
||||
function insertCursorToken(lines: string[], cursorPos: Position) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure character position is within bounds or at the end of the line.
|
||||
const lineLength = lines[cursorPos.line].length;
|
||||
const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
|
||||
|
||||
lines[cursorPos.line] =
|
||||
lines[cursorPos.line].slice(0, charPos) +
|
||||
USER_CURSOR_IS_HERE_TOKEN +
|
||||
lines[cursorPos.line].slice(charPos);
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
function insertEditableRegionTokensWithStaticRange(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
editableRegionStart?: number,
|
||||
editableRegionEnd?: number,
|
||||
) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure editable regions are within bounds.
|
||||
if (editableRegionStart === undefined) {
|
||||
editableRegionStart = Math.max(
|
||||
cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
0,
|
||||
);
|
||||
}
|
||||
if (editableRegionEnd === undefined) {
|
||||
editableRegionEnd = Math.min(
|
||||
cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
lines.length - 1, // Line numbers should be zero-indexed.
|
||||
);
|
||||
}
|
||||
|
||||
// console.log("editableRegionStart:", editableRegionStart);
|
||||
|
||||
const instrumentedLines = [
|
||||
...lines.slice(0, editableRegionStart),
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
...lines.slice(editableRegionStart, editableRegionEnd + 1),
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
...lines.slice(editableRegionEnd + 1),
|
||||
];
|
||||
|
||||
return instrumentedLines;
|
||||
}
|
||||
|
||||
function insertEditableRegionTokensWithAst(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure character position is within bounds or at the end of the line.
|
||||
const lineLength = lines[cursorPos.line].length;
|
||||
const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
|
||||
|
||||
(lines[cursorPos.line] =
|
||||
lines[cursorPos.line].slice(0, charPos) + USER_CURSOR_IS_HERE_TOKEN),
|
||||
lines[cursorPos.line].slice(charPos);
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
|
|
|||
236
core/nextEdit/templating/NextEditPromptEngine.vitest.ts
Normal file
236
core/nextEdit/templating/NextEditPromptEngine.vitest.ts
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { Position } from "../..";
|
||||
import { SnippetPayload } from "../../autocomplete/snippets";
|
||||
import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
|
||||
import { HelperVars } from "../../autocomplete/util/HelperVars";
|
||||
import {
|
||||
CURRENT_FILE_CONTENT_CLOSE,
|
||||
CURRENT_FILE_CONTENT_OPEN,
|
||||
CURSOR,
|
||||
EDIT_DIFF_HISTORY_CLOSE,
|
||||
EDIT_DIFF_HISTORY_OPEN,
|
||||
RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
|
||||
RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
|
||||
USER_CURSOR_IS_HERE_TOKEN,
|
||||
} from "../constants";
|
||||
import {
|
||||
NextEditModelName,
|
||||
renderDefaultSystemPrompt,
|
||||
renderDefaultUserPrompt,
|
||||
renderPrompt,
|
||||
} from "./NextEditPromptEngine";
|
||||
|
||||
describe("NextEditPromptEngine", () => {
|
||||
describe("renderPrompt", () => {
|
||||
let mercuryHelper: HelperVars;
|
||||
let model1Helper: HelperVars;
|
||||
let testHelper: HelperVars;
|
||||
let unsupportedHelper: HelperVars;
|
||||
let ctx: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mercuryHelper = {
|
||||
modelName: "inception/mercury-coder-nextedit" as NextEditModelName,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
model1Helper = {
|
||||
modelName: "continuedev/model-1" as NextEditModelName,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
testHelper = {
|
||||
modelName: "this field is not used" as NextEditModelName,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
unsupportedHelper = {
|
||||
modelName: "mistral/codestral" as NextEditModelName,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
|
||||
ctx = {
|
||||
recentlyViewedCodeSnippets: [
|
||||
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
|
||||
],
|
||||
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
|
||||
editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@",
|
||||
editableRegionStartLine: 0,
|
||||
editableRegionEndLine: 3,
|
||||
userEdits: "Added constant a",
|
||||
languageShorthand: "ts",
|
||||
userExcerpts: "const a = 1;",
|
||||
};
|
||||
});
|
||||
|
||||
it("should render mercury-coder-nextedit prompt correctly", async () => {
|
||||
const result = await renderPrompt(mercuryHelper, ctx);
|
||||
|
||||
expect(result).toHaveProperty("prompt");
|
||||
expect(result.prompt.role).toBe("user");
|
||||
|
||||
const content = result.prompt.content;
|
||||
expect(content).toContain(RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
|
||||
expect(content).toContain(RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
|
||||
expect(content).toContain(CURRENT_FILE_CONTENT_OPEN);
|
||||
expect(content).toContain(CURRENT_FILE_CONTENT_CLOSE);
|
||||
expect(content).toContain(EDIT_DIFF_HISTORY_OPEN);
|
||||
expect(content).toContain(EDIT_DIFF_HISTORY_CLOSE);
|
||||
|
||||
expect(result.userEdits).toBe(ctx.editDiffHistory);
|
||||
expect(result.userExcerpts).toContain(CURSOR);
|
||||
});
|
||||
|
||||
it("should render model-1 prompt correctly", async () => {
|
||||
const result = await renderPrompt(model1Helper, ctx);
|
||||
|
||||
expect(result).toHaveProperty("prompt");
|
||||
expect(result.prompt.role).toBe("user");
|
||||
expect(result.prompt.content).toContain("### User Edits:");
|
||||
expect(result.prompt.content).toContain("### User Excerpts:");
|
||||
expect(result.prompt.content).toContain("```ts");
|
||||
|
||||
expect(result.userEdits).toBe(ctx.userEdits);
|
||||
expect(result.userExcerpts).toContain(USER_CURSOR_IS_HERE_TOKEN);
|
||||
});
|
||||
|
||||
it("should handle 'this field is not used' model name", async () => {
|
||||
const result = await renderPrompt(testHelper, ctx);
|
||||
|
||||
expect(result).toHaveProperty("prompt");
|
||||
expect(result.prompt.role).toBe("user");
|
||||
expect(result.prompt.content).toBe("NEXT_EDIT");
|
||||
expect(result.userEdits).toBe("");
|
||||
expect(result.userExcerpts).toBe(testHelper.fileContents);
|
||||
});
|
||||
|
||||
it("should throw error for unsupported model name", async () => {
|
||||
await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow(
|
||||
"mistral/codestral is not yet supported for next edit.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderDefaultSystemPrompt", () => {
|
||||
it("should return a system prompt with expected role and content", () => {
|
||||
const result = renderDefaultSystemPrompt();
|
||||
|
||||
expect(result.role).toBe("system");
|
||||
expect(result.content).toContain("You are an expert polyglot developer");
|
||||
expect(result.content).toContain("Do not hallucinate.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderDefaultUserPrompt", () => {
|
||||
it("should render a user prompt with the correct structure", () => {
|
||||
const snippets: SnippetPayload = {
|
||||
rootPathSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "root path",
|
||||
},
|
||||
],
|
||||
importDefinitionSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "import def",
|
||||
},
|
||||
],
|
||||
ideSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "ide snippets",
|
||||
},
|
||||
],
|
||||
recentlyEditedRangeSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "recent edits",
|
||||
},
|
||||
],
|
||||
diffSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
content: "diff snippets",
|
||||
},
|
||||
],
|
||||
clipboardSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Clipboard,
|
||||
content: "clipboard",
|
||||
copiedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
recentlyVisitedRangesSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "visited ranges",
|
||||
},
|
||||
],
|
||||
recentlyOpenedFileSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "recently opened files",
|
||||
},
|
||||
],
|
||||
staticSnippet: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Static,
|
||||
filepath: "",
|
||||
content: "static content",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const helper: HelperVars = {
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
|
||||
const result = renderDefaultUserPrompt(snippets, helper);
|
||||
|
||||
expect(result.role).toBe("user");
|
||||
expect(result.content).toContain("Your junior made the following edit:");
|
||||
expect(result.content).toContain("typescript");
|
||||
expect(result.content).toContain("root path");
|
||||
});
|
||||
});
|
||||
|
||||
describe("insertTokens", () => {
|
||||
it("should correctly insert cursor and editable region tokens", () => {
|
||||
const mercuryHelper = {
|
||||
modelName: "inception/mercury-coder-nextedit" as NextEditModelName,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
|
||||
const ctx = {
|
||||
recentlyViewedCodeSnippets: [
|
||||
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
|
||||
],
|
||||
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
|
||||
editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@",
|
||||
editableRegionStartLine: 0,
|
||||
editableRegionEndLine: 3,
|
||||
userEdits: "Added constant a",
|
||||
languageShorthand: "ts",
|
||||
userExcerpts: "const a = 1;",
|
||||
};
|
||||
|
||||
return renderPrompt(mercuryHelper, ctx).then((result) => {
|
||||
expect(result.userExcerpts).toContain(CURSOR);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
63
core/nextEdit/templating/mercuryCoderNextEdit.ts
Normal file
63
core/nextEdit/templating/mercuryCoderNextEdit.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { Position, Range } from "../..";
|
||||
import { CODE_TO_EDIT_CLOSE, CODE_TO_EDIT_OPEN, CURSOR } from "../constants";
|
||||
import { insertCursorToken } from "./utils";
|
||||
|
||||
export function recentlyViewedCodeSnippetsBlock(
|
||||
recentlyViewedCodeSnippets: { filepath: string; content: string }[],
|
||||
) {
|
||||
return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => {
|
||||
const block = [
|
||||
`code_snippet_file_path: ${snippet.filepath}`,
|
||||
snippet.content,
|
||||
].join("\n");
|
||||
|
||||
return (
|
||||
acc + block + (i === recentlyViewedCodeSnippets.length - 1 ? "" : "\n")
|
||||
);
|
||||
}, "");
|
||||
}
|
||||
|
||||
export function currentFileContentBlock(
|
||||
currentFileContent: string,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
cursorPosition: Position,
|
||||
) {
|
||||
const currentFileContentLines = currentFileContent.split("\n");
|
||||
|
||||
const insertedCursorLines = insertCursorToken(
|
||||
currentFileContentLines,
|
||||
cursorPosition,
|
||||
CURSOR,
|
||||
);
|
||||
|
||||
const instrumentedLines = [
|
||||
...insertedCursorLines.slice(0, editableRegionStartLine),
|
||||
CODE_TO_EDIT_OPEN,
|
||||
...insertedCursorLines.slice(
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine + 1,
|
||||
),
|
||||
CODE_TO_EDIT_CLOSE,
|
||||
...insertedCursorLines.slice(editableRegionEndLine + 1),
|
||||
];
|
||||
|
||||
return instrumentedLines.join("\n");
|
||||
}
|
||||
|
||||
export function editHistoryBlock(
|
||||
editDiffHistory: string, // could be a singe large unified diff
|
||||
) {
|
||||
return editDiffHistory;
|
||||
}
|
||||
|
||||
function mercuryNextEditTemplateBuilder(
|
||||
recentlyViewedCodeSnippets: { filepath: string; code: string }[],
|
||||
currentFileContent: string,
|
||||
codeToEdit: string,
|
||||
codeToEditRange: Range,
|
||||
cursorPosition: Position,
|
||||
editDiffHistory: string, // could be a singe large unified diff
|
||||
): string {
|
||||
return "";
|
||||
}
|
||||
115
core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts
Normal file
115
core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { Position } from "../..";
|
||||
import { CODE_TO_EDIT_CLOSE, CODE_TO_EDIT_OPEN, CURSOR } from "../constants";
|
||||
import {
|
||||
currentFileContentBlock,
|
||||
editHistoryBlock,
|
||||
recentlyViewedCodeSnippetsBlock,
|
||||
} from "./mercuryCoderNextEdit";
|
||||
|
||||
describe("mercuryCoderNextEdit", () => {
|
||||
describe("recentlyViewedCodeSnippetsBlock", () => {
|
||||
it("should format a list of code snippets correctly", () => {
|
||||
const snippets = [
|
||||
{ filepath: "/path/to/file1.ts", content: "const a = 1;" },
|
||||
{
|
||||
filepath: "/path/to/file2.ts",
|
||||
content: "function test() { return true; }",
|
||||
},
|
||||
];
|
||||
|
||||
const result = recentlyViewedCodeSnippetsBlock(snippets);
|
||||
|
||||
const expected =
|
||||
"code_snippet_file_path: /path/to/file1.ts\n" +
|
||||
"const a = 1;\n" +
|
||||
"code_snippet_file_path: /path/to/file2.ts\n" +
|
||||
"function test() { return true; }";
|
||||
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle empty snippets array", () => {
|
||||
const result = recentlyViewedCodeSnippetsBlock([]);
|
||||
expect(result).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("currentFileContentBlock", () => {
|
||||
it("should correctly format current file content with editable region and cursor", () => {
|
||||
const fileContent = "line 1\nline 2\nline 3\nline 4\nline 5";
|
||||
const editableRegionStartLine = 1;
|
||||
const editableRegionEndLine = 3;
|
||||
const cursorPosition: Position = { line: 2, character: 3 };
|
||||
|
||||
const result = currentFileContentBlock(
|
||||
fileContent,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
cursorPosition,
|
||||
);
|
||||
|
||||
const expected =
|
||||
"line 1\n" +
|
||||
CODE_TO_EDIT_OPEN +
|
||||
"\n" +
|
||||
"line 2\n" +
|
||||
"lin" +
|
||||
CURSOR +
|
||||
"e 3\n" +
|
||||
"line 4\n" +
|
||||
CODE_TO_EDIT_CLOSE +
|
||||
"\n" +
|
||||
"line 5";
|
||||
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle cursor at the beginning of a line", () => {
|
||||
const fileContent = "line 1\nline 2\nline 3";
|
||||
const editableRegionStartLine = 0;
|
||||
const editableRegionEndLine = 2;
|
||||
const cursorPosition: Position = { line: 1, character: 0 };
|
||||
|
||||
const result = currentFileContentBlock(
|
||||
fileContent,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
cursorPosition,
|
||||
);
|
||||
|
||||
expect(result).toContain(CODE_TO_EDIT_OPEN);
|
||||
expect(result).toContain(CURSOR + "line 2");
|
||||
expect(result).toContain(CODE_TO_EDIT_CLOSE);
|
||||
});
|
||||
|
||||
it("should handle cursor at the end of a line", () => {
|
||||
const fileContent = "line 1\nline 2\nline 3";
|
||||
const editableRegionStartLine = 0;
|
||||
const editableRegionEndLine = 2;
|
||||
const cursorPosition: Position = { line: 1, character: 6 };
|
||||
|
||||
const result = currentFileContentBlock(
|
||||
fileContent,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
cursorPosition,
|
||||
);
|
||||
|
||||
expect(result).toContain("line 2" + CURSOR);
|
||||
});
|
||||
});
|
||||
|
||||
describe("editHistoryBlock", () => {
|
||||
it("should return the edit diff history unchanged", () => {
|
||||
const diffHistory = "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@";
|
||||
const result = editHistoryBlock(diffHistory);
|
||||
expect(result).toBe(diffHistory);
|
||||
});
|
||||
|
||||
it("should handle empty diff history", () => {
|
||||
const result = editHistoryBlock("");
|
||||
expect(result).toBe("");
|
||||
});
|
||||
});
|
||||
});
|
||||
63
core/nextEdit/templating/utils.ts
Normal file
63
core/nextEdit/templating/utils.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { Position } from "../..";
|
||||
import {
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
} from "../constants";
|
||||
|
||||
export function insertCursorToken(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
cursorToken: string,
|
||||
) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure character position is within bounds or at the end of the line.
|
||||
const lineLength = lines[cursorPos.line].length;
|
||||
const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
|
||||
|
||||
lines[cursorPos.line] =
|
||||
lines[cursorPos.line].slice(0, charPos) +
|
||||
cursorToken +
|
||||
lines[cursorPos.line].slice(charPos);
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function insertEditableRegionTokensWithStaticRange(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
editableRegionStart?: number,
|
||||
editableRegionEnd?: number,
|
||||
) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure editable regions are within bounds.
|
||||
if (editableRegionStart === undefined) {
|
||||
editableRegionStart = Math.max(
|
||||
cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
0,
|
||||
);
|
||||
}
|
||||
if (editableRegionEnd === undefined) {
|
||||
editableRegionEnd = Math.min(
|
||||
cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
lines.length - 1, // Line numbers should be zero-indexed.
|
||||
);
|
||||
}
|
||||
|
||||
const instrumentedLines = [
|
||||
...lines.slice(0, editableRegionStart),
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
...lines.slice(editableRegionStart, editableRegionEnd + 1),
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
...lines.slice(editableRegionEnd + 1),
|
||||
];
|
||||
|
||||
return instrumentedLines;
|
||||
}
|
||||
134
core/nextEdit/templating/utils.vitest.ts
Normal file
134
core/nextEdit/templating/utils.vitest.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { Position } from "../..";
|
||||
import {
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
} from "../constants";
|
||||
import {
|
||||
insertCursorToken,
|
||||
insertEditableRegionTokensWithStaticRange,
|
||||
} from "./utils";
|
||||
|
||||
describe("insertCursorToken", () => {
|
||||
it("should insert cursor token at the specified position", () => {
|
||||
const lines = ["line one", "line two", "line three"];
|
||||
const cursorPos: Position = { line: 1, character: 5 };
|
||||
const cursorToken = "|CURSOR|";
|
||||
|
||||
const result = insertCursorToken(lines, cursorPos, cursorToken);
|
||||
|
||||
expect(result).toEqual(["line one", "line |CURSOR|two", "line three"]);
|
||||
});
|
||||
|
||||
it("should handle cursor at the beginning of a line", () => {
|
||||
const lines = ["line one", "line two", "line three"];
|
||||
const cursorPos: Position = { line: 1, character: 0 };
|
||||
const cursorToken = "|CURSOR|";
|
||||
|
||||
const result = insertCursorToken(lines, cursorPos, cursorToken);
|
||||
|
||||
expect(result).toEqual(["line one", "|CURSOR|line two", "line three"]);
|
||||
});
|
||||
|
||||
it("should handle cursor at the end of a line", () => {
|
||||
const lines = ["line one", "line two", "line three"];
|
||||
const cursorPos: Position = { line: 1, character: 8 };
|
||||
const cursorToken = "|CURSOR|";
|
||||
|
||||
const result = insertCursorToken(lines, cursorPos, cursorToken);
|
||||
|
||||
expect(result).toEqual(["line one", "line two|CURSOR|", "line three"]);
|
||||
});
|
||||
|
||||
it("should not modify lines if cursor position is out of bounds (negative line)", () => {
|
||||
const lines = ["line one", "line two", "line three"];
|
||||
const cursorPos: Position = { line: -1, character: 5 };
|
||||
const cursorToken = "|CURSOR|";
|
||||
|
||||
const result = insertCursorToken(lines, cursorPos, cursorToken);
|
||||
|
||||
expect(result).toEqual(lines);
|
||||
});
|
||||
|
||||
it("should not modify lines if cursor position is out of bounds (line too large)", () => {
|
||||
const lines = ["line one", "line two", "line three"];
|
||||
const cursorPos: Position = { line: 3, character: 5 };
|
||||
const cursorToken = "|CURSOR|";
|
||||
|
||||
const result = insertCursorToken(lines, cursorPos, cursorToken);
|
||||
|
||||
expect(result).toEqual(lines);
|
||||
});
|
||||
|
||||
it("should cap the character position to the line length if it exceeds it", () => {
|
||||
const lines = ["line one", "line two", "line three"];
|
||||
const cursorPos: Position = { line: 1, character: 100 };
|
||||
const cursorToken = "|CURSOR|";
|
||||
|
||||
const result = insertCursorToken(lines, cursorPos, cursorToken);
|
||||
|
||||
expect(result).toEqual(["line one", "line two|CURSOR|", "line three"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("insertEditableRegionTokensWithStaticRange", () => {
|
||||
it("should insert editable region tokens with default margins", () => {
|
||||
const lines = ["line 0", "line 1", "line 2", "line 3", "line 4"];
|
||||
const cursorPos: Position = { line: 2, character: 3 };
|
||||
|
||||
const result = insertEditableRegionTokensWithStaticRange(lines, cursorPos);
|
||||
|
||||
const expectedStart = Math.max(2 - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0);
|
||||
const expectedEnd = Math.min(
|
||||
2 + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
lines.length - 1,
|
||||
);
|
||||
|
||||
const expected = [
|
||||
...lines.slice(0, expectedStart),
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
...lines.slice(expectedStart, expectedEnd + 1),
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
...lines.slice(expectedEnd + 1),
|
||||
];
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should insert editable region tokens with explicit range", () => {
|
||||
const lines = ["line 0", "line 1", "line 2", "line 3", "line 4"];
|
||||
const cursorPos: Position = { line: 2, character: 3 };
|
||||
const editableRegionStart = 1;
|
||||
const editableRegionEnd = 3;
|
||||
|
||||
const result = insertEditableRegionTokensWithStaticRange(
|
||||
lines,
|
||||
cursorPos,
|
||||
editableRegionStart,
|
||||
editableRegionEnd,
|
||||
);
|
||||
|
||||
const expected = [
|
||||
"line 0",
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
"line 1",
|
||||
"line 2",
|
||||
"line 3",
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
"line 4",
|
||||
];
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should not modify lines if cursor position is out of bounds", () => {
|
||||
const lines = ["line 0", "line 1", "line 2"];
|
||||
const cursorPos: Position = { line: 5, character: 3 };
|
||||
|
||||
const result = insertEditableRegionTokensWithStaticRange(lines, cursorPos);
|
||||
|
||||
expect(result).toEqual(lines);
|
||||
});
|
||||
});
|
||||
|
|
@ -81,8 +81,16 @@ export interface NextEditTemplate {
|
|||
template: string;
|
||||
}
|
||||
|
||||
export interface TemplateVars {
|
||||
export interface TemplateVars {}
|
||||
|
||||
export interface Model1TemplateVars extends TemplateVars {
|
||||
userEdits: string;
|
||||
languageShorthand: string;
|
||||
userExcerpts: string;
|
||||
}
|
||||
|
||||
export interface MercuryTemplateVars extends TemplateVars {
|
||||
recentlyViewedCodeSnippets: string;
|
||||
currentFileContent: string;
|
||||
editDiffHistory: string; // could be a singe large unified diff
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ export class JumpManager {
|
|||
private _disposables: vscode.Disposable[] = [];
|
||||
|
||||
private _jumpInProgress: boolean = false;
|
||||
private _jumpAccepted: boolean = false;
|
||||
private _completionAfterJump: CompletionDataForAfterJump | null = null;
|
||||
private _oldCursorPosition: vscode.Position | undefined;
|
||||
|
||||
|
|
@ -48,13 +49,14 @@ export class JumpManager {
|
|||
currentPosition: vscode.Position,
|
||||
nextJumpLocation: vscode.Position,
|
||||
completionContent?: string,
|
||||
) {
|
||||
): Promise<boolean> {
|
||||
// Deduplication logic.
|
||||
// If the content at the next jump location is
|
||||
// identical to the completion content,
|
||||
// then we don't have to jump.
|
||||
if (completionContent !== undefined) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
|
||||
if (editor) {
|
||||
try {
|
||||
const completionLines = completionContent.split("\n");
|
||||
|
|
@ -102,14 +104,14 @@ export class JumpManager {
|
|||
console.log(
|
||||
"Skipping jump as content is identical at jump location",
|
||||
);
|
||||
return; // Exit early, don't suggest jump.
|
||||
return false; // Exit early, don't suggest jump.
|
||||
}
|
||||
} else {
|
||||
// Only one line and it matches.
|
||||
console.log(
|
||||
"Skipping jump as content is identical at jump location",
|
||||
);
|
||||
return; // Exit early, don't suggest jump.
|
||||
return false; // Exit early, don't suggest jump.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -120,53 +122,61 @@ export class JumpManager {
|
|||
}
|
||||
}
|
||||
|
||||
console.log("this._jumpInProgress");
|
||||
this._jumpInProgress = true;
|
||||
this._oldCursorPosition = currentPosition;
|
||||
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
|
||||
if (editor) {
|
||||
const visibleRanges = editor.visibleRanges;
|
||||
|
||||
if (visibleRanges.length > 0) {
|
||||
const visibleRange = visibleRanges[0];
|
||||
const topLineNumber = visibleRange.start.line;
|
||||
const bottomLineNumber = visibleRange.end.line;
|
||||
|
||||
const decorationLine = nextJumpLocation.line;
|
||||
|
||||
// Check if jump location is outside the visible range.
|
||||
if (decorationLine < topLineNumber) {
|
||||
await this.renderTabToJumpDecoration(
|
||||
editor,
|
||||
topLineNumber,
|
||||
nextJumpLocation,
|
||||
);
|
||||
} else if (decorationLine > bottomLineNumber) {
|
||||
await this.renderTabToJumpDecoration(
|
||||
editor,
|
||||
bottomLineNumber,
|
||||
nextJumpLocation,
|
||||
);
|
||||
} else {
|
||||
// No suggestion is made when the decoration is within visibleRange.
|
||||
await this.renderTabToJumpDecoration(
|
||||
editor,
|
||||
decorationLine,
|
||||
nextJumpLocation,
|
||||
);
|
||||
}
|
||||
|
||||
// Scroll to show the jump location.
|
||||
editor.revealRange(
|
||||
new vscode.Range(decorationLine, 0, decorationLine, 0),
|
||||
vscode.TextEditorRevealType.InCenter,
|
||||
);
|
||||
}
|
||||
if (!editor) {
|
||||
console.log("No active editor, cannot suggest jump");
|
||||
this._jumpInProgress = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
const visibleRanges = editor.visibleRanges;
|
||||
if (visibleRanges.length === 0) {
|
||||
console.log("No visible ranges in editor, cannot suggest jump");
|
||||
this._jumpInProgress = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
const visibleRange = visibleRanges[0];
|
||||
const topLineNumber = visibleRange.start.line;
|
||||
const bottomLineNumber = visibleRange.end.line;
|
||||
|
||||
const decorationLine = nextJumpLocation.line;
|
||||
|
||||
// Check if jump location is outside the visible range.
|
||||
if (decorationLine < topLineNumber) {
|
||||
await this.renderTabToJumpDecoration(
|
||||
editor,
|
||||
topLineNumber,
|
||||
nextJumpLocation,
|
||||
);
|
||||
} else if (decorationLine > bottomLineNumber) {
|
||||
await this.renderTabToJumpDecoration(
|
||||
editor,
|
||||
bottomLineNumber,
|
||||
nextJumpLocation,
|
||||
);
|
||||
} else {
|
||||
// No suggestion is made when the decoration is within visibleRange.
|
||||
await this.renderTabToJumpDecoration(
|
||||
editor,
|
||||
decorationLine,
|
||||
nextJumpLocation,
|
||||
);
|
||||
}
|
||||
|
||||
// Scroll to show the jump location.
|
||||
editor.revealRange(
|
||||
new vscode.Range(decorationLine, 0, decorationLine, 0),
|
||||
vscode.TextEditorRevealType.InCenter,
|
||||
);
|
||||
|
||||
// Set up a way to detect when the jump is complete.
|
||||
const disposable = vscode.window.onDidChangeTextEditorSelection(() => {
|
||||
console.log("_jumpInProgress is false");
|
||||
this._jumpInProgress = false;
|
||||
disposable.dispose();
|
||||
|
||||
|
|
@ -185,7 +195,9 @@ export class JumpManager {
|
|||
setTimeout(() => {
|
||||
this._jumpInProgress = false;
|
||||
disposable.dispose();
|
||||
}, 5000);
|
||||
}, 10000);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private async renderTabToJumpDecoration(
|
||||
|
|
@ -256,9 +268,13 @@ export class JumpManager {
|
|||
"continue.acceptJump",
|
||||
async () => {
|
||||
if (this._jumpDecorationVisible) {
|
||||
this._jumpAccepted = true;
|
||||
|
||||
// Move cursor to the jump position.
|
||||
editor.selection = new vscode.Selection(jumpPosition, jumpPosition);
|
||||
await this.clearJumpDecoration();
|
||||
|
||||
this._jumpAccepted = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
|
@ -312,6 +328,10 @@ export class JumpManager {
|
|||
return this._jumpInProgress;
|
||||
}
|
||||
|
||||
wasJumpJustAccepted(): boolean {
|
||||
return this._jumpAccepted;
|
||||
}
|
||||
|
||||
setCompletionAfterJump(completionData: CompletionDataForAfterJump): void {
|
||||
this._completionAfterJump = completionData;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -236,6 +236,15 @@ export class ContinueCompletionProvider
|
|||
let recentlyEditedRanges =
|
||||
await this.recentlyEditedTracker.getRecentlyEditedRanges();
|
||||
|
||||
console.log(
|
||||
"chain exists?",
|
||||
this.nextEditProvider.chainExists(),
|
||||
", length:",
|
||||
this.nextEditProvider.getChainLength(),
|
||||
", next regions queue:",
|
||||
this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(),
|
||||
);
|
||||
|
||||
if (this.nextEditProvider.chainExists()) {
|
||||
// The chain of edits is alive because the user has accepted the previous completion.
|
||||
// Get the next editable region and set the pos to be within that range.
|
||||
|
|
@ -415,32 +424,50 @@ export class ContinueCompletionProvider
|
|||
|
||||
if (this.isNextEditActive) {
|
||||
if (!this.nextEditProvider.isStartOfChain()) {
|
||||
const jumpPosition = new vscode.Position(
|
||||
(outcome as NextEditOutcome).editableRegionStartLine,
|
||||
0,
|
||||
);
|
||||
// Try suggesting jumps for each location in the queue.
|
||||
let jumpSuccessful = false;
|
||||
|
||||
// Suggest a jump if there is a valid next location.
|
||||
// This will set isJumpInProgress if a jump is suggested.
|
||||
await this.jumpManager.suggestJump(
|
||||
currCursorPos,
|
||||
jumpPosition,
|
||||
outcome.completion,
|
||||
);
|
||||
while (
|
||||
this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength() >
|
||||
0 &&
|
||||
!jumpSuccessful
|
||||
) {
|
||||
const nextRegion =
|
||||
this.nextEditProvider.shiftNextEditableRegionsInTheCurrentChain();
|
||||
if (!nextRegion) continue;
|
||||
|
||||
// If a jump was just suggested, don't show ghost text yet.
|
||||
if (this.jumpManager.isJumpInProgress()) {
|
||||
// Store this completion to be rendered after jump is complete.
|
||||
this.jumpManager.setCompletionAfterJump({
|
||||
completionId: completionId,
|
||||
outcome: outcome as NextEditOutcome,
|
||||
currentPosition: jumpPosition,
|
||||
});
|
||||
const jumpPosition = new vscode.Position(
|
||||
nextRegion.range.start.line,
|
||||
nextRegion.range.start.character,
|
||||
);
|
||||
|
||||
return undefined; // Don't show anything yet!
|
||||
// Try to suggest a jump to this location.
|
||||
jumpSuccessful = await this.jumpManager.suggestJump(
|
||||
currCursorPos,
|
||||
jumpPosition,
|
||||
outcome.completion,
|
||||
);
|
||||
|
||||
if (jumpSuccessful) {
|
||||
// Store completion to be rendered after jump.
|
||||
this.jumpManager.setCompletionAfterJump({
|
||||
completionId: completionId,
|
||||
outcome: outcome as NextEditOutcome,
|
||||
currentPosition: jumpPosition,
|
||||
});
|
||||
|
||||
return undefined; // Don't show anything yet!
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
// If no jump was successful after trying multiple locations,
|
||||
// proceed with other completion display logic or return undefined.
|
||||
if (!jumpSuccessful) {
|
||||
console.log(
|
||||
"No suitable jump location found after trying multiple positions",
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Check the diff between old and new editable region.
|
||||
|
|
|
|||
|
|
@ -426,6 +426,7 @@ export class VsCodeExtension {
|
|||
// Listen for editor changes to clean up decorations when editor closes.
|
||||
vscode.window.onDidChangeVisibleTextEditors(async () => {
|
||||
// If our active editor is no longer visible, clear decorations.
|
||||
console.log("deleteChain called from onDidChangeVisibleTextEditors");
|
||||
await NextEditProvider.getInstance().deleteChain();
|
||||
});
|
||||
|
||||
|
|
@ -442,7 +443,10 @@ export class VsCodeExtension {
|
|||
}
|
||||
|
||||
// 2. A jump is in progress.
|
||||
if (JumpManager.getInstance().isJumpInProgress()) {
|
||||
if (
|
||||
JumpManager.getInstance().isJumpInProgress() ||
|
||||
JumpManager.getInstance().wasJumpJustAccepted()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -472,6 +476,7 @@ export class VsCodeExtension {
|
|||
}
|
||||
|
||||
// Otherwise, delete the chain (for rejection or unrelated movement).
|
||||
console.log("deleteChain called from onDidChangeTextEditorSelection");
|
||||
await NextEditProvider.getInstance().deleteChain();
|
||||
|
||||
NextEditProvider.getInstance().loadNextEditableRegionsInTheCurrentChain(
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ class Calculator {
|
|||
return this;
|
||||
}
|
||||
subtract(number) {
|
||||
this.result -= number;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue