π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(agent): stream live sub-agent progress to the parked parent (#17115)
Arvin Xue34acc59907b
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.mdindex cfd6a7ff50d..41bcc27bd0f 100644--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md@@ -1043,3 +1043,52 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, β¦`). The h- **Works**: seed an `agents` row and set `topics.agent_id` (and `messages.agent_id`)before opening the share page. Verify the fetch actually fired via`agent-browser network requests | grep getMessages`, not by waiting on the UI.+### E15. β Next dev does NOT hot-reload `apps/server/**` β you are testing STALE compiled server code++- **Situation**: verifying a working-tree change inside `apps/server/src/**` (an agent-runtime+ service, a tool executor, a router) against a `bun run dev` server that was started before the+ edit. The app behaves normally, the feature simply does nothing.+- **Doesn't work**: assuming HMR covers it because `@/server/*` maps to `apps/server/src/*` in+ `tsconfig.json` (source, no `dist`), so it "should" recompile. It does not, at least for large+ service files. Measured: a `console.error` added at the top of a code path that demonstrably ran+ (child ops were created, the DB rows appeared) printed **zero** lines across four separate runs;+ after a dev-server restart, the same line printed on the first run. The whole feature under test+ had never executed once.+- **Why this is a trap and not a nuisance**: the failure mode is silent and looks exactly like a+ logic bug. You will go hunting in your own diff for a fault that is not there.+- **Works**: after ANY edit under `apps/server/**`, restart the dev server before drawing a+ conclusion. If a run "should" have hit your code and didn't, prove the server is running your+ code FIRST β drop a `console.error` on the path and restart β before debugging the code itself.++### E16. β `source`-ing an unquoted JSON env var silently corrupts it (JWKS\_KEY β gateway auth\_failed)++- **Situation**: writing an env file for the local gateway loop with+ `JWKS_KEY={"keys":[{"kty":"RSA",...}]}` on one line, then `set -a; source that-file`.+- **Doesn't work**: the shell strips every double quote from an unquoted assignment, so the process+ receives `{keys:[{kty:RSA,...}]}` β invalid JSON. `getJwksKey()` (`packages/trpc/src/utils/internalJwt.ts:13-20`)+ throws on `JSON.parse`, `signUserJWT` throws, and the server hands the client an **empty** gateway+ token. The browser sends `{"token":"","type":"auth"}` and the gateway answers `auth_failed`.+- **What makes it genuinely deceptive**: `local-gateway-setup.sh` and `local-gateway-probe.mjs` read+ `JWKS_KEY` out of the file with a **regex**, not by sourcing it β so both are unaffected. The probe+ cheerfully prints `β auth_success` while the real browser path is broken. A green probe is NOT+ evidence the app's own token works.+- **Works**: single-quote the value in the env file (`export JWKS_KEY='{"keys":[...]}'`) and prove the+ round-trip before starting the server:+ ```bash+ (source env-file && node -e 'JSON.parse(process.env.JWKS_KEY); console.log("ok")')+ ```+ To diagnose an `auth_failed`, hook `ws.send` in the page and read the token the client actually+ sends β an empty string means the SERVER failed to sign, not that the gateway rejected a signature.++### E17. The chat input silently refuses to send when the agent's model is retired++- **Situation**: driving a real turn (store `sendMessage` or type+Enter). The call resolves, no error+ is thrown, `activeTopicId` stays `null`, and no `agent_operations` row appears. Nothing in the dev+ server log β the request is never even issued.+- **Cause**: the composer shows a small inline warning ("ε½ε樑εε·²δΈηΊΏγθ―·ιζ©ε Άδ»ζ¨‘εεη»§η»δ½Ώη¨γ")+ and disables send. A model id that was valid a while ago (e.g. `deepseek-chat`) can be retired from+ the model bank while the agent row still points at it.+- **Works**: read the actually-enabled models out of the store before configuring a fixture agent β+ `window.__LOBE_STORES.aiInfra().enabledChatModelList` β `[{id: provider, children: [{id: model}]}]` β+ and pick one from there. Also: a send that "resolves fine but creates no operation" is a UI-gate+ symptom; **screenshot the composer** instead of re-reading your store call.diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 524b4815ac6..c1d1a4c99c1 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -174,6 +174,7 @@ export const buildServerVirtualSubAgentRunner = (started: true,subOperationId: result?.operationId,threadId: result?.threadId ?? '',+ toolMessageId: placeholder.id,};},};diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 0f75a30732f..930914c4064 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -1131,6 +1131,8 @@ export class AgentRuntimeService {type: 'step_complete',});+ await this.publishSubAgentProgress(stepResult.newState, stepIndex);+// Build enhanced step completion log & presentation dataconst { presentation: stepPresentationData, summary: stepSummary } = buildStepPresentation(stepResult,@@ -2035,6 +2037,47 @@ export class AgentRuntimeService {}}+ /**+ * Stream a `callSubAgent` child's running totals to the client, once per step.+ *+ * Addressed to the PARENT's operationId, not the child's: the client opens one+ * WebSocket per operation and never subscribes to the child's channel. The+ * parent's channel is still live because parking at `waiting_for_async_tool`+ * deliberately does not publish a stream-end event (see+ * `AgentRuntimeCoordinator.STREAM_END_STATUSES`).+ *+ * Rides `step_complete` rather than a new event type because `AgentStreamEventType`+ * is a closed union shared with the out-of-repo gateway worker; `phase` is the+ * established discriminator and unknown phases are ignored by older clients.+ *+ * The three stat fields are read from exactly the same state paths that+ * `completeSubAgentBridge` uses for its final backfill, so the live numbers+ * converge on the persisted ones instead of jumping when the run ends.+ *+ * Best-effort: a publish failure must not fail the sub-agent's step.+ */+ private async publishSubAgentProgress(state: AgentState, stepIndex: number): Promise<void> {+ const anchor = state?.metadata?.subAgentProgress as+ { parentOperationId: string; toolMessageId: string } | undefined;+ if (!anchor?.parentOperationId || !anchor.toolMessageId) return;++ try {+ await this.streamManager.publishStreamEvent(anchor.parentOperationId, {+ data: {+ model: state?.modelRuntimeConfig?.model,+ phase: 'subagent_progress',+ toolMessageId: anchor.toolMessageId,+ totalTokens: state?.usage?.llm?.tokens?.total,+ totalToolCalls: state?.usage?.tools?.totalCalls,+ },+ stepIndex,+ type: 'step_complete',+ });+ } catch (error) {+ log('[%s] failed to publish sub-agent progress (non-fatal): %O', state?.operationId, error);+ }+ }+/*** Sub-agent completion bridge for the server `callSubAgent` deferred-tool* path. Runs when a child sub-agent op reaches a terminal state β invokeddiff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex ba65c71fc66..49ee27b9771 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -356,6 +356,19 @@ export interface OperationCreationParams {scope?: string | null;/** Source user message ID used for same-turn Agent Signal procedure suppression. */sourceMessageId?: string;+ /**+ * Live-progress anchor for a `callSubAgent` child, spread onto+ * `state.metadata.subAgentProgress`.+ *+ * The child runs on its own operationId, but the client only ever subscribes+ * to the PARENT's gateway channel β which stays open across the sub-agent run+ * because `waiting_for_async_tool` is excluded from `STREAM_END_STATUSES`.+ * So the child's step loop publishes its running totals onto the parent's+ * channel, addressed at the placeholder tool message by `toolMessageId`.+ * Without this the client sees nothing until `completeSubAgentBridge`+ * backfills `pluginState` at the very end.+ */+ subAgentProgress?: { parentOperationId: string; toolMessageId: string };taskId?: string;threadId?: string | null;topicId?: string | null;diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex d19b3610265..e9c807c04e5 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -3312,15 +3312,16 @@ export class AiAgentService {// gates. manifestMap is intentionally broader for discovery and must not// by itself authorize a tool in chat/custom mode or without function calls.const historicalActivatedToolIds = extractActivatedToolIdsFromMessages(allMessages) ?? [];- const activatableToolIds = toolsEngine && historicalActivatedToolIds.length > 0- ? toolsEngine.generateToolsDetailed({- context: { isExplicitActivation: true },- model,- provider,- skipDefaultTools: true,- toolIds: historicalActivatedToolIds,- }).enabledToolIds- : [];+ const activatableToolIds =+ toolsEngine && historicalActivatedToolIds.length > 0+ ? toolsEngine.generateToolsDetailed({+ context: { isExplicitActivation: true },+ model,+ provider,+ skipDefaultTools: true,+ toolIds: historicalActivatedToolIds,+ }).enabledToolIds+ : [];log('execAgent: prepared evalContext for executor');@@ -3694,6 +3695,10 @@ export class AiAgentService {orchestrationRole: appContext?.orchestrationRole,scope: appContext?.scope,sourceMessageId: userMessageRecord?.id ?? parentMessageId ?? undefined,+ // Live-progress anchor for a callSubAgent child β carries the parked+ // parent's operationId + placeholder tool message so the child's step+ // loop can stream its running totals down the parent's gateway channel.+ subAgentProgress: appContext?.subAgentProgress,taskId: operationTaskId,threadId: appContext?.threadId,topicId,@@ -4207,10 +4212,20 @@ export class AiAgentService {}}+ // Live progress for a `callSubAgent` child: its per-step totals ride down the+ // parked parent's gateway channel (see `appContext.subAgentProgress`). Group+ // members are excluded β their whole stream is already mirrored onto the+ // supervisor's channel via `mirrorToOperationId`.+ const subAgentProgress =+ options.resumeParentOnComplete && parentOperationId && options.orchestrationRole !== 'member'+ ? { parentOperationId, toolMessageId: parentMessageId }+ : undefined;+const appContext: NonNullable<InternalExecAgentParams['appContext']> = {groupId,isSubAgent: options.isSubAgent,orchestrationRole: options.orchestrationRole,+ subAgentProgress,threadId: thread.id,topicId,};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.tsindex 9e06398542c..207a6e7a0d0 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -171,7 +171,7 @@ class LobeAgentExecutionRuntime {return buildError('instruction is required.', 'INVALID_ARGUMENTS');}- const { started, error, threadId, subOperationId } = await ctx.subAgent.run({+ const { started, error, threadId, subOperationId, toolMessageId } = await ctx.subAgent.run({description,instruction,timeout,@@ -192,7 +192,9 @@ class LobeAgentExecutionRuntime {// No tool_result yet β the bridge fills this in when the sub-op completes.content: '',deferred: true,- state: { status: 'pending', subOperationId, threadId },+ // `toolMessageId` rides along so the runtime's pause chunk can tell the+ // client which row to fetch; the client never sees it as tool state.+ state: { status: 'pending', subOperationId, threadId, toolMessageId },success: true,};};diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex 09becd1c84f..26432d80984 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -46,6 +46,14 @@ export interface ServerSubAgentRunResult {subOperationId?: string;/** The isolation thread holding the sub-agent's full message trace. */threadId: string;+ /**+ * The placeholder tool message the child was anchored to. Surfaced back up to+ * the runtime so the `pauseForTools` chunk can carry `toolMessageIds` β that is+ * what makes the client refetch and actually put this row in its store, which+ * in turn is what lets live sub-agent progress patch onto it while the parent+ * is parked.+ */+ toolMessageId?: string;}/**diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.tsindex 18314d6aed4..db67f473be6 100644--- a/packages/agent-gateway-client/src/index.ts+++ b/packages/agent-gateway-client/src/index.ts@@ -11,6 +11,7 @@ export type {StreamChunkData,StreamChunkType,StreamStartData,+ SubAgentProgressData,ToolEndData,ToolExecuteData,ToolResultMessage,diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex a2eaeed73de..b39008f3c6d 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -131,6 +131,28 @@ export interface StepCompleteData {reasonDetail?: string;}+/**+ * `step_complete` carrying `phase: 'subagent_progress'` β a `callSubAgent`+ * child's running totals, emitted once per child step.+ *+ * Published onto the PARENT operation's channel, because the client opens one+ * WebSocket per operation and never subscribes to the child's. Rides+ * `step_complete` rather than a new `AgentStreamEventType` so the out-of-repo+ * gateway worker needs no change, and so older clients (which only act on+ * `phase: 'execution_complete'`) ignore it.+ *+ * Advisory only β the authoritative stats are backfilled onto the tool+ * message's `pluginState` by `completeSubAgentBridge` when the child finishes.+ */+export interface SubAgentProgressData extends StepCompleteData {+ model?: string;+ phase: 'subagent_progress';+ /** The parked parent's placeholder tool message these stats belong to. */+ toolMessageId: string;+ totalTokens?: number;+ totalToolCalls?: number;+}+/*** Producer β consumer: structured-input request the user must answer* directly (no tool execution involved). The producer's tool handler staysdiff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex cd117b473a1..16a5465f784 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -268,6 +268,99 @@ describe('tool executors', () => {expect(stopped.nextContext).toBeUndefined();});+ // A deferred tool (callSubAgent) parks the parent WITHOUT a tool_end, so the+ // pause chunk is the only thing that can tell the client its placeholder row+ // exists. Drop `toolMessageIds` and the row never enters the client store β+ // every later update addressed at it silently no-ops.+ it('advertises a deferred tool placeholder id on the pause chunk', async () => {+ runTool.mockResolvedValue({+ attempts: 1,+ result: {+ content: '',+ deferred: true,+ state: { status: 'pending', threadId: 'thread-9', toolMessageId: 'tool-msg-deferred' },+ success: true,+ },+ });++ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: createToolCall('sub-agent-call', 'lobe-agent'),+ },+ type: 'call_tool',+ };++ const result = await callTool(host)(instruction, createState());++ expect(publishChunk).toHaveBeenCalledWith(+ expect.objectContaining({+ chunkType: 'tools_calling',+ toolMessageIds: { 'sub-agent-call': 'tool-msg-deferred' },+ }),+ );+ // No tool_end for a deferred tool β the completion bridge resolves it later.+ expect(publishEvent).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'tool_end' }));+ expect(result.newState.status).toBe('waiting_for_async_tool');+ expect(result.events).toContainEqual(+ expect.objectContaining({ reason: 'async_tool', type: 'interrupted' }),+ );+ });++ it('omits toolMessageIds when a deferred tool reports no placeholder', async () => {+ runTool.mockResolvedValue({+ attempts: 1,+ result: { content: '', deferred: true, state: { status: 'pending' }, success: true },+ });++ await callTool(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: createToolCall('sub-agent-call', 'lobe-agent'),+ },+ type: 'call_tool',+ },+ createState(),+ );++ expect(publishChunk).toHaveBeenCalledWith(+ expect.not.objectContaining({ toolMessageIds: expect.anything() }),+ );+ });++ it('collects placeholder ids for every deferred tool in a batch', async () => {+ runTool.mockImplementation(async (tool: { id: string }) => ({+ attempts: 1,+ result: {+ content: '',+ deferred: true,+ state: { status: 'pending', toolMessageId: `msg-for-${tool.id}` },+ success: true,+ },+ }));++ await callToolsBatch(host)(+ {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [+ createToolCall('sub-a', 'lobe-agent'),+ createToolCall('sub-b', 'lobe-agent'),+ ],+ },+ type: 'call_tools_batch',+ },+ createState(),+ );++ expect(publishChunk).toHaveBeenCalledWith(+ expect.objectContaining({+ toolMessageIds: { 'sub-a': 'msg-for-sub-a', 'sub-b': 'msg-for-sub-b' },+ }),+ );+ });+it('executes server tools in a mixed batch then parks for client tools', async () => {const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {payload: {diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex a5df21801ad..a1158696c4e 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -175,22 +175,43 @@ const publishError = async (host: AgentRuntimeHost, error: unknown, phase: strin});};+/**+ * A deferred tool's runtime has already created the row its result will be+ * backfilled into (e.g. `callSubAgent`'s pending placeholder) and hands the id+ * back on the execution state. Lift it out so the pause chunk can advertise it.+ */+const deferredToolMessageId = (result: { state?: unknown }): string | undefined => {+ const state = result.state as { toolMessageId?: unknown } | undefined;+ return typeof state?.toolMessageId === 'string' ? state.toolMessageId : undefined;+};+const pauseForTools = async ({host,instruction,reason,state,+ toolMessageIds,toolsCalling,}: {host: AgentRuntimeHost;instruction?: AgentInstruction;reason: string;state: AgentState;+ /**+ * `tool_call_id β tool message id`, for pending tools whose row the server has+ * already created (today: deferred async tools such as `callSubAgent`). Tells+ * the client to pull those rows in β without it the parked parent's placeholder+ * never reaches the store, and anything addressed at it silently no-ops.+ * Same optional field the human-approval pause chunk carries; legacy consumers+ * ignore it.+ */+ toolMessageIds?: Record<string, string>;toolsCalling: ChatToolPayload[];}) => {await host.transports.stream.publishChunk({chunkType: 'tools_calling',stepIndex: host.operation.stepIndex,+ ...(toolMessageIds && Object.keys(toolMessageIds).length > 0 && { toolMessageIds }),toolsCalling,});@@ -358,10 +379,12 @@ export const callTool =}if (execution.result.deferred) {+ const deferredId = deferredToolMessageId(execution.result);return pauseForTools({host,reason: 'async_tool',state,+ toolMessageIds: deferredId ? { [tool.id]: deferredId } : undefined,toolsCalling: [tool],});}@@ -538,6 +561,8 @@ export const callToolsBatch =const toolMessageIds: string[] = [];const toolResults: ToolResultEntry[] = [];const deferredTools: ChatToolPayload[] = [];+ // `tool_call_id β placeholder message id` for the deferred tools in this batch.+ const deferredToolMessageIds: Record<string, string> = {};const toolsToExecute = serverTools.length > 0 ? serverTools : toolsCalling;await Promise.all(@@ -555,6 +580,8 @@ export const callToolsBatch =if (execution.result.deferred) {deferredTools.push(tool);+ const deferredId = deferredToolMessageId(execution.result);+ if (deferredId) deferredToolMessageIds[tool.id] = deferredId;return;}@@ -662,6 +689,7 @@ export const callToolsBatch =host,reason: pauseReason,state: newState,+ toolMessageIds: deferredToolMessageIds,toolsCalling: pendingTools,});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.tsxindex 3ded38320cd..355836221f7 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@@ -45,9 +45,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({/*** Collapsed row for lobe-agent's `callSubAgent`. Mirrors the Claude Code Agent- * tool: leading bot icon + "Call SubAgent" label + the description in a chip.- * Once the run finishes, the persisted state feeds a compact stats tail- * (tool count Β· model Β· tokens).+ * tool: leading bot icon + "Call SubAgent" label + the description in a chip,+ * with a compact stats tail (tool count Β· model Β· tokens) that ticks up live+ * while the sub-agent runs and settles on the persisted totals when it finishes.*/export const CallSubAgentInspector = memo<BuiltinInspectorProps<CallSubAgentParams, CallSubAgentState>@@ -57,6 +57,14 @@ export const CallSubAgentInspector = memo<const description = (args?.description || partialArgs?.description)?.trim();const isShiny = isArgumentsStreaming || isLoading;+ // 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+ // the running sub-agent. Prefer the flat ones so the tail never regresses to a+ // stale live sample once the run is done.+ const hasFinalStats =+ pluginState?.totalTokens !== undefined || pluginState?.totalToolCalls !== undefined;+ const stats = hasFinalStats ? pluginState : pluginState?.progress;+return (<divclassName={cx(inspectorTextStyles.root, styles.root, isShiny && shinyTextStyles.shinyText)}@@ -64,11 +72,11 @@ export const CallSubAgentInspector = memo<<GroupBotIcon className={styles.icon} size={14} /><span className={styles.label}>{t('builtins.lobe-agent.apiName.callSubAgent')}</span>{description && <span className={styles.chip}>{description}</span>}- {!isShiny && pluginState && (+ {stats && (<SubAgentStats- model={pluginState.model}- totalTokens={pluginState.totalTokens}- totalToolCalls={pluginState.totalToolCalls}+ model={stats.model}+ totalTokens={stats.totalTokens}+ totalToolCalls={stats.totalToolCalls}/>)}</div>diff --git a/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx b/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsxindex 3c09ecc5c63..45ffa2c7c1f 100644--- a/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx+++ b/packages/builtin-tool-lobe-agent/src/client/components/SubAgentStats.tsx@@ -26,8 +26,8 @@ const formatTokens = (n: number): string => {/*** Compact one-line sub-agent run stats: tool count Β· model Β· token count.- * Renders nothing when no stat is available (e.g. while the run is still in- * flight, before the tool result state is persisted).+ * Fed live during the run (streamed totals) and by the persisted state after it,+ * so the same row serves both. Renders nothing until the first stat arrives.*/export const SubAgentStats = memo<SubAgentRunStats>(({ model, totalToolCalls, totalTokens }) => {const { t } = useTranslation('plugin');diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.tsindex ea54f26ba94..393ee1bacb8 100644--- a/packages/builtin-tool-lobe-agent/src/types.ts+++ b/packages/builtin-tool-lobe-agent/src/types.ts@@ -78,6 +78,14 @@ export interface SubAgentRunStats {* Inspector row.*/export interface CallSubAgentState extends SubAgentRunStats {+ /**+ * 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+ * for the authoritative flat stats, which are written exactly once β by the+ * completion bridge β when the run finishes.+ */+ progress?: SubAgentRunStats;+ status?: 'pending' | 'completed' | 'error';threadId: string;}diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 052b2b70eca..89d593a16cc 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -108,6 +108,18 @@ export interface ExecAgentAppContext {sessionId?: string;/** Optional assistant message id that anchors the run (e.g. parent for an isolated thread). */sourceMessageId?: string;+ /**+ * Live-progress anchor for a `callSubAgent` child, spread onto+ * `state.metadata.subAgentProgress`.+ *+ * The child runs under its own operationId, but the client only ever subscribes+ * to the PARENT's gateway channel β which stays open across the sub-agent run+ * because `waiting_for_async_tool` is excluded from `STREAM_END_STATUSES`. So+ * the child's step loop publishes its running totals onto the parent's channel,+ * addressed at the placeholder tool message by `toolMessageId`. Without it the+ * client sees no stats until the completion bridge backfills `pluginState`.+ */+ subAgentProgress?: { parentOperationId: string; toolMessageId: string };/*** Suppresses AgentSignal `agent.user.message` re-emission when this run is itself driven by a* background/builtin agent. Required for self-iteration / memory-writer / skill-manager runs todiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.tsindex cb9423930cb..83d999307ec 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts@@ -40,9 +40,11 @@ const createStore = (dbMessagesMap: Record<string, UIChatMessage[]> = {}) =>}) as unknown as ChatStore;// The handler enqueues work on an internal promise chain; flush the microtask-// queue so async event handlers settle before assertions.+// queue so async event handlers settle before assertions. Each `await` inside a+// queued handler costs a tick, so keep this comfortably above the longest chain+// rather than tuned to today's exact hop count.const flush = async () => {- for (let i = 0; i < 5; i += 1) await Promise.resolve();+ for (let i = 0; i < 50; i += 1) await Promise.resolve();};describe('createGatewayEventHandler', () => {@@ -165,6 +167,114 @@ describe('createGatewayEventHandler', () => {expect(store.replaceMessages).not.toHaveBeenCalled();});+ // The placeholder tool row only reaches the store via the `toolMessageIds`+ // refetch queued by the preceding tools_calling chunk. A fast sub-agent emits+ // its progress event while that fetch is still in flight β dispatched inline it+ // would land on a row that doesn't exist yet and no-op away the whole live+ // readout (a single-step child has no later sample to self-heal with).+ it('queues sub-agent progress behind the placeholder refetch it depends on', async () => {+ const order: string[] = [];+ let resolveFetch: (() => void) | undefined;+ vi.spyOn(messageService, 'getMessages').mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveFetch = () => {+ order.push('fetch');+ resolve([] as unknown as UIChatMessage[]);+ };+ }),+ );++ const store = createStore();+ (store.internal_dispatchMessage as ReturnType<typeof vi.fn>).mockImplementation(+ (payload: { type?: string }) => {+ if (payload?.type === 'updatePluginState') order.push('progress');+ },+ );++ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'seed-msg',+ context,+ operationId: 'op-1',+ });++ handler(+ makeEvent('stream_chunk', {+ chunkType: 'tools_calling',+ toolMessageIds: { 'call-1': 'tool-msg-sub' },+ toolsCalling: [{ apiName: 'callSubAgent', id: 'call-1' }],+ }),+ );+ handler(+ makeEvent('step_complete', {+ phase: 'subagent_progress',+ toolMessageId: 'tool-msg-sub',+ totalTokens: 4321,+ totalToolCalls: 3,+ }),+ );++ await flush();+ // The fetch is still pending, so the progress patch must not have run yet.+ expect(order).toEqual([]);++ resolveFetch?.();+ await flush();++ expect(order).toEqual(['fetch', 'progress']);+ });++ it('patches live sub-agent progress onto the placeholder tool message, in memory only', async () => {+ const getMessages = vi+ .spyOn(messageService, 'getMessages')+ .mockResolvedValue([] as unknown as UIChatMessage[]);+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'seed-msg',+ context,+ operationId: 'op-1',+ });++ handler(+ makeEvent('step_complete', {+ model: 'claude-sonnet-5',+ phase: 'subagent_progress',+ toolMessageId: 'tool-msg-sub',+ totalTokens: 4321,+ totalToolCalls: 3,+ }),+ );+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'tool-msg-sub',+ key: 'progress',+ type: 'updatePluginState',+ value: { model: 'claude-sonnet-5', totalTokens: 4321, totalToolCalls: 3 },+ },+ { operationId: 'op-1' },+ );+ // Live progress is advisory β the completion bridge owns the persisted value,+ // so this must never trigger a DB read or write.+ expect(getMessages).not.toHaveBeenCalled();+ expect(store.replaceMessages).not.toHaveBeenCalled();+ });++ it('ignores a sub-agent progress event with no tool message anchor', async () => {+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'seed-msg',+ context,+ operationId: 'op-1',+ });++ handler(makeEvent('step_complete', { phase: 'subagent_progress', totalTokens: 10 }));+ await flush();++ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ });+it('preserves existing result_msg_id when a tools_calling chunk omits result links', async () => {const store = createStore({key: [diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex cb8acb9c1d8..65eb4f78f0e 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -3,6 +3,7 @@ import type {StepCompleteData,StreamChunkData,StreamStartData,+ SubAgentProgressData,ToolEndData,ToolExecuteData,ToolStartData,@@ -571,7 +572,7 @@ export const createGatewayEventHandler = (}case 'stream_chunk': {- enqueue(() => {+ enqueue(async () => {const data = event.data as StreamChunkData | undefined;if (!data) return;@@ -629,12 +630,17 @@ export const createGatewayEventHandler = ();// If the server attached a `toolMessageIds` map, it has persisted- // pending tool messages (human approval path). Fetch the latest- // messages so ApprovalActions can read them by id instead of- // waiting for `agent_runtime_end` (which won't fire while paused- // in `waiting_for_human`).+ // pending tool messages (human approval, deferred async tools).+ // Fetch the latest messages so ApprovalActions can read them by id+ // instead of waiting for `agent_runtime_end` (which won't fire while+ // paused in `waiting_for_human` / `waiting_for_async_tool`).+ //+ // AWAITED so the fetch is actually part of the queued work. Anything+ // enqueued behind this chunk addresses rows that only exist once it+ // lands β a fire-and-forget fetch would let the next event overtake+ // it and dispatch onto a message the store doesn't have yet.if ((data as any).toolMessageIds) {- fetchAndReplaceMessages(get, context).catch(console.error);+ await fetchAndReplaceMessages(get, context).catch(console.error);}}});@@ -783,6 +789,41 @@ export const createGatewayEventHandler = (case 'step_complete': {const data = event.data as StepCompleteData | undefined;+ // A parked `callSubAgent` child reporting its running totals. Patch them+ // onto the placeholder tool message in memory only β the persisted values+ // are written once, by `completeSubAgentBridge`, when the child finishes.+ // Kept under a `progress` key so a DB refetch can never leave a stale live+ // number sitting where the authoritative one belongs.+ //+ // ENQUEUED, not dispatched inline: the placeholder row only enters the+ // store via the `toolMessageIds` refetch that the preceding `tools_calling`+ // chunk queued. A fast child can emit its first progress event while that+ // fetch is still in flight, and `updatePluginState` against a row the store+ // doesn't have is a silent no-op β for a single-step sub-agent that lone+ // sample is the whole live readout, so there is nothing later to self-heal+ // it. Queueing puts this behind the fetch that creates its target.+ if (data?.phase === 'subagent_progress') {+ const progress = event.data as SubAgentProgressData;+ if (progress.toolMessageId) {+ enqueue(() => {+ get().internal_dispatchMessage(+ {+ id: progress.toolMessageId,+ key: 'progress',+ type: 'updatePluginState',+ value: {+ model: progress.model,+ totalTokens: progress.totalTokens,+ totalToolCalls: progress.totalToolCalls,+ },+ },+ dispatchContext,+ );+ });+ }+ break;+ }+// Refresh on execution_complete to ensure final step state is consistentif (data?.phase === 'execution_complete') {enqueue(async () => {