Merge branch 'main' of https://github.com/continuedev/continue into dallin/con-4022-hide-empty-prompts-resources

This commit is contained in:
Dallin Romney 2025-10-01 09:39:23 -07:00
commit caaff16fbd
84 changed files with 5162 additions and 3910 deletions

View file

@ -62,7 +62,7 @@ import { localPathToUri } from "../util/pathToUri";
import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import { PolicySingleton } from "../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../tools";
import { getBaseToolDefinitions, serializeTool } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
import { loadConfigContextProviders } from "./loadContextProviders";
@ -672,7 +672,7 @@ async function finalToBrowserConfig(
experimental: final.experimental,
rules: final.rules,
docs: final.docs,
tools: final.tools,
tools: final.tools.map(serializeTool),
mcpServerStatuses: final.mcpServerStatuses,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),

View file

@ -213,6 +213,13 @@ export default async function doLoadConfig(options: {
newConfig.mcpServerStatuses = serializableStatuses;
for (const server of mcpServerStatuses) {
server.errors.forEach((error) => {
// MCP errors will also show as config loading errors
errors.push({
fatal: false,
message: error,
});
});
if (server.status === "connected") {
const serverTools: Tool[] = server.tools.map((tool) => ({
displayTitle: server.name + " " + tool.name,

View file

@ -1091,7 +1091,6 @@ export class Core {
const tool = config.tools.find((t) => t.function.name === toolName);
if (!tool) {
// Tool not found, return base policy
return { policy: basePolicy };
}
@ -1101,17 +1100,32 @@ export class Core {
displayValue = args.command as string;
}
// If tool has evaluateToolCallPolicy function, use it
if (tool.evaluateToolCallPolicy) {
const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
return { policy: evaluatedPolicy, displayValue };
}
// Otherwise return base policy unchanged
return { policy: basePolicy, displayValue };
},
);
on("tools/preprocessArgs", async ({ data: { toolName, args } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config?.tools.find((t) => t.function.name === toolName);
if (!tool) {
throw new Error(`Tool ${toolName} not found`);
}
const preprocessedArgs = await tool.preprocessArgs?.(args, {
ide: this.ide,
});
return {
preprocessedArgs,
};
});
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
});

View file

@ -7,22 +7,23 @@ export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
* Validates a single edit operation
*/
export function validateSingleEdit(
oldString: string,
newString: string,
oldString: unknown,
newString: unknown,
replaceAll: unknown,
index?: number,
): void {
): { oldString: string; newString: string; replaceAll?: boolean } {
const context = index !== undefined ? `edit at index ${index}: ` : "";
if (!oldString && oldString !== "") {
if (oldString === undefined || typeof oldString !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingOldString,
`${context}old_string is required`,
`${context}string old_string is required`,
);
}
if (newString === undefined) {
if (newString === undefined || typeof newString !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingNewString,
`${context}new_string is required`,
`${context}string new_string is required`,
);
}
if (oldString === newString) {
@ -31,6 +32,13 @@ export function validateSingleEdit(
`${context}old_string and new_string must be different`,
);
}
if (replaceAll !== undefined && typeof replaceAll !== "boolean") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
`${context}replace_all must be a valid boolean`,
);
}
return { oldString, newString, replaceAll };
}
export function trimEmptyLines({

View file

@ -6,39 +6,69 @@ describe("validateSingleEdit", () => {
describe("valid inputs", () => {
it("should not throw for valid non-empty strings", () => {
expect(() => {
validateSingleEdit("old", "new");
validateSingleEdit("old", "new", undefined);
}).not.toThrow();
});
it("should allow empty old_string for file creation", () => {
expect(() => {
validateSingleEdit("", "new content");
validateSingleEdit("", "new content", undefined);
}).not.toThrow();
});
it("should allow empty new_string for deletion", () => {
expect(() => {
validateSingleEdit("delete me", "");
validateSingleEdit("delete me", "", undefined);
}).not.toThrow();
});
it("should allow multiline strings", () => {
expect(() => {
validateSingleEdit("line1\nline2", "newline1\nnewline2");
validateSingleEdit("line1\nline2", "newline1\nnewline2", undefined);
}).not.toThrow();
});
it("should allow special characters", () => {
expect(() => {
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g");
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g", undefined);
}).not.toThrow();
});
it("should allow replaceAll as true", () => {
expect(() => {
validateSingleEdit("old", "new", true);
}).not.toThrow();
});
it("should allow replaceAll as false", () => {
expect(() => {
validateSingleEdit("old", "new", false);
}).not.toThrow();
});
it("should return validated values including replaceAll", () => {
const result = validateSingleEdit("old", "new", true);
expect(result).toEqual({
oldString: "old",
newString: "new",
replaceAll: true,
});
});
it("should return validated values with replaceAll undefined", () => {
const result = validateSingleEdit("old", "new", undefined);
expect(result).toEqual({
oldString: "old",
newString: "new",
replaceAll: undefined,
});
});
});
describe("invalid inputs", () => {
it("should throw error when old_string is null", () => {
expect(() => {
validateSingleEdit(null as any, "new");
validateSingleEdit(null as any, "new", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -48,7 +78,7 @@ describe("validateSingleEdit", () => {
it("should throw error when old_string is undefined", () => {
expect(() => {
validateSingleEdit(undefined as any, "new");
validateSingleEdit(undefined as any, "new", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -58,7 +88,7 @@ describe("validateSingleEdit", () => {
it("should throw error when new_string is undefined", () => {
expect(() => {
validateSingleEdit("old", undefined as any);
validateSingleEdit("old", undefined as any, undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
@ -68,7 +98,7 @@ describe("validateSingleEdit", () => {
it("should throw error when old_string and new_string are identical", () => {
expect(() => {
validateSingleEdit("same", "same");
validateSingleEdit("same", "same", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
@ -78,19 +108,49 @@ describe("validateSingleEdit", () => {
it("should throw error when both are empty strings", () => {
expect(() => {
validateSingleEdit("", "");
validateSingleEdit("", "", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should throw error when replaceAll is not a boolean", () => {
expect(() => {
validateSingleEdit("old", "new", "invalid" as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should throw error when replaceAll is null", () => {
expect(() => {
validateSingleEdit("old", "new", null as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should throw error when replaceAll is a number", () => {
expect(() => {
validateSingleEdit("old", "new", 1 as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
});
describe("error messages with context", () => {
it("should include edit number in error messages when index provided", () => {
expect(() => {
validateSingleEdit(null as any, "new", 2);
validateSingleEdit(null as any, "new", undefined, 2);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -100,7 +160,7 @@ describe("validateSingleEdit", () => {
it("should include edit number for new_string errors", () => {
expect(() => {
validateSingleEdit("old", undefined as any, 0);
validateSingleEdit("old", undefined as any, undefined, 0);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
@ -110,7 +170,7 @@ describe("validateSingleEdit", () => {
it("should include edit number for identical strings error", () => {
expect(() => {
validateSingleEdit("same", "same", 4);
validateSingleEdit("same", "same", undefined, 4);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
@ -118,9 +178,19 @@ describe("validateSingleEdit", () => {
);
});
it("should include edit number for replaceAll validation error", () => {
expect(() => {
validateSingleEdit("old", "new", "invalid" as any, 3);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should not include context when index not provided", () => {
expect(() => {
validateSingleEdit("same", "same");
validateSingleEdit("same", "same", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,

View file

@ -2,26 +2,30 @@ import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { validateSingleEdit } from "./findAndReplaceUtils";
export interface MultiEditValidationResult {
edits: EditOperation[];
}
/**
* Validates multi-edit arguments and all edits in a single pass
* @param args - The arguments object containing the edits array
* @returns Validated edits array
* @throws ContinueError if validation fails
*/
export function validateMultiEdit(args: any): MultiEditValidationResult {
const { edits } = args;
export function validateMultiEdit(args: unknown): {
edits: EditOperation[];
} {
if (typeof args !== "object" || !args || !("edits" in args)) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayRequired,
"invalid multi-edit args",
);
}
// Validate that edits is a non-empty array
if (!edits || !Array.isArray(edits)) {
if (!Array.isArray(args.edits)) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayRequired,
"edits array is required",
);
}
const { edits } = args;
if (edits.length === 0) {
throw new ContinueError(
@ -35,7 +39,7 @@ export function validateMultiEdit(args: any): MultiEditValidationResult {
const edit = edits[i];
// Use existing single edit validation
validateSingleEdit(edit.old_string, edit.new_string, i);
validateSingleEdit(edit.old_string, edit.new_string, edit.replace_all, i);
// Only the first edit can have empty old_string (for insertion at beginning)
if (i > 0 && edit.old_string === "") {

View file

@ -0,0 +1,23 @@
import { IDE } from "../..";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { resolveRelativePathInDir } from "../../util/ideUtils";
export async function validateSearchAndReplaceFilepath(
filepath: unknown,
ide: IDE,
) {
if (!filepath || typeof filepath !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingFilepath,
"filepath (string) is required",
);
}
const resolvedFilepath = await resolveRelativePathInDir(filepath, ide);
if (!resolvedFilepath) {
throw new ContinueError(
ContinueErrorReason.FileNotFound,
`File ${filepath} does not exist`,
);
}
return resolvedFilepath;
}

9
core/index.d.ts vendored
View file

@ -1082,7 +1082,6 @@ export interface Tool {
parameters?: Record<string, any>;
strict?: boolean | null;
};
displayTitle: string;
wouldLikeTo?: string;
isCurrently?: string;
@ -1099,6 +1098,12 @@ export interface Tool {
};
defaultToolPolicy?: ToolPolicy;
toolCallIcon?: string;
preprocessArgs?: (
args: Record<string, unknown>,
extras: {
ide: IDE;
},
) => Promise<Record<string, unknown>>;
evaluateToolCallPolicy?: (
basePolicy: ToolPolicy,
parsedArgs: Record<string, unknown>,
@ -1779,7 +1784,7 @@ export interface BrowserSerializedContinueConfig {
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
tools: Omit<Tool, "preprocessArgs", "evaluatePolicy">[];
mcpServerStatuses: MCPServerStatus[];
rules: RuleWithSource[];
usePlatform: boolean;

View file

@ -314,6 +314,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
{ policy: ToolPolicy; displayValue?: string },
];
"tools/preprocessArgs": [
{ toolName: string; args: Record<string, unknown> },
{ preprocessedArgs?: Record<string, unknown> },
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];

View file

@ -81,6 +81,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"didChangeSelectedOrg",
"tools/call",
"tools/evaluatePolicy",
"tools/preprocessArgs",
"controlPlane/getEnvironment",
"controlPlane/getFreeTrialStatus",
"controlPlane/getModelsAddOnUpgradeUrl",

View file

@ -1,2 +1,4 @@
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";
export const ERRORED_TOOL_CALL_OUTPUT_MESSAGE =
"There was an error calling the tool.";

View file

@ -1,4 +1,7 @@
import { Tool } from "../..";
import { validateMultiEdit } from "../../edit/searchAndReplace/multiEditValidation";
import { executeMultiFindAndReplace } from "../../edit/searchAndReplace/performReplace";
import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
@ -107,4 +110,24 @@ WARNINGS:
],
},
defaultToolPolicy: "allowedWithPermission",
preprocessArgs: async (args, extras) => {
const { edits } = validateMultiEdit(args);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ide,
);
const editingFileContents = await extras.ide.readFile(fileUri);
const newFileContents = executeMultiFindAndReplace(
editingFileContents,
edits,
);
return {
...args,
fileUri,
editingFileContents,
newFileContents,
};
},
};

View file

@ -1,4 +1,7 @@
import { Tool } from "../..";
import { validateSingleEdit } from "../../edit/searchAndReplace/findAndReplaceUtils";
import { executeFindAndReplace } from "../../edit/searchAndReplace/performReplace";
import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
@ -70,4 +73,31 @@ WARNINGS:
],
},
defaultToolPolicy: "allowedWithPermission",
preprocessArgs: async (args, extras) => {
const { oldString, newString, replaceAll } = validateSingleEdit(
args.old_string,
args.new_string,
args.replace_all,
);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ide,
);
const editingFileContents = await extras.ide.readFile(fileUri);
const newFileContents = executeFindAndReplace(
editingFileContents,
oldString,
newString,
replaceAll ?? false,
0,
);
return {
...args,
fileUri,
editingFileContents,
newFileContents,
};
},
};

View file

@ -51,3 +51,8 @@ export const getConfigDependentToolDefinitions = (
return tools;
};
export function serializeTool(tool: Tool) {
const { preprocessArgs, evaluateToolCallPolicy, ...rest } = tool;
return rest;
}

View file

@ -30,6 +30,7 @@ export type GlobalContextType = {
selectedModelsByProfileId: {
[profileId: string]: GlobalContextModelSelections;
};
cliSelectedModel?: string; // CLI-specific model selection for unauthenticated users
/**
* This is needed to handle the case where a JetBrains user has created

View file

@ -27,6 +27,7 @@ export enum ContinueErrorReason {
FindAndReplaceMissingOldString = "find_and_replace_missing_old_string",
FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string",
FindAndReplaceMissingNewString = "find_and_replace_missing_new_string",
FindAndReplaceInvalidReplaceAll = "find_and_replace_invalid_replace_all",
FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found",
FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences",
FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath",
@ -48,6 +49,6 @@ export enum ContinueErrorReason {
ParentDirectoryNotFound = "parent_directory_not_found",
// Other
Unspecified = "unspecified",
Unknown = "unknown",
Unspecified = "unspecified", // I.e. a known error but no specific code for it
Unknown = "unknown", // I.e. an unexpected error
}

View file

@ -186,7 +186,7 @@
"pages": [
"hub/introduction",
{
"group": "agents",
"group": "Agents",
"icon": "robot",
"pages": [
"hub/agents/intro",
@ -222,6 +222,11 @@
"hub/secrets/secret-resolution"
]
},
{
"group": "Workflows",
"icon": "cloud",
"pages": ["hub/workflows/intro"]
},
"hub/sharing",
"hub/source-control"
]
@ -256,6 +261,7 @@
"pages": [
"guides/posthog-github-continuous-ai",
"guides/snyk-mcp-continue-cookbook",
"guides/dlt-mcp-continue-cookbook",
"guides/netlify-mcp-continuous-deployment"
]
}

View file

@ -0,0 +1,484 @@
---
title: "Building Data Pipelines with dlt MCP and Continue"
description: "Set up an AI-powered data engineering workflow that helps you develop, debug, and inspect dlt data pipelines using natural language commands."
sidebarTitle: "dlt Data Pipelines with Continue"
---
<Card title="What You'll Build" icon="database">
An AI-powered data pipeline development system that uses Continue's AI agent with dlt
MCP to inspect pipeline execution, retrieve schemas, analyze datasets, and debug load errors - all through simple natural language prompts
</Card>
## Prerequisites
Before starting, ensure you have:
- Continue account with **Hub access**
- Read: [Understanding Agents — How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents)
- Python 3.8+ installed locally
- A dlt pipeline project (or create one during this guide)
- Basic understanding of data pipelines
For all options, first:
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
</Step>
<Step title="Install dlt">
```bash
pip install dlt
```
</Step>
</Steps>
<Warning>
To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys).
</Warning>
## dlt MCP Workflow Options
<Card title="🚀 Fastest Path to Success" icon="zap">
Skip the manual setup and use our pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) that includes
the dlt MCP and optimized data pipeline workflows for more consistent results. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize it for your specific needs.
</Card>
After ensuring you meet the **Prerequisites** above, you have two paths to get started:
<Tabs>
<Tab title="⚡ Quick Start (Recommended)">
<Steps>
<Step title="Load the Pre-Built Agent">
Navigate to your pipeline project directory and run:
```bash
cn --config dlthub/dlt-assistant
```
This agent includes:
- **dlt MCP** pre-configured and ready to use
- **Pipeline-focused rules** for data engineering best practices
</Step>
<Step title="Run Your First Pipeline Inspection">
Start with a comprehensive pipeline check:
```bash
# TUI mode
Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes.
```
That's it! The agent handles everything automatically.
</Step>
</Steps>
<Info>
**Why Use the Agent?** The pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) provides consistent pipeline development workflows and handles MCP configuration automatically, making it easier to get started with AI-powered data engineering. You can [remix and customize this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) later to fit your team's specific workflow.
</Info>
</Tab>
<Tab title="🛠️ Manual Setup">
<Steps>
<Step title="Create a New Agent via the Continue Hub">
Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent).
</Step>
<Step title="Connect dlt MCP via Continue Hub">
Visit the [dlt MCP on Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp) and click **Install** to add it to the agent you created in the step above.
This will add dlt MCP to your agent's available tools. The Hub listing automatically configures the MCP command.
<Tip>
**Alternative installation methods:**
1. **Quick CLI install**: `cn --mcp dlthub/dlt-mcp`
2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section
Once installed, dlt MCP tools become available to your Continue agent for all prompts.
</Tip>
<Info>
The MCP will work with your existing dlt pipelines in your current directory.
</Info>
</Step>
<Step title="Run Your First Pipeline Inspection">
Start with a comprehensive pipeline check:
```bash
# TUI mode
cn
# Then type: Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes.
```
</Step>
</Steps>
</Tab>
</Tabs>
<Accordion title="Agent Requirements">
To use the pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant), you need either:
- **Continue CLI Pro Plan** with the models add-on, OR
- **Your own API keys** added to Continue Hub secrets (same as manual setup)
The agent will automatically detect and use your configuration along with the pre-configured dlt MCP for pipeline operations.
</Accordion>
---
## dlt MCP vs dlt+ MCP
<Card title="Understanding the Difference" icon="info-circle">
**dlt MCP** is focused on local pipeline development and inspection. It provides tools to:
- Inspect pipeline execution and load information
- Retrieve schema metadata from your local pipelines
- Query dataset records from destination databases
- Analyze load errors, timings, and file sizes
**[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** extends these capabilities with cloud-based features for production deployments:
- Connect to dlt+ Projects and manage deployments
- Monitor pipeline runs across multiple environments
- Access centralized logging and observability
- Collaborate with team members on pipeline development
For local development and getting started, **[dlt MCP](https://hub.continue.dev/dlthub/dlt-mcp)** is the right choice. Consider **[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** when you need production deployment features and team collaboration.
</Card>
---
## Pipeline Development Recipes
Now you can use natural language prompts to develop and debug your dlt pipelines. The Continue agent automatically calls the appropriate dlt MCP tools.
<Info>
You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section.
</Info>
<Info>
**Where to run these workflows:**
- **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
- **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
- **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands
**Test in Plan Mode First**: Before running pipeline operations that might make
changes, test your prompts in plan mode (see the [Plan Mode
Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This
shows you what the agent will do without executing it.
</Info>
<Info>
**About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like pipeline inspection, schema retrieval, and error analysis.
</Info>
### Pipeline Inspection
<Card title="Inspect Pipeline Execution" icon="magnifying-glass">
Review pipeline execution details including load timing and file sizes.
**TUI Mode Prompt:**
```
Inspect my dlt pipeline execution and provide a summary of the load info.
Show me the timing breakdown and file sizes for each table.
```
**Headless Mode Prompt:**
```bash
cn -p "Inspect my dlt pipeline execution and provide a summary of the load info. Show me the timing breakdown and file sizes for each table." --auto
```
</Card>
### Schema Management
<Card title="Retrieve Schema Metadata" icon="diagram-project">
Get detailed schema information for your pipeline's tables.
**TUI Mode Prompt:**
```
Show me the schema for my users table including all columns,
data types, and any constraints.
```
**Headless Mode Prompt:**
```bash
cn -p "Show me the schema for my users table including all columns, data types, and any constraints." --auto
```
</Card>
### Data Exploration
<Card title="Query Dataset Records" icon="table">
Retrieve and analyze records from your destination database.
**TUI Mode Prompt:**
```
Get the last 10 records from my orders table and show me
the distribution of order statuses.
```
**Headless Mode Prompt:**
```bash
cn -p "Get the last 10 records from my orders table and show me the distribution of order statuses." --auto
```
</Card>
### Error Debugging
<Card title="Analyze Load Errors" icon="triangle-exclamation">
Investigate and understand pipeline load errors.
**TUI Mode Prompt:**
```
Check for any load errors in my last pipeline run. If there are errors,
explain what went wrong and suggest fixes.
```
**Headless Mode Prompt:**
```bash
cn -p "Check for any load errors in my last pipeline run. If there are errors, explain what went wrong and suggest fixes." --auto
```
</Card>
### Pipeline Creation
<Card title="Build New Pipeline" icon="plus">
Create a new dlt pipeline from an API or data source.
**TUI Mode Prompt:**
```
Help me create a new dlt pipeline that loads data from the
JSONPlaceholder API users endpoint into DuckDB.
```
**Headless Mode Prompt:**
```bash
cn -p "Help me create a new dlt pipeline that loads data from the JSONPlaceholder API users endpoint into DuckDB." --auto
```
</Card>
### Schema Evolution
<Card title="Handle Schema Changes" icon="code-branch">
Review and manage schema evolution in your pipelines.
**TUI Mode Prompt:**
```
Check if my pipeline schema has evolved since the last run.
Show me what columns were added or modified.
```
**Headless Mode Prompt:**
```bash
cn -p "Check if my pipeline schema has evolved since the last run. Show me what columns were added or modified." --auto
```
</Card>
## Continuous Data Pipelines with GitHub Actions
This example demonstrates a **Continuous AI workflow** where data pipeline validation runs automatically in your CI/CD pipeline in headless mode using the [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant). Consider [remixing this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to add your organization's specific validation rules.
### Add GitHub Secrets
Navigate to **Repository Settings → Secrets and variables → Actions** and add:
- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
- Any required database credentials for your destination
<Info>
The workflow uses the pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) with `--config dlthub/dlt-assistant`. This agent comes pre-configured with the dlt MCP and optimized rules for pipeline operations. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize the validation rules and prompts for your specific pipeline requirements.
</Info>
### Create Workflow File
This workflow automatically validates your dlt data pipelines on pull requests using the Continue CLI in [headless mode](/cli/overview#headless-mode%3A-production-automation). It inspects pipeline schemas, checks for errors, and posts a summary report as a PR comment. The workflow can also be triggered manually via `workflow_dispatch`.
Create `.github/workflows/dlt-pipeline-validation.yml` in your repository:
```yaml
name: Data Pipeline Validation with dlt MCP
on:
pull_request:
branches: [main]
workflow_dispatch:
jobs:
validate-pipeline:
runs-on: ubuntu-latest
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "18"
- name: Install dlt
run: |
pip install dlt
echo "✅ dlt installed"
- name: Install Continue CLI
run: |
npm install -g @continuedev/cli
echo "✅ Continue CLI installed"
- name: Validate Pipeline Schema
run: |
echo "🔍 Validating pipeline schema..."
cn --config dlthub/dlt-assistant \
-p "Inspect the pipeline schema and verify all required tables
and columns are present. Flag any missing or unexpected changes." \
--auto
- name: Check Pipeline Health
run: |
echo "📊 Checking pipeline health..."
cn --config dlthub/dlt-assistant \
-p "Analyze the last pipeline run for errors or warnings.
Report any issues that need attention." \
--auto
- name: Comment Pipeline Report on PR
if: always() && github.event_name == 'pull_request'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
REPORT=$(cn --config dlthub/dlt-assistant \
-p "Generate a concise summary (200 words or less) of:
- Pipeline schemas and row counts
- Any load errors or warnings
- Performance metrics (timing, file sizes)
- Recommended improvements" \
--auto)
gh pr comment ${{ github.event.pull_request.number }} --body "$REPORT"
```
<Info>
The dlt MCP works with your local pipeline state. Make sure your CI environment
has access to the necessary pipeline configuration and credentials.
</Info>
## Pipeline Development Best Practices
Implement automated pipeline quality checks using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips.
<Card title="Schema Validation" icon="check-circle">
```bash
"Before committing pipeline changes, verify the schema
matches expectations and flag any unexpected modifications."
```
</Card>
<Card title="Error Handling" icon="shield-exclamation">
```bash
"When load errors occur, analyze the error details and
suggest specific code fixes to handle the data issues."
```
</Card>
<Card title="Performance Monitoring" icon="gauge-high">
```bash
"Track pipeline execution times and file sizes. Alert if
performance degrades significantly from baseline."
```
</Card>
<Card title="Data Quality" icon="check-double">
```bash
"After each pipeline run, validate row counts and check for
null values in critical columns."
```
</Card>
## Troubleshooting
### Pipeline Not Found
```bash
"Check if there's a dlt pipeline in the current directory.
If not, help me initialize a new pipeline."
```
### Destination Connection Issues
```bash
"Verify the destination connection and credentials for my pipeline.
Test the connection and report any issues."
```
### Schema Inference Problems
<Check>
**Verification Steps:**
- dlt MCP is installed via [Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp)
- Pipeline directory is accessible
- Destination database credentials are configured
- Pipeline has been run at least once
</Check>
## What You've Built
After completing this guide, you have a complete **AI-powered data pipeline development system** that:
✅ Uses natural language — Simple prompts instead of complex pipeline commands
✅ Debugs automatically — AI analyzes errors and suggests fixes
✅ Runs continuously — Automated validation in CI/CD pipelines
✅ Ensures quality — Pipeline checks prevent bad data from shipping
<Card title="Continuous AI" icon="rocket">
Your data pipeline workflow now operates at **[Level 2 Continuous
AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
AI handles routine pipeline inspection and debugging with human oversight
through review and approval of changes.
</Card>
## Next Steps
1. **Inspect your first pipeline** - Try the pipeline inspection prompt on your current project
2. **Debug load errors** - Use the error analysis prompt to fix any issues
3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo
4. **Create new pipelines** - Use AI to scaffold new data sources
5. **Monitor performance** - Track pipeline execution metrics over time
## Additional Resources
<CardGroup cols={2}>
<Card title="dlt Documentation" icon="book" href="https://dlthub.com/docs">
Complete dlt platform documentation
</Card>
<Card title="Continue Hub" icon="plug" href="https://hub.continue.dev">
Explore more MCP integrations and agents
</Card>
<Card
title="dlt Blog: MCP Deep Dive"
icon="newspaper"
href="https://dlthub.com/blog/deep-dive-assistants-mcp-continue"
>
Learn about AI assistants, MCP, and Continue integration
</Card>
<Card
title="MCP Concepts"
icon="puzzle-piece"
href="https://dlthub.com/blog/deep-dive-assistants-mcp-continue"
>
Deep dive into dlt MCP integration
</Card>
</CardGroup>

View file

@ -33,8 +33,18 @@ For all options, first:
1. Sign up for a Snyk account at [snyk.io](https://snyk.io/)
2. Create a new project in Snyk by importing your code repository (Git
provider or manual upload)
3. Install and authenticate the Snyk CLI locally:
```bash
npm install -g snyk
snyk auth
```
This will open your browser to authenticate with your Snyk account.
</Step>
</Steps>
<Note>
**Important**: The Snyk MCP requires the Snyk CLI to be authenticated locally. Run `snyk auth` to authenticate before using the Continue agent with Snyk MCP.
</Note>
<Warning>
To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys).
</Warning>
@ -66,8 +76,8 @@ After ensuring you meet the **Prerequisites** above, you have two paths to get s
<Step title="Run Your First Security Scan">
Start with a comprehensive security scan:
```bash
# TUI mode
cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity."
# Headless mode
cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." --auto
```
That's it! The agent handles everything automatically.
@ -159,7 +169,7 @@ You can add prompts to your agent's configuration for easy access in future sess
**Where to run these workflows:**
- **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
- **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
- **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands
- **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for headless commands
**Test in Plan Mode First**: Before running security scans that might make
changes, test your prompts in plan mode (see the [Plan Mode
@ -182,7 +192,7 @@ and rerun to verify.
**Headless Mode Prompt:**
```bash
cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summarize issues with file:line. Propose minimal diffs for the top 3 and rerun to verify."
cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summarize issues with file:line. Propose minimal diffs for the top 3 and rerun to verify." --auto
```
</Card>
@ -201,7 +211,7 @@ Re-test after the plan (dry run).
**Headless Mode Prompt:**
```bash
cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerable paths and propose a minimal-risk upgrade plan. Re-test after the plan (dry run)."
cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerable paths and propose a minimal-risk upgrade plan. Re-test after the plan (dry run)." --auto
```
</Card>
@ -219,7 +229,7 @@ with exact files/lines. Provide code changes and re-scan to confirm.
**Headless Mode Prompt:**
```bash
cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm."
cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm." --auto
```
</Card>
@ -238,7 +248,7 @@ Re-test after the change (dry run).
**Headless Mode Prompt:**
```bash
cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree. Recommend a safer base image or upgrades. Re-test after the change (dry run)."
cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree. Recommend a safer base image or upgrades. Re-test after the change (dry run)." --auto
```
</Card>
@ -256,7 +266,7 @@ Block if new high issues would be introduced. Show deltas.
**Headless Mode Prompt:**
```bash
cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas."
cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas." --auto
```
</Card>
@ -273,35 +283,38 @@ Open Snyk Learn lessons related to the top CWE(s) from this scan.
**Headless Mode Prompt:**
```bash
cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan."
cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan." --auto
```
</Card>
## Continuous Security with GitHub Actions
This example demonstrates a **Continuous AI workflow** where security scanning runs automatically in your CI/CD pipeline Headless Mode Prompt in headless mode (`cn -p`) with Snyk MCP.
This example demonstrates a **Continuous AI workflow** where security scanning runs automatically on pull requests, generates AI-powered mitigation suggestions, and posts them as PR comments.
<Info>
**About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like security scanning, vulnerability analysis, and fix validation.
</Info>
### Add GitHub Secrets
Navigate to **Repository Settings → Secrets and variables → Actions** and add:
- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
- `SNYK_TOKEN`: Your Snyk authentication token from [app.snyk.io/account](https://app.snyk.io/account)
### Create Workflow File
Create `.github/workflows/snyk-security.yml` in your repository:
```yaml
name: Security Scanning with Snyk MCP
name: Snyk Security Scanning
on:
pull_request:
branches: [main]
push:
branches: [main]
schedule:
- cron: "0 8 * * *" # Daily at 8 AM UTC
jobs:
security-scan:
@ -309,55 +322,259 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch all history for git diff
- name: Get Changed Files
id: changed-files
run: |
echo "📝 Getting changed files since main branch..."
CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | tr '\n' ' ')
echo "changed_files=$CHANGED_FILES" >> $GITHUB_OUTPUT
echo "Changed files: $CHANGED_FILES"
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "18"
node-version: '18'
- name: Install Snyk CLI
run: |
npm install -g snyk
echo "✅ Snyk CLI installed"
- name: Install Continue CLI
run: |
npm install -g @continuedev/cli
echo "✅ Continue CLI installed"
- name: Authenticate Continue CLI
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
- name: Validate Secrets
run: |
cn auth login --api-key "$CONTINUE_API_KEY"
echo "✅ Continue CLI authenticated"
if [ -z "${{ secrets.SNYK_TOKEN }}" ]; then
echo "❌ Error: SNYK_TOKEN secret is not set"
exit 1
fi
if [ -z "${{ secrets.CONTINUE_API_KEY }}" ]; then
echo "⚠️ Warning: CONTINUE_API_KEY not set - AI mitigation suggestions will be skipped"
fi
echo "✅ Required secrets validated"
- name: Authenticate Snyk
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
run: |
snyk auth "$SNYK_TOKEN"
echo "✅ Snyk authenticated"
- name: Run Security Scans
id: security-scan
continue-on-error: true
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
CHANGED_FILES: ${{ steps.changed-files.outputs.changed_files }}
run: |
echo "🔍 Running code vulnerability scan..."
cn -p "Run Snyk Code scan with severity high on this repo.
Fail if any high issues are present."
SCAN_FAILED=0
if [ -n "$CHANGED_FILES" ]; then
echo "🔍 Running targeted scan on changed files..."
echo "Changed files: $CHANGED_FILES"
FILE_ARGS=""
for file in $CHANGED_FILES; do
if [[ "$file" =~ \.(js|jsx|ts|tsx|py|java|go|rb)$ ]]; then
FILE_ARGS="$FILE_ARGS --file=$file"
fi
done
if [ -n "$FILE_ARGS" ]; then
echo "🔍 Running Snyk Code scan on changed files..."
snyk code test $FILE_ARGS --severity-threshold=high --json > snyk-code-results.json || {
echo "❌ Snyk Code found high severity issues in changed files"
SCAN_FAILED=1
}
else
echo "⚠️ No scannable code files changed, skipping Snyk Code scan"
echo '{"runs": [{"results": []}]}' > snyk-code-results.json
fi
else
echo "⚠️ No changed files detected, creating empty results"
echo '{"runs": [{"results": []}]}' > snyk-code-results.json
fi
echo "📦 Checking dependencies..."
cn -p "Run Snyk Open Source on this repo.
Fail on fixable high issues."
snyk test --severity-threshold=high --json > snyk-oss-results.json || {
echo "❌ Snyk Open Source found high severity issues"
SCAN_FAILED=1
}
if [ $SCAN_FAILED -eq 1 ]; then
echo "scan_status=failed" >> $GITHUB_OUTPUT
echo "⚠️ Scans completed with issues - continuing to generate mitigation suggestions"
else
echo "scan_status=passed" >> $GITHUB_OUTPUT
echo "✅ All security scans passed"
fi
- name: Generate AI Mitigation Suggestions
if: always() && steps.security-scan.outputs.scan_status == 'failed'
continue-on-error: true
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
run: |
echo "🤖 Generating AI-powered mitigation suggestions..."
# Create a summary of findings for Continue CLI
FINDINGS_SUMMARY=$(cat snyk-code-results.json snyk-oss-results.json | jq -r '
if .runs then
.runs[0].results[] | "Code Issue: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri) (Severity: \(.level))"
elif .vulnerabilities then
.vulnerabilities[] | "Dependency Issue: \(.title) in \(.packageName)@\(.version) (Severity: \(.severity))"
else
empty
end
' | head -20)
if [ -n "$FINDINGS_SUMMARY" ]; then
echo "📋 Security findings to analyze:"
echo "$FINDINGS_SUMMARY"
echo ""
# Use Continue CLI to generate mitigation suggestions
PROMPT="Analyze these Snyk security findings and provide specific, actionable mitigation steps for each issue. Focus on: 1) Root cause, 2) Immediate fix, 3) Long-term prevention. Findings: $FINDINGS_SUMMARY. Provide clear, prioritized recommendations."
cn --config continuedev/snyk-continuous-ai -p "$PROMPT" --auto > mitigation-suggestions.md || {
echo "⚠️ Warning: Could not generate AI suggestions"
exit 0
}
if [ -f mitigation-suggestions.md ]; then
echo "✅ AI mitigation suggestions generated"
echo ""
echo "--- Mitigation Suggestions ---"
cat mitigation-suggestions.md
fi
else
echo "⚠️ No findings to analyze"
fi
- name: Post Mitigation Summary to PR
if: steps.security-scan.outputs.scan_status == 'failed' && hashFiles('mitigation-suggestions.md') != ''
continue-on-error: true
env:
GH_TOKEN: ${{ github.token }}
run: |
if [ -f mitigation-suggestions.md ]; then
echo "💬 Posting mitigation summary to PR..."
# Create PR comment with mitigation suggestions
cat > pr-comment.md <<'EOF'
## 🛡️ Snyk Mitigation Summary
Snyk has identified security issues in this PR. Here are AI-generated mitigation recommendations:
EOF
cat mitigation-suggestions.md >> pr-comment.md
cat >> pr-comment.md <<EOF
---
**Scan Details:**
- 📊 Full report available in workflow artifacts
- 🔍 Review the [workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for complete details
- 🤖 Generated with Continue CLI + Snyk
_This is an automated security analysis. Please review and address the findings before merging._
EOF
gh pr comment ${{ github.event.pull_request.number }} --body-file pr-comment.md
echo "✅ Mitigation summary posted to PR"
else
echo "⚠️ No mitigation suggestions file found"
fi
- name: Generate Security Report
if: always()
continue-on-error: true
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
run: |
cn -p "Generate a markdown security report summarizing:
- Total vulnerabilities by severity
- Top 3 critical issues (if any)
- Recommended next steps
Save to security-report.md"
echo "📊 Generating security report..."
{
echo "# Security Scan Report"
echo ""
echo "**Date:** $(date -u +"%Y-%m-%d %H:%M:%S UTC")"
echo "**Branch:** ${{ github.ref_name }}"
echo "**Commit:** ${{ github.sha }}"
echo "**Status:** ${{ steps.security-scan.outputs.scan_status }}"
echo ""
echo "## Snyk Code Scan Results"
if [ -f snyk-code-results.json ]; then
jq -r '.runs[0].results[] | "- **\(.level | ascii_upcase)**: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri)"' snyk-code-results.json || echo "No code issues found"
else
echo "No scan results available"
fi
echo ""
echo "## Snyk Open Source Scan Results"
if [ -f snyk-oss-results.json ]; then
jq -r '.vulnerabilities[] | "- **\(.severity | ascii_upcase)**: \(.title) (\(.packageName)@\(.version))"' snyk-oss-results.json || echo "No dependency issues found"
else
echo "No scan results available"
fi
echo ""
if [ -f mitigation-suggestions.md ]; then
echo "## AI-Powered Mitigation Suggestions"
echo ""
cat mitigation-suggestions.md
fi
} > scan-results.md
if [ -f scan-results.md ]; then
echo "✅ Security report generated successfully"
cat scan-results.md
else
echo "⚠️ Warning: scan-results.md was not created"
fi
- name: Upload Security Report
uses: actions/upload-artifact@v4
if: always()
continue-on-error: true
uses: actions/upload-artifact@v4
with:
name: security-report-${{ github.run_number }}
path: security-report.md
retention-days: 30
name: security-scan-results
path: |
scan-results.md
snyk-code-results.json
snyk-oss-results.json
mitigation-suggestions.md
if-no-files-found: warn
- name: Fail if Security Issues Found
if: steps.security-scan.outputs.scan_status == 'failed'
run: |
echo "❌ Security scan failed - high severity issues found"
echo "📋 Review the security report artifact for details and mitigation suggestions"
exit 1
```
<Info>
The Snyk MCP authentication is handled through Continue Hub. No need to manage
Snyk tokens directly in CI - the agent manages authentication.
**About SNYK_TOKEN**: The workflow uses the SNYK_TOKEN in two ways:
1. **Direct Snyk CLI authentication** - Authenticates the Snyk CLI for running scans
2. **Continue CLI access** - Available as an environment variable when Continue generates AI mitigation suggestions
The `cn` agent automatically uses the SNYK_TOKEN when needed for Snyk MCP operations.
</Info>
<Info>
This workflow demonstrates several advanced features:
- **Changed Files Detection**: Only scans files modified in the PR
- **AI Mitigation**: Uses Continue CLI to generate actionable mitigation steps
- **PR Comments**: Automatically posts mitigation suggestions as PR comments
- **Comprehensive Reporting**: Generates detailed security reports with artifacts
</Info>
## Security Guardrails

View file

@ -0,0 +1,97 @@
---
title: "Introduction"
description: "Run Continuous AI workflows in the background"
---
<Info>
Workflows are in beta. Please share any feedback with us in [GitHub discussions](https://github.com/continuedev/continue/discussions/8051).
</Info>
Workflows are a way to run and manage background agents in Continue. You can use them for:
- Addressing small nitpicks and bugs
- Building boilerplate-heavy features
- Investigating an issue to kickstart your work
- [Automated security scanning](../../guides/snyk-mcp-continue-cookbook)
- Running repeatable tasks with your own rules, prompts, and MCP servers
- Much more!
## Quickstart
To run your first workflow
1. Go to [hub.continue.dev/agents](https://hub.continue.dev/agents)
![Agent Setup](/images/hub/workflows/images/workflows-setup.png)
2. Connect with your GitHub account
3. Enter the prompt for your agent
## Example Workflow Tasks
Here are some example tasks you can try with your workflows:
<AccordionGroup>
<Accordion title="Bug Fixes & Code Quality">
- "Fix the TypeError in api/users.ts where the user object might be undefined"
- "Add null checks to all database query results in the services/ directory"
- "Fix all ESLint warnings in the components folder"
- "Update deprecated React lifecycle methods to hooks in legacy components"
</Accordion>
<Accordion title="Feature Development">
- "Create a new REST endpoint for user profile updates with validation and error handling"
- "Add pagination to the products list page with previous/next buttons"
- "Implement dark mode toggle using Tailwind CSS classes across all pages"
- "Add unit tests for the authentication service using Jest"
</Accordion>
<Accordion title="Security & Compliance">
- "Scan the codebase for hardcoded API keys and move them to environment variables"
- "Add input sanitization to all user-facing form fields"
- "Update all npm packages with known security vulnerabilities"
- "Implement rate limiting on the /api/login endpoint"
</Accordion>
<Accordion title="Documentation & Boilerplate">
- "Add JSDoc comments to all exported functions in the utils/ directory"
- "Create a README.md for the new payment-processing module with setup instructions"
- "Generate TypeScript interfaces for all API response schemas"
- "Add error handling boilerplate to all async functions missing try-catch blocks"
</Accordion>
<Accordion title="Investigation & Analysis">
- "Investigate why the login API is returning 500 errors intermittently and suggest fixes"
- "Analyze the performance bottleneck in the data processing pipeline"
- "Review the database schema for the orders table and suggest optimizations"
- "Find all TODO comments related to authentication and create a summary"
</Accordion>
<Accordion title="Refactoring">
- "Extract the repeated validation logic in controllers into a shared utility function"
- "Convert all class components in src/legacy to functional components with hooks"
- "Rename all instances of 'userId' to 'accountId' across the codebase"
- "Split the 500-line UserService.ts into smaller, single-responsibility services"
</Accordion>
</AccordionGroup>
## How to use background agents
The practice of using background agents, which we call Continuous AI, requires practice and forethought to set up the right guiderails and habits to fit your development workflow, much like learning to work with a larger engineering team. We are constantly sharing our learnings on the [Continuous AI Blog](https://blog.continue.dev), but these few high-level tips are a great way to quickly become successful with workflows:
- Practice first with the [Continue CLI](../../guides/cli) in "TUI mode". The same agent that powers our CLI is used for workflows, so you can easily test your prompts locally.
- Identify and begin with tasks that you are confident can be accomplished by Continue. For example, ask Continue to fix a small bug where you already know the solution is simple.
- Once you have merged a PR created by Continue, be increasingly ambitious with your tasks. By being willing to start tasks that might not succeed on the first try, you will learn about prompting best practices and limitations of current language models.
- Use thorough prompts. Workflows can run for a long time to complete their task, so it is worthwhile to invest in sharing all of the important details.
- Discuss the use of workflows with your team. Truly embracing Continuous AI likely means acknowledging that a higher volume of PRs will be created and adjusting your code review habits.

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

View file

@ -8,6 +8,7 @@ import nodeFetch from "node-fetch";
import open from "open";
import { getApiClient } from "../config.js";
// eslint-disable-next-line import/order
import { env } from "../env.js";
if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
@ -96,13 +97,24 @@ export function getConfigUri(config: AuthConfig): string | null {
/**
* Gets the model name from any auth config type
* For unauthenticated users or when auth config has no modelName, checks GlobalContext
*/
export function getModelName(config: AuthConfig): string | null {
if (config === null) return null;
return config.modelName || null;
// Priority 1: Logged-in users with modelName in auth config
if (config !== null && config.modelName) {
return config.modelName;
}
// Priority 2: Fall back to GlobalContext (for logged-out users or logged-in without modelName)
return getPersistedModelName();
}
// URI utility functions have been moved to ./uriUtils.ts
import {
getPersistedModelName,
persistModelName,
} from "../util/modelPersistence.js";
import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
import {
@ -214,21 +226,30 @@ export function updateConfigUri(configUri: string | null): void {
/**
* Updates the model name in the authentication configuration
* Returns the updated config so the caller can update in-memory state
* For unauthenticated users, saves to GlobalContext
*/
export function updateModelName(modelName: string | null): void {
export function updateModelName(modelName: string | null): AuthConfig {
// If using CONTINUE_API_KEY environment variable, don't save anything
if (process.env.CONTINUE_API_KEY) {
return;
return loadAuthConfig();
}
const config = loadAuthConfig();
// If logged in, save to auth.json
if (config && isAuthenticatedConfig(config)) {
const updatedConfig: AuthenticatedConfig = {
...config,
modelName: modelName || undefined,
};
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// If logged out, save to GlobalContext
persistModelName(modelName);
return config;
}
/**

View file

@ -3,12 +3,18 @@ import chalk from "chalk";
import { login as workosLogin } from "../auth/workos.js";
import { gracefulExit } from "../util/exit.js";
import { chat } from "./chat.js";
export async function login() {
console.info(chalk.yellow("Logging in to Continue..."));
try {
await workosLogin();
console.info(chalk.green("Successfully logged in!"));
// Start the CLI session after successful login
console.info(chalk.blue("Starting Continue CLI..."));
await chat();
} catch (error: any) {
console.error(chalk.red(`Login failed: ${error.message}`));
await gracefulExit(1);

View file

@ -1,10 +1,9 @@
import { render } from "ink";
import React from "react";
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
import { env } from "../env.js";
import { listSessions, loadSessionById } from "../session.js";
import { SessionSelector } from "../ui/SessionSelector.js";
import { ApiRequestError, post } from "../util/apiClient.js";
import { logger } from "../util/logger.js";
import { chat } from "./chat.js";
@ -27,26 +26,19 @@ function setSessionId(sessionId: string): void {
}
export async function getTunnelForAgent(agentId: string): Promise<string> {
const authConfig = loadAuthConfig();
const accessToken = getAccessToken(authConfig);
const resp = await fetch(
new URL(`agents/${encodeURIComponent(agentId)}/tunnel`, env.apiBase),
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
},
);
if (!resp.ok) {
throw new Error(
`Failed to get tunnel for agent ${agentId}: ${await resp.text()}`,
try {
const response = await post<{ url: string }>(
`agents/${encodeURIComponent(agentId)}/tunnel`,
);
return response.data.url;
} catch (error) {
if (error instanceof ApiRequestError) {
throw new Error(
`Failed to get tunnel for agent ${agentId}: ${error.response || error.statusText}`,
);
}
throw error;
}
const data = await resp.json();
return data.url;
}
/**

View file

@ -8,11 +8,13 @@ vi.mock("../env.js");
vi.mock("../telemetry/telemetryService.js");
vi.mock("../ui/index.js");
vi.mock("../util/git.js");
vi.mock("../util/exit.js");
const mockWorkos = vi.mocked(await import("../auth/workos.js"));
const mockEnv = vi.mocked(await import("../env.js"));
const mockGit = vi.mocked(await import("../util/git.js"));
const mockStartRemoteTUIChat = vi.mocked(await import("../ui/index.js"));
const mockExit = vi.mocked(await import("../util/exit.js"));
// Mock fetch globally
const mockFetch = vi.fn();
@ -62,6 +64,10 @@ describe("remote command", () => {
mockFetch.mockResolvedValue({
ok: true,
headers: {
get: (name: string) =>
name === "content-type" ? "application/json" : null,
},
json: async () => ({
id: "test-agent-id",
url: "ws://test-url.com",
@ -70,6 +76,9 @@ describe("remote command", () => {
});
mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any);
// Mock gracefulExit to prevent process.exit during tests
mockExit.gracefulExit.mockResolvedValue(undefined);
});
it("should include idempotency key in request body when provided", async () => {
@ -151,10 +160,18 @@ describe("remote command", () => {
mockFetch
.mockResolvedValueOnce({
ok: true,
headers: {
get: (name: string) =>
name === "content-type" ? "application/json" : null,
},
json: async () => ({ url: "ws://tunnel-url.com", port: 9090 }),
})
.mockResolvedValue({
ok: true,
headers: {
get: (name: string) =>
name === "content-type" ? "application/json" : null,
},
json: async () => ({
id: "test-agent-id",
url: "ws://test-url.com",
@ -187,6 +204,10 @@ describe("remote command", () => {
mockFetch.mockResolvedValueOnce({
ok: true,
headers: {
get: (name: string) =>
name === "content-type" ? "application/json" : null,
},
json: async () => tunnelResponse,
});

View file

@ -1,9 +1,13 @@
import chalk from "chalk";
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
import { env } from "../env.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
import {
ApiRequestError,
AuthenticationRequiredError,
post,
} from "../util/apiClient.js";
import { gracefulExit } from "../util/exit.js";
import { getRepoUrl } from "../util/git.js";
import { logger } from "../util/logger.js";
@ -28,12 +32,6 @@ type AgentCreationResponse = TunnelResponse & {
id: string;
};
class AuthenticationRequiredError extends Error {
constructor() {
super("Not authenticated. Please run 'cn login' first.");
}
}
export async function remote(
prompt: string | undefined,
options: RemoteCommandOptions = {},
@ -46,19 +44,12 @@ export async function remote(
return;
}
const accessToken = requireAccessToken();
if (options.id) {
await connectExistingAgent(
options.id,
accessToken,
actualPrompt,
options.start,
);
await connectExistingAgent(options.id, actualPrompt, options.start);
return;
}
await createAndConnectRemoteEnvironment(accessToken, actualPrompt, options);
await createAndConnectRemoteEnvironment(actualPrompt, options);
} catch (error) {
await handleRemoteError(error);
}
@ -99,29 +90,12 @@ async function connectToRemoteUrl(
await launchRemoteTUI(remoteUrl, prompt);
}
function requireAccessToken(): string {
const authConfig = loadAuthConfig();
if (!authConfig) {
throw new AuthenticationRequiredError();
}
const accessToken = getAccessToken(authConfig);
if (!accessToken) {
throw new AuthenticationRequiredError();
}
return accessToken;
}
async function connectExistingAgent(
agentId: string,
accessToken: string,
prompt: string | undefined,
startOnly?: boolean,
) {
const tunnel = await fetchAgentTunnel(agentId, accessToken);
const tunnel = await fetchAgentTunnel(agentId);
if (startOnly) {
printStartJson({
@ -142,30 +116,24 @@ async function connectExistingAgent(
}
async function createAndConnectRemoteEnvironment(
accessToken: string,
prompt: string | undefined,
options: RemoteCommandOptions,
) {
const requestBody = buildAgentRequestBody(options, prompt);
const response = await fetch(new URL("agents", env.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`Failed to create remote environment: ${response.status} ${errorText}`,
);
let result: AgentCreationResponse;
try {
const response = await post<AgentCreationResponse>("agents", requestBody);
result = response.data;
} catch (error) {
if (error instanceof ApiRequestError) {
throw new Error(
`Failed to create remote environment: ${error.status} ${error.response || error.statusText}`,
);
}
throw error;
}
const result = (await response.json()) as AgentCreationResponse;
if (options.start) {
printStartJson({
status: "success",
@ -216,26 +184,18 @@ function buildAgentRequestBody(
return body;
}
async function fetchAgentTunnel(agentId: string, accessToken: string) {
const response = await fetch(
new URL(`agents/${agentId}/tunnel`, env.apiBase),
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
},
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`Failed to create tunnel for agent ${agentId}: ${response.status} ${errorText}`,
);
async function fetchAgentTunnel(agentId: string) {
try {
const response = await post<TunnelResponse>(`agents/${agentId}/tunnel`);
return response.data;
} catch (error) {
if (error instanceof ApiRequestError) {
throw new Error(
`Failed to create tunnel for agent ${agentId}: ${error.status} ${error.response || error.statusText}`,
);
}
throw error;
}
return (await response.json()) as TunnelResponse;
}
async function launchRemoteTUI(remoteUrl: string, prompt: string | undefined) {

View file

@ -259,6 +259,32 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
});
});
// POST /pause - Pause the current agent run (like pressing escape in TUI)
app.post("/pause", async (_req: Request, res: Response) => {
state.lastActivity = Date.now();
// Check if there's anything to pause
if (!state.isProcessing) {
return res.json({
success: false,
message: "No active processing to pause",
});
}
// Abort the current processing
if (state.currentAbortController) {
state.currentAbortController.abort();
}
// Set isProcessing to false
state.isProcessing = false;
res.json({
success: true,
message: "Agent run paused",
});
});
// GET /diff - Return git diff against main branch
app.get("/diff", async (_req: Request, res: Response) => {
state.lastActivity = Date.now();
@ -343,6 +369,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
" POST /permission - Approve/reject tool (body: { requestId, approved })",
),
);
console.log(chalk.dim(" POST /pause - Pause the current agent run"));
console.log(
chalk.dim(" GET /diff - Get git diff against main branch"),
);

View file

@ -115,7 +115,7 @@ models:
if (configExists) {
const configContent = await fs.readFile(configPath, "utf-8");
expect(configContent).toContain("anthropic/claude-4-sonnet");
expect(configContent).toContain("anthropic/claude-sonnet-4-5");
expect(configContent).toContain(
"ANTHROPIC_API_KEY: TEST-test-invalid-key-format",
);

View file

@ -0,0 +1,209 @@
/**
* E2E test for headless mode permission errors
* Verifies that when a tool requires permission in headless mode,
* an appropriate error message is displayed suggesting the --auto flag
*/
import * as http from "http";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import {
cleanupMockLLMServer,
setupMockLLMTest,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode Permission Errors", () => {
let context: any;
let mockServer: MockLLMServer;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
if (mockServer) {
await cleanupMockLLMServer(mockServer);
}
await cleanupTestContext(context);
});
it("should display error message with --auto suggestion when tool requires permission", async () => {
// Set up mock LLM to return a tool call that requires permission (Write tool)
mockServer = await setupMockLLMTest(context, {
customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
if (req.method === "POST" && req.url === "/chat/completions") {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
// Send a Write tool call (requires permission by default)
res.write(
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
);
res.write(
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
);
// Send usage data
res.write(
`data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
);
// End the stream
res.write(`data: [DONE]\n\n`);
res.end();
} else {
res.writeHead(404);
res.end("Not found");
}
});
},
});
// Run CLI in headless mode without permission flags
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Create a file test.txt"],
timeout: 15000,
});
// Expect non-zero exit code
expect(result.exitCode).toBe(1);
// Verify the error message contains the expected information
expect(result.stderr).toContain("requires permission");
expect(result.stderr).toContain("headless mode");
expect(result.stderr).toContain("--auto");
expect(result.stderr).toContain("--allow");
expect(result.stderr).toContain("--exclude");
}, 20000);
it("should succeed with --auto flag when tool requires permission", async () => {
// Set up mock LLM to return a Write tool call
mockServer = await setupMockLLMTest(context, {
customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
if (req.method === "POST" && req.url === "/chat/completions") {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
// Send a Write tool call
res.write(
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
);
res.write(
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
);
// Send usage data
res.write(
`data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
);
// End the stream
res.write(`data: [DONE]\n\n`);
res.end();
} else {
res.writeHead(404);
res.end("Not found");
}
});
},
});
// Run CLI with --auto flag
const result = await runCLI(context, {
args: [
"-p",
"--auto",
"--config",
context.configPath,
"Create a file test.txt",
],
timeout: 15000,
});
// Should succeed
expect(result.exitCode).toBe(0);
expect(result.stderr).not.toContain("requires permission");
}, 20000);
it("should succeed with --allow flag for specific tool", async () => {
// Set up mock LLM to return a Write tool call
mockServer = await setupMockLLMTest(context, {
customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
if (req.method === "POST" && req.url === "/chat/completions") {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
// Send a Write tool call
res.write(
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
);
res.write(
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
);
// Send usage data
res.write(
`data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
);
// End the stream
res.write(`data: [DONE]\n\n`);
res.end();
} else {
res.writeHead(404);
res.end("Not found");
}
});
},
});
// Run CLI with --allow Write flag
const result = await runCLI(context, {
args: [
"-p",
"--allow",
"Write",
"--config",
context.configPath,
"Create a file test.txt",
],
timeout: 15000,
});
// Should succeed
expect(result.exitCode).toBe(0);
expect(result.stderr).not.toContain("requires permission");
}, 20000);
});

View file

@ -0,0 +1,205 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
AuthenticatedConfig,
getModelName,
loadAuthConfig,
saveAuthConfig,
updateModelName,
} from "../auth/workos.js";
import * as config from "../config.js";
import { ModelService } from "../services/ModelService.js";
import { persistModelName } from "../util/modelPersistence.js";
// Mock the config module
vi.mock("../config.js");
describe("Model Persistence End-to-End", () => {
let testDir: string;
let originalContinueHome: string | undefined;
let mockAssistant: AssistantUnrolled;
let mockAuthConfig: AuthenticatedConfig;
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
beforeEach(() => {
vi.clearAllMocks();
// Create a temporary directory for testing
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = testDir;
// Clear GlobalContext for clean test state
persistModelName(null);
mockAssistant = {
name: "test-assistant",
version: "1.0.0",
models: [
{
provider: "openai",
model: "gpt-4",
name: "GPT-4",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
name: "Claude 3.5 Sonnet",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-opus-20240229",
name: "Claude 3 Opus",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
],
} as AssistantUnrolled;
mockAuthConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000, // 1 hour from now
organizationId: "test-org",
};
// Setup default mock behavior
vi.mocked(config.getLlmApi).mockReturnValue([
mockLlmApi as any,
mockAssistant.models![0] as ModelConfig,
]);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
});
afterEach(() => {
// Cleanup
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true });
}
if (originalContinueHome) {
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
} else {
delete process.env.CONTINUE_GLOBAL_DIR;
}
});
test("should restore model selection after restart", async () => {
// Step 1: Initial session - user starts with default model (GPT-4)
saveAuthConfig(mockAuthConfig);
let service = new ModelService();
let state = await service.initialize(mockAssistant, mockAuthConfig);
console.log("Initial model:", state.model?.name);
expect(state.model?.name).toBe("GPT-4");
// Step 2: User switches to Claude 3.5 Sonnet (index 1)
await service.switchModel(1);
state = service.getState();
console.log("After switch:", state.model?.name);
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
// Step 3: Persist the model choice (this should happen in useModelSelector)
updateModelName("Claude 3.5 Sonnet");
// Verify it was saved to auth.json
const savedConfig = loadAuthConfig();
console.log("Saved model name:", getModelName(savedConfig));
expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
// Step 4: Simulate restart - create new service instance
// Load fresh auth config from disk (this is what the real code does)
const freshAuthConfig = loadAuthConfig();
console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
service = new ModelService();
state = await service.initialize(mockAssistant, freshAuthConfig);
// Step 5: Verify the persisted model is restored
console.log("After restart:", state.model?.name);
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
expect(state.model?.provider).toBe("anthropic");
});
test("should handle model name mismatch gracefully", async () => {
// Save auth config with a model that doesn't exist
mockAuthConfig.modelName = "Non-existent Model";
saveAuthConfig(mockAuthConfig);
const service = new ModelService();
const state = await service.initialize(mockAssistant, mockAuthConfig);
// Should fall back to first available model (GPT-4)
expect(state.model?.name).toBe("GPT-4");
});
test("should check both name and model fields when matching", async () => {
// Some configs might have model field instead of name
const assistantWithModelField = {
...mockAssistant,
models: [
{
provider: "openai",
model: "gpt-4",
// No name field, just model
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
// No name field, just model
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
],
} as AssistantUnrolled;
mockAuthConfig.modelName = "claude-3-5-sonnet-20241022";
saveAuthConfig(mockAuthConfig);
const service = new ModelService();
const state = await service.initialize(
assistantWithModelField,
mockAuthConfig,
);
// Should match by model field
expect(state.model?.model).toBe("claude-3-5-sonnet-20241022");
});
test("should persist model through multiple switches", async () => {
saveAuthConfig(mockAuthConfig);
const service = new ModelService();
await service.initialize(mockAssistant, mockAuthConfig);
// Switch to Claude 3.5 Sonnet
await service.switchModel(1);
updateModelName("Claude 3.5 Sonnet");
expect(getModelName(loadAuthConfig())).toBe("Claude 3.5 Sonnet");
// Switch to Claude 3 Opus
await service.switchModel(2);
updateModelName("Claude 3 Opus");
expect(getModelName(loadAuthConfig())).toBe("Claude 3 Opus");
// Restart and verify last selection
const freshAuthConfig = loadAuthConfig();
console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
const newService = new ModelService();
const state = await newService.initialize(mockAssistant, freshAuthConfig);
expect(state.model?.name).toBe("Claude 3 Opus");
});
});

View file

@ -0,0 +1,245 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
getModelName,
loadAuthConfig,
updateModelName,
} from "../auth/workos.js";
import * as config from "../config.js";
import { ModelService } from "../services/ModelService.js";
import {
getPersistedModelName,
persistModelName,
} from "../util/modelPersistence.js";
// Mock the config module
vi.mock("../config.js");
describe("Model Persistence for Unauthenticated Users", () => {
let testDir: string;
let originalContinueHome: string | undefined;
let mockAssistant: AssistantUnrolled;
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
beforeEach(() => {
vi.clearAllMocks();
// Create a temporary directory for testing
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = testDir;
// Clear GlobalContext for clean test state
persistModelName(null);
mockAssistant = {
name: "test-assistant",
version: "1.0.0",
models: [
{
provider: "openai",
model: "gpt-4",
name: "GPT-4",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
name: "Claude 3.5 Sonnet",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-opus-20240229",
name: "Claude 3 Opus",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
],
} as AssistantUnrolled;
// Setup default mock behavior
vi.mocked(config.getLlmApi).mockReturnValue([
mockLlmApi as any,
mockAssistant.models![0] as ModelConfig,
]);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
});
afterEach(() => {
// Cleanup
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true });
}
if (originalContinueHome) {
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
} else {
delete process.env.CONTINUE_GLOBAL_DIR;
}
});
test("should persist model selection for logged-out users", () => {
// User is logged out (no auth config)
const authConfig = loadAuthConfig();
expect(authConfig).toBeNull();
// User switches model
updateModelName("Claude 3.5 Sonnet");
// Verify it was saved to GlobalContext
const persistedModel = getPersistedModelName();
expect(persistedModel).toBe("Claude 3.5 Sonnet");
// Verify getModelName returns it for null config
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
});
test("should restore model selection on next session for logged-out users", async () => {
// Session 1: User is logged out and switches model
const authConfig = loadAuthConfig();
expect(authConfig).toBeNull();
const modelService = new ModelService();
await modelService.initialize(mockAssistant, authConfig);
await modelService.switchModel(1);
updateModelName("Claude 3.5 Sonnet");
// Session 2: User reopens CLI (still logged out)
const newAuthConfig = loadAuthConfig();
expect(newAuthConfig).toBeNull();
const newModelService = new ModelService();
const state = await newModelService.initialize(
mockAssistant,
newAuthConfig,
);
// Should restore Claude 3.5 Sonnet
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
});
test("should handle multiple model switches for logged-out users", () => {
updateModelName("GPT-4");
expect(getModelName(null)).toBe("GPT-4");
updateModelName("Claude 3.5 Sonnet");
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
updateModelName("Claude 3 Opus");
expect(getModelName(null)).toBe("Claude 3 Opus");
});
test("should clear model selection when set to null", () => {
updateModelName("Claude 3.5 Sonnet");
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
updateModelName(null);
expect(getModelName(null)).toBeNull();
});
test("should preserve GlobalContext model when user logs in", () => {
// User is logged out with a persisted model
updateModelName("Claude 3.5 Sonnet");
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
// User logs in (simulated by having auth.json)
const authPath = path.join(testDir, "auth.json");
fs.writeFileSync(
authPath,
JSON.stringify({
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
}),
);
const authConfig = loadAuthConfig();
expect(authConfig).not.toBeNull();
// GlobalContext model should still exist
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
// When auth config has no modelName, it should fall back to GlobalContext
expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
});
test("should use auth config model when both exist", () => {
// Clear previous state
updateModelName(null);
// Set GlobalContext model
updateModelName("GPT-4");
expect(getPersistedModelName()).toBe("GPT-4");
// Create auth config with different model
const authPath = path.join(testDir, "auth.json");
fs.writeFileSync(
authPath,
JSON.stringify({
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
modelName: "Claude 3.5 Sonnet",
}),
);
const authConfig = loadAuthConfig();
// Auth config should take precedence
expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
});
test("should not save to GlobalContext when using CONTINUE_API_KEY", () => {
// Clear any existing model
updateModelName(null);
expect(getPersistedModelName()).toBeNull();
// Capture original value to restore after test
const originalApiKey = process.env.CONTINUE_API_KEY;
process.env.CONTINUE_API_KEY = "test-api-key";
updateModelName("Claude 3.5 Sonnet");
// Should not be saved to GlobalContext
expect(getPersistedModelName()).toBeNull();
// Restore original value
if (originalApiKey === undefined) {
delete process.env.CONTINUE_API_KEY;
} else {
process.env.CONTINUE_API_KEY = originalApiKey;
}
});
test("should work across config changes for logged-out users", async () => {
// User switches model with one config
updateModelName("Claude 3.5 Sonnet");
const modelService = new ModelService();
let state = await modelService.initialize(mockAssistant, null);
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
// User switches to a different model
await modelService.switchModel(2);
updateModelName("Claude 3 Opus");
// Create new service (simulating restart)
const newModelService = new ModelService();
state = await newModelService.initialize(mockAssistant, null);
expect(state.model?.name).toBe("Claude 3 Opus");
});
});

View file

@ -0,0 +1,153 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
AuthenticatedConfig,
getModelName,
loadAuthConfig,
saveAuthConfig,
} from "../auth/workos.js";
import * as config from "../config.js";
import { AuthService } from "../services/AuthService.js";
import { ModelService } from "../services/ModelService.js";
// Mock the config module
vi.mock("../config.js");
describe("Model Persistence User Flow", () => {
let testDir: string;
let originalContinueHome: string | undefined;
let mockAssistant: AssistantUnrolled;
let mockAuthConfig: AuthenticatedConfig;
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
beforeEach(() => {
vi.clearAllMocks();
// Create a temporary directory for testing
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = testDir;
mockAssistant = {
name: "test-assistant",
version: "1.0.0",
models: [
{
provider: "openai",
model: "gpt-4",
name: "GPT-4",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
name: "Claude 3.5 Sonnet",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
{
provider: "anthropic",
model: "claude-3-opus-20240229",
name: "Claude 3 Opus",
apiKey: "test-key",
roles: ["chat"],
} as ModelConfig,
],
} as AssistantUnrolled;
mockAuthConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000, // 1 hour from now
organizationId: "test-org",
};
// Setup default mock behavior
vi.mocked(config.getLlmApi).mockReturnValue([
mockLlmApi as any,
mockAssistant.models![0] as ModelConfig,
]);
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
});
afterEach(() => {
// Cleanup
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true });
}
if (originalContinueHome) {
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
} else {
delete process.env.CONTINUE_GLOBAL_DIR;
}
});
test("should persist model choice exactly as user experiences it", async () => {
console.log("\n=== SESSION 1: User opens cn and switches model ===");
// Session 1: User starts CLI
// Save initial auth config (what happens after login)
saveAuthConfig(mockAuthConfig);
console.log("1. Initial auth.json saved");
// Initialize ModelService (what happens on CLI start)
const modelService = new ModelService();
const state = await modelService.initialize(mockAssistant, mockAuthConfig);
console.log("2. Initial model:", state.model?.name);
expect(state.model?.name).toBe("GPT-4");
// User switches to Claude 3.5 Sonnet via UI
await modelService.switchModel(1);
const modelInfo = modelService.getModelInfo();
console.log("3. User switched to:", modelInfo?.name);
expect(modelInfo?.name).toBe("Claude 3.5 Sonnet");
// useModelSelector calls updateModelName
const { updateModelName } = await import("../auth/workos.js");
const updatedAuthConfig = updateModelName("Claude 3.5 Sonnet");
console.log("4. Model name persisted to disk");
// Verify it was saved
const savedConfig = loadAuthConfig();
console.log("5. Read back from disk:", getModelName(savedConfig));
expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
// User closes CLI
console.log("6. User exits CLI\n");
console.log("=== SESSION 2: User reopens cn ===");
// Session 2: User restarts CLI
// Initialize AuthService (loads from disk)
const authService = new AuthService();
const authState = await authService.initialize();
console.log(
"7. AuthService loaded, modelName in auth:",
getModelName(authState.authConfig),
);
// Initialize ModelService with fresh auth state
const newModelService = new ModelService();
const newState = await newModelService.initialize(
mockAssistant,
authState.authConfig,
);
console.log(
"8. ModelService initialized with model:",
newState.model?.name,
);
// EXPECTATION: Should restore Claude 3.5 Sonnet
expect(newState.model?.name).toBe("Claude 3.5 Sonnet");
expect(newState.model?.provider).toBe("anthropic");
console.log("✅ Model persisted correctly!\n");
});
});

View file

@ -0,0 +1,194 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import {
AuthenticatedConfig,
getModelName,
loadAuthConfig,
saveAuthConfig,
updateModelName,
} from "../auth/workos.js";
import { persistModelName } from "../util/modelPersistence.js";
describe("Model Persistence Integration", () => {
let testDir: string;
let originalContinueHome: string | undefined;
beforeEach(() => {
// Create a temporary directory for testing
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
process.env.CONTINUE_GLOBAL_DIR = testDir;
// Clear GlobalContext for clean test state
persistModelName(null);
});
afterEach(() => {
// Cleanup
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true });
}
if (originalContinueHome) {
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
} else {
delete process.env.CONTINUE_GLOBAL_DIR;
}
});
test("should persist model name when user selects a model", () => {
// Create initial auth config without model name
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
};
saveAuthConfig(authConfig);
// User selects a model
updateModelName("Claude 3.5 Sonnet");
// Load config and verify model name is persisted
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
});
test("should update model name when user switches models", () => {
// Create initial auth config with a model
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
modelName: "GPT-4",
};
saveAuthConfig(authConfig);
// User switches to a different model
updateModelName("Claude 3.5 Sonnet");
// Load config and verify new model name
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
});
test("should preserve other auth config fields when updating model", () => {
// Create initial auth config
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
configUri: "slug://owner/my-config",
};
saveAuthConfig(authConfig);
// Update model name
updateModelName("Claude 3.5 Sonnet");
// Load config and verify all fields are preserved
const loadedConfig = loadAuthConfig();
expect(loadedConfig).toMatchObject({
userId: "test-user",
userEmail: "test@example.com",
organizationId: "test-org",
configUri: "slug://owner/my-config",
modelName: "Claude 3.5 Sonnet",
});
});
test("should clear model name when set to null", () => {
// Create initial auth config with a model
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
modelName: "GPT-4",
};
saveAuthConfig(authConfig);
// Clear model name
updateModelName(null);
// Load config and verify model name is cleared
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBeNull();
});
test("should return null for model name when not authenticated and no GlobalContext", () => {
// No auth config exists and no GlobalContext model
persistModelName(null); // Ensure GlobalContext is clear
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBeNull();
});
test("should not persist model name when using CONTINUE_API_KEY", () => {
// Clear GlobalContext first
persistModelName(null);
// Capture original value to restore after test
const originalApiKey = process.env.CONTINUE_API_KEY;
// Set environment variable
process.env.CONTINUE_API_KEY = "test-api-key";
// Try to update model name
updateModelName("Claude 3.5 Sonnet");
// Load config - should be environment auth config without model name
const loadedConfig = loadAuthConfig();
expect(getModelName(loadedConfig)).toBeNull();
// Restore original value
if (originalApiKey === undefined) {
delete process.env.CONTINUE_API_KEY;
} else {
process.env.CONTINUE_API_KEY = originalApiKey;
}
});
test("should persist model name in auth.json file with correct format", () => {
// Create and save auth config
const authConfig: AuthenticatedConfig = {
userId: "test-user",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh",
expiresAt: Date.now() + 3600000,
organizationId: "test-org",
};
saveAuthConfig(authConfig);
updateModelName("Claude 3.5 Sonnet");
// Read the raw file content
const authPath = path.join(testDir, "auth.json");
const rawContent = fs.readFileSync(authPath, "utf8");
const parsedContent = JSON.parse(rawContent);
// Verify the file structure
expect(parsedContent).toHaveProperty("userId", "test-user");
expect(parsedContent).toHaveProperty("userEmail", "test@example.com");
expect(parsedContent).toHaveProperty("organizationId", "test-org");
expect(parsedContent).toHaveProperty("modelName", "Claude 3.5 Sonnet");
// Verify it's pretty-printed (has indentation)
expect(rawContent).toContain("\n ");
});
});

View file

@ -0,0 +1,66 @@
import { describe, expect, it, vi } from "vitest";
import type { PreprocessedToolCall } from "../tools/types.js";
import { handleHeadlessPermission } from "./streamChatResponse.helpers.js";
describe("streamChatResponse.helpers", () => {
describe("handleHeadlessPermission", () => {
it("should display error message and exit when tool requires permission in headless mode", async () => {
// Mock the tool call
const toolCall: PreprocessedToolCall = {
id: "call_123",
name: "Write",
arguments: { filepath: "test.txt", content: "hello" },
argumentsStr: '{"filepath":"test.txt","content":"hello"}',
startNotified: false,
tool: {
name: "Write",
displayName: "Write",
description: "Write to a file",
parameters: {
type: "object",
properties: {},
},
run: vi.fn(),
isBuiltIn: true,
},
};
// Mock safeStderr to capture output
const stderrOutputs: string[] = [];
vi.doMock("../init.js", () => ({
safeStderr: (message: string) => {
stderrOutputs.push(message);
},
}));
// Mock gracefulExit to prevent actual process exit
let exitCode: number | undefined;
vi.doMock("../util/exit.js", () => ({
gracefulExit: async (code: number) => {
exitCode = code;
},
}));
// Call the function (it should exit gracefully)
try {
await handleHeadlessPermission(toolCall);
} catch (error) {
// Expected to throw after exit
}
// Verify error message was displayed
const fullOutput = stderrOutputs.join("");
expect(fullOutput).toContain("requires permission");
expect(fullOutput).toContain("headless mode");
expect(fullOutput).toContain("--auto");
expect(fullOutput).toContain("--allow");
expect(fullOutput).toContain("--exclude");
expect(fullOutput).toContain("Write");
// Verify it tried to exit with code 1
expect(exitCode).toBe(1);
});
});
});

View file

@ -51,25 +51,30 @@ export function handlePermissionDenied(
}
// Helper function to handle headless mode permission
export function handleHeadlessPermission(
export async function handleHeadlessPermission(
toolCall: PreprocessedToolCall,
): never {
): Promise<never> {
const allBuiltinTools = getAllBuiltinTools();
const tool = allBuiltinTools.find((t) => t.name === toolCall.name);
const toolName = tool?.displayName || toolCall.name;
console.error(
`Error: Tool '${toolName}' requires permission but cn is running in headless mode.`,
// Import safeStderr to bypass console blocking in headless mode
const { safeStderr } = await import("../init.js");
safeStderr(
`Error: Tool '${toolName}' requires permission but cn is running in headless mode.\n`,
);
console.error(`If you want to allow this tool, use --allow ${toolName}.`);
console.error(
`If you don't want the tool to be included, use --exclude ${toolName}.`,
safeStderr(
`If you want to allow all tools without asking, use cn -p --auto "your prompt".\n`,
);
safeStderr(`If you want to allow this tool, use --allow ${toolName}.\n`);
safeStderr(
`If you don't want the tool to be included, use --exclude ${toolName}.\n`,
);
// Use graceful exit to flush telemetry even in headless denial
// Note: We purposely trigger an async exit without awaiting in this sync path
import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1));
// Throw to satisfy the never return type; process will exit shortly
const { gracefulExit } = await import("../util/exit.js");
await gracefulExit(1);
// This line will never be reached, but TypeScript needs it for the 'never' return type
throw new Error("Exiting due to headless permission requirement");
}
@ -133,7 +138,7 @@ export async function checkToolPermissionApproval(
return { approved: true };
} else if (permissionCheck.permission === "ask") {
if (isHeadless) {
handleHeadlessPermission(toolCall);
await handleHeadlessPermission(toolCall);
}
const userApproved = await requestUserPermission(toolCall, callbacks);
return userApproved

View file

@ -104,18 +104,22 @@ WARNINGS:
},
},
preprocess: async (args) => {
const { old_string, new_string, replace_all = false } = args as EditArgs;
const { old_string, new_string, replace_all } = args as EditArgs;
const { resolvedPath } = validateAndResolveFilePath(args);
validateSingleEdit(old_string, new_string);
const { oldString, newString, replaceAll } = validateSingleEdit(
old_string,
new_string,
replace_all,
);
const oldContent = fs.readFileSync(resolvedPath, "utf-8");
const newContent = executeFindAndReplace(
oldContent,
old_string,
new_string,
replace_all,
oldString,
newString,
replaceAll ?? false,
0,
);

View file

@ -23,6 +23,7 @@ import { multiEditTool } from "./multiEdit.js";
import { readFileTool } from "./readFile.js";
import { runTerminalCommandTool } from "./runTerminalCommand.js";
import { searchCodeTool } from "./searchCode.js";
import { statusTool } from "./status.js";
import {
type Tool,
type ToolCall,
@ -70,6 +71,11 @@ function getDynamicTools(): Tool[] {
// Service not ready yet, no dynamic tools
}
// Add beta status tool if --beta-status-tool flag is present
if (process.argv.includes("--beta-status-tool")) {
dynamicTools.push(statusTool);
}
return dynamicTools;
}

View file

@ -0,0 +1,78 @@
import {
ApiRequestError,
AuthenticationRequiredError,
post,
} from "../util/apiClient.js";
import { logger } from "../util/logger.js";
import { Tool } from "./types.js";
/**
* Extract the agent ID from the --id command line flag
*/
function getAgentIdFromArgs(): string | undefined {
const args = process.argv;
const idIndex = args.indexOf("--id");
if (idIndex !== -1 && idIndex + 1 < args.length) {
return args[idIndex + 1];
}
return undefined;
}
export const statusTool: Tool = {
name: "Status",
displayName: "Status",
description: `Set the current status of your task for the user to see
The available statuses are:
- PLANNING: You are creating a plan before beginning implementation
- WORKING: The task is in progress
- DONE: The task is complete
- BLOCKED: You need further information from the user in order to proceed
You should use this tool to notify the user whenever the state of your work changes. By default, the status is assumed to be "PLANNING" prior to you setting a different status.`,
parameters: {
type: "object",
required: ["status"],
properties: {
status: {
type: "string",
description: "The status value to set",
},
},
},
readonly: true,
isBuiltIn: true,
run: async (args: { status: string }): Promise<string> => {
try {
// Get agent ID from --id flag
const agentId = getAgentIdFromArgs();
if (!agentId) {
const errorMessage =
"Agent ID is required. Please use the --id flag with cn serve.";
logger.error(errorMessage);
return `Error: ${errorMessage}`;
}
// Call the API endpoint using shared client
await post(`agents/${agentId}/status`, { status: args.status });
logger.info(`Status: ${args.status}`);
return `Status set: ${args.status}`;
} catch (error) {
if (error instanceof AuthenticationRequiredError) {
logger.error(error.message);
return "Error: Authentication required";
}
if (error instanceof ApiRequestError) {
return `Error setting status: ${error.status} ${error.response || error.statusText}`;
}
const errorMessage =
error instanceof Error ? error.message : String(error);
logger.error(`Error setting status: ${errorMessage}`);
return `Error setting status: ${errorMessage}`;
}
},
};

View file

@ -264,6 +264,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
configPath,
setChatHistory,
handleClear,
setStaticRefreshTrigger,
);
// Session selection handler

View file

@ -611,6 +611,30 @@ describe("TextBuffer", () => {
expect(buffer.cursor).toBe(2);
});
it("should limit ctrl+u deletion to current line", () => {
const text = "first line\nsecond line\nthird";
buffer.setText(text);
buffer.setCursor(text.indexOf("second line") + "second line".length);
const result = buffer.handleInput("u", { ctrl: true } as any);
expect(result).toBe(true);
expect(buffer.text).toBe("first line\n\nthird");
expect(buffer.cursor).toBe("first line\n".length);
});
it("should limit ctrl+k deletion to current line", () => {
const text = "first line\nsecond line\nthird";
buffer.setText(text);
buffer.setCursor(text.indexOf("second line"));
const result = buffer.handleInput("k", { ctrl: true } as any);
expect(result).toBe(true);
expect(buffer.text).toBe("first line\n\nthird");
expect(buffer.cursor).toBe(text.indexOf("second line"));
});
it("should handle arrow keys", () => {
let result = buffer.handleInput("", { leftArrow: true } as any);
expect(result).toBe(true);
@ -644,6 +668,38 @@ describe("TextBuffer", () => {
expect(buffer.cursor).toBe(0);
});
it("should delete to start of line with meta+backspace", () => {
const text = "first line\nsecond line\nthird line";
buffer.setText(text);
const cursorPosition = text.indexOf("second line") + "second line".length;
buffer.setCursor(cursorPosition);
const result = buffer.handleInput("", {
meta: true,
backspace: true,
} as any);
expect(result).toBe(true);
expect(buffer.text).toBe("first line\n\nthird line");
expect(buffer.cursor).toBe("first line\n".length);
});
it("should delete to end of line with meta+delete", () => {
const text = "first line\nsecond line\nthird line";
buffer.setText(text);
const cursorPosition = text.indexOf("second line");
buffer.setCursor(cursorPosition);
const result = buffer.handleInput("", {
meta: true,
delete: true,
} as any);
expect(result).toBe(true);
expect(buffer.text).toBe("first line\n\nthird line");
expect(buffer.cursor).toBe(cursorPosition);
});
it("should handle option key sequences", () => {
const result = buffer.handleInput("\u001b\u007f", {} as any);
expect(result).toBe(true);

View file

@ -137,6 +137,38 @@ export class TextBuffer {
}
}
private deleteLineBackward(): void {
if (this._cursor === 0) {
return;
}
const lastNewline = this._text.lastIndexOf("\n", this._cursor - 1);
const lineStart = lastNewline === -1 ? 0 : lastNewline + 1;
if (lineStart === this._cursor) {
return;
}
this._text =
this._text.slice(0, lineStart) + this._text.slice(this._cursor);
this._cursor = lineStart;
}
private deleteLineForward(): void {
if (this._cursor >= this._text.length) {
return;
}
const nextNewline = this._text.indexOf("\n", this._cursor);
const lineEnd = nextNewline === -1 ? this._text.length : nextNewline;
if (lineEnd === this._cursor) {
return;
}
this._text = this._text.slice(0, this._cursor) + this._text.slice(lineEnd);
}
moveToStart(): void {
this._cursor = 0;
}
@ -402,13 +434,10 @@ export class TextBuffer {
this.moveToEnd();
return true;
case "u":
// Delete from cursor to start of line
this._text = this._text.slice(this._cursor);
this._cursor = 0;
this.deleteLineBackward();
return true;
case "k":
// Delete from cursor to end of line
this._text = this._text.slice(0, this._cursor);
this.deleteLineForward();
return true;
case "w":
this.deleteWordBackward();
@ -422,8 +451,12 @@ export class TextBuffer {
}
private handleMetaKey(input: string, key: Key): boolean {
if (key.backspace || key.delete) {
this.deleteWordBackward();
if (key.backspace) {
this.deleteLineBackward();
return true;
}
if (key.delete) {
this.deleteLineForward();
return true;
}
if (key.leftArrow) {

View file

@ -4,7 +4,7 @@ import {
serviceContainer,
services,
} from "../../services/index.js";
import { ModelServiceState } from "../../services/types.js";
import { AuthServiceState, ModelServiceState } from "../../services/types.js";
import { useNavigation } from "../context/NavigationContext.js";
interface ModelOption {
@ -21,11 +21,13 @@ interface UseModelSelectorProps {
messageType: "system";
}) => void;
onModelSwitch?: () => void;
onRefreshUI?: () => void;
}
export function useModelSelector({
onMessage,
onModelSwitch,
onRefreshUI,
}: UseModelSelectorProps) {
const { closeCurrentScreen } = useNavigation();
@ -44,8 +46,17 @@ export function useModelSelector({
);
// Persist the model choice using the actual model name
// and update the auth service state to reflect the change
if (modelInfo?.name) {
updateModelName(modelInfo.name);
const updatedAuthConfig = updateModelName(modelInfo.name);
// Update the AUTH service state in the container with the new config
// This ensures that when MODEL service is reloaded, it gets the updated auth config
const currentAuthState = services.auth.getState();
serviceContainer.set<AuthServiceState>(SERVICE_NAMES.AUTH, {
...currentAuthState,
authConfig: updatedAuthConfig,
});
}
onMessage({
@ -58,6 +69,11 @@ export function useModelSelector({
if (onModelSwitch) {
onModelSwitch();
}
// Force UI refresh to update the IntroMessage with new model
if (onRefreshUI) {
onRefreshUI();
}
} catch (error: any) {
onMessage({
role: "system",

View file

@ -175,6 +175,7 @@ export function useSelectors(
configPath: string | undefined,
setChatHistory: React.Dispatch<React.SetStateAction<any[]>>,
handleClear: () => void,
setStaticRefreshTrigger?: React.Dispatch<React.SetStateAction<number>>,
): {
handleConfigSelect: (config: ConfigOption) => Promise<void>;
handleModelSelect: (model: ModelOption) => Promise<void>;
@ -205,6 +206,12 @@ export function useSelectors(
},
]);
},
onRefreshUI: () => {
// Force a UI refresh to update the IntroMessage with new model
if (setStaticRefreshTrigger) {
setStaticRefreshTrigger((prev) => prev + 1);
}
},
});
return {

View file

@ -0,0 +1,283 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
ApiRequestError,
AuthenticationRequiredError,
del,
get,
makeAuthenticatedRequest,
post,
put,
} from "./apiClient.js";
// Mock the dependencies
vi.mock("../auth/workos.js", () => ({
loadAuthConfig: vi.fn(),
getAccessToken: vi.fn(),
}));
vi.mock("../env.js", () => ({
env: {
apiBase: "https://api.continue.dev",
},
}));
vi.mock("./logger.js", () => ({
logger: {
debug: vi.fn(),
error: vi.fn(),
},
}));
// Mock fetch globally
global.fetch = vi.fn();
describe("apiClient", () => {
let mockLoadAuthConfig: any;
let mockGetAccessToken: any;
const mockFetch = vi.mocked(global.fetch);
beforeEach(async () => {
vi.clearAllMocks();
// Get mocked functions
const authModule = await import("../auth/workos.js");
mockLoadAuthConfig = vi.mocked(authModule.loadAuthConfig);
mockGetAccessToken = vi.mocked(authModule.getAccessToken);
// Setup default successful authentication
mockLoadAuthConfig.mockReturnValue({ some: "config" });
mockGetAccessToken.mockReturnValue("test-access-token");
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("makeAuthenticatedRequest", () => {
test("should make successful API request", async () => {
mockFetch.mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: { get: vi.fn().mockReturnValue("application/json") },
json: vi.fn().mockResolvedValue({ data: "test" }),
} as unknown as Response);
const result = await makeAuthenticatedRequest("test-endpoint", {
method: "POST",
body: { key: "value" },
});
expect(mockFetch).toHaveBeenCalledWith(
new URL("test-endpoint", "https://api.continue.dev"),
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-access-token",
},
body: JSON.stringify({ key: "value" }),
},
);
expect(result).toEqual({
data: { data: "test" },
status: 200,
ok: true,
});
});
test("should handle non-JSON response", async () => {
mockFetch.mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: { get: vi.fn().mockReturnValue("text/plain") },
text: vi.fn().mockResolvedValue("plain text response"),
} as unknown as Response);
const result = await makeAuthenticatedRequest("test-endpoint");
expect(result.data).toBe("plain text response");
});
test("should throw AuthenticationRequiredError when no auth config", async () => {
mockLoadAuthConfig.mockReturnValue(null);
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
AuthenticationRequiredError,
);
});
test("should throw AuthenticationRequiredError when no access token", async () => {
mockGetAccessToken.mockReturnValue(null);
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
AuthenticationRequiredError,
);
});
test("should throw ApiRequestError on API error", async () => {
mockFetch.mockResolvedValue({
ok: false,
status: 404,
statusText: "Not Found",
headers: { get: vi.fn() },
text: vi.fn().mockResolvedValue("Resource not found"),
} as unknown as Response);
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
ApiRequestError,
);
});
test("should handle network error", async () => {
mockFetch.mockRejectedValue(new Error("Network error"));
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
"Request failed: Network error",
);
});
test("should handle string body", async () => {
mockFetch.mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: { get: vi.fn().mockReturnValue("application/json") },
json: vi.fn().mockResolvedValue({ success: true }),
} as unknown as Response);
await makeAuthenticatedRequest("test-endpoint", {
method: "POST",
body: "raw string body",
});
expect(mockFetch).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
body: "raw string body",
}),
);
});
test("should merge custom headers", async () => {
mockFetch.mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: { get: vi.fn().mockReturnValue("application/json") },
json: vi.fn().mockResolvedValue({}),
} as unknown as Response);
await makeAuthenticatedRequest("test-endpoint", {
headers: { "Custom-Header": "custom-value" },
});
expect(mockFetch).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-access-token",
"Custom-Header": "custom-value",
},
}),
);
});
});
describe("convenience methods", () => {
beforeEach(() => {
mockFetch.mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: { get: vi.fn().mockReturnValue("application/json") },
json: vi.fn().mockResolvedValue({ success: true }),
} as unknown as Response);
});
test("get method should make GET request", async () => {
await get("test-endpoint");
expect(mockFetch).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({ method: "GET" }),
);
});
test("post method should make POST request", async () => {
await post("test-endpoint", { data: "test" });
expect(mockFetch).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
method: "POST",
body: JSON.stringify({ data: "test" }),
}),
);
});
test("put method should make PUT request", async () => {
await put("test-endpoint", { data: "test" });
expect(mockFetch).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
method: "PUT",
body: JSON.stringify({ data: "test" }),
}),
);
});
test("del method should make DELETE request", async () => {
await del("test-endpoint");
expect(mockFetch).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({ method: "DELETE" }),
);
});
});
describe("error classes", () => {
test("AuthenticationRequiredError should have correct properties", () => {
const error = new AuthenticationRequiredError();
expect(error.name).toBe("AuthenticationRequiredError");
expect(error.message).toBe(
"Not authenticated. Please run 'cn login' first.",
);
});
test("AuthenticationRequiredError should accept custom message", () => {
const customMessage = "Custom auth error";
const error = new AuthenticationRequiredError(customMessage);
expect(error.message).toBe(customMessage);
});
test("ApiRequestError should have correct properties", () => {
const error = new ApiRequestError(404, "Not Found", "Resource not found");
expect(error.name).toBe("ApiRequestError");
expect(error.status).toBe(404);
expect(error.statusText).toBe("Not Found");
expect(error.response).toBe("Resource not found");
expect(error.message).toContain("404");
expect(error.message).toContain("Not Found");
expect(error.message).toContain("Resource not found");
});
test("ApiRequestError should work without response text", () => {
const error = new ApiRequestError(500, "Internal Server Error");
expect(error.response).toBeUndefined();
expect(error.message).toContain("500");
expect(error.message).toContain("Internal Server Error");
expect(error.message).not.toContain("undefined");
});
});
});

View file

@ -0,0 +1,193 @@
/* eslint-disable max-classes-per-file */
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
import { env } from "../env.js";
import { logger } from "./logger.js";
export interface ApiRequestOptions {
method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
body?: Record<string, unknown> | string;
headers?: Record<string, string>;
}
export interface ApiResponse<T = any> {
data: T;
status: number;
ok: boolean;
}
export interface ApiError extends Error {
status: number;
statusText: string;
response?: string;
}
/**
* Authentication error thrown when user is not authenticated
*/
export class AuthenticationRequiredError extends Error {
constructor(message = "Not authenticated. Please run 'cn login' first.") {
super(message);
this.name = "AuthenticationRequiredError";
}
}
/**
* API error thrown when the request fails
*/
export class ApiRequestError extends Error implements ApiError {
status: number;
statusText: string;
response?: string;
constructor(status: number, statusText: string, response?: string) {
const message = response
? `API request failed: ${status} ${statusText} - ${response}`
: `API request failed: ${status} ${statusText}`;
super(message);
this.name = "ApiRequestError";
this.status = status;
this.statusText = statusText;
this.response = response;
}
}
/**
* Make an authenticated API request to the Continue API
* Handles authentication, error handling, and response parsing
*/
export async function makeAuthenticatedRequest<T = any>(
endpoint: string,
options: ApiRequestOptions = {},
): Promise<ApiResponse<T>> {
// Handle authentication
const authConfig = loadAuthConfig();
if (!authConfig) {
throw new AuthenticationRequiredError();
}
const accessToken = getAccessToken(authConfig);
if (!accessToken) {
throw new AuthenticationRequiredError(
"No access token available. Please run 'cn login' first.",
);
}
// Prepare request options
const { method = "GET", body, headers = {} } = options;
const requestOptions: RequestInit = {
method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
...headers,
},
};
// Add body if provided
if (body) {
requestOptions.body =
typeof body === "string" ? body : JSON.stringify(body);
}
try {
// Make the request
const url = new URL(endpoint, env.apiBase);
logger.debug(`Making ${method} request to: ${url.toString()}`);
const response = await fetch(url, requestOptions);
// Handle error responses
if (!response.ok) {
const errorText = await response.text();
logger.error(`API request failed: ${response.status} ${errorText}`);
throw new ApiRequestError(
response.status,
response.statusText,
errorText,
);
}
// Parse response
let data: T;
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
data = await response.json();
} else {
// If not JSON, return the text as data
data = (await response.text()) as T;
}
logger.debug(`API request successful: ${response.status}`);
return {
data,
status: response.status,
ok: response.ok,
};
} catch (error) {
// Re-throw our custom errors
if (
error instanceof AuthenticationRequiredError ||
error instanceof ApiRequestError
) {
throw error;
}
// Handle network/other errors
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error(`Network/request error: ${errorMessage}`);
throw new Error(`Request failed: ${errorMessage}`);
}
}
/**
* Convenience function for GET requests
*/
export async function get<T = any>(
endpoint: string,
headers?: Record<string, string>,
): Promise<ApiResponse<T>> {
return makeAuthenticatedRequest<T>(endpoint, { method: "GET", headers });
}
/**
* Convenience function for POST requests
*/
export async function post<T = any>(
endpoint: string,
body?: Record<string, unknown> | string,
headers?: Record<string, string>,
): Promise<ApiResponse<T>> {
return makeAuthenticatedRequest<T>(endpoint, {
method: "POST",
body,
headers,
});
}
/**
* Convenience function for PUT requests
*/
export async function put<T = any>(
endpoint: string,
body?: Record<string, unknown> | string,
headers?: Record<string, string>,
): Promise<ApiResponse<T>> {
return makeAuthenticatedRequest<T>(endpoint, {
method: "PUT",
body,
headers,
});
}
/**
* Convenience function for DELETE requests
*/
export async function del<T = any>(
endpoint: string,
headers?: Record<string, string>,
): Promise<ApiResponse<T>> {
return makeAuthenticatedRequest<T>(endpoint, { method: "DELETE", headers });
}

View file

@ -0,0 +1,19 @@
import { GlobalContext } from "core/util/GlobalContext.js";
/**
* Get the persisted model name for CLI from GlobalContext
* Used for unauthenticated users
*/
export function getPersistedModelName(): string | null {
const globalContext = new GlobalContext();
return globalContext.get("cliSelectedModel") ?? null;
}
/**
* Persist the model name for CLI to GlobalContext
* Used for unauthenticated users
*/
export function persistModelName(modelName: string | null): void {
const globalContext = new GlobalContext();
globalContext.update("cliSelectedModel", modelName ?? undefined);
}

View file

@ -12,7 +12,7 @@ describe("updateAnthropicModelInYaml", () => {
expect(result).toContain("name: Local Config");
expect(result).toContain("version: 1.0.0");
expect(result).toContain("schema: v1");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
@ -21,7 +21,7 @@ describe("updateAnthropicModelInYaml", () => {
const result = updateAnthropicModelInYaml(invalidYaml, testApiKey);
expect(result).toContain("name: Local Config");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
});
@ -44,7 +44,7 @@ models:
expect(result).toContain("# My Continue config");
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("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
@ -55,7 +55,7 @@ version: 1.0.0
schema: v1
# List of available models
models:
- uses: anthropic/claude-4-sonnet
- uses: anthropic/claude-sonnet-4-5
with:
ANTHROPIC_API_KEY: old-key
`;
@ -64,7 +64,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("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).not.toContain("old-key");
});
@ -84,7 +84,7 @@ models:
const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
expect(result).toContain("uses: openai/gpt-4");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
});
@ -94,7 +94,7 @@ models:
version: 1.0.0
schema: v1
models:
- uses: anthropic/claude-4-sonnet
- uses: anthropic/claude-sonnet-4-5
with:
ANTHROPIC_API_KEY: old-anthropic-key
- uses: openai/gpt-4
@ -104,7 +104,7 @@ models:
const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("uses: openai/gpt-4");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
@ -112,7 +112,7 @@ models:
// Should only have one anthropic model
const anthropicMatches = result.match(
/uses: anthropic\/claude-4-sonnet/g,
/uses: anthropic\/claude-sonnet-4-5/g,
);
expect(anthropicMatches).toHaveLength(1);
});
@ -130,7 +130,7 @@ schema: v1
expect(result).toContain("name: Local Config");
expect(result).toContain("models:");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
@ -147,7 +147,7 @@ models: []
);
expect(result).toContain("name: Local Config");
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});
});
@ -189,7 +189,7 @@ models: "not an array"
const result = updateAnthropicModelInYaml(malformedConfig, testApiKey);
expect(result).toContain("uses: anthropic/claude-4-sonnet");
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
});

View file

@ -27,7 +27,7 @@ export function updateAnthropicModelInYaml(
apiKey: string,
): string {
const newModel: ModelConfig = {
uses: "anthropic/claude-4-sonnet",
uses: "anthropic/claude-sonnet-4-5",
with: {
ANTHROPIC_API_KEY: apiKey,
},
@ -62,7 +62,7 @@ export function updateAnthropicModelInYaml(
// Filter out existing anthropic models
config.models = config.models.filter(
(model: any) => !model || model.uses !== "anthropic/claude-4-sonnet",
(model: any) => !model || model.uses !== "anthropic/claude-sonnet-4-5",
);
// Add the new anthropic model

View file

@ -145,6 +145,7 @@ class MessageTypes {
"didChangeSelectedOrg",
"tools/call",
"tools/evaluatePolicy",
"tools/preprocessArgs",
"controlPlane/openUrl",
"isItemTooBig",
"process/markAsBackgrounded",

View file

@ -44,22 +44,8 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
"file:///Users/user/workspace1",
"file:///Users/user/workspace2",
],
"history/list": [
{
title: "Session 1",
sessionId: "session-1",
dateCreated: new Date().toString(),
workspaceDirectory: "/tmp",
},
{
title: "Remote Agent",
sessionId: "remote-agent-123",
dateCreated: new Date().toString(),
workspaceDirectory: "",
isRemote: true,
remoteId: "agent-123",
},
],
"history/list": [],
"docs/getIndexedPages": [],
"history/save": undefined,
getControlPlaneSessionInfo: {
AUTH_TYPE: AuthType.WorkOsStaging,
@ -92,6 +78,10 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
},
],
},
"context/getSymbolsForFiles": {},
"tools/preprocessArgs": {
preprocessedArgs: undefined,
},
"llm/compileChat": {
compiledChatMessages: [],
didPrune: false,
@ -114,6 +104,15 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
],
};
const DEFAULT_MOCK_CORE_RESPONSE_HANDLERS: MockResponseHandlers = {
"tools/evaluatePolicy": async (data) => {
return {
policy: data.basePolicy,
displayValue: undefined,
};
},
};
const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
{
role: "assistant",
@ -165,7 +164,9 @@ export class MockIdeMessenger implements IIdeMessenger {
}
responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
responseHandlers: MockResponseHandlers = {};
responseHandlers: MockResponseHandlers = {
...DEFAULT_MOCK_CORE_RESPONSE_HANDLERS,
};
chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
chatStreamDelay: number = 0;
setChatResponseText(text: string): void {
@ -253,7 +254,7 @@ export class MockIdeMessenger implements IIdeMessenger {
resetMocks(): void {
this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
this.responseHandlers = {};
this.responseHandlers = { ...DEFAULT_MOCK_CORE_RESPONSE_HANDLERS };
this.chatResponse = DEFAULT_CHAT_RESPONSE;
this.chatStreamDelay = 0;
}

View file

@ -10,6 +10,7 @@ import { Provider } from "react-redux";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AuthProvider } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { MockIdeMessenger } from "../../../../context/MockIdeMessenger";
import { createMockStore } from "../../../../util/test/mockStore";
import DocsIndexingStatus from "./DocsIndexingStatus";
@ -27,19 +28,12 @@ describe("DocsIndexingStatus", () => {
const renderComponent = async (
props: any = {},
storeState = {},
mockIdeMessengerSetup?: (mock: any) => void,
mockMessenger?: MockIdeMessenger,
) => {
const { mockIdeMessenger, ...store } = createMockStore(storeState);
// Configure the mockIdeMessenger for this test
if (mockIdeMessengerSetup) {
mockIdeMessengerSetup(mockIdeMessenger);
} else {
mockIdeMessenger.request.mockResolvedValue({
status: "success",
content: ["page1.html", "page2.html"],
});
}
const { mockIdeMessenger, ...store } = createMockStore(
storeState,
mockMessenger,
);
const result = await act(async () =>
render(
@ -127,11 +121,16 @@ describe("DocsIndexingStatus", () => {
},
};
const { mockIdeMessenger } = await renderComponent({}, storeState);
const { mockIdeMessenger } = await renderComponent(
{},
storeState,
new MockIdeMessenger(),
);
const postSpy = vi.spyOn(mockIdeMessenger, "post");
const stopButton = screen.getByTestId("stop-indexing");
fireEvent.click(stopButton);
expect(mockIdeMessenger.post).toHaveBeenCalledWith("indexing/abort", {
expect(postSpy).toHaveBeenCalledWith("indexing/abort", {
type: "docs",
id: "https://example.com",
});
@ -171,10 +170,11 @@ describe("DocsIndexingStatus", () => {
};
const { mockIdeMessenger } = await renderComponent({}, storeState);
const postSpy = vi.spyOn(mockIdeMessenger, "post");
const reindexButton = screen.getByTestId("reindex-docs");
fireEvent.click(reindexButton);
expect(mockIdeMessenger.post).toHaveBeenCalledWith("indexing/reindex", {
expect(postSpy).toHaveBeenCalledWith("indexing/reindex", {
type: "docs",
id: "https://example.com",
});
@ -195,13 +195,11 @@ describe("DocsIndexingStatus", () => {
};
const { mockIdeMessenger } = await renderComponent({}, storeState);
const postSpy = vi.spyOn(mockIdeMessenger, "post");
const titleElement = screen.getByText("Example Docs");
fireEvent.click(titleElement);
expect(mockIdeMessenger.post).toHaveBeenCalledWith(
"openUrl",
"https://example.com/docs",
);
expect(postSpy).toHaveBeenCalledWith("openUrl", "https://example.com/docs");
});
it("fetches indexed pages when status becomes complete", async () => {
@ -218,15 +216,13 @@ describe("DocsIndexingStatus", () => {
},
};
const { mockIdeMessenger } = await renderComponent({}, storeState);
const mockMessenger = new MockIdeMessenger();
const spy = vi.spyOn(mockMessenger, "request");
await renderComponent({}, storeState, mockMessenger);
await waitFor(() => {
expect(mockIdeMessenger.request).toHaveBeenCalledWith(
"docs/getIndexedPages",
{
startUrl: "https://example.com",
},
);
expect(spy).toHaveBeenCalledWith("docs/getIndexedPages", {
startUrl: "https://example.com",
});
});
});
@ -244,12 +240,13 @@ describe("DocsIndexingStatus", () => {
},
};
await renderComponent({}, storeState, (mockIdeMessenger) => {
mockIdeMessenger.request.mockResolvedValue({
status: "success",
content: ["page1.html", "page2.html", "page3.html"],
});
});
const mockMessenger = new MockIdeMessenger();
mockMessenger.responses["docs/getIndexedPages"] = [
"page1.html",
"page2.html",
"page3.html",
];
await renderComponent({}, storeState, mockMessenger);
await waitFor(() => {
expect(screen.getByText("3 pages indexed")).toBeInTheDocument();
@ -270,12 +267,9 @@ describe("DocsIndexingStatus", () => {
},
};
await renderComponent({}, storeState, (mockIdeMessenger) => {
mockIdeMessenger.request.mockResolvedValue({
status: "success",
content: ["page1.html"],
});
});
const mockMessenger = new MockIdeMessenger();
mockMessenger.responses["docs/getIndexedPages"] = ["page1.html"];
await renderComponent({}, storeState, mockMessenger);
await waitFor(() => {
expect(screen.getByText("1 page indexed")).toBeInTheDocument();
@ -317,12 +311,11 @@ describe("DocsIndexingStatus", () => {
},
};
await renderComponent({}, storeState, (mockIdeMessenger) => {
mockIdeMessenger.request.mockResolvedValue({
status: "error",
error: "Failed to fetch pages",
});
});
const mockMessenger = new MockIdeMessenger();
mockMessenger.responseHandlers["docs/getIndexedPages"] = async (data) => {
throw new Error("Failed to fetch pages");
};
await renderComponent({}, storeState, mockMessenger);
await waitFor(() => {
expect(consoleSpy).toHaveBeenCalledWith(
@ -357,10 +350,12 @@ describe("DocsIndexingStatus", () => {
},
};
await renderComponent({}, storeState, (mockIdeMessenger) => {
// Mock a delayed response to keep in loading state
mockIdeMessenger.request.mockImplementation(() => new Promise(() => {}));
});
const mockMessenger = new MockIdeMessenger();
mockMessenger.responseHandlers["docs/getIndexedPages"] = async (data) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
return [];
};
await renderComponent({}, storeState, mockMessenger);
expect(screen.getByText("Loading site info...")).toBeInTheDocument();
});

View file

@ -84,28 +84,23 @@ describe("IndexedPagesTooltip", () => {
it("opens URL when page is clicked", () => {
const { mockIdeMessenger } = renderComponent();
const spy = vi.spyOn(mockIdeMessenger, "post");
const pageLink = screen.getByText("/page1");
fireEvent.click(pageLink);
expect(mockIdeMessenger.post).toHaveBeenCalledWith(
"openUrl",
"https://example.com/page1",
);
expect(spy).toHaveBeenCalledWith("openUrl", "https://example.com/page1");
});
it("opens each page URL correctly when clicked", () => {
const { mockIdeMessenger } = renderComponent();
const spy = vi.spyOn(mockIdeMessenger, "post");
// Click on different pages
fireEvent.click(screen.getByText("/page2"));
expect(mockIdeMessenger.post).toHaveBeenCalledWith(
"openUrl",
"https://example.com/page2",
);
expect(spy).toHaveBeenCalledWith("openUrl", "https://example.com/page2");
fireEvent.click(screen.getByText("/sub/page3"));
expect(mockIdeMessenger.post).toHaveBeenCalledWith(
expect(spy).toHaveBeenCalledWith(
"openUrl",
"https://example.com/sub/page3",
);

View file

@ -19,8 +19,9 @@ import { cn } from "../../../util/cn";
import { getStatusIcon } from "./utils";
interface FindAndReplaceDisplayProps {
fileUri?: string;
editingFileContents?: string;
fileUri?: string; // Added during args preprocessing
newFileContents?: string; // Added during args preprocessing
editingFileContents?: string; // Added args preprocessing
relativeFilePath?: string;
edits: EditOperation[];
toolCallId: string;
@ -84,6 +85,7 @@ function DiffStats({ added, removed }: { added: number; removed: number }) {
export function FindAndReplaceDisplay({
fileUri,
newFileContents,
relativeFilePath,
editingFileContents,
edits,
@ -124,39 +126,37 @@ export function FindAndReplaceDisplay({
}, [editingFileContents, edits]);
const diffResult = useMemo(() => {
if (!currentFileContent) {
return null;
}
try {
// Apply all edits sequentially
let newContent = currentFileContent;
for (let i = 0; i < edits.length; i++) {
const {
old_string: oldString,
new_string: newString,
replace_all: replaceAll,
} = edits[i];
newContent = executeFindAndReplace(
newContent,
oldString,
newString,
!!replaceAll,
i,
);
let contentsAfterReplace = newFileContents;
if (typeof contentsAfterReplace === "undefined") {
// Apply all edits sequentially
contentsAfterReplace = currentFileContent;
for (let i = 0; i < edits.length; i++) {
const {
old_string: oldString,
new_string: newString,
replace_all: replaceAll,
} = edits[i];
contentsAfterReplace = executeFindAndReplace(
contentsAfterReplace,
oldString,
newString,
!!replaceAll,
i,
);
}
}
// Generate diff between original and final content
const diff = diffLines(currentFileContent, newContent);
return { diff, newContent, error: null };
const diff = diffLines(currentFileContent, contentsAfterReplace);
return { diff, error: null };
} catch (error) {
return {
diff: null,
newContent: null,
error: error instanceof Error ? error.message : "Unknown error",
};
}
}, [currentFileContent, edits]);
}, [currentFileContent, newFileContents, edits]);
const diffStats = useMemo(() => {
if (!diffResult?.diff) {

View file

@ -45,7 +45,8 @@ function FunctionSpecificToolCallDiv({
return (
<FindAndReplaceDisplay
editingFileContents={args?.editingFileContents}
fileUri={args?.fileUri}
fileUri={args?.fileUri ?? ""}
newFileContents={args?.newFileContents}
relativeFilePath={args?.filepath ?? ""}
edits={edits}
toolCallId={toolCall.id}
@ -57,7 +58,8 @@ function FunctionSpecificToolCallDiv({
<FindAndReplaceDisplay
editingFileContents={args?.editingFileContents}
relativeFilePath={args?.filepath ?? ""}
fileUri={args?.fileUri}
fileUri={args?.fileUri ?? ""}
newFileContents={args?.newFileContents}
edits={args?.edits ?? []}
toolCallId={toolCall.id}
historyIndex={historyIndex}

View file

@ -1,15 +1,37 @@
import { screen } from "@testing-library/dom";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
import { renderWithProviders } from "../../util/test/render";
import HistoryPage from "./index";
const mockIdeMessenger = new MockIdeMessenger();
mockIdeMessenger.responses["history/list"] = [
{
title: "Session 1",
sessionId: "session-1",
dateCreated: new Date().toString(),
workspaceDirectory: "/tmp",
},
{
title: "Remote Agent",
sessionId: "remote-agent-123",
dateCreated: new Date().toString(),
workspaceDirectory: "",
isRemote: true,
remoteId: "agent-123",
},
];
describe("history Page test", () => {
it("History text is existed after render", async () => {
await renderWithProviders(<HistoryPage />);
await renderWithProviders(<HistoryPage />, {
mockIdeMessenger,
});
expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument();
});
it("History shows the first item in the list", async () => {
await renderWithProviders(<HistoryPage />);
await renderWithProviders(<HistoryPage />, {
mockIdeMessenger,
});
const sessionElement = await screen.findByText(
"Session 1",
{},

View file

@ -36,7 +36,7 @@ export const EMPTY_CONFIG: BrowserSerializedContinueConfig = {
rules: [],
};
const initialState: ConfigState = {
export const INITIAL_CONFIG_SLICE: ConfigState = {
configError: undefined,
config: EMPTY_CONFIG,
loading: false,
@ -44,7 +44,7 @@ const initialState: ConfigState = {
export const configSlice = createSlice({
name: "config",
initialState,
initialState: INITIAL_CONFIG_SLICE,
reducers: {
setConfigResult: (
state,

View file

@ -18,7 +18,7 @@ export const INITIAL_EDIT_APPLY_STATE: ApplyState = {
status: "not-started",
};
const initialState: EditState = {
export const INITIAL_EDIT_STATE: EditState = {
applyState: INITIAL_EDIT_APPLY_STATE,
codeToEdit: [],
returnToMode: "chat",
@ -28,7 +28,7 @@ const initialState: EditState = {
export const editStateSlice = createSlice({
name: "editState",
initialState,
initialState: INITIAL_EDIT_STATE,
reducers: {
setReturnToModeAfterEdit: (
state,

View file

@ -8,7 +8,7 @@ export type IndexingState = {
};
};
const initialState: IndexingState = {
export const INITIAL_INDEXING_STATE: IndexingState = {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
@ -19,7 +19,7 @@ const initialState: IndexingState = {
export const indexingSlice = createSlice({
name: "indexing",
initialState,
initialState: INITIAL_INDEXING_STATE,
reducers: {
updateIndexingStatus: (
state,

View file

@ -19,7 +19,7 @@ export interface ProfilesState {
preferencesByProfileId: Record<string, PreferencesState>;
}
const initialState: ProfilesState = {
export const INITIAL_PROFILES_STATE: ProfilesState = {
preferencesByProfileId: {},
selectedProfileId: null,
selectedOrganizationId: null,
@ -51,7 +51,7 @@ const initialState: ProfilesState = {
export const profilesSlice = createSlice({
name: "profiles",
initialState,
initialState: INITIAL_PROFILES_STATE,
reducers: {
setSelectedProfile: (state, { payload }: PayloadAction<string | null>) => {
state.selectedProfileId = payload;

View file

@ -9,6 +9,7 @@ import { JSONContent } from "@tiptap/react";
import {
ApplyState,
AssistantChatMessage,
BaseSessionMetadata,
ChatHistoryItem,
ChatMessage,
ContextItem,
@ -18,7 +19,6 @@ import {
PromptLog,
RuleWithSource,
Session,
BaseSessionMetadata,
ThinkingChatMessage,
Tool,
ToolCallDelta,
@ -51,7 +51,11 @@ import { findChatHistoryItemByToolCallId, findToolCallById } from "../util";
function filterMultipleEditToolCalls(
toolCalls: ToolCallDelta[],
): ToolCallDelta[] {
const editToolNames = [BuiltInToolNames.EditExistingFile];
const editToolNames = [
BuiltInToolNames.EditExistingFile,
BuiltInToolNames.SingleFindAndReplace,
BuiltInToolNames.MultiEdit,
];
let hasSeenEditTool = false;
return toolCalls.filter((toolCall) => {
@ -228,7 +232,7 @@ type SessionState = {
compactionLoading: Record<number, boolean>; // Track compaction loading by message index
};
const initialState: SessionState = {
export const INITIAL_SESSION_STATE: SessionState = {
isSessionMetadataLoading: false,
allSessionMetadata: [],
history: [],
@ -250,7 +254,7 @@ const initialState: SessionState = {
export const sessionSlice = createSlice({
name: "session",
initialState,
initialState: INITIAL_SESSION_STATE,
reducers: {
addPromptCompletionPair: (
state,
@ -306,7 +310,10 @@ export const sessionSlice = createSlice({
// Cancel any tool calls that are dangling and generated
if (message.toolCallStates) {
message.toolCallStates.forEach((toolCallState) => {
if (toolCallState.status === "generated") {
if (
toolCallState.status === "generated" ||
toolCallState.status === "generating"
) {
toolCallState.status = "canceled";
}
});

View file

@ -11,7 +11,7 @@ interface TabsState {
tabs: Tab[];
}
const initialState: TabsState = {
export const INITIAL_TABS_STATE: TabsState = {
tabs: [
{
id: Date.now().toString(36) + Math.random().toString(36).substring(2),
@ -23,7 +23,7 @@ const initialState: TabsState = {
export const tabsSlice = createSlice({
name: "tabs",
initialState,
initialState: INITIAL_TABS_STATE,
reducers: {
setTabs: (state, action: PayloadAction<Tab[]>) => {
state.tabs = action.payload;

View file

@ -1,7 +1,7 @@
import { ToolPolicy } from "@continuedev/terminal-security";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RuleWithSource, Tool } from "core";
import { ToolPolicy } from "@continuedev/terminal-security";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn";
import { BUILT_IN_GROUP_NAME } from "core/tools/builtIn";
import {
defaultOnboardingCardState,
OnboardingCardState,
@ -18,7 +18,7 @@ export type ToolGroupPolicies = { [toolGroupName: string]: ToolGroupPolicy };
type UIState = {
showDialog: boolean;
dialogMessage: string | JSX.Element | undefined;
dialogMessage: JSX.Element | undefined;
dialogEntryOn: boolean;
onboardingCard: OnboardingCardState;
isExploreDialogOpen: boolean;
@ -32,26 +32,27 @@ type UIState = {
export const DEFAULT_TOOL_SETTING: ToolPolicy = "allowedWithPermission";
export const DEFAULT_RULE_SETTING: RulePolicy = "on";
export const DEFAULT_UI_SLICE: UIState = {
showDialog: false,
dialogMessage: undefined,
dialogEntryOn: false,
onboardingCard: defaultOnboardingCardState,
isExploreDialogOpen:
getLocalStorage(LocalStorageKey.IsExploreDialogOpen) ?? false,
hasDismissedExploreDialog:
getLocalStorage(LocalStorageKey.HasDismissedExploreDialog) ?? false,
shouldAddFileForEditing: false,
ttsActive: false,
toolSettings: {},
toolGroupSettings: {
[BUILT_IN_GROUP_NAME]: "include",
},
ruleSettings: {},
};
export const uiSlice = createSlice({
name: "ui",
initialState: {
showDialog: false,
dialogMessage: "",
dialogEntryOn: false,
onboardingCard: defaultOnboardingCardState,
isExploreDialogOpen: getLocalStorage(LocalStorageKey.IsExploreDialogOpen),
hasDismissedExploreDialog: getLocalStorage(
LocalStorageKey.HasDismissedExploreDialog,
),
shouldAddFileForEditing: false,
ttsActive: false,
toolSettings: {},
toolGroupSettings: {
[BUILT_IN_GROUP_NAME]: "include",
},
ruleSettings: {},
} as UIState,
initialState: DEFAULT_UI_SLICE,
reducers: {
setOnboardingCard: (
state,

View file

@ -12,16 +12,17 @@ import {
setToolCallCalling,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
import { ThunkApiType } from "../store";
import { findToolCallById, logToolUsage } from "../util";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export const callToolById = createAsyncThunk<
void,
{ toolCallId: string },
{ toolCallId: string; isAutoApproved?: boolean; depth?: number },
ThunkApiType
>("chat/callTool", async ({ toolCallId }, { dispatch, extra, getState }) => {
>("chat/callTool", async (inputs, { dispatch, extra, getState }) => {
const { toolCallId, isAutoApproved, depth = 0 } = inputs;
const state = getState();
const toolCallState = findToolCallById(state.session.history, toolCallId);
if (!toolCallState) {
@ -36,14 +37,6 @@ export const callToolById = createAsyncThunk<
// Track tool call acceptance and start timing
const startTime = Date.now();
// Check if this is an auto-approved tool
const toolSettings = state.ui.toolSettings;
const toolPolicy =
toolSettings[toolCallState.toolCall.function.name] ??
toolCallState.tool?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
const isAutoApproved = toolPolicy === "allowedWithoutPermission";
const selectedChatModel = selectSelectedChatModel(state);
posthog.capture("tool_call_decision", {
@ -164,6 +157,7 @@ export const callToolById = createAsyncThunk<
const wrapped = await dispatch(
streamResponseAfterToolCall({
toolCallId,
depth: depth + 1,
}),
);
unwrapResult(wrapped);

View file

@ -0,0 +1,117 @@
import { ToolPolicy } from "@continuedev/terminal-security";
import { Tool, ToolCallState } from "core";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { errorToolCall, updateToolCallOutput } from "../slices/sessionSlice";
import { DEFAULT_TOOL_SETTING, ToolPolicies } from "../slices/uiSlice";
import { AppThunkDispatch } from "../store";
interface EvaluatedPolicy {
policy: ToolPolicy;
displayValue?: string;
toolCallState: ToolCallState;
}
/**
* Evaluates the tool policy for a tool call, including dynamic policy evaluation
* Note that tool group policies are not considered here because activeTools already excludes disabled groups
*/
async function evaluateToolPolicy(
ideMessenger: IIdeMessenger,
activeTools: Tool[],
toolCallState: ToolCallState,
toolPolicies: ToolPolicies,
): Promise<EvaluatedPolicy> {
const basePolicy =
toolPolicies[toolCallState.toolCall.function.name] ??
activeTools.find(
(tool) => tool.function.name === toolCallState.toolCall.function.name,
)?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
// Use already parsed arguments
const parsedArgs = toolCallState.parsedArgs || {};
const toolName = toolCallState.toolCall.function.name;
const result = await ideMessenger.request("tools/evaluatePolicy", {
toolName,
basePolicy,
args: parsedArgs,
});
// Evaluate the policy dynamically
if (result.status === "error") {
console.error(`Error evaluating tool policy for ${toolName}`, result.error);
return { policy: "disabled", toolCallState };
}
const dynamicPolicy = result.content.policy;
const displayValue = result.content.displayValue;
// Ensure dynamic policy cannot be more lenient than base policy
// Policy hierarchy (most restrictive to least): disabled > allowedWithPermission > allowedWithoutPermission
if (basePolicy === "disabled") {
return { policy: "disabled", displayValue, toolCallState }; // Cannot override disabled
}
if (
basePolicy === "allowedWithPermission" &&
dynamicPolicy === "allowedWithoutPermission"
) {
return { policy: "allowedWithPermission", displayValue, toolCallState }; // Cannot make more lenient
}
return { policy: dynamicPolicy, displayValue, toolCallState };
}
/*
1. Get arg-dependent tool policies from core
2. Mark any disabled ones as errored
3. Mark others as generated
*/
export async function evaluateToolPolicies(
dispatch: AppThunkDispatch,
ideMessenger: IIdeMessenger,
activeTools: Tool[],
generatedToolCalls: ToolCallState[],
toolPolicies: ToolPolicies,
): Promise<EvaluatedPolicy[]> {
// Check if ALL tool calls are auto-approved using dynamic evaluation
const policyResults = await Promise.all(
generatedToolCalls.map((toolCallState) =>
evaluateToolPolicy(
ideMessenger,
activeTools,
toolCallState,
toolPolicies,
),
),
);
const disabledResults = policyResults.filter(
({ policy }) => policy === "disabled",
);
for (const { displayValue, toolCallState } of disabledResults) {
dispatch(errorToolCall({ toolCallId: toolCallState.toolCallId }));
// Use the displayValue from the policy evaluation, or fallback to function name
const command = displayValue || toolCallState.toolCall.function.name;
// Add error message explaining why it's disabled
dispatch(
updateToolCallOutput({
toolCallId: toolCallState.toolCallId,
contextItems: [
{
icon: "problems",
name: "Security Policy Violation",
description: "Command Disabled",
content: `This command has been disabled by security policy:\n\n${command}\n\nThis command cannot be executed as it may pose a security risk.`,
hidden: false,
},
],
}),
);
}
return policyResults;
}

View file

@ -0,0 +1,59 @@
import { ToolCallState } from "core";
import { IIdeMessenger } from "../../context/IdeMessenger";
import {
errorToolCall,
setToolCallArgs,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { AppThunkDispatch } from "../store";
export async function preprocessToolCalls(
dispatch: AppThunkDispatch,
ideMessenger: IIdeMessenger,
generatedToolCalls: ToolCallState[],
): Promise<void> {
// Tool call pre-processing
await Promise.all(
generatedToolCalls.map(async (tcState) => {
try {
const result = await ideMessenger.request("tools/preprocessArgs", {
toolName: tcState.toolCall.function.name,
args: tcState.parsedArgs,
});
if (result.status === "success") {
if (result.content.preprocessedArgs) {
dispatch(
setToolCallArgs({
toolCallId: tcState.toolCallId,
newArgs: result.content.preprocessedArgs,
}),
);
}
} else {
throw new Error(result.error);
}
} catch (e) {
let errorMessage = e instanceof Error ? e.message : `Unknown error`;
dispatch(
errorToolCall({
toolCallId: tcState.toolCallId,
}),
);
dispatch(
updateToolCallOutput({
toolCallId: tcState.toolCallId,
contextItems: [
{
icon: "problems",
name: "Invalid Tool Call",
description: "",
content: `${tcState.toolCall.function.name} failed because the arguments were invalid, with the following message: ${errorMessage}\n\nPlease try something else or request further instructions.`,
hidden: false,
},
],
}),
);
}
}),
);
}

View file

@ -1,5 +1,5 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage, Session, BaseSessionMetadata } from "core";
import { BaseSessionMetadata, ChatMessage, Session } from "core";
import { RemoteSessionMetadata } from "core/control-plane/client";
import { NEW_SESSION_TITLE } from "core/util/constants";
import { renderChatMessage } from "core/util/messageContent";

View file

@ -1,20 +1,12 @@
import { ToolPolicy } from "@continuedev/terminal-security";
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import {
LLMFullCompletionOptions,
ModelDescription,
Tool,
ToolCallState,
} from "core";
import { LLMFullCompletionOptions, ModelDescription } from "core";
import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
import { ToCoreProtocol } from "core/protocol";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { selectActiveTools } from "../selectors/selectActiveTools";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
abortStream,
addPromptCompletionPair,
errorToolCall,
setActive,
setAppliedRulesAtIndex,
setContextPercentage,
@ -23,174 +15,23 @@ import {
setIsPruned,
setToolGenerated,
streamUpdate,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { AppThunkDispatch, RootState, ThunkApiType } from "../store";
import { ThunkApiType } from "../store";
import { constructMessages } from "../util/constructMessages";
import { modelSupportsNativeTools } from "core/llm/toolSupport";
import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage";
import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls";
import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks";
import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
import {
selectCurrentToolCalls,
selectPendingToolCalls,
} from "../selectors/selectToolCalls";
import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
import { callToolById } from "./callToolById";
import { enhanceParsedArgs } from "./enhanceParsedArgs";
/**
* Evaluates the tool policy for a tool call, including dynamic policy evaluation
*/
async function evaluateToolPolicy(
toolCallState: ToolCallState,
toolSettings: Record<string, ToolPolicy>,
activeTools: Tool[],
ideMessenger: IIdeMessenger,
): Promise<{ policy: ToolPolicy; displayValue?: string }> {
const basePolicy =
toolSettings[toolCallState.toolCall.function.name] ??
activeTools.find(
(tool) => tool.function.name === toolCallState.toolCall.function.name,
)?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
// Use already parsed arguments
const parsedArgs = toolCallState.parsedArgs || {};
let result;
try {
result = await ideMessenger.request("tools/evaluatePolicy", {
toolName: toolCallState.toolCall.function.name,
basePolicy,
args: parsedArgs,
});
} catch (error) {
// If request fails, return disabled
return { policy: "disabled" };
}
// Evaluate the policy dynamically
if (!result || result.status === "error") {
// If evaluation fails, treat as disabled
return { policy: "disabled" };
}
const dynamicPolicy = result.content.policy;
const displayValue = result.content.displayValue;
// Ensure dynamic policy cannot be more lenient than base policy
// Policy hierarchy (most restrictive to least): disabled > allowedWithPermission > allowedWithoutPermission
if (basePolicy === "disabled") {
return { policy: "disabled", displayValue }; // Cannot override disabled
}
if (
basePolicy === "allowedWithPermission" &&
dynamicPolicy === "allowedWithoutPermission"
) {
return { policy: "allowedWithPermission", displayValue }; // Cannot make more lenient
}
return { policy: dynamicPolicy, displayValue };
}
/**
* Handles the execution of tool calls that may be automatically accepted.
* Sets all tools as generated first, then executes auto-approved tool calls.
*/
async function handleToolCallExecution(
dispatch: AppThunkDispatch,
getState: () => RootState,
activeTools: Tool[],
ideMessenger: IIdeMessenger,
): Promise<boolean> {
// Return whether all tools were auto-approved
const newState = getState();
const toolSettings = newState.ui.toolSettings;
const allToolCallStates = selectCurrentToolCalls(newState);
// Only process tool calls that are in "generating" status (newly created during this streaming session)
const toolCallStates = allToolCallStates.filter(
(toolCallState) => toolCallState.status === "generating",
);
// If no generating tool calls, nothing to process
if (toolCallStates.length === 0) {
return false; // No tools to process, need to set inactive
}
// Check if ALL tool calls are auto-approved using dynamic evaluation
const policyResults = await Promise.all(
toolCallStates.map((toolCallState) =>
evaluateToolPolicy(
toolCallState,
toolSettings,
activeTools,
ideMessenger,
),
),
);
// Handle disabled tool calls and set others as generated
const autoApprovedResults = await Promise.all(
toolCallStates.map(async (toolCallState, index) => {
const { policy, displayValue } = policyResults[index];
if (policy === "disabled") {
// Mark as errored instead of generated
dispatch(errorToolCall({ toolCallId: toolCallState.toolCallId }));
// Use the displayValue from the policy evaluation, or fallback to function name
const command = displayValue || toolCallState.toolCall.function.name;
// Add error message explaining why it's disabled
dispatch(
updateToolCallOutput({
toolCallId: toolCallState.toolCallId,
contextItems: [
{
icon: "problems",
name: "Security Policy Violation",
description: "Command Disabled",
content: `This command has been disabled by security policy:\n\n${command}\n\nThis command cannot be executed as it may pose a security risk.`,
hidden: false,
},
],
}),
);
return false;
} else {
// Set as generated for non-disabled tools
dispatch(
setToolGenerated({
toolCallId: toolCallState.toolCallId,
tools: newState.config.config.tools,
}),
);
return policy === "allowedWithoutPermission";
}
}),
);
const allAutoApproved = autoApprovedResults.every(Boolean);
// Only run if we have auto-approve for all non-disabled tools
if (allAutoApproved && toolCallStates.length > 0) {
const nonDisabledToolCalls = toolCallStates.filter(
(_, index) => policyResults[index].policy !== "disabled",
);
const toolCallPromises = nonDisabledToolCalls.map(async (toolCallState) => {
const response = await dispatch(
callToolById({ toolCallId: toolCallState.toolCallId }),
);
unwrapResult(response);
});
await Promise.all(toolCallPromises);
}
return allAutoApproved;
}
import { evaluateToolPolicies } from "./evaluateToolPolicies";
import { preprocessToolCalls } from "./preprocessToolCallArgs";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
/**
* Builds completion options with reasoning configuration based on session state and model capabilities.
@ -228,11 +69,20 @@ export const streamNormalInput = createAsyncThunk<
void,
{
legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
depth?: number;
},
ThunkApiType
>(
"chat/streamNormalInput",
async ({ legacySlashCommandData }, { dispatch, extra, getState }) => {
async (
{ legacySlashCommandData, depth = 0 },
{ dispatch, extra, getState },
) => {
if (process.env.NODE_ENV === "test" && depth > 50) {
const message = `Max stream depth of ${50} reached in test`;
console.error(message, JSON.stringify(getState(), null, 2));
throw new Error(message);
}
const state = getState();
const selectedChatModel = selectSelectedChatModel(state);
@ -385,35 +235,78 @@ export const streamNormalInput = createAsyncThunk<
}
}
// Check if we have any tool calls that were just generated
const newState = getState();
const toolSettings = newState.ui.toolSettings;
const allToolCallStates = selectCurrentToolCalls(newState);
// Tool call sequence:
// 1. Mark generating tool calls as generated
const state1 = getState();
const originalToolCalls = selectCurrentToolCalls(state1);
await Promise.all(
allToolCallStates.map((tcState) =>
enhanceParsedArgs(
extra.ideMessenger,
dispatch,
tcState?.toolCall.function.name,
tcState.toolCallId,
tcState.parsedArgs,
),
),
const generatingCalls = originalToolCalls.filter(
(tc) => tc.status === "generating",
);
for (const { toolCallId } of generatingCalls) {
dispatch(
setToolGenerated({
toolCallId,
tools: state1.config.config.tools,
}),
);
}
// Handle tool call execution if there are any generating tool calls
const allAutoApproved = await handleToolCallExecution(
// 2. Pre-process args to catch invalid args before checking policies
const state2 = getState();
const generatedCalls2 = selectPendingToolCalls(state2);
await preprocessToolCalls(dispatch, extra.ideMessenger, generatedCalls2);
// 3. Security check: evaluate updated policies based on args
const state3 = getState();
const generatedCalls3 = selectPendingToolCalls(state3);
const toolPolicies = state3.ui.toolSettings;
const policies = await evaluateToolPolicies(
dispatch,
getState,
activeTools,
extra.ideMessenger,
activeTools,
generatedCalls3,
toolPolicies,
);
const anyRequireApproval = policies.find(
({ policy }) => policy === "allowedWithPermission",
);
// 4. Execute remaining tool calls
// Only set inactive if not all tools were auto-approved
// This prevents UI flashing for auto-approved tools
if (!allAutoApproved) {
if (originalToolCalls.length === 0 || anyRequireApproval) {
dispatch(setInactive());
} else {
// auto stream cases increase thunk depth by 1
const state4 = getState();
const generatedCalls4 = selectPendingToolCalls(state4);
if (generatedCalls4.length > 0) {
// All that didn't fail are auto approved - call them
await Promise.all(
generatedCalls4.map(async ({ toolCallId }) => {
unwrapResult(
await dispatch(
callToolById({
toolCallId,
isAutoApproved: true,
depth: depth + 1,
}),
),
);
}),
);
} else {
// All failed - stream on
for (const { toolCallId } of originalToolCalls) {
unwrapResult(
await dispatch(
streamResponseAfterToolCall({ toolCallId, depth: depth + 1 }),
),
);
}
}
}
},
);

File diff suppressed because it is too large Load diff

View file

@ -35,7 +35,6 @@ export const streamResponseThunk = createAsyncThunk<
if (!selectedChatModel) {
throw new Error("No chat model selected");
}
dispatch(
submitEditorAndInitAtIndex({ index: inputIndex, editorState }),
);
@ -45,13 +44,6 @@ export const streamResponseThunk = createAsyncThunk<
const defaultContextProviders =
state.config.config.experimental?.defaultContext ?? [];
if (!selectedChatModel) {
console.error(
"gatherContext thunk: Cannot gather context, no model selected",
);
throw new Error("No chat model selected");
}
// Resolve context providers and construct new history
const {
selectedContextItems,

View file

@ -1,13 +1,13 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage } from "core";
import { renderContextItems } from "core/util/messageContent";
import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
import {
ChatHistoryItemWithMessageId,
resetNextCodeBlockToApplyIndex,
streamUpdate,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCallById } from "../util";
import { streamNormalInput } from "./streamNormalInput";
import { streamThunkWrapper } from "./streamThunkWrapper";
@ -15,11 +15,11 @@ import { streamThunkWrapper } from "./streamThunkWrapper";
* Determines if we should continue streaming based on tool call completion status.
*/
function areAllToolsDoneStreaming(
assistantMessage: ChatHistoryItemWithMessageId | undefined,
assistantMessage: ChatHistoryItemWithMessageId,
continueAfterToolRejection: boolean | undefined,
): boolean {
// This might occur because of race conditions, if so, the tools are completed
if (!assistantMessage?.toolCallStates) {
if (!assistantMessage.toolCallStates) {
return true;
}
@ -36,18 +36,17 @@ function areAllToolsDoneStreaming(
export const streamResponseAfterToolCall = createAsyncThunk<
void,
{ toolCallId: string },
{ toolCallId: string; depth?: number },
ThunkApiType
>(
"chat/streamAfterToolCall",
async ({ toolCallId }, { dispatch, getState }) => {
async ({ toolCallId, depth = 0 }, { dispatch, getState }) => {
await dispatch(
streamThunkWrapper(async () => {
const state = getState();
const toolCallState = findToolCallById(
state.session.history,
toolCallId,
const currentToolCalls = selectCurrentToolCalls(state);
const toolCallState = currentToolCalls.find(
(tc) => tc.toolCallId === toolCallId,
);
if (!toolCallState) {
@ -57,7 +56,6 @@ export const streamResponseAfterToolCall = createAsyncThunk<
const toolOutput = toolCallState.output ?? [];
dispatch(resetNextCodeBlockToApplyIndex());
// await new Promise((resolve) => setTimeout(resolve, 0));
// Create and dispatch the tool message
const newMessage: ChatMessage = {
@ -76,12 +74,13 @@ export const streamResponseAfterToolCall = createAsyncThunk<
);
if (
assistantMessage &&
areAllToolsDoneStreaming(
assistantMessage,
state.config.config.ui?.continueAfterToolRejection,
)
) {
unwrapResult(await dispatch(streamNormalInput({})));
unwrapResult(await dispatch(streamNormalInput({ depth: depth + 1 })));
}
}),
);

View file

@ -1,7 +1,7 @@
import { JSONContent } from "@tiptap/core";
import { InputModifiers } from "core";
import { describe, expect, it, vi } from "vitest";
import { createMockStore } from "../../util/test/mockStore";
import { createMockStore, getEmptyRootState } from "../../util/test/mockStore";
import { streamResponseThunk } from "./streamResponse";
// Mock external dependencies only - let selectors run naturally
@ -36,23 +36,17 @@ vi.mock(
}),
);
import { ModelDescription } from "core";
import { unwrapResult } from "@reduxjs/toolkit";
import posthog from "posthog-js";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
import { getRootStateWithClaude } from "./streamResponse.test";
const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage);
const mockPosthog = vi.mocked(posthog);
const mockResolveEditorContent = vi.mocked(resolveEditorContent);
const mockClaudeModel: ModelDescription = {
title: "Claude 3.5 Sonnet",
model: "claude-3-5-sonnet-20241022",
provider: "anthropic",
underlyingProviderName: "anthropic",
completionOptions: { reasoningBudgetTokens: 2048 },
};
// Mock editor state (what user types in the input)
const mockEditorState: JSONContent = {
type: "doc",
@ -70,12 +64,8 @@ const mockModifiers: InputModifiers = {
noContext: false,
};
function setupTest() {
beforeEach(() => {
vi.clearAllMocks();
// Default mock implementations for external functions
// Default mock for resolveEditorContent (can be overridden in individual tests)
mockResolveEditorContent.mockResolvedValue({
selectedContextItems: [],
selectedCode: [],
@ -85,133 +75,25 @@ function setupTest() {
// Mock getBaseSystemMessage to return simple system message for readable tests
mockGetBaseSystemMessage.mockReturnValue("You are a helpful assistant.");
// Create store with realistic state that selectors can work with
const mockStore = createMockStore({
session: {
history: [
{
message: { id: "1", role: "user", content: "Hello" },
contextItems: [],
},
],
hasReasoningEnabled: false,
isStreaming: true,
id: "session-123",
mode: "chat",
streamAborter: new AbortController(),
contextPercentage: 0,
isPruned: false,
isInEdit: false,
title: "",
lastSessionId: undefined,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: undefined,
},
config: {
config: {
tools: [],
rules: [],
tabAutocompleteModel: undefined,
selectedModelByRole: {
chat: mockClaudeModel,
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
} as any,
lastSelectedModelByRole: {
chat: mockClaudeModel.title,
},
} as any,
ui: {
toolSettings: {},
ruleSettings: {},
showDialog: false,
dialogMessage: undefined,
} as any,
});
const mockIdeMessenger = mockStore.mockIdeMessenger;
return { mockStore, mockIdeMessenger };
}
});
describe("streamResponseThunk", () => {
it("should throw error when no chat model is selected", async () => {
const { mockStore, mockIdeMessenger } = setupTest();
const noModelState = getEmptyRootState();
noModelState.session.history = [
{
message: { id: "1", role: "user", content: "Hello" },
contextItems: [],
},
];
// Create store with no selected chat model
const mockStoreNoModel = createMockStore({
session: {
history: [
{
message: { id: "1", role: "user", content: "Hello" },
contextItems: [],
},
],
hasReasoningEnabled: false,
isStreaming: true,
id: "session-123",
mode: "chat",
streamAborter: new AbortController(),
contextPercentage: 0,
isPruned: false,
isInEdit: false,
title: "",
lastSessionId: undefined,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: undefined,
},
config: {
config: {
tools: [],
rules: [],
tabAutocompleteModel: undefined,
selectedModelByRole: {
chat: null, // No model selected
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
} as any,
lastSelectedModelByRole: {},
} as any,
ui: {
toolSettings: {},
ruleSettings: {},
showDialog: false,
dialogMessage: undefined,
} as any,
});
const mockStoreNoModel = createMockStore(noModelState);
const requestSpy = vi.spyOn(mockStoreNoModel.mockIdeMessenger, "request");
const chatSpy = vi.spyOn(
mockStoreNoModel.mockIdeMessenger,
"llmStreamChat",
);
// Execute thunk and expect it to be rejected
const result = await mockStoreNoModel.dispatch(
@ -225,7 +107,7 @@ describe("streamResponseThunk", () => {
expect(result.type).toBe("chat/streamResponse/fulfilled");
// Verify the complete error handling flow
const dispatchedActions = (mockStoreNoModel as any).getActions();
const dispatchedActions = mockStoreNoModel.getActions();
expect(dispatchedActions).toEqual([
{
type: "chat/streamResponse/pending",
@ -316,68 +198,22 @@ describe("streamResponseThunk", () => {
]);
// Verify no IDE messenger calls were made
expect(mockStoreNoModel.mockIdeMessenger.request).not.toHaveBeenCalled();
expect(
mockStoreNoModel.mockIdeMessenger.llmStreamChat,
).not.toHaveBeenCalled();
expect(requestSpy).not.toHaveBeenCalled();
expect(chatSpy).not.toHaveBeenCalled();
// Verify final state shows error dialog and inactive streaming
const finalState = mockStoreNoModel.getState();
expect(finalState).toEqual({
...noModelState,
session: {
history: [
{
contextItems: [],
isGatheringContext: false,
message: { id: "1", role: "user", content: "Hello" },
},
],
hasReasoningEnabled: false,
isStreaming: false, // Set to inactive after error
id: "session-123",
mode: "chat",
...noModelState.session,
streamAborter: expect.any(AbortController),
contextPercentage: 0,
isPruned: false,
isInEdit: false,
title: "",
lastSessionId: undefined,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: undefined,
},
config: {
config: {
tools: [],
rules: [],
tabAutocompleteModel: undefined,
selectedModelByRole: {
chat: null, // No model selected
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
},
lastSelectedModelByRole: {},
loading: false,
configError: undefined,
history: [
{ ...noModelState.session.history[0], isGatheringContext: false },
],
},
ui: {
toolSettings: {},
ruleSettings: {},
...noModelState.ui,
showDialog: true, // Error dialog is shown
dialogMessage: expect.objectContaining({
props: expect.objectContaining({
@ -387,37 +223,33 @@ describe("streamResponseThunk", () => {
}),
}),
},
editModeState: {
isInEdit: false,
returnToMode: "chat",
},
indexing: {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
},
tabs: {
tabsItems: [],
},
profiles: {
organizations: [],
selectedProfileId: null,
selectedOrganizationId: null,
preferencesByProfileId: {},
},
});
});
it("should handle compilation error - not enough context", async () => {
const { mockStore, mockIdeMessenger } = setupTest();
const initialState = getRootStateWithClaude();
initialState.session.history = [
{
message: { id: "1", role: "user", content: "Hello" },
contextItems: [],
},
];
initialState.session.id = "session-123";
const mockStore = createMockStore(initialState);
const mockIdeMessenger = mockStore.mockIdeMessenger;
const requestSpy = vi.spyOn(mockIdeMessenger, "request");
const chatSpy = vi.spyOn(mockIdeMessenger, "llmStreamChat");
// Mock compilation failure with "Not enough context" error
mockIdeMessenger.request.mockResolvedValue({
status: "error",
error: "Not enough context available for this request",
requestSpy.mockImplementation(async (message, data) => {
if (message === "llm/compileChat") {
return {
done: true,
status: "error",
error: "Not enough context available for this request",
};
} else {
return await new MockIdeMessenger().request(message, data);
}
});
// Execute thunk
@ -427,12 +259,13 @@ describe("streamResponseThunk", () => {
modifiers: mockModifiers,
}) as any,
);
unwrapResult(result);
// Verify thunk completed successfully (doesn't throw, handles error gracefully)
expect(result.type).toBe("chat/streamResponse/fulfilled");
// Verify exact action sequence for this error path
const dispatchedActions = (mockStore as any).getActions();
const dispatchedActions = mockStore.getActions();
expect(dispatchedActions).toEqual([
{
type: "chat/streamResponse/pending",
@ -561,7 +394,7 @@ describe("streamResponseThunk", () => {
arg: expect.objectContaining({
history: expect.any(Array),
sessionId: "session-123",
title: "New Session",
title: "Hello",
workspaceDirectory: "",
}),
requestId: expect.any(String),
@ -573,7 +406,7 @@ describe("streamResponseThunk", () => {
type: "session/updateSessionMetadata",
payload: {
sessionId: "session-123",
title: "New Session",
title: "Hello",
},
},
{
@ -586,21 +419,21 @@ describe("streamResponseThunk", () => {
payload: undefined,
},
{
type: "session/refreshMetadata/rejected",
type: "session/setIsSessionMetadataLoading",
payload: false,
},
{
type: "session/setAllSessionMetadata",
payload: [],
},
{
type: "session/refreshMetadata/fulfilled",
meta: {
aborted: false,
arg: {},
condition: false,
rejectedWithValue: false,
arg: expect.objectContaining({}),
requestId: expect.any(String),
requestStatus: "rejected",
},
payload: undefined,
error: {
message: "Not enough context available for this request",
name: "Error",
stack: expect.any(String),
requestStatus: expect.any(String),
},
payload: [],
},
{
type: "session/update/fulfilled",
@ -608,7 +441,7 @@ describe("streamResponseThunk", () => {
arg: expect.objectContaining({
history: expect.any(Array),
sessionId: "session-123",
title: "New Session",
title: "Hello",
workspaceDirectory: "",
}),
requestId: expect.any(String),
@ -652,7 +485,7 @@ describe("streamResponseThunk", () => {
]);
// Verify IDE messenger was called for compilation but not streaming
expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", {
expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", {
messages: [
{
role: "system",
@ -677,16 +510,17 @@ describe("streamResponseThunk", () => {
],
},
],
options: {
reasoning: false,
},
options: {},
});
expect(mockIdeMessenger.llmStreamChat).not.toHaveBeenCalled();
expect(chatSpy).not.toHaveBeenCalled();
// Verify final state shows error condition
const finalState = mockStore.getState();
expect(finalState).toEqual({
...initialState,
session: {
...initialState.session,
title: "Hello",
history: [
{
contextItems: [],
@ -729,88 +563,36 @@ describe("streamResponseThunk", () => {
},
},
],
hasReasoningEnabled: false,
isStreaming: false, // Should be inactive due to error
id: "session-123",
mode: "chat",
streamAborter: expect.any(AbortController),
contextPercentage: 0, // Unchanged - no successful compilation
isPruned: false, // Unchanged - no successful compilation
isInEdit: false,
title: "New Session",
lastSessionId: undefined,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: "out-of-context", // Error message set
},
config: {
config: {
tools: [],
rules: [],
tabAutocompleteModel: undefined,
selectedModelByRole: {
chat: mockClaudeModel,
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
},
lastSelectedModelByRole: {
chat: mockClaudeModel.title,
},
loading: false,
configError: undefined,
},
ui: {
toolSettings: {},
ruleSettings: {},
showDialog: false,
dialogMessage: undefined,
},
editModeState: {
isInEdit: false,
returnToMode: "chat",
},
indexing: {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
},
tabs: {
tabsItems: [],
},
profiles: {
organizations: [],
selectedProfileId: null,
selectedOrganizationId: null,
preferencesByProfileId: {},
},
});
});
it("should throw error for other compilation errors", async () => {
const { mockStore, mockIdeMessenger } = setupTest();
const initialState = getRootStateWithClaude();
initialState.session.history = [
{
message: { id: "1", role: "user", content: "Hello" },
contextItems: [],
},
];
const mockStore = createMockStore(initialState);
const mockIdeMessenger = mockStore.mockIdeMessenger;
const requestSpy = vi.spyOn(mockIdeMessenger, "request");
const chatSpy = vi.spyOn(mockIdeMessenger, "llmStreamChat");
// Mock compilation failure with generic error
mockIdeMessenger.request.mockResolvedValue({
status: "error",
error: "Model configuration is invalid",
requestSpy.mockImplementation(async (message, data) => {
if (message === "llm/compileChat") {
return {
done: true,
status: "error",
error: "Model configuration is invalid",
};
} else {
return await mockIdeMessenger.request(message, data);
}
});
// Execute thunk and expect it to be rejected
@ -825,7 +607,7 @@ describe("streamResponseThunk", () => {
expect(result.type).toBe("chat/streamResponse/fulfilled");
// Verify exact action sequence for compilation error with dialog
const dispatchedActions = (mockStore as any).getActions();
const dispatchedActions = mockStore.getActions();
expect(dispatchedActions).toEqual([
{
type: "chat/streamResponse/pending",
@ -1004,7 +786,7 @@ describe("streamResponseThunk", () => {
]);
// Verify IDE messenger was called for compilation but not streaming
expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", {
expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", {
messages: [
{
role: "system",
@ -1029,71 +811,21 @@ describe("streamResponseThunk", () => {
],
},
],
options: {
reasoning: false,
},
options: {},
});
expect(mockIdeMessenger.llmStreamChat).not.toHaveBeenCalled();
expect(chatSpy).not.toHaveBeenCalled();
// Verify final state shows error dialog and inactive streaming
const finalState = mockStore.getState();
expect(finalState).toEqual({
...initialState,
session: {
history: [
{
contextItems: [],
message: { id: "1", role: "user", content: "Hello" },
},
],
hasReasoningEnabled: false,
isStreaming: false, // Set to inactive after error
id: "session-123",
mode: "chat",
...initialState.session,
streamAborter: expect.any(AbortController),
contextPercentage: 0,
isPruned: false,
isInEdit: false,
title: "",
lastSessionId: undefined,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: undefined,
mainEditorContentTrigger: mockEditorState, // Editor content that triggered the request
},
config: {
config: {
tools: [],
rules: [],
tabAutocompleteModel: undefined,
selectedModelByRole: {
chat: mockClaudeModel,
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
},
lastSelectedModelByRole: {
chat: mockClaudeModel.title,
},
loading: false,
configError: undefined,
},
ui: {
toolSettings: {},
ruleSettings: {},
...initialState.ui,
showDialog: true, // Error dialog is shown
dialogMessage: expect.objectContaining({
props: expect.objectContaining({
@ -1103,27 +835,6 @@ describe("streamResponseThunk", () => {
}),
}),
},
editModeState: {
isInEdit: false,
returnToMode: "chat",
},
indexing: {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
},
tabs: {
tabsItems: [],
},
profiles: {
organizations: [],
selectedProfileId: null,
selectedOrganizationId: null,
preferencesByProfileId: {},
},
});
});
});

File diff suppressed because it is too large Load diff

View file

@ -13,7 +13,6 @@ export const streamThunkWrapper = createAsyncThunk<
() => Promise<void>,
ThunkApiType
>("chat/streamWrapper", async (runStream, { dispatch, extra, getState }) => {
const initialState = getState();
try {
await runStream();
const state = getState();

View file

@ -5,6 +5,7 @@ import {
ContextItemWithId,
RuleWithSource,
ThinkingChatMessage,
ToolCall,
ToolResultChatMessage,
UserChatMessage,
} from "core";
@ -435,27 +436,26 @@ describe("constructMessages", () => {
});
test("should handle multiple tool calls in a single assistant message", () => {
const toolCall1: ToolCall = {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
};
const toolCall2: ToolCall = {
id: "tool-call-2",
type: "function",
function: {
name: "weather",
arguments: '{"location": "New York"}',
},
};
const assistantWithMultipleToolCalls: AssistantChatMessage = {
role: "assistant",
content: "I will search and check the weather",
toolCalls: [
{
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
{
id: "tool-call-2",
type: "function",
function: {
name: "weather",
arguments: '{"location": "New York"}',
},
},
],
toolCalls: [toolCall1, toolCall2],
};
// Only the first tool call has output
@ -465,21 +465,20 @@ describe("constructMessages", () => {
contextItems: [],
toolCallStates: [
{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
toolCallId: toolCall1.id,
toolCall: toolCall1,
status: "done",
parsedArgs: { query: "test" },
output: [
createContextItem("search-result", "Search result content"),
],
},
{
toolCallId: toolCall2.id,
toolCall: toolCall2,
status: "done",
parsedArgs: { location: "New York" },
},
],
},
];
@ -957,27 +956,36 @@ describe("constructMessages", () => {
expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
});
test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState is undefined", () => {
test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState output is undefined", () => {
const toolCall: ToolCall = {
id: "search-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
};
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I'll search for that",
toolCalls: [
{
id: "search-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
],
toolCalls: [toolCall],
};
mockHistory = [
{
message: assistantWithToolCall,
contextItems: [],
// No toolCallStates array
toolCallStates: [
{
toolCall,
parsedArgs: {
query: "test",
},
status: "generated",
toolCallId: toolCall.id,
// no output defined
},
],
},
];

View file

@ -13,6 +13,7 @@ import { RulePolicies } from "core/llm/rules/types";
import { BuiltInToolNames } from "core/tools/builtIn";
import {
CANCELLED_TOOL_CALL_MESSAGE,
ERRORED_TOOL_CALL_OUTPUT_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "core/tools/constants";
import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools";
@ -126,26 +127,25 @@ export function constructMessages(
});
// Add a tool message for each tool call
if (item.message.toolCalls?.length) {
if (item.toolCallStates?.length) {
// If the assistant message has tool calls, we need to insert tool messages
for (const toolCall of item.message.toolCalls) {
for (const toolCallState of item.toolCallStates) {
const { output, status, toolCall } = toolCallState;
let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE;
// Find the corresponding tool call state for this specific tool call
const toolCallState = item.toolCallStates?.find(
(state) => state.toolCallId === toolCall.id,
);
if (toolCallState?.status === "canceled") {
if (status === "canceled") {
content = CANCELLED_TOOL_CALL_MESSAGE;
} else if (
toolCallState?.output &&
toolCall.function?.name == BuiltInToolNames.RunTerminalCommand
) {
// Add status for tools containing detailed status outcomes per context item
content = renderContextItemsWithStatus(toolCallState.output);
} else if (toolCallState?.output) {
content = renderContextItems(toolCallState?.output);
} else if (output) {
if (
toolCall.function?.name == BuiltInToolNames.RunTerminalCommand
) {
// Add status for tools containing detailed status outcomes per context item
content = renderContextItemsWithStatus(output);
} else {
content = renderContextItems(output);
}
} else if (toolCallState.status === "errored") {
content = ERRORED_TOOL_CALL_OUTPUT_MESSAGE;
}
msgs.push({

View file

@ -30,7 +30,7 @@ function createToolCallState(
// Helper function to create a chat history item
function createChatHistoryItem(
role: "user" | "assistant" | "tool",
role: "user" | "assistant" | "tool" | "thinking",
content: string,
options?: {
toolCallStates?: ToolCallState[];
@ -187,6 +187,82 @@ describe("findCurrentToolCalls", () => {
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual(toolCallStates);
});
it("should return empty array if user message interrupts assistant sequence", () => {
const toolCallStates = [createToolCallState("tool-1", "get_weather")];
const chatHistory = [
createChatHistoryItem("assistant", "I'll check the weather", {
toolCallStates,
}),
createChatHistoryItem("user", "Actually, nevermind"),
createChatHistoryItem("assistant", "Ok, no problem"),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual([]);
});
it("should handle thinking messages as part of assistant sequence", () => {
const toolCallStates = [createToolCallState("tool-1", "get_weather")];
const chatHistory = [
createChatHistoryItem("user", "What's the weather?"),
createChatHistoryItem("thinking", "I need to get weather data"),
createChatHistoryItem("assistant", "I'll check the weather", {
toolCallStates,
}),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual(toolCallStates);
});
it("should find tool calls from last assistant message in sequence", () => {
const firstToolCallStates = [createToolCallState("tool-1", "get_weather")];
const secondToolCallStates = [createToolCallState("tool-2", "get_time")];
const chatHistory = [
createChatHistoryItem("user", "What's the weather?"),
createChatHistoryItem("assistant", "Let me check", {
toolCallStates: firstToolCallStates,
}),
createChatHistoryItem("thinking", "Now I should also get the time"),
createChatHistoryItem("assistant", "And the time too", {
toolCallStates: secondToolCallStates,
}),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual(secondToolCallStates);
});
it("should ignore tool calls from earlier conversation turns", () => {
const oldToolCallStates = [createToolCallState("old-tool", "old_function")];
const newToolCallStates = [createToolCallState("new-tool", "new_function")];
const chatHistory = [
createChatHistoryItem("user", "First question"),
createChatHistoryItem("assistant", "First response", {
toolCallStates: oldToolCallStates,
}),
createChatHistoryItem("user", "Second question"),
createChatHistoryItem("assistant", "Second response", {
toolCallStates: newToolCallStates,
}),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual(newToolCallStates);
});
it("should handle tool message followed by assistant message", () => {
const toolCallStates = [createToolCallState("tool-1", "get_weather")];
const chatHistory = [
createChatHistoryItem("user", "What's the weather?"),
createChatHistoryItem("assistant", "I'll check the weather", {
toolCallStates,
}),
createChatHistoryItem("tool", "Weather data: sunny", {
toolCallId: "tool-1",
}),
createChatHistoryItem("assistant", "It's sunny today!"),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual([]);
});
});
describe("findToolCall", () => {

View file

@ -41,17 +41,25 @@ export function findAllCurToolCalls(
chatHistory: RootState["session"]["history"],
): ToolCallState[] {
// Find the most recent assistant message that has tool call states
let seenAssistantMessage = false;
let passedAssistantMessage = false;
for (let i = chatHistory.length - 1; i >= 0; i--) {
const item = chatHistory[i];
if (
item.message.role === "assistant" &&
item.toolCallStates &&
item.toolCallStates.length > 0
) {
return item.toolCallStates;
if (item.message.role === "user") {
return [];
}
if (item.message.role === "assistant" || item.message.role === "thinking") {
seenAssistantMessage = true;
if (item.toolCallStates && item.toolCallStates.length > 0) {
return item.toolCallStates;
}
} else if (seenAssistantMessage) {
passedAssistantMessage = true;
}
if (passedAssistantMessage) {
return [];
}
}
return [];
}

View file

@ -46,7 +46,11 @@ describe("multiEditImpl GUI specific", () => {
describe("filepath validation", () => {
it("should throw if filepath is missing", async () => {
await expect(
multiEditImpl({ edits: [] }, "id", mockExtras),
multiEditImpl(
{ edits: [{ old_string: "old", new_string: "new" }] },
"id",
mockExtras,
),
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingFilepath,
@ -107,29 +111,6 @@ describe("multiEditImpl GUI specific", () => {
});
});
it("should use editingFileContents if provided instead of reading file", async () => {
const editingContents = "Custom content";
await multiEditImpl(
{
filepath: "file.txt",
edits: [{ old_string: "content", new_string: "text" }],
editingFileContents: editingContents,
},
"id",
mockExtras,
);
expect(mockExtras.ideMessenger.ide.readFile).not.toHaveBeenCalled();
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "Custom text",
filepath: "file:///dir/test/file.txt",
isSearchAndReplace: true,
});
});
it("should wrap IDE readFile errors", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()

View file

@ -1,37 +1,35 @@
import { validateMultiEdit } from "core/edit/searchAndReplace/multiEditValidation";
import { executeMultiFindAndReplace } from "core/edit/searchAndReplace/performReplace";
import { validateSearchAndReplaceFilepath } from "core/edit/searchAndReplace/validateArgs";
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
import { validateSearchAndReplaceFilepath } from "./singleFindAndReplaceImpl";
export const multiEditImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
const { filepath, editingFileContents } = args;
const resolvedUri = await validateSearchAndReplaceFilepath(
filepath,
// Note that this is fully duplicate of what occurs in args preprocessing
// This is to handle cases where file changes while tool call is pending
const { edits } = validateMultiEdit(args);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ideMessenger.ide,
);
const { edits } = validateMultiEdit(args);
const currentContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedUri));
const fileUri = resolvedUri;
const newContent = executeMultiFindAndReplace(currentContent, edits);
const editingFileContents = await extras.ideMessenger.ide.readFile(fileUri);
const newFileContents = executeMultiFindAndReplace(
editingFileContents,
edits,
);
const streamId = uuid();
void extras.dispatch(
applyForEditTool({
streamId,
toolCallId,
text: newContent,
text: newFileContents,
filepath: fileUri,
isSearchAndReplace: true,
}),

View file

@ -1,62 +1,33 @@
import { IDE } from "core";
import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils";
import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { validateSearchAndReplaceFilepath } from "core/edit/searchAndReplace/validateArgs";
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
export async function validateSearchAndReplaceFilepath(
filepath: any,
ide: IDE,
) {
if (!filepath || typeof filepath !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingFilepath,
"filepath (string) is required",
);
}
const resolvedFilepath = await resolveRelativePathInDir(filepath, ide);
if (!resolvedFilepath) {
throw new ContinueError(
ContinueErrorReason.FileNotFound,
`File ${filepath} does not exist`,
);
}
return resolvedFilepath;
}
export const singleFindAndReplaceImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
const {
filepath,
old_string,
new_string,
replace_all = false,
editingFileContents,
} = args;
const resolvedUri = await validateSearchAndReplaceFilepath(
filepath,
// Note that this is fully duplicate of what occurs in args preprocessing
// This is to handle cases where file changes while tool call is pending
const { oldString, newString, replaceAll } = validateSingleEdit(
args.old_string,
args.new_string,
args.replace_all,
);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ideMessenger.ide,
);
validateSingleEdit(old_string, new_string);
// Read the current file content
const originalContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedUri));
// Perform the find and replace operation
const newContent = executeFindAndReplace(
originalContent,
old_string,
new_string,
replace_all,
const editingFileContents = await extras.ideMessenger.ide.readFile(fileUri);
const newFileContents = executeFindAndReplace(
editingFileContents,
oldString,
newString,
replaceAll ?? false,
0,
);
@ -66,8 +37,8 @@ export const singleFindAndReplaceImpl: ClientToolImpl = async (
applyForEditTool({
streamId,
toolCallId,
text: newContent,
filepath: resolvedUri,
text: newFileContents,
filepath: fileUri,
isSearchAndReplace: true,
}),
);

View file

@ -1,23 +1,64 @@
import { configureStore } from "@reduxjs/toolkit";
import { copyOf } from "core/util";
import { vi } from "vitest";
import configReducer from "../../redux/slices/configSlice";
import editModeStateReducer from "../../redux/slices/editState";
import indexingReducer from "../../redux/slices/indexingSlice";
import { profilesReducer } from "../../redux/slices/profilesSlice";
import sessionReducer from "../../redux/slices/sessionSlice";
import tabsReducer from "../../redux/slices/tabsSlice";
import uiReducer from "../../redux/slices/uiSlice";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
import configReducer, {
INITIAL_CONFIG_SLICE,
} from "../../redux/slices/configSlice";
import editModeStateReducer, {
INITIAL_EDIT_STATE,
} from "../../redux/slices/editState";
import indexingReducer, {
INITIAL_INDEXING_STATE,
} from "../../redux/slices/indexingSlice";
import {
INITIAL_PROFILES_STATE,
profilesReducer,
} from "../../redux/slices/profilesSlice";
import sessionReducer, {
INITIAL_SESSION_STATE,
} from "../../redux/slices/sessionSlice";
import tabsReducer, { INITIAL_TABS_STATE } from "../../redux/slices/tabsSlice";
import uiReducer, { DEFAULT_UI_SLICE } from "../../redux/slices/uiSlice";
import { RootState } from "../../redux/store";
export const createMockStore = (initialState?: Partial<RootState>) => {
const mockIdeMessenger = {
request: vi.fn(),
post: vi.fn(),
respond: vi.fn(),
streamRequest: vi.fn(),
llmStreamChat: vi.fn(),
ide: {} as any,
// TODO remove non-serializable streamAborter, causes headaches
export const getEmptyRootState: () => RootState = () => {
const withoutSession: Omit<RootState, "session"> = {
config: INITIAL_CONFIG_SLICE,
ui: DEFAULT_UI_SLICE,
editModeState: INITIAL_EDIT_STATE,
indexing: INITIAL_INDEXING_STATE,
profiles: INITIAL_PROFILES_STATE,
tabs: INITIAL_TABS_STATE,
};
const { streamAborter, ...serializableSession } = INITIAL_SESSION_STATE;
const sessionCopy = copyOf(serializableSession) as Omit<
RootState["session"],
"streamAborter"
>;
const withoutSessionCopy = copyOf(withoutSession) as Omit<
RootState,
"session"
>;
return {
...withoutSessionCopy,
session: {
...sessionCopy,
streamAborter: new AbortController(),
},
};
};
export const createMockStore = (
initialState?: Partial<RootState>,
mockMessenger?: MockIdeMessenger,
): ReturnType<typeof configureStore> & {
mockIdeMessenger: MockIdeMessenger;
getActions: () => any[];
clearActions: () => void;
} => {
const mockIdeMessenger = mockMessenger ?? new MockIdeMessenger();
const store = configureStore({
reducer: {
@ -30,94 +71,14 @@ export const createMockStore = (initialState?: Partial<RootState>) => {
profiles: profilesReducer,
},
preloadedState: {
session: {
history: [],
title: "",
id: "",
lastSessionId: undefined,
mode: "chat",
isStreaming: false,
streamAborter: new AbortController(),
hasReasoningEnabled: false,
contextPercentage: 0,
isPruned: false,
isInEdit: false,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: undefined,
...initialState?.session,
},
ui: {
showDialog: false,
dialogMessage: null,
toolSettings: {},
ruleSettings: {},
...initialState?.ui,
},
editModeState: {
isInEdit: false,
returnToMode: "chat",
...initialState?.editModeState,
},
config: {
config: {
models: [],
tabAutocompleteModel: undefined,
tools: [],
rules: [],
selectedModelByRole: {
chat: null,
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
...initialState?.config?.config,
},
lastSelectedModelByRole: {},
loading: false,
configError: undefined,
...initialState?.config,
},
indexing: {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
...initialState?.indexing,
},
tabs: {
tabsItems: [],
...initialState?.tabs,
},
profiles: {
organizations: [],
selectedProfileId: null,
selectedOrganizationId: null,
preferencesByProfileId: {},
...initialState?.profiles,
},
} as RootState,
...getEmptyRootState(),
...initialState,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredPaths: ["session.streamAborter"],
ignoredActions: [
"chat/streamNormalInput/pending",
"chat/streamNormalInput/fulfilled",
"chat/streamNormalInput/rejected",
],
ignoredPaths: ["session.streamAborter", "ui.dialogMessage"],
ignoredActions: ["ui/setDialogMessage"],
},
thunk: {
extraArgument: {
@ -141,11 +102,13 @@ export const createMockStore = (initialState?: Partial<RootState>) => {
}
actions.push(action);
return originalDispatch(action);
}) as any;
(store as any).getActions = () => actions;
(store as any).clearActions = () => actions.splice(0, actions.length);
});
// Expose mockIdeMessenger so tests can configure it
return { ...store, mockIdeMessenger };
return {
...store,
mockIdeMessenger,
getActions: () => actions,
clearActions: () => actions.splice(0, actions.length),
};
};

View file

@ -17,6 +17,7 @@ import { setupStore } from "../../redux/store";
type ExtendedRenderOptions = Omit<RenderOptions, "queries"> & {
store?: ReturnType<typeof setupStore>;
routerProps?: RouterProps;
mockIdeMessenger?: MockIdeMessenger;
};
function setupMocks() {
@ -32,7 +33,8 @@ export async function renderWithProviders(
extendedRenderOptions: ExtendedRenderOptions = {},
) {
setupMocks();
const ideMessenger = new MockIdeMessenger();
const ideMessenger =
extendedRenderOptions?.mockIdeMessenger ?? new MockIdeMessenger();
const {
// Automatically create a store instance if no store was passed in

File diff suppressed because it is too large Load diff

View file

@ -15,7 +15,7 @@
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-yaml": "file:../config-yaml",
"@openapitools/openapi-generator-cli": "^2.19.1",
"@openapitools/openapi-generator-cli": "^2.24.0",
"express": "^4.18.2",
"swagger-ui-express": "^5.0.0"
},