Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(hetero): keep subagent threads linear across replicas and resumable after finalize (#21917)

AmAzing-b270b42b43c3
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts
index 76f909e8713..1e529bf6bf3 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts
@@ -386,5 +386,10 @@ export async function applySubagentIntent(
await deps.threadModel.update(intent.threadId, { status: ThreadStatus.Active });
return;
}
+
+ case 'reopenThread': {
+ await deps.threadModel.update(intent.threadId, { status: ThreadStatus.Processing });
+ return;
+ }
}
}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts
index 61fcfbf796d..0a9ef177026 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts
@@ -3,6 +3,7 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { __resetOperationStatesForTesting, HeterogeneousPersistenceHandler } from '.';
+import { operationStates } from './operationState';
/**
* Regression for the SERVER-ONLY "ε€§ι‡ζ— ζ„δΉ‰ηš„ SubAgent" bug.
@@ -506,3 +507,203 @@ describe('HeterogeneousPersistenceHandler β€” subagent run survives a cold repli
expect(new Set(toolRows.map((m) => m.parentId))).toEqual(new Set([assistants[0].id]));
});
});
+
+/**
+ * Regression for a production subagent thread whose assistants forked into
+ * four branches, so the thread panel followed a branch with no text.
+ *
+ * Root cause: a WARM replica that handled an earlier batch keeps the run in
+ * memory, and the in-memory copy used to win over the DB. When a later batch
+ * landed on it after another replica had advanced the thread, its stale
+ * `lastChainParentId` parented the next assistant onto an old node.
+ *
+ * Each replica gets its own `operationStates` contents; the DB is shared.
+ */
+describe('HeterogeneousPersistenceHandler β€” subagent run across warm replicas', () => {
+ const PARENT = 'tc-spawn-1';
+ const replicas = {
+ a: new Map<string, any>(),
+ b: new Map<string, any>(),
+ c: new Map<string, any>(),
+ };
+
+ beforeEach(() => {
+ __resetOperationStatesForTesting();
+ for (const replica of Object.values(replicas)) replica.clear();
+ });
+ afterEach(() => __resetOperationStatesForTesting());
+
+ const ingestOn = async (
+ h: ReturnType<typeof createHarness>,
+ replica: keyof typeof replicas,
+ events: AgentStreamEvent[],
+ ) => {
+ const memory = replicas[replica];
+ operationStates.clear();
+ for (const [key, value] of memory) operationStates.set(key, value);
+ try {
+ await h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ } finally {
+ memory.clear();
+ for (const [key, value] of operationStates) memory.set(key, value);
+ }
+ };
+
+ const subTools = (stepIndex: number, turnId: string, toolIds: string[], spawn = false) =>
+ buildEvent('stream_chunk', stepIndex, {
+ chunkType: 'tools_calling',
+ subagent: {
+ parentToolCallId: PARENT,
+ ...(spawn ? { spawnMetadata: { prompt: 'go', subagentType: 'Explore' } } : {}),
+ subagentMessageId: turnId,
+ },
+ toolsCalling: toolIds.map(innerTool),
+ });
+
+ const subText = (stepIndex: number, turnId: string, content: string) =>
+ buildEvent('stream_chunk', stepIndex, {
+ chunkType: 'text',
+ content,
+ subagent: { parentToolCallId: PARENT, subagentMessageId: turnId },
+ });
+
+ const threadAssistants = (h: ReturnType<typeof createHarness>) => {
+ const threadId = [...h.threads.keys()][0];
+ return [...h.messages.values()].filter(
+ (m) => m.role === 'assistant' && m.threadId === threadId,
+ );
+ };
+
+ /** Every assistant after the first must chain off the one before it. */
+ const expectLinearChain = (h: ReturnType<typeof createHarness>) => {
+ const assistants = threadAssistants(h);
+ for (let i = 1; i < assistants.length; i++) {
+ expect(assistants[i].parentId).toBe(assistants[i - 1].id);
+ }
+ };
+
+ it('chains a new turn off the thread tail when a stale warm replica handles it', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await ingestOn(h, 'a', [subTools(0, 'm1', ['t1'], true)]);
+ await ingestOn(h, 'b', [subTools(0, 'm2', ['t2'])]);
+ // Replica A still holds the run as of m1 in memory.
+ await ingestOn(h, 'a', [subTools(0, 'm3', ['t3'])]);
+ await ingestOn(h, 'b', [subTools(0, 'm4', ['t4'])]);
+
+ expect(h.threads.size).toBe(1);
+ expect(threadAssistants(h)).toHaveLength(4);
+ expectLinearChain(h);
+ });
+
+ it('keeps text a turn wrote on another replica when the turn continues', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await ingestOn(h, 'a', [subTools(0, 'm1', ['t1'], true)]);
+ await ingestOn(h, 'a', [subText(0, 'm2', 'hello ')]);
+ await ingestOn(h, 'b', [subText(0, 'm2', 'world')]);
+ await ingestOn(h, 'a', [subText(0, 'm2', '!')]);
+
+ const assistants = threadAssistants(h);
+ expect(assistants).toHaveLength(2);
+ expect(assistants[1].content).toBe('hello world!');
+ });
+
+ it('keeps tools a turn persisted on another replica when the turn continues', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await ingestOn(h, 'a', [subTools(0, 'm1', ['t1'], true)]);
+ // CC re-sends the turn's cumulative tool list.
+ await ingestOn(h, 'b', [subTools(0, 'm1', ['t1', 't2'])]);
+
+ const assistants = threadAssistants(h);
+ expect(assistants).toHaveLength(1);
+ expect(assistants[0].tools?.map((t: any) => t.id)).toEqual(['t1', 't2']);
+ });
+
+ it('resumes a finalized subagent on a stale warm replica after the tail', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await ingestOn(h, 'a', [subTools(0, 'm1', ['t1'], true)]);
+ await ingestOn(h, 'b', [
+ subTools(0, 'm2', ['t2']),
+ buildEvent('tool_result', 0, { content: 'plan ready', toolCallId: PARENT }),
+ ]);
+ const threadId = [...h.threads.keys()][0];
+ expect(h.threads.get(threadId)!.status).toBe('active');
+
+ // SendMessage resumed the subagent; replica A still holds the m1 run.
+ await ingestOn(h, 'a', [subTools(1, 'm3', ['t3'])]);
+ await ingestOn(h, 'b', [subTools(1, 'm4', ['t4'])]);
+
+ const assistants = threadAssistants(h);
+ expect(assistants.map((m) => m.content)).toContain('plan ready');
+ expect(assistants).toHaveLength(5); // m1, m2, hand-back, m3, m4
+ expectLinearChain(h);
+ expect(h.threads.get(threadId)!.status).toBe('processing');
+ });
+
+ it('resumes a finalized subagent on a cold replica but ignores replays of its turns', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await ingestOn(h, 'a', [
+ subTools(0, 'm1', ['t1'], true),
+ buildEvent('tool_result', 0, { content: 'plan ready', toolCallId: PARENT }),
+ ]);
+ // Cold replica C: a replayed old turn, then the resumed turn.
+ await ingestOn(h, 'c', [subTools(0, 'm1', ['t1'], true)]);
+ expect(threadAssistants(h)).toHaveLength(2);
+
+ await ingestOn(h, 'c', [subTools(1, 'm2', ['t2'])]);
+
+ expect(h.threads.size).toBe(1);
+ expect(threadAssistants(h)).toHaveLength(3);
+ expectLinearChain(h);
+ const toolRows = [...h.messages.values()].filter((m) => m.role === 'tool');
+ expect(toolRows.map((m) => m.tool_call_id)).toEqual(['t1', 't2']);
+ });
+
+ it('finalizes a resumed run on the terminal drain', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await ingestOn(h, 'a', [
+ subTools(0, 'm1', ['t1'], true),
+ buildEvent('tool_result', 0, { content: 'plan ready', toolCallId: PARENT }),
+ ]);
+ await ingestOn(h, 'b', [subText(1, 'm2', 'evidence captured')]);
+ await ingestOn(h, 'a', [buildEvent('agent_runtime_end', 2, {})]);
+
+ const threadId = [...h.threads.keys()][0];
+ expect(h.threads.get(threadId)!.status).toBe('active');
+ expect(threadAssistants(h).at(-1)!.content).toBe('evidence captured');
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
index 1d4fc1a4460..1826c6800f6 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
@@ -40,6 +40,16 @@ const opensSignalTurn = (event: AgentStreamEvent): boolean =>
const isMainStreamStart = (event: AgentStreamEvent): boolean =>
event.type === 'stream_start' && getEventScope(event).kind === 'main';
+/** `parentToolCallId`s of the subagent runs a batch writes to. */
+const subagentParentsOf = (events: AgentStreamEvent[]): Set<string> => {
+ const parents = new Set<string>();
+ for (const event of events) {
+ const scope = getEventScope(event);
+ if (scope.kind === 'subagent') parents.add(scope.ctx.parentToolCallId);
+ }
+ return parents;
+};
+
/** The raw text a CLI would have echoed into the answer for this failure. */
const errorEchoText = (error: { body?: Record<string, unknown>; message?: string }): string => {
const body = error.body ?? {};
@@ -123,9 +133,11 @@ export class HeterogeneousPersistenceHandler {
await syncAssistantPointerForAdvancedStep(this.deps, state);
}
+ const subagentParents = subagentParentsOf(params.events);
+
await refreshToolMessageIndex(this.deps, state);
await refreshMainStateFromDb(this.deps, state);
- await refreshSubagentRunsFromDb(this.deps, state);
+ await refreshSubagentRunsFromDb(this.deps, state, subagentParents);
// Only a batch that opens a signal turn needs the tool anchor; skip the
// lookup for the rest.
if (params.events.some(opensSignalTurn)) {
@@ -155,6 +167,7 @@ export class HeterogeneousPersistenceHandler {
// picking up this operation always sees the latest content in the DB,
// even if it never processes a step boundary or terminal event.
await this.flushBatchContent(state);
+ await this.flushSubagentContent(state, subagentParents);
}
/**
@@ -427,4 +440,20 @@ export class HeterogeneousPersistenceHandler {
};
await this.deps.messageModel.update(state.main.currentAssistantId, update);
}
+
+ /**
+ * Subagent counterpart of {@link flushBatchContent}, limited to the runs this
+ * batch wrote to. Without it, a turn whose text spans replicas loses the part
+ * the earlier replica only held in memory.
+ */
+ private async flushSubagentContent(state: OperationState, parents: Set<string>): Promise<void> {
+ for (const parentToolCallId of parents) {
+ const run = state.main.subagents.runs.get(parentToolCallId);
+ if (!run || (!run.accContent && !run.accReasoning)) continue;
+ const update: Record<string, any> = {};
+ if (run.accContent) update.content = run.accContent;
+ if (run.accReasoning) update.reasoning = { content: run.accReasoning };
+ await this.deps.messageModel.update(run.currentAssistantId, update);
+ }
+ }
}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
index bb92c136cbc..ea51dca2cdf 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
@@ -6,12 +6,16 @@ import { LOADING_FLAT } from '@lobechat/const';
import type {
MainAgentInterventionTransition,
MainAgentTurnToolState,
- SubagentRunSnapshot,
+ SubagentRun,
+ SubagentThreadMessage,
ToolCallPayload,
} from '@lobechat/heterogeneous-agents';
import {
+ buildFinalizedSubagentRunSnapshot,
+ buildSubagentRunSnapshot,
createMainAgentRunState,
- rehydrateSubagentRunsState,
+ restoreFinalizedSubagentRun,
+ restoreSubagentRun,
} from '@lobechat/heterogeneous-agents';
import { type ChatToolPayload, ThreadStatus, ThreadType } from '@lobechat/types';
import debug from 'debug';
@@ -455,28 +459,44 @@ export async function recoverLastToolMessageFromDb(
}
}
+async function loadThreadMessages(
+ deps: HeterogeneousPersistenceHandlerDeps,
+ state: OperationState,
+ threadId: string,
+): Promise<SubagentThreadMessage[]> {
+ return (await deps.messageModel.query({
+ threadId,
+ topicId: state.topicId,
+ })) as SubagentThreadMessage[];
+}
+
/**
- * Rebuild the in-flight subagent runs (`state.main.subagents`) from DB.
+ * Reconcile the subagent runs (`state.main.subagents`) with the DB before a
+ * batch is reduced. The DB decides where each thread ends; memory only keeps
+ * the accumulators of a turn that is still the thread's tail.
+ *
+ * Serverless replicas each hold their own `operationStates`, and batches of one
+ * run spread across them. Three cases follow:
*
- * The shared reducer keys runs by `parentToolCallId` and only lazy-creates a
- * thread when the run is ABSENT from this map. On a cold serverless replica
- * `createMainAgentRunState` seeds an empty map, so a subagent event whose
- * thread already exists (created by an earlier batch / another replica) would
- * fork a brand-new thread β€” the "ε€§ι‡ζ— ζ„δΉ‰ηš„ Subagent" bug. `refreshMainStateFromDb`
- * rebuilds the main-agent half; this rebuilds the subagent half the same way.
+ * - Cold replica (run missing): the reducer would hit `!existing` and fork a
+ * brand-new thread β€” the "ε€§ι‡ζ— ζ„δΉ‰ηš„ Subagent" bug. Rebuild the run.
+ * - Warm replica behind the thread's tail (another replica opened newer
+ * turns): its stale `lastChainParentId` would parent the next turn onto an
+ * old node and fork the chain. Rebuild the run.
+ * - Warm replica still at the tail: keep its accumulators, but adopt text
+ * another replica appended to this same turn.
*
- * 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.
+ * Rebuilt runs restore the in-flight turn's text and tools too, so a
+ * continuation appends to them instead of replacing them.
*
- * 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.
+ * Finalized (`Active`) spawns are never live runs (resurrecting one would mint
+ * spurious empty assistants and re-finalize churn), and a warm copy of one is
+ * dropped. Their `sourceToolCallId` IS recorded in `finalizedParents` so a
+ * REPLAYED first-event can't fork a duplicate thread (the "δΈ€ζ¨‘δΈ€ζ ·ηš„δΈ€δΈͺ
+ * thread" bug) β€” dedup keyed by the DB-homed `sourceToolCallId`, independent
+ * of in-memory state. When the batch carries events for a finalized parent
+ * (`referencedParents`), its resume anchor is rebuilt from the thread so a
+ * subagent woken by `SendMessage` continues the thread from its tail.
*
* Best-effort: any DB hiccup (or a partial test mock without the query
* methods) leaves `state.main.subagents` untouched rather than aborting the
@@ -485,13 +505,13 @@ export async function recoverLastToolMessageFromDb(
export async function refreshSubagentRunsFromDb(
deps: HeterogeneousPersistenceHandlerDeps,
state: OperationState,
+ referencedParents: ReadonlySet<string> = new Set(),
): Promise<void> {
try {
const threads = await 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 runs = new Map(state.main.subagents.runs);
const finalizedParents = new Set(state.main.subagents.finalizedParents);
+ const finalizedRuns = new Map(state.main.subagents.finalizedRuns);
for (const thread of threads ?? []) {
if (thread.type !== ThreadType.Isolation) continue;
@@ -506,85 +526,63 @@ export async function refreshSubagentRunsFromDb(
// can't attribute them, and the live run re-creates what it needs).
if (meta?.operationId !== state.operationId) continue;
const parentToolCallId = meta?.sourceToolCallId;
- if (!parentToolCallId || existing.has(parentToolCallId)) continue;
+ if (!parentToolCallId) continue;
- // Finalized spawn β†’ remember the key (blocks duplicate create), don't
- // rehydrate it as a live run.
if (thread.status !== ThreadStatus.Processing) {
+ runs.delete(parentToolCallId);
finalizedParents.add(parentToolCallId);
+ if (referencedParents.has(parentToolCallId)) {
+ const messages = await loadThreadMessages(deps, state, thread.id);
+ const anchor = buildFinalizedSubagentRunSnapshot(parentToolCallId, thread.id, messages);
+ if (anchor) finalizedRuns.set(parentToolCallId, restoreFinalizedSubagentRun(anchor));
+ }
continue;
}
- const messages = await deps.messageModel.query({
+ // Processing β€” possibly reopened by another replica since this one finalized it.
+ finalizedParents.delete(parentToolCallId);
+ finalizedRuns.delete(parentToolCallId);
+
+ const run = runs.get(parentToolCallId);
+ const tailId = await deps.messageModel.getLatestSpineMessageId({
threadId: thread.id,
topicId: state.topicId,
});
- const snapshot = buildSubagentSnapshot(parentToolCallId, thread.id, messages);
- if (snapshot) snapshots.push(snapshot);
- }
+ if (run && tailId === run.currentAssistantId) {
+ const tail = (await deps.messageModel.findById(tailId)) as
+ SubagentThreadMessage | undefined;
+ runs.set(parentToolCallId, adoptPersistedTurnText(run, tail));
+ continue;
+ }
- // 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;
+ const messages = await loadThreadMessages(deps, state, thread.id);
+ const snapshot = buildSubagentRunSnapshot(parentToolCallId, thread.id, messages);
+ if (snapshot) runs.set(parentToolCallId, restoreSubagentRun(snapshot));
}
- // Union: rehydrated (missing) runs + the in-memory ones (which win, since
- // 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 };
+ state.main = { ...state.main, subagents: { finalizedParents, finalizedRuns, runs } };
} catch (err) {
log('refreshSubagentRunsFromDb failed op=%s err=%O', state.operationId, err);
}
}
/**
- * Reconstruct one {@link SubagentRunSnapshot} from a thread's persisted
- * messages (ordered `createdAt` asc by the query). Returns undefined when the
- * thread has no assistant yet β€” without one there is nothing to attach a
- * continuation turn to, and the first-event path will (correctly) seed it.
+ * Subagent text arrives as deltas, so a longer persisted text means another
+ * replica appended to this turn after this replica last saw it.
*/
-function buildSubagentSnapshot(
- parentToolCallId: string,
- threadId: string,
- messages: Array<{
- id: string;
- metadata?: Record<string, any> | null;
- parentId?: string | null;
- role: string;
- tool_call_id?: string;
- }>,
-): SubagentRunSnapshot | undefined {
- const assistants = messages.filter((m) => m.role === 'assistant');
- const currentAssistant = assistants.at(-1);
- if (!currentAssistant) return undefined;
-
- const toolRows = messages.filter((m) => m.role === 'tool' && m.tool_call_id);
- // Chain rule: the next turn's assistant parents off the
- // prior assistant (the spine), not its last child tool β€” recover the anchor
- // as the current assistant itself (matches the subagent reducer, and is
- // fork-resistant since it reads the thread's real latest assistant from DB).
- const lastChainParentId = currentAssistant.id;
- // Recover the in-flight turn's CC message.id so a continuation event is
- // recognized as the SAME turn (no spurious boundary β†’ no fragmentation).
- const currentSubagentMessageId =
- typeof currentAssistant.metadata?.subagentMessageId === 'string'
- ? currentAssistant.metadata.subagentMessageId
- : undefined;
-
+function adoptPersistedTurnText(
+ run: SubagentRun,
+ tail: SubagentThreadMessage | undefined,
+): SubagentRun {
+ const content = tail?.content ?? '';
+ const reasoning = tail?.reasoning?.content ?? '';
+ if (content.length <= run.accContent.length && reasoning.length <= run.accReasoning.length) {
+ return run;
+ }
return {
- currentAssistantId: currentAssistant.id,
- currentSubagentMessageId,
- lastChainParentId,
- lifetimeToolCallIds: toolRows.map((m) => m.tool_call_id!),
- parentToolCallId,
- threadId,
+ ...run,
+ accContent: content.length > run.accContent.length ? content : run.accContent,
+ accReasoning: reasoning.length > run.accReasoning.length ? reasoning : run.accReasoning,
};
}
diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.ts
index 535bc69a9e4..1a561e1162d 100644
--- a/packages/heterogeneous-agents/src/index.ts
+++ b/packages/heterogeneous-agents/src/index.ts
@@ -129,25 +129,33 @@ export type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './
export type {
CreateMessageIntent,
CreateThreadIntent,
+ FinalizedSubagentRunSnapshot,
FinalizeThreadIntent,
PersistContentIntent,
PersistToolBatchEntry,
PersistToolBatchIntent,
RecordUsageIntent,
+ ReopenThreadIntent,
ResolveToolResultIntent,
StreamContentIntent,
SubagentIntent,
SubagentReduceCtx,
+ SubagentRun,
SubagentRunSnapshot,
SubagentRunsState,
+ SubagentThreadMessage,
UpdateToolStateIntent,
} from './subagentCoordinator';
export {
+ buildFinalizedSubagentRunSnapshot,
+ buildSubagentRunSnapshot,
createSubagentRunsState,
type EventScope,
getEventScope,
reduceSubagentRuns,
rehydrateSubagentRunsState,
+ restoreFinalizedSubagentRun,
+ restoreSubagentRun,
} from './subagentCoordinator';
export type {
AgentEventAdapter,
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/index.ts b/packages/heterogeneous-agents/src/subagentCoordinator/index.ts
index 1f1d9489133..aa11f5006b3 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/index.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/index.ts
@@ -1,13 +1,21 @@
export { type EventScope, getEventScope } from './getEventScope';
export { reduce as reduceSubagentRuns } from './reducer';
+export {
+ buildFinalizedSubagentRunSnapshot,
+ buildSubagentRunSnapshot,
+ type SubagentThreadMessage,
+} from './snapshot';
export type {
CreateMessageIntent,
CreateThreadIntent,
+ FinalizedSubagentRun,
+ FinalizedSubagentRunSnapshot,
FinalizeThreadIntent,
PersistContentIntent,
PersistToolBatchEntry,
PersistToolBatchIntent,
RecordUsageIntent,
+ ReopenThreadIntent,
ResolveToolResultIntent,
StreamContentIntent,
SubagentIntent,
@@ -18,4 +26,9 @@ export type {
SubagentTurnToolState,
UpdateToolStateIntent,
} from './types';
-export { createSubagentRunsState, rehydrateSubagentRunsState } from './types';
+export {
+ createSubagentRunsState,
+ rehydrateSubagentRunsState,
+ restoreFinalizedSubagentRun,
+ restoreSubagentRun,
+} from './types';
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
index e973964a8d2..d1f8409c6cf 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
-import { createSubagentRunsState, reduceSubagentRuns } from './index';
-import type { SubagentIntent, SubagentReduceCtx } from './types';
+import { createSubagentRunsState, reduceSubagentRuns, rehydrateSubagentRunsState } from './index';
+import type { PersistToolBatchIntent, SubagentIntent, SubagentReduceCtx } from './types';
/** Deterministic id factory: `thd_1`, `msg_1`, `msg_2`, … per kind. */
const makeCtx = (over: Partial<SubagentReduceCtx> = {}): SubagentReduceCtx => {
@@ -291,6 +291,141 @@ describe('subagent reducer', () => {
expect(state.finalizedParents.has('task-1')).toBe(true);
});
+ it('reopens a finalized thread when the subagent resumes with a NEW turn', () => {
+ // CC `SendMessage` resumes a completed subagent; its events keep the
+ // original `parent_tool_use_id`. The new turn must continue the existing
+ // thread from its tail, not be dropped as a stale replay.
+ const { steps, state } = run([
+ textEvent('task-1', 'm1', 'working'),
+ toolsEvent('task-1', 'm1', [tool('tc-1')]),
+ { data: { content: 'answer', toolCallId: 'task-1' }, type: 'tool_result' }, // finalize
+ toolsEvent('task-1', 'm2', [tool('tc-2')]),
+ ]);
+
+ // seed msg_1, assistant msg_2, tool msg_3, hand-back msg_4
+ expect(kinds(steps[3])).toEqual(['reopenThread', 'createMessage', 'persistToolBatch']);
+ expect(steps[3][0]).toMatchObject({ threadId: 'thd_1' });
+ expect(steps[3][1]).toMatchObject({
+ messageId: 'msg_5',
+ parentId: 'msg_4',
+ role: 'assistant',
+ subagentMessageId: 'm2',
+ threadId: 'thd_1',
+ });
+ expect(state.runs.get('task-1')).toMatchObject({
+ currentAssistantId: 'msg_5',
+ currentSubagentMessageId: 'm2',
+ threadId: 'thd_1',
+ });
+ expect(state.finalizedParents.has('task-1')).toBe(false);
+ });
+
+ it('keeps dropping a replay of a turn the finalized thread already holds', () => {
+ const { steps, state } = run([
+ textEvent('task-1', 'm1', 'working'),
+ toolsEvent('task-1', 'm2', [tool('tc-1')]),
+ { data: { content: 'answer', toolCallId: 'task-1' }, type: 'tool_result' }, // finalize
+ // ↓ replays of both earlier turns
+ textEvent('task-1', 'm1', 'working'),
+ toolsEvent('task-1', 'm2', [tool('tc-1')]),
+ ]);
+
+ expect(steps[3]).toEqual([]);
+ expect(steps[4]).toEqual([]);
+ expect(state.runs.has('task-1')).toBe(false);
+ expect(state.finalizedParents.has('task-1')).toBe(true);
+ });
+
+ it('re-finalizes a resumed run and remembers its resumed turns', () => {
+ const { steps, state } = run([
+ textEvent('task-1', 'm1', 'working'),
+ { data: { content: 'answer', toolCallId: 'task-1' }, type: 'tool_result' }, // finalize
+ textEvent('task-1', 'm2', 'resumed'),
+ { data: {}, type: 'agent_runtime_end' }, // orphan drain closes the resumed run
+ textEvent('task-1', 'm2', 'resumed'), // replay of the resumed turn
+ textEvent('task-1', 'm3', 'resumed again'),
+ ]);
+
+ expect(kinds(steps[3])).toEqual(['persistContent', 'finalizeThread']);
+ expect(steps[4]).toEqual([]);
+ // m3 chains off the resumed turn's assistant (msg_4), not the first hand-back.
+ expect(kinds(steps[5])).toEqual(['reopenThread', 'createMessage', 'streamContent']);
+ expect(steps[5][1]).toMatchObject({ messageId: 'msg_5', parentId: 'msg_4' });
+ expect(state.runs.get('task-1')!.currentSubagentMessageId).toBe('m3');
+ });
+
+ it('resumes from a rehydrated finalized anchor (cold replica)', () => {
+ const state0 = rehydrateSubagentRunsState(
+ [],
+ ['task-1'],
+ [
+ {
+ lastChainParentId: 'asst-tail',
+ lifetimeToolCallIds: ['tc-1'],
+ parentToolCallId: 'task-1',
+ threadId: 'thd-x',
+ turnIds: ['m1'],
+ },
+ ],
+ );
+
+ const replay = reduceSubagentRuns(
+ state0,
+ toolsEvent('task-1', 'm1', [tool('tc-1')]),
+ makeCtx(),
+ );
+ expect(replay.intents).toEqual([]);
+
+ const resumed = reduceSubagentRuns(
+ state0,
+ toolsEvent('task-1', 'm2', [tool('tc-1'), tool('tc-2')]),
+ makeCtx(),
+ );
+ expect(kinds(resumed.intents)).toEqual(['reopenThread', 'createMessage', 'persistToolBatch']);
+ expect(resumed.intents[1]).toMatchObject({ parentId: 'asst-tail', threadId: 'thd-x' });
+ // tc-1 already lives in the thread β€” only tc-2 becomes a new tool row.
+ const batch = resumed.intents[2] as PersistToolBatchIntent;
+ expect(batch.tools.map((t) => t.payload.id)).toEqual(['tc-2']);
+ });
+
+ it('continues a rehydrated in-flight turn with its persisted text and tools', () => {
+ // A replica that rebuilds the run from DB mid-turn must keep the turn's
+ // earlier text and tools; otherwise the next write replaces them.
+ const state0 = rehydrateSubagentRunsState([
+ {
+ accContent: 'first half ',
+ currentAssistantId: 'asst-1',
+ currentSubagentMessageId: 'm1',
+ lifetimeToolCallIds: ['tc-1'],
+ parentToolCallId: 'task-1',
+ threadId: 'thd-x',
+ turnTools: [{ payload: tool('tc-1'), toolMessageId: 'tool-msg-1' }],
+ },
+ ]);
+
+ const text = reduceSubagentRuns(state0, textEvent('task-1', 'm1', 'second half'), makeCtx());
+ expect(text.intents).toEqual([
+ {
+ content: 'first half second half',
+ kind: 'streamContent',
+ messageId: 'asst-1',
+ threadId: 'thd-x',
+ },
+ ]);
+
+ const tools = reduceSubagentRuns(
+ text.state,
+ toolsEvent('task-1', 'm1', [tool('tc-1'), tool('tc-2')]),
+ makeCtx(),
+ );
+ const batch = tools.intents[0] as PersistToolBatchIntent;
+ expect(batch.content).toBe('first half second half');
+ expect(batch.tools.map((t) => [t.payload.id, t.isNew, t.toolMessageId])).toEqual([
+ ['tc-1', false, 'tool-msg-1'],
+ ['tc-2', true, 'msg_1'],
+ ]);
+ });
+
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.ts
index bf0383d30e8..df9725b66f1 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
@@ -50,6 +50,7 @@ const copyRun = (run: SubagentRun): SubagentRun => ({
...run,
lifetimeToolCallIds: new Set(run.lifetimeToolCallIds),
toolState: copyToolState(run.toolState),
+ turnIds: new Set(run.turnIds),
});
/** Clone the runs map, deep-copying only the run we're about to mutate. */
@@ -69,16 +70,38 @@ const withRun = (
* `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.
+ * The run's tail is kept as a resume anchor in case the subagent wakes up again.
*/
const markRunFinalized = (
state: SubagentRunsState,
parentToolCallId: string,
+ run: SubagentRun,
): SubagentRunsState => {
const runs = new Map(state.runs);
runs.delete(parentToolCallId);
const finalizedParents = new Set(state.finalizedParents);
finalizedParents.add(parentToolCallId);
- return { ...state, finalizedParents, runs };
+ const finalizedRuns = new Map(state.finalizedRuns);
+ finalizedRuns.set(parentToolCallId, {
+ lastChainParentId: run.lastChainParentId,
+ lifetimeToolCallIds: run.lifetimeToolCallIds,
+ threadId: run.threadId,
+ turnIds: run.turnIds,
+ });
+ return { ...state, finalizedParents, finalizedRuns, runs };
+};
+
+/** Move a resumed parent from the finalized set back into the live runs. */
+const markRunReopened = (
+ state: SubagentRunsState,
+ parentToolCallId: string,
+ run: SubagentRun,
+): SubagentRunsState => {
+ const finalizedParents = new Set(state.finalizedParents);
+ finalizedParents.delete(parentToolCallId);
+ const finalizedRuns = new Map(state.finalizedRuns);
+ finalizedRuns.delete(parentToolCallId);
+ return withRun({ ...state, finalizedParents, finalizedRuns }, parentToolCallId, run);
};
const SUBAGENT_TITLE_MAX = 80;
@@ -95,9 +118,11 @@ interface ReduceResult {
* 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.
+ * When the parent already FINALIZED (its thread is `Active`, tracked in
+ * `finalizedParents`), only a turn the thread has never seen resumes it: the
+ * thread reopens and the turn chains onto its tail. Anything else is a stale
+ * replay of a completed spawn β€” re-creating its thread would duplicate it β€” so
+ * this returns `run: null` and the caller drops the event.
*/
const ensureRun = (
state: SubagentRunsState,
@@ -107,9 +132,46 @@ const ensureRun = (
const intents: SubagentIntent[] = [];
const existing = state.runs.get(subCtx.parentToolCallId);
- // ─── Stale replay of an already-finalized spawn β†’ no-op (no duplicate thread) ───
+ // ─── Finalized spawn: resume on a new turn, otherwise a stale replay β†’ no-op ───
if (!existing && state.finalizedParents.has(subCtx.parentToolCallId)) {
- return { intents, run: null, state };
+ const anchor = state.finalizedRuns.get(subCtx.parentToolCallId);
+ const turnId = subCtx.subagentMessageId;
+ if (!anchor || !turnId || anchor.turnIds.has(turnId)) {
+ return { intents, run: null, state };
+ }
+
+ const assistantId = ctx.newId('message');
+ intents.push(
+ { kind: 'reopenThread', threadId: anchor.threadId },
+ {
+ agentId: ctx.agentId,
+ content: '',
+ kind: 'createMessage',
+ messageId: assistantId,
+ parentId: anchor.lastChainParentId,
+ role: 'assistant',
+ subagentMessageId: turnId,
+ threadId: anchor.threadId,
+ topicId: ctx.topicId,
+ },
+ );
+
+ const run: SubagentRun = {
+ accContent: '',
+ accReasoning: '',
+ currentAssistantId: assistantId,
+ currentSubagentMessageId: turnId,
+ lastChainParentId: assistantId,
+ lifetimeToolCallIds: new Set(anchor.lifetimeToolCallIds),
+ threadId: anchor.threadId,
+ toolState: emptyToolState(),
+ turnIds: new Set([...anchor.turnIds, turnId]),
+ };
+ return {
+ intents,
+ run,
+ state: markRunReopened(state, subCtx.parentToolCallId, run),
+ };
}
// ─── First event for this parent β†’ lazy-create Thread + seed + assistant ───
@@ -166,6 +228,7 @@ const ensureRun = (
lifetimeToolCallIds: new Set(),
threadId,
toolState: emptyToolState(),
+ turnIds: new Set(subCtx.subagentMessageId ? [subCtx.subagentMessageId] : []),
};
return { intents, run, state: withRun(state, subCtx.parentToolCallId, run) };
}
@@ -199,6 +262,7 @@ const ensureRun = (
run.currentAssistantId = nextAssistantId;
run.currentSubagentMessageId = subCtx.subagentMessageId;
+ run.turnIds.add(subCtx.subagentMessageId);
run.lastChainParentId = nextAssistantId;
run.toolState = emptyToolState();
run.accContent = '';
@@ -256,7 +320,7 @@ const finalizeRun = (
intents.push({ kind: 'finalizeThread', threadId: run.threadId });
- return { intents, state: markRunFinalized(state, parentToolCallId) };
+ return { intents, state: markRunFinalized(state, parentToolCallId, run) };
};
/** Find the run that owns an inner tool_call id (lifetime lookup). */
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/snapshot.test.ts b/packages/heterogeneous-agents/src/subagentCoordinator/snapshot.test.ts
new file mode 100644
index 00000000000..efc9784b42a
--- /dev/null
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/snapshot.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+
+import type { SubagentThreadMessage } from './snapshot';
+import { buildFinalizedSubagentRunSnapshot, buildSubagentRunSnapshot } from './snapshot';
+
+const tool = (id: string) => ({
+ apiName: 'Bash',
+ arguments: '{}',
+ id,
+ identifier: 'bash',
+ type: 'default',
+});
+
+const messages: SubagentThreadMessage[] = [
+ // Parent rows a thread query returns alongside the thread's own rows.
+ { id: 'main-asst', role: 'assistant', threadId: null },
+ { content: 'go', id: 'seed', role: 'user', threadId: 'thd-1' },
+ {
+ content: 'looking',
+ id: 'asst-1',
+ metadata: { subagentMessageId: 'm1' },
+ role: 'assistant',
+ threadId: 'thd-1',
+ tools: [{ ...tool('t1'), result_msg_id: 'tool-1' }],
+ },
+ { id: 'tool-1', role: 'tool', threadId: 'thd-1', tool_call_id: 't1' },
+ {
+ content: 'half a sentence',
+ id: 'asst-2',
+ // A usage write re-stamps the turn id as `heteroMessageId`.
+ metadata: { heteroMessageId: 'm2' },
+ reasoning: { content: 'thinking' },
+ role: 'assistant',
+ threadId: 'thd-1',
+ tools: [tool('t2')],
+ },
+ { id: 'tool-2', role: 'tool', threadId: 'thd-1', tool_call_id: 't2' },
+];
+
+describe('buildSubagentRunSnapshot', () => {
+ it('restores the in-flight turn from the thread tail', () => {
+ expect(buildSubagentRunSnapshot('task-1', 'thd-1', messages)).toEqual({
+ accContent: 'half a sentence',
+ accReasoning: 'thinking',
+ currentAssistantId: 'asst-2',
+ currentSubagentMessageId: 'm2',
+ lastChainParentId: 'asst-2',
+ lifetimeToolCallIds: ['t1', 't2'],
+ parentToolCallId: 'task-1',
+ threadId: 'thd-1',
+ turnIds: ['m1', 'm2'],
+ // No result_msg_id yet: the tool row id comes from the row itself.
+ turnTools: [{ payload: tool('t2'), toolMessageId: 'tool-2' }],
+ });
+ });
+
+ it('returns undefined when the thread has no assistant yet', () => {
+ expect(buildSubagentRunSnapshot('task-1', 'thd-1', messages.slice(0, 2))).toBeUndefined();
+ });
+});
+
+describe('buildFinalizedSubagentRunSnapshot', () => {
+ it('anchors on the newest non-tool row and keeps the known turns', () => {
+ const finalized = [
+ ...messages,
+ { content: 'final report', id: 'hand-back', role: 'assistant', threadId: 'thd-1' },
+ ];
+
+ expect(buildFinalizedSubagentRunSnapshot('task-1', 'thd-1', finalized)).toEqual({
+ lastChainParentId: 'hand-back',
+ lifetimeToolCallIds: ['t1', 't2'],
+ parentToolCallId: 'task-1',
+ threadId: 'thd-1',
+ turnIds: ['m1', 'm2'],
+ });
+ });
+
+ it('returns undefined for a thread without rows', () => {
+ expect(buildFinalizedSubagentRunSnapshot('task-1', 'thd-1', messages.slice(0, 1))).toBe(
+ undefined,
+ );
+ });
+});
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/snapshot.ts b/packages/heterogeneous-agents/src/subagentCoordinator/snapshot.ts
new file mode 100644
index 00000000000..81c343834ba
--- /dev/null
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/snapshot.ts
@@ -0,0 +1,105 @@
+import type { ToolCallPayload } from '../types';
+import type { FinalizedSubagentRunSnapshot, SubagentRunSnapshot } from './types';
+
+/**
+ * A persisted message as a thread query returns it, narrowed to the fields
+ * subagent rehydration reads. Both the server's DB rows and the renderer's
+ * `UIChatMessage`s fit this shape.
+ */
+export interface SubagentThreadMessage {
+ content?: string | null;
+ id: string;
+ metadata?: Record<string, any> | null;
+ reasoning?: { content?: string } | null;
+ role: string;
+ threadId?: string | null;
+ tool_call_id?: string | null;
+ tools?: (ToolCallPayload & { result_msg_id?: string })[] | null;
+}
+
+/** Adapter turn id persisted on an in-thread assistant (`heteroMessageId` carries the same id). */
+const turnIdOf = (message: SubagentThreadMessage): string | undefined => {
+ const turnId = message.metadata?.subagentMessageId ?? message.metadata?.heteroMessageId;
+ return typeof turnId === 'string' ? turnId : undefined;
+};
+
+const turnIdsOf = (messages: SubagentThreadMessage[]): string[] =>
+ messages
+ .filter((m) => m.role === 'assistant')
+ .map(turnIdOf)
+ .filter((id): id is string => !!id);
+
+/**
+ * Rebuild the snapshot of an in-flight subagent run from its thread's messages
+ * (ordered `createdAt` asc). A thread query also returns the parent rows the
+ * thread was forked from, so only rows of `threadId` count.
+ *
+ * Returns undefined when the thread has no assistant yet β€” there is nothing to
+ * attach a continuation turn to, and the first-event path seeds it.
+ */
+export const buildSubagentRunSnapshot = (
+ parentToolCallId: string,
+ threadId: string,
+ allMessages: SubagentThreadMessage[],
+): SubagentRunSnapshot | undefined => {
+ const messages = allMessages.filter((m) => m.threadId === threadId);
+ const currentAssistant = messages.findLast((m) => m.role === 'assistant');
+ if (!currentAssistant) return undefined;
+
+ const toolMessageIdByCallId = new Map(
+ messages.filter((m) => m.role === 'tool' && m.tool_call_id).map((m) => [m.tool_call_id!, m.id]),
+ );
+ const turnTools = (currentAssistant.tools ?? []).flatMap((tool) => {
+ const toolMessageId = tool.result_msg_id ?? toolMessageIdByCallId.get(tool.id);
+ if (!toolMessageId) return [];
+ const payload: ToolCallPayload = {
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ id: tool.id,
+ identifier: tool.identifier,
+ type: tool.type,
+ };
+ return [{ payload, toolMessageId }];
+ });
+
+ return {
+ accContent: currentAssistant.content || undefined,
+ accReasoning: currentAssistant.reasoning?.content || undefined,
+ currentAssistantId: currentAssistant.id,
+ // The in-flight turn's CC message.id, so a continuation event is the SAME
+ // turn (no spurious boundary β†’ no fragmentation).
+ currentSubagentMessageId: turnIdOf(currentAssistant),
+ // Chain rule: the next turn's assistant parents off the prior assistant
+ // (the spine), not its last child tool.
+ lastChainParentId: currentAssistant.id,
+ lifetimeToolCallIds: [...toolMessageIdByCallId.keys()],
+ parentToolCallId,
+ threadId,
+ turnIds: turnIdsOf(messages),
+ turnTools,
+ };
+};
+
+/**
+ * Resume anchor of a finalized thread: its newest non-tool row (normally the
+ * hand-back answer), the turns it already holds, and its inner tool ids.
+ */
+export const buildFinalizedSubagentRunSnapshot = (
+ parentToolCallId: string,
+ threadId: string,
+ allMessages: SubagentThreadMessage[],
+): FinalizedSubagentRunSnapshot | undefined => {
+ const messages = allMessages.filter((m) => m.threadId === threadId);
+ const tail = messages.findLast((m) => m.role !== 'tool');
+ if (!tail) return undefined;
+
+ return {
+ lastChainParentId: tail.id,
+ lifetimeToolCallIds: messages
+ .filter((m) => m.role === 'tool' && m.tool_call_id)
+ .map((m) => m.tool_call_id!),
+ parentToolCallId,
+ threadId,
+ turnIds: turnIdsOf(messages),
+ };
+};
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts b/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
index 1225e9aa564..5fdcf92b8c1 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
@@ -68,6 +68,25 @@ export interface SubagentRun {
threadId: string;
/** Per-turn tool persistence state. */
toolState: SubagentTurnToolState;
+ /**
+ * Every adapter `subagentMessageId` this run has opened an assistant for.
+ * Carried into {@link FinalizedSubagentRun} so a replay of one of these turns
+ * after finalize stays a no-op instead of reopening the thread.
+ */
+ turnIds: Set<string>;
+}
+
+/**
+ * What a finalized run leaves behind so the same subagent can resume later.
+ * CC's `SendMessage` wakes a completed subagent and its events keep the
+ * original `parentToolCallId`; a NEW turn id reopens the thread and chains
+ * onto `lastChainParentId`, while a known turn id is a stale replay.
+ */
+export interface FinalizedSubagentRun {
+ lastChainParentId: string;
+ lifetimeToolCallIds: Set<string>;
+ threadId: string;
+ turnIds: Set<string>;
}
export interface SubagentRunsState {
@@ -82,12 +101,19 @@ export interface SubagentRunsState {
* boundaries; on the server it is reseeded from DB `Active` isolation threads.
*/
finalizedParents: Set<string>;
+ /**
+ * Resume anchors for finalized parents, keyed by `parentToolCallId`. A
+ * finalized parent without an anchor (e.g. a cold replica that only knows
+ * the thread is `Active`) cannot resume and drops every event.
+ */
+ finalizedRuns: Map<string, FinalizedSubagentRun>;
/** Active subagent runs, keyed by `parentToolCallId`. */
runs: Map<string, SubagentRun>;
}
export const createSubagentRunsState = (): SubagentRunsState => ({
finalizedParents: new Set(),
+ finalizedRuns: new Map(),
runs: new Map(),
});
@@ -116,6 +142,10 @@ export const createSubagentRunsState = (): SubagentRunsState => ({
* turn behavior as before, no duplicate thread.
*/
export interface SubagentRunSnapshot {
+ /** Persisted text of the in-flight turn, so a continuation appends instead of replacing it. */
+ accContent?: string;
+ /** Persisted reasoning of the in-flight turn. */
+ accReasoning?: string;
/** Latest in-thread assistant id (where a continuation turn would otherwise append). */
currentAssistantId: string;
/** CC `message.id` of the in-flight turn, from the latest assistant's `metadata.subagentMessageId`. */
@@ -128,39 +158,81 @@ export interface SubagentRunSnapshot {
parentToolCallId: string;
/** The existing isolation Thread this run owns. */
threadId: string;
+ /** Every `subagentMessageId` already persisted in the thread. */
+ turnIds?: string[];
+ /** Tools already on the in-flight assistant, so a cumulative `tools_calling` keeps them. */
+ turnTools?: { payload: ToolCallPayload; toolMessageId: string }[];
+}
+
+/** DB-derived snapshot of a finalized run, used to rebuild its {@link FinalizedSubagentRun}. */
+export interface FinalizedSubagentRunSnapshot {
+ /** The thread's latest non-tool message, where a resumed turn chains on. */
+ lastChainParentId: string;
+ lifetimeToolCallIds?: string[];
+ parentToolCallId: string;
+ threadId: string;
+ turnIds?: string[];
}
+/** Rebuild one live {@link SubagentRun} from its DB snapshot. */
+export const restoreSubagentRun = (s: SubagentRunSnapshot): SubagentRun => {
+ const turnTools = s.turnTools ?? [];
+ return {
+ accContent: s.accContent ?? '',
+ accReasoning: s.accReasoning ?? '',
+ currentAssistantId: s.currentAssistantId,
+ currentSubagentMessageId: s.currentSubagentMessageId ?? '',
+ lastChainParentId: s.lastChainParentId ?? s.currentAssistantId,
+ lifetimeToolCallIds: new Set(s.lifetimeToolCallIds ?? []),
+ threadId: s.threadId,
+ toolState: {
+ payloads: turnTools.map(({ payload }) => ({ ...payload })),
+ persistedIds: new Set(turnTools.map(({ payload }) => payload.id)),
+ toolMsgIdByCallId: new Map(
+ turnTools.map(({ payload, toolMessageId }) => [payload.id, toolMessageId]),
+ ),
+ },
+ turnIds: new Set(s.turnIds ?? []),
+ };
+};
+
+/** Rebuild one {@link FinalizedSubagentRun} resume anchor from its DB snapshot. */
+export const restoreFinalizedSubagentRun = (
+ s: FinalizedSubagentRunSnapshot,
+): FinalizedSubagentRun => ({
+ lastChainParentId: s.lastChainParentId,
+ lifetimeToolCallIds: new Set(s.lifetimeToolCallIds ?? []),
+ threadId: s.threadId,
+ turnIds: new Set(s.turnIds ?? []),
+});
+
/**
* Rebuild a {@link SubagentRunsState} from DB-derived snapshots of in-flight
* runs. Use on a cold start so a continuing subagent reuses its existing thread
- * 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`.
+ * instead of forking a new one. The in-flight turn's text and tools come back
+ * from the snapshot when provided; inner tool_results 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.
+ * `finalizedRuns` adds resume anchors for the finalized parents that may resume.
*/
export const rehydrateSubagentRunsState = (
snapshots: SubagentRunSnapshot[],
finalizedParentToolCallIds: string[] = [],
-): SubagentRunsState => {
- const runs = new Map<string, SubagentRun>();
- for (const s of snapshots) {
- runs.set(s.parentToolCallId, {
- accContent: '',
- accReasoning: '',
- currentAssistantId: s.currentAssistantId,
- currentSubagentMessageId: s.currentSubagentMessageId ?? '',
- lastChainParentId: s.lastChainParentId ?? s.currentAssistantId,
- lifetimeToolCallIds: new Set(s.lifetimeToolCallIds ?? []),
- threadId: s.threadId,
- toolState: { payloads: [], persistedIds: new Set(), toolMsgIdByCallId: new Map() },
- });
- }
- return { finalizedParents: new Set(finalizedParentToolCallIds), runs };
-};
+ finalizedRuns: FinalizedSubagentRunSnapshot[] = [],
+): SubagentRunsState => ({
+ finalizedParents: new Set([
+ ...finalizedParentToolCallIds,
+ ...finalizedRuns.map((s) => s.parentToolCallId),
+ ]),
+ finalizedRuns: new Map(
+ finalizedRuns.map((s) => [s.parentToolCallId, restoreFinalizedSubagentRun(s)]),
+ ),
+ runs: new Map(snapshots.map((s) => [s.parentToolCallId, restoreSubagentRun(s)])),
+});
// ─── Reduce context (per event) ───
@@ -199,7 +271,8 @@ export type SubagentIntent =
| UpdateToolStateIntent
| ResolveToolResultIntent
| RecordUsageIntent
- | FinalizeThreadIntent;
+ | FinalizeThreadIntent
+ | ReopenThreadIntent;
/** Lazy-create the subagent Thread (status Processing). */
export interface CreateThreadIntent {
@@ -336,3 +409,9 @@ export interface FinalizeThreadIntent {
kind: 'finalizeThread';
threadId: string;
}
+
+/** A finalized subagent resumed: mark its Thread running again (Active β†’ Processing). */
+export interface ReopenThreadIntent {
+ kind: 'reopenThread';
+ threadId: string;
+}
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index dfcc1e9ec8b..e3585aea60f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -5,6 +5,7 @@ import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ip
import {
appendAttachedFilesToPrompt,
buildHeterogeneousAgentAuthRequiredError,
+ buildSubagentRunSnapshot,
createMainAgentRunState,
type HeteroAttachedFileRef,
isHeterogeneousAgentAuthRequired,
@@ -1142,28 +1143,15 @@ export const executeHeterogeneousAgent = async (
threadId: thread.id,
topicId: context.topicId,
});
- const currentAssistant = messages.findLast((message) => message.role === 'assistant');
- if (!currentAssistant) continue;
+ const snapshot = buildSubagentRunSnapshot(parentToolCallId, thread.id, messages);
+ if (!snapshot) continue;
- const toolRows = messages.filter(
- (message) => message.role === 'tool' && message.tool_call_id,
- );
- for (const message of toolRows) {
- toolMsgIdByCallId.set(message.tool_call_id!, message.id);
- toolThreadIdByCallId.set(message.tool_call_id!, thread.id);
+ for (const message of messages) {
+ if (message.role !== 'tool' || !message.tool_call_id) continue;
+ toolMsgIdByCallId.set(message.tool_call_id, message.id);
+ toolThreadIdByCallId.set(message.tool_call_id, thread.id);
}
- const subagentMessageId = (currentAssistant.metadata as Record<string, unknown> | null)
- ?.subagentMessageId;
-
- snapshots.push({
- currentAssistantId: currentAssistant.id,
- currentSubagentMessageId:
- typeof subagentMessageId === 'string' ? subagentMessageId : undefined,
- lastChainParentId: currentAssistant.id,
- lifetimeToolCallIds: toolRows.map((message) => message.tool_call_id!),
- parentToolCallId,
- threadId: thread.id,
- });
+ snapshots.push(snapshot);
}
mainState = {
@@ -1485,6 +1473,17 @@ export const executeHeterogeneousAgent = async (
if (t) completeSubagentOp(t.subOperationId);
return;
}
+
+ case 'reopenThread': {
+ try {
+ await threadService.updateThread(intent.threadId, { status: ThreadStatus.Processing });
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to reopen subagent thread:', err);
+ }
+ // Finalize completed the thread's sub-op; the resumed turns need a live one.
+ subagentThreads.set(intent.threadId, beginSubagentRun(intent.threadId));
+ return;
+ }
}
};