π€― 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
β»οΈ refactor(hetero-agent): shared subagent-run coordinator + fix device-mode subagent streaming (#15613)
Arvin Xufdb4f37053e6
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 27849a6f051..a3da37bcbea 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -720,6 +720,103 @@ describe('hetero exec command', () => {expect(textSnapshots).toEqual(['first message', 'second message']);});+ it('forwards subagent text raw (no snapshot coalescing, no cross-scope pollution of main text)', async () => {+ // Subagent text is emitted as ONE full block per turn and the server's+ // subagent path *appends* it (no snapshot semantics). It must therefore+ // bypass the main-agent `replace`-snapshot coalescing: folding it into the+ // shared accumulator would (a) splice main text into the subagent message+ // and (b) make the server append a replace-snapshot β duplicated content.+ const ingested: any[] = [];+ mockHeteroIngestMutate.mockImplementation(async ({ events }: any) => {+ for (const e of events) ingested.push(e);+ return { ack: true };+ });++ const subagent = { parentToolCallId: 'task-1', subagentMessageId: 'msg-sub-1' };++ mockSpawnAgent.mockReturnValue(+ createFakeHandle({+ events: [+ // Main-agent streamed text delta (coalesced).+ {+ data: { chunkType: 'text', content: 'hello ' },+ operationId: 'op-server',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_chunk',+ },+ // Subagent full-block text β must pass through untouched.+ {+ data: { chunkType: 'text', content: 'I checked the files.', subagent },+ operationId: 'op-server',+ stepIndex: 0,+ timestamp: 2,+ type: 'stream_chunk',+ },+ {+ data: {+ chunkType: 'tools_calling',+ toolsCalling: [+ {+ apiName: 'Bash',+ arguments: '{"cmd":"ls"}',+ id: 'tc-1',+ identifier: 'bash',+ type: 'default',+ },+ ],+ },+ operationId: 'op-server',+ stepIndex: 1,+ timestamp: 3,+ type: 'stream_chunk',+ },+ {+ data: { reason: 'success' },+ operationId: 'op-server',+ stepIndex: 1,+ timestamp: 4,+ type: 'agent_runtime_end',+ },+ ],+ exitCode: 0,+ }),+ );++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'claude-code',+ '--prompt',+ 'hi',+ '--topic',+ 'topic-1',+ '--operation-id',+ 'op-server',+ '--render',+ 'none',+ ]);++ const textEvents = ingested.filter(+ (e) => e.type === 'stream_chunk' && e.data?.chunkType === 'text',+ );++ // Subagent text forwarded verbatim: keeps its subagent tag, original+ // content, and is NOT converted into a replace snapshot.+ const subagentText = textEvents.find((e) => e.data?.subagent);+ expect(subagentText).toBeDefined();+ expect(subagentText.data.content).toBe('I checked the files.');+ expect(subagentText.data.snapshotMode).toBeUndefined();++ // Main snapshot is untainted by the subagent block.+ const mainText = textEvents.find((e) => !e.data?.subagent);+ expect(mainText).toBeDefined();+ expect(mainText.data.content).toBe('hello ');+ expect(mainText.data.snapshotMode).toBe('replace');+ expect(mainText.data.content).not.toContain('I checked');+ });+it('--raw-dump writes a session folder with meta.json, wires onRawStdout, and tees stderr', async () => {const root = await mkdtemp(path.join(tmpdir(), 'hetero-rawdump-'));diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex 625c86b3132..347d6dd3060 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -224,10 +224,25 @@ class SerialServerIngester {push(event: AgentStreamEvent): void {if (this.fatalError) return;+ // Text-snapshot coalescing is a MAIN-AGENT-ONLY transport optimization:+ // it debounces the main agent's token-level text *deltas* into one+ // `replace` snapshot to cut ingest calls. Subagent text is explicitly+ // excluded (`!event.data?.subagent`) for two reasons:+ // 1. Subagent text is emitted as ONE full block per turn (see+ // claudeCode adapter `handleSubagentAssistant` β "the full block IS+ // the only emission"), so there is nothing to coalesce.+ // 2. `accumulatedText` is a single shared accumulator with no subagent+ // scope. Folding subagent blocks in would (a) splice main-agent text+ // into the subagent message via the shared buffer, and (b) emit a+ // `replace` snapshot that the server's subagent path *appends*+ // (`persistSubagentText` has no snapshot semantics) β duplicated /+ // cross-scope content. Forwarding the raw block straight through lets+ // the server append it exactly once, correctly.if (event.type === 'stream_chunk' &&event.data?.chunkType === 'text' &&- typeof event.data?.content === 'string'+ typeof event.data?.content === 'string' &&+ !event.data?.subagent) {this.accumulatedText += event.data.content;this.pendingTextEvent = event;diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.tsindex 7b3040b9918..c0f439f03b1 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts@@ -1,5 +1,11 @@import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { LOADING_FLAT } from '@lobechat/const';+import type {+ SubagentIntent,+ SubagentReduceCtx,+ SubagentRunsState,+} from '@lobechat/heterogeneous-agents';+import { createSubagentRunsState, reduceSubagentRuns } from '@lobechat/heterogeneous-agents';import {AgentRuntimeErrorType,type ChatMessageError,@@ -116,32 +122,6 @@ interface ToolPersistenceState {persistedIds: Set<string>;}-interface SubagentEventContext {- parentToolCallId: string;- spawnMetadata?: {- description?: string;- prompt?: string;- subagentType?: string;- };- subagentMessageId?: string;-}--/**- * Per-spawn subagent run state. Mirrors `SubagentRunState` in the renderer- * (`src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts`),- * minus UI-only fields (`stream`, `subOperationId`, `pendingFlushTarget`).- */-interface SubagentRunState {- accumulatedContent: string;- accumulatedReasoning: string;- currentAssistantMsgId: string;- currentSubagentMessageId: string;- lastChainParentId: string;- lifetimeToolCallIds: Set<string>;- state: ToolPersistenceState;- threadId: string;-}-/*** Per-operation in-memory state. Lifetime spans the whole CLI run from first* `heteroIngest` batch through `heteroFinish`. Multi-replica caveat: state is@@ -162,7 +142,8 @@ interface OperationState {messageMetadata: Record<string, any>;operationId: string;processedKeys: Set<string>;- subagentRuns: Map<string, SubagentRunState>;+ /** Shared subagent run coordinator state (see `@lobechat/heterogeneous-agents`). */+ subagentState: SubagentRunsState;toolMsgIdByCallId: Map<string, string>;toolState: ToolPersistenceState;topicId: string;@@ -580,7 +561,7 @@ export class HeterogeneousPersistenceHandler {messageMetadata: restoredMetadata,operationId,processedKeys: new Set(),- subagentRuns: new Map(),+ subagentState: createSubagentRunsState(),toolMsgIdByCallId,toolState: { payloads: restoredTools, persistedIds: restoredPersistedIds },topicId,@@ -732,24 +713,13 @@ export class HeterogeneousPersistenceHandler {private async handleTurnMetadata(state: OperationState, event: AgentStreamEvent) {const { model, provider, usage } = event.data ?? {};- const subagentCtx = (event.data as any)?.subagent as SubagentEventContext | undefined;-- if (subagentCtx) {- // Subagent-tagged usage: write it (plus the subagent's own model/provider)- // onto the subagent's in-thread assistant. The chip's totals are derived- // from these per-message `usage` snapshots on read (live aggregation +- // SQL rollup in `threadModel.queryByTopicId`), so nothing is tracked on- // the run. Do NOT touch `state.lastModel` / `state.lastProvider` β those- // carry main-agent step boundary state and would contaminate the next- // main-agent assistant create.- if (!usage) return;- const run = state.subagentRuns.get(subagentCtx.parentToolCallId);- if (!run) return;- await this.deps.messageModel.update(run.currentAssistantMsgId, {- metadata: { usage },- ...(model && { model }),- ...(provider && { provider }),- });++ // Subagent-tagged usage routes through the coordinator (RecordUsage intent β+ // written onto the subagent's in-thread assistant). It must NOT touch+ // `state.lastModel` / `state.lastProvider`, which carry main-agent step+ // boundary state and would contaminate the next main-agent assistant.+ if ((event.data as any)?.subagent) {+ await this.reduceAndApply(state, event);return;}@@ -845,57 +815,51 @@ export class HeterogeneousPersistenceHandler {private async handleStreamChunk(state: OperationState, event: AgentStreamEvent) {const chunk = event.data ?? {};- const subagentCtx = chunk.subagent as SubagentEventContext | undefined;++ // Subagent-scoped chunks (text / reasoning / tools_calling) are routed+ // through the shared run coordinator β it owns thread create, turn+ // boundaries, tool persistence, and finalize.+ if (chunk.subagent) {+ await this.reduceAndApply(state, event);+ return;+ }if (chunk.chunkType === 'text' && typeof chunk.content === 'string') {- if (subagentCtx) {- await this.persistSubagentText(state, subagentCtx, 'text', chunk.content);- } else {- const snapshotMode = chunk.snapshotMode;- const snapshotSeq =- typeof chunk.snapshotSeq === 'number' ? Number(chunk.snapshotSeq) : undefined;-- if (snapshotMode === 'replace' && snapshotSeq !== undefined) {- if (snapshotSeq <= state.lastTextSnapshotSeq) {- log(- 'skip stale text snapshot op=%s seq=%d current=%d',- state.operationId,- snapshotSeq,- state.lastTextSnapshotSeq,- );- return;- }- state.lastTextSnapshotSeq = snapshotSeq;- state.messageMetadata = {- ...state.messageMetadata,- heteroTextSnapshotSeq: snapshotSeq,- };- state.accumulatedContent = chunk.content;- } else {- state.accumulatedContent += chunk.content;+ const snapshotMode = chunk.snapshotMode;+ const snapshotSeq =+ typeof chunk.snapshotSeq === 'number' ? Number(chunk.snapshotSeq) : undefined;++ if (snapshotMode === 'replace' && snapshotSeq !== undefined) {+ if (snapshotSeq <= state.lastTextSnapshotSeq) {+ log(+ 'skip stale text snapshot op=%s seq=%d current=%d',+ state.operationId,+ snapshotSeq,+ state.lastTextSnapshotSeq,+ );+ return;}+ state.lastTextSnapshotSeq = snapshotSeq;+ state.messageMetadata = {+ ...state.messageMetadata,+ heteroTextSnapshotSeq: snapshotSeq,+ };+ state.accumulatedContent = chunk.content;+ } else {+ state.accumulatedContent += chunk.content;}return;}if (chunk.chunkType === 'reasoning' && typeof chunk.reasoning === 'string') {- if (subagentCtx) {- await this.persistSubagentText(state, subagentCtx, 'reasoning', chunk.reasoning);- } else {- state.accumulatedReasoning += chunk.reasoning;- }+ state.accumulatedReasoning += chunk.reasoning;return;}if (chunk.chunkType === 'tools_calling') {const tools = chunk.toolsCalling as ToolCallPayload[] | undefined;if (!tools?.length) return;-- if (subagentCtx) {- await this.persistSubagentToolBatch(state, subagentCtx, tools);- } else {- await this.persistMainToolBatch(state, tools);- }+ await this.persistMainToolBatch(state, tools);}}@@ -922,13 +886,13 @@ export class HeterogeneousPersistenceHandler {log('tool_result for unknown toolCallId=%s op=%s', toolCallId, state.operationId);}- // If this tool_result is for a subagent's spawning tool_use (parent- // toolCallId matches a registered subagent run), the subagent ended β- // finalize so its terminal assistant carries the authoritative result- // before any subsequent step boundary swaps the main assistant.- if (state.subagentRuns.has(toolCallId)) {- await this.finalizeSubagentRun(state, toolCallId, content);- }+ // Route through the coordinator. For a parent-spawn tool_result it+ // finalizes the run (terminal assistant + thread Active); for a subagent+ // inner tool_result the coordinator emits ResolveToolResult, which the+ // server interpreter no-ops because the generic `toolMsgIdByCallId` update+ // above already wrote the DB content. Main-agent tool_results yield no+ // intents.+ await this.reduceAndApply(state, event);}private async handleTerminal(state: OperationState, event: AgentStreamEvent) {@@ -956,11 +920,10 @@ export class HeterogeneousPersistenceHandler {}// Drain any subagent runs that never saw their parent tool_result (CLI- // crashed mid-spawn, or main never closed the spawn). Flush only β no- // terminal assistant since we don't have authoritative resultContent.- for (const parentToolCallId of state.subagentRuns.keys()) {- await this.finalizeSubagentRun(state, parentToolCallId, undefined);- }+ // crashed mid-spawn, or main never closed the spawn). The coordinator+ // flushes each run's trailing content and marks the thread Active β no+ // terminal assistant, since there's no authoritative resultContent.+ await this.reduceAndApply(state, event);// Reset accumulators so a `finish()` flush after a terminal event in the// stream is a no-op (idempotent finalize).@@ -1129,185 +1092,151 @@ export class HeterogeneousPersistenceHandler {// βββ Subagent thread + turn tracking βββββββββββββββββββββββββββββββββββββ- private async ensureSubagentRun(- state: OperationState,- subagentCtx: SubagentEventContext,- ): Promise<SubagentRunState | undefined> {- let run = state.subagentRuns.get(subagentCtx.parentToolCallId);-- // βββ First subagent event for this parent β lazy-create Thread βββ- if (!run) {- const { spawnMetadata } = subagentCtx;- const threadId = generateThreadId();- const title =- spawnMetadata?.description?.slice(0, 80) || spawnMetadata?.subagentType || 'Subagent';-- // Failures here propagate so a retry replays the lazy-create. The- // run isn't registered in `subagentRuns` until all three rows land,- // so a partial-failure retry re-attempts the whole sequence; the- // ThreadModel.create uses `onConflictDoNothing` on id so re-running- // with the same generated id is safe.- await this.deps.threadModel.create({- id: threadId,- metadata: {- sourceToolCallId: subagentCtx.parentToolCallId,- startedAt: new Date().toISOString(),- subagentType: spawnMetadata?.subagentType,- },- sourceMessageId: state.currentAssistantMessageId,- status: ThreadStatus.Processing,- title,- topicId: state.topicId,- type: ThreadType.Isolation,- } as any);+ // βββ Subagent run coordinator (shared reducer) interpreter βββββββββββββββ- const userMsg = await this.deps.messageModel.create({- agentId: state.agentId ?? undefined,- content: spawnMetadata?.prompt ?? '',- parentId: state.currentAssistantMessageId,- role: 'user',- threadId,- topicId: state.topicId,- });+ private subagentReduceCtx(state: OperationState): SubagentReduceCtx {+ return {+ agentId: state.agentId,+ mainAssistantId: state.currentAssistantMessageId,+ // Pre-allocate DB-compatible ids so the reducer can chain parentId+ // without a createβread round-trip. `thd_β¦` matches `generateThreadId`.+ newId: (kind) => (kind === 'thread' ? generateThreadId() : `msg_${createNanoId(18)()}`),+ topicId: state.topicId,+ };+ }- const firstAssistant = await this.deps.messageModel.create({- agentId: state.agentId ?? undefined,- content: '',- parentId: userMsg.id,- role: 'assistant',- threadId,- topicId: state.topicId,- });+ /**+ * Reduce one event through the shared subagent coordinator and apply the+ * resulting intents. Commit-on-success: `state.subagentState` is only+ * advanced after every intent lands, so a throwing intent leaves the event+ * unmarked in `processedKeys` and the CLI BatchIngester replays it against+ * the unchanged state (same resilience the per-event idempotency loop relies+ * on elsewhere).+ */+ private async reduceAndApply(state: OperationState, event: AgentStreamEvent) {+ const { state: next, intents } = reduceSubagentRuns(+ state.subagentState,+ event,+ this.subagentReduceCtx(state),+ );+ for (const intent of intents) await this.applySubagentIntent(state, intent);+ state.subagentState = next;+ }- run = {- accumulatedContent: '',- accumulatedReasoning: '',- currentAssistantMsgId: firstAssistant.id,- currentSubagentMessageId: subagentCtx.subagentMessageId ?? '',- lastChainParentId: firstAssistant.id,- lifetimeToolCallIds: new Set(),- state: { payloads: [], persistedIds: new Set() },- threadId,- };- state.subagentRuns.set(subagentCtx.parentToolCallId, run);- return run;- }+ private async applySubagentIntent(state: OperationState, intent: SubagentIntent) {+ switch (intent.kind) {+ case 'createThread': {+ await this.deps.threadModel.create({+ id: intent.threadId,+ metadata: {+ sourceToolCallId: intent.sourceToolCallId,+ startedAt: new Date().toISOString(),+ subagentType: intent.subagentType,+ },+ sourceMessageId: intent.sourceMessageId,+ status: ThreadStatus.Processing,+ title: intent.title,+ topicId: intent.topicId ?? state.topicId,+ type: ThreadType.Isolation,+ } as any);+ return;+ }- // βββ New subagent turn β flush old content, cut a new assistant βββ- if (- subagentCtx.subagentMessageId &&- subagentCtx.subagentMessageId !== run.currentSubagentMessageId- ) {- if (run.accumulatedContent || run.accumulatedReasoning) {- const update: Record<string, any> = {};- if (run.accumulatedContent) update.content = run.accumulatedContent;- if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };- await this.deps.messageModel.update(run.currentAssistantMsgId, update);+ case 'createMessage': {+ await this.deps.messageModel.create(+ {+ agentId: intent.agentId ?? undefined,+ content: intent.content,+ parentId: intent.parentId,+ role: intent.role,+ threadId: intent.threadId,+ topicId: intent.topicId ?? state.topicId,+ },+ intent.messageId,+ );+ return;}- const nextAssistant = await this.deps.messageModel.create({- agentId: state.agentId ?? undefined,- content: '',- parentId: run.lastChainParentId,- role: 'assistant',- threadId: run.threadId,- topicId: state.topicId,- });- run.currentAssistantMsgId = nextAssistant.id;- run.currentSubagentMessageId = subagentCtx.subagentMessageId;- run.lastChainParentId = nextAssistant.id;- run.state = { payloads: [], persistedIds: new Set() };- run.accumulatedContent = '';- run.accumulatedReasoning = '';- }+ // Live in-memory UI updates have no server surface; durable writes land+ // via persistContent / persistToolBatch.+ case 'streamContent': {+ return;+ }- return run;- }+ // Inner subagent tool_result DB content is already written by the generic+ // `toolMsgIdByCallId` update in handleToolResult; nothing extra server-side.+ case 'resolveToolResult': {+ return;+ }- private async persistSubagentText(- state: OperationState,- subagentCtx: SubagentEventContext,- kind: 'text' | 'reasoning',- chunk: string,- ) {- const run = await this.ensureSubagentRun(state, subagentCtx);- if (!run) return;- if (kind === 'text') run.accumulatedContent += chunk;- else run.accumulatedReasoning += chunk;- }+ case 'persistContent': {+ const update: Record<string, any> = {};+ if (intent.content) update.content = intent.content;+ if (intent.reasoning) update.reasoning = { content: intent.reasoning };+ if (Object.keys(update).length > 0) {+ await this.deps.messageModel.update(intent.messageId, update);+ }+ return;+ }- private async persistSubagentToolBatch(- state: OperationState,- subagentCtx: SubagentEventContext,- tools: ToolCallPayload[],- ) {- const run = await this.ensureSubagentRun(state, subagentCtx);- if (!run) return;-- for (const tool of tools) run.lifetimeToolCallIds.add(tool.id);-- const { newToolMsgIds } = await this.persistToolBatch(- tools,- run.state,- run.currentAssistantMsgId,- state,- { content: run.accumulatedContent, reasoning: run.accumulatedReasoning },- run.threadId,- );+ case 'persistToolBatch': {+ const buildUpdate = (withResult: boolean): Record<string, any> => {+ const update: Record<string, any> = {+ tools: intent.tools.map((t) =>+ withResult ? { ...t.payload, result_msg_id: t.toolMessageId } : { ...t.payload },+ ),+ };+ if (intent.content) update.content = intent.content;+ if (intent.reasoning) update.reasoning = { content: intent.reasoning };+ return update;+ };++ // Phase 1: pre-register assistant.tools[] (no result_msg_id yet).+ await this.deps.messageModel.update(intent.assistantMessageId, buildUpdate(false));++ // Phase 2: create rows for new tools with their pre-allocated ids and+ // register them in the global tool-message map for tool_result lookup.+ for (const t of intent.tools) {+ if (!t.isNew) continue;+ await this.deps.messageModel.create(+ {+ agentId: state.agentId ?? undefined,+ content: '',+ parentId: intent.assistantMessageId,+ plugin: {+ apiName: t.payload.apiName,+ arguments: t.payload.arguments,+ identifier: t.payload.identifier,+ type: t.payload.type,+ },+ role: 'tool',+ threadId: intent.threadId,+ tool_call_id: t.payload.id,+ topicId: state.topicId,+ } as any,+ t.toolMessageId,+ );+ state.toolMsgIdByCallId.set(t.payload.id, t.toolMessageId);+ }- // Chain next turn's assistant off the LAST tool message of this batch β- // mirrors main-agent step-boundary logic.- const lastToolMsgId = newToolMsgIds.at(-1);- if (lastToolMsgId) run.lastChainParentId = lastToolMsgId;- }+ // Phase 3: backfill result_msg_id on assistant.tools[].+ await this.deps.messageModel.update(intent.assistantMessageId, buildUpdate(true));+ return;+ }- /**- * Two-step finalization: flush trailing content on the current in-thread- * assistant, then (when `resultContent` is provided) create a terminal- * assistant carrying the authoritative summary so the thread always ends- * with `... β tool β asst(result)`.- *- * `resultContent` is omitted when the spawn never closed (CLI crash);- * called from `handleTerminal` to drain orphan runs without faking a- * result.- */- private async finalizeSubagentRun(- state: OperationState,- parentToolCallId: string,- resultContent: string | undefined,- ) {- const run = state.subagentRuns.get(parentToolCallId);- if (!run) return;-- if (run.accumulatedContent || run.accumulatedReasoning) {- const update: Record<string, any> = {};- if (run.accumulatedContent) update.content = run.accumulatedContent;- if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };- await this.deps.messageModel.update(run.currentAssistantMsgId, update);- run.accumulatedContent = '';- run.accumulatedReasoning = '';- }+ case 'recordUsage': {+ await this.deps.messageModel.update(intent.messageId, {+ metadata: { usage: intent.usage as any },+ ...(intent.model && { model: intent.model }),+ ...(intent.provider && { provider: intent.provider }),+ });+ return;+ }- if (resultContent) {- const terminal = await this.deps.messageModel.create({- agentId: state.agentId ?? undefined,- content: resultContent,- parentId: run.lastChainParentId,- role: 'assistant',- threadId: run.threadId,- topicId: state.topicId,- });- run.currentAssistantMsgId = terminal.id;- run.lastChainParentId = terminal.id;+ case 'finalizeThread': {+ await this.deps.threadModel.update(intent.threadId, { status: ThreadStatus.Active });+ return;+ }}-- // Mark the thread complete (created as `Processing`). The chip's- // tool-count / token / model metrics are NOT denormalized here β they're- // derived on read from the child messages (`threadModel.queryByTopicId`- // aggregates them in SQL, mirroring the live `aggregateSubagentMetrics`),- // so finalize owns only the status transition. Idempotent.- await this.deps.threadModel.update(run.threadId, { status: ThreadStatus.Active });-- state.subagentRuns.delete(parentToolCallId);}}diff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.tsindex 6cedf93f526..3a50bcd9c69 100644--- a/apps/server/src/services/message/__tests__/index.test.ts+++ b/apps/server/src/services/message/__tests__/index.test.ts@@ -286,7 +286,7 @@ describe('MessageService', () => {const result = await messageService.createMessage(params as any);- expect(mockMessageModel.create).toHaveBeenCalledWith(params);+ expect(mockMessageModel.create).toHaveBeenCalledWith(params, undefined);expect(mockMessageModel.query).toHaveBeenCalledWith({agentId: 'agent-1',@@ -356,7 +356,7 @@ describe('MessageService', () => {const result = await messageService.createMessage(params as any);- expect(mockMessageModel.create).toHaveBeenCalledWith(params);+ expect(mockMessageModel.create).toHaveBeenCalledWith(params, undefined);expect(mockMessageModel.query).toHaveBeenCalledWith({agentId: 'agent-1',diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.tsindex 1c366d0e7b2..afbc81fb876 100644--- a/apps/server/src/services/message/index.ts+++ b/apps/server/src/services/message/index.ts@@ -133,8 +133,11 @@ export class MessageService {* reducing the need for separate refresh calls and improving performance.*/async createMessage(params: CreateMessageParams): Promise<CreateMessageResult> {- // 1. Create the message (using agentId)- const item = await this.messageModel.create(params);+ // 1. Create the message (using agentId). Honor a caller-pre-allocated id+ // when present (passing `undefined` falls back to the model's genId+ // default), so flows that chain parentId across not-yet-created messages+ // (e.g. the subagent run coordinator) can assign ids up front.+ const item = await this.messageModel.create(params, params.id);// 2. Query all messages for this agent/topic// Use agentId field for querydiff --git a/packages/database/src/models/__tests__/messages/message.create.test.ts b/packages/database/src/models/__tests__/messages/message.create.test.tsindex e03a0400137..ae4c2cf147d 100644--- a/packages/database/src/models/__tests__/messages/message.create.test.ts+++ b/packages/database/src/models/__tests__/messages/message.create.test.ts@@ -132,7 +132,7 @@ describe('MessageModel Create Tests', () => {// Assert resultconst result = await serverDB.select().from(messages).where(eq(messages.userId, userId));expect(result[0].id).toBeDefined();- expect(result[0].id).toHaveLength(18);+ expect(result[0].id).toHaveLength(22);});it('should create a tool message and insert into messagePlugins table', async () => {diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.tsindex dc8bb9cdb16..07e176d3f42 100644--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts@@ -158,8 +158,8 @@ describe('MessageModel Statistics Tests', () => {// @ts-ignore - accessing private method for testingconst id2 = model.genId();- expect(id1).toHaveLength(18);- expect(id2).toHaveLength(18);+ expect(id1).toHaveLength(22);+ expect(id2).toHaveLength(22);expect(id1).not.toBe(id2);expect(id1).toMatch(/^msg_/);expect(id2).toMatch(/^msg_/);diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex b6d36ba371f..c2959c9f8d0 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -2708,7 +2708,10 @@ export class MessageModel {// **************** Helper *************** //- private genId = () => idGenerator('messages', 14);+ // 18-char hash (was 14): widen the message id space β the coordinator-driven+ // hetero subagent flow allocates many ids per run, and a few extra chars keep+ // collision odds negligible at that volume.+ private genId = () => idGenerator('messages', 18);private matchSession = (sessionId?: string | null) => {if (sessionId === INBOX_SESSION_ID) return isNull(messages.sessionId);diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex c4fccd2ce34..883d7a69abf 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -12,6 +12,26 @@ export {} from './config';export { HETEROGENEOUS_TYPE_LABELS } from './labels';export { createAdapter, listAgentTypes } from './registry';+export type {+ CreateMessageIntent,+ CreateThreadIntent,+ FinalizeThreadIntent,+ PersistContentIntent,+ PersistToolBatchEntry,+ PersistToolBatchIntent,+ RecordUsageIntent,+ ResolveToolResultIntent,+ StreamContentIntent,+ SubagentIntent,+ SubagentReduceCtx,+ SubagentRunsState,+} from './subagentCoordinator';+export {+ createSubagentRunsState,+ type EventScope,+ getEventScope,+ reduceSubagentRuns,+} from './subagentCoordinator';export type {AgentEventAdapter,AgentProcessConfig,diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/getEventScope.ts b/packages/heterogeneous-agents/src/subagentCoordinator/getEventScope.tsnew file mode 100644index 00000000000..58dec6a89a2--- /dev/null+++ b/packages/heterogeneous-agents/src/subagentCoordinator/getEventScope.ts@@ -0,0 +1,20 @@+import type { SubagentEventContext } from '../types';++/**+ * Classify a stream event's scope. The adapter stamps `data.subagent` (a+ * {@link SubagentEventContext}) on every event originating from a subagent+ * turn; main-agent events leave it undefined.+ *+ * Accepts a structural event (`{ type, data }`) so it works for both the+ * package's `HeterogeneousAgentEvent` and the wire `AgentStreamEvent` without a+ * cross-package type dependency.+ */+export type EventScope = { kind: 'main' } | { ctx: SubagentEventContext; kind: 'subagent' };++export const getEventScope = (event: { data?: any }): EventScope => {+ const ctx = event?.data?.subagent as SubagentEventContext | undefined;+ if (ctx && typeof ctx.parentToolCallId === 'string') {+ return { ctx, kind: 'subagent' };+ }+ return { kind: 'main' };+};diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/index.ts b/packages/heterogeneous-agents/src/subagentCoordinator/index.tsnew file mode 100644index 00000000000..b3a52db574a--- /dev/null+++ b/packages/heterogeneous-agents/src/subagentCoordinator/index.ts@@ -0,0 +1,19 @@+export { type EventScope, getEventScope } from './getEventScope';+export { reduce as reduceSubagentRuns } from './reducer';+export type {+ CreateMessageIntent,+ CreateThreadIntent,+ FinalizeThreadIntent,+ PersistContentIntent,+ PersistToolBatchEntry,+ PersistToolBatchIntent,+ RecordUsageIntent,+ ResolveToolResultIntent,+ StreamContentIntent,+ SubagentIntent,+ SubagentReduceCtx,+ SubagentRun,+ SubagentRunsState,+ SubagentTurnToolState,+} from './types';+export { createSubagentRunsState } from './types';diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.tsnew file mode 100644index 00000000000..aaa7296517f--- /dev/null+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts@@ -0,0 +1,316 @@+import { describe, expect, it } from 'vitest';++import { createSubagentRunsState, reduceSubagentRuns } from './index';+import type { SubagentIntent, SubagentReduceCtx } from './types';++/** Deterministic id factory: `thd_1`, `msg_1`, `msg_2`, β¦ per kind. */+const makeCtx = (over: Partial<SubagentReduceCtx> = {}): SubagentReduceCtx => {+ const counters = { message: 0, thread: 0 };+ return {+ agentId: 'agent-1',+ mainAssistantId: 'main-asst-1',+ newId: (kind) => {+ counters[kind] += 1;+ return `${kind === 'thread' ? 'thd' : 'msg'}_${counters[kind]}`;+ },+ topicId: 'topic-1',+ ...over,+ };+};++const sub = (parentToolCallId: string, subagentMessageId?: string, spawnMetadata?: any) => ({+ parentToolCallId,+ ...(subagentMessageId ? { subagentMessageId } : {}),+ ...(spawnMetadata ? { spawnMetadata } : {}),+});++const textEvent = (+ parentToolCallId: string,+ subagentMessageId: string,+ content: string,+ spawnMetadata?: any,+) => ({+ data: {+ chunkType: 'text',+ content,+ subagent: sub(parentToolCallId, subagentMessageId, spawnMetadata),+ },+ type: 'stream_chunk',+});++const toolsEvent = (parentToolCallId: string, subagentMessageId: string, tools: any[]) => ({+ data: {+ chunkType: 'tools_calling',+ subagent: sub(parentToolCallId, subagentMessageId),+ toolsCalling: tools,+ },+ type: 'stream_chunk',+});++const tool = (id: string) => ({+ apiName: 'Bash',+ arguments: '{}',+ id,+ identifier: 'bash',+ type: 'default',+});++const kinds = (intents: SubagentIntent[]) => intents.map((i) => i.kind);++/** Apply a sequence of events with commit-on-success and return the final state + per-step intents. */+const run = (events: { data?: any; type?: string }[], ctx = makeCtx()) => {+ let state = createSubagentRunsState();+ const steps: SubagentIntent[][] = [];+ for (const e of events) {+ const r = reduceSubagentRuns(state, e, ctx);+ steps.push(r.intents);+ state = r.state; // commit+ }+ return { state, steps };+};++describe('subagent reducer', () => {+ it('lazy-creates thread + user seed + first assistant on the first subagent chunk', () => {+ const { steps, state } = run([+ textEvent('task-1', 'm1', 'Investigating', {+ description: 'Find bug',+ prompt: 'go find',+ subagentType: 'explorer',+ }),+ ]);++ expect(kinds(steps[0])).toEqual([+ 'createThread',+ 'createMessage',+ 'createMessage',+ 'streamContent',+ ]);+ const [createThread, userMsg, asstMsg, stream] = steps[0] as any[];++ expect(createThread).toMatchObject({+ sourceMessageId: 'main-asst-1',+ sourceToolCallId: 'task-1',+ subagentType: 'explorer',+ threadId: 'thd_1',+ title: 'Find bug',+ topicId: 'topic-1',+ });+ expect(userMsg).toMatchObject({+ content: 'go find',+ parentId: 'main-asst-1',+ role: 'user',+ messageId: 'msg_1',+ });+ expect(asstMsg).toMatchObject({+ content: '',+ parentId: 'msg_1',+ role: 'assistant',+ messageId: 'msg_2',+ });+ // text accumulates onto the first assistant (live, replace)+ expect(stream).toMatchObject({+ content: 'Investigating',+ messageId: 'msg_2',+ threadId: 'thd_1',+ });++ expect(state.runs.get('task-1')).toMatchObject({+ accContent: 'Investigating',+ currentAssistantId: 'msg_2',+ currentSubagentMessageId: 'm1',+ lastChainParentId: 'msg_2',+ threadId: 'thd_1',+ });+ });++ it('falls back to subagentType then "Subagent" for the thread title', () => {+ const a = run([textEvent('t', 'm', 'x', { subagentType: 'explorer' })]);+ expect((a.steps[0][0] as any).title).toBe('explorer');+ const b = run([textEvent('t', 'm', 'x')]);+ expect((b.steps[0][0] as any).title).toBe('Subagent');+ });++ it('accumulates text as replace snapshots across chunks within a turn', () => {+ const { steps } = run([+ textEvent('task-1', 'm1', 'Hello '),+ textEvent('task-1', 'm1', 'world'),+ ]);+ // 2nd chunk: no new thread/message, just a streamContent carrying the full accumulation+ expect(kinds(steps[1])).toEqual(['streamContent']);+ expect((steps[1][0] as any).content).toBe('Hello world');+ });++ it('persists a tool batch with pre-allocated ids, isNew flags, and advances the chain', () => {+ const { steps, state } = run([+ textEvent('task-1', 'm1', 'thinking'),+ toolsEvent('task-1', 'm1', [tool('tc-1'), tool('tc-2')]),+ ]);++ const batch = steps[1].find((i) => i.kind === 'persistToolBatch') as any;+ expect(batch).toMatchObject({+ assistantMessageId: 'msg_2',+ content: 'thinking',+ threadId: 'thd_1',+ });+ expect(batch.tools).toHaveLength(2);+ expect(batch.tools[0]).toMatchObject({+ isNew: true,+ toolMessageId: 'msg_3',+ payload: { id: 'tc-1' },+ });+ expect(batch.tools[1]).toMatchObject({+ isNew: true,+ toolMessageId: 'msg_4',+ payload: { id: 'tc-2' },+ });++ // next assistant chains off the LAST tool message of the batch+ expect(state.runs.get('task-1')!.lastChainParentId).toBe('msg_4');+ expect([...state.runs.get('task-1')!.lifetimeToolCallIds]).toEqual(['tc-1', 'tc-2']);+ });++ it('de-dupes already-persisted tools in the same turn (isNew false, no new id)', () => {+ const { steps } = run([+ toolsEvent('task-1', 'm1', [tool('tc-1')]),+ toolsEvent('task-1', 'm1', [tool('tc-1'), tool('tc-2')]),+ ]);+ const batch2 = steps[1].find((i) => i.kind === 'persistToolBatch') as any;+ expect(batch2.tools.map((t: any) => [t.payload.id, t.isNew, t.toolMessageId])).toEqual([+ ['tc-1', false, 'msg_3'], // reused id from first batch+ ['tc-2', true, 'msg_4'],+ ]);+ });++ it('cuts a new turn on subagentMessageId change: flush prior + new assistant chained off last tool', () => {+ const { steps, state } = run([+ textEvent('task-1', 'm1', 'first turn text'),+ toolsEvent('task-1', 'm1', [tool('tc-1')]), // lastChainParentId β msg_3+ textEvent('task-1', 'm2', 'second turn'), // turn boundary+ ]);++ // boundary flushes prior turn content, opens a new assistant off the last tool msg (msg_3)+ expect(kinds(steps[2])).toEqual(['persistContent', 'createMessage', 'streamContent']);+ expect(steps[2][0]).toMatchObject({ content: 'first turn text', messageId: 'msg_2' });+ expect(steps[2][1]).toMatchObject({ messageId: 'msg_4', parentId: 'msg_3', role: 'assistant' });+ expect(steps[2][2]).toMatchObject({ content: 'second turn', messageId: 'msg_4' });++ const r = state.runs.get('task-1')!;+ expect(r.currentAssistantId).toBe('msg_4');+ expect(r.currentSubagentMessageId).toBe('m2');+ expect(r.accContent).toBe('second turn');+ expect(r.toolState.persistedIds.size).toBe(0); // per-turn reset+ });++ it('resolves an inner tool_result into its owning run', () => {+ const { steps } = run([+ toolsEvent('task-1', 'm1', [tool('tc-1')]),+ { data: { content: 'ls output', isError: false, toolCallId: 'tc-1' }, type: 'tool_result' },+ ]);+ expect(steps[1]).toEqual([+ {+ content: 'ls output',+ isError: false,+ kind: 'resolveToolResult',+ pluginState: undefined,+ threadId: 'thd_1',+ toolCallId: 'tc-1',+ },+ ]);+ });++ it('finalizes on the parent tool_result: flush + terminal assistant + finalizeThread + deletes run', () => {+ const { steps, state } = run([+ textEvent('task-1', 'm1', 'trailing summary'),+ { data: { content: 'subagent answer', toolCallId: 'task-1' }, type: 'tool_result' },+ ]);++ expect(kinds(steps[1])).toEqual(['persistContent', 'createMessage', 'finalizeThread']);+ expect(steps[1][0]).toMatchObject({ content: 'trailing summary', messageId: 'msg_2' });+ expect(steps[1][1]).toMatchObject({+ content: 'subagent answer',+ parentId: 'msg_2',+ role: 'assistant',+ messageId: 'msg_3',+ });+ expect(steps[1][2]).toMatchObject({ threadId: 'thd_1' });+ expect(state.runs.has('task-1')).toBe(false); // deleted+ });++ it('records subagent usage onto the current assistant', () => {+ const usage = { totalTokens: 42 };+ const { steps } = run([+ textEvent('task-1', 'm1', 'x'),+ {+ data: {+ model: 'claude',+ phase: 'turn_metadata',+ provider: 'claude-code',+ subagent: sub('task-1', 'm1'),+ usage,+ },+ type: 'step_complete',+ },+ ]);+ expect(steps[1]).toEqual([+ {+ kind: 'recordUsage',+ messageId: 'msg_2',+ model: 'claude',+ provider: 'claude-code',+ threadId: 'thd_1',+ usage,+ },+ ]);+ });++ it('drains orphan runs on agent_runtime_end (flush only, no terminal assistant)', () => {+ const { steps, state } = run([+ textEvent('task-1', 'm1', 'orphan content'),+ { data: { reason: 'success' }, type: 'agent_runtime_end' },+ ]);+ expect(kinds(steps[1])).toEqual(['persistContent', 'finalizeThread']);+ expect(steps[1][0]).toMatchObject({ content: 'orphan content', messageId: 'msg_2' });+ expect(state.runs.size).toBe(0);+ });++ it('drains multiple orphan runs independently', () => {+ const { steps } = run([+ toolsEvent('task-1', 'm1', [tool('a')]),+ toolsEvent('task-2', 'n1', [tool('b')]),+ { data: {}, type: 'error' },+ ]);+ // two runs β two finalizeThread intents+ expect(steps[2].filter((i) => i.kind === 'finalizeThread')).toHaveLength(2);+ });++ it('ignores main-scoped events and unowned tool_results (no intents, state unchanged)', () => {+ const state0 = createSubagentRunsState();+ const main = reduceSubagentRuns(+ state0,+ { data: { chunkType: 'text', content: 'hi' }, type: 'stream_chunk' },+ makeCtx(),+ );+ expect(main.intents).toEqual([]);+ expect(main.state).toBe(state0);++ const orphanResult = reduceSubagentRuns(+ state0,+ { data: { content: 'x', toolCallId: 'unknown' }, type: 'tool_result' },+ makeCtx(),+ );+ expect(orphanResult.intents).toEqual([]);+ });++ it('is transactional: reduce does not mutate the input state', () => {+ const state0 = createSubagentRunsState();+ const r1 = reduceSubagentRuns(state0, textEvent('task-1', 'm1', 'a'), makeCtx());+ // input untouched+ expect(state0.runs.size).toBe(0);+ expect(r1.state.runs.size).toBe(1);++ // mutating the next state's run must not bleed into a re-reduce of the old state+ const r2 = reduceSubagentRuns(r1.state, toolsEvent('task-1', 'm1', [tool('tc-1')]), makeCtx());+ expect(r1.state.runs.get('task-1')!.toolState.persistedIds.size).toBe(0);+ expect(r2.state.runs.get('task-1')!.toolState.persistedIds.size).toBe(1);+ });+});diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.tsnew file mode 100644index 00000000000..9097d4fa5da--- /dev/null+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts@@ -0,0 +1,425 @@+import type { SubagentEventContext, ToolCallPayload } from '../types';+import { getEventScope } from './getEventScope';+import type {+ SubagentIntent,+ SubagentReduceCtx,+ SubagentRun,+ SubagentRunsState,+ SubagentTurnToolState,+} from './types';++/**+ * Pure, transactional subagent run reducer.+ *+ * `reduce(state, event, ctx)` returns the NEXT state plus the intents to apply+ * β it never mutates `state` in place. The caller commits the returned state+ * ONLY after the intents are successfully applied:+ *+ * const { state: next, intents } = reduce(state, event, ctx);+ * await applyIntents(intents); // may throw / be best-effort+ * state = next; // commit on success+ *+ * This commit-on-success contract subsumes the renderer's old+ * `pendingFlushTarget` error-recovery: if applying a flush fails and the caller+ * keeps the old state, the run is preserved with its accumulators intact and+ * `currentAssistantId` un-advanced, so a later finalize naturally retries+ * against the correct (original-turn) assistant. On the server, a throw leaves+ * the event unmarked so the CLI BatchIngester replays it against the old state.+ *+ * Finalize DELETES the run (server-style). This unifies the two engines' old+ * divergent idempotency strategies (server deleted; renderer relied on cleared+ * accumulators) onto one: a second finalize / orphan drain finds no run and is+ * a clean no-op, with the same DB end-state (thread Active, terminal once).+ */++// βββ State copy helpers (structural sharing) βββ++const copyToolState = (s: SubagentTurnToolState): SubagentTurnToolState => ({+ payloads: s.payloads.map((p) => ({ ...p })),+ persistedIds: new Set(s.persistedIds),+ toolMsgIdByCallId: new Map(s.toolMsgIdByCallId),+});++const emptyToolState = (): SubagentTurnToolState => ({+ payloads: [],+ persistedIds: new Set(),+ toolMsgIdByCallId: new Map(),+});++const copyRun = (run: SubagentRun): SubagentRun => ({+ ...run,+ lifetimeToolCallIds: new Set(run.lifetimeToolCallIds),+ toolState: copyToolState(run.toolState),+});++/** Clone the runs map, deep-copying only the run we're about to mutate. */+const withRun = (+ state: SubagentRunsState,+ parentToolCallId: string,+ run: SubagentRun,+): SubagentRunsState => {+ const runs = new Map(state.runs);+ runs.set(parentToolCallId, run);+ return { runs };+};++const withoutRun = (state: SubagentRunsState, parentToolCallId: string): SubagentRunsState => {+ const runs = new Map(state.runs);+ runs.delete(parentToolCallId);+ return { runs };+};++const SUBAGENT_TITLE_MAX = 80;++interface ReduceResult {+ intents: SubagentIntent[];+ state: SubagentRunsState;+}++/**+ * Ensure a run exists for `subCtx.parentToolCallId` and its current turn+ * matches `subCtx.subagentMessageId`. Returns the (possibly new / turn-advanced)+ * run, the next state, and any structural intents (thread + message creates,+ * prior-turn flush). The returned `run` is a fresh copy safe to mutate further+ * by the caller before it calls `withRun` to fold it back into state.+ */+const ensureRun = (+ state: SubagentRunsState,+ subCtx: SubagentEventContext,+ ctx: SubagentReduceCtx,+): { intents: SubagentIntent[]; run: SubagentRun; state: SubagentRunsState } => {+ const intents: SubagentIntent[] = [];+ const existing = state.runs.get(subCtx.parentToolCallId);++ // βββ First event for this parent β lazy-create Thread + seed + assistant βββ+ if (!existing) {+ const threadId = ctx.newId('thread');+ const userMsgId = ctx.newId('message');+ const firstAssistantId = ctx.newId('message');+ const { spawnMetadata } = subCtx;+ const title =+ spawnMetadata?.description?.slice(0, SUBAGENT_TITLE_MAX) ||+ spawnMetadata?.subagentType ||+ 'Subagent';++ intents.push(+ {+ kind: 'createThread',+ parentToolCallId: subCtx.parentToolCallId,+ sourceMessageId: ctx.mainAssistantId,+ sourceToolCallId: subCtx.parentToolCallId,+ subagentType: spawnMetadata?.subagentType,+ threadId,+ title,+ topicId: ctx.topicId,+ },+ {+ agentId: ctx.agentId,+ content: spawnMetadata?.prompt ?? '',+ kind: 'createMessage',+ messageId: userMsgId,+ parentId: ctx.mainAssistantId,+ role: 'user',+ threadId,+ topicId: ctx.topicId,+ },+ {+ agentId: ctx.agentId,+ content: '',+ kind: 'createMessage',+ messageId: firstAssistantId,+ parentId: userMsgId,+ role: 'assistant',+ threadId,+ topicId: ctx.topicId,+ },+ );++ const run: SubagentRun = {+ accContent: '',+ accReasoning: '',+ currentAssistantId: firstAssistantId,+ currentSubagentMessageId: subCtx.subagentMessageId ?? '',+ lastChainParentId: firstAssistantId,+ lifetimeToolCallIds: new Set(),+ threadId,+ toolState: emptyToolState(),+ };+ return { intents, run, state: withRun(state, subCtx.parentToolCallId, run) };+ }++ const run = copyRun(existing);++ // βββ Turn boundary (new subagentMessageId) β flush prior turn + new assistant βββ+ if (subCtx.subagentMessageId && subCtx.subagentMessageId !== run.currentSubagentMessageId) {+ if (run.accContent || run.accReasoning) {+ intents.push({+ content: run.accContent || undefined,+ kind: 'persistContent',+ messageId: run.currentAssistantId,+ reasoning: run.accReasoning || undefined,+ threadId: run.threadId,+ });+ }++ const nextAssistantId = ctx.newId('message');+ intents.push({+ agentId: ctx.agentId,+ content: '',+ kind: 'createMessage',+ messageId: nextAssistantId,+ parentId: run.lastChainParentId,+ role: 'assistant',+ threadId: run.threadId,+ topicId: ctx.topicId,+ });++ run.currentAssistantId = nextAssistantId;+ run.currentSubagentMessageId = subCtx.subagentMessageId;+ run.lastChainParentId = nextAssistantId;+ run.toolState = emptyToolState();+ run.accContent = '';+ run.accReasoning = '';+ }++ return { intents, run, state: withRun(state, subCtx.parentToolCallId, run) };+};++/**+ * Finalize a run: flush trailing content, optionally write a terminal assistant+ * (when `resultContent` is provided β the parent tool_result's answer), mark the+ * Thread Active, and DELETE the run. Called with `resultContent` from the parent+ * tool_result, and without it from terminal orphan drain.+ */+const finalizeRun = (+ state: SubagentRunsState,+ parentToolCallId: string,+ resultContent: string | undefined,+ ctx: SubagentReduceCtx,+): ReduceResult => {+ const existing = state.runs.get(parentToolCallId);+ if (!existing) return { intents: [], state };++ const intents: SubagentIntent[] = [];+ const run = copyRun(existing);++ if (run.accContent || run.accReasoning) {+ intents.push({+ content: run.accContent || undefined,+ kind: 'persistContent',+ messageId: run.currentAssistantId,+ reasoning: run.accReasoning || undefined,+ threadId: run.threadId,+ });+ run.accContent = '';+ run.accReasoning = '';+ }++ if (resultContent) {+ const terminalId = ctx.newId('message');+ intents.push({+ agentId: ctx.agentId,+ content: resultContent,+ kind: 'createMessage',+ messageId: terminalId,+ parentId: run.lastChainParentId,+ role: 'assistant',+ threadId: run.threadId,+ topicId: ctx.topicId,+ });+ run.currentAssistantId = terminalId;+ run.lastChainParentId = terminalId;+ }++ intents.push({ kind: 'finalizeThread', threadId: run.threadId });++ return { intents, state: withoutRun(state, parentToolCallId) };+};++/** Find the run that owns an inner tool_call id (lifetime lookup). */+const findRunByInnerToolCallId = (+ state: SubagentRunsState,+ toolCallId: string,+): { parentToolCallId: string; run: SubagentRun } | undefined => {+ for (const [parentToolCallId, run] of state.runs) {+ if (run.lifetimeToolCallIds.has(toolCallId)) return { parentToolCallId, run };+ }+ return undefined;+};++const reduceTextChunk = (+ state: SubagentRunsState,+ subCtx: SubagentEventContext,+ kind: 'text' | 'reasoning',+ chunk: string,+ ctx: SubagentReduceCtx,+): ReduceResult => {+ const ensured = ensureRun(state, subCtx, ctx);+ const run = ensured.run;+ const intents = ensured.intents;++ if (kind === 'text') run.accContent += chunk;+ else run.accReasoning += chunk;++ intents.push({+ kind: 'streamContent',+ messageId: run.currentAssistantId,+ threadId: run.threadId,+ ...(kind === 'text' ? { content: run.accContent } : { reasoning: run.accReasoning }),+ });++ return { intents, state: withRun(ensured.state, subCtx.parentToolCallId, run) };+};++const reduceToolsChunk = (+ state: SubagentRunsState,+ subCtx: SubagentEventContext,+ tools: ToolCallPayload[],+ ctx: SubagentReduceCtx,+): ReduceResult => {+ const ensured = ensureRun(state, subCtx, ctx);+ const run = ensured.run;+ const intents = ensured.intents;++ for (const tool of tools) run.lifetimeToolCallIds.add(tool.id);++ const newToolMsgIds: string[] = [];+ for (const tool of tools) {+ if (!run.toolState.persistedIds.has(tool.id)) {+ run.toolState.persistedIds.add(tool.id);+ run.toolState.payloads.push({+ apiName: tool.apiName,+ arguments: tool.arguments,+ id: tool.id,+ identifier: tool.identifier,+ type: tool.type,+ });+ const toolMessageId = ctx.newId('message');+ run.toolState.toolMsgIdByCallId.set(tool.id, toolMessageId);+ newToolMsgIds.push(toolMessageId);+ }+ }++ intents.push({+ assistantMessageId: run.currentAssistantId,+ content: run.accContent || undefined,+ kind: 'persistToolBatch',+ reasoning: run.accReasoning || undefined,+ threadId: run.threadId,+ tools: run.toolState.payloads.map((p) => ({+ isNew: newToolMsgIds.includes(run.toolState.toolMsgIdByCallId.get(p.id)!),+ payload: { ...p },+ toolMessageId: run.toolState.toolMsgIdByCallId.get(p.id)!,+ })),+ });++ // Chain the next turn's assistant off the LAST tool message of this batch.+ const lastToolMsgId = newToolMsgIds.at(-1);+ if (lastToolMsgId) run.lastChainParentId = lastToolMsgId;++ return { intents, state: withRun(ensured.state, subCtx.parentToolCallId, run) };+};++/**+ * Reduce a single stream event. Returns the next state and intents to apply.+ *+ * The caller routes an event here when it is subagent-tagged, OR it is a+ * `tool_result` (to catch the parent-spawn finalize whose tool_result is+ * main-scoped), OR it is a terminal event (orphan drain). For any event that+ * doesn't concern a subagent run, it returns `{ state, intents: [] }` unchanged+ * so the caller's main-agent path still owns it.+ */+export const reduce = (+ state: SubagentRunsState,+ event: { data?: any; type?: string },+ ctx: SubagentReduceCtx,+): ReduceResult => {+ const type = event.type;+ const data = event.data ?? {};++ if (type === 'stream_chunk') {+ const scope = getEventScope(event);+ if (scope.kind !== 'subagent') return { intents: [], state };+ const subCtx = scope.ctx;++ if (data.chunkType === 'text' && typeof data.content === 'string' && data.content) {+ return reduceTextChunk(state, subCtx, 'text', data.content, ctx);+ }+ if (data.chunkType === 'reasoning' && typeof data.reasoning === 'string' && data.reasoning) {+ return reduceTextChunk(state, subCtx, 'reasoning', data.reasoning, ctx);+ }+ if (data.chunkType === 'tools_calling') {+ const tools = (data.toolsCalling as ToolCallPayload[] | undefined) ?? [];+ if (tools.length === 0) return { intents: [], state };+ return reduceToolsChunk(state, subCtx, tools, ctx);+ }+ return { intents: [], state };+ }++ if (type === 'tool_result') {+ const toolCallId: string | undefined = data.toolCallId;+ if (!toolCallId) return { intents: [], state };+ const content: string = data.content ?? '';++ // Parent-spawn tool_result (main-scoped): the subagent ended β finalize.+ if (state.runs.has(toolCallId)) {+ return finalizeRun(state, toolCallId, content, ctx);+ }++ // Inner subagent tool_result β resolve into its thread.+ const owner = findRunByInnerToolCallId(state, toolCallId);+ if (owner) {+ return {+ intents: [+ {+ content,+ isError: !!data.isError,+ kind: 'resolveToolResult',+ pluginState: data.pluginState,+ threadId: owner.run.threadId,+ toolCallId,+ },+ ],+ state,+ };+ }++ // A main-agent tool_result we don't own β caller's main path handles it.+ return { intents: [], state };+ }++ if (type === 'step_complete' && data.phase === 'turn_metadata') {+ const subCtx = data.subagent as SubagentEventContext | undefined;+ if (!subCtx || !data.usage) return { intents: [], state };+ const run = state.runs.get(subCtx.parentToolCallId);+ if (!run) return { intents: [], state };+ return {+ intents: [+ {+ kind: 'recordUsage',+ messageId: run.currentAssistantId,+ model: data.model,+ provider: data.provider,+ threadId: run.threadId,+ usage: data.usage,+ },+ ],+ state,+ };+ }++ if (type === 'agent_runtime_end' || type === 'error') {+ // Orphan drain: finalize every run that never saw its parent tool_result+ // (flush only β no terminal assistant, no authoritative result).+ let next = state;+ const intents: SubagentIntent[] = [];+ for (const parentToolCallId of state.runs.keys()) {+ const r = finalizeRun(next, parentToolCallId, undefined, ctx);+ intents.push(...r.intents);+ next = r.state;+ }+ return { intents, state: next };+ }++ return { intents: [], state };+};diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts b/packages/heterogeneous-agents/src/subagentCoordinator/types.tsnew file mode 100644index 00000000000..fe9b34124de--- /dev/null+++ b/packages/heterogeneous-agents/src/subagentCoordinator/types.ts@@ -0,0 +1,222 @@+import type { ToolCallPayload } from '../types';++/**+ * Subagent run coordinator β shared, side-effect-free state machine for+ * heterogeneous-agent (Claude Code / Codex) subagent runs.+ *+ * Background: both the renderer executor (`heterogeneousAgentExecutor.ts`) and+ * the server persistence handler (`HeterogeneousPersistenceHandler.ts`) used to+ * hand-write the SAME subagent run state machine β lazy Thread create, turn+ * boundary cut on `subagentMessageId` change, finalize on the parent+ * tool_result, orphan drain, chain parenting, turn-scoped vs lifetime tool ids.+ * That duplication was the epicenter of nearly every hetero subagent bug.+ *+ * This module owns the "when to create / cut / finalize" decisions in ONE pure+ * reducer. It performs no I/O: it returns a list of {@link SubagentIntent}s that+ * each environment's interpreter executes against its own persistence + UI+ * surfaces (renderer: DB via messageService + live store dispatch; server:+ * DB via messageModel). The reducer pre-allocates every id (via `ctx.newId`) so+ * intents can carry concrete `parentId` chains with no "create then backfill+ * id" reverse dependency.+ */++// βββ Reducer state βββ++/** Per-turn tool persistence state. Reset on every subagent turn boundary. */+export interface SubagentTurnToolState {+ /**+ * Cumulative `tools[]` payloads for the CURRENT in-thread assistant. Carries+ * NO `result_msg_id` β the interpreter backfills that from the pre-allocated+ * tool-message id when it writes the assistant's `tools[]` (phase 3).+ */+ payloads: ToolCallPayload[];+ /** tool_call ids already turned into tool messages this turn (de-dupe). */+ persistedIds: Set<string>;+ /** Pre-allocated tool-message id per tool_call id, for this turn's payloads. */+ toolMsgIdByCallId: Map<string, string>;+}++/**+ * Per-spawn subagent run state, keyed by `parentToolCallId`. Mirrors the+ * `SubagentRunState` that previously lived in both engines, minus the+ * environment-specific I/O handles (store dispatcher, sub-operation id,+ * pendingFlushTarget) which stay in each interpreter.+ */+export interface SubagentRun {+ /** Accumulated text for the current in-thread assistant turn. */+ accContent: string;+ /** Accumulated reasoning (thinking) for the current turn. */+ accReasoning: string;+ /** The in-thread assistant message currently being appended to. */+ currentAssistantId: string;+ /** Adapter `subagentMessageId` for the current turn (change = new assistant). */+ currentSubagentMessageId: string;+ /**+ * Most recent parentId in the thread chain (`user β asst β tool β asst β¦`).+ * Advances to the last tool message of each batch so the next assistant+ * chains off it β mirrors main-agent step-boundary parenting.+ */+ lastChainParentId: string;+ /**+ * Run-lifetime set of every inner tool_call_id this subagent has persisted.+ * Unlike per-turn `toolState.persistedIds` (wiped on turn boundary), this+ * only grows, so a delayed `tool_result` landing after its owning turn rolled+ * over still resolves back to the right run.+ */+ lifetimeToolCallIds: Set<string>;+ /** The subagent Thread this spawn's messages belong to. */+ threadId: string;+ /** Per-turn tool persistence state. */+ toolState: SubagentTurnToolState;+}++export interface SubagentRunsState {+ /** Active subagent runs, keyed by `parentToolCallId`. */+ runs: Map<string, SubagentRun>;+}++export const createSubagentRunsState = (): SubagentRunsState => ({+ runs: new Map(),+});++// βββ Reduce context (per event) βββ++/**+ * Per-event context the interpreter supplies. `mainAssistantId` / `topicId` /+ * `agentId` describe the MAIN-agent state at the moment the subagent event is+ * processed (the thread's `sourceMessageId` and the user-seed `parentId` both+ * point at the main assistant that spawned the Task). `newId` pre-allocates an+ * environment-appropriate, DB-compatible id.+ */+export interface SubagentReduceCtx {+ agentId?: string | null;+ /** Main-agent assistant id that spawned this subagent (for thread + seed parenting). */+ mainAssistantId: string;+ /** Allocate a prefixed id (`thd_β¦` / `msg_β¦`). Deterministic counter in tests. */+ newId: (kind: 'thread' | 'message') => string;+ topicId: string | null;+}++// βββ Intents βββ++/**+ * Declarative "what happened" instructions. Each interpreter maps these to its+ * own I/O. Two content intents (`streamContent` live vs `persistContent`+ * durable) are intentional: the renderer applies `streamContent` to its thread+ * store bucket for token-level UI and only writes DB on `persistContent` /+ * `persistToolBatch`; the server no-ops `streamContent` and persists only on+ * `persistContent` / `persistToolBatch` (one DB write per token would be wasteful).+ */+export type SubagentIntent =+ | CreateThreadIntent+ | CreateMessageIntent+ | StreamContentIntent+ | PersistContentIntent+ | PersistToolBatchIntent+ | ResolveToolResultIntent+ | RecordUsageIntent+ | FinalizeThreadIntent;++/** Lazy-create the subagent Thread (status Processing). */+export interface CreateThreadIntent {+ kind: 'createThread';+ parentToolCallId: string;+ /** Main assistant that spawned this subagent. */+ sourceMessageId: string;+ sourceToolCallId: string;+ subagentType?: string;+ threadId: string;+ title: string;+ topicId: string | null;+}++/**+ * Create an in-thread message β the user seed (role `user`), each turn's+ * assistant, or the terminal result assistant (role `assistant`). The renderer+ * also dispatches this into its thread store bucket for live display.+ */+export interface CreateMessageIntent {+ agentId?: string | null;+ content: string;+ kind: 'createMessage';+ messageId: string;+ parentId: string;+ role: 'user' | 'assistant';+ threadId: string;+ topicId: string | null;+}++/** Live in-memory content update (replace). Renderer applies; server no-ops. */+export interface StreamContentIntent {+ content?: string;+ kind: 'streamContent';+ messageId: string;+ reasoning?: string;+ threadId: string;+}++/** Durable content/reasoning flush (turn boundary / finalize). Both persist. */+export interface PersistContentIntent {+ content?: string;+ kind: 'persistContent';+ messageId: string;+ reasoning?: string;+ threadId: string;+}++/** A single tool in a {@link PersistToolBatchIntent}. */+export interface PersistToolBatchEntry {+ /** True when this tool's row must be created this batch (not seen before). */+ isNew: boolean;+ payload: ToolCallPayload;+ /** Pre-allocated tool-message id; row is created with this id when `isNew`. */+ toolMessageId: string;+}++/**+ * Persist a batch of subagent tool calls into the thread-scoped assistant.+ * Interpreter runs the 3-phase write: (1) `assistant.tools[]` without+ * result_msg_id, (2) create rows for `isNew` entries with their pre-allocated+ * ids + populate the tool-message lookup map, (3) re-write `assistant.tools[]`+ * with `result_msg_id` backfilled from each entry's `toolMessageId`.+ */+export interface PersistToolBatchIntent {+ assistantMessageId: string;+ /** Latest accumulated content snapshot to persist alongside the tools. */+ content?: string;+ kind: 'persistToolBatch';+ reasoning?: string;+ threadId: string;+ tools: PersistToolBatchEntry[];+}++/**+ * Resolve an inner subagent tool_result. The interpreter looks up the+ * tool-message id from its own `toolCallId β messageId` map (populated by+ * `persistToolBatch` phase 2; on the server it is also DB-backed so a+ * cross-replica result still lands).+ */+export interface ResolveToolResultIntent {+ content: string;+ isError: boolean;+ kind: 'resolveToolResult';+ pluginState?: Record<string, any>;+ threadId: string;+ toolCallId: string;+}++/** Attach per-turn usage/model/provider to the current in-thread assistant. */+export interface RecordUsageIntent {+ kind: 'recordUsage';+ messageId: string;+ model?: string;+ provider?: string;+ threadId: string;+ usage: unknown;+}++/** Mark the subagent Thread complete (Processing β Active). */+export interface FinalizeThreadIntent {+ kind: 'finalizeThread';+ threadId: string;+}diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.tsindex c8bb3f0e244..61c48bb4fef 100644--- a/packages/types/src/message/ui/params.ts+++ b/packages/types/src/message/ui/params.ts@@ -51,12 +51,14 @@ export interface CreateNewMessageParams {content: string;// ========== Error handling ==========error?: ChatMessageError | null;-fileChunks?: MessageSemanticSearchChunk[];+// ========== Content ==========files?: string[];-groupId?: string;++ /** Caller-pre-allocated message id. Omitted β the DB generates one. */+ id?: string;// ========== Model info ==========model?: string;@@ -186,6 +188,10 @@ export const CreateNewMessageParamsSchema = z// Required fieldsrole: UIMessageRoleTypeSchema,content: z.string(),+ // Caller-pre-allocated id (e.g. the subagent run coordinator assigns ids up+ // front so parentId chains resolve without a createβbackfill round-trip).+ // Omitted β the DB generates one.+ id: z.string().optional(),// agentId is required, but can be resolved from sessionId in the routeragentId: z.string().optional(),/**diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.tsindex f5c667bf79d..30f39cb4943 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -2543,27 +2543,86 @@ describe('heterogeneousAgentExecutor DB persistence', () => {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.+ // Ids are now caller-pre-allocated (the coordinator assigns them and the+ // interpreter creates rows WITH that id), so we resolve the two relevant+ // in-thread assistants by their create payloads rather than a literal id:+ // - the FIRST streaming-turn assistant (role assistant, empty content)+ // - the terminal assistant (role assistant, the resultContent)+ const firstAssistantId = mockCreateMessage.mock.calls.find(+ ([p]: any) =>+ p.role === 'assistant' &&+ p.content === '' &&+ typeof p.threadId === 'string' &&+ p.threadId.startsWith('thd_'),+ )?.[0].id;+ const terminalCreate = mockCreateMessage.mock.calls.find(+ ([p]: any) => p.role === 'assistant' && p.content === 'terminal result',+ );+ expect(firstAssistantId).toBeDefined();+ // Terminal assistant carrying the authoritative `resultContent` was still+ // created as a fresh row (not overwritten by the retry), with its OWN id.+ expect(terminalCreate).toBeDefined();+ expect(terminalCreate![0].id).not.toBe(firstAssistantId);+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.+ // Every attempt β including the retry β must target the FIRST streaming+ // turn's assistant, NOT the terminal row, so the authoritative+ // `resultContent` is never clobbered by the leftover streamed buffer.for (const [id] of streamedWrites) {- expect(id).toBe('thread-ast-1');+ expect(id).toBe(firstAssistantId);}+ });- // Terminal assistant carrying the authoritative `resultContent`- // was still created as a fresh row (not overwritten by the retry).- const terminalCreate = mockCreateMessage.mock.calls.find(+ it('retries the lazy thread create on the next event when a create intent fails (commit-on-success)', async () => {+ // A transient failure on createThread / createMessage must NOT advance+ // the coordinator state: committing would make the run look alive while+ // nothing landed, so later chunks could never recreate the thread and+ // the streamed content would be orphaned. With commit-on-success the+ // failed event is dropped and the NEXT subagent event re-runs the lazy+ // create end-to-end with fresh ids.+ mockCreateThread.mockRejectedValueOnce(new Error('transient IndexedDB failure'));++ await runWithEvents([+ ccInit(),+ ccToolUse('msg_main', 'toolu_task', 'Task', {+ description: 'x',+ prompt: 'go',+ subagent_type: 'Explore',+ }),+ // First subagent event: createThread throws β state must not commit.+ ccSubagentText('msg_sub', 'toolu_task', 'lost '),+ // Next subagent event retries the lazy create.+ ccSubagentText('msg_sub', 'toolu_task', 'kept'),+ ccSubagentSpawnResult('toolu_task', 'terminal result'),+ ccResult(),+ ]);++ // Lazy create attempted twice β first failed, retry landed with a fresh id.+ expect(mockCreateThread).toHaveBeenCalledTimes(2);+ const retryThreadId = mockCreateThread.mock.calls[1][0].id;+ expect(retryThreadId).not.toBe(mockCreateThread.mock.calls[0][0].id);++ // Every in-thread row (seed user, turn assistant, terminal assistant)+ // belongs to the retried thread β nothing was written against the+ // thread whose create failed.+ const threadCreates = mockCreateMessage.mock.calls.filter(+ ([p]: any) => typeof p.threadId === 'string' && p.threadId.startsWith('thd_'),+ );+ expect(threadCreates.length).toBeGreaterThan(0);+ for (const [p] of threadCreates) {+ expect(p.threadId).toBe(retryThreadId);+ }++ // The run still finalized normally inside the retried thread.+ const terminal = mockCreateMessage.mock.calls.find(([p]: any) => p.role === 'assistant' && p.content === 'terminal result',);- expect(terminalCreate).toBeDefined();+ expect(terminal).toBeDefined();+ expect(terminal![0].threadId).toBe(retryThreadId);});it('creates a terminal in-thread assistant with the main tool_result content', async () => {diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.tsindex 49db250305c..502f5851da5 100644--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts@@ -10,7 +10,15 @@ import {type HeterogeneousAgentSessionError,HeterogeneousAgentSessionErrorCode,} from '@lobechat/electron-client-ipc';-import type { SubagentEventContext, ToolCallPayload } from '@lobechat/heterogeneous-agents';+import {+ createSubagentRunsState,+ reduceSubagentRuns,+ type SubagentEventContext,+ type SubagentIntent,+ type SubagentReduceCtx,+ type SubagentRunsState,+ type ToolCallPayload,+} from '@lobechat/heterogeneous-agents';import type {ChatMessageError,ChatToolPayload,@@ -430,581 +438,6 @@ const persistToolBatch = async (}};-/**- * Per-subagent-spawn state tracking the current Thread + current- * subagent assistant message for a given parent Task tool_use. One entry- * per `parentToolCallId`, created lazily on the first subagent event.- *- * `subagentMessageId` mirrors main-agent turn tracking: when the- * adapter-reported subagent message.id changes, the executor cuts a new- * subagent assistant message inside the Thread (same-shaped recursion- * as the main agent's step boundary β `user β assistant β tool β assistant`).- */-interface SubagentRunState {- /**- * Accumulated text content for the CURRENT in-thread assistant turn.- * Mirrors the main agent's `accumulatedContent`: subagent text chunks- * append while the turn streams, the value travels alongside tools[]- * in each persist batch update so DB sees content + tools in one go,- * and is flushed on turn change / subagent finalization.- */- accumulatedContent: string;- /** Accumulated reasoning (thinking) content for the current turn. */- accumulatedReasoning: string;- /** The in-thread assistant message currently being appended to. */- currentAssistantMsgId: string;- /** Adapter's `subagentMessageId` for the current turn (change = new assistant). */- currentSubagentMessageId: string;- /**- * Tools created in the most recent persist batch, keyed by tool_use.id- * β tool message DB id. Used to chain the NEXT turn's assistant off the- * last tool message (mirrors main agent's step-boundary parentId logic).- * Populated after each persist from the caller-provided global map.- */- lastBatchToolMsgIds: string[];- /**- * Most recent parentId in the thread's chain. Flows like the main- * topic: `user β assistant#1 β tool β assistant#2 β tool β ...`.- * Updated as new tool messages / assistant messages are created so- * the next write lands on the end of the chain.- */- lastChainParentId: string;- /**- * Run-lifetime set of every inner tool_call_id this subagent has ever- * persisted into its thread. Unlike `state.persistedIds`, which is- * turn-scoped and wiped when `currentSubagentMessageId` advances, this- * set only grows β so a delayed `tool_result` that lands after the- * owning turn has rolled over still resolves back to the right run via- * `findRunByInnerToolCallId`. Without this, the thread-bucket- * `updateMessage` path is skipped and the in-thread tool bubble stays- * stuck on the loading spinner until the user re-opens the Thread- * (main-topic `fetchAndReplaceMessages` does not rehydrate thread- * buckets).- */- lifetimeToolCallIds: Set<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;-}--/**- * Handle a subagent `tools_calling` chunk: ensure Thread + current- * subagent assistant exist, then run the shared 3-phase persist- * targeting the in-thread assistant.- *- * Lazy Thread creation: the FIRST subagent chunk for a given parent- * carries `spawnMetadata` (title / prompt / subagentType) on the- * event's `subagent` peer. That's when we create the Thread row + the- * `role:'user'` seed message. Subsequent chunks omit `spawnMetadata`- * and just append to the existing Thread.- *- * Turn tracking: when `subagent.subagentMessageId` differs from the- * stored `currentSubagentMessageId`, we cut a new in-thread assistant- * and reset per-turn state. Chain parenting mirrors main-agent step- * handling: `user β asst#1 β tool β asst#2 β tool β ...`.- */-/**- * Ensure a `SubagentRunState` exists for the given spawn + its current- * turn matches `subagentMessageId`. Handles two lazy actions:- *- * 1. **First event for a new parent** β create the Thread row, seed- * its `role:'user'` prompt message, open the first in-thread- * `role:'assistant'`.- * 2. **Turn boundary** (new `subagentMessageId`) β flush the prior- * turn's accumulated content to DB, then open the next in-thread- * assistant chained off the last tool message (same shape as- * main-agent step boundaries).- *- * Returns the run or `undefined` if any of the creates failed (the- * caller drops the event gracefully).- *- * Shared by `persistSubagentToolChunk` and `persistSubagentTextChunk`- * so text-only turns (e.g. the subagent's closing summary) and- * tool-only turns both flow through the same Thread-lifecycle code.- */-const ensureSubagentRun = async (- subagentCtx: SubagentEventContext,- 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- * in-memory list the UI is rendering. Fire-and-forget; the executor- * shouldn't block persistence on UI-side cache refresh.- */- onThreadCreated?: (threadId: string) => void,-): Promise<SubagentRunState | undefined> => {- if (!context.topicId) {- // Without a topicId we can't create a Thread β drop silently (same- // fallback as the main path; a non-topic-scoped test harness).- return undefined;- }-- let run = subagentRuns.get(subagentCtx.parentToolCallId);-- // βββ First subagent event for this parent β lazy-create Thread βββ- if (!run) {- const { spawnMetadata } = subagentCtx;- const threadId = generateThreadId();- const startedAt = new Date().toISOString();- const title =- spawnMetadata?.description?.slice(0, 80) || spawnMetadata?.subagentType || 'Subagent';-- try {- await threadService.createThread({- id: threadId,- metadata: {- sourceToolCallId: subagentCtx.parentToolCallId,- startedAt,- subagentType: spawnMetadata?.subagentType,- },- sourceMessageId: mainAssistantMessageId,- status: ThreadStatus.Processing,- title,- topicId: context.topicId,- type: ThreadType.Isolation,- });- onThreadCreated?.(threadId);- } catch (err) {- console.error('[HeterogeneousAgent] Failed to create subagent thread:', err);- return undefined;- }-- let userMsgId: string | undefined;- try {- const userMsg = await messageService.createMessage({- agentId: context.agentId,- content: spawnMetadata?.prompt ?? '',- parentId: mainAssistantMessageId,- role: 'user',- threadId,- topicId: context.topicId,- });- userMsgId = userMsg.id;- } catch (err) {- console.error('[HeterogeneousAgent] Failed to create subagent user message:', err);- return undefined;- }-- let firstAssistantId: string;- try {- const firstAssistant = await messageService.createMessage({- agentId: context.agentId,- content: '',- parentId: userMsgId,- role: 'assistant',- threadId,- topicId: context.topicId,- });- firstAssistantId = firstAssistant.id;- } catch (err) {- console.error('[HeterogeneousAgent] Failed to create subagent assistant message:', err);- 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: '',- currentAssistantMsgId: firstAssistantId,- currentSubagentMessageId: subagentCtx.subagentMessageId ?? '',- lastBatchToolMsgIds: [],- lastChainParentId: firstAssistantId,- lifetimeToolCallIds: new Set(),- state: { payloads: [], persistedIds: new Set() },- stream,- subOperationId,- threadId,- };- subagentRuns.set(subagentCtx.parentToolCallId, run);- return run;- }-- // βββ New subagent turn β flush old content, cut a new assistant βββ- if (- subagentCtx.subagentMessageId &&- subagentCtx.subagentMessageId !== run.currentSubagentMessageId- ) {- // Flush accumulated content for the PRIOR turn before it loses its- // assistant reference. We rely on persistToolBatch to also keep- // content+tools in sync during the turn, but a turn with NO tool- // calls (e.g. the subagent's final text-only summary) would never- // hit that path otherwise.- if (run.accumulatedContent || run.accumulatedReasoning) {- try {- const update: Record<string, any> = {};- if (run.accumulatedContent) update.content = run.accumulatedContent;- if (run.accumulatedReasoning) update.reasoning = { content: run.accumulatedReasoning };- await messageService.updateMessage(run.currentAssistantMsgId, update, {- agentId: context.agentId,- topicId: context.topicId,- });- run.stream.update(run.currentAssistantMsgId, update);- } catch (err) {- console.error('[HeterogeneousAgent] Failed to flush subagent turn content:', err);- }- }- try {- const nextAssistant = await messageService.createMessage({- agentId: context.agentId,- content: '',- parentId: run.lastChainParentId,- role: 'assistant',- 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;- run.state = { payloads: [], persistedIds: new Set() };- run.lastBatchToolMsgIds = [];- run.accumulatedContent = '';- run.accumulatedReasoning = '';- } catch (err) {- console.error('[HeterogeneousAgent] Failed to create subagent turn assistant:', err);- return undefined;- }- }-- return run;-};--/**- * Handle a subagent `tools_calling` chunk: ensure Thread + current- * subagent assistant exist, then run the shared 3-phase persist- * targeting the in-thread assistant. Accumulated text/reasoning rides- * along in the update so DB sees content + tools in one write.- */-const persistSubagentToolChunk = async (- tools: ToolCallPayload[],- subagentCtx: SubagentEventContext,- mainAssistantMessageId: string,- 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(- subagentCtx,- mainAssistantMessageId,- context,- subagentRuns,- beginSubagentRun,- onThreadCreated,- );- if (!run) return;-- // Record every incoming tool_use id in the run-lifetime lookup set- // before persisting, so a `tool_result` that arrives after this turn- // has rolled over still finds its owning run via- // `findRunByInnerToolCallId` (which can't rely on `state.persistedIds`- // alone β that one is wiped on turn advance).- for (const tool of tools) run.lifetimeToolCallIds.add(tool.id);-- // Snapshot the tool id set BEFORE the batch so we can compute which- // ids this call added (for chain-parent advancement below).- const preBatchIds = new Set(toolMsgIdByCallId.keys());-- await persistToolBatch(- tools,- run.state,- run.currentAssistantMsgId,- context,- { 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()]- .filter(([id]) => !preBatchIds.has(id))- .map(([, msgId]) => msgId);- run.lastBatchToolMsgIds.push(...newIds);- const lastToolMsgId = newIds.at(-1);- if (lastToolMsgId) run.lastChainParentId = lastToolMsgId;-};--/**- * Handle a subagent text/reasoning chunk: accumulate the content onto- * the run state. The actual DB write happens either on the next- * `persistToolBatch` (content rides along with tools[]) or at turn /- * finalization flush (`ensureSubagentRun` / `finalizeSubagentRun`).- *- * Keeping the write batched β instead of writing on every chunk β- * matches the main agent's content handling and avoids one DB round- * trip per streamed token.- */-const persistSubagentTextChunk = async (- kind: 'text' | 'reasoning',- chunk: string,- subagentCtx: SubagentEventContext,- mainAssistantMessageId: string,- context: ConversationContext,- subagentRuns: Map<string, SubagentRunState>,- beginSubagentRun: (threadId: string) => {- stream: SubagentStoreDispatcher;- subOperationId: string;- },- onThreadCreated?: (threadId: string) => void,-) => {- const run = await ensureSubagentRun(- subagentCtx,- mainAssistantMessageId,- context,- subagentRuns,- beginSubagentRun,- onThreadCreated,- );- if (!run) return;- 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>);- }-};--/**- * Finalize a completed subagent run when the main-agent receives the- * `tool_result` for its spawn tool_use.- *- * Two-step persistence:- *- * 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,- 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) {- // 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);- }- }-- // Mark the subagent Thread complete (created as `Processing`). The chip's- // tool-count / token / model metrics are NOT written here β they're derived- // on read from the child messages (live: `aggregateSubagentMetrics` over- // `dbMessagesMap`; cold-load: the same aggregation in SQL via- // `threadModel.queryByTopicId`), so finalize owns only the status transition.- // Best-effort β a failure here must not break finalize.- try {- await threadService.updateThread(run.threadId, { status: ThreadStatus.Active });- } catch (err) {- console.error('[HeterogeneousAgent] Failed to mark subagent thread complete:', err);- }-- completeSubOp(run.subOperationId);-};-/*** Update a tool message's content in DB when tool_result arrives.*@@ -1148,17 +581,36 @@ export const executeHeterogeneousAgent = async (*/const toolMsgIdByCallId: Map<string, string> = new Map();/**- * Per-subagent-spawn runtime state, keyed by the main-agent Task- * tool_use id (`SubagentEventContext.parentToolCallId`). One entry per- * spawn, carrying the Thread id + current in-thread assistant + that- * assistant's per-turn `ToolPersistenceState`. Lazy-created on the- * first subagent event from `persistSubagentToolChunk`.- *- * Lives at executor scope (not on main `toolState`) because- * `toolState` resets on every main-agent step boundary, whereas a- * subagent spawn can emit events before and after a step cut.+ * Shared subagent run coordinator state (the pure reducer in+ * `@lobechat/heterogeneous-agents`). Holds the run map keyed by the+ * main-agent Task tool_use id; the renderer interpreter+ * (`applySubagentIntent`) maps the reducer's intents onto DB writes ++ * live thread-bucket dispatch. Reassigned (commit-on-success) by+ * `reduceAndApplySubagent`. Lives at executor scope because a subagent+ * spawn can emit events before and after a main-agent step cut.*/- const subagentRuns: Map<string, SubagentRunState> = new Map();+ let subagentState: SubagentRunsState = createSubagentRunsState();+ /**+ * Per-thread UI handles the reducer doesn't model: the thread-scoped store+ * dispatcher + its sub-operation id. Created on the `createThread` intent,+ * keyed by threadId, consumed by later intents for the same thread.+ */+ const subagentThreads = new Map<+ string,+ { stream: SubagentStoreDispatcher; subOperationId: string }+ >();+ /**+ * Renderer-local flush retry, keyed by threadId. A `persistContent` whose DB+ * write throws stashes its (pinned messageId + content) here instead of+ * losing the streamed buffer; the next successful `persistContent` for the+ * thread clears it, and `onComplete` replays any survivors. Preserves the+ * old `pendingFlushTarget` resilience without the reducer (which is pure)+ * having to model transient I/O failure.+ */+ const pendingSubagentFlush = new Map<+ string,+ { content?: string; messageId: string; reasoning?: string }+ >();/** Serializes async persist operations so ordering is stable. */let persistQueue: Promise<void> = Promise.resolve();/** Tracks the current assistant message being written to (switches on new steps) */@@ -1213,7 +665,7 @@ export const executeHeterogeneousAgent = async (!!accumulatedReasoning ||toolState.payloads.length > 0 ||toolMsgIdByCallId.size > 0 ||- subagentRuns.size > 0;+ subagentState.runs.size > 0;const clearStaleResumeMetadata = async () => {if (!context.topicId || !updateTopicMetadata) return;@@ -1279,9 +731,9 @@ export const executeHeterogeneousAgent = async (** 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).+ * on the coordinator's `finalizeThread` intent β fired when the spawn's+ * tool_result arrives on main, and again via the `onComplete` orphan drain+ * for any spawn whose tool_result never landed (CLI crash, abort).*/const beginSubagentRun = (threadId: string,@@ -1313,29 +765,276 @@ export const executeHeterogeneousAgent = async (/*** Mark a per-spawn sub-operation completed. Wrapper around- * `completeOperation` so module-level helpers (`finalizeSubagentRun`)- * stay free of store coupling. Idempotent: `completeOperation` on an+ * `completeOperation` so the coordinator interpreter (`finalizeThread`)+ * stays free of store coupling. Idempotent: `completeOperation` on an* already-completed op is a no-op.*/const completeSubagentOp = (subOperationId: string) => {get().completeOperation(subOperationId);};+ // βββ Subagent run coordinator (shared reducer) interpreter βββββββββββββββ+/**- * Look up a subagent run by the tool_call_id of ANY tool inside it β- * across ALL turns of the run, not just the current one. Uses- * `lifetimeToolCallIds` (run-scoped, append-only) rather than- * `state.persistedIds` (turn-scoped, wiped by `ensureSubagentRun` when- * the subagent advances to a new `subagentMessageId`), so a delayed- * `tool_result` arriving after the owning turn has rolled over still- * routes to the right run and clears the in-thread tool bubble's- * loading state.+ * Apply ONE coordinator intent against the renderer's surfaces: DB via+ * `messageService` / `threadService` AND the thread-scoped store dispatcher+ * (so the Thread view streams in step with the DB, exactly as the standalone+ * helpers used to). Best-effort per op (errors logged), mirroring the prior+ * persist helpers.*/- const findRunByInnerToolCallId = (toolCallId: string): SubagentRunState | undefined => {- for (const run of subagentRuns.values()) {- if (run.lifetimeToolCallIds.has(toolCallId)) return run;+ const applySubagentIntent = async (intent: SubagentIntent) => {+ // Narrows `context.topicId` to `string` for every DB write below (the+ // caller already guards, but this function is a separate closure). All+ // subagent rows are topic-scoped.+ if (!context.topicId) return;+ switch (intent.kind) {+ case 'createThread': {+ try {+ await threadService.createThread({+ id: intent.threadId,+ metadata: {+ sourceToolCallId: intent.sourceToolCallId,+ startedAt: new Date().toISOString(),+ subagentType: intent.subagentType,+ },+ sourceMessageId: intent.sourceMessageId,+ status: ThreadStatus.Processing,+ title: intent.title,+ topicId: context.topicId,+ type: ThreadType.Isolation,+ });+ } catch (err) {+ // Rethrow so `reduceAndApplySubagent` skips the state commit β the+ // run stays absent and the next chunk retries the lazy create.+ console.error('[HeterogeneousAgent] Failed to create subagent thread:', err);+ throw err;+ }+ onSubagentThreadCreated();+ // Open the per-spawn sub-op + dispatcher so subsequent intents for this+ // thread route into the Thread's messagesMap bucket.+ subagentThreads.set(intent.threadId, beginSubagentRun(intent.threadId));+ return;+ }++ case 'createMessage': {+ const t = subagentThreads.get(intent.threadId);+ const msg = {+ agentId: intent.agentId ?? undefined,+ content: intent.content,+ id: intent.messageId,+ parentId: intent.parentId,+ role: intent.role,+ threadId: intent.threadId,+ topicId: context.topicId,+ };+ try {+ await messageService.createMessage(msg);+ } catch (err) {+ // Rethrow so `reduceAndApplySubagent` skips the state commit β the+ // run keeps its pre-create shape and the next event re-emits the+ // turn-boundary / lazy-create with fresh ids.+ console.error('[HeterogeneousAgent] Failed to create subagent message:', err);+ throw err;+ }+ t?.stream.create(msg as UIChatMessage);+ return;+ }++ // Live token-level UI only β no DB write (durable content lands via+ // persistContent / persistToolBatch). Mirrors the old text-chunk path.+ case 'streamContent': {+ const t = subagentThreads.get(intent.threadId);+ const value: Partial<UIChatMessage> = {};+ if (intent.content !== undefined) value.content = intent.content;+ if (intent.reasoning !== undefined)+ (value as any).reasoning = { content: intent.reasoning };+ t?.stream.update(intent.messageId, value);+ return;+ }++ case 'persistContent': {+ const t = subagentThreads.get(intent.threadId);+ const update: Record<string, any> = {};+ if (intent.content) update.content = intent.content;+ if (intent.reasoning) update.reasoning = { content: intent.reasoning };+ if (Object.keys(update).length === 0) return;+ try {+ await messageService.updateMessage(intent.messageId, update, {+ agentId: context.agentId,+ topicId: context.topicId,+ });+ // Success drains any prior pending flush for this thread.+ pendingSubagentFlush.delete(intent.threadId);+ t?.stream.update(intent.messageId, update as Partial<UIChatMessage>);+ } catch (err) {+ // Transient failure: stash the buffer pinned to THIS message id so+ // the onComplete replay retries it against the original turn's+ // assistant β never the terminal row the reducer advanced onto.+ console.error('[HeterogeneousAgent] Failed to flush subagent content:', err);+ pendingSubagentFlush.set(intent.threadId, {+ content: intent.content,+ messageId: intent.messageId,+ reasoning: intent.reasoning,+ });+ }+ return;+ }++ case 'persistToolBatch': {+ const t = subagentThreads.get(intent.threadId);+ const buildUpdate = (withResult: boolean): Record<string, any> => {+ const update: Record<string, any> = {+ tools: intent.tools.map((x) =>+ withResult ? { ...x.payload, result_msg_id: x.toolMessageId } : { ...x.payload },+ ),+ };+ if (intent.content) update.content = intent.content;+ if (intent.reasoning) update.reasoning = { content: intent.reasoning };+ return update;+ };++ // Phase 1: pre-register assistant.tools[] (no result_msg_id yet).+ try {+ await messageService.updateMessage(intent.assistantMessageId, buildUpdate(false), {+ agentId: context.agentId,+ topicId: context.topicId,+ });+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to pre-register subagent tools:', err);+ }++ // Phase 2: create rows for new tools with their pre-allocated ids,+ // register the global lookup, and seed the thread bucket bubble.+ for (const x of intent.tools) {+ if (!x.isNew) continue;+ const toolMsg = {+ agentId: context.agentId,+ content: '',+ id: x.toolMessageId,+ parentId: intent.assistantMessageId,+ plugin: {+ apiName: x.payload.apiName,+ arguments: x.payload.arguments,+ identifier: x.payload.identifier,+ type: x.payload.type as ChatToolPayload['type'],+ },+ role: 'tool' as const,+ threadId: intent.threadId,+ tool_call_id: x.payload.id,+ topicId: context.topicId,+ };+ try {+ await messageService.createMessage(toolMsg);+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to create subagent tool message:', err);+ continue;+ }+ toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);+ t?.stream.create(toolMsg as UIChatMessage);+ }++ // Phase 3: backfill result_msg_id on assistant.tools[].+ try {+ await messageService.updateMessage(intent.assistantMessageId, buildUpdate(true), {+ agentId: context.agentId,+ topicId: context.topicId,+ });+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to finalize subagent tools:', err);+ }++ // Surface the live assistant tools[] + content into the thread bucket.+ t?.stream.update(intent.assistantMessageId, buildUpdate(true) as Partial<UIChatMessage>);+ return;+ }++ case 'resolveToolResult': {+ const t = subagentThreads.get(intent.threadId);+ // DB write (via the global tool-message map) + live thread bucket update.+ await persistToolResult(+ intent.toolCallId,+ intent.content,+ intent.isError,+ toolMsgIdByCallId,+ context,+ intent.pluginState,+ );+ const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);+ if (toolMsgId) {+ const update: Partial<UIChatMessage> = { content: intent.content };+ if (intent.pluginState) (update as any).pluginState = intent.pluginState;+ if (intent.isError) (update as any).pluginError = { message: intent.content };+ t?.stream.update(toolMsgId, update);+ }+ return;+ }++ case 'recordUsage': {+ const t = subagentThreads.get(intent.threadId);+ const update = {+ metadata: { usage: intent.usage as any },+ ...(intent.model && { model: intent.model }),+ ...(intent.provider && { provider: intent.provider }),+ };+ t?.stream.update(intent.messageId, update as Partial<UIChatMessage>);+ try {+ await messageService.updateMessage(intent.messageId, update, {+ agentId: context.agentId,+ topicId: context.topicId,+ });+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to record subagent usage:', err);+ }+ return;+ }++ case 'finalizeThread': {+ try {+ await threadService.updateThread(intent.threadId, { status: ThreadStatus.Active });+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to mark subagent thread complete:', err);+ }+ const t = subagentThreads.get(intent.threadId);+ if (t) completeSubagentOp(t.subOperationId);+ return;+ }+ }+ };++ /**+ * Reduce one event through the shared coordinator and apply its intents.+ * `mainAssistantId` is snapshotted at event-arrival time (the spawning main+ * assistant) and threaded in as the thread/seed parent. Commit-on-success:+ * `subagentState` advances only after all intents land β a throwing create+ * intent (createThread / createMessage) skips the commit so the next event+ * re-emits the lazy create / turn boundary, while flush failures are pinned+ * in `pendingSubagentFlush` for the onComplete replay (subsumes the old+ * `pendingFlushTarget`). Always invoked inside `persistQueue` so reduce reads+ * the latest committed state and ordering matches arrival.+ */+ const reduceAndApplySubagent = async (event: AgentStreamEvent, mainAssistantId: string) => {+ // Without a topicId we can't scope a Thread β drop subagent routing+ // silently (non-topic-scoped run / test harness), matching the old guard.+ if (!context.topicId) return;+ const ctx: SubagentReduceCtx = {+ agentId: context.agentId,+ mainAssistantId,+ newId: (kind) => (kind === 'thread' ? generateThreadId() : `msg_${createNanoId(18)()}`),+ topicId: context.topicId ?? null,+ };+ const { state: next, intents } = reduceSubagentRuns(subagentState, event, ctx);+ try {+ for (const intent of intents) await applySubagentIntent(intent);+ } catch (err) {+ // An intent failed to land (e.g. transient IndexedDB / message-service+ // error on createThread / createMessage). Do NOT commit `next`: keeping+ // the prior state lets the next event re-emit the create / flush, and+ // keeps the run visible to the onComplete orphan drain. Swallow here so+ // the rejection doesn't poison the shared persistQueue chain.+ console.error('[HeterogeneousAgent] Subagent intent failed, run state not advanced:', err);+ return;}- return undefined;+ subagentState = next;};try {@@ -1463,68 +1162,41 @@ export const executeHeterogeneousAgent = async (// βββ tool_result: update tool message content in DB (ACP-only) βββif (event.type === 'tool_result') {- const { content, isError, pluginState, toolCallId } = event.data as {+ const { content, isError, pluginState, subagent, toolCallId } = event.data as {content: string;isError?: boolean;pluginState?: Record<string, any>;subagent?: SubagentEventContext;toolCallId: string;};- // Subagent vs main lookup is transparent β one global- // `toolMsgIdByCallId` map spans both scopes.- persistQueue = persistQueue.then(() =>- persistToolResult(- toolCallId,- content,- !!isError,- toolMsgIdByCallId,- context,- 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 β 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 stream 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,- });- });++ // Main tools (including a subagent's parent Task tool, which is+ // main-scoped) get their DB content written here via the global+ // `toolMsgIdByCallId` map. Subagent INNER tool_results are skipped β+ // the coordinator's `resolveToolResult` intent owns their DB write ++ // thread-bucket update (avoids a double write).+ if (!subagent) {+ persistQueue = persistQueue.then(() =>+ persistToolResult(+ toolCallId,+ content,+ !!isError,+ toolMsgIdByCallId,+ context,+ pluginState,+ ),+ );+ }++ // Route through the coordinator: an inner subagent tool_result β+ // resolveToolResult (DB + live thread bucket); a parent-spawn+ // tool_result β finalize (terminal assistant + thread Active); a plain+ // main tool_result β no intents. Queued so earlier subagent chunks in+ // the same batch have registered the run before the parent finalize+ // checks for it.+ const mainAsstId = currentAssistantMessageId;+ persistQueue = persistQueue.then(() => reduceAndApplySubagent(event, mainAsstId));+// Don't forward β the tool_end that follows triggers fetchAndReplaceMessages// which reads the updated content from DB.return;@@ -1543,43 +1215,15 @@ export const executeHeterogeneousAgent = async (// of all prior steps. Sum of turn_metadata equals result_usage for// a healthy run.if (event.type === 'step_complete' && event.data?.phase === 'turn_metadata') {- const subagentCtx = event.data.subagent as SubagentEventContext | undefined;const turnUsage = event.data.usage;- if (subagentCtx) {- // Subagent-tagged usage: write it (plus the subagent's own- // model/provider) onto the subagent's in-thread assistant β NOT the- // main agent's. The chip derives its totals from these per-message- // `usage` snapshots (live + cold-load both aggregate the messages),- // so nothing is tracked on the run. Don't touch the MAIN agent's- // `lastModel` / `lastProvider` β those are main-agent step state and- // would contaminate the next main turn's create.- const turnModel = event.data.model as string | undefined;- const turnProvider = event.data.provider as string | undefined;- if (turnUsage) {- persistQueue = persistQueue.then(async () => {- const run = subagentRuns.get(subagentCtx.parentToolCallId);- if (!run) return;-- const update = {- metadata: { usage: turnUsage },- ...(turnModel && { model: turnModel }),- ...(turnProvider && { provider: turnProvider }),- };- // Mirror the DB write into the thread's local message bucket- // so the inspector chip's live aggregation sees the usage as- // it lands. Without this `run.stream.update`, dbMessagesMap- // only learns the new metadata.usage after the next thread- // refresh β i.e. the chip stays at 0 tokens during streaming.- run.stream.update(run.currentAssistantMsgId, update as Partial<UIChatMessage>);- await messageService- .updateMessage(run.currentAssistantMsgId, update, {- agentId: context.agentId,- topicId: context.topicId,- })- .catch(console.error);- });- }+ // Subagent-tagged usage routes through the coordinator (RecordUsage+ // intent β written onto the subagent's in-thread assistant + thread+ // bucket). It must NOT touch the MAIN agent's `lastModel` /+ // `lastProvider`, which carry main-agent step state.+ if (event.data.subagent) {+ const mainAsstId = currentAssistantMessageId;+ persistQueue = persistQueue.then(() => reduceAndApplySubagent(event, mainAsstId));return;}@@ -1712,76 +1356,29 @@ export const executeHeterogeneousAgent = async (// βββ stream_chunk: accumulate content + persist tool_use βββif (event.type === 'stream_chunk') {const chunk = event.data;- const chunkSubagentCtx = chunk?.subagent as SubagentEventContext | undefined;- if (chunk?.chunkType === 'text' && chunk.content) {- if (chunkSubagentCtx) {- // Subagent text β accumulates on the run's in-thread- // assistant, NOT on the main assistant's content.- const mainAsstId = currentAssistantMessageId;- persistQueue = persistQueue.then(() =>- persistSubagentTextChunk(- 'text',- chunk.content,- chunkSubagentCtx,- mainAsstId,- context,- subagentRuns,- beginSubagentRun,- onSubagentThreadCreated,- ),- );- } else {++ // Subagent-scoped chunks (text / reasoning / tools_calling) route+ // through the shared coordinator β it owns thread create, turn+ // boundaries, tool persistence, and live thread-bucket streaming. Kept+ // off the main path so main-agent snapshot logic stays untouched.+ if (chunk?.subagent) {+ const mainAsstId = currentAssistantMessageId;+ persistQueue = persistQueue.then(() => reduceAndApplySubagent(event, mainAsstId));+ } else {+ if (chunk?.chunkType === 'text' && chunk.content) {accumulatedContent += chunk.content;}- }- if (chunk?.chunkType === 'reasoning' && chunk.reasoning) {- if (chunkSubagentCtx) {- const mainAsstId = currentAssistantMessageId;- persistQueue = persistQueue.then(() =>- persistSubagentTextChunk(- 'reasoning',- chunk.reasoning,- chunkSubagentCtx,- mainAsstId,- context,- subagentRuns,- beginSubagentRun,- onSubagentThreadCreated,- ),- );- } else {+ if (chunk?.chunkType === 'reasoning' && chunk.reasoning) {accumulatedReasoning += chunk.reasoning;}- }- if (chunk?.chunkType === 'tools_calling') {- const tools = chunk.toolsCalling as ToolCallPayload[];- const subagentCtx = chunk.subagent as SubagentEventContext | undefined;- if (tools?.length) {- if (subagentCtx) {- // Subagent chunk β lazy-create Thread + in-thread- // assistant, then persist into that scope. Kept off the- // main path so main-agent snapshot logic stays untouched.- const mainAsstId = currentAssistantMessageId;- persistQueue = persistQueue.then(() =>- persistSubagentToolChunk(- tools,- subagentCtx,- mainAsstId,- context,- subagentRuns,- toolMsgIdByCallId,- beginSubagentRun,- onSubagentThreadCreated,- ),- );- } else {- // Main-agent chunk β existing path.- // Snapshot accumulators sync β must travel with the- // same step's assistantMessageId. A late-bound getter- // would read NEW step's content if a step transition- // lands between scheduling and execution, while- // assistantMessageId would still be the OLD one (also- // captured sync) β cross-step contamination.+ if (chunk?.chunkType === 'tools_calling') {+ const tools = chunk.toolsCalling as ToolCallPayload[];+ if (tools?.length) {+ // Snapshot accumulators sync β must travel with the same step's+ // assistantMessageId. A late-bound getter would read the NEW+ // step's content if a step transition lands between scheduling+ // and execution, while assistantMessageId would still be the OLD+ // one (also captured sync) β cross-step contamination.const snapshot = {content: accumulatedContent,reasoning: accumulatedReasoning,@@ -1864,18 +1461,40 @@ export const executeHeterogeneousAgent = async (// Wait for all tool persistence to finish before writing final stateawait persistQueue.catch(console.error);- // Flush any subagent runs that didn't see their parent's- // tool_result (e.g. CLI crashed mid-subagent, or CC emitted the- // 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({- completeSubOp: completeSubagentOp,- context,- parentToolCallId: parentId,- subagentRuns,- }).catch(console.error);+ // Drain any subagent runs that didn't see their parent's tool_result+ // (e.g. CLI crashed mid-subagent, or CC emitted the spawn's+ // tool_result after the stream closed). The coordinator flushes each+ // run's trailing content and marks the thread Active. Drive it with a+ // synthetic terminal event so the reducer's orphan-drain path runs.+ await reduceAndApplySubagent(+ deferredTerminalEvent ?? {+ data: {},+ operationId,+ stepIndex: 0,+ timestamp: Date.now(),+ type: 'agent_runtime_end',+ },+ currentAssistantMessageId,+ ).catch(console.error);++ // Replay any subagent flush that failed transiently mid-stream, pinned+ // to its original in-thread assistant (NOT the terminal row).+ for (const [threadId, pending] of pendingSubagentFlush) {+ const update: Record<string, any> = {};+ if (pending.content) update.content = pending.content;+ if (pending.reasoning) update.reasoning = { content: pending.reasoning };+ if (Object.keys(update).length === 0) continue;+ try {+ await messageService.updateMessage(pending.messageId, update, {+ agentId: context.agentId,+ topicId: context.topicId,+ });+ subagentThreads.get(threadId)?.stream.update(pending.messageId, update);+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to replay subagent flush:', err);+ }}+ pendingSubagentFlush.clear();// Persist final content + reasoning + model for the last step BEFORE the// terminal event triggers fetchAndReplaceMessages. Usage for this step