Merge pull request #7107 from continuedev/jacob/con-3358

fix: prompt building
This commit is contained in:
Jacob Kim 2025-08-12 15:03:13 -07:00 • committed by GitHub
commit e8de12e34a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 414 additions and 270 deletions

View file

@ -178,7 +178,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
NEXT_EDIT_MODELS.MODEL_1,
NEXT_EDIT_MODELS.INSTINCT,
];
function modelSupportsNextEdit(

View file

@ -245,8 +245,10 @@ describe("modelSupportsNextEdit", () => {
).toBe(true);
});
it("should return true for model-1", () => {
expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true);
it("should return true for instinct", () => {
expect(modelSupportsNextEdit(undefined, "instinct", undefined)).toBe(
true,
);
});
it("should return true when model contains supported model name as substring", () => {
@ -269,9 +271,9 @@ describe("modelSupportsNextEdit", () => {
).toBe(true);
});
it("should return true when title contains model-1", () => {
it("should return true when title contains instinct", () => {
expect(
modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"),
modelSupportsNextEdit(undefined, "some-model", "instinct deployment"),
).toBe(true);
});
@ -317,7 +319,7 @@ describe("modelSupportsNextEdit", () => {
it("should handle case sensitivity correctly", () => {
expect(
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"),
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
).toBe(true);
});

View file

@ -21,7 +21,7 @@ export enum LLMConfigurationStatuses {
export enum NEXT_EDIT_MODELS {
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
MODEL_1 = "model-1",
INSTINCT = "instinct",
}
export {

View file

@ -1,11 +1,9 @@
import Parser from "web-tree-sitter";
import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from "..";
import { getAst } from "../autocomplete/util/ast";
import { NEXT_EDIT_MODELS } from "../llm/constants";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker";
import {
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "./constants";
import { MODEL_WINDOW_SIZES } from "./constants";
export enum EditableRegionStrategy {
Naive = "naive",
@ -60,16 +58,16 @@ function naiveJump(ctx: any): RangeInFile[] | null {
// Sliding splits the file using into sliding window.
function slidingJump(ctx: any): RangeInFile[] | null {
const { fileLines, filepath } = ctx;
if (!fileLines || !filepath) {
console.warn("Missing required context for naive jump");
const { fileLines, filepath, modelName, currentCursorPos } = ctx;
if (!fileLines || !filepath || !modelName || !currentCursorPos) {
console.warn("Missing required context for sliding jump");
return null;
}
const windowSize =
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN +
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN +
1; // 1 for current line;
const topMargin = MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].topMargin;
const bottomMargin =
MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].bottomMargin;
const windowSize = topMargin + bottomMargin + 1; // 1 for current line
if (fileLines.length <= windowSize) {
return [
@ -86,29 +84,74 @@ function slidingJump(ctx: any): RangeInFile[] | null {
];
}
const slidingStep = Math.max(1, Math.floor(windowSize / 2));
const ranges: RangeInFile[] = [];
const cursorLine = currentCursorPos.line;
for (
let startLine = 0;
startLine < fileLines.length;
startLine += slidingStep
) {
const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1);
// Create the first window centered around the cursor position
const firstWindowStart = Math.max(0, cursorLine - topMargin);
const firstWindowEnd = Math.min(
fileLines.length - 1,
cursorLine + bottomMargin,
);
ranges.push({
filepath,
range: {
start: { line: startLine, character: 0 },
end: {
line: endLine,
character: fileLines[endLine].length,
},
ranges.push({
filepath,
range: {
start: { line: firstWindowStart, character: 0 },
end: {
line: firstWindowEnd,
character: fileLines[firstWindowEnd].length,
},
});
},
});
if (endLine >= fileLines.length - 1) {
break;
// Alternating pattern: down once, up once, repeat
const slidingStep = Math.max(1, Math.floor(windowSize / 2));
let currentStartDown = firstWindowEnd + 1;
let currentStartUp = firstWindowStart - slidingStep;
while (currentStartDown < fileLines.length || currentStartUp >= 0) {
// Go down once
if (currentStartDown < fileLines.length) {
const windowStart = currentStartDown;
const windowEnd = Math.min(
windowStart + windowSize - 1,
fileLines.length - 1,
);
ranges.push({
filepath,
range: {
start: { line: windowStart, character: 0 },
end: {
line: windowEnd,
character: fileLines[windowEnd].length,
},
},
});
currentStartDown += slidingStep;
}
// Go up once
if (currentStartUp >= 0) {
const windowStart = Math.max(0, currentStartUp);
const windowEnd = Math.min(
windowStart + windowSize - 1,
fileLines.length - 1,
);
ranges.push({
filepath,
range: {
start: { line: windowStart, character: 0 },
end: {
line: windowEnd,
character: fileLines[windowEnd].length,
},
},
});
currentStartUp -= slidingStep;
}
}

View file

@ -59,6 +59,11 @@ export class PrefetchQueue {
!this.abortController.signal.aborted
) {
const location = this.dequeueUnprocessed();
console.log("processing:");
console.log(
location?.range.start.line + " to " + location?.range.end.line,
);
if (!location) break;
try {
@ -70,12 +75,20 @@ export class PrefetchQueue {
this.usingFullFileDiff,
);
if (!outcome) continue;
if (!outcome) {
console.log("outcome is undefined");
continue;
}
this.enqueueProcessed({
location,
outcome,
});
console.log(
"the length of processed queue after processing is:",
this.processedQueue.length,
);
} catch (error) {
if (!this.abortController.signal.aborted) {
// Handle error
@ -115,6 +128,16 @@ export class PrefetchQueue {
return this.processedQueue[0];
}
peekThreeProcessed(): void {
const count = Math.min(3, this.processedQueue.length);
const firstThree = this.processedQueue.slice(0, count);
firstThree.forEach((item, index) => {
console.log(
`Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`,
);
});
}
setPreetchLimit(limit: number): void {
this.prefetchLimit = limit;
}

View file

@ -35,11 +35,10 @@ import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import { replaceEscapedCharacters } from "../util/text.js";
import {
INSTINCT_SYSTEM_PROMPT,
MERCURY_CODE_TO_EDIT_OPEN,
MERCURY_SYSTEM_PROMPT,
MODEL_1_SYSTEM_PROMPT,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
MODEL_WINDOW_SIZES,
} from "./constants.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import {
@ -83,7 +82,7 @@ export class NextEditProvider {
private loggingService: NextEditLoggingService;
private contextRetrievalService: ContextRetrievalService;
private endpointType: "default" | "fineTuned";
private diffContext: string = "";
private diffContext: string[] = [];
private autocompleteContext: string = "";
private promptMetadata: PromptMetadata | null = null;
private currentEditChainId: string | null = null;
@ -136,7 +135,10 @@ export class NextEditProvider {
}
public addDiffToContext(diff: string): void {
this.diffContext = diff;
this.diffContext.push(diff);
if (this.diffContext.length > 5) {
this.diffContext.shift();
}
}
public addAutocompleteContext(ctx: string): void {
@ -390,16 +392,20 @@ export class NextEditProvider {
this.ide.getWorkspaceDirs(),
]);
const modelName = helper.modelName.includes("mercury-coder-nextedit")
? "mercury-coder-nextedit"
: "instinct";
const { editableRegionStartLine, editableRegionEndLine } =
opts?.usingFullFileDiff
? this._calculateOptimalEditableRegion(helper, "tokenizer")
: {
editableRegionStartLine: Math.max(
helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
0,
),
editableRegionEndLine: Math.min(
helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
helper.fileLines.length - 1,
),
};
@ -558,7 +564,7 @@ export class NextEditProvider {
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
};
} else if (modelName.includes("model-1")) {
} else if (modelName.includes("instinct")) {
// Calculate the window around the cursor position (25 lines above and below).
const windowStart = Math.max(0, helper.pos.line - 25);
const windowEnd = Math.min(
@ -566,23 +572,29 @@ export class NextEditProvider {
helper.pos.line + 25,
);
// The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
const actualEditableStart = Math.max(0, helper.pos.line - 1);
const actualEditableEnd = Math.min(
helper.fileLines.length - 1,
helper.pos.line + 5,
);
// // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
// const actualEditableStart = Math.max(
// 0,
// helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin,
// );
// const actualEditableEnd = Math.min(
// helper.fileLines.length - 1,
// helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin,
// );
// Ensure editable region boundaries are within the window.
const adjustedEditableStart = Math.max(windowStart, actualEditableStart);
const adjustedEditableEnd = Math.min(windowEnd, actualEditableEnd);
const adjustedEditableStart = Math.max(
windowStart,
editableRegionStartLine,
);
const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
ctx = {
contextSnippets: this.autocompleteContext,
currentFileContent: helper.fileContents,
windowStart,
windowEnd,
adjustedEditableStart,
adjustedEditableEnd,
editableRegionStartLine: adjustedEditableStart,
editableRegionEndLine: adjustedEditableEnd,
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
languageShorthand: helper.lang.name,
@ -598,7 +610,7 @@ export class NextEditProvider {
role: "system",
content: modelName.includes("mercury-coder-nextedit")
? MERCURY_SYSTEM_PROMPT
: MODEL_1_SYSTEM_PROMPT,
: INSTINCT_SYSTEM_PROMPT,
};
return [systemPrompt, promptMetadata.prompt];
@ -666,6 +678,8 @@ export class NextEditProvider {
if (!llm) return undefined;
const msg: ChatMessage = await llm.chat(prompts, token);
console.log("message");
console.log(msg.content);
if (typeof msg.content !== "string") {
return undefined;
@ -677,16 +691,17 @@ export class NextEditProvider {
? replaceEscapedCharacters(
msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1],
).replace(/\n$/, "")
: "";
: replaceEscapedCharacters(msg.content);
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
return await this._handlePartialFileDiff(
// we could use fillFileDiff
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
editableRegionStartLine,
editableRegionEndLine,
);
} else {
return await this._handleFullFileDiff(
@ -702,11 +717,11 @@ export class NextEditProvider {
private async _handlePartialFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
editableRegionStartLine: number,
editableRegionEndLine: number,
): Promise<NextEditOutcome | undefined> {
const oldEditRangeSlice = helper.fileContents
.split("\n")
@ -1016,6 +1031,7 @@ export class NextEditProvider {
try {
const previousOutcome = this.getPreviousCompletion();
if (!previousOutcome) {
console.log("previousOutcome is undefined");
return undefined;
}
@ -1026,6 +1042,7 @@ export class NextEditProvider {
ctx,
);
if (!input) {
console.log("input is undefined");
return undefined;
}

View file

@ -1,14 +1,27 @@
import { NEXT_EDIT_MODELS } from "../llm/constants";
export const IS_NEXT_EDIT_ACTIVE = false;
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0;
export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
export const MODEL_WINDOW_SIZES: Record<
NEXT_EDIT_MODELS,
{ topMargin: number; bottomMargin: number }
> = {
"mercury-coder-nextedit": {
topMargin: 0,
bottomMargin: 5,
}, // mercury coder nextedit uses full file diff, so this should be unnecessary
instinct: { topMargin: 1, bottomMargin: 5 },
};
// Model 1-specific tokens.
export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
export const MODEL_1_CONTEXT_FILE_TOKEN = "<|context_file|>";
export const MODEL_1_SNIPPET_TOKEN = "<|snippet|>";
export const MODEL_1_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags.
export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>";
export const INSTINCT_SNIPPET_TOKEN = "<|snippet|>";
export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags.
You have access to the following information to help you make informed suggestions:
@ -31,7 +44,7 @@ Your task is to predict and complete the changes the developer would have made n
- Provide only the revised code within the tags. Do not include the tags in your output.
- Ensure that you do not output duplicate code that exists outside of these tags.
- Avoid undoing or reverting the developer's last change unless there are obvious typos or errors.`;
export const MODEL_1_USER_PROMPT_PREFIX =
export const INSTINCT_USER_PROMPT_PREFIX =
"Reference the user excerpt, user edits, and the snippets to understand the developer's intent. Update the editable region of the user excerpt by predicting and completing the changes they would have made next. This may be a deletion, addition, or modification of code.";
// Mercury Coder Next Edit-specific tokens.

View file

@ -4,35 +4,33 @@ import { SnippetPayload } from "../../autocomplete/snippets";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_PROMPT_PREFIX,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
MERCURY_EDIT_DIFF_HISTORY_CLOSE,
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
MODEL_1_USER_PROMPT_PREFIX,
} from "../constants";
import {
InstinctTemplateVars,
MercuryTemplateVars,
Model1TemplateVars,
NextEditTemplate,
PromptMetadata,
SystemPrompt,
TemplateVars,
UserPrompt,
} from "../types";
import {
contextSnippetsBlock,
currentFileContentBlock as instinctCurrentFileContentBlock,
editHistoryBlock as instinctEditHistoryBlock,
} from "./instinct";
import {
currentFileContentBlock,
editHistoryBlock,
recentlyViewedCodeSnippetsBlock,
} from "./mercuryCoderNextEdit";
import {
contextSnippetsBlock,
currentFileContentBlock as model1CurrentFileContentBlock,
editHistoryBlock as model1EditHistoryBlock,
} from "./model1";
import {
insertCursorToken,
insertEditableRegionTokensWithStaticRange,
@ -44,8 +42,8 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
"mercury-coder-nextedit": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_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 {{{currentFilePath}}}.\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: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`,
instinct: {
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
},
};
@ -95,11 +93,11 @@ export async function renderPrompt(
case "mercury-coder-nextedit": {
userEdits = ctx.editDiffHistory;
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
MERCURY_CURSOR,
);
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// MERCURY_CURSOR,
// );
const mercuryCtx: MercuryTemplateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
@ -117,20 +115,22 @@ export async function renderPrompt(
tv = mercuryCtx;
editedCodeWithTokens = mercuryCtx.currentFileContent;
break;
}
case "model-1": {
case "instinct": {
userEdits = ctx.editDiffHistory;
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
);
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
// );
const model1Ctx: Model1TemplateVars = {
const instinctCtx: InstinctTemplateVars = {
contextSnippets: contextSnippetsBlock(ctx.contextSnippets),
currentFileContent: model1CurrentFileContentBlock(
currentFileContent: instinctCurrentFileContentBlock(
ctx.currentFileContent,
ctx.windowStart,
ctx.windowEnd,
@ -138,12 +138,14 @@ export async function renderPrompt(
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: model1EditHistoryBlock(ctx.editDiffHistory),
editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
languageShorthand: ctx.languageShorthand,
};
tv = model1Ctx;
tv = instinctCtx;
editedCodeWithTokens = instinctCtx.currentFileContent;
break;
}

View file

@ -5,6 +5,8 @@ import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
INSTINCT_USER_PROMPT_PREFIX,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
@ -12,8 +14,6 @@ import {
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
MODEL_1_USER_PROMPT_PREFIX,
} from "../constants";
import {
renderDefaultSystemPrompt,
@ -24,7 +24,7 @@ import {
describe("NextEditPromptEngine", () => {
describe("renderPrompt", () => {
let mercuryHelper: HelperVars;
let model1Helper: HelperVars;
let instinctHelper: HelperVars;
let testHelper: HelperVars;
let unsupportedHelper: HelperVars;
let ctx: any;
@ -36,8 +36,8 @@ describe("NextEditPromptEngine", () => {
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
model1Helper = {
modelName: "continuedev/model-1" as NEXT_EDIT_MODELS,
instinctHelper = {
modelName: "continuedev/instinct" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
@ -54,7 +54,7 @@ describe("NextEditPromptEngine", () => {
{ 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 @@",
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
editableRegionStartLine: 0,
editableRegionEndLine: 3,
userEdits: "Added constant a",
@ -81,35 +81,35 @@ describe("NextEditPromptEngine", () => {
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
});
it("should render model-1 prompt correctly", async () => {
// Create proper model-1 context structure matching NextEditProvider.ts
const model1Ctx = {
it("should render instinct prompt correctly", async () => {
// Create proper instinct context structure matching NextEditProvider.ts
const instinctCtx = {
contextSnippets:
"+++++ /path/to/context.ts\nconst contextVar = 'test';",
currentFileContent: model1Helper.fileContents,
currentFileContent: instinctHelper.fileContents,
windowStart: 0, // Math.max(0, helper.pos.line - 25)
windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25)
adjustedEditableStart: 0, // Math.max(0, helper.pos.line - 1) within window
adjustedEditableEnd: 2, // Math.min(helper.pos.line + 5) within window
editDiffHistory:
"diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", // unified diff
editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window
editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window
editDiffHistory: [
"diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }",
], // unified diff
currentFilePath: "/path/to/file.ts",
languageShorthand: "ts",
};
const result = await renderPrompt(model1Helper, model1Ctx);
const result = await renderPrompt(instinctHelper, instinctCtx);
console.log(result);
expect(result).toHaveProperty("prompt");
expect(result.prompt.role).toBe("user");
expect(result.prompt.content).toContain(MODEL_1_USER_PROMPT_PREFIX);
expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX);
expect(result.prompt.content).toContain("### Context:");
expect(result.prompt.content).toContain("### User Edits:");
expect(result.prompt.content).toContain("### User Excerpts:");
expect(result.prompt.content).toContain("```ts");
expect(result.userEdits).toBe(model1Ctx.editDiffHistory);
expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN);
expect(result.userEdits).toBe(instinctCtx.editDiffHistory);
expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN);
});
it("should throw error for unsupported model name", async () => {
@ -223,7 +223,7 @@ describe("NextEditPromptEngine", () => {
{ 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 @@",
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
editableRegionStartLine: 0,
editableRegionEndLine: 3,
userEdits: "Added constant a",

View file

@ -0,0 +1,129 @@
import { Position } from "../..";
import {
INSTINCT_CONTEXT_FILE_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
INSTINCT_SNIPPET_TOKEN,
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import { insertCursorToken } from "./utils";
/**
* @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string.
*/
export function contextSnippetsBlock(contextSnippets: string) {
const headerRegex = /^(\+\+\+\+\+ )(.*)/;
const lines = contextSnippets.split("\n");
return lines
.reduce<string[]>((acc, line) => {
const matches = line.match(headerRegex);
if (matches) {
const filename = matches[2];
acc.push(`${INSTINCT_CONTEXT_FILE_TOKEN}: ${filename}`);
} else {
if (
acc.length > 0 &&
acc[acc.length - 1].startsWith(INSTINCT_CONTEXT_FILE_TOKEN) // if header was added just before
) {
acc.push(`${INSTINCT_SNIPPET_TOKEN}`);
}
acc.push(line);
}
return acc;
}, [])
.join("\n");
}
export function currentFileContentBlock(
currentFileContent: string,
windowStart: number,
windowEnd: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
cursorPosition: Position,
) {
const currentFileContentLines = currentFileContent.split("\n");
const insertedCursorLines = insertCursorToken(
currentFileContentLines,
cursorPosition,
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
);
const instrumentedLines = [
...insertedCursorLines.slice(windowStart, editableRegionStartLine),
INSTINCT_EDITABLE_REGION_START_TOKEN,
...insertedCursorLines.slice(
editableRegionStartLine,
editableRegionEndLine + 1,
),
INSTINCT_EDITABLE_REGION_END_TOKEN,
...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1),
];
return instrumentedLines.join("\n");
}
export function editHistoryBlock(
editDiffHistories: string[], // array of unified diffs with Index headers
) {
if (!editDiffHistories.length) {
return "";
}
const blocks: string[] = [];
for (const editDiffHistory of editDiffHistories) {
if (!editDiffHistory.trim()) {
continue;
}
// Split on Index: lines to get the unified diff.
const diffSections = editDiffHistory
.split(/^Index: /m)
.filter((section) => section.trim());
for (const section of diffSections) {
const lines = section.split("\n");
// Extract filename from the first line (after "Index: " was split off).
const filename = lines[0];
// Find the start of the actual diff content (skip ---, +++, and === lines).
const diffLines = lines
.filter(
(line) =>
!line.startsWith("---") &&
!line.startsWith("+++") &&
!line.startsWith("===") &&
line.trim() !== "", // remove empty lines from header section
)
.slice(1); // remove the filename line
// Only include lines that are actual diff content (@@, +, -, or context lines).
const actualDiffContent = diffLines.filter(
(line) =>
line.startsWith("@@") ||
line.startsWith("+") ||
line.startsWith("-") ||
line.startsWith(" "), // context lines
);
if (actualDiffContent.length === 0) continue;
const diffBlock = [
`User edited file "${filename}"`,
"",
"```diff",
actualDiffContent.join("\n"),
"```",
].join("\n");
blocks.push(diffBlock);
}
}
return blocks.join("\n");
}

View file

@ -4,7 +4,7 @@ import {
contextSnippetsBlock,
currentFileContentBlock,
editHistoryBlock,
} from "./model1";
} from "./instinct";
describe("contextSnippetsBlock", () => {
test("should format empty context snippets", () => {
@ -291,7 +291,7 @@ line 3`;
describe("editHistoryBlock", () => {
test("should format empty edit history", () => {
const result = editHistoryBlock("");
const result = editHistoryBlock([]);
expect(result).toBe("");
});
@ -306,7 +306,7 @@ describe("editHistoryBlock", () => {
+ console.log("new");
}`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "test.js"
\`\`\`diff
@ -337,7 +337,45 @@ Index: file2.js
-let x = "old";
+let x = "new";`;
const result = editHistoryBlock(unifiedDiff);
const result = editHistoryBlock([unifiedDiff]);
const expected = `User edited file "file1.js"
\`\`\`diff
@@ -1 +1 @@
-const old = 1;
+const new = 1;
\`\`\`
User edited file "file2.js"
\`\`\`diff
@@ -1 +1 @@
-let x = "old";
+let x = "new";
\`\`\``;
expect(result).toBe(expected);
});
test("should format multiple diff history entries", () => {
// Multiple diffs should be concatenated into a single string
const unifiedDiffs = [
`Index: file1.js
===================================================================
--- a/file1.js 2023-01-01 10:00:00.000000000 +0000
+++ b/file1.js 2023-01-01 10:01:00.000000000 +0000
@@ -1 +1 @@
-const old = 1;
+const new = 1;`,
`Index: file2.js
===================================================================
--- a/file2.js 2023-01-01 10:02:00.000000000 +0000
+++ b/file2.js 2023-01-01 10:03:00.000000000 +0000
@@ -1 +1 @@
-let x = "old";
+let x = "new";`,
];
const result = editHistoryBlock(unifiedDiffs);
const expected = `User edited file "file1.js"
\`\`\`diff
@ -366,7 +404,7 @@ User edited file "file2.js"
-export const Button = () => <button>Old</button>;
+export const Button = () => <button>New</button>;`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "src/components/Button/Button.tsx"
\`\`\`diff
@ -388,7 +426,7 @@ User edited file "file2.js"
+ return "hello world";
+}`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "newfile.js"
\`\`\`diff
@ -411,7 +449,7 @@ User edited file "file2.js"
- return "goodbye";
-}`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "deletedfile.js"
\`\`\`diff
@ -431,7 +469,7 @@ User edited file "file2.js"
-old text
+new text`;
const result = editHistoryBlock(diff);
const result = editHistoryBlock([diff]);
const expected = `User edited file "simple.txt"
\`\`\`diff

View file

@ -50,12 +50,15 @@ export function currentFileContentBlock(
}
export function editHistoryBlock(
editDiffHistory: string, // could be a singe large unified diff
editDiffHistory: string[], // could be a singe large unified diff
) {
// diffHistory is made from createDiff.
// This uses createPatch from npm diff library, which includes an index line and a separator.
// We get rid of these first two lines.
return editDiffHistory.split("\n").slice(2).join("\n");
return editDiffHistory
.map((diff) => diff.split("\n").slice(2).join("\n"))
.join("\n");
// return editDiffHistory.split("\n").slice(2).join("\n");
}
function mercuryNextEditTemplateBuilder(

View file

@ -108,12 +108,12 @@ describe("mercuryCoderNextEdit", () => {
it("should return the edit diff history unchanged", () => {
const diffHistory =
"diff --git a/file.ts b/file.ts\n==============================\n@@ -1,3 +1,4 @@";
const result = editHistoryBlock(diffHistory);
const result = editHistoryBlock([diffHistory]);
expect(result).toBe("@@ -1,3 +1,4 @@");
});
it("should handle empty diff history", () => {
const result = editHistoryBlock("");
const result = editHistoryBlock([]);
expect(result).toBe("");
});
});

View file

@ -1,123 +0,0 @@
import { Position } from "../..";
import {
MODEL_1_CONTEXT_FILE_TOKEN,
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
MODEL_1_SNIPPET_TOKEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import { insertCursorToken } from "./utils";
/**
* @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string.
*/
export function contextSnippetsBlock(contextSnippets: string) {
const headerRegex = /^(\+\+\+\+\+ )(.*)/;
const lines = contextSnippets.split("\n");
return lines
.reduce<string[]>((acc, line) => {
const matches = line.match(headerRegex);
if (matches) {
const filename = matches[2];
acc.push(`${MODEL_1_CONTEXT_FILE_TOKEN}: ${filename}`);
} else {
if (
acc.length > 0 &&
acc[acc.length - 1].startsWith(MODEL_1_CONTEXT_FILE_TOKEN) // if header was added just before
) {
acc.push(`${MODEL_1_SNIPPET_TOKEN}`);
}
acc.push(line);
}
return acc;
}, [])
.join("\n");
}
export function currentFileContentBlock(
currentFileContent: string,
windowStart: number,
windowEnd: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
cursorPosition: Position,
) {
const currentFileContentLines = currentFileContent.split("\n");
const insertedCursorLines = insertCursorToken(
currentFileContentLines,
cursorPosition,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
);
const instrumentedLines = [
...insertedCursorLines.slice(windowStart, editableRegionStartLine),
MODEL_1_EDITABLE_REGION_START_TOKEN,
...insertedCursorLines.slice(
editableRegionStartLine,
editableRegionEndLine + 1,
),
MODEL_1_EDITABLE_REGION_END_TOKEN,
...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1),
];
return instrumentedLines.join("\n");
}
export function editHistoryBlock(
editDiffHistories: string, // unified diffs with Index headers
) {
if (!editDiffHistories.trim()) {
return "";
}
const blocks: string[] = [];
// Split on Index: lines to get the unified diff.
const diffSections = editDiffHistories
.split(/^Index: /m)
.filter((section) => section.trim());
for (const section of diffSections) {
const lines = section.split("\n");
// Extract filename from the first line (after "Index: " was split off).
const filename = lines[0];
// Find the start of the actual diff content (skip ---, +++, and === lines).
const diffLines = lines
.filter(
(line) =>
!line.startsWith("---") &&
!line.startsWith("+++") &&
!line.startsWith("===") &&
line.trim() !== "", // remove empty lines from header section
)
.slice(1); // remove the filename line
// Only include lines that are actual diff content (@@, +, -, or context lines).
const actualDiffContent = diffLines.filter(
(line) =>
line.startsWith("@@") ||
line.startsWith("+") ||
line.startsWith("-") ||
line.startsWith(" "), // context lines
);
if (actualDiffContent.length === 0) continue;
const diffBlock = [
`User edited file "${filename}"`,
"",
"```diff",
actualDiffContent.join("\n"),
"```",
].join("\n");
blocks.push(diffBlock);
}
return blocks.join("\n");
}

View file

@ -1,7 +1,7 @@
import { Position } from "../..";
import {
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "../constants";
@ -53,9 +53,9 @@ export function insertEditableRegionTokensWithStaticRange(
const instrumentedLines = [
...lines.slice(0, editableRegionStart),
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
...lines.slice(editableRegionStart, editableRegionEnd + 1),
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
...lines.slice(editableRegionEnd + 1),
];

View file

@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import { Position } from "../..";
import {
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "../constants";
@ -88,9 +88,9 @@ describe("insertEditableRegionTokensWithStaticRange", () => {
const expected = [
...lines.slice(0, expectedStart),
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
...lines.slice(expectedStart, expectedEnd + 1),
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
...lines.slice(expectedEnd + 1),
];
@ -112,11 +112,11 @@ describe("insertEditableRegionTokensWithStaticRange", () => {
const expected = [
"line 0",
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
"line 1",
"line 2",
"line 3",
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
"line 4",
];

View file

@ -90,7 +90,7 @@ export interface NextEditTemplate {
export interface TemplateVars {}
export interface Model1TemplateVars extends TemplateVars {
export interface InstinctTemplateVars extends TemplateVars {
contextSnippets: string;
currentFileContent: string;
editDiffHistory: string; // could be a singe large unified diff

View file

@ -261,18 +261,15 @@ export class ContinueCompletionProvider
let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
// console.log(
// "chain exists?",
// this.nextEditProvider.chainExists(),
// ", length:",
// this.nextEditProvider.getChainLength(),
// ", next regions queue:",
// this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(),
// );
// TODO: We can probably decide here if we want to do the jumping logic.
// If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager.
// It would simplify the logic quite substantially.
// Determine why this method was triggered.
const isJumping = this.jumpManager.isJumpInProgress();
const chainExists = this.nextEditProvider.chainExists();
console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
this.prefetchQueue.peekThreeProcessed();
if (isJumping && chainExists) {
// Case 2: Jumping (chain exists, jump was taken)
@ -340,7 +337,6 @@ export class ContinueCompletionProvider
if (isJumpSuggested) {
// Store completion to be rendered after a jump.
// TODO: setCompletionAfterJump must have a 1-1 correspondence to the jump location.
this.jumpManager.setCompletionAfterJump({
completionId: completionId,
outcome,

View file

@ -113,7 +113,8 @@ export class VsCodeExtension {
Date.now() - state.lastDocumentChangeTime;
if (
state.isTypingSession &&
timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY
timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY &&
!NextEditWindowManager.getInstance().hasAccepted()
) {
console.log("VsCodeExtension: typing in progress, preserving chain");
return true;