diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 9b037a068..7a0d494c9 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -17,11 +17,9 @@ import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; export function HistoryTableRow({ sessionMetadata, - date, index, }: { sessionMetadata: SessionMetadata; - date: Date; index: number; }) { const dispatch = useAppDispatch(); @@ -67,7 +65,7 @@ export function HistoryTableRow({ onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} data-testid={`history-row-${index}`} - className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3" + className="hover:bg-list-hover relative box-border flex w-full cursor-pointer overflow-hidden rounded-lg p-3" onClick={async () => { await dispatch(exitEdit({})); if (sessionMetadata.sessionId !== currentSessionId) { @@ -83,7 +81,7 @@ export function HistoryTableRow({ >
{editing ? ( -
+
) : ( - + {sessionMetadata.title} )} -
- +
+ {getUriPathBasename(sessionMetadata.workspaceDirectory || "")} {/* Uncomment to show the date */} @@ -119,7 +117,7 @@ export function HistoryTableRow({
{hovered && !editing && ( -
+
{ @@ -127,7 +125,7 @@ export function HistoryTableRow({ setEditing(true); }} > - + - +
)} diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index 1f2e7331a..fd5bec166 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -160,7 +160,7 @@ export function History() { >
)}
-
+
{filteredAndSortedSessions.length === 0 && (
{isSessionMetadataLoading ? ( @@ -229,27 +229,27 @@ export function History() {
)} - + ); })}
-
- {`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`} +
+ + Data is saved in{" "} + + {platform === "windows" + ? "%USERPROFILE%/.continue" + : "~/.continue/sessions"} + + - Clear session history + (Clear session history)
diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 07098f003..00c0e1ed6 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -35,7 +35,101 @@ import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/util import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; -import { findToolCallById, findToolOutputById } from "../util"; +import { findChatHistoryItemByToolCallId, findToolCallById } from "../util"; + +/** + * Initializes tool call states for a new message containing tool calls. + * This function is called when we receive a complete message with tool calls, + * typically in non-streaming scenarios or when processing the first chunk + * of a streaming message that contains tool calls. + * + * @param message - The chat message containing tool calls to process + * @param lastItem - The chat history item to attach tool call states to + */ +export function handleToolCallsInMessage( + message: ChatMessage, + lastItem: ChatHistoryItemWithMessageId, +): void { + if ( + (message.role === "assistant" || message.role === "thinking") && + message.toolCalls?.length + ) { + // Initialize tool call states for each tool call in the message + // Each tool call gets its own state to track generation/execution progress + lastItem.toolCallStates = message.toolCalls.map((toolCallDelta) => + addToolCallDeltaToState(toolCallDelta, undefined), + ); + + // Update the message's toolCalls array to reflect the processed tool calls + // We can safely cast because we verified the role above + const curMessage = lastItem.message as + | AssistantChatMessage + | ThinkingChatMessage; + curMessage.toolCalls = lastItem.toolCallStates.map( + (state) => state.toolCall, + ); + } +} + +/** + * Handles incremental updates to tool calls during streaming responses. + * This function processes streaming deltas for tool calls, updating existing + * tool call states or creating new ones as needed. It uses ID-based matching + * to ensure tool call updates are applied to the correct tool call state. + * + * @param message - The streaming message chunk containing tool call deltas + * @param lastItem - The chat history item containing existing tool call states + */ +export function handleStreamingToolCallUpdates( + message: ChatMessage, + lastItem: ChatHistoryItemWithMessageId, +): void { + if ( + message.role === "assistant" && + message.toolCalls?.length && + lastItem.message.role === "assistant" + ) { + // Start with existing tool call states or empty array if none exist + const existingToolCallStates = lastItem.toolCallStates || []; + const updatedToolCallStates: ToolCallState[] = [...existingToolCallStates]; + + // Process each incoming tool call delta, matching by ID to update the correct state + for (const toolCallDelta of message.toolCalls) { + // Find existing state by matching toolCallId - this ensures we update + // the correct tool call even when multiple tool calls are being streamed + const existingStateIndex = updatedToolCallStates.findIndex( + (state) => state.toolCallId === toolCallDelta.id, + ); + + const existingState = + existingStateIndex >= 0 + ? updatedToolCallStates[existingStateIndex] + : undefined; + + // Apply the delta to create an updated state (either updating existing or creating new) + const updatedState = addToolCallDeltaToState( + toolCallDelta, + existingState, + ); + + if (existingStateIndex >= 0) { + // Update existing tool call state in place + updatedToolCallStates[existingStateIndex] = updatedState; + } else { + // Add new tool call state for a newly discovered tool call + updatedToolCallStates.push(updatedState); + } + } + + // Replace the entire tool call states array with the updated version + lastItem.toolCallStates = updatedToolCallStates; + + // Update the message's toolCalls array to reflect current tool call states + (lastItem.message as any).toolCalls = updatedToolCallStates.map( + (state) => state.toolCall, + ); + } +} // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -320,6 +414,7 @@ export const sessionSlice = createSlice({ } }, setInactive: (state) => { + debugger; const curMessage = state.history.at(-1); if (curMessage) { @@ -389,23 +484,7 @@ export const sessionSlice = createSlice({ lastItem = state.history[state.history.length - 1]; lastMessage = lastItem.message; - if ( - (message.role === "assistant" || message.role === "thinking") && - message.toolCalls?.length - ) { - // Handle multiple tool calls - lastItem.toolCallStates = message.toolCalls.map( - (toolCallDelta) => - addToolCallDeltaToState(toolCallDelta, undefined), - ); - // We know this is one of these two types because we just added it - const curMessage = lastMessage as - | AssistantChatMessage - | ThinkingChatMessage; - curMessage.toolCalls = lastItem.toolCallStates.map( - (state) => state.toolCall, - ); - } + handleToolCallsInMessage(message, lastItem); return; } @@ -426,17 +505,7 @@ export const sessionSlice = createSlice({ }, contextItems: [], }; - if (message.role === "assistant" && message.toolCalls?.length) { - // Handle multiple tool calls - historyItem.toolCallStates = message.toolCalls.map( - (toolCallDelta) => - addToolCallDeltaToState(toolCallDelta, undefined), - ); - // Set toolCalls on the message for compatibility - (historyItem.message as any).toolCalls = historyItem.toolCallStates.map( - (state) => state.toolCall, - ); - } + handleToolCallsInMessage(message, historyItem); state.history.push(historyItem); lastItem = state.history[state.history.length - 1]; lastMessage = lastItem.message; @@ -486,42 +555,7 @@ export const sessionSlice = createSlice({ message.toolCalls?.length && lastMessage.role === "assistant" ) { - // Handle multiple tool calls in streaming updates - ID-based approach - const existingToolCallStates = lastItem.toolCallStates || []; - const updatedToolCallStates: ToolCallState[] = [ - ...existingToolCallStates, - ]; - - // Process each incoming tool call delta by ID - for (const toolCallDelta of message.toolCalls) { - // Find existing state by toolCallId - const existingStateIndex = updatedToolCallStates.findIndex( - (state) => state.toolCallId === toolCallDelta.id, - ); - - const existingState = - existingStateIndex >= 0 - ? updatedToolCallStates[existingStateIndex] - : undefined; - - const updatedState = addToolCallDeltaToState( - toolCallDelta, - existingState, - ); - - if (existingStateIndex >= 0) { - // Update existing state - updatedToolCallStates[existingStateIndex] = updatedState; - } else { - // Add new state - updatedToolCallStates.push(updatedState); - } - } - - lastItem.toolCallStates = updatedToolCallStates; - (lastMessage as any).toolCalls = updatedToolCallStates.map( - (state) => state.toolCall, - ); + handleStreamingToolCallUpdates(message, lastItem); } } } @@ -700,7 +734,7 @@ export const sessionSlice = createSlice({ if (toolCallState) { toolCallState.output = action.payload.contextItems; } - const toolItem = findToolOutputById( + const toolItem = findChatHistoryItemByToolCallId( state.history, action.payload.toolCallId, ); diff --git a/gui/src/redux/thunks/resetStateForNewMessage.ts b/gui/src/redux/thunks/resetStateForNewMessage.ts deleted file mode 100644 index 3844e34e4..000000000 --- a/gui/src/redux/thunks/resetStateForNewMessage.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import { resetNextCodeBlockToApplyIndex } from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; - -export const resetStateForNewMessage = createAsyncThunk< - void, - undefined, - ThunkApiType ->("chat/resetStateForNewMessage", async (_, { dispatch }) => { - dispatch(resetNextCodeBlockToApplyIndex()); -}); diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index ac7af1ec2..a283c5238 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -6,11 +6,11 @@ import { v4 as uuidv4 } from "uuid"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; import { selectSelectedChatModel } from "../slices/configSlice"; import { + resetNextCodeBlockToApplyIndex, submitEditorAndInitAtIndex, updateHistoryItemAtIndex, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; import { streamThunkWrapper } from "./streamThunkWrapper"; import { updateFileSymbolsFromFiles } from "./updateFileSymbols"; @@ -39,7 +39,8 @@ export const streamResponseThunk = createAsyncThunk< dispatch( submitEditorAndInitAtIndex({ index: inputIndex, editorState }), ); - resetStateForNewMessage(); + + dispatch(resetNextCodeBlockToApplyIndex()); const defaultContextProviders = state.config.config.experimental?.defaultContext ?? []; diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index ab01de3d8..58a63f598 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,13 +1,83 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; import { renderContextItems } from "core/util/messageContent"; -import { streamUpdate } from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; +import { + resetNextCodeBlockToApplyIndex, + streamUpdate, +} from "../slices/sessionSlice"; +import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; import { findToolCallById } from "../util"; -import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; import { streamThunkWrapper } from "./streamThunkWrapper"; +/** + * Finds the assistant message that contains the specified tool call. + */ +function findAssistantMessageWithToolCall( + history: RootState["session"]["history"], + toolCallId: string, +) { + return history.find( + (item) => + item.message.role === "assistant" && + item.toolCallStates?.some((tc) => tc.toolCallId === toolCallId), + ); +} + +/** + * Checks if all parallel tool calls in an assistant message are complete. + */ +function areAllToolCallsComplete( + toolCallStates: NonNullable< + ReturnType + >["toolCallStates"], +): boolean { + if (!toolCallStates) return false; + + const completedToolCalls = toolCallStates.filter( + (tc) => tc.status === "done", + ); + + return completedToolCalls.length === toolCallStates.length; +} + +/** + * Determines if we should continue streaming based on tool call completion status. + */ +function shouldContinueStreaming( + assistantMessage: ReturnType, +): boolean { + if (!assistantMessage?.toolCallStates) { + return false; // No assistant message found - don't stream + } + + const totalToolCalls = assistantMessage.toolCallStates.length; + + // Single tool call - always continue streaming + if (totalToolCalls === 1) { + return true; + } + + // Multiple tool calls - only continue if all are complete + return areAllToolCallsComplete(assistantMessage.toolCallStates); +} + +/** + * Creates and dispatches a tool message for the completed tool call. + */ +function createAndDispatchToolMessage( + dispatch: AppThunkDispatch, + toolCallId: string, + toolOutput: any[], +): void { + const newMessage: ChatMessage = { + role: "tool", + content: renderContextItems(toolOutput), + toolCallId, + }; + dispatch(streamUpdate([newMessage])); +} + export const streamResponseAfterToolCall = createAsyncThunk< void, { toolCallId: string }, @@ -17,7 +87,6 @@ export const streamResponseAfterToolCall = createAsyncThunk< async ({ toolCallId }, { dispatch, getState }) => { await dispatch( streamThunkWrapper(async () => { - debugger; const state = getState(); const toolCallState = findToolCallById( @@ -31,39 +100,20 @@ export const streamResponseAfterToolCall = createAsyncThunk< const toolOutput = toolCallState.output ?? []; - resetStateForNewMessage(); - + dispatch(resetNextCodeBlockToApplyIndex()); await new Promise((resolve) => setTimeout(resolve, 0)); - // TODO parallel tool calls - dispatch one tool message per tool call - const newMessage: ChatMessage = { - role: "tool", - content: renderContextItems(toolOutput), - toolCallId, - }; - dispatch(streamUpdate([newMessage])); + // Create and dispatch the tool message + createAndDispatchToolMessage(dispatch, toolCallId, toolOutput); - // Check if all parallel tool calls are complete before continuing + // Check if we should continue streaming based on tool call completion const history = getState().session.history; - const assistantMessage = history.find( - (item) => - item.message.role === "assistant" && - item.toolCallStates?.some((tc) => tc.toolCallId === toolCallId), + const assistantMessage = findAssistantMessageWithToolCall( + history, + toolCallId, ); - if (assistantMessage && assistantMessage.toolCallStates) { - const totalToolCalls = assistantMessage.toolCallStates.length; - const completedToolCalls = assistantMessage.toolCallStates.filter( - (tc) => tc.status === "done", - ); - - // Only continue streaming if ALL parallel tool calls are complete - if (completedToolCalls.length === totalToolCalls) { - unwrapResult(await dispatch(streamNormalInput({}))); - } - // If not all are complete, just wait - don't continue streaming yet - } else { - // Fallback: use original logic for single tool call (only when no assistant message found) + if (shouldContinueStreaming(assistantMessage)) { unwrapResult(await dispatch(streamNormalInput({}))); } }), diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index dd16e2582..2bceb8fb3 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -43,7 +43,11 @@ export function findAllCurToolCalls( // Find the most recent assistant message that has tool call states for (let i = chatHistory.length - 1; i >= 0; i--) { const item = chatHistory[i]; - if (item.message.role === "assistant" && item.toolCallStates && item.toolCallStates.length > 0) { + if ( + item.message.role === "assistant" && + item.toolCallStates && + item.toolCallStates.length > 0 + ) { return item.toolCallStates; } } @@ -76,7 +80,7 @@ export function findToolCallById( return undefined; } -export function findToolOutputById( +export function findChatHistoryItemByToolCallId( chatHistory: RootState["session"]["history"], toolCallId: string, ): ChatHistoryItemWithMessageId | undefined {