Merge pull request #6108 from shssoichiro/issue-5419

fix: enable parsing of OpenAI-compatible agent mode messages
This commit is contained in:
Dallin Romney 2025-07-08 10:14:13 -07:00 • committed by GitHub
commit 11c4ba7497
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 542 additions and 45 deletions

View file

@ -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:
"<think>I should send the user a response.</think> 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: "<think>I should use a tool call.</think>",
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: "<think>I should use a tool call.</think>",
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: "<think>",
},
{
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: "</think>",
},
{
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!");
});
});
});

View file

@ -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<ChatMessage[]>) => {
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(
/<think>([\s\S]*)<\/think>([\s\S]*)/,
);
if (thinkMatches) {
// The order that they seem to consistently use is:
//
// <think>Thinking text</think>
// 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("<think>")) {
lastItem.reasoning = {
startAt: Date.now(),
active: true,
text: messageContent.replace("<think>", "").trim(),
};
} else if (
lastItem.reasoning?.active &&
messageContent.includes("</think>")
lastItem = state.history[state.history.length - 1];
lastMessage = lastItem.message;
}
// Add to the existing message
if (messageContent) {
if (messageContent.includes("<think>")) {
lastItem.reasoning = {
startAt: Date.now(),
active: true,
text: messageContent.replace("<think>", "").trim(),
};
} else if (
lastItem.reasoning?.active &&
messageContent.includes("</think>")
) {
const [reasoningEnd, answerStart] =
messageContent.split("</think>");
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("</think>");
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];
}
}
}