π€― 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
π fix(hetero): dedupe subagent thread create on cold replica after finalize (#15849)
Arvin Xuc9c57bb7ba6d
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.tsindex d780a75b425..6ba05eed902 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts@@ -575,9 +575,16 @@ export class HeterogeneousPersistenceHandler {** Merge semantics: only runs MISSING from the in-memory map are rehydrated, so* a warm replica's live per-turn accumulators (`accContent`, current- * `toolState`) are never clobbered by the DB projection. Finalized runs are- * excluded (their thread is `Active`, not `Processing`), so a completed spawn- * is never resurrected.+ * `toolState`) are never clobbered by the DB projection.+ *+ * Finalized (`Active`) spawns are NOT rehydrated as live runs (a completed+ * spawn is never resurrected β that would mint spurious empty assistants and+ * re-finalize churn), but their `sourceToolCallId` IS recorded in+ * `finalizedParents` so a REPLAYED first-event on a cold replica can't fork a+ * duplicate thread for a spawn that already finished (the "δΈζ¨‘δΈζ ·ηδΈ€δΈͺ+ * thread" bug). This mirrors #15838's main-turn idempotency for the subagent+ * thread-create step: dedup keyed by the DB-homed `sourceToolCallId`,+ * independent of in-memory state and of thread status.** Best-effort: any DB hiccup (or a partial test mock without the query* methods) leaves `state.main.subagents` untouched rather than aborting the@@ -588,12 +595,13 @@ export class HeterogeneousPersistenceHandler {const threads = await this.deps.threadModel.queryByTopicId(state.topicId);const existing = state.main.subagents.runs;const snapshots: SubagentRunSnapshot[] = [];+ // Union with any parents finalized in-memory on a warm replica.+ const finalizedParents = new Set(state.main.subagents.finalizedParents);for (const thread of threads ?? []) {if (thread.type !== ThreadType.Isolation) continue;- if (thread.status !== ThreadStatus.Processing) continue;const meta = thread.metadata as { operationId?: string; sourceToolCallId?: string } | null;- // Operation-scoped: only rehydrate threads THIS operation created.+ // Operation-scoped: only attend to threads THIS operation created.// Topics are reused across turns, so a prior run that crashed / was// cancelled without an ingested terminal event can leave its subagent// thread stuck in `Processing`. Without this guard the next operation@@ -605,6 +613,13 @@ export class HeterogeneousPersistenceHandler {const parentToolCallId = meta?.sourceToolCallId;if (!parentToolCallId || existing.has(parentToolCallId)) continue;+ // Finalized spawn β remember the key (blocks duplicate create), don't+ // rehydrate it as a live run.+ if (thread.status !== ThreadStatus.Processing) {+ finalizedParents.add(parentToolCallId);+ continue;+ }+const messages = await this.deps.messageModel.query({threadId: thread.id,topicId: state.topicId,@@ -613,11 +628,20 @@ export class HeterogeneousPersistenceHandler {if (snapshot) snapshots.push(snapshot);}- if (snapshots.length === 0) return;+ // Nothing new to project: no rehydratable runs AND no finalized keys+ // beyond what memory already tracked (the set started as a copy of it and+ // only grows, so an unchanged size means no new Active threads were found).+ if (+ snapshots.length === 0 &&+ finalizedParents.size === state.main.subagents.finalizedParents.size+ ) {+ return;+ }// Union: rehydrated (missing) runs + the in-memory ones (which win, since- // they carry live accumulators the DB hasn't caught up to yet).- const merged = rehydrateSubagentRunsState(snapshots);+ // they carry live accumulators the DB hasn't caught up to yet) + the+ // finalized-parent guard set.+ const merged = rehydrateSubagentRunsState(snapshots, [...finalizedParents]);for (const [parentToolCallId, run] of existing) merged.runs.set(parentToolCallId, run);state.main = { ...state.main, subagents: merged };} catch (err) {diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.tsindex de52e34ed06..ff6553374d6 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts@@ -274,6 +274,66 @@ describe('HeterogeneousPersistenceHandler β subagent run survives a cold repliexpect([...h.threads.values()].some((t) => t.title === 'Subagent')).toBe(false);});+ // The screenshot bug: a subagent that already FINISHED (its parent+ // tool_result landed β thread flipped Active) has its FIRST event replayed on+ // a cold replica (BatchIngester retry / re-delivery where the in-memory+ // `processedKeys` dedupe is gone). Because finalized threads aren't rehydrated+ // as live runs, the empty reducer used to hit `!existing` and fork a SECOND+ // thread with the identical title ("δΈζ¨‘δΈζ ·ηδΈ€δΈͺ thread"). The fix records+ // the finalized parent's `sourceToolCallId` in `finalizedParents` from the DB+ // `Active` thread, so the replayed first-event is a stale no-op.+ it('does NOT re-create the thread when a FINISHED subagent replays its first event on a fresh replica', async () => {+ const h = createHarness({+ assistantMessageId: 'asst-1',+ operationId: 'op-1',+ topicId: 'topic-1',+ });+ const PARENT = 'tc-spawn-1';++ const firstChunk = buildEvent('stream_chunk', 0, {+ chunkType: 'tools_calling',+ subagent: {+ parentToolCallId: PARENT,+ spawnMetadata: {+ description: 'Map client runtime completion paths',+ prompt: 'investigate',+ subagentType: 'Explore',+ },+ subagentMessageId: 'sub-msg-1',+ },+ toolsCalling: [innerTool('inner-1')],+ });++ // ββ Batch 1 (replica A): subagent runs, then its parent tool_result lands β+ // the run finalizes and the thread is flipped Active. ββ+ await h.handler.ingest({+ assistantMessageId: 'asst-1',+ events: [firstChunk, buildEvent('tool_result', 1, { content: 'done', toolCallId: PARENT })],+ operationId: 'op-1',+ topicId: 'topic-1',+ });++ expect(h.threads.size).toBe(1);+ const finishedThreadId = [...h.threads.keys()][0];+ expect(h.threads.get(finishedThreadId)!.status).toBe('active');++ // ββ Cold replica: warm state gone, DB persists. ββ+ __resetOperationStatesForTesting();++ // ββ Replay of the SAME first event (processedKeys is empty on the fresh+ // replica, so it is NOT deduped away β it really re-enters the reducer). ββ+ await h.handler.ingest({+ assistantMessageId: 'asst-1',+ events: [firstChunk],+ operationId: 'op-1',+ topicId: 'topic-1',+ });++ // Still exactly one thread β no duplicate, no second "Map client runtimeβ¦".+ expect(h.threads.size).toBe(1);+ expect([...h.threads.keys()]).toEqual([finishedThreadId]);+ });+// P1: a tools_calling batch reprocessed on a cold replica (BatchIngester// retry, or a turn split across a cold boundary so the cumulative array is// re-seen) must NOT mint a second tool message for an inner tool the rundiff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.tsindex aaa7296517f..81205aeccd4 100644--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts@@ -236,6 +236,24 @@ describe('subagent reducer', () => {expect(state.runs.has('task-1')).toBe(false); // deleted});+ it('does NOT re-create the thread when a finalized spawn replays its first event', () => {+ // Finalize via the parent tool_result, then replay the SAME first chunk a+ // cold-replica retry / double IPC delivery would resend. `ensureRun` must+ // treat the already-finalized parent as a stale no-op β no second thread.+ const { steps, state } = run([+ textEvent('task-1', 'm1', 'working', { description: 'Map client runtime' }),+ { data: { content: 'answer', toolCallId: 'task-1' }, type: 'tool_result' }, // finalize+ // β exact replay of the very first subagent chunk for task-1+ textEvent('task-1', 'm1', 'working', { description: 'Map client runtime' }),+ ]);++ // The replay produces NO intents (no createThread, no createMessage).+ expect(steps[2]).toEqual([]);+ // Run stays deleted; the parent is remembered as finalized.+ expect(state.runs.has('task-1')).toBe(false);+ expect(state.finalizedParents.has('task-1')).toBe(true);+ });+it('records subagent usage onto the current assistant', () => {const usage = { totalTokens: 42 };const { steps } = run([diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.tsindex 88c39f4d594..4aa953c594d 100644--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts@@ -60,13 +60,25 @@ const withRun = (): SubagentRunsState => {const runs = new Map(state.runs);runs.set(parentToolCallId, run);- return { runs };+ return { ...state, runs };};-const withoutRun = (state: SubagentRunsState, parentToolCallId: string): SubagentRunsState => {+/**+ * Finalize bookkeeping: drop the live run AND remember its `parentToolCallId` in+ * `finalizedParents` so a replayed first-event never re-creates the (now+ * `Active`) thread. The remembered set is what makes thread creation idempotent+ * across cold-replica retries / double IPC delivery β keyed by the DB-homed+ * `sourceToolCallId`, independent of whether the live `runs` map still holds it.+ */+const markRunFinalized = (+ state: SubagentRunsState,+ parentToolCallId: string,+): SubagentRunsState => {const runs = new Map(state.runs);runs.delete(parentToolCallId);- return { runs };+ const finalizedParents = new Set(state.finalizedParents);+ finalizedParents.add(parentToolCallId);+ return { ...state, finalizedParents, runs };};const SUBAGENT_TITLE_MAX = 80;@@ -82,15 +94,24 @@ interface ReduceResult {* 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.+ *+ * Returns `run: null` when the parent already FINALIZED (its thread is `Active`,+ * tracked in `finalizedParents`): the event is a stale replay of a completed+ * spawn β re-creating its thread would duplicate it. The caller drops the event.*/const ensureRun = (state: SubagentRunsState,subCtx: SubagentEventContext,ctx: SubagentReduceCtx,-): { intents: SubagentIntent[]; run: SubagentRun; state: SubagentRunsState } => {+): { intents: SubagentIntent[]; run: SubagentRun | null; state: SubagentRunsState } => {const intents: SubagentIntent[] = [];const existing = state.runs.get(subCtx.parentToolCallId);+ // βββ Stale replay of an already-finalized spawn β no-op (no duplicate thread) βββ+ if (!existing && state.finalizedParents.has(subCtx.parentToolCallId)) {+ return { intents, run: null, state };+ }+// βββ First event for this parent β lazy-create Thread + seed + assistant βββif (!existing) {const threadId = ctx.newId('thread');@@ -235,7 +256,7 @@ const finalizeRun = (intents.push({ kind: 'finalizeThread', threadId: run.threadId });- return { intents, state: withoutRun(state, parentToolCallId) };+ return { intents, state: markRunFinalized(state, parentToolCallId) };};/** Find the run that owns an inner tool_call id (lifetime lookup). */@@ -259,6 +280,8 @@ const reduceTextChunk = (const ensured = ensureRun(state, subCtx, ctx);const run = ensured.run;const intents = ensured.intents;+ // Stale replay of a finalized spawn β drop without re-creating its thread.+ if (!run) return { intents, state: ensured.state };if (kind === 'text') run.accContent += chunk;else run.accReasoning += chunk;@@ -282,6 +305,8 @@ const reduceToolsChunk = (const ensured = ensureRun(state, subCtx, ctx);const run = ensured.run;const intents = ensured.intents;+ // Stale replay of a finalized spawn β drop without re-creating its thread.+ if (!run) return { intents, state: ensured.state };const newToolMsgIds: string[] = [];for (const tool of tools) {diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts b/packages/heterogeneous-agents/src/subagentCoordinator/types.tsindex 06411babb9c..941af9911cd 100644--- a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts+++ b/packages/heterogeneous-agents/src/subagentCoordinator/types.ts@@ -71,11 +71,23 @@ export interface SubagentRun {}export interface SubagentRunsState {+ /**+ * `parentToolCallId`s whose subagent already FINALIZED (thread is `Active`).+ * The run itself is deleted from `runs` on finalize, but the parent is+ * remembered here so a REPLAYED first-event (cold-replica retry, double IPC+ * delivery) does NOT fork a brand-new duplicate thread for a spawn that is+ * already done. Distinct from `runs` on purpose: finalized spawns must block+ * re-creation WITHOUT being resurrected into the live turn machinery (which+ * would mint spurious empty assistants / re-finalize churn). Survives turn+ * boundaries; on the server it is reseeded from DB `Active` isolation threads.+ */+ finalizedParents: Set<string>;/** Active subagent runs, keyed by `parentToolCallId`. */runs: Map<string, SubagentRun>;}export const createSubagentRunsState = (): SubagentRunsState => ({+ finalizedParents: new Set(),runs: new Map(),});@@ -124,8 +136,16 @@ export interface SubagentRunSnapshot {* instead of forking a new one. `accContent` / `accReasoning` / per-turn* `toolState` start empty β the next turn boundary opens a fresh in-thread* assistant, and inner tool_results still resolve through `lifetimeToolCallIds`.+ *+ * `finalizedParentToolCallIds` seeds {@link SubagentRunsState.finalizedParents}+ * β `parentToolCallId`s whose thread already finalized (`Active`). These are NOT+ * live runs (a completed spawn is never resurrected); they only block a replayed+ * first-event from forking a duplicate thread on a cold replica.*/-export const rehydrateSubagentRunsState = (snapshots: SubagentRunSnapshot[]): SubagentRunsState => {+export const rehydrateSubagentRunsState = (+ snapshots: SubagentRunSnapshot[],+ finalizedParentToolCallIds: string[] = [],+): SubagentRunsState => {const runs = new Map<string, SubagentRun>();for (const s of snapshots) {runs.set(s.parentToolCallId, {@@ -139,7 +159,7 @@ export const rehydrateSubagentRunsState = (snapshots: SubagentRunSnapshot[]): SutoolState: { payloads: [], persistedIds: new Set(), toolMsgIdByCallId: new Map() },});}- return { runs };+ return { finalizedParents: new Set(finalizedParentToolCallIds), runs };};// βββ Reduce context (per event) βββ