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: migrate client call llm to runtime transport (#17140)

Arvin Xu6c0c0a90e34b
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index 603e17de6a8..f49cf7af8c1 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -255,6 +255,44 @@ describe('callLlmFinalizer', () => {
});
});
+ it('preserves structured client metadata and maps abort completion to human_abort', async () => {
+ const messages = createMessageTransport();
+
+ const result = await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-1',
+ events: [],
+ host: createHost(messages),
+ model: 'claude',
+ output: createOutput({
+ content: 'Partial answer',
+ finishReason: 'abort',
+ observationId: 'observation-1',
+ reasoning: { content: 'Reasoning', duration: 120, signature: 'signature-1' },
+ traceId: 'trace-1',
+ }),
+ provider: 'anthropic',
+ shouldReplayAssistantReasoning: true,
+ state: AgentRuntime.createInitialState({ operationId: 'operation-1' }),
+ });
+
+ expect(messages.update).toHaveBeenCalledWith(
+ 'assistant-1',
+ expect.objectContaining({
+ metadata: { finishType: 'abort' },
+ observationId: 'observation-1',
+ reasoning: { content: 'Reasoning', duration: 120, signature: 'signature-1' },
+ traceId: 'trace-1',
+ }),
+ );
+ expect(result.nextContext).toMatchObject({
+ payload: {
+ parentMessageId: 'assistant-1',
+ reason: 'user_cancelled',
+ },
+ phase: 'human_abort',
+ });
+ });
+
it('persists partial interrupted output and skips empty interruptions', async () => {
const messages = createMessageTransport();
const host = createHost(messages);
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index a80f17fce40..c51f19ab1d1 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -27,6 +27,7 @@ type CallLlmCollectedOutput = Pick<
| 'contentParts'
| 'hasContentImages'
| 'hasReasoningImages'
+ | 'reasoning'
| 'reasoningParts'
| 'thinkingContent'
>;
@@ -59,18 +60,21 @@ const buildMessageMetadata = ({
answerSalvagedFromReasoning,
currentStepSpeed,
currentStepUsage,
+ finishType,
hasContentImages,
interruptedMidStream,
}: {
answerSalvagedFromReasoning?: boolean;
currentStepSpeed?: ModelPerformance;
currentStepUsage?: ModelUsage;
+ finishType?: string;
hasContentImages?: boolean;
interruptedMidStream?: boolean;
}): CallLlmMessageMetadata | undefined => {
const metadata: CallLlmMessageMetadata = {
...(currentStepUsage && { ...currentStepUsage, usage: currentStepUsage }),
...(currentStepSpeed && { ...currentStepSpeed, performance: currentStepSpeed }),
+ ...(finishType && { finishType }),
...(hasContentImages && { isMultimodal: true }),
...(answerSalvagedFromReasoning && { answerSalvagedFromReasoning: true }),
...(interruptedMidStream && { interruptedMidStream: true }),
@@ -87,6 +91,13 @@ const buildFinalReasoning = (output: CallLlmCollectedOutput): ModelReasoning | u
};
}
+ if (output.reasoning) {
+ return {
+ ...output.reasoning,
+ content: output.thinkingContent || output.reasoning.content,
+ };
+ }
+
return output.thinkingContent ? { content: output.thinkingContent } : undefined;
};
@@ -125,6 +136,7 @@ const persistFinalMessage = async ({
answerSalvagedFromReasoning: output.answerSalvagedFromReasoning,
currentStepSpeed: output.speed,
currentStepUsage: output.usage,
+ finishType: output.finishReason,
hasContentImages: output.hasContentImages,
});
@@ -133,9 +145,11 @@ const persistFinalMessage = async ({
content: finalContent,
imageList: output.imageList.length > 0 ? output.imageList : undefined,
metadata,
+ observationId: output.observationId,
reasoning: finalReasoning,
search: output.grounding,
tools: sanitizePersistedTools(output.toolsCalling),
+ traceId: output.traceId,
});
} catch (error) {
console.error('[call_llm] Failed to update message:', error);
@@ -237,6 +251,7 @@ export const finalizeCallLlmTurn = async ({
operation.allowEarlyFinalAnswerVisibleOutputEnd ?? true;
if (
canPublishEarlyFinalAnswerVisibleEnd &&
+ output.finishReason !== 'abort' &&
output.toolsCalling.length === 0 &&
output.toolCalls.length === 0
) {
@@ -267,6 +282,31 @@ export const finalizeCallLlmTurn = async ({
await recordResult?.(output);
+ if (output.finishReason === 'abort') {
+ return {
+ events,
+ newState,
+ nextContext: {
+ payload: {
+ hasToolsCalling: output.toolsCalling.length > 0,
+ parentMessageId: assistantMessageId,
+ reason: 'user_cancelled',
+ result: { content: output.content, tool_calls: output.toolCalls },
+ toolsCalling: output.toolsCalling,
+ },
+ phase: 'human_abort',
+ session: {
+ eventCount: events.length,
+ messageCount: newState.messages.length,
+ sessionId: operation.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ stepUsage: output.usage,
+ },
+ };
+ }
+
return {
events,
newState,
diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.ts
index 9d6fdf47a8e..14ee64689ec 100644
--- a/packages/agent-runtime/src/transport/llm.ts
+++ b/packages/agent-runtime/src/transport/llm.ts
@@ -4,6 +4,7 @@ import type {
GroundingSearch,
MessageToolCall,
ModelPerformance,
+ ModelReasoning,
ModelUsage,
OpenAIChatMessage,
} from '@lobechat/types';
@@ -51,12 +52,16 @@ export interface LLMAttemptOutput {
hasContentImages: boolean;
hasReasoningImages: boolean;
imageList: ChatImageItem[];
+ observationId?: string;
+ /** Adapter-produced structured reasoning metadata such as duration and signature. */
+ reasoning?: ModelReasoning;
reasoningParts: LLMAttemptContentPart[];
speed?: ModelPerformance;
/** Raw streamed thinking text; finalization converts it to the message reasoning object. */
thinkingContent: string;
toolCalls: MessageToolCall[];
toolsCalling: ChatToolPayload[];
+ traceId?: string;
usage?: ModelUsage;
}
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 5f72af9ef31..423d78d6d69 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -62,7 +62,6 @@ import {
} from './mecha';
import { type FetchOptions } from './types';
-const defaultProvider = ModelProvider.OpenAI;
const providersWithDeploymentName = new Set<string>([
ModelProvider.Azure,
ModelProvider.AzureAI,
@@ -72,7 +71,7 @@ const providersWithDeploymentName = new Set<string>([
ModelProvider.Volcengine,
ModelProvider.VolcengineCodingPlan,
]);
-interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'messages'>> {
+export interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'messages'>> {
agentId?: string;
groupId?: string;
messages: UIChatMessage[];
@@ -84,6 +83,11 @@ interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'mess
topicId?: string;
}
+export interface PreparedAssistantMessageContext {
+ options: FetchOptions;
+ params: Partial<ChatStreamPayload>;
+}
+
type ChatStreamInputParams = Partial<Omit<ChatStreamPayload, 'messages'>> & {
messages?: (UIChatMessage | OpenAIChatMessage)[];
};
@@ -127,7 +131,7 @@ class ChatService {
return targetAgentId || undefined;
};
- createAssistantMessage = async (
+ buildAssistantMessageContext = async (
{
messages,
agentId,
@@ -137,7 +141,7 @@ class ChatService {
...params
}: GetChatCompletionPayload,
options?: FetchOptions,
- ) => {
+ ): Promise<PreparedAssistantMessageContext> => {
const payload = merge(
{
model: DEFAULT_AGENT_CONFIG.model,
@@ -323,8 +327,9 @@ class ChatService {
provider: payload.provider!,
});
- return this.getChatCompletion(
- {
+ return {
+ options: { ...options, agentId: targetAgentId, topicId },
+ params: {
...params,
...extendParams,
enabledSearch: searchConfig.enabledSearch && searchConfig.useModelSearch ? true : undefined,
@@ -333,8 +338,13 @@ class ChatService {
stream: chatConfig.enableStreaming !== false,
tools,
},
- { ...options, agentId: targetAgentId, topicId },
- );
+ };
+ };
+
+ createAssistantMessage = async (params: GetChatCompletionPayload, options?: FetchOptions) => {
+ const prepared = await this.buildAssistantMessageContext(params, options);
+
+ return this.getChatCompletion(prepared.params, prepared.options);
};
createAssistantMessageStream = async ({
@@ -360,10 +370,12 @@ class ChatService {
metadata,
signal: abortController?.signal,
stepContext,
- trace: this.mapTrace(trace, TraceTagMap.Chat),
+ trace: this.mapChatTrace(trace),
});
};
+ mapChatTrace = (trace?: TracePayload): TracePayload => this.mapTrace(trace, TraceTagMap.Chat);
+
getChatCompletion = async (params: Partial<ChatStreamPayload>, options?: FetchOptions) => {
const { agentId, metadata, signal, responseAnimation, topicId } = options ?? {};
const requestTrigger = metadata?.trigger;
diff --git a/src/store/chat/agents/StreamingHandler.ts b/src/store/chat/agents/StreamingHandler.ts
index fb2838b3fbb..18cc7337cf7 100644
--- a/src/store/chat/agents/StreamingHandler.ts
+++ b/src/store/chat/agents/StreamingHandler.ts
@@ -159,6 +159,26 @@ export class StreamingHandler {
return this.output;
}
+ getContentParts(): MessageContentPart[] {
+ return [...this.contentParts];
+ }
+
+ getReasoningParts(): MessageContentPart[] {
+ return [...this.reasoningParts];
+ }
+
+ getThinkingContent(): string {
+ return this.thinkingContent;
+ }
+
+ hasContentImages(): boolean {
+ return this.contentParts.some((part) => part.type === 'image');
+ }
+
+ hasReasoningImages(): boolean {
+ return this.reasoningParts.some((part) => part.type === 'image');
+ }
+
/**
* Get reasoning duration
*/
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 ed7d638e430..fe8e5226cdf 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
@@ -1,1858 +1,342 @@
-import { type GeneralAgentCallLLMResultPayload } from '@lobechat/agent-runtime';
-import { LOADING_FLAT } from '@lobechat/const';
-import type { MessageToolCall } from '@lobechat/types';
-import { RequestTrigger } from '@lobechat/types';
-import { describe, expect, it, vi } from 'vitest';
+import { AgentRuntime, type AgentState } from '@lobechat/agent-runtime';
+import type { UIChatMessage } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_CONFIG } from '@/const/settings';
import { chatService } from '@/services/chat';
+import type { ResolvedAgentConfig } from '@/services/chat/mecha';
+import { messageService } from '@/services/message';
import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
+import type { ChatStore } from '@/store/chat/store';
-import {
- createAssistantMessage,
- createCallLLMInstruction,
- createMockStore,
- createUserMessage,
-} from './fixtures';
-import {
- createInitialState,
- createTestContext,
- executeWithMockContext,
- expectMessageCreated,
- expectNextContext,
- expectValidExecutorResult,
-} from './helpers';
+const messageKey = 'agent-1_topic-1';
+const operationId = 'operation-1';
-// Mock external services at module level
-vi.mock('@/services/chat', () => ({
- chatService: {
- createAssistantMessageStream: vi.fn(),
+const createResolvedAgentConfig = (): ResolvedAgentConfig => ({
+ agentConfig: {
+ ...DEFAULT_AGENT_CONFIG,
+ model: 'test-model',
+ provider: 'test-provider',
},
-}));
-
-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 () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext({ agentId: 'test-session', topicId: 'test-topic' });
- const instruction = createCallLLMInstruction({
- model: 'gpt-4',
- provider: 'openai',
- messages: [createUserMessage()],
- });
- const state = createInitialState({ operationId: 'test-session' });
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expectMessageCreated(mockStore, 'assistant');
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'test-session',
- content: LOADING_FLAT,
- role: 'assistant',
- model: 'gpt-4',
- provider: 'openai',
- topicId: 'test-topic',
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
-
- it('should call chatService.createAssistantMessageStream with correct params', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const userMsg = createUserMessage({ content: 'Hello' });
- const instruction = createCallLLMInstruction({
- model: 'gpt-4',
- provider: 'openai',
- messages: [userMsg],
- });
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- model: 'gpt-4',
- provider: 'openai',
- }),
- }),
- );
- });
-
- it('should forward request metadata to chatService', async () => {
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction({
- messages: [createUserMessage({ content: 'Hello' })],
- });
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- metadata: { trigger: RequestTrigger.Onboarding },
- state,
- mockStore,
- context,
- });
-
- expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
- expect.objectContaining({
- metadata: { trigger: RequestTrigger.Onboarding },
- }),
- );
- });
-
- it('should merge activated tools even when selectedTools are provided', async () => {
- const mockStore = createMockStore();
- const context = createTestContext();
- const userMsg = createUserMessage({ content: 'Use notebook' });
- const instruction = createCallLLMInstruction({
- model: 'gpt-4',
- provider: 'openai',
- messages: [userMsg],
- });
- const state = createInitialState();
- const notebookTool = {
- function: { name: 'lobe-notebook____createDocument' },
- type: 'function',
- } as const;
- const activatedTool = {
- function: { name: 'lobe-skills____runSkill' },
- type: 'function',
- } as const;
- const toolsEngine = {
- generateToolsDetailed: vi.fn().mockReturnValue({
- enabledManifests: [{ identifier: 'lobe-skills' }],
- enabledToolIds: ['lobe-skills'],
- tools: [activatedTool],
- }),
- };
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
- mockStore.operations[context.operationId] = {
- abortController: new AbortController(),
- childOperationIds: [],
- context: {
- agentId: context.agentId,
- messageId: context.parentId,
- topicId: context.topicId,
- },
- id: context.operationId,
- metadata: { startTime: Date.now() },
- status: 'running',
- type: 'execAgentRuntime',
- } as any;
-
- const executors = createAgentExecutors({
- agentConfig: {
- agentConfig: { model: 'gpt-4', provider: 'openai' } as any,
- chatConfig: {} as any,
- enabledManifests: [{ identifier: 'lobe-notebook' }] as any,
- enabledToolIds: ['lobe-notebook'],
- isBuiltinAgent: false,
- plugins: ['lobe-notebook'],
- tools: [notebookTool] as any,
- },
- get: () => mockStore,
- messageKey: context.messageKey,
- operationId: context.operationId,
- parentId: context.parentId,
- toolsEngine: toolsEngine as any,
- });
-
- await executors.call_llm!(instruction, state, {
- initialContext: {
- selectedTools: [{ identifier: 'lobe-notebook', name: 'Notebook' }],
- },
- phase: 'init',
- stepContext: {
- activatedToolIds: ['lobe-skills', 'lobe-activator'],
- },
- } as any);
-
- expect(toolsEngine.generateToolsDetailed).toHaveBeenCalledWith(
- expect.objectContaining({
- skipDefaultTools: true,
- toolIds: ['lobe-skills', 'lobe-activator'],
- }),
- );
- expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- resolvedAgentConfig: expect.objectContaining({
- enabledToolIds: ['lobe-notebook', 'lobe-skills'],
- tools: [notebookTool, activatedTool],
- }),
- }),
- }),
- );
- });
-
- it('should associate message with operation', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.associateMessageWithOperation).toHaveBeenCalledWith(
- expect.any(String),
- context.operationId,
- );
- });
-
- it('should return correct result structure with events and newState', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expectValidExecutorResult(result);
- expect(result.events).toEqual([]);
- expect(result.newState).toBeDefined();
- expect(result.nextContext).toBeDefined();
- });
- });
-
- describe('Skip Create First Message Mode', () => {
- it('should reuse parentId when skipCreateFirstMessage is true', async () => {
- // Given
- const mockStore = createMockStore();
- const parentId = 'msg_existing';
- const context = createTestContext({ parentId });
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- skipCreateFirstMessage: true,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();
- // The stream should still be called (message reuse doesn't skip LLM call)
- expect(chatService.createAssistantMessageStream).toHaveBeenCalled();
- });
- });
-
- describe('Parent Message ID Handling', () => {
- it('should use llmPayload.parentMessageId if provided', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext({ parentId: 'msg_context_parent' });
- const instruction = createCallLLMInstruction({
- parentMessageId: 'msg_payload_parent',
- });
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- parentId: 'msg_payload_parent',
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
-
- it('should fall back to context.parentId if parentMessageId not provided', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext({ parentId: 'msg_context_parent' });
- const instruction = createCallLLMInstruction({
- parentMessageId: undefined,
- });
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- parentId: 'msg_context_parent',
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
- });
-
- describe('Usage Tracking', () => {
- it('should accumulate LLM usage from currentStepUsage', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction({
- model: 'gpt-4',
- provider: 'openai',
- });
- const state = createInitialState({
- usage: {
- humanInteraction: {
- approvalRequests: 0,
- promptRequests: 0,
- selectRequests: 0,
- totalWaitingTimeMs: 0,
- },
- llm: {
- apiCalls: 1,
- processingTimeMs: 0,
- tokens: {
- input: 100,
- output: 50,
- total: 150,
- },
- },
- tools: {
- byTool: [],
- totalCalls: 0,
- totalTimeMs: 0,
- },
- },
- });
-
- mockStreamResponse({
- content: 'AI response',
- usage: {
- totalInputTokens: 50,
- totalOutputTokens: 30,
- totalTokens: 80,
- },
- });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(result.newState.usage).toBeDefined();
- expect(result.newState.usage.llm.tokens.input).toBeGreaterThan(state.usage.llm.tokens.input);
- expect(result.newState.usage.llm.tokens.output).toBeGreaterThan(
- state.usage.llm.tokens.output,
- );
- });
-
- it('should update state.usage and state.cost correctly', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction({
- model: 'gpt-4',
- provider: 'openai',
- });
- const state = createInitialState({
- usage: {
- humanInteraction: {
- approvalRequests: 0,
- promptRequests: 0,
- selectRequests: 0,
- totalWaitingTimeMs: 0,
- },
- llm: {
- apiCalls: 0,
- processingTimeMs: 0,
- tokens: {
- input: 0,
- output: 0,
- total: 0,
- },
- },
- tools: {
- byTool: [],
- totalCalls: 0,
- totalTimeMs: 0,
- },
- },
- });
-
- mockStreamResponse({
- content: 'AI response',
- usage: {
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- cost: 0.002,
- },
- });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(result.newState.usage).toBeDefined();
- expect(result.newState.cost).toBeDefined();
- });
-
- it('should handle no usage data returned', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response', usage: undefined });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then - should preserve original usage
- expect(result.newState.usage).toEqual(state.usage);
- });
- });
-
- describe('Abort Handling', () => {
- it('should return nextContext with phase: human_abort when finishType is abort', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState({ stepCount: 3 });
-
- mockStreamResponse({ content: 'Partial response', finishType: 'abort' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expectNextContext(result, 'human_abort');
- expect(result.nextContext!.session!.status).toBe('running');
- expect(result.nextContext!.session!.stepCount).toBe(4);
- });
-
- it('should include correct payload with reason and result when aborted', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'Partial response', finishType: 'abort' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- const payload = result.nextContext!.payload as GeneralAgentCallLLMResultPayload;
- expect(payload).toMatchObject({
- reason: 'user_cancelled',
- hasToolsCalling: false,
- result: {
- content: 'Partial response',
- tool_calls: undefined,
- },
- });
- });
-
- it('should include toolsCalling in abort payload when tools were being called', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- const toolCallsRaw: MessageToolCall[] = [
- {
- id: 'tool_1',
- type: 'function',
- function: {
- name: 'lobe-web-browsing____search',
- arguments: JSON.stringify({ query: 'test' }),
- },
- },
- ];
-
- mockStreamResponse({
- content: '',
- finishType: 'abort',
- tool_calls: toolCallsRaw,
- });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- const payload = result.nextContext!.payload as GeneralAgentCallLLMResultPayload;
- expect(payload).toMatchObject({
- reason: 'user_cancelled',
- hasToolsCalling: true,
- });
- expect(payload.toolsCalling.length).toBeGreaterThan(0);
- });
-
- it('should not throw error on abort', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'Partial', finishType: 'abort' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When & Then - should not throw
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- expect(result).toBeDefined();
- expect(result.nextContext!.phase).toBe('human_abort');
- });
- });
-
- describe('Normal Completion', () => {
- it('should return nextContext with phase: llm_result on normal completion', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expectNextContext(result, 'llm_result');
- });
-
- it('should include hasToolsCalling and result in llm_result payload', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'Here is the result' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- const payload = result.nextContext!.payload as GeneralAgentCallLLMResultPayload;
- expect(payload).toMatchObject({
- hasToolsCalling: false,
- result: {
- content: 'Here is the result',
- tool_calls: undefined,
- },
- });
- });
-
- it('should include toolCalling when LLM returns tools', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- const toolCallsRaw: MessageToolCall[] = [
- {
- id: 'tool_1',
- type: 'function',
- function: {
- name: 'lobe-web-browsing____search',
- arguments: JSON.stringify({ query: 'AI news' }),
- },
- },
- ];
-
- mockStreamResponse({
- content: '',
- finishType: 'tool_calls',
- tool_calls: toolCallsRaw,
- });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- const payload = result.nextContext!.payload as GeneralAgentCallLLMResultPayload;
- expect(payload.hasToolsCalling).toBe(true);
- expect(payload.toolsCalling.length).toBeGreaterThan(0);
- });
-
- it('should increment stepCount', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState({ stepCount: 5 });
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(result.nextContext!.session!.stepCount).toBe(6);
- });
-
- it('should include stepUsage in nextContext', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState({
- usage: {
- humanInteraction: {
- approvalRequests: 0,
- promptRequests: 0,
- selectRequests: 0,
- totalWaitingTimeMs: 0,
- },
- llm: {
- apiCalls: 0,
- processingTimeMs: 0,
- tokens: {
- input: 0,
- output: 0,
- total: 0,
- },
- },
- tools: {
- byTool: [],
- totalCalls: 0,
- totalTimeMs: 0,
- },
- },
- });
-
- const stepUsage = {
- totalInputTokens: 100,
- totalOutputTokens: 50,
- totalTokens: 150,
- };
-
- mockStreamResponse({ content: 'AI response', usage: stepUsage });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(result.nextContext!.stepUsage).toEqual(stepUsage);
- });
- });
-
- describe('State Management', () => {
- it('should update messages from dbMessagesMap', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState({ messages: [] });
-
- const updatedMessages = [
- createUserMessage({ content: 'Hello' }),
- createAssistantMessage({ content: 'Hi there' }),
- ];
-
- mockStreamResponse({ content: 'Hi there' });
- mockStore.dbMessagesMap[context.messageKey] = updatedMessages;
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(result.newState.messages).toEqual(updatedMessages);
- });
-
- it('should preserve other state fields', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState({
- operationId: 'test-session',
- stepCount: 10,
- status: 'running',
- });
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(result.newState.operationId).toBe(state.operationId);
- expect(result.newState.stepCount).toBe(state.stepCount);
- expect(result.newState.status).toBe(state.status);
- });
-
- it('should not mutate original state', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState({
- messages: [createUserMessage()],
- });
- const originalState = structuredClone(state);
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [createUserMessage(), createAssistantMessage()];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(state).toEqual(originalState);
- expect(result.newState).not.toBe(state);
- });
- });
-
- describe('Edge Cases', () => {
- it('should throw error when message creation fails', async () => {
- // Given
- const mockStore = createMockStore({
- optimisticCreateMessage: vi.fn().mockResolvedValue(null),
- });
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- // When & Then
- await expect(
- executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- }),
- ).rejects.toThrow('Failed to create assistant message');
- });
-
- it('should handle empty messages array', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction({
- messages: [],
- });
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- messages: [],
- }),
- }),
- );
- expect(result).toBeDefined();
- });
-
- it('should handle multiple tools returned', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- const toolCallsRaw: MessageToolCall[] = [
- {
- id: 'tool_1',
- type: 'function',
- function: {
- name: 'lobe-web-browsing____search',
- arguments: JSON.stringify({ query: 'AI' }),
- },
- },
- {
- id: 'tool_2',
- type: 'function',
- function: {
- name: 'lobe-web-browsing____craw',
- arguments: JSON.stringify({ url: 'https://example.com' }),
- },
- },
- {
- id: 'tool_3',
- type: 'function',
- function: {
- name: 'lobe-image-generator____generate',
- arguments: JSON.stringify({ prompt: 'AI art' }),
- },
- },
- ];
-
- mockStreamResponse({
- content: '',
- finishType: 'tool_calls',
- tool_calls: toolCallsRaw,
- });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- const payload = result.nextContext!.payload as GeneralAgentCallLLMResultPayload;
- expect(payload.toolsCalling).toHaveLength(3);
- expect(payload.hasToolsCalling).toBe(true);
- });
-
- it('should handle empty dbMessagesMap', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState({ messages: [createUserMessage()] });
-
- mockStreamResponse({ content: 'AI response' });
- // dbMessagesMap[messageKey] doesn't exist
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then - should default to empty array
- expect(result.newState.messages).toEqual([]);
- });
- });
-
- describe('Message Filtering', () => {
- it('should exclude assistant message from messages sent to LLM', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
-
- const userMsg = createUserMessage({ id: 'msg_user', content: 'Hello' });
- const assistantMsg = createAssistantMessage({ id: 'msg_assistant', content: 'Loading...' });
-
- const instruction = createCallLLMInstruction({
- messages: [userMsg, assistantMsg],
- });
- const state = createInitialState();
-
- mockStore.optimisticCreateMessage = vi.fn().mockResolvedValue({
- id: 'msg_assistant',
- role: 'assistant',
- content: LOADING_FLAT,
- });
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
+ chatConfig: { ...DEFAULT_AGENT_CHAT_CONFIG },
+ enabledManifests: [],
+ enabledToolIds: [],
+ isBuiltinAgent: false,
+ plugins: [],
+ tools: [],
+});
- // Then - should filter out the assistant message with matching ID
- expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- messages: expect.not.arrayContaining([
- expect.objectContaining({ id: 'msg_assistant' }),
- ]),
- }),
- }),
- );
- });
+const createState = (messages: UIChatMessage[]): AgentState =>
+ AgentRuntime.createInitialState({
+ messages,
+ metadata: { agentId: 'agent-1', topicId: 'topic-1' },
+ modelRuntimeConfig: { model: 'test-model', provider: 'test-provider' },
+ operationId,
+ operationToolSet: {
+ enabledToolIds: [],
+ manifestMap: {},
+ sourceMap: {},
+ tools: [],
+ },
});
- describe('Different Model Configurations', () => {
- it('should handle different model and provider combinations', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction({
- model: 'claude-3-opus',
- provider: 'anthropic',
- });
- const state = createInitialState();
-
- mockStreamResponse({ content: 'Claude response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
+const createStore = (messages: UIChatMessage[]) => {
+ const dbMessagesMap = { [messageKey]: messages };
+ const operations = {
+ [operationId]: {
+ abortController: new AbortController(),
+ context: {
+ agentId: 'agent-1',
+ messageId: messages.at(-1)?.id,
+ topicId: 'topic-1',
+ },
+ id: operationId,
+ metadata: { startTime: Date.now() },
+ status: 'running',
+ type: 'execAgentRuntime',
+ },
+ };
+
+ const store = {
+ associateMessageWithOperation: vi.fn(),
+ completeOperation: vi.fn(),
+ dbMessagesMap,
+ internal_dispatchMessage: vi.fn((action: any) => {
+ if (action.type === 'createMessage') {
+ dbMessagesMap[messageKey].push(action.value);
+ return;
+ }
+
+ if (action.type === 'updateMessage') {
+ const message = dbMessagesMap[messageKey].find((item) => item.id === action.id);
+ if (message) Object.assign(message, action.value);
+ }
+ }),
+ internal_toggleToolCallingStreaming: vi.fn(),
+ internal_transformToolCalls: vi.fn(() => []),
+ operations,
+ optimisticUpdateMessageError: vi.fn(),
+ startOperation: vi.fn(() => ({ operationId: 'reasoning-operation' })),
+ updateOperationMetadata: vi.fn(),
+ } as unknown as ChatStore;
+
+ return { dbMessagesMap, store };
+};
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
+const createInstruction = (overrides: Record<string, unknown> = {}) => ({
+ payload: {
+ messages: [],
+ model: 'test-model',
+ parentMessageId: 'user-1',
+ provider: 'test-provider',
+ tools: [],
+ ...overrides,
+ },
+ type: 'call_llm' as const,
+});
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- model: 'claude-3-opus',
- provider: 'anthropic',
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
- expect.objectContaining({
- params: expect.objectContaining({
- model: 'claude-3-opus',
- provider: 'anthropic',
- }),
- }),
- );
- });
+describe('createAgentExecutors call_llm', () => {
+ beforeEach(() => {
+ vi.spyOn(chatService, 'buildAssistantMessageContext').mockImplementation(
+ async ({ messages, model, provider }) => ({
+ options: {},
+ params: { messages: messages as any, model, provider },
+ }),
+ );
+ vi.spyOn(messageService, 'batchMutate').mockImplementation(async (operations) => ({
+ results: operations.map((operation, index) => ({
+ id: operation.type === 'createMessage' ? operation.message.id : operation.id,
+ index,
+ success: true,
+ type: operation.type,
+ })),
+ success: true,
+ }));
});
- describe('Context Propagation', () => {
- it('should include correct messageCount in nextContext', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- const messages = [
- createUserMessage(),
- createAssistantMessage(),
- createUserMessage(),
- createAssistantMessage(),
- ];
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = messages;
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(result.nextContext!.session!.messageCount).toBe(4);
- });
-
- it('should preserve sessionId in nextContext', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState({ operationId: 'custom-session-123' });
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- const result = await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(result.nextContext!.session!.sessionId).toBe('custom-session-123');
- });
+ afterEach(() => {
+ vi.restoreAllMocks();
});
- describe('Thread Support', () => {
- it('should handle threadId when provided in operation context', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext({ agentId: 'test-session', topicId: 'test-topic' });
- const threadId = 'thread_123';
-
- // Setup operation with threadId
- mockStore.operations[context.operationId] = {
- id: context.operationId,
- type: 'execAgentRuntime',
- status: 'running',
- context: {
- agentId: 'test-session',
- topicId: 'test-topic',
- threadId,
- },
- abortController: new AbortController(),
- metadata: { startTime: Date.now() },
- childOperationIds: [],
- };
-
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- threadId,
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
-
- it('should handle undefined threadId', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- threadId: undefined,
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
+ it('runs the package executor through client adapters and batch-persisted messages', async () => {
+ const userMessage = { content: 'Question', id: 'user-1', role: 'user' } as UIChatMessage;
+ const { dbMessagesMap, store } = createStore([userMessage]);
+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (_params, options) => {
+ options?.onMessageHandle?.({ text: 'Answer', type: 'text' } as any);
+ await options?.onFinish?.('Answer', {
+ grounding: undefined,
+ observationId: 'observation-1',
+ traceId: 'trace-1',
+ type: 'stop',
+ });
+ return new Response();
+ });
+ const executor = createAgentExecutors({
+ agentConfig: createResolvedAgentConfig(),
+ get: () => store,
+ messageKey,
+ operationId,
+ parentId: userMessage.id,
+ }).call_llm!;
+
+ const result = await executor(
+ createInstruction({ messages: [userMessage] }),
+ createState([userMessage]),
+ );
+
+ expect(result.nextContext?.phase).toBe('llm_result');
+ expect(dbMessagesMap[messageKey]).toHaveLength(2);
+ expect(dbMessagesMap[messageKey][1]).toMatchObject({
+ content: 'Answer',
+ observationId: 'observation-1',
+ search: null,
+ traceId: 'trace-1',
+ });
+ expect(messageService.batchMutate).toHaveBeenNthCalledWith(1, [
+ expect.objectContaining({
+ message: expect.objectContaining({ content: '', role: 'assistant' }),
+ type: 'createMessage',
+ }),
+ ]);
+ expect(messageService.batchMutate).toHaveBeenNthCalledWith(2, [
+ expect.objectContaining({
+ type: 'updateMessage',
+ value: expect.objectContaining({ content: 'Answer', search: null }),
+ }),
+ ]);
});
- describe('Group Orchestration: subAgentId Support', () => {
- it('should use subAgentId for message.agentId when present in operation context', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext({
- agentId: 'supervisor-agent', // Main agent (supervisor)
- scope: 'group_agent',
- subAgentId: 'worker-agent', // Actual executing agent
- topicId: 'group-topic',
- });
- const instruction = createCallLLMInstruction({
- model: 'gpt-4',
- provider: 'openai',
- messages: [createUserMessage()],
- });
- const state = createInitialState({ operationId: context.operationId });
-
- mockStreamResponse({ content: 'AI response from worker agent' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'worker-agent',
- role: 'assistant',
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
-
- it('should fall back to agentId when subAgentId is not present', 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: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'normal-agent',
- role: 'assistant',
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
-
- it('should pass groupId to message when present in operation context', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext({
- agentId: 'supervisor-agent',
- scope: 'group_agent',
- subAgentId: 'worker-agent',
- groupId: 'group-123',
- topicId: 'group-topic',
- });
- const instruction = createCallLLMInstruction({
- model: 'gpt-4',
- provider: 'openai',
- messages: [createUserMessage()],
- });
- const state = createInitialState({ operationId: context.operationId });
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- groupId: 'group-123',
- agentId: 'worker-agent',
- role: 'assistant',
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
-
- it('should use subAgentId even without explicit scope when groupId is present (backward compatibility)', async () => {
- // Given - Group scenario without explicit scope (backward compatibility test)
- const mockStore = createMockStore();
- const context = createTestContext({
- agentId: 'supervisor-agent',
- subAgentId: 'worker-agent',
- groupId: 'group-123',
- topicId: 'group-topic',
- // No explicit scope - should infer from groupId
- });
- const instruction = createCallLLMInstruction({
- model: 'gpt-4',
- provider: 'openai',
- messages: [createUserMessage()],
- });
- const state = createInitialState({ operationId: context.operationId });
-
- mockStreamResponse({ content: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then - should still use subAgentId for backward compatibility
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'worker-agent', // Should use subAgentId even without explicit scope
- groupId: 'group-123',
- role: 'assistant',
- }),
- expect.objectContaining({
- operationId: expect.any(String),
- }),
- );
- });
-
- it('should not include groupId when not in group chat context', 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: 'AI response' });
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'normal-agent',
- role: 'assistant',
- }),
- expect.objectContaining({
- 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();
- });
+ it('accepts a parent message hidden inside a compressed group', async () => {
+ const compressedAssistant = {
+ content: 'Previous answer',
+ id: 'assistant-compressed',
+ role: 'assistant',
+ } as UIChatMessage;
+ const compressedGroup = {
+ compressedMessages: [compressedAssistant],
+ content: 'Conversation summary',
+ id: 'compressed-group-1',
+ role: 'compressedGroup',
+ } as UIChatMessage;
+ const { store } = createStore([compressedGroup]);
+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (_params, options) => {
+ options?.onMessageHandle?.({ text: 'Answer after compression', type: 'text' } as any);
+ await options?.onFinish?.('Answer after compression', { type: 'stop' });
+ return new Response();
+ });
+ const executor = createAgentExecutors({
+ agentConfig: createResolvedAgentConfig(),
+ get: () => store,
+ messageKey,
+ operationId,
+ parentId: compressedAssistant.id,
+ }).call_llm!;
+
+ const result = await executor(
+ createInstruction({
+ messages: [compressedGroup],
+ parentMessageId: compressedAssistant.id,
+ }),
+ createState([compressedGroup]),
+ );
+
+ expect(result.nextContext?.phase).toBe('llm_result');
+ expect(messageService.batchMutate).toHaveBeenNthCalledWith(1, [
+ expect.objectContaining({
+ message: expect.objectContaining({ parentId: compressedAssistant.id }),
+ type: 'createMessage',
+ }),
+ ]);
});
- 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),
- }),
- );
- });
+ it('treats image content parts as a non-empty completion', async () => {
+ const userMessage = { content: 'Create an image', id: 'user-1', role: 'user' } as UIChatMessage;
+ const { store } = createStore([userMessage]);
+ const getChatCompletion = vi
+ .spyOn(chatService, 'getChatCompletion')
+ .mockImplementation(async (_params, options) => {
+ await options?.onMessageHandle?.({
+ content: 'base64data',
+ mimeType: 'image/png',
+ partType: 'image',
+ type: 'content_part',
+ } as any);
+ await options?.onFinish?.('', { type: 'stop' });
+ return new Response();
+ });
+ const executor = createAgentExecutors({
+ agentConfig: createResolvedAgentConfig(),
+ get: () => store,
+ messageKey,
+ operationId,
+ parentId: userMessage.id,
+ }).call_llm!;
+
+ const result = await executor(
+ createInstruction({ messages: [userMessage] }),
+ createState([userMessage]),
+ );
+
+ expect(result.nextContext?.phase).toBe('llm_result');
+ expect(getChatCompletion).toHaveBeenCalledTimes(1);
+ expect(messageService.batchMutate).toHaveBeenLastCalledWith([
+ expect.objectContaining({
+ type: 'updateMessage',
+ value: expect.objectContaining({
+ metadata: expect.objectContaining({ isMultimodal: true }),
+ }),
+ }),
+ ]);
});
- 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();
- });
+ it('reuses a seeded assistant message without creating a duplicate', async () => {
+ const userMessage = { content: 'Question', id: 'user-1', role: 'user' } as UIChatMessage;
+ const assistantMessage = {
+ content: '',
+ id: 'assistant-1',
+ parentId: userMessage.id,
+ role: 'assistant',
+ } as UIChatMessage;
+ const { store } = createStore([userMessage, assistantMessage]);
+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (_params, options) => {
+ options?.onMessageHandle?.({ text: 'Regenerated', type: 'text' } as any);
+ await options?.onFinish?.('Regenerated', { type: 'stop' });
+ return new Response();
+ });
+ const executor = createAgentExecutors({
+ agentConfig: createResolvedAgentConfig(),
+ get: () => store,
+ messageKey,
+ operationId,
+ parentId: assistantMessage.id,
+ }).call_llm!;
+
+ await executor(
+ createInstruction({
+ assistantMessageId: assistantMessage.id,
+ messages: [userMessage, assistantMessage],
+ parentMessageId: userMessage.id,
+ }),
+ createState([userMessage]),
+ );
+
+ expect(messageService.batchMutate).toHaveBeenCalledTimes(1);
+ expect(messageService.batchMutate).toHaveBeenCalledWith([
+ expect.objectContaining({ id: assistantMessage.id, type: 'updateMessage' }),
+ ]);
});
- describe('Google blocked stream errors', () => {
- it('should keep normal content and update message error state', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- vi.mocked(chatService.createAssistantMessageStream).mockImplementation(
- async (params: any) => {
- if (params.onMessageHandle) {
- await params.onMessageHandle({ text: 'Partial output', type: 'text' });
- }
-
- if (params.onErrorHandle) {
- params.onErrorHandle({
- body: {
- context: {
- finishReason: 'PROHIBITED_CONTENT',
- },
- provider: 'google',
- },
- message:
- 'Your request may contain prohibited content. Please adjust your request to comply with the usage guidelines.',
- type: 'ProviderBizError',
- });
- }
-
- if (params.onFinish) {
- await params.onFinish('Partial output', { type: 'error' });
- }
- },
- );
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticUpdateMessageError).toHaveBeenCalled();
-
- const contentCall = vi.mocked(mockStore.optimisticUpdateMessageContent).mock.calls.at(-1);
- const finalContent = contentCall?.[1] as string;
-
- expect(finalContent).toBe('Partial output');
+ it('returns human_abort when the client stream is cancelled', async () => {
+ const userMessage = { content: 'Question', id: 'user-1', role: 'user' } as UIChatMessage;
+ const { store } = createStore([userMessage]);
+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (_params, options) => {
+ options?.onMessageHandle?.({ text: 'Partial', type: 'text' } as any);
+ await options?.onFinish?.('Partial', { type: 'abort' });
+ return new Response();
+ });
+ const executor = createAgentExecutors({
+ agentConfig: createResolvedAgentConfig(),
+ get: () => store,
+ messageKey,
+ operationId,
+ parentId: userMessage.id,
+ }).call_llm!;
+
+ const result = await executor(
+ createInstruction({ messages: [userMessage] }),
+ createState([userMessage]),
+ );
+
+ expect(result.nextContext?.phase).toBe('human_abort');
+ expect(result.nextContext?.payload).toMatchObject({
+ parentMessageId: expect.any(String),
+ reason: 'user_cancelled',
});
});
- describe('Error traceId preservation', () => {
- it('should preserve backend traceId when local traceId is undefined', async () => {
- // Given
- const mockStore = createMockStore();
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- const backendTraceId = 'backend-trace-id-123';
-
- vi.mocked(chatService.createAssistantMessageStream).mockImplementation(
- async (params: any) => {
- if (params.onErrorHandle) {
- params.onErrorHandle({
- body: {
- traceId: backendTraceId,
- },
- message: 'Provider error',
- type: 'ProviderBizError',
- });
- }
-
- if (params.onFinish) {
- await params.onFinish('', { type: 'error' });
- }
- },
- );
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then
- expect(mockStore.optimisticUpdateMessageError).toHaveBeenCalled();
- const errorCall = vi.mocked(mockStore.optimisticUpdateMessageError).mock.calls[0];
- const errorArg = errorCall[1] as any;
- expect(errorArg.body.traceId).toBe(backendTraceId);
- });
-
- it('should use local traceId when available', async () => {
- // Given
- const mockStore = createMockStore();
- const localTraceId = 'local-trace-id-456';
- const context = createTestContext();
- const instruction = createCallLLMInstruction();
- const state = createInitialState();
-
- // Set traceId on operation metadata
- mockStore.operations[context.operationId] = {
- abortController: new AbortController(),
- childOperationIds: [],
- context: {
- agentId: context.agentId,
- messageId: context.parentId,
- topicId: context.topicId,
- },
- id: context.operationId,
- metadata: { startTime: Date.now(), traceId: localTraceId },
- status: 'running',
- type: 'execAgentRuntime',
- };
-
- mockStore.dbMessagesMap[context.messageKey] = [];
-
- vi.mocked(chatService.createAssistantMessageStream).mockImplementation(
- async (params: any) => {
- if (params.onErrorHandle) {
- params.onErrorHandle({
- body: {
- traceId: 'backend-trace-id',
- },
- message: 'Provider error',
- type: 'ProviderBizError',
- });
- }
-
- if (params.onFinish) {
- await params.onFinish('', { type: 'error' });
- }
- },
- );
-
- // When
- await executeWithMockContext({
- executor: 'call_llm',
- instruction,
- state,
- mockStore,
- context,
- });
-
- // Then - local traceId should take precedence
- expect(mockStore.optimisticUpdateMessageError).toHaveBeenCalled();
- const errorCall = vi.mocked(mockStore.optimisticUpdateMessageError).mock.calls[0];
- const errorArg = errorCall[1] as any;
- expect(errorArg.body.traceId).toBe(localTraceId);
- });
+ it('maps a thrown fetch abort to human_abort instead of an error state', async () => {
+ const userMessage = { content: 'Question', id: 'user-1', role: 'user' } as UIChatMessage;
+ const { store } = createStore([userMessage]);
+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async () => {
+ const operation = store.operations[operationId];
+ operation.status = 'cancelled';
+ operation.abortController.abort();
+ throw new DOMException('The operation was aborted', 'AbortError');
+ });
+ const executor = createAgentExecutors({
+ agentConfig: createResolvedAgentConfig(),
+ get: () => store,
+ messageKey,
+ operationId,
+ parentId: userMessage.id,
+ }).call_llm!;
+
+ const result = await executor(
+ createInstruction({ messages: [userMessage] }),
+ createState([userMessage]),
+ );
+
+ expect(result.nextContext?.phase).toBe('human_abort');
+ expect(result.newState.status).not.toBe('error');
});
});
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts b/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts
index 24a669bf60b..3344e8fc05b 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts
@@ -36,7 +36,6 @@ export const executeWithMockContext = async ({
mockStore,
context,
metadata,
- skipCreateFirstMessage = false,
}: {
context: {
agentId?: string;
@@ -52,7 +51,6 @@ export const executeWithMockContext = async ({
metadata?: Pick<MessageMetadata, 'trigger'>;
instruction: AgentInstruction;
mockStore: ChatStore;
- skipCreateFirstMessage?: boolean;
state: AgentState;
}) => {
// Ensure operation exists in store
@@ -83,7 +81,6 @@ export const executeWithMockContext = async ({
messageKey: context.messageKey,
operationId: context.operationId,
parentId: context.parentId,
- skipCreateFirstMessage,
});
const executorFn = executors[executor];
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 19c2a1ab2b0..c178f7ef8e0 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -1,14 +1,11 @@
import type {
AgentEvent,
AgentInstruction,
- AgentInstructionCallLlm,
AgentInstructionCompressContext,
AgentInstructionExecSubAgent,
AgentInstructionExecSubAgents,
AgentRuntimeContext,
AgentRuntimeHost,
- GeneralAgentCallLLMInstructionPayload,
- GeneralAgentCallLLMResultPayload,
GeneralAgentCompressionResultPayload,
InstructionExecutor,
SubAgentResultPayload,
@@ -16,39 +13,27 @@ import type {
SubAgentTask,
} from '@lobechat/agent-runtime';
import {
+ callLlm as createCallLlmExecutor,
callTool as createCallToolExecutor,
finish as createFinishExecutor,
requestHumanApprove as createRequestHumanApproveExecutor,
resolveAbortedTools as createResolveAbortedToolsExecutor,
- UsageCounter,
} from '@lobechat/agent-runtime';
import { countContextTokens, type ToolsEngine } from '@lobechat/context-engine';
import { chainCompressContext } from '@lobechat/prompts';
-import {
- type ChatMessageError,
- type MessageMetadata,
- type MessageToolCall,
- type ModelUsage,
- TraceNameMap,
-} from '@lobechat/types';
-import { dedupeBy } from '@lobechat/utils';
+import { type MessageMetadata } from '@lobechat/types';
import debug from 'debug';
-import { t } from 'i18next';
import pMap from 'p-map';
-import { LOADING_FLAT } from '@/const/message';
import { aiAgentService } from '@/services/aiAgent';
import { chatService } from '@/services/chat';
import { type ResolvedAgentConfig } from '@/services/chat/mecha';
import { messageService } from '@/services/message';
import { type ChatStore } from '@/store/chat/store';
import { getCompressionCandidateMessageIds } from '@/store/chat/utils/compression';
-import { getFileStoreState } from '@/store/file/store';
import { sleep } from '@/utils/sleep';
-import { StreamingHandler } from './StreamingHandler';
import { buildClientRuntimeHost } from './transports/buildClientRuntimeHost';
-import { type StreamChunk } from './types/streaming';
const log = debug('lobe-store:agent-executors');
@@ -62,69 +47,6 @@ const isAbortError = (error: unknown, abortController?: AbortController) =>
const createAbortError = () =>
Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });
-const getGoogleBlockedReason = (error: ChatMessageError): string | undefined => {
- const body = error.body as
- | {
- context?: {
- finishReason?: unknown;
- promptFeedback?: {
- blockReason?: unknown;
- };
- };
- provider?: unknown;
- }
- | undefined;
-
- if (body?.provider !== 'google') return undefined;
-
- const promptFeedbackReason = body.context?.promptFeedback?.blockReason;
- if (typeof promptFeedbackReason === 'string') return promptFeedbackReason;
-
- const finishReason = body.context?.finishReason;
- if (typeof finishReason === 'string') return finishReason;
-
- return undefined;
-};
-
-const localizeGoogleBlockedError = (error: ChatMessageError): ChatMessageError => {
- const blockReason = getGoogleBlockedReason(error);
- if (!blockReason) return error;
-
- const translationKey = `response.GoogleAIBlockReason.${blockReason}`;
- const localized = t(translationKey as any, {
- defaultValue: error.message ?? '',
- ns: 'error',
- }).trim();
-
- if (!localized || localized === translationKey) return error;
-
- const normalizedBody =
- error.body && typeof error.body === 'object' ? (error.body as Record<string, any>) : {};
-
- return {
- ...error,
- body: {
- ...normalizedBody,
- message: localized,
- },
- message: localized,
- };
-};
-
-const localizeError = (error: ChatMessageError): ChatMessageError => {
- const body = error.body as
- | {
- provider?: unknown;
- }
- | undefined;
-
- if (body?.provider === 'google') {
- return localizeGoogleBlockedError(error);
- }
-
- return error;
-};
-
const formatSubAgentBatchResultContent = (
tasks: SubAgentTask[],
results: SubAgentsBatchResultPayload['results'],
@@ -148,7 +70,6 @@ const formatSubAgentBatchResultContent = (
* @param context.get - Store getter function
* @param context.messageKey - Message map key
* @param context.parentId - Parent message ID
- * @param context.skipCreateFirstMessage - Skip first message creation
*/
export const createAgentExecutors = (context: {
/** Pre-resolved agent config with isSubAgent filtering applied */
@@ -158,12 +79,9 @@ export const createAgentExecutors = (context: {
messageKey: string;
operationId: string;
parentId: string;
- skipCreateFirstMessage?: boolean;
/** ToolsEngine for expanding dynamically activated tools */
toolsEngine?: ToolsEngine;
}) => {
- let shouldSkipCreateMessage = context.skipCreateFirstMessage;
-
/**
* Get operation context via closure
* Returns the business context (agentId, topicId, etc.) captured by the operation
@@ -193,499 +111,24 @@ export const createAgentExecutors = (context: {
: opContext.agentId;
};
- /**
- * Get subAgentId and scope for metadata (when scope is 'sub_agent')
- */
- const getMetadataForSubAgent = () => {
- const opContext = getOperationContext();
-
- if (opContext.scope === 'sub_agent' && opContext.subAgentId) {
- return {
- subAgentId: opContext.subAgentId,
- scope: opContext.scope,
- };
- }
- return null;
- };
-
const usePackageExecutor =
(factory: (host: AgentRuntimeHost) => InstructionExecutor): InstructionExecutor =>
(instruction, state, runtimeContext) =>
factory(
buildClientRuntimeHost({
+ agentConfig: context.agentConfig,
get: context.get,
+ metadata: context.metadata,
messageKey: context.messageKey,
operationId: context.operationId,
+ runtimeContext,
stepIndex: state.stepCount,
+ toolsEngine: context.toolsEngine,
}),
)(instruction, state, runtimeContext);
const executors: Partial<Record<AgentInstruction['type'], InstructionExecutor>> = {
- /**
- * Custom call_llm executor
- * Creates assistant message and calls internal_fetchAIChatMessage
- */
- call_llm: async (instruction, state, runtimeContext) => {
- const sessionLogId = `${state.operationId}:${state.stepCount}`;
- const stagePrefix = `[${sessionLogId}][call_llm]`;
-
- const llmPayload = (instruction as AgentInstructionCallLlm)
- .payload as GeneralAgentCallLLMInstructionPayload;
-
- log(
- `${stagePrefix} Starting session. Input: state.messages=%d, llmPayload.messages=%d, messageKey=%s`,
- state.messages.length,
- llmPayload.messages.length,
- context.messageKey,
- );
-
- let assistantMessageId: string;
-
- // Check if we should skip message creation:
- // - shouldSkipCreateMessage is true (e.g., regenerate mode)
- // - BUT if createAssistantMessage is explicitly true, always create new message
- // (e.g., after compression we need a new assistant message)
- if (shouldSkipCreateMessage && !llmPayload.createAssistantMessage) {
- // Skip first creation, subsequent calls will not skip
- assistantMessageId = context.parentId;
- shouldSkipCreateMessage = false;
- } else {
- // Get context from operation
- const opContext = getOperationContext();
- // Get effective agentId (depends on scope)
- const effectiveAgentId = getEffectiveAgentId();
- // Get subAgentId metadata (for sub_agent scope)
- const subAgentMetadata = getMetadataForSubAgent();
-
- // If this is the first regenerated creation of userMessage, llmPayload doesn't have parentMessageId
- // So we assign it this way
- // TODO: Maybe this should be implemented with an init method in the future
- if (!llmPayload.parentMessageId) {
- llmPayload.parentMessageId = context.parentId;
- }
-
- // Build metadata
- const metadata: Record<string, any> = {};
- if (opContext.isSupervisor) {
- metadata.isSupervisor = true;
- }
- if (subAgentMetadata) {
- // Store subAgentId and scope in metadata for sub_agent mode
- // This will be used by conversation-flow to transform agentId for display
- Object.assign(metadata, subAgentMetadata);
- }
-
- // Create assistant message (following server-side pattern)
- const assistantMessageItem = await context.get().optimisticCreateMessage(
- {
- content: LOADING_FLAT,
- groupId: opContext.groupId,
- metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
- model: llmPayload.model,
- parentId: llmPayload.parentMessageId,
- provider: llmPayload.provider,
- role: 'assistant',
- agentId: effectiveAgentId!,
- threadId: opContext.threadId,
- topicId: opContext.topicId ?? undefined,
- },
- { operationId: context.operationId },
- );
-
- if (!assistantMessageItem) {
- throw new Error('Failed to create assistant message');
- }
- assistantMessageId = assistantMessageItem.id;
-
- // Associate the assistant message with the operation for UI loading states
- context.get().associateMessageWithOperation(assistantMessageId, context.operationId);
- }
-
- log(`${stagePrefix} Created assistant message, id: %s`, assistantMessageId);
-
- log(
- `${stagePrefix} calling model-runtime chat (model: %s, messages: %d, tools: %d)`,
- llmPayload.model,
- llmPayload.messages.length,
- llmPayload.tools?.length ?? 0,
- );
-
- // ======== Inlined streaming logic (previously internal_fetchAIChatMessage) ========
- const {
- 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 } = context.agentConfig;
-
- let finalUsage: ModelUsage | undefined;
- let finalToolCalls: MessageToolCall[] | undefined;
-
- // Expand dynamically activated tools (from lobe-activator activateTools API)
- // and merge them into the agent config for this LLM call.
- // Built before the StreamingHandler so we can bind the offered tool
- // names into the transformToolCalls callback ().
- const activatedToolIds = runtimeContext?.stepContext?.activatedToolIds;
- let resolvedAgentConfig = context.agentConfig;
-
- if (activatedToolIds?.length && context.toolsEngine) {
- const additional = context.toolsEngine.generateToolsDetailed({
- context: { isExplicitActivation: true },
- model: agentConfigData.model,
- provider: agentConfigData.provider!,
- skipDefaultTools: true,
- toolIds: activatedToolIds,
- });
-
- if (additional.tools?.length) {
- const mergedEnabledManifests = dedupeBy(
- [...(context.agentConfig.enabledManifests || []), ...additional.enabledManifests],
- (manifest) => manifest.identifier,
- );
- const mergedEnabledToolIds = [
- ...new Set([
- ...(context.agentConfig.enabledToolIds || []),
- ...additional.enabledToolIds,
- ]),
- ];
- const mergedTools = dedupeBy(
- [...(context.agentConfig.tools || []), ...additional.tools],
- (tool) => tool.function.name,
- );
-
- resolvedAgentConfig = {
- ...context.agentConfig,
- enabledManifests: mergedEnabledManifests,
- enabledToolIds: mergedEnabledToolIds,
- tools: mergedTools,
- };
-
- log(
- `${stagePrefix} Injected %d activated tools: %o`,
- activatedToolIds.length,
- activatedToolIds,
- );
- }
- }
-
- // Names of tools actually sent to the LLM this turn. Passed to the
- // resolver's missing-prefix fallback so a model can't reach tools that
- // weren't enabled, and disabled duplicates can't shadow enabled calls.
- const offeredToolNames = (resolvedAgentConfig.tools ?? []).map((tool) => tool.function.name);
-
- // 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: (calls) =>
- context.get().internal_transformToolCalls(calls, offeredToolNames),
- toggleToolCallingStreaming: internal_toggleToolCallingStreaming,
- },
- );
-
- const messages = llmPayload.messages.filter((message) => message.id !== assistantMessageId);
-
- await chatService.createAssistantMessageStream({
- abortController,
- params: {
- agentId: agentId || undefined,
- groupId,
- messages,
- model: llmPayload.model,
- provider: llmPayload.provider,
- resolvedAgentConfig,
- topicId: topicId ?? undefined,
- ...agentConfigData.params,
- },
- initialContext: runtimeContext?.initialContext,
- metadata: context.metadata,
- stepContext: runtimeContext?.stepContext,
- trace: {
- traceId,
- topicId: topicId ?? undefined,
- traceName: TraceNameMap.Conversation,
- },
- onErrorHandle: async (error) => {
- const enrichedError = {
- ...error,
- body: {
- ...error.body,
- traceId: traceId ?? error.body?.traceId,
- },
- };
- const localizedError = localizeError(enrichedError);
-
- await context.get().optimisticUpdateMessageError(assistantMessageId, localizedError, {
- operationId: context.operationId,
- });
- },
- onFinish: async (
- _content,
- { traceId, observationId, toolCalls, reasoning, grounding, usage, speed, type },
- ) => {
- void _content;
-
- 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)
- const latestMessages = context.get().dbMessagesMap[context.messageKey] || [];
-
- log(
- `${stagePrefix} After fetch: dbMessagesMap[${context.messageKey}]=%d messages, available keys=%o`,
- latestMessages.length,
- Object.keys(context.get().dbMessagesMap),
- );
-
- // Get updated assistant message to extract usage/cost information
- const assistantMessage = latestMessages.find((m) => m.id === assistantMessageId);
-
- const toolCalls = tools || [];
-
- // Log llm result
- if (content) {
- log(`[${sessionLogId}][content]`, content);
- }
- if (assistantMessage?.reasoning?.content) {
- log(`[${sessionLogId}][reasoning]`, assistantMessage.reasoning.content);
- }
- if (toolCalls.length > 0) {
- log(`[${sessionLogId}][toolsCalling] `, toolCalls);
- }
-
- // Log usage
- if (currentStepUsage) {
- log(`[${sessionLogId}][usage] %O`, currentStepUsage);
- }
-
- log(
- '[%s:%d] call_llm completed, finishType: %s, outputMessages: %d',
- state.operationId,
- state.stepCount,
- finishType,
- latestMessages.length,
- );
-
- // Accumulate usage and cost to state
- const newState = { ...state, messages: latestMessages };
-
- if (currentStepUsage) {
- // Use UsageCounter to accumulate LLM usage and cost
- const { usage, cost } = UsageCounter.accumulateLLM({
- cost: state.cost,
- model: llmPayload.model,
- modelUsage: currentStepUsage,
- provider: llmPayload.provider,
- usage: state.usage,
- });
-
- newState.usage = usage;
- if (cost) newState.cost = cost;
- }
-
- // If operation was aborted, enter human_abort phase to let agent decide how to handle
- if (finishType === 'abort') {
- log(
- '[%s:%d] call_llm aborted by user, entering human_abort phase',
- state.operationId,
- state.stepCount,
- );
-
- return {
- events: [],
- newState,
- nextContext: {
- payload: {
- reason: 'user_cancelled',
- parentMessageId: assistantMessageId,
- hasToolsCalling: isFunctionCall,
- toolsCalling: toolCalls,
- result: { content, tool_calls },
- },
- phase: 'human_abort',
- session: {
- messageCount: newState.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- return {
- events: [],
- newState,
- nextContext: {
- payload: {
- hasToolsCalling: isFunctionCall,
- parentMessageId: assistantMessageId,
- result: { content, tool_calls },
- toolsCalling: toolCalls,
- } as GeneralAgentCallLLMResultPayload,
- phase: 'llm_result',
- session: {
- messageCount: newState.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- stepUsage: currentStepUsage,
- } as AgentRuntimeContext,
- };
- },
+ call_llm: usePackageExecutor(createCallLlmExecutor),
call_tool: usePackageExecutor(createCallToolExecutor),
diff --git a/src/store/chat/agents/transports/ClientContextBuilder.test.ts b/src/store/chat/agents/transports/ClientContextBuilder.test.ts
new file mode 100644
index 00000000000..9b9c18d1c64
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientContextBuilder.test.ts
@@ -0,0 +1,136 @@
+import { AgentRuntime } from '@lobechat/agent-runtime';
+import type { ToolsEngine } from '@lobechat/context-engine';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_CONFIG } from '@/const/settings';
+import { chatService } from '@/services/chat';
+import type { ResolvedAgentConfig } from '@/services/chat/mecha';
+import type { ChatStore } from '@/store/chat/store';
+
+import { ClientContextBuilder } from './ClientContextBuilder';
+
+describe('ClientContextBuilder', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('prepares context once and resolves step-activated tools for the LLM transport', async () => {
+ const activatedManifest = {
+ api: [{ description: 'Search', name: 'search', parameters: {} }],
+ identifier: 'dynamic-search',
+ meta: { title: 'Search' },
+ type: 'builtin' as const,
+ };
+ const activatedTool = {
+ function: {
+ description: 'Search',
+ name: 'dynamic-search____search',
+ parameters: {},
+ },
+ type: 'function' as const,
+ };
+ const toolsEngine = {
+ generateToolsDetailed: vi.fn().mockReturnValue({
+ enabledManifests: [activatedManifest],
+ enabledToolIds: [activatedManifest.identifier],
+ filteredTools: [],
+ tools: [activatedTool],
+ }),
+ } as unknown as ToolsEngine;
+ const agentConfig: ResolvedAgentConfig = {
+ agentConfig: {
+ ...DEFAULT_AGENT_CONFIG,
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ chatConfig: { ...DEFAULT_AGENT_CHAT_CONFIG },
+ enabledManifests: [],
+ enabledToolIds: [],
+ isBuiltinAgent: false,
+ plugins: [],
+ tools: [],
+ };
+ const store = {
+ operations: {
+ 'operation-1': {
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ metadata: { traceId: 'trace-1' },
+ },
+ },
+ } as unknown as ChatStore;
+ const prepareContext = vi
+ .spyOn(chatService, 'buildAssistantMessageContext')
+ .mockImplementation(async ({ messages, resolvedAgentConfig }) => ({
+ options: {},
+ params: {
+ messages: messages as any,
+ model: 'test-model',
+ provider: 'test-provider',
+ tools: resolvedAgentConfig.tools,
+ },
+ }));
+ const builder = new ClientContextBuilder({
+ agentConfig,
+ get: () => store,
+ operationId: 'operation-1',
+ runtimeContext: {
+ payload: {},
+ phase: 'init',
+ session: {
+ messageCount: 1,
+ sessionId: 'session-1',
+ status: 'running',
+ stepCount: 1,
+ },
+ stepContext: { activatedToolIds: ['dynamic-search'] },
+ },
+ toolsEngine,
+ });
+ const userMessage = { content: 'Question', id: 'user-1', role: 'user' as const };
+ const assistantMessage = { content: '', id: 'assistant-1', role: 'assistant' as const };
+ const state = AgentRuntime.createInitialState({
+ messages: [userMessage],
+ operationId: 'operation-1',
+ operationToolSet: {
+ enabledToolIds: [],
+ manifestMap: {},
+ sourceMap: {},
+ tools: [],
+ },
+ });
+
+ const result = await builder.build({
+ model: 'test-model',
+ payload: {
+ assistantMessageId: assistantMessage.id,
+ messages: [userMessage, assistantMessage],
+ model: 'test-model',
+ provider: 'test-provider',
+ tools: [],
+ } as any,
+ provider: 'test-provider',
+ state,
+ });
+
+ expect(toolsEngine.generateToolsDetailed).toHaveBeenCalledWith(
+ expect.objectContaining({ toolIds: ['dynamic-search'] }),
+ );
+ expect(prepareContext).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messages: [userMessage],
+ resolvedAgentConfig: expect.objectContaining({
+ enabledToolIds: ['dynamic-search'],
+ tools: [activatedTool],
+ }),
+ }),
+ expect.any(Object),
+ );
+ expect(result.resolvedTools).toMatchObject({
+ enabledToolIds: ['dynamic-search'],
+ tools: [activatedTool],
+ });
+ expect(result.modelParameters).toMatchObject({
+ params: { model: 'test-model', provider: 'test-provider', tools: [activatedTool] },
+ });
+ });
+});
diff --git a/src/store/chat/agents/transports/ClientContextBuilder.ts b/src/store/chat/agents/transports/ClientContextBuilder.ts
new file mode 100644
index 00000000000..23ac3c255ad
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientContextBuilder.ts
@@ -0,0 +1,154 @@
+import type {
+ AgentRuntimeContext,
+ ContextBuilder,
+ ContextBuildInput,
+ ContextBuildOutput,
+} from '@lobechat/agent-runtime';
+import { ToolResolver, type ToolsEngine } from '@lobechat/context-engine';
+import type { MessageMetadata } from '@lobechat/types';
+import { TraceNameMap } from '@lobechat/types';
+import { dedupeBy } from '@lobechat/utils';
+
+import { chatService } from '@/services/chat';
+import type { ResolvedAgentConfig } from '@/services/chat/mecha';
+import type { FetchOptions } from '@/services/chat/types';
+import type { ChatStore } from '@/store/chat/store';
+import type { ChatStreamPayload } from '@/types/openai/chat';
+
+export interface ClientLLMModelParameters {
+ options: FetchOptions;
+ params: Omit<Partial<ChatStreamPayload>, 'messages'>;
+}
+
+interface ClientContextBuilderOptions {
+ agentConfig: ResolvedAgentConfig;
+ get: () => ChatStore;
+ metadata?: Pick<MessageMetadata, 'trigger'>;
+ operationId: string;
+ runtimeContext?: AgentRuntimeContext;
+ toolsEngine?: ToolsEngine;
+}
+
+export class ClientContextBuilder implements ContextBuilder {
+ constructor(private readonly context: ClientContextBuilderOptions) {}
+
+ async build(input: ContextBuildInput): Promise<ContextBuildOutput> {
+ const operation = this.context.get().operations[this.context.operationId];
+ if (!operation) throw new Error(`Operation not found: ${this.context.operationId}`);
+
+ const resolvedAgentConfig = this.resolveAgentConfig(input);
+ const manifestMap = Object.fromEntries(
+ (resolvedAgentConfig.enabledManifests ?? []).map((manifest) => [
+ manifest.identifier,
+ manifest,
+ ]),
+ );
+ const operationToolSet = {
+ enabledToolIds: resolvedAgentConfig.enabledToolIds ?? [],
+ executorMap: input.state.operationToolSet?.executorMap,
+ manifestMap,
+ sourceMap: input.state.operationToolSet?.sourceMap ?? {},
+ tools: resolvedAgentConfig.tools ?? [],
+ };
+ const resolvedTools = new ToolResolver().resolve(
+ operationToolSet,
+ {
+ activatedTools: [],
+ ...(input.state.forceFinish && { deactivatedToolIds: ['*'] }),
+ },
+ [],
+ input.payload.allowedToolNames,
+ );
+ const promptAgentConfig: ResolvedAgentConfig = {
+ ...resolvedAgentConfig,
+ enabledManifests: Object.values(resolvedTools.promptManifestMap),
+ enabledToolIds: resolvedTools.enabledToolIds,
+ tools: resolvedTools.tools.length > 0 ? resolvedTools.tools : undefined,
+ };
+ const { agentConfig } = promptAgentConfig;
+ const { agentId, groupId, subAgentId, topicId } = operation.context;
+ const effectiveAgentId = groupId && subAgentId ? subAgentId : agentId;
+ const assistantMessageId = (input.payload as { assistantMessageId?: string })
+ .assistantMessageId;
+ const messages = input.payload.messages.filter(
+ (message) => !assistantMessageId || message.id !== assistantMessageId,
+ );
+ const prepared = await chatService.buildAssistantMessageContext(
+ {
+ agentId: effectiveAgentId || undefined,
+ groupId,
+ messages,
+ model: input.model,
+ provider: input.provider,
+ resolvedAgentConfig: promptAgentConfig,
+ topicId: topicId ?? undefined,
+ ...agentConfig.params,
+ },
+ {
+ initialContext: this.context.runtimeContext?.initialContext,
+ metadata: this.context.metadata,
+ stepContext: this.context.runtimeContext?.stepContext,
+ trace: chatService.mapChatTrace({
+ traceId: operation.metadata?.traceId,
+ topicId: topicId ?? undefined,
+ traceName: TraceNameMap.Conversation,
+ }),
+ },
+ );
+ const { messages: preparedMessages = [], ...params } = prepared.params;
+
+ return {
+ messages: preparedMessages,
+ modelParameters: {
+ options: prepared.options,
+ params,
+ } satisfies ClientLLMModelParameters,
+ preserveThinking:
+ typeof prepared.params.preserveThinking === 'boolean'
+ ? prepared.params.preserveThinking
+ : undefined,
+ replayAssistantReasoning: true,
+ resolvedTools,
+ };
+ }
+
+ private resolveAgentConfig(input: ContextBuildInput): ResolvedAgentConfig {
+ const activatedToolIds = [
+ ...(this.context.runtimeContext?.stepContext?.activatedToolIds ?? []),
+ ...(input.state.activatedStepTools?.map((tool) => tool.id) ?? []),
+ ];
+ const uniqueActivatedToolIds = [...new Set(activatedToolIds)];
+
+ if (!uniqueActivatedToolIds.length || !this.context.toolsEngine) {
+ return this.context.agentConfig;
+ }
+
+ const additional = this.context.toolsEngine.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: input.model,
+ provider: input.provider,
+ skipDefaultTools: true,
+ toolIds: uniqueActivatedToolIds,
+ });
+
+ if (!additional.tools?.length) return this.context.agentConfig;
+
+ return {
+ ...this.context.agentConfig,
+ enabledManifests: dedupeBy(
+ [...(this.context.agentConfig.enabledManifests ?? []), ...additional.enabledManifests],
+ (manifest) => manifest.identifier,
+ ),
+ enabledToolIds: [
+ ...new Set([
+ ...(this.context.agentConfig.enabledToolIds ?? []),
+ ...additional.enabledToolIds,
+ ]),
+ ],
+ tools: dedupeBy(
+ [...(this.context.agentConfig.tools ?? []), ...additional.tools],
+ (tool) => tool.function.name,
+ ),
+ };
+ }
+}
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.ts b/src/store/chat/agents/transports/ClientLLMTransport.ts
new file mode 100644
index 00000000000..6811508ab0e
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientLLMTransport.ts
@@ -0,0 +1,431 @@
+import type {
+ LLMAttemptExecution,
+ LLMAttemptInput,
+ LLMAttemptOutput,
+ LLMCallErrorInput,
+ LLMRetryInput,
+ LLMRetryPolicy,
+ LLMStreamPayload,
+ LLMStreamResult,
+ LLMTransport,
+} from '@lobechat/agent-runtime';
+import {
+ classifyLLMError,
+ resolveLLMMaxAttempts,
+ resolveLLMRetryBudget,
+} from '@lobechat/agent-runtime';
+import { BRANDING_PROVIDER } from '@lobechat/business-const';
+import { isEmptyModelCompletion, ModelEmptyError } from '@lobechat/model-runtime';
+import type { ChatMessageError, MessageMetadata, ModelReasoning } from '@lobechat/types';
+import { ChatErrorType } from '@lobechat/types';
+import { t } from 'i18next';
+
+import { chatService } from '@/services/chat';
+import { getFileStoreState } from '@/store/file/store';
+import { sleep } from '@/utils/sleep';
+
+import type { ChatStore } from '../../store';
+import { StreamingHandler } from '../StreamingHandler';
+import type { StreamChunk, StreamingResult } from '../types/streaming';
+import type { ClientLLMModelParameters } from './ClientContextBuilder';
+import type { ClientRuntimeSession } from './ClientRuntimeStreamSink';
+
+const CLIENT_LLM_RETRY_POLICY = {
+ isEmptyCompletionError: (error: unknown) => error instanceof ModelEmptyError,
+ noRetryProviders: [BRANDING_PROVIDER],
+};
+
+const createStreamExecutionError = (errorData: unknown) => {
+ if (errorData instanceof Error) return errorData;
+
+ const record =
+ errorData && typeof errorData === 'object' ? (errorData as Record<string, any>) : undefined;
+ const message =
+ (typeof record?.message === 'string' && record.message) ||
+ (typeof errorData === 'string' ? errorData : JSON.stringify(errorData));
+ const error = new Error(message || 'LLM stream failed');
+
+ if (record) Object.assign(error, record);
+ return error;
+};
+
+const getGoogleBlockedReason = (error: ChatMessageError): string | undefined => {
+ const body = error.body as
+ | {
+ context?: { finishReason?: unknown; promptFeedback?: { blockReason?: unknown } };
+ provider?: unknown;
+ }
+ | undefined;
+
+ if (body?.provider !== 'google') return undefined;
+
+ const promptFeedbackReason = body.context?.promptFeedback?.blockReason;
+ if (typeof promptFeedbackReason === 'string') return promptFeedbackReason;
+
+ const finishReason = body.context?.finishReason;
+ return typeof finishReason === 'string' ? finishReason : undefined;
+};
+
+const localizeError = (error: ChatMessageError): ChatMessageError => {
+ const blockReason = getGoogleBlockedReason(error);
+ if (!blockReason) return error;
+
+ const translationKey = `response.GoogleAIBlockReason.${blockReason}`;
+ const localized = t(translationKey as any, {
+ defaultValue: error.message ?? '',
+ ns: 'error',
+ }).trim();
+
+ if (!localized || localized === translationKey) return error;
+
+ return {
+ ...error,
+ body: {
+ ...(error.body && typeof error.body === 'object' ? error.body : {}),
+ message: localized,
+ },
+ message: localized,
+ };
+};
+
+const toChatMessageError = (error: unknown, traceId?: string): ChatMessageError => {
+ const record = error && typeof error === 'object' ? (error as Record<string, any>) : {};
+ const body = record.body && typeof record.body === 'object' ? record.body : record;
+
+ return localizeError({
+ ...record,
+ body: { ...body, ...(traceId && { traceId }) },
+ message:
+ typeof record.message === 'string'
+ ? record.message
+ : error instanceof Error
+ ? error.message
+ : String(error),
+ type: record.errorType ?? record.type ?? ChatErrorType.UnknownChatFetchError,
+ });
+};
+
+class ClientLLMRetryPolicy implements LLMRetryPolicy {
+ constructor(
+ private readonly get: () => ChatStore,
+ private readonly operationId: string,
+ private readonly session: ClientRuntimeSession,
+ ) {}
+
+ classifyError(error: unknown) {
+ return classifyLLMError(error);
+ }
+
+ maxAttempts(provider: string) {
+ return resolveLLMMaxAttempts(provider, CLIENT_LLM_RETRY_POLICY);
+ }
+
+ onError({ error, events, interrupted, retryBudget }: LLMCallErrorInput) {
+ if (error instanceof ModelEmptyError && error.diagnostics) {
+ error.diagnostics.retryBudget = retryBudget;
+ error.diagnostics.retryEvents = events
+ .filter((event) => event.type === 'stream_retry')
+ .map((event) => event.data);
+ }
+
+ if (interrupted || !this.session.assistantMessageId) return;
+
+ const localizedError = toChatMessageError(
+ error,
+ this.get().operations[this.operationId]?.metadata?.traceId,
+ );
+ if (error && typeof error === 'object') Object.assign(error, localizedError);
+ this.get().internal_dispatchMessage(
+ {
+ id: this.session.assistantMessageId,
+ type: 'updateMessage',
+ value: { error: localizedError },
+ },
+ { operationId: this.operationId },
+ );
+ }
+
+ onRetry(_input: LLMRetryInput) {
+ // The package publishes the canonical stream_retry event through StreamSink.
+ }
+
+ resolveRetryBudget(provider: string, error: unknown) {
+ return resolveLLMRetryBudget(provider, error, CLIENT_LLM_RETRY_POLICY);
+ }
+
+ async waitForRetry(delayMs: number): Promise<void> {
+ await sleep(delayMs);
+ }
+}
+
+interface ClientLLMTransportOptions {
+ get: () => ChatStore;
+ metadata?: Pick<MessageMetadata, 'trigger'>;
+ operationId: string;
+ session: ClientRuntimeSession;
+}
+
+export class ClientLLMTransport implements LLMTransport {
+ readonly retryPolicy: LLMRetryPolicy;
+
+ constructor(private readonly context: ClientLLMTransportOptions) {
+ this.retryPolicy = new ClientLLMRetryPolicy(context.get, context.operationId, context.session);
+ }
+
+ async runAttempt(input: LLMAttemptInput): Promise<LLMAttemptExecution> {
+ const operation = this.context.get().operations[this.context.operationId];
+ if (!operation) throw new Error(`Operation not found: ${this.context.operationId}`);
+
+ const assistantMessageId = this.context.session.assistantMessageId;
+ if (!assistantMessageId) throw new Error('Client call_llm stream started without a message id');
+
+ const { groupId, subAgentId, topicId } = operation.context;
+ const agentId = groupId && subAgentId ? subAgentId : operation.context.agentId!;
+ const modelParameters = input.context.modelParameters as ClientLLMModelParameters | undefined;
+ if (!modelParameters) throw new Error('Client call_llm requires prepared model parameters');
+
+ const offeredToolNames = (input.context.resolvedTools?.tools ?? []).map(
+ (tool) => tool.function.name,
+ );
+ const handler = new StreamingHandler(
+ {
+ agentId,
+ groupId,
+ messageId: assistantMessageId,
+ operationId: this.context.operationId,
+ topicId,
+ },
+ {
+ onContentUpdate: (content, reasoning, contentMetadata) => {
+ this.dispatchMessage(assistantMessageId, {
+ content,
+ reasoning,
+ ...(contentMetadata && {
+ metadata: {
+ isMultimodal: contentMetadata.isMultimodal,
+ tempDisplayContent: contentMetadata.tempDisplayContent,
+ },
+ }),
+ });
+ },
+ onGroundingUpdate: (search) => this.dispatchMessage(assistantMessageId, { search }),
+ onImagesUpdate: (imageList) => this.dispatchMessage(assistantMessageId, { imageList }),
+ onReasoningComplete: (operationId) => this.context.get().completeOperation(operationId),
+ onReasoningStart: () => {
+ const { operationId } = this.context.get().startOperation({
+ context: { ...operation.context, agentId, messageId: assistantMessageId },
+ parentOperationId: this.context.operationId,
+ type: 'reasoning',
+ });
+ this.context.get().associateMessageWithOperation(assistantMessageId, operationId);
+ return operationId;
+ },
+ onReasoningUpdate: (reasoning) => this.dispatchMessage(assistantMessageId, { reasoning }),
+ onToolCallsUpdate: (tools) => this.dispatchMessage(assistantMessageId, { tools }),
+ toggleToolCallingStreaming: this.context.get().internal_toggleToolCallingStreaming,
+ transformToolCalls: (calls) =>
+ this.context.get().internal_transformToolCalls(calls, offeredToolNames),
+ uploadBase64Image: (data) =>
+ getFileStoreState()
+ .uploadBase64FileWithProgress(data)
+ .then((file) => ({
+ alt: file?.filename || file?.id,
+ id: file?.id,
+ url: file?.url,
+ })),
+ },
+ );
+
+ let finalResult: StreamingResult | undefined;
+ let finishData: Parameters<StreamingHandler['handleFinish']>[0] = {};
+ let streamError: unknown;
+ let firstChunkReceived = false;
+ const markFirstChunk = () => {
+ if (firstChunkReceived) return;
+ firstChunkReceived = true;
+ input.onFirstChunk?.();
+ };
+
+ try {
+ await chatService.getChatCompletion(
+ {
+ ...modelParameters.params,
+ messages: input.context.messages as any,
+ model: input.model,
+ provider: input.provider,
+ },
+ {
+ ...modelParameters.options,
+ metadata: this.context.metadata,
+ onErrorHandle: (error) => {
+ streamError = createStreamExecutionError(error);
+ },
+ onFinish: async (
+ _content,
+ { traceId, observationId, toolCalls, reasoning, grounding, usage, speed, type },
+ ) => {
+ finishData = {
+ grounding,
+ observationId,
+ reasoning,
+ speed,
+ toolCalls,
+ traceId,
+ type,
+ usage,
+ };
+ finalResult = await handler.handleFinish(finishData);
+ },
+ onMessageHandle: async (chunk) => {
+ markFirstChunk();
+ handler.handleChunk(chunk as StreamChunk);
+ },
+ signal: operation.abortController.signal,
+ },
+ );
+ } catch (error) {
+ streamError = error;
+ }
+
+ const interrupted =
+ operation.abortController.signal.aborted ||
+ this.context.get().operations[this.context.operationId]?.status === 'cancelled';
+ if (interrupted && !finishData.type) finishData.type = 'abort';
+ if (interrupted && finalResult && !finalResult.finishType) {
+ finalResult = {
+ ...finalResult,
+ finishType: 'abort',
+ metadata: { ...finalResult.metadata, finishType: 'abort' },
+ };
+ }
+
+ finalResult ??= await handler.handleFinish(finishData);
+ const output = this.buildAttemptOutput(handler, finalResult, finishData);
+
+ if (streamError && !interrupted) return { error: streamError, ok: false, output };
+
+ if (
+ isEmptyModelCompletion({
+ content: output.content,
+ imageCount: output.imageList.length + (output.hasContentImages ? 1 : 0),
+ outputTokens: output.usage?.totalOutputTokens,
+ reasoning: output.thinkingContent,
+ toolCallCount: output.toolsCalling.length + output.toolCalls.length,
+ }) &&
+ !interrupted
+ ) {
+ return {
+ error: new ModelEmptyError(undefined, {
+ attempt: input.attempt,
+ contentLength: output.content.length,
+ finishReason: output.finishReason,
+ imageCount: output.imageList.length,
+ maxAttempts: input.maxAttempts,
+ model: input.model,
+ outputTokens: output.usage?.totalOutputTokens,
+ provider: input.provider,
+ reasoningLength: output.thinkingContent.length,
+ toolCallCount: output.toolsCalling.length + output.toolCalls.length,
+ }),
+ ok: false,
+ output,
+ };
+ }
+
+ return { ok: true, output };
+ }
+
+ async stream(
+ payload: LLMStreamPayload,
+ handlers?: Parameters<LLMTransport['stream']>[1],
+ signal?: AbortSignal,
+ ): Promise<LLMStreamResult> {
+ let content = '';
+ let reasoning = '';
+ let usage: LLMStreamResult['usage'];
+ let streamError: unknown;
+
+ await chatService.getChatCompletion(payload as any, {
+ onErrorHandle: (error) => {
+ streamError = createStreamExecutionError(error);
+ handlers?.onError?.(streamError);
+ },
+ onFinish: async (_content, data) => {
+ content = _content || content;
+ reasoning = data.reasoning?.content || reasoning;
+ usage = data.usage;
+ },
+ onMessageHandle: (chunk) => {
+ const streamChunk = chunk as StreamChunk;
+ handlers?.onChunk?.(streamChunk);
+ if (streamChunk.type === 'text') {
+ content += streamChunk.text;
+ handlers?.onText?.(streamChunk.text);
+ }
+ if (streamChunk.type === 'reasoning') reasoning += streamChunk.text;
+ },
+ signal,
+ });
+
+ if (streamError) throw streamError;
+
+ const result = { content, reasoning, usage };
+ handlers?.onFinish?.(result);
+ return result;
+ }
+
+ private buildAttemptOutput(
+ handler: StreamingHandler,
+ result: StreamingResult,
+ finishData: Parameters<StreamingHandler['handleFinish']>[0],
+ ): LLMAttemptOutput {
+ let content = handler.getOutput();
+ let thinkingContent = handler.getThinkingContent();
+ let reasoning = result.metadata.reasoning as ModelReasoning | undefined;
+ let answerSalvagedFromReasoning = false;
+ const isTerminalStop = result.finishType === 'end_turn' || result.finishType === 'stop';
+
+ if (
+ isTerminalStop &&
+ !content.trim() &&
+ thinkingContent.trim() &&
+ !handler.hasReasoningImages() &&
+ !result.tools?.length &&
+ !result.toolCalls?.length
+ ) {
+ content = thinkingContent;
+ thinkingContent = '';
+ reasoning = undefined;
+ answerSalvagedFromReasoning = true;
+ }
+
+ return {
+ answerSalvagedFromReasoning,
+ content,
+ contentParts: handler.getContentParts(),
+ finishReason: result.finishType,
+ grounding: result.metadata.search ?? null,
+ hasContentImages: handler.hasContentImages(),
+ hasReasoningImages: handler.hasReasoningImages(),
+ imageList: result.metadata.imageList ?? [],
+ observationId: finishData.observationId ?? undefined,
+ reasoning,
+ reasoningParts: handler.getReasoningParts(),
+ speed: result.metadata.performance,
+ thinkingContent,
+ toolCalls: result.toolCalls ?? [],
+ toolsCalling: result.tools ?? [],
+ traceId: finishData.traceId ?? undefined,
+ usage: result.usage,
+ };
+ }
+
+ private dispatchMessage(id: string, value: Record<string, unknown>) {
+ this.context
+ .get()
+ .internal_dispatchMessage(
+ { id, type: 'updateMessage', value },
+ { operationId: this.context.operationId },
+ );
+ }
+}
diff --git a/src/store/chat/agents/transports/ClientMessageTransport.test.ts b/src/store/chat/agents/transports/ClientMessageTransport.test.ts
index 02d95835c28..7725941eea5 100644
--- a/src/store/chat/agents/transports/ClientMessageTransport.test.ts
+++ b/src/store/chat/agents/transports/ClientMessageTransport.test.ts
@@ -10,6 +10,11 @@ const createStore = () =>
({
dbMessagesMap: { 'message-key': [] },
internal_dispatchMessage: vi.fn(),
+ operations: {
+ 'operation-1': {
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ },
+ },
optimisticCreateMessage: vi.fn(),
optimisticUpdatePluginState: vi.fn(),
optimisticUpdateToolMessage: vi.fn(),
diff --git a/src/store/chat/agents/transports/ClientMessageTransport.ts b/src/store/chat/agents/transports/ClientMessageTransport.ts
index b5dbacf1ada..311fcd11a57 100644
--- a/src/store/chat/agents/transports/ClientMessageTransport.ts
+++ b/src/store/chat/agents/transports/ClientMessageTransport.ts
@@ -26,7 +26,26 @@ export class ClientMessageTransport implements MessageTransport {
) {}
createAssistantMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
- return this.createMessage(params);
+ const operation = this.get().operations[this.operationId];
+ if (!operation) throw new Error(`Operation not found: ${this.operationId}`);
+
+ const { agentId, groupId, isSupervisor, scope, subAgentId, threadId, topicId } =
+ operation.context;
+ const effectiveAgentId = subAgentId && scope !== 'sub_agent' ? subAgentId : agentId;
+ const metadata = {
+ ...params.metadata,
+ ...(isSupervisor && { isSupervisor: true }),
+ ...(scope === 'sub_agent' && subAgentId && { scope, subAgentId }),
+ };
+
+ return this.createMessage({
+ ...params,
+ ...(effectiveAgentId && { agentId: effectiveAgentId }),
+ ...(groupId && { groupId }),
+ ...(Object.keys(metadata).length > 0 && { metadata }),
+ ...(threadId && { threadId }),
+ ...(topicId && { topicId }),
+ });
}
createToolMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
@@ -45,7 +64,14 @@ export class ClientMessageTransport implements MessageTransport {
}
async findById(id: string): Promise<RuntimeMessageRef | undefined> {
- return this.getMessages().find((message) => message.id === id);
+ for (const message of this.getMessages()) {
+ if (message.id === id) return message;
+
+ const compressedMessage = message.compressedMessages?.find((item) => item.id === id);
+ if (compressedMessage) return compressedMessage;
+ }
+
+ return undefined;
}
async query(
@@ -120,7 +146,7 @@ export class ClientMessageTransport implements MessageTransport {
const optimisticContext = { operationId };
store.internal_dispatchMessage(
- { id, type: 'createMessage', value: message },
+ { id, type: 'createMessage', value: { ...message } },
optimisticContext,
);
diff --git a/src/store/chat/agents/transports/ClientRuntimeStreamSink.ts b/src/store/chat/agents/transports/ClientRuntimeStreamSink.ts
new file mode 100644
index 00000000000..603aeca1b40
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientRuntimeStreamSink.ts
@@ -0,0 +1,90 @@
+import type { RuntimeStreamEvent, StreamErrorInput, StreamSink } from '@lobechat/agent-runtime';
+import { ChatErrorType, type ChatMessageError } from '@lobechat/types';
+
+import type { ChatStore } from '@/store/chat/store';
+
+export interface ClientRuntimeSession {
+ assistantMessageId?: string;
+}
+
+const toChatMessageError = (error: unknown): ChatMessageError => {
+ if (error && typeof error === 'object') {
+ const record = error as Record<string, any>;
+ const type = record.errorType ?? record.type ?? ChatErrorType.UnknownChatFetchError;
+
+ return {
+ ...record,
+ body: record.body,
+ message: typeof record.message === 'string' ? record.message : String(error),
+ type,
+ };
+ }
+
+ return {
+ body: error,
+ message: error instanceof Error ? error.message : String(error),
+ type: ChatErrorType.UnknownChatFetchError,
+ };
+};
+
+export class ClientRuntimeStreamSink implements StreamSink {
+ constructor(
+ private readonly get: () => ChatStore,
+ private readonly operationId: string,
+ private readonly session: ClientRuntimeSession,
+ ) {}
+
+ async publishChunk(): Promise<void> {}
+
+ async publishError({ error }: StreamErrorInput): Promise<void> {
+ if (!this.session.assistantMessageId) return;
+
+ this.get().internal_dispatchMessage(
+ {
+ id: this.session.assistantMessageId,
+ type: 'updateMessage',
+ value: { error: toChatMessageError(error) },
+ },
+ { operationId: this.operationId },
+ );
+ }
+
+ async publishEvent(event: RuntimeStreamEvent): Promise<void> {
+ if (event.type === 'stream_start') {
+ const assistantMessage = (event.data as { assistantMessage?: { id?: string } })
+ .assistantMessage;
+ if (!assistantMessage?.id) return;
+
+ this.session.assistantMessageId = assistantMessage.id;
+ this.get().associateMessageWithOperation(assistantMessage.id, this.operationId);
+ return;
+ }
+
+ if (event.type === 'stream_retry') {
+ const data = event.data as {
+ attempt?: number;
+ delayMs?: number;
+ errorType?: string;
+ maxAttempts?: number;
+ };
+ this.get().updateOperationMetadata(this.operationId, {
+ streamRetry: {
+ attempt: data.attempt,
+ delayMs: data.delayMs,
+ error: data.errorType,
+ maxAttempts: data.maxAttempts,
+ },
+ });
+ return;
+ }
+
+ if (event.type === 'stream_end') {
+ this.get().updateOperationMetadata(this.operationId, { streamRetry: undefined });
+ return;
+ }
+
+ if (event.type === 'visible_output_end') {
+ this.get().updateOperationMetadata(this.operationId, { visibleLoadingDone: true });
+ }
+ }
+}
diff --git a/src/store/chat/agents/transports/buildClientRuntimeHost.ts b/src/store/chat/agents/transports/buildClientRuntimeHost.ts
index 3c018932b2e..143a569907f 100644
--- a/src/store/chat/agents/transports/buildClientRuntimeHost.ts
+++ b/src/store/chat/agents/transports/buildClientRuntimeHost.ts
@@ -1,26 +1,30 @@
-import type { AgentRuntimeHost, OperationStore, StreamSink } from '@lobechat/agent-runtime';
+import type {
+ AgentRuntimeContext,
+ AgentRuntimeHost,
+ AgentState,
+ OperationStore,
+} from '@lobechat/agent-runtime';
+import type { ToolsEngine } from '@lobechat/context-engine';
+import type { MessageMetadata } from '@lobechat/types';
+import type { ResolvedAgentConfig } from '@/services/chat/mecha';
import type { ChatStore } from '@/store/chat/store';
+import { ClientContextBuilder } from './ClientContextBuilder';
+import { ClientLLMTransport } from './ClientLLMTransport';
import { ClientMessageTransport } from './ClientMessageTransport';
+import { type ClientRuntimeSession, ClientRuntimeStreamSink } from './ClientRuntimeStreamSink';
import { ClientToolTransport } from './ClientToolTransport';
-const localOperationStore: OperationStore = {
- clearRunningMark: async () => {},
-};
-
-// Client runs consume returned AgentEvents directly. Transport stream output is
-// only needed by remote server runs, where it is forwarded through Redis/SSE.
-const localStreamSink: StreamSink = {
- publishChunk: async () => {},
- publishEvent: async () => {},
-};
-
export const buildClientRuntimeHost = (context: {
+ agentConfig: ResolvedAgentConfig;
get: () => ChatStore;
+ metadata?: Pick<MessageMetadata, 'trigger'>;
messageKey: string;
operationId: string;
+ runtimeContext?: AgentRuntimeContext;
stepIndex: number;
+ toolsEngine?: ToolsEngine;
}): AgentRuntimeHost => {
const runtimeOperation = context.get().operations[context.operationId];
if (!runtimeOperation) throw new Error(`Operation not found: ${context.operationId}`);
@@ -28,6 +32,17 @@ export const buildClientRuntimeHost = (context: {
const { agentId, groupId, scope, subAgentId, threadId, topicId } = runtimeOperation.context;
const effectiveAgentId = subAgentId && scope !== 'sub_agent' ? subAgentId : agentId;
const messages = new ClientMessageTransport(context.get, context.messageKey, context.operationId);
+ const session: ClientRuntimeSession = {};
+ const stream = new ClientRuntimeStreamSink(context.get, context.operationId, session);
+ const operationStore: OperationStore = {
+ clearRunningMark: async () => {},
+ loadState: async (operationId) => {
+ const operation = context.get().operations[operationId];
+ if (operation?.status !== 'cancelled') return null;
+
+ return { status: 'interrupted' } as AgentState;
+ },
+ };
return {
operation: {
@@ -39,9 +54,23 @@ export const buildClientRuntimeHost = (context: {
topicId: topicId ?? undefined,
},
transports: {
+ context: new ClientContextBuilder({
+ agentConfig: context.agentConfig,
+ get: context.get,
+ metadata: context.metadata,
+ operationId: context.operationId,
+ runtimeContext: context.runtimeContext,
+ toolsEngine: context.toolsEngine,
+ }),
+ llm: new ClientLLMTransport({
+ get: context.get,
+ metadata: context.metadata,
+ operationId: context.operationId,
+ session,
+ }),
messages,
- operationStore: localOperationStore,
- stream: localStreamSink,
+ operationStore,
+ stream,
tools: new ClientToolTransport(
context.get,
context.messageKey,
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index 3c66461f9a1..72024c6c51e 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -132,6 +132,53 @@ const mockInternalCreateAgentState = (value: ReturnType<typeof realCreateAgentSt
});
};
+const spyOnClientLLMStream = (
+ implementation: (input: {
+ initialContext?: unknown;
+ onFinish?: (...args: any[]) => Promise<void>;
+ params: Record<string, any>;
+ trace?: unknown;
+ }) => Promise<void> = async ({ onFinish }) => {
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});
+ },
+) => {
+ vi.spyOn(chatService, 'buildAssistantMessageContext').mockImplementation(
+ async (params, options) => ({
+ options: options ?? {},
+ params: { ...params, messages: params.messages as any } as any,
+ }),
+ );
+
+ return vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (params, options) => {
+ const onFinish = async (...args: any[]) => {
+ const content = args[0];
+ if (content) options?.onMessageHandle?.({ text: content, type: 'text' } as any);
+ await options?.onFinish?.(args[0], args[1]);
+ };
+ await implementation({
+ initialContext: options?.initialContext,
+ onFinish,
+ params,
+ trace: options?.trace,
+ });
+ return new Response();
+ });
+};
+
+const seedDbMessages = (
+ context: Parameters<typeof messageMapKey>[0],
+ messages: UIChatMessage[],
+) => {
+ act(() => {
+ useChatStore.setState((state) => ({
+ dbMessagesMap: {
+ ...state.dbMessagesMap,
+ [messageMapKey(context)]: messages,
+ },
+ }));
+ });
+};
+
beforeEach(() => {
resetTestEnvironment();
setupMockSelectors();
@@ -172,12 +219,11 @@ describe('StreamingExecutor actions', () => {
topicId: TEST_IDS.TOPIC_ID,
} as UIChatMessage;
const messages = [userMessage];
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, messages);
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
- });
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
+ });
await act(async () => {
await result.current.executeClientAgent({
@@ -228,31 +274,30 @@ describe('StreamingExecutor actions', () => {
topicId: TEST_IDS.TOPIC_ID,
} as UIChatMessage;
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
let streamCallCount = 0;
let cancelDuringFirstCall = false;
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- streamCallCount++;
-
- // Cancel during the first LLM call to simulate mid-execution cancellation
- if (streamCallCount === 1) {
- const operations = Object.values(result.current.operations);
- const execOperation = operations.find((op) => op.type === 'execAgentRuntime');
- if (execOperation) {
- act(() => {
- result.current.cancelOperation(execOperation.id, 'user_cancelled');
- });
- cancelDuringFirstCall = true;
- }
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {
+ streamCallCount++;
+
+ // Cancel during the first LLM call to simulate mid-execution cancellation
+ if (streamCallCount === 1) {
+ const operations = Object.values(result.current.operations);
+ const execOperation = operations.find((op) => op.type === 'execAgentRuntime');
+ if (execOperation) {
+ act(() => {
+ result.current.cancelOperation(execOperation.id, 'user_cancelled');
+ });
+ cancelDuringFirstCall = true;
}
+ }
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
- toolCalls: [
- { 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 () => {
await result.current.executeClientAgent({
@@ -285,35 +330,34 @@ describe('StreamingExecutor actions', () => {
topicId: TEST_IDS.TOPIC_ID,
} as UIChatMessage;
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
let streamCallCount = 0;
let cancelledAfterStep = false;
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- streamCallCount++;
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {
+ streamCallCount++;
- // First call - LLM returns tool calls
- if (streamCallCount === 1) {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
- toolCalls: [
- { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },
- ],
- } as any);
-
- // Cancel immediately after LLM step completes
- // This triggers the after-step cancellation check
- await new Promise((resolve) => setTimeout(resolve, 20));
- const operations = Object.values(result.current.operations);
- const execOperation = operations.find((op) => op.type === 'execAgentRuntime');
- if (execOperation && execOperation.status === 'running') {
- act(() => {
- result.current.cancelOperation(execOperation.id, 'user_cancelled');
- });
- cancelledAfterStep = true;
- }
+ // First call - LLM returns tool calls
+ if (streamCallCount === 1) {
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
+ toolCalls: [
+ { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },
+ ],
+ } as any);
+
+ // Cancel immediately after LLM step completes
+ // This triggers the after-step cancellation check
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ const operations = Object.values(result.current.operations);
+ const execOperation = operations.find((op) => op.type === 'execAgentRuntime');
+ if (execOperation && execOperation.status === 'running') {
+ act(() => {
+ result.current.cancelOperation(execOperation.id, 'user_cancelled');
+ });
+ cancelledAfterStep = true;
}
- });
+ }
+ });
await act(async () => {
await result.current.executeClientAgent({
@@ -375,11 +419,10 @@ describe('StreamingExecutor actions', () => {
topicId: TEST_IDS.TOPIC_ID,
} as UIChatMessage;
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
- });
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
+ });
await act(async () => {
await result.current.executeClientAgent({
@@ -421,11 +464,10 @@ describe('StreamingExecutor actions', () => {
topicId: TEST_IDS.TOPIC_ID,
} as UIChatMessage;
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
- });
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
+ });
await act(async () => {
await result.current.executeClientAgent({
@@ -458,43 +500,42 @@ describe('StreamingExecutor actions', () => {
topicId: TEST_IDS.TOPIC_ID,
} as UIChatMessage;
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
let cancelledAfterLLM = false;
let streamCallCount = 0;
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish }) => {
- streamCallCount++;
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish }) => {
+ streamCallCount++;
- // First call - LLM returns with tool calls
- if (streamCallCount === 1) {
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
- toolCalls: [
- {
- id: 'tool-1',
- type: 'function',
- function: { name: 'weatherQuery', arguments: '{"city":"Beijing"}' },
- },
- {
- id: 'tool-2',
- type: 'function',
- function: { name: 'calculator', arguments: '{"expression":"1+1"}' },
- },
- ],
- } as any);
-
- // User cancels after LLM completes but before tool execution
- await new Promise((resolve) => setTimeout(resolve, 20));
- const operations = Object.values(result.current.operations);
- const execOperation = operations.find((op) => op.type === 'execAgentRuntime');
- if (execOperation && execOperation.status === 'running') {
- act(() => {
- result.current.cancelOperation(execOperation.id, 'user_cancelled');
- });
- cancelledAfterLLM = true;
- }
+ // First call - LLM returns with tool calls
+ if (streamCallCount === 1) {
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
+ toolCalls: [
+ {
+ id: 'tool-1',
+ type: 'function',
+ function: { name: 'weatherQuery', arguments: '{"city":"Beijing"}' },
+ },
+ {
+ id: 'tool-2',
+ type: 'function',
+ function: { name: 'calculator', arguments: '{"expression":"1+1"}' },
+ },
+ ],
+ } as any);
+
+ // User cancels after LLM completes but before tool execution
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ const operations = Object.values(result.current.operations);
+ const execOperation = operations.find((op) => op.type === 'execAgentRuntime');
+ if (execOperation && execOperation.status === 'running') {
+ act(() => {
+ result.current.cancelOperation(execOperation.id, 'user_cancelled');
+ });
+ cancelledAfterLLM = true;
}
- });
+ }
+ });
await act(async () => {
await result.current.executeClientAgent({
@@ -540,7 +581,8 @@ describe('StreamingExecutor actions', () => {
topicId: contextTopicId,
} as UIChatMessage;
- const streamSpy = vi.spyOn(chatService, 'createAssistantMessageStream');
+ seedDbMessages({ agentId: contextSessionId, topicId: contextTopicId }, [userMessage]);
+ const streamSpy = spyOnClientLLMStream();
await act(async () => {
await result.current.executeClientAgent({
@@ -553,6 +595,7 @@ describe('StreamingExecutor actions', () => {
// Verify trace was called with context topicId, not active ones
expect(streamSpy).toHaveBeenCalledWith(
+ expect.any(Object),
expect.objectContaining({
trace: expect.objectContaining({
topicId: contextTopicId,
@@ -884,24 +927,24 @@ describe('StreamingExecutor actions', () => {
const capturedInitialContexts: any[] = [];
let streamCallCount = 0;
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish, initialContext }) => {
- streamCallCount++;
- capturedInitialContexts.push(initialContext);
-
- if (streamCallCount === 1) {
- // First LLM call returns tool calls
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
- toolCalls: [
- { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },
- ],
- } as any);
- } else {
- // Second LLM call (after tool execution) returns final response
- await onFinish?.('Final response', {} as any);
- }
- });
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
+
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish, initialContext }) => {
+ streamCallCount++;
+ capturedInitialContexts.push(initialContext);
+
+ if (streamCallCount === 1) {
+ // First LLM call returns tool calls
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
+ toolCalls: [
+ { id: 'tool-1', type: 'function', function: { name: 'test', arguments: '{}' } },
+ ],
+ } as any);
+ } else {
+ // Second LLM call (after tool execution) returns final response
+ await onFinish?.('Final response', {} as any);
+ }
+ });
// Mock internal_createAgentState to include initialContext
const mockInitialContext = {
@@ -962,28 +1005,28 @@ describe('StreamingExecutor actions', () => {
const capturedInitialContexts: any[] = [];
let streamCallCount = 0;
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish, initialContext }) => {
- streamCallCount++;
- capturedInitialContexts.push(initialContext);
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
- if (streamCallCount < 3) {
- // Return tool calls to continue the loop
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
- toolCalls: [
- {
- id: `tool-${streamCallCount}`,
- type: 'function',
- function: { name: 'test', arguments: '{}' },
- },
- ],
- } as any);
- } else {
- // Final response without tool calls
- await onFinish?.('Final response', {} as any);
- }
- });
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish, initialContext }) => {
+ streamCallCount++;
+ capturedInitialContexts.push(initialContext);
+
+ if (streamCallCount < 3) {
+ // Return tool calls to continue the loop
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {
+ toolCalls: [
+ {
+ id: `tool-${streamCallCount}`,
+ type: 'function',
+ function: { name: 'test', arguments: '{}' },
+ },
+ ],
+ } as any);
+ } else {
+ // Final response without tool calls
+ await onFinish?.('Final response', {} as any);
+ }
+ });
const mockInitialContext = {
pageEditor: {
@@ -1541,25 +1584,25 @@ describe('StreamingExecutor actions', () => {
}),
} as any);
- const streamSpy = vi
- .spyOn(chatService, 'createAssistantMessageStream')
- .mockImplementation(async ({ onFinish, params }) => {
- expect(params.resolvedAgentConfig.enabledToolIds).toEqual([
- 'lobe-artifacts',
- 'lobe-notebook',
- ]);
- expect(params.resolvedAgentConfig.tools).toEqual([
- {
- function: { name: 'lobe-artifacts____create' },
- type: 'function',
- },
- {
- function: { name: 'lobe-notebook____createDocument' },
- type: 'function',
- },
- ]);
- await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
- });
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
+
+ const streamSpy = spyOnClientLLMStream(async ({ onFinish, params }) => {
+ expect(params.resolvedAgentConfig.enabledToolIds).toEqual([
+ 'lobe-artifacts',
+ 'lobe-notebook',
+ ]);
+ expect(params.resolvedAgentConfig.tools).toEqual([
+ {
+ function: { name: 'lobe-artifacts____create' },
+ type: 'function',
+ },
+ {
+ function: { name: 'lobe-notebook____createDocument' },
+ type: 'function',
+ },
+ ]);
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
+ });
await act(async () => {
await result.current.executeClientAgent({
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index 013af95d082..8d6e9ad1706 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -294,13 +294,17 @@ export class StreamingExecutorActionImpl {
const workingDirectory = topicWorkingDirectory ?? agentWorkingDirectory;
// Create initial state or use provided state
- const state =
+ const baseState =
initialState ||
AgentRuntime.createInitialState({
maxSteps: 400,
messages,
metadata: {
+ agentId,
+ groupId,
sessionId: agentId,
+ scope,
+ subAgentId: paramSubAgentId,
threadId,
topicId,
workingDirectory,
@@ -316,6 +320,18 @@ export class StreamingExecutorActionImpl {
toolManifestMap,
userInterventionConfig,
});
+ const state: AgentState = {
+ ...baseState,
+ metadata: {
+ ...baseState.metadata,
+ agentId,
+ groupId,
+ scope,
+ subAgentId: paramSubAgentId,
+ threadId,
+ topicId,
+ },
+ };
// Build initialContext for page editor if lobe-page-agent is enabled
let runtimeInitialContext: RuntimeInitialContext | undefined;
@@ -549,6 +565,14 @@ export class StreamingExecutorActionImpl {
isSubAgent, // Pass isSubAgent to filter out lobe-agent tool in sub-agent context
});
+ if (params.skipCreateFirstMessage) {
+ initialAgentState.pendingAssistantMessageId = params.parentMessageId;
+ initialAgentContext.payload = {
+ ...(initialAgentContext.payload as Record<string, unknown>),
+ assistantMessageId: params.parentMessageId,
+ };
+ }
+
// Use model/provider from resolved agentConfig
const { agentConfig: agentConfigData } = agentConfig;
const model = agentConfigData.model;
@@ -589,7 +613,6 @@ export class StreamingExecutorActionImpl {
messageKey,
operationId,
parentId: params.parentMessageId,
- skipCreateFirstMessage: params.skipCreateFirstMessage,
toolsEngine, // Pass toolsEngine for dynamic tool injection via activateTools
}),
getOperation: (opId: string) => {