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.

πŸ› fix(heterogeneous-agents): stream subagent Thread + fix parallel-tool orphan (#14024)

Arvin Xuf3fca500e46e
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 029c859c9ba..f54b0112ecd 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -11,6 +11,7 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createGatewayEventHandler } from '../gatewayEventHandler';
import { executeHeterogeneousAgent } from '../heterogeneousAgentExecutor';
// ─── Mocks ───
@@ -97,6 +98,10 @@ function setupIpcCapture() {
}
function createMockStore(overrides: Record<string, any> = {}) {
+ // Hand out a fresh AbortController + monotonically increasing sub-op id
+ // for each subagent run, mirroring `startOperation`'s contract just
+ // enough that the executor can build dispatchers + completion calls.
+ let subOpCounter = 0;
return {
associateMessageWithOperation: vi.fn(),
completeOperation: vi.fn(),
@@ -104,6 +109,13 @@ function createMockStore(overrides: Record<string, any> = {}) {
internal_toggleToolCallingStreaming: vi.fn(),
refreshThreads: vi.fn(async () => {}),
replaceMessages: vi.fn(),
+ startOperation: vi.fn(() => {
+ subOpCounter += 1;
+ return {
+ abortController: new AbortController(),
+ operationId: `sub-op-${subOpCounter}`,
+ };
+ }),
...overrides,
} as any;
}
@@ -1565,6 +1577,190 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(finalizeWrite).toBeDefined();
});
+ it('retains subagent buffers + pinned target when the finalize flush fails', async () => {
+ // Transient DB failures on the finalize-time flush used to silently
+ // wipe the accumulators (buffer clear was outside the try/catch), so
+ // the onComplete fallback had nothing left to retry. With buffers
+ // preserved AND the flush target pinned, the retry writes the
+ // leftover stream text to the ORIGINAL in-thread assistant β€” not to
+ // the terminal message `resultContent` already advanced
+ // `currentAssistantMsgId` onto.
+ const idCounter = { tool: 0, assistant: 0, user: 0 };
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ if (params.role === 'tool') {
+ idCounter.tool++;
+ return { id: `tool-${idCounter.tool}` };
+ }
+ if (params.role === 'user') {
+ idCounter.user++;
+ return { id: `thread-user-${idCounter.user}` };
+ }
+ idCounter.assistant++;
+ return { id: `thread-ast-${idCounter.assistant}` };
+ });
+
+ // Make the FIRST write targeting the in-thread streaming assistant
+ // fail. The `content === 'streamed text'` check pins the rejection
+ // to the finalize-time flush; the onComplete retry uses the same
+ // update shape and must succeed.
+ let failed = false;
+ mockUpdateMessage.mockImplementation(async (_id: string, val: any) => {
+ if (!failed && val.content === 'streamed text') {
+ failed = true;
+ throw new Error('transient DB failure');
+ }
+ });
+
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'x',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentText('msg_sub', 'toolu_task', 'streamed text'),
+ ccSubagentSpawnResult('toolu_task', 'terminal result'),
+ ccResult(),
+ ]);
+
+ // Streamed content landed on the FIRST in-thread assistant
+ // (`thread-ast-1`) across the failure+retry β€” NOT on the terminal
+ // assistant created by the resultContent branch.
+ const streamedWrites = mockUpdateMessage.mock.calls.filter(
+ ([, val]: any) => val.content === 'streamed text',
+ );
+ // At least the retry must have landed after the original failure.
+ expect(streamedWrites.length).toBeGreaterThanOrEqual(2);
+ // Every attempt β€” including the retry β€” must target the streaming
+ // turn's assistant, so the terminal row's content never gets
+ // clobbered by the leftover buffer.
+ for (const [id] of streamedWrites) {
+ expect(id).toBe('thread-ast-1');
+ }
+
+ // Terminal assistant carrying the authoritative `resultContent`
+ // was still created as a fresh row (not overwritten by the retry).
+ const terminalCreate = mockCreateMessage.mock.calls.find(
+ ([p]: any) => p.role === 'assistant' && p.content === 'terminal result',
+ );
+ expect(terminalCreate).toBeDefined();
+ });
+
+ it('creates a terminal in-thread assistant with the main tool_result content', async () => {
+ // CC never emits the subagent's final summary as a
+ // `parent_tool_use_id`-tagged assistant event β€” the summary only
+ // exists on the main side, as the `tool_result.content` of the
+ // Agent spawn. Without an explicit terminal-assistant write, the
+ // Thread ends mid-conversation (last message = a tool), and the
+ // user has no visible result inside the subagent thread.
+ //
+ // This test covers the pure-tools subagent case (no inner text
+ // event) to prove we still get a terminal summary message.
+ const spawnResult = 'Here is what I found: ...';
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'x',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub', 'toolu_task', 'toolu_child', 'Bash', { command: 'ls' }),
+ ccToolResult('toolu_child', 'ls output'),
+ ccSubagentSpawnResult('toolu_task', spawnResult),
+ ccResult(),
+ ]);
+
+ const threadId = mockCreateThread.mock.calls[0][0].id;
+ const terminalCreate = mockCreateMessage.mock.calls.find(
+ ([payload]: any) =>
+ payload.role === 'assistant' &&
+ payload.threadId === threadId &&
+ payload.content === spawnResult,
+ );
+ expect(terminalCreate).toBeDefined();
+
+ // Terminal message should chain off the last tool, not off the
+ // thread's initial assistant, so the transcript flows
+ // user β†’ asst(tools) β†’ tool β†’ asst(result).
+ const toolCreate = mockCreateMessage.mock.calls.find(
+ ([payload]: any) => payload.role === 'tool' && payload.tool_call_id === 'toolu_child',
+ );
+ expect(toolCreate).toBeDefined();
+ // The tool create returns an id; since the mock returns { id } we
+ // just assert the terminal's parentId is NOT the first assistant
+ // (id of which was returned earlier in mockCreateMessage).
+ const firstAssistantCreate = mockCreateMessage.mock.calls.find(
+ ([payload]: any) => payload.role === 'assistant' && payload.threadId === threadId,
+ );
+ expect(terminalCreate![0].parentId).not.toBe(firstAssistantCreate![0].id);
+ });
+
+ it('streams the terminal assistant into the thread messagesMap bucket', async () => {
+ // UI relies on internal_dispatchMessage to see the terminal
+ // message arrive in the thread bucket β€” otherwise the Thread view
+ // only picks it up on re-open / SWR refresh.
+ const spawnResult = 'Final handoff text.';
+ const { store } = await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'x',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub', 'toolu_task', 'toolu_child', 'Bash'),
+ ccSubagentSpawnResult('toolu_task', spawnResult),
+ ccResult(),
+ ]);
+
+ // The thread-scoped sub-op opened by `beginSubagentRun` is the
+ // dispatchCtx.operationId for every Thread bucket dispatch β€” so
+ // we identify it via the `startOperation` call with type
+ // 'subagentThread' and filter dispatches against that id, instead
+ // of inspecting threadId directly (the threadId override at the
+ // dispatch boundary is gone β€” context flows through the standard
+ // operation registry path now).
+ const startOpCalls = (store.startOperation as ReturnType<typeof vi.fn>).mock;
+ const subOpIdx = startOpCalls.calls.findIndex(([p]: any) => p?.type === 'subagentThread');
+ expect(subOpIdx).toBeGreaterThanOrEqual(0);
+ const subOperationId = startOpCalls.results[subOpIdx].value.operationId;
+
+ const dispatches = (store.internal_dispatchMessage as ReturnType<typeof vi.fn>).mock.calls;
+ const terminalDispatch = dispatches.find(
+ ([payload, ctx]: any) =>
+ ctx?.operationId === subOperationId &&
+ payload.type === 'createMessage' &&
+ payload.value.role === 'assistant' &&
+ payload.value.content === spawnResult,
+ );
+ expect(terminalDispatch).toBeDefined();
+ });
+
+ it('does NOT create a terminal assistant when onComplete fires without a spawn tool_result', async () => {
+ // CLI closed before the Agent's tool_result arrived (e.g. crash
+ // mid-run). The fallback finalize in onComplete should only flush
+ // any streamed content β€” NOT synthesize a terminal message out
+ // of thin air, since no authoritative result exists yet.
+ await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'x',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub', 'toolu_task', 'toolu_child', 'Bash'),
+ ccToolResult('toolu_child', 'ls output'),
+ ccResult(),
+ ]);
+
+ const threadId = mockCreateThread.mock.calls[0][0].id;
+ // Thread assistants created in this run: ONLY the seed assistant.
+ // No terminal assistant should have been synthesized.
+ const assistantCreatesInThread = mockCreateMessage.mock.calls.filter(
+ ([payload]: any) => payload.role === 'assistant' && payload.threadId === threadId,
+ );
+ expect(assistantCreatesInThread.length).toBe(1);
+ });
+
it('invokes store.refreshThreads on lazy Thread creation (sidebar auto-refresh)', async () => {
// Without this hook the new subagent Thread is only visible in the
// sidebar after the user navigates topics / refreshes β€” an earlier
@@ -1594,5 +1790,328 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(store.refreshThreads).not.toHaveBeenCalled();
});
+
+ /**
+ * Thread-scoped in-memory streaming. Per-spawn sub-operation is
+ * opened via `startOperation({ type: 'subagentThread',
+ * parentOperationId, context: { ..., threadId, scope: 'thread' } })`,
+ * and every Thread bucket dispatch carries that sub-op's id β€”
+ * `internal_getConversationContext` resolves the Thread context
+ * through the standard operation registry path (no threadId-override
+ * hack at the dispatch boundary). Without these dispatches the
+ * Thread view would stay empty until SWR re-fetches on next open
+ * (`fetchAndReplaceMessages` is main-topic scoped).
+ */
+ it('streams subagent create/update dispatches via a thread-scoped sub-operation', async () => {
+ const { store } = await runWithEvents([
+ ccInit(),
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'inspect',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccSubagentToolUse('msg_sub_1', 'toolu_task', 'toolu_child', 'Bash', { command: 'ls' }),
+ ccToolResult('toolu_child', 'ls output'),
+ ccSubagentText('msg_sub_2', 'toolu_task', 'final summary'),
+ ccSubagentSpawnResult('toolu_task', 'done'),
+ ccResult(),
+ ]);
+
+ const threadId = mockCreateThread.mock.calls[0][0].id;
+ const startOpMock = store.startOperation as ReturnType<typeof vi.fn>;
+
+ // Sub-op opened with `subagentThread` type, parented to the main op,
+ // carrying the Thread's ConversationContext (threadId + thread scope)
+ // so dispatches resolve into the Thread bucket via the standard
+ // `internal_getConversationContext` path.
+ const subOpCallIdx = startOpMock.mock.calls.findIndex(
+ ([p]: any) => p?.type === 'subagentThread',
+ );
+ expect(subOpCallIdx).toBeGreaterThanOrEqual(0);
+ const subOpCallArg = startOpMock.mock.calls[subOpCallIdx][0];
+ expect(subOpCallArg).toMatchObject({
+ type: 'subagentThread',
+ parentOperationId: 'op-1',
+ context: { threadId, scope: 'thread' },
+ });
+ const subOperationId = startOpMock.mock.results[subOpCallIdx].value.operationId;
+
+ const dispatches = (store.internal_dispatchMessage as ReturnType<typeof vi.fn>).mock.calls;
+ const threadDispatches = dispatches.filter(
+ ([, ctx]: any) => ctx?.operationId === subOperationId,
+ );
+
+ // Seed: user + first in-thread assistant + tool message must each
+ // get a createMessage dispatch so the Thread renders the moment
+ // the user opens it.
+ const threadCreates = threadDispatches.filter(
+ ([payload]: any) => payload.type === 'createMessage',
+ );
+ const threadCreateRoles = threadCreates.map(([p]: any) => (p.value as any).role);
+ expect(threadCreateRoles).toContain('user');
+ expect(threadCreateRoles).toContain('assistant');
+ expect(threadCreateRoles).toContain('tool');
+
+ // The tool createMessage carries the inner tool_use's tool_call_id
+ // + apiName so the bubble renders with the right plugin shell.
+ const toolCreate = threadCreates.find(([p]: any) => (p.value as any).role === 'tool');
+ expect((toolCreate![0].value as any).tool_call_id).toBe('toolu_child');
+ expect((toolCreate![0].value as any).plugin?.apiName).toBe('Bash');
+
+ // Streaming: updateMessage dispatches must deliver the assistant's
+ // tools[] (so the tool card animates) and the accumulated text
+ // (so the closing summary streams).
+ const threadUpdates = threadDispatches.filter(
+ ([payload]: any) => payload.type === 'updateMessage',
+ );
+ const anyToolsUpdate = threadUpdates.some(([p]: any) =>
+ Array.isArray((p.value as any).tools),
+ );
+ expect(anyToolsUpdate).toBe(true);
+ const anyTextUpdate = threadUpdates.some(
+ ([p]: any) =>
+ typeof (p.value as any).content === 'string' && (p.value as any).content.length > 0,
+ );
+ expect(anyTextUpdate).toBe(true);
+
+ // Tool result lands on the thread-scoped tool message id (the
+ // DB-generated one captured by the createMessage dispatch above).
+ const toolMsgId = toolCreate![0].id;
+ const toolResultUpdate = threadUpdates.find(
+ ([p]: any) => p.id === toolMsgId && (p.value as any).content === 'ls output',
+ );
+ expect(toolResultUpdate).toBeDefined();
+
+ // Main bucket must NOT receive updates targeting the in-thread tool
+ // message id β€” keep the main bubble clean of subagent bleed.
+ const mainLeaks = dispatches.filter(
+ ([payload, ctx]: any) =>
+ ctx?.operationId !== subOperationId &&
+ payload.type === 'updateMessage' &&
+ payload.id === toolMsgId,
+ );
+ expect(mainLeaks).toHaveLength(0);
+
+ // Sub-op is marked completed once the spawn's tool_result lands +
+ // `finalizeSubagentRun` writes the terminal assistant. Cancel /
+ // cleanup cascade then flow through the existing parent/child
+ // operation linkage instead of any subagent-specific bookkeeping.
+ expect(store.completeOperation).toHaveBeenCalledWith(subOperationId);
+ });
+
+ /**
+ * Regression: parallel main tool_use + subagent inner tool_use rendered
+ * Task/Agent as an orphan in the main bubble.
+ *
+ * The gateway handler is main-agent-only: its `stream_chunk`
+ * case dispatches `updateMessage { tools }` to
+ * `currentAssistantMessageId` (main). Forwarding a subagent-tagged
+ * chunk would overwrite main.tools[] with the subagent's inner tools
+ * in the in-memory store. The main's own Task / Agent tool_call_id
+ * then has no matching entry in main.tools[], and every tool message
+ * under it renders with the "orphan tool call" banner until the next
+ * fetchAndReplaceMessages (or forever, if the last corrupting chunk
+ * lands after the final fetch).
+ *
+ * DB persistence is separate (persistSubagent*Chunk writes to the
+ * thread scope) and already correct β€” this guards only the forwarding
+ * path.
+ */
+ it('does NOT forward subagent-tagged stream_chunks to the gateway handler', async () => {
+ await runWithEvents([
+ ccInit(),
+ // Main emits Task + a parallel Read in the same message.id.
+ ccToolUse('msg_main', 'toolu_task', 'Task', {
+ description: 'inspect',
+ prompt: 'go',
+ subagent_type: 'Explore',
+ }),
+ ccToolUse('msg_main', 'toolu_read', 'Read', { file_path: '/a.ts' }),
+ // Subagent inner tools + closing text.
+ ccSubagentToolUse('msg_sub_1', 'toolu_task', 'toolu_grep', 'Grep'),
+ ccSubagentText('msg_sub_2', 'toolu_task', 'subagent summary'),
+ ccToolResult('toolu_read', 'content'),
+ ccSubagentSpawnResult('toolu_task', 'task done'),
+ ccResult(),
+ ]);
+
+ const handlerSpy = vi.mocked(createGatewayEventHandler).mock.results[0]?.value as ReturnType<
+ typeof vi.fn
+ >;
+ expect(handlerSpy).toBeDefined();
+
+ // Collect every stream_chunk that reached the handler.
+ const forwardedChunks = handlerSpy.mock.calls
+ .map((call) => call[0])
+ .filter((e: any) => e?.type === 'stream_chunk');
+
+ // None of them may carry subagent context β€” those are already
+ // persisted to the in-thread assistant and must not touch main.
+ for (const chunk of forwardedChunks) {
+ expect((chunk as any).data?.subagent).toBeUndefined();
+ }
+
+ // Sanity: main's parallel tool chunk (Task + Read) still reaches the
+ // handler so the in-memory main.tools[] animation still fires.
+ const mainToolsCallingChunks = forwardedChunks.filter(
+ (e: any) => e.data?.chunkType === 'tools_calling',
+ );
+ const seenToolIds = new Set<string>();
+ for (const c of mainToolsCallingChunks) {
+ for (const t of (c as any).data.toolsCalling ?? []) seenToolIds.add(t.id);
+ }
+ expect(seenToolIds).toContain('toolu_task');
+ expect(seenToolIds).toContain('toolu_read');
+ expect(seenToolIds).not.toContain('toolu_grep');
+ });
+ });
+
+ // ────────────────────────────────────────────────────
+ // LOBE-7365: Monitor parentId chain regression
+ // ────────────────────────────────────────────────────
+
+ describe('LOBE-7365 Monitor parentId chain', () => {
+ /**
+ * Monitor pattern: initial tool_use returns immediately ("Monitor started"),
+ * then Monitor's stdout is fed back as synthetic user content that drives
+ * new CC assistant turns. Each step should parent to the previous step's
+ * last tool message to form a single assistantGroup in the UI.
+ */
+ it('basic flow: each step parents to previous step last tool', async () => {
+ const idCounter = { tool: 0, assistant: 0 };
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ if (params.role === 'tool') {
+ idCounter.tool++;
+ return { id: `tool-${idCounter.tool}` };
+ }
+ idCounter.assistant++;
+ return { id: `ast-new-${idCounter.assistant}` };
+ });
+
+ await runWithEvents([
+ ccInit(),
+ // Step 0: Monitor starts a long-running task
+ ccMessageStart('msg_01'),
+ ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', {
+ shell: 'until curl localhost/health; do sleep 5; done',
+ }),
+ ccMessageDelta({ input_tokens: 100, output_tokens: 20 }),
+ ccToolResult('toolu_mon_0', 'Monitor started, task abc'),
+ // Step 1 (new msg id): CC reacts to Monitor stdout with Bash + new Monitor
+ ccMessageStart('msg_02'),
+ ccToolUse('msg_02', 'toolu_bash_1', 'Bash', { command: 'echo ok' }),
+ ccToolUse('msg_02', 'toolu_mon_1', 'Monitor', { shell: 'tail -f log' }),
+ ccMessageDelta({ input_tokens: 150, output_tokens: 30 }),
+ ccToolResult('toolu_bash_1', 'ok'),
+ ccToolResult('toolu_mon_1', 'Monitor started, task def'),
+ // Step 2 (new msg id)
+ ccMessageStart('msg_03'),
+ ccToolUse('msg_03', 'toolu_bash_2', 'Bash', { command: 'date' }),
+ ccMessageDelta({ input_tokens: 200, output_tokens: 40 }),
+ ccToolResult('toolu_bash_2', 'Mon Apr 21'),
+ ccResult(),
+ ]);
+
+ const assistantCreates = mockCreateMessage.mock.calls.filter(
+ ([p]: any) => p.role === 'assistant',
+ );
+ // Two new assistants (step 1 + step 2); step 0 uses ast-initial
+ expect(assistantCreates.length).toBe(2);
+
+ // Step 1 parent = Monitor tool from step 0 (tool-1)
+ expect(assistantCreates[0][0].parentId).toBe('tool-1');
+ // Step 2 parent = LAST tool from step 1 = Monitor_1 (tool-3)
+ expect(assistantCreates[1][0].parentId).toBe('tool-3');
+ });
+
+ /**
+ * Hypothesis 2 from the issue: a toolless step in the middle.
+ * If Monitor's stdout triggers CC to respond with only text (no tool_use),
+ * the next step must still chain through. This test documents current
+ * behavior: toolless step breaks tool β†’ next-tool chain.
+ */
+ it('toolless middle step: chain visibly breaks at text-only step', async () => {
+ const idCounter = { tool: 0, assistant: 0 };
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ if (params.role === 'tool') {
+ idCounter.tool++;
+ return { id: `tool-${idCounter.tool}` };
+ }
+ idCounter.assistant++;
+ return { id: `ast-new-${idCounter.assistant}` };
+ });
+
+ await runWithEvents([
+ ccInit(),
+ // Step 0: Monitor
+ ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', { shell: 'watch -n1 date' }),
+ ccToolResult('toolu_mon_0', 'Monitor started'),
+ // Step 1 (new msg id): TEXT ONLY β€” no tool_use
+ ccText('msg_02', 'Looks like it started. I will wait for output.'),
+ // Step 2 (new msg id): Monitor emits a line, CC reacts with Bash
+ ccToolUse('msg_03', 'toolu_bash_2', 'Bash', { command: 'echo reacting' }),
+ ccToolResult('toolu_bash_2', 'reacting'),
+ ccResult(),
+ ]);
+
+ const assistantCreates = mockCreateMessage.mock.calls.filter(
+ ([p]: any) => p.role === 'assistant',
+ );
+ expect(assistantCreates.length).toBe(2);
+
+ // Step 1 parent = Monitor tool from step 0 β†’ this IS correct (tool-1)
+ expect(assistantCreates[0][0].parentId).toBe('tool-1');
+
+ // Step 2 parent: step 1 had NO tools, so toolState.payloads is empty.
+ // Code falls back to currentAssistantMessageId (= step 1 assistant).
+ // BUG: this breaks the assistantGroup chain because collectAssistantChain
+ // only walks tool β†’ assistant, never assistant β†’ assistant.
+ expect(assistantCreates[1][0].parentId).toBe('ast-new-1');
+ // ^ If this assertion passes, the chain IS broken.
+ });
+
+ /**
+ * Hypothesis: Monitor's tool_result arrives AFTER the next message_start.
+ * In CC's stream, tool_result comes from a `user` event AFTER the assistant
+ * event that issued the tool_use, and BEFORE the next assistant turn.
+ * But what if CC emits the next message_start BEFORE the tool_result lands?
+ * (The adapter routes message_start via openMainMessage, which triggers
+ * stream_start(newStep); stepParentId is computed in persistQueue β€”
+ * this queue serializes with persistToolBatch but NOT with persistToolResult.)
+ */
+ it('delayed tool_result: Monitor tool_result arrives after next message_start', async () => {
+ const idCounter = { tool: 0, assistant: 0 };
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ if (params.role === 'tool') {
+ idCounter.tool++;
+ return { id: `tool-${idCounter.tool}` };
+ }
+ idCounter.assistant++;
+ return { id: `ast-new-${idCounter.assistant}` };
+ });
+
+ await runWithEvents([
+ ccInit(),
+ // Step 0: Monitor
+ ccMessageStart('msg_01'),
+ ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', { shell: '...' }),
+ // Step 1 BEGINS before the Monitor tool_result arrives
+ ccMessageStart('msg_02'),
+ // NOW Monitor's tool_result arrives (interleaved)
+ ccToolResult('toolu_mon_0', 'Monitor started'),
+ ccToolUse('msg_02', 'toolu_bash_1', 'Bash', {}),
+ ccToolResult('toolu_bash_1', 'ok'),
+ ccResult(),
+ ]);
+
+ const assistantCreates = mockCreateMessage.mock.calls.filter(
+ ([p]: any) => p.role === 'assistant',
+ );
+ expect(assistantCreates.length).toBe(1);
+ // Step 1 parent should be the Monitor tool from step 0
+ // result_msg_id is set by persistToolBatch Phase 2 (queued on persistQueue
+ // BEFORE the step_boundary persistQueue.then), so this should work.
+ expect(assistantCreates[0][0].parentId).toBe('tool-1');
+ });
});
});
diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
index 80d60f5f5bf..d1cbab1a279 100644
--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts
@@ -10,6 +10,8 @@ import type {
ChatToolPayload,
ConversationContext,
HeterogeneousProviderConfig,
+ MessageMapScope,
+ UIChatMessage,
} from '@lobechat/types';
import { ThreadStatus, ThreadType } from '@lobechat/types';
import { createNanoId } from '@lobechat/utils';
@@ -136,6 +138,30 @@ interface ToolPersistenceState {
persistedIds: Set<string>;
}
+/**
+ * Thread-scoped in-memory dispatcher for a single subagent run. The
+ * caller binds it to a per-spawn sub-operation whose
+ * `OperationContext.threadId` + `scope: 'thread'` cause
+ * `internal_dispatchMessage` to route every create/update into the
+ * Thread's `messagesMap` bucket through the SAME context-resolution
+ * path the main agent uses β€” no special-cased threadId override on the
+ * dispatch boundary.
+ *
+ * Subagent streaming mirrors the main agent's gateway-handler flow:
+ * DB writes are authoritative (see `persistSubagent*Chunk` +
+ * `persistToolBatch`) and these dispatches feed the UI the same content
+ * as tokens arrive, so the Thread view streams with the same cadence as
+ * the main bubble. `fetchAndReplaceMessages` (main-topic scoped) never
+ * refreshes the thread bucket, so without these dispatches the Thread
+ * would only show stale DB state until the user re-navigates.
+ */
+interface SubagentStoreDispatcher {
+ /** Push a new message into the thread bucket (user / assistant / tool). */
+ create: (msg: UIChatMessage) => void;
+ /** Update a message already in the thread bucket by id. */
+ update: (id: string, value: Partial<UIChatMessage>) => void;
+}
+
/**
* Runs the 3-phase tool persistence flow for ONE assistant message β€”
* either the main-agent assistant or a subagent-thread-scoped assistant.
@@ -176,6 +202,18 @@ const persistToolBatch = async (
* agent scope (tools live under the main topic, threadId stays null).
*/
threadId?: string,
+ /**
+ * Invoked immediately after each fresh tool's `role:'tool'` DB row is
+ * created, with the DB-generated id + the payload. Subagent callers
+ * use this to seed the thread's messagesMap bucket so the UI shows
+ * the tool bubble in sync with the DB row; main-agent callers leave
+ * it undefined (fetchAndReplaceMessages hydrates the main bucket).
+ */
+ onToolCreated?: (args: {
+ assistantMessageId: string;
+ toolMessageId: string;
+ tool: ToolCallPayload;
+ }) => void,
) => {
const freshTools = incoming.filter((t) => !state.persistedIds.has(t.id));
if (freshTools.length === 0) return;
@@ -223,6 +261,7 @@ const persistToolBatch = async (
toolMsgIdByCallId.set(tool.id, result.id);
const entry = state.payloads.find((p) => p.id === tool.id);
if (entry) entry.result_msg_id = result.id;
+ onToolCreated?.({ assistantMessageId, toolMessageId: result.id, tool });
} catch (err) {
console.error('[HeterogeneousAgent] Failed to create tool message:', err);
}
@@ -278,12 +317,37 @@ interface SubagentRunState {
* the next write lands on the end of the chain.
*/
lastChainParentId: string;
+ /**
+ * Assistant message id that a deferred buffer flush is still owed to.
+ * Set when `finalizeSubagentRun` captures the flush target but the DB
+ * write fails; the next retry (typically the `onComplete` fallback)
+ * reads this instead of the live `currentAssistantMsgId` β€” which the
+ * subsequent terminal-message branch may have advanced to the spawn
+ * result row, i.e. the WRONG target for a leftover streamed buffer.
+ */
+ pendingFlushTarget?: string;
/**
* Per-subagent-assistant persistence state (tools[] payloads +
* dedupe). Reset on every turn boundary so each in-thread assistant
* has its own tools[].
*/
state: ToolPersistenceState;
+ /**
+ * Thread-scoped store dispatcher β€” mutates the thread's messagesMap
+ * bucket in sync with the DB writes so the UI streams subagent text /
+ * tools / results token-by-token (same UX as the main bubble). Created
+ * once per spawn alongside the Thread row + the per-spawn sub-op.
+ */
+ stream: SubagentStoreDispatcher;
+ /**
+ * Per-spawn sub-operation id. Created via `startOperation` with
+ * `parentOperationId` = the main run's op + `context.threadId` set, so
+ * `internal_getConversationContext` resolves dispatches to the Thread
+ * bucket without any threadId-override hack at the dispatch boundary.
+ * Cancellation and cleanup cascade automatically via the existing
+ * parent/child operation linkage.
+ */
+ subOperationId: string;
/** The subagent Thread this spawn's messages belong to. */
threadId: string;
}
@@ -328,6 +392,19 @@ const ensureSubagentRun = async (
mainAssistantMessageId: string,
context: ConversationContext,
subagentRuns: Map<string, SubagentRunState>,
+ /**
+ * Starts the per-spawn sub-operation (so `internal_dispatchMessage`
+ * resolves into the Thread bucket via the standard operation context
+ * path) and returns its id + a thread-scoped dispatcher bound to it.
+ * Closed over `get` + parent `operationId` + `context` in the caller
+ * so this helper doesn't need to know about the store / operation
+ * registry. Called exactly once per spawn (on lazy-create) β€”
+ * subsequent turn boundaries reuse `run.stream` + `run.subOperationId`.
+ */
+ beginSubagentRun: (threadId: string) => {
+ stream: SubagentStoreDispatcher;
+ subOperationId: string;
+ },
/**
* Invoked once per Thread creation (the lazy-create path) so the
* caller can invalidate SWR caches / push the new thread into any
@@ -403,6 +480,31 @@ const ensureSubagentRun = async (
return undefined;
}
+ const { stream, subOperationId } = beginSubagentRun(threadId);
+ // Seed the thread bucket with user + first assistant so the UI
+ // renders the Thread body the moment it opens β€” without this the
+ // thread's messagesMap entry stays empty until something triggers a
+ // main-topic fetch that happens to include thread rows, leaving the
+ // first subagent turn invisible.
+ stream.create({
+ agentId: context.agentId,
+ content: spawnMetadata?.prompt ?? '',
+ id: userMsgId,
+ parentId: mainAssistantMessageId,
+ role: 'user',
+ threadId,
+ topicId: context.topicId,
+ } as UIChatMessage);
+ stream.create({
+ agentId: context.agentId,
+ content: '',
+ id: firstAssistantId,
+ parentId: userMsgId,
+ role: 'assistant',
+ threadId,
+ topicId: context.topicId,
+ } as UIChatMessage);
+
run = {
accumulatedContent: '',
accumulatedReasoning: '',
@@ -411,6 +513,8 @@ const ensureSubagentRun = async (
lastBatchToolMsgIds: [],
lastChainParentId: firstAssistantId,
state: { payloads: [], persistedIds: new Set() },
+ stream,
+ subOperationId,
threadId,
};
subagentRuns.set(subagentCtx.parentToolCallId, run);
@@ -436,6 +540,7 @@ const ensureSubagentRun = async (
agentId: context.agentId,
topicId: context.topicId,
});
+ run.stream.update(run.currentAssistantMsgId, update);
} catch (err) {
console.error('[HeterogeneousAgent] Failed to flush subagent turn content:', err);
}
@@ -449,6 +554,15 @@ const ensureSubagentRun = async (
threadId: run.threadId,
topicId: context.topicId,
});
+ run.stream.create({
+ agentId: context.agentId,
+ content: '',
+ id: nextAssistant.id,
+ parentId: run.lastChainParentId,
+ role: 'assistant',
+ threadId: run.threadId,
+ topicId: context.topicId,
+ } as UIChatMessage);
run.currentAssistantMsgId = nextAssistant.id;
run.currentSubagentMessageId = subagentCtx.subagentMessageId;
run.lastChainParentId = nextAssistant.id;
@@ -478,6 +592,10 @@ const persistSubagentToolChunk = async (
context: ConversationContext,
subagentRuns: Map<string, SubagentRunState>,
toolMsgIdByCallId: Map<string, string>,
+ beginSubagentRun: (threadId: string) => {
+ stream: SubagentStoreDispatcher;
+ subOperationId: string;
+ },
onThreadCreated?: (threadId: string) => void,
) => {
const run = await ensureSubagentRun(
@@ -485,6 +603,7 @@ const persistSubagentToolChunk = async (
mainAssistantMessageId,
context,
subagentRuns,
+ beginSubagentRun,
onThreadCreated,
);
if (!run) return;
@@ -501,8 +620,39 @@ const persistSubagentToolChunk = async (
{ content: run.accumulatedContent, reasoning: run.accumulatedReasoning },
toolMsgIdByCallId,
run.threadId,
+ ({ assistantMessageId, toolMessageId, tool }) => {
+ // Seed the tool row in the thread bucket right after its DB row
+ // exists, so the tool bubble renders while the result is still
+ // streaming in (matches the main-agent UX where tools[] +
+ // eventual fetchAndReplace bring the row in).
+ run.stream.create({
+ agentId: context.agentId,
+ content: '',
+ id: toolMessageId,
+ parentId: assistantMessageId,
+ plugin: {
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ identifier: tool.identifier,
+ type: tool.type as ChatToolPayload['type'],
+ },
+ role: 'tool',
+ threadId: run.threadId,
+ tool_call_id: tool.id,
+ topicId: context.topicId,
+ } as UIChatMessage);
+ },
);
+ // Surface the latest tools[] (with backfilled `result_msg_id`) and any
+ // accumulated text / reasoning on the in-thread assistant so the
+ // subagent bubble streams in step with the DB writes.
+ const assistantUpdate: Partial<UIChatMessage> = { tools: [...run.state.payloads] };
+ if (run.accumulatedContent) (assistantUpdate as any).content = run.accumulatedContent;
+ if (run.accumulatedReasoning)
+ (assistantUpdate as any).reasoning = { content: run.accumulatedReasoning };
+ run.stream.update(run.currentAssistantMsgId, assistantUpdate);
+
// Update chain parent to the last tool message THIS batch created so
// the NEXT turn's assistant chains off a tool (same shape as main).
const newIds = [...toolMsgIdByCallId.entries()]
@@ -530,6 +680,10 @@ const persistSubagentTextChunk = async (
mainAssistantMessageId: string,
context: ConversationContext,
subagentRuns: Map<string, SubagentRunState>,
+ beginSubagentRun: (threadId: string) => {
+ stream: SubagentStoreDispatcher;
+ subOperationId: string;
+ },
onThreadCreated?: (threadId: string) => void,
) => {
const run = await ensureSubagentRun(
@@ -537,42 +691,132 @@ const persistSubagentTextChunk = async (
mainAssistantMessageId,
context,
subagentRuns,
+ beginSubagentRun,
onThreadCreated,
);
if (!run) return;
- if (kind === 'text') run.accumulatedContent += chunk;
- else run.accumulatedReasoning += chunk;
+ if (kind === 'text') {
+ run.accumulatedContent += chunk;
+ run.stream.update(run.currentAssistantMsgId, { content: run.accumulatedContent });
+ } else {
+ run.accumulatedReasoning += chunk;
+ run.stream.update(run.currentAssistantMsgId, {
+ reasoning: { content: run.accumulatedReasoning },
+ } as Partial<UIChatMessage>);
+ }
};
/**
- * Flush any pending content/reasoning on the in-thread assistant for a
- * completed subagent run. Called when the main-agent receives the
- * `tool_result` for the subagent's spawn tool_use (the run's
- * `parentToolCallId`) β€” at that point the subagent is done and its
- * last turn's summary text needs to land in DB before the UI refreshes.
+ * Finalize a completed subagent run when the main-agent receives the
+ * `tool_result` for its spawn tool_use.
+ *
+ * Two-step persistence:
*
- * Pure DB write; does not mutate `subagentRuns` (we don't delete the
- * entry so late/out-of-order chunks still have a target if they arrive).
+ * 1. **Flush** any streamed text/reasoning on the current in-thread
+ * assistant. CC itself never emits the subagent's final summary as
+ * a `parent_tool_use_id`-tagged assistant event (the summary only
+ * reaches us via the main-side `tool_result.content`), so this
+ * branch is usually a no-op for CC. Other adapters that stream
+ * subagent text will see their accumulated content landed here.
+ *
+ * 2. **Create** a terminal `role:'assistant'` message carrying the
+ * authoritative `resultContent` (what the subagent actually handed
+ * back to the main agent). The thread's shape becomes
+ * `user β†’ asst(tools) β†’ tool β†’ … β†’ asst(tools) β†’ tool β†’ asst(result)`,
+ * so opening the Thread view always ends with the subagent's final
+ * answer β€” matching the main tool_result 1:1 and exposing the
+ * summary in the thread transcript instead of hiding it inside the
+ * main tool bubble.
+ *
+ * `resultContent` is optional: the main tool_result path passes it, but
+ * the `onComplete` fallback (called when the CLI closed without emitting
+ * the spawn's tool_result) leaves it undefined so only the flush step
+ * runs. Accumulators are cleared after flush so a repeat call (e.g.
+ * onComplete re-running after the tool_result already finalized the
+ * run) doesn't re-flush the same content.
*/
-const finalizeSubagentRun = async (
- parentToolCallId: string,
- context: ConversationContext,
- subagentRuns: Map<string, SubagentRunState>,
-) => {
+const finalizeSubagentRun = async ({
+ parentToolCallId,
+ context,
+ subagentRuns,
+ resultContent,
+ completeSubOp,
+}: {
+ /**
+ * Marks the run's sub-operation as completed once the terminal
+ * persistence steps land. Closed over `get().completeOperation` in
+ * the caller so this helper stays free of store coupling. Idempotent
+ * β€” `completeOperation` no-ops on already-completed ops.
+ */
+ completeSubOp: (subOperationId: string) => void;
+ context: ConversationContext;
+ parentToolCallId: string;
+ resultContent?: string;
+ subagentRuns: Map<string, SubagentRunState>;
+}) => {
const run = subagentRuns.get(parentToolCallId);
if (!run) return;
- if (!run.accumulatedContent && !run.accumulatedReasoning) return;
- const update: Record<string, any> = {};
- if (run.accumulatedContent) update.content = run.accumulatedContent;
- if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };
- try {
- await messageService.updateMessage(run.currentAssistantMsgId, update, {
- agentId: context.agentId,
- topicId: context.topicId,
- });
- } catch (err) {
- console.error('[HeterogeneousAgent] Failed to finalize subagent run:', err);
+
+ if (run.accumulatedContent || run.accumulatedReasoning) {
+ // Pin the flush target BEFORE the DB attempt β€” the subsequent
+ // `resultContent` branch advances `currentAssistantMsgId` to the
+ // terminal message, so a retry (onComplete fallback) that read
+ // `currentAssistantMsgId` after the fact would overwrite the
+ // authoritative terminal content with leftover streamed buffer.
+ // `pendingFlushTarget` carries the correct target forward across
+ // retries; clearing it is part of the success path so a fresh
+ // finalize after a successful flush falls back to
+ // `currentAssistantMsgId` for the next turn's content.
+ const flushTarget = run.pendingFlushTarget ?? run.currentAssistantMsgId;
+ const update: Record<string, any> = {};
+ if (run.accumulatedContent) update.content = run.accumulatedContent;
+ if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };
+ try {
+ await messageService.updateMessage(flushTarget, update, {
+ agentId: context.agentId,
+ topicId: context.topicId,
+ });
+ run.stream.update(flushTarget, update);
+ // Only drain the in-memory buffers after DB confirms the flush β€”
+ // otherwise a transient updateMessage failure would swallow the
+ // streamed text/reasoning, and the `onComplete` fallback couldn't
+ // retry because the accumulators are already empty.
+ run.accumulatedContent = '';
+ run.accumulatedReasoning = '';
+ run.pendingFlushTarget = undefined;
+ } catch (err) {
+ run.pendingFlushTarget = flushTarget;
+ console.error('[HeterogeneousAgent] Failed to flush subagent streaming content:', err);
+ }
}
+
+ if (resultContent) {
+ try {
+ const terminal = await messageService.createMessage({
+ agentId: context.agentId,
+ content: resultContent,
+ parentId: run.lastChainParentId,
+ role: 'assistant',
+ threadId: run.threadId,
+ topicId: context.topicId ?? undefined,
+ });
+ run.stream.create({
+ agentId: context.agentId,
+ content: resultContent,
+ id: terminal.id,
+ parentId: run.lastChainParentId,
+ role: 'assistant',
+ threadId: run.threadId,
+ topicId: context.topicId,
+ } as UIChatMessage);
+ run.currentAssistantMsgId = terminal.id;
+ run.lastChainParentId = terminal.id;
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to create subagent terminal assistant:', err);
+ }
+ }
+
+ completeSubOp(run.subOperationId);
};
/**
@@ -729,6 +973,66 @@ export const executeHeterogeneousAgent = async (
if (typeof refresh === 'function') refresh().catch(console.error);
};
+ /**
+ * Open the per-spawn sub-operation that carries the subagent Thread's
+ * `ConversationContext` (threadId + scope='thread'), then build a
+ * dispatcher bound to that sub-op's id. This routes every create /
+ * update through the standard `internal_getConversationContext` ->
+ * `messageMapKey` resolution path the main agent already uses, so no
+ * per-dispatch threadId override is needed at the store boundary.
+ *
+ * Lifecycle: the sub-op is a child of the main `operationId` (so
+ * cancellation cascades + cleanup are free). It's marked completed
+ * inside `finalizeSubagentRun` once the spawn's tool_result arrives
+ * on main, and again as a fallback in `onComplete` for any spawn
+ * whose tool_result never landed (CLI crash, abort).
+ */
+ const beginSubagentRun = (
+ threadId: string,
+ ): { stream: SubagentStoreDispatcher; subOperationId: string } => {
+ const subOp = get().startOperation({
+ context: { ...context, scope: 'thread' as MessageMapScope, threadId },
+ parentOperationId: operationId,
+ type: 'subagentThread',
+ });
+ const dispatchCtx = { operationId: subOp.operationId };
+ return {
+ stream: {
+ create(msg) {
+ get().internal_dispatchMessage(
+ { id: msg.id, type: 'createMessage', value: msg as any },
+ dispatchCtx,
+ );
+ },
+ update(id, value) {
+ get().internal_dispatchMessage(
+ { id, type: 'updateMessage', value: value as any },
+ dispatchCtx,
+ );
+ },
+ },
+ subOperationId: subOp.operationId,
+ };
+ };
+
+ /**
+ * Mark a per-spawn sub-operation completed. Wrapper around
+ * `completeOperation` so module-level helpers (`finalizeSubagentRun`)
+ * stay free of store coupling. Idempotent: `completeOperation` on an
+ * already-completed op is a no-op.
+ */
+ const completeSubagentOp = (subOperationId: string) => {
+ get().completeOperation(subOperationId);
+ };
+
+ /** Look up a subagent run by the tool_call_id of ANY tool inside it. */
+ const findRunByInnerToolCallId = (toolCallId: string): SubagentRunState | undefined => {
+ for (const run of subagentRuns.values()) {
+ if (run.state.persistedIds.has(toolCallId)) return run;
+ }
+ return undefined;
+ };
+
try {
// Start session (pass resumeSessionId for multi-turn --resume)
const result = await heterogeneousAgentService.startSession({
@@ -793,16 +1097,49 @@ export const executeHeterogeneousAgent = async (
pluginState,
),
);
+ // Mirror the tool_result content into the owning subagent
+ // run's thread bucket so the in-thread tool bubble stops
+ // showing "loading" and renders the result the moment it
+ // arrives (main-topic fetchAndReplace does not refresh
+ // thread buckets, so without this the subagent UI would
+ // stay stuck on the spinner until the user re-opens the
+ // Thread). Lookup is deferred into the queue because the
+ // prior `persistSubagentToolChunk` that adds this toolCallId
+ // to the run's `persistedIds` is still pending when the
+ // tool_result event arrives.
+ persistQueue = persistQueue.then(() => {
+ const run = findRunByInnerToolCallId(toolCallId);
+ if (!run) return;
+ const toolMsgId = toolMsgIdByCallId.get(toolCallId);
+ if (!toolMsgId) return;
+ const update: Partial<UIChatMessage> = { content };
+ if (pluginState) (update as any).pluginState = pluginState;
+ if (isError) (update as any).pluginError = { message: content };
+ run.stream.update(toolMsgId, update);
+ });
// If this tool_result IS for a subagent's spawning tool_use
// (tool_result lands on the MAIN side but its toolCallId
// matches a subagent run's parent), the subagent run just
- // ended β€” flush any pending in-thread assistant content so
- // the final summary lands in DB before fetchAndReplace.
- if (subagentRuns.has(toolCallId)) {
- persistQueue = persistQueue.then(() =>
- finalizeSubagentRun(toolCallId, context, subagentRuns),
- );
- }
+ // ended β€” finalize so the terminal assistant with the
+ // authoritative result lands in DB before fetchAndReplace.
+ //
+ // The `subagentRuns.has` check is deferred INTO the queue so
+ // that any subagent tool_use/text chunks from earlier in the
+ // same onRawLine batch β€” which register the run via
+ // `persistSubagent*Chunk` β€” have already drained. Checking
+ // synchronously here races with those writes and silently
+ // misses the run in pure-tools subagents (no preceding text
+ // event to force an earlier registration).
+ persistQueue = persistQueue.then(() => {
+ if (!subagentRuns.has(toolCallId)) return;
+ return finalizeSubagentRun({
+ completeSubOp: completeSubagentOp,
+ context,
+ parentToolCallId: toolCallId,
+ resultContent: content,
+ subagentRuns,
+ });
+ });
// Don't forward β€” the tool_end that follows triggers fetchAndReplaceMessages
// which reads the updated content from DB.
continue;
@@ -949,6 +1286,7 @@ export const executeHeterogeneousAgent = async (
mainAsstId,
context,
subagentRuns,
+ beginSubagentRun,
onSubagentThreadCreated,
),
);
@@ -967,6 +1305,7 @@ export const executeHeterogeneousAgent = async (
mainAsstId,
context,
subagentRuns,
+ beginSubagentRun,
onSubagentThreadCreated,
),
);
@@ -991,6 +1330,7 @@ export const executeHeterogeneousAgent = async (
context,
subagentRuns,
toolMsgIdByCallId,
+ beginSubagentRun,
onSubagentThreadCreated,
),
);
@@ -1021,6 +1361,21 @@ export const executeHeterogeneousAgent = async (
}
}
+ // Subagent-tagged stream_chunks are persisted above via
+ // persistSubagent*Chunk into the in-thread assistant. The gateway
+ // handler is main-agent-only: forwarding would dispatch
+ // `updateMessage { tools }` onto `currentAssistantMessageId` (main),
+ // overwriting main.tools[] with subagent tools β€” main's own
+ // tool_use messages then lose their tools[] pairing and render
+ // as orphans until the next fetchAndReplaceMessages. Text /
+ // reasoning chunks similarly bleed subagent content into the
+ // main bubble. DB state is already correct (the subagent persist
+ // path writes to the thread scope), so dropping the forward
+ // keeps in-memory state aligned with DB.
+ if (event.type === 'stream_chunk' && (event.data as any)?.subagent) {
+ continue;
+ }
+
// Forward to the unified Gateway handler.
// If a step transition is pending, defer through persistQueue so the
// handler receives stream_start (with new assistant ID) FIRST.
@@ -1058,7 +1413,12 @@ export const executeHeterogeneousAgent = async (
// spawn's tool_result after the stream closed). Ensures the
// in-thread assistant has its final text before fetchAndReplace.
for (const parentId of subagentRuns.keys()) {
- await finalizeSubagentRun(parentId, context, subagentRuns).catch(console.error);
+ await finalizeSubagentRun({
+ completeSubOp: completeSubagentOp,
+ context,
+ parentToolCallId: parentId,
+ subagentRuns,
+ }).catch(console.error);
}
// Persist final content + reasoning + model for the last step BEFORE the
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 79e64f63d10..ba2f226e54f 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -19,6 +19,7 @@ export type OperationType =
| 'execAgentRuntime' // Execute agent runtime (client-side, entire agent runtime execution)
| 'execServerAgentRuntime' // Execute server agent runtime (server-side, e.g., Group Chat)
| 'execHeterogeneousAgent'
+ | 'subagentThread' // Per-spawn subagent Thread context (child of execHeterogeneousAgent); carries thread-scoped ConversationContext so dispatches resolve to the Thread's messagesMap bucket. NOT in AI_RUNTIME_OPERATION_TYPES β€” it's a context container, not an independent loading state.
| 'createAssistantMessage' // Create assistant message (sub-operation of execAgentRuntime)
// === LLM execution (sub-operations) ===
| 'callLLM' // Call LLM streaming response (sub-operation of execAgentRuntime)