Merge branch 'main' of https://github.com/continuedev/continue into dallin/docs-redirects-agent

This commit is contained in:
Dallin Romney 2025-08-22 14:53:18 -07:00
commit 82dae6f402
94 changed files with 6075 additions and 4658 deletions

View file

@ -93,6 +93,13 @@ runs:
path: binary/node_modules
key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
- name: Install binary dependencies
if: steps.binary-cache.outputs.cache-hit != 'true'
shell: bash
run: |
cd binary
npm ci
- name: Build the binaries
shell: bash
run: |

View file

@ -18,19 +18,28 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Install dependencies
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
uses: ./.github/actions/setup-component
with:
component: core
include-root: true
- name: Install CLI dependencies
working-directory: extensions/cli
run: npm ci
env:

View file

@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
@ -36,7 +36,7 @@ jobs:
- name: Install dependencies
run: |
cd extensions/cli
npm ci
npm ci --include=optional
- name: Run linting
run: |
@ -52,14 +52,20 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "npm"
cache-dependency-path: extensions/cli/package-lock.json
- name: Cache CLI node_modules
uses: actions/cache@v4
with:
path: extensions/cli/node_modules
key: ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-${{ hashFiles('extensions/cli/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-
- name: Setup packages
uses: ./.github/actions/setup-packages
@ -72,13 +78,18 @@ jobs:
- name: Install dependencies
run: |
cd extensions/cli
npm ci
npm ci --include=optional
- name: Build
run: |
cd extensions/cli
npm run build
- name: Run smoke tests
run: |
cd extensions/cli
npm run test:smoke
# e2e tests are failing on Windows specifically - likely due to stdout flush issues
- name: Run tests
if: matrix.os != 'windows-latest'

View file

@ -1,32 +0,0 @@
name: Docs Check
on:
push:
paths:
- 'docs2/**'
pull_request:
paths:
- 'docs2/**'
jobs:
check-broken-links:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: docs2/package-lock.json
- name: Install dependencies
working-directory: ./docs2
run: npm ci
- name: Check for broken links
working-directory: ./docs2
run: npx mintlify broken-links

View file

@ -189,6 +189,8 @@ jobs:
cd ../../gui
npm ci
npm run build
env:
NODE_OPTIONS: "--max-old-space-size=8192"
# Run prepackage.js script
- name: Run prepackage script

View file

@ -34,13 +34,13 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
@ -141,6 +141,17 @@ jobs:
# Update version to stable (remove beta suffix)
npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version
- name: Setup packages (for direct stable release)
if: ${{ inputs.release_type == 'direct-stable' }}
uses: ./.github/actions/setup-packages
- name: Setup core component (for direct stable release)
if: ${{ inputs.release_type == 'direct-stable' }}
uses: ./.github/actions/setup-component
with:
component: core
include-root: true
- name: Prepare package for direct stable release
if: ${{ inputs.release_type == 'direct-stable' }}
working-directory: extensions/cli

View file

@ -29,11 +29,24 @@ export function loadConfigContextProviders(
} {
const providers: IContextProvider[] = [];
const errors: ConfigValidationError[] = [];
const defaultProviders: IContextProvider[] = [
new FileContextProvider({}),
new CurrentFileContextProvider({}),
new DiffContextProvider({}),
new TerminalContextProvider({}),
new ProblemsContextProvider({}),
new RulesContextProvider({}),
];
// Add from config
if (configContext) {
for (const config of configContext) {
const cls = contextProviderClassFromName(config.provider) as any;
if (!cls) {
if (
!cls &&
!defaultProviders.find((p) => p.description.title === config.provider)
) {
errors.push({
fatal: false,
message: `Unknown context provider ${config.provider}`,
@ -50,15 +63,6 @@ export function loadConfigContextProviders(
}
// Add from defaults if not found in config
const defaultProviders: IContextProvider[] = [
new FileContextProvider({}),
new CurrentFileContextProvider({}),
new DiffContextProvider({}),
new TerminalContextProvider({}),
new ProblemsContextProvider({}),
new RulesContextProvider({}),
];
for (const defaultProvider of defaultProviders) {
if (
!providers.find(

View file

@ -37,21 +37,6 @@ class FileContextProvider extends BaseContextProvider {
await extras.ide.getWorkspaceDirs(),
);
if (isSecurityConcern(relativePathOrBasename)) {
return [
{
description: last2Parts,
content:
"Content redacted, this file cannot be viewed for security reasons",
name: baseName,
uri: {
type: "file",
value: fileUri,
},
},
];
}
return [
{
name: baseName,

View file

@ -29,14 +29,6 @@ class ProblemsContextProvider extends BaseContextProvider {
problem.filepath,
workspaceDirs,
);
if (isSecurityConcern(relativePathOrBasename)) {
return {
description: "Problems in current file",
content:
"Content was redacted because the file is detected as a potential security concern",
name: `Warnings in ${baseName}`,
};
}
const content = await ide.readFile(problem.filepath);
const lines = content.split("\n");
const rangeContent = lines

View file

@ -12,6 +12,7 @@ import DebugLocalsProvider from "./DebugLocalsProvider";
import DiffContextProvider from "./DiffContextProvider";
import DiscordContextProvider from "./DiscordContextProvider";
import DocsContextProvider from "./DocsContextProvider";
import FileContextProvider from "./FileContextProvider";
import FileTreeContextProvider from "./FileTreeContextProvider";
import FolderContextProvider from "./FolderContextProvider";
import GitCommitContextProvider from "./GitCommitContextProvider";
@ -41,6 +42,7 @@ import WebContextProvider from "./WebContextProvider";
* See this issue for details: https://github.com/continuedev/continue/issues/1365
*/
export const Providers: (typeof BaseContextProvider)[] = [
FileContextProvider,
DiffContextProvider,
FileTreeContextProvider,
GitHubIssuesContextProvider,

View file

@ -37,7 +37,7 @@ export async function retrieveContextItemsFromEmbeddings(
const nFinal =
options?.nFinal ??
Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2);
const useReranking = !!extras.reranker;
const useReranking = options?.useReranking ?? !!extras.reranker;
const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal;
const branches = (await Promise.race([

View file

@ -67,14 +67,6 @@ export const DEFAULT_SECURITY_IGNORE_DIRS = [
// Environment and configuration directories
".env/",
"env/",
".venv/",
"venv/",
// IDE directories that may contain cached credentials
// For now excluding, reasons for this unclear
// ".vscode/",
// ".idea/",
// ".vs/",
// Cloud provider credential directories
".aws/",
@ -168,6 +160,8 @@ export const ADDITIONAL_INDEXING_IGNORE_FILETYPES = [
"*.swp",
"*.jsonl",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
// Application specific
".continue/",
];
export const ADDITIONAL_INDEXING_IGNORE_DIRS = [
@ -189,6 +183,13 @@ export const ADDITIONAL_INDEXING_IGNORE_DIRS = [
".cache/",
"gems/",
"vendor/",
".venv/",
"venv/",
".vscode/",
".idea/",
".vs/",
];
// Combined patterns: security + additional

View file

@ -81,18 +81,7 @@ describe("isSecurityConcern", () => {
it("should detect environment directories as security concerns", () => {
expect(isSecurityConcern(".env/")).toBe(true);
expect(isSecurityConcern("env/")).toBe(true);
expect(isSecurityConcern(".venv/")).toBe(true);
expect(isSecurityConcern("venv/")).toBe(true);
expect(isSecurityConcern(".env/config")).toBe(true);
expect(isSecurityConcern("project/.venv/lib")).toBe(true);
});
it("should detect IDE directories as security concerns", () => {
// expect(isSecurityConcern(".vscode/")).toBe(true);
// expect(isSecurityConcern(".idea/")).toBe(true);
// expect(isSecurityConcern(".vs/")).toBe(true);
expect(isSecurityConcern(".vscode/settings.json")).toBe(true);
// expect(isSecurityConcern(".idea/workspace.xml")).toBe(true);
});
it("should detect cloud provider directories as security concerns", () => {

View file

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

View file

@ -220,7 +220,7 @@ describe("modelSupportsNextEdit", () => {
expect(
modelSupportsNextEdit(
{ nextEdit: false },
"mercury-coder-nextedit",
"mercury-coder",
"Mercury Coder",
),
).toBe(false);
@ -231,7 +231,7 @@ describe("modelSupportsNextEdit", () => {
expect(
modelSupportsNextEdit(
{ nextEdit: false },
"mercury-coder-nextedit",
"mercury-coder",
"Mercury Coder",
),
).toBe(false);
@ -239,10 +239,10 @@ describe("modelSupportsNextEdit", () => {
});
describe("when capabilities.nextEdit is undefined", () => {
it("should return true for mercury-coder-nextedit model (case insensitive)", () => {
expect(
modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined),
).toBe(true);
it("should return true for mercury-coder model (case insensitive)", () => {
expect(modelSupportsNextEdit(undefined, "Mercury-Coder", undefined)).toBe(
true,
);
});
it("should return true for instinct", () => {
@ -255,7 +255,7 @@ describe("modelSupportsNextEdit", () => {
expect(
modelSupportsNextEdit(
undefined,
"provider/mercury-coder-nextedit-v2",
"provider/mercury-coder-v2",
undefined,
),
).toBe(true);
@ -266,7 +266,7 @@ describe("modelSupportsNextEdit", () => {
modelSupportsNextEdit(
undefined,
"some-model",
"This is mercury-coder-nextedit model",
"This is mercury-coder model",
),
).toBe(true);
});
@ -312,14 +312,14 @@ describe("modelSupportsNextEdit", () => {
});
it("should handle undefined title gracefully", () => {
expect(
modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined),
).toBe(true);
expect(modelSupportsNextEdit(undefined, "mercury-coder", undefined)).toBe(
true,
);
});
it("should handle case sensitivity correctly", () => {
expect(
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
modelSupportsNextEdit(undefined, "MERCURY-CODER", "instinct"),
).toBe(true);
});

View file

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

View file

@ -46,6 +46,8 @@ export const EDIT_CODE_INSTRUCTIONS = `\
of changes unless the user specifically asks for code only.
`;
const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks (>20 lines), use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'`;
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
You are in chat mode.
@ -64,6 +66,11 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
If you need to use multiple tools, you can call multiple read only tools simultaneously.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${BRIEF_LAZY_INSTRUCTIONS}
However, only output codeblocks for suggestion and demonstration purposes, for example, when enumerating multiple hypothetical options. For implementing changes, use the edit tools.
</important_rules>`;
// The note about read-only tools is for MCP servers
@ -75,7 +82,10 @@ export const DEFAULT_PLAN_SYSTEM_MESSAGE = `\
If the user wants to make changes, offer that they can switch to Agent mode to give you access to write tools to make the suggested updates.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}
${BRIEF_LAZY_INSTRUCTIONS}
However, only output codeblocks for suggestion and planning purposes. When ready to implement changes, request to switch to Agent mode.
In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan.
</important_rules>`;

View file

@ -213,7 +213,7 @@ describe("LLM", () => {
testLLM(
new Anthropic({
model: "claude-3-5-sonnet-latest",
model: "claude-sonnet-4-0",
apiKey: process.env.ANTHROPIC_API_KEY,
}),
{ skip: false, testToolCall: true },

View file

@ -280,6 +280,34 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
});
});
describe("novita", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["novita"];
it("should return true for exact match models", () => {
expect(supportsFn("deepseek/deepseek-r1-0528")).toBe(true);
expect(supportsFn("deepseek/deepseek-r1-turbo")).toBe(true);
expect(supportsFn("deepseek/deepseek-v3-0324")).toBe(true);
expect(supportsFn("deepseek/deepseek-v3-turbo")).toBe(true);
expect(supportsFn("meta-llama/llama-3.3-70b-instruct")).toBe(true);
expect(supportsFn("qwen/qwen-2.5-72b-instruct")).toBe(true);
expect(supportsFn("zai-org/glm-4.5")).toBe(true);
expect(supportsFn("moonshotai/kimi-k2-instruct")).toBe(true);
});
it("should return true for prefix match models", () => {
expect(supportsFn("qwen/qwen3-235b-a22b-instruct-2507")).toBe(true);
expect(supportsFn("openai/gpt-oss-20b")).toBe(true);
expect(supportsFn("openai/gpt-oss-120b")).toBe(true);
});
it("should return false for unsupported models", () => {
expect(supportsFn("deepseek/deepseek-chat")).toBe(false);
expect(supportsFn("meta-llama/llama-2-7b")).toBe(false);
expect(supportsFn("qwen/qwen-2.0-7b")).toBe(false);
expect(supportsFn("openai/gpt-4")).toBe(false);
});
});
describe("openrouter", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["openrouter"];
@ -297,6 +325,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false);
expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false);
expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false);
expect(PROVIDER_TOOL_SUPPORT["novita"]("")).toBe(false);
});
it("should handle non-existent provider", () => {

View file

@ -334,6 +334,36 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return true;
}
return false;
},
novita: (model) => {
const lower = model.toLowerCase();
// Exact match models
const exactMatches = [
"deepseek/deepseek-r1-0528",
"deepseek/deepseek-r1-turbo",
"deepseek/deepseek-v3-0324",
"deepseek/deepseek-v3-turbo",
"meta-llama/llama-3.3-70b-instruct",
"qwen/qwen-2.5-72b-instruct",
"zai-org/glm-4.5",
"moonshotai/kimi-k2-instruct",
];
if (exactMatches.includes(lower)) {
return true;
}
// Prefix match models
const prefixMatches = ["qwen/qwen3", "openai/gpt-oss"];
for (const prefix of prefixMatches) {
if (lower.startsWith(prefix)) {
return true;
}
}
return false;
},
};

View file

@ -1,15 +1,6 @@
import * as path from "path";
import { v4 as uuidv4 } from "uuid";
import { ConfigHandler } from "../config/ConfigHandler.js";
import {
ChatMessage,
DiffLine,
IDE,
ILLM,
Position,
Range,
RangeInFile,
} from "../index.js";
import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
@ -18,10 +9,7 @@ import { ContextRetrievalService } from "../autocomplete/context/ContextRetrieva
import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
import {
getAllSnippetsWithoutRace,
SnippetPayload,
} from "../autocomplete/snippets/index.js";
import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
import { getAst } from "../autocomplete/util/ast.js";
@ -29,39 +17,23 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce
import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { AutocompleteInput } from "../autocomplete/util/types.js";
import { myersDiff } from "../diff/myers.js";
import { isSecurityConcern } from "../indexing/ignore.js";
import { modelSupportsNextEdit } from "../llm/autodetect.js";
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import {
INSTINCT_SYSTEM_PROMPT,
MERCURY_SYSTEM_PROMPT,
MODEL_WINDOW_SIZES,
UNIQUE_TOKEN,
} from "./constants.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import {
calculateFinalCursorPosition,
DiffGroup,
groupDiffLines,
} from "./diff/diff.js";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
import { NextEditLoggingService } from "./NextEditLoggingService.js";
import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
import {
renderDefaultSystemPrompt,
renderDefaultUserPrompt,
renderPrompt,
} from "./templating/NextEditPromptEngine.js";
import {
ModelSpecificContext,
NextEditOutcome,
Prompt,
PromptMetadata,
RecentlyEditedRange,
} from "./types.js";
import { isWhitespaceOnlyDeletion } from "./utils.js";
const autocompleteCache = AutocompleteLruCache.get();
@ -92,6 +64,9 @@ export class NextEditProvider {
private previousCompletions: NextEditOutcome[] = [];
// private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
// Model-specific provider instance.
private modelProvider: BaseNextEditProvider | null = null;
private constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
@ -298,28 +273,23 @@ export class NextEditProvider {
} = await this._initializeCompletionRequest(input, token);
if (!helper) return undefined;
// Create model-specific provider based on the model name.
this.modelProvider = NextEditProviderFactory.createProvider(
helper.modelName,
);
const { editableRegionStartLine, editableRegionEndLine, prompts } =
await this._generatePrompts(helper, opts);
if (this.endpointType === "default") {
return await this._handleDefaultEndpointCompletion(
helper,
prompts,
abortToken,
startTime,
editableRegionEndLine,
);
} else {
return await this._handleFineTunedEndpointCompletion(
helper,
prompts,
abortToken,
startTime,
editableRegionStartLine,
editableRegionEndLine,
opts,
);
}
return await this._handleCompletion(
helper,
prompts,
abortToken,
startTime,
editableRegionStartLine,
editableRegionEndLine,
opts,
);
} catch (e: any) {
this.onError(e);
} finally {
@ -335,7 +305,7 @@ export class NextEditProvider {
startTime: number;
helper: HelperVars | undefined;
}> {
// Create abort signal if not given.
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
@ -345,7 +315,7 @@ export class NextEditProvider {
const startTime = Date.now();
const options = await this._getAutocompleteOptions();
// Debounce.
// Debounce
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
return { token, startTime, helper: undefined };
}
@ -355,9 +325,7 @@ export class NextEditProvider {
return { token, startTime, helper: undefined };
}
// In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts.
// For other editors, this check should be done in their respective config reloaders.
// This is left for a final check.
// Check model capabilities
if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
console.error(`${llm.model} is not capable of next edit.`);
return { token, startTime, helper: undefined };
@ -387,6 +355,10 @@ export class NextEditProvider {
editableRegionEndLine: number;
prompts: Prompt[];
}> {
if (!this.modelProvider) {
throw new Error("Model provider not initialized");
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippetsWithoutRace({
helper,
@ -397,56 +369,118 @@ export class NextEditProvider {
this.ide.getWorkspaceDirs(),
]);
const modelName = helper.modelName.includes(
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
)
? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT
: helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)
? NEXT_EDIT_MODELS.MERCURY_CODER
: NEXT_EDIT_MODELS.INSTINCT;
// Calculate editable region based on model and options.
const { editableRegionStartLine, editableRegionEndLine } =
opts?.usingFullFileDiff
? this._calculateOptimalEditableRegion(helper, "tokenizer")
: {
editableRegionStartLine: Math.max(
helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
0,
),
editableRegionEndLine: Math.min(
helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
helper.fileLines.length - 1,
),
};
this.modelProvider.calculateEditableRegion(
helper,
opts?.usingFullFileDiff ?? false,
);
// const editableRegionStartLine = opts?.usingFullFileDiff
// ? 0
// : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0);
// Build context for model-specific prompt generation.
const context: ModelSpecificContext = {
helper,
snippetPayload,
editableRegionStartLine,
editableRegionEndLine,
diffContext: this.diffContext,
autocompleteContext: this.autocompleteContext,
historyDiff: createDiff({
beforeContent:
DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
localPathOrUriToPath(helper.filepath),
) ?? "",
afterContent: helper.fileContents,
filePath: helper.filepath,
diffType: DiffFormatType.Unified,
contextLines: 3,
}),
};
// const editableRegionEndLine = opts?.usingFullFileDiff
// ? helper.fileLines.length - 1
// : Math.min(
// helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
// helper.fileLines.length - 1,
// );
const prompts = await this.modelProvider.generatePrompts(context);
const prompts: Prompt[] = [];
this.promptMetadata = this.modelProvider.buildPromptMetadata(context);
if (this.endpointType === "default") {
prompts.push(renderDefaultSystemPrompt());
prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
return { editableRegionStartLine, editableRegionEndLine, prompts };
}
private async _handleCompletion(
helper: HelperVars,
prompts: Prompt[],
token: AbortSignal,
startTime: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
opts?: {
withChain: boolean;
usingFullFileDiff: boolean;
},
): Promise<NextEditOutcome | undefined> {
if (!this.modelProvider) {
throw new Error("Model provider not initialized");
}
const llm = await this._prepareLlm();
if (!llm) return undefined;
// Inject unique token if needed (for Mercury models).
if (this.modelProvider.shouldInjectUniqueToken()) {
const uniqueToken = this.modelProvider.getUniqueToken();
if (uniqueToken) {
const lastPrompt = prompts[prompts.length - 1];
if (lastPrompt && typeof lastPrompt.content === "string") {
lastPrompt.content += uniqueToken;
}
}
}
// Send prompts to LLM (using only user prompt for fine-tuned models).
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
stream: false,
});
if (typeof msg.content !== "string") {
return undefined;
}
// Extract completion using model-specific logic.
const nextCompletion = this.modelProvider.extractCompletion(msg.content);
let outcome: NextEditOutcome | undefined;
// Handle based on diff type.
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
outcome = await this.modelProvider.handlePartialFileDiff(
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
this.promptMetadata!,
this.ide,
);
} else {
prompts.push(
...(await this._generateFineTunedPrompts(
helper,
snippetPayload,
editableRegionStartLine,
editableRegionEndLine,
)),
outcome = await this.modelProvider.handleFullFileDiff(
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
this.promptMetadata!,
this.ide,
);
}
return { editableRegionStartLine, editableRegionEndLine, prompts };
if (outcome) {
// Handle NextEditProvider-specific state
this.previousCompletions.push(outcome);
// Mark as displayed for JetBrains
await this._markDisplayedIfJetBrains(helper.input.completionId, outcome);
}
return outcome;
}
private _calculateOptimalEditableRegion(
@ -540,500 +574,6 @@ export class NextEditProvider {
};
}
private async _generateFineTunedPrompts(
helper: HelperVars,
snippetPayload: SnippetPayload,
editableRegionStartLine: number,
editableRegionEndLine: number,
): Promise<Prompt[]> {
const historyDiff = createDiff({
beforeContent:
DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
localPathOrUriToPath(helper.filepath),
) ?? "",
afterContent: helper.fileContents,
filePath: helper.filepath,
diffType: DiffFormatType.Unified,
contextLines: 3,
});
const modelName = helper.modelName;
let ctx: any;
if (
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
) {
ctx = {
recentlyViewedCodeSnippets:
snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
filepath: snip.filepath,
content: snip.content,
})) ?? [],
currentFileContent: helper.fileContents,
editableRegionStartLine,
editableRegionEndLine,
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
};
} else if (modelName.includes(NEXT_EDIT_MODELS.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(
helper.fileLines.length - 1,
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 - 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,
editableRegionStartLine,
);
const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
ctx = {
contextSnippets: this.autocompleteContext,
currentFileContent: helper.fileContents,
windowStart,
windowEnd,
editableRegionStartLine: adjustedEditableStart,
editableRegionEndLine: adjustedEditableEnd,
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
languageShorthand: helper.lang.name,
};
} else {
ctx = {};
}
const promptMetadata = await renderPrompt(helper, ctx);
this.promptMetadata = promptMetadata;
const systemPrompt: Prompt = {
role: "system",
content:
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
? MERCURY_SYSTEM_PROMPT
: INSTINCT_SYSTEM_PROMPT,
};
return [systemPrompt, promptMetadata.prompt];
}
private async _handleDefaultEndpointCompletion(
helper: HelperVars,
prompts: Prompt[],
token: AbortSignal,
startTime: number,
editableRegionEndLine: number,
): Promise<NextEditOutcome | undefined> {
const llm = await this._prepareLlm();
if (!llm) return undefined;
const msg: ChatMessage = await llm.chat(prompts, token);
if (typeof msg.content === "string") {
const nextCompletion = JSON.parse(msg.content).newCode;
const finalCursorPos: Position = {
line: editableRegionEndLine,
character: 0,
};
const outcomeNext = await this._createNextEditOutcome({
helper,
startTime,
llm,
promptContent: prompts.join("\n"),
completion: nextCompletion,
finalCursorPosition: finalCursorPos,
editableRegionStartLine: 0,
editableRegionEndLine: 0,
userEdits: "",
userExcerpts: "",
originalEditableRange: "",
diffLines: [],
});
// Mark as displayed for JetBrains extension
await this._markDisplayedIfJetBrains(
helper.input.completionId,
outcomeNext,
);
return outcomeNext;
}
return undefined;
}
private async _handleFineTunedEndpointCompletion(
helper: HelperVars,
prompts: Prompt[],
token: AbortSignal,
startTime: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
opts?: {
withChain: boolean;
usingFullFileDiff: boolean;
},
): Promise<NextEditOutcome | undefined> {
const llm = await this._prepareLlm();
if (!llm) return undefined;
// Check for mercury models, and inject unique token for next edit.
// Capture the unique tokens in llm Inception.ts and apis Inception.ts
const modelName = helper.modelName;
if (
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
) {
// Inject the unique token to the last prompt's content.
const lastPrompt = prompts[prompts.length - 1];
if (lastPrompt && typeof lastPrompt.content === "string") {
lastPrompt.content += UNIQUE_TOKEN;
}
}
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
stream: false,
});
if (typeof msg.content !== "string") {
return undefined;
}
// NOTE: Keep this in case there is a change in spec.
// const nextCompletion =
// msg.content
// .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
// .replace(/\n$/, "") ?? msg.content;
const nextCompletion = msg.content.slice(
msg.content.indexOf("```\n") + "'''\n".length,
msg.content.lastIndexOf("\n\n```"),
);
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
return await this._handlePartialFileDiff(
// we could use fillFileDiff
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
);
} else {
return await this._handleFullFileDiff(
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
);
}
}
private async _handlePartialFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
): Promise<NextEditOutcome | undefined> {
const oldEditRangeSlice = helper.fileContents
.split("\n")
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const finalCursorPos = calculateFinalCursorPosition(
helper.pos,
editableRegionStartLine,
oldEditRangeSlice,
nextCompletion,
);
const outcomeNext = await this._createNextEditOutcome({
helper,
startTime,
llm,
promptContent: this.promptMetadata!.prompt.content,
completion: nextCompletion,
finalCursorPosition: finalCursorPos,
editableRegionStartLine,
editableRegionEndLine,
userEdits: this.promptMetadata!.userEdits,
userExcerpts: this.promptMetadata!.userExcerpts,
originalEditableRange: oldEditRangeSlice,
diffLines: [],
});
this.previousCompletions.push(outcomeNext);
// Mark as displayed for JetBrains extension
await this._markDisplayedIfJetBrains(
helper.input.completionId,
outcomeNext,
);
return outcomeNext;
}
private async _handleFullFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
): Promise<NextEditOutcome | undefined> {
const fileSlice = helper.fileLines
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const diffLines = myersDiff(fileSlice, nextCompletion);
const diffGroups = groupDiffLines(
diffLines,
editableRegionStartLine,
5,
).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
const currentLine = helper.pos.line;
const prefetchQueue = PrefetchQueue.getInstance();
// Process diff groups and find the one containing the cursor
const cursorLocalDiffGroup = await this._processDiffGroups(
diffGroups,
currentLine,
helper,
startTime,
llm,
prefetchQueue,
);
// Handle the diff group containing the cursor if found
if (cursorLocalDiffGroup) {
return await this._createOutcomeFromDiffGroup(
cursorLocalDiffGroup,
helper,
startTime,
llm,
helper.input.completionId,
true,
);
// } else if (diffGroups.length > 0) {
// // Fallback to first diff group if cursor's group not found
// return await this._createOutcomeFromDiffGroup(
// diffGroups[0],
// helper,
// startTime,
// llm,
// helper.input.completionId,
// false,
// );
}
return undefined;
}
private async _processDiffGroups(
diffGroups: DiffGroup[],
currentLine: number,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
): Promise<DiffGroup | undefined> {
let cursorGroup: DiffGroup | undefined;
console.log("diffGroups:");
console.log(diffGroups);
for (const group of diffGroups) {
if (currentLine >= group.startLine && currentLine <= group.endLine) {
cursorGroup = group;
} else {
// Add non-cursor groups to prefetch queue
await this._addDiffGroupToPrefetchQueue(
group,
helper,
startTime,
llm,
prefetchQueue,
);
}
}
return cursorGroup;
}
private async _addDiffGroupToPrefetchQueue(
group: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
): Promise<void> {
const groupContent = group.lines
.filter((l) => l.type !== "old")
.map((l) => l.line)
.join("\n");
// Create a range for this diff group
const rangeInFile: RangeInFile = {
filepath: helper.filepath,
range: {
start: { line: group.startLine, character: 0 },
end: {
line: group.endLine,
character: group.lines[group.lines.length - 1].line.length,
},
},
};
const originalContent = group.lines
.filter((l) => l.type !== "new")
.map((l) => l.line)
.join("\n");
// Build outcome for this diff group
const groupOutcome = await this._createNextEditOutcome({
helper,
startTime,
llm,
promptContent: this.promptMetadata!.prompt.content,
completion: groupContent,
finalCursorPosition: {
line: group.endLine,
character: group.lines[group.lines.length - 1].line.length,
},
editableRegionStartLine: group.startLine,
editableRegionEndLine: group.endLine,
userEdits: this.promptMetadata!.userEdits,
userExcerpts: this.promptMetadata!.userExcerpts,
originalEditableRange: originalContent,
cursorPosition: { line: group.startLine, character: 0 },
completionId: uuidv4(), // Generate a new ID for this prefetched item
diffLines: group.lines,
});
// Add to prefetch queue
prefetchQueue.enqueueProcessed({
location: rangeInFile,
outcome: groupOutcome,
});
}
private async _createOutcomeFromDiffGroup(
diffGroup: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
completionId: string,
isCurrentCursorGroup: boolean,
): Promise<NextEditOutcome> {
const groupContent = diffGroup.lines
.filter((l) => l.type !== "old")
.map((line) => line.line)
.join("\n");
const originalContent = diffGroup.lines
.filter((l) => l.type !== "new")
.map((l) => l.line)
.join("\n");
// Use the actual cursor position if this is the group containing the cursor
// Otherwise use the start of the diff group
const cursorPos = isCurrentCursorGroup
? helper.pos
: { line: diffGroup.startLine, character: 0 };
const finalCursorPos = calculateFinalCursorPosition(
cursorPos,
diffGroup.startLine,
originalContent,
groupContent,
);
const outcomeNext = await this._createNextEditOutcome({
helper,
startTime,
llm,
promptContent: this.promptMetadata!.prompt.content,
completion: groupContent,
finalCursorPosition: finalCursorPos,
editableRegionStartLine: diffGroup.startLine,
editableRegionEndLine: diffGroup.endLine,
userEdits: this.promptMetadata!.userEdits,
userExcerpts: this.promptMetadata!.userExcerpts,
originalEditableRange: originalContent,
cursorPosition: cursorPos,
completionId,
diffLines: diffGroup.lines,
});
this.previousCompletions.push(outcomeNext);
// Mark as displayed for JetBrains
await this._markDisplayedIfJetBrains(completionId, outcomeNext);
return outcomeNext;
}
private async _createNextEditOutcome(outcomeCtx: {
helper: HelperVars;
startTime: number;
llm: ILLM;
promptContent: string;
completion: string;
finalCursorPosition: Position;
editableRegionStartLine: number;
editableRegionEndLine: number;
userEdits: string;
userExcerpts: string;
originalEditableRange: string;
cursorPosition?: Position;
completionId?: string;
diffLines: DiffLine[];
}): Promise<NextEditOutcome> {
return {
elapsed: Date.now() - outcomeCtx.startTime,
modelProvider: outcomeCtx.llm.underlyingProviderName,
modelName: outcomeCtx.llm.model + ":zetaDataset",
completionOptions: null,
completionId:
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
fileUri: outcomeCtx.helper.filepath,
workspaceDirUri:
outcomeCtx.helper.workspaceUris[0] ??
path.dirname(outcomeCtx.helper.filepath),
prompt: outcomeCtx.promptContent,
userEdits: outcomeCtx.userEdits ?? "",
userExcerpts: outcomeCtx.userExcerpts ?? "",
originalEditableRange: outcomeCtx.originalEditableRange ?? "",
completion: outcomeCtx.completion,
cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
finalCursorPosition: outcomeCtx.finalCursorPosition,
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
diffLines: outcomeCtx.diffLines,
...outcomeCtx.helper.options,
};
}
private async _markDisplayedIfJetBrains(
completionId: string,
outcome: NextEditOutcome,

View file

@ -0,0 +1,16 @@
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
import { InstinctProvider } from "./providers/InstinctNextEditProvider.js";
import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js";
export class NextEditProviderFactory {
static createProvider(modelName: string): BaseNextEditProvider {
if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) {
return new MercuryCoderProvider();
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
return new InstinctProvider();
} else {
throw new Error(`Unsupported model: ${modelName}`);
}
}
}

View file

@ -12,10 +12,6 @@ export const MODEL_WINDOW_SIZES: Record<
topMargin: 0,
bottomMargin: 5,
}, // mercury coder uses full file diff, so this should be unnecessary
"mercury-coder-nextedit": {
topMargin: 0,
bottomMargin: 5,
}, // mercury coder nextedit uses full file diff, so this should be unnecessary
instinct: { topMargin: 1, bottomMargin: 5 },
};

View file

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

View file

@ -0,0 +1,155 @@
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
import { INSTINCT_SYSTEM_PROMPT } from "../constants.js";
import {
contextSnippetsBlock,
currentFileContentBlock,
editHistoryBlock,
} from "../templating/instinct.js";
import {
NEXT_EDIT_MODEL_TEMPLATES,
PromptTemplateRenderer,
} from "../templating/NextEditPromptEngine.js";
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
export class InstinctProvider extends BaseNextEditProvider {
private templateRenderer: PromptTemplateRenderer;
constructor() {
super(NEXT_EDIT_MODELS.INSTINCT);
const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT];
this.templateRenderer = new PromptTemplateRenderer(template.template);
}
getSystemPrompt(): string {
return INSTINCT_SYSTEM_PROMPT;
}
getWindowSize() {
return { topMargin: 1, bottomMargin: 5 };
}
shouldInjectUniqueToken(): boolean {
return false; // Instinct doesn't use unique tokens.
}
extractCompletion(message: string): string {
return message; // Instinct returns the completion directly.
}
buildPromptContext(context: ModelSpecificContext): any {
// Calculate the window around the cursor position (25 lines above and below).
const windowStart = Math.max(0, context.helper.pos.line - 25);
const windowEnd = Math.min(
context.helper.fileLines.length - 1,
context.helper.pos.line + 25,
);
// Ensure editable region boundaries are within the window.
const adjustedEditableStart = Math.max(
windowStart,
context.editableRegionStartLine,
);
const adjustedEditableEnd = Math.min(
windowEnd,
context.editableRegionEndLine,
);
return {
contextSnippets: context.autocompleteContext,
currentFileContent: context.helper.fileContents,
windowStart,
windowEnd,
editableRegionStartLine: adjustedEditableStart,
editableRegionEndLine: adjustedEditableEnd,
editDiffHistory: context.diffContext,
currentFilePath: context.helper.filepath,
languageShorthand: context.helper.lang.name,
};
}
async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> {
const promptCtx = this.buildPromptContext(context);
const templateVars = {
contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets),
currentFileContent: currentFileContentBlock(
promptCtx.currentFileContent,
promptCtx.windowStart,
promptCtx.windowEnd,
promptCtx.editableRegionStartLine,
promptCtx.editableRegionEndLine,
context.helper.pos,
),
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
currentFilePath: promptCtx.currentFilePath,
languageShorthand: promptCtx.languageShorthand,
};
const userPromptContent = this.templateRenderer.render(templateVars);
return [
{
role: "system",
content: this.getSystemPrompt(),
},
{
role: "user",
content: userPromptContent,
},
];
}
buildPromptMetadata(context: ModelSpecificContext): PromptMetadata {
const promptCtx = this.buildPromptContext(context);
const templateVars = {
contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets),
currentFileContent: currentFileContentBlock(
promptCtx.currentFileContent,
promptCtx.windowStart,
promptCtx.windowEnd,
promptCtx.editableRegionStartLine,
promptCtx.editableRegionEndLine,
context.helper.pos,
),
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
currentFilePath: promptCtx.currentFilePath,
languageShorthand: promptCtx.languageShorthand,
};
const userPromptContent = this.templateRenderer.render(templateVars);
return {
prompt: {
role: "user",
content: userPromptContent,
},
userEdits: promptCtx.editDiffHistory.join("\n"),
userExcerpts: templateVars.currentFileContent,
};
}
calculateEditableRegion(
helper: HelperVars,
usingFullFileDiff: boolean,
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
} {
if (usingFullFileDiff) {
return this.calculateOptimalEditableRegion(helper, 512, "tokenizer");
} else {
const { topMargin, bottomMargin } = this.getWindowSize();
return {
editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0),
editableRegionEndLine: Math.min(
helper.pos.line + bottomMargin,
helper.fileLines.length - 1,
),
};
}
}
}

View file

@ -0,0 +1,145 @@
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
import { MERCURY_SYSTEM_PROMPT, UNIQUE_TOKEN } from "../constants.js";
import {
currentFileContentBlock,
editHistoryBlock,
recentlyViewedCodeSnippetsBlock,
} from "../templating/mercuryCoderNextEdit.js";
import {
NEXT_EDIT_MODEL_TEMPLATES,
PromptTemplateRenderer,
} from "../templating/NextEditPromptEngine.js";
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
export class MercuryCoderProvider extends BaseNextEditProvider {
private templateRenderer: PromptTemplateRenderer;
constructor() {
super(NEXT_EDIT_MODELS.MERCURY_CODER);
const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER];
this.templateRenderer = new PromptTemplateRenderer(template.template);
}
getSystemPrompt(): string {
return MERCURY_SYSTEM_PROMPT;
}
getWindowSize() {
return { topMargin: 0, bottomMargin: 5 };
}
shouldInjectUniqueToken(): boolean {
return true;
}
getUniqueToken(): string {
return UNIQUE_TOKEN;
}
extractCompletion(message: string): string {
// Extract the code between the markdown code blocks.
return message.slice(
message.indexOf("```\n") + "```\n".length,
message.lastIndexOf("\n\n```"),
);
}
buildPromptContext(context: ModelSpecificContext): any {
return {
recentlyViewedCodeSnippets:
context.snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
filepath: snip.filepath,
content: snip.content,
})) ?? [],
currentFileContent: context.helper.fileContents,
editableRegionStartLine: context.editableRegionStartLine,
editableRegionEndLine: context.editableRegionEndLine,
editDiffHistory: context.diffContext,
currentFilePath: context.helper.filepath,
};
}
async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> {
const promptCtx = this.buildPromptContext(context);
const templateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
promptCtx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
promptCtx.currentFileContent,
promptCtx.editableRegionStartLine,
promptCtx.editableRegionEndLine,
context.helper.pos,
),
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
currentFilePath: promptCtx.currentFilePath,
};
const userPromptContent = this.templateRenderer.render(templateVars);
return [
{
role: "system",
content: this.getSystemPrompt(),
},
{
role: "user",
content: userPromptContent,
},
];
}
buildPromptMetadata(context: ModelSpecificContext): PromptMetadata {
const promptCtx = this.buildPromptContext(context);
const templateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
promptCtx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
promptCtx.currentFileContent,
promptCtx.editableRegionStartLine,
promptCtx.editableRegionEndLine,
context.helper.pos,
),
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
currentFilePath: promptCtx.currentFilePath,
};
const userPromptContent = this.templateRenderer.render(templateVars);
return {
prompt: {
role: "user",
content: userPromptContent,
},
userEdits: promptCtx.editDiffHistory.join("\n"),
userExcerpts: templateVars.currentFileContent,
};
}
calculateEditableRegion(
helper: HelperVars,
usingFullFileDiff: boolean,
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
} {
if (usingFullFileDiff) {
return this.calculateOptimalEditableRegion(helper, 512, "tokenizer");
} else {
const { topMargin, bottomMargin } = this.getWindowSize();
return {
editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0),
editableRegionEndLine: Math.min(
helper.pos.line + bottomMargin,
helper.fileLines.length - 1,
),
};
}
}
}

View file

@ -1,7 +1,4 @@
import Handlebars from "handlebars";
import { Position } from "../..";
import { SnippetPayload } from "../../autocomplete/snippets";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_PROMPT_PREFIX,
@ -12,274 +9,39 @@ import {
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
} from "../constants";
import {
InstinctTemplateVars,
MercuryTemplateVars,
NextEditTemplate,
PromptMetadata,
SystemPrompt,
TemplateVars,
UserPrompt,
} from "../types";
import {
contextSnippetsBlock,
currentFileContentBlock as instinctCurrentFileContentBlock,
editHistoryBlock as instinctEditHistoryBlock,
} from "./instinct";
import {
currentFileContentBlock,
editHistoryBlock,
recentlyViewedCodeSnippetsBlock,
} from "./mercuryCoderNextEdit";
import {
insertCursorToken,
insertEditableRegionTokensWithStaticRange,
} from "./utils";
import { NextEditTemplate, TemplateVars } from "../types";
type TemplateRenderer = (vars: TemplateVars) => string;
const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
// Keep the template registry
export const NEXT_EDIT_MODEL_TEMPLATES: Record<
NEXT_EDIT_MODELS,
NextEditTemplate
> = {
"mercury-coder": {
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`,
},
"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`,
},
instinct: {
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
},
};
function templateRendererOfModel(
modelName: NEXT_EDIT_MODELS,
): TemplateRenderer {
let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
// Export a utility for providers to use
export class PromptTemplateRenderer {
private compiledTemplate: HandlebarsTemplateDelegate;
constructor(template: string) {
this.compiledTemplate = Handlebars.compile(template);
}
render(vars: TemplateVars): string {
return this.compiledTemplate(vars);
}
}
// Keep for backward compatibility or remove if not needed
export function getTemplateForModel(modelName: NEXT_EDIT_MODELS): string {
const template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
if (!template) {
throw new Error(`Model ${modelName} is not supported for next edit.`);
}
const compiledTemplate = Handlebars.compile(template.template);
return (vars: TemplateVars): string => {
return compiledTemplate(vars);
};
}
export async function renderPrompt(
helper: HelperVars,
ctx: any,
): Promise<PromptMetadata> {
let modelName = helper.modelName as NEXT_EDIT_MODELS;
// Validate that the modelName is actually a supported model.
if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
// Check if modelName includes any known model name as substring.
const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) =>
modelName.includes(key),
);
if (matchingModel) {
modelName = matchingModel as NEXT_EDIT_MODELS;
} else {
throw new Error(
`${helper.modelName} is not yet supported for next edit.`,
);
}
}
const renderer = templateRendererOfModel(modelName);
let userEdits = "";
let editedCodeWithTokens = "";
let tv: TemplateVars;
switch (modelName) {
case NEXT_EDIT_MODELS.MERCURY_CODER: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// MERCURY_CURSOR,
// );
const mercuryCtx: MercuryTemplateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
ctx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
ctx.currentFileContent,
ctx.editableRegionStartLine,
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
};
tv = mercuryCtx;
editedCodeWithTokens = mercuryCtx.currentFileContent;
break;
}
case NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// MERCURY_CURSOR,
// );
const mercuryCtx: MercuryTemplateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
ctx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
ctx.currentFileContent,
ctx.editableRegionStartLine,
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
};
tv = mercuryCtx;
editedCodeWithTokens = mercuryCtx.currentFileContent;
break;
}
case NEXT_EDIT_MODELS.INSTINCT: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
// );
const instinctCtx: InstinctTemplateVars = {
contextSnippets: contextSnippetsBlock(ctx.contextSnippets),
currentFileContent: instinctCurrentFileContentBlock(
ctx.currentFileContent,
ctx.windowStart,
ctx.windowEnd,
ctx.editableRegionStartLine,
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
languageShorthand: ctx.languageShorthand,
};
tv = instinctCtx;
editedCodeWithTokens = instinctCtx.currentFileContent;
break;
}
default:
tv = {};
break;
}
return {
prompt: {
role: "user",
content: renderer(tv),
},
userEdits,
userExcerpts: editedCodeWithTokens,
};
}
export function renderDefaultSystemPrompt(): SystemPrompt {
return {
role: "system",
content: [
/* Identity forming */
"You are an expert polyglot developer who is overseeing a junior developer write code in some language.",
"You are psychic as well, so you are an expert at reading minds just from what the junior has done.",
"As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.",
/* Action crash course */
"An action is a change in code state that preserves the well-formedness of the code.",
"Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.",
/* Input description */
// 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.',
// "language is the language the code is written in.",
// "originalCode is the code state before the junior has taken some edit action.",
// "editedCode is the code state after the junior has taken some edit action.",
// "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.",
// "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.",
'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.',
"rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.",
"recentlyEditedRange is the code that the junior has recently edited.",
"Do not guess what previous edit the junior has taken right before the request -- this is already given to you.",
"The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.",
"The junior might want to add new code, delete existing code, or replace different parts of code.",
"The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.",
/* Output description */
'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.',
/* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/
/* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */
"actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.",
// "actionType is the type of action the junior has taken.",
"newCode is what the full code looks like after applying your nextEditContent.",
// "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.",
"Given the above definition of an action, you should prioritize fixing the following:",
"- Patterns and repetition in code.",
"- Static errors that the compiler of the language may return.",
"- The junior's code style.",
"If the junior has deleted some code, there's a good chance that the next edit will also be deletions.",
"If the junior has added some code, there's a good chance that the next edit will also be additions.",
"If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.",
"Careful of language intricacies.",
// "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.",
"Do not reply in markdown.",
"Do not hallucinate.",
].join(" "),
};
}
export function renderDefaultUserPrompt(
// originalCode: string,
// editedCode: string,
snippets: SnippetPayload,
helper: HelperVars,
): UserPrompt {
const userEdit = {
language: helper.lang,
rootPathSnippets: snippets.rootPathSnippets,
importDefinitionSnippets: snippets.importDefinitionSnippets,
ideSnippets: snippets.ideSnippets,
recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets,
diffSnippets: snippets.diffSnippets,
clipboardSnippets: snippets.clipboardSnippets,
recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets,
};
return {
role: "user",
content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`,
};
}
function insertTokens(
lines: string[],
cursorPos: Position,
cursorToken: string,
editableRegionStart?: number,
editableRegionEnd?: number,
) {
const a = insertCursorToken(lines, cursorPos, cursorToken);
const b = insertEditableRegionTokensWithStaticRange(
a,
cursorPos,
editableRegionStart,
editableRegionEnd,
);
return b.join("\n");
return template.template;
}

View file

@ -1,243 +1,112 @@
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 { describe, expect, it } from "vitest";
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,
MERCURY_EDIT_DIFF_HISTORY_CLOSE,
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
} from "../constants";
import {
renderDefaultSystemPrompt,
renderDefaultUserPrompt,
renderPrompt,
NEXT_EDIT_MODEL_TEMPLATES,
PromptTemplateRenderer,
getTemplateForModel,
} from "./NextEditPromptEngine";
describe("NextEditPromptEngine", () => {
describe("renderPrompt", () => {
let mercuryHelper: HelperVars;
let instinctHelper: HelperVars;
let testHelper: HelperVars;
let unsupportedHelper: HelperVars;
let ctx: any;
beforeEach(() => {
mercuryHelper = {
modelName: "inception/mercury-coder" 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" },
} as HelperVars;
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" },
} as HelperVars;
unsupportedHelper = {
modelName: "mistral/codestral" 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" },
} 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 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(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE);
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
expect(result.userEdits).toBe(ctx.editDiffHistory);
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
});
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: instinctHelper.fileContents,
windowStart: 0, // Math.max(0, helper.pos.line - 25)
windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25)
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(instinctHelper, instinctCtx);
console.log(result);
expect(result).toHaveProperty("prompt");
expect(result.prompt.role).toBe("user");
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 Excerpt:");
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 () => {
await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow(
"mistral/codestral is not yet supported for next edit.",
describe("NEXT_EDIT_MODEL_TEMPLATES", () => {
it("should contain templates for all supported models", () => {
expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty(
NEXT_EDIT_MODELS.MERCURY_CODER,
);
expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty(
NEXT_EDIT_MODELS.INSTINCT,
);
});
});
describe("renderDefaultSystemPrompt", () => {
it("should return a system prompt with expected role and content", () => {
const result = renderDefaultSystemPrompt();
it("mercury-coder template should contain expected tokens", () => {
const template =
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template;
expect(result.role).toBe("system");
expect(result.content).toContain("You are an expert polyglot developer");
expect(result.content).toContain("Do not hallucinate.");
expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
expect(template).toContain("{{{recentlyViewedCodeSnippets}}}");
expect(template).toContain("{{{currentFileContent}}}");
expect(template).toContain("{{{editDiffHistory}}}");
});
it("instinct template should contain expected tokens", () => {
const template =
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT].template;
expect(template).toContain(INSTINCT_USER_PROMPT_PREFIX);
expect(template).toContain("### Context:");
expect(template).toContain("### User Edits:");
expect(template).toContain("### User Excerpt:");
expect(template).toContain("{{{contextSnippets}}}");
expect(template).toContain("{{{currentFileContent}}}");
expect(template).toContain("{{{editDiffHistory}}}");
expect(template).toContain("{{{currentFilePath}}}");
});
});
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",
},
],
};
describe("PromptTemplateRenderer", () => {
it("should render a template with provided variables", () => {
const template = "Hello {{{name}}}, you have {{{count}}} messages";
const renderer = new PromptTemplateRenderer(template);
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 NEXT_EDIT_MODELS,
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(MERCURY_CURSOR);
const result = renderer.render({
name: "Alice",
count: "5",
});
expect(result).toBe("Hello Alice, you have 5 messages");
});
it("should handle missing variables gracefully", () => {
const template = "Hello {{{name}}}";
const renderer = new PromptTemplateRenderer(template);
const result = renderer.render({});
expect(result).toBe("Hello ");
});
it("should render complex templates correctly", () => {
const template =
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template;
const renderer = new PromptTemplateRenderer(template);
const result = renderer.render({
recentlyViewedCodeSnippets: "snippet1",
currentFileContent: "file content",
editDiffHistory: "diff history",
});
expect(result).toContain("snippet1");
expect(result).toContain("file content");
expect(result).toContain("diff history");
});
});
describe("getTemplateForModel", () => {
it("should return the correct template for a supported model", () => {
const template = getTemplateForModel(NEXT_EDIT_MODELS.MERCURY_CODER);
expect(template).toBe(
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template,
);
});
it("should throw an error for an unsupported model", () => {
expect(() =>
getTemplateForModel("unsupported" as NEXT_EDIT_MODELS),
).toThrow("Model unsupported is not supported for next edit.");
});
});
});

View file

@ -5,7 +5,9 @@ import {
RangeInFile,
TabAutocompleteOptions,
} from "../";
import { SnippetPayload } from "../autocomplete/snippets";
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
import { HelperVars } from "../autocomplete/util/HelperVars";
export type RecentlyEditedRange = RangeInFile & {
timestamp: number;
@ -104,3 +106,36 @@ export interface MercuryTemplateVars extends TemplateVars {
editDiffHistory: string; // could be a singe large unified diff
currentFilePath: string;
}
/**
* Context object containing all necessary information for model-specific operations.
*/
export interface ModelSpecificContext {
helper: HelperVars;
snippetPayload: SnippetPayload;
editableRegionStartLine: number;
editableRegionEndLine: number;
diffContext: string[];
autocompleteContext: string;
historyDiff?: string;
workspaceDirs?: string[];
}
/**
* Configuration for editable region calculation.
*/
export interface EditableRegionConfig {
usingFullFileDiff?: boolean;
maxTokens?: number;
topMargin?: number;
bottomMargin?: number;
}
/**
* Configuration for prompt generation.
*/
export interface PromptConfig {
includeHistory?: boolean;
includeRecentEdits?: boolean;
maxContextSnippets?: number;
}

View file

@ -1,4 +1,5 @@
import { DiffLine } from "..";
import { NEXT_EDIT_MODELS } from "../llm/constants";
export function isNextEditTest(): boolean {
const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
@ -21,3 +22,11 @@ export function isWhitespaceOnlyDeletion(diffLines: DiffLine[]): boolean {
(diff.line.trim() === "" || /^\s+$/.test(diff.line)),
);
}
export function convertNextEditModelNameToEnum(
modelName: string,
): NEXT_EDIT_MODELS | undefined {
const nextEditModels = Object.values(NEXT_EDIT_MODELS);
return nextEditModels.find((model) => modelName.includes(model));
}

View file

@ -1,6 +1,11 @@
import { describe, expect, test, vi } from "vitest";
import { DiffLine } from "..";
import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils";
import { NEXT_EDIT_MODELS } from "../llm/constants";
import {
convertNextEditModelNameToEnum,
isNextEditTest,
isWhitespaceOnlyDeletion,
} from "./utils";
describe("isNextEditTest", () => {
test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => {
@ -57,3 +62,35 @@ describe("isWhitespaceOnlyDeletion", () => {
expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
});
});
describe("convertNextEditModelNameToEnum", () => {
test("returns correct enum for exact matches", () => {
Object.values(NEXT_EDIT_MODELS).forEach((model) => {
expect(convertNextEditModelNameToEnum(model)).toBe(model);
});
});
test("returns correct enum when model name is contained in a longer string", () => {
expect(convertNextEditModelNameToEnum("inception/mercury-coder")).toBe(
NEXT_EDIT_MODELS.MERCURY_CODER,
);
expect(convertNextEditModelNameToEnum("blah/instinct")).toBe(
NEXT_EDIT_MODELS.INSTINCT,
);
});
test("returns undefined for non-matching model names", () => {
expect(convertNextEditModelNameToEnum("unknown-model")).toBeUndefined();
expect(convertNextEditModelNameToEnum("random-string")).toBeUndefined();
expect(convertNextEditModelNameToEnum("")).toBeUndefined();
});
test("returns first match when multiple models could match", () => {
const modelName = "model-that-contains-multiple-matches";
const result = convertNextEditModelNameToEnum(modelName);
if (result !== undefined) {
expect(Object.values(NEXT_EDIT_MODELS)).toContain(result);
}
});
});

337
core/package-lock.json generated
View file

@ -25,7 +25,6 @@
"@sentry/esbuild-plugin": "^4.0.2",
"@sentry/node": "^9.43.0",
"@sentry/vite-plugin": "^4.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
@ -105,6 +104,8 @@
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"@typescript-eslint/eslint-plugin": "^8.40.0",
"@typescript-eslint/parser": "^8.40.0",
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
@ -227,6 +228,7 @@
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.14",
"@types/json-schema": "^7.0.15",
"@types/node": "^24.3.0",
"cross-env": "^7.0.3",
"semantic-release": "^24.2.7",
"ts-jest": "^29.2.3",
@ -3388,9 +3390,10 @@
}
},
"node_modules/@eslint-community/eslint-utils": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz",
"integrity": "sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==",
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz",
"integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==",
"license": "MIT",
"dependencies": {
"eslint-visitor-keys": "^3.4.3"
},
@ -6984,122 +6987,150 @@
}
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.18.0.tgz",
"integrity": "sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==",
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.40.0.tgz",
"integrity": "sha512-w/EboPlBwnmOBtRbiOvzjD+wdiZdgFeo17lkltrtn7X37vagKKWJABvyfsJXTlHe6XBzugmYgd4A4nW+k8Mixw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/regexpp": "^4.10.0",
"@typescript-eslint/scope-manager": "7.18.0",
"@typescript-eslint/type-utils": "7.18.0",
"@typescript-eslint/utils": "7.18.0",
"@typescript-eslint/visitor-keys": "7.18.0",
"@typescript-eslint/scope-manager": "8.40.0",
"@typescript-eslint/type-utils": "8.40.0",
"@typescript-eslint/utils": "8.40.0",
"@typescript-eslint/visitor-keys": "8.40.0",
"graphemer": "^1.4.0",
"ignore": "^5.3.1",
"ignore": "^7.0.0",
"natural-compare": "^1.4.0",
"ts-api-utils": "^1.3.0"
"ts-api-utils": "^2.1.0"
},
"engines": {
"node": "^18.18.0 || >=20.0.0"
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"@typescript-eslint/parser": "^7.0.0",
"eslint": "^8.56.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
"license": "MIT",
"engines": {
"node": ">= 4"
"@typescript-eslint/parser": "^8.40.0",
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/parser": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.18.0.tgz",
"integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==",
"peer": true,
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.40.0.tgz",
"integrity": "sha512-jCNyAuXx8dr5KJMkecGmZ8KI61KBUhkCob+SD+C+I5+Y1FWI2Y3QmY4/cxMCC5WAsZqoEtEETVhUiUMIGCf6Bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/scope-manager": "7.18.0",
"@typescript-eslint/types": "7.18.0",
"@typescript-eslint/typescript-estree": "7.18.0",
"@typescript-eslint/visitor-keys": "7.18.0",
"@typescript-eslint/scope-manager": "8.40.0",
"@typescript-eslint/types": "8.40.0",
"@typescript-eslint/typescript-estree": "8.40.0",
"@typescript-eslint/visitor-keys": "8.40.0",
"debug": "^4.3.4"
},
"engines": {
"node": "^18.18.0 || >=20.0.0"
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.56.0"
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/project-service": {
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.40.0.tgz",
"integrity": "sha512-/A89vz7Wf5DEXsGVvcGdYKbVM9F7DyFXj52lNYUDS1L9yJfqjW/fIp5PgMuEJL/KeqVTe2QSbXAGUZljDUpArw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/tsconfig-utils": "^8.40.0",
"@typescript-eslint/types": "^8.40.0",
"debug": "^4.3.4"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/scope-manager": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.18.0.tgz",
"integrity": "sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==",
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.40.0.tgz",
"integrity": "sha512-y9ObStCcdCiZKzwqsE8CcpyuVMwRouJbbSrNuThDpv16dFAj429IkM6LNb1dZ2m7hK5fHyzNcErZf7CEeKXR4w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "7.18.0",
"@typescript-eslint/visitor-keys": "7.18.0"
"@typescript-eslint/types": "8.40.0",
"@typescript-eslint/visitor-keys": "8.40.0"
},
"engines": {
"node": "^18.18.0 || >=20.0.0"
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript-eslint/type-utils": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.18.0.tgz",
"integrity": "sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==",
"dependencies": {
"@typescript-eslint/typescript-estree": "7.18.0",
"@typescript-eslint/utils": "7.18.0",
"debug": "^4.3.4",
"ts-api-utils": "^1.3.0"
},
"node_modules/@typescript-eslint/tsconfig-utils": {
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.40.0.tgz",
"integrity": "sha512-jtMytmUaG9d/9kqSl/W3E3xaWESo4hFDxAIHGVW/WKKtQhesnRIJSAJO6XckluuJ6KDB5woD1EiqknriCtAmcw==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.18.0 || >=20.0.0"
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.56.0"
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/type-utils": {
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.40.0.tgz",
"integrity": "sha512-eE60cK4KzAc6ZrzlJnflXdrMqOBaugeukWICO2rB0KNvwdIMaEaYiywwHMzA1qFpTxrLhN9Lp4E/00EgWcD3Ow==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.40.0",
"@typescript-eslint/typescript-estree": "8.40.0",
"@typescript-eslint/utils": "8.40.0",
"debug": "^4.3.4",
"ts-api-utils": "^2.1.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/types": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.18.0.tgz",
"integrity": "sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==",
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.40.0.tgz",
"integrity": "sha512-ETdbFlgbAmXHyFPwqUIYrfc12ArvpBhEVgGAxVYSwli26dn8Ko+lIo4Su9vI9ykTZdJn+vJprs/0eZU0YMAEQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.18.0 || >=20.0.0"
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
@ -7107,36 +7138,40 @@
}
},
"node_modules/@typescript-eslint/typescript-estree": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.18.0.tgz",
"integrity": "sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==",
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.40.0.tgz",
"integrity": "sha512-k1z9+GJReVVOkc1WfVKs1vBrR5MIKKbdAjDTPvIK3L8De6KbFfPFt6BKpdkdk7rZS2GtC/m6yI5MYX+UsuvVYQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "7.18.0",
"@typescript-eslint/visitor-keys": "7.18.0",
"@typescript-eslint/project-service": "8.40.0",
"@typescript-eslint/tsconfig-utils": "8.40.0",
"@typescript-eslint/types": "8.40.0",
"@typescript-eslint/visitor-keys": "8.40.0",
"debug": "^4.3.4",
"globby": "^11.1.0",
"fast-glob": "^3.3.2",
"is-glob": "^4.0.3",
"minimatch": "^9.0.4",
"semver": "^7.6.0",
"ts-api-utils": "^1.3.0"
"ts-api-utils": "^2.1.0"
},
"engines": {
"node": "^18.18.0 || >=20.0.0"
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
"peerDependencies": {
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/semver": {
"version": "7.6.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
"integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==",
"version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
@ -7145,42 +7180,60 @@
}
},
"node_modules/@typescript-eslint/utils": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.18.0.tgz",
"integrity": "sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==",
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.40.0.tgz",
"integrity": "sha512-Cgzi2MXSZyAUOY+BFwGs17s7ad/7L+gKt6Y8rAVVWS+7o6wrjeFN4nVfTpbE25MNcxyJ+iYUXflbs2xR9h4UBg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.4.0",
"@typescript-eslint/scope-manager": "7.18.0",
"@typescript-eslint/types": "7.18.0",
"@typescript-eslint/typescript-estree": "7.18.0"
"@eslint-community/eslint-utils": "^4.7.0",
"@typescript-eslint/scope-manager": "8.40.0",
"@typescript-eslint/types": "8.40.0",
"@typescript-eslint/typescript-estree": "8.40.0"
},
"engines": {
"node": "^18.18.0 || >=20.0.0"
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.56.0"
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/visitor-keys": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.18.0.tgz",
"integrity": "sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==",
"version": "8.40.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.40.0.tgz",
"integrity": "sha512-8CZ47QwalyRjsypfwnbI3hKy5gJDPmrkLjkgMxhi0+DZZ2QNx2naS6/hWoVYUHU7LU2zleF68V9miaVZvhFfTA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "7.18.0",
"eslint-visitor-keys": "^3.4.3"
"@typescript-eslint/types": "8.40.0",
"eslint-visitor-keys": "^4.2.1"
},
"engines": {
"node": "^18.18.0 || >=20.0.0"
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
"integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"url": "https://opencollective.com/eslint"
}
},
"node_modules/@ungap/structured-clone": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.1.tgz",
@ -7652,14 +7705,6 @@
"resolved": "https://registry.npmjs.org/array-timsort/-/array-timsort-1.0.3.tgz",
"integrity": "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ=="
},
"node_modules/array-union": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz",
"integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==",
"engines": {
"node": ">=8"
}
},
"node_modules/array.prototype.findlastindex": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz",
@ -9450,17 +9495,6 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/dir-glob": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz",
"integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==",
"dependencies": {
"path-type": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/doctrine": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",
@ -10956,15 +10990,17 @@
"integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="
},
"node_modules/fast-glob": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz",
"integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==",
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.stat": "^2.0.2",
"@nodelib/fs.walk": "^1.2.3",
"glob-parent": "^5.1.2",
"merge2": "^1.3.0",
"micromatch": "^4.0.4"
"micromatch": "^4.0.8"
},
"engines": {
"node": ">=8.6.0"
@ -10974,6 +11010,8 @@
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"license": "ISC",
"dependencies": {
"is-glob": "^4.0.1"
},
@ -11687,34 +11725,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/globby": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz",
"integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==",
"dependencies": {
"array-union": "^2.1.0",
"dir-glob": "^3.0.1",
"fast-glob": "^3.2.9",
"ignore": "^5.2.0",
"merge2": "^1.4.1",
"slash": "^3.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/globby/node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/google-auth-library": {
"version": "9.15.0",
"resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.0.tgz",
@ -14514,6 +14524,8 @@
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
}
@ -14616,6 +14628,7 @@
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"dependencies": {
"braces": "^3.0.3",
"picomatch": "^2.3.1"
@ -15841,14 +15854,6 @@
"node": ">=16"
}
},
"node_modules/path-type": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz",
"integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==",
"engines": {
"node": ">=8"
}
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
@ -17624,6 +17629,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
"integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==",
"dev": true,
"engines": {
"node": ">=8"
}
@ -18614,14 +18620,16 @@
}
},
"node_modules/ts-api-utils": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
"integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==",
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
"integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=16"
"node": ">=18.12"
},
"peerDependencies": {
"typescript": ">=4.2.0"
"typescript": ">=4.8.4"
}
},
"node_modules/ts-jest": {
@ -18885,6 +18893,7 @@
"version": "5.7.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz",
"integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==",
"devOptional": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"

View file

@ -36,6 +36,8 @@
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"@typescript-eslint/eslint-plugin": "^8.40.0",
"@typescript-eslint/parser": "^8.40.0",
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
@ -66,7 +68,6 @@
"@sentry/esbuild-plugin": "^4.0.2",
"@sentry/node": "^9.43.0",
"@sentry/vite-plugin": "^4.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",

View file

@ -13,7 +13,7 @@ export const readCurrentlyOpenFileTool: Tool = {
function: {
name: BuiltInToolNames.ReadCurrentlyOpenFile,
description:
"Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, try using this",
"Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, or is requesting an action on content that seems missing, try using this tool.",
parameters: {
type: "object",
properties: {},

View file

@ -18,11 +18,11 @@ description: "These blocks form the foundation of the entire assistant experienc
| Model role | Best open models | Best closed models | Notes |
|:------------|:------------------|:-------------------|:--------|
| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed models are slightly better than open models |
| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance |
| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder | Closed models are slightly better than open models |
| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Qwen2.5-Coder (32B), Devstral (27B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), GPT-4, [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro), DeepSeek models | Closed models are slightly better than open models |
| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B), DeepSeek Chat | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance |
| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder, Mercury Coder Small, DeepSeek Coder | Closed models are slightly better than open models |
| Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role |
| Embed | N/A | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed | Open models are basically non-existent / not good enough for this model role |
| Embed | Nomic Embed Text | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed, text-embedding-3-large, text-embedding-004 | Open embeddings models are emerging but closed models still perform better |
| Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role |
| Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models |

View file

@ -92,7 +92,7 @@ If you use Azure Machine Learning Studio to deploy Codestral:
## How to Configure Azure AI Foundry Embeddings Models
We recommend configuring **text-embedding-3-large** as your embeddings model.
For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
<Tabs>
<Tab title="YAML">

View file

@ -41,7 +41,7 @@ We recommend configuring **DeepSeek Chat** as your chat model.
## How to Set Up DeepSeek Autocomplete Models
We recommend configuring **DeepSeek Coder** as your autocomplete model.
For recommended autocomplete models, please refer to our [Model Recommendations page](/customization/models).
<Tabs>
<Tab title="YAML">

View file

@ -48,7 +48,7 @@ Gemini currently does not offer any autocomplete models.
## How to Configure Gemini Embeddings Models
We recommend configuring **text-embedding-004** as your embeddings model.
For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
<Tabs>
<Tab title="YAML">

View file

@ -65,7 +65,7 @@ We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
## How to Set Up Ollama Embeddings Models
We recommend configuring **Nomic Embed Text** as your embeddings model.
For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
<Tabs>
<Tab title="YAML">
@ -123,7 +123,7 @@ To configure a remote instance of Ollama, add the `"apiBase"` property to your m
]
}
```
</Tab>
</Tab>
</Tabs>
## How to Configure Model Capabilities in Ollama

View file

@ -1103,6 +1103,10 @@
{
"source": "/customize/model-providers",
"destination": "/customize/model-providers/overview"
},
{
"source": "/features/edit/next-edit",
"destination": "/features/autocomplete/next-edit"
}
]
}

View file

@ -27,22 +27,7 @@ Instead of relying solely on native tool calling APIs (which vary between provid
- **Better reliability** - Models that struggle with native tools often perform better with system message tools
- **Seamless switching** - Change between providers without modifying your workflow
### What Models Are Recommended for Agent Mode
For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities:
**Premium Models:**
- **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning
- **GPT-4** models (OpenAI) - Excellent native tool support
- **DeepSeek** models - Strong performance with competitive pricing
**Local Models:**
While more limited in capabilities, these models can work with system message tools:
- Qwen2.5-Coder 32B - Best local option for Agent mode
- Devstral 27B - Good for code-specific tasks
- Smaller models (7B-13B) - May struggle with complex tool interactions
For recommended Agent models, please refer to our [Model Recommendations page](/customization/models).
### How to Configure Agent Mode

View file

@ -10,49 +10,11 @@ Setting up the right model for autocomplete is crucial for a smooth coding exper
For a complete comparison of all autocomplete models, see our [comprehensive model recommendations](/customization/models#recommended-models).
</Info>
## Recommended Models for Autocomplete in Continue
### Hosted (Best Performance)
For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral.
This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
**Codestral Quick Setup:**
1. Get your API key from [Mistral AI](https://console.mistral.ai)
2. Add [Codestral](https://hub.continue.dev/mistral/codestral) to your assistant on Continue Hub
3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the assistant selector in the Continue IDE extension
### Hosted (Best Speed/Quality Tradeoff)
For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception.
This model is specifically designed for code completion and is particularly fast because it is a diffusion model.
**Mercury Coder Small Quick Setup:**
1. Get your API key from [Inception](https://platform.inceptionlabs.ai/)
2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub
3. Add `INCEPTION_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the assistant selector in the Continue IDE extension
### Local (Offline / Privacy First)
For a fully local autocomplete experience, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)**.
This model provides good suggestions while keeping your code completely private.
**Quick Setup:**
1. Install [Ollama](https://ollama.ai/)
2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub
3. Click `Reload config` in the assistant selector in the Continue IDE extension
For model recommendations, please refer to our [Model Recommendations page](/customization/models).
## Next Edit Model
For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/edit/next-edit) models:
For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/autocomplete/next-edit) models:
**Supported Next Edit model:**

View file

@ -7,16 +7,7 @@ The model you use for for Chat mode will be
For a comprehensive comparison of all available models by role, see our [model recommendations table](/customization/models#recommended-models).
</Info>
## What Models Are Recommended for Chat?
Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic.
Its strong tool calling and reasoning capabilities make it the best model for Agent mode.
1. Get your API key from [Anthropic](https://console.anthropic.com/)
2. Add [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) to your assistant on Continue Hub
3. Add `ANTHROPIC_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the assistant selector in the Continue IDE extension
For model recommendations, please refer to our [Model Recommendations page](/customization/models).
### What Other Hosted Models Are Available?

View file

@ -14,7 +14,7 @@ When you start an edit session, Continue:
If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes.
<Info>
**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/edit/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications.
**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/autocomplete/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications.
</Info>
If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](/troubleshooting#check-the-logs).

View file

@ -16,10 +16,7 @@ The recommended models and how to set them up can be found [here](/features/chat
We also recommend setting up an Apply model for the best Edit experience.
**Recommended Apply models:**
- [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)
For recommended Apply models, please refer to our [Model Recommendations page](/customization/models).
## How to Determine Model Compatibility

View file

@ -14,7 +14,7 @@ Before getting started, ensure your system meets these requirements:
## How to Install Ollama - Step-by-Step
### Step 1: How to Install Ollama
### Step 1: Install Ollama
Choose the installation method for your operating system:
@ -29,7 +29,7 @@ curl -fsSL https://ollama.ai/install.sh | sh
# Download from ollama.ai
```
### Step 2: How to Start Ollama
### Step 2: Start Ollama Service
After installation, start the Ollama service:
@ -40,12 +40,17 @@ ollama serve
# Verify it's running
curl http://localhost:11434
# Should return "Ollama is running"
# Check Ollama version
ollama --version
```
### Step 3: How to Download Models
### Step 3: Download Models
<Warning>
**Important**: Always use `ollama pull` instead of `ollama run` to download models. The `run` command starts an interactive session which isn't needed for Continue.
**Important**: Always use `ollama pull` instead of `ollama run` to download
models. The `run` command starts an interactive session which isn't needed for
Continue.
</Warning>
Download models using the exact tag specified:
@ -62,12 +67,15 @@ ollama list
```
**Common Model Tags:**
- `:latest` - Default version (used if no tag specified)
- `:32b`, `:7b`, `:1.5b` - Parameter count versions
- `:instruct`, `:base` - Model variants
<Note>
If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be a different size.
If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it
with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be
a different size.
</Note>
## How to Configure Ollama with Continue
@ -76,10 +84,9 @@ There are multiple ways to configure Ollama models in Continue:
### Method 1: Using Hub Model Blocks in Local config.yaml
The easiest way is to use pre-configured model blocks from the Continue Hub in your local configuration:
The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration:
```yaml
# ~/.continue/assistants/My Local Assistant.yaml
```yaml title="~/.continue/assistants/My Local Assistant.yaml"
name: My Local Assistant
version: 0.0.1
schema: v1
@ -90,20 +97,20 @@ models:
```
<Warning>
**Important**: Hub blocks only provide configuration - you still need to pull the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue to use `model: deepseek-r1:32b`, but the actual model must be installed:
```bash
# Check what the hub block expects (view on hub.continue.dev)
# Then pull that exact model tag locally
ollama pull deepseek-r1:32b # Required for ollama/deepseek-r1-32b hub block
```
If the model isn't installed, Ollama will return: `404 model "deepseek-r1:32b" not found, try pulling it first`
**Important**: Hub blocks only provide configuration - you still need to pull
the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue
to use `model: deepseek-r1:32b`, but the actual model must be installed:
```bash # Check what the hub block expects (view on hub.continue.dev) # Then
pull that exact model tag locally ollama pull deepseek-r1:32b # Required for
ollama/deepseek-r1-32b hub block ``` If the model isn't installed, Ollama will
return: `404 model "deepseek-r1:32b" not found, try pulling it first`
</Warning>
### Method 2: Using Autodetect
Continue can automatically detect available Ollama models. You can configure this in your YAML:
```yaml
```yaml title="~/.continue/config.yaml"
models:
- name: Autodetect
provider: ollama
@ -112,6 +119,8 @@ models:
- chat
- edit
- apply
- rerank
- autocomplete
```
Or use it through the GUI:
@ -122,7 +131,12 @@ Or use it through the GUI:
4. Select your desired model from the detected list
<Note>
The Autodetect feature scans your local Ollama installation and lists all available models. When set to `AUTODETECT`, Continue will dynamically populate the model list based on what's installed locally via `ollama list`. This is useful for quickly switching between models without manual configuration.
The Autodetect feature scans your local Ollama installation and lists all
available models. When set to `AUTODETECT`, Continue will dynamically populate
the model list based on what's installed locally via `ollama list`. This is
useful for quickly switching between models without manual configuration. For
any roles not covered by the detected models, you may need to manually
configure them.
</Note>
You can update `apiBase` with the IP address of a remote machine serving Ollama.
@ -135,12 +149,12 @@ For custom configurations or models not on the hub:
models:
- name: DeepSeek R1 32B
provider: ollama
model: deepseek-r1:32b # Must match exactly what `ollama list` shows
model: deepseek-r1:32b # Must match exactly what `ollama list` shows
apiBase: http://localhost:11434
roles:
- chat
- edit
capabilities: # Add if not auto-detected
capabilities: # Add if not auto-detected
- tool_use
- name: Qwen2.5-Coder 1.5B
provider: ollama
@ -161,14 +175,16 @@ models:
provider: ollama
model: deepseek-r1:latest
capabilities:
- tool_use # Add this to enable tools
- tool_use # Add this to enable tools
```
<Warning>
**Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not supported" or "does not support tools" even with capabilities configured. This is a known limitation where the model's actual tool support differs from its advertised capabilities.
**Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not
supported" or "does not support tools" even with capabilities configured. This
is a known limitation where the model's actual tool support differs from its
advertised capabilities.
</Warning>
#### If Agent Mode Shows "Not Supported"
1. First, add `capabilities: [tool_use]` to your model config
@ -181,29 +197,70 @@ See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for
For optimal performance, consider these advanced configuration options:
- Memory optimization: Adjust `num_ctx` for context window size
- GPU acceleration: Use `num_gpu` to control GPU layers
- Custom model parameters: Temperature, top_p, top_k settings
- Performance tuning: Batch size and threading options
```yaml
models:
- name: Optimized DeepSeek
provider: ollama
model: deepseek-r1:32b
contextLength: 8192 # Adjust context window (default varies by model)
completionOptions:
temperature: 0.7 # Controls randomness (0.0-1.0)
top_p: 0.9 # Nucleus sampling threshold
top_k: 40 # Top-k sampling
num_predict: 2048 # Max tokens to generate
# Ollama-specific options (set via environment or modelfile)
# num_gpu: 35 # Number of GPU layers to offload
# num_thread: 8 # CPU threads to use
```
For GPU acceleration and memory tuning, create an Ollama Modelfile:
```
# Create custom model with optimizations
FROM deepseek-r1:32b
PARAMETER num_gpu 35
PARAMETER num_thread 8
PARAMETER num_ctx 4096
```
## What Are the Best Practices for Ollama
### How to Choose the Right Model
Choose models based on your specific needs:
Choose models based on your specific needs (see [recommended models](/customization/models#recommended-models) for more options):
1. **Code Generation**: Use CodeLlama or Mistral
2. **Chat**: Llama2 or Mistral
3. **Specialized Tasks**: Domain-specific models
1. **Code Generation**:
- `qwen2.5-coder:7b` - Excellent for code completion
- `codellama:13b` - Strong general coding support
- `deepseek-coder:6.7b` - Fast and efficient
2. **Chat & Reasoning**:
- `llama3.1:8b` - Latest Llama with tool support
- `mistral:7b` - Fast and versatile
- `deepseek-r1:32b` - Advanced reasoning capabilities
3. **Autocomplete**:
- `qwen2.5-coder:1.5b` - Lightweight and fast
- `starcoder2:3b` - Optimized for code completion
4. **Memory Requirements**:
- 1.5B-3B models: ~4GB RAM
- 7B models: ~8GB RAM
- 13B models: ~16GB RAM
- 32B models: ~32GB RAM
### How to Optimize Performance
To get the best performance from Ollama:
- Monitor system resources
- Adjust context window size
- Use appropriate model sizes
- Enable GPU acceleration when available
- Monitor system resources with `ollama ps` to see memory usage
- Adjust context window size based on available RAM
- Use appropriate model sizes for your hardware
- Enable GPU acceleration when available (NVIDIA CUDA or AMD ROCm)
- Use `ollama logs` to debug performance issues
## How to Troubleshoot Ollama Issues
@ -214,7 +271,8 @@ To get the best performance from Ollama:
This error occurs when the model isn't installed locally:
**Problem**: Using a hub block or config that references a model not yet pulled
**Solution**:
**Solution**:
```bash
# Check what models you have
ollama list
@ -227,6 +285,7 @@ ollama pull model-name:tag # e.g., deepseek-r1:32b
**Problem**: `ollama pull deepseek-r1` installs `:latest` but hub block expects `:32b`
**Solution**: Always pull with the exact tag:
```bash
# Wrong - pulls :latest
ollama pull deepseek-r1
@ -239,6 +298,7 @@ ollama pull deepseek-r1:32b
**Problem**: Model doesn't support tools/function calling
**Solutions**:
1. Add `capabilities: [tool_use]` to your model config
2. If still not working, the model may not actually support tools
3. Switch to a model with confirmed tool support (Llama 3.1, Mistral)
@ -247,6 +307,7 @@ ollama pull deepseek-r1:32b
**Problem**: Unclear how to use hub models locally
**Solution**: Create a local assistant file:
```yaml
# ~/.continue/assistants/Local.yaml
name: Local Assistant
@ -269,13 +330,29 @@ models:
- Model too large: Check available memory with `ollama ps`
- GPU issues: Verify CUDA/ROCm installation for GPU acceleration
- Slow generation: Adjust `num_gpu` layers in model configuration
- Check system diagnostics: `ollama ps` for active models and memory usage
## What Are Example Workflows with Ollama
### How to Use Ollama for Code Generation
```
# Example: Generate a FastAPI endpointdef create_user_endpoint(): # Continue will help generate the implementation pass
```python
# Example: Generate a FastAPI endpoint
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
email: str
age: int
@app.post("/users/")
async def create_user(user: User):
# Continue will help complete this implementation
# Use Cmd+I (Mac) or Ctrl+I (Windows/Linux) to generate code
pass
```
### How to Use Ollama for Code Review
@ -293,4 +370,4 @@ Ollama with Continue provides a powerful local development environment for AI-as
---
_This guide is based on Ollama v0.1.x and Continue v0.8.x. Please check for updates regularly._
_This guide is based on Ollama v0.11.x and Continue v1.1.x. Please check for updates regularly._

74
extensions/cli/BUILD.md Normal file
View file

@ -0,0 +1,74 @@
# Build Process Documentation
## Overview
The Continue CLI uses esbuild to bundle the application along with local packages (`@continuedev/config-yaml` and `@continuedev/openai-adapters`) into a single distributable file. This ensures that users who install the CLI from npm don't need to worry about local file references.
## Build Steps
1. **Install dependencies**: `npm install`
2. **Build**: `npm run build`
- This first builds the local packages
- Then bundles everything with esbuild
## How it Works
### Bundling Strategy
The `build.mjs` script uses esbuild to:
- Bundle all TypeScript/JavaScript code into a single ES module
- Include local packages (`@continuedev/config-yaml`, `@continuedev/openai-adapters`) directly in the bundle
- Keep problematic or native dependencies external (e.g., `@sentry/profiling-node`, `winston`, `express`)
- Create a wrapper script (`dist/cn.js`) with the proper shebang for CLI execution
### Key Features
- **Local Package Bundling**: Local packages are bundled directly, avoiding `file:` reference issues
- **Stub for Optional Dependencies**: `react-devtools-core` is stubbed to prevent runtime errors
- **CommonJS Compatibility**: Adds `createRequire` to support packages that use dynamic requires
- **Source Maps**: Generates source maps for debugging
- **Metadata**: Creates `dist/meta.json` with bundle analysis information
## Testing
### Smoke Tests
Run smoke tests to verify the build:
```bash
npm run test:smoke
```
The smoke tests verify:
- Bundle files exist
- CLI commands work (--version, --help)
- Bundle size is reasonable (<20MB)
- Local packages are properly bundled
- No missing runtime dependencies
## Troubleshooting
### Common Issues
1. **Module not found errors**: Check if the module needs to be added to the external list in `build.mjs`
2. **Native module issues**: Native modules should be marked as external
3. **Bundle too large**: Review bundled packages in `dist/meta.json` and consider marking large packages as external
### Analyzing the Bundle
After building, check `dist/meta.json` to see:
- What packages were bundled
- Bundle size breakdown
- Input/output file mappings
## Publishing
When publishing to npm:
1. The bundled files in `dist/` are included
2. Users install via `npm install -g @continuedev/cli`
3. The `cn` command becomes available globally
4. No local file references or missing dependencies

91
extensions/cli/build.mjs Normal file
View file

@ -0,0 +1,91 @@
#!/usr/bin/env node
import * as esbuild from "esbuild";
import { writeFileSync, chmodSync } from "fs";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
// List of packages to mark as external (ONLY native modules that cannot be bundled)
// Note: Everything else will be bundled to create a self-contained CLI
// Users should not need to install any additional dependencies
const external = [
"@sentry/profiling-node", // Contains native profiler bindings (optional)
"fsevents", // macOS native file watcher (optional dependency)
];
console.log("Building CLI with esbuild...");
// Plugin to handle optional react-devtools-core
const optionalDevtoolsPlugin = {
name: "optional-devtools",
setup(build) {
build.onResolve({ filter: /^react-devtools-core$/ }, () => {
// Return path to our stub instead of marking as external
return { path: resolve(__dirname, "stubs/react-devtools-core.js") };
});
},
};
try {
const result = await esbuild.build({
entryPoints: ["src/index.ts"],
bundle: true,
platform: "node",
target: "node18",
format: "esm",
outfile: "dist/index.js",
external,
sourcemap: true,
minify: true, // Minify for smaller bundle size
metafile: true,
plugins: [optionalDevtoolsPlugin],
// Handle .js extensions in imports
resolveExtensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
// Handle TypeScript paths and local packages
alias: {
"@continuedev/config-yaml": resolve(
__dirname,
"../../packages/config-yaml/dist/index.js",
),
"@continuedev/openai-adapters": resolve(
__dirname,
"../../packages/openai-adapters/dist/index.js",
),
"@continuedev/config-types": resolve(
__dirname,
"../../packages/config-types/dist/index.js",
),
"core": resolve(__dirname, "../../core"),
"@continuedev/fetch": resolve(__dirname, "../../packages/fetch/dist/index.js"),
"@continuedev/llm-info": resolve(__dirname, "../../packages/llm-info/dist/index.js"),
},
// Add banner to create require for CommonJS packages
banner: {
js: `import { createRequire } from 'module';
const require = createRequire(import.meta.url);`,
},
});
// Write metafile for analysis
writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2));
// Create wrapper script with shebang
writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');");
// Make the wrapper script executable
chmodSync("dist/cn.js", 0o755);
// Calculate bundle size
const bundleSize = result.metafile.outputs["dist/index.js"].bytes;
console.log(
`✓ Build complete! Bundle size: ${(bundleSize / 1024 / 1024).toFixed(2)} MB`,
);
} catch (error) {
console.error("Build failed:", error);
process.exit(1);
}

File diff suppressed because it is too large Load diff

View file

@ -6,15 +6,20 @@
"types": "dist/index.d.ts",
"type": "module",
"bin": {
"cn": "dist/index.js"
"cn": "dist/cn.js"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch",
"test:ui": "vitest --ui",
"test:e2e": "vitest run --config vitest.e2e.config.ts",
"build": "tsc -p tsconfig.build.json",
"start": "node dist/index.js",
"test:smoke": "node smoke-test.mjs",
"build:tsc": "tsc -p tsconfig.build.json",
"build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && cd ../extensions/cli && npm i",
"build:validate": "node validate-aliases.mjs",
"build:bundle": "node build.mjs",
"build": "npm run build:validate && npm run build:bundle",
"start": "node dist/cn.js",
"dev": "tsx src/index.ts",
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
@ -39,8 +44,11 @@
},
"homepage": "https://continue.dev",
"dependencies": {
"@continuedev/config-yaml": "^1.0.96",
"@continuedev/openai-adapters": "^1.4.1",
"@sentry/profiling-node": "^9.43.0"
},
"devDependencies": {
"@continuedev/config-yaml": "file:../../packages/config-yaml",
"@continuedev/openai-adapters": "file:../../packages/openai-adapters",
"@continuedev/sdk": "^0.0.13",
"@modelcontextprotocol/sdk": "^1.17.2",
"@opentelemetry/api": "^1.9.0",
@ -52,7 +60,6 @@
"@opentelemetry/sdk-node": "^0.203.0",
"@opentelemetry/semantic-conventions": "^1.36.0",
"@sentry/node": "^9.43.0",
"@sentry/profiling-node": "^9.43.0",
"@types/express": "^5.0.3",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",
@ -83,12 +90,9 @@
"swr": "^2.3.4",
"turndown": "^7.2.0",
"typescript": "^5.8.3",
"uri-js": "^4.4.1",
"uuid": "^9.0.1",
"winston": "^3.17.0",
"yaml": "^2.8.0"
},
"devDependencies": {
"yaml": "^2.8.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^11.0.3",
@ -96,7 +100,6 @@
"@testing-library/react": "^16.3.0",
"@types/date-fns": "^2.5.3",
"@types/diff": "^7.0.2",
"@types/express": "^5.0.3",
"@types/glob": "^8.1.0",
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
@ -105,17 +108,18 @@
"@types/readline-sync": "^1.4.8",
"@types/shell-quote": "^1.7.5",
"@types/supertest": "^6.0.3",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"@vitest/ui": "^3.2.4",
"conventional-changelog-conventionalcommits": "^9.1.0",
"cross-env": "^7.0.3",
"esbuild": "^0.25.9",
"eslint": "^9.32.0",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-unused-imports": "^4.1.4",
"execa": "^9.6.0",
"express": "^5.1.0",
"happy-dom": "^18.0.1",
"ink-testing-library": "^4.0.0",
"jsdom": "^26.1.0",

230
extensions/cli/smoke-test.mjs Executable file
View file

@ -0,0 +1,230 @@
#!/usr/bin/env node
import { execSync } from "child_process";
import { existsSync, readFileSync } from "fs";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
// Colors for output
const colors = {
green: "\x1b[32m",
red: "\x1b[31m",
yellow: "\x1b[33m",
reset: "\x1b[0m",
};
let testsPassed = 0;
let testsFailed = 0;
function runTest(name, testFn) {
process.stdout.write(`Testing ${name}... `);
try {
testFn();
console.log(`${colors.green}✓${colors.reset}`);
testsPassed++;
} catch (error) {
console.log(`${colors.red}✗${colors.reset}`);
console.error(` Error: ${error.message}`);
testsFailed++;
}
}
function execCommand(command, options = {}) {
return execSync(command, {
cwd: __dirname,
encoding: "utf8",
stdio: "pipe",
...options,
});
}
console.log("🧪 Running smoke tests for bundled CLI...\n");
// Test 1: Check if bundle exists
runTest("Bundle file exists", () => {
if (!existsSync(resolve(__dirname, "dist/index.js"))) {
throw new Error("dist/index.js not found");
}
if (!existsSync(resolve(__dirname, "dist/cn.js"))) {
throw new Error("dist/cn.js not found");
}
});
// Test 2: Check if wrapper script is executable
runTest("Wrapper script has shebang", () => {
const content = readFileSync(resolve(__dirname, "dist/cn.js"), "utf8");
if (!content.startsWith("#!/usr/bin/env node")) {
throw new Error("Wrapper script missing shebang");
}
});
// Cross-platform command execution helper
function getCLICommand(args = "") {
const isWindows = process.platform === "win32";
if (isWindows) {
return `node dist/cn.js ${args}`;
} else {
return `./dist/cn.js ${args}`;
}
}
// Test 3: Version command works
runTest("Version command", () => {
const output = execCommand(getCLICommand("--version"));
const packageJson = JSON.parse(
readFileSync(resolve(__dirname, "package.json"), "utf8"),
);
if (!output.includes(packageJson.version)) {
throw new Error(
`Version mismatch. Expected ${packageJson.version}, got: ${output}`,
);
}
});
// Test 4: Help command works
runTest("Help command", () => {
const output = execCommand(getCLICommand("--help"));
if (!output.includes("Continue CLI") || !output.includes("--version")) {
throw new Error("Help output missing expected content");
}
});
// Test 5: Check bundle size
runTest("Bundle size is reasonable", () => {
const isWindows = process.platform === "win32";
const command = isWindows
? `powershell -Command "(Get-Item dist/index.js).length / 1MB"`
: `ls -lh dist/index.js`;
let sizeInMB;
if (isWindows) {
try {
const output = execCommand(command);
sizeInMB = parseFloat(output.trim());
} catch {
// Fallback for Windows if PowerShell fails
const stats = readFileSync(resolve(__dirname, "dist/index.js"));
sizeInMB = stats.length / (1024 * 1024);
}
} else {
const stats = execCommand(command);
const sizeMatch = stats.match(/(\d+(?:\.\d+)?[MK])/);
if (sizeMatch) {
const size = sizeMatch[1];
const numSize = parseFloat(size);
const unit = size.slice(-1);
sizeInMB = unit === "M" ? numSize : numSize / 1024;
}
}
console.log(`(${sizeInMB.toFixed(1)}M)`);
// This is arbitrary. We might go over at some point,
// in which case you can just increase this.
if (sizeInMB > 20) {
throw new Error(`Bundle too large: ${sizeInMB.toFixed(1)}M`);
}
});
// Test 6: Check that local packages are bundled
runTest("Local packages are bundled", () => {
const bundleContent = readFileSync(
resolve(__dirname, "dist/index.js"),
"utf8",
);
// Check for code from @continuedev/config-yaml
if (
!bundleContent.includes("AssistantUnrolled") &&
!bundleContent.includes("config-yaml")
) {
throw new Error("@continuedev/config-yaml not properly bundled");
}
// Check for code from @continuedev/openai-adapters
// Since the bundle is minified, check for strings that would be present
// even after minification (e.g., error messages, property names)
if (
!bundleContent.includes("anthropic") &&
!bundleContent.includes("gemini") &&
!bundleContent.includes("openai") &&
!bundleContent.includes("azure") &&
!bundleContent.includes("bedrock")
) {
throw new Error("@continuedev/openai-adapters not properly bundled");
}
});
// Test 7: Test that the CLI can be invoked programmatically
runTest("CLI can be invoked", () => {
try {
// Test that the CLI runs without crashing when given no args
const isWindows = process.platform === "win32";
const nullDevice = isWindows ? "nul" : "/dev/null";
execCommand(`${getCLICommand("--help")} > ${nullDevice} 2>&1`);
} catch (error) {
throw new Error(`CLI invocation failed: ${error.message}`);
}
});
// Test 8: Check metadata file
runTest("Build metadata exists", () => {
if (!existsSync(resolve(__dirname, "dist/meta.json"))) {
throw new Error("dist/meta.json not found");
}
const meta = JSON.parse(
readFileSync(resolve(__dirname, "dist/meta.json"), "utf8"),
);
if (!meta.inputs || !meta.outputs) {
throw new Error("Invalid metadata structure");
}
});
// Test 9: Verify no missing external dependencies
runTest("No missing runtime dependencies", () => {
// This would fail in Test 3 if dependencies were missing, but let's be explicit
const output = execCommand(`${getCLICommand("--version")} 2>&1`, {
env: { ...process.env, NODE_ENV: "production" },
});
if (
output.includes("Cannot find module") ||
output.includes("MODULE_NOT_FOUND")
) {
throw new Error("Missing module detected in output");
}
});
// Test 10: Test npm link scenario
runTest("CLI works via npm link", () => {
try {
// Simply test that we can execute with node directly
const output = execCommand("node dist/cn.js --version 2>&1");
const packageJson = JSON.parse(
readFileSync(resolve(__dirname, "package.json"), "utf8"),
);
if (!output.includes(packageJson.version)) {
throw new Error("Version not found when running via node");
}
} catch (error) {
throw new Error(`npm link scenario failed: ${error.message}`);
}
});
// Summary
console.log("\n" + "=".repeat(50));
if (testsFailed === 0) {
console.log(
`${colors.green}✅ All ${testsPassed} tests passed!${colors.reset}`,
);
process.exit(0);
} else {
console.log(
`${colors.red}❌ ${testsFailed} test(s) failed, ${testsPassed} passed${colors.reset}`,
);
process.exit(1);
}

View file

@ -27,26 +27,27 @@ describe("asciiArt", () => {
expect(result).toBe(CONTINUE_ASCII_ART);
});
it("should return simple text version when terminal is too narrow", () => {
it("should return CN ASCII art version when terminal is too narrow", () => {
// Set process.stdout.columns to simulate narrow terminal
process.stdout.columns = 60;
const result = getDisplayableAsciiArt();
expect(result).toContain("CONTINUE");
// expect(result).toContain("v0.0.0-dev");
expect(result).toContain("██████╗");
expect(result).toContain("(alpha)");
expect(result).not.toBe(CONTINUE_ASCII_ART);
// Should be much shorter than the full ASCII art
expect(result.length).toBeLessThan(CONTINUE_ASCII_ART.length / 2);
});
it("should return simple text version when terminal is below threshold", () => {
it("should return CN ASCII art version when terminal is below threshold", () => {
// Test the edge case at exactly 74 columns (below our threshold of 75)
process.stdout.columns = 74;
const result = getDisplayableAsciiArt();
expect(result).toContain("CONTINUE");
expect(result).toContain("██████╗");
expect(result).toContain("(alpha)");
expect(result).not.toBe(CONTINUE_ASCII_ART);
});

View file

@ -12,7 +12,17 @@ ${mind.multiline(` ██████╗ ██████╗ ███╗
██║ ██║ ██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║██╔══╝
╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝███████╗
╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝`)}
${d("v" + getVersion())}`;
${d("v" + getVersion() + " (alpha)")}`;
// ASCII art for just "CN" (first two letters)
const CN_ASCII_ART = `
${mind.multiline(` ██████╗███╗ ██╗
██╔════╝████╗ ██║
██║ ██╔██╗ ██║
██║ ██║╚██╗██║
╚██████╗██║ ╚████║
╚═════╝╚═╝ ╚═══╝`)}
${d("v" + getVersion() + " (alpha)")}`;
// Minimum terminal width required to display ASCII art properly
const MIN_WIDTH_FOR_ASCII_ART = 75;
@ -28,8 +38,8 @@ export function getDisplayableAsciiArt(): string {
return CONTINUE_ASCII_ART;
}
// If terminal is too narrow, just show a simple version
return `\n${chalk.bold.blue("CONTINUE")} ${d("v" + getVersion())}\n`;
// If terminal is too narrow, show just "CN" ASCII art
return CN_ASCII_ART;
}
export const CONTINUE_LOGO_ASCII_ART = `

View file

@ -291,7 +291,7 @@ async function unrollAssistantWithConfig(
apiBase: env.apiBase,
rootPath:
packageIdentifier.uriType === "file"
? dirname(packageIdentifier.filePath)
? dirname(packageIdentifier.fileUri)
: undefined,
}),
{
@ -328,7 +328,7 @@ async function loadConfigYaml(
apiClient: DefaultApiInterface,
): Promise<AssistantUnrolled> {
return await unrollAssistantWithConfig(
{ filePath, uriType: "file" },
{ fileUri: filePath, uriType: "file" },
accessToken,
organizationId,
apiClient,

View file

@ -1,19 +1,19 @@
import {
isValidAnthropicApiKey,
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
describe("Free Trial Transition API Key Validation", () => {
it("should validate API keys properly for free trial transition", () => {
// Valid API keys
expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true);
expect(isValidAnthropicApiKey("sk-ant-1234567890")).toBe(true);
expect(
isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"),
isValidAnthropicApiKey("sk-ant-api03_T3BlbkFJ1234567890abcdef"),
).toBe(true);
// Invalid API keys
expect(isValidAnthropicApiKey("TEST-")).toBe(false);
expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false);
expect(isValidAnthropicApiKey("sk-ant-")).toBe(false);
expect(isValidAnthropicApiKey("TEST-openai-1234")).toBe(false);
expect(isValidAnthropicApiKey("")).toBe(false);
expect(isValidAnthropicApiKey(null)).toBe(false);
@ -25,14 +25,14 @@ describe("Free Trial Transition API Key Validation", () => {
expect(getApiKeyValidationError(null)).toBe("API key is required");
expect(getApiKeyValidationError(undefined)).toBe("API key is required");
expect(getApiKeyValidationError("TEST-")).toBe(
'API key must start with "TEST-ant-"',
'API key must start with "sk-ant-"',
);
expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
'API key must start with "TEST-ant-"',
'API key must start with "sk-ant-"',
);
expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short");
expect(getApiKeyValidationError("sk-ant-")).toBe("API key is too short");
expect(getApiKeyValidationError("invalid")).toBe(
'API key must start with "TEST-ant-"',
'API key must start with "sk-ant-"',
);
});
});

View file

@ -0,0 +1,52 @@
/**
* Optional profiling integration loader
* This module handles the optional @sentry/profiling-node dependency
* which contains native bindings and may not be available in all environments
*/
let profilingIntegration: any = null;
let profilingLoadAttempted = false;
/**
* Lazy load the profiling integration
*/
async function loadProfilingIntegration() {
if (profilingLoadAttempted) {
return profilingIntegration;
}
profilingLoadAttempted = true;
try {
// Try to load the native profiling module if available
const profilingModule = await import("@sentry/profiling-node");
profilingIntegration = profilingModule.nodeProfilingIntegration;
} catch {
// Profiling module not available - this is fine, profiling is optional
// The CLI will work without it, just without performance profiling
}
return profilingIntegration;
}
/**
* Returns the profiling integration if available, or a no-op function
* Note: This is now async to handle lazy loading
*/
export async function getProfilingIntegration() {
const integration = await loadProfilingIntegration();
if (integration) {
return integration();
}
// Return empty object as a no-op integration
return {};
}
/**
* Check if profiling is available
* Note: This is now async to handle lazy loading
*/
export async function isProfilingAvailable(): Promise<boolean> {
await loadProfilingIntegration();
return profilingIntegration !== null;
}

View file

@ -1,6 +1,9 @@
import * as Sentry from "@sentry/node";
import { nodeProfilingIntegration } from "@sentry/profiling-node";
import {
getProfilingIntegration,
isProfilingAvailable,
} from "./sentry-profiling.js";
import { logger } from "./util/logger.js";
import { getVersion } from "./version.js";
@ -45,12 +48,21 @@ class SentryService {
};
}
private initialize() {
private async initialize() {
if (this.initialized || !this.config.dsn) {
return;
}
try {
const integrations = [];
const profilingIntegration = await getProfilingIntegration();
if (
profilingIntegration &&
Object.keys(profilingIntegration).length > 0
) {
integrations.push(profilingIntegration);
}
Sentry.init({
dsn: this.config.dsn,
environment: this.config.environment,
@ -58,7 +70,7 @@ class SentryService {
sampleRate: this.config.sampleRate,
profilesSampleRate: this.config.profilesSampleRate,
tracesSampleRate: this.config.tracesSampleRate,
integrations: [nodeProfilingIntegration()],
integrations,
beforeSend(event) {
// Filter out certain error types if needed
if (event.exception?.values?.[0]?.type === "AbortError") {
@ -72,6 +84,7 @@ class SentryService {
logger.debug("Sentry initialized", {
environment: this.config.environment,
release: this.config.release,
profilingAvailable: await isProfilingAvailable(),
});
} catch (error) {
logger.error("Failed to initialize Sentry", error);

View file

@ -3,6 +3,7 @@ import { glob, GlobOptionsWithFileTypesFalse } from "glob";
import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js";
import { getFileWatcher } from "../util/fileWatcher.js";
import { isGitRepo } from "../util/git.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
import { serviceContainer } from "./ServiceContainer.js";
@ -88,7 +89,7 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
console.error("Error performing full file index:", error);
logger.error("Error performing full file index:", error);
this.setState({ isIndexing: false, error: errorMessage });
}
}
@ -103,7 +104,7 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
// and provides little value since files change less predictably
const inGitRepo = isGitRepo();
if (!inGitRepo) {
console.log("Skipping file watcher: not in a git repository");
logger.debug("Skipping file watcher: not in a git repository");
return;
}
@ -153,13 +154,9 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
}));
this.setState({ files });
console.log(
`File index updated: +${addedFiles.length} -${removedFiles.length} files`,
);
}
} catch (error) {
console.error("Error handling file system change:", error);
logger.error("Error handling file system change:", error);
const errorMessage =
error instanceof Error ? error.message : String(error);
this.setState({ error: errorMessage });

View file

@ -4,8 +4,8 @@ import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
import {
AuthConfig,
getAccessToken,
getOrganizationId,
getModelName,
getOrganizationId,
} from "../auth/workos.js";
import { getLlmApi } from "../config.js";
import { logger } from "../util/logger.js";

View file

@ -1,6 +1,6 @@
// Import after mocking
import { AssistantUnrolled } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, vi, test } from "vitest";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import * as workos from "./auth/workos.js";
import * as commands from "./commands/commands.js";
@ -138,18 +138,10 @@ describe("handleSlashCommands", () => {
expect(result).toBeNull();
});
test("unknown slash command should return error", async () => {
test("unknown slash command should return null", async () => {
const result = await handleSlashCommands("/unknown", mockAssistant);
expect(result).not.toBeNull();
expect(result?.output).toBe("Unknown command: unknown");
});
test("/org command should no longer exist (now merged into /config)", async () => {
const result = await handleSlashCommands("/org list", mockAssistant);
expect(result).not.toBeNull();
expect(result?.output).toBe("Unknown command: org");
expect(result).toBeNull();
});
});
});

View file

@ -163,5 +163,16 @@ export async function handleSlashCommands(
return { newInput };
}
// Check if this command would match any available commands (same logic as UI)
const allCommands = getAllSlashCommands(assistant);
const hasMatches = allCommands.some((cmd) =>
cmd.name.toLowerCase().includes(command.toLowerCase()),
);
// If no commands match, treat this as regular text instead of an unknown command
if (!hasMatches) {
return null;
}
return { output: `Unknown command: ${command}` };
}

View file

@ -1,7 +1,5 @@
import * as fs from "fs";
import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import {
calculateLinesOfCodeDiff,
@ -97,7 +95,7 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a
preprocess: async (args) => {
// Get and validate args
const { filepath, diffs } = parseSearchAndReplaceArgs(args);
throwIfFileIsSecurityConcern(filepath);
// Get current file contents
if (!fs.existsSync(filepath)) {
throw new Error(`file ${filepath} does not exist`);

View file

@ -9,8 +9,8 @@ import useSWR from "swr";
import { listUserOrganizations } from "../auth/workos.js";
import { env } from "../env.js";
import {
isValidAnthropicApiKey,
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "../util/apiKeyValidation.js";
import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js";
@ -270,7 +270,7 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
<Text></Text>
{errorMessage && <Text color="red">{errorMessage}</Text>}
<Text color="gray">
Type your API key and press Enter (must start with 'TEST-ant-')
Type your API key and press Enter (must start with 'sk-ant-')
</Text>
</Box>
);

View file

@ -85,7 +85,9 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
{/* Rules */}
{allRules.length > 0 && (
<>
<Text color="blue">Rules:</Text>
<Text bold color="blue">
Rules:
</Text>
{allRules.map((rule, index) => (
<Text key={index}>
- <Text color="white">{rule}</Text>

View file

@ -1,5 +1,4 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
import { Box, Text, useApp, useInput } from "ink";
import React, { useCallback, useState } from "react";
@ -153,6 +152,17 @@ const UserInput: React.FC<UserInputProps> = ({
}
}
// Check if there are any matching commands
const filteredCommands = allCommands.filter((cmd) =>
cmd.name.toLowerCase().includes(afterSlash.toLowerCase()),
);
// If no commands match, hide the dropdown to allow normal Enter behavior
if (filteredCommands.length === 0) {
setShowSlashCommands(false);
return;
}
// Show selector for partial matches
setShowSlashCommands(true);
setSlashCommandFilter(afterSlash);
@ -255,7 +265,6 @@ const UserInput: React.FC<UserInputProps> = ({
// Read the file content and notify parent component
if (onFileAttached) {
try {
throwIfFileIsSecurityConcern(filePath);
const fs = await import("fs/promises");
const content = await fs.readFile(filePath, "utf-8");
onFileAttached(filePath, content);

View file

@ -20,7 +20,10 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
case "tool-start":
return (
<Box key={index} marginLeft={1} marginBottom={1}>
<Text color="white">○ {message.content}</Text>
{/* TODO: Change back to empty circle (○) with white color once we want to differentiate in-progress vs completed tool calls */}
<Text color="green">
●<Text color="white"> {message.content}</Text>
</Text>
</Box>
);
@ -87,7 +90,7 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
return (
<Box key={index} marginLeft={1} marginBottom={1}>
<Text color={isUser ? "green" : "magenta"}>●</Text>
<Text color={isUser ? "green" : "white"}>●</Text>
<Text> </Text>
{isUser ? (
<Text color="gray">{message.content}</Text>

View file

@ -1,21 +1,21 @@
import {
isValidAnthropicApiKey,
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "./apiKeyValidation.js";
describe("isValidAnthropicApiKey", () => {
it("should return true for valid API keys", () => {
expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true);
expect(isValidAnthropicApiKey("TEST-ant-abcdefghijklmnop")).toBe(true);
expect(isValidAnthropicApiKey("TEST-ant-test-key-with-dashes")).toBe(true);
expect(isValidAnthropicApiKey("sk-ant-1234567890")).toBe(true);
expect(isValidAnthropicApiKey("sk-ant-abcdefghijklmnop")).toBe(true);
expect(isValidAnthropicApiKey("sk-ant-test-key-with-dashes")).toBe(true);
expect(
isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"),
isValidAnthropicApiKey("sk-ant-api03_T3BlbkFJ1234567890abcdef"),
).toBe(true);
});
it("should return false for invalid API keys", () => {
expect(isValidAnthropicApiKey("")).toBe(false);
expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false);
expect(isValidAnthropicApiKey("sk-ant-")).toBe(false);
expect(isValidAnthropicApiKey("TEST-")).toBe(false);
expect(isValidAnthropicApiKey("TEST-openai-1234567890")).toBe(false);
expect(isValidAnthropicApiKey("invalid-key")).toBe(false);
@ -40,14 +40,14 @@ describe("getApiKeyValidationError", () => {
expect(getApiKeyValidationError(null)).toBe("API key is required");
expect(getApiKeyValidationError(undefined)).toBe("API key is required");
expect(getApiKeyValidationError("TEST-")).toBe(
'API key must start with "TEST-ant-"',
'API key must start with "sk-ant-"',
);
expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
'API key must start with "TEST-ant-"',
'API key must start with "sk-ant-"',
);
expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short");
expect(getApiKeyValidationError("sk-ant-")).toBe("API key is too short");
expect(getApiKeyValidationError("invalid")).toBe(
'API key must start with "TEST-ant-"',
'API key must start with "sk-ant-"',
);
});
});

View file

@ -10,8 +10,8 @@ export function isValidAnthropicApiKey(
return false;
}
// Anthropic API keys must start with "TEST-ant-" and have additional characters
return apiKey.startsWith("TEST-ant-") && apiKey.length > "TEST-ant-".length;
// Anthropic API keys must start with "sk-ant-" and have additional characters
return apiKey.startsWith("sk-ant-") && apiKey.length > "sk-ant-".length;
}
/**
@ -26,11 +26,11 @@ export function getApiKeyValidationError(
return "API key is required";
}
if (!apiKey.startsWith("TEST-ant-")) {
return 'API key must start with "TEST-ant-"';
if (!apiKey.startsWith("sk-ant-")) {
return 'API key must start with "sk-ant-"';
}
if (apiKey.length <= "TEST-ant-".length) {
if (apiKey.length <= "sk-ant-".length) {
return "API key is too short";
}

View file

@ -3,7 +3,7 @@ import { parse } from "yaml";
import { updateAnthropicModelInYaml } from "./yamlConfigUpdater.js";
describe("updateAnthropicModelInYaml", () => {
const testApiKey = "TEST-ant-test123456789";
const testApiKey = "sk-ant-test123456789";
describe("empty or invalid input", () => {
it("should create new config from empty string", () => {
@ -13,7 +13,7 @@ describe("updateAnthropicModelInYaml", () => {
expect(result).toContain("version: 1.0.0");
expect(result).toContain("schema: v1");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
it("should create new config from invalid YAML", () => {
@ -22,7 +22,7 @@ describe("updateAnthropicModelInYaml", () => {
expect(result).toContain("name: Local Config");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
});
@ -45,7 +45,7 @@ models:
expect(result).toContain("# List of available models");
expect(result).toContain("uses: openai/gpt-4");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
it("should preserve comments when updating existing model", () => {
@ -65,7 +65,7 @@ models:
expect(result).toContain("# My Continue config");
expect(result).toContain("# List of available models");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).not.toContain("old-key");
});
});
@ -85,7 +85,7 @@ models:
expect(result).toContain("uses: openai/gpt-4");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
});
@ -106,7 +106,7 @@ models:
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: openai/gpt-4");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
expect(result).not.toContain("old-anthropic-key");
@ -131,7 +131,7 @@ schema: v1
expect(result).toContain("name: Local Config");
expect(result).toContain("models:");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
it("should handle config with empty models array", () => {
@ -148,7 +148,7 @@ models: []
expect(result).toContain("name: Local Config");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
});
@ -190,14 +190,14 @@ models: "not an array"
const result = updateAnthropicModelInYaml(malformedConfig, testApiKey);
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
it("should handle different API key formats", () => {
const differentKeys = [
"TEST-ant-1234567890",
"TEST-ant-abcdefghijklmnop",
"TEST-ant-test-key-with-dashes",
"sk-ant-1234567890",
"sk-ant-abcdefghijklmnop",
"sk-ant-test-key-with-dashes",
];
differentKeys.forEach((key) => {

View file

@ -0,0 +1,6 @@
// Stub for react-devtools-core to prevent errors when it's not installed
export default {
connectToDevTools: () => {
// No-op - devtools not available in production bundle
},
};

View file

@ -0,0 +1,184 @@
#!/usr/bin/env node
import { readFileSync, existsSync } from "fs";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
// Colors for output
const colors = {
green: "\x1b[32m",
red: "\x1b[31m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
reset: "\x1b[0m",
};
/**
* Parse the build.mjs file to extract defined aliases
*/
function getDefinedAliases() {
const buildPath = resolve(__dirname, "build.mjs");
const buildContent = readFileSync(buildPath, "utf8");
// Find the alias object in the build file
const aliasMatch = buildContent.match(/alias:\s*{([^}]+)}/s);
if (!aliasMatch) {
console.warn(`${colors.yellow}Warning: No aliases found in build.mjs${colors.reset}`);
return new Set();
}
// Extract package names from the alias definitions
// Split by lines and filter out comments
const aliasBlock = aliasMatch[1];
const lines = aliasBlock.split('\n');
const aliases = new Set();
for (const line of lines) {
// Skip commented lines
if (line.trim().startsWith('//')) {
continue;
}
// Look for package names in non-commented lines
// Match both @continuedev/* packages and simple package names like "core"
const packageMatch = line.match(/"(@continuedev\/[^"]+|[^"@\/]+)":/);
if (packageMatch) {
aliases.add(packageMatch[1]);
}
}
return aliases;
}
/**
* Find all local packages referenced with file: in package.json files
*/
function findLocalPackages(startPath, visited = new Set()) {
const localPackages = new Set();
function scanPackageJson(packageJsonPath, depth = 0) {
// Avoid infinite recursion
if (visited.has(packageJsonPath) || depth > 10) {
return;
}
visited.add(packageJsonPath);
if (!existsSync(packageJsonPath)) {
return;
}
try {
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
const packageDir = dirname(packageJsonPath);
// Check both dependencies and devDependencies
const allDeps = {
...packageJson.dependencies,
...packageJson.devDependencies,
};
for (const [depName, depVersion] of Object.entries(allDeps)) {
if (typeof depVersion === "string" && depVersion.startsWith("file:")) {
// This is a local package
localPackages.add(depName);
// Recursively check this package's dependencies
const depPath = resolve(packageDir, depVersion.replace("file:", ""));
const depPackageJson = resolve(depPath, "package.json");
if (existsSync(depPackageJson)) {
scanPackageJson(depPackageJson, depth + 1);
}
}
}
} catch (error) {
console.error(`${colors.red}Error reading ${packageJsonPath}: ${error.message}${colors.reset}`);
}
}
// Start from the CLI's package.json
scanPackageJson(startPath);
return localPackages;
}
/**
* Main validation function
*/
function validateAliases() {
console.log(`${colors.blue}🔍 Validating esbuild aliases...${colors.reset}\n`);
// Get defined aliases from build.mjs
const definedAliases = getDefinedAliases();
console.log(`Found ${definedAliases.size} aliases in build.mjs:`);
definedAliases.forEach(alias => {
console.log(` ✓ ${alias}`);
});
console.log();
// Find all local packages that need aliases
const cliPackageJson = resolve(__dirname, "package.json");
const localPackages = findLocalPackages(cliPackageJson);
console.log(`Found ${localPackages.size} local package dependencies:`);
localPackages.forEach(pkg => {
console.log(` • ${pkg}`);
});
console.log();
// Check for missing aliases
const missingAliases = [];
for (const pkg of localPackages) {
if (!definedAliases.has(pkg)) {
missingAliases.push(pkg);
}
}
// Check for unnecessary aliases (defined but not used)
const unnecessaryAliases = [];
for (const alias of definedAliases) {
if (!localPackages.has(alias)) {
unnecessaryAliases.push(alias);
}
}
// Report results
if (missingAliases.length > 0) {
console.log(`${colors.red}❌ Missing aliases (WILL CAUSE RUNTIME ERRORS):${colors.reset}`);
missingAliases.forEach(pkg => {
console.log(` ✗ ${pkg}`);
});
console.log();
console.log(`${colors.red}Add these to the alias section in build.mjs:${colors.reset}`);
missingAliases.forEach(pkg => {
const packageName = pkg.replace("@continuedev/", "").replace(/-/g, "_");
console.log(` "${pkg}": resolve(__dirname, "../../packages/${pkg.replace("@continuedev/", "")}/dist/index.js"),`);
});
console.log();
}
if (unnecessaryAliases.length > 0) {
console.log(`${colors.yellow}⚠️ Potentially unnecessary aliases:${colors.reset}`);
unnecessaryAliases.forEach(alias => {
console.log(` ? ${alias}`);
});
console.log();
}
// Exit with appropriate code
if (missingAliases.length > 0) {
console.log(`${colors.red}✗ Validation failed! Missing ${missingAliases.length} required alias(es).${colors.reset}`);
console.log(`${colors.red}This would cause runtime errors in the bundled CLI.${colors.reset}`);
process.exit(1);
} else if (unnecessaryAliases.length > 0) {
console.log(`${colors.yellow}✓ Validation passed with warnings.${colors.reset}`);
process.exit(0);
} else {
console.log(`${colors.green}✅ All aliases are correctly configured!${colors.reset}`);
process.exit(0);
}
}
// Run validation
validateAliases();

View file

@ -1,5 +1,5 @@
pluginGroup=com.github.continuedev.continueintellijextension
pluginVersion=1.0.39
pluginVersion=1.0.40
platformVersion=2024.1
kotlin.stdlib.default.dependency=false
org.gradle.configuration-cache=true

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.71",
"version": "1.1.79",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.71",
"version": "1.1.79",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../../packages/config-types",
@ -111,6 +111,11 @@
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@sentry/cli": "^2.50.2",
"@sentry/core": "^9.43.0",
"@sentry/esbuild-plugin": "^4.0.2",
"@sentry/node": "^9.43.0",
"@sentry/vite-plugin": "^4.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
@ -143,7 +148,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.104.0",
"openai": "^5.13.1",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.80",
"version": "1.1.83",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -122,6 +122,11 @@ export class NextEditWindowManager {
private editableRegionStartLine: number = 0;
private editableRegionEndLine: number = 0;
// State tracking for key reservation.
// By default it is set to free, and is only set to reserved when the transition is done.
private keyReservationState: "free" | "reserved" | "transitioning" = "free";
private latestOperationId = 0;
// Disposables
private disposables: vscode.Disposable[] = [];
@ -170,20 +175,71 @@ export class NextEditWindowManager {
this.loggingService = NextEditLoggingService.getInstance();
}
// This is an implementation of last-action-wins.
// For each action that fires setKeyReservation, it keeps its own operationId while incrementing latestOperationId.
// When an action completes, checking for operationId === latestOperationId will determine which one came last.
private async setKeyReservation(reserve: boolean): Promise<void> {
// Increment and capture this operation's ID.
const operationId = ++this.latestOperationId;
// Return early when already in desired state.
if (
(reserve && this.keyReservationState === "reserved") ||
(!reserve && this.keyReservationState === "free")
) {
return;
}
try {
await this.performKeyReservation(reserve);
// Only update state if we're still the latest operation.
if (operationId === this.latestOperationId) {
this.keyReservationState = reserve ? "reserved" : "free";
}
} catch (err) {
console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`);
// Only reset to free if we're still the latest operation.
if (operationId === this.latestOperationId) {
this.keyReservationState = "free";
}
throw err;
}
}
public async resetKeyReservation(): Promise<void> {
// Reset internal tracking.
this.keyReservationState = "free";
this.latestOperationId = 0;
// Ensure VS Code context matches.
try {
await this.performKeyReservation(false);
} catch (err) {
console.error(`Failed to reset nextEditWindowActive context: ${err}`);
}
}
private async performKeyReservation(reserve: boolean): Promise<void> {
try {
await vscode.commands.executeCommand(
"setContext",
"nextEditWindowActive",
reserve,
);
} catch (err) {
console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`);
throw err;
}
}
public static async reserveTabAndEsc() {
await vscode.commands.executeCommand(
"setContext",
"nextEditWindowActive",
true,
);
await NextEditWindowManager.getInstance().setKeyReservation(true);
}
public static async freeTabAndEsc() {
await vscode.commands.executeCommand(
"setContext",
"nextEditWindowActive",
false,
);
await NextEditWindowManager.getInstance().setKeyReservation(false);
}
/**
@ -202,7 +258,8 @@ export class NextEditWindowManager {
// Set nextEditWindowActive to false to free esc and tab,
// letting them return to their original behaviors.
await NextEditWindowManager.freeTabAndEsc();
await this.resetKeyReservation();
// await NextEditWindowManager.freeTabAndEsc();
// Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks.
this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => {
@ -353,14 +410,21 @@ export class NextEditWindowManager {
// Create and apply decoration with the text.
if (newEditRangeSlice !== "") {
await this.renderWindow(
editor,
currCursorPos,
oldEditRangeSlice,
newEditRangeSlice,
this.editableRegionStartLine,
diffLines,
);
try {
await this.renderWindow(
editor,
currCursorPos,
oldEditRangeSlice,
newEditRangeSlice,
this.editableRegionStartLine,
diffLines,
);
} catch (error) {
console.error("Failed to render window:", error);
// Clean up and reset state.
await this.hideAllNextEditWindows();
return;
}
}
const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
@ -368,14 +432,26 @@ export class NextEditWindowManager {
this.renderDeletions(editor, diffChars);
// Reserve tab and esc to either accept or reject the displayed next edit contents.
await NextEditWindowManager.reserveTabAndEsc();
try {
await NextEditWindowManager.reserveTabAndEsc();
} catch (err) {
console.error(
`Error reserving Tab/Esc after showing decorations: ${err}`,
);
await this.hideAllNextEditWindows();
return;
}
}
/**
* Hide all tooltips in all editors.
*/
public async hideAllNextEditWindows() {
await NextEditWindowManager.freeTabAndEsc();
try {
await NextEditWindowManager.freeTabAndEsc();
} catch (err) {
console.error(`Error freeing Tab/Esc while hiding: ${err}`);
}
if (this.currentDecoration) {
vscode.window.visibleTextEditors.forEach((editor) => {
@ -502,6 +578,10 @@ export class NextEditWindowManager {
* Dispose of the NextEditWindowManager.
*/
public dispose() {
void this.resetKeyReservation().catch((err) =>
console.error(`Failed to reset keys on dispose: ${err}`),
);
// Dispose current decoration.
if (this.currentDecoration) {
this.currentDecoration.dispose();

View file

@ -0,0 +1,970 @@
import {
afterEach,
beforeEach,
describe,
expect,
it,
MockedFunction,
vi,
} from "vitest";
// Mock all modules FIRST with inline factories (no external references)
vi.mock("vscode", () => ({
commands: {
executeCommand: vi.fn(),
registerCommand: vi.fn(),
},
window: {
activeTextEditor: undefined,
visibleTextEditors: [],
createTextEditorDecorationType: vi.fn(),
onDidChangeTextEditorSelection: vi.fn(() => ({ dispose: vi.fn() })),
onDidChangeVisibleTextEditors: vi.fn(() => ({ dispose: vi.fn() })),
onDidChangeActiveColorTheme: vi.fn(() => ({ dispose: vi.fn() })),
showInformationMessage: vi.fn(),
},
workspace: {
getConfiguration: vi.fn(() => ({
get: vi.fn((key: string) => {
const config: Record<string, any> = {
fontSize: 14,
fontFamily: "monospace",
showInlineTip: true,
};
return config[key];
}),
})),
onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })),
},
Position: class {
constructor(
public line: number,
public character: number,
) {}
},
Range: class {
constructor(
public start: any,
public end: any,
) {}
},
Selection: class {
constructor(
public anchor: any,
public active: any,
) {}
},
Uri: {
parse: vi.fn((str: string) => ({ toString: () => str, scheme: "file" })),
},
DecorationRangeBehavior: {
ClosedClosed: 1,
},
MarkdownString: class {
value: string = "";
isTrusted: boolean = false;
supportHtml: boolean = false;
constructor(value: string) {
this.value = value;
}
},
ExtensionContext: class {
subscriptions: any[] = [];
},
ViewColumn: {
One: 1,
Two: 2,
},
}));
vi.mock("core/control-plane/env", () => ({
EXTENSION_NAME: "continue",
}));
vi.mock("../util/getTheme", () => ({
getThemeString: vi.fn(() => "dark"),
}));
vi.mock("core/codeRenderer/CodeRenderer", () => ({
CodeRenderer: {
getInstance: vi.fn(() => ({
setTheme: vi.fn(),
getDataUri: vi.fn().mockResolvedValue("data:image/svg+xml;base64,mock"),
})),
},
}));
vi.mock("core/nextEdit/NextEditProvider", () => ({
NextEditProvider: {
getInstance: vi.fn(() => ({
deleteChain: vi.fn(),
})),
},
}));
vi.mock("core/nextEdit/NextEditLoggingService", () => ({
NextEditLoggingService: {
getInstance: vi.fn(() => ({
cancelRejectionTimeout: vi.fn(),
cancelRejectionTimeoutButKeepCompletionId: vi.fn(),
})),
},
}));
vi.mock("core/diff/myers", () => ({
myersCharDiff: vi.fn(() => []),
}));
vi.mock("core/nextEdit/diff/diff", () => ({
getOffsetPositionAtLastNewLine: vi.fn(() => ({ line: 0, character: 0 })),
}));
// Import after mocks are set up
import * as vscode from "vscode";
import {
ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
HIDE_NEXT_EDIT_SUGGESTION_COMMAND,
NextEditWindowManager,
} from "./NextEditWindowManager";
const mockVscode = vi.mocked(vscode);
describe("NextEditWindowManager", () => {
let manager: NextEditWindowManager;
let mockEditor: any;
let mockDocument: any;
let mockContext: any;
beforeEach(() => {
vi.clearAllMocks();
// Clear singleton instance
NextEditWindowManager.clearInstance();
// Create mock document
mockDocument = {
uri: { toString: () => "file:///test.ts", scheme: "file" },
version: 1,
lineCount: 10,
lineAt: vi.fn((line: number) => ({
text: `line ${line} content`,
range: new mockVscode.Range(
new mockVscode.Position(line, 0),
new mockVscode.Position(line, 20),
),
})),
};
// Create mock editor
mockEditor = {
document: mockDocument,
selection: {
active: new mockVscode.Position(0, 0),
},
setDecorations: vi.fn(),
edit: vi.fn((callback: any) => {
callback({
replace: vi.fn(),
delete: vi.fn(),
});
return Promise.resolve(true);
}),
};
// Create mock context
mockContext = {
subscriptions: [],
};
// Setup default mock implementations
(
mockVscode.commands.executeCommand as MockedFunction<any>
).mockResolvedValue(undefined);
(mockVscode.commands.registerCommand as MockedFunction<any>)
//@ts-ignore
.mockImplementation((command: string, callback: any) => ({
dispose: vi.fn(),
}));
(
mockVscode.window.createTextEditorDecorationType as MockedFunction<any>
).mockReturnValue({
dispose: vi.fn(),
});
// Get manager instance
manager = NextEditWindowManager.getInstance();
});
afterEach(() => {
NextEditWindowManager.clearInstance();
});
describe("Singleton Pattern", () => {
it("should return the same instance", () => {
const instance1 = NextEditWindowManager.getInstance();
const instance2 = NextEditWindowManager.getInstance();
expect(instance1).toBe(instance2);
});
it("should properly clear instance", () => {
const instance1 = NextEditWindowManager.getInstance();
NextEditWindowManager.clearInstance();
const instance2 = NextEditWindowManager.getInstance();
expect(instance1).not.toBe(instance2);
});
});
describe("Key Reservation State Management", () => {
beforeEach(async () => {
await manager.setupNextEditWindowManager(mockContext);
});
it("should start with keys in free state", () => {
expect(manager["keyReservationState"]).toBe("free");
});
it("should reserve keys when showing window", async () => {
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(0, 0),
0,
0,
"old",
"new",
[],
);
expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith(
"setContext",
"nextEditWindowActive",
true,
);
expect(manager["keyReservationState"]).toBe("reserved");
});
it("should free keys when hiding windows", async () => {
// First show a window
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(0, 0),
0,
0,
"old",
"new",
[],
);
// Then hide it
await manager.hideAllNextEditWindows();
expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith(
"setContext",
"nextEditWindowActive",
false,
);
expect(manager["keyReservationState"]).toBe("free");
});
it("should handle sequential reserve/free operations", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await NextEditWindowManager.reserveTabAndEsc();
expect(manager["keyReservationState"]).toBe("reserved");
await NextEditWindowManager.freeTabAndEsc();
expect(manager["keyReservationState"]).toBe("free");
await NextEditWindowManager.reserveTabAndEsc();
expect(manager["keyReservationState"]).toBe("reserved");
// Should have been called 3 times + 1 from beforeEach
expect(executeCommand).toHaveBeenCalledTimes(4);
});
it("should skip redundant reserve operations", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await NextEditWindowManager.reserveTabAndEsc();
executeCommand.mockClear();
// Try to reserve again
await NextEditWindowManager.reserveTabAndEsc();
// Should not have called executeCommand again
expect(executeCommand).not.toHaveBeenCalled();
expect(manager["keyReservationState"]).toBe("reserved");
});
it("should skip redundant free operations", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
executeCommand.mockClear();
// Already free, try to free again
await NextEditWindowManager.freeTabAndEsc();
// Should not have called executeCommand
expect(executeCommand).not.toHaveBeenCalled();
expect(manager["keyReservationState"]).toBe("free");
});
});
describe("Race Condition Prevention", () => {
beforeEach(async () => {
await manager.setupNextEditWindowManager(mockContext);
});
it("should handle concurrent operations with random delays and last-write-wins", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
let completedOperations: string[] = [];
// Reset key reservation to ensure clean state
await manager.resetKeyReservation();
// Start from reserved state so first free() will proceed
manager["keyReservationState"] = "reserved";
executeCommand.mockClear();
// Make executeCommand take random time and track completions
executeCommand.mockImplementation((cmd, key, value) => {
const operationId = `${value ? "reserve" : "free"}-${Date.now()}-${Math.random()}`;
return new Promise((resolve) => {
setTimeout(() => {
completedOperations.push(operationId);
// Immediately update state to ensure next operation proceeds
// This simulates fast state changes
manager["keyReservationState"] = value ? "reserved" : "free";
resolve(undefined);
}, Math.random() * 50);
});
});
// Fire multiple operations concurrently
const operations = [
NextEditWindowManager.reserveTabAndEsc(), // operation 1: reserve (skipped - already reserved)
NextEditWindowManager.freeTabAndEsc(), // operation 2: free (proceeds)
NextEditWindowManager.reserveTabAndEsc(), // operation 3: reserve (proceeds after 2 completes)
NextEditWindowManager.freeTabAndEsc(), // operation 4: free (proceeds after 3 completes)
];
await Promise.all(operations);
// Count how many actually proceeded (those that didn't early return)
const actualCalls = executeCommand.mock.calls.length;
// The state should match the last operation's intent
// But the actual number of calls depends on timing and early returns
expect(manager["latestOperationId"]).toBeGreaterThanOrEqual(actualCalls);
});
it("should ignore stale operations", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await manager.resetKeyReservation();
executeCommand.mockClear();
// Create deferred promises with guaranteed resolvers
const createDeferred = () => {
let resolve: Function;
const promise = new Promise((res) => {
resolve = res;
});
return { promise, resolve: resolve! };
};
const deferred1 = createDeferred();
const deferred2 = createDeferred();
// Control when each operation completes
executeCommand
.mockImplementationOnce(() => deferred1.promise)
.mockImplementationOnce(() => deferred2.promise);
// Start operations
const op1 = NextEditWindowManager.reserveTabAndEsc();
const op2 = NextEditWindowManager.freeTabAndEsc();
// Complete op2 first (even though op1 started first)
deferred2.resolve(undefined);
await op2;
// State should be free (from op2)
expect(manager["keyReservationState"]).toBe("free");
expect(manager["latestOperationId"]).toBe(2);
// Now complete op1 (should be ignored as stale)
deferred1.resolve(undefined);
await op1;
// State should still be free (op1 was ignored)
expect(manager["keyReservationState"]).toBe("free");
expect(manager["latestOperationId"]).toBe(2);
});
it("should handle rapid fire operations correctly (loop)", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await manager.resetKeyReservation();
executeCommand.mockClear();
// Make operations instant
executeCommand.mockResolvedValue(undefined);
// Fire many operations rapidly
const operations = [];
for (let i = 0; i < 20; i++) {
operations.push(
i % 2 === 0
? NextEditWindowManager.reserveTabAndEsc()
: NextEditWindowManager.freeTabAndEsc(),
);
}
await Promise.all(operations);
// Last operation (i=19) was free (odd number)
expect(manager["keyReservationState"]).toBe("free");
expect(manager["latestOperationId"]).toBe(20);
});
it("should handle alternating reserve/free with delays", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await manager.resetKeyReservation();
executeCommand.mockClear();
// Track actual VS Code context values set
const contextValues: boolean[] = [];
executeCommand.mockImplementation((cmd, key, value) => {
if (cmd === "setContext") {
//@ts-ignore
contextValues.push(value);
}
return Promise.resolve(undefined);
});
// Alternating operations
await NextEditWindowManager.reserveTabAndEsc();
expect(manager["keyReservationState"]).toBe("reserved");
await NextEditWindowManager.freeTabAndEsc();
expect(manager["keyReservationState"]).toBe("free");
await NextEditWindowManager.reserveTabAndEsc();
expect(manager["keyReservationState"]).toBe("reserved");
// Check that context was set correctly each time
expect(contextValues).toEqual([true, false, true]);
});
it("should handle rapid alternations correctly", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await manager.resetKeyReservation();
executeCommand.mockClear();
// Track all setContext calls
const contextCalls: boolean[] = [];
executeCommand.mockImplementation((cmd, key, value) => {
if (cmd === "setContext" && key === "nextEditWindowActive") {
//@ts-ignore
contextCalls.push(value);
}
return Promise.resolve();
});
// Simulate rapid SEQUENTIAL user interactions:
// These need to be sequential to ensure state changes between calls
await NextEditWindowManager.reserveTabAndEsc(); // free -> reserved
await NextEditWindowManager.freeTabAndEsc(); // reserved -> free
await NextEditWindowManager.reserveTabAndEsc(); // free -> reserved
await NextEditWindowManager.freeTabAndEsc(); // reserved -> free
// Should end in free state (last operation)
expect(manager["keyReservationState"]).toBe("free");
// Should have made all 4 calls since state alternates
expect(contextCalls).toEqual([true, false, true, false]);
});
it("should handle concurrent duplicate operations efficiently", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await manager.resetKeyReservation();
executeCommand.mockClear();
// Track all setContext calls
const contextCalls: boolean[] = [];
executeCommand.mockImplementation((cmd, key, value) => {
if (cmd === "setContext" && key === "nextEditWindowActive") {
//@ts-ignore
contextCalls.push(value);
}
return Promise.resolve();
});
// When multiple reserve operations happen concurrently (e.g., multiple completions)
// Only the first should actually make the call
const operations = [
NextEditWindowManager.reserveTabAndEsc(),
NextEditWindowManager.reserveTabAndEsc(),
NextEditWindowManager.reserveTabAndEsc(),
];
await Promise.all(operations);
// Should have made only the necessary calls
// Since all start with state "free", all will proceed to call setContext
// This is because they all check state before any completes
expect(contextCalls.length).toBeGreaterThan(0);
expect(manager["keyReservationState"]).toBe("reserved");
// All calls should be trying to reserve (true)
expect(contextCalls.every((call) => call === true)).toBe(true);
});
it("should handle truly concurrent mixed operations", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await manager.resetKeyReservation();
// Start in reserved state
await NextEditWindowManager.reserveTabAndEsc();
executeCommand.mockClear();
// Track all setContext calls
const contextCalls: boolean[] = [];
executeCommand.mockImplementation((cmd, key, value) => {
if (cmd === "setContext" && key === "nextEditWindowActive") {
//@ts-ignore
contextCalls.push(value);
// Add small delay to simulate real async behavior
return new Promise((resolve) => setTimeout(resolve, 5));
}
return Promise.resolve();
});
// Mix of operations starting from "reserved" state
const operations = [
NextEditWindowManager.freeTabAndEsc(), // Will proceed (reserved -> free)
NextEditWindowManager.freeTabAndEsc(), // Will proceed (checks while first is in flight)
NextEditWindowManager.reserveTabAndEsc(), // Will proceed (different operation)
];
await Promise.all(operations);
// The last operation to complete wins (but order is non-deterministic)
// State should be either "free" or "reserved" depending on completion order
expect(["free", "reserved"]).toContain(manager["keyReservationState"]);
// Should have made at least some calls
expect(contextCalls.length).toBeGreaterThan(0);
});
it("should maintain correct state with stale operations", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
await manager.resetKeyReservation();
executeCommand.mockClear();
// Create a controlled execution order
let resolveFirst: () => void;
let resolveSecond: () => void;
const firstPromise = new Promise<void>((resolve) => {
resolveFirst = resolve;
});
const secondPromise = new Promise<void>((resolve) => {
resolveSecond = resolve;
});
executeCommand
.mockImplementationOnce(() => firstPromise)
.mockImplementationOnce(() => secondPromise);
// Start operations
const op1 = NextEditWindowManager.reserveTabAndEsc();
const op2 = NextEditWindowManager.freeTabAndEsc();
// Complete second operation first (out of order)
resolveSecond!();
await op2;
// State should be free (last operation to start, even though it completed first)
expect(manager["keyReservationState"]).toBe("free");
// Complete first operation
resolveFirst!();
await op1;
// State should still be free (op1 was stale)
expect(manager["keyReservationState"]).toBe("free");
});
});
describe("Error Recovery", () => {
beforeEach(async () => {
await manager.setupNextEditWindowManager(mockContext);
});
it("should recover from failed key reservation", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
// Make reservation fail
executeCommand.mockRejectedValueOnce(new Error("VS Code busy"));
await expect(NextEditWindowManager.reserveTabAndEsc()).rejects.toThrow(
"VS Code busy",
);
// State should reset to free
expect(manager["keyReservationState"]).toBe("free");
// Should be able to try again
executeCommand.mockResolvedValueOnce(undefined);
await NextEditWindowManager.reserveTabAndEsc();
expect(manager["keyReservationState"]).toBe("reserved");
});
it("should recover from failed key freeing", async () => {
const executeCommand = mockVscode.commands
.executeCommand as MockedFunction<any>;
// First reserve successfully
await NextEditWindowManager.reserveTabAndEsc();
expect(manager["keyReservationState"]).toBe("reserved");
// Make freeing fail
executeCommand.mockRejectedValueOnce(new Error("VS Code busy"));
await expect(NextEditWindowManager.freeTabAndEsc()).rejects.toThrow(
"VS Code busy",
);
// State should still reset to free (safety mechanism)
expect(manager["keyReservationState"]).toBe("free");
});
it("should handle decoration creation failure", async () => {
const createDecoration = mockVscode.window
.createTextEditorDecorationType as MockedFunction<any>;
createDecoration.mockImplementationOnce(() => {
throw new Error("Failed to create decoration");
});
// Should not throw, but should clean up
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(0, 0),
0,
0,
"old",
"new",
[],
);
// Keys should be freed due to error
expect(manager["keyReservationState"]).toBe("free");
expect(manager["currentDecoration"]).toBeNull();
});
});
describe("Command Registration", () => {
it("should register hide command", async () => {
await manager.setupNextEditWindowManager(mockContext);
expect(mockVscode.commands.registerCommand).toHaveBeenCalledWith(
HIDE_NEXT_EDIT_SUGGESTION_COMMAND,
expect.any(Function),
);
});
it("should register accept command", async () => {
await manager.setupNextEditWindowManager(mockContext);
expect(mockVscode.commands.registerCommand).toHaveBeenCalledWith(
ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
expect.any(Function),
);
});
it("should handle command registration failure gracefully", async () => {
const registerCommand = mockVscode.commands
.registerCommand as MockedFunction<any>;
registerCommand.mockImplementationOnce(() => {
throw new Error("Command already registered");
});
// Should not throw
await expect(
manager.setupNextEditWindowManager(mockContext),
).resolves.not.toThrow();
});
});
describe("Window Management", () => {
beforeEach(async () => {
await manager.setupNextEditWindowManager(mockContext);
});
it("should store tooltip text when showing window", async () => {
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(0, 0),
0,
2,
"old code",
"new code",
[],
);
expect(manager["currentTooltipText"]).toBe("new code");
expect(manager["activeEditor"]).toBe(mockEditor);
});
it("should clear tooltip text when hiding windows", async () => {
// Show first
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(0, 0),
0,
2,
"old",
"new",
[],
);
// Then hide
await manager.hideAllNextEditWindows();
expect(manager["currentTooltipText"]).toBeNull();
expect(manager["activeEditor"]).toBeNull();
});
it("should handle line deletion case", async () => {
mockEditor.document.lineAt = vi.fn((lineNumber: number) => ({
text: "line to delete",
}));
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(1, 0),
1,
1,
"line to delete",
"", // Empty means deletion
[{ type: "old", line: "line to delete" }],
);
expect(manager["isLineDelete"]).toBe(true);
// Final cursor should be at end of previous line
expect(manager["finalCursorPos"]?.line).toBe(0);
});
it("should skip rendering for excluded URIs", async () => {
mockEditor.document.uri = {
toString: () => "output://test",
scheme: "output",
};
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(0, 0),
0,
0,
"old",
"new",
[],
);
// Should not create decoration for excluded URI
expect(
mockVscode.window.createTextEditorDecorationType,
).not.toHaveBeenCalled();
expect(manager["currentDecoration"]).toBeNull();
});
});
describe("Accept/Reject Flow", () => {
beforeEach(async () => {
await manager.setupNextEditWindowManager(mockContext);
});
it("should apply text when accepting", async () => {
// Show window first
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(0, 0),
0,
0,
"old",
"new text",
[],
);
// Get the accept command callback
const registerCalls = (
mockVscode.commands.registerCommand as MockedFunction<any>
).mock.calls;
const acceptCall = registerCalls.find(
(call) => call[0] === ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
);
//@ts-ignore
const acceptCallback = acceptCall[1];
// Call accept
//@ts-ignore
await acceptCallback();
// Should have called edit
expect(mockEditor.edit).toHaveBeenCalled();
// Should have cleared the decoration
expect(manager["currentTooltipText"]).toBeNull();
expect(manager["keyReservationState"]).toBe("free");
});
it("should not accept when no active window", async () => {
// Get the accept command callback
const registerCalls = (
mockVscode.commands.registerCommand as MockedFunction<any>
).mock.calls;
const acceptCall = registerCalls.find(
(call) => call[0] === ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
);
//@ts-ignore
const acceptCallback = acceptCall[1];
// Call accept without showing window
//@ts-ignore
await acceptCallback();
// Should not have called edit
expect(mockEditor.edit).not.toHaveBeenCalled();
});
it("should hide window when rejecting", async () => {
// Show window first
await manager.showNextEditWindow(
mockEditor,
new mockVscode.Position(0, 0),
0,
0,
"old",
"new",
[],
);
// Get the hide command callback
const registerCalls = (
mockVscode.commands.registerCommand as MockedFunction<any>
).mock.calls;
const hideCall = registerCalls.find(
(call) => call[0] === HIDE_NEXT_EDIT_SUGGESTION_COMMAND,
);
//@ts-ignore
const hideCallback = hideCall[1];
// Call hide
//@ts-ignore
await hideCallback();
// Should have cleared everything
expect(manager["currentTooltipText"]).toBeNull();
expect(manager["activeEditor"]).toBeNull();
expect(manager["keyReservationState"]).toBe("free");
});
});
describe("Disposal", () => {
it("should free keys on disposal", async () => {
await manager.setupNextEditWindowManager(mockContext);
// Reserve keys first
await NextEditWindowManager.reserveTabAndEsc();
expect(manager["keyReservationState"]).toBe("reserved");
// Dispose
manager.dispose();
// Should attempt to free keys
expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith(
"setContext",
"nextEditWindowActive",
false,
);
});
it("should dispose decorations on disposal", async () => {
await manager.setupNextEditWindowManager(mockContext);
const mockDecoration = { dispose: vi.fn() };
const mockDisposable1 = { dispose: vi.fn() };
const mockDisposable2 = { dispose: vi.fn() };
manager["currentDecoration"] = mockDecoration as any;
manager["disposables"] = [mockDisposable1, mockDisposable2];
manager.dispose();
expect(mockDecoration.dispose).toHaveBeenCalled();
expect(mockDisposable1.dispose).toHaveBeenCalled();
expect(mockDisposable2.dispose).toHaveBeenCalled();
});
});
describe("Configuration Changes", () => {
it("should update on theme change", async () => {
await manager.setupNextEditWindowManager(mockContext);
// Get the configuration change listener
const onDidChange = mockVscode.workspace
.onDidChangeConfiguration as MockedFunction<any>;
const changeCallback = onDidChange.mock.calls[0][0];
// Simulate theme change
//@ts-ignore
await changeCallback({
affectsConfiguration: (key: string) => key === "workbench.colorTheme",
});
// Should have updated theme
const { getThemeString } = await import("../util/getTheme");
expect(getThemeString).toHaveBeenCalled();
});
it("should update on font size change", async () => {
await manager.setupNextEditWindowManager(mockContext);
const onDidChange = mockVscode.workspace
.onDidChangeConfiguration as MockedFunction<any>;
const changeCallback = onDidChange.mock.calls[0][0];
// Change font size
(
mockVscode.workspace.getConfiguration as MockedFunction<any>
).mockReturnValueOnce({
get: (key: string) => (key === "fontSize" ? 16 : "monospace"),
});
//@ts-ignore
await changeCallback({
affectsConfiguration: (key: string) => key === "editor.fontSize",
});
expect(manager["fontSize"]).toBe(16);
});
});
});

View file

@ -50,45 +50,36 @@ export class ApplyManager {
toolCallId,
});
try {
const hasExistingDocument = !!activeTextEditor.document.getText().trim();
const hasExistingDocument = !!activeTextEditor.document.getText().trim();
if (hasExistingDocument) {
// Currently `isSearchAndReplace` will always provide a full file rewrite
// as the contents of `text`, so we can just instantly apply
if (isSearchAndReplace) {
const diffLinesGenerator = generateLines(
myersDiff(activeTextEditor.document.getText(), text),
);
if (hasExistingDocument) {
// Currently `isSearchAndReplace` will always provide a full file rewrite
// as the contents of `text`, so we can just instantly apply
if (isSearchAndReplace) {
const diffLinesGenerator = generateLines(
myersDiff(activeTextEditor.document.getText(), text),
);
await this.verticalDiffManager.streamDiffLines(
diffLinesGenerator,
true,
streamId,
toolCallId,
);
} else {
await this.handleExistingDocument(
activeTextEditor,
text,
streamId,
toolCallId,
);
}
await this.verticalDiffManager.streamDiffLines(
diffLinesGenerator,
true,
streamId,
toolCallId,
);
} else {
await this.handleEmptyDocument(
await this.handleExistingDocument(
activeTextEditor,
text,
streamId,
toolCallId,
);
}
} finally {
await this.webviewProtocol.request("updateApplyState", {
} else {
await this.handleEmptyDocument(
activeTextEditor,
text,
streamId,
status: "done",
toolCallId,
});
);
}
}

129
gui/package-lock.json generated
View file

@ -148,7 +148,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"iconv-lite": "^0.6.3",
"ignore": "^5.3.1",
"ignore": "^7.0.5",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
@ -5094,6 +5094,20 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@ -6257,6 +6271,21 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
@ -6374,13 +6403,11 @@
}
},
"node_modules/es-define-property": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz",
"integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==",
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"dev": true,
"dependencies": {
"get-intrinsic": "^1.2.4"
},
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
@ -6421,10 +6448,11 @@
}
},
"node_modules/es-object-atoms": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz",
"integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==",
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
@ -6433,14 +6461,16 @@
}
},
"node_modules/es-set-tostringtag": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz",
"integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==",
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"dev": true,
"license": "MIT",
"dependencies": {
"get-intrinsic": "^1.2.4",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.1"
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
@ -7371,13 +7401,16 @@
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"dev": true,
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@ -7468,16 +7501,22 @@
}
},
"node_modules/get-intrinsic": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz",
"integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==",
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"has-proto": "^1.0.1",
"has-symbols": "^1.0.3",
"hasown": "^2.0.0"
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
@ -7486,6 +7525,20 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"dev": true,
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/get-stream": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz",
@ -7568,12 +7621,13 @@
}
},
"node_modules/gopd": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz",
"integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==",
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"dev": true,
"dependencies": {
"get-intrinsic": "^1.1.3"
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
@ -7688,10 +7742,11 @@
}
},
"node_modules/has-symbols": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz",
"integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==",
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
@ -9430,6 +9485,16 @@
"node": ">= 20"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/mdast-util-definitions": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/mdast-util-definitions/-/mdast-util-definitions-4.0.0.tgz",

View file

@ -6,7 +6,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger";
type SectionKey = Exclude<
keyof ConfigYaml,
"name" | "version" | "schema" | "metadata"
"name" | "version" | "schema" | "metadata" | "env"
>;
interface EditBlockButtonProps<T extends SectionKey> {
@ -42,10 +42,10 @@ export default function EditBlockButton<T extends SectionKey>({
element: { sourceFile },
});
} else if (block && isUsesBlock(block)) {
openUrl(`${block.uses}/new-version`);
void openUrl(`${block.uses}/new-version`);
} else if (selectedProfile?.fullSlug) {
const slug = `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}`;
openUrl(`${slug}/new-version`);
void openUrl(`${slug}/new-version`);
}
};

View file

@ -1,14 +1,10 @@
import { useCallback, useContext, useEffect, useRef } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { FromCoreProtocol } from "core/protocol";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { setConfigLoading, setConfigResult } from "../redux/slices/configSlice";
import {
setLastNonEditSessionEmpty,
updateEditStateApplyState,
} from "../redux/slices/editState";
import { setLastNonEditSessionEmpty } from "../redux/slices/editState";
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import {
initializeProfilePreferences,
@ -17,27 +13,21 @@ import {
setSelectedProfile,
} from "../redux/slices/profilesSlice";
import {
acceptToolCall,
addContextItemsAtIndex,
setHasReasoningEnabled,
setIsSessionMetadataLoading,
updateApplyState,
} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
import { exitEdit } from "../redux/thunks/edit";
import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfterToolCall";
import { store } from "../redux/store";
import { cancelStream } from "../redux/thunks/cancelStream";
import { handleApplyStateUpdate } from "../redux/thunks/handleApplyStateUpdate";
import { refreshSessionMetadata } from "../redux/thunks/session";
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
import { findToolCallById, logToolUsage } from "../redux/util";
import {
setDocumentStylesFromLocalStorage,
setDocumentStylesFromTheme,
} from "../styles/theme";
import { isJetBrains } from "../util";
import { logAgentModeEditOutcome } from "../util/editOutcomeLogger";
import { setLocalStorage } from "../util/localStorage";
import { migrateLocalStorage } from "../util/migrateLocalStorage";
import { useWebviewListener } from "./useWebviewListener";
@ -51,9 +41,7 @@ function ParallelListeners() {
(store) => store.profiles.selectedProfileId,
);
const hasDoneInitialConfigLoad = useRef(false);
const autoAcceptEditToolDiffs = useAppSelector(
(store) => store.config.config.ui?.autoAcceptEditToolDiffs,
);
// Load symbols for chat on any session change
const sessionId = useAppSelector((state) => state.session.id);
@ -235,83 +223,9 @@ function ParallelListeners() {
useWebviewListener(
"updateApplyState",
async (state) => {
if (state.streamId === EDIT_MODE_STREAM_ID) {
dispatch(updateEditStateApplyState(state));
if (state.status === "closed") {
const toolCallState = findToolCallById(
store.getState().session.history,
state.toolCallId!,
);
if (toolCallState) {
logToolUsage(toolCallState, true, true, ideMessenger);
}
void dispatch(exitEdit({}));
}
} else {
// chat or agent
dispatch(updateApplyState(state));
// Handle apply status updates - use toolCallId from event payload
if (state.toolCallId) {
if (state.status === "done" && autoAcceptEditToolDiffs) {
ideMessenger.post("acceptDiff", {
streamId: state.streamId,
filepath: state.filepath,
});
}
if (state.status === "closed") {
// Find the tool call to check if it was canceled
const toolCallState = findToolCallById(
store.getState().session.history,
state.toolCallId,
);
if (toolCallState) {
const accepted = toolCallState.status !== "canceled";
logToolUsage(toolCallState, accepted, true, ideMessenger);
// Log edit outcome for Agent Mode
const applyState = store
.getState()
.session.codeBlockApplyStates.states.find(
(s) => s.streamId === state.streamId,
);
if (applyState) {
void logAgentModeEditOutcome(
toolCallState,
applyState,
accepted,
ideMessenger,
);
}
if (accepted) {
dispatch(
acceptToolCall({
toolCallId: state.toolCallId,
}),
);
void dispatch(
streamResponseAfterToolCall({
toolCallId: state.toolCallId,
}),
);
}
}
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
// dispatch(setToolCallOutput([]));
}
}
}
void dispatch(handleApplyStateUpdate(state));
},
[autoAcceptEditToolDiffs, ideMessenger],
[],
);
useEffect(() => {

View file

@ -1,19 +1,16 @@
import { BuiltInToolNames } from "core/tools/builtIn";
import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar";
import {
addAndSelectMockLlm,
triggerConfigUpdate,
} from "../../../util/test/config";
import { renderWithProviders } from "../../../util/test/render";
import { Chat } from "../Chat";
import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar";
import { waitFor } from "@testing-library/dom";
import { act } from "@testing-library/react";
import { ChatMessage } from "core";
import {
setToolPolicy,
toggleToolSetting,
} from "../../../redux/slices/uiSlice";
import { setToolPolicy } from "../../../redux/slices/uiSlice";
import {
getElementByTestId,
getElementByText,
@ -63,6 +60,7 @@ test(
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
const messengerRequestSpy = vi.spyOn(ideMessenger, "request");
addAndSelectMockLlm(store, ideMessenger);
@ -92,7 +90,7 @@ test(
// Tool call, check that applyToFile was called for edit
await waitFor(() => {
expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", {
streamId: expect.any(String),
filepath: EDIT_FILE_URI,
text: EDIT_CHANGES,
@ -101,7 +99,7 @@ test(
});
// Extract stream ID and initiate mock streaming
const streamId = messengerPostSpy.mock.calls.find(
const streamId = messengerRequestSpy.mock.calls.find(
(call) => call[0] === "applyToFile",
)?.[1]?.streamId;
expect(streamId).toBeDefined();
@ -172,6 +170,7 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => {
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
const messengerRequestSpy = vi.spyOn(ideMessenger, "request");
addAndSelectMockLlm(store, ideMessenger);
@ -219,7 +218,7 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => {
);
// Tool call, check that applyToFile was called for edit
await waitFor(() => {
expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", {
streamId: expect.any(String),
filepath: EDIT_FILE_URI,
text: EDIT_CHANGES,
@ -228,7 +227,7 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => {
});
// Extract stream ID and initiate mock streaming
const streamId = messengerPostSpy.mock.calls.find(
const streamId = messengerRequestSpy.mock.calls.find(
(call) => call[0] === "applyToFile",
)?.[1]?.streamId;
expect(streamId).toBeDefined();

View file

@ -0,0 +1,153 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { ApplyState } from "core";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { logAgentModeEditOutcome } from "../../util/editOutcomeLogger";
import {
selectApplyStateByToolCallId,
selectToolCallById,
} from "../selectors/selectToolCalls";
import { updateEditStateApplyState } from "../slices/editState";
import {
acceptToolCall,
errorToolCall,
updateApplyState,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCallById, logToolUsage } from "../util";
import { exitEdit } from "./edit";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export const handleApplyStateUpdate = createAsyncThunk<
void,
ApplyState,
ThunkApiType
>(
"apply/handleStateUpdate",
async (applyState, { dispatch, getState, extra }) => {
if (applyState.streamId === EDIT_MODE_STREAM_ID) {
dispatch(updateEditStateApplyState(applyState));
if (applyState.status === "closed") {
const toolCallState = findToolCallById(
getState().session.history,
applyState.toolCallId!,
);
if (toolCallState) {
logToolUsage(toolCallState, true, true, extra.ideMessenger);
}
void dispatch(exitEdit({}));
}
} else {
// chat or agent
dispatch(updateApplyState(applyState));
// Handle apply status updates - use toolCallId from event payload
if (applyState.toolCallId) {
if (
applyState.status === "done" &&
getState().config.config?.ui?.autoAcceptEditToolDiffs
) {
extra.ideMessenger.post("acceptDiff", {
streamId: applyState.streamId,
filepath: applyState.filepath,
});
}
if (applyState.status === "closed") {
// Find the tool call to check if it was canceled
const toolCallState = findToolCallById(
getState().session.history,
applyState.toolCallId,
);
if (toolCallState) {
const accepted = toolCallState.status !== "canceled";
logToolUsage(toolCallState, accepted, true, extra.ideMessenger);
// Log edit outcome for Agent Mode
const newApplyState =
getState().session.codeBlockApplyStates.states.find(
(s) => s.streamId === applyState.streamId,
);
const newState = getState();
if (newApplyState) {
void logAgentModeEditOutcome(
newState.session.history,
newState.config.config,
toolCallState,
newApplyState,
accepted,
extra.ideMessenger,
);
}
if (accepted) {
if (toolCallState.status !== "errored") {
dispatch(
acceptToolCall({
toolCallId: applyState.toolCallId,
}),
);
}
void dispatch(
streamResponseAfterToolCall({
toolCallId: applyState.toolCallId,
}),
);
}
}
// TODO return output from edit tools so the model knows the result
}
}
}
},
);
export const handleEditToolApplyError = createAsyncThunk<
void,
{ toolCallId: string },
ThunkApiType
>(
"apply/handleEditError",
async ({ toolCallId }, { dispatch, getState, extra }) => {
const state = getState();
const toolCallState = selectToolCallById(state, toolCallId);
const applyState = selectApplyStateByToolCallId(state, toolCallId);
if (
toolCallState &&
applyState &&
applyState.status !== "closed" &&
toolCallState.status === "calling"
) {
dispatch(
errorToolCall({
toolCallId,
}),
);
dispatch(
updateToolCallOutput({
toolCallId,
contextItems: [
{
icon: "problems",
name: "Apply Error",
description: "Failed to apply changes",
content: `Error editing file: failed to apply changes to file.\n\nPlease try again with correct args or notify the user and request further instructions.`,
hidden: false,
},
],
}),
);
void dispatch(
handleApplyStateUpdate({
status: "closed",
streamId: applyState.streamId,
toolCallId,
}),
);
}
},
);

View file

@ -1,5 +1,7 @@
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { v4 as uuid } from "uuid";
import { updateApplyState } from "../../redux/slices/sessionSlice";
import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
export const editToolImpl: ClientToolImpl = async (
args,
@ -19,13 +21,29 @@ export const editToolImpl: ClientToolImpl = async (
throw new Error(`${args.filepath} does not exist`);
}
const streamId = uuid();
extras.ideMessenger.post("applyToFile", {
streamId,
text: args.changes,
toolCallId,
filepath: firstUriMatch,
});
extras.dispatch(
updateApplyState({
streamId,
toolCallId,
status: "not-started",
}),
);
void extras.ideMessenger
.request("applyToFile", {
streamId,
text: args.changes,
toolCallId,
filepath: firstUriMatch,
})
.then((res) => {
if (res.status === "error") {
void extras.dispatch(
handleEditToolApplyError({
toolCallId,
}),
);
}
});
return {
respondImmediately: false,
output: undefined, // No immediate output.

View file

@ -581,32 +581,6 @@ keep this too`;
),
).rejects.toThrow("Failed to apply search and replace: File read error");
});
it("should handle applyToFile errors", async () => {
mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
mockParseAllSearchReplaceBlocks.mockReturnValue([
{
isComplete: true,
searchContent: "content",
replaceContent: "replacement",
},
]);
mockIdeMessenger.ide.readFile.mockResolvedValue("content");
mockFindSearchMatch.mockReturnValue({
startIndex: 0,
endIndex: 7,
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed"));
await expect(
searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
),
).rejects.toThrow("Failed to apply search and replace: Apply failed");
});
});
describe("edge cases", () => {

View file

@ -3,6 +3,8 @@ import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSea
import { resolveRelativePathInDir } from "core/util/ideUtils";
import posthog from "posthog-js";
import { v4 as uuid } from "uuid";
import { updateApplyState } from "../../redux/slices/sessionSlice";
import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
export const searchReplaceToolImpl: ClientToolImpl = async (
@ -81,14 +83,31 @@ export const searchReplaceToolImpl: ClientToolImpl = async (
// Single applyToFile call with all accumulated changes
// This works becaues of our logic in `applyCodeBlock` that determines
// that the full file rewrite here can be applied instantly, so the diff
// lines are just st
await extras.ideMessenger.request("applyToFile", {
streamId,
toolCallId,
text: currentContent,
filepath: resolvedFilepath,
isSearchAndReplace: true,
});
// lines are generated with meyers diff and streamed instantaneously
extras.dispatch(
updateApplyState({
streamId,
toolCallId,
status: "not-started",
}),
);
void extras.ideMessenger
.request("applyToFile", {
streamId,
toolCallId,
text: currentContent,
filepath: resolvedFilepath,
isSearchAndReplace: true,
})
.then((res) => {
if (res.status === "error") {
void extras.dispatch(
handleEditToolApplyError({
toolCallId,
}),
);
}
});
// Return success - applyToFile will handle the completion state
return {

View file

@ -1,5 +1,10 @@
import { ApplyState, ToolCallState } from "core";
import {
ApplyState,
BrowserSerializedContinueConfig,
ToolCallState,
} from "core";
import { describe, expect, it, vi } from "vitest";
import { EMPTY_CONFIG } from "../redux/slices/configSlice";
import { assembleEditOutcomeData } from "./editOutcomeLogger";
vi.mock("../redux/store", () => ({
@ -17,6 +22,19 @@ vi.mock("../redux/store", () => ({
},
}));
const EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED: BrowserSerializedContinueConfig = {
...EMPTY_CONFIG,
selectedModelByRole: {
...EMPTY_CONFIG.selectedModelByRole,
chat: {
provider: "test",
model: "test-model",
title: "Test model",
underlyingProviderName: "provider",
},
},
};
describe("assembleEditOutcomeData", () => {
it("should assemble complete edit outcome data correctly", () => {
const toolCallState: ToolCallState = {
@ -37,7 +55,13 @@ describe("assembleEditOutcomeData", () => {
fileContent: "const new = 2;\nconst another = 3;",
};
const result = assembleEditOutcomeData(toolCallState, applyState, true);
const result = assembleEditOutcomeData(
[],
EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED,
toolCallState,
applyState,
true,
);
console.log(result);
expect(result).toMatchObject({
@ -71,7 +95,13 @@ describe("assembleEditOutcomeData", () => {
fileContent: "",
};
const result = assembleEditOutcomeData(toolCallState, applyState, false);
const result = assembleEditOutcomeData(
[],
EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED,
toolCallState,
applyState,
false,
);
expect(result.previousCodeLines).toBe(0);
expect(result.newCodeLines).toBe(0);

View file

@ -1,18 +1,23 @@
import { ApplyState, ToolCallState } from "core";
import {
ApplyState,
BrowserSerializedContinueConfig,
ToolCallState,
} from "core";
import { IIdeMessenger } from "../context/IdeMessenger";
import { store } from "../redux/store";
import { ChatHistoryItemWithMessageId } from "../redux/slices/sessionSlice";
/**
* Extract model information from tool call state
*/
function extractModelInfo(toolCallState: ToolCallState): {
function extractModelInfo(
history: ChatHistoryItemWithMessageId[],
config: BrowserSerializedContinueConfig,
toolCallState: ToolCallState,
): {
modelProvider: string;
modelName: string;
modelTitle: string;
} {
// Get the conversation history to find the model info
const history = store.getState().session.history;
// Find the assistant message that contains this tool call
const assistantMessage = history.find(
(item) =>
@ -35,7 +40,6 @@ function extractModelInfo(toolCallState: ToolCallState): {
}
// Fallback to config if not found in message
const config = store.getState().config.config;
const chatModel = config?.selectedModelByRole?.chat;
return {
@ -48,12 +52,13 @@ function extractModelInfo(toolCallState: ToolCallState): {
/**
* Extract prompt and completion from tool call state
*/
function extractPromptAndCompletion(toolCallState: ToolCallState): {
function extractPromptAndCompletion(
history: ChatHistoryItemWithMessageId[],
toolCallState: ToolCallState,
): {
prompt: string;
completion: string;
} {
const history = store.getState().session.history;
// Find the assistant message with this tool call
const assistantMessageIndex = history.findIndex(
(item) =>
@ -144,12 +149,17 @@ function extractCodeChanges(applyState: ApplyState): {
* Assemble complete edit outcome data from tool call and apply state
*/
export function assembleEditOutcomeData(
history: ChatHistoryItemWithMessageId[],
config: BrowserSerializedContinueConfig,
toolCallState: ToolCallState,
applyState: ApplyState,
accepted: boolean,
) {
const modelInfo = extractModelInfo(toolCallState);
const promptAndCompletion = extractPromptAndCompletion(toolCallState);
const modelInfo = extractModelInfo(history, config, toolCallState);
const promptAndCompletion = extractPromptAndCompletion(
history,
toolCallState,
);
const codeChanges = extractCodeChanges(applyState);
return {
@ -174,6 +184,8 @@ export function assembleEditOutcomeData(
* Log Agent Mode edit outcome to editOutcome.jsonl
*/
export async function logAgentModeEditOutcome(
history: ChatHistoryItemWithMessageId[],
config: BrowserSerializedContinueConfig,
toolCallState: ToolCallState,
applyState: ApplyState,
accepted: boolean,
@ -182,6 +194,8 @@ export async function logAgentModeEditOutcome(
// Use the original file content stored in applyState, captured before edits were applied
const editOutcomeData = assembleEditOutcomeData(
history,
config,
toolCallState,
applyState,
accepted,

2
package-lock.json generated
View file

@ -1,5 +1,5 @@
{
"name": "continue",
"name": "wt-nate-4",
"lockfileVersion": 3,
"requires": true,
"packages": {

View file

@ -13,6 +13,7 @@ export function mergePackages(
rules: [...(current.rules ?? []), ...(incoming.rules ?? [])],
prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])],
docs: [...(current.docs ?? []), ...(incoming.docs ?? [])],
env: { ...current.env, ...incoming.env },
};
}
@ -29,5 +30,6 @@ export function mergeUnrolledAssistants(
data: [...(current.data ?? []), ...(incoming.data ?? [])],
mcpServers: [...(current.mcpServers ?? []), ...(incoming.mcpServers ?? [])],
prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])],
env: { ...current.env, ...incoming.env },
};
}

View file

@ -321,7 +321,7 @@ export async function unrollBlocks(
const sections: (keyof Omit<
ConfigYaml,
"name" | "version" | "rules" | "schema" | "metadata"
"name" | "version" | "rules" | "schema" | "metadata" | "env"
>)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"];
// Process all sections in parallel

View file

@ -105,11 +105,17 @@ export const commonMetadataSchema = z.object({
iconUrl: z.string().optional(),
});
const envRecord = z.record(
z.string(),
z.union([z.string(), z.number(), z.boolean()]),
);
export const baseConfigYamlSchema = z.object({
name: z.string(),
version: z.string(),
schema: z.string().optional(),
metadata: z.record(z.string()).and(commonMetadataSchema.partial()).optional(),
env: envRecord.optional(),
});
const modelsUsesSchema = z
@ -254,6 +260,7 @@ export const configSchema = z.object({
proxy: z.string().optional(),
api_base: z.string().optional(),
api_key: z.string().optional(),
env: envRecord.optional(),
});
export type Config = z.infer<typeof configSchema>;

View file

@ -1124,13 +1124,15 @@
}
},
"node_modules/form-data": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
"integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {

View file

@ -32,6 +32,7 @@
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.14",
"@types/json-schema": "^7.0.15",
"@types/node": "^24.3.0",
"cross-env": "^7.0.3",
"semantic-release": "^24.2.7",
"ts-jest": "^29.2.3",
@ -1369,7 +1370,7 @@
"version": "1.0.14",
"license": "Apache-2.0",
"dependencies": {
"zod": "^3.24.2"
"zod": "^3.23.8"
}
},
"node_modules/@continuedev/config-yaml": {
@ -4021,13 +4022,13 @@
"dev": true
},
"node_modules/@types/node": {
"version": "24.1.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.1.0.tgz",
"integrity": "sha512-ut5FthK5moxFKH2T1CUOC6ctR67rQRvvHdFLCD2Ql6KXmMuCrjsSsRI9UsLCm9M18BMwClv4pn327UvB7eeO1w==",
"version": "24.3.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.0.tgz",
"integrity": "sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.8.0"
"undici-types": "~7.10.0"
}
},
"node_modules/@types/normalize-package-data": {
@ -12549,9 +12550,9 @@
}
},
"node_modules/undici-types": {
"version": "7.8.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.8.0.tgz",
"integrity": "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==",
"version": "7.10.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz",
"integrity": "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==",
"dev": true,
"license": "MIT"
},

View file

@ -35,6 +35,7 @@
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.14",
"@types/json-schema": "^7.0.15",
"@types/node": "^24.3.0",
"cross-env": "^7.0.3",
"semantic-release": "^24.2.7",
"ts-jest": "^29.2.3",