fix streaming bugs

This commit is contained in:
Patrick Erichsen 2025-07-10 19:09:19 -07:00
parent daf6cfb8c6
commit fc27add2ba
7 changed files with 212 additions and 136 deletions

View file

@ -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({
>
<div className="flex-1 cursor-pointer space-y-1">
{editing ? (
<div className="text-md">
<div>
<Input
type="text"
className="w-full"
@ -95,13 +93,13 @@ export function HistoryTableRow({
/>
</div>
) : (
<span className="line-clamp-1 break-all text-base font-semibold">
<span className="line-clamp-1 break-all text-sm font-semibold">
{sessionMetadata.title}
</span>
)}
<div className="flex" style={{ color: "#9ca3af" }}>
<span className="line-clamp-1 break-all">
<div className="text-description-muted flex">
<span className="line-clamp-1 break-all text-xs">
{getUriPathBasename(sessionMetadata.workspaceDirectory || "")}
</span>
{/* Uncomment to show the date */}
@ -119,7 +117,7 @@ export function HistoryTableRow({
</div>
{hovered && !editing && (
<div className="bg-vsc-background absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-2 rounded-full py-1.5 pl-4 pr-4 shadow-md">
<div className="bg-vsc-background absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
<HeaderButtonWithToolTip
text="Edit"
onClick={async (e) => {
@ -127,7 +125,7 @@ export function HistoryTableRow({
setEditing(true);
}}
>
<PencilSquareIcon width="1.3em" height="1.3em" />
<PencilSquareIcon width="1em" height="1em" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
text="Delete"
@ -136,7 +134,7 @@ export function HistoryTableRow({
await dispatch(deleteSession(sessionMetadata.sessionId));
}}
>
<TrashIcon width="1.3em" height="1.3em" />
<TrashIcon width="1em" height="1em" />
</HeaderButtonWithToolTip>
</div>
)}

View file

@ -160,7 +160,7 @@ export function History() {
>
<div className="relative my-2 flex justify-center space-x-2">
<input
className="bg-vsc-input-background text-vsc-foreground flex-1 rounded-md border border-none py-1 pl-2 pr-8 text-base outline-none focus:outline-none"
className="bg-vsc-input-background text-vsc-foreground flex-1 rounded-md border border-none py-1 pl-2 pr-8 text-sm outline-none focus:outline-none"
ref={searchInputRef}
placeholder="Search past sessions"
type="text"
@ -179,7 +179,7 @@ export function History() {
/>
)}
</div>
<div className="thin-scrollbar flex flex-1 flex-col overflow-y-auto pr-4">
<div className="thin-scrollbar flex flex-1 flex-col overflow-y-auto">
{filteredAndSortedSessions.length === 0 && (
<div className="m-3 text-center">
{isSessionMetadataLoading ? (
@ -229,27 +229,27 @@ export function History() {
</div>
)}
<HistoryTableRow
sessionMetadata={session}
date={date}
index={index}
/>
<HistoryTableRow sessionMetadata={session} index={index} />
</Fragment>
);
})}
</tbody>
</table>
</div>
<div className="flex flex-col items-end justify-center border-0 border-t border-solid border-gray-400 px-2 py-1.5 text-sm">
<i
className=""
data-testid="history-sessions-note"
>{`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`}</i>
<div className="border-border flex items-center justify-center border-0 border-t border-solid px-2 py-3 text-xs">
<span data-testid="history-sessions-note">
Data is saved in{" "}
<span className="italic">
{platform === "windows"
? "%USERPROFILE%/.continue"
: "~/.continue/sessions"}
</span>
</span>
<span
className="cursor-pointer text-xs text-gray-400 hover:underline"
className="text-2xs text-description-muted ml-1 cursor-pointer hover:underline"
onClick={showClearSessionsDialog}
>
Clear session history
(Clear session history)
</span>
</div>
</div>

View file

@ -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,
);

View file

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

View file

@ -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 ?? [];

View file

@ -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<typeof findAssistantMessageWithToolCall>
>["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<typeof findAssistantMessageWithToolCall>,
): 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({})));
}
}),

View file

@ -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 {