Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor: refactor client agent runtime (#12482)

Arvin Xub29a533285ba
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index f5ecd2a65ae..f965dad562b 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -553,9 +553,6 @@
}
},
"src/store/chat/agents/createAgentExecutors.ts": {
- "prefer-const": {
- "count": 1
- },
"sort-keys-fix/sort-keys-fix": {
"count": 1
}
@@ -603,11 +600,6 @@
"count": 1
}
},
- "src/store/chat/slices/aiChat/actions/streamingExecutor.ts": {
- "no-unused-private-class-members": {
- "count": 1
- }
- },
"src/store/chat/slices/message/actions/optimisticUpdate.ts": {
"no-unused-private-class-members": {
"count": 1
diff --git a/src/store/chat/slices/aiChat/actions/StreamingHandler.test.ts b/src/store/chat/agents/StreamingHandler.test.ts
similarity index 100%
rename from src/store/chat/slices/aiChat/actions/StreamingHandler.test.ts
rename to src/store/chat/agents/StreamingHandler.test.ts
diff --git a/src/store/chat/slices/aiChat/actions/StreamingHandler.ts b/src/store/chat/agents/StreamingHandler.ts
similarity index 99%
rename from src/store/chat/slices/aiChat/actions/StreamingHandler.ts
rename to src/store/chat/agents/StreamingHandler.ts
index ccb2101ec05..321ac3f1916 100644
--- a/src/store/chat/slices/aiChat/actions/StreamingHandler.ts
+++ b/src/store/chat/agents/StreamingHandler.ts
@@ -9,7 +9,7 @@ import debug from 'debug';
import { throttle } from 'es-toolkit/compat';
import pMap from 'p-map';
-import { cleanSpeakerTag } from '../../../utils/cleanSpeakerTag';
+import { cleanSpeakerTag } from '../utils/cleanSpeakerTag';
import {
type FinishData,
type GroundingData,
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
index 00af02f79a3..79b18a36784 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
@@ -1,8 +1,10 @@
import { type GeneralAgentCallLLMResultPayload } from '@lobechat/agent-runtime';
import { LOADING_FLAT } from '@lobechat/const';
-import { type ChatToolPayload } from '@lobechat/types';
+import { type MessageToolCall } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
+import { chatService } from '@/services/chat';
+
import {
createAssistantMessage,
createCallLLMInstruction,
@@ -18,6 +20,77 @@ import {
expectValidExecutorResult,
} from './helpers';
+// Mock external services at module level
+vi.mock('@/services/chat', () => ({
+ chatService: {
+ createAssistantMessageStream: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: {
+ updateMessage: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ currentActiveTopicSummary: vi.fn().mockReturnValue(undefined),
+ },
+}));
+
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: vi.fn().mockReturnValue({
+ uploadBase64FileWithProgress: vi.fn().mockResolvedValue(null),
+ }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {},
+}));
+
+vi.mock('@/store/agent/store', () => ({
+ getAgentStoreState: vi.fn().mockReturnValue({}),
+}));
+
+/**
+ * Helper to mock chatService.createAssistantMessageStream
+ * Simulates streaming by calling onMessageHandle with chunks then onFinish
+ */
+const mockStreamResponse = (response: {
+ content?: string;
+ finishType?: string;
+ tool_calls?: MessageToolCall[];
+ usage?: any;
+}) => {
+ const { content = '', finishType = 'stop', tool_calls, usage } = response;
+
+ vi.mocked(chatService.createAssistantMessageStream).mockImplementation(async (params: any) => {
+ // Simulate text streaming
+ if (content && params.onMessageHandle) {
+ await params.onMessageHandle({ type: 'text', text: content });
+ }
+
+ // Simulate tool call streaming
+ if (tool_calls && params.onMessageHandle) {
+ await params.onMessageHandle({
+ isAnimationActives: tool_calls.map(() => true),
+ tool_calls,
+ type: 'tool_calls',
+ });
+ }
+
+ // Simulate finish
+ if (params.onFinish) {
+ await params.onFinish(content, {
+ toolCalls: tool_calls,
+ type: finishType,
+ usage,
+ });
+ }
+ });
+};
+
describe('call_llm executor', () => {
describe('Basic Behavior', () => {
it('should create assistant message with LOADING_FLAT content', async () => {
@@ -31,15 +104,11 @@ describe('call_llm executor', () => {
});
const state = createInitialState({ operationId: 'test-session' });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
- const result = await executeWithMockContext({
+ await executeWithMockContext({
executor: 'call_llm',
instruction,
state,
@@ -64,7 +133,7 @@ describe('call_llm executor', () => {
);
});
- it('should call internal_fetchAIChatMessage with correct params', async () => {
+ it('should call chatService.createAssistantMessageStream with correct params', async () => {
// Given
const mockStore = createMockStore();
const context = createTestContext();
@@ -76,11 +145,7 @@ describe('call_llm executor', () => {
});
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -93,13 +158,12 @@ describe('call_llm executor', () => {
});
// Then
- expect(mockStore.internal_fetchAIChatMessage).toHaveBeenCalledWith(
+ expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
expect.objectContaining({
- messageId: expect.any(String),
- messages: [userMsg], // Should exclude assistant message
- model: 'gpt-4',
- provider: 'openai',
- operationId: context.operationId,
+ params: expect.objectContaining({
+ model: 'gpt-4',
+ provider: 'openai',
+ }),
}),
);
});
@@ -111,11 +175,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -141,11 +201,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -174,11 +230,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -193,11 +245,8 @@ describe('call_llm executor', () => {
// Then
expect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();
- expect(mockStore.internal_fetchAIChatMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- messageId: parentId,
- }),
- );
+ // The stream should still be called (message reuse doesn't skip LLM call)
+ expect(chatService.createAssistantMessageStream).toHaveBeenCalled();
});
});
@@ -211,11 +260,7 @@ describe('call_llm executor', () => {
});
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -247,11 +292,7 @@ describe('call_llm executor', () => {
});
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -309,10 +350,8 @@ describe('call_llm executor', () => {
},
});
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
+ mockStreamResponse({
content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
usage: {
totalInputTokens: 50,
totalOutputTokens: 30,
@@ -371,10 +410,8 @@ describe('call_llm executor', () => {
},
});
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
+ mockStreamResponse({
content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
usage: {
totalInputTokens: 100,
totalOutputTokens: 50,
@@ -405,12 +442,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- usage: undefined,
- });
+ mockStreamResponse({ content: 'AI response', usage: undefined });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -435,11 +467,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState({ stepCount: 3 });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'Partial response',
- finishType: 'abort',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'Partial response', finishType: 'abort' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -464,12 +492,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'Partial response',
- finishType: 'abort',
- isFunctionCall: false,
- tool_calls: undefined,
- });
+ mockStreamResponse({ content: 'Partial response', finishType: 'abort' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -500,22 +523,21 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- const toolCalls: ChatToolPayload[] = [
+ const toolCallsRaw: MessageToolCall[] = [
{
id: 'tool_1',
- identifier: 'lobe-web-browsing',
- apiName: 'search',
- arguments: JSON.stringify({ query: 'test' }),
- type: 'default',
+ type: 'function',
+ function: {
+ name: 'lobe-web-browsing____search',
+ arguments: JSON.stringify({ query: 'test' }),
+ },
},
];
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
+ mockStreamResponse({
content: '',
finishType: 'abort',
- isFunctionCall: true,
- tools: toolCalls,
- tool_calls: [{ id: 'tool_1', type: 'function', function: { name: 'search' } }],
+ tool_calls: toolCallsRaw,
});
mockStore.dbMessagesMap[context.messageKey] = [];
@@ -533,8 +555,8 @@ describe('call_llm executor', () => {
expect(payload).toMatchObject({
reason: 'user_cancelled',
hasToolsCalling: true,
- toolsCalling: toolCalls,
});
+ expect(payload.toolsCalling.length).toBeGreaterThan(0);
});
it('should not throw error on abort', async () => {
@@ -544,11 +566,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'Partial',
- finishType: 'abort',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'Partial', finishType: 'abort' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When & Then - should not throw
@@ -573,11 +591,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -600,12 +614,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'Here is the result',
- finishType: 'stop',
- isFunctionCall: false,
- tool_calls: undefined,
- });
+ mockStreamResponse({ content: 'Here is the result' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -635,22 +644,21 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- const toolCalls: ChatToolPayload[] = [
+ const toolCallsRaw: MessageToolCall[] = [
{
id: 'tool_1',
- identifier: 'lobe-web-browsing',
- apiName: 'search',
- arguments: JSON.stringify({ query: 'AI news' }),
- type: 'default',
+ type: 'function',
+ function: {
+ name: 'lobe-web-browsing____search',
+ arguments: JSON.stringify({ query: 'AI news' }),
+ },
},
];
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
+ mockStreamResponse({
content: '',
finishType: 'tool_calls',
- isFunctionCall: true,
- tools: toolCalls,
- tool_calls: [{ id: 'tool_1', type: 'function', function: { name: 'search' } }],
+ tool_calls: toolCallsRaw,
});
mockStore.dbMessagesMap[context.messageKey] = [];
@@ -665,10 +673,8 @@ describe('call_llm executor', () => {
// Then
const payload = result.nextContext!.payload as GeneralAgentCallLLMResultPayload;
- expect(payload).toMatchObject({
- hasToolsCalling: true,
- toolsCalling: toolCalls,
- });
+ expect(payload.hasToolsCalling).toBe(true);
+ expect(payload.toolsCalling.length).toBeGreaterThan(0);
});
it('should increment stepCount', async () => {
@@ -678,11 +684,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState({ stepCount: 5 });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -734,12 +736,7 @@ describe('call_llm executor', () => {
totalTokens: 150,
};
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- usage: stepUsage,
- });
+ mockStreamResponse({ content: 'AI response', usage: stepUsage });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -769,11 +766,7 @@ describe('call_llm executor', () => {
createAssistantMessage({ content: 'Hi there' }),
];
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'Hi there',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'Hi there' });
mockStore.dbMessagesMap[context.messageKey] = updatedMessages;
// When
@@ -800,11 +793,7 @@ describe('call_llm executor', () => {
status: 'running',
});
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -830,13 +819,9 @@ describe('call_llm executor', () => {
const state = createInitialState({
messages: [createUserMessage()],
});
- const originalState = JSON.parse(JSON.stringify(state));
+ const originalState = structuredClone(state);
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [createUserMessage(), createAssistantMessage()];
// When
@@ -885,11 +870,7 @@ describe('call_llm executor', () => {
});
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -902,9 +883,11 @@ describe('call_llm executor', () => {
});
// Then
- expect(mockStore.internal_fetchAIChatMessage).toHaveBeenCalledWith(
+ expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
expect.objectContaining({
- messages: [],
+ params: expect.objectContaining({
+ messages: [],
+ }),
}),
);
expect(result).toBeDefined();
@@ -917,36 +900,37 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- const toolCalls: ChatToolPayload[] = [
+ const toolCallsRaw: MessageToolCall[] = [
{
id: 'tool_1',
- identifier: 'lobe-web-browsing',
- apiName: 'search',
- arguments: JSON.stringify({ query: 'AI' }),
- type: 'default',
+ type: 'function',
+ function: {
+ name: 'lobe-web-browsing____search',
+ arguments: JSON.stringify({ query: 'AI' }),
+ },
},
{
id: 'tool_2',
- identifier: 'lobe-web-browsing',
- apiName: 'craw',
- arguments: JSON.stringify({ url: 'https://example.com' }),
- type: 'default',
+ type: 'function',
+ function: {
+ name: 'lobe-web-browsing____craw',
+ arguments: JSON.stringify({ url: 'https://example.com' }),
+ },
},
{
id: 'tool_3',
- identifier: 'lobe-image-generator',
- apiName: 'generate',
- arguments: JSON.stringify({ prompt: 'AI art' }),
- type: 'default',
+ type: 'function',
+ function: {
+ name: 'lobe-image-generator____generate',
+ arguments: JSON.stringify({ prompt: 'AI art' }),
+ },
},
];
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
+ mockStreamResponse({
content: '',
finishType: 'tool_calls',
- isFunctionCall: true,
- tools: toolCalls,
- tool_calls: toolCalls.map((t) => ({ id: t.id, type: 'function' as const })),
+ tool_calls: toolCallsRaw,
});
mockStore.dbMessagesMap[context.messageKey] = [];
@@ -972,11 +956,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState({ messages: [createUserMessage()] });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
// dbMessagesMap[messageKey] doesn't exist
// When
@@ -1012,11 +992,7 @@ describe('call_llm executor', () => {
role: 'assistant',
content: LOADING_FLAT,
});
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -1029,9 +1005,13 @@ describe('call_llm executor', () => {
});
// Then - should filter out the assistant message with matching ID
- expect(mockStore.internal_fetchAIChatMessage).toHaveBeenCalledWith(
+ expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
expect.objectContaining({
- messages: expect.not.arrayContaining([expect.objectContaining({ id: 'msg_assistant' })]),
+ params: expect.objectContaining({
+ messages: expect.not.arrayContaining([
+ expect.objectContaining({ id: 'msg_assistant' }),
+ ]),
+ }),
}),
);
});
@@ -1048,15 +1028,11 @@ describe('call_llm executor', () => {
});
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'Claude response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'Claude response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
- const result = await executeWithMockContext({
+ await executeWithMockContext({
executor: 'call_llm',
instruction,
state,
@@ -1074,10 +1050,12 @@ describe('call_llm executor', () => {
operationId: expect.any(String),
}),
);
- expect(mockStore.internal_fetchAIChatMessage).toHaveBeenCalledWith(
+ expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
expect.objectContaining({
- model: 'claude-3-opus',
- provider: 'anthropic',
+ params: expect.objectContaining({
+ model: 'claude-3-opus',
+ provider: 'anthropic',
+ }),
}),
);
});
@@ -1098,11 +1076,7 @@ describe('call_llm executor', () => {
createAssistantMessage(),
];
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = messages;
// When
@@ -1125,11 +1099,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState({ operationId: 'custom-session-123' });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -1142,7 +1112,6 @@ describe('call_llm executor', () => {
});
// Then
- // Note: AgentRuntimeContext.session uses sessionId for backward compatibility
expect(result.nextContext!.session!.sessionId).toBe('custom-session-123');
});
});
@@ -1160,7 +1129,7 @@ describe('call_llm executor', () => {
type: 'execAgentRuntime',
status: 'running',
context: {
- sessionId: 'test-session',
+ agentId: 'test-session',
topicId: 'test-topic',
threadId,
},
@@ -1172,15 +1141,11 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
- const result = await executeWithMockContext({
+ await executeWithMockContext({
executor: 'call_llm',
instruction,
state,
@@ -1206,11 +1171,7 @@ describe('call_llm executor', () => {
const instruction = createCallLLMInstruction();
const state = createInitialState();
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -1236,11 +1197,11 @@ describe('call_llm executor', () => {
describe('Group Orchestration: subAgentId Support', () => {
it('should use subAgentId for message.agentId when present in operation context', async () => {
- // Given - Group orchestration scenario where subAgentId is the actual executing agent
+ // Given
const mockStore = createMockStore();
const context = createTestContext({
- agentId: 'supervisor-agent', // Main agent (supervisor)
- subAgentId: 'worker-agent', // Actual executing agent
+ agentId: 'supervisor-agent',
+ subAgentId: 'worker-agent',
topicId: 'group-topic',
});
const instruction = createCallLLMInstruction({
@@ -1250,11 +1211,7 @@ describe('call_llm executor', () => {
});
const state = createInitialState({ operationId: context.operationId });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response from worker agent',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response from worker agent' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -1266,10 +1223,10 @@ describe('call_llm executor', () => {
context,
});
- // Then - message should be created with subAgentId as the agentId
+ // Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
expect.objectContaining({
- agentId: 'worker-agent', // Should use subAgentId, not agentId
+ agentId: 'worker-agent',
role: 'assistant',
}),
expect.objectContaining({
@@ -1279,12 +1236,11 @@ describe('call_llm executor', () => {
});
it('should fall back to agentId when subAgentId is not present', async () => {
- // Given - Normal scenario without subAgentId
+ // Given
const mockStore = createMockStore();
const context = createTestContext({
agentId: 'normal-agent',
topicId: 'normal-topic',
- // No subAgentId
});
const instruction = createCallLLMInstruction({
model: 'gpt-4',
@@ -1293,11 +1249,7 @@ describe('call_llm executor', () => {
});
const state = createInitialState({ operationId: context.operationId });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -1309,10 +1261,10 @@ describe('call_llm executor', () => {
context,
});
- // Then - message should be created with agentId
+ // Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
expect.objectContaining({
- agentId: 'normal-agent', // Should use agentId when no subAgentId
+ agentId: 'normal-agent',
role: 'assistant',
}),
expect.objectContaining({
@@ -1322,7 +1274,7 @@ describe('call_llm executor', () => {
});
it('should pass groupId to message when present in operation context', async () => {
- // Given - Group chat scenario
+ // Given
const mockStore = createMockStore();
const context = createTestContext({
agentId: 'supervisor-agent',
@@ -1337,11 +1289,7 @@ describe('call_llm executor', () => {
});
const state = createInitialState({ operationId: context.operationId });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -1353,7 +1301,7 @@ describe('call_llm executor', () => {
context,
});
- // Then - message should be created with groupId
+ // Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
expect.objectContaining({
groupId: 'group-123',
@@ -1367,12 +1315,11 @@ describe('call_llm executor', () => {
});
it('should not include groupId when not in group chat context', async () => {
- // Given - Normal (non-group) scenario
+ // Given
const mockStore = createMockStore();
const context = createTestContext({
agentId: 'normal-agent',
topicId: 'normal-topic',
- // No groupId
});
const instruction = createCallLLMInstruction({
model: 'gpt-4',
@@ -1381,11 +1328,7 @@ describe('call_llm executor', () => {
});
const state = createInitialState({ operationId: context.operationId });
- mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({
- content: 'AI response',
- finishType: 'stop',
- isFunctionCall: false,
- });
+ mockStreamResponse({ content: 'AI response' });
mockStore.dbMessagesMap[context.messageKey] = [];
// When
@@ -1397,10 +1340,9 @@ describe('call_llm executor', () => {
context,
});
- // Then - message should be created without groupId (undefined)
+ // Then
expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
expect.objectContaining({
- groupId: undefined,
agentId: 'normal-agent',
role: 'assistant',
}),
@@ -1408,6 +1350,194 @@ describe('call_llm executor', () => {
operationId: expect.any(String),
}),
);
+ // Verify groupId is not in the call (undefined)
+ const callArgs = vi.mocked(mockStore.optimisticCreateMessage).mock.calls[0][0];
+ expect(callArgs.groupId).toBeUndefined();
+ });
+ });
+
+ describe('Supervisor Metadata', () => {
+ it('should add isSupervisor metadata when operation context indicates supervisor', async () => {
+ // Given
+ const mockStore = createMockStore();
+ const context = createTestContext({
+ agentId: 'supervisor-agent',
+ topicId: 'group-topic',
+ });
+
+ // Setup operation with isSupervisor flag
+ mockStore.operations[context.operationId] = {
+ id: context.operationId,
+ type: 'execAgentRuntime',
+ status: 'running',
+ context: {
+ agentId: 'supervisor-agent',
+ topicId: 'group-topic',
+ isSupervisor: true,
+ },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ childOperationIds: [],
+ };
+
+ const instruction = createCallLLMInstruction({
+ model: 'gpt-4',
+ provider: 'openai',
+ messages: [createUserMessage()],
+ });
+ const state = createInitialState({ operationId: context.operationId });
+
+ mockStreamResponse({ content: 'Supervisor response' });
+ mockStore.dbMessagesMap[context.messageKey] = [];
+
+ // When
+ await executeWithMockContext({
+ executor: 'call_llm',
+ instruction,
+ state,
+ mockStore,
+ context,
+ });
+
+ // Then
+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: { isSupervisor: true },
+ role: 'assistant',
+ }),
+ expect.objectContaining({
+ operationId: expect.any(String),
+ }),
+ );
+ });
+
+ it('should not add isSupervisor metadata for normal agents', async () => {
+ // Given
+ const mockStore = createMockStore();
+ const context = createTestContext({
+ agentId: 'normal-agent',
+ topicId: 'normal-topic',
+ });
+ const instruction = createCallLLMInstruction({
+ model: 'gpt-4',
+ provider: 'openai',
+ messages: [createUserMessage()],
+ });
+ const state = createInitialState({ operationId: context.operationId });
+
+ mockStreamResponse({ content: 'Normal response' });
+ mockStore.dbMessagesMap[context.messageKey] = [];
+
+ // When
+ await executeWithMockContext({
+ executor: 'call_llm',
+ instruction,
+ state,
+ mockStore,
+ context,
+ });
+
+ // Then
+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: undefined,
+ role: 'assistant',
+ }),
+ expect.objectContaining({
+ operationId: expect.any(String),
+ }),
+ );
+ });
+ });
+
+ describe('createAssistantMessage flag', () => {
+ it('should create message even when skipCreateFirstMessage is true if createAssistantMessage is explicitly true', async () => {
+ // Given - This scenario happens after compression, where a new assistant message is needed
+ const mockStore = createMockStore();
+ const context = createTestContext({ parentId: 'msg_parent' });
+ const instruction = createCallLLMInstruction({
+ createAssistantMessage: true,
+ });
+ const state = createInitialState();
+
+ mockStreamResponse({ content: 'Post-compression response' });
+ mockStore.dbMessagesMap[context.messageKey] = [];
+
+ // When
+ await executeWithMockContext({
+ executor: 'call_llm',
+ instruction,
+ state,
+ mockStore,
+ context,
+ skipCreateFirstMessage: true,
+ });
+
+ // Then - should still create a new assistant message
+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ role: 'assistant',
+ content: LOADING_FLAT,
+ }),
+ expect.objectContaining({
+ operationId: expect.any(String),
+ }),
+ );
+ });
+
+ it('should skip message creation only on first call when skipCreateFirstMessage is true', async () => {
+ // Given
+ const mockStore = createMockStore();
+ const context = createTestContext({ parentId: 'msg_parent' });
+ const instruction1 = createCallLLMInstruction();
+ const instruction2 = createCallLLMInstruction({ createAssistantMessage: undefined });
+ const state = createInitialState();
+
+ mockStreamResponse({ content: 'AI response' });
+ mockStore.dbMessagesMap[context.messageKey] = [];
+
+ // Ensure operation exists for the context
+ mockStore.operations[context.operationId] = {
+ id: context.operationId,
+ type: 'execAgentRuntime',
+ status: 'running',
+ context: {
+ agentId: context.agentId,
+ topicId: context.topicId,
+ messageId: context.parentId,
+ },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ childOperationIds: [],
+ };
+
+ // When - First call should skip, second should create
+ const { createAgentExecutors } = await import('@/store/chat/agents/createAgentExecutors');
+ const executors = createAgentExecutors({
+ agentConfig: {
+ agentConfig: { model: 'gpt-4', provider: 'openai' } as any,
+ chatConfig: {} as any,
+ isBuiltinAgent: false,
+ plugins: [],
+ },
+ get: () => mockStore,
+ messageKey: context.messageKey,
+ operationId: context.operationId,
+ parentId: context.parentId,
+ skipCreateFirstMessage: true,
+ });
+
+ await executors.call_llm!(instruction1, state);
+
+ // Then - First call should NOT create message
+ expect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();
+
+ // When - Second call
+ mockStreamResponse({ content: 'Second response' });
+ await executors.call_llm!(instruction2, state);
+
+ // Then - Second call SHOULD create message
+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalled();
});
});
});
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts b/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts
index c3102fe7fd4..16902c1e5d6 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/fixtures/mockStore.ts
@@ -58,10 +58,20 @@ export const createMockStore = (overrides: Partial<ChatStore> = {}): ChatStore =
// AI chat methods
internal_dispatchMessage: vi.fn(),
- internal_fetchAIChatMessage: vi.fn().mockResolvedValue(undefined),
-
internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({ error: null }),
+ internal_toggleToolCallingStreaming: vi.fn(),
+
+ internal_transformToolCalls: vi.fn().mockImplementation((toolCalls: any[]) =>
+ toolCalls.map((tc: any) => ({
+ apiName: tc.function?.name?.split('____')[1] || tc.function?.name || 'unknown',
+ arguments: tc.function?.arguments || '{}',
+ id: tc.id,
+ identifier: tc.function?.name?.split('____')[0] || 'unknown',
+ type: 'default',
+ })),
+ ),
+
messageOperationMap,
onOperationCancel: vi.fn(),
@@ -86,6 +96,8 @@ export const createMockStore = (overrides: Partial<ChatStore> = {}): ChatStore =
optimisticUpdateMessageContent: vi.fn().mockResolvedValue(undefined),
+ optimisticUpdateMessageError: vi.fn().mockResolvedValue(undefined),
+
optimisticUpdateMessagePlugin: vi.fn().mockResolvedValue(undefined),
optimisticUpdateMessagePluginError: vi.fn().mockResolvedValue(undefined),
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/assertions.ts b/src/store/chat/agents/__tests__/createAgentExecutors/helpers/assertions.ts
index 424cfae2eed..263d2cf3c3b 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/assertions.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/helpers/assertions.ts
@@ -114,20 +114,6 @@ export const expectMessagePluginUpdated = (
}
};
-/**
- * Assert that internal_fetchAIChatMessage was called with correct params
- */
-export const expectFetchAIChatMessageCalled = (mockStore: ChatStore, messageId?: string) => {
- if (messageId) {
- expect(mockStore.internal_fetchAIChatMessage).toHaveBeenCalledWith(
- messageId,
- expect.anything(),
- );
- } else {
- expect(mockStore.internal_fetchAIChatMessage).toHaveBeenCalled();
- }
-};
-
/**
* Assert that internal_invokeDifferentTypePlugin was called
*/
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 76b678ca7b3..1919c7a12a9 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -25,6 +25,9 @@ import {
type ChatToolPayload,
type ConversationContext,
type CreateMessageParams,
+ type MessageToolCall,
+ type ModelUsage,
+ TraceNameMap,
} from '@lobechat/types';
import debug from 'debug';
import pMap from 'p-map';
@@ -38,8 +41,13 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import { getAgentStoreState } from '@/store/agent/store';
import { type ChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { getFileStoreState } from '@/store/file/store';
import { sleep } from '@/utils/sleep';
+import { topicSelectors } from '../selectors';
+import { StreamingHandler } from './StreamingHandler';
+import { type StreamChunk } from './types/streaming';
+
const log = debug('lobe-store:agent-executors');
// Tool pricing configuration (USD per call)
@@ -169,33 +177,214 @@ export const createAgentExecutors = (context: {
llmPayload.tools?.length ?? 0,
);
- // Call existing internal_fetchAIChatMessage
- // This method already handles:
- // - Stream processing (text, tool_calls, reasoning, grounding, base64_image)
- // - UI updates via dispatchMessage
- // - Loading state management
- // - Error handling
- // Use messages from state (already contains full conversation history)
- const messages = llmPayload.messages.filter((message) => message.id !== assistantMessageId);
+ // ======== Inlined streaming logic (previously internal_fetchAIChatMessage) ========
const {
- isFunctionCall,
- content,
- tools,
- usage: currentStepUsage,
- tool_calls,
- finishType,
- } = await context.get().internal_fetchAIChatMessage({
- messageId: assistantMessageId,
- messages,
- model: llmPayload.model,
- provider: llmPayload.provider,
- operationId: context.operationId,
- agentConfig: context.agentConfig, // Pass pre-resolved config
- // Pass runtime context for page editor injection
+ optimisticUpdateMessageContent,
+ internal_dispatchMessage,
+ internal_toggleToolCallingStreaming,
+ } = context.get();
+
+ // Get agentId, topicId, groupId and abortController from operation
+ const operation = context.get().operations[context.operationId];
+ if (!operation) {
+ throw new Error(`Operation not found: ${context.operationId}`);
+ }
+ const { subAgentId, groupId, topicId } = operation.context;
+ const abortController = operation.abortController;
+
+ // In group orchestration, subAgentId is the actual responding agent
+ const agentId = groupId && subAgentId ? subAgentId : operation.context.agentId!;
+
+ const traceId = operation.metadata?.traceId;
+
+ const fetchContext = { ...operation.context, agentId };
+
+ const { agentConfig: agentConfigData, chatConfig } = context.agentConfig;
+
+ let finalUsage: ModelUsage | undefined;
+ let finalToolCalls: MessageToolCall[] | undefined;
+
+ // Create streaming handler with callbacks
+ const handler = new StreamingHandler(
+ {
+ messageId: assistantMessageId,
+ operationId: context.operationId,
+ agentId,
+ groupId,
+ topicId,
+ },
+ {
+ onContentUpdate: (content, reasoning, contentMetadata) => {
+ internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: {
+ content,
+ reasoning,
+ ...(contentMetadata && {
+ metadata: {
+ isMultimodal: contentMetadata.isMultimodal,
+ tempDisplayContent: contentMetadata.tempDisplayContent,
+ },
+ }),
+ },
+ },
+ { operationId: context.operationId },
+ );
+ },
+ onReasoningUpdate: (reasoning) => {
+ internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: { reasoning },
+ },
+ { operationId: context.operationId },
+ );
+ },
+ onToolCallsUpdate: (tools) => {
+ internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: { tools },
+ },
+ { operationId: context.operationId },
+ );
+ },
+ onGroundingUpdate: (grounding) => {
+ internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: { search: grounding },
+ },
+ { operationId: context.operationId },
+ );
+ },
+ onImagesUpdate: (images) => {
+ internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: { imageList: images },
+ },
+ { operationId: context.operationId },
+ );
+ },
+ onReasoningStart: () => {
+ const { operationId: reasoningOpId } = context.get().startOperation({
+ type: 'reasoning',
+ context: { ...fetchContext, messageId: assistantMessageId },
+ parentOperationId: context.operationId,
+ });
+ context.get().associateMessageWithOperation(assistantMessageId, reasoningOpId);
+ return reasoningOpId;
+ },
+ onReasoningComplete: (opId) => context.get().completeOperation(opId),
+ uploadBase64Image: (data) =>
+ getFileStoreState()
+ .uploadBase64FileWithProgress(data)
+ .then((file) => ({
+ id: file?.id,
+ url: file?.url,
+ alt: file?.filename || file?.id,
+ })),
+ transformToolCalls: context.get().internal_transformToolCalls,
+ toggleToolCallingStreaming: internal_toggleToolCallingStreaming,
+ },
+ );
+
+ const messages = llmPayload.messages.filter((message) => message.id !== assistantMessageId);
+
+ const historySummary = chatConfig.enableCompressHistory
+ ? topicSelectors.currentActiveTopicSummary(context.get())
+ : undefined;
+
+ await chatService.createAssistantMessageStream({
+ abortController,
+ params: {
+ agentId: agentId || undefined,
+ groupId,
+ messages,
+ model: llmPayload.model,
+ provider: llmPayload.provider,
+ resolvedAgentConfig: context.agentConfig,
+ topicId: topicId ?? undefined,
+ ...agentConfigData.params,
+ },
+ historySummary: historySummary?.content,
initialContext: runtimeContext?.initialContext,
stepContext: runtimeContext?.stepContext,
+ trace: {
+ traceId,
+ topicId: topicId ?? undefined,
+ traceName: TraceNameMap.Conversation,
+ },
+ onErrorHandle: async (error) => {
+ await context.get().optimisticUpdateMessageError(assistantMessageId, error, {
+ operationId: context.operationId,
+ });
+ },
+ onFinish: async (
+ content,
+ { traceId, observationId, toolCalls, reasoning, grounding, usage, speed, type },
+ ) => {
+ if (traceId) {
+ messageService.updateMessage(
+ assistantMessageId,
+ { traceId, observationId: observationId ?? undefined },
+ { agentId, groupId, topicId },
+ );
+ }
+
+ const result = await handler.handleFinish({
+ traceId,
+ observationId,
+ toolCalls,
+ reasoning,
+ grounding,
+ usage,
+ speed,
+ type,
+ });
+
+ finalUsage = result.usage;
+ finalToolCalls = result.toolCalls;
+
+ await optimisticUpdateMessageContent(
+ assistantMessageId,
+ result.content,
+ {
+ tools: result.tools,
+ reasoning: result.metadata.reasoning,
+ search: result.metadata.search,
+ imageList: result.metadata.imageList,
+ metadata: {
+ ...result.metadata.usage,
+ ...result.metadata.performance,
+ performance: result.metadata.performance,
+ usage: result.metadata.usage,
+ finishType: result.metadata.finishType,
+ ...(result.metadata.isMultimodal && { isMultimodal: true }),
+ },
+ },
+ { operationId: context.operationId },
+ );
+ },
+ onMessageHandle: async (chunk) => {
+ handler.handleChunk(chunk as StreamChunk);
+ },
});
+ const isFunctionCall = handler.getIsFunctionCall();
+ const content = handler.getOutput();
+ const tools = handler.getTools();
+ const currentStepUsage = finalUsage;
+ const tool_calls = finalToolCalls;
+ const finishType = handler.getFinishType();
+
log(`[${sessionLogId}] finish model-runtime calling`);
// Get latest messages from store (already updated by internal_fetchAIChatMessage)
@@ -328,9 +517,8 @@ export const createAgentExecutors = (context: {
// Get context from operation
const opContext = getOperationContext();
- let toolOperationId: string | undefined;
// ============ Create toolCalling operation (top-level) ============
- const { operationId } = context.get().startOperation({
+ const { operationId: toolOperationId } = context.get().startOperation({
type: 'toolCalling',
context: {
agentId: opContext.agentId!,
@@ -345,7 +533,6 @@ export const createAgentExecutors = (context: {
tool_call_id: chatToolPayload.id,
},
});
- toolOperationId = operationId;
try {
// Get assistant message to extract groupId
@@ -691,7 +878,7 @@ export const createAgentExecutors = (context: {
} catch (error) {
log('[%s][call_tool] ERROR: Tool execution failed: %O', sessionLogId, error);
- events.push({ error: error, type: 'error' });
+ events.push({ error, type: 'error' });
// Return current state on error (no state change)
return { events, newState: state };
diff --git a/src/store/chat/slices/aiChat/actions/types/streaming.ts b/src/store/chat/agents/types/streaming.ts
similarity index 100%
rename from src/store/chat/slices/aiChat/actions/types/streaming.ts
rename to src/store/chat/agents/types/streaming.ts
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/StreamingHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/StreamingHandler.test.ts
deleted file mode 100644
index bf3c09ebbdd..00000000000
--- a/src/store/chat/slices/aiChat/actions/__tests__/StreamingHandler.test.ts
+++ /dev/null
@@ -1,302 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-
-import { StreamingHandler } from '../StreamingHandler';
-import type { StreamChunk, StreamingCallbacks, StreamingContext } from '../types/streaming';
-
-// Helper to create a mock streaming context
-const createContext = (overrides: Partial<StreamingContext> = {}): StreamingContext => ({
- agentId: 'test-agent',
- messageId: 'test-message',
- operationId: 'test-op',
- ...overrides,
-});
-
-// Helper to create mock callbacks
-const createCallbacks = (overrides: Partial<StreamingCallbacks> = {}): StreamingCallbacks => ({
- onContentUpdate: vi.fn(),
- onGroundingUpdate: vi.fn(),
- onImagesUpdate: vi.fn(),
- onReasoningComplete: vi.fn(),
- onReasoningStart: vi.fn().mockReturnValue('reasoning-op-id'),
- onReasoningUpdate: vi.fn(),
- onToolCallsUpdate: vi.fn(),
- toggleToolCallingStreaming: vi.fn(),
- transformToolCalls: vi.fn().mockReturnValue([]),
- uploadBase64Image: vi
- .fn()
- .mockResolvedValue({ id: 'img-id', url: 'https://uploaded.url/img.png' }),
- ...overrides,
-});
-
-describe('StreamingHandler', () => {
- describe('content_part image handling', () => {
- it('should pass contentMetadata with isMultimodal when content_part image chunks are received', () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- // Send a text content_part
- handler.handleChunk({
- type: 'content_part',
- partType: 'text',
- content: 'Here is an image: ',
- });
-
- // Send an image content_part
- handler.handleChunk({
- type: 'content_part',
- partType: 'image',
- content: 'base64imagedata',
- mimeType: 'image/png',
- });
-
- // The last onContentUpdate call should include contentMetadata
- const lastCall = (callbacks.onContentUpdate as ReturnType<typeof vi.fn>).mock.calls.at(-1);
- expect(lastCall).toBeDefined();
-
- const [content, reasoning, contentMetadata] = lastCall!;
- expect(content).toBe('Here is an image: ');
- expect(contentMetadata).toBeDefined();
- expect(contentMetadata.isMultimodal).toBe(true);
- expect(contentMetadata.tempDisplayContent).toBeDefined();
- // tempDisplayContent should be a serialized JSON string containing the parts
- const parsed = JSON.parse(contentMetadata.tempDisplayContent);
- expect(parsed).toHaveLength(2);
- expect(parsed[0]).toEqual({ type: 'text', text: 'Here is an image: ' });
- expect(parsed[1]).toEqual(
- expect.objectContaining({
- type: 'image',
- image: expect.stringContaining('data:image/png;base64,'),
- }),
- );
- });
-
- it('should NOT pass contentMetadata when only text content_part chunks are received', () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({
- type: 'content_part',
- partType: 'text',
- content: 'Hello ',
- });
- handler.handleChunk({
- type: 'content_part',
- partType: 'text',
- content: 'world',
- });
-
- const lastCall = (callbacks.onContentUpdate as ReturnType<typeof vi.fn>).mock.calls.at(-1);
- expect(lastCall).toBeDefined();
-
- const [content, _reasoning, contentMetadata] = lastCall!;
- expect(content).toBe('Hello world');
- // No contentMetadata when there are no images
- expect(contentMetadata).toBeUndefined();
- });
-
- it('should include isMultimodal in final result metadata when content has images', async () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- // Send mixed content
- handler.handleChunk({
- type: 'content_part',
- partType: 'text',
- content: 'A cat: ',
- });
- handler.handleChunk({
- type: 'content_part',
- partType: 'image',
- content: 'base64catimage',
- mimeType: 'image/jpeg',
- });
-
- const result = await handler.handleFinish({});
-
- expect(result.metadata.isMultimodal).toBe(true);
- // Content should be serialized JSON containing text + image parts
- const parsed = JSON.parse(result.content);
- expect(parsed).toHaveLength(2);
- expect(parsed[0].type).toBe('text');
- expect(parsed[1].type).toBe('image');
- });
-
- it('should NOT include isMultimodal in final result when only text content', async () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({ type: 'text', text: 'Hello world' });
-
- const result = await handler.handleFinish({});
-
- expect(result.metadata.isMultimodal).toBeUndefined();
- expect(result.content).toBe('Hello world');
- });
- });
-
- describe('text chunk handling', () => {
- it('should accumulate text chunks and notify via onContentUpdate', () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({ type: 'text', text: 'Hello' });
- handler.handleChunk({ type: 'text', text: ' World' });
-
- expect(callbacks.onContentUpdate).toHaveBeenCalledTimes(2);
- expect(handler.getOutput()).toBe('Hello World');
- });
- });
-
- describe('reasoning chunk handling', () => {
- it('should track reasoning content and start/end timing', () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- // Reasoning starts
- handler.handleChunk({ type: 'reasoning', text: 'Let me think...' });
- expect(callbacks.onReasoningStart).toHaveBeenCalledTimes(1);
- expect(callbacks.onReasoningUpdate).toHaveBeenCalledWith({ content: 'Let me think...' });
-
- // Text ends reasoning
- handler.handleChunk({ type: 'text', text: 'Answer' });
- expect(handler.getThinkingDuration()).toBeDefined();
- expect(handler.getThinkingDuration()).toBeGreaterThanOrEqual(0);
- });
-
- it('should include reasoning in final result with signature', async () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({ type: 'reasoning', text: 'Thinking' });
- handler.handleChunk({ type: 'text', text: 'Answer' });
-
- const result = await handler.handleFinish({
- reasoning: { content: 'Thinking', signature: 'test-sig' },
- });
-
- expect(result.metadata.reasoning).toBeDefined();
- expect(result.metadata.reasoning?.content).toBe('Thinking');
- expect(result.metadata.reasoning?.signature).toBe('test-sig');
- // Duration may be 0 in fast tests (which becomes undefined due to `0 && ...` check)
- // So we just verify it's a number or undefined
- expect(
- result.metadata.reasoning?.duration === undefined ||
- typeof result.metadata.reasoning?.duration === 'number',
- ).toBe(true);
- });
- });
-
- describe('reasoning_part with images', () => {
- it('should handle reasoning_part image chunks and report isMultimodal', () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({
- type: 'reasoning_part',
- partType: 'text',
- content: 'Thinking about image: ',
- });
- handler.handleChunk({
- type: 'reasoning_part',
- partType: 'image',
- content: 'base64data',
- mimeType: 'image/png',
- });
-
- const lastCall = (callbacks.onReasoningUpdate as ReturnType<typeof vi.fn>).mock.calls.at(-1);
- expect(lastCall).toBeDefined();
- expect(lastCall![0].isMultimodal).toBe(true);
- expect(lastCall![0].tempDisplayContent).toBeDefined();
- });
- });
-
- describe('tool_calls handling', () => {
- it('should mark as function call when tool_calls chunk is received', () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({
- type: 'tool_calls',
- tool_calls: [
- { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },
- ],
- isAnimationActives: [true],
- });
-
- expect(handler.getIsFunctionCall()).toBe(true);
- expect(callbacks.toggleToolCallingStreaming).toHaveBeenCalledWith('test-message', [true]);
- });
- });
-
- describe('handleFinish with tool calls', () => {
- it('should process final tool calls and set isFunctionCall', async () => {
- const callbacks = createCallbacks({
- transformToolCalls: vi.fn().mockReturnValue([{ identifier: 'test', arguments: '{}' }]),
- });
- const handler = new StreamingHandler(createContext(), callbacks);
-
- const result = await handler.handleFinish({
- toolCalls: [{ id: 'tool-1', type: 'function', function: { name: 'test', arguments: '' } }],
- });
-
- expect(result.isFunctionCall).toBe(true);
- expect(result.tools).toBeDefined();
- expect(result.tools).toHaveLength(1);
- });
- });
-
- describe('base64_image handling', () => {
- it('should dispatch images immediately and upload async', async () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({
- type: 'base64_image',
- image: { id: 'img-1', data: 'base64data' },
- images: [{ id: 'img-1', data: 'base64data' }],
- });
-
- expect(callbacks.onImagesUpdate).toHaveBeenCalledWith([
- { alt: 'img-1', id: 'img-1', url: 'base64data' },
- ]);
-
- // After finish, uploaded images should be in the result
- const result = await handler.handleFinish({});
- expect(result.metadata.imageList).toBeDefined();
- expect(result.metadata.imageList).toHaveLength(1);
- expect(result.metadata.imageList![0].url).toBe('https://uploaded.url/img.png');
- });
- });
-
- describe('grounding handling', () => {
- it('should forward citations to onGroundingUpdate', () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({
- type: 'grounding',
- grounding: {
- citations: [{ url: 'https://example.com', title: 'Example' }],
- searchQueries: ['query'],
- },
- } as any);
-
- expect(callbacks.onGroundingUpdate).toHaveBeenCalledWith({
- citations: [{ url: 'https://example.com', title: 'Example' }],
- searchQueries: ['query'],
- });
- });
-
- it('should skip grounding when no citations', () => {
- const callbacks = createCallbacks();
- const handler = new StreamingHandler(createContext(), callbacks);
-
- handler.handleChunk({
- type: 'grounding',
- grounding: { citations: [], searchQueries: [] },
- } as any);
-
- expect(callbacks.onGroundingUpdate).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
index 0a354ad8431..e9566d39414 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
@@ -4,7 +4,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { chatService } from '@/services/chat';
import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';
-import { messageService } from '@/services/message';
import { useChatStore } from '../../../../store';
import {
@@ -40,618 +39,6 @@ afterEach(() => {
});
describe('StreamingExecutor actions', () => {
- describe('internal_fetchAIChatMessage', () => {
- it('should fetch and return AI chat response', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({ type: 'text', text: TEST_CONTENT.AI_RESPONSE } as any);
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});
- });
-
- await act(async () => {
- const response = await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- agentConfig: createMockResolvedAgentConfig(),
- });
- expect(response.isFunctionCall).toEqual(false);
- expect(response.content).toEqual(TEST_CONTENT.AI_RESPONSE);
- });
-
- streamSpy.mockRestore();
- });
-
- it('should handle streaming errors gracefully', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onErrorHandle }) => {
- await onErrorHandle?.({ type: 'InvalidProviderAPIKey', message: 'Network error' } as any);
- });
-
- const updateMessageSpy = vi.spyOn(messageService, 'updateMessage');
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- model: 'gpt-4o-mini',
- provider: 'openai',
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- expect(updateMessageSpy).toHaveBeenCalledWith(
- TEST_IDS.ASSISTANT_MESSAGE_ID,
- expect.objectContaining({
- error: expect.objectContaining({ type: 'InvalidProviderAPIKey' }),
- }),
- expect.objectContaining({
- agentId: TEST_IDS.SESSION_ID,
- topicId: TEST_IDS.TOPIC_ID,
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should handle tool call chunks during streaming', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({
- type: 'tool_calls',
- isAnimationActives: [true],
- tool_calls: [
- { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },
- ],
- } as any);
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
- toolCalls: [
- { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },
- ],
- } as any);
- });
-
- await act(async () => {
- const response = await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- agentConfig: createMockResolvedAgentConfig(),
- });
- expect(response.isFunctionCall).toEqual(true);
- });
-
- streamSpy.mockRestore();
- });
-
- it('should handle text chunks during streaming', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
-
- // Create operation for this test
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: TEST_IDS.SESSION_ID,
- topicId: null,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test AI Generation',
- });
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({ type: 'text', text: 'Hello' } as any);
- await onMessageHandle?.({ type: 'text', text: ' World' } as any);
- await onFinish?.('Hello World', {} as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- id: TEST_IDS.ASSISTANT_MESSAGE_ID,
- type: 'updateMessage',
- value: expect.objectContaining({ content: 'Hello' }),
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should handle reasoning chunks during streaming', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
-
- // Create operation for this test
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: TEST_IDS.SESSION_ID,
- topicId: null,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test AI Generation',
- });
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({ type: 'reasoning', text: 'Thinking...' } as any);
- await onMessageHandle?.({ type: 'text', text: 'Answer' } as any);
- await onFinish?.('Answer', {} as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- id: TEST_IDS.ASSISTANT_MESSAGE_ID,
- type: 'updateMessage',
- value: expect.objectContaining({ reasoning: { content: 'Thinking...' } }),
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should skip grounding when citations are empty', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({
- type: 'grounding',
- grounding: { citations: [], searchQueries: [] },
- } as any);
- await onFinish?.('Answer', {} as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- // Should not dispatch when citations are empty
- const groundingCalls = dispatchSpy.mock.calls.filter((call) => {
- const dispatch = call[0];
- return dispatch?.type === 'updateMessage' && 'value' in dispatch && dispatch.value?.search;
- });
- expect(groundingCalls).toHaveLength(0);
-
- streamSpy.mockRestore();
- });
-
- it('should handle grounding chunks during streaming', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
-
- // Create operation for this test
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: TEST_IDS.SESSION_ID,
- topicId: null,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test AI Generation',
- });
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({
- type: 'grounding',
- grounding: {
- citations: [{ url: 'https://example.com', title: 'Example' }],
- searchQueries: ['test query'],
- },
- } as any);
- await onFinish?.('Answer', {} as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- id: TEST_IDS.ASSISTANT_MESSAGE_ID,
- type: 'updateMessage',
- value: expect.objectContaining({
- search: expect.objectContaining({
- citations: expect.any(Array),
- }),
- }),
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should handle base64 image chunks during streaming', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
-
- // Create operation for this test
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: TEST_IDS.SESSION_ID,
- topicId: null,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test AI Generation',
- });
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({
- type: 'base64_image',
- image: { id: 'img-1', data: 'base64data' },
- images: [{ id: 'img-1', data: 'base64data' }],
- } as any);
- await onFinish?.('Answer', {} as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- expect(dispatchSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- id: TEST_IDS.ASSISTANT_MESSAGE_ID,
- type: 'updateMessage',
- value: expect.objectContaining({
- imageList: expect.any(Array),
- }),
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should handle empty tool call arguments', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
- toolCalls: [
- { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '' } },
- ],
- } as any);
- });
-
- await act(async () => {
- const response = await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- agentConfig: createMockResolvedAgentConfig(),
- });
- expect(response.isFunctionCall).toEqual(true);
- });
-
- streamSpy.mockRestore();
- });
-
- it('should update message with traceId when provided in onFinish', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const traceId = 'test-trace-123';
-
- const updateMessageSpy = vi.spyOn(messageService, 'updateMessage');
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, { traceId } as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- expect(updateMessageSpy).toHaveBeenCalledWith(
- TEST_IDS.ASSISTANT_MESSAGE_ID,
- expect.objectContaining({ traceId }),
- expect.objectContaining({
- agentId: expect.any(String),
- topicId: expect.any(String),
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- describe('effectiveAgentId for group orchestration', () => {
- it('should use subAgentId as agentId when groupId is present (group orchestration)', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const supervisorAgentId = 'supervisor-agent-id';
- const subAgentId = 'sub-agent-id';
- const groupId = 'test-group-id';
-
- // Create operation with groupId and subAgentId (group orchestration scenario)
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: supervisorAgentId,
- subAgentId: subAgentId,
- groupId: groupId, // groupId present = group orchestration
- topicId: TEST_IDS.TOPIC_ID,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test Group Orchestration',
- });
-
- // Pre-resolved config for the sub-agent (in real usage, resolved by internal_createAgentState)
- const subAgentConfig = createMockResolvedAgentConfig();
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- agentConfig: subAgentConfig,
- });
- });
-
- // In group orchestration (groupId present), subAgentId should be used as agentId
- expect(streamSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- agentId: subAgentId, // subAgentId used for context injection in group orchestration
- resolvedAgentConfig: subAgentConfig,
- }),
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should use agentId when subAgentId is present but groupId is not (non-group scenario)', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const agentId = 'normal-agent-id';
- const subAgentId = 'sub-agent-id';
-
- // Create operation with subAgentId but NO groupId (not a group orchestration scenario)
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: agentId,
- subAgentId: subAgentId, // subAgentId present but no groupId
- topicId: TEST_IDS.TOPIC_ID,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test Non-Group with SubAgentId',
- });
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- // Without groupId, should use agentId even if subAgentId is present
- expect(streamSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- // agentId used since no groupId
- params: expect.objectContaining({ agentId }),
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should pass agentId to chatService when no subAgentId is set (normal chat)', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const agentId = 'normal-agent-id';
-
- // Create operation without subAgentId (normal chat scenario)
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: agentId,
- // No subAgentId
- topicId: TEST_IDS.TOPIC_ID,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test Normal Chat',
- });
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- // Verify chatService was called with agentId (no subAgentId present)
- expect(streamSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- agentId: agentId, // Should be agentId since no subAgentId
- }),
- }),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should pass resolvedAgentConfig through chatService in group orchestration speak scenario', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const supervisorAgentId = 'supervisor-agent-id';
- const subAgentId = 'speaking-agent-id';
- const groupId = 'test-group-id';
-
- // Create operation simulating group orchestration speak scenario
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: supervisorAgentId, // The supervisor/session ID
- subAgentId: subAgentId, // The actual speaking agent
- groupId: groupId,
- topicId: TEST_IDS.TOPIC_ID,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- scope: 'group',
- },
- label: 'Test Speak Executor',
- });
-
- // Create a mock resolved config that represents the speaking agent's config
- const speakingAgentConfig = createMockResolvedAgentConfig();
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- // Pass pre-resolved config for the speaking agent
- // In real usage, this is resolved in internal_createAgentState using subAgentId
- agentConfig: speakingAgentConfig,
- });
- });
-
- // In group orchestration (groupId present), subAgentId is used as agentId for context injection
- // The speaking agent's config is passed via resolvedAgentConfig
- expect(streamSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- // subAgentId used as agentId in group orchestration
- agentId: subAgentId,
- // resolvedAgentConfig contains the speaking agent's config
- resolvedAgentConfig: speakingAgentConfig,
- }),
- }),
- );
-
- streamSpy.mockRestore();
- });
- });
- });
-
describe('internal_execAgentRuntime', () => {
it('should handle the core AI message processing', async () => {
act(() => {
@@ -942,99 +329,6 @@ describe('StreamingExecutor actions', () => {
// RAG is now handled by Knowledge Base Tools (searchKnowledgeBase and readKnowledge)
});
- describe('StreamingExecutor OptimisticUpdateContext isolation', () => {
- it('should pass context to optimisticUpdateMessageContent in internal_fetchAIChatMessage', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const contextAgentId = 'context-session';
- const contextTopicId = 'context-topic';
-
- const updateContentSpy = vi.spyOn(result.current, 'optimisticUpdateMessageContent');
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({ type: 'text', text: TEST_CONTENT.AI_RESPONSE } as any);
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});
- });
-
- // Create operation with specific context
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: contextAgentId,
- topicId: contextTopicId,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test AI Generation',
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- operationId,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- expect(updateContentSpy).toHaveBeenCalledWith(
- TEST_IDS.ASSISTANT_MESSAGE_ID,
- TEST_CONTENT.AI_RESPONSE,
- expect.any(Object),
- {
- operationId: expect.any(String),
- },
- );
-
- streamSpy.mockRestore();
- });
-
- it('should use activeAgentId/activeTopicId when context not provided', async () => {
- act(() => {
- useChatStore.setState({
- activeAgentId: 'active-session',
- activeTopicId: 'active-topic',
- });
- });
-
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
-
- const updateContentSpy = vi.spyOn(result.current, 'optimisticUpdateMessageContent');
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({ type: 'text', text: TEST_CONTENT.AI_RESPONSE } as any);
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- expect(updateContentSpy).toHaveBeenCalledWith(
- TEST_IDS.ASSISTANT_MESSAGE_ID,
- TEST_CONTENT.AI_RESPONSE,
- expect.any(Object),
- {
- operationId: undefined,
- },
- );
-
- streamSpy.mockRestore();
- });
- });
-
describe('afterCompletion hooks', () => {
it('should execute afterCompletion callbacks after runtime completes', async () => {
const { result } = renderHook(() => useChatStore());
@@ -1791,174 +1085,6 @@ describe('StreamingExecutor actions', () => {
});
});
- describe('content_part multimodal streaming', () => {
- it('should dispatch isMultimodal metadata when content_part image chunks are received', async () => {
- // Mock file store to prevent upload from hanging
- const fileStoreMod = await import('@/store/file/store');
- vi.spyOn(fileStoreMod, 'getFileStoreState').mockReturnValue({
- uploadBase64FileWithProgress: vi
- .fn()
- .mockResolvedValue({ id: 'img-id', url: 'https://cdn.example.com/img.png' }),
- } as any);
-
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
-
- // Create operation for this test
- const { operationId } = result.current.startOperation({
- type: 'execAgentRuntime',
- context: {
- agentId: TEST_IDS.SESSION_ID,
- topicId: null,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- },
- label: 'Test AI Generation',
- });
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- // Send text content_part
- await onMessageHandle?.({
- type: 'content_part',
- partType: 'text',
- content: 'Here is a cat: ',
- } as any);
- // Send image content_part
- await onMessageHandle?.({
- type: 'content_part',
- partType: 'image',
- content: 'base64catimage',
- mimeType: 'image/jpeg',
- } as any);
- await onFinish?.('Here is a cat: ', {} as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gemini-3-pro-image-preview',
- provider: 'google',
- operationId,
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- // Find dispatch calls with metadata.isMultimodal
- const multimodalDispatches = dispatchSpy.mock.calls.filter((call) => {
- const dispatch = call[0];
- return (
- dispatch?.type === 'updateMessage' &&
- 'value' in dispatch &&
- dispatch.value?.metadata?.isMultimodal === true
- );
- });
-
- // Should have dispatched at least once with isMultimodal metadata during streaming
- expect(multimodalDispatches.length).toBeGreaterThanOrEqual(1);
-
- // Verify the dispatch includes tempDisplayContent
- const firstMultimodalDispatch = multimodalDispatches[0][0] as any;
- expect(firstMultimodalDispatch.value.metadata.tempDisplayContent).toBeDefined();
-
- streamSpy.mockRestore();
- });
-
- it('should call optimisticUpdateMessageContent with isMultimodal metadata for multimodal content', async () => {
- // Mock file store to prevent upload from hanging
- const fileStoreMod = await import('@/store/file/store');
- vi.spyOn(fileStoreMod, 'getFileStoreState').mockReturnValue({
- uploadBase64FileWithProgress: vi
- .fn()
- .mockResolvedValue({ id: 'img-id', url: 'https://cdn.example.com/img.png' }),
- } as any);
-
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const updateContentSpy = vi.spyOn(result.current, 'optimisticUpdateMessageContent');
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({
- type: 'content_part',
- partType: 'text',
- content: 'Generated image: ',
- } as any);
- await onMessageHandle?.({
- type: 'content_part',
- partType: 'image',
- content: 'base64imagedata',
- mimeType: 'image/png',
- } as any);
- await onFinish?.('Generated image: ', {} as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gemini-3-pro-image-preview',
- provider: 'google',
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- // optimisticUpdateMessageContent should be called with metadata containing isMultimodal
- expect(updateContentSpy).toHaveBeenCalledWith(
- TEST_IDS.ASSISTANT_MESSAGE_ID,
- expect.any(String), // serialized JSON content
- expect.objectContaining({
- metadata: expect.objectContaining({
- isMultimodal: true,
- }),
- }),
- expect.any(Object),
- );
-
- streamSpy.mockRestore();
- });
-
- it('should NOT dispatch isMultimodal metadata for plain text streaming', async () => {
- const { result } = renderHook(() => useChatStore());
- const messages = [createMockMessage({ role: 'user' })];
- const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
-
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onMessageHandle, onFinish }) => {
- await onMessageHandle?.({ type: 'text', text: 'Hello World' } as any);
- await onFinish?.('Hello World', {} as any);
- });
-
- await act(async () => {
- await result.current.internal_fetchAIChatMessage({
- messages,
- messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- model: 'gpt-4o-mini',
- provider: 'openai',
- agentConfig: createMockResolvedAgentConfig(),
- });
- });
-
- // No dispatch should contain isMultimodal metadata
- const multimodalDispatches = dispatchSpy.mock.calls.filter((call) => {
- const dispatch = call[0];
- return (
- dispatch?.type === 'updateMessage' &&
- 'value' in dispatch &&
- dispatch.value?.metadata?.isMultimodal === true
- );
- });
-
- expect(multimodalDispatches).toHaveLength(0);
-
- streamSpy.mockRestore();
- });
- });
-
describe('isSubTask filtering', () => {
it('should filter out lobe-gtd tools when isSubTask is true', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 82958c76691..a0416a127b8 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -10,21 +10,14 @@ import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';
import { isDesktop } from '@lobechat/const';
import {
- type ChatToolPayload,
type ConversationContext,
- type MessageMapScope,
- type MessageToolCall,
- type ModelUsage,
type RuntimeInitialContext,
- type RuntimeStepContext,
type UIChatMessage,
} from '@lobechat/types';
-import { TraceNameMap } from '@lobechat/types';
import debug from 'debug';
import { t } from 'i18next';
import { createAgentToolsEngine } from '@/helpers/toolEngineering';
-import { chatService } from '@/services/chat';
import { type ResolvedAgentConfig } from '@/services/chat/mecha';
import { resolveAgentConfig } from '@/services/chat/mecha';
import { messageService } from '@/services/message';
@@ -32,7 +25,6 @@ import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
import { type ChatStore } from '@/store/chat/store';
-import { getFileStoreState } from '@/store/file/store';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
import { type StoreSetter } from '@/store/types';
import { toolInterventionSelectors } from '@/store/user/selectors';
@@ -43,8 +35,6 @@ import { topicSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
import { topicMapKey } from '../../../utils/topicMapKey';
import { selectTodosFromMessages } from '../../message/selectors/dbMessage';
-import { StreamingHandler } from './StreamingHandler';
-import { type StreamChunk } from './types/streaming';
const log = debug('lobe-store:streaming-executor');
@@ -58,6 +48,7 @@ export const streamingExecutor = (set: Setter, get: () => ChatStore, _api?: unkn
export class StreamingExecutorActionImpl {
readonly #get: () => ChatStore;
+ // eslint-disable-next-line no-unused-private-class-members
readonly #set: Setter;
constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
@@ -255,307 +246,6 @@ export class StreamingExecutorActionImpl {
return { agentConfig: agentConfigWithTools, context, state };
};
- internal_fetchAIChatMessage = async ({
- messageId,
- messages,
- model,
- provider,
- operationId,
- agentConfig,
- traceId: traceIdParam,
- initialContext,
- stepContext,
- }: {
- messageId: string;
- messages: UIChatMessage[];
- model: string;
- provider: string;
- operationId?: string;
- traceId?: string;
- agentConfig: ResolvedAgentConfig;
- initialContext?: RuntimeInitialContext;
- stepContext?: RuntimeStepContext;
- }): Promise<{
- isFunctionCall: boolean;
- tools?: ChatToolPayload[];
- tool_calls?: MessageToolCall[];
- content: string;
- traceId?: string;
- finishType?: string;
- usage?: ModelUsage;
- }> => {
- const {
- optimisticUpdateMessageContent,
- internal_dispatchMessage,
- internal_toggleToolCallingStreaming,
- } = this.#get();
-
- // Get agentId, topicId, groupId and abortController from operation
- let agentId: string;
- let subAgentId: string | undefined;
- let topicId: string | null | undefined;
- let threadId: string | undefined;
- let groupId: string | undefined;
- let scope: MessageMapScope | undefined;
- let traceId: string | undefined = traceIdParam;
- let abortController: AbortController;
-
- if (operationId) {
- const operation = this.#get().operations[operationId];
- if (!operation) {
- log('[internal_fetchAIChatMessage] ERROR: Operation not found: %s', operationId);
- throw new Error(`Operation not found: ${operationId}`);
- }
- topicId = operation.context.topicId;
- threadId = operation.context.threadId ?? undefined;
- groupId = operation.context.groupId;
- scope = operation.context.scope;
- subAgentId = operation.context.subAgentId;
- abortController = operation.abortController; // 👈 Use operation's abortController
-
- // In group orchestration scenarios (has groupId), subAgentId is the actual responding agent
- // Use it for context injection instead of the session agentId
- if (groupId && subAgentId) {
- agentId = subAgentId;
- } else {
- agentId = operation.context.agentId!;
- }
-
- log(
- '[internal_fetchAIChatMessage] get context from operation %s: agentId=%s, subAgentId=%s, topicId=%s, groupId=%s, aborted=%s',
- operationId,
- agentId,
- subAgentId,
- topicId,
- groupId,
- abortController.signal.aborted,
- );
- // Get traceId from operation metadata if not explicitly provided
- if (!traceId) {
- traceId = operation.metadata?.traceId;
- }
- } else {
- // Fallback to global state (for legacy code paths without operation)
- agentId = this.#get().activeAgentId;
- topicId = this.#get().activeTopicId;
- groupId = this.#get().activeGroupId;
- abortController = new AbortController();
- log(
- '[internal_fetchAIChatMessage] use global context: agentId=%s, topicId=%s, groupId=%s',
- agentId,
- topicId,
- groupId,
- );
- }
-
- // Create base context for child operations and message queries
- const fetchContext = { agentId, topicId, threadId, groupId, scope };
-
- // Use pre-resolved agent config (from internal_createAgentState)
- // This ensures isSubTask filtering and other runtime modifications are preserved
- const { agentConfig: agentConfigData, chatConfig, plugins: pluginIds } = agentConfig;
- log('[internal_fetchAIChatMessage] using pre-resolved config, plugins=%o', pluginIds);
-
- let finalUsage: ModelUsage | undefined;
- let finalToolCalls: MessageToolCall[] | undefined;
-
- // Create streaming handler with callbacks
- const handler = new StreamingHandler(
- { messageId, operationId, agentId, groupId, topicId },
- {
- onContentUpdate: (content, reasoning, contentMetadata) => {
- internal_dispatchMessage(
- {
- id: messageId,
- type: 'updateMessage',
- value: {
- content,
- reasoning,
- ...(contentMetadata && {
- metadata: {
- isMultimodal: contentMetadata.isMultimodal,
- tempDisplayContent: contentMetadata.tempDisplayContent,
- },
- }),
- },
- },
- { operationId },
- );
- },
- onReasoningUpdate: (reasoning) => {
- internal_dispatchMessage(
- {
- id: messageId,
- type: 'updateMessage',
- value: { reasoning },
- },
- { operationId },
- );
- },
- onToolCallsUpdate: (tools) => {
- internal_dispatchMessage(
- {
- id: messageId,
- type: 'updateMessage',
- value: { tools },
- },
- { operationId },
- );
- },
- onGroundingUpdate: (grounding) => {
- internal_dispatchMessage(
- {
- id: messageId,
- type: 'updateMessage',
- value: { search: grounding },
- },
- { operationId },
- );
- },
- onImagesUpdate: (images) => {
- internal_dispatchMessage(
- {
- id: messageId,
- type: 'updateMessage',
- value: { imageList: images },
- },
- { operationId },
- );
- },
- onReasoningStart: () => {
- const { operationId: reasoningOpId } = this.#get().startOperation({
- type: 'reasoning',
- context: { ...fetchContext, messageId },
- parentOperationId: operationId,
- });
- this.#get().associateMessageWithOperation(messageId, reasoningOpId);
- return reasoningOpId;
- },
- onReasoningComplete: (opId) => this.#get().completeOperation(opId),
- uploadBase64Image: (data) =>
- getFileStoreState()
- .uploadBase64FileWithProgress(data)
- .then((file) => ({
- id: file?.id,
- url: file?.url,
- alt: file?.filename || file?.id,
- })),
- transformToolCalls: this.#get().internal_transformToolCalls,
- toggleToolCallingStreaming: internal_toggleToolCallingStreaming,
- },
- );
-
- const historySummary = chatConfig.enableCompressHistory
- ? topicSelectors.currentActiveTopicSummary(this.#get())
- : undefined;
- await chatService.createAssistantMessageStream({
- abortController,
- params: {
- // agentId is used for context, not for config resolution (config is pre-resolved)
- agentId: agentId || undefined,
- groupId,
- messages,
- model,
- provider,
- // Pass pre-resolved config to avoid duplicate resolveAgentConfig calls
- // This ensures isSubTask filtering and other runtime modifications are preserved
- resolvedAgentConfig: agentConfig,
- topicId: topicId ?? undefined, // Pass topicId for GTD context injection
- ...agentConfigData.params,
- },
- historySummary: historySummary?.content,
- // Pass page editor context from agent runtime
- initialContext,
- stepContext,
- trace: {
- traceId,
- topicId: topicId ?? undefined,
- traceName: TraceNameMap.Conversation,
- },
- onErrorHandle: async (error) => {
- log(
- '[internal_fetchAIChatMessage] onError: messageId=%s, error=%s, operationId=%s',
- messageId,
- error.message,
- operationId,
- );
- await this.#get().optimisticUpdateMessageError(messageId, error, { operationId });
- },
- onFinish: async (
- content,
- { traceId, observationId, toolCalls, reasoning, grounding, usage, speed, type },
- ) => {
- // if there is traceId, update it
- if (traceId) {
- messageService.updateMessage(
- messageId,
- { traceId, observationId: observationId ?? undefined },
- { agentId, groupId, topicId },
- );
- }
-
- // Handle finish using StreamingHandler
- const result = await handler.handleFinish({
- traceId,
- observationId,
- toolCalls,
- reasoning,
- grounding,
- usage,
- speed,
- type,
- });
-
- // Store for return value
- finalUsage = result.usage;
- finalToolCalls = result.toolCalls;
-
- // update the content after fetch result
- await optimisticUpdateMessageContent(
- messageId,
- result.content,
- {
- tools: result.tools,
- reasoning: result.metadata.reasoning,
- search: result.metadata.search,
- imageList: result.metadata.imageList,
- metadata: {
- ...result.metadata.usage,
- ...result.metadata.performance,
- performance: result.metadata.performance,
- usage: result.metadata.usage,
- finishType: result.metadata.finishType,
- ...(result.metadata.isMultimodal && { isMultimodal: true }),
- },
- },
- { operationId },
- );
- },
- onMessageHandle: async (chunk) => {
- // Delegate chunk handling to StreamingHandler
- handler.handleChunk(chunk as StreamChunk);
- },
- });
-
- log(
- '[internal_fetchAIChatMessage] completed: messageId=%s, finishType=%s, isFunctionCall=%s, operationId=%s',
- messageId,
- handler.getFinishType(),
- handler.getIsFunctionCall(),
- operationId,
- );
-
- return {
- isFunctionCall: handler.getIsFunctionCall(),
- traceId: handler.getTraceId(),
- content: handler.getOutput(),
- tools: handler.getTools(),
- usage: finalUsage,
- tool_calls: finalToolCalls,
- finishType: handler.getFinishType(),
- };
- };
-
internal_execAgentRuntime = async (params: {
context: ConversationContext;
disableTools?: boolean;