fix tests

This commit is contained in:
Patrick Erichsen 2025-09-09 13:43:06 -07:00
parent 464842fab8
commit ff2b56fff3
6 changed files with 635 additions and 368 deletions

View file

@ -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(<Chat />);
// 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(<Chat />);
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,
// });
});

View file

@ -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(<Chat />);
// 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,
// });
});

View file

@ -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(<Chat />);
// 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(<Chat />);
// 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(<Chat />);
// 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");
});
});

View file

@ -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(<Chat />);
// 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");
});
});

View file

@ -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(<Chat />);
// 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");
});
});

View file

@ -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(<Chat />);
// 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");
});
});