Elffuss BraidHub

kikocis/continue public

Merge pull request #6108 from shssoichiro/issue-5419

fix: enable parsing of OpenAI-compatible agent mode messages
Changesetfcc262fbb143f5851d7636827aa19a7d00baf90645695d1c8071a5a444fddc1d
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-08 10:14 -07:00
CommitterGitHub <noreply@github.com> · 2025-07-08 10:14 -07:00
Parents3cacb00b7d18, 07b50b98a899

Browse the files at this changeset

2 files changed

added gui/src/redux/slices/sessionSlice.test.ts +418 −0
@@ -0,0 +1,418 @@
1+import { ChatMessage } from "core";
2+import { renderChatMessage } from "core/util/messageContent";
3+import { v4 as uuidv4 } from "uuid";
4+import { beforeEach, describe, expect, it, vi } from "vitest";
5+import { addToolCallDeltaToState } from "../../util/toolCallState";
6+import { ChatHistoryItemWithMessageId, sessionSlice } from "./sessionSlice";
7+
8+// Mock dependencies
9+vi.mock("uuid");
10+vi.mock("core/util/messageContent");
11+vi.mock("../../util/toolCallState");
12+
13+const mockUuidv4 = vi.mocked(uuidv4);
14+const mockRenderChatMessage = vi.mocked(renderChatMessage);
15+const mockAddToolCallDeltaToState = vi.mocked(addToolCallDeltaToState);
16+
17+describe("sessionSlice streamUpdate", () => {
18+ beforeEach(() => {
19+ // Reset mocks before each test
20+ vi.clearAllMocks();
21+
22+ // Mock uuidv4 to return predictable values
23+ let callCount = 0;
24+ mockUuidv4.mockImplementation(() => `mock-uuid-${++callCount}`);
25+
26+ // Mock renderChatMessage to return content as is
27+ mockRenderChatMessage.mockImplementation((message: ChatMessage) => {
28+ if (typeof message.content === "string") {
29+ return message.content;
30+ }
31+ return "";
32+ });
33+
34+ // Mock addToolCallDeltaToState
35+ mockAddToolCallDeltaToState.mockImplementation((delta, state) => {
36+ return {
37+ status: "generating" as const,
38+ toolCall: {
39+ id: delta.id || "mock-tool-id",
40+ type: "function" as const,
41+ function: {
42+ name: delta.function?.name || "mock-function",
43+ arguments: delta.function?.arguments || "{}",
44+ },
45+ },
46+ toolCallId: delta.id || "mock-tool-id",
47+ parsedArgs: {},
48+ };
49+ });
50+ });
51+
52+ const createInitialState = () => ({
53+ lastSessionId: undefined,
54+ allSessionMetadata: [],
55+ history: [
56+ {
57+ message: {
58+ role: "user" as const,
59+ content: "This is a test.",
60+ id: "initial-user-message",
61+ },
62+ contextItems: [],
63+ },
64+ ] as ChatHistoryItemWithMessageId[],
65+ isStreaming: false,
66+ title: "Test Session",
67+ id: "test-session-id",
68+ streamAborter: new AbortController(),
69+ symbols: {},
70+ mode: "chat" as const,
71+ isInEdit: false,
72+ codeBlockApplyStates: {
73+ states: [],
74+ curIndex: 0,
75+ },
76+ newestToolbarPreviewForInput: {},
77+ isSessionMetadataLoading: false,
78+ });
79+
80+ describe("Basic Chat Message", () => {
81+ it("should append assistant message to history", () => {
82+ const initialState = createInitialState();
83+ const action = {
84+ type: "session/streamUpdate",
85+ payload: [
86+ {
87+ role: "assistant" as const,
88+ content: "Here is a response to your message without thinking.",
89+ },
90+ ],
91+ };
92+
93+ const newState = sessionSlice.reducer(initialState, action);
94+
95+ expect(newState.history).toHaveLength(2);
96+ expect(newState.history[1].message.role).toBe("assistant");
97+ expect(newState.history[1].message.content).toBe(
98+ "Here is a response to your message without thinking.",
99+ );
100+ expect(newState.history[1].message.id).toBe("mock-uuid-1");
101+ expect(newState.history[1].contextItems).toEqual([]);
102+ });
103+ });
104+
105+ describe("Chat Message With Thinking", () => {
106+ it("should split thinking and assistant content correctly", () => {
107+ const initialState = createInitialState();
108+ const action = {
109+ type: "session/streamUpdate",
110+ payload: [
111+ {
112+ role: "assistant" as const,
113+ content:
114+ "<think>I should send the user a response.</think> Here is a response to your message with thinking.",
115+ },
116+ ],
117+ };
118+
119+ const newState = sessionSlice.reducer(initialState, action);
120+
121+ expect(newState.history).toHaveLength(2);
122+
123+ // Check reasoning
124+ expect(newState.history[0].reasoning?.text).toBe(
125+ "I should send the user a response.",
126+ );
127+
128+ // Check assistant message
129+ expect(newState.history[1].message.role).toBe("assistant");
130+ expect(newState.history[1].message.content).toBe(
131+ "Here is a response to your message with thinking.",
132+ );
133+ expect(newState.history[1].message.id).toBe("mock-uuid-1");
134+ });
135+ });
136+
137+ describe("Tool Call With Response", () => {
138+ it("should handle tool call followed by tool response and assistant message", () => {
139+ const initialState = createInitialState();
140+ const toolCallAction = {
141+ type: "session/streamUpdate",
142+ payload: [
143+ {
144+ role: "assistant" as const,
145+ content: "<think>I should use a tool call.</think>",
146+ toolCalls: [
147+ {
148+ id: "1234",
149+ type: "function" as const,
150+ function: {
151+ name: "builtin_ls",
152+ arguments: '{"dirPath":".","recursive":false}',
153+ },
154+ },
155+ ],
156+ },
157+ ],
158+ };
159+
160+ let newState = sessionSlice.reducer(initialState, toolCallAction);
161+ expect(newState.history).toHaveLength(2);
162+
163+ // Check reasoning
164+ expect(newState.history[0].reasoning?.text).toBe(
165+ "I should use a tool call.",
166+ );
167+
168+ // Check generating message
169+ expect(newState.history[1].message.role).toBe("assistant");
170+ expect(newState.history[1].message.content).toBe("");
171+ expect(newState.history[1].toolCallState?.status).toBe("generating");
172+ expect(newState.history[1].toolCallState?.toolCallId).toBe("1234");
173+
174+ const toolResponseAction = {
175+ type: "session/streamUpdate",
176+ payload: [
177+ {
178+ role: "tool" as const,
179+ toolCallId: "1234",
180+ content: "foo.txt\nbar.txt\nexample.php",
181+ },
182+ {
183+ role: "assistant" as const,
184+ content: "I see, the tool found 3 files.",
185+ },
186+ ],
187+ };
188+ newState = sessionSlice.reducer(newState, toolResponseAction);
189+ expect(newState.history).toHaveLength(4);
190+
191+ // Check tool message
192+ expect(newState.history[2].message.role).toBe("tool");
193+ expect(newState.history[2].message.content).toBe(
194+ "foo.txt\nbar.txt\nexample.php",
195+ );
196+ expect((newState.history[2].message as any).toolCallId).toBe("1234");
197+
198+ // Check final assistant message
199+ expect(newState.history[3].message.role).toBe("assistant");
200+ expect(newState.history[3].message.content).toBe(
201+ "I see, the tool found 3 files.",
202+ );
203+ });
204+ });
205+
206+ describe("Tool Call With Streaming Response", () => {
207+ it("should handle streaming assistant response after tool call", () => {
208+ const initialState = createInitialState();
209+ const toolCallAction = {
210+ type: "session/streamUpdate",
211+ payload: [
212+ {
213+ role: "assistant" as const,
214+ content: "<think>I should use a tool call.</think>",
215+ toolCalls: [
216+ {
217+ id: "1234",
218+ type: "function" as const,
219+ function: {
220+ name: "builtin_ls",
221+ arguments: '{"dirPath":".","recursive":false}',
222+ },
223+ },
224+ ],
225+ },
226+ ],
227+ };
228+
229+ let newState = sessionSlice.reducer(initialState, toolCallAction);
230+ expect(newState.history).toHaveLength(2);
231+
232+ // Check reasoning
233+ expect(newState.history[0].reasoning?.text).toBe(
234+ "I should use a tool call.",
235+ );
236+
237+ // Check generating message
238+ expect(newState.history[1].message.role).toBe("assistant");
239+ expect(newState.history[1].message.content).toBe("");
240+ expect(newState.history[1].toolCallState?.status).toBe("generating");
241+ expect(newState.history[1].toolCallState?.toolCallId).toBe("1234");
242+
243+ const toolResponseAction = {
244+ type: "session/streamUpdate",
245+ payload: [
246+ {
247+ role: "tool" as const,
248+ toolCallId: "1234",
249+ content: "foo.txt\nbar.txt\nexample.php",
250+ },
251+ {
252+ role: "assistant" as const,
253+ content: "<think>",
254+ },
255+ {
256+ role: "assistant" as const,
257+ content: "Good, ",
258+ },
259+ {
260+ role: "assistant" as const,
261+ content: "I received a list",
262+ },
263+ {
264+ role: "assistant" as const,
265+ content: " of files.",
266+ },
267+ {
268+ role: "assistant" as const,
269+ content: "</think>",
270+ },
271+ {
272+ role: "assistant" as const,
273+ content: "\n",
274+ },
275+ {
276+ role: "assistant" as const,
277+ content: "I see, ",
278+ },
279+ {
280+ role: "assistant" as const,
281+ content: "the tool ",
282+ },
283+ {
284+ role: "assistant" as const,
285+ content: "found 3 ",
286+ },
287+ {
288+ role: "assistant" as const,
289+ content: "files.",
290+ },
291+ ],
292+ };
293+
294+ newState = sessionSlice.reducer(newState, toolResponseAction);
295+
296+ expect(newState.history).toHaveLength(4);
297+
298+ // Check tool message
299+ expect(newState.history[2].message.role).toBe("tool");
300+ expect(newState.history[2].message.content).toBe(
301+ "foo.txt\nbar.txt\nexample.php",
302+ );
303+
304+ // Check response message
305+ expect(newState.history[3].message.role).toBe("assistant");
306+ expect(newState.history[3].message.content).toBe(
307+ "I see, the tool found 3 files.",
308+ );
309+ expect(newState.history[3].reasoning?.text).toBe(
310+ "Good, I received a list of files.",
311+ );
312+ expect(newState.history[3].reasoning?.active).toBe(false);
313+ });
314+ });
315+
316+ describe("Edge Cases", () => {
317+ it("should handle empty history gracefully", () => {
318+ const initialState = createInitialState();
319+ initialState.history = [];
320+
321+ const action = {
322+ type: "session/streamUpdate",
323+ payload: [
324+ {
325+ role: "assistant" as const,
326+ content: "Hello",
327+ },
328+ ],
329+ };
330+
331+ const newState = sessionSlice.reducer(initialState, action);
332+
333+ // Should not crash and history should remain empty
334+ expect(newState.history).toHaveLength(0);
335+ });
336+
337+ it("should handle redacted thinking messages", () => {
338+ const initialState = createInitialState();
339+ const action = {
340+ type: "session/streamUpdate",
341+ payload: [
342+ {
343+ role: "thinking" as const,
344+ content: "This should be hidden",
345+ redactedThinking: true,
346+ },
347+ ],
348+ };
349+
350+ const newState = sessionSlice.reducer(initialState, action);
351+
352+ expect(newState.history).toHaveLength(2);
353+ expect(newState.history[1].message.role).toBe("thinking");
354+ expect(newState.history[1].message.content).toBe(
355+ "internal reasoning is hidden due to safety reasons",
356+ );
357+ expect((newState.history[1].message as any).redactedThinking).toBe(true);
358+ });
359+
360+ it("should handle signature updates for thinking messages", () => {
361+ const initialState = createInitialState();
362+ // First add a thinking message
363+ initialState.history.push({
364+ message: {
365+ role: "thinking",
366+ content: "Some thinking",
367+ id: "thinking-message",
368+ },
369+ contextItems: [],
370+ });
371+
372+ const action = {
373+ type: "session/streamUpdate",
374+ payload: [
375+ {
376+ role: "thinking" as const,
377+ signature: "test-signature",
378+ },
379+ ],
380+ };
381+
382+ const newState = sessionSlice.reducer(initialState, action);
383+
384+ expect(newState.history).toHaveLength(2);
385+ expect((newState.history[1].message as any).signature).toBe(
386+ "test-signature",
387+ );
388+ });
389+
390+ it("should accumulate content for same role messages", () => {
391+ const initialState = createInitialState();
392+ // Add an assistant message first
393+ initialState.history.push({
394+ message: {
395+ role: "assistant",
396+ content: "Hello ",
397+ id: "assistant-message",
398+ },
399+ contextItems: [],
400+ });
401+
402+ const action = {
403+ type: "session/streamUpdate",
404+ payload: [
405+ {
406+ role: "assistant" as const,
407+ content: "world!",
408+ },
409+ ],
410+ };
411+
412+ const newState = sessionSlice.reducer(initialState, action);
413+
414+ expect(newState.history).toHaveLength(2);
415+ expect(newState.history[1].message.content).toBe("Hello world!");
416+ });
417+ });
418+});
modified gui/src/redux/slices/sessionSlice.ts +124 −45
@@ -8,6 +8,7 @@
88 import { JSONContent } from "@tiptap/react";
99 import {
1010 ApplyState,
11+ AssistantChatMessage,
1112 ChatHistoryItem,
1213 ChatMessage,
1314 ContextItem,
@@ -18,6 +19,7 @@
1819 RuleWithSource,
1920 Session,
2021 SessionMetadata,
22+ ThinkingChatMessage,
2123 Tool,
2224 } from "core";
2325 import { NEW_SESSION_TITLE } from "core/util/constants";
@@ -330,12 +332,10 @@
330332 streamUpdate: (state, action: PayloadAction<ChatMessage[]>) => {
331333 if (state.history.length) {
332334 for (const message of action.payload) {
333- const lastItem = state.history[state.history.length - 1];
334- const lastMessage = lastItem.message;
335+ let lastItem = state.history[state.history.length - 1];
336+ let lastMessage = lastItem.message;
335337
336338 if (message.role === "thinking" && message.redactedThinking) {
337- console.log("add redacted_thinking blocks");
338-
339339 state.history.push({
340340 message: {
341341 role: "thinking",
@@ -348,6 +348,74 @@
348348 continue;
349349 }
350350
351+ const messageContent = message.content
352+ ? renderChatMessage(message)
353+ : "";
354+
355+ // OpenAI-compatible models in agent mode sometimes send
356+ // all of their data in one message, so we handle that case early.
357+ if (messageContent) {
358+ const thinkMatches = messageContent.match(
359+ /<think>([\s\S]*)<\/think>([\s\S]*)/,
360+ );
361+ if (thinkMatches) {
362+ // The order that they seem to consistently use is:
363+ //
364+ // <think>Thinking text</think>
365+ // Text to show to the user
366+
367+ lastItem.reasoning = {
368+ text: thinkMatches[1].trim(),
369+ startAt: Date.now(),
370+ endAt: Date.now(),
371+ active: false,
372+ };
373+
374+ // This is the chat message that we should show to the user.
375+ // We always need to push this even if it is empty,
376+ // because we cannot attach tool calls to a Thinking message.
377+ // That would break `messageHasToolCallId`.
378+ state.history.push({
379+ message: {
380+ role: "assistant",
381+ content: thinkMatches[2].trim(),
382+ id: uuidv4(),
383+ },
384+ contextItems: [],
385+ });
386+ lastItem = state.history[state.history.length - 1];
387+ lastMessage = lastItem.message;
388+
389+ if (
390+ (message.role === "assistant" || message.role === "thinking") &&
391+ message.toolCalls?.[0]
392+ ) {
393+ // Only support one tool call for now.
394+ // There are further changes required throughout the system
395+ // to support multiple tool calls in a single message from
396+ // OpenAI-compatible providers.
397+ const toolCallDelta = message.toolCalls[0];
398+ const newToolCallState = addToolCallDeltaToState(
399+ toolCallDelta,
400+ lastItem.toolCallState,
401+ );
402+ lastItem.toolCallState = newToolCallState;
403+ // We know this is one of these two types because we just added it
404+ const curMessage = lastMessage as
405+ | AssistantChatMessage
406+ | ThinkingChatMessage;
407+ if (curMessage.toolCalls) {
408+ curMessage.toolCalls.push(newToolCallState.toolCall);
409+ } else {
410+ curMessage.toolCalls = [newToolCallState.toolCall];
411+ }
412+ }
413+
414+ return;
415+ }
416+ }
417+
418+ // The remainder of this function handles streaming messages
351419 if (
352420 lastMessage.role !== message.role ||
353421 // This is for when a tool call comes immediately before/after tool call
@@ -363,7 +431,7 @@
363431 const historyItem: ChatHistoryItemWithMessageId = {
364432 message: {
365433 ...message,
366- content: renderChatMessage(message),
434+ content: "",
367435 id: uuidv4(),
368436 },
369437 contextItems: [],
@@ -376,51 +444,62 @@
376444 );
377445 }
378446 state.history.push(historyItem);
379- } else {
380- // Add to the existing message
381- if (message.content) {
382- const messageContent = renderChatMessage(message);
383- if (messageContent.includes("<think>")) {
384- lastItem.reasoning = {
385- startAt: Date.now(),
386- active: true,
387- text: messageContent.replace("<think>", "").trim(),
388- };
389- } else if (
390- lastItem.reasoning?.active &&
391- messageContent.includes("</think>")
447+ lastItem = state.history[state.history.length - 1];
448+ lastMessage = lastItem.message;
449+ }
450+
451+ // Add to the existing message
452+ if (messageContent) {
453+ if (messageContent.includes("<think>")) {
454+ lastItem.reasoning = {
455+ startAt: Date.now(),
456+ active: true,
457+ text: messageContent.replace("<think>", "").trim(),
458+ };
459+ } else if (
460+ lastItem.reasoning?.active &&
461+ messageContent.includes("</think>")
462+ ) {
463+ const [reasoningEnd, answerStart] =
464+ messageContent.split("</think>");
465+ lastItem.reasoning.text += reasoningEnd.trimEnd();
466+ lastItem.reasoning.active = false;
467+ lastItem.reasoning.endAt = Date.now();
468+ lastMessage.content += answerStart.trimStart();
469+ } else if (lastItem.reasoning?.active) {
470+ if (
471+ lastItem.reasoning.text.length > 0 ||
472+ messageContent.trim().length > 0
392473 ) {
393- const [reasoningEnd, answerStart] =
394- messageContent.split("</think>");
395- lastItem.reasoning.text += reasoningEnd.trimEnd();
396- lastItem.reasoning.active = false;
397- lastItem.reasoning.endAt = Date.now();
398- lastMessage.content += answerStart.trimStart();
399- } else if (lastItem.reasoning?.active) {
400474 lastItem.reasoning.text += messageContent;
401- } else {
402- // Note this only works because new message above
403- // was already rendered from parts to string
404- lastMessage.content += messageContent;
405475 }
406- } else if (message.role === "thinking" && message.signature) {
407- if (lastMessage.role === "thinking") {
408- lastMessage.signature = message.signature;
476+ } else {
477+ // Note this only works because new message above
478+ // was already rendered from parts to string
479+ if (
480+ lastMessage.content.length > 0 ||
481+ messageContent.trim().length > 0
482+ ) {
483+ lastMessage.content += messageContent;
409484 }
410- } else if (
411- message.role === "assistant" &&
412- message.toolCalls?.[0] &&
413- lastMessage.role === "assistant"
414- ) {
415- // Intentionally only supporting one tool call for now.
416- const toolCallDelta = message.toolCalls[0];
417- const newToolCallState = addToolCallDeltaToState(
418- toolCallDelta,
419- lastItem.toolCallState,
420- );
421- lastItem.toolCallState = newToolCallState;
422- lastMessage.toolCalls = [newToolCallState.toolCall];
423485 }
486+ } else if (message.role === "thinking" && message.signature) {
487+ if (lastMessage.role === "thinking") {
488+ lastMessage.signature = message.signature;
489+ }
490+ } else if (
491+ message.role === "assistant" &&
492+ message.toolCalls?.[0] &&
493+ lastMessage.role === "assistant"
494+ ) {
495+ // Intentionally only supporting one tool call for now.
496+ const toolCallDelta = message.toolCalls[0];
497+ const newToolCallState = addToolCallDeltaToState(
498+ toolCallDelta,
499+ lastItem.toolCallState,
500+ );
501+ lastItem.toolCallState = newToolCallState;
502+ lastMessage.toolCalls = [newToolCallState.toolCall];
424503 }
425504 }
426505 }