diff --git a/gui/src/redux/slices/sessionSlice.test.ts b/gui/src/redux/slices/sessionSlice.test.ts
new file mode 100644
index 000000000..f332d74cc
--- /dev/null
+++ b/gui/src/redux/slices/sessionSlice.test.ts
@@ -0,0 +1,418 @@
+import { ChatMessage } from "core";
+import { renderChatMessage } from "core/util/messageContent";
+import { v4 as uuidv4 } from "uuid";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { addToolCallDeltaToState } from "../../util/toolCallState";
+import { ChatHistoryItemWithMessageId, sessionSlice } from "./sessionSlice";
+
+// Mock dependencies
+vi.mock("uuid");
+vi.mock("core/util/messageContent");
+vi.mock("../../util/toolCallState");
+
+const mockUuidv4 = vi.mocked(uuidv4);
+const mockRenderChatMessage = vi.mocked(renderChatMessage);
+const mockAddToolCallDeltaToState = vi.mocked(addToolCallDeltaToState);
+
+describe("sessionSlice streamUpdate", () => {
+ beforeEach(() => {
+ // Reset mocks before each test
+ vi.clearAllMocks();
+
+ // Mock uuidv4 to return predictable values
+ let callCount = 0;
+ mockUuidv4.mockImplementation(() => `mock-uuid-${++callCount}`);
+
+ // Mock renderChatMessage to return content as is
+ mockRenderChatMessage.mockImplementation((message: ChatMessage) => {
+ if (typeof message.content === "string") {
+ return message.content;
+ }
+ return "";
+ });
+
+ // Mock addToolCallDeltaToState
+ mockAddToolCallDeltaToState.mockImplementation((delta, state) => {
+ return {
+ status: "generating" as const,
+ toolCall: {
+ id: delta.id || "mock-tool-id",
+ type: "function" as const,
+ function: {
+ name: delta.function?.name || "mock-function",
+ arguments: delta.function?.arguments || "{}",
+ },
+ },
+ toolCallId: delta.id || "mock-tool-id",
+ parsedArgs: {},
+ };
+ });
+ });
+
+ const createInitialState = () => ({
+ lastSessionId: undefined,
+ allSessionMetadata: [],
+ history: [
+ {
+ message: {
+ role: "user" as const,
+ content: "This is a test.",
+ id: "initial-user-message",
+ },
+ contextItems: [],
+ },
+ ] as ChatHistoryItemWithMessageId[],
+ isStreaming: false,
+ title: "Test Session",
+ id: "test-session-id",
+ streamAborter: new AbortController(),
+ symbols: {},
+ mode: "chat" as const,
+ isInEdit: false,
+ codeBlockApplyStates: {
+ states: [],
+ curIndex: 0,
+ },
+ newestToolbarPreviewForInput: {},
+ isSessionMetadataLoading: false,
+ });
+
+ describe("Basic Chat Message", () => {
+ it("should append assistant message to history", () => {
+ const initialState = createInitialState();
+ const action = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "assistant" as const,
+ content: "Here is a response to your message without thinking.",
+ },
+ ],
+ };
+
+ const newState = sessionSlice.reducer(initialState, action);
+
+ expect(newState.history).toHaveLength(2);
+ expect(newState.history[1].message.role).toBe("assistant");
+ expect(newState.history[1].message.content).toBe(
+ "Here is a response to your message without thinking.",
+ );
+ expect(newState.history[1].message.id).toBe("mock-uuid-1");
+ expect(newState.history[1].contextItems).toEqual([]);
+ });
+ });
+
+ describe("Chat Message With Thinking", () => {
+ it("should split thinking and assistant content correctly", () => {
+ const initialState = createInitialState();
+ const action = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "assistant" as const,
+ content:
+ "I should send the user a response. Here is a response to your message with thinking.",
+ },
+ ],
+ };
+
+ const newState = sessionSlice.reducer(initialState, action);
+
+ expect(newState.history).toHaveLength(2);
+
+ // Check reasoning
+ expect(newState.history[0].reasoning?.text).toBe(
+ "I should send the user a response.",
+ );
+
+ // Check assistant message
+ expect(newState.history[1].message.role).toBe("assistant");
+ expect(newState.history[1].message.content).toBe(
+ "Here is a response to your message with thinking.",
+ );
+ expect(newState.history[1].message.id).toBe("mock-uuid-1");
+ });
+ });
+
+ describe("Tool Call With Response", () => {
+ it("should handle tool call followed by tool response and assistant message", () => {
+ const initialState = createInitialState();
+ const toolCallAction = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "assistant" as const,
+ content: "I should use a tool call.",
+ toolCalls: [
+ {
+ id: "1234",
+ type: "function" as const,
+ function: {
+ name: "builtin_ls",
+ arguments: '{"dirPath":".","recursive":false}',
+ },
+ },
+ ],
+ },
+ ],
+ };
+
+ let newState = sessionSlice.reducer(initialState, toolCallAction);
+ expect(newState.history).toHaveLength(2);
+
+ // Check reasoning
+ expect(newState.history[0].reasoning?.text).toBe(
+ "I should use a tool call.",
+ );
+
+ // Check generating message
+ expect(newState.history[1].message.role).toBe("assistant");
+ expect(newState.history[1].message.content).toBe("");
+ expect(newState.history[1].toolCallState?.status).toBe("generating");
+ expect(newState.history[1].toolCallState?.toolCallId).toBe("1234");
+
+ const toolResponseAction = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "tool" as const,
+ toolCallId: "1234",
+ content: "foo.txt\nbar.txt\nexample.php",
+ },
+ {
+ role: "assistant" as const,
+ content: "I see, the tool found 3 files.",
+ },
+ ],
+ };
+ newState = sessionSlice.reducer(newState, toolResponseAction);
+ expect(newState.history).toHaveLength(4);
+
+ // Check tool message
+ expect(newState.history[2].message.role).toBe("tool");
+ expect(newState.history[2].message.content).toBe(
+ "foo.txt\nbar.txt\nexample.php",
+ );
+ expect((newState.history[2].message as any).toolCallId).toBe("1234");
+
+ // Check final assistant message
+ expect(newState.history[3].message.role).toBe("assistant");
+ expect(newState.history[3].message.content).toBe(
+ "I see, the tool found 3 files.",
+ );
+ });
+ });
+
+ describe("Tool Call With Streaming Response", () => {
+ it("should handle streaming assistant response after tool call", () => {
+ const initialState = createInitialState();
+ const toolCallAction = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "assistant" as const,
+ content: "I should use a tool call.",
+ toolCalls: [
+ {
+ id: "1234",
+ type: "function" as const,
+ function: {
+ name: "builtin_ls",
+ arguments: '{"dirPath":".","recursive":false}',
+ },
+ },
+ ],
+ },
+ ],
+ };
+
+ let newState = sessionSlice.reducer(initialState, toolCallAction);
+ expect(newState.history).toHaveLength(2);
+
+ // Check reasoning
+ expect(newState.history[0].reasoning?.text).toBe(
+ "I should use a tool call.",
+ );
+
+ // Check generating message
+ expect(newState.history[1].message.role).toBe("assistant");
+ expect(newState.history[1].message.content).toBe("");
+ expect(newState.history[1].toolCallState?.status).toBe("generating");
+ expect(newState.history[1].toolCallState?.toolCallId).toBe("1234");
+
+ const toolResponseAction = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "tool" as const,
+ toolCallId: "1234",
+ content: "foo.txt\nbar.txt\nexample.php",
+ },
+ {
+ role: "assistant" as const,
+ content: "",
+ },
+ {
+ role: "assistant" as const,
+ content: "Good, ",
+ },
+ {
+ role: "assistant" as const,
+ content: "I received a list",
+ },
+ {
+ role: "assistant" as const,
+ content: " of files.",
+ },
+ {
+ role: "assistant" as const,
+ content: "",
+ },
+ {
+ role: "assistant" as const,
+ content: "\n",
+ },
+ {
+ role: "assistant" as const,
+ content: "I see, ",
+ },
+ {
+ role: "assistant" as const,
+ content: "the tool ",
+ },
+ {
+ role: "assistant" as const,
+ content: "found 3 ",
+ },
+ {
+ role: "assistant" as const,
+ content: "files.",
+ },
+ ],
+ };
+
+ newState = sessionSlice.reducer(newState, toolResponseAction);
+
+ expect(newState.history).toHaveLength(4);
+
+ // Check tool message
+ expect(newState.history[2].message.role).toBe("tool");
+ expect(newState.history[2].message.content).toBe(
+ "foo.txt\nbar.txt\nexample.php",
+ );
+
+ // Check response message
+ expect(newState.history[3].message.role).toBe("assistant");
+ expect(newState.history[3].message.content).toBe(
+ "I see, the tool found 3 files.",
+ );
+ expect(newState.history[3].reasoning?.text).toBe(
+ "Good, I received a list of files.",
+ );
+ expect(newState.history[3].reasoning?.active).toBe(false);
+ });
+ });
+
+ describe("Edge Cases", () => {
+ it("should handle empty history gracefully", () => {
+ const initialState = createInitialState();
+ initialState.history = [];
+
+ const action = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "assistant" as const,
+ content: "Hello",
+ },
+ ],
+ };
+
+ const newState = sessionSlice.reducer(initialState, action);
+
+ // Should not crash and history should remain empty
+ expect(newState.history).toHaveLength(0);
+ });
+
+ it("should handle redacted thinking messages", () => {
+ const initialState = createInitialState();
+ const action = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "thinking" as const,
+ content: "This should be hidden",
+ redactedThinking: true,
+ },
+ ],
+ };
+
+ const newState = sessionSlice.reducer(initialState, action);
+
+ expect(newState.history).toHaveLength(2);
+ expect(newState.history[1].message.role).toBe("thinking");
+ expect(newState.history[1].message.content).toBe(
+ "internal reasoning is hidden due to safety reasons",
+ );
+ expect((newState.history[1].message as any).redactedThinking).toBe(true);
+ });
+
+ it("should handle signature updates for thinking messages", () => {
+ const initialState = createInitialState();
+ // First add a thinking message
+ initialState.history.push({
+ message: {
+ role: "thinking",
+ content: "Some thinking",
+ id: "thinking-message",
+ },
+ contextItems: [],
+ });
+
+ const action = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "thinking" as const,
+ signature: "test-signature",
+ },
+ ],
+ };
+
+ const newState = sessionSlice.reducer(initialState, action);
+
+ expect(newState.history).toHaveLength(2);
+ expect((newState.history[1].message as any).signature).toBe(
+ "test-signature",
+ );
+ });
+
+ it("should accumulate content for same role messages", () => {
+ const initialState = createInitialState();
+ // Add an assistant message first
+ initialState.history.push({
+ message: {
+ role: "assistant",
+ content: "Hello ",
+ id: "assistant-message",
+ },
+ contextItems: [],
+ });
+
+ const action = {
+ type: "session/streamUpdate",
+ payload: [
+ {
+ role: "assistant" as const,
+ content: "world!",
+ },
+ ],
+ };
+
+ const newState = sessionSlice.reducer(initialState, action);
+
+ expect(newState.history).toHaveLength(2);
+ expect(newState.history[1].message.content).toBe("Hello world!");
+ });
+ });
+});
diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts
index 45d68b456..8d1ef3e3e 100644
--- a/gui/src/redux/slices/sessionSlice.ts
+++ b/gui/src/redux/slices/sessionSlice.ts
@@ -8,6 +8,7 @@ import {
import { JSONContent } from "@tiptap/react";
import {
ApplyState,
+ AssistantChatMessage,
ChatHistoryItem,
ChatMessage,
ContextItem,
@@ -18,6 +19,7 @@ import {
RuleWithSource,
Session,
SessionMetadata,
+ ThinkingChatMessage,
Tool,
} from "core";
import { NEW_SESSION_TITLE } from "core/util/constants";
@@ -330,12 +332,10 @@ export const sessionSlice = createSlice({
streamUpdate: (state, action: PayloadAction) => {
if (state.history.length) {
for (const message of action.payload) {
- const lastItem = state.history[state.history.length - 1];
- const lastMessage = lastItem.message;
+ let lastItem = state.history[state.history.length - 1];
+ let lastMessage = lastItem.message;
if (message.role === "thinking" && message.redactedThinking) {
- console.log("add redacted_thinking blocks");
-
state.history.push({
message: {
role: "thinking",
@@ -348,6 +348,74 @@ export const sessionSlice = createSlice({
continue;
}
+ const messageContent = message.content
+ ? renderChatMessage(message)
+ : "";
+
+ // OpenAI-compatible models in agent mode sometimes send
+ // all of their data in one message, so we handle that case early.
+ if (messageContent) {
+ const thinkMatches = messageContent.match(
+ /([\s\S]*)<\/think>([\s\S]*)/,
+ );
+ if (thinkMatches) {
+ // The order that they seem to consistently use is:
+ //
+ // Thinking text
+ // Text to show to the user
+
+ lastItem.reasoning = {
+ text: thinkMatches[1].trim(),
+ startAt: Date.now(),
+ endAt: Date.now(),
+ active: false,
+ };
+
+ // This is the chat message that we should show to the user.
+ // We always need to push this even if it is empty,
+ // because we cannot attach tool calls to a Thinking message.
+ // That would break `messageHasToolCallId`.
+ state.history.push({
+ message: {
+ role: "assistant",
+ content: thinkMatches[2].trim(),
+ id: uuidv4(),
+ },
+ contextItems: [],
+ });
+ lastItem = state.history[state.history.length - 1];
+ lastMessage = lastItem.message;
+
+ if (
+ (message.role === "assistant" || message.role === "thinking") &&
+ message.toolCalls?.[0]
+ ) {
+ // Only support one tool call for now.
+ // There are further changes required throughout the system
+ // to support multiple tool calls in a single message from
+ // OpenAI-compatible providers.
+ const toolCallDelta = message.toolCalls[0];
+ const newToolCallState = addToolCallDeltaToState(
+ toolCallDelta,
+ lastItem.toolCallState,
+ );
+ lastItem.toolCallState = newToolCallState;
+ // We know this is one of these two types because we just added it
+ const curMessage = lastMessage as
+ | AssistantChatMessage
+ | ThinkingChatMessage;
+ if (curMessage.toolCalls) {
+ curMessage.toolCalls.push(newToolCallState.toolCall);
+ } else {
+ curMessage.toolCalls = [newToolCallState.toolCall];
+ }
+ }
+
+ return;
+ }
+ }
+
+ // The remainder of this function handles streaming messages
if (
lastMessage.role !== message.role ||
// This is for when a tool call comes immediately before/after tool call
@@ -363,7 +431,7 @@ export const sessionSlice = createSlice({
const historyItem: ChatHistoryItemWithMessageId = {
message: {
...message,
- content: renderChatMessage(message),
+ content: "",
id: uuidv4(),
},
contextItems: [],
@@ -376,51 +444,62 @@ export const sessionSlice = createSlice({
);
}
state.history.push(historyItem);
- } else {
- // Add to the existing message
- if (message.content) {
- const messageContent = renderChatMessage(message);
- if (messageContent.includes("")) {
- lastItem.reasoning = {
- startAt: Date.now(),
- active: true,
- text: messageContent.replace("", "").trim(),
- };
- } else if (
- lastItem.reasoning?.active &&
- messageContent.includes("")
+ lastItem = state.history[state.history.length - 1];
+ lastMessage = lastItem.message;
+ }
+
+ // Add to the existing message
+ if (messageContent) {
+ if (messageContent.includes("")) {
+ lastItem.reasoning = {
+ startAt: Date.now(),
+ active: true,
+ text: messageContent.replace("", "").trim(),
+ };
+ } else if (
+ lastItem.reasoning?.active &&
+ messageContent.includes("")
+ ) {
+ const [reasoningEnd, answerStart] =
+ messageContent.split("");
+ lastItem.reasoning.text += reasoningEnd.trimEnd();
+ lastItem.reasoning.active = false;
+ lastItem.reasoning.endAt = Date.now();
+ lastMessage.content += answerStart.trimStart();
+ } else if (lastItem.reasoning?.active) {
+ if (
+ lastItem.reasoning.text.length > 0 ||
+ messageContent.trim().length > 0
) {
- const [reasoningEnd, answerStart] =
- messageContent.split("");
- lastItem.reasoning.text += reasoningEnd.trimEnd();
- lastItem.reasoning.active = false;
- lastItem.reasoning.endAt = Date.now();
- lastMessage.content += answerStart.trimStart();
- } else if (lastItem.reasoning?.active) {
lastItem.reasoning.text += messageContent;
- } else {
- // Note this only works because new message above
- // was already rendered from parts to string
+ }
+ } else {
+ // Note this only works because new message above
+ // was already rendered from parts to string
+ if (
+ lastMessage.content.length > 0 ||
+ messageContent.trim().length > 0
+ ) {
lastMessage.content += messageContent;
}
- } else if (message.role === "thinking" && message.signature) {
- if (lastMessage.role === "thinking") {
- lastMessage.signature = message.signature;
- }
- } else if (
- message.role === "assistant" &&
- message.toolCalls?.[0] &&
- lastMessage.role === "assistant"
- ) {
- // Intentionally only supporting one tool call for now.
- const toolCallDelta = message.toolCalls[0];
- const newToolCallState = addToolCallDeltaToState(
- toolCallDelta,
- lastItem.toolCallState,
- );
- lastItem.toolCallState = newToolCallState;
- lastMessage.toolCalls = [newToolCallState.toolCall];
}
+ } else if (message.role === "thinking" && message.signature) {
+ if (lastMessage.role === "thinking") {
+ lastMessage.signature = message.signature;
+ }
+ } else if (
+ message.role === "assistant" &&
+ message.toolCalls?.[0] &&
+ lastMessage.role === "assistant"
+ ) {
+ // Intentionally only supporting one tool call for now.
+ const toolCallDelta = message.toolCalls[0];
+ const newToolCallState = addToolCallDeltaToState(
+ toolCallDelta,
+ lastItem.toolCallState,
+ );
+ lastItem.toolCallState = newToolCallState;
+ lastMessage.toolCalls = [newToolCallState.toolCall];
}
}
}