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/core.ts b/core/core.ts index dd66dae44..c10969b04 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1104,7 +1104,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 }; } @@ -1114,17 +1113,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 8650c6ae2..a5a2b8fc2 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1080,7 +1080,6 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; - displayTitle: string; wouldLikeTo?: string; isCurrently?: string; @@ -1097,6 +1096,12 @@ export interface Tool { }; defaultToolPolicy?: ToolPolicy; toolCallIcon?: string; + preprocessArgs?: ( + args: Record, + extras: { + ide: IDE; + }, + ) => Promise>; evaluateToolCallPolicy?: ( basePolicy: ToolPolicy, parsedArgs: Record, @@ -1776,7 +1781,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 c92945888..296ef041c 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -318,6 +318,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 f02727a37..3d4542f1b 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -82,6 +82,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/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/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/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 f9d82e377..79e23da5a 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 @@ -144,6 +144,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