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.

✨ feat(agent-runtime): run sub-agents in the background and deliver their results as messages (#20862)

Arvin Xu7293336cb228
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentBackground.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentBackground.test.ts
new file mode 100644
index 00000000000..cc03b97bd17
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentBackground.test.ts
@@ -0,0 +1,149 @@
+import { type AgentState } from '@lobechat/agent-runtime';
+import { type ChatToolPayload } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type RuntimeExecutorContext } from '../context';
+import { buildServerVirtualSubAgentRunner } from '../executorHelpers';
+
+/**
+ * `callSubAgent({ runInBackground })`: the placeholder must say it belongs to a
+ * background run before the child starts — the completion bridge reads that to
+ * choose delivery over resuming a parent that never parked — and the running
+ * thread is linked onto it without touching the status the bridge owns.
+ */
+describe('buildServerVirtualSubAgentRunner in background mode', () => {
+ const buildRunner = (
+ execResult: Record<string, unknown> = {
+ operationId: 'child-op',
+ success: true,
+ threadId: 'thread-1',
+ },
+ ) => {
+ const calls: string[] = [];
+ const messageModel = {
+ create: vi.fn(async () => {
+ calls.push('create');
+ return { id: 'placeholder-1' };
+ }),
+ deleteMessage: vi.fn(),
+ updatePluginState: vi.fn().mockResolvedValue(undefined),
+ };
+ const execVirtualSubAgent = vi.fn(async () => {
+ calls.push('exec');
+ return execResult;
+ });
+ const ctx = {
+ execVirtualSubAgent,
+ messageModel,
+ operationId: 'parent-op',
+ topicId: 'topic-1',
+ } as unknown as RuntimeExecutorContext;
+
+ const runner = buildServerVirtualSubAgentRunner(
+ ctx,
+ {
+ operationId: 'parent-op',
+ origin: { agentId: 'agent-1', topicId: 'topic-1' },
+ } as unknown as AgentState,
+ { id: 'tool-call-1' } as ChatToolPayload,
+ 'assistant-1',
+ );
+
+ return { calls, execVirtualSubAgent, messageModel, runner: runner! };
+ };
+
+ it('marks the placeholder as background before starting the child', async () => {
+ const { calls, execVirtualSubAgent, messageModel, runner } = buildRunner();
+
+ const result = await runner.run({
+ background: true,
+ description: 'research',
+ instruction: 'go',
+ });
+
+ expect(calls).toEqual(['create', 'exec']);
+ expect(messageModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ pluginState: {
+ background: true,
+ sender: { agentId: 'agent-1', name: 'research' },
+ status: 'pending',
+ },
+ }),
+ );
+ expect(execVirtualSubAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ background: true, parentMessageId: 'placeholder-1' }),
+ );
+ expect(result).toMatchObject({ started: true, toolMessageId: 'placeholder-1' });
+ });
+
+ it('links the running thread without writing the status', async () => {
+ const { messageModel, runner } = buildRunner();
+
+ await runner.run({ background: true, description: 'research', instruction: 'go' });
+
+ expect(messageModel.updatePluginState).toHaveBeenCalledWith('placeholder-1', {
+ threadId: 'thread-1',
+ });
+ });
+
+ it('still starts when linking the thread fails', async () => {
+ const { messageModel, runner } = buildRunner();
+ messageModel.updatePluginState.mockRejectedValue(new Error('db down'));
+
+ const result = await runner.run({
+ background: true,
+ description: 'research',
+ instruction: 'go',
+ });
+
+ expect(result).toMatchObject({ started: true, threadId: 'thread-1' });
+ });
+
+ it('leaves a foreground placeholder as before', async () => {
+ const { messageModel, runner } = buildRunner();
+
+ await runner.run({ description: 'research', instruction: 'go' });
+
+ expect(messageModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({ pluginState: { status: 'pending' } }),
+ );
+ expect(messageModel.updatePluginState).not.toHaveBeenCalled();
+ });
+
+ // The right panel and the thread portal tell a sub-agent from an ordinary
+ // thread by the tool call that spawned it — a named callAgent target included.
+ it('records the spawning tool call on the sub-agent thread', async () => {
+ const { execVirtualSubAgent, runner } = buildRunner();
+
+ await runner.run({ description: 'research', instruction: 'go' });
+ await runner.run({ agentId: 'named-agent', description: 'Poet', instruction: 'go' });
+
+ expect(execVirtualSubAgent).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ sourceToolCallId: 'tool-call-1' }),
+ );
+ expect(execVirtualSubAgent).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ sourceToolCallId: 'tool-call-1' }),
+ );
+ });
+
+ // The answer is delivered as a message from whoever answered.
+ it('records a named callAgent target as the sender', async () => {
+ const { messageModel, runner } = buildRunner();
+
+ await runner.run({
+ agentId: 'named-agent',
+ background: true,
+ description: 'Poet',
+ instruction: 'go',
+ });
+
+ expect(messageModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ pluginState: expect.objectContaining({ sender: { agentId: 'named-agent', name: 'Poet' } }),
+ }),
+ );
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 45a3343cbe2..2e27f8b5d17 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -446,6 +446,9 @@ export class ServerToolTransport implements ToolTransport {
mocked: toolCallMocked || execution.mocked,
result: executionResult,
resultBlocked: controlled.blocked,
+ // A tool that created its own row (a background sub-agent's placeholder)
+ // gets its result written there instead of into a second tool message.
+ toolMessageId: execution.toolMessageId ?? executionResult.toolMessageId,
};
} catch (error) {
executeToolSpan.recordException(error as Error);
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index 85b103ce1b3..c8421b4154e 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -268,7 +268,14 @@ export const buildServerVirtualSubAgentRunner = (
const parentDeviceId = resolveRunActiveDeviceId(state);
return {
- run: async ({ agentId: targetAgentId, description, instruction, subAgentId, timeout }) => {
+ run: async ({
+ agentId: targetAgentId,
+ background,
+ description,
+ instruction,
+ subAgentId,
+ timeout,
+ }) => {
// This runner serves two tools, and only one of them may swap the model:
// - `callSubAgent` names no agent, so the child is an anonymous clone of
// the parent — it takes the parent's `agencyConfig.subagent` override,
@@ -291,9 +298,18 @@ export const buildServerVirtualSubAgentRunner = (
// 1. Create (or, after approval, reuse) the pending placeholder tool message (mirrors the normal
// tool-message shape in call_tool) that anchors the isolation thread
// and renders a loading state until the bridge backfills it.
- const pendingState = subAgentId
- ? { status: 'pending', threadId: subAgentId }
- : { status: 'pending' };
+ // `background` is written before the child starts so the completion bridge
+ // can never see this row without it, however fast the child finishes. The
+ // sender is who the answer will be delivered as: the named target, or the
+ // parent itself for an anonymous clone.
+ const pendingState = {
+ ...(background && {
+ background: true,
+ sender: { agentId: targetAgentId ?? agentId, name: description },
+ }),
+ status: 'pending',
+ ...(subAgentId && { threadId: subAgentId }),
+ };
if (existingToolMessageId) {
await ctx.messageModel.updatePluginState(existingToolMessageId, pendingState);
}
@@ -319,6 +335,7 @@ export const buildServerVirtualSubAgentRunner = (
// bridge that backfills this tool message and resumes the parent op.
const result = (await execVirtualSubAgent({
agentId: targetAgentId ?? agentId,
+ background,
chatConfig: subAgentChatConfig,
deviceId: targetAgentId ? undefined : parentDeviceId,
groupId: state.origin?.groupId ?? undefined,
@@ -328,6 +345,8 @@ export const buildServerVirtualSubAgentRunner = (
parentMessageId: placeholder.id,
parentOperationId: ctx.operationId,
provider: subAgentModel?.provider,
+ // Marks the thread as a sub-agent (the right panel, the thread portal).
+ sourceToolCallId: chatToolPayload.id,
threadId: subAgentId,
timeout,
title: description,
@@ -369,6 +388,21 @@ export const buildServerVirtualSubAgentRunner = (
};
}
+ // A background parent never parks, so its card has no other way to link
+ // the running thread. Only `threadId` is patched: the merge leaves the
+ // `status` key to the completion bridge, which may already have written it.
+ if (background && result.threadId && !subAgentId) {
+ await ctx.messageModel
+ .updatePluginState(placeholder.id, { threadId: result.threadId })
+ .catch((error: unknown) =>
+ log(
+ 'buildServerVirtualSubAgentRunner: failed to link thread on %s: %O',
+ placeholder.id,
+ error,
+ ),
+ );
+ }
+
return {
started: true,
subOperationId: result?.operationId,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts
index 524ac3e5dc4..0536df1ed23 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts
@@ -145,6 +145,7 @@ describe('AgentRuntimeService', () => {
});
updateToolMessage = vi.fn().mockResolvedValue({ success: true });
(service as any).messageModel.updateToolMessage = updateToolMessage;
+ (service as any).messageModel.findMessagePlugin = vi.fn().mockResolvedValue(undefined);
resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);
});
@@ -661,6 +662,134 @@ describe('AgentRuntimeService', () => {
).rejects.toThrow('db down');
expect(resumeSpy).not.toHaveBeenCalled();
});
+
+ describe('background sub-agent', () => {
+ let deliver: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ (service as any).messageModel.findMessagePlugin = vi.fn().mockResolvedValue({
+ apiName: 'callSubAgent',
+ identifier: 'lobe-agent',
+ state: { background: true, status: 'pending' },
+ });
+ (service as any).messageModel.findById = vi
+ .fn()
+ .mockResolvedValue({ id: 'tool-msg-1', topicId: 'topic-1' });
+ deliver = vi.fn().mockResolvedValue(undefined);
+ (service as any).delegate.deliverBackgroundSubAgentResults = deliver;
+ });
+
+ it('keeps the start receipt, stores the answer and delivers instead of resuming', async () => {
+ const won = await service.completeSubAgentBridge({
+ ...bridgeParams,
+ finalState: childState as any,
+ });
+
+ expect(won).toBe(false);
+ // No `content`: the tool result stays the receipt the parent already read.
+ expect(updateToolMessage).toHaveBeenCalledWith('tool-msg-1', {
+ pluginError: undefined,
+ pluginState: {
+ model: 'gpt-test',
+ result: 'final answer',
+ status: 'completed',
+ threadId: 'thread-1',
+ totalCost: undefined,
+ totalInputTokens: undefined,
+ totalOutputTokens: undefined,
+ totalToolCalls: 2,
+ totalTokens: 42,
+ },
+ });
+ expect(resumeSpy).not.toHaveBeenCalled();
+ expect(deliver).toHaveBeenCalledWith({ topicId: 'topic-1' });
+ });
+
+ it('stores a failure as an error result', async () => {
+ await service.completeSubAgentBridge({
+ ...bridgeParams,
+ finalState: { ...childState, error: { message: 'Budget exceeded' } } as any,
+ reason: 'error',
+ });
+
+ const [, update] = updateToolMessage.mock.calls[0];
+ expect(update.pluginState).toMatchObject({ status: 'error' });
+ expect(update.pluginState.result).toContain('Budget exceeded');
+ expect(update.pluginError).toBeDefined();
+ expect(deliver).toHaveBeenCalled();
+ });
+
+ it('gates the finished answer through afterToolCall before storing and delivering it', async () => {
+ // The answer never returns through ServerToolTransport: the delivery
+ // below publishes it into the parent conversation, so the controls have
+ // to be applied to the stored result — not only to the start receipt.
+ const privateContent = 'synthetic-private-background-answer';
+ const denialReason = 'The child result is restricted by policy.';
+ const stored: any = {
+ apiName: 'callSubAgent',
+ arguments: '{"instruction":"original"}',
+ id: 'tool-msg-1',
+ identifier: 'lobe-agent',
+ state: { background: true, status: 'pending' },
+ toolCallId: 'native-child',
+ };
+ (service as any).messageModel.findMessagePlugin = vi.fn(async () => stored);
+ (service as any).messageModel.findById = vi
+ .fn()
+ .mockResolvedValue({ id: 'tool-msg-1', parentId: 'assistant', topicId: 'topic-1' });
+ const fetchHook = vi
+ .spyOn(globalThis, 'fetch')
+ .mockImplementation(
+ async () => new Response(JSON.stringify({ decision: 'deny', reason: denialReason })),
+ );
+ mockCoordinator.loadAgentState.mockResolvedValue({
+ operationId: 'parent-op-1',
+ stepCount: 3,
+ host: {
+ hooks: [
+ {
+ id: 'after-control',
+ type: 'afterToolCall',
+ webhook: { url: 'https://hooks.example/control', responseHandling: 'toolCall' },
+ },
+ ],
+ },
+ });
+
+ try {
+ const won = await service.completeSubAgentBridge({
+ ...bridgeParams,
+ finalState: {
+ ...childState,
+ messages: [{ content: privateContent, role: 'assistant' }],
+ } as any,
+ });
+
+ expect(won).toBe(false);
+ expect(JSON.parse(String(fetchHook.mock.calls[0][1]?.body))).toMatchObject({
+ result: { content: expect.stringContaining(privateContent) },
+ });
+ // The denied answer must not reach the placeholder the delivery reads.
+ expect(JSON.stringify(updateToolMessage.mock.calls)).not.toContain(privateContent);
+ expect(updateToolMessage).toHaveBeenCalledWith('tool-msg-1', {
+ pluginError: 'hook_denied',
+ pluginState: expect.objectContaining({ result: denialReason, status: 'error' }),
+ });
+ expect(deliver).toHaveBeenCalledWith({ topicId: 'topic-1' });
+ } finally {
+ fetchHook.mockRestore();
+ }
+ });
+
+ it('throws when the answer cannot be stored, so the callback is redelivered', async () => {
+ updateToolMessage.mockResolvedValue({ success: false });
+
+ await expect(
+ service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any }),
+ ).rejects.toThrow(/failed to record the result/);
+ expect(deliver).not.toHaveBeenCalled();
+ });
+ });
});
describe('resolveAsyncToolOnComplete', () => {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts
index f319178600a..2cab98f3cf4 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts
@@ -195,6 +195,11 @@ export class AgentRuntimeService {
});
this.completionLifecycle = new CompletionLifecycle(db, userId, workspaceId, {
includeShareVisitor,
+ onTopicRunSettled: ({ operationId, topicId }) =>
+ this.delegate.deliverBackgroundSubAgentResults?.({
+ settledOperationId: operationId,
+ topicId,
+ }) ?? Promise.resolve(),
});
this.humanIntervention = new HumanInterventionHandler(db, this.messageModel);
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts
index 74b2e693f89..34efacc6588 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts
@@ -1,4 +1,5 @@
import type { AgentState } from '@lobechat/agent-runtime';
+import type { CallSubAgentState } from '@lobechat/builtin-tool-lobe-agent';
import { appendSubAgentReference, isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';
import debug from 'debug';
@@ -18,6 +19,7 @@ export type SubAgentBridgeDeps = Pick<
AgentRuntimeServiceContext,
| 'controlCompletedToolResult'
| 'coordinator'
+ | 'delegate'
| 'isCallSubAgentToolMessage'
| 'messageModel'
| 'resolveLastAssistantContentFromThread'
@@ -173,6 +175,48 @@ export async function completeSubAgentBridge(
? `Sub-agent did not complete (${reason}): ${errorReason}`
: `Sub-agent did not complete (${reason}).`
: lastAssistantContent || 'Sub-agent completed without a textual answer.';
+
+ // A background sub-agent's parent never parked on it: the placeholder holds
+ // the start receipt the parent already read, so the answer is kept for a
+ // delivery of its own instead of a backfill + resume.
+ if (await isBackgroundSubAgentPlaceholder(deps, toolMessageId)) {
+ // The answer is published into the parent's conversation on a later turn,
+ // so the result controls must run here too: otherwise an `afterToolCall`
+ // policy sees the start receipt and never the finished output it could
+ // deny, and both the stored answer and the message the delivery writes
+ // would carry content the policy had replaced.
+ const controlled = await deps.controlCompletedToolResult({
+ operationId: parentOperationId,
+ preserveUsage: true,
+ result: {
+ content: resultContent,
+ error: failed ? formatErrorForMetadata(finalState?.error ?? params.errorMessage) : undefined,
+ state: {
+ model: finalState?.modelRuntimeConfig?.model,
+ status: failed ? 'error' : 'completed',
+ threadId,
+ totalCost: finalState?.cost?.total,
+ totalInputTokens: finalState?.usage?.llm?.tokens?.input,
+ totalOutputTokens: finalState?.usage?.llm?.tokens?.output,
+ totalToolCalls: finalState?.usage?.tools?.totalCalls,
+ totalTokens: finalState?.usage?.llm?.tokens?.total,
+ },
+ success: !failed,
+ },
+ toolMessageId,
+ });
+
+ await recordBackgroundSubAgentResult(deps, {
+ error: controlled.result.error,
+ finalState,
+ result: controlled.result.content,
+ status: failed || controlled.blocked || controlled.cancelled ? 'error' : 'completed',
+ threadId,
+ toolMessageId,
+ });
+ return false;
+ }
+
// callSubAgent results carry the sub-agent id so the parent can later send
// this same sub-agent a follow-up (`callSubAgent({ subAgentId })`) — e.g.
// to hand over what it gathered before failing — instead of redoing it.
@@ -227,6 +271,67 @@ export async function completeSubAgentBridge(
);
}
+/**
+ * Whether the bridged placeholder was started with `runInBackground`
+ * (`callSubAgent` or `callAgent` — only their runner writes the flag).
+ */
+async function isBackgroundSubAgentPlaceholder(
+ deps: SubAgentBridgeDeps,
+ toolMessageId: string,
+): Promise<boolean> {
+ const plugin = await deps.messageModel.findMessagePlugin(toolMessageId);
+ return (plugin?.state as CallSubAgentState | undefined)?.background === true;
+}
+
+/**
+ * Store a finished background sub-agent's answer on its placeholder, then try
+ * to deliver it. The tool result (the start receipt) is left as the parent
+ * read it; the answer goes into `state.result` for the delivery to carry.
+ *
+ * Throws when the answer cannot be stored, so the queue-mode callback is
+ * redelivered. A failed delivery does not throw: the answer is stored, and
+ * the next settle of the topic picks it up.
+ */
+async function recordBackgroundSubAgentResult(
+ deps: SubAgentBridgeDeps,
+ params: {
+ error?: unknown;
+ finalState?: AgentState;
+ result: string;
+ status: 'completed' | 'error';
+ threadId: string;
+ toolMessageId: string;
+ },
+): Promise<void> {
+ const { error, finalState, result, status, threadId, toolMessageId } = params;
+ const state: Partial<CallSubAgentState> = {
+ model: finalState?.modelRuntimeConfig?.model,
+ result,
+ status,
+ threadId,
+ totalCost: finalState?.cost?.total,
+ totalInputTokens: finalState?.usage?.llm?.tokens?.input,
+ totalOutputTokens: finalState?.usage?.llm?.tokens?.output,
+ totalToolCalls: finalState?.usage?.tools?.totalCalls,
+ totalTokens: finalState?.usage?.llm?.tokens?.total,
+ };
+
+ const recorded = await deps.messageModel.updateToolMessage(toolMessageId, {
+ pluginError: error,
+ pluginState: state,
+ });
+ if (!recorded.success) {
+ throw new Error(
+ `Background sub-agent: failed to record the result on tool message ${toolMessageId}`,
+ );
+ }
+
+ const placeholder = await deps.messageModel.findById(toolMessageId);
+ if (!placeholder?.topicId || !deps.delegate.deliverBackgroundSubAgentResults) return;
+
+ await deps.delegate.deliverBackgroundSubAgentResults({ topicId: placeholder.topicId });
+}
+
/**
* Whether the bridged placeholder belongs to `lobe-agent.callSubAgent` (the
* same bridge also serves `callAgent`, whose children cannot be continued).
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts
index 6d291c2c708..4c46ce55b57 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts
@@ -127,6 +127,17 @@ export interface InterventionLifecycleCheckpoint {
* top-level option. One named home for the whole upward-call surface.
*/
export interface AgentRuntimeDelegate {
+ /**
+ * Hand the topic's finished background sub-agent results to their parent
+ * agent as a new turn, unless a run of that topic is still going (its own
+ * completion delivers them then). Called when a background sub-agent finishes
+ * and when a topic run settles. Never throws.
+ */
+ deliverBackgroundSubAgentResults?: (params: {
+ /** The run that is settling right now, which no longer counts as busy. */
+ settledOperationId?: string;
+ topicId: string;
+ }) => Promise<void>;
/**
* Fork a group member ("call agent member") under a `lobe-group-management`
* tool call. Handles both in-group (non-isolated, shared group session) and
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
index 4696e92f7ce..bac36b017b0 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
@@ -32,6 +32,7 @@ import type {
CompletionLifecycleDeps,
OperationCompletionInput,
SignalEvent,
+ TopicRunSettledHandler,
} from './types';
export { CriticalAgentInterventionPersistenceError } from './intervention';
@@ -42,7 +43,11 @@ export {
normalizeCompletionMessages,
} from './messageContent';
export { isAgentShareRun } from './signals';
-export type { CompleteOperationOptions, OperationCompletionInput } from './types';
+export type {
+ CompleteOperationOptions,
+ OperationCompletionInput,
+ TopicRunSettledHandler,
+} from './types';
const log = debug('lobe-server:completion-lifecycle');
@@ -54,6 +59,10 @@ const log = debug('lobe-server:completion-lifecycle');
* file-Work registration) must cover the capped reasons too — gating them on
* `reason === 'done'` alone silently drops capped runs' artifacts.
*/
+/** Terminal reasons after which the topic's agent may be woken again. */
+const isTopicRunSettledReason = (reason: string) =>
+ reason !== 'interrupted' && reason !== 'waiting_for_human' && reason !== 'waiting_for_async_tool';
+
export const isSuccessLikeCompletionReason = (reason: string): boolean =>
reason === 'done' ||
reason === 'max_steps' ||
@@ -81,6 +90,7 @@ export class CompletionLifecycle {
* (instantiation is fire-and-forget at start and may not have settled yet).
*/
private readonly verifyPlanInstantiations = new Map<string, Promise<void>>();
+ private readonly onTopicRunSettled?: TopicRunSettledHandler;
constructor(
private readonly serverDB: LobeChatDatabase,
@@ -93,10 +103,13 @@ export class CompletionLifecycle {
* creator's identity.
*/
includeShareVisitor?: boolean;
+ /** See {@link TopicRunSettledHandler}. */
+ onTopicRunSettled?: TopicRunSettledHandler;
},
) {
this.workspaceId = workspaceId;
this.includeShareVisitor = options?.includeShareVisitor ?? false;
+ this.onTopicRunSettled = options?.onTopicRunSettled;
this.messageModel = new MessageModel(serverDB, userId, workspaceId, undefined, {
includeShareVisitor: this.includeShareVisitor,
});
@@ -407,6 +420,21 @@ export class CompletionLifecycle {
);
}
+ const settledTopicId = typeof runOrigin.topicId === 'string' ? runOrigin.topicId : undefined;
+ if (
+ this.onTopicRunSettled &&
+ settledTopicId &&
+ isTopicRunSettledReason(reason) &&
+ !runOrigin.lineage?.parentOperationId &&
+ runOrigin.lineage?.isSubAgent !== true &&
+ runOrigin.lineage?.orchestrationRole !== 'member' &&
+ !runOrigin.signal &&
+ !isAgentShareRun(state)
+ ) {
+ const onTopicRunSettled = this.onTopicRunSettled;
+ after(() => onTopicRunSettled({ operationId, topicId: settledTopicId }));
+ }
+
// Delivery checker: on a successful completion, run the confirmed verify
// plan against the deliverable. Fire-and-forget and self-guarded — a run
// without an opted-in plan is a no-op, and failures never affect the run.
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
index ef384c9572a..93dae3b0a6a 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts
@@ -6,6 +6,18 @@ import type { SerializedHook } from '../hooks';
export type SignalEvent = { [key: string]: unknown; type: string };
+/**
+ * Runs after a topic's own run settles — not a child run (sub-agent, group
+ * member, `callAgent` target), not a park for approval, not a user stop. The
+ * topic is free for the next turn at that point, which is when work that was
+ * waiting on it (background sub-agent results) can be handed over. Scheduled
+ * after the response; the handler owns its errors.
+ */
+export type TopicRunSettledHandler = (params: {
+ operationId: string;
+ topicId: string;
+}) => Promise<void>;
+
/**
* Normalized terminal-completion input for {@link CompletionLifecycle.completeOperation}.
*
diff --git a/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts
new file mode 100644
index 00000000000..85548a82ed7
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { CompletionLifecycle, type TopicRunSettledHandler } from '../CompletionLifecycle';
+import { hookDispatcher } from '../hooks';
+
+const { after } = vi.hoisted(() => ({ after: vi.fn() }));
+
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after }));
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({
+ notifyAgentRunCompleted: vi.fn(async () => {}),
+}));
+vi.mock('@/server/services/workRegistration', () => ({ registerWorksForOperation: vi.fn() }));
+vi.mock('@/server/services/verify', () => ({
+ runVerifyOnCompletion: vi.fn(async () => {}),
+ settleFailedRepair: vi.fn(async () => {}),
+}));
+
+/**
+ * A topic's own run settling is when work waiting on that topic — background
+ * sub-agent results — may be handed over. Child runs, approval parks and user
+ * stops must not trigger it.
+ */
+describe('CompletionLifecycle — topic run settled', () => {
+ let onTopicRunSettled: ReturnType<typeof vi.fn<TopicRunSettledHandler>>;
+
+ const run = async (origin: Record<string, unknown>, reason: string) => {
+ const lifecycle = new CompletionLifecycle({} as any, 'user-1', undefined, {
+ onTopicRunSettled,
+ });
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'notifyPendingAgentIntervention').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'registerFileWorks').mockResolvedValue(undefined);
+ await lifecycle.dispatchHooks('op-1', { host: { hooks: [] }, origin, status: reason }, reason);
+ };
+
+ /** Run every post-response task the lifecycle handed over. */
+ const flushAfter = async () => {
+ for (const [task] of after.mock.calls) await task();
+ };
+
+ afterEach(() => vi.restoreAllMocks());
+ beforeEach(() => {
+ after.mockReset();
+ onTopicRunSettled = vi.fn<TopicRunSettledHandler>().mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ });
+
+ it.each(['done', 'error', 'max_steps'])(
+ 'reports the topic as settled after a %s run, as post-response work',
+ async (reason) => {
+ await run({ agentId: 'a', topicId: 'topic-1' }, reason);
+
+ expect(onTopicRunSettled).not.toHaveBeenCalled();
+ await flushAfter();
+ expect(onTopicRunSettled).toHaveBeenCalledWith({ operationId: 'op-1', topicId: 'topic-1' });
+ },
+ );
+
+ it.each(['interrupted', 'waiting_for_human', 'waiting_for_async_tool'])(
+ 'stays quiet when the run was %s',
+ async (reason) => {
+ await run({ agentId: 'a', topicId: 'topic-1' }, reason);
+ await flushAfter();
+
+ expect(onTopicRunSettled).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ['a sub-agent', { lineage: { isSubAgent: true, parentOperationId: 'p' } }],
+ ['a group member', { lineage: { orchestrationRole: 'member' } }],
+ ['a callAgent child', { lineage: { parentOperationId: 'p' } }],
+ ['an Agent Signal run', { signal: { kind: 'self-iteration' } }],
+ ])('stays quiet for %s', async (_label, extra) => {
+ await run({ agentId: 'a', topicId: 'topic-1', ...extra }, 'done');
+ await flushAfter();
+
+ expect(onTopicRunSettled).not.toHaveBeenCalled();
+ });
+
+ it('stays quiet for a run without a topic', async () => {
+ await run({ agentId: 'a' }, 'done');
+ await flushAfter();
+
+ expect(onTopicRunSettled).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/__tests__/backgroundSubAgentDelivery.test.ts b/apps/server/src/services/aiAgent/__tests__/backgroundSubAgentDelivery.test.ts
new file mode 100644
index 00000000000..8d6654be5e0
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/backgroundSubAgentDelivery.test.ts
@@ -0,0 +1,217 @@
+import { RequestTrigger } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ type BackgroundSubAgentDeliveryDeps,
+ deliverBackgroundSubAgentResults,
+} from '../backgroundSubAgentDelivery';
+
+const finished = (
+ id: string,
+ overrides: {
+ sender?: { agentId?: string; name?: string };
+ state?: object;
+ threadId?: string | null;
+ } = {},
+) => ({
+ agentId: 'agent-1',
+ arguments: null,
+ id,
+ state: {
+ background: true,
+ result: `Answer of ${id}`,
+ sender: overrides.sender ?? { agentId: 'agent-1', name: `Task ${id}` },
+ status: 'completed',
+ threadId: `thread-${id}`,
+ ...overrides.state,
+ },
+ threadId: overrides.threadId ?? null,
+});
+
+const createDeps = (opts: {
+ marker?: { operationId: string } | null;
+ markerStatus?: string;
+ pending?: ReturnType<typeof finished>[];
+}) => {
+ const deps = {
+ agentOperationModel: {
+ findById: vi.fn().mockResolvedValue(opts.markerStatus ? { status: opts.markerStatus } : null),
+ },
+ appendResultMessages: vi.fn().mockResolvedValue('leaf-msg'),
+ execAgent: vi.fn().mockResolvedValue({ operationId: 'wake-op', success: true }),
+ messageModel: {
+ claimBackgroundSubAgentDelivery: vi.fn(async (ids: string[]) => ids),
+ listBackgroundSubAgentCalls: vi.fn().mockResolvedValue(opts.pending ?? []),
+ releaseBackgroundSubAgentDelivery: vi.fn().mockResolvedValue(undefined),
+ },
+ resolveInterventionConfig: vi.fn().mockResolvedValue({ allowList: [], approvalMode: 'manual' }),
+ topicModel: {
+ findById: vi.fn().mockResolvedValue({
+ agentId: 'agent-1',
+ id: 'topic-1',
+ metadata: { runningOperation: opts.marker ?? null },
+ }),
+ },
+ };
+ return deps as typeof deps & BackgroundSubAgentDeliveryDeps;
+};
+
+describe('deliverBackgroundSubAgentResults', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ // The answer lands as a message from the sub-agent, and the parent runs off
+ // that history — no made-up user turn.
+ it('lands each answer as a message from its sender, then wakes the parent once', async () => {
+ const deps = createDeps({
+ pending: [finished('a'), finished('b', { sender: { agentId: 'poet', name: 'Poet' } })],
+ });
+
+ await deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' });
+
+ expect(deps.appendResultMessages).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ results: [
+ {
+ callId: 'a',
+ result: 'Answer of a',
+ sender: { agentId: 'agent-1', name: 'Task a' },
+ status: 'completed',
+ threadId: 'thread-a',
+ },
+ {
+ callId: 'b',
+ result: 'Answer of b',
+ sender: { agentId: 'poet', name: 'Poet' },
+ status: 'completed',
+ threadId: 'thread-b',
+ },
+ ],
+ topicId: 'topic-1',
+ });
+ expect(deps.execAgent).toHaveBeenCalledTimes(1);
+ expect(deps.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ autoStart: true,
+ parentMessageId: 'leaf-msg',
+ suppressUserMessage: true,
+ trigger: RequestTrigger.Chat,
+ userInterventionConfig: { allowList: [], approvalMode: 'manual' },
+ }),
+ );
+ });
+
+ it('waits while another run holds the topic', async () => {
+ const deps = createDeps({
+ marker: { operationId: 'user-op' },
+ markerStatus: 'running',
+ pending: [finished('a')],
+ });
+
+ await deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' });
+
+ expect(deps.messageModel.listBackgroundSubAgentCalls).not.toHaveBeenCalled();
+ expect(deps.appendResultMessages).not.toHaveBeenCalled();
+ expect(deps.execAgent).not.toHaveBeenCalled();
+ });
+
+ it('does not count the run that is settling right now as busy', async () => {
+ const deps = createDeps({
+ marker: { operationId: 'parent-op' },
+ markerStatus: 'running',
+ pending: [finished('a')],
+ });
+
+ await deliverBackgroundSubAgentResults(deps, {
+ settledOperationId: 'parent-op',
+ topicId: 'topic-1',
+ });
+
+ expect(deps.agentOperationModel.findById).not.toHaveBeenCalled();
+ expect(deps.execAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats a mark left by a run that already ended as free', async () => {
+ const deps = createDeps({
+ marker: { operationId: 'old-op' },
+ markerStatus: 'done',
+ pending: [finished('a')],
+ });
+
+ await deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' });
+
+ expect(deps.execAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('only delivers what it claimed, so a racing delivery cannot repeat a result', async () => {
+ const deps = createDeps({ pending: [finished('a'), finished('b')] });
+ deps.messageModel.claimBackgroundSubAgentDelivery.mockResolvedValue(['b']);
+
+ await deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' });
+
+ const [{ results }] = deps.appendResultMessages.mock.calls[0];
+ expect(results.map((item: { callId: string }) => item.callId)).toEqual(['b']);
+ });
+
+ it('starts nothing when every result was already claimed', async () => {
+ const deps = createDeps({ pending: [finished('a')] });
+ deps.messageModel.claimBackgroundSubAgentDelivery.mockResolvedValue([]);
+
+ await deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' });
+
+ expect(deps.appendResultMessages).not.toHaveBeenCalled();
+ expect(deps.execAgent).not.toHaveBeenCalled();
+ });
+
+ it('hands the claims back when the turn cannot start', async () => {
+ const deps = createDeps({ pending: [finished('a')] });
+ deps.execAgent.mockRejectedValue(new Error('Topic topic-1 remained busy'));
+
+ await expect(
+ deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' }),
+ ).resolves.toBeUndefined();
+
+ expect(deps.messageModel.releaseBackgroundSubAgentDelivery).toHaveBeenCalledWith(['a']);
+ });
+
+ it('hands the claims back when the turn reports it did not start', async () => {
+ const deps = createDeps({ pending: [finished('a')] });
+ deps.execAgent.mockResolvedValue({ error: 'no model', success: false });
+
+ await deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' });
+
+ expect(deps.messageModel.releaseBackgroundSubAgentDelivery).toHaveBeenCalledWith(['a']);
+ });
+
+ it('carries a failure as an error result', async () => {
+ const deps = createDeps({
+ pending: [finished('a', { state: { result: 'boom', status: 'error' } })],
+ });
+
+ await deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' });
+
+ const [{ results }] = deps.appendResultMessages.mock.calls[0];
+ expect(results[0]).toMatchObject({ result: 'boom', status: 'error' });
+ });
+
+ it('leaves calls made inside a thread alone', async () => {
+ const deps = createDeps({ pending: [finished('a', { threadId: 'user-thread' })] });
+
+ await deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' });
+
+ expect(deps.messageModel.claimBackgroundSubAgentDelivery).not.toHaveBeenCalled();
+ expect(deps.execAgent).not.toHaveBeenCalled();
+ });
+
+ it('never throws, even when the topic lookup fails', async () => {
+ const deps = createDeps({});
+ deps.topicModel.findById.mockRejectedValue(new Error('db down'));
+
+ await expect(
+ deliverBackgroundSubAgentResults(deps, { topicId: 'topic-1' }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/backgroundSubAgentDelivery.ts b/apps/server/src/services/aiAgent/backgroundSubAgentDelivery.ts
new file mode 100644
index 00000000000..845e793cec7
--- /dev/null
+++ b/apps/server/src/services/aiAgent/backgroundSubAgentDelivery.ts
@@ -0,0 +1,159 @@
+import type { ExecAgentResult, UserInterventionConfig } from '@lobechat/types';
+import { isAgentOperationInFlight, RequestTrigger } from '@lobechat/types';
+import debug from 'debug';
+
+import type { AgentOperationModel } from '@/database/models/agentOperation';
+import type { MessageModel } from '@/database/models/message';
+import type { TopicModel } from '@/database/models/topic';
+
+import type { InternalExecAgentParams } from './types';
+
+const log = debug('lobe-server:ai-agent:background-sub-agent');
+
+/**
+ * Background sub-agents (`callSubAgent` / `callAgent` with `runInBackground`)
+ * report to a parent that did not wait for them. A finished one stores its
+ * answer on its placeholder (see `AgentRuntimeService.completeSubAgentBridge`);
+ * this module hands those answers back to the conversation.
+ *
+ * Each answer lands on the conversation's main line as a user message whose
+ * sender is the sub-agent (`metadata.subAgentCallback`) — the chat shows the
+ * sub-agent speaking, the model reads it wrapped as `<sub_agent_result>` — and
+ * the parent agent then runs off that history.
+ *
+ * It runs when a background sub-agent finishes and whenever a run of the topic
+ * settles, so an answer that arrives mid-turn is delivered once that turn ends
+ * — the parent is never interrupted, and never waits on a result it chose not
+ * to wait for. Each answer is claimed before it is delivered, so the two
+ * triggers racing cannot deliver it twice; a turn that fails to start hands
+ * its claims back for the next settle, and the callback rows' ids are derived
+ * from the call so a retry does not repeat them.
+ */
+
+export interface BackgroundSubAgentResult {
+ /** The background call's placeholder tool message. */
+ callId: string;
+ result: string;
+ sender: { agentId?: string; name: string };
+ status: 'completed' | 'error';
+ /** The sub-agent's isolation thread. */
+ threadId: string;
+}
+
+export interface BackgroundSubAgentDeliveryDeps {
+ agentOperationModel: Pick<AgentOperationModel, 'findById'>;
+ /**
+ * Append one callback message per result to the topic's main line, in order,
+ * skipping any that already exist; returns the id of the line's last message.
+ */
+ appendResultMessages: (params: {
+ agentId: string;
+ results: BackgroundSubAgentResult[];
+ topicId: string;
+ }) => Promise<string | undefined>;
+ execAgent: (params: InternalExecAgentParams) => Promise<ExecAgentResult>;
+ messageModel: Pick<
+ MessageModel,
+ | 'claimBackgroundSubAgentDelivery'
+ | 'listBackgroundSubAgentCalls'
+ | 'releaseBackgroundSubAgentDelivery'
+ >;
+ /** Approval policy for the wake-up run — the user's foreground preferences. */
+ resolveInterventionConfig: () => Promise<UserInterventionConfig>;
+ topicModel: Pick<TopicModel, 'findById'>;
+}
+
+type PendingCall = Awaited<
+ ReturnType<BackgroundSubAgentDeliveryDeps['messageModel']['listBackgroundSubAgentCalls']>
+>[number];
+
+const toResult = (call: PendingCall): BackgroundSubAgentResult => {
+ const sender = call.state.sender as { agentId?: string; name?: string } | undefined;
+ return {
+ callId: call.id,
+ result:
+ typeof call.state.result === 'string' && call.state.result
+ ? call.state.result
+ : 'Finished without a textual answer.',
+ sender: { agentId: sender?.agentId, name: sender?.name ?? '' },
+ status: call.state.status === 'error' ? 'error' : 'completed',
+ threadId: typeof call.state.threadId === 'string' ? call.state.threadId : '',
+ };
+};
+
+/**
+ * Whether another run still holds the topic. `settledOperationId` is the run
+ * whose completion triggered this delivery: its mark may not be cleared yet,
+ * but it is done. A mark naming a run that already ended is stale.
+ */
+const isTopicBusy = async (
+ deps: BackgroundSubAgentDeliveryDeps,
+ marker: { operationId?: string } | null | undefined,
+ settledOperationId: string | undefined,
+): Promise<boolean> => {
+ const operationId = marker?.operationId;
+ if (!operationId || operationId === settledOperationId) return false;
+
+ const operation = await deps.agentOperationModel.findById(operationId);
+ return !!operation && isAgentOperationInFlight(operation.status);
+};
+
+/**
+ * Deliver the topic's finished background sub-agent results, unless another
+ * run still holds the topic — its own completion calls this again. Never
+ * throws: an undelivered result stays stored for the next attempt.
+ */
+export const deliverBackgroundSubAgentResults = async (
+ deps: BackgroundSubAgentDeliveryDeps,
+ params: { settledOperationId?: string; topicId: string },
+): Promise<void> => {
+ const { settledOperationId, topicId } = params;
+
+ try {
+ const topic = await deps.topicModel.findById(topicId);
+ if (!topic?.agentId) return;
+ if (await isTopicBusy(deps, topic.metadata?.runningOperation, settledOperationId)) {
+ log('topic %s is busy; results wait for its run to settle', topicId);
+ return;
+ }
+
+ // Background calls only start from the main line (see
+ // `checkBackgroundSubAgentAllowed`), which is where they report back.
+ const pending = (
+ await deps.messageModel.listBackgroundSubAgentCalls({ scope: 'undelivered', topicId })
+ ).filter((call) => !call.threadId);
+ if (pending.length === 0) return;
+
+ const claimed = new Set(
+ await deps.messageModel.claimBackgroundSubAgentDelivery(
+ pending.map((call) => call.id),
+ new Date().toISOString(),
+ ),
+ );
+ const results = pending.filter((call) => claimed.has(call.id)).map(toResult);
+ if (results.length === 0) return;
+
+ const agentId = topic.agentId;
+ try {
+ const parentMessageId = await deps.appendResultMessages({ agentId, results, topicId });
+ const started = await deps.execAgent({
+ agentId,
+ appContext: { topicId },
+ autoStart: true,
+ parentMessageId,
+ prompt: `Process ${results.length} finished background result${results.length === 1 ? '' : 's'}`,
+ suppressUserMessage: true,
+ trigger: RequestTrigger.Chat,
+ userInterventionConfig: await deps.resolveInterventionConfig(),
+ });
+ if (!started.success) throw new Error(started.error ?? 'the turn did not start');
+
+ log('woke agent %s in topic %s with %d result(s)', agentId, topicId, results.length);
+ } catch (error) {
+ log('waking agent %s in topic %s failed, results kept: %O', agentId, topicId, error);
+ await deps.messageModel.releaseBackgroundSubAgentDelivery([...claimed]);
+ }
+ } catch (error) {
+ log('delivering background results for topic %s failed: %O', topicId, error);
+ }
+};
diff --git a/apps/server/src/services/aiAgent/foregroundIntervention.ts b/apps/server/src/services/aiAgent/foregroundIntervention.ts
new file mode 100644
index 00000000000..5430355bc35
--- /dev/null
+++ b/apps/server/src/services/aiAgent/foregroundIntervention.ts
@@ -0,0 +1,25 @@
+import type { UserInterventionConfig, UserToolConfig } from '@lobechat/types';
+
+import { UserModel } from '@/database/models/user';
+import type { LobeChatDatabase } from '@/database/type';
+
+/**
+ * Approval policy for a run the server starts to continue a user-facing
+ * conversation on its own (a finished task or background sub-agent reporting
+ * back): the same preferences as a foreground send, including the allow list.
+ * The user's `headless` preference maps to `auto-run`, which still honours
+ * per-tool requirements a run with nobody watching cannot skip.
+ */
+export const resolveForegroundInterventionConfig = async (
+ db: LobeChatDatabase,
+ userId: string,
+): Promise<UserInterventionConfig> => {
+ const settings = await new UserModel(db, userId).getUserSettings();
+ const intervention = (settings?.tool as UserToolConfig | undefined)?.humanIntervention;
+ const approvalMode =
+ intervention?.approvalMode === 'headless'
+ ? 'auto-run'
+ : (intervention?.approvalMode ?? 'manual');
+
+ return { allowList: intervention?.allowList ?? [], approvalMode };
+};
diff --git a/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts b/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts
index 618e50cc941..b8a8936f265 100644
--- a/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts
+++ b/apps/server/src/services/aiAgent/hooks/__tests__/threadRunHooks.test.ts
@@ -1,18 +1,82 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
-import { pickThreadUsageBaseline } from '../threadRunHooks';
+import { createThreadHooks, pickThreadCarryOver } from '../threadRunHooks';
-describe('pickThreadUsageBaseline', () => {
+describe('pickThreadCarryOver', () => {
it('ignores legacy totalSteps when no versioned LLM baseline exists', () => {
- const baseline = pickThreadUsageBaseline({ totalSteps: 9 } as any);
+ const baseline = pickThreadCarryOver({ totalSteps: 9 } as any);
// Legacy `totalSteps` is in execution-step units; reusing it would mix units.
expect(baseline.totalLlmCalls).toBeUndefined();
});
it('uses the versioned totalLlmCalls baseline', () => {
- const baseline = pickThreadUsageBaseline({ totalLlmCalls: 3, totalSteps: 9 } as any);
+ const baseline = pickThreadCarryOver({ totalLlmCalls: 3, totalSteps: 9 } as any);
expect(baseline.totalLlmCalls).toBe(3);
});
});
+
+/**
+ * The thread-completion hook copies a sub-agent's final answer into its source
+ * message — the placeholder the parent reads. A background run's placeholder
+ * holds the start receipt instead, which must survive: its answer is delivered
+ * to the parent as a message of its own.
+ */
+describe('createThreadHooks thread-completion', () => {
+ const finalState = {
+ messages: [
+ { content: 'go', role: 'user' },
+ { content: 'the answer', role: 'assistant' },
+ ],
+ operationId: 'child-op',
+ };
+
+ const runCompletion = async (options?: { updateSourceMessage?: boolean }) => {
+ const messageModel = { update: vi.fn().mockResolvedValue(undefined) };
+ const threadModel = { update: vi.fn().mockResolvedValue(undefined) };
+ const hooks = createThreadHooks(
+ {} as any,
+ threadModel as any,
+ messageModel as any,
+ 'thread-1',
+ new Date().toISOString(),
+ 'placeholder-1',
+ 'execVirtualSubAgent',
+ { sourceToolCallId: 'call-1', totalTokens: 10 },
+ options,
+ );
+ const completion = hooks.find((hook) => hook.id === 'thread-completion')!;
+ await completion.handler!({ finalState, operationId: 'child-op', reason: 'done' } as any);
+ return { messageModel, threadModel };
+ };
+
+ it('copies the answer into the source message by default', async () => {
+ const { messageModel } = await runCompletion();
+
+ expect(messageModel.update).toHaveBeenCalledWith('placeholder-1', { content: 'the answer' });
+ });
+
+ it('leaves the source message alone for a background run, but still settles the thread', async () => {
+ const { messageModel, threadModel } = await runCompletion({ updateSourceMessage: false });
+
+ expect(messageModel.update).not.toHaveBeenCalled();
+ expect(threadModel.update).toHaveBeenCalledWith(
+ 'thread-1',
+ expect.objectContaining({ status: expect.anything() }),
+ );
+ });
+
+ // Thread writes replace metadata; dropping the marker would turn the
+ // sub-agent back into a plain thread in the UI once it finishes.
+ it('keeps the spawning tool call on the finished thread', async () => {
+ const { threadModel } = await runCompletion();
+
+ expect(threadModel.update).toHaveBeenCalledWith(
+ 'thread-1',
+ expect.objectContaining({
+ metadata: expect.objectContaining({ sourceToolCallId: 'call-1' }),
+ }),
+ );
+ });
+});
diff --git a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
index 5dcade0b4ea..77e512eb28d 100644
--- a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
+++ b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts
@@ -25,16 +25,24 @@ export function calculateTotalTokens(usage?: AgentState['usage']): number | unde
}
/**
- * Usage a continued sub-agent thread accumulated in its earlier runs. Every
- * run starts fresh counters and each thread write replaces `metadata`, so a
- * follow-up run carries these forward and adds its own usage on top.
+ * What a thread's metadata carries from one write and one run to the next.
+ * Every thread write replaces `metadata`, so each writer spreads these back
+ * in: the tool call that spawned the thread (how the UI tells a sub-agent
+ * from an ordinary thread), and the usage of earlier runs, which a follow-up
+ * run adds its own usage on top of.
*/
-export type ThreadUsageBaseline = Pick<
+export type ThreadCarryOver = Pick<
ThreadMetadata,
- 'totalCost' | 'totalLlmCalls' | 'totalMessages' | 'totalTokens' | 'totalToolCalls'
+ | 'sourceToolCallId'
+ | 'totalCost'
+ | 'totalLlmCalls'
+ | 'totalMessages'
+ | 'totalTokens'
+ | 'totalToolCalls'
>;
-export const pickThreadUsageBaseline = (metadata?: ThreadMetadata | null): ThreadUsageBaseline => ({
+export const pickThreadCarryOver = (metadata?: ThreadMetadata | null): ThreadCarryOver => ({
+ sourceToolCallId: metadata?.sourceToolCallId,
totalCost: metadata?.totalCost,
totalMessages: metadata?.totalMessages,
totalLlmCalls: metadata?.totalLlmCalls,
@@ -190,8 +198,17 @@ export function createThreadHooks(
startedAt: string,
sourceMessageId: string | undefined,
logScope: 'execSubAgent' | 'execVirtualSubAgent',
- usageBaseline: ThreadUsageBaseline = {},
+ carryOver: ThreadCarryOver = {},
+ options: {
+ /**
+ * Copy the run's final answer into the source message. Off for background
+ * sub-agents, whose source message is the start receipt the parent already
+ * read — their answer is delivered as a separate message instead.
+ */
+ updateSourceMessage?: boolean;
+ } = {},
): AgentHook[] {
+ const { updateSourceMessage = true } = options;
return [
{
handler: async (event: AgentHookEvent) => {
@@ -202,16 +219,14 @@ export function createThreadHooks(
await threadModel.update(threadId, {
metadata: {
operationId: event.operationId,
+ sourceToolCallId: carryOver.sourceToolCallId,
startedAt,
- totalCost: usageBaseline.totalCost,
+ totalCost: carryOver.totalCost,
totalMessages: state.messages?.length ?? 0,
- totalSteps: addUsage(usageBaseline.totalLlmCalls, getLlmCallCount(state)),
- totalLlmCalls: addUsage(usageBaseline.totalLlmCalls, getLlmCallCount(state)),
- totalTokens: addUsage(usageBaseline.totalTokens, calculateTotalTokens(state.usage)),
- totalToolCalls: addUsage(
- usageBaseline.totalToolCalls,
- state.usage?.tools?.totalCalls,
- ),
+ totalSteps: addUsage(carryOver.totalLlmCalls, getLlmCallCount(state)),
+ totalLlmCalls: addUsage(carryOver.totalLlmCalls, getLlmCallCount(state)),
+ totalTokens: addUsage(carryOver.totalTokens, calculateTotalTokens(state.usage)),
+ totalToolCalls: addUsage(carryOver.totalToolCalls, state.usage?.tools?.totalCalls),
},
});
} catch (error) {
@@ -270,7 +285,7 @@ export function createThreadHooks(
.reverse()
.find((m: { role: string }) => m.role === 'assistant');
- if (sourceMessageId && lastAssistantMessage?.content) {
+ if (updateSourceMessage && sourceMessageId && lastAssistantMessage?.content) {
await messageModel.update(sourceMessageId, {
content: lastAssistantMessage.content,
});
@@ -284,17 +299,15 @@ export function createThreadHooks(
duration,
error: formattedError,
operationId: finalState.operationId,
+ sourceToolCallId: carryOver.sourceToolCallId,
startedAt,
- totalCost: addUsage(usageBaseline.totalCost, finalState.cost?.total),
+ totalCost: addUsage(carryOver.totalCost, finalState.cost?.total),
totalMessages: finalState.messages?.length ?? 0,
- totalSteps: addUsage(usageBaseline.totalLlmCalls, getLlmCallCount(finalState)),
- totalLlmCalls: addUsage(usageBaseline.totalLlmCalls, getLlmCallCount(finalState)),
- totalTokens: addUsage(
- usageBaseline.totalTokens,
- calculateTotalTokens(finalState.usage),
- ),
+ totalSteps: addUsage(carryOver.totalLlmCalls, getLlmCallCount(finalState)),
+ totalLlmCalls: addUsage(carryOver.totalLlmCalls, getLlmCallCount(finalState)),
+ totalTokens: addUsage(carryOver.totalTokens, calculateTotalTokens(finalState.usage)),
totalToolCalls: addUsage(
- usageBaseline.totalToolCalls,
+ carryOver.totalToolCalls,
finalState.usage?.tools?.totalCalls,
),
},
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 2a158dbbc93..f441f264c9a 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -16,6 +16,7 @@ import type {
import { RequestTrigger } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
+import { sql } from 'drizzle-orm';
import { AgentModel } from '@/database/models/agent';
import { AgentOperationModel } from '@/database/models/agentOperation';
@@ -51,6 +52,11 @@ import { ComposioService } from '@/server/services/composio';
import { MarketService } from '@/server/services/market';
import type { SteerQueueScope } from '@/server/services/redis/steerQueue';
+import {
+ type BackgroundSubAgentResult,
+ deliverBackgroundSubAgentResults,
+} from './backgroundSubAgentDelivery';
+import { resolveForegroundInterventionConfig } from './foregroundIntervention';
import { createGraphAwareAgentFactory } from './helpers/agentFactory';
import { InterventionController } from './intervention/InterventionController';
import type { ApprovalClaimState } from './pipeline/approvalResume';
@@ -163,6 +169,7 @@ export class AiAgentService {
//
// Arrow fields are auto-bound, so no `.bind(this)`.
delegate: {
+ deliverBackgroundSubAgentResults: this.deliverBackgroundSubAgentResults,
execSubAgent: this.execSubAgent,
execVirtualSubAgent: this.execVirtualSubAgent,
execGroupMember: this.execGroupMember,
@@ -714,6 +721,7 @@ export class AiAgentService {
*/
execVirtualSubAgent = async (params: ExecVirtualSubAgentParams): Promise<ExecSubAgentResult> =>
execAgentThreadRun(this.subAgentRunDeps, params, {
+ background: params.background,
chatConfig: params.chatConfig,
deviceId: params.deviceId,
isSubAgent: true,
@@ -727,6 +735,74 @@ export class AiAgentService {
resumeParentOnComplete: true,
});
+ /**
+ * Hand a topic's finished background sub-agent results to their parent agent
+ * as a new turn — see `backgroundSubAgentDelivery`. Runtime delegate entry.
+ */
+ deliverBackgroundSubAgentResults = (params: {
+ settledOperationId?: string;
+ topicId: string;
+ }): Promise<void> =>
+ deliverBackgroundSubAgentResults(
+ {
+ agentOperationModel: this.agentOperationModel,
+ appendResultMessages: this.appendBackgroundResultMessages,
+ execAgent: (execParams) => this.execAgent(execParams),
+ messageModel: this.messageModel,
+ resolveInterventionConfig: () => resolveForegroundInterventionConfig(this.db, this.userId),
+ topicModel: this.topicModel,
+ },
+ params,
+ );
+
+ /**
+ * Land background sub-agent answers on the topic's main line as user
+ * messages whose sender is each sub-agent. Serialized per topic
+ * (with task callbacks too) so concurrent deliveries cannot anchor on the
+ * same leaf and fork the line; ids derive from the call, so a retried
+ * delivery skips what it already wrote. Returns the line's new leaf.
+ */
+ private appendBackgroundResultMessages = async (params: {
+ agentId: string;
+ results: BackgroundSubAgentResult[];
+ topicId: string;
+ }): Promise<string | undefined> => {
+ const { agentId, results, topicId } = params;
+
+ return this.db.transaction(async (tx) => {
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${topicId}))`);
+ const messageModel = new MessageModel(tx, this.userId, this.workspaceId);
+ let leafId = await messageModel.getLastMainThreadSpineMessageId(topicId);
+
+ for (const item of results) {
+ const messageId = `subagent-cb-${item.callId}`;
+ if (await messageModel.findById(messageId)) continue;
+
+ await messageModel.create(
+ {
+ agentId,
+ content: item.result,
+ metadata: {
+ subAgentCallback: {
+ agentId: item.sender.agentId,
+ name: item.sender.name,
+ status: item.status,
+ threadId: item.threadId,
+ },
+ },
+ parentId: leafId,
+ role: 'user',
+ topicId,
+ },
+ messageId,
+ );
+ leafId = messageId;
+ }
+
+ return leafId;
+ });
+ };
+
/**
* Fork a single group member ("call agent member") under a `lobe-group-management`
* tool call. Dispatches to the in-group (non-isolated, shared group session)
diff --git a/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.ts b/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.ts
index 4adb49b8e8c..5460272b403 100644
--- a/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.ts
+++ b/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.ts
@@ -12,7 +12,7 @@ import type {
import {
createGroupActionMemberBridgeHook,
createThreadHooks,
- pickThreadUsageBaseline,
+ pickThreadCarryOver,
} from '../hooks/threadRunHooks';
import type { InternalExecAgentParams } from '../types';
@@ -74,7 +74,7 @@ export const createGroupMemberApprovalDeps = (models: {
// The recovered group-member bridge owns result publication.
undefined,
'execVirtualSubAgent',
- pickThreadUsageBaseline(thread.metadata),
+ pickThreadCarryOver(thread.metadata),
);
},
findMessagePlugin: (messageId) => models.messageModel.findMessagePlugin(messageId),
diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.ts
index fa05f666559..566d44cfb4e 100644
--- a/apps/server/src/services/aiAgent/subAgentRuns.ts
+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts
@@ -27,8 +27,8 @@ import {
createGroupActionMemberBridgeHook,
createSubAgentBridgeHook,
createThreadHooks,
- pickThreadUsageBaseline,
- type ThreadUsageBaseline,
+ pickThreadCarryOver,
+ type ThreadCarryOver,
} from './hooks/threadRunHooks';
import type { InternalExecAgentParams } from './types';
@@ -47,6 +47,13 @@ export interface SubAgentRunDeps {
}
export interface ExecAgentThreadRunOptions {
+ /**
+ * Detached `callSubAgent({ runInBackground })` run. Its placeholder already
+ * holds the start receipt the parent read, so the thread hooks must not
+ * replace it with the answer, and nobody is listening on the parent's
+ * channel for live progress.
+ */
+ background?: boolean;
/**
* Override the default sub-agent completion bridge with a custom hook
* (e.g. the group-action member bridge for isolated executeAgentTask(s)).
@@ -111,13 +118,14 @@ type ThreadRow = NonNullable<Awaited<ReturnType<ThreadModel['findById']>>>;
* previous run is still going. The final compare-and-set claim makes
* concurrent follow-ups to one sub-agent race-safe.
*
- * Returns the usage the thread accumulated so far; the claim and every later
- * write of this run carry it forward instead of resetting the totals.
+ * Returns what the thread carries (its spawning tool call and the usage it
+ * accumulated so far); the claim and every later write of this run carry it
+ * forward instead of resetting it.
*/
const claimSubAgentThread = async (
deps: SubAgentRunDeps,
params: { agentId: string; startedAt: string; threadId: string; topicId: string },
-): Promise<{ error: string } | { thread: ThreadRow; usageBaseline: ThreadUsageBaseline }> => {
+): Promise<{ error: string } | { thread: ThreadRow; carryOver: ThreadCarryOver }> => {
const { agentId, startedAt, threadId, topicId } = params;
const thread = await deps.threadModel.findById(threadId);
@@ -153,14 +161,14 @@ const claimSubAgentThread = async (
if (stillRunning) return { error: busyError };
- const usageBaseline = pickThreadUsageBaseline(previousMetadata);
+ const carryOver = pickThreadCarryOver(previousMetadata);
const claimed = await deps.threadModel.claimForRun(
thread.id,
{ operationId: previousOperationId ?? null, status: thread.status },
- { ...usageBaseline, startedAt },
+ { ...carryOver, startedAt },
);
- return claimed ? { thread, usageBaseline } : { error: busyError };
+ return claimed ? { thread, carryOver } : { error: busyError };
};
/**
@@ -201,7 +209,7 @@ export const execAgentThreadRun = async (
const startedAt = new Date().toISOString();
const continueThreadId = 'threadId' in params ? params.threadId : undefined;
let thread: ThreadRow;
- let usageBaseline: ThreadUsageBaseline = {};
+ let carryOver: ThreadCarryOver = {};
if (continueThreadId) {
// 1-2. Continue an earlier callSubAgent thread: claim it (→ processing).
@@ -238,7 +246,7 @@ export const execAgentThreadRun = async (
}
thread = claim.thread;
- usageBaseline = claim.usageBaseline;
+ carryOver = claim.carryOver;
log('%s: continuing thread %s', options.logScope, thread.id);
} else {
// 1. Create Thread for isolated agent execution
@@ -258,9 +266,14 @@ export const execAgentThreadRun = async (
thread = created;
log('%s: created thread %s', options.logScope, thread.id);
+ // The spawning tool call marks the thread as a sub-agent in the UI; it rides
+ // along on every later metadata write.
+ const sourceToolCallId = 'sourceToolCallId' in params ? params.sourceToolCallId : undefined;
+ if (sourceToolCallId) carryOver = { sourceToolCallId };
+
// 2. Update Thread status to processing with startedAt timestamp
await deps.threadModel.update(thread.id, {
- metadata: { startedAt },
+ metadata: { ...carryOver, startedAt },
status: ThreadStatus.Processing,
});
}
@@ -276,7 +289,8 @@ export const execAgentThreadRun = async (
startedAt,
hasCompletionBridge ? undefined : parentMessageId,
options.logScope,
- usageBaseline,
+ carryOver,
+ { updateSourceMessage: !options.background },
);
// For the virtual sub-agent path, also register the completion bridge that
// backfills the parent's placeholder tool message and resumes the parked
@@ -314,7 +328,10 @@ export const execAgentThreadRun = async (
// members are excluded — their whole stream is already mirrored onto the
// supervisor's channel via `mirrorToOperationId`.
const subAgentProgress =
- options.resumeParentOnComplete && parentOperationId && options.orchestrationRole !== 'member'
+ options.resumeParentOnComplete &&
+ parentOperationId &&
+ options.orchestrationRole !== 'member' &&
+ !options.background
? { parentOperationId, toolMessageId: parentMessageId }
: undefined;
@@ -360,7 +377,7 @@ export const execAgentThreadRun = async (
await deps.threadModel
.update(thread.id, {
metadata: {
- ...usageBaseline,
+ ...carryOver,
completedAt: new Date().toISOString(),
error: String(error),
startedAt,
@@ -387,7 +404,7 @@ export const execAgentThreadRun = async (
// 5. Store operationId in Thread metadata
await deps.threadModel.update(thread.id, {
- metadata: { ...usageBaseline, operationId: result.operationId, startedAt },
+ metadata: { ...carryOver, operationId: result.operationId, startedAt },
});
// 6. If operation failed to start, update thread status
@@ -395,7 +412,7 @@ export const execAgentThreadRun = async (
const completedAt = new Date().toISOString();
await deps.threadModel.update(thread.id, {
metadata: {
- ...usageBaseline,
+ ...carryOver,
completedAt,
duration: Date.now() - new Date(startedAt).getTime(),
error: result.error,
diff --git a/apps/server/src/services/taskResultBridge/index.ts b/apps/server/src/services/taskResultBridge/index.ts
index 56068bcfe6b..52dfaf25dd1 100644
--- a/apps/server/src/services/taskResultBridge/index.ts
+++ b/apps/server/src/services/taskResultBridge/index.ts
@@ -2,7 +2,7 @@ import type {
ChatTopicBotContext,
TaskContext,
TaskTopicHandoff,
- UserToolConfig,
+ UserInterventionConfig,
} from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
@@ -12,13 +12,13 @@ import { MessageModel } from '@/database/models/message';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
-import { UserModel } from '@/database/models/user';
import type { LobeChatDatabase } from '@/database/type';
import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
import type { BotCallbackBody } from '@/server/services/bot/BotCallbackService';
import { BotCallbackService } from '@/server/services/bot/BotCallbackService';
import { AiAgentService } from '../aiAgent';
+import { resolveForegroundInterventionConfig } from '../aiAgent/foregroundIntervention';
import { acquireTopicStartReservation } from '../aiAgent/topicStartReservation';
import { TaskResultCallbackRedisStore } from './redisStore';
@@ -244,14 +244,9 @@ export class TaskResultBridgeService {
// A creator wakeup continues a user-facing conversation. Preserve the
// same approval preferences as a foreground send, including its allow
// list. Bot channels still lack this UI/resume contract and stay headless.
- const settings = botContext
- ? undefined
- : await new UserModel(this.db, this.userId).getUserSettings();
- const intervention = (settings?.tool as UserToolConfig | undefined)?.humanIntervention;
- const approvalMode =
- intervention?.approvalMode === 'headless'
- ? 'auto-run'
- : (intervention?.approvalMode ?? 'manual');
+ const userInterventionConfig: UserInterventionConfig = botContext
+ ? { approvalMode: 'headless' }
+ : await resolveForegroundInterventionConfig(this.db, this.userId);
const result = await new AiAgentService(this.db, this.userId, {
workspaceId: this.workspaceId,
@@ -266,9 +261,7 @@ export class TaskResultBridgeService {
suppressUserMessage: true,
topicStartReservationId: reservationId,
trigger: RequestTrigger.AgentSignal,
- userInterventionConfig: botContext
- ? { approvalMode: 'headless' }
- : { allowList: intervention?.allowList ?? [], approvalMode },
+ userInterventionConfig,
});
await callbackStore.attachCreatorOperation(receiptIds, result.operationId);
} catch (error) {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.callAgentBackground.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.callAgentBackground.test.ts
new file mode 100644
index 00000000000..2e6b1affe66
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.callAgentBackground.test.ts
@@ -0,0 +1,84 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentManagementRuntime } from '../agentManagement';
+
+const { mockGetAgentConfigById, mockListBackgroundSubAgentCalls } = vi.hoisted(() => ({
+ mockGetAgentConfigById: vi.fn(),
+ mockListBackgroundSubAgentCalls: vi.fn(),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn(function () {
+ return { listBackgroundSubAgentCalls: mockListBackgroundSubAgentCalls };
+ }),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(function () {
+ return { getAgentConfigById: mockGetAgentConfigById };
+ }),
+}));
+
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+vi.mock('@/server/services/agent', () => ({ AgentService: vi.fn() }));
+vi.mock('@/server/services/discover', () => ({ DiscoverService: vi.fn() }));
+
+const createRuntime = () =>
+ agentManagementRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+describe('agentManagementRuntime callAgent', () => {
+ describe('runInBackground', () => {
+ const topicCtx = { topicId: 'topic-1', toolManifestMap: {} };
+
+ beforeEach(() => {
+ mockListBackgroundSubAgentCalls.mockResolvedValue([]);
+ mockGetAgentConfigById.mockResolvedValue({ title: 'Poet' });
+ });
+
+ // The reply arrives later as a message from the target; the caller keeps going.
+ it('returns the start receipt at once, written into the runner placeholder', async () => {
+ const run = vi.fn().mockResolvedValue({
+ started: true,
+ subOperationId: 'op-child',
+ threadId: 'thread-child',
+ toolMessageId: 'placeholder-1',
+ });
+ const runtime = createRuntime();
+
+ const result = await runtime.callAgent(
+ { agentId: 'agent-target', instruction: 'Write a poem', runInBackground: true },
+ { ...topicCtx, subAgent: { run } },
+ );
+
+ expect(run).toHaveBeenCalledWith(
+ expect.objectContaining({ background: true, description: 'Poet' }),
+ );
+ expect(result.deferred).toBeUndefined();
+ expect(result).toMatchObject({ success: true, toolMessageId: 'placeholder-1' });
+ expect(result.content).toContain('Started in the background');
+ // A callAgent target cannot be continued with subAgentId, so no handle.
+ expect(result.content).not.toContain('<sub_agent');
+ });
+
+ it('refuses in a group conversation without starting anything', async () => {
+ const run = vi.fn();
+ const runtime = createRuntime();
+
+ const result = await runtime.callAgent(
+ { agentId: 'agent-target', instruction: 'Write a poem', runInBackground: true },
+ { ...topicCtx, groupId: 'group-1', subAgent: { run } },
+ );
+
+ expect(result).toMatchObject({
+ error: { code: 'BACKGROUND_SUB_AGENT_UNSUPPORTED' },
+ success: false,
+ });
+ expect(run).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
index 930265b6ed4..9dc575bb163 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
@@ -242,6 +242,7 @@ describe('agentManagementRuntime', () => {
expect(run).toHaveBeenCalledWith({
agentId: 'agent-target',
+ background: false,
description: 'Call agent agent-target',
instruction: 'Do delegated work',
timeout: 1_800_000,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/backgroundSubAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/backgroundSubAgent.test.ts
new file mode 100644
index 00000000000..d5bcd07acbf
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/backgroundSubAgent.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { MAX_RUNNING_BACKGROUND_SUB_AGENTS, startBackgroundSubAgent } from '../backgroundSubAgent';
+
+// The running set the limit check counts: every started run's placeholder.
+const placeholders = vi.hoisted(() => new Map<string, string[]>());
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return {
+ listBackgroundSubAgentCalls: async ({ topicId }: { topicId: string }) => {
+ // Let concurrent checks interleave, as real database reads do.
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ return (placeholders.get(topicId) ?? []).map((id) => ({ id }));
+ },
+ };
+ }),
+}));
+
+const startOn = (topicId: string, id: string) =>
+ startBackgroundSubAgent({
+ db: {} as any,
+ retryHint: 'Retry in the foreground.',
+ start: async () => {
+ // The runner writes the placeholder before it resolves.
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ placeholders.set(topicId, [...(placeholders.get(topicId) ?? []), id]);
+ return id;
+ },
+ topicId,
+ userId: 'user-1',
+ });
+
+describe('startBackgroundSubAgent', () => {
+ // One tool batch runs its calls concurrently: without serializing, every call
+ // counts the same empty running set and all of them start.
+ it('starts no more than the limit when one batch fires calls concurrently', async () => {
+ const outcomes = await Promise.all(
+ Array.from({ length: MAX_RUNNING_BACKGROUND_SUB_AGENTS + 2 }, (_, index) =>
+ startOn('topic-batch', `call-${index}`),
+ ),
+ );
+
+ expect(outcomes.filter((outcome) => 'result' in outcome)).toHaveLength(
+ MAX_RUNNING_BACKGROUND_SUB_AGENTS,
+ );
+ expect(outcomes.filter((outcome) => 'refusal' in outcome)).toEqual([
+ { refusal: expect.objectContaining({ code: 'BACKGROUND_SUB_AGENT_LIMIT' }) },
+ { refusal: expect.objectContaining({ code: 'BACKGROUND_SUB_AGENT_LIMIT' }) },
+ ]);
+ expect(placeholders.get('topic-batch')).toHaveLength(MAX_RUNNING_BACKGROUND_SUB_AGENTS);
+ });
+
+ it('keeps the queue moving after a start throws', async () => {
+ const failing = startBackgroundSubAgent({
+ db: {} as any,
+ retryHint: 'Retry in the foreground.',
+ start: async () => {
+ throw new Error('boom');
+ },
+ topicId: 'topic-throw',
+ userId: 'user-1',
+ });
+
+ await expect(failing).rejects.toThrow('boom');
+ await expect(startOn('topic-throw', 'after')).resolves.toEqual({ result: 'after' });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.callSubAgentBackground.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.callSubAgentBackground.test.ts
new file mode 100644
index 00000000000..2d97c1f342a
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.callSubAgentBackground.test.ts
@@ -0,0 +1,106 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ToolExecutionContext } from '../../types';
+
+const mockListBackgroundSubAgentCalls = vi.hoisted(() => vi.fn());
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return {
+ listBackgroundSubAgentCalls: (...args: any[]) => mockListBackgroundSubAgentCalls(...args),
+ };
+ }),
+}));
+
+const { lobeAgentRuntime } = await import('../lobeAgent');
+const { MAX_RUNNING_BACKGROUND_SUB_AGENTS } = await import('../backgroundSubAgent');
+
+describe('lobeAgentRuntime callSubAgent', () => {
+ const baseContext: ToolExecutionContext = {
+ messageId: 'msg-1',
+ serverDB: {} as any,
+ toolManifestMap: {},
+ userId: 'user-1',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockListBackgroundSubAgentCalls.mockResolvedValue([]);
+ });
+
+ describe('runInBackground', () => {
+ const topicContext = { ...baseContext, topicId: 'topic-1' } as ToolExecutionContext;
+
+ it('returns the start receipt at once, written into the runner placeholder', async () => {
+ const runtime = lobeAgentRuntime.factory(topicContext);
+ const run = vi.fn().mockResolvedValue({
+ started: true,
+ subOperationId: 'sub-op-1',
+ threadId: 'thread-1',
+ toolMessageId: 'placeholder-1',
+ });
+
+ const result = await runtime.callSubAgent(
+ { description: 'Research', instruction: 'Find the answer', runInBackground: true },
+ { ...topicContext, subAgent: { run } } as ToolExecutionContext,
+ );
+
+ expect(run).toHaveBeenCalledWith(expect.objectContaining({ background: true }));
+ expect(result.deferred).toBeUndefined();
+ expect(result).toMatchObject({ success: true, toolMessageId: 'placeholder-1' });
+ expect(result.content).toContain('Started in the background');
+ expect(result.content).toMatch(/<sub_agent id="thread-1" \/>$/);
+ });
+
+ it('refuses in a group conversation without starting anything', async () => {
+ const groupContext = { ...topicContext, groupId: 'group-1' } as ToolExecutionContext;
+ const runtime = lobeAgentRuntime.factory(groupContext);
+ const run = vi.fn();
+
+ const result = await runtime.callSubAgent(
+ { description: 'Research', instruction: 'Find the answer', runInBackground: true },
+ { ...groupContext, subAgent: { run } } as ToolExecutionContext,
+ );
+
+ expect(result).toMatchObject({
+ error: { code: 'BACKGROUND_SUB_AGENT_UNSUPPORTED' },
+ success: false,
+ });
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it('refuses once the conversation already runs the maximum', async () => {
+ mockListBackgroundSubAgentCalls.mockResolvedValue(
+ Array.from({ length: MAX_RUNNING_BACKGROUND_SUB_AGENTS }, (_, index) => ({
+ id: `running-${index}`,
+ })),
+ );
+ const runtime = lobeAgentRuntime.factory(topicContext);
+ const run = vi.fn();
+
+ const result = await runtime.callSubAgent(
+ { description: 'Research', instruction: 'Find the answer', runInBackground: true },
+ { ...topicContext, subAgent: { run } } as ToolExecutionContext,
+ );
+
+ expect(mockListBackgroundSubAgentCalls).toHaveBeenCalledWith(
+ expect.objectContaining({ scope: 'running', topicId: 'topic-1' }),
+ );
+ expect(result).toMatchObject({ error: { code: 'BACKGROUND_SUB_AGENT_LIMIT' } });
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it('still reports a start failure inline', async () => {
+ const runtime = lobeAgentRuntime.factory(topicContext);
+ const run = vi.fn().mockResolvedValue({ error: 'boom', started: false, threadId: '' });
+
+ const result = await runtime.callSubAgent(
+ { description: 'Research', instruction: 'Find the answer', runInBackground: true },
+ { ...topicContext, subAgent: { run } } as ToolExecutionContext,
+ );
+
+ expect(result).toMatchObject({ error: { code: 'SUB_AGENT_START_FAILED' }, success: false });
+ expect(result.toolMessageId).toBeUndefined();
+ });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
index 5064206e1dd..fb816885d76 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
@@ -968,6 +968,7 @@ describe('lobeAgentRuntime', () => {
);
expect(run).toHaveBeenCalledWith({
+ background: false,
description: 'Research',
instruction: 'Find the answer',
timeout: 1000,
@@ -1064,6 +1065,7 @@ describe('lobeAgentRuntime', () => {
);
expect(run).toHaveBeenCalledWith({
+ background: false,
description: 'Research',
instruction: 'Find the answer',
subAgentId: undefined,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
index 79449c496a6..b7513debdf9 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
@@ -10,6 +10,7 @@ import {
type UpdateAgentParams,
type UpdatePromptParams,
} from '@lobechat/builtin-tool-agent-management';
+import { buildBackgroundSubAgentReceipt } from '@lobechat/builtin-tool-lobe-agent';
import { searchAgentsResultsPrompt } from '@lobechat/prompts';
import {
getPluginMode,
@@ -26,6 +27,7 @@ import { AgentService } from '@/server/services/agent';
import { DiscoverService } from '@/server/services/discover';
import { type ToolExecutionContext, type ToolExecutionResult } from '../types';
+import { startBackgroundSubAgent } from './backgroundSubAgent';
import {
NEXT_RUN_NOTE,
resolveOrInstallMarketPlugin,
@@ -98,12 +100,46 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
};
}
- const { started, error, subOperationId, threadId } = await ctx.subAgent.run({
- agentId,
- description: `Call agent ${agentId}`,
- instruction,
- timeout: 1_800_000,
- });
+ const background = params.runInBackground === true;
+
+ // The target's name titles its thread and, for a background call, is who
+ // the reply is delivered as.
+ const targetTitle = (await agentModel.getAgentConfigById(agentId))?.title;
+
+ const runner = ctx.subAgent;
+ const startRun = () =>
+ runner.run({
+ agentId,
+ background,
+ description: targetTitle || `Call agent ${agentId}`,
+ instruction,
+ timeout: 1_800_000,
+ });
+
+ let runResult: Awaited<ReturnType<typeof startRun>>;
+ if (background) {
+ const outcome = await startBackgroundSubAgent({
+ db: context.serverDB!,
+ groupId: ctx.groupId,
+ retryHint: 'Call callAgent again without runInBackground to wait for the reply.',
+ start: startRun,
+ threadId: ctx.threadId,
+ topicId: ctx.topicId,
+ userId: context.userId!,
+ workspaceId: context.workspaceId,
+ });
+ if ('refusal' in outcome) {
+ return {
+ content: outcome.refusal.message,
+ error: { code: outcome.refusal.code, message: outcome.refusal.message },
+ success: false,
+ };
+ }
+ runResult = outcome.result;
+ } else {
+ runResult = await startRun();
+ }
+ const { started, error, subOperationId, threadId, toolMessageId } = runResult;
if (!started) {
const detail = error ? `: ${error}` : '.';
@@ -115,6 +151,13 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
};
}
+ // Detached: the receipt is the whole tool result; the reply arrives later
+ // as a message from the target. It goes into the runner's placeholder,
+ // which anchors the thread.
+ if (background) {
+ return { content: buildBackgroundSubAgentReceipt(), success: true, toolMessageId };
+ }
+
return {
content: '',
deferred: true,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/backgroundSubAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/backgroundSubAgent.ts
new file mode 100644
index 00000000000..155f88b04e7
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/backgroundSubAgent.ts
@@ -0,0 +1,100 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import { MessageModel } from '@/database/models/message';
+
+/**
+ * Background sub-agents one conversation may have running at once. Nobody waits
+ * on them, so without a ceiling a looping parent could fan out unbounded spend.
+ */
+export const MAX_RUNNING_BACKGROUND_SUB_AGENTS = 5;
+
+export interface BackgroundSubAgentRefusal {
+ code: 'BACKGROUND_SUB_AGENT_LIMIT' | 'BACKGROUND_SUB_AGENT_UNSUPPORTED';
+ message: string;
+}
+
+interface BackgroundSubAgentCheckParams {
+ db: LobeChatDatabase;
+ groupId?: string | null;
+ /** How to call the tool in the foreground instead, for the refusal text. */
+ retryHint: string;
+ threadId?: string | null;
+ topicId?: string | null;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Why a background sub-agent (`callSubAgent` / `callAgent` with
+ * `runInBackground`) cannot start from this call; `undefined` when it can.
+ *
+ * Its answer is delivered as a callback message on the conversation's main
+ * line plus a new turn of the conversation's agent, so the parent must be that
+ * main line: not a group (several agents, one supervisor) and not a thread.
+ */
+export const checkBackgroundSubAgentAllowed = async (
+ params: BackgroundSubAgentCheckParams,
+): Promise<BackgroundSubAgentRefusal | undefined> => {
+ const { db, groupId, retryHint, threadId, topicId, userId, workspaceId } = params;
+
+ if (groupId) {
+ return {
+ code: 'BACKGROUND_SUB_AGENT_UNSUPPORTED',
+ message: `Background runs are not supported in group conversations. ${retryHint}`,
+ };
+ }
+ if (!topicId || threadId) {
+ return {
+ code: 'BACKGROUND_SUB_AGENT_UNSUPPORTED',
+ message: `Background runs can only report back to a conversation's main line. ${retryHint}`,
+ };
+ }
+
+ const running = await new MessageModel(db, userId, workspaceId).listBackgroundSubAgentCalls({
+ scope: 'running',
+ topicId,
+ });
+ if (running.length >= MAX_RUNNING_BACKGROUND_SUB_AGENTS) {
+ return {
+ code: 'BACKGROUND_SUB_AGENT_LIMIT',
+ message: `${running.length} background runs are already going in this conversation (limit ${MAX_RUNNING_BACKGROUND_SUB_AGENTS}). Wait for their results to arrive, or ${retryHint.charAt(0).toLowerCase()}${retryHint.slice(1)}`,
+ };
+ }
+};
+
+/** Tail of each topic's start queue; see `startBackgroundSubAgent`. */
+const topicStartQueues = new Map<string, Promise<unknown>>();
+
+/**
+ * Check the limit and start a background sub-agent as one step per topic.
+ *
+ * The tools of one batch run concurrently, so six background calls in a single
+ * step would all count the same running set before any of them wrote its
+ * placeholder, and all pass. `start` writes the placeholder (with
+ * `state.background`) before it resolves, so running each topic's check-and-
+ * start in turn makes every check see the runs started ahead of it. A batch
+ * executes in one process, which is what this in-process queue covers.
+ */
+export const startBackgroundSubAgent = async <T>(
+ params: BackgroundSubAgentCheckParams & { start: () => Promise<T> },
+): Promise<{ refusal: BackgroundSubAgentRefusal } | { result: T }> => {
+ const { start, ...checkParams } = params;
+ const run = async () => {
+ const refusal = await checkBackgroundSubAgentAllowed(checkParams);
+ if (refusal) return { refusal };
+ return { result: await start() };
+ };
+
+ const key = checkParams.topicId;
+ if (!key) return run();
+
+ const previous = topicStartQueues.get(key) ?? Promise.resolve();
+ const current = previous.then(run, run);
+ const tail = current.catch(() => undefined);
+ topicStartQueues.set(key, tail);
+ try {
+ return await current;
+ } finally {
+ if (topicStartQueues.get(key) === tail) topicStartQueues.delete(key);
+ }
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
index 7eeb3184458..dfb6f399775 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
@@ -8,6 +8,7 @@ import type {
} from '@lobechat/builtin-tool-lobe-agent';
import {
buildAnalyzeMediaContent,
+ buildBackgroundSubAgentReceipt,
createMediaFileItemsFromMessage,
createUrlMediaFileItems,
formatMediaUrlValidationError,
@@ -40,6 +41,7 @@ import {
} from '@/server/services/vent';
import type { ToolExecutionContext } from '../types';
+import { startBackgroundSubAgent } from './backgroundSubAgent';
import { normalizeMultimodalImageItems } from './lobeAgentImage';
import { createServerPlanRuntimeService } from './lobeAgentPlan';
import type { ServerRuntimeRegistration } from './types';
@@ -325,13 +327,30 @@ class LobeAgentExecutionRuntime {
// declared field, so "start a new sub-agent" arrives as `subAgentId: ""`
// rather than an omitted key. Blank means new.
const subAgentId = params.subAgentId?.trim() || undefined;
-
- const { started, error, threadId, subOperationId, toolMessageId } = await ctx.subAgent.run({
- description,
- instruction,
- subAgentId,
- timeout,
- });
+ const background = params.runInBackground === true;
+
+ const runner = ctx.subAgent;
+ const startRun = () =>
+ runner.run({ background, description, instruction, subAgentId, timeout });
+
+ let runResult: Awaited<ReturnType<typeof startRun>>;
+ if (background) {
+ const outcome = await startBackgroundSubAgent({
+ db: this.db,
+ groupId: this.groupId,
+ retryHint: 'Call callSubAgent again without runInBackground to wait for the result.',
+ start: startRun,
+ threadId: this.threadId,
+ topicId: this.topicId,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ if ('refusal' in outcome) return buildError(outcome.refusal.message, outcome.refusal.code);
+ runResult = outcome.result;
+ } else {
+ runResult = await startRun();
+ }
+ const { started, error, threadId, subOperationId, toolMessageId } = runResult;
// The child op failed to start — no completion bridge will ever fire to
// backfill a placeholder, so we must NOT defer/park here. Return a normal
@@ -345,6 +364,17 @@ class LobeAgentExecutionRuntime {
);
}
+ // Detached: the receipt is the whole tool result and the parent keeps going.
+ // It goes into the placeholder the runner created (it anchors the thread);
+ // the answer reaches the parent later as its own message.
+ if (background) {
+ return {
+ content: buildBackgroundSubAgentReceipt(threadId),
+ success: true,
+ toolMessageId,
+ };
+ }
+
return {
// No tool_result yet — the bridge fills this in when the sub-op completes.
content: '',
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index 0211329aad1..d4440dfd87a 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -24,6 +24,13 @@ export interface ToolExecutionMemoryEmbeddingRuntime {
export interface ServerSubAgentRunParams {
/** Target agent id; defaults to the parent agent when omitted. */
agentId?: string;
+ /**
+ * Run detached from the parent (`callSubAgent({ runInBackground })`): the
+ * placeholder is written with the start receipt as its final tool result, and
+ * the child's answer is delivered to the parent as a later message instead of
+ * resuming a parked parent. Only set by `callSubAgent`.
+ */
+ background?: boolean;
/** Short label shown in the UI (sub-agent thread title). */
description: string;
/** Detailed instruction/prompt for the sub-agent run. */
@@ -378,6 +385,11 @@ export interface ToolExecutionResult {
errorData?: DeviceUnavailableErrorData;
state?: Record<string, any>;
success: boolean;
+ /**
+ * The tool message this call already created for itself; the agent runtime
+ * writes the result into that row instead of creating a second one.
+ */
+ toolMessageId?: string;
/**
* Transient Work-registration intent produced by the executor and consumed by
* the agent runtime (`callTool` / `callToolsBatch`) once the tool call's
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 40ae2e3d1d9..46e484f4c88 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2260,6 +2260,8 @@
"stt.action": "Voice Input",
"stt.loading": "Recognizing...",
"stt.prettifying": "Polishing...",
+ "subAgentCallback.failed": "Did not finish",
+ "subAgentCallback.tag": "Sub-agent",
"supervisor.label": "Orchestrator",
"supervisor.todoList.allComplete": "All tasks completed",
"supervisor.todoList.title": "Tasks Completed",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 0696b20dbeb..5e0cdc1bda0 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -222,6 +222,8 @@
"builtins.lobe-agent.apiName.vent.category.platform_bug": "Platform bug",
"builtins.lobe-agent.apiName.vent.category.schema_mismatch": "Schema mismatch",
"builtins.lobe-agent.apiName.vent.rejected": "Not recorded",
+ "builtins.lobe-agent.subAgent.backgroundHint": "The result will be sent to this conversation when it finishes.",
+ "builtins.lobe-agent.subAgent.backgroundRunning": "Running in background",
"builtins.lobe-agent.subAgent.stats.tokens": "{{count}} tokens",
"builtins.lobe-agent.subAgent.stats.tools": "{{count}} tools",
"builtins.lobe-agent.subAgent.stopped": "Stopped before finishing",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index d90f6d3b8ac..e2a6af27bd6 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2260,6 +2260,8 @@
"stt.action": "语音输入",
"stt.loading": "识别中…",
"stt.prettifying": "润色中…",
+ "subAgentCallback.failed": "未完成",
+ "subAgentCallback.tag": "子代理",
"supervisor.label": "主管",
"supervisor.todoList.allComplete": "所有任务已完成",
"supervisor.todoList.title": "任务完成",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index b2bdf76aa28..2f6c3e91a05 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -222,6 +222,8 @@
"builtins.lobe-agent.apiName.vent.category.platform_bug": "平台缺陷",
"builtins.lobe-agent.apiName.vent.category.schema_mismatch": "参数不匹配",
"builtins.lobe-agent.apiName.vent.rejected": "未记录",
+ "builtins.lobe-agent.subAgent.backgroundHint": "完成后,结果会作为新消息发回本对话。",
+ "builtins.lobe-agent.subAgent.backgroundRunning": "后台运行中",
"builtins.lobe-agent.subAgent.stats.tokens": "{{count}} tokens",
"builtins.lobe-agent.subAgent.stats.tools": "{{count}} 个工具",
"builtins.lobe-agent.subAgent.stopped": "未完成即中止",
diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.ts
index 568d136ec23..a02c562197f 100644
--- a/packages/agent-runtime/src/transport/tool.ts
+++ b/packages/agent-runtime/src/transport/tool.ts
@@ -26,6 +26,12 @@ export interface ToolRunResult {
/** Tool result requests the current runtime flow to stop. */
stop?: boolean;
success: boolean;
+ /**
+ * The tool message the tool already created for this call (e.g. a background
+ * sub-agent's placeholder). Transports lift it onto
+ * {@link ToolRunExecution.toolMessageId} so the result lands in that row.
+ */
+ toolMessageId?: string;
/**
* Work-registration intent produced by the tool execution (task / skill /
* document identity). The executor forwards it to
diff --git a/packages/builtin-tool-agent-management/src/callAgentManifest.ts b/packages/builtin-tool-agent-management/src/callAgentManifest.ts
index e23c1128395..f52e7a8e38a 100644
--- a/packages/builtin-tool-agent-management/src/callAgentManifest.ts
+++ b/packages/builtin-tool-agent-management/src/callAgentManifest.ts
@@ -8,6 +8,9 @@ const callAgentSystemRole = `You have a callAgent tool to delegate tasks to othe
<execution_guide>
### Synchronous Call
callAgent(agentId, instruction) — agent responds directly in conversation.
+
+### Background Call
+callAgent(agentId, instruction, runInBackground: true) — returns at once; the agent's reply arrives later as a message from that agent. Do not poll for it.
</execution_guide>`;
/**
diff --git a/packages/builtin-tool-agent-management/src/executor.ts b/packages/builtin-tool-agent-management/src/executor.ts
index b0fce897af2..dda482369b5 100644
--- a/packages/builtin-tool-agent-management/src/executor.ts
+++ b/packages/builtin-tool-agent-management/src/executor.ts
@@ -111,6 +111,16 @@ class AgentManagementExecutor extends BaseExecutor<typeof AgentManagementApiName
): Promise<BuiltinToolResult> => {
const { agentId, instruction, skipCallSupervisor = false } = params;
+ // Background delivery wakes the caller through the server runtime, which
+ // this runtime does not have.
+ if (params.runInBackground) {
+ return {
+ content:
+ 'Background agent calls (runInBackground) are not supported in this runtime. Call callAgent again without runInBackground to wait for the reply.',
+ success: false,
+ };
+ }
+
// Execute as synchronous speak
// Two modes: Group vs Agents
diff --git a/packages/builtin-tool-agent-management/src/manifest.ts b/packages/builtin-tool-agent-management/src/manifest.ts
index ffdb31c41a8..aaef4c70781 100644
--- a/packages/builtin-tool-agent-management/src/manifest.ts
+++ b/packages/builtin-tool-agent-management/src/manifest.ts
@@ -293,6 +293,11 @@ export const AgentManagementManifest: BuiltinToolManifest = {
'The instruction or task for the agent to execute. Be specific about expected deliverables.',
type: 'string',
},
+ runInBackground: {
+ description:
+ 'Optional. Start the agent and get control back immediately instead of waiting for its reply. Use it only when you have other independent work to do meanwhile, or when the user should not wait on this reply. The reply arrives later as a message from that agent (waking you up if your turn has ended) — never poll or wait for it. Default is false: wait for the reply in this turn.',
+ type: 'boolean',
+ },
skipCallSupervisor: {
default: false,
description:
diff --git a/packages/builtin-tool-agent-management/src/systemRole.ts b/packages/builtin-tool-agent-management/src/systemRole.ts
index 130b8c0ded8..2cc4a7456d7 100644
--- a/packages/builtin-tool-agent-management/src/systemRole.ts
+++ b/packages/builtin-tool-agent-management/src/systemRole.ts
@@ -158,6 +158,13 @@ For quick responses in the conversation context:
callAgent(agentId, instruction)
\`\`\`
The agent will respond directly in the current conversation.
+
+### Background Call
+When you have other independent work to do meanwhile, or the user should not wait:
+\`\`\`
+callAgent(agentId, instruction, runInBackground: true)
+\`\`\`
+The call returns at once. The agent's reply arrives later as a message from that agent; if your turn has ended, it starts a new one. Do not poll or call the agent again to check on it.
</execution_guide>`;
const subAgentContextSection = `
diff --git a/packages/builtin-tool-agent-management/src/types.ts b/packages/builtin-tool-agent-management/src/types.ts
index 14b754ce98a..9628335b733 100644
--- a/packages/builtin-tool-agent-management/src/types.ts
+++ b/packages/builtin-tool-agent-management/src/types.ts
@@ -284,6 +284,11 @@ export interface CallAgentParams {
* Instruction or task for the agent to execute
*/
instruction: string;
+ /**
+ * Start the agent and return right away instead of waiting for its reply,
+ * which reaches the caller later as a message from that agent.
+ */
+ runInBackground?: boolean;
/**
* If true (and in a group context), skip calling supervisor after agent responds.
* Only relevant when used within agent groups. Default: false
diff --git a/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx
index 68742997e2a..1f907aa827f 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Inspector/CallSubAgent/index.tsx
@@ -1,8 +1,8 @@
'use client';
import type { BuiltinInspectorProps } from '@lobechat/types';
-import { GroupBotIcon } from '@lobehub/ui/icons';
import { createStaticStyles, cx } from '@lobehub/ui';
+import { GroupBotIcon } from '@lobehub/ui/icons';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,6 +12,11 @@ import type { CallSubAgentParams, CallSubAgentState } from '../../../types';
import { SubAgentStats } from '../../components/SubAgentStats';
const styles = createStaticStyles(({ css, cssVar }) => ({
+ background: css`
+ flex-shrink: 0;
+ font-size: 12px;
+ color: ${cssVar.colorTextDescription};
+ `,
chip: css`
overflow: hidden;
display: inline-flex;
@@ -55,7 +60,10 @@ export const CallSubAgentInspector = memo<
const { t } = useTranslation('plugin');
const description = (args?.description || partialArgs?.description)?.trim();
- const isShiny = isArgumentsStreaming || isLoading;
+ // A background call finishes its tool step at once, so `isLoading` drops
+ // while the sub-agent is still working.
+ const runningInBackground = pluginState?.background === true && pluginState.status === 'pending';
+ const isShiny = isArgumentsStreaming || isLoading || runningInBackground;
// The completion bridge writes the authoritative stats flat onto pluginState at
// the end of the run; until then `progress` holds the live totals streamed off
@@ -72,6 +80,11 @@ export const CallSubAgentInspector = memo<
{t('builtins.lobe-agent.apiName.callSubAgent')}
</span>
{description && <span className={styles.chip}>{description}</span>}
+ {runningInBackground && (
+ <span className={styles.background}>
+ {t('builtins.lobe-agent.subAgent.backgroundRunning')}
+ </span>
+ )}
{stats && (
<SubAgentStats
model={stats.model}
diff --git a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx
index e4860948b62..3e0dfb87c5b 100644
--- a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx
+++ b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx
@@ -1,9 +1,7 @@
'use client';
import type { BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Icon, Markdown } from '@lobehub/ui';
-import { Button, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx } from '@lobehub/ui';
+import { Button, createStaticStyles, cssVar, cx, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
import { AlertTriangle, ListTree } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -64,7 +62,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
* than rendered as a dead no-op.
*
* A run that stopped before finishing is marked with a warning, so its partial
- * summary is not mistaken for a finished result.
+ * summary is not mistaken for a finished result. A background run says it is
+ * still running until its answer arrives on the state.
*/
export const CallSubAgentRender = memo<
BuiltinRenderProps<CallSubAgentParams, CallSubAgentState, string>
@@ -72,7 +71,15 @@ export const CallSubAgentRender = memo<
const { t } = useTranslation('plugin');
const { t: tChat } = useTranslation('chat');
const prompt = args?.instruction?.trim();
- const result = typeof content === 'string' ? stripSubAgentReference(content).trim() : '';
+ // A background run's tool result is only its start receipt; the answer is
+ // kept on the state once it arrives.
+ const background = pluginState?.background === true;
+ const result = background
+ ? (pluginState?.result ?? '').trim()
+ : typeof content === 'string'
+ ? stripSubAgentReference(content).trim()
+ : '';
+ const runningInBackground = background && pluginState?.status === 'pending';
const threadId = pluginState?.threadId;
const stopped = pluginState?.status === 'error';
@@ -97,7 +104,7 @@ export const CallSubAgentRender = memo<
if (!prompt && !result && !subagentThread) return null;
- const showResultSection = !!result || !!subagentThread;
+ const showResultSection = !!result || !!subagentThread || runningInBackground;
return (
<Flexbox className={styles.container} gap={12}>
@@ -129,6 +136,10 @@ export const CallSubAgentRender = memo<
{t('builtins.lobe-agent.subAgent.stopped')}
</Text>
</Flexbox>
+ ) : runningInBackground ? (
+ <Text className={styles.label}>
+ {t('builtins.lobe-agent.subAgent.backgroundRunning')}
+ </Text>
) : (
<Text className={styles.label}>{t('builtins.lobe-claude-code.agent.result')}</Text>
)}
@@ -146,6 +157,9 @@ export const CallSubAgentRender = memo<
</Button>
)}
</Flexbox>
+ {runningInBackground && (
+ <Text className={styles.label}>{t('builtins.lobe-agent.subAgent.backgroundHint')}</Text>
+ )}
{result && (
<Flexbox className={cx(styles.resultBox, stopped && styles.stoppedResultBox)}>
<Markdown style={{ maxHeight: 320, overflow: 'auto' }} variant={'chat'}>
diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts b/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts
index 8fa69458a5e..150dbb7d610 100644
--- a/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts
+++ b/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts
@@ -111,3 +111,20 @@ describe('lobeAgentExecutor.callSubAgent', () => {
expect(result.success).toBe(false);
});
});
+
+describe('lobeAgentExecutor.callSubAgent runInBackground', () => {
+ // Delivering a background result needs the server runtime. Quietly running in
+ // the foreground instead would block the turn the model meant to keep going.
+ it('refuses without starting a sub-agent', async () => {
+ const run = vi.fn();
+
+ const result = await lobeAgentExecutor.callSubAgent(
+ { ...params, runInBackground: true },
+ createContext(run),
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('not supported in this runtime');
+ expect(run).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
index 1ce94f33418..32e8e35349e 100644
--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
@@ -481,6 +481,17 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {
};
}
+ // Background delivery wakes the parent through the server runtime, which
+ // this runtime does not have. Running it in the foreground instead would
+ // block a turn the model expected to keep going.
+ if (params.runInBackground) {
+ return {
+ content:
+ 'Background sub-agents (runInBackground) are not supported in this runtime. Call callSubAgent again without runInBackground to wait for the result.',
+ success: false,
+ };
+ }
+
if (!ctx.subAgent) {
return { content: 'Sub-agent execution is not available in this runtime.', success: false };
}
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.ts
index ceb1ac2b15f..671df279971 100644
--- a/packages/builtin-tool-lobe-agent/src/manifest.ts
+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts
@@ -256,6 +256,11 @@ export const LobeAgentManifest: BuiltinToolManifest = {
'Optional. The id from the `<sub_agent id="..." />` tag at the end of an earlier callSubAgent result. Sends `instruction` as a new message to that same sub-agent, which keeps all of its previous work and history — use it to continue a sub-agent that stopped or failed, ask it to hand over what it has found so far, or follow up on its answer. Leave empty (or omit) to start a new sub-agent; never invent an id.',
type: 'string',
},
+ runInBackground: {
+ description:
+ 'Optional. Start the sub-agent and get control back immediately instead of waiting for it. Use it only when you have other independent work to do meanwhile, or when the user should not wait on this result. The result arrives later as a new message (waking you up if your turn has ended) — never poll or wait for it. Default is false: wait for the result in this turn.',
+ type: 'boolean',
+ },
...(isDesktop && {
runInClient: {
description:
diff --git a/packages/builtin-tool-lobe-agent/src/subAgentReference.ts b/packages/builtin-tool-lobe-agent/src/subAgentReference.ts
index 429e5698f31..e31904f3899 100644
--- a/packages/builtin-tool-lobe-agent/src/subAgentReference.ts
+++ b/packages/builtin-tool-lobe-agent/src/subAgentReference.ts
@@ -39,3 +39,15 @@ export const appendSubAgentReference = (content: string, subAgentId: string): st
return body ? `${body}\n\n${reference}` : reference;
};
+
+/**
+ * Tool result of a background call (`callSubAgent` / `callAgent` with
+ * `runInBackground`) — what the parent sees in place of the answer, which
+ * arrives later as a message of its own. `subAgentId` is appended as the
+ * follow-up handle when the sub-agent can be continued (`callSubAgent` only).
+ */
+export const buildBackgroundSubAgentReceipt = (subAgentId?: string): string => {
+ const receipt =
+ 'Started in the background. The result will be delivered to you as a new message when it finishes — do not wait or poll for it. Continue with other work, or end your turn and tell the user what is running.';
+ return subAgentId ? appendSubAgentReference(receipt, subAgentId) : receipt;
+};
diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.ts
index 2ef608389c6..b91eac4cb7b 100644
--- a/packages/builtin-tool-lobe-agent/src/systemRole.ts
+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts
@@ -38,6 +38,12 @@ You can dispatch **sub-agents** to handle long-running, multi-step work in isola
- \`callSubAgent\`: Dispatch a single sub-agent. **Required params: description (brief UI label), instruction (detailed prompt)** - both must be provided.
- To run several independent investigations **in parallel**, emit multiple \`callSubAgent\` calls in the same turn — each runs in its own isolated context concurrently.
+**Background sub-agents (\`runInBackground: true\`):**
+- By default you wait for a sub-agent's result in the same turn. That is the right choice whenever your next step depends on the result.
+- Set \`runInBackground: true\` only when you have other independent work to do meanwhile, or when the user should not have to wait for this result. The call returns right away with the sub-agent's id.
+- The background result is delivered to you later as a message from the sub-agent wrapped in \`<sub_agent_result>\`; if your turn has already ended, it starts a new turn. Do not poll, sleep, or call the sub-agent again to check on it — continue with your other work, or end your turn and tell the user what is running.
+- When the result arrives, use it to finish what the user asked for; the user has not seen it yet.
+
**Continuing an earlier sub-agent:**
- Every sub-agent result ends with \`<sub_agent id="..." />\`. Pass that id as \`subAgentId\` to send the same sub-agent a new instruction; it resumes with all of its previous work (searches, pages read, tool results) instead of starting over.
- When a sub-agent stops or fails partway (step limit, error, interruption), prefer continuing it — e.g. ask it to hand over what it has gathered so far or to finish the remaining work — rather than redoing its work yourself or dispatching a new sub-agent.
diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.ts
index 988274ad8b4..5f79de5f604 100644
--- a/packages/builtin-tool-lobe-agent/src/types.ts
+++ b/packages/builtin-tool-lobe-agent/src/types.ts
@@ -142,6 +142,12 @@ export interface CallSubAgentParams {
description: string;
inheritMessages?: boolean;
instruction: string;
+ /**
+ * Start the sub-agent and return right away instead of waiting for it. The
+ * parent keeps working; when the sub-agent finishes, its result reaches the
+ * parent as a new message (waking it up if its turn has already ended).
+ */
+ runInBackground?: boolean;
runInClient?: boolean;
/**
* Id of an earlier sub-agent (from its result's `<sub_agent id>` trailer).
@@ -181,6 +187,18 @@ export interface SubAgentRunStats {
* Inspector row.
*/
export interface CallSubAgentState extends SubAgentRunStats {
+ /**
+ * Started with `runInBackground`: the tool result is only the start receipt,
+ * and the sub-agent's answer is delivered to the parent as a separate
+ * message. The completion bridge reads this to choose that delivery instead
+ * of backfilling the result and resuming a parked parent.
+ */
+ background?: boolean;
+ /**
+ * When the finished background result was handed to the parent. Unset while
+ * the result is still waiting for the parent's conversation to go idle.
+ */
+ deliveredAt?: string;
/**
* Live totals streamed from the running sub-agent, patched into the store in
* memory only (never persisted). Held in its own key so it can't be mistaken
@@ -188,6 +206,16 @@ export interface CallSubAgentState extends SubAgentRunStats {
* completion bridge — when the run finishes.
*/
progress?: SubAgentRunStats;
+ /**
+ * Final answer of a background run, held here for its delivery to the parent
+ * — the tool result itself stays the start receipt the parent already read.
+ */
+ result?: string;
+ /**
+ * Who a background run's answer is delivered as: the named `callAgent`
+ * target, or the parent itself (with the call's description) for a clone.
+ */
+ sender?: { agentId: string; name: string };
status?: 'pending' | 'completed' | 'error';
threadId: string;
}
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index cbb3e84f4fb..5a683aeb9f9 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -20,6 +20,7 @@ import {
PlaceholderVariablesProcessor,
ReactionFeedbackProcessor,
StaleToolResultTrimProcessor,
+ SubAgentResultMessageProcessor,
SupervisorRoleRestoreProcessor,
TaskCallbackMessageProcessor,
TaskMessageProcessor,
@@ -525,6 +526,9 @@ export class MessagesEngine {
// Flattens group/task messages, applies templates and variables
// =============================================
+ // Background sub-agent results arrive as user messages from the
+ // sub-agent; mark them as its report before any user-text template
+ new SubAgentResultMessageProcessor(),
// Input template processing
new InputTemplateProcessor({ inputTemplate }),
// AgentCouncil message flatten
diff --git a/packages/context-engine/src/processors/InputTemplate.ts b/packages/context-engine/src/processors/InputTemplate.ts
index e9e7e9f06b3..39ad630b552 100644
--- a/packages/context-engine/src/processors/InputTemplate.ts
+++ b/packages/context-engine/src/processors/InputTemplate.ts
@@ -54,8 +54,9 @@ export class InputTemplateProcessor extends BaseProcessor {
for (let i = 0; i < clonedContext.messages.length; i++) {
const message = clonedContext.messages[i];
- // Only apply template to user messages
- if (message.role === 'user') {
+ // Only apply template to what the human typed — not to a background
+ // sub-agent's report, which arrives as a user message from that sub-agent
+ if (message.role === 'user' && !message.metadata?.subAgentCallback) {
try {
const originalContent = message.content;
const processedContent = compiler({ text: originalContent });
diff --git a/packages/context-engine/src/processors/SubAgentResultMessage.ts b/packages/context-engine/src/processors/SubAgentResultMessage.ts
new file mode 100644
index 00000000000..bd0a02ce744
--- /dev/null
+++ b/packages/context-engine/src/processors/SubAgentResultMessage.ts
@@ -0,0 +1,57 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { PipelineContext } from '../types';
+
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ subAgentResultMessagesWrapped?: number;
+ }
+}
+
+const log = debug('context-engine:processor:SubAgentResultMessageProcessor');
+
+const escapeAttribute = (value: string) =>
+ value
+ .replaceAll('&', '&amp;')
+ .replaceAll('"', '&quot;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;');
+
+/**
+ * Sub-Agent Result Message Processor
+ *
+ * A background sub-agent (`callSubAgent` / `callAgent` with `runInBackground`)
+ * reports back as a `user` message whose sender is that sub-agent
+ * (`metadata.subAgentCallback`), with its answer as the content. The chat shows
+ * it as the sub-agent speaking; the model must not read it as the human, so
+ * the content is wrapped in `<sub_agent_result>` — whose `id` is what
+ * `callSubAgent({ subAgentId })` takes to follow up.
+ */
+export class SubAgentResultMessageProcessor extends BaseProcessor {
+ readonly name = 'SubAgentResultMessageProcessor';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ let wrapped = 0;
+
+ clonedContext.messages = clonedContext.messages.map((message) => {
+ const sender = message.metadata?.subAgentCallback;
+ if (message.role !== 'user' || !sender || typeof message.content !== 'string') {
+ return message;
+ }
+
+ wrapped += 1;
+ return {
+ ...message,
+ content: `<sub_agent_result id="${escapeAttribute(sender.threadId)}" name="${escapeAttribute(sender.name)}" status="${sender.status}">\n${message.content.trim()}\n</sub_agent_result>`,
+ };
+ });
+
+ clonedContext.metadata.subAgentResultMessagesWrapped = wrapped;
+ if (wrapped > 0) log(`Wrapped ${wrapped} sub-agent result message(s)`);
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/processors/__tests__/InputTemplate.test.ts b/packages/context-engine/src/processors/__tests__/InputTemplate.test.ts
index adccd17441d..40f8d825ef7 100644
--- a/packages/context-engine/src/processors/__tests__/InputTemplate.test.ts
+++ b/packages/context-engine/src/processors/__tests__/InputTemplate.test.ts
@@ -240,4 +240,28 @@ describe('InputTemplateProcessor', () => {
expect(result.messages[2].content).toBe('System message'); // Unchanged
expect(result.metadata.inputTemplateProcessed).toBe(1);
});
+
+ // A background sub-agent's report arrives as a user message from that
+ // sub-agent; the template is for what the human typed.
+ it('leaves a sub-agent result message untouched', async () => {
+ const processor = new InputTemplateProcessor({ inputTemplate: 'Template: {{text}} - End' });
+
+ const result = await processor.process({
+ initialState: { messages: [], model: 'gpt-4', provider: 'openai', systemRole: '', tools: [] },
+ isAborted: false,
+ messages: [
+ {
+ content: 'The poem',
+ createdAt: Date.now(),
+ id: '1',
+ metadata: { subAgentCallback: { name: 'Poet', status: 'completed', threadId: 'thd' } },
+ role: 'user',
+ updatedAt: Date.now(),
+ },
+ ],
+ metadata: { maxTokens: 4096, model: 'gpt-4' },
+ } as any);
+
+ expect(result.messages[0].content).toBe('The poem');
+ });
});
diff --git a/packages/context-engine/src/processors/__tests__/SubAgentResultMessage.test.ts b/packages/context-engine/src/processors/__tests__/SubAgentResultMessage.test.ts
new file mode 100644
index 00000000000..4446b03db28
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/SubAgentResultMessage.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { SubAgentResultMessageProcessor } from '../SubAgentResultMessage';
+
+describe('SubAgentResultMessageProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ // The chat shows the sub-agent speaking; the model must read it as that
+ // sub-agent reporting back, not as the human, with the id it can follow up with.
+ it('wraps a sub-agent result message with its id, name and status', async () => {
+ const result = await new SubAgentResultMessageProcessor().process(
+ createContext([
+ { content: 'Write a poem in the background', role: 'user' },
+ {
+ content: 'Found three sources.\n',
+ metadata: {
+ subAgentCallback: { name: 'Research "X"', status: 'completed', threadId: 'thd_1' },
+ },
+ role: 'user',
+ },
+ ]),
+ );
+
+ expect(result.messages[0].content).toBe('Write a poem in the background');
+ expect(result.messages[1]).toMatchObject({
+ content:
+ '<sub_agent_result id="thd_1" name="Research &quot;X&quot;" status="completed">\nFound three sources.\n</sub_agent_result>',
+ role: 'user',
+ });
+ expect(result.metadata.subAgentResultMessagesWrapped).toBe(1);
+ });
+
+ it('carries a failure into the status', async () => {
+ const result = await new SubAgentResultMessageProcessor().process(
+ createContext([
+ {
+ content: 'Budget exceeded',
+ metadata: { subAgentCallback: { name: 'Poet', status: 'error', threadId: 'thd_2' } },
+ role: 'user',
+ },
+ ]),
+ );
+
+ expect(result.messages[0].content).toContain('status="error"');
+ });
+});
diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.ts
index 4545f6d6c42..3b7ba4fa702 100644
--- a/packages/context-engine/src/processors/index.ts
+++ b/packages/context-engine/src/processors/index.ts
@@ -31,6 +31,7 @@ export {
type StaleToolResultTrimConfig,
StaleToolResultTrimProcessor,
} from './StaleToolResultTrim';
+export { SubAgentResultMessageProcessor } from './SubAgentResultMessage';
export { SupervisorRoleRestoreProcessor } from './SupervisorRoleRestore';
export { TaskCallbackMessageProcessor } from './TaskCallbackMessage';
export { TaskMessageProcessor } from './TaskMessage';
diff --git a/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts b/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts
new file mode 100644
index 00000000000..d8684266d79
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts
@@ -0,0 +1,170 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messagePlugins, messages, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'background-sub-agent-user';
+const otherUserId = 'background-sub-agent-other';
+const messageModel = new MessageModel(serverDB, userId);
+
+const identifier = 'lobe-agent';
+const apiName = 'callSubAgent';
+const query = { topicId: 'bsa-topic' };
+
+const seedCall = async (opts: {
+ apiName?: string;
+ createdAt?: Date;
+ id: string;
+ ownerId?: string;
+ state: Record<string, unknown> | null;
+ topicId?: string;
+}) => {
+ const owner = opts.ownerId ?? userId;
+ await serverDB.insert(messages).values({
+ content: '',
+ createdAt: opts.createdAt ?? new Date('2026-10-01T00:00:00Z'),
+ id: opts.id,
+ role: 'tool',
+ topicId: opts.topicId ?? 'bsa-topic',
+ userId: owner,
+ });
+ await serverDB.insert(messagePlugins).values({
+ apiName: opts.apiName ?? apiName,
+ id: opts.id,
+ identifier,
+ state: opts.state,
+ toolCallId: `tc-${opts.id}`,
+ userId: owner,
+ });
+};
+
+const readState = async (id: string) => {
+ const [row] = await serverDB
+ .select({ state: messagePlugins.state })
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, id));
+ return row?.state as Record<string, unknown> | null;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values([
+ { id: 'bsa-topic', userId },
+ { id: 'bsa-topic2', userId },
+ { id: 'bsa-other-topic', userId: otherUserId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('MessageModel background sub-agent calls', () => {
+ describe('listBackgroundSubAgentCalls', () => {
+ it('lists only still-running background calls for the running scope', async () => {
+ await seedCall({ id: 'running', state: { background: true, status: 'pending' } });
+ await seedCall({ id: 'done', state: { background: true, status: 'completed' } });
+ await seedCall({ id: 'foreground', state: { status: 'pending' } });
+ await seedCall({ id: 'no-state', state: null });
+
+ const rows = await messageModel.listBackgroundSubAgentCalls({ ...query, scope: 'running' });
+
+ expect(rows.map((row) => row.id)).toEqual(['running']);
+ });
+
+ it('lists finished, undelivered background calls oldest first', async () => {
+ await seedCall({
+ createdAt: new Date('2026-10-01T00:00:02Z'),
+ id: 'failed',
+ state: { background: true, status: 'error', threadId: 'thd-2' },
+ });
+ await seedCall({
+ createdAt: new Date('2026-10-01T00:00:01Z'),
+ id: 'completed',
+ state: { background: true, status: 'completed', threadId: 'thd-1' },
+ });
+ await seedCall({
+ id: 'delivered',
+ state: { background: true, deliveredAt: '2026-10-01T00:00:03Z', status: 'completed' },
+ });
+ await seedCall({ id: 'running', state: { background: true, status: 'pending' } });
+
+ const rows = await messageModel.listBackgroundSubAgentCalls({
+ ...query,
+ scope: 'undelivered',
+ });
+
+ expect(rows.map((row) => row.id)).toEqual(['completed', 'failed']);
+ expect(rows[0].state).toMatchObject({ status: 'completed', threadId: 'thd-1' });
+ });
+
+ it('covers every background call of the topic and owner, whichever tool made it', async () => {
+ const state = { background: true, status: 'completed' };
+ await seedCall({ createdAt: new Date('2026-10-01T00:00:01Z'), id: 'mine', state });
+ await seedCall({
+ apiName: 'callAgent',
+ createdAt: new Date('2026-10-01T00:00:02Z'),
+ id: 'call-agent',
+ state,
+ });
+ await seedCall({ id: 'other-topic', state, topicId: 'bsa-topic2' });
+ await seedCall({ id: 'other-user', ownerId: otherUserId, state, topicId: 'bsa-other-topic' });
+
+ const rows = await messageModel.listBackgroundSubAgentCalls({
+ ...query,
+ scope: 'undelivered',
+ });
+
+ expect(rows.map((row) => row.id)).toEqual(['mine', 'call-agent']);
+ });
+ });
+
+ describe('claimBackgroundSubAgentDelivery', () => {
+ it('stamps deliveredAt once and keeps the rest of the state', async () => {
+ await seedCall({ id: 'a', state: { background: true, status: 'completed', threadId: 't' } });
+
+ const first = await messageModel.claimBackgroundSubAgentDelivery(['a'], 'when-1');
+ const second = await messageModel.claimBackgroundSubAgentDelivery(['a'], 'when-2');
+
+ expect(first).toEqual(['a']);
+ expect(second).toEqual([]);
+ expect(await readState('a')).toEqual({
+ background: true,
+ deliveredAt: 'when-1',
+ status: 'completed',
+ threadId: 't',
+ });
+ });
+
+ it('cannot claim another user’s row', async () => {
+ await seedCall({
+ id: 'foreign',
+ ownerId: otherUserId,
+ state: { background: true, status: 'completed' },
+ topicId: 'bsa-other-topic',
+ });
+
+ expect(await messageModel.claimBackgroundSubAgentDelivery(['foreign'], 'when')).toEqual([]);
+ expect(await readState('foreign')).not.toHaveProperty('deliveredAt');
+ });
+
+ it('lets a released row be claimed again', async () => {
+ await seedCall({ id: 'b', state: { background: true, status: 'completed' } });
+ await messageModel.claimBackgroundSubAgentDelivery(['b'], 'when-1');
+
+ await messageModel.releaseBackgroundSubAgentDelivery(['b']);
+
+ expect(await readState('b')).toEqual({ background: true, status: 'completed' });
+ expect(await messageModel.claimBackgroundSubAgentDelivery(['b'], 'when-2')).toEqual(['b']);
+ });
+ });
+});
diff --git a/packages/database/src/models/message/backgroundSubAgent.ts b/packages/database/src/models/message/backgroundSubAgent.ts
new file mode 100644
index 00000000000..1808b032c56
--- /dev/null
+++ b/packages/database/src/models/message/backgroundSubAgent.ts
@@ -0,0 +1,103 @@
+import { and, asc, eq, inArray, sql } from 'drizzle-orm';
+
+import { messagePlugins, messages } from '../../schemas';
+import { MessageScope } from './scope';
+
+/**
+ * Bookkeeping of background sub-agent calls (`callSubAgent` / `callAgent` with
+ * `runInBackground`): which are still running, and which finished results are
+ * waiting to be handed to their parent agent.
+ */
+export class MessageBackgroundSubAgentQueries extends MessageScope {
+ /**
+ * Background sub-agent calls in a topic — tool rows whose `state.background`
+ * is set (`callSubAgent` / `callAgent` with `runInBackground`; only their
+ * runner writes the flag).
+ *
+ * - `running`: the sub-agent has not reported back yet (`state.status` is
+ * `pending`). Used to cap how many run at once.
+ * - `undelivered`: it finished (`completed` / `error`) but its result has not
+ * been handed to the parent yet (`state.deliveredAt` unset), oldest first.
+ */
+ listBackgroundSubAgentCalls = async (params: {
+ scope: 'running' | 'undelivered';
+ topicId: string;
+ }): Promise<
+ {
+ agentId: string | null;
+ arguments: string | null;
+ id: string;
+ state: Record<string, any>;
+ threadId: string | null;
+ }[]
+ > => {
+ const statusCondition =
+ params.scope === 'running'
+ ? sql`${messagePlugins.state}->>'status' = 'pending'`
+ : and(
+ sql`${messagePlugins.state}->>'status' in ('completed', 'error')`,
+ sql`not coalesce(jsonb_exists(${messagePlugins.state}, 'deliveredAt'), false)`,
+ );
+
+ const rows = await this.db
+ .select({
+ agentId: messages.agentId,
+ arguments: messagePlugins.arguments,
+ id: messages.id,
+ state: messagePlugins.state,
+ threadId: messages.threadId,
+ })
+ .from(messagePlugins)
+ .innerJoin(messages, eq(messagePlugins.id, messages.id))
+ .where(
+ and(
+ eq(messages.topicId, params.topicId),
+ sql`coalesce(${messagePlugins.state}->>'background', '') = 'true'`,
+ statusCondition,
+ this.ownership(),
+ this.pluginsOwnership(),
+ ),
+ )
+ .orderBy(asc(messages.createdAt), asc(messages.id));
+
+ return rows.map((row) => ({ ...row, state: (row.state ?? {}) as Record<string, any> }));
+ };
+
+ /**
+ * Claim finished background sub-agent results for delivery: stamps
+ * `state.deliveredAt` on the rows that do not carry it yet and returns their
+ * ids. Two deliveries racing for the same row cannot both win it.
+ */
+ claimBackgroundSubAgentDelivery = async (
+ ids: string[],
+ deliveredAt: string,
+ ): Promise<string[]> => {
+ if (ids.length === 0) return [];
+
+ const claimed = await this.db
+ .update(messagePlugins)
+ .set({
+ state: sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify({ deliveredAt })}::jsonb`,
+ })
+ .where(
+ and(
+ inArray(messagePlugins.id, ids),
+ sql`not coalesce(jsonb_exists(${messagePlugins.state}, 'deliveredAt'), false)`,
+ this.pluginsOwnership(),
+ ),
+ )
+ .returning({ id: messagePlugins.id });
+
+ return claimed.map((row) => row.id);
+ };
+
+ /** Hand claimed background results back, so a later delivery retries them. */
+ releaseBackgroundSubAgentDelivery = async (ids: string[]): Promise<void> => {
+ if (ids.length === 0) return;
+
+ await this.db
+ .update(messagePlugins)
+ .set({ state: sql`${messagePlugins.state} - 'deliveredAt'` })
+ .where(and(inArray(messagePlugins.id, ids), this.pluginsOwnership()));
+ };
+}
diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.ts
index 7798dc07689..0fd729754c2 100644
--- a/packages/database/src/models/message/index.ts
+++ b/packages/database/src/models/message/index.ts
@@ -7,6 +7,7 @@ import { messages } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { MessageAnalyticsQueries } from './analytics';
import { MessageAnnotationMutations } from './annotation';
+import { MessageBackgroundSubAgentQueries } from './backgroundSubAgent';
import { MessageBranchSnapshots } from './branchSnapshots';
import { MessageDeleteMutations } from './delete';
import { MessageLookupQueries } from './lookup';
@@ -114,6 +115,10 @@ export class MessageModel {
softDeleteTopicless: MessageTrashMutations['softDeleteTopicless'];
purgeMessages: MessageTrashMutations['purgeMessages'];
+ listBackgroundSubAgentCalls: MessageBackgroundSubAgentQueries['listBackgroundSubAgentCalls'];
+ claimBackgroundSubAgentDelivery: MessageBackgroundSubAgentQueries['claimBackgroundSubAgentDelivery'];
+ releaseBackgroundSubAgentDelivery: MessageBackgroundSubAgentQueries['releaseBackgroundSubAgentDelivery'];
+
private readonly annotations: MessageAnnotationMutations;
constructor(
@@ -134,6 +139,7 @@ export class MessageModel {
const writes = new MessageWriteMutations(...args);
const plugins = new MessagePluginStore(args, { lookups });
const tools = new MessageToolMutations(...args);
+ const backgroundSubAgents = new MessageBackgroundSubAgentQueries(...args);
const spine = new MessageSpineQueries(...args);
const annotations = new MessageAnnotationMutations(args, { lookups });
const snapshots = new MessageBranchSnapshots(...args);
@@ -198,6 +204,9 @@ export class MessageModel {
this.findToolMessageIdByToolCallId = plugins.findToolMessageIdByToolCallId;
this.updateToolMessage = tools.updateToolMessage;
this.updateToolArguments = tools.updateToolArguments;
+ this.listBackgroundSubAgentCalls = backgroundSubAgents.listBackgroundSubAgentCalls;
+ this.claimBackgroundSubAgentDelivery = backgroundSubAgents.claimBackgroundSubAgentDelivery;
+ this.releaseBackgroundSubAgentDelivery = backgroundSubAgents.releaseBackgroundSubAgentDelivery;
this.getLastMainThreadSpineMessageId = spine.getLastMainThreadSpineMessageId;
this.isMessageDescendantOf = spine.isMessageDescendantOf;
this.getLatestSpineMessageId = spine.getLatestSpineMessageId;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index ca0b8b6ad8c..a1626302472 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1869,6 +1869,8 @@ export default {
'stt.action': 'Voice Input',
'stt.loading': 'Recognizing...',
'stt.prettifying': 'Polishing...',
+ 'subAgentCallback.failed': 'Did not finish',
+ 'subAgentCallback.tag': 'Sub-agent',
'supervisor.label': 'Orchestrator',
'supervisor.todoList.allComplete': 'All tasks completed',
'supervisor.todoList.title': 'Tasks Completed',
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 3b0b6977cdf..1fe098d4ab9 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -88,6 +88,9 @@ export default {
'builtins.lobe-agent.apiName.analyzeMedia.result':
'Analyze media: <question>{{question}}</question>',
'builtins.lobe-agent.apiName.callSubAgent': 'Call sub-agent',
+ 'builtins.lobe-agent.subAgent.backgroundHint':
+ 'The result will be sent to this conversation when it finishes.',
+ 'builtins.lobe-agent.subAgent.backgroundRunning': 'Running in background',
'builtins.lobe-agent.subAgent.stats.tokens': '{{count}} tokens',
'builtins.lobe-agent.subAgent.stats.tools': '{{count}} tools',
'builtins.lobe-agent.subAgent.stopped': 'Stopped before finishing',
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 17b2ffe552a..e87ae7ef18d 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -641,6 +641,12 @@ export interface ExecSubAgentParams {
export interface ExecVirtualSubAgentParams {
/** The agent ID to execute */
agentId: string;
+ /**
+ * Detached run (`callSubAgent({ runInBackground })`): the parent is not
+ * parked on it, its placeholder already holds the start receipt, and the
+ * answer is delivered to the parent as a separate message on completion.
+ */
+ background?: boolean;
/**
* chatConfig overrides (thinking / reasoning-effort extend params) for the
* sub-agent run, from the parent agent's `agencyConfig.subagent.chatConfig`.
@@ -676,6 +682,12 @@ export interface ExecVirtualSubAgentParams {
parentOperationId: string;
/** Provider for {@link model}. */
provider?: string;
+ /**
+ * The tool call (`callSubAgent` / `callAgent`) that spawned this sub-agent,
+ * stored on a new thread's metadata so the UI shows the thread as a
+ * sub-agent. A continued thread keeps the call that first spawned it.
+ */
+ sourceToolCallId?: string;
/**
* Existing isolation thread of an earlier `callSubAgent` run to continue.
* When set, the instruction becomes a new turn on that thread (the sub-agent
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 056c4712c87..a1fd100fd6a 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -177,6 +177,13 @@ export const MessageSignalSchema = z.object({
type: z.enum(['tool-stdout', 'tool-callback', 'task-completion']),
});
+export const MessageSubAgentCallbackSchema = z.object({
+ agentId: z.string().optional(),
+ name: z.string(),
+ status: z.enum(['completed', 'error']),
+ threadId: z.string(),
+});
+
export const MessageTaskCallbackSchema = z.object({
// Task identifier (e.g. `T-42`) for the card header + jump link.
identifier: z.string(),
@@ -357,6 +364,9 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche
// External-signal lineage for Monitor-style callback turns ().
signal: MessageSignalSchema.optional(),
steer: z.boolean().optional(),
+ // User message carrying a background sub-agent's answer back to its parent;
+ // its sender is that sub-agent.
+ subAgentCallback: MessageSubAgentCallbackSchema.optional(),
subAgentId: z.string().optional(),
// role='taskCallback' card: which task delivered its handoff back to this
// conversation, and the run outcome. The card header + jump link read this.
@@ -645,6 +655,13 @@ export interface MessageMetadata {
* - scope: 'group' | 'group_agent': indicates the agent that generated this message in group mode
* Used by callAgent tool (sub_agent) and group orchestration (group modes)
*/
+ /**
+ * Present on a user message that delivers a background sub-agent's answer
+ * (`callSubAgent` / `callAgent` with `runInBackground`) back to its parent
+ * conversation: the answer is the content, and this is its sender in place
+ * of the human.
+ */
+ subAgentCallback?: MessageSubAgentCallback;
subAgentId?: string;
/**
* Task-callback card pointer (for role='taskCallback' messages). Identifies
@@ -704,6 +721,20 @@ export interface MessageWorkMetadata {
userMessageId?: string;
}
+/** Who sent a background sub-agent's answer — see `MessageMetadata.subAgentCallback`. */
+export interface MessageSubAgentCallback {
+ /**
+ * The agent that answered: a `callAgent` target, or the parent agent itself
+ * for an anonymous `callSubAgent` clone. Its avatar is the sender's.
+ */
+ agentId?: string;
+ /** The sender's label: the call's description, or the target agent's name. */
+ name: string;
+ status: 'completed' | 'error';
+ /** The sub-agent's isolation thread (its full trace, and its id to follow up). */
+ threadId: string;
+}
+
/**
* Pointer carried on a `role='taskCallback'` message — the result-bridge card
* that reports a finished task's handoff back to its creator conversation
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index f910e561c03..9a6ee921c93 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -561,6 +561,12 @@ export interface BuiltinServerRuntimeOutput {
errorData?: DeviceUnavailableErrorData;
state?: any;
success: boolean;
+ /**
+ * The tool message this call already created for itself (e.g. a background
+ * sub-agent's placeholder, which anchors its thread). The agent runtime
+ * writes the result into that row instead of creating a second one.
+ */
+ toolMessageId?: string;
}
export interface BuiltinInterventionProps<Arguments = any> {
diff --git a/src/features/Conversation/Messages/User/SubAgentSender.test.tsx b/src/features/Conversation/Messages/User/SubAgentSender.test.tsx
new file mode 100644
index 00000000000..b6bda6ba962
--- /dev/null
+++ b/src/features/Conversation/Messages/User/SubAgentSender.test.tsx
@@ -0,0 +1,105 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, renderHook, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ SubAgentSenderTags,
+ SubAgentThreadLink,
+ useSubAgentSenderIdentity,
+} from './SubAgentSender';
+
+const agentState = vi.hoisted(() => ({
+ agentMap: { 'agt-poet': { avatar: '🪶', title: '诗人' } } as Record<string, any>,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: unknown) => unknown) => selector(agentState),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: {
+ getAgentMetaById: (id: string) => (s: typeof agentState) => s.agentMap[id] ?? {},
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) =>
+ selector({ closeThreadPortal: vi.fn(), openThreadInPortal: vi.fn() }),
+}));
+
+const threads = vi.hoisted(() => ({ list: [] as { id: string; sourceMessageId: string }[] }));
+
+vi.mock('@/store/chat/selectors', () => ({
+ portalThreadSelectors: { portalThreadId: () => undefined },
+ threadSelectors: { currentTopicThreads: () => threads.list },
+}));
+
+describe('useSubAgentSenderIdentity', () => {
+ // The report is a user turn whose sender is the agent that answered.
+ it('speaks as the answering agent, under the call name when there is one', () => {
+ const named = renderHook(() =>
+ useSubAgentSenderIdentity({
+ agentId: 'agt-poet',
+ name: '列 todo 并写雪诗',
+ status: 'completed',
+ threadId: 'thd_1',
+ }),
+ );
+ const bare = renderHook(() =>
+ useSubAgentSenderIdentity({
+ agentId: 'agt-poet',
+ name: '',
+ status: 'completed',
+ threadId: 'thd_2',
+ }),
+ );
+
+ expect(named.result.current).toEqual({ avatar: '🪶', title: '列 todo 并写雪诗' });
+ expect(bare.result.current).toEqual({ avatar: '🪶', title: '诗人' });
+ });
+
+ it('is absent for an ordinary user message', () => {
+ const { result } = renderHook(() => useSubAgentSenderIdentity(undefined));
+
+ expect(result.current).toBeUndefined();
+ });
+});
+
+describe('SubAgentSenderTags', () => {
+ it('tags the sender as a sub-agent and marks one that did not finish', () => {
+ const { rerender } = render(
+ <SubAgentSenderTags callback={{ name: 'Poet', status: 'completed', threadId: 'thd' }} />,
+ );
+ expect(screen.getByText('subAgentCallback.tag')).toBeTruthy();
+ expect(screen.queryByText('subAgentCallback.failed')).toBeNull();
+
+ rerender(<SubAgentSenderTags callback={{ name: 'Poet', status: 'error', threadId: 'thd' }} />);
+ expect(screen.getByText('subAgentCallback.failed')).toBeTruthy();
+ });
+});
+
+describe('SubAgentThreadLink', () => {
+ // The thread link sits under the report, not in its header.
+ it('offers the thread under the message once the thread is listed', () => {
+ const callback = { name: 'Poet', status: 'completed' as const, threadId: 'thd_1' };
+
+ threads.list = [];
+ const { rerender } = render(<SubAgentThreadLink callback={callback} />);
+ expect(screen.queryByText('thread.openSubagentThread')).toBeNull();
+
+ threads.list = [{ id: 'thd_1', sourceMessageId: 'msg_tool' }];
+ rerender(<SubAgentThreadLink callback={callback} />);
+ expect(screen.getByText('thread.openSubagentThread')).toBeTruthy();
+ });
+
+ it('leaves the thread link out of the header tags', () => {
+ threads.list = [{ id: 'thd_1', sourceMessageId: 'msg_tool' }];
+ render(
+ <SubAgentSenderTags callback={{ name: 'Poet', status: 'completed', threadId: 'thd_1' }} />,
+ );
+
+ expect(screen.queryByText('thread.openSubagentThread')).toBeNull();
+ });
+});
diff --git a/src/features/Conversation/Messages/User/SubAgentSender.tsx b/src/features/Conversation/Messages/User/SubAgentSender.tsx
new file mode 100644
index 00000000000..06d87ca83fe
--- /dev/null
+++ b/src/features/Conversation/Messages/User/SubAgentSender.tsx
@@ -0,0 +1,83 @@
+'use client';
+
+import type { MessageSubAgentCallback } from '@lobechat/types';
+import { Button, Flexbox, Tag } from '@lobehub/ui';
+import { ListTree } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';
+
+/**
+ * Who a background sub-agent's report reads as: the answering agent's avatar
+ * (the parent itself for an anonymous `callSubAgent` clone) under the call's
+ * name, falling back to the agent's own title.
+ */
+export const useSubAgentSenderIdentity = (
+ callback: MessageSubAgentCallback | undefined,
+): { avatar?: string; title: string } | undefined => {
+ const agentId = callback?.agentId;
+ // Primitive selections: the meta selector builds a new object per call.
+ const avatar = useAgentStore((s) =>
+ agentId ? agentSelectors.getAgentMetaById(agentId)(s).avatar : undefined,
+ );
+ const agentTitle = useAgentStore((s) =>
+ agentId ? agentSelectors.getAgentMetaById(agentId)(s).title : undefined,
+ );
+
+ if (!callback) return undefined;
+ return { avatar, title: callback.name || agentTitle || '' };
+};
+
+/** Header addons of a sub-agent's report: the sub-agent tag and its outcome. */
+export const SubAgentSenderTags = ({ callback }: { callback: MessageSubAgentCallback }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <>
+ <Tag size={'small'}>{t('subAgentCallback.tag')}</Tag>
+ {callback.status === 'error' && (
+ <Tag color={'error'} size={'small'}>
+ {t('subAgentCallback.failed')}
+ </Tag>
+ )}
+ </>
+ );
+};
+
+/** Under a sub-agent's report: the way into its thread, once the thread is listed. */
+export const SubAgentThreadLink = ({ callback }: { callback: MessageSubAgentCallback }) => {
+ const { t } = useTranslation('chat');
+
+ const thread = useChatStore((s) =>
+ (threadSelectors.currentTopicThreads(s) ?? []).find(
+ (candidate) => candidate.id === callback.threadId,
+ ),
+ );
+ const openThreadInPortal = useChatStore((s) => s.openThreadInPortal);
+ const closeThreadPortal = useChatStore((s) => s.closeThreadPortal);
+ const isOpenInPortal = useChatStore(
+ (s) => !!thread && portalThreadSelectors.portalThreadId(s) === thread.id,
+ );
+
+ if (!thread) return null;
+
+ return (
+ <Flexbox horizontal justify={'flex-end'}>
+ <Button
+ icon={ListTree}
+ size={'small'}
+ type={'text'}
+ onClick={() =>
+ isOpenInPortal
+ ? closeThreadPortal()
+ : openThreadInPortal(thread.id, thread.sourceMessageId)
+ }
+ >
+ {isOpenInPortal ? t('thread.closeSubagentThread') : t('thread.openSubagentThread')}
+ </Button>
+ </Flexbox>
+ );
+};
diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsx
index 45620cac896..c55be3fd8cc 100644
--- a/src/features/Conversation/Messages/User/index.tsx
+++ b/src/features/Conversation/Messages/User/index.tsx
@@ -29,6 +29,11 @@ import { ScmEventAvatar, ScmEventSenderTitle } from './components/ScmEventSender
import { UserMessageExtra } from './Extra';
import { getAgentSender, getBotSender, resolveSenderIdentity } from './resolveSenderIdentity';
import ScheduledRunFooter from './ScheduledRunFooter';
+import {
+ SubAgentSenderTags,
+ SubAgentThreadLink,
+ useSubAgentSenderIdentity,
+} from './SubAgentSender';
interface UserMessageProps {
disableEditing?: boolean;
@@ -47,6 +52,10 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {
// A wake-up message from the SCM integration is authored by the pull
// request, so GitHub takes the sender slot instead of the card's header.
const scmSource = useMemo(() => getScmEventSource(content), [content]);
+ // A background sub-agent reporting back speaks in a user turn of its own.
+ const subAgentCallback = metadata?.subAgentCallback;
+ const subAgentSender = useSubAgentSenderIdentity(subAgentCallback);
+ const editingDisabled = disableEditing || !!subAgentCallback;
const { t } = useTranslation('chat');
const selfAvatar = useUserAvatar();
@@ -59,8 +68,10 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {
// hidden-avatar behavior. Self identity applies only to the viewer's own
// rows — see resolveSenderIdentity.
// A bot-channel row is authored by someone else even in personal mode, so
- // its sender is always shown. Same for an agent → agent turn.
- const showSender = Boolean(activeWorkspaceId) || !!botSender || !!scmSource || !!agentSender;
+ // its sender is always shown. Same for an agent → agent turn and a
+ // background sub-agent's report.
+ const showSender =
+ Boolean(activeWorkspaceId) || !!botSender || !!scmSource || !!agentSender || !!subAgentSender;
const currentUserId = useUserStore(userProfileSelectors.userId);
const { avatar, title } = resolveSenderIdentity({
currentUserId,
@@ -68,6 +79,7 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {
selfAvatar,
selfTitle,
sender,
+ subAgentSender,
unknownLabel: t('sender.unknownMember'),
});
@@ -92,19 +104,19 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {
return <Tag>{t('dm.visibleTo', { target: targetName })}</Tag>;
}, [targetId, userName, agents, t]);
- const onDoubleClick = useDoubleClickEdit({ disableEditing, error, id, role });
+ const onDoubleClick = useDoubleClickEdit({ disableEditing: editingDisabled, error, id, role });
const setMessageItemActionElementPortialContext = useSetMessageItemActionElementPortialContext();
const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();
const onMouseEnter: MouseEventHandler<HTMLDivElement> = useCallback(
(e) => {
- if (disableEditing) return;
+ if (editingDisabled) return;
setMessageItemActionElementPortialContext(e.currentTarget);
setMessageItemActionTypeContext({ id, index, type: 'user' });
},
[
- disableEditing,
+ editingDisabled,
id,
index,
setMessageItemActionElementPortialContext,
@@ -114,9 +126,8 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {
return (
<ChatItem
- actions={<Actions data={item} disableEditing={disableEditing} id={id} />}
+ actions={<Actions data={item} disableEditing={editingDisabled} id={id} />}
avatar={{ avatar, title }}
- belowMessage={<ScheduledRunFooter id={id} />}
customAvatarRender={scmSource ? () => <ScmEventAvatar /> : undefined}
editing={editing}
headerAddon={scmSource ? <ScmEventSenderTitle source={scmSource} /> : undefined}
@@ -132,13 +143,16 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {
<MessageCommentBadge count={commentCount} messageId={id} topicId={commentTopicId} />
) : undefined
}
+ belowMessage={
+ <>
+ {subAgentCallback && <SubAgentThreadLink callback={subAgentCallback} />}
+ <ScheduledRunFooter id={id} />
+ </>
+ }
titleAddon={
- // The row is `row-reverse` (right-aligned), so `headerAddon` renders on
- // the far side of the author name. The source link belongs on the near
- // side instead: the author name stays next to its own avatar, and the
- // topic it came from reads as a leading qualifier rather than splitting
- // the name from its avatar.
- dmIndicator || agentSender?.topicId ? (
+ subAgentCallback ? (
+ <SubAgentSenderTags callback={subAgentCallback} />
+ ) : dmIndicator || agentSender?.topicId ? (
<>
{dmIndicator}
{agentSender?.topicId && (
diff --git a/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts b/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts
index 1410d3d1e73..e8baf0b0179 100644
--- a/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts
+++ b/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts
@@ -12,6 +12,20 @@ const viewer = {
};
describe('resolveSenderIdentity', () => {
+ // A background sub-agent's report is a user turn spoken by that agent.
+ it('speaks as an agent sender ahead of every other identity', () => {
+ expect(
+ resolveSenderIdentity({
+ ...viewer,
+ message: {
+ metadata: { botSender: { fullName: 'Bot user', id: 'u1', platform: 'discord' } },
+ },
+ sender: { avatar: null, fullName: 'Viewer', id: 'user-viewer', username: null },
+ subAgentSender: { avatar: '🪶', title: '诗人' },
+ }),
+ ).toEqual({ avatar: '🪶', isOwn: false, title: '诗人' });
+ });
+
it('uses the sender profile for another member', () => {
expect(
resolveSenderIdentity({
diff --git a/src/features/Conversation/Messages/User/resolveSenderIdentity.ts b/src/features/Conversation/Messages/User/resolveSenderIdentity.ts
index 7b67df79c3e..ab43d787a6c 100644
--- a/src/features/Conversation/Messages/User/resolveSenderIdentity.ts
+++ b/src/features/Conversation/Messages/User/resolveSenderIdentity.ts
@@ -54,6 +54,12 @@ interface ResolveSenderIdentityOptions {
/** Viewer's display name, applied only to their own messages. */
selfTitle?: string;
sender?: MessageSender | null;
+ /**
+ * A background sub-agent reporting back in a user turn of its own. Resolved
+ * client-side from the live agent, and wins over everything else, since the
+ * row is the parent conversation's.
+ */
+ subAgentSender?: { avatar?: string; title: string } | null;
/** Label for another member whose profile carries no usable name. */
unknownLabel: string;
}
@@ -73,8 +79,17 @@ export const resolveSenderIdentity = ({
selfAvatar,
selfTitle,
sender,
+ subAgentSender,
unknownLabel,
}: ResolveSenderIdentityOptions) => {
+ if (subAgentSender) {
+ return {
+ avatar: subAgentSender.avatar,
+ isOwn: false,
+ title: subAgentSender.title || unknownLabel,
+ };
+ }
+
const agentSender = getAgentSender(message);
const botSender = getBotSender(message);
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
index 203c05fcf1e..5c46b2661e6 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
@@ -162,7 +162,12 @@ function createFakeMux(): GatewayMuxClient & Emitter {
const GATEWAY_URL = 'https://gateway.test.com';
function createTestAction(overrides: Record<string, any> = {}) {
- const state: Record<string, any> = { gatewayConnections: {}, gatewayFeed: {} };
+ const state: Record<string, any> = {
+ gatewayConnections: {},
+ gatewayFeed: {},
+ operations: {},
+ operationsByContext: {},
+ };
const set = vi.fn((updater: any) => {
if (typeof updater === 'function') Object.assign(state, updater(state));
else Object.assign(state, updater);
@@ -343,7 +348,9 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {
});
it('records mux lifecycle notices in gatewayFeed, attaching once per mux', () => {
- const { action, mux, state } = createTestAction();
+ const { action, mux, state } = createTestAction({
+ refreshTopic: vi.fn().mockResolvedValue(undefined),
+ });
action.connectToGateway({
gatewayUrl: GATEWAY_URL,
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts
new file mode 100644
index 00000000000..228b50fe440
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts
@@ -0,0 +1,362 @@
+import type { GatewayMuxClient, OperationClient } from '@lobechat/agent-gateway-client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ConstVersion from '@/const/version';
+import { messageService } from '@/services/message';
+import * as serverConfigStore from '@/store/serverConfig';
+
+import { GatewayActionImpl } from '../transports/gateway/gateway';
+import { resetGatewayMuxRegistry } from '../transports/gateway/muxRegistry';
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: {
+ execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
+ issueGatewayUserToken: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: {
+ execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
+ issueGatewayUserToken: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: { getMessages: vi.fn().mockResolvedValue([]) },
+}));
+
+vi.mock('@/services/topic', () => ({
+ topicService: {
+ getTopicDetail: vi.fn().mockResolvedValue(null),
+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),
+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),
+}));
+
+/** The two server-side halves the transport requires: capability + rollout. */
+const mockServer = vi.hoisted(() => ({ agentGatewayProtocol: 2 as 1 | 2, enableGatewayMux: true }));
+const mockUserState = vi.hoisted(() => ({
+ profile: { id: 'user-1' },
+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },
+}));
+
+vi.mock('@/store/user', () => ({
+ getUserStoreState: vi.fn(() => mockUserState),
+ useUserStore: { getState: vi.fn(() => mockUserState) },
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ settingsSelectors: { defaultAgentConfig: () => ({ chatConfig: {} }) },
+ toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },
+ userGeneralSettingsSelectors: { telemetry: () => false },
+ userProfileSelectors: { userId: (state: typeof mockUserState) => state.profile.id },
+}));
+
+vi.mock('@/const/version', async (importOriginal) => ({
+ ...(await importOriginal<typeof ConstVersion>()),
+ isDesktop: false,
+}));
+
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: { getDeviceInfo: vi.fn() },
+}));
+
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: () => ({ activeAgentId: undefined, agentMap: {} }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => () => undefined,
+ getAgentById: () => () => undefined,
+ },
+ agentSelectors: {
+ currentAgentWorkingDirectory: () => () => undefined,
+ getAgentConfigById: () => () => undefined,
+ },
+ chatConfigByIdSelectors: {
+ getChatConfigById: () => () => ({}),
+ isChatModeById: () => () => false,
+ isLocalSystemEnabledById: () => () => false,
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: { getState: () => ({ topicDataMap: {}, topicDetailMap: {} }) },
+}));
+
+// ─── Fakes ───
+
+type Emitter = { emit: (event: string, ...args: any[]) => void };
+
+function createListenerBag() {
+ const listeners = new Map<string, Set<(...args: any[]) => void>>();
+ const on = vi.fn((event: string, listener: (...args: any[]) => void) => {
+ let set = listeners.get(event);
+ if (!set) {
+ set = new Set();
+ listeners.set(event, set);
+ }
+ set.add(listener);
+ return () => set!.delete(listener);
+ });
+ const emit = (event: string, ...args: any[]) => {
+ listeners.get(event)?.forEach((listener) => listener(...args));
+ };
+ return { emit, on };
+}
+
+/** v1-shaped client the injected `createClient` seam returns (flag off). */
+function createMockV1Client() {
+ const { emit, on } = createListenerBag();
+ return {
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ emit,
+ on,
+ reconnect: vi.fn(async () => {}),
+ sendToolResult: vi.fn(() => true),
+ updateToken: vi.fn(),
+ };
+}
+
+/** Adapter-shaped client the injected `createMuxClient` seam returns (flag on). */
+function createMockOperationClient(): OperationClient & Emitter {
+ const { emit, on } = createListenerBag();
+ return {
+ connect: vi.fn(),
+ connectionStatus: 'disconnected',
+ disconnect: vi.fn(),
+ emit,
+ lastEventId: '',
+ on: on as OperationClient['on'],
+ reconnect: vi.fn(async () => {}),
+ sendToolResult: vi.fn(() => true),
+ updateToken: vi.fn(),
+ };
+}
+
+function createFakeMux(): GatewayMuxClient & Emitter {
+ const { emit, on } = createListenerBag();
+ return {
+ connect: vi.fn(async () => {}),
+ disconnect: vi.fn(),
+ emit,
+ on,
+ status: 'disconnected',
+ subscribe: vi.fn(),
+ takePendingToolResults: vi.fn(() => []),
+ } as unknown as GatewayMuxClient & Emitter;
+}
+
+const GATEWAY_URL = 'https://gateway.test.com';
+
+function createTestAction(overrides: Record<string, any> = {}) {
+ const state: Record<string, any> = {
+ gatewayConnections: {},
+ gatewayFeed: {},
+ operations: {},
+ operationsByContext: {},
+ };
+ const set = vi.fn((updater: any) => {
+ if (typeof updater === 'function') Object.assign(state, updater(state));
+ else Object.assign(state, updater);
+ });
+ const get = vi.fn(() => ({ ...state, ...overrides })) as any;
+ const action = new GatewayActionImpl(set as any, get, undefined);
+
+ const v1Client = createMockV1Client();
+ action.createClient = vi.fn(() => v1Client);
+ const muxClient = createMockOperationClient();
+ action.createMuxClient = vi.fn(() => muxClient);
+ const mux = createFakeMux();
+ action.resolveGatewayMux = vi.fn(() => mux);
+
+ return { action, get, mux, muxClient, set, state, v1Client };
+}
+
+describe('GatewayActionImpl (multiplexed gateway transport)', () => {
+ beforeEach(() => {
+ mockServer.agentGatewayProtocol = 2;
+ mockServer.enableGatewayMux = true;
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({
+ featureFlags: { enableGatewayMux: mockServer.enableGatewayMux },
+ serverConfig: {
+ agentGatewayProtocol: mockServer.agentGatewayProtocol,
+ agentGatewayUrl: GATEWAY_URL,
+ enableGatewayMode: true,
+ },
+ }),
+ },
+ };
+ // The conversation read resolves Gateway mode from this store too.
+ vi.spyOn(serverConfigStore, 'getServerConfigStoreState').mockReturnValue({
+ featureFlags: { enableGatewayMux: mockServer.enableGatewayMux },
+ serverConfig: {
+ agentGatewayProtocol: mockServer.agentGatewayProtocol,
+ agentGatewayUrl: GATEWAY_URL,
+ enableGatewayMode: true,
+ },
+ } as unknown as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);
+ vi.mocked(messageService.getMessages).mockClear();
+ });
+
+ afterEach(() => {
+ resetGatewayMuxRegistry();
+ delete (globalThis as any).window;
+ vi.restoreAllMocks();
+ });
+
+ describe('runs this tab did not start', () => {
+ const setup = () => {
+ const refreshTopic = vi.fn().mockResolvedValue(undefined);
+ const refreshMessages = vi.fn().mockResolvedValue(undefined);
+ const refreshThreads = vi.fn().mockResolvedValue(undefined);
+ const test = createTestAction({ refreshMessages, refreshThreads, refreshTopic });
+ // Attach the feed through a live connection, as a real run would.
+ test.action.connectToGateway({
+ gatewayUrl: GATEWAY_URL,
+ operationId: 'own-op',
+ token: 'tok',
+ topicId: 'topic-1',
+ });
+ test.state.gatewayConnections = { 'own-op': { status: 'connected' } };
+ return { ...test, refreshMessages, refreshThreads, refreshTopic };
+ };
+
+ const lifecycle = (operationId: string, status: string, meta?: Record<string, string>) => ({
+ at: Date.now(),
+ meta,
+ operationId,
+ status,
+ type: 'op_lifecycle',
+ });
+
+ // A background sub-agent's result wakes its parent with a run the server
+ // starts on its own; refetching the topic lands its running marker, which
+ // the conversation's reconnect hook attaches to.
+ it('refetches the topic when a top-level run starts elsewhere, once per transition', () => {
+ const { mux, refreshTopic } = setup();
+
+ const wake = lifecycle('wake-op', 'running', { agentId: 'agent-1', topicId: 'topic-1' });
+ mux.emit('lifecycle', wake);
+ mux.emit('lifecycle', { ...wake, at: wake.at + 1 });
+
+ expect(refreshTopic).toHaveBeenCalledTimes(1);
+ expect(refreshTopic).toHaveBeenCalledWith(expect.stringContaining('agent-1'));
+ });
+
+ it('ignores runs this tab is already streaming and runs without a topic', () => {
+ const { mux, refreshTopic } = setup();
+
+ mux.emit('lifecycle', lifecycle('own-op', 'running', { agentId: 'a', topicId: 'topic-1' }));
+ mux.emit('lifecycle', lifecycle('bare-op', 'running', { agentId: 'a' }));
+
+ expect(refreshTopic).not.toHaveBeenCalled();
+ });
+
+ // The result card's thread link and the right panel's sub-agent list read
+ // the topic's thread list, which a live wake would otherwise leave stale.
+ it('refetches the topic threads when a background child starts', () => {
+ const { mux, refreshThreads } = setup();
+
+ mux.emit(
+ 'lifecycle',
+ lifecycle('bg-child', 'running', {
+ agentId: 'a',
+ parentOperationId: 'gone-parent',
+ topicId: 'topic-1',
+ }),
+ );
+
+ expect(refreshThreads).toHaveBeenCalledWith('topic-1');
+ });
+
+ it('does not refetch the topic for a child run starting', () => {
+ const { mux, refreshTopic } = setup();
+
+ mux.emit(
+ 'lifecycle',
+ lifecycle('child-op', 'running', {
+ agentId: 'a',
+ parentOperationId: 'gone-parent',
+ topicId: 'topic-1',
+ }),
+ );
+
+ expect(refreshTopic).not.toHaveBeenCalled();
+ });
+
+ it('refetches messages when a child ends after its parent stopped streaming', () => {
+ const { mux, refreshMessages, refreshThreads } = setup();
+ const meta = { agentId: 'a', parentOperationId: 'gone-parent', topicId: 'topic-1' };
+
+ mux.emit('lifecycle', lifecycle('bg-child', 'running', meta));
+ mux.emit('lifecycle', lifecycle('bg-child', 'completed', meta));
+
+ expect(refreshMessages).toHaveBeenCalledWith({ agentId: 'a', topicId: 'topic-1' });
+ expect(refreshThreads).toHaveBeenLastCalledWith('topic-1');
+ });
+
+ // The parent's stream carries the answer but not the topic's thread list.
+ it('refreshes only the threads for a child whose parent streams here', () => {
+ const { mux, refreshMessages, refreshThreads } = setup();
+
+ mux.emit(
+ 'lifecycle',
+ lifecycle('fg-child', 'completed', {
+ agentId: 'a',
+ parentOperationId: 'own-op',
+ topicId: 'topic-1',
+ }),
+ );
+
+ expect(refreshMessages).not.toHaveBeenCalled();
+ expect(refreshThreads).toHaveBeenCalledWith('topic-1');
+ });
+
+ // A run this tab just started is announced before its connection exists;
+ // following it opened a second resuming stream and left the spinner on.
+ it('does not follow a run while this tab has a turn going on the topic', () => {
+ const { mux, refreshTopic, state } = setup();
+ state.operationsByContext = { main_a_topic_1: ['local-send'] };
+ state.operations = {
+ 'local-send': {
+ context: { agentId: 'a', scope: 'main', threadId: null, topicId: 'topic_1' },
+ id: 'local-send',
+ metadata: {},
+ status: 'running',
+ type: 'sendMessage',
+ },
+ };
+
+ mux.emit('lifecycle', lifecycle('new-op', 'running', { agentId: 'a', topicId: 'topic_1' }));
+ mux.emit('lifecycle', lifecycle('new-op', 'completed', { agentId: 'a', topicId: 'topic_1' }));
+
+ expect(refreshTopic).not.toHaveBeenCalled();
+ });
+
+ // The running notice can beat the topic's running marker, and a short
+ // wake-up can end before anything refetches; its end converges the view.
+ it('refetches messages and the topic when a top-level run ends elsewhere', () => {
+ const { mux, refreshMessages, refreshTopic } = setup();
+ const meta = { agentId: 'a', topicId: 'topic-1' };
+
+ mux.emit('lifecycle', lifecycle('wake-op', 'completed', meta));
+
+ expect(refreshMessages).toHaveBeenCalledWith({ agentId: 'a', topicId: 'topic-1' });
+ expect(refreshTopic).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index f129946e885..918a32eb3d8 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -314,6 +314,7 @@ export class GatewayActionImpl {
// A one-shot relay channel (a single LLM call outside any run) is not a
// run of this user's: nothing in the feed is about it.
if (isLlmRelayChannelId(lifecycle.operationId)) return;
+ const previousStatus = this.#get().gatewayFeed[lifecycle.operationId]?.status;
this.#set(
(state) => ({
gatewayFeed: {
@@ -328,9 +329,74 @@ export class GatewayActionImpl {
false,
'gateway/lifecycle',
);
+ // The hub repeats a status on every stored change; act on transitions only.
+ if (lifecycle.status !== previousStatus) this.#followUnownedRun(lifecycle);
});
};
+ /**
+ * React to a run this tab is not streaming. The hub announces every op the
+ * user owns, and for a run the server started on its own — a background
+ * sub-agent's result waking its parent, a run from another tab — that notice
+ * is the only signal this tab gets.
+ *
+ * - A top-level run starting: refetch its topic so the row carries the run's
+ * `runningOperation` marker; the conversation's `useGatewayReconnect` then
+ * attaches to it exactly as on a page load.
+ * - A child run starting or ending: refetch the topic's threads so it shows
+ * up as a sub-agent (right panel, the result message's thread link); when
+ * its parent is not streaming here (a background sub-agent), refetch the
+ * messages on its end too so its tool card settles.
+ * - A top-level run ending that this tab did not follow: refetch the topic's
+ * messages and row, in case the live attach missed a short run.
+ */
+ #followUnownedRun = (lifecycle: MuxOpLifecycleMessage): void => {
+ const { agentId, groupId, parentOperationId, topicId } = lifecycle.meta ?? {};
+ if (!agentId || !topicId) return;
+
+ const state = this.#get();
+ if (state.gatewayConnections[lifecycle.operationId]) return;
+
+ if (lifecycle.status === 'running' && !parentOperationId) {
+ // A run this tab just started is announced before its own connection is
+ // registered (even before its runtime operation exists — only the send
+ // is in flight); following it would open a second, resuming stream that
+ // leaves the original run's spinner on forever. Such a turn is already
+ // in progress on the topic here — a server-started run (a wake-up after
+ // the parent's turn ended) is not.
+ if (operationSelectors.isInputLoadingByContext({ agentId, topicId })(state)) return;
+
+ state.refreshTopic(topicMapKey({ agentId, groupId })).catch(console.error);
+ return;
+ }
+
+ const ended =
+ lifecycle.status === 'completed' ||
+ lifecycle.status === 'error' ||
+ lifecycle.status === 'interrupted';
+
+ // The running notice can beat the topic's running marker to the database,
+ // and a short wake-up may finish before anything else refetches the topic
+ // — so its end converges the conversation even if the live attach missed.
+ if (!parentOperationId) {
+ // A turn of this tab still finishing settles through its own stream.
+ if (ended && !operationSelectors.isInputLoadingByContext({ agentId, topicId })(state)) {
+ state.refreshMessages({ agentId, topicId }).catch(console.error);
+ state.refreshTopic(topicMapKey({ agentId, groupId })).catch(console.error);
+ }
+ return;
+ }
+
+ // The parent's stream carries the child's result but never the topic's
+ // thread list, so the sub-agent list refreshes either way.
+ if (lifecycle.status === 'running' || ended) {
+ state.refreshThreads(topicId).catch(console.error);
+ }
+ if (ended && !state.gatewayConnections[parentOperationId]) {
+ state.refreshMessages({ agentId, topicId }).catch(console.error);
+ }
+ };
+
/**
* Hand every operation on this mux back to the v1 per-operation socket once
* the mux declares protocol v2 unusable.