diff --git a/core/config/load.ts b/core/config/load.ts index 22a7ab22f..69b982405 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -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()), diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 89c6696c9..97011a77c 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -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, diff --git a/core/core.ts b/core/core.ts index 02e05a628..17479774d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -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); }); diff --git a/core/edit/searchAndReplace/findAndReplaceUtils.ts b/core/edit/searchAndReplace/findAndReplaceUtils.ts index b85dcdfb9..e3185374e 100644 --- a/core/edit/searchAndReplace/findAndReplaceUtils.ts +++ b/core/edit/searchAndReplace/findAndReplaceUtils.ts @@ -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({ diff --git a/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts b/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts index b08413a9d..1489de7ac 100644 --- a/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts +++ b/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts @@ -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, diff --git a/core/edit/searchAndReplace/multiEditValidation.ts b/core/edit/searchAndReplace/multiEditValidation.ts index b103884fb..3600eeebc 100644 --- a/core/edit/searchAndReplace/multiEditValidation.ts +++ b/core/edit/searchAndReplace/multiEditValidation.ts @@ -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 === "") { diff --git a/core/edit/searchAndReplace/validateArgs.ts b/core/edit/searchAndReplace/validateArgs.ts new file mode 100644 index 000000000..623503515 --- /dev/null +++ b/core/edit/searchAndReplace/validateArgs.ts @@ -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; +} diff --git a/core/index.d.ts b/core/index.d.ts index 43b296027..9b20f1a72 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1082,7 +1082,6 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; - displayTitle: string; wouldLikeTo?: string; isCurrently?: string; @@ -1099,6 +1098,12 @@ export interface Tool { }; defaultToolPolicy?: ToolPolicy; toolCallIcon?: string; + preprocessArgs?: ( + args: Record, + extras: { + ide: IDE; + }, + ) => Promise>; evaluateToolCallPolicy?: ( basePolicy: ToolPolicy, parsedArgs: Record, @@ -1779,7 +1784,7 @@ export interface BrowserSerializedContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; - tools: Tool[]; + tools: Omit[]; mcpServerStatuses: MCPServerStatus[]; rules: RuleWithSource[]; usePlatform: boolean; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index a14c2dcba..cdd20c7b5 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -314,6 +314,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { { toolName: string; basePolicy: ToolPolicy; args: Record }, { policy: ToolPolicy; displayValue?: string }, ]; + "tools/preprocessArgs": [ + { toolName: string; args: Record }, + { preprocessedArgs?: Record }, + ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; "controlPlane/getEnvironment": [undefined, ControlPlaneEnv]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 192e5596b..e27e53c47 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -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", diff --git a/core/tools/constants.ts b/core/tools/constants.ts index 0b5278209..332a270ef 100644 --- a/core/tools/constants.ts +++ b/core/tools/constants.ts @@ -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."; diff --git a/core/tools/definitions/multiEdit.ts b/core/tools/definitions/multiEdit.ts index 1fb045b22..e526b90e5 100644 --- a/core/tools/definitions/multiEdit.ts +++ b/core/tools/definitions/multiEdit.ts @@ -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, + }; + }, }; diff --git a/core/tools/definitions/singleFindAndReplace.ts b/core/tools/definitions/singleFindAndReplace.ts index 653fba584..c5b2995e1 100644 --- a/core/tools/definitions/singleFindAndReplace.ts +++ b/core/tools/definitions/singleFindAndReplace.ts @@ -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, + }; + }, }; diff --git a/core/tools/index.ts b/core/tools/index.ts index e021a601c..bdc519dc9 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -51,3 +51,8 @@ export const getConfigDependentToolDefinitions = ( return tools; }; + +export function serializeTool(tool: Tool) { + const { preprocessArgs, evaluateToolCallPolicy, ...rest } = tool; + return rest; +} diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 0a1778395..44b9b5f11 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -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 diff --git a/core/util/errors.ts b/core/util/errors.ts index 9a5c07443..4c6cfb16d 100644 --- a/core/util/errors.ts +++ b/core/util/errors.ts @@ -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 } diff --git a/docs/docs.json b/docs/docs.json index 796eb1f77..94be18094 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -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" ] } diff --git a/docs/guides/dlt-mcp-continue-cookbook.mdx b/docs/guides/dlt-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..c3460ed24 --- /dev/null +++ b/docs/guides/dlt-mcp-continue-cookbook.mdx @@ -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" +--- + + + 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 + + +## 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: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + ```bash + pip install dlt + ``` + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + + +## dlt MCP Workflow Options + + + 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. + + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + 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 + + + + 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. + + + + + **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. + + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + 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. + + + **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. + + + + The MCP will work with your existing dlt pipelines in your current directory. + + + + + + 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. + ``` + + + + + + + + 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. + + + +--- + +## dlt MCP vs dlt+ MCP + + + **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. + + +--- + +## 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. + + +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. + + + + **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. + + + + + **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. + + + +### Pipeline Inspection + + + 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 +``` + + + +### Schema Management + + + 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 +``` + + + +### Data Exploration + + + 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 +``` + + + +### Error Debugging + + + 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 +``` + + + +### Pipeline Creation + + + 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 +``` + + + +### Schema Evolution + + + 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 +``` + + + +## 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 + + + 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. + + +### 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" +``` + + + The dlt MCP works with your local pipeline state. Make sure your CI environment + has access to the necessary pipeline configuration and credentials. + + +## 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. + + + ```bash + "Before committing pipeline changes, verify the schema + matches expectations and flag any unexpected modifications." + ``` + + + + ```bash + "When load errors occur, analyze the error details and + suggest specific code fixes to handle the data issues." + ``` + + + + ```bash + "Track pipeline execution times and file sizes. Alert if + performance degrades significantly from baseline." + ``` + + + + ```bash + "After each pipeline run, validate row counts and check for + null values in critical columns." + ``` + + +## 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 + + + **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 + + +## 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 + + + 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. + + +## 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 + + + + Complete dlt platform documentation + + + Explore more MCP integrations and agents + + + Learn about AI assistants, MCP, and Continue integration + + + Deep dive into dlt MCP integration + + \ No newline at end of file diff --git a/docs/guides/snyk-mcp-continue-cookbook.mdx b/docs/guides/snyk-mcp-continue-cookbook.mdx index 709cfd604..5a1d3b343 100644 --- a/docs/guides/snyk-mcp-continue-cookbook.mdx +++ b/docs/guides/snyk-mcp-continue-cookbook.mdx @@ -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. + + + **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. + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). @@ -66,8 +76,8 @@ After ensuring you meet the **Prerequisites** above, you have two paths to get s 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 ``` @@ -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 ``` @@ -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 ``` @@ -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 ``` @@ -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 ``` @@ -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 ``` ## 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. + + + + **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. + + ### 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 < 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 ``` - 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. + + + + 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 ## Security Guardrails diff --git a/docs/hub/workflows/intro.mdx b/docs/hub/workflows/intro.mdx new file mode 100644 index 000000000..1c5fd3d5b --- /dev/null +++ b/docs/hub/workflows/intro.mdx @@ -0,0 +1,97 @@ +--- +title: "Introduction" +description: "Run Continuous AI workflows in the background" +--- + + + Workflows are in beta. Please share any feedback with us in [GitHub discussions](https://github.com/continuedev/continue/discussions/8051). + + +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: + + + + + - "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" + + + + + + - "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" + + + + + + - "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" + + + + + + - "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" + + + + + + - "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" + + + + + + - "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" + + + + +## 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. diff --git a/docs/images/hub/workflows/images/workflows-setup.png b/docs/images/hub/workflows/images/workflows-setup.png new file mode 100644 index 000000000..05419e84d Binary files /dev/null and b/docs/images/hub/workflows/images/workflows-setup.png differ diff --git a/extensions/cli/src/auth/workos.ts b/extensions/cli/src/auth/workos.ts index d110ea161..a005eb56a 100644 --- a/extensions/cli/src/auth/workos.ts +++ b/extensions/cli/src/auth/workos.ts @@ -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; } /** diff --git a/extensions/cli/src/commands/login.ts b/extensions/cli/src/commands/login.ts index a1c6cc4f8..e5abf3136 100644 --- a/extensions/cli/src/commands/login.ts +++ b/extensions/cli/src/commands/login.ts @@ -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); diff --git a/extensions/cli/src/commands/ls.ts b/extensions/cli/src/commands/ls.ts index d78ae162d..529c711b8 100644 --- a/extensions/cli/src/commands/ls.ts +++ b/extensions/cli/src/commands/ls.ts @@ -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 { - 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; } /** diff --git a/extensions/cli/src/commands/remote.test.ts b/extensions/cli/src/commands/remote.test.ts index 625ac18a8..a8025a4d7 100644 --- a/extensions/cli/src/commands/remote.test.ts +++ b/extensions/cli/src/commands/remote.test.ts @@ -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, }); diff --git a/extensions/cli/src/commands/remote.ts b/extensions/cli/src/commands/remote.ts index 61110f2e1..919c720fd 100644 --- a/extensions/cli/src/commands/remote.ts +++ b/extensions/cli/src/commands/remote.ts @@ -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("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(`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) { diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 2aee9e23a..8256ca6f1 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -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"), ); diff --git a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts index a5ccf0970..ccb2437c9 100644 --- a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts +++ b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts @@ -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", ); diff --git a/extensions/cli/src/e2e/headless-permission-error.test.ts b/extensions/cli/src/e2e/headless-permission-error.test.ts new file mode 100644 index 000000000..60a10d16f --- /dev/null +++ b/extensions/cli/src/e2e/headless-permission-error.test.ts @@ -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); +}); diff --git a/extensions/cli/src/integration/model-persistence-e2e.test.ts b/extensions/cli/src/integration/model-persistence-e2e.test.ts new file mode 100644 index 000000000..22354c989 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-e2e.test.ts @@ -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"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts b/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts new file mode 100644 index 000000000..db4b30ee4 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts @@ -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"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence-user-flow.test.ts b/extensions/cli/src/integration/model-persistence-user-flow.test.ts new file mode 100644 index 000000000..35f9eb544 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-user-flow.test.ts @@ -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"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence.test.ts b/extensions/cli/src/integration/model-persistence.test.ts new file mode 100644 index 000000000..9e352143d --- /dev/null +++ b/extensions/cli/src/integration/model-persistence.test.ts @@ -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 "); + }); +}); diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.test.ts b/extensions/cli/src/stream/streamChatResponse.helpers.test.ts new file mode 100644 index 000000000..4b13eec25 --- /dev/null +++ b/extensions/cli/src/stream/streamChatResponse.helpers.test.ts @@ -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); + }); + }); +}); diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index cc987aecb..b613fd1cb 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -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 { 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 diff --git a/extensions/cli/src/tools/edit.ts b/extensions/cli/src/tools/edit.ts index a3623361d..30aaacb86 100644 --- a/extensions/cli/src/tools/edit.ts +++ b/extensions/cli/src/tools/edit.ts @@ -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, ); diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index fda429563..36837f233 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -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; } diff --git a/extensions/cli/src/tools/status.ts b/extensions/cli/src/tools/status.ts new file mode 100644 index 000000000..ff85dcd93 --- /dev/null +++ b/extensions/cli/src/tools/status.ts @@ -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 => { + 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}`; + } + }, +}; diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index e7714fbc7..8f8f24226 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -264,6 +264,7 @@ const TUIChat: React.FC = ({ configPath, setChatHistory, handleClear, + setStaticRefreshTrigger, ); // Session selection handler diff --git a/extensions/cli/src/ui/TextBuffer.test.ts b/extensions/cli/src/ui/TextBuffer.test.ts index 4d88015af..a9d539ed3 100644 --- a/extensions/cli/src/ui/TextBuffer.test.ts +++ b/extensions/cli/src/ui/TextBuffer.test.ts @@ -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); diff --git a/extensions/cli/src/ui/TextBuffer.ts b/extensions/cli/src/ui/TextBuffer.ts index 103b48571..65784e852 100644 --- a/extensions/cli/src/ui/TextBuffer.ts +++ b/extensions/cli/src/ui/TextBuffer.ts @@ -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) { diff --git a/extensions/cli/src/ui/hooks/useModelSelector.ts b/extensions/cli/src/ui/hooks/useModelSelector.ts index c01439bd9..e00f21981 100644 --- a/extensions/cli/src/ui/hooks/useModelSelector.ts +++ b/extensions/cli/src/ui/hooks/useModelSelector.ts @@ -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(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", diff --git a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts index 04b4cf25d..6025496f5 100644 --- a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts +++ b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts @@ -175,6 +175,7 @@ export function useSelectors( configPath: string | undefined, setChatHistory: React.Dispatch>, handleClear: () => void, + setStaticRefreshTrigger?: React.Dispatch>, ): { handleConfigSelect: (config: ConfigOption) => Promise; handleModelSelect: (model: ModelOption) => Promise; @@ -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 { diff --git a/extensions/cli/src/util/apiClient.test.ts b/extensions/cli/src/util/apiClient.test.ts new file mode 100644 index 000000000..09bb12ed5 --- /dev/null +++ b/extensions/cli/src/util/apiClient.test.ts @@ -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"); + }); + }); +}); diff --git a/extensions/cli/src/util/apiClient.ts b/extensions/cli/src/util/apiClient.ts new file mode 100644 index 000000000..16119c4a0 --- /dev/null +++ b/extensions/cli/src/util/apiClient.ts @@ -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; + headers?: Record; +} + +export interface ApiResponse { + 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( + endpoint: string, + options: ApiRequestOptions = {}, +): Promise> { + // 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( + endpoint: string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { method: "GET", headers }); +} + +/** + * Convenience function for POST requests + */ +export async function post( + endpoint: string, + body?: Record | string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { + method: "POST", + body, + headers, + }); +} + +/** + * Convenience function for PUT requests + */ +export async function put( + endpoint: string, + body?: Record | string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { + method: "PUT", + body, + headers, + }); +} + +/** + * Convenience function for DELETE requests + */ +export async function del( + endpoint: string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { method: "DELETE", headers }); +} diff --git a/extensions/cli/src/util/modelPersistence.ts b/extensions/cli/src/util/modelPersistence.ts new file mode 100644 index 000000000..ace51c396 --- /dev/null +++ b/extensions/cli/src/util/modelPersistence.ts @@ -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); +} diff --git a/extensions/cli/src/util/yamlConfigUpdater.test.ts b/extensions/cli/src/util/yamlConfigUpdater.test.ts index cb65b6b9e..c92d035aa 100644 --- a/extensions/cli/src/util/yamlConfigUpdater.test.ts +++ b/extensions/cli/src/util/yamlConfigUpdater.test.ts @@ -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"); }); diff --git a/extensions/cli/src/util/yamlConfigUpdater.ts b/extensions/cli/src/util/yamlConfigUpdater.ts index 738f075cf..4c249bb1f 100644 --- a/extensions/cli/src/util/yamlConfigUpdater.ts +++ b/extensions/cli/src/util/yamlConfigUpdater.ts @@ -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 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 34c3dad6b..417f12cdb 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -145,6 +145,7 @@ class MessageTypes { "didChangeSelectedOrg", "tools/call", "tools/evaluatePolicy", + "tools/preprocessArgs", "controlPlane/openUrl", "isItemTooBig", "process/markAsBackgrounded", diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts index 1669612e1..e2e8a8ec9 100644 --- a/gui/src/context/MockIdeMessenger.ts +++ b/gui/src/context/MockIdeMessenger.ts @@ -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; } diff --git a/gui/src/pages/config/sections/docs/DocsIndexingStatus.test.tsx b/gui/src/pages/config/sections/docs/DocsIndexingStatus.test.tsx index d77f723fd..9c09e839a 100644 --- a/gui/src/pages/config/sections/docs/DocsIndexingStatus.test.tsx +++ b/gui/src/pages/config/sections/docs/DocsIndexingStatus.test.tsx @@ -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(); }); diff --git a/gui/src/pages/config/sections/docs/IndexedPagesTooltip.test.tsx b/gui/src/pages/config/sections/docs/IndexedPagesTooltip.test.tsx index 80a620a01..c5d0d5b4d 100644 --- a/gui/src/pages/config/sections/docs/IndexedPagesTooltip.test.tsx +++ b/gui/src/pages/config/sections/docs/IndexedPagesTooltip.test.tsx @@ -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", ); diff --git a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx index 8c0e76b93..95afc2d89 100644 --- a/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FindAndReplace.tsx @@ -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) { diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 010035c79..0ce5810d5 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -45,7 +45,8 @@ function FunctionSpecificToolCallDiv({ return ( { it("History text is existed after render", async () => { - await renderWithProviders(); + await renderWithProviders(, { + mockIdeMessenger, + }); expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument(); }); it("History shows the first item in the list", async () => { - await renderWithProviders(); + await renderWithProviders(, { + mockIdeMessenger, + }); const sessionElement = await screen.findByText( "Session 1", {}, diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 0deb9f6e4..678354655 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -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, diff --git a/gui/src/redux/slices/editState.ts b/gui/src/redux/slices/editState.ts index 74379b29f..c76351e4c 100644 --- a/gui/src/redux/slices/editState.ts +++ b/gui/src/redux/slices/editState.ts @@ -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, diff --git a/gui/src/redux/slices/indexingSlice.ts b/gui/src/redux/slices/indexingSlice.ts index 6f5bad403..724167878 100644 --- a/gui/src/redux/slices/indexingSlice.ts +++ b/gui/src/redux/slices/indexingSlice.ts @@ -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, diff --git a/gui/src/redux/slices/profilesSlice.ts b/gui/src/redux/slices/profilesSlice.ts index a60c7b775..f63c797a9 100644 --- a/gui/src/redux/slices/profilesSlice.ts +++ b/gui/src/redux/slices/profilesSlice.ts @@ -19,7 +19,7 @@ export interface ProfilesState { preferencesByProfileId: Record; } -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) => { state.selectedProfileId = payload; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 1a0cd3a58..541787888 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -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; // 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"; } }); diff --git a/gui/src/redux/slices/tabsSlice.ts b/gui/src/redux/slices/tabsSlice.ts index bceab688b..670ca9966 100644 --- a/gui/src/redux/slices/tabsSlice.ts +++ b/gui/src/redux/slices/tabsSlice.ts @@ -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) => { state.tabs = action.payload; diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 48c23bd9b..e261af346 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -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, diff --git a/gui/src/redux/thunks/callToolById.ts b/gui/src/redux/thunks/callToolById.ts index cbf6801fc..9c9689b87 100644 --- a/gui/src/redux/thunks/callToolById.ts +++ b/gui/src/redux/thunks/callToolById.ts @@ -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); diff --git a/gui/src/redux/thunks/evaluateToolPolicies.ts b/gui/src/redux/thunks/evaluateToolPolicies.ts new file mode 100644 index 000000000..990aef4c8 --- /dev/null +++ b/gui/src/redux/thunks/evaluateToolPolicies.ts @@ -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 { + 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 { + // 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; +} diff --git a/gui/src/redux/thunks/preprocessToolCallArgs.ts b/gui/src/redux/thunks/preprocessToolCallArgs.ts new file mode 100644 index 000000000..f6b973323 --- /dev/null +++ b/gui/src/redux/thunks/preprocessToolCallArgs.ts @@ -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 { + // 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, + }, + ], + }), + ); + } + }), + ); +} diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index c2fe35c36..f6314cbb0 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -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"; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 1b86c9a91..b1f5d10ff 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -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, - 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 { - // 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 }), + ), + ); + } + } } }, ); diff --git a/gui/src/redux/thunks/streamResponse.test.ts b/gui/src/redux/thunks/streamResponse.test.ts index 3a43d979d..cff4eb7ae 100644 --- a/gui/src/redux/thunks/streamResponse.test.ts +++ b/gui/src/redux/thunks/streamResponse.test.ts @@ -1,7 +1,12 @@ import { JSONContent } from "@tiptap/core"; -import { InputModifiers } from "core"; +import { + AssistantChatMessage, + ChatMessage, + InputModifiers, + PromptLog, +} 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 @@ -37,8 +42,11 @@ vi.mock( ); import { ModelDescription } from "core"; +import { serializeTool } from "core/tools"; +import { grepSearchTool } from "core/tools/definitions"; import posthog from "posthog-js"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; +import { RootState } from "../store"; const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage); @@ -70,11 +78,25 @@ const mockModifiers: InputModifiers = { noContext: false, }; -function setupTest() { +export function getRootStateWithClaude(): RootState { + const state = getEmptyRootState(); + return { + ...state, + config: { + ...state.config, + config: { + ...state.config.config, + selectedModelByRole: { + ...state.config.config.selectedModelByRole, + chat: mockClaudeModel, + }, + }, + }, + }; +} + +beforeEach(() => { vi.clearAllMocks(); - - // Default mock implementations for external functions - // Default mock for resolveEditorContent (can be overridden in individual tests) mockResolveEditorContent.mockResolvedValue({ selectedContextItems: [], @@ -85,114 +107,47 @@ 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 execute complete streaming flow with all dispatches", 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; - // Mock all necessary IDE messenger calls - mockIdeMessenger.request.mockImplementation((endpoint: string) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Hello" }], - didPrune: false, - contextPercentage: 0.8, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "session/refreshMetadata") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Hello" }], - didPrune: false, - contextPercentage: 0.8, - }, - }); - } - return Promise.resolve({ status: "success", content: {} }); - }); + mockIdeMessenger.responses["llm/compileChat"] = { + compiledChatMessages: [{ role: "user", content: "Hello" }], + didPrune: false, + contextPercentage: 0.8, + }; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); + const postSpy = vi.spyOn(mockIdeMessenger, "post"); // Setup streaming generator - async function* mockStreamGenerator() { + async function* mockStreamGenerator(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "First chunk" }]; yield [{ role: "assistant", content: "Second chunk" }]; return { prompt: "Hello", completion: "Hi there!", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamGenerator()); + const mockStreamChat = vi.fn(); + mockStreamChat.mockReturnValue(mockStreamGenerator()); + mockIdeMessenger.llmStreamChat = mockStreamChat; // Execute thunk const result = await mockStore.dispatch( @@ -203,7 +158,7 @@ describe("streamResponseThunk", () => { ); // Verify exact sequence of dispatched actions with payloads - const dispatchedActions = (mockStore as any).getActions(); + const dispatchedActions = mockStore.getActions(); expect(dispatchedActions).toEqual([ { @@ -318,6 +273,7 @@ describe("streamResponseThunk", () => { prompt: "Hello", completion: "Hi there!", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }, ], }, @@ -352,7 +308,7 @@ describe("streamResponseThunk", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -368,14 +324,14 @@ describe("streamResponseThunk", () => { }, { type: "session/setAllSessionMetadata", - payload: {}, + payload: [], }, { type: "session/refreshMetadata/fulfilled", meta: expect.objectContaining({ requestStatus: "fulfilled", }), - payload: {}, + payload: [], }, { type: "session/update/fulfilled", @@ -410,7 +366,7 @@ describe("streamResponseThunk", () => { ]); // Verify IDE messenger calls - expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", { + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { messages: [ { role: "system", @@ -435,16 +391,12 @@ describe("streamResponseThunk", () => { ], }, ], - options: { - reasoning: false, - }, + options: {}, }); expect(mockIdeMessenger.llmStreamChat).toHaveBeenCalledWith( { - completionOptions: { - reasoning: false, - }, + completionOptions: {}, legacySlashCommandData: undefined, messageOptions: { precompiled: true }, messages: [ @@ -459,7 +411,7 @@ describe("streamResponseThunk", () => { ); // Verify dev data logging call - expect(mockIdeMessenger.post).toHaveBeenCalledWith("devdata/log", { + expect(postSpy).toHaveBeenCalledWith("devdata/log", { name: "chatInteraction", data: { prompt: "Hello", @@ -472,17 +424,21 @@ describe("streamResponseThunk", () => { }); // Verify session save was called - expect(mockIdeMessenger.request).toHaveBeenCalledWith( - "history/save", - expect.anything(), - ); + expect(requestSpy).toHaveBeenCalledWith("history/save", expect.anything()); expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify final state after thunk completion const finalState = mockStore.getState(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, + streamAborter: expect.any(AbortController), + title: "Session summary", + isPruned: false, + inlineErrorMessage: undefined, + contextPercentage: 0.8, history: [ { contextItems: [], @@ -511,208 +467,72 @@ describe("streamResponseThunk", () => { completion: "Hi there!", modelProvider: "anthropic", prompt: "Hello", + modelTitle: "Claude 3.5 Sonnet", }, ], }, ], - hasReasoningEnabled: false, - isStreaming: false, - id: "session-123", - mode: "chat", - streamAborter: expect.any(AbortController), - contextPercentage: 0.8, - isPruned: false, - isInEdit: false, - title: "New Session", - 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, - }, - }, - 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 execute streaming flow with tool call execution", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Set up auto-approved tool setting for our test tool - const mockStoreWithToolSettings = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please search the codebase", - }, - 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, + const stateWithToolSettings = getRootStateWithClaude(); + stateWithToolSettings.session.history = [ + { + message: { + id: "1", + role: "user", + content: "Please search the codebase", }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + contextItems: [], }, - 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: { - search_codebase: "allowedWithoutPermission", // Auto-approve this tool - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); + ]; + const grepTool = serializeTool(grepSearchTool); + const grepName = grepTool.function.name; + stateWithToolSettings.config.config.tools = [grepTool]; + + stateWithToolSettings.ui.toolSettings = { + [grepName]: "allowedWithoutPermission", // Auto-approve this tool + }; + stateWithToolSettings.session.id = "session-123"; + const mockStoreWithToolSettings = createMockStore(stateWithToolSettings); const mockIdeMessengerWithTool = mockStoreWithToolSettings.mockIdeMessenger; // Setup successful compilation and tool responses - mockIdeMessengerWithTool.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Please search the codebase" }, - ], - didPrune: false, - contextPercentage: 0.9, - }, - }); - } else if (endpoint === "tools/evaluatePolicy") { - // Mock dynamic policy evaluation - return auto-approve for this test - return Promise.resolve({ - status: "success", - content: { policy: "allowedWithoutPermission" }, - }); - } else if (endpoint === "tools/call") { - // Mock server-side tool call response - return Promise.resolve({ - status: "success", - content: { - contextItems: [ - { - name: "Search Results", - description: "Found 3 matches", - content: "Result 1\nResult 2\nResult 3", - icon: "search", - hidden: false, - }, - ], - errorMessage: undefined, - }, - }); - } else if (endpoint === "history/save") { - // Mock session save - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - // Let other endpoints pass through or return success - return Promise.resolve({ status: "success", content: {} }); - }, - ); + mockIdeMessengerWithTool.responses["llm/compileChat"] = { + compiledChatMessages: [ + { role: "user", content: "Please search the codebase" }, + ], + didPrune: false, + contextPercentage: 0.9, + }; + mockIdeMessengerWithTool.responses["tools/call"] = { + contextItems: [ + { + name: "Search Results", + description: "Found 3 matches", + content: "Result 1\nResult 2\nResult 3", + icon: "search", + hidden: false, + }, + ], + errorMessage: undefined, + }; + const requestSpy = vi.spyOn(mockIdeMessengerWithTool, "request"); // Setup streaming generator with tool call - async function* mockStreamGeneratorWithTool() { + async function* mockStreamGeneratorWithTool(): AsyncGenerator< + ChatMessage[], + PromptLog + > { yield [ - { role: "assistant", content: "I'll search the codebase for you." }, + { + role: "assistant", + content: "I'll search the codebase for you.", + }, ]; yield [ { @@ -723,7 +543,7 @@ describe("streamResponseThunk", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepTool.function.name, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -734,29 +554,35 @@ describe("streamResponseThunk", () => { prompt: "Please search the codebase", completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } // Mock different streaming responses for multiple calls let streamCallCount = 0; - mockIdeMessengerWithTool.llmStreamChat.mockImplementation(() => { + const mockStreamChat = vi.fn().mockImplementation(() => { streamCallCount++; if (streamCallCount === 1) { // First call - main streaming with tool call return mockStreamGeneratorWithTool(); } else { // Subsequent calls from streamResponseAfterToolCall - return minimal response - async function* simpleGenerator() { + async function* simpleGenerator(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "Search completed." }]; return { prompt: "continuing after tool", completion: "Search completed.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } return simpleGenerator(); } }); + mockIdeMessengerWithTool.llmStreamChat = mockStreamChat; // Execute thunk const result = await mockStoreWithToolSettings.dispatch( @@ -767,7 +593,7 @@ describe("streamResponseThunk", () => { ); // Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist) - const dispatchedActions = (mockStoreWithToolSettings as any).getActions(); + const dispatchedActions = mockStoreWithToolSettings.getActions(); // Verify exact action sequence const actionTypes = dispatchedActions.map((action: any) => action.type); @@ -837,7 +663,7 @@ describe("streamResponseThunk", () => { const setContextPercentageAction = dispatchedActions.find( (a: any) => a.type === "session/setContextPercentage", ); - expect(setContextPercentageAction.payload).toBe(0.9); + expect(setContextPercentageAction?.payload).toBe(0.9); const streamUpdates = dispatchedActions.filter( (a: any) => a.type === "session/streamUpdate", @@ -854,7 +680,7 @@ describe("streamResponseThunk", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -869,6 +695,7 @@ describe("streamResponseThunk", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ]); @@ -895,66 +722,59 @@ describe("streamResponseThunk", () => { }); // Verify IDE messenger calls - expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Please search the codebase", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { + messages: [ + { + role: "system", + content: "You are a helpful assistant.", }, - }, - ); + { + role: "user", + content: [ + { + type: "text", + text: "Please search the codebase", + }, + ], + }, + { + role: "user", + content: [ + { + type: "text", + text: "Hello, please help me with this code", + }, + ], + }, + ], + options: { tools: [grepTool] }, + }); - expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( - "tools/call", - { - toolCall: { - id: "tool-call-1", - type: "function", - function: { - name: "search_codebase", - arguments: JSON.stringify({ query: "test function" }), - }, + expect(requestSpy).toHaveBeenCalledWith("tools/call", { + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: grepName, + arguments: JSON.stringify({ query: "test function" }), }, }, - ); + }); // Verify that multiple compilation calls were made (due to tool call continuation) - const compileCallsCount = - mockIdeMessengerWithTool.request.mock.calls.filter( - (call: any) => call[0] === "llm/compileChat", - ).length; - expect(compileCallsCount).toBeGreaterThanOrEqual(1); + expect(requestSpy).toHaveBeenCalledWith( + "llm/compileChat", + expect.any(Object), + ); expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify final state after tool call execution const finalState = mockStoreWithToolSettings.getState(); expect(finalState).toEqual({ + ...stateWithToolSettings, session: { + ...stateWithToolSettings.session, history: [ { contextItems: [], @@ -985,7 +805,7 @@ describe("streamResponseThunk", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -995,6 +815,7 @@ describe("streamResponseThunk", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ], @@ -1005,7 +826,7 @@ describe("streamResponseThunk", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -1020,6 +841,7 @@ describe("streamResponseThunk", () => { hidden: false, }, ], + tool: grepTool, }, ], }, @@ -1044,85 +866,19 @@ describe("streamResponseThunk", () => { { completion: "Search completed.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "continuing after tool", }, ], }, ], - hasReasoningEnabled: false, - isStreaming: false, + title: "Session summary", id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), contextPercentage: 0.9, isPruned: false, - isInEdit: false, - title: "New Session", - 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, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: { - search_codebase: "allowedWithoutPermission", - }, - 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: {}, - }, }); }); @@ -1130,84 +886,31 @@ describe("streamResponseThunk", () => { // Create an AbortController that we'll abort during streaming const testAbortController = new AbortController(); - // Use setupTest to get proper mock configuration - const { mockStore: baseStore, mockIdeMessenger: baseMessenger } = - setupTest(); - // Create store with our test abort controller, starting from setupTest config - const mockStoreWithAbort = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Hello" }, - contextItems: [], - }, - ], - hasReasoningEnabled: false, - isStreaming: true, - id: "session-123", - mode: "chat", - streamAborter: testAbortController, // Use our test controller - contextPercentage: 0, - isPruned: false, - isInEdit: false, - title: "", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + const abortState = getRootStateWithClaude(); + abortState.session.streamAborter = testAbortController; + abortState.session.history = [ + { + message: { id: "1", role: "user", content: "Hello" }, + contextItems: [], }, - 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, - }); - + ]; + abortState.session.id = "session-123"; + const mockStoreWithAbort = createMockStore(abortState); const mockIdeMessengerAbort = mockStoreWithAbort.mockIdeMessenger; - - // Setup successful compilation - mockIdeMessengerAbort.request.mockResolvedValue({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Hello" }], - didPrune: false, - contextPercentage: 0.8, - }, - }); + mockIdeMessengerAbort.responses["llm/compileChat"] = { + compiledChatMessages: [{ role: "user", content: "Hello" }], + didPrune: false, + contextPercentage: 0.8, + }; + const requestSpy = vi.spyOn(mockIdeMessengerAbort, "request"); + const postSpy = vi.spyOn(mockIdeMessengerAbort, "post"); // Setup streaming generator that simulates abort by user interaction - async function* mockStreamGeneratorWithAbort() { + async function* mockStreamGeneratorWithAbort(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "First chunk" }]; // Add a delay to allow the first chunk to be processed @@ -1226,12 +929,14 @@ describe("streamResponseThunk", () => { prompt: "Hello", completion: "Complete response", modelProvider: "anthropic", + modelTitle: "claude", }; } - mockIdeMessengerAbort.llmStreamChat.mockReturnValue( - mockStreamGeneratorWithAbort(), - ); + const mockStreamChat = vi + .fn() + .mockReturnValue(mockStreamGeneratorWithAbort()); + mockIdeMessengerAbort.llmStreamChat = mockStreamChat; // Execute thunk - should be aborted const result = await mockStoreWithAbort.dispatch( @@ -1245,7 +950,7 @@ describe("streamResponseThunk", () => { expect(result.type).toBe("chat/streamResponse/fulfilled"); // Verify exact action sequence - should start but then be aborted - const dispatchedActions = (mockStoreWithAbort as any).getActions(); + const dispatchedActions = mockStoreWithAbort.getActions(); expect(dispatchedActions).toEqual([ { type: "chat/streamResponse/pending", @@ -1397,7 +1102,7 @@ describe("streamResponseThunk", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -1409,7 +1114,7 @@ describe("streamResponseThunk", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -1427,16 +1132,7 @@ describe("streamResponseThunk", () => { }, { type: "session/setAllSessionMetadata", - payload: { - compiledChatMessages: [ - { - content: "Hello", - role: "user", - }, - ], - contextPercentage: 0.8, - didPrune: false, - }, + payload: [], }, { type: "session/refreshMetadata/fulfilled", @@ -1445,16 +1141,7 @@ describe("streamResponseThunk", () => { requestId: expect.any(String), requestStatus: "fulfilled", }, - payload: { - compiledChatMessages: [ - { - content: "Hello", - role: "user", - }, - ], - contextPercentage: 0.8, - didPrune: false, - }, + payload: [], }, { type: "session/update/fulfilled", @@ -1462,7 +1149,7 @@ describe("streamResponseThunk", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -1506,44 +1193,37 @@ describe("streamResponseThunk", () => { ]); // Verify IDE messenger calls - expect(mockIdeMessengerAbort.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { + messages: [ + { + role: "system", + content: "You are a helpful assistant.", }, - }, - ); + { + role: "user", + content: [ + { + type: "text", + text: "Hello", + }, + ], + }, + { + role: "user", + content: [ + { + type: "text", + text: "Hello, please help me with this code", + }, + ], + }, + ], + options: {}, + }); expect(mockIdeMessengerAbort.llmStreamChat).toHaveBeenCalledWith( { - completionOptions: { - reasoning: false, - }, + completionOptions: {}, legacySlashCommandData: undefined, messageOptions: { precompiled: true }, messages: [ @@ -1558,21 +1238,17 @@ describe("streamResponseThunk", () => { ); // Dev data logging should not occur since streaming was stopped early - expect(mockIdeMessengerAbort.post).not.toHaveBeenCalledWith( - "devdata/log", - expect.anything(), - ); + expect(postSpy).not.toHaveBeenCalledWith("devdata/log", expect.anything()); // Verify session save was called despite abort - expect(mockIdeMessengerAbort.request).toHaveBeenCalledWith( - "history/save", - expect.anything(), - ); + expect(requestSpy).toHaveBeenCalledWith("history/save", expect.anything()); // Verify final state - streaming should be stopped, partial content preserved const finalState = mockStoreWithAbort.getState(); expect(finalState).toEqual({ + ...abortState, session: { + ...abortState.session, history: [ { contextItems: [], @@ -1599,86 +1275,12 @@ describe("streamResponseThunk", () => { // No promptLogs because streaming was stopped before completion }, ], - hasReasoningEnabled: false, - isStreaming: false, // False because setInactive was called id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), // New controller after abort contextPercentage: 0.8, - isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: { - compiledChatMessages: [ - { - content: "Hello", - role: "user", - }, - ], - contextPercentage: 0.8, - didPrune: false, - }, - 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, - }, - }, - 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: {}, + isPruned: false, + title: "Session summary", }, }); }); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index a283c5238..b6536731a 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -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, diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 357ef944e..173d3a1e6 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -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 }))); } }), ); diff --git a/gui/src/redux/thunks/streamResponse_errorHandling.test.ts b/gui/src/redux/thunks/streamResponse_errorHandling.test.ts index c8fbb3262..563145381 100644 --- a/gui/src/redux/thunks/streamResponse_errorHandling.test.ts +++ b/gui/src/redux/thunks/streamResponse_errorHandling.test.ts @@ -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: {}, - }, }); }); }); diff --git a/gui/src/redux/thunks/streamResponse_toolCalls.test.ts b/gui/src/redux/thunks/streamResponse_toolCalls.test.ts index d3c1fda47..e8a5393d8 100644 --- a/gui/src/redux/thunks/streamResponse_toolCalls.test.ts +++ b/gui/src/redux/thunks/streamResponse_toolCalls.test.ts @@ -1,14 +1,9 @@ import { JSONContent } from "@tiptap/core"; -import { InputModifiers } from "core"; +import { AssistantChatMessage, InputModifiers, PromptLog } from "core"; import { describe, expect, it, vi } from "vitest"; import { createMockStore } from "../../util/test/mockStore"; import { streamResponseThunk } from "./streamResponse"; -// Mock external dependencies only - let selectors run naturally -// Removed: modelSupportsNativeTools - let it run naturally - -// Removed: addSystemMessageToolsToSystemMessage - let it run naturally - // Mock system message construction to keep test readable vi.mock("../util/getBaseSystemMessage", () => ({ getBaseSystemMessage: vi.fn(), @@ -16,9 +11,6 @@ vi.mock("../util/getBaseSystemMessage", () => ({ import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; -// Removed: shouldAutoEnableSystemMessageTools - let it run naturally - -// Additional mocks for streamResponseThunk vi.mock("posthog-js", () => ({ default: { capture: vi.fn(), @@ -37,8 +29,24 @@ vi.mock( ); import { ModelDescription } from "core"; +import { serializeTool } from "core/tools"; +import { + editFileTool, + grepSearchTool, + runTerminalCommandTool, +} from "core/tools/definitions"; import posthog from "posthog-js"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; +import { RootState } from "../store"; +import { getRootStateWithClaude } from "./streamResponse.test"; + +const grepTool = serializeTool(grepSearchTool); +const grepName = grepTool.function.name; +const editTool = serializeTool(editFileTool); +const editName = editTool.function.name; +const terminalTool = serializeTool(runTerminalCommandTool); +const terminalName = terminalTool.function.name; const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage); @@ -70,11 +78,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: [], @@ -83,196 +88,58 @@ function setupTest() { legacyCommandWithInput: undefined, }); - // 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 - tool calls", () => { it("should execute streaming flow with tool call execution", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Set up auto-approved tool setting for our test tool - const mockStoreWithToolSettings = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please search the codebase", - }, - 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, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { + id: "1", + role: "user", + content: "Please search the codebase", }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + contextItems: [], }, - 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: { - search_codebase: "allowedWithoutPermission", // Auto-approve this tool - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); - + ]; + initialState.ui.toolSettings = { + [grepName]: "allowedWithoutPermission", // Auto-approve this tool + }; + initialState.session.id = "session-123"; + initialState.config.config.tools = [grepTool]; + const mockStoreWithToolSettings = createMockStore(initialState); const mockIdeMessengerWithTool = mockStoreWithToolSettings.mockIdeMessenger; - // Setup successful compilation and tool responses - mockIdeMessengerWithTool.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Please search the codebase" }, - ], - didPrune: false, - contextPercentage: 0.9, - }, - }); - } else if (endpoint === "tools/evaluatePolicy") { - // Mock dynamic policy evaluation - return auto-approve for this test - return Promise.resolve({ - status: "success", - content: { policy: "allowedWithoutPermission" }, - }); - } else if (endpoint === "tools/call") { - // Mock server-side tool call response - return Promise.resolve({ - status: "success", - content: { - contextItems: [ - { - name: "Search Results", - description: "Found 3 matches", - content: "Result 1\nResult 2\nResult 3", - icon: "search", - hidden: false, - }, - ], - errorMessage: undefined, - }, - }); - } else if (endpoint === "history/save") { - // Mock session save - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - // Let other endpoints pass through or return success - return Promise.resolve({ status: "success", content: {} }); - }, - ); + const requestSpy = vi.spyOn(mockIdeMessengerWithTool, "request"); + + mockIdeMessengerWithTool.responses["llm/compileChat"] = { + compiledChatMessages: [ + { role: "user", content: "Please search the codebase" }, + ], + didPrune: false, + contextPercentage: 0.9, + }; + mockIdeMessengerWithTool.responses["tools/call"] = { + contextItems: [ + { + name: "Search Results", + description: "Found 3 matches", + content: "Result 1\nResult 2\nResult 3", + icon: "search", + hidden: false, + }, + ], + errorMessage: undefined, + }; // Setup streaming generator with tool call - async function* mockStreamGeneratorWithTool() { + async function* mockStreamGeneratorWithTool(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", content: "I'll search the codebase for you." }, ]; @@ -285,7 +152,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -296,41 +163,48 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Please search the codebase", completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } // Mock different streaming responses for multiple calls let streamCallCount = 0; - mockIdeMessengerWithTool.llmStreamChat.mockImplementation(() => { + const mockStreamChat = vi.fn().mockImplementation(() => { streamCallCount++; if (streamCallCount === 1) { // First call - main streaming with tool call return mockStreamGeneratorWithTool(); } else { // Subsequent calls from streamResponseAfterToolCall - return minimal response - async function* simpleGenerator() { + async function* simpleGenerator(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "Search completed." }]; return { prompt: "continuing after tool", completion: "Search completed.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } return simpleGenerator(); } }); + mockIdeMessengerWithTool.llmStreamChat = mockStreamChat; + // Track isStreaming state changes to detect UI flashing during auto-approved tool execution const streamingStateChanges: boolean[] = []; - let lastStreamingState = - mockStoreWithToolSettings.getState().session.isStreaming; + let lastStreamingState = (mockStoreWithToolSettings.getState() as RootState) + .session.isStreaming; // Record the initial state streamingStateChanges.push(lastStreamingState); // Subscribe to store changes to catch ALL state updates const unsubscribe = mockStoreWithToolSettings.subscribe(() => { - const currentState = - mockStoreWithToolSettings.getState().session.isStreaming; + const currentState = (mockStoreWithToolSettings.getState() as RootState) + .session.isStreaming; if (currentState !== lastStreamingState) { console.log( `Store subscription: isStreaming changed from ${lastStreamingState} to ${currentState}`, @@ -340,7 +214,7 @@ describe("streamResponseThunk - tool calls", () => { } }); - // Execute thunk + // // Execute thunk const result = await mockStoreWithToolSettings.dispatch( streamResponseThunk({ editorState: mockEditorState, @@ -349,7 +223,7 @@ describe("streamResponseThunk - tool calls", () => { ); // Debug: check what happened - const debugState = mockStoreWithToolSettings.getState(); + const debugState = mockStoreWithToolSettings.getState() as RootState; const finalStreamingState = debugState.session.isStreaming; const toolCallStates = debugState.session.history.flatMap( (item) => item.toolCallStates || [], @@ -377,10 +251,10 @@ describe("streamResponseThunk - tool calls", () => { // Verify no UI flashing during auto-approved tool execution // DESIRED: Should stay true throughout tool execution, only becoming false at the very end // We expect [true, false] - streaming starts true, stays true during tool execution, then false when all done - expect(streamingStateChanges).toEqual([true, false]); + expect(streamingStateChanges).toEqual([false, true, false]); // Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist) - const dispatchedActions = (mockStoreWithToolSettings as any).getActions(); + const dispatchedActions = mockStoreWithToolSettings.getActions(); // Verify exact action sequence const actionTypes = dispatchedActions.map((action: any) => action.type); @@ -467,7 +341,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -482,6 +356,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ]); @@ -508,58 +383,51 @@ describe("streamResponseThunk - tool calls", () => { }); // Verify IDE messenger calls - expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Please search the codebase", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { + messages: [ + { + role: "system", + content: "You are a helpful assistant.", }, + { + role: "user", + content: [ + { + type: "text", + text: "Please search the codebase", + }, + ], + }, + { + role: "user", + content: [ + { + type: "text", + text: "Hello, please help me with this code", + }, + ], + }, + ], + options: { + tools: [grepTool], }, - ); + }); - expect(mockIdeMessengerWithTool.request).toHaveBeenCalledWith( - "tools/call", - { - toolCall: { - id: "tool-call-1", - type: "function", - function: { - name: "search_codebase", - arguments: JSON.stringify({ query: "test function" }), - }, + expect(requestSpy).toHaveBeenCalledWith("tools/call", { + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: grepName, + arguments: JSON.stringify({ query: "test function" }), }, }, - ); + }); // Verify that multiple compilation calls were made (due to tool call continuation) - const compileCallsCount = - mockIdeMessengerWithTool.request.mock.calls.filter( - (call: any) => call[0] === "llm/compileChat", - ).length; + const compileCallsCount = requestSpy.mock.calls.filter( + (call: any) => call[0] === "llm/compileChat", + ).length; expect(compileCallsCount).toBeGreaterThanOrEqual(1); expect(result.type).toBe("chat/streamResponse/fulfilled"); @@ -570,7 +438,7 @@ describe("streamResponseThunk - tool calls", () => { "tool_call_decision", expect.objectContaining({ decision: "auto_accept", - toolName: "search_codebase", + toolName: grepName, toolCallId: "tool-call-1", }), ); @@ -579,14 +447,14 @@ describe("streamResponseThunk - tool calls", () => { "tool_call_outcome", expect.objectContaining({ succeeded: true, - toolName: "search_codebase", + toolName: grepName, errorReason: undefined, duration_ms: expect.any(Number), }), ); // Verify final state after tool call execution - const finalState = mockStoreWithToolSettings.getState(); + const finalState = mockStoreWithToolSettings.getState() as RootState; // Check that the tool was executed (status should be 'done' if auto-approved and executed) const toolCallState = finalState.session.history.find( @@ -598,7 +466,9 @@ describe("streamResponseThunk - tool calls", () => { expect(toolCallState?.output).toBeDefined(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, history: [ { contextItems: [], @@ -629,7 +499,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -639,6 +509,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ], @@ -649,7 +520,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-call-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -664,6 +535,7 @@ describe("streamResponseThunk - tool calls", () => { hidden: false, }, ], + tool: grepTool, }, ], }, @@ -688,834 +560,58 @@ describe("streamResponseThunk - tool calls", () => { { completion: "Search completed.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "continuing after tool", }, ], }, ], - hasReasoningEnabled: false, - isStreaming: false, id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), contextPercentage: 0.9, isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: [], - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, + title: "Session summary", 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, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: { - search_codebase: "allowedWithoutPermission", - }, - 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 handle tool call rejection error", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - - // Create store with tool settings that will reject the tool call - const mockStoreWithToolReject = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please edit this file", - }, - 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: { - edit_existing_file: "disabled", // Tool is disabled/rejected - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); - - const mockIdeMessengerReject = mockStoreWithToolReject.mockIdeMessenger; - - // Setup successful compilation - mockIdeMessengerReject.request.mockResolvedValue({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Please edit this file" }, - ], - didPrune: false, - contextPercentage: 0.7, - }, - }); - - // Setup streaming generator with tool call that will be rejected - async function* mockStreamGeneratorWithRejectedTool() { - yield [{ role: "assistant", content: "I'll edit the file for you." }]; - yield [ - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-reject-1", - type: "function", - function: { - name: "edit_existing_file", - arguments: JSON.stringify({ - filepath: "test.js", - changes: "const x = 1;", - }), - }, - }, - ], - }, - ]; - return { - prompt: "Please edit this file", - completion: "I'll edit the file for you.", - modelProvider: "anthropic", - }; - } - - mockIdeMessengerReject.llmStreamChat.mockReturnValue( - mockStreamGeneratorWithRejectedTool(), - ); - - // Execute thunk - const result = await mockStoreWithToolReject.dispatch( - streamResponseThunk({ - editorState: mockEditorState, - modifiers: mockModifiers, - }) as any, - ); - - // Verify thunk completed successfully (tool rejection is handled gracefully) - expect(result.type).toBe("chat/streamResponse/fulfilled"); - - // Verify exact action sequence includes tool generation but rejection handling - const dispatchedActions = (mockStoreWithToolReject as any).getActions(); - expect(dispatchedActions).toEqual([ - { - type: "chat/streamResponse/pending", - meta: { - arg: { - editorState: mockEditorState, - modifiers: mockModifiers, - }, - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "chat/streamWrapper/pending", - meta: { - arg: expect.any(Function), - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/submitEditorAndInitAtIndex", - payload: { - editorState: mockEditorState, - index: 1, - }, - }, - { - type: "session/resetNextCodeBlockToApplyIndex", - payload: undefined, - }, - { - type: "symbols/updateFromContextItems/pending", - meta: { - arg: [], - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/updateHistoryItemAtIndex", - payload: { - index: 1, - updates: { - contextItems: [], - message: { - content: "Hello, please help me with this code", - id: "mock-uuid-123", - role: "user", - }, - }, - }, - }, - { - type: "chat/streamNormalInput/pending", - meta: { - arg: { - legacySlashCommandData: undefined, - }, - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/setAppliedRulesAtIndex", - payload: { - appliedRules: [], - index: 1, - }, - }, - { - type: "session/setActive", - payload: undefined, - }, - { - type: "session/setInlineErrorMessage", - payload: undefined, - }, - { - type: "session/setIsPruned", - payload: false, - }, - { - type: "session/setContextPercentage", - payload: 0.7, - }, - { - type: "symbols/updateFromContextItems/fulfilled", - meta: { - arg: [], - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "session/streamUpdate", - payload: [ - { - role: "assistant", - content: "I'll edit the file for you.", - }, - ], - }, - { - type: "session/streamUpdate", - payload: [ - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-reject-1", - type: "function", - function: { - name: "edit_existing_file", - arguments: '{"filepath":"test.js","changes":"const x = 1;"}', - }, - }, - ], - }, - ], - }, - { - type: "session/addPromptCompletionPair", - payload: [ - { - completion: "I'll edit the file for you.", - modelProvider: "anthropic", - prompt: "Please edit this file", - }, - ], - }, - { - type: "session/errorToolCall", - payload: { - toolCallId: "tool-reject-1", - }, - }, - { - type: "session/updateToolCallOutput", - payload: { - toolCallId: "tool-reject-1", - contextItems: [ - { - icon: "problems", - name: "Security Policy Violation", - description: "Command Disabled", - content: `This command has been disabled by security policy:\n\nedit_existing_file\n\nThis command cannot be executed as it may pose a security risk.`, - hidden: false, - }, - ], - }, - }, - { - type: "session/setInactive", - payload: undefined, - }, - { - type: "chat/streamNormalInput/fulfilled", - meta: { - arg: { - legacySlashCommandData: undefined, - }, - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "session/saveCurrent/pending", - meta: { - arg: { - generateTitle: true, - openNewSession: false, - }, - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/update/pending", - meta: { - arg: expect.objectContaining({ - history: expect.any(Array), - sessionId: "session-123", - title: "New Session", - workspaceDirectory: "", - }), - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/updateSessionMetadata", - payload: { - sessionId: "session-123", - title: "New Session", - }, - }, - { - type: "session/refreshMetadata/pending", - meta: { - arg: {}, - requestId: expect.any(String), - requestStatus: "pending", - }, - payload: undefined, - }, - { - type: "session/setIsSessionMetadataLoading", - payload: false, - }, - { - type: "session/setAllSessionMetadata", - payload: { - compiledChatMessages: [ - { - content: "Please edit this file", - role: "user", - }, - ], - contextPercentage: 0.7, - didPrune: false, - }, - }, - { - type: "session/refreshMetadata/fulfilled", - meta: { - arg: {}, - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: { - compiledChatMessages: [ - { - content: "Please edit this file", - role: "user", - }, - ], - contextPercentage: 0.7, - didPrune: false, - }, - }, - { - type: "session/update/fulfilled", - meta: { - arg: expect.objectContaining({ - history: expect.any(Array), - sessionId: "session-123", - title: "New Session", - workspaceDirectory: "", - }), - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "session/saveCurrent/fulfilled", - meta: { - arg: { - generateTitle: true, - openNewSession: false, - }, - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "chat/streamWrapper/fulfilled", - meta: { - arg: expect.any(Function), - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - { - type: "chat/streamResponse/fulfilled", - meta: { - arg: { - editorState: mockEditorState, - modifiers: mockModifiers, - }, - requestId: expect.any(String), - requestStatus: "fulfilled", - }, - payload: undefined, - }, - ]); - - // Verify IDE messenger calls - compilation should succeed, streaming should happen - expect(mockIdeMessengerReject.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Please edit this file", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, - }, - }, - ); - - expect(mockIdeMessengerReject.llmStreamChat).toHaveBeenCalledWith( - { - completionOptions: { - reasoning: false, - }, - legacySlashCommandData: undefined, - messageOptions: { precompiled: true }, - messages: [ - { - role: "user", - content: "Please edit this file", - }, - ], - title: "Claude 3.5 Sonnet", - }, - expect.any(AbortSignal), - ); - - // Should NOT call tools/call since tool is disabled/rejected - expect(mockIdeMessengerReject.request).not.toHaveBeenCalledWith( - "tools/call", - expect.anything(), - ); - - // Verify session save was called - expect(mockIdeMessengerReject.request).toHaveBeenCalledWith( - "history/save", - expect.anything(), - ); - - // Verify final state contains the tool call but it's not executed - const finalState = mockStoreWithToolReject.getState(); - expect(finalState).toEqual({ - session: { - history: [ - { - contextItems: [], - message: { - id: "1", - role: "user", - content: "Please edit this file", - }, - }, - { - appliedRules: [], - contextItems: [], - editorState: mockEditorState, - message: { - content: "Hello, please help me with this code", - id: expect.any(String), - role: "user", - }, - }, - { - contextItems: [], - isGatheringContext: false, - message: { - content: "I'll edit the file for you.", - id: "mock-uuid-123", - role: "assistant", - toolCalls: [ - { - id: "tool-reject-1", - type: "function", - function: { - name: "edit_existing_file", - arguments: JSON.stringify({ - filepath: "test.js", - changes: "const x = 1;", - }), - }, - }, - ], - }, - promptLogs: [ - { - completion: "I'll edit the file for you.", - modelProvider: "anthropic", - prompt: "Please edit this file", - }, - ], - toolCallStates: [ - { - toolCallId: "tool-reject-1", - toolCall: { - id: "tool-reject-1", - type: "function", - function: { - name: "edit_existing_file", - arguments: JSON.stringify({ - filepath: "test.js", - changes: "const x = 1;", - }), - }, - }, - parsedArgs: { - filepath: "test.js", - changes: "const x = 1;", - }, - status: "errored", // Tool call is marked as errored due to being disabled - output: [ - { - icon: "problems", - name: "Security Policy Violation", - description: "Command Disabled", - content: `This command has been disabled by security policy:\n\nedit_existing_file\n\nThis command cannot be executed as it may pose a security risk.`, - hidden: false, - }, - ], - }, - ], - }, - ], - hasReasoningEnabled: false, - isStreaming: false, - id: "session-123", - mode: "chat", - streamAborter: expect.any(AbortController), - contextPercentage: 0.7, - isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: { - compiledChatMessages: [ - { - content: "Please edit this file", - role: "user", - }, - ], - contextPercentage: 0.7, - didPrune: false, - }, - 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, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, - ui: { - toolSettings: { - edit_existing_file: "disabled", - }, - 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 handle tool call requiring manual approval", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Create store with tool settings that require manual approval (ask first) - const mockStoreWithManualApproval = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please search the codebase", - }, - 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, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { + id: "1", + role: "user", + content: "Please search the codebase", }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + contextItems: [], }, - 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: { - search_codebase: "askFirst", // Requires manual approval - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); + ]; + initialState.session.id = "session-123"; + initialState.ui.toolSettings = { + [grepName]: "allowedWithPermission", // Requires manual approval + }; + initialState.config.config.tools = [grepTool]; + const mockStoreWithManualApproval = createMockStore(initialState); const mockIdeMessengerManual = mockStoreWithManualApproval.mockIdeMessenger; - + const requestSpy = vi.spyOn(mockIdeMessengerManual, "request"); // Setup successful compilation - mockIdeMessengerManual.request.mockResolvedValue({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Please search the codebase" }, - ], - didPrune: false, - contextPercentage: 0.9, - }, - }); + mockIdeMessengerManual.responses["llm/compileChat"] = { + compiledChatMessages: [ + { role: "user", content: "Please search the codebase" }, + ], + didPrune: false, + contextPercentage: 0.9, + }; // Setup streaming generator with tool call requiring approval - async function* mockStreamGeneratorWithApprovalTool() { + async function* mockStreamGeneratorWithApprovalTool(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", content: "I'll search the codebase for you." }, ]; @@ -1528,7 +624,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -1539,24 +635,26 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Please search the codebase", completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessengerManual.llmStreamChat.mockReturnValue( - mockStreamGeneratorWithApprovalTool(), - ); + const mockChat = vi + .fn() + .mockReturnValue(mockStreamGeneratorWithApprovalTool()); + mockIdeMessengerManual.llmStreamChat = mockChat; // Track isStreaming state changes to ensure it doesn't become false after tool generation const streamingStates: boolean[] = []; const originalDispatch = mockStoreWithManualApproval.dispatch; - mockStoreWithManualApproval.dispatch = ((action: any) => { + mockStoreWithManualApproval.dispatch = (action: any) => { const result = originalDispatch(action); // Capture isStreaming state after each action - const currentState = - mockStoreWithManualApproval.getState().session.isStreaming; + const currentState = (mockStoreWithManualApproval.getState() as RootState) + .session.isStreaming; streamingStates.push(currentState); return result; - }) as any; + }; // Execute thunk const result = await mockStoreWithManualApproval.dispatch( @@ -1571,12 +669,13 @@ describe("streamResponseThunk - tool calls", () => { // Since tool requires approval, isStreaming should become false after completion // but should stay true throughout the initial streaming phase - const finalStreamingState = - mockStoreWithManualApproval.getState().session.isStreaming; + const finalStreamingState = ( + mockStoreWithManualApproval.getState() as RootState + ).session.isStreaming; expect(finalStreamingState).toBe(false); // Final state should be false since we're waiting for approval // Verify exact action sequence includes tool generation but NO execution - const dispatchedActions = (mockStoreWithManualApproval as any).getActions(); + const dispatchedActions = mockStoreWithManualApproval.getActions(); expect(dispatchedActions).toEqual([ { type: "chat/streamResponse/pending", @@ -1696,7 +795,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -1710,6 +809,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ], @@ -1718,7 +818,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/setToolGenerated", payload: { toolCallId: "tool-approval-1", - tools: [], + tools: [grepTool], }, }, { @@ -1754,7 +854,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -1766,7 +866,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -1784,16 +884,7 @@ describe("streamResponseThunk - tool calls", () => { }, { type: "session/setAllSessionMetadata", - payload: { - compiledChatMessages: [ - { - content: "Please search the codebase", - role: "user", - }, - ], - contextPercentage: 0.9, - didPrune: false, - }, + payload: [], }, { type: "session/refreshMetadata/fulfilled", @@ -1802,16 +893,7 @@ describe("streamResponseThunk - tool calls", () => { requestId: expect.any(String), requestStatus: "fulfilled", }, - payload: { - compiledChatMessages: [ - { - content: "Please search the codebase", - role: "user", - }, - ], - contextPercentage: 0.9, - didPrune: false, - }, + payload: [], }, { type: "session/update/fulfilled", @@ -1819,7 +901,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -1863,44 +945,37 @@ describe("streamResponseThunk - tool calls", () => { ]); // Verify IDE messenger calls - compilation should happen, streaming should happen - expect(mockIdeMessengerManual.request).toHaveBeenCalledWith( - "llm/compileChat", - { - messages: [ - { - role: "system", - content: "You are a helpful assistant.", - }, - { - role: "user", - content: [ - { - type: "text", - text: "Please search the codebase", - }, - ], - }, - { - role: "user", - content: [ - { - type: "text", - text: "Hello, please help me with this code", - }, - ], - }, - ], - options: { - reasoning: false, + expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", { + messages: [ + { + role: "system", + content: "You are a helpful assistant.", }, - }, - ); + { + role: "user", + content: [ + { + type: "text", + text: "Please search the codebase", + }, + ], + }, + { + role: "user", + content: [ + { + type: "text", + text: "Hello, please help me with this code", + }, + ], + }, + ], + options: { tools: [grepTool] }, + }); expect(mockIdeMessengerManual.llmStreamChat).toHaveBeenCalledWith( { - completionOptions: { - reasoning: false, - }, + completionOptions: { tools: [grepTool] }, legacySlashCommandData: undefined, messageOptions: { precompiled: true }, messages: [ @@ -1915,21 +990,20 @@ describe("streamResponseThunk - tool calls", () => { ); // Should NOT call tools/call since tool requires approval - expect(mockIdeMessengerManual.request).not.toHaveBeenCalledWith( + expect(requestSpy).not.toHaveBeenCalledWith( "tools/call", expect.anything(), ); // Verify session save was called - expect(mockIdeMessengerManual.request).toHaveBeenCalledWith( - "history/save", - expect.anything(), - ); + expect(requestSpy).toHaveBeenCalledWith("history/save", expect.anything()); // Verify final state contains the tool call in "generated" state (waiting for approval) const finalState = mockStoreWithManualApproval.getState(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, history: [ { contextItems: [], @@ -1961,7 +1035,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -1971,6 +1045,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search the codebase for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase", }, ], @@ -1981,219 +1056,84 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, parsedArgs: { query: "test function" }, status: "generated", // Waiting for user approval + tool: grepTool, }, ], }, ], - hasReasoningEnabled: false, - isStreaming: false, - id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), contextPercentage: 0.9, isPruned: false, - isInEdit: false, - title: "New Session", - lastSessionId: undefined, - isSessionMetadataLoading: false, - allSessionMetadata: { - compiledChatMessages: [ - { - content: "Please search the codebase", - role: "user", - }, - ], - contextPercentage: 0.9, - didPrune: false, - }, - symbols: {}, - codeBlockApplyStates: { - states: [], - curIndex: 0, - }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, + title: "Session summary", 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, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, - }, ui: { + ...initialState.ui, toolSettings: { - search_codebase: "askFirst", + [grepName]: "allowedWithPermission", }, - 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 handle complete user approval and tool execution flow", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Create store with tool settings that require manual approval - const mockStoreWithApproval = createMockStore({ - session: { - history: [ - { - message: { - id: "1", - role: "user", - content: "Please search the codebase for test functions", - }, - 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, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { + id: "1", + role: "user", + content: "Please search the codebase for test functions", }, - newestToolbarPreviewForInput: {}, - compactionLoading: {}, - inlineErrorMessage: undefined, + contextItems: [], }, - 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: { - search_codebase: "askFirst", // Requires manual approval - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - }); + ]; + initialState.ui.toolSettings = { + [grepName]: "allowedWithPermission", // Requires manual approval + }; + initialState.session.id = "session-123"; + initialState.config.config.tools = [grepTool]; + const mockStoreWithApproval = createMockStore(initialState); const mockIdeMessengerApproval = mockStoreWithApproval.mockIdeMessenger; - // Setup successful compilation - mockIdeMessengerApproval.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { - role: "user", - content: "Please search the codebase for test functions", - }, - ], - didPrune: false, - contextPercentage: 0.85, - }, - }); - } else if (endpoint === "tools/call") { - // Mock server-side tool call response for search_codebase - return Promise.resolve({ - status: "success", - content: { - contextItems: [ - { - name: "Search Results", - description: "Found test functions", - content: - "function testUserLogin() {...}\\nfunction testDataValidation() {...}", - icon: "search", - hidden: false, - }, - ], - errorMessage: undefined, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - return Promise.resolve({ status: "success", content: {} }); - }, - ); + mockIdeMessengerApproval.responses["llm/compileChat"] = { + compiledChatMessages: [ + { + role: "user", + content: "Please search the codebase for test functions", + }, + ], + didPrune: false, + contextPercentage: 0.85, + }; + + mockIdeMessengerApproval.responses["tools/call"] = { + contextItems: [ + { + name: "Search Results", + description: "Found test functions", + content: + "function testUserLogin() {...}\\nfunction testDataValidation() {...}", + icon: "search", + hidden: false, + }, + ], + errorMessage: undefined, + }; // Setup streaming generator with tool call - async function* mockStreamGeneratorWithApprovalFlow() { + async function* mockStreamGeneratorWithApprovalFlow(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", @@ -2209,7 +1149,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-flow-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -2220,19 +1160,23 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Please search the codebase for test functions", completion: "I'll search for test functions in the codebase.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } // Mock subsequent streaming calls (after tool execution) let streamCallCount = 0; - mockIdeMessengerApproval.llmStreamChat.mockImplementation(() => { + const mockChat = vi.fn().mockImplementation(() => { streamCallCount++; if (streamCallCount === 1) { // First call - initial streaming with tool call return mockStreamGeneratorWithApprovalFlow(); } else { // Subsequent calls from streamResponseAfterToolCall - async function* followupGenerator() { + async function* followupGenerator(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", @@ -2245,28 +1189,32 @@ describe("streamResponseThunk - tool calls", () => { completion: "I found several test functions in your codebase. Here are the main ones I discovered...", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } return followupGenerator(); } }); + mockIdeMessengerApproval.llmStreamChat = mockChat; + const requestSpy = vi.spyOn(mockIdeMessengerApproval, "request"); // Track isStreaming state changes throughout the entire test const streamingStateChanges: boolean[] = []; - let lastStreamingState = - mockStoreWithApproval.getState().session.isStreaming; + let lastStreamingState = (mockStoreWithApproval.getState() as RootState) + .session.isStreaming; const originalDispatch = mockStoreWithApproval.dispatch; - mockStoreWithApproval.dispatch = ((action: any) => { + mockStoreWithApproval.dispatch = (action: any) => { const result = originalDispatch(action); - const currentStreamingState = - mockStoreWithApproval.getState().session.isStreaming; + const currentStreamingState = ( + mockStoreWithApproval.getState() as RootState + ).session.isStreaming; // Only record when the state actually changes if (currentStreamingState !== lastStreamingState) { streamingStateChanges.push(currentStreamingState); lastStreamingState = currentStreamingState; } return result; - }) as any; + }; // Execute initial thunk - this should generate the tool call but not execute it const initialResult = await mockStoreWithApproval.dispatch( @@ -2280,7 +1228,7 @@ describe("streamResponseThunk - tool calls", () => { expect(initialResult.type).toBe("chat/streamResponse/fulfilled"); // Verify exact initial action sequence by comparing action types - const initialActions = (mockStoreWithApproval as any).getActions(); + const initialActions = mockStoreWithApproval.getActions(); expect(initialActions).toEqual([ { @@ -2401,7 +1349,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-flow-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -2415,6 +1363,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search for test functions in the codebase.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase for test functions", }, ], @@ -2423,7 +1372,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/setToolGenerated", payload: { toolCallId: "tool-approval-flow-1", - tools: [], + tools: [grepTool], }, }, { @@ -2459,7 +1408,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -2471,7 +1420,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -2506,7 +1455,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -2550,7 +1499,7 @@ describe("streamResponseThunk - tool calls", () => { ]); // Clear the actions array to track only the approval flow - (mockStoreWithApproval as any).clearActions(); + mockStoreWithApproval.clearActions(); // Import the callToolById thunk to simulate user approval const { callToolById } = await import("./callToolById"); @@ -2564,7 +1513,7 @@ describe("streamResponseThunk - tool calls", () => { expect(approvalResult.type).toBe("chat/callTool/fulfilled"); // Verify exact approval flow actions - const approvalActions = (mockStoreWithApproval as any).getActions(); + const approvalActions = mockStoreWithApproval.getActions(); expect(approvalActions).toEqual([ { type: "chat/callTool/pending", @@ -2603,6 +1552,7 @@ describe("streamResponseThunk - tool calls", () => { type: "chat/streamAfterToolCall/pending", meta: { arg: { + depth: 1, toolCallId: "tool-approval-flow-1", }, requestId: expect.any(String), @@ -2637,7 +1587,7 @@ describe("streamResponseThunk - tool calls", () => { { type: "chat/streamNormalInput/pending", meta: { - arg: {}, + arg: { depth: 2 }, requestId: expect.any(String), requestStatus: "pending", }, @@ -2683,6 +1633,7 @@ describe("streamResponseThunk - tool calls", () => { completion: "I found several test functions in your codebase. Here are the main ones I discovered...", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "continuing after tool execution", }, ], @@ -2694,7 +1645,7 @@ describe("streamResponseThunk - tool calls", () => { { type: "chat/streamNormalInput/fulfilled", meta: { - arg: {}, + arg: { depth: 2 }, requestId: expect.any(String), requestStatus: "fulfilled", }, @@ -2718,7 +1669,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -2730,7 +1681,7 @@ describe("streamResponseThunk - tool calls", () => { type: "session/updateSessionMetadata", payload: { sessionId: "session-123", - title: "New Session", + title: "Session summary", }, }, { @@ -2765,7 +1716,7 @@ describe("streamResponseThunk - tool calls", () => { arg: expect.objectContaining({ history: expect.any(Array), sessionId: "session-123", - title: "New Session", + title: "Session summary", workspaceDirectory: "", }), requestId: expect.any(String), @@ -2798,6 +1749,7 @@ describe("streamResponseThunk - tool calls", () => { type: "chat/streamAfterToolCall/fulfilled", meta: { arg: { + depth: 1, toolCallId: "tool-approval-flow-1", }, requestId: expect.any(String), @@ -2822,7 +1774,7 @@ describe("streamResponseThunk - tool calls", () => { "tool_call_decision", expect.objectContaining({ decision: "accept", - toolName: "search_codebase", + toolName: grepName, toolCallId: "tool-approval-flow-1", }), ); @@ -2831,26 +1783,23 @@ describe("streamResponseThunk - tool calls", () => { "tool_call_outcome", expect.objectContaining({ succeeded: true, - toolName: "search_codebase", + toolName: grepName, errorReason: undefined, duration_ms: expect.any(Number), }), ); // Verify IDE messenger calls for tool execution - expect(mockIdeMessengerApproval.request).toHaveBeenCalledWith( - "tools/call", - { - toolCall: { - id: "tool-approval-flow-1", - type: "function", - function: { - name: "search_codebase", - arguments: JSON.stringify({ query: "test function" }), - }, + expect(requestSpy).toHaveBeenCalledWith("tools/call", { + toolCall: { + id: "tool-approval-flow-1", + type: "function", + function: { + name: grepName, + arguments: JSON.stringify({ query: "test function" }), }, }, - ); + }); // Verify second streaming call was made for continuation expect(streamCallCount).toBe(2); @@ -2858,7 +1807,10 @@ describe("streamResponseThunk - tool calls", () => { // Verify final state shows completed tool call and follow-up response const finalState = mockStoreWithApproval.getState(); expect(finalState).toEqual({ + ...initialState, session: { + ...initialState.session, + title: "Session summary", history: [ { contextItems: [], @@ -2890,7 +1842,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-flow-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -2900,6 +1852,7 @@ describe("streamResponseThunk - tool calls", () => { { completion: "I'll search for test functions in the codebase.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "Please search the codebase for test functions", }, ], @@ -2910,7 +1863,7 @@ describe("streamResponseThunk - tool calls", () => { id: "tool-approval-flow-1", type: "function", function: { - name: "search_codebase", + name: grepName, arguments: JSON.stringify({ query: "test function" }), }, }, @@ -2926,6 +1879,7 @@ describe("streamResponseThunk - tool calls", () => { hidden: false, }, ], + tool: grepTool, }, ], }, @@ -2953,201 +1907,78 @@ describe("streamResponseThunk - tool calls", () => { completion: "I found several test functions in your codebase. Here are the main ones I discovered...", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", prompt: "continuing after tool execution", }, ], }, ], - hasReasoningEnabled: false, isStreaming: false, // Inactive after complete flow id: "session-123", - mode: "chat", streamAborter: expect.any(AbortController), contextPercentage: 0.85, - isPruned: false, - isInEdit: false, - title: "New Session", - 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, - }, - }, - lastSelectedModelByRole: { - chat: mockClaudeModel.title, - }, - loading: false, - configError: undefined, + isPruned: false, }, ui: { + ...initialState.ui, toolSettings: { - search_codebase: "askFirst", + [grepName]: "allowedWithPermission", }, - 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: {}, }, }); }); describe("dynamic policy evaluation", () => { it("should call tools/evaluatePolicy with correct parameters", async () => { - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Run echo 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, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Run echo hello" }, + contextItems: [], }, - 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: { - run_terminal_command: "allowedWithoutPermission", - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - } as any); + ]; + initialState.ui.toolSettings = { + [terminalName]: "allowedWithoutPermission", + }; + initialState.config.config.tools = [grepTool]; + const mockStore = createMockStore(initialState); const mockIdeMessenger = mockStore.mockIdeMessenger; - - // Simple mock - just return a different policy for testing - mockIdeMessenger.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "tools/evaluatePolicy") { - // For this test, simulate that echo commands require permission - if (data.args.command?.toLowerCase().startsWith("echo")) { - return Promise.resolve({ - status: "success", - content: { policy: "allowedWithPermission" }, - }); - } - return Promise.resolve({ - status: "success", - content: { policy: data.basePolicy }, - }); - } else if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Run echo hello" }, - ], - didPrune: false, - contextPercentage: 0.5, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - return Promise.resolve({ status: "success", content: {} }); - }, - ); - + mockIdeMessenger.responseHandlers["tools/evaluatePolicy"] = async ( + data, + ) => { + if ( + "command" in data.args && + typeof data.args.command === "string" && + data.args.command?.toLowerCase().startsWith("echo") + ) { + return { policy: "allowedWithPermission" }; + } + return { policy: data.basePolicy }; + }; + mockIdeMessenger.responses["llm/compileChat"] = { + compiledChatMessages: [{ role: "user", content: "Run echo hello" }], + didPrune: false, + contextPercentage: 0.5, + }; // Setup streaming with echo command (should require permission despite auto-approve base) - async function* mockStreamWithEcho() { + async function* mockStreamWithEcho(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "I'll run the echo command." }]; + const toolId = `tool-echo-${Date.now()}`; yield [ { role: "assistant", content: "", toolCalls: [ { - id: "tool-echo-1", + id: toolId, type: "function", function: { - name: "run_terminal_command", + name: terminalName, arguments: JSON.stringify({ command: "echo hello" }), }, }, @@ -3158,10 +1989,13 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Run echo hello", completion: "I'll run the echo command.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithEcho()); + const mockChat = vi.fn().mockReturnValue(mockStreamWithEcho()); + mockIdeMessenger.llmStreamChat = mockChat; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); // Execute thunk await mockStore.dispatch( @@ -3169,129 +2003,82 @@ describe("streamResponseThunk - tool calls", () => { editorState: mockEditorState, modifiers: mockModifiers, }) as any, - ); - - // Just verify the call was made with correct params - expect(mockIdeMessenger.request).toHaveBeenCalledWith( - "tools/evaluatePolicy", - expect.objectContaining({ - toolName: "run_terminal_command", - basePolicy: "allowedWithoutPermission", - args: { command: "echo hello" }, - }), - ); + ), + // Just verify the call was made with correct params + expect(requestSpy).toHaveBeenCalledWith( + "tools/evaluatePolicy", + expect.objectContaining({ + toolName: terminalName, + basePolicy: "allowedWithoutPermission", + args: { command: "echo hello" }, + }), + ); // Verify tool wasn't auto-executed (policy changed to require permission) - expect(mockIdeMessenger.request).not.toHaveBeenCalledWith( + expect(requestSpy).not.toHaveBeenCalledWith( "tools/call", expect.any(Object), ); }); it("should respect disabled policy", async () => { - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Run ls" }, - 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, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Run ls" }, + contextItems: [], }, - 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: { - run_terminal_command: "disabled", // Tool is disabled - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - } as any); - + ]; + initialState.ui.toolSettings = { + [terminalName]: "allowedWithPermission", + }; + initialState.config.config.tools = [terminalTool]; + const mockStore = createMockStore(initialState); const mockIdeMessenger = mockStore.mockIdeMessenger; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); // Simple mock - just return disabled policy - mockIdeMessenger.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "tools/evaluatePolicy") { - // Backend should respect disabled state - return Promise.resolve({ - status: "success", - content: { policy: "disabled" }, - }); - } else if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Run ls" }], - didPrune: false, - contextPercentage: 0.5, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); - } - return Promise.resolve({ status: "success", content: {} }); - }, - ); - - // Setup streaming with regular command - async function* mockStreamWithLs() { + mockIdeMessenger.responseHandlers["llm/compileChat"] = async (data) => { + const history = (mockStore.getState() as RootState).session.history; + return { + compiledChatMessages: [ + ...history.map((i) => i.message), + { role: "user", content: "Run ls" }, + ], + didPrune: false, + contextPercentage: 0.5, + }; + }; + let numCalls = 0; + mockIdeMessenger.responseHandlers["tools/evaluatePolicy"] = async ( + data, + ) => { + numCalls++; + if (numCalls <= 1) { + return { + policy: "disabled", + }; + } + return { + policy: "allowedWithPermission", + }; + }; + async function* mockStreamWithLs(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "I'll list the files." }]; + const id = `tool-ls-${(() => Date.now())()}`; yield [ { role: "assistant", content: "", toolCalls: [ { - id: "tool-ls-1", + id, type: "function", function: { - name: "run_terminal_command", + name: terminalName, arguments: JSON.stringify({ command: "ls" }), }, }, @@ -3302,10 +2089,12 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Run ls", completion: "I'll list the files.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithLs()); + const mockChat = vi.fn().mockImplementation(() => mockStreamWithLs()); + mockIdeMessenger.llmStreamChat = mockChat; // Execute thunk await mockStore.dispatch( @@ -3313,116 +2102,93 @@ describe("streamResponseThunk - tool calls", () => { editorState: mockEditorState, modifiers: mockModifiers, }) as any, - ); + ), + // Verify tools/evaluatePolicy was called + expect(requestSpy).toHaveBeenCalledWith( + "tools/evaluatePolicy", + expect.objectContaining({ + toolName: terminalName, + basePolicy: "allowedWithPermission", + args: { command: "ls" }, + }), + ); - // Verify tools/evaluatePolicy was called - expect(mockIdeMessenger.request).toHaveBeenCalledWith( - "tools/evaluatePolicy", - expect.objectContaining({ - toolName: "run_terminal_command", - basePolicy: "disabled", - args: { command: "ls" }, - }), - ); - - // Tool should NOT be executed since it's disabled - expect(mockIdeMessenger.request).not.toHaveBeenCalledWith( + // Tool should NOT be executed since it's disabled by policy + expect(requestSpy).not.toHaveBeenCalledWith( "tools/call", expect.any(Object), ); + + const state = mockStore.getState() as RootState; + expect(state.ui.dialogMessage).toBeUndefined(); }); it("should handle evaluation errors gracefully", async () => { - const mockStore = createMockStore({ - session: { - history: [ - { - message: { id: "1", role: "user", content: "Do something" }, - 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, + const initialState = getRootStateWithClaude(); + initialState.session.history = [ + { + message: { id: "1", role: "user", content: "Do something" }, + contextItems: [], }, - 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: { - some_tool: "allowedWithoutPermission", - }, - ruleSettings: {}, - showDialog: false, - dialogMessage: undefined, - } as any, - } as any); + ]; + const someTool = { + ...grepTool, + function: { + ...grepTool.function, + name: "some_tool", + }, + }; + initialState.config.config.tools = [someTool]; + initialState.ui.toolSettings = { + some_tool: "allowedWithoutPermission", + }; + const mockStore = createMockStore(initialState); const mockIdeMessenger = mockStore.mockIdeMessenger; // Mock evaluation failure - mockIdeMessenger.request.mockImplementation((endpoint: string) => { + let numCalls = 0; + const requestSpy = vi.spyOn(mockIdeMessenger, "request"); + requestSpy.mockImplementation(async (endpoint, data) => { if (endpoint === "tools/evaluatePolicy") { - // Simulate evaluation error - return Promise.resolve({ - status: "error", - error: "Failed to evaluate policy", - }); - } else if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [{ role: "user", content: "Do something" }], - didPrune: false, - contextPercentage: 0.5, - }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); + numCalls++; + if (numCalls <= 1) { + // Simulate evaluation error + return { + done: true as const, + status: "error", + error: "Failed to evaluate policy", + }; + } else { + return { + done: true as const, + status: "success", + content: { + policy: "allowedWithPermission", + }, + }; + } } - return Promise.resolve({ status: "success", content: {} }); + mockIdeMessenger.responseHandlers["llm/compileChat"] = async (data) => { + const history = (mockStore.getState() as RootState).session.history; + return { + compiledChatMessages: [ + ...history.map((i) => i.message), + { role: "user", content: "Do something" }, + ], + didPrune: false, + contextPercentage: 0.5, + }; + }; + + return new MockIdeMessenger().request(endpoint, data); }); // Setup streaming with tool call - async function* mockStreamWithTool() { + async function* mockStreamWithTool(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [{ role: "assistant", content: "I'll help you." }]; yield [ { @@ -3444,10 +2210,12 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Do something", completion: "I'll help you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithTool()); + const mockChat = vi.fn().mockImplementation(() => mockStreamWithTool()); + mockIdeMessenger.llmStreamChat = mockChat; // Execute thunk - should handle error gracefully const result = await mockStore.dispatch( @@ -3465,92 +2233,59 @@ describe("streamResponseThunk - tool calls", () => { "tools/call", expect.any(Object), ); + + const state = mockStore.getState() as RootState; + expect(state.ui.dialogMessage).toBeUndefined(); }); it("should properly handle disabled commands and show error status", async () => { - const { mockStore, mockIdeMessenger } = setupTest(); - // Setup store with runTerminalCommand tool - const mockStoreWithTerminalTool = createMockStore({ - ...mockStore.getState(), - config: { - ...mockStore.getState().config, - config: { - ...mockStore.getState().config.config, - tools: [ - { - type: "function", - displayTitle: "Run Terminal Command", - function: { - name: "runTerminalCommand", - description: "Execute a terminal command", - parameters: { - type: "object", - properties: { - command: { - type: "string", - description: "The command to execute", - }, - }, - required: ["command"], - }, - }, - defaultToolPolicy: "allowedWithPermission", - readonly: false, - group: "code", - }, - ], - }, - }, - ui: { - ...mockStore.getState().ui, - toolSettings: { - runTerminalCommand: "allowedWithPermission", - }, - }, - }); + const initialState = getRootStateWithClaude(); + initialState.config.config.tools = [terminalTool]; + initialState.ui.toolSettings = { + runTerminalCommand: "allowedWithPermission", + }; + const mockStoreWithTerminalTool = createMockStore(initialState); const mockTerminalIdeMessenger = mockStoreWithTerminalTool.mockIdeMessenger; - // Setup compilation and policy evaluation responses - mockTerminalIdeMessenger.request.mockImplementation( - (endpoint: string, data: any) => { - if (endpoint === "llm/compileChat") { - return Promise.resolve({ - status: "success", - content: { - compiledChatMessages: [ - { role: "user", content: "Run eval command" }, - ], - didPrune: false, - contextPercentage: 0.9, - }, - }); - } else if (endpoint === "tools/evaluatePolicy") { - // Return disabled for eval command - const args = data.args || {}; - if (args.command && args.command.includes("eval")) { - return Promise.resolve({ - status: "success", - content: { policy: "disabled" }, - }); - } - return Promise.resolve({ - status: "success", - content: { policy: "allowedWithPermission" }, - }); - } else if (endpoint === "history/save") { - return Promise.resolve({ status: "success" }); - } else if (endpoint === "history/list") { - return Promise.resolve({ status: "success", content: [] }); + mockTerminalIdeMessenger.responseHandlers["llm/compileChat"] = async ( + data, + ) => { + const history = (mockStoreWithTerminalTool.getState() as RootState) + .session.history; + return { + compiledChatMessages: [ + ...history.map((i) => i.message), + { role: "user", content: "Run eval command" }, + ], + didPrune: false, + contextPercentage: 0.9, + }; + }; + + let numCalls = 0; + mockTerminalIdeMessenger.responseHandlers["tools/evaluatePolicy"] = + async (data) => { + const args = data.args || {}; + numCalls++; + if ( + numCalls <= 1 && + args.command && + typeof args.command === "string" && + args.command.includes("eval") + ) { + return { policy: "disabled" }; } - return Promise.resolve({ status: "success", content: {} }); - }, - ); + return { policy: "allowedWithPermission" }; + }; // Setup streaming with eval command tool call - async function* mockStreamWithEvalCommand() { + async function* mockStreamWithEvalCommand(): AsyncGenerator< + AssistantChatMessage[], + PromptLog + > { yield [ { role: "assistant", content: "I'll run the eval command for you." }, ]; @@ -3574,12 +2309,14 @@ describe("streamResponseThunk - tool calls", () => { prompt: "Run eval command", completion: "I'll run the eval command for you.", modelProvider: "anthropic", + modelTitle: "Claude 3.5 Sonnet", }; } - mockTerminalIdeMessenger.llmStreamChat.mockReturnValue( - mockStreamWithEvalCommand(), - ); + mockTerminalIdeMessenger.llmStreamChat = vi + .fn() + .mockImplementation(() => mockStreamWithEvalCommand()); + const requestSpy = vi.spyOn(mockTerminalIdeMessenger, "request"); // Execute thunk await mockStoreWithTerminalTool.dispatch( @@ -3590,7 +2327,7 @@ describe("streamResponseThunk - tool calls", () => { ); // Get final state - const finalState = mockStoreWithTerminalTool.getState(); + const finalState = mockStoreWithTerminalTool.getState() as RootState; const toolCallStates = finalState.session.history.flatMap( (item) => item.toolCallStates || [], ); @@ -3611,11 +2348,13 @@ describe("streamResponseThunk - tool calls", () => { expect(errorOutput?.content).toContain("disabled"); // Verify the command was NOT executed (no tool/call request) - const toolCallRequests = - mockTerminalIdeMessenger.request.mock.calls.filter( - (call) => call[0] === "tools/call", - ); + const toolCallRequests = requestSpy.mock.calls.filter( + (call) => call[0] === "tools/call", + ); expect(toolCallRequests).toHaveLength(0); + + const state = mockStoreWithTerminalTool.getState() as RootState; + expect(state.ui.dialogMessage).toBeUndefined(); }); }); }); diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index 0a29f3a8f..4454246cd 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -13,7 +13,6 @@ export const streamThunkWrapper = createAsyncThunk< () => Promise, ThunkApiType >("chat/streamWrapper", async (runStream, { dispatch, extra, getState }) => { - const initialState = getState(); try { await runStream(); const state = getState(); diff --git a/gui/src/redux/util/constructMessages.test.ts b/gui/src/redux/util/constructMessages.test.ts index 6fd213a75..f43ab6d80 100644 --- a/gui/src/redux/util/constructMessages.test.ts +++ b/gui/src/redux/util/constructMessages.test.ts @@ -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 + }, + ], }, ]; diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index 9b3593082..71d461ed7 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -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({ diff --git a/gui/src/redux/util/index.test.ts b/gui/src/redux/util/index.test.ts index 8ca3c6494..ffac94a08 100644 --- a/gui/src/redux/util/index.test.ts +++ b/gui/src/redux/util/index.test.ts @@ -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", () => { diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index 8a390e32e..ad75f9cb5 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -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 []; } diff --git a/gui/src/util/clientTools/multiEditImpl.test.ts b/gui/src/util/clientTools/multiEditImpl.test.ts index a4632573a..393564838 100644 --- a/gui/src/util/clientTools/multiEditImpl.test.ts +++ b/gui/src/util/clientTools/multiEditImpl.test.ts @@ -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() diff --git a/gui/src/util/clientTools/multiEditImpl.ts b/gui/src/util/clientTools/multiEditImpl.ts index 3886d0482..4c013c40d 100644 --- a/gui/src/util/clientTools/multiEditImpl.ts +++ b/gui/src/util/clientTools/multiEditImpl.ts @@ -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, }), diff --git a/gui/src/util/clientTools/singleFindAndReplaceImpl.ts b/gui/src/util/clientTools/singleFindAndReplaceImpl.ts index 8620e4bdc..0fcc09401 100644 --- a/gui/src/util/clientTools/singleFindAndReplaceImpl.ts +++ b/gui/src/util/clientTools/singleFindAndReplaceImpl.ts @@ -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, }), ); diff --git a/gui/src/util/test/mockStore.ts b/gui/src/util/test/mockStore.ts index ce4fb4ecd..38394a2ad 100644 --- a/gui/src/util/test/mockStore.ts +++ b/gui/src/util/test/mockStore.ts @@ -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) => { - 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 = { + 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, + mockMessenger?: MockIdeMessenger, +): ReturnType & { + mockIdeMessenger: MockIdeMessenger; + getActions: () => any[]; + clearActions: () => void; +} => { + const mockIdeMessenger = mockMessenger ?? new MockIdeMessenger(); const store = configureStore({ reducer: { @@ -30,94 +71,14 @@ export const createMockStore = (initialState?: Partial) => { 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) => { } 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), + }; }; diff --git a/gui/src/util/test/render.tsx b/gui/src/util/test/render.tsx index 7a2838e4b..f2d49d436 100644 --- a/gui/src/util/test/render.tsx +++ b/gui/src/util/test/render.tsx @@ -17,6 +17,7 @@ import { setupStore } from "../../redux/store"; type ExtendedRenderOptions = Omit & { store?: ReturnType; 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 diff --git a/packages/continue-sdk/package-lock.json b/packages/continue-sdk/package-lock.json index 0c6a6dff0..66bc98adf 100644 --- a/packages/continue-sdk/package-lock.json +++ b/packages/continue-sdk/package-lock.json @@ -10,7 +10,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" }, @@ -45,33 +45,188 @@ "zod-to-json-schema": "^3.24.5" } }, - "node_modules/@babel/runtime": { - "version": "7.27.0", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.0.tgz", - "integrity": "sha512-VtPOkrdPHZsKc/clNqyi9WUA8TINkZ4cGk63UUE3u4pmB2k+ZMQRDuIOagv8UVd6j7k0T3+RRIb7beKTebNbcw==", - "dependencies": { - "regenerator-runtime": "^0.14.0" - }, - "engines": { - "node": ">=6.9.0" + "node_modules/@borewit/text-codec": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.1.1.tgz", + "integrity": "sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" } }, "node_modules/@continuedev/config-yaml": { "resolved": "../config-yaml", "link": true }, + "node_modules/@inquirer/external-editor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-1.0.2.tgz", + "integrity": "sha512-yy9cOoBnx58TlsPrIxauKIFQTiyH+0MK4e97y4sV9ERbI+zDxw7i2hxHLCIEGIE/8PPvDxGhgzIOTSOWcs6/MQ==", + "license": "MIT", + "dependencies": { + "chardet": "^2.1.0", + "iconv-lite": "^0.7.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor/node_modules/iconv-lite": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz", + "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@isaacs/balanced-match": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz", + "integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==", + "license": "MIT", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@isaacs/brace-expansion": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz", + "integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==", + "license": "MIT", + "dependencies": { + "@isaacs/balanced-match": "^4.0.1" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/@lukeed/csprng": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz", "integrity": "sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==", + "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/@nestjs/axios": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.0.tgz", - "integrity": "sha512-1cB+Jyltu/uUPNQrpUimRHEQHrnQrpLzVj6dU3dgn6iDDDdahr10TgHFGTmw5VuJ9GzKZsCLDL78VSwJAs/9JQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.1.tgz", + "integrity": "sha512-68pFJgu+/AZbWkGu65Z3r55bTsCPlgyKaV4BSG8yUAD72q1PPuyVRgUwFv6BxdnibTUHlyxm06FmYWNC+bjN7A==", + "license": "MIT", "peerDependencies": { "@nestjs/common": "^10.0.0 || ^11.0.0", "axios": "^1.3.1", @@ -79,11 +234,12 @@ } }, "node_modules/@nestjs/common": { - "version": "11.0.20", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.0.20.tgz", - "integrity": "sha512-/GH8NDCczjn6+6RNEtSNAts/nq/wQE8L1qZ9TRjqjNqEsZNE1vpFuRIhmcO2isQZ0xY5rySnpaRdrOAul3gQ3A==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.6.tgz", + "integrity": "sha512-krKwLLcFmeuKDqngG2N/RuZHCs2ycsKcxWIDgcm7i1lf3sQ0iG03ci+DsP/r3FcT/eJDFsIHnKtNta2LIi7PzQ==", + "license": "MIT", "dependencies": { - "file-type": "20.4.1", + "file-type": "21.0.0", "iterare": "1.2.1", "load-esm": "1.0.2", "tslib": "2.8.1", @@ -94,8 +250,8 @@ "url": "https://opencollective.com/nest" }, "peerDependencies": { - "class-transformer": "*", - "class-validator": "*", + "class-transformer": ">=0.4.1", + "class-validator": ">=0.13.2", "reflect-metadata": "^0.1.12 || ^0.2.0", "rxjs": "^7.1.0" }, @@ -109,10 +265,11 @@ } }, "node_modules/@nestjs/core": { - "version": "11.0.20", - "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.0.20.tgz", - "integrity": "sha512-yUkEzBGiRNSEThVl6vMCXgoA9sDGWoRbJsTLdYdCC7lg7PE1iXBnna1FiBfQjT995pm0fjyM1e3WsXmyWeJXbw==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.6.tgz", + "integrity": "sha512-siWX7UDgErisW18VTeJA+x+/tpNZrJewjTBsRPF3JVxuWRuAB1kRoiJcxHgln8Lb5UY9NdvklITR84DUEXD0Cg==", "hasInstallScript": true, + "license": "MIT", "dependencies": { "@nuxt/opencollective": "0.4.1", "fast-safe-stringify": "2.1.1", @@ -152,6 +309,7 @@ "version": "0.4.1", "resolved": "https://registry.npmjs.org/@nuxt/opencollective/-/opencollective-0.4.1.tgz", "integrity": "sha512-GXD3wy50qYbxCJ652bDrDzgMr3NFEkIS374+IgFQKkCvk9yiYcLvX2XDYr7UyQxf4wK0e+yqDYRubZ0DtOxnmQ==", + "license": "MIT", "dependencies": { "consola": "^3.2.3" }, @@ -186,25 +344,25 @@ "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==" }, "node_modules/@openapitools/openapi-generator-cli": { - "version": "2.19.1", - "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.19.1.tgz", - "integrity": "sha512-APP3EPI/m7bg220qS+7UAFiyLJFbNCjlsEEjrP2sLmW4Za44U8e3Lb2zDy3sbvJvIUnpYWe+hu9RbrxrPP9djQ==", + "version": "2.24.0", + "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.24.0.tgz", + "integrity": "sha512-VS0sfW46oe/hQq7g1YZU1cJJebAQIwKhKqjsDY1/QFmcJMXYfe339yjMDTv02kMbsx621cSH46HIdvmW+i+7mg==", "hasInstallScript": true, + "license": "Apache-2.0", "dependencies": { - "@nestjs/axios": "4.0.0", - "@nestjs/common": "11.0.20", - "@nestjs/core": "11.0.20", + "@nestjs/axios": "4.0.1", + "@nestjs/common": "11.1.6", + "@nestjs/core": "11.1.6", "@nuxtjs/opencollective": "0.3.2", - "axios": "1.8.4", + "axios": "1.12.2", "chalk": "4.1.2", "commander": "8.3.0", - "compare-versions": "4.1.4", - "concurrently": "6.5.1", + "compare-versions": "6.1.1", + "concurrently": "9.2.1", "console.table": "0.10.0", - "fs-extra": "11.3.0", - "glob": "9.3.5", - "inquirer": "8.2.6", - "lodash": "4.17.21", + "fs-extra": "11.3.2", + "glob": "11.0.3", + "inquirer": "8.2.7", "proxy-agent": "6.5.0", "reflect-metadata": "0.2.2", "rxjs": "7.8.2", @@ -231,6 +389,7 @@ "version": "0.2.7", "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.2.7.tgz", "integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==", + "license": "MIT", "dependencies": { "debug": "^4.4.0", "fflate": "^0.8.2", @@ -247,7 +406,8 @@ "node_modules/@tokenizer/token": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", - "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==" + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "license": "MIT" }, "node_modules/@tootallnate/quickjs-emscripten": { "version": "0.23.0", @@ -278,6 +438,7 @@ "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "license": "MIT", "dependencies": { "type-fest": "^0.21.3" }, @@ -292,6 +453,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", "engines": { "node": ">=8" } @@ -329,23 +491,20 @@ "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" }, "node_modules/axios": { - "version": "1.8.4", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz", - "integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz", + "integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==", + "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", - "form-data": "^4.0.0", + "form-data": "^4.0.4", "proxy-from-env": "^1.1.0" } }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" - }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -363,7 +522,8 @@ "type": "consulting", "url": "https://feross.org/support" } - ] + ], + "license": "MIT" }, "node_modules/basic-ftp": { "version": "5.0.5", @@ -377,6 +537,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", @@ -419,15 +580,6 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, - "node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, "node_modules/buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -446,6 +598,7 @@ "url": "https://feross.org/support" } ], + "license": "MIT", "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" @@ -502,14 +655,16 @@ } }, "node_modules/chardet": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", - "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==" + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.1.0.tgz", + "integrity": "sha512-bNFETTG/pM5ryzQ9Ad0lJOTa6HWD/YsScAR3EnCPZRPlQh77JocYktSHOUHelyhm8IARL+o4c4F1bP5KVOjiRA==", + "license": "MIT" }, "node_modules/cli-cursor": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "license": "MIT", "dependencies": { "restore-cursor": "^3.1.0" }, @@ -521,6 +676,7 @@ "version": "2.9.2", "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "license": "MIT", "engines": { "node": ">=6" }, @@ -532,24 +688,30 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "license": "ISC", "engines": { "node": ">= 10" } }, "node_modules/cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", "dependencies": { "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", + "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" } }, "node_modules/cliui/node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -590,6 +752,7 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", "dependencies": { "delayed-stream": "~1.0.0" }, @@ -606,46 +769,40 @@ } }, "node_modules/compare-versions": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-4.1.4.tgz", - "integrity": "sha512-FemMreK9xNyL8gQevsdRMrvO4lFCkQP7qbuktn1q8ndcNk1+0mz7lgE7b/sNvbhVgY4w6tMN1FDp6aADjqw2rw==" + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz", + "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==", + "license": "MIT" }, "node_modules/concurrently": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-6.5.1.tgz", - "integrity": "sha512-FlSwNpGjWQfRwPLXvJ/OgysbBxPkWpiVjy1042b0U7on7S7qwwMIILRj7WTN1mTgqa582bG6NFuScOoh6Zgdag==", + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz", + "integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==", + "license": "MIT", "dependencies": { - "chalk": "^4.1.0", - "date-fns": "^2.16.1", - "lodash": "^4.17.21", - "rxjs": "^6.6.3", - "spawn-command": "^0.0.2-1", - "supports-color": "^8.1.0", - "tree-kill": "^1.2.2", - "yargs": "^16.2.0" + "chalk": "4.1.2", + "rxjs": "7.8.2", + "shell-quote": "1.8.3", + "supports-color": "8.1.1", + "tree-kill": "1.2.2", + "yargs": "17.7.2" }, "bin": { - "concurrently": "bin/concurrently.js" + "conc": "dist/bin/concurrently.js", + "concurrently": "dist/bin/concurrently.js" }, "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/concurrently/node_modules/rxjs": { - "version": "6.6.7", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", - "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", - "dependencies": { - "tslib": "^1.9.0" + "node": ">=18" }, - "engines": { - "npm": ">=2.0.0" + "funding": { + "url": "https://github.com/open-cli-tools/concurrently?sponsor=1" } }, "node_modules/concurrently/node_modules/supports-color": { "version": "8.1.1", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -656,15 +813,11 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, - "node_modules/concurrently/node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==" - }, "node_modules/consola": { "version": "3.4.2", "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "license": "MIT", "engines": { "node": "^14.18.0 || >=16.10.0" } @@ -712,6 +865,20 @@ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/data-uri-to-buffer": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", @@ -720,21 +887,6 @@ "node": ">= 14" } }, - "node_modules/date-fns": { - "version": "2.30.0", - "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz", - "integrity": "sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==", - "dependencies": { - "@babel/runtime": "^7.21.0" - }, - "engines": { - "node": ">=0.11" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/date-fns" - } - }, "node_modules/debug": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", @@ -779,6 +931,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", "engines": { "node": ">=0.4.0" } @@ -813,6 +966,12 @@ "node": ">= 0.4" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, "node_modules/easy-table": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/easy-table/-/easy-table-1.1.0.tgz", @@ -829,7 +988,8 @@ "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" }, "node_modules/encodeurl": { "version": "2.0.0", @@ -870,6 +1030,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", @@ -884,6 +1045,7 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", "engines": { "node": ">=6" } @@ -897,6 +1059,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "license": "MIT", "engines": { "node": ">=0.8.0" } @@ -1020,33 +1183,23 @@ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==" }, - "node_modules/external-editor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", - "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", - "dependencies": { - "chardet": "^0.7.0", - "iconv-lite": "^0.4.24", - "tmp": "^0.0.33" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/fast-safe-stringify": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", - "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==" + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" }, "node_modules/fflate": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", - "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==" + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "license": "MIT" }, "node_modules/figures": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "license": "MIT", "dependencies": { "escape-string-regexp": "^1.0.5" }, @@ -1058,17 +1211,18 @@ } }, "node_modules/file-type": { - "version": "20.4.1", - "resolved": "https://registry.npmjs.org/file-type/-/file-type-20.4.1.tgz", - "integrity": "sha512-hw9gNZXUfZ02Jo0uafWLaFVPter5/k2rfcrjFJJHX/77xtSDOfJuEFb6oKlFV86FLP1SuyHMW1PSk0U9M5tKkQ==", + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.0.0.tgz", + "integrity": "sha512-ek5xNX2YBYlXhiUXui3D/BXa3LdqPmoLJ7rqEx2bKJ7EAUEfmXgW0Das7Dc6Nr9MvqaOnIqiPV0mZk/r/UpNAg==", + "license": "MIT", "dependencies": { - "@tokenizer/inflate": "^0.2.6", - "strtok3": "^10.2.0", + "@tokenizer/inflate": "^0.2.7", + "strtok3": "^10.2.2", "token-types": "^6.0.0", "uint8array-extras": "^1.4.0" }, "engines": { - "node": ">=18" + "node": ">=20" }, "funding": { "url": "https://github.com/sindresorhus/file-type?sponsor=1" @@ -1105,15 +1259,16 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, "node_modules/follow-redirects": { - "version": "1.15.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", - "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", "funding": [ { "type": "individual", "url": "https://github.com/sponsors/RubenVerborgh" } ], + "license": "MIT", "engines": { "node": ">=4.0" }, @@ -1123,6 +1278,22 @@ } } }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/form-data": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", @@ -1156,9 +1327,10 @@ } }, "node_modules/fs-extra": { - "version": "11.3.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.0.tgz", - "integrity": "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew==", + "version": "11.3.2", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.2.tgz", + "integrity": "sha512-Xr9F6z6up6Ws+NjzMCZc6WXg2YFRlrLP9NQDO3VQrWrfiojdhS56TzueT88ze0uBdCTwEIhQ3ptnmKeWGFAe0A==", + "license": "MIT", "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -1168,11 +1340,6 @@ "node": ">=14.14" } }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" - }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -1185,6 +1352,7 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", "engines": { "node": "6.* || 8.* || >= 10.*" } @@ -1238,17 +1406,23 @@ } }, "node_modules/glob": { - "version": "9.3.5", - "resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz", - "integrity": "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q==", + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.3.tgz", + "integrity": "sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==", + "license": "ISC", "dependencies": { - "fs.realpath": "^1.0.0", - "minimatch": "^8.0.2", - "minipass": "^4.2.4", - "path-scurry": "^1.6.1" + "foreground-child": "^3.3.1", + "jackspeak": "^4.1.1", + "minimatch": "^10.0.3", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -1268,7 +1442,8 @@ "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" }, "node_modules/has-flag": { "version": "4.0.0", @@ -1293,6 +1468,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", "dependencies": { "has-symbols": "^1.0.3" }, @@ -1381,7 +1557,8 @@ "type": "consulting", "url": "https://feross.org/support" } - ] + ], + "license": "BSD-3-Clause" }, "node_modules/inherits": { "version": "2.0.4", @@ -1389,15 +1566,16 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "node_modules/inquirer": { - "version": "8.2.6", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.6.tgz", - "integrity": "sha512-M1WuAmb7pn9zdFRtQYk26ZBoY043Sse0wVDdk4Bppr+JOXyQYybdtvK+l9wUibhtjdjvtoiNy8tk+EgsYIUqKg==", + "version": "8.2.7", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.7.tgz", + "integrity": "sha512-UjOaSel/iddGZJ5xP/Eixh6dY1XghiBw4XK13rCCIJcJfyhhoul/7KhLLUGtebEj6GDYM6Vnx/mVsjx2L/mFIA==", + "license": "MIT", "dependencies": { + "@inquirer/external-editor": "^1.0.0", "ansi-escapes": "^4.2.1", "chalk": "^4.1.1", "cli-cursor": "^3.1.0", "cli-width": "^3.0.0", - "external-editor": "^3.0.3", "figures": "^3.0.0", "lodash": "^4.17.21", "mute-stream": "0.0.8", @@ -1437,6 +1615,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", "engines": { "node": ">=8" } @@ -1445,6 +1624,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "license": "MIT", "engines": { "node": ">=8" } @@ -1453,6 +1633,7 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "license": "MIT", "engines": { "node": ">=10" }, @@ -1460,23 +1641,46 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, "node_modules/iterare": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz", "integrity": "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==", + "license": "ISC", "engines": { "node": ">=6" } }, + "node_modules/jackspeak": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.1.1.tgz", + "integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/jsbn": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz", "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==" }, "node_modules/jsonfile": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", - "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", + "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "license": "MIT", "dependencies": { "universalify": "^2.0.0" }, @@ -1498,6 +1702,7 @@ "url": "https://buymeacoffee.com/borewit" } ], + "license": "MIT", "engines": { "node": ">=13.2.0" } @@ -1505,12 +1710,14 @@ "node_modules/lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" }, "node_modules/log-symbols": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "license": "MIT", "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" @@ -1523,9 +1730,13 @@ } }, "node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==" + "version": "11.2.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.2.tgz", + "integrity": "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==", + "license": "ISC", + "engines": { + "node": "20 || >=22" + } }, "node_modules/math-intrinsics": { "version": "1.1.0", @@ -1593,30 +1804,33 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", "engines": { "node": ">=6" } }, "node_modules/minimatch": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-8.0.4.tgz", - "integrity": "sha512-W0Wvr9HyFXZRGIDgCicunpQ299OKXs9RgZfaukz4qAW/pJhcpUfupc9c+OObPOFueNy8VSrZgEmDtk6Kh4WzDA==", + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.3.tgz", + "integrity": "sha512-IPZ167aShDZZUMdRk66cyQAW3qr0WzbHkPdMYa8bzZhlHhO3jALbKdxcaak7W9FfT2rZNpQuUu4Od7ILEpXSaw==", + "license": "ISC", "dependencies": { - "brace-expansion": "^2.0.1" + "@isaacs/brace-expansion": "^5.0.0" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/minipass": { - "version": "4.2.8", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.2.8.tgz", - "integrity": "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", "engines": { - "node": ">=8" + "node": ">=16 || 14 >=14.17" } }, "node_modules/ms": { @@ -1627,7 +1841,8 @@ "node_modules/mute-stream": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", - "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "license": "ISC" }, "node_modules/negotiator": { "version": "0.6.3", @@ -1690,6 +1905,7 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", "dependencies": { "mimic-fn": "^2.1.0" }, @@ -1704,6 +1920,7 @@ "version": "5.4.1", "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "license": "MIT", "dependencies": { "bl": "^4.1.0", "chalk": "^4.1.0", @@ -1722,14 +1939,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/pac-proxy-agent": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", @@ -1760,6 +1969,12 @@ "node": ">= 14" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -1768,49 +1983,40 @@ "node": ">= 0.8" } }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/path-scurry": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", - "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "license": "BlueOak-1.0.0", "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" }, "engines": { - "node": ">=16 || 14 >=14.18" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/path-scurry/node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, "node_modules/path-to-regexp": { "version": "8.2.0", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", + "license": "MIT", "engines": { "node": ">=16" } }, - "node_modules/peek-readable": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-7.0.0.tgz", - "integrity": "sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Borewit" - } - }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -1894,6 +2100,7 @@ "version": "3.6.2", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", @@ -1906,17 +2113,14 @@ "node_modules/reflect-metadata": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", - "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==" - }, - "node_modules/regenerator-runtime": { - "version": "0.14.1", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", - "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==" + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -1925,6 +2129,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "license": "MIT", "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" @@ -1933,10 +2138,17 @@ "node": ">=8" } }, + "node_modules/restore-cursor/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, "node_modules/run-async": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "license": "MIT", "engines": { "node": ">=0.12.0" } @@ -1945,6 +2157,7 @@ "version": "7.8.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", "dependencies": { "tslib": "^2.1.0" } @@ -2036,6 +2249,39 @@ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shell-quote": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", + "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -2105,9 +2351,16 @@ } }, "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } }, "node_modules/smart-buffer": { "version": "4.2.0", @@ -2153,11 +2406,6 @@ "node": ">=0.10.0" } }, - "node_modules/spawn-command": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/spawn-command/-/spawn-command-0.0.2.tgz", - "integrity": "sha512-zC8zGoGkmc8J9ndvml8Xksr1Amk9qBujgbF0JAIWO7kXr43w0h/0GJNM/Vustixu+YE8N/MTrQ7N31FvHUACxQ==" - }, "node_modules/sprintf-js": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", @@ -2175,6 +2423,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", "dependencies": { "safe-buffer": "~5.2.0" } @@ -2183,6 +2432,22 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -2196,6 +2461,20 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -2204,12 +2483,12 @@ } }, "node_modules/strtok3": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.2.2.tgz", - "integrity": "sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==", + "version": "10.3.4", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.4.tgz", + "integrity": "sha512-KIy5nylvC5le1OdaaoCJ07L+8iQzJHGH6pWDuzS+d07Cu7n1MZ2x26P8ZKIWfbK02+XIL8Mp4RkWeqdUCrDMfg==", + "license": "MIT", "dependencies": { - "@tokenizer/token": "^0.3.0", - "peek-readable": "^7.0.0" + "@tokenizer/token": "^0.3.0" }, "engines": { "node": ">=18" @@ -2255,18 +2534,8 @@ "node_modules/through": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==" - }, - "node_modules/tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", - "dependencies": { - "os-tmpdir": "~1.0.2" - }, - "engines": { - "node": ">=0.6.0" - } + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "license": "MIT" }, "node_modules/toidentifier": { "version": "1.0.1", @@ -2277,10 +2546,12 @@ } }, "node_modules/token-types": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.0.0.tgz", - "integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==", + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.1.tgz", + "integrity": "sha512-kh9LVIWH5CnL63Ipf0jhlBIy0UsrMj/NJDfpsy1SqOXlLKEVyXXYrnFxFT1yOOYVGBSApeVnjPw/sBz5BfEjAQ==", + "license": "MIT", "dependencies": { + "@borewit/text-codec": "^0.1.0", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" }, @@ -2301,6 +2572,7 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "license": "MIT", "bin": { "tree-kill": "cli.js" } @@ -2314,6 +2586,7 @@ "version": "0.21.3", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "license": "(MIT OR CC0-1.0)", "engines": { "node": ">=10" }, @@ -2351,6 +2624,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.2.tgz", "integrity": "sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==", + "license": "MIT", "dependencies": { "@lukeed/csprng": "^1.0.0" }, @@ -2359,9 +2633,10 @@ } }, "node_modules/uint8array-extras": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.4.0.tgz", - "integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", + "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", + "license": "MIT", "engines": { "node": ">=18" }, @@ -2373,6 +2648,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "license": "MIT", "engines": { "node": ">= 10.0.0" } @@ -2388,7 +2664,8 @@ "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" }, "node_modules/utils-merge": { "version": "1.0.1", @@ -2428,10 +2705,26 @@ "webidl-conversions": "^3.0.0" } }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/wrap-ansi": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -2441,37 +2734,58 @@ "node": ">=8" } }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", "engines": { "node": ">=10" } }, "node_modules/yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", "dependencies": { - "cliui": "^7.0.2", + "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", - "string-width": "^4.2.0", + "string-width": "^4.2.3", "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" + "yargs-parser": "^21.1.1" }, "engines": { - "node": ">=10" + "node": ">=12" } }, "node_modules/yargs-parser": { - "version": "20.2.9", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", - "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", "engines": { - "node": ">=10" + "node": ">=12" } } } diff --git a/packages/continue-sdk/package.json b/packages/continue-sdk/package.json index ae682237e..cd07ad95a 100644 --- a/packages/continue-sdk/package.json +++ b/packages/continue-sdk/package.json @@ -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" },