This commit is contained in:
Patrick Erichsen 2025-07-13 21:21:34 -07:00
parent b56ca0209d
commit f39d3527fd
10 changed files with 169 additions and 119 deletions

View file

@ -13,7 +13,9 @@ export interface SessionGroup {
sessions: SessionMetadata[];
}
export const groupSessionsByDate = (sessions: SessionMetadata[]): SessionGroup[] => {
export const groupSessionsByDate = (
sessions: SessionMetadata[],
): SessionGroup[] => {
const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24);
const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7);
const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30);
@ -45,4 +47,4 @@ export const groupSessionsByDate = (sessions: SessionMetadata[]): SessionGroup[]
groups.push({ label: "Older", sessions: olderSessions });
return groups;
};
};

View file

@ -28,7 +28,7 @@ export function ToolbarButtonWithTooltip({
}}
data-tooltip-id={tooltipId}
data-testid={testId}
className="hover:description-muted/30 cursor-pointer select-none rounded bg-transparent px-0.5 py-0.5 hover:opacity-80 flex items-center justify-center"
className="hover:description-muted/30 flex cursor-pointer select-none items-center justify-center rounded bg-transparent px-0.5 py-0.5 hover:opacity-80"
>
{children}
</div>

View file

@ -27,9 +27,7 @@ import { TabBar } from "../../components/TabBar/TabBar";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import {
selectPendingToolCalls,
} from "../../redux/selectors/selectToolCalls";
import { selectPendingToolCalls } from "../../redux/selectors/selectToolCalls";
import {
cancelToolCall,
ChatHistoryItemWithMessageId,
@ -141,10 +139,10 @@ export function Chat() {
);
const pendingToolCalls = useAppSelector(selectPendingToolCalls);
const pendingApplyStates = useAppSelector(
(state) => state.session.codeBlockApplyStates.states.filter(
(applyState) => applyState.status === "done"
)
const pendingApplyStates = useAppSelector((state) =>
state.session.codeBlockApplyStates.states.filter(
(applyState) => applyState.status === "done",
),
);
const sendInput = useCallback(
@ -162,7 +160,7 @@ export function Chat() {
}),
);
});
// Reject all pending apply states
pendingApplyStates.forEach((applyState) => {
if (applyState.status !== "closed") {

View file

@ -24,7 +24,10 @@ describe("Parallel Tool Calls", () => {
type: "function",
function: {
name: "write_file",
arguments: JSON.stringify({ filepath: "output.js", content: "test" }),
arguments: JSON.stringify({
filepath: "output.js",
content: "test",
}),
},
},
],
@ -53,10 +56,11 @@ describe("Parallel Tool Calls", () => {
// 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
(item) =>
item.message.role === "assistant" && item.toolCallStates?.length,
);
expect(assistantMessage).toBeDefined();
@ -83,7 +87,9 @@ describe("Parallel Tool Calls", () => {
});
const { findAllCurToolCallsByStatus } = await import("../../../redux/util");
const { cancelToolCall } = await import("../../../redux/slices/sessionSlice");
const { cancelToolCall } = await import(
"../../../redux/slices/sessionSlice"
);
// Verify we have multiple pending tool calls
let state = store.getState();
@ -104,7 +110,7 @@ describe("Parallel Tool Calls", () => {
state.session.history,
"generated",
);
// The second tool call should still be pending
expect(pendingToolCalls).toHaveLength(1);
expect(pendingToolCalls[0].toolCallId).toBe("tool-call-2");
@ -187,22 +193,28 @@ describe("Parallel Tool Calls", () => {
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");
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");
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);
const toolCallIds = assistantMessage.toolCallStates!.map(
(tc) => tc.toolCallId,
);
expect(toolCallIds).toContain("tool-call-1");
expect(toolCallIds).toContain("tool-call-2");
});
});
});

View file

@ -168,7 +168,9 @@ describe("sessionSlice streamUpdate", () => {
// Check generating message
expect(newState.history[1].message.role).toBe("assistant");
expect(newState.history[1].message.content).toBe("");
expect(newState.history[1].toolCallStates?.[0]?.status).toBe("generating");
expect(newState.history[1].toolCallStates?.[0]?.status).toBe(
"generating",
);
expect(newState.history[1].toolCallStates?.[0]?.toolCallId).toBe("1234");
const toolResponseAction = {
@ -237,7 +239,9 @@ describe("sessionSlice streamUpdate", () => {
// Check generating message
expect(newState.history[1].message.role).toBe("assistant");
expect(newState.history[1].message.content).toBe("");
expect(newState.history[1].toolCallStates?.[0]?.status).toBe("generating");
expect(newState.history[1].toolCallStates?.[0]?.status).toBe(
"generating",
);
expect(newState.history[1].toolCallStates?.[0]?.toolCallId).toBe("1234");
const toolResponseAction = {
@ -418,7 +422,7 @@ describe("sessionSlice streamUpdate", () => {
it("should handle basic tool call streaming", () => {
const initialState = createInitialState();
const toolCallId = "call_123";
const action = {
type: "session/streamUpdate",
payload: [

View file

@ -42,24 +42,29 @@ import { findChatHistoryItemByToolCallId, findToolCallById } from "../util";
/**
* Helper function to filter out duplicate edit/search-replace tool calls.
* Only keeps the first occurrence of edit tools.
*
* We don't support multiple parallel apply calls - see tool definitions for
*
* We don't support multiple parallel apply calls - see tool definitions for
* instructions we provide to models to prevent this behavior.
*/
function filterMultipleEditToolCalls(toolCalls: ToolCallDelta[]): ToolCallDelta[] {
const editToolNames = [BuiltInToolNames.EditExistingFile, BuiltInToolNames.SearchAndReplaceInFile];
function filterMultipleEditToolCalls(
toolCalls: ToolCallDelta[],
): ToolCallDelta[] {
const editToolNames = [
BuiltInToolNames.EditExistingFile,
BuiltInToolNames.SearchAndReplaceInFile,
];
let hasSeenEditTool = false;
return toolCalls.filter(toolCall => {
return toolCalls.filter((toolCall) => {
const isEditTool = editToolNames.includes(toolCall.function?.name as any);
if (isEditTool) {
if (hasSeenEditTool) {
return false; // Skip this duplicate edit tool
}
hasSeenEditTool = true;
}
return true;
});
}
@ -103,12 +108,12 @@ export function handleToolCallsInMessage(
/**
* Applies a single tool call delta to the tool call states array.
*
*
* This function handles the core logic for OpenAI-style tool call streaming where:
* - Initial tool calls come with full details (ID, name, arguments)
* - Subsequent argument fragments come without IDs and need to update the most recent tool call
* - Multiple parallel tool calls can be streamed simultaneously
*
*
* @param toolCallDelta - The incoming tool call delta from the LLM stream
* @param toolCallStates - Array of existing tool call states (modified in place)
*/
@ -119,19 +124,19 @@ function applyToolCallDelta(
// Find existing state by matching toolCallId - this ensures we update
// the correct tool call even when multiple tool calls are being streamed
let existingStateIndex = -1;
if (toolCallDelta.id) {
// Tool call has an ID - find by exact match
// This handles: new tool calls or explicit updates to existing ones
existingStateIndex = toolCallStates.findIndex(
(state) => state.toolCallId === toolCallDelta.id
(state) => state.toolCallId === toolCallDelta.id,
);
} else {
// No ID in delta (common in OpenAI streaming fragments)
// Strategy: Update the most recently added tool call that's still being generated
// This handles the pattern: initial tool call with ID, then fragments without ID
existingStateIndex = toolCallStates.length - 1;
// Ensure we have at least one tool call to update
if (existingStateIndex < 0) {
existingStateIndex = -1; // Will create new tool call
@ -139,15 +144,10 @@ function applyToolCallDelta(
}
const existingState =
existingStateIndex >= 0
? toolCallStates[existingStateIndex]
: undefined;
existingStateIndex >= 0 ? toolCallStates[existingStateIndex] : undefined;
// Apply the delta to create an updated state (either updating existing or creating new)
const updatedState = addToolCallDeltaToState(
toolCallDelta,
existingState,
);
const updatedState = addToolCallDeltaToState(toolCallDelta, existingState);
if (existingStateIndex >= 0) {
// Update existing tool call state in place

View file

@ -316,20 +316,24 @@ describe("constructMessages", () => {
{
message: assistantWithToolCall,
contextItems: [],
toolCallStates: [{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
toolCallStates: [
{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "done",
parsedArgs: { query: "test" },
output: [
createContextItem("search-result", "Search result content"),
],
},
status: "done",
parsedArgs: { query: "test" },
output: [createContextItem("search-result", "Search result content")],
}],
],
},
];
@ -370,19 +374,21 @@ describe("constructMessages", () => {
{
message: assistantWithToolCall,
contextItems: [],
toolCallStates: [{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
toolCallStates: [
{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "canceled",
parsedArgs: { query: "test" },
},
status: "canceled",
parsedArgs: { query: "test" },
}],
],
},
];
@ -422,19 +428,21 @@ describe("constructMessages", () => {
{
message: assistantWithToolCall,
contextItems: [],
toolCallStates: [{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
toolCallStates: [
{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "generating", // Not done yet
parsedArgs: { query: "test" },
},
status: "generating", // Not done yet
parsedArgs: { query: "test" },
}],
],
},
];
@ -499,20 +507,24 @@ describe("constructMessages", () => {
{
message: assistantWithMultipleToolCalls,
contextItems: [],
toolCallStates: [{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
toolCallStates: [
{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "done",
parsedArgs: { query: "test" },
output: [
createContextItem("search-result", "Search result content"),
],
},
status: "done",
parsedArgs: { query: "test" },
output: [createContextItem("search-result", "Search result content")],
}],
],
},
];
@ -665,20 +677,22 @@ describe("constructMessages", () => {
{
message: assistantWithToolCall,
contextItems: [],
toolCallStates: [{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
toolCallStates: [
{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "done",
parsedArgs: { query: "test" },
output: [triggeringToolOutput],
},
status: "done",
parsedArgs: { query: "test" },
output: [triggeringToolOutput],
}],
],
},
];

View file

@ -9,17 +9,21 @@ afterAll(() => {
});
// Suppress uncaught ProseMirror errors in test environment
window.addEventListener('error', (event) => {
if (event.error?.message?.includes('getClientRects') ||
event.error?.message?.includes('prosemirror')) {
window.addEventListener("error", (event) => {
if (
event.error?.message?.includes("getClientRects") ||
event.error?.message?.includes("prosemirror")
) {
event.preventDefault();
return false;
}
});
window.addEventListener('unhandledrejection', (event) => {
if (event.reason?.message?.includes('getClientRects') ||
event.reason?.message?.includes('prosemirror')) {
window.addEventListener("unhandledrejection", (event) => {
if (
event.reason?.message?.includes("getClientRects") ||
event.reason?.message?.includes("prosemirror")
) {
event.preventDefault();
return false;
}
@ -41,14 +45,28 @@ Object.defineProperty(window, "matchMedia", {
});
// Mock getBoundingClientRect and getClientRects for ProseMirror
Object.defineProperty(Element.prototype, 'getClientRects', {
Object.defineProperty(Element.prototype, "getClientRects", {
value: vi.fn(() => ({
length: 1,
0: { top: 0, bottom: 20, left: 0, right: 100, width: 100, height: 20 },
item: () => ({ top: 0, bottom: 20, left: 0, right: 100, width: 100, height: 20 })
}))
item: () => ({
top: 0,
bottom: 20,
left: 0,
right: 100,
width: 100,
height: 20,
}),
})),
});
Object.defineProperty(Element.prototype, 'getBoundingClientRect', {
value: vi.fn(() => ({ top: 0, bottom: 20, left: 0, right: 100, width: 100, height: 20 }))
Object.defineProperty(Element.prototype, "getBoundingClientRect", {
value: vi.fn(() => ({
top: 0,
bottom: 20,
left: 0,
right: 100,
width: 100,
height: 20,
})),
});

View file

@ -8,7 +8,6 @@ export function addToolCallDeltaToState(
toolCallDelta: ToolCallDelta,
currentState: ToolCallState | undefined,
): ToolCallState {
const currentCall = currentState?.toolCall;
// These will/should not be partially streamed

View file

@ -49,7 +49,10 @@ export default defineConfig({
},
onUnhandledRejection(err) {
// Suppress ProseMirror DOM errors in test environment
if (err.message?.includes("getClientRects") || err.message?.includes("prosemirror")) {
if (
err.message?.includes("getClientRects") ||
err.message?.includes("prosemirror")
) {
return false;
}
return true;