From da33742bbee5adef67a594c4f3e563ae45bb9f2c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:49:11 -0700 Subject: [PATCH 01/22] feat: delete chain for files closed --- core/core.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/core.ts b/core/core.ts index 0a561f0fa..200cfae6f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -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) { From e8a1aadd3a58e78b7b0996173a73002f991ba337 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:49:20 -0700 Subject: [PATCH 02/22] feat: add more tokens --- core/nextEdit/constants.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index c4dd70f51..05ac1caa3 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -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|>"; From b1a67fe6467069163197c110ac1499791cb1c38d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:49:37 -0700 Subject: [PATCH 03/22] feat: add template variables for different next edit models --- core/nextEdit/types.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 26e2b156a..5b3d96eee 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -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 +} From eba911ddc148c14455eac91f11d75a8d1500e116 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:51:12 -0700 Subject: [PATCH 04/22] refactor: move util functions --- core/nextEdit/templating/utils.ts | 85 +++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 core/nextEdit/templating/utils.ts diff --git a/core/nextEdit/templating/utils.ts b/core/nextEdit/templating/utils.ts new file mode 100644 index 000000000..9eca26866 --- /dev/null +++ b/core/nextEdit/templating/utils.ts @@ -0,0 +1,85 @@ +import { Position } from "../.."; +import { + EDITABLE_REGION_END_TOKEN, + EDITABLE_REGION_START_TOKEN, + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + USER_CURSOR_IS_HERE_TOKEN, +} 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. + ); + } + + // 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; +} + +export 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; +} From d6fc9bb3bd28892c0948f6b98d4172505bcf1374 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:52:08 -0700 Subject: [PATCH 05/22] chore: remove console.logs --- .../NextEditEditableRegionCalculator.ts | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 7f5d13b66..0bb9537d7 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -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) { From 1fe41e8ca34a9a1b7bd00f3ae0d3b195b67c0f52 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:52:26 -0700 Subject: [PATCH 06/22] feat: support multiple models and new mercury model --- core/nextEdit/NextEditProvider.ts | 92 ++++++++++++++++++++++--------- 1 file changed, 66 insertions(+), 26 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index b431f0503..5a398a8dd 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -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]; } @@ -302,6 +307,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[] = []; @@ -320,37 +335,53 @@ export class NextEditProvider { contextLines: 3, }); + 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, - historyDiff ?? this.diffContext, + // historyDiff ?? this.diffContext, + 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) @@ -408,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$/, "") : ""; @@ -519,6 +548,9 @@ export class NextEditProvider { ); if (this.nextEditableRegionsInTheCurrentChain.length === 0) { + console.log( + "deleteChain called from provideInlineCompletionItemsWithChain", + ); await this.deleteChain(); return undefined; } @@ -574,6 +606,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 } } From bded0d389c1db074d0fede0f99746589a0f98e68 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:52:36 -0700 Subject: [PATCH 07/22] feat: add mercury-specific functions --- .../templating/mercuryCoderNextEdit.ts | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 core/nextEdit/templating/mercuryCoderNextEdit.ts diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.ts b/core/nextEdit/templating/mercuryCoderNextEdit.ts new file mode 100644 index 000000000..a7f79962b --- /dev/null +++ b/core/nextEdit/templating/mercuryCoderNextEdit.ts @@ -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) => { + const block = [ + `code_snippet_file_path: ${snippet.filepath}`, + snippet.content, + ].join("\n"); + + return acc + block; + }, ""), + ].join("\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 ""; +} From 65ebc7b99eda6fa6bdfc273a64fa346f41c9daaa Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:52:55 -0700 Subject: [PATCH 08/22] feat: generate prompts for new mercury model --- .../templating/NextEditPromptEngine.ts | 263 ++++++------------ 1 file changed, 81 insertions(+), 182 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index bad3f5166..ffbf41af3 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -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 = { "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,8 @@ function templateRendererOfModel( export async function renderPrompt( helper: HelperVars, - userEdits: string, + // userEdits: string, + ctx: any, ): Promise { let modelName = helper.modelName as NextEditModelName; @@ -58,7 +79,7 @@ export async function renderPrompt( role: "user", content: "NEXT_EDIT", }, - userEdits, + userEdits: "", userExcerpts: helper.fileContents, }; } @@ -80,18 +101,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 +237,14 @@ export function renderDefaultUserPrompt( }; } -// export async function renderFineTunedUserPrompt( -// snippets: SnippetPayload, -// ide: IDE, -// helper: HelperVars, -// ): Promise { -// 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 { -// 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 { -// 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 +253,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; -} From 91c89b19dabb6289f7b1f0d58ae0a850c1ae6a73 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:53:21 -0700 Subject: [PATCH 09/22] fix: race condition, defensive programming --- .../vscode/src/activation/JumpManager.ts | 109 +++++++++++------- 1 file changed, 67 insertions(+), 42 deletions(-) diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 1d180c072..9ba4ce8a1 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -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 { // 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,66 @@ 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; } + // if (editor) { + const visibleRanges = editor.visibleRanges; + if (visibleRanges.length === 0) { + console.log("No visible ranges in editor, cannot suggest jump"); + this._jumpInProgress = false; + return false; + } + + // 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, + ); + // } + + // } + // 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(); @@ -186,6 +201,8 @@ export class JumpManager { this._jumpInProgress = false; disposable.dispose(); }, 5000); + + return true; } private async renderTabToJumpDecoration( @@ -256,9 +273,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 +333,10 @@ export class JumpManager { return this._jumpInProgress; } + wasJumpJustAccepted(): boolean { + return this._jumpAccepted; + } + setCompletionAfterJump(completionData: CompletionDataForAfterJump): void { this._completionAfterJump = completionData; } From cf004ba42ed8d4237cf477ede63703177a954581 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:53:57 -0700 Subject: [PATCH 10/22] feat: consume next editable regions in the queue until we get a suggestion --- .../src/autocomplete/completionProvider.ts | 99 +++++++++++++++---- 1 file changed, 78 insertions(+), 21 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 4be4b7cef..d6d7875d5 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -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. @@ -414,33 +423,81 @@ export class ContinueCompletionProvider const currCursorPos = editor.selection.active; if (this.isNextEditActive) { + // if (!this.nextEditProvider.isStartOfChain()) { + // const jumpPosition = new vscode.Position( + // (outcome as NextEditOutcome).editableRegionStartLine, + // 0, + // ); + + // // 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, + // ); + + // // 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, + // }); + + // return undefined; // Don't show anything yet! + // } + + // return undefined; + // } 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; + // let attempts = 0; - // 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 + ) { + // Limit attempts + // attempts++; + 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", + ); + } } // Check the diff between old and new editable region. From 3f1c55216998c46b5e1244ddf3df4809436d0844 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 29 Jul 2025 18:54:07 -0700 Subject: [PATCH 11/22] fix: race condition --- extensions/vscode/src/extension/VsCodeExtension.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 05debe7e9..1ee0229b1 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -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( From eddb7bf1f2213537717ff64162e8429faf59e51c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 09:56:39 -0700 Subject: [PATCH 12/22] fix: add a newline accordingly --- .../templating/mercuryCoderNextEdit.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.ts b/core/nextEdit/templating/mercuryCoderNextEdit.ts index a7f79962b..616700b17 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.ts @@ -5,16 +5,16 @@ import { insertCursorToken } from "./utils"; export function recentlyViewedCodeSnippetsBlock( recentlyViewedCodeSnippets: { filepath: string; content: string }[], ) { - return [ - recentlyViewedCodeSnippets.reduce((acc, snippet) => { - const block = [ - `code_snippet_file_path: ${snippet.filepath}`, - snippet.content, - ].join("\n"); + return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => { + const block = [ + `code_snippet_file_path: ${snippet.filepath}`, + snippet.content, + ].join("\n"); - return acc + block; - }, ""), - ].join("\n"); + return ( + acc + block + (i === recentlyViewedCodeSnippets.length - 1 ? "" : "\n") + ); + }, ""); } export function currentFileContentBlock( From cdce8200307c853fc14b6d3bf7425e693283835a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 09:56:53 -0700 Subject: [PATCH 13/22] test: add vitest for mercuryCoderNextEdit --- .../templating/mercuryCoderNextEdit.vitest.ts | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts new file mode 100644 index 000000000..2849082b7 --- /dev/null +++ b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts @@ -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(""); + }); + }); +}); From affe6abe1a715a1cd128bedef8ab61556bbf40fd Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 10:00:29 -0700 Subject: [PATCH 14/22] refactor: remove unused function --- core/nextEdit/templating/utils.ts | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/core/nextEdit/templating/utils.ts b/core/nextEdit/templating/utils.ts index 9eca26866..a75712689 100644 --- a/core/nextEdit/templating/utils.ts +++ b/core/nextEdit/templating/utils.ts @@ -4,7 +4,6 @@ import { EDITABLE_REGION_START_TOKEN, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; export function insertCursorToken( @@ -52,8 +51,6 @@ export function insertEditableRegionTokensWithStaticRange( ); } - // console.log("editableRegionStart:", editableRegionStart); - const instrumentedLines = [ ...lines.slice(0, editableRegionStart), EDITABLE_REGION_START_TOKEN, @@ -64,22 +61,3 @@ export function insertEditableRegionTokensWithStaticRange( return instrumentedLines; } - -export 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; -} From 7a0d44a7ff4010fb58d9ce6c5e8dc265d594d943 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 10:00:39 -0700 Subject: [PATCH 15/22] test: add vitest for utils --- core/nextEdit/templating/utils.vitest.ts | 134 +++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 core/nextEdit/templating/utils.vitest.ts diff --git a/core/nextEdit/templating/utils.vitest.ts b/core/nextEdit/templating/utils.vitest.ts new file mode 100644 index 000000000..a2f8772ba --- /dev/null +++ b/core/nextEdit/templating/utils.vitest.ts @@ -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); + }); +}); From 8e0811ac430df53fe911a6b0d312082f578f2531 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 10:15:48 -0700 Subject: [PATCH 16/22] chore: delete comment --- core/nextEdit/templating/NextEditPromptEngine.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index ffbf41af3..1369ebbc6 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -68,7 +68,6 @@ function templateRendererOfModel( export async function renderPrompt( helper: HelperVars, - // userEdits: string, ctx: any, ): Promise { let modelName = helper.modelName as NextEditModelName; From 884bc7ef26715b1c046362094757d62c022894d5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 10:16:00 -0700 Subject: [PATCH 17/22] test: add vitest for NextEditPromptEngine --- .../templating/NextEditPromptEngine.vitest.ts | 236 ++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 core/nextEdit/templating/NextEditPromptEngine.vitest.ts diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts new file mode 100644 index 000000000..aa3fad6a6 --- /dev/null +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -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); + }); + }); + }); +}); From ec26d5719df3c9c31b45317c8f96157d634b8a56 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 10:18:10 -0700 Subject: [PATCH 18/22] refactor: it's easier to test next edit without the minus --- manual-testing-sandbox/test.js | 1 - 1 file changed, 1 deletion(-) diff --git a/manual-testing-sandbox/test.js b/manual-testing-sandbox/test.js index ae47c4610..d2920d6af 100644 --- a/manual-testing-sandbox/test.js +++ b/manual-testing-sandbox/test.js @@ -8,7 +8,6 @@ class Calculator { return this; } subtract(number) { - this.result -= number; return this; } From 4f3c176762259cab8a03820a3aee2172eb669867 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 10:58:02 -0700 Subject: [PATCH 19/22] fix: prettier --- extensions/vscode/src/extension/VsCodeExtension.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 1ee0229b1..d5b0766ae 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -445,8 +445,8 @@ export class VsCodeExtension { // 2. A jump is in progress. if ( JumpManager.getInstance().isJumpInProgress() || - JumpManager.getInstance().wasJumpJustAccepted - ()) { + JumpManager.getInstance().wasJumpJustAccepted() + ) { return; } From bd3288e75105c5f7560574e4a04159fc7dfe8c4a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 15:27:03 -0700 Subject: [PATCH 20/22] chore: delete comments --- core/nextEdit/NextEditProvider.ts | 1 - .../vscode/src/activation/JumpManager.ts | 7 +--- .../src/autocomplete/completionProvider.ts | 42 +++---------------- 3 files changed, 7 insertions(+), 43 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index b4c30d99f..014427819 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -366,7 +366,6 @@ export class NextEditProvider { const promptMetadata = await renderPrompt( helper, - // historyDiff ?? this.diffContext, ctx, ); diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 9ba4ce8a1..48797f007 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -133,7 +133,6 @@ export class JumpManager { return false; } - // if (editor) { const visibleRanges = editor.visibleRanges; if (visibleRanges.length === 0) { console.log("No visible ranges in editor, cannot suggest jump"); @@ -141,7 +140,6 @@ export class JumpManager { return false; } - // if (visibleRanges.length > 0) { const visibleRange = visibleRanges[0]; const topLineNumber = visibleRange.start.line; const bottomLineNumber = visibleRange.end.line; @@ -175,9 +173,6 @@ export class JumpManager { 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(() => { @@ -200,7 +195,7 @@ export class JumpManager { setTimeout(() => { this._jumpInProgress = false; disposable.dispose(); - }, 5000); + }, 10000); return true; } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 949494c99..452df25a6 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -423,46 +423,15 @@ export class ContinueCompletionProvider const currCursorPos = editor.selection.active; if (this.isNextEditActive) { - // if (!this.nextEditProvider.isStartOfChain()) { - // const jumpPosition = new vscode.Position( - // (outcome as NextEditOutcome).editableRegionStartLine, - // 0, - // ); - - // // 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, - // ); - - // // 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, - // }); - - // return undefined; // Don't show anything yet! - // } - - // return undefined; - // } if (!this.nextEditProvider.isStartOfChain()) { - // Try suggesting jumps for each location in the queue + // Try suggesting jumps for each location in the queue. let jumpSuccessful = false; - // let attempts = 0; while ( this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength() > 0 && !jumpSuccessful ) { - // Limit attempts - // attempts++; const nextRegion = this.nextEditProvider.shiftNextEditableRegionsInTheCurrentChain(); if (!nextRegion) continue; @@ -472,7 +441,7 @@ export class ContinueCompletionProvider nextRegion.range.start.character, ); - // Try to suggest a jump to this location + // Try to suggest a jump to this location. jumpSuccessful = await this.jumpManager.suggestJump( currCursorPos, jumpPosition, @@ -480,23 +449,24 @@ export class ContinueCompletionProvider ); if (jumpSuccessful) { - // Store completion to be rendered after jump + // 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; // Don't show anything yet! } } // If no jump was successful after trying multiple locations, - // proceed with other completion display logic or return undefined + // proceed with other completion display logic or return undefined. if (!jumpSuccessful) { console.log( "No suitable jump location found after trying multiple positions", ); + return undefined; } } From 484b4833c13dfe35173304fa932a6e8e7e6b17f3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 15:29:06 -0700 Subject: [PATCH 21/22] fix: prettier --- core/nextEdit/NextEditProvider.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 014427819..1ae21c152 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -364,10 +364,7 @@ export class NextEditProvider { ctx = {}; } - const promptMetadata = await renderPrompt( - helper, - ctx, - ); + const promptMetadata = await renderPrompt(helper, ctx); this.promptMetadata = promptMetadata; From cb6b819dea819bc49f65b34250602e351c49dcce Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 30 Jul 2025 15:29:15 -0700 Subject: [PATCH 22/22] fix: restore launch settings --- .vscode/launch.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 7d8624157..656f25993 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -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,