From ff2b56fff3c55e4166253947987b0966fcd5ae18 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 9 Sep 2025 13:43:06 -0700 Subject: [PATCH] fix tests --- .../gui/chat-tests/EditToolScenarios.test.tsx | 172 ++++--------- .../chat-tests/EditToolScenariosYolo.test.tsx | 229 +++++++++++++++++ .../gui/chat-tests/ParallelToolCalls.test.tsx | 242 ------------------ .../ParallelToolCallsActions.test.tsx | 123 +++++++++ .../ParallelToolCallsBasic.test.tsx | 105 ++++++++ .../ParallelToolCallsStreaming.test.tsx | 132 ++++++++++ 6 files changed, 635 insertions(+), 368 deletions(-) create mode 100644 gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx delete mode 100644 gui/src/pages/gui/chat-tests/ParallelToolCalls.test.tsx create mode 100644 gui/src/pages/gui/chat-tests/ParallelToolCallsActions.test.tsx create mode 100644 gui/src/pages/gui/chat-tests/ParallelToolCallsBasic.test.tsx create mode 100644 gui/src/pages/gui/chat-tests/ParallelToolCallsStreaming.test.tsx diff --git a/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx b/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx index be4ac3b35..656b8c261 100644 --- a/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx +++ b/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx @@ -4,6 +4,7 @@ import { addAndSelectMockLlm, triggerConfigUpdate, } from "../../../util/test/config"; +import { updateConfig } from "../../../redux/slices/configSlice"; import { renderWithProviders } from "../../../util/test/render"; import { Chat } from "../Chat"; @@ -11,6 +12,7 @@ import { waitFor } from "@testing-library/dom"; import { act } from "@testing-library/react"; import { ChatMessage } from "core"; import { setToolPolicy } from "../../../redux/slices/uiSlice"; +import { setInactive } from "../../../redux/slices/sessionSlice"; import { getElementByTestId, getElementByText, @@ -47,8 +49,14 @@ const EDIT_MESSAGES: ChatMessage[] = [ ]; const POST_EDIT_RESPONSE = "Edit applied successfully"; -beforeEach(() => { +beforeEach(async () => { vi.clearAllMocks(); + // Clear any persisted state to ensure test isolation + localStorage.clear(); + sessionStorage.clear(); + + // Add a small delay to ensure cleanup is complete + await new Promise(resolve => setTimeout(resolve, 50)); }); test( @@ -57,15 +65,51 @@ test( async () => { // Setup const { ideMessenger, store, user } = await renderWithProviders(); + + // Reset mocks to ensure clean state + ideMessenger.resetMocks(); + + // Reset streaming state to prevent test interference + store.dispatch(setInactive()); ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; ideMessenger.responses["tools/evaluatePolicy"] = { policy: "allowedWithPermission", }; + + // Mock context/getSymbolsForFiles to prevent errors during streaming + ideMessenger.responses["context/getSymbolsForFiles"] = {}; + const messengerPostSpy = vi.spyOn(ideMessenger, "post"); const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); - addAndSelectMockLlm(store, ideMessenger); + // Instead of using addAndSelectMockLlm (which relies on events that might be failing), + // directly dispatch the config update to set the selected model + const currentConfig = store.getState().config.config; + store.dispatch(updateConfig({ + ...currentConfig, + selectedModelByRole: { + ...currentConfig.selectedModelByRole, + chat: { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + }, + modelsByRole: { + ...currentConfig.modelsByRole, + chat: [ + ...(currentConfig.modelsByRole.chat || []), + { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + ] + } + })); // Send the input that will respond with an edit tool call await sendInputWithMockedResponse( @@ -167,127 +211,3 @@ test( }, ); -test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => { - // Setup - const { ideMessenger, store, user } = await renderWithProviders(); - - ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; - ideMessenger.responses["tools/evaluatePolicy"] = { - policy: "allowedWithoutPermission", - }; - const messengerPostSpy = vi.spyOn(ideMessenger, "post"); - const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); - - addAndSelectMockLlm(store, ideMessenger); - - // Enable automatic edit and yolo mode - store.dispatch( - setToolPolicy({ - toolName: BuiltInToolNames.EditExistingFile, - policy: "allowedWithoutPermission", - }), - ); - triggerConfigUpdate({ - store, - ideMessenger, - editConfig: (current) => { - current.ui = { - ...current.ui, - autoAcceptEditToolDiffs: true, // Enable auto-accept for edit tool diffs - }; - return current; - }, - }); - expect(store.getState().config.config.ui?.autoAcceptEditToolDiffs).toBe(true); - - // Send the input that will respond with an edit tool call - await sendInputWithMockedResponse( - ideMessenger, - "Edit this file", - EDIT_MESSAGES, - ); - - // Wait for streaming to complete and tool calls to be processed - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 1000)); - }); - - // Toggle the codeblock and make sure the changes show - const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock"); - - await user.click(toggleCodeblockChevron); - await getElementByText(EDIT_CHANGES); - - // Make sure there's no pending tool call - await verifyNotPresentByTestId( - generateToolCallButtonTestId("accept", EDIT_TOOL_CALL_ID), - ); - // Tool call, check that applyToFile was called for edit - await waitFor(() => { - expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { - streamId: expect.any(String), - filepath: EDIT_FILE_URI, - text: EDIT_CHANGES, - toolCallId: EDIT_TOOL_CALL_ID, - }); - }); - - // Extract stream ID and initiate mock streaming - const streamId = messengerRequestSpy.mock.calls.find( - (call) => call[0] === "applyToFile", - )?.[1]?.streamId; - expect(streamId).toBeDefined(); - - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "streaming", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Mid stream, should show applying in notch - await getElementByTestId("notch-applying-text"); - await getElementByTestId("notch-applying-cancel-button"); - - // Close the stream - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "done", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Set the chat response text before the auto-accept triggers - ideMessenger.setChatResponseText(POST_EDIT_RESPONSE); - - await waitFor(() => { - expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", { - streamId, - filepath: EDIT_FILE_URI, - }); - }); - - // Close the stream, ensure response is shown and diff buttons are not present - ideMessenger.mockMessageToWebview("updateApplyState", { - status: "closed", - streamId, - toolCallId: EDIT_TOOL_CALL_ID, - filepath: EDIT_FILE_URI, - }); - - // Allow time for the auto-streaming to complete - await new Promise((resolve) => setTimeout(resolve, 1000)); - - await verifyNotPresentByTestId("edit-accept-button"); - await verifyNotPresentByTestId("edit-reject-button"); - - // Try to manually trigger the streaming by checking if the response is set - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 500)); - }); - - // TODO: Fix this test - the POST_EDIT_RESPONSE is not being displayed - // await waitFor(() => getElementByText(POST_EDIT_RESPONSE), { - // timeout: 8000, - // }); -}); diff --git a/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx b/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx new file mode 100644 index 000000000..4ca1e72f2 --- /dev/null +++ b/gui/src/pages/gui/chat-tests/EditToolScenariosYolo.test.tsx @@ -0,0 +1,229 @@ +import { BuiltInToolNames } from "core/tools/builtIn"; +import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; +import { + triggerConfigUpdate, +} from "../../../util/test/config"; +import { updateConfig } from "../../../redux/slices/configSlice"; +import { renderWithProviders } from "../../../util/test/render"; +import { Chat } from "../Chat"; + +import { waitFor } from "@testing-library/dom"; +import { act } from "@testing-library/react"; +import { ChatMessage } from "core"; +import { setToolPolicy } from "../../../redux/slices/uiSlice"; +import { setInactive } from "../../../redux/slices/sessionSlice"; +import { + getElementByTestId, + getElementByText, + sendInputWithMockedResponse, + verifyNotPresentByTestId, +} from "../../../util/test/utils"; + +const EDIT_WORKSPACE_DIR = "file:///workspace"; +const EDIT_FILEPATH = "test.txt"; +const EDIT_FILE_URI = `${EDIT_WORKSPACE_DIR}/${EDIT_FILEPATH}`; +const EDIT_CHANGES = "New content"; +const EDIT_TOOL_CALL_ID = "known-id"; +const EDIT_MESSAGES: ChatMessage[] = [ + { + role: "assistant", + content: "I'll edit the file for you.", + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: EDIT_TOOL_CALL_ID, + function: { + name: BuiltInToolNames.EditExistingFile, + arguments: JSON.stringify({ + filepath: EDIT_FILEPATH, + changes: EDIT_CHANGES, + }), + }, + }, + ], + }, +]; + +const POST_EDIT_RESPONSE = "Edit applied successfully"; +beforeEach(async () => { + vi.clearAllMocks(); + // Clear any persisted state to ensure test isolation + localStorage.clear(); + sessionStorage.clear(); + + // Add a small delay to ensure cleanup is complete + await new Promise(resolve => setTimeout(resolve, 50)); +}); + +test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => { + // Additional cleanup before test starts + localStorage.clear(); + sessionStorage.clear(); + await new Promise(resolve => setTimeout(resolve, 100)); + + // Setup + const { ideMessenger, store, user } = await renderWithProviders(); + + // Reset mocks to ensure clean state + ideMessenger.resetMocks(); + + // Reset streaming state to prevent test interference + store.dispatch(setInactive()); + + // Additional delay to ensure state is fully reset + await new Promise(resolve => setTimeout(resolve, 100)); + + ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; + ideMessenger.responses["tools/evaluatePolicy"] = { + policy: "allowedWithoutPermission", + }; + + // Mock context/getSymbolsForFiles to prevent errors during streaming + ideMessenger.responses["context/getSymbolsForFiles"] = {}; + + const messengerPostSpy = vi.spyOn(ideMessenger, "post"); + const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); + + // Instead of using addAndSelectMockLlm (which relies on events that might be failing), + // directly dispatch the config update to set the selected model + const currentConfig = store.getState().config.config; + store.dispatch(updateConfig({ + ...currentConfig, + selectedModelByRole: { + ...currentConfig.selectedModelByRole, + chat: { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + }, + modelsByRole: { + ...currentConfig.modelsByRole, + chat: [ + ...(currentConfig.modelsByRole.chat || []), + { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + ] + } + })); + + // Enable automatic edit and yolo mode + store.dispatch( + setToolPolicy({ + toolName: BuiltInToolNames.EditExistingFile, + policy: "allowedWithoutPermission", + }), + ); + triggerConfigUpdate({ + store, + ideMessenger, + editConfig: (current) => { + current.ui = { + ...current.ui, + autoAcceptEditToolDiffs: true, // Enable auto-accept for edit tool diffs + }; + return current; + }, + }); + expect(store.getState().config.config.ui?.autoAcceptEditToolDiffs).toBe(true); + + // Send the input that will respond with an edit tool call + await sendInputWithMockedResponse( + ideMessenger, + "Edit this file", + EDIT_MESSAGES, + ); + + // Wait for streaming to complete and tool calls to be processed + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 1000)); + }); + + + // Toggle the codeblock and make sure the changes show + const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock"); + + await user.click(toggleCodeblockChevron); + await getElementByText(EDIT_CHANGES); + + // Make sure there's no pending tool call + await verifyNotPresentByTestId( + generateToolCallButtonTestId("accept", EDIT_TOOL_CALL_ID), + ); + // Tool call, check that applyToFile was called for edit + await waitFor(() => { + expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { + streamId: expect.any(String), + filepath: EDIT_FILE_URI, + text: EDIT_CHANGES, + toolCallId: EDIT_TOOL_CALL_ID, + }); + }); + + // Extract stream ID and initiate mock streaming + const streamId = messengerRequestSpy.mock.calls.find( + (call) => call[0] === "applyToFile", + )?.[1]?.streamId; + expect(streamId).toBeDefined(); + + ideMessenger.mockMessageToWebview("updateApplyState", { + status: "streaming", + streamId, + toolCallId: EDIT_TOOL_CALL_ID, + filepath: EDIT_FILE_URI, + }); + + // Mid stream, should show applying in notch + await getElementByTestId("notch-applying-text"); + await getElementByTestId("notch-applying-cancel-button"); + + // Close the stream + ideMessenger.mockMessageToWebview("updateApplyState", { + status: "done", + streamId, + toolCallId: EDIT_TOOL_CALL_ID, + filepath: EDIT_FILE_URI, + }); + + // Set the chat response text before the auto-accept triggers + ideMessenger.setChatResponseText(POST_EDIT_RESPONSE); + + await waitFor(() => { + expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", { + streamId, + filepath: EDIT_FILE_URI, + }); + }); + + // Close the stream, ensure response is shown and diff buttons are not present + ideMessenger.mockMessageToWebview("updateApplyState", { + status: "closed", + streamId, + toolCallId: EDIT_TOOL_CALL_ID, + filepath: EDIT_FILE_URI, + }); + + // Allow time for the auto-streaming to complete + await new Promise((resolve) => setTimeout(resolve, 1000)); + + await verifyNotPresentByTestId("edit-accept-button"); + await verifyNotPresentByTestId("edit-reject-button"); + + // Try to manually trigger the streaming by checking if the response is set + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 500)); + }); + + // TODO: Fix this test - the POST_EDIT_RESPONSE is not being displayed + // await waitFor(() => getElementByText(POST_EDIT_RESPONSE), { + // timeout: 8000, + // }); +}); \ No newline at end of file diff --git a/gui/src/pages/gui/chat-tests/ParallelToolCalls.test.tsx b/gui/src/pages/gui/chat-tests/ParallelToolCalls.test.tsx deleted file mode 100644 index efb982a12..000000000 --- a/gui/src/pages/gui/chat-tests/ParallelToolCalls.test.tsx +++ /dev/null @@ -1,242 +0,0 @@ -import { act } from "@testing-library/react"; -import { ChatMessage } from "core"; -import { addAndSelectMockLlm } from "../../../util/test/config"; -import { renderWithProviders } from "../../../util/test/render"; -import { sendInputWithMockedResponse } from "../../../util/test/utils"; -import { Chat } from "../Chat"; - -describe("Parallel Tool Calls", () => { - const PARALLEL_TOOL_CALL_RESPONSE: ChatMessage[] = [ - { - role: "assistant", - content: "I'll call both tools in parallel.", - }, - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-call-1", - type: "function", - function: { - name: "read_file", - arguments: JSON.stringify({ filepath: "test.js" }), - }, - }, - { - id: "tool-call-2", - type: "function", - function: { - name: "write_file", - arguments: JSON.stringify({ - filepath: "output.js", - content: "test", - }), - }, - }, - ], - }, - ]; - - test("should handle assistant message with multiple tool calls", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - // Mock the tools/evaluatePolicy response to allow tools without permission - ideMessenger.responses["tools/evaluatePolicy"] = { - policy: "allowedWithPermission", - }; - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - await sendInputWithMockedResponse( - ideMessenger, - "Use both tools", - PARALLEL_TOOL_CALL_RESPONSE, - ); - - // Wait for streaming to complete and tool calls to be set to generated - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 500)); - }); - - const state = store.getState(); - const history = state.session.history; - - // Should have user message and assistant message - expect(history).toHaveLength(2); - - // Find assistant message with tool calls - const assistantMessage = history.find( - (item) => - item.message.role === "assistant" && item.toolCallStates?.length, - ); - - expect(assistantMessage).toBeDefined(); - expect(assistantMessage!.toolCallStates).toHaveLength(2); - expect(assistantMessage!.toolCallStates![0].toolCallId).toBe("tool-call-1"); - expect(assistantMessage!.toolCallStates![1].toolCallId).toBe("tool-call-2"); - }); - - test("should handle individual tool call actions without breaking other calls", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - // Mock the tools/evaluatePolicy response to allow tools without permission - ideMessenger.responses["tools/evaluatePolicy"] = { - policy: "allowedWithPermission", - }; - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - await sendInputWithMockedResponse( - ideMessenger, - "Use multiple tools", - PARALLEL_TOOL_CALL_RESPONSE, - ); - - // Wait for streaming to complete and tool calls to be set to generated - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 500)); - }); - - const { findAllCurToolCallsByStatus } = await import("../../../redux/util"); - const { cancelToolCall } = await import( - "../../../redux/slices/sessionSlice" - ); - - // Verify we have multiple pending tool calls - let state = store.getState(); - let pendingToolCalls = findAllCurToolCallsByStatus( - state.session.history, - "generated", - ); - expect(pendingToolCalls).toHaveLength(2); - - // Cancel the first tool call - await act(async () => { - store.dispatch(cancelToolCall({ toolCallId: "tool-call-1" })); - }); - - // Check state after canceling first tool call - state = store.getState(); - pendingToolCalls = findAllCurToolCallsByStatus( - state.session.history, - "generated", - ); - - // The second tool call should still be pending - expect(pendingToolCalls).toHaveLength(1); - expect(pendingToolCalls[0].toolCallId).toBe("tool-call-2"); - - // The first tool call should now be canceled - const canceledToolCalls = findAllCurToolCallsByStatus( - state.session.history, - "canceled", - ); - expect(canceledToolCalls).toHaveLength(1); - expect(canceledToolCalls[0].toolCallId).toBe("tool-call-1"); - }); - - test("should handle streaming deltas for multiple tool calls", async () => { - const { ideMessenger, store } = await renderWithProviders(); - - // Mock the tools/evaluatePolicy response to allow tools without permission - ideMessenger.responses["tools/evaluatePolicy"] = { - policy: "allowedWithPermission", - }; - - await act(async () => { - addAndSelectMockLlm(store, ideMessenger); - }); - - // Simulate streaming behavior with deltas - const STREAMING_RESPONSE: ChatMessage[] = [ - { - role: "assistant", - content: "I'll call both tools in parallel.", - }, - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-call-1", - type: "function", - function: { - name: "read_file", - arguments: "", - }, - }, - ], - }, - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-call-1", - type: "function", - function: { - name: "read_file", - arguments: '{"filepath": "test.js"}', - }, - }, - ], - }, - { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-call-2", - type: "function", - function: { - name: "write_file", - arguments: '{"filepath": "output.js", "content": "test"}', - }, - }, - ], - }, - ]; - - await sendInputWithMockedResponse( - ideMessenger, - "Use both tools with streaming", - STREAMING_RESPONSE, - ); - - // Wait for streaming to complete and tool calls to be set to generated - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 500)); - }); - - const state = store.getState(); - const history = state.session.history; - - // Should have only one assistant message after streaming - const assistantMessages = history.filter( - (item) => item.message.role === "assistant", - ); - expect(assistantMessages).toHaveLength(1); - - const assistantMessage = assistantMessages[0]; - - // Should preserve original content - expect(assistantMessage.message.content).toContain( - "I'll call both tools in parallel", - ); - - // Should have both tool calls after streaming completes - expect(assistantMessage.toolCallStates).toHaveLength(2); - - // Verify tool calls are properly constructed - const toolCallIds = assistantMessage.toolCallStates!.map( - (tc) => tc.toolCallId, - ); - expect(toolCallIds).toContain("tool-call-1"); - expect(toolCallIds).toContain("tool-call-2"); - }); -}); diff --git a/gui/src/pages/gui/chat-tests/ParallelToolCallsActions.test.tsx b/gui/src/pages/gui/chat-tests/ParallelToolCallsActions.test.tsx new file mode 100644 index 000000000..f71c1b45c --- /dev/null +++ b/gui/src/pages/gui/chat-tests/ParallelToolCallsActions.test.tsx @@ -0,0 +1,123 @@ +import { act } from "@testing-library/react"; +import { ChatMessage } from "core"; +import { renderWithProviders } from "../../../util/test/render"; +import { sendInputWithMockedResponse } from "../../../util/test/utils"; +import { Chat } from "../Chat"; +import { findAllCurToolCallsByStatus } from "../../../redux/util"; +import { cancelToolCall } from "../../../redux/slices/sessionSlice"; +import { updateConfig } from "../../../redux/slices/configSlice"; + +describe("Parallel Tool Calls - Actions", () => { + const PARALLEL_TOOL_CALL_RESPONSE: ChatMessage[] = [ + { + role: "assistant", + content: "I'll call both tools in parallel.", + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ filepath: "test.js" }), + }, + }, + { + id: "tool-call-2", + type: "function", + function: { + name: "write_file", + arguments: JSON.stringify({ + filepath: "output.js", + content: "test", + }), + }, + }, + ], + }, + ]; + + test("should handle individual tool call actions without breaking other calls", async () => { + const { ideMessenger, store } = await renderWithProviders(); + + // Mock required responses + ideMessenger.responses["tools/evaluatePolicy"] = { + policy: "allowedWithPermission", + }; + ideMessenger.responses["context/getSymbolsForFiles"] = {}; + + // Setup mock model with direct Redux dispatch + const currentConfig = store.getState().config.config; + store.dispatch(updateConfig({ + ...currentConfig, + selectedModelByRole: { + ...currentConfig.selectedModelByRole, + chat: { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + }, + modelsByRole: { + ...currentConfig.modelsByRole, + chat: [ + ...(currentConfig.modelsByRole.chat || []), + { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + ] + } + })); + + await sendInputWithMockedResponse( + ideMessenger, + "Use multiple tools", + PARALLEL_TOOL_CALL_RESPONSE, + ); + + // Wait for streaming to complete + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 500)); + }); + + // Verify we have multiple pending tool calls + let state = store.getState(); + let pendingToolCalls = findAllCurToolCallsByStatus( + state.session.history, + "generated", + ); + + expect(pendingToolCalls).toHaveLength(2); + + // Cancel the first tool call + await act(async () => { + store.dispatch(cancelToolCall({ toolCallId: "tool-call-1" })); + }); + + // Check state after canceling first tool call + state = store.getState(); + pendingToolCalls = findAllCurToolCallsByStatus( + state.session.history, + "generated", + ); + + // The second tool call should still be pending + expect(pendingToolCalls).toHaveLength(1); + expect(pendingToolCalls[0].toolCallId).toBe("tool-call-2"); + + // The first tool call should now be canceled + const canceledToolCalls = findAllCurToolCallsByStatus( + state.session.history, + "canceled", + ); + expect(canceledToolCalls).toHaveLength(1); + expect(canceledToolCalls[0].toolCallId).toBe("tool-call-1"); + }); +}); \ No newline at end of file diff --git a/gui/src/pages/gui/chat-tests/ParallelToolCallsBasic.test.tsx b/gui/src/pages/gui/chat-tests/ParallelToolCallsBasic.test.tsx new file mode 100644 index 000000000..4bb88e7b4 --- /dev/null +++ b/gui/src/pages/gui/chat-tests/ParallelToolCallsBasic.test.tsx @@ -0,0 +1,105 @@ +import { act } from "@testing-library/react"; +import { ChatMessage } from "core"; +import { renderWithProviders } from "../../../util/test/render"; +import { sendInputWithMockedResponse } from "../../../util/test/utils"; +import { Chat } from "../Chat"; +import { updateConfig } from "../../../redux/slices/configSlice"; + +describe("Parallel Tool Calls - Basic", () => { + const PARALLEL_TOOL_CALL_RESPONSE: ChatMessage[] = [ + { + role: "assistant", + content: "I'll call both tools in parallel.", + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ filepath: "test.js" }), + }, + }, + { + id: "tool-call-2", + type: "function", + function: { + name: "write_file", + arguments: JSON.stringify({ + filepath: "output.js", + content: "test", + }), + }, + }, + ], + }, + ]; + + test("should handle assistant message with multiple tool calls", async () => { + const { ideMessenger, store } = await renderWithProviders(); + + // Mock required responses + ideMessenger.responses["tools/evaluatePolicy"] = { + policy: "allowedWithPermission", + }; + ideMessenger.responses["context/getSymbolsForFiles"] = {}; + + // Setup mock model with direct Redux dispatch + const currentConfig = store.getState().config.config; + store.dispatch(updateConfig({ + ...currentConfig, + selectedModelByRole: { + ...currentConfig.selectedModelByRole, + chat: { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + }, + modelsByRole: { + ...currentConfig.modelsByRole, + chat: [ + ...(currentConfig.modelsByRole.chat || []), + { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + ] + } + })); + + await sendInputWithMockedResponse( + ideMessenger, + "Use both tools", + PARALLEL_TOOL_CALL_RESPONSE, + ); + + // Wait for streaming to complete + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 500)); + }); + + const state = store.getState(); + const history = state.session.history; + + // Should have user message and assistant message + expect(history).toHaveLength(2); + + // Find assistant message with tool calls + const assistantMessage = history.find( + (item) => + item.message.role === "assistant" && item.toolCallStates?.length, + ); + + expect(assistantMessage).toBeDefined(); + expect(assistantMessage!.toolCallStates).toHaveLength(2); + expect(assistantMessage!.toolCallStates![0].toolCallId).toBe("tool-call-1"); + expect(assistantMessage!.toolCallStates![1].toolCallId).toBe("tool-call-2"); + }); +}); \ No newline at end of file diff --git a/gui/src/pages/gui/chat-tests/ParallelToolCallsStreaming.test.tsx b/gui/src/pages/gui/chat-tests/ParallelToolCallsStreaming.test.tsx new file mode 100644 index 000000000..eda9f067d --- /dev/null +++ b/gui/src/pages/gui/chat-tests/ParallelToolCallsStreaming.test.tsx @@ -0,0 +1,132 @@ +import { act } from "@testing-library/react"; +import { ChatMessage } from "core"; +import { renderWithProviders } from "../../../util/test/render"; +import { sendInputWithMockedResponse } from "../../../util/test/utils"; +import { Chat } from "../Chat"; +import { updateConfig } from "../../../redux/slices/configSlice"; + +describe("Parallel Tool Calls - Streaming", () => { + test("should handle streaming deltas for multiple tool calls", async () => { + const { ideMessenger, store } = await renderWithProviders(); + + // Mock required responses + ideMessenger.responses["tools/evaluatePolicy"] = { + policy: "allowedWithPermission", + }; + ideMessenger.responses["context/getSymbolsForFiles"] = {}; + + // Setup mock model with direct Redux dispatch + const currentConfig = store.getState().config.config; + store.dispatch(updateConfig({ + ...currentConfig, + selectedModelByRole: { + ...currentConfig.selectedModelByRole, + chat: { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + }, + modelsByRole: { + ...currentConfig.modelsByRole, + chat: [ + ...(currentConfig.modelsByRole.chat || []), + { + model: "mock", + provider: "mock", + title: "Mock LLM", + underlyingProviderName: "mock", + } + ] + } + })); + + // Simulate streaming behavior with deltas + const STREAMING_RESPONSE: ChatMessage[] = [ + { + role: "assistant", + content: "I'll call both tools in parallel.", + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "read_file", + arguments: "", + }, + }, + ], + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "read_file", + arguments: '{"filepath": "test.js"}', + }, + }, + ], + }, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-call-2", + type: "function", + function: { + name: "write_file", + arguments: '{"filepath": "output.js", "content": "test"}', + }, + }, + ], + }, + ]; + + await sendInputWithMockedResponse( + ideMessenger, + "Use both tools with streaming", + STREAMING_RESPONSE, + ); + + // Wait for streaming to complete + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 500)); + }); + + const state = store.getState(); + const history = state.session.history; + + // Should have only one assistant message after streaming + const assistantMessages = history.filter( + (item) => item.message.role === "assistant", + ); + expect(assistantMessages).toHaveLength(1); + + const assistantMessage = assistantMessages[0]; + + // Should preserve original content + expect(assistantMessage.message.content).toContain( + "I'll call both tools in parallel", + ); + + // Should have both tool calls after streaming completes + expect(assistantMessage.toolCallStates).toHaveLength(2); + + // Verify tool calls are properly constructed + const toolCallIds = assistantMessage.toolCallStates!.map( + (tc) => tc.toolCallId, + ); + expect(toolCallIds).toContain("tool-call-1"); + expect(toolCallIds).toContain("tool-call-2"); + }); +}); \ No newline at end of file