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.

♻️ refactor(hetero-agent): assistant-anchored message-chain write spine (#15930)

Arvin Xudc3b325040f4
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 796cb2f45cc..9ad425897d2 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -115,14 +115,6 @@ interface OperationState {
main: MainAgentRunState;
operationId: string;
processedKeys: Set<string>;
- /**
- * The operation's seeded placeholder assistant (the row `execAgent` creates
- * before the first ingest). Immutable for the run's lifetime. Used as the
- * `createdAt` floor when anchoring the chain to the run's real last tool β€”
- * a topic runs at most one operation at a time, so "tool messages on/after
- * the seed" scopes to THIS run without a recursive parent walk.
- */
- seedAssistantMessageId: string;
/**
* Run-global DB index for every tool message in the topic, keyed by
* `tool_call_id`. Main and subagent reducers keep only their per-turn maps;
@@ -404,7 +396,6 @@ export class HeterogeneousPersistenceHandler {
main: createMainAgentRunState(currentAssistantMessageId),
operationId,
processedKeys: new Set(),
- seedAssistantMessageId: baseAssistantMessageId,
toolMsgIdByCallId: new Map(),
topicId,
};
@@ -479,17 +470,6 @@ export class HeterogeneousPersistenceHandler {
return toolState;
}
- private getLastSnapshotToolMessageId(
- snapshot: AssistantDbSnapshot,
- toolMsgIdByCallId: Map<string, string>,
- ): string | undefined {
- for (const tool of [...snapshot.tools].reverse()) {
- const toolMessageId = tool.result_msg_id ?? toolMsgIdByCallId.get(tool.id);
- if (toolMessageId) return toolMessageId;
- }
- return undefined;
- }
-
private async refreshToolMessageIndex(state: OperationState): Promise<void> {
const toolPlugins = await this.deps.messageModel.listMessagePluginsByTopic(state.topicId);
for (const plugin of toolPlugins) {
@@ -497,10 +477,6 @@ export class HeterogeneousPersistenceHandler {
}
}
- private async getLastChildToolMessageId(assistantMessageId: string): Promise<string | undefined> {
- return await this.deps.messageModel.getLastChildToolMessageId?.(assistantMessageId);
- }
-
/**
* Rehydrate reducer state from the DB projection of the current assistant.
* This preserves the shared pure reducer as the single state machine while
@@ -553,49 +529,16 @@ export class HeterogeneousPersistenceHandler {
if (snapshot.model) state.main.turnModel = snapshot.model;
if (snapshot.provider) state.main.turnProvider = snapshot.provider;
- // Anchor the chain to the RUN's real latest main-thread tool message, read
- // straight from the DB and independent of `currentAssistantId`. The latter
- // can regress to the seeded placeholder on a cold / non-sticky replica
- // (see the multi-replica caveat on the class) when `heteroCurrentMsgId` is
- // not yet bound to this operation: anchoring off its child tools would then
- // collapse onto the run's FIRST tool, and every later step opens off that
- // same node β€” forking the wire into orphan siblings. Ordering by createdAt
- // also sidesteps the multi-tool-batch hazard where an earlier tool's
- // result_msg_id is backfilled before a later tool row's JSONB is rewritten.
- const runLastToolId = await this.getLastRunToolMessageId(state);
- if (runLastToolId) {
- state.main.lastToolMsgIdEver = runLastToolId;
- return;
- }
-
- // No tool persisted in this run yet β€” fall back to the per-assistant lookups
- // so the very first turn still chains correctly before any tool exists.
- const currentTurnToolId =
- (await this.getLastChildToolMessageId(state.main.currentAssistantId)) ??
- this.getLastSnapshotToolMessageId(snapshot, state.toolMsgIdByCallId);
- if (currentTurnToolId) {
- state.main.lastToolMsgIdEver = currentTurnToolId;
- return;
- }
-
- const toolMessageIds = new Set(state.toolMsgIdByCallId.values());
- if (snapshot.parentId && toolMessageIds.has(snapshot.parentId)) {
- state.main.lastToolMsgIdEver = snapshot.parentId;
- }
- }
-
- /**
- * Latest main-thread tool message created on/after the run's seed assistant.
- * Scopes to the current operation via the seed's `createdAt` floor without a
- * recursive walk, and stays correct even when `currentAssistantId` has
- * regressed on a cold replica. Optional on the model so test mocks that don't
- * implement it transparently fall back to the per-assistant anchors.
- */
- private async getLastRunToolMessageId(state: OperationState): Promise<string | undefined> {
- return await this.deps.messageModel.getLastMainThreadToolMessageIdSince?.(
- state.topicId,
- state.seedAssistantMessageId,
- );
+ // Recover the chain spine from the DB (LOBE-10445 phase 2). The next normal
+ // turn parents off the run's latest NON-tool / NON-signal main-thread
+ // message; reading it straight from the DB (independent of
+ // `currentAssistantId`, which can regress to the seed placeholder on a cold
+ // / non-sticky replica β€” see the multi-replica caveat on the class) keeps
+ // consecutive cold-replica steps chained linearly instead of forking onto a
+ // stale node. Signal turns still anchor off `lastToolMsgIdEver`, which is
+ // maintained in-memory across the run's tool batches.
+ const spineId = await this.deps.messageModel.getLastMainThreadSpineMessageId?.(state.topicId);
+ if (spineId) state.main.lastSpineMessageId = spineId;
}
/**
@@ -706,8 +649,11 @@ export class HeterogeneousPersistenceHandler {
if (!currentAssistant) return undefined;
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;
+ // Chain rule (LOBE-10445 phase 2): 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 =
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
index 41c076e67d4..b1ab7f970a2 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
@@ -9,19 +9,19 @@ import {
/**
* Regression for the remote-device chain-fork (observed on tpc_3DKmFfAmx9YA):
- * several CONSECUTIVE, DISTINCT main-agent steps all parented onto the run's
- * FIRST tool message instead of chaining linearly.
+ * several CONSECUTIVE, DISTINCT main-agent steps all parented onto the same
+ * stale node instead of chaining linearly.
*
- * Root cause: `refreshMainStateFromDb` used to anchor `lastToolMsgIdEver` off
- * `getLastChildToolMessageId(currentAssistantId)`. On a non-sticky / cold
- * replica (a WS reconnect storm spreads one run's batches across replicas),
- * `currentAssistantId` regresses to the operation's seeded placeholder when the
- * `heteroCurrentMsgId` pointer is not yet visible. The anchor then collapses to
- * the SEED's first child tool, and every later `newStep` opens off that same
- * node β†’ orphan sibling forks.
+ * On a non-sticky / cold replica (a WS reconnect storm spreads one run's batches
+ * across replicas), `currentAssistantId` regresses to the operation's seeded
+ * placeholder when the `heteroCurrentMsgId` pointer is not yet visible. If the
+ * chain parent were derived from that in-memory pointer, every later `newStep`
+ * would open off the seed β†’ orphan sibling forks.
*
- * The fix anchors the chain to the RUN's real latest main-thread tool, read
- * from the DB and ordered by createdAt, independent of `currentAssistantId`.
+ * LOBE-10445 phase 2 anchors the chain to the run's latest NON-tool / NON-signal
+ * main-thread message (`getLastMainThreadSpineMessageId`), read straight from the
+ * DB and ordered by createdAt β€” independent of `currentAssistantId`. So step 2
+ * chains off step 1's assistant even though the in-memory pointer regressed.
*
* This harness models the precondition deterministically: `updateMetadata`
* never persists `heteroCurrentMsgId`, so every cold load regresses
@@ -103,18 +103,15 @@ const createHarness = () => {
return [...messages.values()].filter((m) => m.threadId === params.threadId);
return [...messages.values()].filter((m) => !m.threadId && m.topicId === params?.topicId);
}),
- getLastChildToolMessageId: vi.fn(async (assistantMessageId: string) => {
- const match = [...messages.values()]
- .filter((m) => m.role === 'tool' && m.parentId === assistantMessageId && !m.threadId)
- .sort((a, b) => b.seq - a.seq)[0];
- return match?.id;
- }),
- getLastMainThreadToolMessageIdSince: vi.fn(async (topicId: string, sinceMessageId: string) => {
- const seed = messages.get(sinceMessageId);
- if (!seed) return undefined;
+ getLastMainThreadSpineMessageId: vi.fn(async (topicId: string) => {
+ // Most recent main-thread, non-tool, non-signal message β€” the spine anchor.
const match = [...messages.values()]
.filter(
- (m) => m.topicId === topicId && m.role === 'tool' && !m.threadId && m.seq >= seed.seq,
+ (m) =>
+ m.topicId === topicId &&
+ m.role !== 'tool' &&
+ !m.threadId &&
+ !(m as any).metadata?.signal,
)
.sort((a, b) => b.seq - a.seq)[0];
return match?.id;
@@ -184,7 +181,7 @@ describe('HeterogeneousPersistenceHandler β€” chain anchor survives a regressed
beforeEach(() => __resetOperationStatesForTesting());
afterEach(() => __resetOperationStatesForTesting());
- it('chains consecutive cold-replica steps off the run last tool, not the seed first tool', async () => {
+ it('chains consecutive cold-replica steps linearly off the spine, not forking onto the seed', async () => {
const h = createHarness();
// Step 1 on a cold replica (currentAssistantId regresses to SEED).
@@ -209,18 +206,22 @@ describe('HeterogeneousPersistenceHandler β€” chain anchor survives a regressed
expect(assistants).toHaveLength(2);
const [a1, a2] = assistants.sort((x, y) => x.seq - y.seq);
- const toolA = [...h.messages.values()].find((m) => m.tool_call_id === 'tc-A')!;
- // First step still chains off the run's only existing tool (T1, seed's child).
- expect(a1.parentId).toBe(T1);
- // Second step must chain off step 1's tool β€” NOT collapse back onto T1.
- expect(a2.parentId).toBe(toolA.id);
- expect(a2.parentId).not.toBe(T1);
+ // Step 1 chains off the spine = the seed assistant (T1 is a tool, excluded).
+ expect(a1.parentId).toBe(SEED);
+ // Step 2 chains off step 1's assistant β€” the spine query found a1 from the DB
+ // despite the in-memory currentAssistantId having regressed to SEED.
+ expect(a2.parentId).toBe(a1.id);
- // No fork: T1 has exactly one assistant child across the whole run.
- const t1AssistantChildren = [...h.messages.values()].filter(
- (m) => m.role === 'assistant' && m.parentId === T1,
+ // No fork: the seed has exactly one assistant child (a1), and a1 has exactly
+ // one assistant child (a2) β€” a linear spine, not a fan-out.
+ const seedAssistantChildren = [...h.messages.values()].filter(
+ (m) => m.role === 'assistant' && m.parentId === SEED,
+ );
+ expect(seedAssistantChildren).toHaveLength(1);
+ const a1AssistantChildren = [...h.messages.values()].filter(
+ (m) => m.role === 'assistant' && m.parentId === a1.id,
);
- expect(t1AssistantChildren).toHaveLength(1);
+ expect(a1AssistantChildren).toHaveLength(1);
});
});
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
index 5cc3b3e28a9..15502967268 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
@@ -122,9 +122,9 @@ const createHarness = (
},
),
findById: vi.fn(async (id: string) => messages.get(id) ?? null),
- getLastChildToolMessageId: vi.fn(async (assistantMessageId: string) => {
+ getLastMainThreadSpineMessageId: vi.fn(async (_topicId: string) => {
const match = [...messages.values()].findLast(
- (m) => m.role === 'tool' && m.parentId === assistantMessageId && !m.threadId,
+ (m) => m.role !== 'tool' && !m.threadId && !(m as any).metadata?.signal,
);
return match?.id;
}),
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
index f96d2cb9d6d..0e1d1dc02d8 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
@@ -264,11 +264,12 @@ describe('HeterogeneousPersistenceHandler β€” synthetic CC trace fixture', () =>
// STEP_COUNT-1 new assistants from `stream_start { newStep }` events.
expect(allAssistants.length).toBe(STEP_COUNT);
- // Each new assistant chains off the LAST tool message of the prior step
- // (renderer parity: "the wire becomes asst β†’ tool β†’ asst β†’ tool β†’ ...").
+ // Each new assistant chains off the PRIOR ASSISTANT (the spine, phase 2):
+ // the persisted shape is `user β†’ asst β†’ asst …` with tools as inline
+ // children; the read side reconstructs the `asst β†’ tool β†’ asst` zigzag.
for (let i = 1; i < allAssistants.length; i += 1) {
const parent = h.messages.get(allAssistants[i].parentId!);
- expect(parent?.role).toBe('tool');
+ expect(parent?.role).toBe('assistant');
}
// ─── Bursty-text dedupe key correctness ───
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
index fe05163e01d..b37aee637c1 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
@@ -129,9 +129,9 @@ const createHarness = () => {
return [...messages.values()].filter((m) => m.threadId === params.threadId);
return [...messages.values()].filter((m) => !m.threadId && m.topicId === params?.topicId);
}),
- getLastChildToolMessageId: vi.fn(async (assistantMessageId: string) => {
+ getLastMainThreadSpineMessageId: vi.fn(async (_topicId: string) => {
const match = [...messages.values()].findLast(
- (m) => m.role === 'tool' && m.parentId === assistantMessageId && !m.threadId,
+ (m) => m.role !== 'tool' && !m.threadId && !(m as any).metadata?.signal,
);
return match?.id;
}),
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 ff6553374d6..fd046d30642 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
@@ -123,9 +123,9 @@ const createHarness = (params: {
}
return [...messages.values()].filter((m) => !m.threadId && m.topicId === params?.topicId);
}),
- getLastChildToolMessageId: vi.fn(async (assistantMessageId: string) => {
+ getLastMainThreadSpineMessageId: vi.fn(async (_topicId: string) => {
const match = [...messages.values()].findLast(
- (m) => m.role === 'tool' && m.parentId === assistantMessageId && !m.threadId,
+ (m) => m.role !== 'tool' && !m.threadId && !(m as any).metadata?.signal,
);
return match?.id;
}),
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index 18653d8fae3..8fc57823607 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -117,11 +117,11 @@ const createHarness = (params: {
},
),
findById: vi.fn(async (id: string) => messages.get(id) ?? null),
- getLastChildToolMessageId: vi.fn(async (assistantMessageId: string) => {
- // Mirror the SQL: last-created main-agent (threadId null) tool row whose
- // parentId is the assistant. Map insertion order == creation order.
+ getLastMainThreadSpineMessageId: vi.fn(async (_topicId: string) => {
+ // Mirror the SQL: most recent main-agent (threadId null) message that is
+ // NOT a tool and NOT a signal-tagged callback. Insertion order == creation.
const match = [...messages.values()].findLast(
- (m) => m.role === 'tool' && m.parentId === assistantMessageId && !m.threadId,
+ (m) => m.role !== 'tool' && !m.threadId && !(m as any).metadata?.signal,
);
return match?.id;
}),
@@ -561,7 +561,7 @@ describe('HeterogeneousPersistenceHandler', () => {
});
describe('step boundaries (stream_start newStep)', () => {
- it('flushes prior content, opens a new assistant chained off the last tool message', async () => {
+ it('flushes prior content, opens a new assistant chained off the prior assistant (spine)', async () => {
const h = createHarness({
assistantMessageId: 'asst-1',
operationId: 'op-1',
@@ -591,28 +591,24 @@ describe('HeterogeneousPersistenceHandler', () => {
topicId: 'topic-1',
});
- // First step: asst-1 got content + tools
- // After step boundary: a NEW assistant created chained off the tool msg
+ // First step: asst-1 got content + tools.
+ // After step boundary (phase 2 spine rule): a NEW assistant is created
+ // chained off the prior assistant (asst-1), with the tool as an inline
+ // child β€” the read side reconstructs the zigzag.
const newAssistants = [...h.messages.values()].filter(
(m) => m.role === 'assistant' && m.id !== 'asst-1',
);
expect(newAssistants).toHaveLength(1);
-
- const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
- expect(newAssistants[0].parentId).toBe(toolMsg?.id);
+ expect(newAssistants[0].parentId).toBe('asst-1');
});
- it('chains off the tool message even when the prior tools_calling landed on a DIFFERENT replica (multi-replica recovery)', async () => {
- // Reproduces the prod bug: the in-memory state.toolState gets RESET at
- // the end of every handleStepStart. If the next step's tools_calling
- // event then lands on a different replica, this replica's toolState
- // stays empty, and the FOLLOWING step boundary computes parentId from
- // that empty state β†’ falls back to currentAssistantMessageId β†’
- // new assistant chains off the previous ASSISTANT rather than the
- // previous TOOL message.
- //
- // Fix: `ingest()` refresh adopts `tools[]` from DB as authoritative
- // whenever DB has more resolved tools than memory.
+ it('chains off the prior assistant (spine) across a multi-replica boundary, recovered from DB', async () => {
+ // Phase 2: the chain parent is the run's latest non-tool / non-signal
+ // main message, recovered from the DB (`getLastMainThreadSpineMessageId`)
+ // independent of the in-memory current-assistant pointer. So even when the
+ // prior step's tools_calling drained on a DIFFERENT replica (this replica's
+ // toolState stays empty), step 2 still chains off step 1's assistant β€” a
+ // linear spine, not a fork.
const h = createHarness({
assistantMessageId: 'asst-init',
operationId: 'op-1',
@@ -680,10 +676,8 @@ describe('HeterogeneousPersistenceHandler', () => {
});
// ── Batch 2: step 2 stream_start lands back on THIS replica ──
- // Pre-fix: state.toolState.payloads is still [] β†’ lastToolMsgId is
- // undefined β†’ stepParentId falls back to step1Asst.id (BUG).
- // Post-fix: ingest() refresh reads step1Asst.tools from DB β†’ toolState
- // gets the tool with result_msg_id β†’ handleStepStart chains correctly.
+ // The DB spine query returns step1Asst (the latest non-tool main message),
+ // so step 2 chains off it regardless of this replica's empty toolState.
await h.handler.ingest({
events: [buildEvent('stream_start', 2, { newStep: true })],
operationId: 'op-1',
@@ -694,7 +688,7 @@ describe('HeterogeneousPersistenceHandler', () => {
(m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
);
expect(step2Asst).toBeDefined();
- expect(step2Asst!.parentId).toBe('tool-other-replica');
+ expect(step2Asst!.parentId).toBe(step1Asst.id);
// And the new assistant should inherit model/provider that the other
// replica wrote β€” refresh also restores lastModel/lastProvider so we
// no longer create assistants with model=null/provider=null on the
@@ -703,14 +697,12 @@ describe('HeterogeneousPersistenceHandler', () => {
expect(step2Asst!.provider).toBe('claude-code');
});
- it('chains off the tool ROW when the refresh misses the tools[] result_msg_id backfill', async () => {
- // Residual race the batch-start refresh does NOT cover: the other replica
- // created the tool row (Phase 2) but its assistant.tools[] result_msg_id
- // backfill (Phase 3) is not yet visible. The refresh keys off
- // result_msg_id, so it sees 0 resolved tools β†’ does NOT adopt β†’ toolState
- // stays empty β†’ pre-fix the step boundary falls back to the previous
- // assistant and forks the wire. The fix queries the role:'tool' row
- // itself (committed in Phase 2, independent of the JSONB mirror).
+ it('chains off the spine regardless of the prior step tool backfill state', async () => {
+ // Phase 2: the chain anchors to the spine (latest non-tool main message),
+ // so the prior step's tool-row / result_msg_id backfill timing β€” which
+ // used to matter for the tool anchor β€” no longer affects the chain. Even
+ // with a tool row present but no tools[] backfill, step 2 chains off the
+ // prior assistant.
const h = createHarness({
assistantMessageId: 'asst-init',
operationId: 'op-1',
@@ -763,11 +755,11 @@ describe('HeterogeneousPersistenceHandler', () => {
(m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
);
expect(step2Asst).toBeDefined();
- // Chains off the tool row, NOT the previous assistant β†’ wire stays linear.
- expect(step2Asst!.parentId).toBe('tool-row-only');
+ // Chains off the prior assistant (spine) β†’ wire stays linear; the tool is inline.
+ expect(step2Asst!.parentId).toBe(step1Asst.id);
});
- it('chains off the latest tool row when parallel tools are only partially backfilled', async () => {
+ it('chains off the spine when parallel tools are only partially backfilled', async () => {
// Regression for main-chain breaks with parallel/multi tool calls:
// tool A is visible in assistant.tools[].result_msg_id, while tool B's
// row exists but Phase 3 has not backfilled assistant.tools[] yet. The
@@ -849,7 +841,8 @@ describe('HeterogeneousPersistenceHandler', () => {
(m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
);
expect(step2Asst).toBeDefined();
- expect(step2Asst!.parentId).toBe('tool-b-row-only');
+ // Spine-anchored: parallel-tool backfill state is irrelevant to the chain.
+ expect(step2Asst!.parentId).toBe(step1Asst.id);
});
it('ignores subagent tool rows (threadId set) when resolving the step anchor', async () => {
@@ -1095,9 +1088,10 @@ describe('HeterogeneousPersistenceHandler', () => {
expect(threadTool?.tool_call_id).toBe('inner-tc-1');
expect(threadTool?.parentId).toBe(threadAssts[0].id);
- // Second-turn assistant chains off the tool message
+ // Second-turn assistant chains off the prior in-thread assistant (spine),
+ // with the tool as an inline child (phase 2 rule).
const secondTurn = threadAssts[1];
- expect(secondTurn.parentId).toBe(threadTool?.id);
+ expect(secondTurn.parentId).toBe(threadAssts[0].id);
});
it('finalizes the run with terminal assistant carrying tool_result content', async () => {
diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.ts
index 8c0d58d1159..afb87aef08f 100644
--- a/packages/database/src/models/__tests__/messages/message.query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts
@@ -2957,63 +2957,84 @@ describe('MessageModel Query Tests', () => {
});
});
- describe('getLastChildToolMessageId', () => {
- it('should return the most recently-created tool child of an assistant message', async () => {
+ describe('getLastMainThreadSpineMessageId', () => {
+ it('returns the latest non-tool main-thread message in a topic (tools excluded)', async () => {
+ await serverDB.insert(sessions).values([{ id: 'session1', userId }]);
+ await serverDB.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
await serverDB.insert(messages).values([
{
- id: 'asst-1',
+ id: 'a1',
userId,
+ topicId: 'topic1',
role: 'assistant',
- content: 'assistant step',
+ content: 'step',
createdAt: new Date('2023-01-01T00:00:00'),
},
{
- id: 'tool-early',
+ // newest row, but a tool β€” must NOT be the spine
+ id: 'tool-1',
userId,
+ topicId: 'topic1',
role: 'tool',
- parentId: 'asst-1',
- content: 'first tool',
+ parentId: 'a1',
+ content: 'result',
createdAt: new Date('2023-01-01T00:00:01'),
},
{
- id: 'tool-late',
+ id: 'a2',
userId,
- role: 'tool',
- parentId: 'asst-1',
- content: 'second tool',
+ topicId: 'topic1',
+ role: 'assistant',
+ content: 'final',
createdAt: new Date('2023-01-01T00:00:02'),
},
]);
- const result = await messageModel.getLastChildToolMessageId('asst-1');
- expect(result).toBe('tool-late');
+ expect(await messageModel.getLastMainThreadSpineMessageId('topic1')).toBe('a2');
});
- it('should return undefined when the assistant produced no tool children', async () => {
+ it('excludes signal-tagged reactive callbacks', async () => {
+ await serverDB.insert(sessions).values([{ id: 'session1', userId }]);
+ await serverDB.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
await serverDB.insert(messages).values([
{
- id: 'asst-no-tools',
+ id: 'a1',
userId,
+ topicId: 'topic1',
role: 'assistant',
- content: 'no tools here',
- createdAt: new Date('2023-01-01'),
+ content: 'spine',
+ createdAt: new Date('2023-01-01T00:00:00'),
},
{
- // a non-tool child must be ignored
- id: 'child-assistant',
+ id: 'tool-1',
userId,
+ topicId: 'topic1',
+ role: 'tool',
+ parentId: 'a1',
+ content: 'result',
+ createdAt: new Date('2023-01-01T00:00:01'),
+ },
+ {
+ // newest, but a Monitor-stdout callback (metadata.signal) β€” excluded,
+ // so a normal turn doesn't re-mount onto a callback
+ id: 'cb-1',
+ userId,
+ topicId: 'topic1',
role: 'assistant',
- parentId: 'asst-no-tools',
- content: 'follow-up assistant',
- createdAt: new Date('2023-01-02'),
+ parentId: 'tool-1',
+ content: 'callback',
+ metadata: {
+ signal: { sourceToolCallId: 'tc', sourceToolName: 'Monitor', type: 'tool-stdout' },
+ },
+ createdAt: new Date('2023-01-01T00:00:02'),
},
]);
- const result = await messageModel.getLastChildToolMessageId('asst-no-tools');
- expect(result).toBeUndefined();
+ expect(await messageModel.getLastMainThreadSpineMessageId('topic1')).toBe('a1');
});
- it('should exclude subagent tool rows that live on their own thread', async () => {
+ it('excludes subagent-thread messages and scopes to the current user', async () => {
+ const otherModel = new MessageModel(serverDB, otherUserId);
await serverDB.transaction(async (trx) => {
await trx.insert(sessions).values([{ id: 'session1', userId }]);
await trx.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);
@@ -3022,68 +3043,36 @@ describe('MessageModel Query Tests', () => {
id: 'subagent-thread',
userId,
topicId: 'topic1',
- sourceMessageId: 'asst-main',
+ sourceMessageId: 'a1',
type: 'standalone',
},
]);
await trx.insert(messages).values([
{
- id: 'asst-main',
+ id: 'a1',
userId,
+ topicId: 'topic1',
role: 'assistant',
- content: 'main agent step',
- createdAt: new Date('2023-01-01T00:00:00'),
- },
- {
- id: 'tool-main',
- userId,
- role: 'tool',
- parentId: 'asst-main',
threadId: null,
- content: 'main-agent tool',
- createdAt: new Date('2023-01-01T00:00:01'),
+ content: 'main',
+ createdAt: new Date('2023-01-01T00:00:00'),
},
{
// newer, but on a subagent thread β€” must not anchor the main wire
- id: 'tool-subagent',
+ id: 'sub-asst',
userId,
- role: 'tool',
- parentId: 'asst-main',
+ topicId: 'topic1',
+ role: 'assistant',
threadId: 'subagent-thread',
- content: 'subagent tool',
- createdAt: new Date('2023-01-01T00:00:02'),
+ content: 'subagent',
+ createdAt: new Date('2023-01-01T00:00:01'),
},
]);
});
- const result = await messageModel.getLastChildToolMessageId('asst-main');
- expect(result).toBe('tool-main');
- });
-
- it('should not return tool rows belonging to other users', async () => {
- const otherModel = new MessageModel(serverDB, otherUserId);
- await serverDB.insert(messages).values([
- {
- id: 'asst-shared-id',
- userId: otherUserId,
- role: 'assistant',
- content: 'other user assistant',
- createdAt: new Date('2023-01-01T00:00:00'),
- },
- {
- id: 'tool-other-user',
- userId: otherUserId,
- role: 'tool',
- parentId: 'asst-shared-id',
- content: 'other user tool',
- createdAt: new Date('2023-01-01T00:00:01'),
- },
- ]);
-
- // current user must not see another user's tool rows
- expect(await messageModel.getLastChildToolMessageId('asst-shared-id')).toBeUndefined();
- // the owning user does
- expect(await otherModel.getLastChildToolMessageId('asst-shared-id')).toBe('tool-other-user');
+ expect(await messageModel.getLastMainThreadSpineMessageId('topic1')).toBe('a1');
+ // another user sees nothing in this topic
+ expect(await otherModel.getLastMainThreadSpineMessageId('topic1')).toBeUndefined();
});
});
});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index b551fab0eb4..0a14e12e5df 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -2360,69 +2360,36 @@ export class MessageModel {
};
/**
- * Id of the most recently-created main-agent `role:'tool'` message under an
- * assistant message, or `undefined` when the assistant produced no tools.
+ * Id of the latest main-thread (`threadId IS NULL`) "spine" message in a
+ * topic: the most recent message that is NOT a tool and NOT a signal-tagged
+ * reactive turn (Monitor stdout callbacks etc.). This is the chain anchor for
+ * the heterogeneous-agent write side (LOBE-10445 phase 2): the next normal
+ * turn parents off it, producing a `user β†’ asst β†’ asst …` spine with tools as
+ * inline children.
*
- * Heterogeneous step boundaries chain the next assistant off the previous
- * step's final tool message (the wire is `asst β†’ tool β†’ … β†’ asst β†’ tool`).
- * The persistence handler normally derives that anchor from its in-memory
- * tool state, but on a warm replica that did NOT drain the prior step's
- * `tools_calling` (or before the assistant's `tools[]` JSONB has its
- * `result_msg_id` backfilled) that state is empty β€” so it falls back here.
+ * Read straight from the DB and ordered by `createdAt`, it is independent of
+ * the in-memory current-assistant pointer β€” which can regress to the run's
+ * seed placeholder on a cold / non-sticky serverless replica. Anchoring here
+ * instead keeps consecutive cold-replica steps chained linearly rather than
+ * forking onto a stale node (the remote "ζ–­ι“Ύ" bug). No `createdAt` floor is
+ * needed: a topic runs at most one operation at a time, so the latest spine
+ * message IS this run's continuation point.
*
- * The `role:'tool'` rows are the authoritative anchor: they are created
- * (Phase 2) with `parentId` = their step's assistant, earlier than and
- * independent of the JSONB mirror's `result_msg_id` backfill (Phase 3).
- * `threadId IS NULL` excludes subagent tool rows, which live on their own
- * thread and must not anchor the main-agent wire.
+ * Excludes `role:'tool'` (inline children) and signal-tagged assistants
+ * (`metadata->'signal'`), which are tool-child callbacks β€” anchoring a normal
+ * turn onto a callback would orphan it under the read side's tool-only signal
+ * collection.
*/
- getLastChildToolMessageId = async (assistantMessageId: string): Promise<string | undefined> => {
- const [row] = await this.db
- .select({ id: messages.id })
- .from(messages)
- .where(
- and(
- eq(messages.parentId, assistantMessageId),
- eq(messages.role, 'tool'),
- isNull(messages.threadId),
- this.ownership(),
- ),
- )
- .orderBy(desc(messages.createdAt))
- .limit(1);
-
- return row?.id;
- };
-
- /**
- * Latest main-thread (`threadId IS NULL`) tool message in a topic created on
- * or after `sinceMessageId`. The hetero persistence handler passes the running
- * operation's seed assistant as `sinceMessageId`, so the `createdAt` floor
- * scopes the lookup to that run (a topic runs at most one operation at a time)
- * and the chain anchor stays correct even when the in-memory current-assistant
- * pointer has regressed on a cold replica.
- */
- getLastMainThreadToolMessageIdSince = async (
- topicId: string,
- sinceMessageId: string,
- ): Promise<string | undefined> => {
- const [seed] = await this.db
- .select({ createdAt: messages.createdAt })
- .from(messages)
- .where(and(eq(messages.id, sinceMessageId), this.ownership()))
- .limit(1);
-
- if (!seed?.createdAt) return undefined;
-
+ getLastMainThreadSpineMessageId = async (topicId: string): Promise<string | undefined> => {
const [row] = await this.db
.select({ id: messages.id })
.from(messages)
.where(
and(
eq(messages.topicId, topicId),
- eq(messages.role, 'tool'),
+ not(eq(messages.role, 'tool')),
isNull(messages.threadId),
- gte(messages.createdAt, seed.createdAt),
+ sql`${messages.metadata} -> 'signal' IS NULL`,
this.ownership(),
),
)
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
index f0615c34177..13624f5adaa 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
@@ -156,21 +156,21 @@ describe('main agent reducer', () => {
expect(ofKind(second.intents, 'persistToolBatch')[0].tools[0].isNew).toBe(false);
});
- it('opens a new turn chained off the previous turn last tool', () => {
+ it('opens a new turn chained off the prior assistant (the spine), not its tool', () => {
const { steps } = run([
textEvent('first'),
- toolsEvent([tool('t1')]), // β†’ msg_1
+ toolsEvent([tool('t1')]), // β†’ msg_1, an inline tool child of A0
toolResultEvent('t1', 'ok'),
- newStepEvent(), // β†’ new assistant msg_2, parent = msg_1
+ newStepEvent(), // β†’ new assistant msg_2, parent = A0 (spine); the tool is inline
]);
const flush = ofKind(steps[3], 'persistAssistant')[0];
expect(flush).toMatchObject({ content: 'first', messageId: 'A0' });
const created = ofKind(steps[3], 'createAssistant')[0];
- expect(created).toMatchObject({ messageId: 'msg_2', parentId: 'msg_1' });
+ expect(created).toMatchObject({ messageId: 'msg_2', parentId: 'A0' });
});
- // ─── The ζ–­ι“Ύ regression: toolless reactive (Monitor) turns must NOT fork ───
- it('re-mounts toolless signal turns onto the source tool, not the prior assistant', () => {
+ // ─── Signal/反应式 turns stay tool-mounted; the next normal turn resumes the spine ───
+ it('mounts signal turns on the source tool, and resumes the spine on the next normal turn', () => {
const { steps, state } = run([
textEvent('watching build'),
toolsEvent([tool('t1')]), // Monitor β†’ msg_1
@@ -186,15 +186,19 @@ describe('main agent reducer', () => {
.flatMap((s) => ofKind(s, 'createAssistant'))
.map((c) => ({ messageId: c.messageId, parentId: c.parentId, signalType: c.signal?.type }));
- // EVERY turn after the Monitor tool hangs off msg_1 (the source tool),
- // forming a flat fan-out β€” NOT a linear msg_2 β†’ msg_3 β†’ msg_4 chain that
- // collectAssistantChain would sever at the first signal-tagged assistant.
+ // The two signal-tagged reactive turns (msg_2, msg_3) mount on the source
+ // tool (msg_1) so the reader renders them as tool-child callbacks. The
+ // natural continuation (msg_4, no signal) re-mounts on the SPINE (A0, the
+ // pre-callback assistant) β€” NOT on a signal callback (which the reader skips,
+ // orphaning everything after it) and NOT fanned out onto the tool.
expect(created).toEqual([
{ messageId: 'msg_2', parentId: 'msg_1', signalType: 'tool-stdout' },
{ messageId: 'msg_3', parentId: 'msg_1', signalType: 'tool-stdout' },
- { messageId: 'msg_4', parentId: 'msg_1', signalType: undefined },
+ { messageId: 'msg_4', parentId: 'A0', signalType: undefined },
]);
- // The next real tool advances the chain fallback forward.
+ // Signal turns did NOT advance the spine; the next real tool advances the
+ // signal anchor forward.
+ expect(state.lastSpineMessageId).toBe('msg_4');
expect(state.lastToolMsgIdEver).toBe('msg_5');
});
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
index a7c25cebb0a..def331f6352 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
@@ -100,12 +100,23 @@ const delegateSubagent = (
// ─── Chain rule ───
/**
- * Parent for the NEXT turn's assistant. Prefer the run-lifetime last tool
- * message (`lastToolMsgIdEver`) so toolless reactive turns don't fork the wire;
- * fall back to the current assistant only before any tool has been seen.
+ * Parent for the NEXT turn's assistant (LOBE-10445 phase 2 β€” write-side spine).
+ *
+ * Normal turns parent off the run's spine (`lastSpineMessageId`, the most recent
+ * non-tool / non-signal main message) so the persisted shape is
+ * `user β†’ asst β†’ asst …` with tools as inline children; the read side
+ * reconstructs the zigzag.
+ *
+ * Signal / reactive toolless turns (Monitor stdout pushes etc.) are the one
+ * exception: they parent off the run's most recent tool (`lastToolMsgIdEver`)
+ * so the reader renders them as tool-child callbacks (`collectFlatSignalCallbacks`)
+ * instead of spine turns. They fall back to the spine only before any tool has
+ * been seen.
*/
-const computeTurnParentId = (state: MainAgentRunState): string =>
- state.lastToolMsgIdEver ?? state.currentAssistantId;
+const computeTurnParentId = (state: MainAgentRunState, data: any): string => {
+ if (data?.externalSignal) return state.lastToolMsgIdEver ?? state.lastSpineMessageId;
+ return state.lastSpineMessageId;
+};
// ─── Per-event handlers ───
@@ -123,16 +134,18 @@ const openTurn = (state: MainAgentRunState, data: any, ctx: MainAgentReduceCtx):
intents.push({ kind: 'persistAssistant', messageId: state.currentAssistantId, ...flush });
}
- // 2. Open the new turn's assistant, chained off the last tool (chain rule).
+ // 2. Open the new turn's assistant, chained off the spine (chain rule);
+ // signal/reactive turns parent off the last tool β€” see computeTurnParentId.
const messageId = ctx.newId('message');
const mainMessageId = typeof data?.messageId === 'string' ? data.messageId : undefined;
+ const isSignalTurn = !!data?.externalSignal;
intents.push({
agentId: ctx.agentId,
kind: 'createAssistant',
mainMessageId,
messageId,
model: state.turnModel,
- parentId: computeTurnParentId(state),
+ parentId: computeTurnParentId(state, data),
provider: state.turnProvider,
signal: data?.externalSignal,
topicId: ctx.topicId,
@@ -141,6 +154,10 @@ const openTurn = (state: MainAgentRunState, data: any, ctx: MainAgentReduceCtx):
// 3. Advance: model/provider carry across (a fresh turn_metadata overwrites).
const next = copyState(state);
next.currentAssistantId = messageId;
+ // The spine only advances on NORMAL turns β€” a signal/reactive turn is a
+ // tool-child callback, so the next normal turn re-mounts on the pre-callback
+ // spine assistant, not on the callback.
+ if (!isSignalTurn) next.lastSpineMessageId = messageId;
next.currentMainMessageId = mainMessageId;
next.accContent = '';
next.accReasoning = '';
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
index 49527f184a3..53c3418b97f 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
@@ -27,12 +27,18 @@ import type { ExternalSignalContext, ToolCallPayload } from '../types';
* by delegating subagent-scoped events to `reduceSubagentRuns`, so a single
* `reduce` call is the only entry point both engines need.
*
- * The CHAIN RULE lives here and is authoritative for both engines:
- * the next turn's assistant parents off the last tool message of the most
- * recent tool-bearing turn (`lastToolMsgIdEver`), falling back to the current
- * assistant only when no tool has ever been seen. This keeps the rendered
- * chain a linear `asst β†’ tool β†’ asst β†’ tool …` zigzag even across toolless
- * reactive (signal-tagged) turns.
+ * The CHAIN RULE lives here and is authoritative for both engines (LOBE-10445
+ * phase 2): the next turn's assistant parents off the most recent NON-tool,
+ * NON-signal main-thread message β€” the run's "spine" (`lastSpineMessageId`) β€”
+ * so the persisted shape is `user β†’ asst β†’ asst …` with tools as inline
+ * children. The read side (`conversation-flow`) reconstructs the
+ * `asst β†’ tool β†’ asst` zigzag from this. The one exception is signal-tagged
+ * reactive turns (Monitor stdout pushes), which parent off the run's most
+ * recent tool (`lastToolMsgIdEver`) so the reader renders them as tool-child
+ * callbacks rather than spine turns. On a cold serverless replica the spine
+ * pointer is recovered from the DB (most recent non-tool main message), which
+ * is fork-resistant β€” it does NOT depend on the in-memory current-assistant
+ * pointer that can regress mid-run.
*/
// ─── Reducer state ───
@@ -75,14 +81,24 @@ export interface MainAgentRunState {
currentMainMessageId: string | undefined;
/** Set once a terminal event has been reduced (idempotent finalize). */
ended: boolean;
+ /**
+ * Chain rule (LOBE-10445 phase 2): the most recent NON-tool, NON-signal
+ * main-thread message β€” the run's spine. The next NORMAL turn's assistant
+ * parents off this (signal-tagged reactive turns parent off `lastToolMsgIdEver`
+ * instead). Advances on every normal turn; a signal turn does NOT advance it,
+ * so a normal continuation after a Monitor-callback burst re-mounts on the
+ * pre-callback spine assistant, not on a callback. Seeded to the placeholder
+ * assistant; recovered from the DB on a cold replica (fork-resistant).
+ */
+ lastSpineMessageId: string;
/** Highest seen text snapshot sequence (replace-mode de-dup). */
lastTextSnapshotSeq: number;
/**
- * Run-lifetime id of the most recent main-agent tool message. This is the
- * chain-rule fallback: a new turn whose PRIOR turn produced no tools (e.g. a
- * Monitor-stdout reactive reply) re-mounts onto this tool rather than onto
- * the toolless assistant, so the rendered chain stays a linear zigzag.
- * Only advances on tool batches; never reset across turns.
+ * Run-lifetime id of the most recent main-agent tool message. Since
+ * LOBE-10445 phase 2 this anchors ONLY signal-tagged reactive turns (Monitor
+ * stdout pushes) onto a tool, so the reader renders them as tool-child
+ * callbacks; normal turns parent off `lastSpineMessageId`. Only advances on
+ * tool batches; never reset across turns.
*/
lastToolMsgIdEver: string | undefined;
/** Nested subagent runs β€” delegated to `reduceSubagentRuns`. */
@@ -109,6 +125,7 @@ export const createMainAgentRunState = (seedAssistantId: string): MainAgentRunSt
currentAssistantId: seedAssistantId,
currentMainMessageId: undefined,
ended: false,
+ lastSpineMessageId: seedAssistantId,
lastTextSnapshotSeq: 0,
lastToolMsgIdEver: undefined,
subagents: createSubagentRunsState(),
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
index 81205aeccd4..c1828d4d73e 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.test.ts
@@ -164,8 +164,10 @@ describe('subagent reducer', () => {
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');
+ // Chain rule (phase 2): the next assistant chains off the prior assistant
+ // (the spine), NOT the batch's last tool β€” so lastChainParentId stays at the
+ // current assistant (msg_2) and the tools are inline children.
+ expect(state.runs.get('task-1')!.lastChainParentId).toBe('msg_2');
expect([...state.runs.get('task-1')!.lifetimeToolCallIds]).toEqual(['tc-1', 'tc-2']);
});
@@ -181,17 +183,18 @@ describe('subagent reducer', () => {
]);
});
- it('cuts a new turn on subagentMessageId change: flush prior + new assistant chained off last tool', () => {
+ it('cuts a new turn on subagentMessageId change: flush prior + new assistant chained off the prior assistant', () => {
const { steps, state } = run([
textEvent('task-1', 'm1', 'first turn text'),
- toolsEvent('task-1', 'm1', [tool('tc-1')]), // lastChainParentId β†’ msg_3
+ toolsEvent('task-1', 'm1', [tool('tc-1')]), // tool is an inline child of msg_2
textEvent('task-1', 'm2', 'second turn'), // turn boundary
]);
- // boundary flushes prior turn content, opens a new assistant off the last tool msg (msg_3)
+ // boundary flushes prior turn content, opens a new assistant off the prior
+ // assistant (the spine, msg_2) β€” NOT the last tool β€” with the tool inline
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][1]).toMatchObject({ messageId: 'msg_4', parentId: 'msg_2', role: 'assistant' });
expect(steps[2][2]).toMatchObject({ content: 'second turn', messageId: 'msg_4' });
const r = state.runs.get('task-1')!;
diff --git a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
index 4aa953c594d..ca11163fe1b 100644
--- a/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/subagentCoordinator/reducer.ts
@@ -349,9 +349,11 @@ const reduceToolsChunk = (
})),
});
- // Chain the next turn's assistant off the LAST tool message of this batch.
- const lastToolMsgId = newToolMsgIds.at(-1);
- if (lastToolMsgId) run.lastChainParentId = lastToolMsgId;
+ // Chain rule (LOBE-10445 phase 2): the next turn's assistant parents off the
+ // prior assistant (the spine), NOT this batch's last tool β€” so
+ // `lastChainParentId` stays at `currentAssistantId` here, tools become inline
+ // children, and the read side reconstructs the zigzag. (Subagent threads have
+ // no signal/reactive turns, so there is no tool-anchor exception.)
return { intents, state: withRun(ensured.state, subCtx.parentToolCallId, run) };
};
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 61ea7c02daa..9d01fba62c1 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -634,7 +634,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// ────────────────────────────────────────────────────
describe('multi-step parentId chain', () => {
- it('should create assistant messages chained: assistant β†’ tool β†’ assistant', async () => {
+ it('should chain step assistants along the spine, with tools inline', async () => {
await runWithEvents([
ccInit(),
// Step 1: tool_use Read (message_start primes turn + model/provider
@@ -662,14 +662,15 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
);
expect(tool1Create?.[0].parentId).toBe('ast-initial');
- // Assistant for step 2 β€” parentId should be step 1's TOOL message (not assistant)
+ // Assistant for step 2 β€” parentId should be the spine (the initial
+ // assistant), NOT step 1's tool. Tools are inline children of their own
+ // assistant; the next assistant chains off the most recent non-tool
+ // main message (the spine).
const step2Assistant = mockCreateMessage.mock.calls.find(
([p]: any) => p.role === 'assistant' && p.parentId !== undefined,
);
expect(step2Assistant).toBeDefined();
- // The parentId should be the (pre-allocated) tool message ID from step 1
- const tool1Id = tool1Create![0].id;
- expect(step2Assistant![0].parentId).toBe(tool1Id);
+ expect(step2Assistant![0].parentId).toBe('ast-initial');
// createMessage should carry the adapter provider so step 2's assistant
// lands in DB with provider set from the start (no later backfill needed).
expect(step2Assistant![0].provider).toBe('claude-code');
@@ -1479,15 +1480,14 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
const newAstId = mockCreateMessage.mock.calls.find(
([params]: any) => params.role === 'assistant',
)![0].id;
- const item1ToolId = mockCreateMessage.mock.calls.find(
- ([params]: any) => params.role === 'tool' && params.tool_call_id === 'item_1',
- )![0].id;
+ // The second-turn assistant chains off the spine (turn 1's assistant,
+ // here the initial one), NOT turn 1's last tool.
const secondTurnAssistantCreate = mockCreateMessage.mock.calls.find(
([params]: any) => params.role === 'assistant',
);
expect(secondTurnAssistantCreate?.[0]).toMatchObject({
- parentId: item1ToolId,
+ parentId: 'ast-initial',
role: 'assistant',
});
@@ -1662,18 +1662,16 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
([params]: any) => params.role === 'assistant',
);
expect(assistantCreates).toHaveLength(2);
- const toolIdOf = (callId: string) =>
- mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === callId,
- )![0].id;
const newAst1 = assistantCreates[0]![0].id;
const newAst2 = assistantCreates[1]![0].id;
+ // The cut assistants chain along the spine (each off the previous
+ // non-tool main message), NOT off the preceding turn's last tool.
expect(assistantCreates[0]?.[0]).toMatchObject({
- parentId: toolIdOf('item_3'),
+ parentId: 'ast-initial',
role: 'assistant',
});
expect(assistantCreates[1]?.[0]).toMatchObject({
- parentId: toolIdOf('item_6'),
+ parentId: newAst1,
role: 'assistant',
});
@@ -2246,9 +2244,10 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect.any(Object),
);
- // 3. Step 2 assistant created chained off the Read tool message
+ // 3. Step 2 assistant created chained off the spine (the initial
+ // assistant), with the Read tool inline under step 1.
const step2Create = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'assistant' && p.parentId === readToolId,
+ ([p]: any) => p.role === 'assistant' && p.parentId === 'ast-initial',
);
expect(step2Create).toBeDefined();
@@ -2267,9 +2266,10 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect.any(Object),
);
- // 6. Step 3 assistant created chained off the Write tool message
+ // 6. Step 3 assistant created chained off the spine (step 2 assistant),
+ // with the Write tool inline under step 2.
const step3Create = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'assistant' && p.parentId === writeToolId,
+ ([p]: any) => p.role === 'assistant' && p.parentId === step2Create![0].id,
);
expect(step3Create).toBeDefined();
@@ -2843,20 +2843,18 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
);
expect(terminalCreate).toBeDefined();
- // Terminal message should chain off the last tool, not off the
- // thread's initial assistant, so the transcript flows
- // user β†’ asst(tools) β†’ tool β†’ asst(result).
+ // Terminal message chains off the in-thread assistant (the subagent
+ // spine), with the child tool inline, so the transcript flows
+ // user β†’ asst(tools) β†’ asst(result) β€” the subagent reducer keeps the
+ // chain anchor on the assistant instead of advancing it to the tool.
const toolCreate = mockCreateMessage.mock.calls.find(
([payload]: any) => payload.role === 'tool' && payload.tool_call_id === 'toolu_child',
);
expect(toolCreate).toBeDefined();
- // The tool create returns an id; since the mock returns { id } we
- // just assert the terminal's parentId is NOT the first assistant
- // (id of which was returned earlier in mockCreateMessage).
const firstAssistantCreate = mockCreateMessage.mock.calls.find(
([payload]: any) => payload.role === 'assistant' && payload.threadId === threadId,
);
- expect(terminalCreate![0].parentId).not.toBe(firstAssistantCreate![0].id);
+ expect(terminalCreate![0].parentId).toBe(firstAssistantCreate![0].id);
});
it('streams the terminal assistant into the thread messagesMap bucket', async () => {
@@ -3222,11 +3220,14 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
describe('Monitor parentId chain', () => {
/**
* Monitor pattern: initial tool_use returns immediately ("Monitor started"),
- * then Monitor's stdout is fed back as synthetic user content that drives
- * new CC assistant turns. Each step should parent to the previous step's
- * last tool message to form a single assistantGroup in the UI.
+ * then Monitor's stdout drives new CC assistant turns. These reactive steps
+ * arrive as ordinary CC message steps (no `task_started`/`task_notification`
+ * signal context β€” see the `external signal` describe below for the tagged
+ * case), so under the spine rule each one parents off the most recent
+ * non-tool main message: the conversation chains user β†’ asst β†’ asst with
+ * tools inline, and the reactive callbacks render as plain spine assistants.
*/
- it('basic flow: each step parents to previous step last tool', async () => {
+ it('basic flow: each reactive step chains along the spine', async () => {
const idCounter = { tool: 0, assistant: 0 };
mockCreateMessage.mockImplementation(async (params: any) => {
if (params.role === 'tool') {
@@ -3267,22 +3268,18 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// Two new assistants (step 1 + step 2); step 0 uses ast-initial
expect(assistantCreates.length).toBe(2);
- const toolId = (callId: string) =>
- mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === callId,
- )![0].id;
- // Step 1 parent = Monitor tool from step 0
- expect(assistantCreates[0][0].parentId).toBe(toolId('toolu_mon_0'));
- // Step 2 parent = LAST tool from step 1 = Monitor_1
- expect(assistantCreates[1][0].parentId).toBe(toolId('toolu_mon_1'));
+ // Step 1 parent = the spine (initial assistant); its tools are inline.
+ expect(assistantCreates[0][0].parentId).toBe('ast-initial');
+ // Step 2 parent = the spine advanced to step 1's assistant.
+ expect(assistantCreates[1][0].parentId).toBe(assistantCreates[0][0].id);
});
/**
- * regression: a toolless step in the middle must NOT break the
- * zigzag chain. The next step should chain back to the most recent tool
- * result ever produced in the run, not to the toolless assistant.
+ * regression: a toolless step in the middle keeps the spine linear.
+ * The next step chains off the toolless assistant (the most recent
+ * non-tool main message), so no message is orphaned.
*/
- it('toolless middle step: next step chains back to last real tool', async () => {
+ it('toolless middle step: spine stays linear through the toolless step', async () => {
const idCounter = { tool: 0, assistant: 0 };
mockCreateMessage.mockImplementation(async (params: any) => {
if (params.role === 'tool') {
@@ -3311,26 +3308,21 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
);
expect(assistantCreates.length).toBe(2);
- const monitorToolId = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_mon_0',
- )![0].id;
- // Step 1 parent = Monitor tool from step 0
- expect(assistantCreates[0][0].parentId).toBe(monitorToolId);
+ // Step 1 (toolless) parent = the spine (initial assistant).
+ expect(assistantCreates[0][0].parentId).toBe('ast-initial');
- // Step 2 parent: step 1 was toolless, but the chain must skip back to
- // step 0's Monitor so MessageCollector's assistant β†’ tool β†’ assistant
- // walk keeps every assistant in the same group.
- expect(assistantCreates[1][0].parentId).toBe(monitorToolId);
+ // Step 2 parent = step 1's assistant: the spine advances on the toolless
+ // step too, so the chain stays linear (no skip-back to a tool needed).
+ expect(assistantCreates[1][0].parentId).toBe(assistantCreates[0][0].id);
});
/**
* follow-up: N consecutive toolless steps (Monitor pushing
* stdout line by line, each line triggering a new LLM call that only
- * answers with text). All toolless assistants must chain back to the
- * same originating tool result; otherwise the UI splits one bubble per
- * Monitor line.
+ * answers with text). Each toolless assistant chains off the previous
+ * one, forming a continuous spine β€” no message is dropped.
*/
- it('consecutive toolless steps: all parents resolve to the originating tool', async () => {
+ it('consecutive toolless steps: each chains off the previous spine assistant', async () => {
const idCounter = { tool: 0, assistant: 0 };
mockCreateMessage.mockImplementation(async (params: any) => {
if (params.role === 'tool') {
@@ -3362,16 +3354,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
// 4 new assistants (steps 1–4); step 0 reuses ast-initial
expect(assistantCreates.length).toBe(4);
- const monitorToolId = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_mon_0',
- )![0].id;
- // All toolless steps chain back to the Monitor tool from step 0
- expect(assistantCreates[0][0].parentId).toBe(monitorToolId);
- expect(assistantCreates[1][0].parentId).toBe(monitorToolId);
- expect(assistantCreates[2][0].parentId).toBe(monitorToolId);
- // Step 4 also chains to the Monitor tool β€” its own step had no tools yet
- // at step_start, the Bash tool only persists after stream_start fires.
- expect(assistantCreates[3][0].parentId).toBe(monitorToolId);
+ // Each step chains off the previous spine assistant; step 1 off the seed.
+ expect(assistantCreates[0][0].parentId).toBe('ast-initial');
+ expect(assistantCreates[1][0].parentId).toBe(assistantCreates[0][0].id);
+ expect(assistantCreates[2][0].parentId).toBe(assistantCreates[1][0].id);
+ expect(assistantCreates[3][0].parentId).toBe(assistantCreates[2][0].id);
});
/**
@@ -3412,13 +3399,10 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
([p]: any) => p.role === 'assistant',
);
expect(assistantCreates.length).toBe(1);
- // Step 1 parent should be the Monitor tool from step 0. The tool message
- // id is pre-allocated by the reducer (carried in the persistToolBatch
- // intent), so the chain resolves even though the tool_result interleaves.
- const monitorToolId = mockCreateMessage.mock.calls.find(
- ([p]: any) => p.role === 'tool' && p.tool_call_id === 'toolu_mon_0',
- )![0].id;
- expect(assistantCreates[0][0].parentId).toBe(monitorToolId);
+ // Step 1 parent = the spine (initial assistant). The interleaved Monitor
+ // tool_result does not affect the chain: the spine anchor is the most
+ // recent non-tool main message, independent of tool timing.
+ expect(assistantCreates[0][0].parentId).toBe('ast-initial');
});
});