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 every background-task wake-up in the run's reply (#21939)

AmAzing-c135e007db85
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts
index 905e4ee07e8..c1a5f9beba9 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.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 remote-device chain-fork (observed on tpc_3DKmFfAmx9YA):
@@ -345,3 +346,71 @@ describe('HeterogeneousPersistenceHandler β€” signal turn anchor on a cold repli
expect(signalTurn(h.messages)?.parentId).toBe(SEED);
});
});
+
+/**
+ * Observed in a production topic: two background tasks woke the LLM one after
+ * the other, and each wake-up called a tool. The first wake-up landed on another
+ * replica, so the replica that ran the main turn still held the main turn's tool
+ * as `lastToolMsgIdEver` when the second wake-up reached it. Both wake-ups ended
+ * up under that one tool, and the UI showed only the first.
+ */
+describe('HeterogeneousPersistenceHandler β€” signal turn anchor on a stale warm replica', () => {
+ beforeEach(() => __resetOperationStatesForTesting());
+ afterEach(() => __resetOperationStatesForTesting());
+
+ const textStep = (stepIndex: number, ccMsgId: string, content: string): AgentStreamEvent[] => [
+ buildEvent('stream_start', stepIndex, {
+ messageId: ccMsgId,
+ newStep: true,
+ provider: 'claude-code',
+ }),
+ buildEvent('stream_chunk', stepIndex, { chunkType: 'text', content }),
+ ];
+
+ const wakeUpStep = (
+ stepIndex: number,
+ ccMsgId: string,
+ toolCallId: string,
+ ): AgentStreamEvent[] => [
+ buildEvent('stream_start', stepIndex, {
+ externalSignal: {
+ sourceToolCallId: 'tc-A',
+ sourceToolName: 'Agent',
+ type: 'task-completion',
+ },
+ messageId: ccMsgId,
+ newStep: true,
+ provider: 'claude-code',
+ }),
+ buildEvent('stream_chunk', stepIndex, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ { apiName: 'Bash', arguments: '{}', id: toolCallId, identifier: 'bash', type: 'default' },
+ ],
+ }),
+ ];
+
+ it("anchors the second wake-up onto the first wake-up's tool", async () => {
+ const h = createHarness();
+ const ingest = (events: AgentStreamEvent[]) =>
+ h.handler.ingest({ assistantMessageId: SEED, events, operationId: OP, topicId: TOPIC });
+
+ // Replica A: the main turn launches the task and ends without tools.
+ await ingest([...stepBatch(1, 'cc-A', 'tc-A'), ...textStep(2, 'cc-B', 'still running')]);
+ const replicaA = operationStates.get(OP)!;
+
+ // Replica B: the first wake-up reads the task output, then replies.
+ __resetOperationStatesForTesting();
+ await ingest([...wakeUpStep(3, 'cc-C', 'tc-W1'), ...textStep(4, 'cc-D', 'one task left')]);
+
+ // Replica A again, warm but behind: the second wake-up.
+ __resetOperationStatesForTesting();
+ operationStates.set(OP, replicaA);
+ await ingest(wakeUpStep(5, 'cc-E', 'tc-W2'));
+
+ const toolOf = (toolCallId: string) =>
+ [...h.messages.values()].find((m) => m.tool_call_id === toolCallId)!;
+ const secondWakeUp = toolOf('tc-W2').parentId;
+ expect(h.messages.get(secondWakeUp!)?.parentId).toBe(toolOf('tc-W1').id);
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
index 1826c6800f6..ceea14cb7b9 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts
@@ -139,7 +139,8 @@ export class HeterogeneousPersistenceHandler {
await refreshMainStateFromDb(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.
+ // lookup for the rest. Re-read it even when warm: another replica may have
+ // persisted a newer tool since this one last saw the run.
if (params.events.some(opensSignalTurn)) {
await recoverLastToolMessageFromDb(this.deps, state);
}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
index ea51dca2cdf..77ee8bee4d8 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
@@ -427,21 +427,24 @@ const MAX_SIGNAL_ANCHOR_HOPS = 50;
/**
* Recover `lastToolMsgIdEver` β€” the anchor a signal turn (a background task's
- * wake-up) parents off β€” on a replica that never reduced this run's tool
- * batches. Without it the signal turn falls back onto the toolless spine reply,
- * and the read side, which only collects signal turns under tools, renders it
- * as a separate top-level reply.
+ * wake-up) parents off β€” from the DB instead of trusting this replica's memory.
+ *
+ * A replica that never reduced this run's tool batches has no anchor, so the
+ * signal turn falls back onto the toolless spine reply, and the read side, which
+ * only collects signal turns under tools, renders it as a separate top-level
+ * reply. A warm replica can hold an anchor that another replica has since moved
+ * past (an earlier wake-up called a tool there), which puts the wake-up under an
+ * older tool next to the earlier one. The DB is current in both cases.
*
* Walks the spine from its tip back through main-thread assistants and takes
* the last tool of the first one that called any. Stopping at the first
- * non-assistant (the run's user message) keeps a previous run's tools out.
+ * non-assistant (the run's user message) keeps a previous run's tools out. When
+ * the walk finds no tool, the in-memory anchor stays.
*/
export async function recoverLastToolMessageFromDb(
deps: HeterogeneousPersistenceHandlerDeps,
state: OperationState,
): Promise<void> {
- if (state.main.lastToolMsgIdEver) return;
-
const threadId = state.threadId ?? null;
let messageId: string | null | undefined = state.main.lastSpineMessageId;
for (let hop = 0; messageId && hop < MAX_SIGNAL_ANCHOR_HOPS; hop++) {
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 803f908703f..b2df2289f26 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -723,18 +723,14 @@ export class FlatListBuilder {
const tail = assistantChain.at(-1);
if (!tail) return;
- for (const assistant of assistantChain.slice(0, -1)) {
+ for (const [index, assistant] of assistantChain.slice(0, -1).entries()) {
const childIds = this.childrenMap.get(assistant.id) ?? [];
- const interruptions = childIds.filter((id) => {
- const message = this.messageMap.get(id);
- return (
- message?.role === 'user' &&
- !message.threadId &&
- !processedIds.has(id) &&
- toTime(message.createdAt) >= toTime(assistant.createdAt) &&
- toTime(message.createdAt) <= toTime(tail.createdAt)
- );
- });
+ const interruptions = this.messageCollector.collectGroupInterruptions(
+ assistant,
+ assistantChain[index + 1],
+ tail,
+ processedIds,
+ );
if (interruptions.length === 0) continue;
const activeId = this.branchResolver.getActiveBranchIdFromMetadata(
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index efe2c2752d1..42f5969e091 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -1,5 +1,4 @@
import { isInThreadScope } from '../indexing';
-import { toTime } from '../utils/timestamp';
import type {
ContextNode,
IdNode,
@@ -8,6 +7,7 @@ import type {
SignalCallbacksNode,
ThreadScope,
} from '../types';
+import { toTime } from '../utils/timestamp';
import { BranchResolver } from './BranchResolver';
/**
@@ -52,6 +52,17 @@ const isCallbackSignal = (sig: MessageSignal | undefined): boolean =>
const isTaskCompletionSignal = (sig: MessageSignal | undefined): boolean =>
sig?.type === 'task-completion';
+/**
+ * A signal-tagged turn that called tools: a background task woke the LLM and it
+ * went back to work on the main chain. `getMessageSignal` hides its tag so the
+ * chain walks it, but it is a later step, never a regenerated branch, so it must
+ * not compete with the step's other continuations in branch resolution.
+ */
+const isWakeUpTurn = (msg: Message): boolean =>
+ msg.role === 'assistant' &&
+ !!msg.tools?.length &&
+ !!(msg.metadata as { signal?: MessageSignal } | undefined | null)?.signal;
+
/** Lookups over one message array, each list in that array's order. */
interface MessageArrayIndex {
/** Keyed by the raw `parentId` (not `childrenMap`, which remaps orphans and compressed groups). */
@@ -206,10 +217,18 @@ export class MessageCollector {
const groupAgentId = assistant.agentId;
const allMessages = this.scopedMessages();
const visited = new Set<string>([assistant.id]);
+ const pending: Message[] = [];
let current: Message = assistant;
while (true) {
- const next = this.findFlatChainContinuation(current, [], allMessages, visited, groupAgentId);
+ const next = this.findFlatChainContinuation(
+ current,
+ [],
+ allMessages,
+ visited,
+ groupAgentId,
+ pending,
+ );
if (!next) return false;
if (next.tools && next.tools.length > 0) return true;
@@ -232,6 +251,8 @@ export class MessageCollector {
allToolMessages: Message[],
processedIds: Set<string>,
): void {
+ // Continuations found at earlier steps that a sooner one went ahead of.
+ const pending: Message[] = [];
let current: Message | undefined = currentAssistant;
while (current) {
current = this.collectAssistantChainStep(
@@ -240,6 +261,7 @@ export class MessageCollector {
assistantChain,
allToolMessages,
processedIds,
+ pending,
);
}
}
@@ -254,6 +276,7 @@ export class MessageCollector {
assistantChain: Message[],
allToolMessages: Message[],
processedIds: Set<string>,
+ pending: Message[],
): Message | undefined {
if (processedIds.has(currentAssistant.id)) return;
@@ -280,6 +303,7 @@ export class MessageCollector {
allMessages,
processedIds,
groupAgentId,
+ pending,
);
if (!continuation) return;
@@ -304,6 +328,7 @@ export class MessageCollector {
allMessages,
processedIds,
groupAgentId,
+ pending,
);
}
@@ -329,6 +354,12 @@ export class MessageCollector {
* first resolve the active direct child of this assistant (including
* continuations under different tool results), then resolve regenerated
* siblings under that child.
+ *
+ * Wake-up turns ({@link isWakeUpTurn}) skip branch resolution. The writer
+ * parents them off the run's latest tool result, so they sit next to the
+ * toolless reply that ended the turn, and two of them can share one tool.
+ * They join `pending` with the active continuation, and the earliest pending
+ * one becomes the next step, so every turn renders in creation order.
*/
private findFlatChainContinuation(
currentAssistant: Message,
@@ -336,6 +367,7 @@ export class MessageCollector {
allMessages: Message[],
processedIds: Set<string>,
groupAgentId: string | undefined,
+ pending: Message[],
): Message | undefined {
const candidateParentIds = new Set<string>();
let hasFanOutTool = false;
@@ -354,26 +386,33 @@ export class MessageCollector {
// Equal timestamps fall back to array order, as a stable sort of the
// whole array did before the index.
const { position } = this.messageIndex(allMessages);
+ const byCreation = (a: Message, b: Message) =>
+ toTime(a.createdAt) - toTime(b.createdAt) || position.get(a.id)! - position.get(b.id)!;
const candidates = [...candidateParentIds]
.flatMap((parentId) => this.childrenOf(allMessages, parentId))
.filter((m) => m.role !== 'tool' && !processedIds.has(m.id))
.filter((m) => m.role === 'assistant' && m.agentId === groupAgentId && !getMessageSignal(m))
- .sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt) || position.get(a.id)! - position.get(b.id)!);
-
- const activeId = this.resolveActiveContinuationId(candidates, currentAssistant);
- if (!activeId) {
- this.markUnselectedContinuations(undefined, candidates, processedIds);
- return;
+ .sort(byCreation);
+ const wakeUps = candidates.filter(isWakeUpTurn);
+ const branchCandidates = candidates.filter((m) => !isWakeUpTurn(m));
+
+ const activeId = this.resolveActiveContinuationId(branchCandidates, currentAssistant);
+ const activeContinuation = branchCandidates.find((message) => message.id === activeId);
+ this.markUnselectedContinuations(activeContinuation?.id, branchCandidates, processedIds);
+
+ if (branchCandidates.length > 0 && !activeContinuation) {
+ // No active branch here (one is still being created): the chain stops at
+ // this step, so its wake-ups go with it.
+ this.markUnselectedContinuations(undefined, wakeUps, processedIds);
+ } else {
+ if (activeContinuation) pending.push(activeContinuation);
+ pending.push(...wakeUps);
}
- const activeContinuation = candidates.find((message) => message.id === activeId);
- if (!activeContinuation) {
- this.markUnselectedContinuations(undefined, candidates, processedIds);
- return;
- }
-
- this.markUnselectedContinuations(activeContinuation.id, candidates, processedIds);
- return activeContinuation;
+ pending.sort(byCreation);
+ let next = pending.shift();
+ while (next && processedIds.has(next.id)) next = pending.shift();
+ return next;
}
/**
@@ -539,6 +578,40 @@ export class MessageCollector {
return completions;
}
+ /**
+ * User turns that interrupted a folded group at `assistant`, an intermediate
+ * step whose next step in the chain is `next`. Branch selection among them
+ * stays with the caller.
+ *
+ * A user turn sent after the group's tail is a deliberate rewind and stays
+ * hidden, unless the chain reached `next` from the wake-up queue rather than
+ * from `assistant` itself. Nothing at `assistant` then competes with the user
+ * turn, and it can postdate the tail: before wake-ups joined the chain,
+ * `assistant` was where the rendered reply ended, so users replied to it.
+ */
+ collectGroupInterruptions(
+ assistant: Message,
+ next: Message,
+ tail: Message,
+ processedIds: Set<string>,
+ ): string[] {
+ const nextParent = next.parentId ? this.messageMap.get(next.parentId) : undefined;
+ const continuesHere =
+ next.parentId === assistant.id ||
+ (nextParent?.role === 'tool' && nextParent.parentId === assistant.id);
+
+ return (this.childrenMap.get(assistant.id) ?? []).filter((id) => {
+ const message = this.messageMap.get(id);
+ return (
+ message?.role === 'user' &&
+ !message.threadId &&
+ !processedIds.has(id) &&
+ toTime(message.createdAt) >= toTime(assistant.createdAt) &&
+ (!continuesHere || toTime(message.createdAt) <= toTime(tail.createdAt))
+ );
+ });
+ }
+
/**
* Collect assistant messages for an AssistantGroup (contextTree version)
* Only collects messages from the SAME agent (matching agentId)
@@ -553,10 +626,17 @@ export class MessageCollector {
const agentId = groupAgentId ?? message.agentId;
// Walked iteratively: a group's chain can be thousands of steps long.
+ const pending: IdNode[] = [];
let currentMessage: Message | undefined = message;
let currentNode: IdNode | undefined = idNode;
while (currentMessage && currentNode) {
- currentNode = this.collectAssistantGroupStep(currentMessage, currentNode, children, agentId);
+ currentNode = this.collectAssistantGroupStep(
+ currentMessage,
+ currentNode,
+ children,
+ agentId,
+ pending,
+ );
currentMessage = currentNode ? this.messageMap.get(currentNode.id) : undefined;
}
}
@@ -569,6 +649,7 @@ export class MessageCollector {
idNode: IdNode,
children: ContextNode[],
agentId: string | undefined,
+ pending: IdNode[],
): IdNode | undefined {
// Get tool message IDs if this assistant has tools
const toolIds = idNode.children
@@ -589,7 +670,7 @@ export class MessageCollector {
children.push(messageNode);
// Find the next step's assistant (dual-form aware, see findChainContinuationNode)
- return this.findChainContinuationNode(idNode, agentId);
+ return this.findChainContinuationNode(idNode, agentId, pending);
}
/**
@@ -599,9 +680,14 @@ export class MessageCollector {
* assistant-anchored post-task summary) and branch resolution (>1 non-tool
* siblings under one parent β‡’ pick the active branch) as the flat variant.
* Signal-tagged toolless siblings (Monitor callbacks etc.) are skipped so the
- * main chain walks the real follower.
+ * main chain walks the real follower, and wake-up turns queue in `pending`
+ * outside branch resolution, as in the flat variant.
*/
- private findChainContinuationNode(idNode: IdNode, groupAgentId?: string): IdNode | undefined {
+ private findChainContinuationNode(
+ idNode: IdNode,
+ groupAgentId: string | undefined,
+ pending: IdNode[],
+ ): IdNode | undefined {
const candidateNodes: IdNode[] = [];
let hasFanOutTool = false;
@@ -636,12 +722,23 @@ export class MessageCollector {
c.msg?.role === 'assistant' && c.msg.agentId === groupAgentId && !getMessageSignal(c.msg),
)
.sort((a, b) => toTime(a.msg!.createdAt) - toTime(b.msg!.createdAt));
+ const wakeUps = eligible.filter((c) => isWakeUpTurn(c.msg!)).map((c) => c.node);
+ const branchCandidates = eligible.filter((c) => !isWakeUpTurn(c.msg!));
const activeId = this.resolveActiveContinuationId(
- eligible.map((c) => c.msg!),
+ branchCandidates.map((c) => c.msg!),
this.messageMap.get(idNode.id),
);
- return activeId ? eligible.find((c) => c.node.id === activeId)?.node : undefined;
+ const activeNode = branchCandidates.find((c) => c.node.id === activeId)?.node;
+ // No active branch here: the chain stops at this step, so its wake-ups go with it.
+ if (activeNode || branchCandidates.length === 0) {
+ if (activeNode) pending.push(activeNode);
+ pending.push(...wakeUps);
+ }
+
+ const createdAt = (node: IdNode) => toTime(this.messageMap.get(node.id)!.createdAt);
+ pending.sort((a, b) => createdAt(a) - createdAt(b));
+ return pending.shift();
}
/**
@@ -808,11 +905,12 @@ export class MessageCollector {
*/
private findLastAssistantNodeInGroup(idNode: IdNode, groupAgentId?: string): IdNode {
// Iterative: a group's chain can be thousands of steps long.
+ const pending: IdNode[] = [];
let current = idNode;
- let nextNode = this.findChainContinuationNode(current, groupAgentId);
+ let nextNode = this.findChainContinuationNode(current, groupAgentId, pending);
while (nextNode) {
current = nextNode;
- nextNode = this.findChainContinuationNode(current, groupAgentId);
+ nextNode = this.findChainContinuationNode(current, groupAgentId, pending);
}
return current;
}
diff --git a/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts b/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts
index 63bca571222..3b05d5dbe4a 100644
--- a/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
+import { parse } from '../../parse';
import type { Message } from '../../types';
import { BranchResolver } from '../BranchResolver';
import { FlatListBuilder } from '../FlatListBuilder';
@@ -17,11 +18,11 @@ import { MessageTransformer } from '../MessageTransformer';
* normal turn chains off it (see reducer.test.ts "promotes a tools-bearing
* signal turn onto the spine"). That produces the LINEAR shape below.
*
- * These tests pin the read side's behavior on both shapes, proving the write-side
- * promotion is load-bearing:
+ * These tests pin the read side's behavior on both shapes:
* - LINEAR (post-fix): the whole spine renders, tail included.
- * - FORKED (pre-fix): the reader walks into the signal branch at the fork and
- * DROPS the tail β€” exactly the bug the promotion prevents.
+ * - FORKED (pre-fix): the signal turn and the tail both hang off the fork.
+ * A wake-up is never a branch alternative, so the reader
+ * renders both in creation order instead of dropping one.
*/
const toolArr = (id: string) => [
@@ -48,6 +49,13 @@ const flatten = (messages: Message[]) => {
return builder.flatten(messages);
};
+/** Steps of the run's single AssistantGroup, in render order. */
+const groupStepIds = (flat: Message[]): string[] => {
+ const groups = flat.filter((m) => m.role === ('assistantGroup' as any)) as any[];
+ expect(groups).toHaveLength(1);
+ return groups[0].children.map((step: { id: string }) => step.id);
+};
+
// The last fork of tpc_aGIggi9N8DpK, distilled:
// W β€” spine turn that ran a long Bash `Wait for … agent`
// SIG β€” the task-completion signal turn CC re-invoked; it carries REAL
@@ -146,14 +154,165 @@ describe('signal turn that emits tools β€” spine promotion (tpc_aGIggi9N8DpK)',
expect(group.signalCallbacks ?? []).toHaveLength(0);
});
- it('FORKED (pre-fix): S2 re-mounts on the pre-signal spine β€” reader DROPS the tail', () => {
+ it('FORKED (pre-fix): S2 re-mounts on the pre-signal spine β€” both sides of the fork render', () => {
const flat = flatten(scenario('W'));
- const json = JSON.stringify(flat);
- // The signal branch still renders …
- expect(json).toContain('TASKCOMP');
- // … but everything after the fork (the real conclusion) silently vanishes β€”
- // the exact symptom the write-side promotion eliminates.
- expect(json).not.toContain('TAILMARKER');
+ expect(groupStepIds(flat)).toEqual(['W', 'SIG', 'S2', 'TAIL']);
+ });
+});
+
+/**
+ * Observed in a production topic: the main agent left a background search and
+ * an async subagent running, said "waiting" without a tool, and ended its turn.
+ * CC woke the LLM once per finished task, and each wake-up called a tool before
+ * writing its reply. The writer parents every wake-up off the run's latest tool result,
+ * so the first one competes with the closing reply under `RUN`.
+ *
+ * The second wake-up hangs off the first wake-up's tool on a replica that saw the
+ * whole run (LINEAR), or off the same `toolWait` when a stale replica opened it
+ * (STALE). The final answer was missing from the UI in the STALE shape, and the
+ * closing reply was missing in both.
+ */
+describe('wake-up turns that call tools after a toolless closing reply', () => {
+ const wakeUpScenario = (parentOfWake2: 'toolRead1' | 'toolWait'): Message[] => [
+ { content: 'go', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },
+ {
+ agentId: 'a',
+ content: 'waiting on the code-path analysis',
+ createdAt: 100,
+ id: 'RUN',
+ parentId: 'u1',
+ role: 'assistant',
+ tools: toolArr('wait'),
+ updatedAt: 100,
+ },
+ {
+ content: 'waiting',
+ createdAt: 110,
+ id: 'toolWait',
+ parentId: 'RUN',
+ role: 'tool',
+ tool_call_id: 'wait',
+ updatedAt: 110,
+ } as any,
+ {
+ agentId: 'a',
+ content: 'upstream checked, results soon',
+ createdAt: 115,
+ id: 'REPLY',
+ parentId: 'RUN',
+ role: 'assistant',
+ updatedAt: 115,
+ },
+ {
+ agentId: 'a',
+ content: '',
+ createdAt: 120,
+ id: 'WAKE1',
+ metadata: {
+ signal: { sourceToolCallId: 'search', sourceToolName: 'Bash', type: 'task-completion' },
+ } as any,
+ parentId: 'toolWait',
+ role: 'assistant',
+ tools: toolArr('read1'),
+ updatedAt: 120,
+ },
+ {
+ content: 'search output',
+ createdAt: 125,
+ id: 'toolRead1',
+ parentId: 'WAKE1',
+ role: 'tool',
+ tool_call_id: 'read1',
+ updatedAt: 125,
+ } as any,
+ {
+ agentId: 'a',
+ content: 'search finished, still waiting on the subagent',
+ createdAt: 130,
+ id: 'WAKE1_REPLY',
+ parentId: 'WAKE1',
+ role: 'assistant',
+ updatedAt: 130,
+ },
+ {
+ agentId: 'a',
+ content: '',
+ createdAt: 140,
+ id: 'WAKE2',
+ metadata: {
+ signal: { sourceToolCallId: 'subagent', sourceToolName: 'Agent', type: 'task-completion' },
+ } as any,
+ parentId: parentOfWake2,
+ role: 'assistant',
+ tools: toolArr('read2'),
+ updatedAt: 140,
+ },
+ {
+ content: 'script source',
+ createdAt: 145,
+ id: 'toolRead2',
+ parentId: 'WAKE2',
+ role: 'tool',
+ tool_call_id: 'read2',
+ updatedAt: 145,
+ } as any,
+ {
+ agentId: 'a',
+ content: 'final analysis',
+ createdAt: 150,
+ id: 'FINAL',
+ parentId: 'WAKE2',
+ role: 'assistant',
+ updatedAt: 150,
+ },
+ ];
+
+ const everyStep = ['RUN', 'REPLY', 'WAKE1', 'WAKE1_REPLY', 'WAKE2', 'FINAL'];
+
+ /** The contextTree walk follows the same chain rule as the flat list. */
+ const contextTreeStepIds = (messages: Message[]): string[] => {
+ const groups = parse(messages).contextTree.filter((n) => n.type === 'assistantGroup') as any[];
+ expect(groups).toHaveLength(1);
+ return groups[0].children.map((step: { id: string }) => step.id);
+ };
+
+ it('LINEAR: renders the closing reply and every wake-up in order', () => {
+ expect(groupStepIds(flatten(wakeUpScenario('toolRead1')))).toEqual(everyStep);
+ expect(contextTreeStepIds(wakeUpScenario('toolRead1'))).toEqual(everyStep);
+ });
+
+ it('STALE: renders both wake-ups that share one tool result, final answer included', () => {
+ expect(groupStepIds(flatten(wakeUpScenario('toolWait')))).toEqual(everyStep);
+ expect(contextTreeStepIds(wakeUpScenario('toolWait'))).toEqual(everyStep);
+ });
+
+ // Before the read-side fix the STALE shape ended at WAKE1_REPLY, so a user who
+ // kept chatting replied to it, after FINAL already existed.
+ it('STALE: keeps a later follow-up sent to the formerly visible tail', () => {
+ const messages: Message[] = [
+ ...wakeUpScenario('toolWait'),
+ {
+ content: 'follow-up',
+ createdAt: 200,
+ id: 'u2',
+ parentId: 'WAKE1_REPLY',
+ role: 'user',
+ updatedAt: 200,
+ },
+ {
+ agentId: 'a',
+ content: 'answer',
+ createdAt: 210,
+ id: 'a2',
+ parentId: 'u2',
+ role: 'assistant',
+ updatedAt: 210,
+ },
+ ];
+ const flat = flatten(messages);
+
+ expect(groupStepIds(flat)).toEqual(everyStep);
+ expect(flat.map((m) => m.id)).toEqual(['u1', 'RUN', 'u2', 'a2']);
});
});