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 sub-agent transport (#17240)

Arvin Xu344d9eef4b2d
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
index 04d4be8b8e8..fd9790fd3c9 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts
@@ -122,10 +122,38 @@ describe('aiAgentRouter.execSubAgentTask', () => {
instruction: 'Test instruction',
parentMessageId: 'parent-msg-1',
timeout: undefined,
+ title: undefined,
topicId: testTopicId,
});
});
+ it('should pass parent operation metadata to the service', async () => {
+ mockExecGroupSubAgentTask.mockResolvedValue({
+ assistantMessageId: 'assistant-msg-1',
+ operationId: 'op-123',
+ success: true,
+ threadId: 'thread-123',
+ });
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.execSubAgentTask({
+ agentId: testAgentId,
+ groupId: testGroupId,
+ instruction: 'Test instruction',
+ parentMessageId: 'parent-msg-1',
+ parentOperationId: 'parent-operation-1',
+ title: 'Delegated task',
+ topicId: testTopicId,
+ });
+
+ expect(mockExecGroupSubAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parentOperationId: 'parent-operation-1',
+ title: 'Delegated task',
+ }),
+ );
+ });
+
it('should return result from service', async () => {
mockExecGroupSubAgentTask.mockResolvedValue({
assistantMessageId: 'assistant-msg-1',
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 5a01c824257..39a7182894d 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -324,6 +324,8 @@ const ExecSubAgentTaskSchema = z.object({
instruction: z.string(),
/** The parent message ID (Supervisor's tool call message or task message) */
parentMessageId: z.string(),
+ /** Parent operation ID for dispatching callAgent hooks */
+ parentOperationId: z.string().optional(),
/** Timeout in milliseconds (optional) */
timeout: z.number().optional(),
/** Task title (shown in UI, used as thread title) */
@@ -974,7 +976,16 @@ export const aiAgentRouter = router({
execSubAgentTask: aiAgentWriteProcedure
.input(ExecSubAgentTaskSchema)
.mutation(async ({ input, ctx }) => {
- const { agentId, groupId, instruction, parentMessageId, title, topicId, timeout } = input;
+ const {
+ agentId,
+ groupId,
+ instruction,
+ parentMessageId,
+ parentOperationId,
+ title,
+ topicId,
+ timeout,
+ } = input;
log('execSubAgentTask: agentId=%s, groupId=%s', agentId, groupId);
@@ -985,6 +996,7 @@ export const aiAgentRouter = router({
groupId,
instruction,
parentMessageId,
+ ...(parentOperationId && { parentOperationId }),
timeout,
title,
topicId,
diff --git a/packages/agent-runtime/src/executors/subAgent.test.ts b/packages/agent-runtime/src/executors/subAgent.test.ts
index 8c52fa89088..edb9ae07237 100644
--- a/packages/agent-runtime/src/executors/subAgent.test.ts
+++ b/packages/agent-runtime/src/executors/subAgent.test.ts
@@ -1,13 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { AgentRuntimeHost } from '../transport';
-import type { AgentInstruction, AgentState, SubAgentTask } from '../types';
+import type { AgentRuntimeHost, SubAgentExecutionResult } from '../transport';
+import type { AgentInstruction, AgentState } from '../types';
import { execSubAgent, execSubAgents } from './subAgent';
-interface TargetSubAgentTask extends SubAgentTask {
- targetAgentId: string;
-}
-
const createState = (overrides?: Partial<AgentState>): AgentState => ({
cost: {
calculatedAt: '2026-07-09T00:00:00.000Z',
@@ -44,6 +40,7 @@ const createState = (overrides?: Partial<AgentState>): AgentState => ({
describe('sub-agent executors', () => {
let execSubAgentTransport: ReturnType<typeof vi.fn>;
+ let query: ReturnType<typeof vi.fn>;
let update: ReturnType<typeof vi.fn>;
let host: AgentRuntimeHost;
@@ -54,6 +51,7 @@ describe('sub-agent executors', () => {
success: true,
threadId: 'child-thread',
});
+ query = vi.fn().mockResolvedValue([]);
update = vi.fn().mockResolvedValue(undefined);
host = {
@@ -68,7 +66,7 @@ describe('sub-agent executors', () => {
createToolMessage: vi.fn(),
deleteMessage: vi.fn(),
findById: vi.fn(),
- query: vi.fn(),
+ query,
update,
updatePluginState: vi.fn(),
updateToolMessage: vi.fn(),
@@ -95,7 +93,7 @@ describe('sub-agent executors', () => {
instruction: 'Do useful work',
targetAgentId: 'target-agent',
timeout: 1_800_000,
- } as TargetSubAgentTask,
+ },
},
type: 'exec_sub_agent',
};
@@ -121,6 +119,46 @@ describe('sub-agent executors', () => {
threadId: 'child-thread',
},
});
+ expect(update).not.toHaveBeenCalled();
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('persists a terminal client result and refreshes runtime messages', async () => {
+ const updatedMessages = [{ content: 'Child result', id: 'tool-msg-1', role: 'tool' }];
+ execSubAgentTransport.mockResolvedValueOnce({
+ assistantMessageId: 'assistant-child',
+ operationId: 'child-op',
+ result: 'Child result',
+ status: 'completed',
+ success: true,
+ threadId: 'child-thread',
+ });
+ query.mockResolvedValueOnce(updatedMessages);
+ const instruction: Extract<AgentInstruction, { type: 'exec_sub_agent' }> = {
+ payload: {
+ parentMessageId: 'tool-msg-1',
+ task: { description: 'Call child', instruction: 'Do useful work' },
+ },
+ type: 'exec_sub_agent',
+ };
+
+ const result = await execSubAgent(host)(instruction, createState());
+
+ expect(update).toHaveBeenCalledWith('tool-msg-1', { content: 'Child result' });
+ expect(query).toHaveBeenCalledWith({
+ agentId: 'parent-agent',
+ groupId: undefined,
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ expect(result.newState.messages).toEqual(updatedMessages);
+ expect(result.nextContext?.payload).toMatchObject({
+ result: {
+ result: 'Child result',
+ success: true,
+ threadId: 'child-thread',
+ },
+ });
});
it('blocks nested sub-agent dispatch before transport dispatch', async () => {
@@ -220,7 +258,7 @@ describe('sub-agent executors', () => {
description: 'Task B',
instruction: 'Do B',
targetAgentId: 'target-b',
- } as TargetSubAgentTask,
+ },
],
},
type: 'exec_sub_agents',
@@ -243,5 +281,86 @@ describe('sub-agent executors', () => {
{ success: true, threadId: 'child-thread-2' },
],
});
+ expect(update).not.toHaveBeenCalled();
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('persists aggregate terminal results including partial failures', async () => {
+ execSubAgentTransport
+ .mockResolvedValueOnce({
+ assistantMessageId: 'assistant-child-1',
+ operationId: 'child-op-1',
+ result: 'Result A',
+ status: 'completed',
+ success: true,
+ threadId: 'child-thread-1',
+ })
+ .mockResolvedValueOnce({
+ assistantMessageId: 'assistant-child-2',
+ error: 'Result B failed',
+ operationId: 'child-op-2',
+ status: 'failed',
+ success: false,
+ threadId: 'child-thread-2',
+ });
+ const updatedMessages = [{ content: 'aggregate', id: 'tool-msg-1', role: 'tool' }];
+ query.mockResolvedValueOnce(updatedMessages);
+ const instruction: Extract<AgentInstruction, { type: 'exec_sub_agents' }> = {
+ payload: {
+ parentMessageId: 'tool-msg-1',
+ tasks: [
+ { description: 'Task A', instruction: 'Do A' },
+ { description: 'Task B', instruction: 'Do B' },
+ ],
+ },
+ type: 'exec_sub_agents',
+ };
+
+ const result = await execSubAgents(host)(instruction, createState());
+
+ expect(update).toHaveBeenCalledWith('tool-msg-1', {
+ content: '1. Task A\nResult A\n\n2. Task B\nFailed: Result B failed',
+ });
+ expect(result.newState.messages).toEqual(updatedMessages);
+ expect(result.nextContext?.payload).toMatchObject({
+ results: [
+ { result: 'Result A', success: true, threadId: 'child-thread-1' },
+ { error: 'Result B failed', success: false, threadId: 'child-thread-2' },
+ ],
+ });
+ });
+
+ it('starts batch tasks concurrently', async () => {
+ const resolvers: Array<(result: SubAgentExecutionResult) => void> = [];
+ execSubAgentTransport.mockImplementation(
+ () =>
+ new Promise<SubAgentExecutionResult>((resolve) => {
+ resolvers.push(resolve);
+ }),
+ );
+ const instruction: Extract<AgentInstruction, { type: 'exec_sub_agents' }> = {
+ payload: {
+ parentMessageId: 'tool-msg-1',
+ tasks: [
+ { description: 'Task A', instruction: 'Do A' },
+ { description: 'Task B', instruction: 'Do B' },
+ { description: 'Task C', instruction: 'Do C' },
+ ],
+ },
+ type: 'exec_sub_agents',
+ };
+
+ const execution = execSubAgents(host)(instruction, createState());
+ await vi.waitFor(() => expect(execSubAgentTransport).toHaveBeenCalledTimes(3));
+
+ resolvers.forEach((resolve, index) =>
+ resolve({
+ assistantMessageId: `assistant-${index}`,
+ operationId: `operation-${index}`,
+ success: true,
+ threadId: `thread-${index}`,
+ }),
+ );
+ await execution;
});
});
diff --git a/packages/agent-runtime/src/executors/subAgent.ts b/packages/agent-runtime/src/executors/subAgent.ts
index e5cefbcfaba..4690343a84f 100644
--- a/packages/agent-runtime/src/executors/subAgent.ts
+++ b/packages/agent-runtime/src/executors/subAgent.ts
@@ -1,4 +1,6 @@
-import type { AgentRuntimeHost } from '../transport';
+import pMap from 'p-map';
+
+import type { AgentRuntimeHost, SubAgentExecutionStatus } from '../transport';
import type {
AgentEvent,
AgentInstructionExecSubAgent,
@@ -6,12 +8,14 @@ import type {
AgentRuntimeContext,
AgentState,
InstructionExecutor,
+ SubAgentResultPayload,
+ SubAgentsBatchResultPayload,
SubAgentTask,
} from '../types';
-interface SubAgentTaskWithTarget extends SubAgentTask {
- targetAgentId?: string;
-}
+type TaskExecutionResult = SubAgentResultPayload['result'] & {
+ status?: SubAgentExecutionStatus;
+};
const createSessionContext = (state: AgentState, operationId: string) => ({
messageCount: state.messages.length,
@@ -58,8 +62,109 @@ const createNestedBatchResult = (
session: createSessionContext(state, operationId),
}) as AgentRuntimeContext;
-const resolveTaskAgentId = (task: SubAgentTask, fallbackAgentId?: string) =>
- (task as SubAgentTaskWithTarget).targetAgentId ?? fallbackAgentId;
+const getErrorMessage = (error: unknown): string => {
+ if (error instanceof Error) return error.message;
+ if (typeof error === 'string') return error;
+ return 'Unknown error';
+};
+
+const executeTask = async (
+ host: AgentRuntimeHost,
+ state: AgentState,
+ parentMessageId: string,
+ task: SubAgentTask,
+): Promise<TaskExecutionResult> => {
+ const agentId = host.operation.agentId ?? state.metadata?.agentId;
+ const targetAgentId = task.targetAgentId ?? agentId;
+ const topicId = host.operation.topicId ?? state.metadata?.topicId;
+
+ if (!agentId || !targetAgentId || !topicId) {
+ return {
+ error: 'No valid context available',
+ success: false,
+ threadId: '',
+ };
+ }
+
+ if (!host.transports.subAgent) {
+ return {
+ error: 'Sub-agent dispatch is not available.',
+ success: false,
+ threadId: '',
+ };
+ }
+
+ try {
+ const execution = await host.transports.subAgent.execSubAgent({
+ agentId: targetAgentId,
+ groupId: host.operation.groupId ?? state.metadata?.groupId ?? undefined,
+ instruction: task.instruction,
+ parentMessageId,
+ parentOperationId: host.operation.operationId,
+ timeout: task.timeout,
+ title: task.description,
+ topicId,
+ });
+
+ return {
+ ...(execution.error && { error: execution.error }),
+ ...(execution.result !== undefined && { result: execution.result }),
+ ...(execution.status && { status: execution.status }),
+ success: execution.success,
+ threadId: execution.threadId ?? '',
+ };
+ } catch (error) {
+ return {
+ error: getErrorMessage(error),
+ success: false,
+ threadId: '',
+ };
+ }
+};
+
+const toPayloadResult = (execution: TaskExecutionResult): SubAgentResultPayload['result'] => {
+ const { status: _status, ...result } = execution;
+ return result;
+};
+
+const formatSingleResultContent = (result: TaskExecutionResult): string | undefined => {
+ if (!result.status) return undefined;
+ if (result.success) return result.result ?? 'Completed successfully.';
+
+ if (result.status === 'cancelled') {
+ return result.error === 'Operation cancelled'
+ ? 'Task was cancelled by user.'
+ : 'Task was cancelled';
+ }
+
+ if (result.status === 'timed_out') return result.error ?? 'Task timed out';
+
+ const error = result.error ?? 'Unknown error';
+ return result.threadId ? `Task failed: ${error}` : `Task creation failed: ${error}`;
+};
+
+const formatBatchResultContent = (
+ tasks: SubAgentTask[],
+ results: SubAgentsBatchResultPayload['results'],
+) =>
+ results
+ .map((result, index) => {
+ const title = tasks[index]?.description ?? `Task ${index + 1}`;
+ const content = result.success
+ ? (result.result ?? 'Completed successfully.')
+ : `Failed: ${result.error ?? 'Unknown error'}`;
+
+ return `${index + 1}. ${title}\n${content}`;
+ })
+ .join('\n\n');
+
+const queryMessages = (host: AgentRuntimeHost, state: AgentState) =>
+ host.transports.messages.query({
+ agentId: host.operation.agentId ?? state.metadata?.agentId,
+ groupId: host.operation.groupId ?? state.metadata?.groupId ?? undefined,
+ threadId: host.operation.threadId ?? state.metadata?.threadId,
+ topicId: host.operation.topicId ?? state.metadata?.topicId,
+ });
export const execSubAgent =
(host: AgentRuntimeHost): InstructionExecutor =>
@@ -69,10 +174,6 @@ export const execSubAgent =
const events: AgentEvent[] = [];
const { operationId } = host.operation;
- const topicId = host.operation.topicId ?? state.metadata?.topicId;
- const agentId = state.metadata?.agentId;
- const targetAgentId = resolveTaskAgentId(task, agentId);
-
if (state.metadata?.isSubAgent === true) {
return {
events,
@@ -81,41 +182,27 @@ export const execSubAgent =
};
}
- let dispatched = false;
- let threadId = '';
+ const execution = await executeTask(host, state, parentMessageId, task);
+ let newState = state;
- if (host.transports.subAgent && topicId && agentId && targetAgentId) {
- try {
- const dispatchResult = await host.transports.subAgent.execSubAgent({
- agentId: targetAgentId,
- groupId: state.metadata?.groupId ?? undefined,
- instruction: task.instruction,
- parentMessageId,
- parentOperationId: operationId,
- timeout: task.timeout,
- title: task.description,
- topicId,
- });
- dispatched = dispatchResult.success;
- threadId = dispatchResult.threadId ?? '';
- } catch {
- // Dispatch failures are reported in the sub_agent_result payload.
+ if (execution.status) {
+ const content = formatSingleResultContent(execution);
+ if (content !== undefined) {
+ await host.transports.messages.update(parentMessageId, { content });
}
+ newState = { ...state, messages: await queryMessages(host, state) };
}
return {
events,
- newState: state,
+ newState,
nextContext: {
payload: {
parentMessageId,
- result: {
- success: dispatched,
- threadId,
- },
+ result: toPayloadResult(execution),
},
phase: 'sub_agent_result',
- session: createSessionContext(state, operationId),
+ session: createSessionContext(newState, operationId),
} as AgentRuntimeContext,
};
};
@@ -128,9 +215,6 @@ export const execSubAgents =
const events: AgentEvent[] = [];
const { operationId } = host.operation;
- const topicId = host.operation.topicId ?? state.metadata?.topicId;
- const agentId = state.metadata?.agentId;
-
if (state.metadata?.isSubAgent === true) {
return {
events,
@@ -139,49 +223,32 @@ export const execSubAgents =
};
}
- const taskResults: Array<{ success: boolean; threadId: string }> = [];
-
- for (const task of tasks) {
- const targetAgentId = resolveTaskAgentId(task, agentId);
-
- let taskDispatched = false;
- let threadId = '';
-
- if (host.transports.subAgent && topicId && agentId && targetAgentId) {
- try {
- const dispatchResult = await host.transports.subAgent.execSubAgent({
- agentId: targetAgentId,
- groupId: state.metadata?.groupId ?? undefined,
- instruction: task.instruction,
- parentMessageId,
- parentOperationId: operationId,
- timeout: task.timeout,
- title: task.description,
- topicId,
- });
- taskDispatched = dispatchResult.success;
- threadId = dispatchResult.threadId ?? '';
- } catch {
- // Dispatch failures are reported in the batch result payload.
- }
- }
-
- taskResults.push({
- success: taskDispatched,
- threadId,
+ const executions = await pMap(
+ tasks,
+ (task) => executeTask(host, state, parentMessageId, task),
+ { concurrency: 15 },
+ );
+ const results = executions.map(toPayloadResult);
+ const hasTerminalResults = executions.length > 0 && executions.every((result) => result.status);
+ let newState = state;
+
+ if (hasTerminalResults) {
+ await host.transports.messages.update(parentMessageId, {
+ content: formatBatchResultContent(tasks, results),
});
+ newState = { ...state, messages: await queryMessages(host, state) };
}
return {
events,
- newState: state,
+ newState,
nextContext: {
payload: {
parentMessageId,
- results: taskResults,
+ results,
},
phase: 'sub_agents_batch_result',
- session: createSessionContext(state, operationId),
+ session: createSessionContext(newState, operationId),
} as AgentRuntimeContext,
};
};
diff --git a/packages/agent-runtime/src/transport/subAgent.ts b/packages/agent-runtime/src/transport/subAgent.ts
index c6ad0dcf563..21d533c1c5d 100644
--- a/packages/agent-runtime/src/transport/subAgent.ts
+++ b/packages/agent-runtime/src/transport/subAgent.ts
@@ -4,6 +4,19 @@ import type {
ExecVirtualSubAgentParams,
} from '@lobechat/types';
+export type SubAgentExecutionStatus = 'cancelled' | 'completed' | 'failed' | 'timed_out';
+
+/**
+ * Server transports normally return after dispatch, while client transports
+ * can wait for the child task to reach a terminal state. Optional terminal
+ * fields let the shared executor support both modes without importing client
+ * polling concerns into the package.
+ */
+export interface SubAgentExecutionResult extends ExecSubAgentResult {
+ result?: string;
+ status?: SubAgentExecutionStatus;
+}
+
/**
* Forks child agent runs for the `exec_sub_agent` / `exec_sub_agents`
* executors. `execVirtualSubAgent` additionally installs the async completion
@@ -14,6 +27,6 @@ import type {
* stays bound inside {@link ToolTransport}.
*/
export interface SubAgentTransport {
- execSubAgent: (params: ExecSubAgentParams) => Promise<ExecSubAgentResult>;
- execVirtualSubAgent: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;
+ execSubAgent: (params: ExecSubAgentParams) => Promise<SubAgentExecutionResult>;
+ execVirtualSubAgent: (params: ExecVirtualSubAgentParams) => Promise<SubAgentExecutionResult>;
}
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 991a3d81561..cc198e8d594 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -174,6 +174,8 @@ export interface SubAgentTask {
* run on the server.
*/
runInClient?: boolean;
+ /** Agent selected by callAgent; defaults to the current runtime agent when omitted */
+ targetAgentId?: string;
/** Timeout in milliseconds (optional, default 30 minutes) */
timeout?: number;
}
diff --git a/packages/builtin-tool-agent-management/src/executor.ts b/packages/builtin-tool-agent-management/src/executor.ts
index b5f5aaa35ae..19cc5c36ce3 100644
--- a/packages/builtin-tool-agent-management/src/executor.ts
+++ b/packages/builtin-tool-agent-management/src/executor.ts
@@ -141,7 +141,7 @@ class AgentManagementExecutor extends BaseExecutor<typeof AgentManagementApiName
}
}
- // Return special state recognized by AgentRuntime's legacy exec_sub_agent executor.
+ // Return special state recognized by AgentRuntime's exec_sub_agent executor.
// callAgent keeps this alias until it is redesigned as an explicit agent invocation.
return {
content: `🚀 Triggered async task to call agent "${agentId}"${taskTitle ? `: ${taskTitle}` : ''}`,
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.ts
index bd7c7073bdd..cf2d222e50f 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/exec-task.test.ts
@@ -1,6 +1,6 @@
import { type AgentRuntimeContext, type SubAgentResultPayload } from '@lobechat/agent-runtime';
import { type Mock } from 'vitest';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { aiAgentService } from '@/services/aiAgent';
@@ -13,12 +13,14 @@ vi.mock('@/services/aiAgent', () => ({
aiAgentService: {
execSubAgentTask: vi.fn(),
getSubAgentTaskStatus: vi.fn(),
+ interruptTask: vi.fn(),
},
}));
// Helper to get typed mocks
const mockExecSubAgentTask = aiAgentService.execSubAgentTask as Mock;
const mockGetSubAgentTaskStatus = aiAgentService.getSubAgentTaskStatus as Mock;
+const mockInterruptTask = aiAgentService.interruptTask as Mock;
describe('exec_sub_agent executor', () => {
beforeEach(() => {
@@ -140,11 +142,13 @@ describe('exec_sub_agent executor', () => {
const payload = (result.nextContext as AgentRuntimeContext).payload as SubAgentResultPayload;
expect(payload.result.success).toBe(false);
expect(payload.result.error).toBe('API error');
- expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(
- 'msg_parent',
- 'Task creation failed: API error',
- undefined,
- { operationId: 'test-op' },
+ expect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'msg_parent',
+ type: 'updateMessage',
+ value: { content: 'Task creation failed: API error' },
+ },
+ { operationId: 'op_test' },
);
});
@@ -221,7 +225,7 @@ describe('exec_sub_agent executor', () => {
type: 'updateMessage',
value: { taskDetail: { status: 'completed' } },
},
- { operationId: 'test-op' },
+ { operationId: 'op_test' },
);
const payload = (result.nextContext as AgentRuntimeContext).payload as SubAgentResultPayload;
expect(payload.result.success).toBe(true);
@@ -259,11 +263,13 @@ describe('exec_sub_agent executor', () => {
const payload = (result.nextContext as AgentRuntimeContext).payload as SubAgentResultPayload;
expect(payload.result.success).toBe(false);
expect(payload.result.error).toBe('Task was cancelled');
- expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(
- 'msg_parent',
- 'Task was cancelled',
- undefined,
- { operationId: 'test-op' },
+ expect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'msg_parent',
+ type: 'updateMessage',
+ value: { content: 'Task was cancelled' },
+ },
+ { operationId: 'op_test' },
);
});
});
@@ -307,6 +313,7 @@ describe('exec_sub_agent executor', () => {
expect(payload.result.error).toBe('Operation cancelled');
// getSubAgentTaskStatus should not be called since operation was cancelled before poll
expect(mockGetSubAgentTaskStatus).not.toHaveBeenCalled();
+ expect(mockInterruptTask).toHaveBeenCalledWith({ threadId: 'thread_1' });
});
});
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.ts
index 8f02bcf9b4c..b7582ddddac 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/exec-tasks.test.ts
@@ -3,7 +3,7 @@ import {
type SubAgentsBatchResultPayload,
} from '@lobechat/agent-runtime';
import { type Mock } from 'vitest';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { aiAgentService } from '@/services/aiAgent';
@@ -16,12 +16,14 @@ vi.mock('@/services/aiAgent', () => ({
aiAgentService: {
execSubAgentTask: vi.fn(),
getSubAgentTaskStatus: vi.fn(),
+ interruptTask: vi.fn(),
},
}));
// Helper to get typed mocks
const mockExecSubAgentTask = aiAgentService.execSubAgentTask as Mock;
const mockGetSubAgentTaskStatus = aiAgentService.getSubAgentTaskStatus as Mock;
+const mockInterruptTask = aiAgentService.interruptTask as Mock;
describe('exec_sub_agents executor', () => {
beforeEach(() => {
@@ -205,11 +207,13 @@ describe('exec_sub_agents executor', () => {
.payload as SubAgentsBatchResultPayload;
expect(payload.results[0].success).toBe(false);
expect(payload.results[0].error).toBe('API error');
- expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(
- 'msg_parent',
- '1. Test task\nFailed: API error',
- undefined,
- { operationId: 'test-op' },
+ expect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'msg_parent',
+ type: 'updateMessage',
+ value: { content: '1. Test task\nFailed: API error' },
+ },
+ { operationId: 'op_test' },
);
});
@@ -287,7 +291,7 @@ describe('exec_sub_agents executor', () => {
type: 'updateMessage',
value: { taskDetail: { status: 'completed' } },
},
- { operationId: 'test-op' },
+ { operationId: 'op_test' },
);
const payload = (result.nextContext as AgentRuntimeContext)
.payload as SubAgentsBatchResultPayload;
@@ -327,11 +331,13 @@ describe('exec_sub_agents executor', () => {
.payload as SubAgentsBatchResultPayload;
expect(payload.results[0].success).toBe(false);
expect(payload.results[0].error).toBe('Task was cancelled');
- expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(
- 'msg_parent',
- '1. Test task\nFailed: Task was cancelled',
- undefined,
- { operationId: 'test-op' },
+ expect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'msg_parent',
+ type: 'updateMessage',
+ value: { content: '1. Test task\nFailed: Task was cancelled' },
+ },
+ { operationId: 'op_test' },
);
});
});
@@ -377,6 +383,7 @@ describe('exec_sub_agents executor', () => {
expect(payload.results[0].error).toBe('Operation cancelled');
// getSubAgentTaskStatus should not be called since operation was cancelled before poll
expect(mockGetSubAgentTaskStatus).not.toHaveBeenCalled();
+ expect(mockInterruptTask).toHaveBeenCalledWith({ threadId: 'thread_1' });
});
});
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 5812468b73d..0a14a1f5f18 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -1,84 +1,36 @@
import type {
- AgentEvent,
AgentInstruction,
- AgentInstructionExecSubAgent,
- AgentInstructionExecSubAgents,
- AgentRuntimeContext,
AgentRuntimeHost,
InstructionExecutor,
- SubAgentResultPayload,
- SubAgentsBatchResultPayload,
- SubAgentTask,
} from '@lobechat/agent-runtime';
import {
callLlm as createCallLlmExecutor,
callTool as createCallToolExecutor,
compressContext as createCompressContextExecutor,
+ execSubAgent as createExecSubAgentExecutor,
+ execSubAgents as createExecSubAgentsExecutor,
finish as createFinishExecutor,
requestHumanApprove as createRequestHumanApproveExecutor,
resolveAbortedTools as createResolveAbortedToolsExecutor,
} from '@lobechat/agent-runtime';
import { type ToolsEngine } from '@lobechat/context-engine';
import { type MessageMetadata } from '@lobechat/types';
-import debug from 'debug';
-import pMap from 'p-map';
-import { aiAgentService } from '@/services/aiAgent';
import { type ResolvedAgentConfig } from '@/services/chat/mecha';
import { type ChatStore } from '@/store/chat/store';
-import { sleep } from '@/utils/sleep';
import { buildClientRuntimeHost } from './transports/buildClientRuntimeHost';
-const log = debug('lobe-store:agent-executors');
-
-const formatSubAgentBatchResultContent = (
- tasks: SubAgentTask[],
- results: SubAgentsBatchResultPayload['results'],
-) =>
- results
- .map((result, index) => {
- const title = tasks[index]?.description ?? `Task ${index + 1}`;
- const content = result.success
- ? (result.result ?? 'Completed successfully.')
- : `Failed: ${result.error ?? 'Unknown error'}`;
-
- return `${index + 1}. ${title}\n${content}`;
- })
- .join('\n\n');
-
-/**
- * Creates custom executors for the Chat Agent Runtime
- * These executors wrap existing chat store methods to integrate with agent-runtime
- *
- * @param context.operationId - Operation ID to get business context (agentId, topicId, etc.)
- * @param context.get - Store getter function
- * @param context.messageKey - Message map key
- * @param context.parentId - Parent message ID
- */
+/** Bind package-hosted executors to the current client runtime host. */
export const createAgentExecutors = (context: {
- /** Pre-resolved agent config with isSubAgent filtering applied */
agentConfig: ResolvedAgentConfig;
get: () => ChatStore;
metadata?: Pick<MessageMetadata, 'trigger'>;
messageKey: string;
operationId: string;
parentId: string;
- /** ToolsEngine for expanding dynamically activated tools */
toolsEngine?: ToolsEngine;
}) => {
- /**
- * Get operation context via closure
- * Returns the business context (agentId, topicId, etc.) captured by the operation
- */
- const getOperationContext = () => {
- const operation = context.get().operations[context.operationId];
- if (!operation) {
- throw new Error(`Operation not found: ${context.operationId}`);
- }
- return operation.context;
- };
-
const usePackageExecutor =
(factory: (host: AgentRuntimeHost) => InstructionExecutor): InstructionExecutor =>
(instruction, state, runtimeContext) =>
@@ -97,590 +49,13 @@ export const createAgentExecutors = (context: {
const executors: Partial<Record<AgentInstruction['type'], InstructionExecutor>> = {
call_llm: usePackageExecutor(createCallLlmExecutor),
-
call_tool: usePackageExecutor(createCallToolExecutor),
-
compress_context: usePackageExecutor(createCompressContextExecutor),
-
+ exec_sub_agent: usePackageExecutor(createExecSubAgentExecutor),
+ exec_sub_agents: usePackageExecutor(createExecSubAgentsExecutor),
finish: usePackageExecutor(createFinishExecutor),
-
request_human_approve: usePackageExecutor(createRequestHumanApproveExecutor),
-
resolve_aborted_tools: usePackageExecutor(createResolveAbortedToolsExecutor),
-
- /**
- * exec_sub_agent executor
- * Dispatches a single sub-agent
- *
- * Flow:
- * 1. Call execSubAgentTask API (backend creates thread)
- * 2. Poll for sub-agent completion
- * 3. Update the source tool message with result on completion
- * 4. Return sub_agent_result phase with result
- */
- exec_sub_agent: async (instruction, state) => {
- const { parentMessageId, task } = (instruction as AgentInstructionExecSubAgent).payload;
-
- const events: AgentEvent[] = [];
- const sessionLogId = `${state.operationId}:${state.stepCount}`;
-
- log('[%s][exec_sub_agent] Starting execution of task: %s', sessionLogId, task.description);
-
- // Get context from operation
- const opContext = getOperationContext();
- const { agentId, topicId } = opContext;
-
- // Check for targetAgentId (callAgent mode)
- const targetAgentId = (task as any).targetAgentId;
- const executionAgentId = targetAgentId || agentId;
-
- if (!agentId || !topicId || !executionAgentId) {
- log('[%s][exec_sub_agent] No valid context, cannot execute task', sessionLogId);
- return {
- events,
- newState: state,
- nextContext: {
- payload: {
- parentMessageId,
- result: {
- error: 'No valid context available',
- success: false,
- threadId: '',
- },
- } as SubAgentResultPayload,
- phase: 'sub_agent_result',
- session: {
- messageCount: state.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- if (targetAgentId) {
- log(
- '[%s][exec_sub_agent] callAgent mode - current agent: %s, target agent: %s',
- sessionLogId,
- agentId,
- targetAgentId,
- );
- }
-
- const taskLogId = `${sessionLogId}:task`;
-
- try {
- const resultMessageId = parentMessageId;
-
- // 1. Create and execute task on server
- // IMPORTANT: Use executionAgentId here (targetAgentId if in callAgent mode)
- // This ensures the task executes with the correct agent's config
- log('[%s] Using server-side execution with agentId: %s', taskLogId, executionAgentId);
- const createResult = await aiAgentService.execSubAgentTask({
- agentId: executionAgentId, // Use targetAgentId for callAgent, or current agentId for sub-agent dispatch
- instruction: task.instruction,
- parentMessageId: resultMessageId,
- title: task.description,
- topicId,
- });
-
- if (!createResult.success) {
- log('[%s] Failed to create task: %s', taskLogId, createResult.error);
- await context
- .get()
- .optimisticUpdateMessageContent(
- resultMessageId,
- `Task creation failed: ${createResult.error}`,
- undefined,
- { operationId: state.operationId },
- );
- return {
- events,
- newState: state,
- nextContext: {
- payload: {
- parentMessageId,
- result: {
- error: createResult.error,
- success: false,
- threadId: '',
- },
- } as SubAgentResultPayload,
- phase: 'sub_agent_result',
- session: {
- messageCount: state.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- log('[%s] Task created with threadId: %s', taskLogId, createResult.threadId);
-
- // 2. Poll for task completion
- const pollInterval = 3000; // 3 seconds
- const maxWait = task.timeout || 1_800_000; // Default 30 minutes
- const startTime = Date.now();
-
- while (Date.now() - startTime < maxWait) {
- // Check if parent operation has been cancelled
- const currentOperation = context.get().operations[state.operationId];
- if (currentOperation?.status === 'cancelled') {
- log('[%s] Operation cancelled, stopping polling', taskLogId);
-
- // Send interrupt request to stop the server-side task
- try {
- await aiAgentService.interruptTask({ threadId: createResult.threadId });
- log('[%s] Sent interrupt request for cancelled task', taskLogId);
- } catch (err) {
- log('[%s] Failed to interrupt cancelled task: %O', taskLogId, err);
- }
-
- // Update the source tool message to cancelled state.
- await context
- .get()
- .optimisticUpdateMessageContent(
- resultMessageId,
- 'Task was cancelled by user.',
- undefined,
- { operationId: state.operationId },
- );
-
- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
- return {
- events,
- newState: { ...state, messages: updatedMessages },
- nextContext: {
- payload: {
- parentMessageId,
- result: {
- error: 'Operation cancelled',
- success: false,
- threadId: createResult.threadId,
- },
- } as SubAgentResultPayload,
- phase: 'sub_agent_result',
- session: {
- messageCount: updatedMessages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- const status = await aiAgentService.getSubAgentTaskStatus({
- threadId: createResult.threadId,
- });
-
- // Update taskDetail on the source tool message if available.
- if (status.taskDetail) {
- context.get().internal_dispatchMessage(
- {
- id: resultMessageId,
- type: 'updateMessage',
- value: { taskDetail: status.taskDetail },
- },
- { operationId: state.operationId },
- );
- log('[%s] Updated source tool message with taskDetail', taskLogId);
- }
-
- if (status.status === 'completed') {
- log('[%s] Task completed successfully', taskLogId);
- if (status.result) {
- await context
- .get()
- .optimisticUpdateMessageContent(resultMessageId, status.result, undefined, {
- operationId: state.operationId,
- });
- }
- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
- return {
- events,
- newState: { ...state, messages: updatedMessages },
- nextContext: {
- payload: {
- parentMessageId,
- result: {
- result: status.result,
- success: true,
- threadId: createResult.threadId,
- },
- } as SubAgentResultPayload,
- phase: 'sub_agent_result',
- session: {
- messageCount: updatedMessages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- if (status.status === 'failed') {
- // Extract error message (error is always a string in TaskStatusResult)
- const errorMessage = status.error || 'Unknown error';
- log('[%s] Task failed: %s', taskLogId, errorMessage);
- await context
- .get()
- .optimisticUpdateMessageContent(
- resultMessageId,
- `Task failed: ${errorMessage}`,
- undefined,
- { operationId: state.operationId },
- );
- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
- return {
- events,
- newState: { ...state, messages: updatedMessages },
- nextContext: {
- payload: {
- parentMessageId,
- result: {
- error: status.error,
- success: false,
- threadId: createResult.threadId,
- },
- } as SubAgentResultPayload,
- phase: 'sub_agent_result',
- session: {
- messageCount: updatedMessages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- if (status.status === 'cancel') {
- log('[%s] Task was cancelled', taskLogId);
- // Note: Don't fail the operation here - it was cancelled intentionally
- // The source tool message update records the cancellation.
- await context
- .get()
- .optimisticUpdateMessageContent(resultMessageId, 'Task was cancelled', undefined, {
- operationId: state.operationId,
- });
- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
- return {
- events,
- newState: { ...state, messages: updatedMessages },
- nextContext: {
- payload: {
- parentMessageId,
- result: {
- error: 'Task was cancelled',
- success: false,
- threadId: createResult.threadId,
- },
- } as SubAgentResultPayload,
- phase: 'sub_agent_result',
- session: {
- messageCount: updatedMessages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- // Still processing, wait and poll again
- await sleep(pollInterval);
- }
-
- // Timeout reached
- log('[%s] Task timeout after %dms', taskLogId, maxWait);
-
- // Try to interrupt the task that timed out
- try {
- await aiAgentService.interruptTask({ threadId: createResult.threadId });
- log('[%s] Sent interrupt request for timed out task', taskLogId);
- } catch (err) {
- log('[%s] Failed to interrupt timed out task: %O', taskLogId, err);
- }
-
- await context
- .get()
- .optimisticUpdateMessageContent(
- resultMessageId,
- `Task timeout after ${maxWait}ms`,
- undefined,
- { operationId: state.operationId },
- );
-
- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
- return {
- events,
- newState: { ...state, messages: updatedMessages },
- nextContext: {
- payload: {
- parentMessageId,
- result: {
- error: `Task timeout after ${maxWait}ms`,
- success: false,
- threadId: createResult.threadId,
- },
- } as SubAgentResultPayload,
- phase: 'sub_agent_result',
- session: {
- messageCount: updatedMessages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- } catch (error) {
- log('[%s] Error executing task: %O', taskLogId, error);
- return {
- events,
- newState: state,
- nextContext: {
- payload: {
- parentMessageId,
- result: {
- error: error instanceof Error ? error.message : 'Unknown error',
- success: false,
- threadId: '',
- },
- } as SubAgentResultPayload,
- phase: 'sub_agent_result',
- session: {
- messageCount: state.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
- },
-
- /**
- * exec_sub_agents executor
- * Dispatches one or more sub-agents in parallel
- *
- * Flow:
- * 1. Call execSubAgentTask API for each task
- * 2. Poll for sub-agent completion
- * 3. Update the source tool message once with aggregated results
- * 4. Return sub_agents_batch_result phase with all results
- */
- exec_sub_agents: async (instruction, state) => {
- const { parentMessageId, tasks } = (instruction as AgentInstructionExecSubAgents).payload;
-
- const events: AgentEvent[] = [];
- const sessionLogId = `${state.operationId}:${state.stepCount}`;
-
- log('[%s][exec_sub_agents] Starting execution of %d tasks', sessionLogId, tasks.length);
-
- // Get context from operation
- const opContext = getOperationContext();
- const { agentId, topicId } = opContext;
-
- if (!agentId || !topicId) {
- log('[%s][exec_sub_agents] No valid context, cannot execute tasks', sessionLogId);
- return {
- events,
- newState: state,
- nextContext: {
- payload: {
- parentMessageId,
- results: tasks.map(() => ({
- error: 'No valid context available',
- success: false,
- threadId: '',
- })),
- } as SubAgentsBatchResultPayload,
- phase: 'sub_agents_batch_result',
- session: {
- messageCount: state.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- }
-
- // Execute all tasks in parallel
- const results = await pMap(
- tasks,
- async (task, taskIndex) => {
- const taskLogId = `${sessionLogId}:task-${taskIndex}`;
- log('[%s] Starting task: %s', taskLogId, task.description);
-
- try {
- const resultMessageId = parentMessageId;
-
- // 1. Create and execute task on server
- log('[%s] Using server-side execution', taskLogId);
- const createResult = await aiAgentService.execSubAgentTask({
- agentId,
- instruction: task.instruction,
- parentMessageId: resultMessageId,
- title: task.description,
- topicId,
- });
-
- if (!createResult.success) {
- log('[%s] Failed to create task: %s', taskLogId, createResult.error);
- return {
- error: createResult.error,
- success: false,
- threadId: '',
- };
- }
-
- log('[%s] Task created with threadId: %s', taskLogId, createResult.threadId);
-
- // 2. Poll for task completion
- const pollInterval = 3000; // 3 seconds
- const maxWait = task.timeout || 1_800_000; // Default 30 minutes
- const startTime = Date.now();
-
- while (Date.now() - startTime < maxWait) {
- // Check if parent operation has been cancelled
- const currentOperation = context.get().operations[state.operationId];
- if (currentOperation?.status === 'cancelled') {
- log('[%s] Operation cancelled, stopping polling', taskLogId);
-
- // Send interrupt request to stop the server-side task
- try {
- await aiAgentService.interruptTask({ threadId: createResult.threadId });
- log('[%s] Sent interrupt request for cancelled task', taskLogId);
- } catch (err) {
- log('[%s] Failed to interrupt cancelled task: %O', taskLogId, err);
- }
-
- return {
- error: 'Operation cancelled',
- success: false,
- threadId: createResult.threadId,
- };
- }
-
- const status = await aiAgentService.getSubAgentTaskStatus({
- threadId: createResult.threadId,
- });
-
- // Update taskDetail on the source tool message if available.
- if (status.taskDetail) {
- context.get().internal_dispatchMessage(
- {
- id: resultMessageId,
- type: 'updateMessage',
- value: { taskDetail: status.taskDetail },
- },
- { operationId: state.operationId },
- );
- log('[%s] Updated source tool message with taskDetail', taskLogId);
- }
-
- if (status.status === 'completed') {
- log('[%s] Task completed successfully', taskLogId);
- return {
- result: status.result,
- success: true,
- threadId: createResult.threadId,
- };
- }
-
- if (status.status === 'failed') {
- const errorMessage = status.error || 'Unknown error';
- log('[%s] Task failed: %s', taskLogId, errorMessage);
- return {
- error: status.error,
- success: false,
- threadId: createResult.threadId,
- };
- }
-
- if (status.status === 'cancel') {
- log('[%s] Task was cancelled', taskLogId);
- // Note: Don't fail the operation here - it was cancelled intentionally
- // The aggregate result update below records the cancellation.
- return {
- error: 'Task was cancelled',
- success: false,
- threadId: createResult.threadId,
- };
- }
-
- // Still processing, wait and poll again
- await sleep(pollInterval);
- }
-
- // Timeout reached
- log('[%s] Task timeout after %dms', taskLogId, maxWait);
-
- // Try to interrupt the task that timed out
- try {
- await aiAgentService.interruptTask({ threadId: createResult.threadId });
- log('[%s] Sent interrupt request for timed out task', taskLogId);
- } catch (err) {
- log('[%s] Failed to interrupt timed out task: %O', taskLogId, err);
- }
-
- return {
- error: `Task timeout after ${maxWait}ms`,
- success: false,
- threadId: createResult.threadId,
- };
- } catch (error) {
- log('[%s] Error executing task: %O', taskLogId, error);
- return {
- error: error instanceof Error ? error.message : 'Unknown error',
- success: false,
- threadId: '',
- };
- }
- },
- { concurrency: 15 }, // Limit concurrent tasks
- );
-
- log('[%s][exec_sub_agents] All tasks completed, results: %O', sessionLogId, results);
-
- await context
- .get()
- .optimisticUpdateMessageContent(
- parentMessageId,
- formatSubAgentBatchResultContent(tasks, results),
- undefined,
- { operationId: state.operationId },
- );
-
- // Get latest messages from store
- const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
- const newState = { ...state, messages: updatedMessages };
-
- // Return sub_agents_batch_result phase
- return {
- events,
- newState,
- nextContext: {
- payload: {
- parentMessageId,
- results,
- } as SubAgentsBatchResultPayload,
- phase: 'sub_agents_batch_result',
- session: {
- messageCount: newState.messages.length,
- sessionId: state.operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- } as AgentRuntimeContext,
- };
- },
};
return executors;
diff --git a/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts b/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts
new file mode 100644
index 00000000000..c523fd7db4c
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientSubAgentTransport.test.ts
@@ -0,0 +1,187 @@
+import { type ExecSubAgentParams, ThreadStatus } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentService } from '@/services/aiAgent';
+import type { ChatStore } from '@/store/chat/store';
+
+import { ClientSubAgentTransport } from './ClientSubAgentTransport';
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: {
+ execSubAgentTask: vi.fn(),
+ getSubAgentTaskStatus: vi.fn(),
+ interruptTask: vi.fn(),
+ },
+}));
+
+const params: ExecSubAgentParams = {
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ instruction: 'Investigate the issue',
+ parentMessageId: 'tool-message-1',
+ parentOperationId: 'root-operation',
+ timeout: 30_000,
+ title: 'Investigation',
+ topicId: 'topic-1',
+};
+
+const createStore = () => {
+ const operation = {
+ abortController: new AbortController(),
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ metadata: { startTime: Date.now() },
+ status: 'running',
+ type: 'execAgentRuntime',
+ };
+ const store = {
+ internal_dispatchMessage: vi.fn(),
+ operations: { 'root-operation': operation },
+ } as unknown as ChatStore;
+
+ return { operation, store };
+};
+
+const dispatchResult = {
+ assistantMessageId: 'assistant-message-1',
+ operationId: 'child-operation',
+ success: true,
+ threadId: 'child-thread',
+};
+
+describe('ClientSubAgentTransport', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(aiAgentService.execSubAgentTask).mockResolvedValue(dispatchResult);
+ vi.mocked(aiAgentService.interruptTask).mockResolvedValue({ success: true });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('forwards dispatch context and returns the completed terminal result', async () => {
+ const { store } = createStore();
+ vi.mocked(aiAgentService.getSubAgentTaskStatus).mockResolvedValueOnce({
+ result: 'Investigation complete',
+ status: 'completed',
+ taskDetail: { status: ThreadStatus.Completed, threadId: 'child-thread' },
+ });
+ const transport = new ClientSubAgentTransport(() => store, 'root-operation');
+
+ const result = await transport.execSubAgent(params);
+
+ expect(aiAgentService.execSubAgentTask).toHaveBeenCalledWith(params);
+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'tool-message-1',
+ type: 'updateMessage',
+ value: {
+ taskDetail: { status: ThreadStatus.Completed, threadId: 'child-thread' },
+ },
+ },
+ { operationId: 'root-operation' },
+ );
+ expect(result).toEqual({
+ ...dispatchResult,
+ result: 'Investigation complete',
+ status: 'completed',
+ success: true,
+ });
+ });
+
+ it('returns a terminal failure when dispatch is rejected', async () => {
+ const { store } = createStore();
+ vi.mocked(aiAgentService.execSubAgentTask).mockResolvedValueOnce({
+ assistantMessageId: '',
+ error: 'Dispatch failed',
+ operationId: '',
+ success: false,
+ threadId: '',
+ });
+ const transport = new ClientSubAgentTransport(() => store, 'root-operation');
+
+ const result = await transport.execSubAgent(params);
+
+ expect(result).toMatchObject({
+ error: 'Dispatch failed',
+ status: 'failed',
+ success: false,
+ threadId: '',
+ });
+ expect(aiAgentService.getSubAgentTaskStatus).not.toHaveBeenCalled();
+ });
+
+ it('interrupts an already-dispatched child when status polling fails', async () => {
+ const { store } = createStore();
+ vi.mocked(aiAgentService.getSubAgentTaskStatus).mockRejectedValueOnce(
+ new Error('Status unavailable'),
+ );
+ const transport = new ClientSubAgentTransport(() => store, 'root-operation');
+
+ const result = await transport.execSubAgent(params);
+
+ expect(aiAgentService.interruptTask).toHaveBeenCalledWith({ threadId: 'child-thread' });
+ expect(result).toMatchObject({
+ error: 'Status unavailable',
+ operationId: 'child-operation',
+ status: 'failed',
+ success: false,
+ threadId: 'child-thread',
+ });
+ });
+
+ it('interrupts the child when the parent is cancelled before polling', async () => {
+ const { operation, store } = createStore();
+ vi.mocked(aiAgentService.execSubAgentTask).mockImplementationOnce(async () => {
+ operation.status = 'cancelled';
+ return dispatchResult;
+ });
+ const transport = new ClientSubAgentTransport(() => store, 'root-operation');
+
+ const result = await transport.execSubAgent(params);
+
+ expect(aiAgentService.interruptTask).toHaveBeenCalledWith({ threadId: 'child-thread' });
+ expect(aiAgentService.getSubAgentTaskStatus).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ error: 'Operation cancelled',
+ status: 'cancelled',
+ success: false,
+ threadId: 'child-thread',
+ });
+ });
+
+ it('wakes a pending poll immediately when the parent aborts', async () => {
+ vi.useFakeTimers();
+ const { operation, store } = createStore();
+ vi.mocked(aiAgentService.getSubAgentTaskStatus).mockResolvedValue({ status: 'processing' });
+ const transport = new ClientSubAgentTransport(() => store, 'root-operation');
+
+ const execution = transport.execSubAgent(params);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(aiAgentService.getSubAgentTaskStatus).toHaveBeenCalledOnce();
+
+ operation.abortController.abort();
+ const result = await execution;
+
+ expect(aiAgentService.interruptTask).toHaveBeenCalledOnce();
+ expect(result.status).toBe('cancelled');
+ });
+
+ it('interrupts and reports a timeout after the configured deadline', async () => {
+ vi.useFakeTimers();
+ const { store } = createStore();
+ vi.mocked(aiAgentService.getSubAgentTaskStatus).mockResolvedValue({ status: 'processing' });
+ const transport = new ClientSubAgentTransport(() => store, 'root-operation');
+
+ const execution = transport.execSubAgent({ ...params, timeout: 10 });
+ await vi.advanceTimersByTimeAsync(10);
+ const result = await execution;
+
+ expect(aiAgentService.interruptTask).toHaveBeenCalledWith({ threadId: 'child-thread' });
+ expect(result).toMatchObject({
+ error: 'Task timeout after 10ms',
+ status: 'timed_out',
+ success: false,
+ });
+ });
+});
diff --git a/src/store/chat/agents/transports/ClientSubAgentTransport.ts b/src/store/chat/agents/transports/ClientSubAgentTransport.ts
new file mode 100644
index 00000000000..071f6852b26
--- /dev/null
+++ b/src/store/chat/agents/transports/ClientSubAgentTransport.ts
@@ -0,0 +1,179 @@
+import type { SubAgentExecutionResult, SubAgentTransport } from '@lobechat/agent-runtime';
+import type { ExecSubAgentParams, ExecVirtualSubAgentParams } from '@lobechat/types';
+
+import { aiAgentService } from '@/services/aiAgent';
+import type { ChatStore } from '@/store/chat/store';
+
+const DEFAULT_TIMEOUT_MS = 1_800_000;
+const POLL_INTERVAL_MS = 3000;
+
+const getErrorMessage = (error: unknown): string => {
+ if (error instanceof Error) return error.message;
+ if (typeof error === 'string') return error;
+ return 'Unknown error';
+};
+
+const waitForNextPoll = (delayMs: number, signal: AbortSignal): Promise<void> => {
+ if (signal.aborted) return Promise.resolve();
+
+ return new Promise((resolve) => {
+ const onAbort = () => {
+ clearTimeout(timer);
+ resolve();
+ };
+ const timer = setTimeout(() => {
+ signal.removeEventListener('abort', onAbort);
+ resolve();
+ }, delayMs);
+
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+};
+
+/** Client adapter that waits for a server-backed sub-agent task to finish. */
+export class ClientSubAgentTransport implements SubAgentTransport {
+ constructor(
+ private readonly get: () => ChatStore,
+ private readonly operationId: string,
+ ) {}
+
+ execSubAgent(params: ExecSubAgentParams): Promise<SubAgentExecutionResult> {
+ return this.execute(params);
+ }
+
+ execVirtualSubAgent(params: ExecVirtualSubAgentParams): Promise<SubAgentExecutionResult> {
+ return this.execute(params);
+ }
+
+ private async execute(params: ExecSubAgentParams): Promise<SubAgentExecutionResult> {
+ let dispatchResult: Awaited<ReturnType<typeof aiAgentService.execSubAgentTask>> | undefined;
+ let interruptPromise: Promise<void> | undefined;
+ const interrupt = () => {
+ if (!interruptPromise) {
+ interruptPromise = (async () => {
+ if (!dispatchResult?.threadId) return;
+
+ try {
+ await aiAgentService.interruptTask({ threadId: dispatchResult.threadId });
+ } catch {
+ // The terminal result still needs to reach the parent when interruption fails.
+ }
+ })();
+ }
+
+ return interruptPromise;
+ };
+
+ try {
+ dispatchResult = await aiAgentService.execSubAgentTask(params);
+ if (!dispatchResult.success) {
+ return {
+ ...dispatchResult,
+ error: dispatchResult.error ?? 'Sub-agent dispatch failed',
+ status: 'failed',
+ };
+ }
+
+ const operation = this.get().operations[this.operationId];
+ if (!operation) throw new Error(`Operation not found: ${this.operationId}`);
+
+ const signal = operation.abortController.signal;
+ const timeoutMs = params.timeout ?? DEFAULT_TIMEOUT_MS;
+ const startedAt = Date.now();
+
+ const onAbort = () => void interrupt();
+ signal.addEventListener('abort', onAbort, { once: true });
+
+ try {
+ while (Date.now() - startedAt < timeoutMs) {
+ const currentOperation = this.get().operations[this.operationId];
+ if (signal.aborted || currentOperation?.status === 'cancelled') {
+ await interrupt();
+ return {
+ ...dispatchResult,
+ error: 'Operation cancelled',
+ status: 'cancelled',
+ success: false,
+ };
+ }
+
+ const taskStatus = await aiAgentService.getSubAgentTaskStatus({
+ threadId: dispatchResult.threadId,
+ });
+
+ if (signal.aborted || this.get().operations[this.operationId]?.status === 'cancelled') {
+ await interrupt();
+ return {
+ ...dispatchResult,
+ error: 'Operation cancelled',
+ status: 'cancelled',
+ success: false,
+ };
+ }
+
+ if (taskStatus.taskDetail) {
+ this.get().internal_dispatchMessage(
+ {
+ id: params.parentMessageId,
+ type: 'updateMessage',
+ value: { taskDetail: taskStatus.taskDetail },
+ },
+ { operationId: this.operationId },
+ );
+ }
+
+ if (taskStatus.status === 'completed') {
+ return {
+ ...dispatchResult,
+ result: taskStatus.result,
+ status: 'completed',
+ success: true,
+ };
+ }
+
+ if (taskStatus.status === 'failed') {
+ return {
+ ...dispatchResult,
+ error: taskStatus.error ?? 'Unknown error',
+ status: 'failed',
+ success: false,
+ };
+ }
+
+ if (taskStatus.status === 'cancel') {
+ return {
+ ...dispatchResult,
+ error: 'Task was cancelled',
+ status: 'cancelled',
+ success: false,
+ };
+ }
+
+ const remainingMs = timeoutMs - (Date.now() - startedAt);
+ await waitForNextPoll(Math.min(POLL_INTERVAL_MS, remainingMs), signal);
+ }
+
+ await interrupt();
+ return {
+ ...dispatchResult,
+ error: `Task timeout after ${timeoutMs}ms`,
+ status: 'timed_out',
+ success: false,
+ };
+ } finally {
+ signal.removeEventListener('abort', onAbort);
+ }
+ } catch (error) {
+ if (dispatchResult?.success) await interrupt();
+
+ return {
+ assistantMessageId: dispatchResult?.assistantMessageId ?? '',
+ error: getErrorMessage(error),
+ operationId: dispatchResult?.operationId ?? '',
+ status: 'failed',
+ success: false,
+ threadId: dispatchResult?.threadId ?? '',
+ };
+ }
+ }
+}
diff --git a/src/store/chat/agents/transports/buildClientRuntimeHost.ts b/src/store/chat/agents/transports/buildClientRuntimeHost.ts
index f98c9d4899b..68f0a5d8013 100644
--- a/src/store/chat/agents/transports/buildClientRuntimeHost.ts
+++ b/src/store/chat/agents/transports/buildClientRuntimeHost.ts
@@ -15,6 +15,7 @@ import { ClientContextBuilder } from './ClientContextBuilder';
import { ClientLLMTransport } from './ClientLLMTransport';
import { ClientMessageTransport } from './ClientMessageTransport';
import { type ClientRuntimeSession, ClientRuntimeStreamSink } from './ClientRuntimeStreamSink';
+import { ClientSubAgentTransport } from './ClientSubAgentTransport';
import { ClientToolTransport } from './ClientToolTransport';
export const buildClientRuntimeHost = (context: {
@@ -77,6 +78,7 @@ export const buildClientRuntimeHost = (context: {
messages,
operationStore,
stream,
+ subAgent: new ClientSubAgentTransport(context.get, context.operationId),
tools: new ClientToolTransport(
context.get,
context.messageKey,