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(server): persist subagent turn id so cold replicas don't fragment a turn (#15808)

Arvin Xu01278efdde36
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 67892ff04b3..aee05532221 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -626,7 +626,13 @@ export class HeterogeneousPersistenceHandler {
private buildSubagentSnapshot(
parentToolCallId: string,
threadId: string,
- messages: Array<{ id: string; parentId?: string | null; role: string; tool_call_id?: 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);
@@ -635,9 +641,16 @@ export class HeterogeneousPersistenceHandler {
const toolRows = messages.filter((m) => m.role === 'tool' && m.tool_call_id);
const childTools = toolRows.filter((m) => m.parentId === currentAssistant.id);
const lastChainParentId = childTools.at(-1)?.id ?? 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;
return {
currentAssistantId: currentAssistant.id,
+ currentSubagentMessageId,
lastChainParentId,
lifetimeToolCallIds: toolRows.map((m) => m.tool_call_id!),
parentToolCallId,
@@ -962,11 +975,18 @@ export class HeterogeneousPersistenceHandler {
{
agentId: intent.agentId ?? undefined,
content: intent.content,
+ // Persist the turn's CC message.id so a cold replica can recover
+ // `currentSubagentMessageId` (via buildSubagentSnapshot) and avoid
+ // a spurious turn boundary that fragments one CC turn into multiple
+ // in-thread assistant rows + empty shells.
+ ...(intent.subagentMessageId
+ ? { metadata: { subagentMessageId: intent.subagentMessageId } }
+ : {}),
parentId: intent.parentId,
role: intent.role,
threadId: intent.threadId,
topicId: intent.topicId ?? state.topicId,
- },
+ } as any,
intent.messageId,
);
return;
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
index 25b41fc9ed4..de52e34ed06 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
@@ -101,7 +101,13 @@ const createHarness = (params: {
update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {
const existing = messages.get(id);
if (!existing) return { success: false };
- messages.set(id, { ...existing, ...patch });
+ // Mirror the real MessageModel.update: metadata is DEEP-MERGED, not
+ // replaced β€” so e.g. a usage write doesn't clobber subagentMessageId.
+ const next = { ...existing, ...patch };
+ if (patch.metadata && existing.metadata) {
+ next.metadata = { ...existing.metadata, ...patch.metadata };
+ }
+ messages.set(id, next);
return { success: true };
}),
updateToolMessage: vi.fn(async (id: string, patch: any) => {
@@ -371,4 +377,69 @@ describe('HeterogeneousPersistenceHandler β€” subagent run survives a cold repli
expect(h.threads.get('thd-stale')!.status).toBe('processing');
expect(h.threadModel.update).not.toHaveBeenCalledWith('thd-stale', expect.anything());
});
+
+ // The in-thread analog of the cold-replica bug: one CC subagent turn continued
+ // on a fresh replica must NOT fork into a second in-thread assistant. The turn's
+ // CC message.id is persisted on the assistant's metadata and recovered into
+ // `currentSubagentMessageId`, so a continuation is recognized as the SAME turn.
+ it('does NOT fragment one CC subagent turn across a cold replica (no split / empty shell)', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ const PARENT = 'tc-spawn-1';
+
+ // Batch 1: turn sub-1's first tool β†’ lazy-create thread + user + in-thread
+ // assistant (stamped subagentMessageId=sub-1) + tool t1.
+ await h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ subagent: {
+ parentToolCallId: PARENT,
+ spawnMetadata: { prompt: 'go', subagentType: 'Explore' },
+ subagentMessageId: 'sub-1',
+ },
+ toolsCalling: [innerTool('t1')],
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const threadId = [...h.threads.keys()][0];
+ const assistantsOf = () =>
+ [...h.messages.values()].filter((m) => m.role === 'assistant' && m.threadId === threadId);
+ expect(assistantsOf()).toHaveLength(1);
+ // The turn id was persisted so a cold replica can recover it.
+ expect(assistantsOf()[0].metadata?.subagentMessageId).toBe('sub-1');
+
+ __resetOperationStatesForTesting(); // cold replica
+
+ // Batch 2 (fresh replica): SAME turn sub-1 continues (cumulative [t1, t2]).
+ await h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [
+ buildEvent('stream_chunk', 1, {
+ chunkType: 'tools_calling',
+ subagent: { parentToolCallId: PARENT, subagentMessageId: 'sub-1' },
+ toolsCalling: [innerTool('t1'), innerTool('t2')],
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Still exactly ONE in-thread assistant β€” no fork, no empty shell.
+ const assistants = assistantsOf();
+ expect(assistants).toHaveLength(1);
+ // Both tool rows hang off that same assistant (t1 not duplicated).
+ const toolRows = [...h.messages.values()].filter(
+ (m) => m.role === 'tool' && (m.tool_call_id === 't1' || m.tool_call_id === 't2'),
+ );
+ expect(toolRows).toHaveLength(2);
+ expect(new Set(toolRows.map((m) => m.parentId))).toEqual(new Set([assistants[0].id]));
+ });
});
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
index c00bc351cee..88c39f4d594 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
@@ -130,6 +130,7 @@ const ensureRun = (
messageId: firstAssistantId,
parentId: userMsgId,
role: 'assistant',
+ subagentMessageId: subCtx.subagentMessageId,
threadId,
topicId: ctx.topicId,
},
@@ -170,6 +171,7 @@ const ensureRun = (
messageId: nextAssistantId,
parentId: run.lastChainParentId,
role: 'assistant',
+ subagentMessageId: subCtx.subagentMessageId,
threadId: run.threadId,
topicId: ctx.topicId,
});
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts b/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
index 6828f3c3fc1..06411babb9c 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/types.ts
@@ -93,16 +93,21 @@ export const createSubagentRunsState = (): SubagentRunsState => ({
* server rebuilds main-agent state from DB on cold start; this lets it rebuild
* the subagent runs the same way.
*
- * Only the fields needed to keep the run attached to its EXISTING thread are
- * required. `currentSubagentMessageId` is intentionally NOT recoverable from DB
- * (CC's per-turn `message.id` is not persisted) β€” leaving it empty makes the
- * first post-rehydration subagent event read as a turn boundary, cutting a fresh
- * in-thread assistant chained off `lastChainParentId`. That is correct and safe:
- * it reuses the thread (no duplicate) and never appends to a half-written turn.
+ * Only the fields needed to keep the run attached to its EXISTING thread and to
+ * its IN-FLIGHT turn are required. `currentSubagentMessageId` is recovered from
+ * the latest in-thread assistant's persisted `metadata.subagentMessageId`: a
+ * cold replica must know the in-flight turn's CC `message.id`, otherwise the
+ * next event (`'' !== realId`) reads as a spurious turn boundary and splits one
+ * CC turn across multiple assistant rows (text on one, tools on another) plus
+ * empty shells. When the latest assistant predates this field (or is the
+ * terminal result row), it's omitted and falls back to `''` β€” same single-extra-
+ * turn behavior as before, no duplicate thread.
*/
export interface SubagentRunSnapshot {
/** 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`. */
+ currentSubagentMessageId?: string;
/** Chain anchor for the next turn's assistant β€” last tool row of the thread, else the assistant. */
lastChainParentId?: string;
/** Every inner tool_call_id already persisted in the thread (delayed tool_results resolve via this). */
@@ -127,7 +132,7 @@ export const rehydrateSubagentRunsState = (snapshots: SubagentRunSnapshot[]): Su
accContent: '',
accReasoning: '',
currentAssistantId: s.currentAssistantId,
- currentSubagentMessageId: '',
+ currentSubagentMessageId: s.currentSubagentMessageId ?? '',
lastChainParentId: s.lastChainParentId ?? s.currentAssistantId,
lifetimeToolCallIds: new Set(s.lifetimeToolCallIds ?? []),
threadId: s.threadId,
@@ -200,6 +205,16 @@ export interface CreateMessageIntent {
messageId: string;
parentId: string;
role: 'user' | 'assistant';
+ /**
+ * CC's per-turn `message.id` for an `assistant` turn row. Persisted (server:
+ * onto `metadata.subagentMessageId`) so a cold serverless replica can recover
+ * {@link SubagentRun.currentSubagentMessageId} via {@link SubagentRunSnapshot}
+ * and recognize a CONTINUING turn instead of forcing a spurious turn boundary
+ * β€” which would split one CC turn across multiple in-thread assistant rows
+ * (text on one, tools on another) and leave empty shells. Absent on the user
+ * seed and the terminal result assistant.
+ */
+ subagentMessageId?: string;
threadId: string;
topicId: string | null;
}