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): promote a tools-bearing signal turn back onto the spine (#16750)

Arvin Xud02d2f8d27b0
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 61af3ca4e0c..ad070928446 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -546,8 +546,10 @@ export class HeterogeneousPersistenceHandler {
if (snapshot.provider) state.main.turnProvider = snapshot.provider;
// Recover the chain spine from the DB. 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
+ // turn parents off the run's latest main-thread message that is neither a
+ // tool nor a TOOLLESS signal callback (a tools-bearing signal turn is
+ // main-chain — see `getLastMainThreadSpineMessageId`); 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
diff --git a/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts b/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts
new file mode 100644
index 00000000000..a57c1568647
--- /dev/null
+++ b/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Message } from '../../types';
+import { BranchResolver } from '../BranchResolver';
+import { FlatListBuilder } from '../FlatListBuilder';
+import { MessageCollector } from '../MessageCollector';
+import { MessageTransformer } from '../MessageTransformer';
+
+/**
+ * Read-side half of the tpc_aGIggi9N8DpK "trace 和回复对不上 + 中间截断" fix.
+ *
+ * The write side (main-agent reducer) tags a turn `signal` at stream_start,
+ * before it knows the turn will call tools. A reactive turn that CC re-invokes
+ * off a long-running Bash `Wait for … agent` (`tool-stdout` / `task-completion`)
+ * can then emit its OWN tool_use — at which point it is really back on the main
+ * chain. `reduceMainAgent` now PROMOTES such a turn onto the spine so the next
+ * 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:
+ * - 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.
+ */
+
+const toolArr = (id: string) => [
+ { apiName: 'Bash', arguments: '{}', id, identifier: 'claude-code', type: 'default' as const },
+];
+
+const flatten = (messages: Message[]) => {
+ const messageMap = new Map<string, Message>();
+ const childrenMap = new Map<string | null, string[]>();
+ messages.forEach((msg) => {
+ messageMap.set(msg.id, msg);
+ const parentId = msg.parentId || null;
+ if (!childrenMap.has(parentId)) childrenMap.set(parentId, []);
+ childrenMap.get(parentId)!.push(msg.id);
+ });
+ const builder = new FlatListBuilder(
+ messageMap,
+ new Map(),
+ childrenMap,
+ new BranchResolver(),
+ new MessageCollector(messageMap, childrenMap),
+ new MessageTransformer(),
+ );
+ return builder.flatten(messages);
+};
+
+// 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
+// content ("明白了。两点都定了") AND emits its own tool_use
+// S2 — the next real turn ("完整判断"); `parentOfS2` is what the write side
+// computes for it — SIG when promoted (linear), W when not (forked)
+// TAIL — the final answer ("完整方案"), the message that disappeared in the UI
+const scenario = (parentOfS2: 'SIG' | 'W'): Message[] => [
+ { content: 'go', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },
+ {
+ agentId: 'a', content: '三个探测都回来了,先给你结论', createdAt: 100, id: 'W',
+ parentId: 'u1', role: 'assistant', tools: toolArr('bashwait'), updatedAt: 100,
+ },
+ {
+ content: 'agent done', createdAt: 110, id: 'toolW', parentId: 'W',
+ role: 'tool', tool_call_id: 'bashwait', updatedAt: 110,
+ } as any,
+ {
+ agentId: 'a', content: 'TASKCOMP 明白了。两点都定了', createdAt: 120, id: 'SIG',
+ // Tagged signal at stream_start — but it carries tools, so it is main-chain.
+ metadata: {
+ signal: { sourceToolCallId: 'bashwait', sourceToolName: 'Bash', type: 'task-completion' },
+ } as any,
+ parentId: 'toolW', role: 'assistant', tools: toolArr('bash2'), updatedAt: 120,
+ },
+ {
+ content: 'ok', createdAt: 125, id: 'toolSig', parentId: 'SIG',
+ role: 'tool', tool_call_id: 'bash2', updatedAt: 125,
+ } as any,
+ {
+ agentId: 'a', content: '现在给你完整判断', createdAt: 130, id: 'S2',
+ parentId: parentOfS2, role: 'assistant', tools: toolArr('bash3'), updatedAt: 130,
+ },
+ {
+ content: 'ok2', createdAt: 135, id: 'toolS2', parentId: 'S2',
+ role: 'tool', tool_call_id: 'bash3', updatedAt: 135,
+ } as any,
+ {
+ agentId: 'a', content: 'TAILMARKER 两个开关都定位到了,完整方案', createdAt: 140,
+ id: 'TAIL', parentId: 'S2', role: 'assistant', updatedAt: 140,
+ },
+];
+
+describe('signal turn that emits tools — spine promotion (tpc_aGIggi9N8DpK)', () => {
+ it('LINEAR (post-fix): the promoted turn keeps the chain whole — tail renders', () => {
+ const flat = flatten(scenario('SIG'));
+ const json = JSON.stringify(flat);
+
+ // The whole spine collapses into a single assistantGroup; both the
+ // task-completion content and the final answer are present.
+ expect(json).toContain('TASKCOMP');
+ expect(json).toContain('TAILMARKER');
+
+ // The tools-bearing signal turn is NOT folded into a SignalCallbacks
+ // accordion (that is only for toolless reactive pushes).
+ const group = flat.find((m) => m.role === ('assistantGroup' as any)) as any;
+ expect(group).toBeDefined();
+ expect(group.signalCallbacks ?? []).toHaveLength(0);
+ });
+
+ it('FORKED (pre-fix): S2 re-mounts on the pre-signal spine — reader DROPS the tail', () => {
+ 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');
+ });
+});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 47bfe2093c5..f220af14c84 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -2575,10 +2575,11 @@ export class MessageModel {
* needed: a topic runs at most one operation at a time, so the latest spine
* message IS this run's continuation point.
*
- * 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.
+ * Excludes `role:'tool'` (inline children) and TOOLLESS signal-tagged
+ * assistants (`metadata->'signal'` with no tools), which are tool-child
+ * callbacks — anchoring a normal turn onto a callback would orphan it under
+ * the read side's tool-only signal collection. A signal turn that DID emit
+ * tools is back on the main chain and stays a spine candidate.
*/
getLastMainThreadSpineMessageId = async (topicId: string): Promise<string | undefined> =>
this.getLatestSpineMessageId({ topicId, threadId: null });
@@ -2589,10 +2590,11 @@ export class MessageModel {
* NOT a signal-tagged reactive turn) in a topic, scoped to the main thread
* (`threadId IS NULL`) or to a specific thread.
*
- * Like the main-thread query it EXCLUDES `role:'tool'` and signal-tagged
- * assistants: tools are inline children of their assistant turn, so the
- * conversation head a new turn parents off is the assistant, never the tool
- * result that landed under it.
+ * Like the main-thread query it EXCLUDES `role:'tool'` and TOOLLESS
+ * signal-tagged assistants: tools are inline children of their assistant turn,
+ * so the conversation head a new turn parents off is the assistant, never the
+ * tool result that landed under it. A tools-bearing signal turn is main-chain
+ * and remains a spine candidate.
*
* Used by `sendMessageInServer` to make `parentId` server-authoritative and
* close the concurrent-append race: the client computes `parentId` from a
@@ -2616,13 +2618,24 @@ export class MessageModel {
eq(messages.topicId, topicId),
not(eq(messages.role, 'tool')),
threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),
- // Exclude signal-tagged assistants by key existence. The equivalent
- // `metadata -> 'signal' IS NULL` crashes the serverless Postgres engine
- // when used as a WHERE predicate (rt_fetch out-of-bounds, SQLSTATE
- // XX000) — the `->` operator only survives in the SELECT/ORDER BY
- // position, not as a filter qual. `jsonb_exists` is GIN-friendly and
- // equivalent for real data, since the signal tag is always an object.
- sql`NOT COALESCE(jsonb_exists(${messages.metadata}, 'signal'), false)`,
+ // Exclude signal-tagged assistants — BUT only the toolless ones. The
+ // writer tags a turn `signal` at stream_start before it knows the turn
+ // will call tools; a signal turn that DOES emit a tool_use is really
+ // back on the main chain (see `reduceToolsChunk`'s spine promotion),
+ // so it must stay a spine candidate or a cold replica re-forks the
+ // wire off the pre-signal turn. Match the read side, which likewise
+ // treats a tools-bearing message as non-signal (`getMessageSignal`).
+ //
+ // Key existence (`jsonb_exists`) is used instead of `metadata -> 'signal'
+ // IS NULL`, which crashes the serverless Postgres engine as a WHERE
+ // predicate (rt_fetch out-of-bounds, SQLSTATE XX000 — the `->` operator
+ // only survives in SELECT/ORDER BY). Toolless is expressed with plain
+ // jsonb equality (`= '[]'` / IS NULL) rather than `jsonb_array_length`,
+ // which is unproven on this engine as a qual.
+ sql`NOT (
+ COALESCE(jsonb_exists(${messages.metadata}, 'signal'), false)
+ AND (${messages.tools} IS NULL OR ${messages.tools} = '[]'::jsonb)
+ )`,
this.ownership(),
),
)
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
index 13624f5adaa..904c434eec6 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
@@ -202,6 +202,39 @@ describe('main agent reducer', () => {
expect(state.lastToolMsgIdEver).toBe('msg_5');
});
+ // ─── A signal turn that EMITS a tool_use is back on the main chain ───
+ // Regression for the "trace 和回复对不上 + 中间截断" render bug (tpc_aGIggi9N8DpK):
+ // CC re-invoked the LLM off a long-running Bash `Wait for … agent` (a
+ // tool-stdout / task-completion signal), and that turn then kept calling
+ // tools. Tagged `signal`, it mounted on the source tool and did NOT advance
+ // the spine, so the NEXT normal turn re-mounted on the PRE-signal assistant —
+ // forking the wire. The read side picks the earliest continuation at the fork
+ // (the signal branch) and drops everything after it (the real conclusions).
+ it('promotes a tools-bearing signal turn onto the spine so the next turn chains off it', () => {
+ const { steps, state } = run([
+ textEvent('waiting on agent'),
+ toolsEvent([tool('t1')]), // long-running Bash Wait → msg_1
+ newStepEvent(stdoutSignal(1)), // signal turn re-invoked by the tool → msg_2 (parent msg_1)
+ textEvent('明白了。两点都定了'), // the signal turn carries REAL content …
+ toolsEvent([tool('t2')]), // … AND emits a tool_use → back on the main chain → msg_3
+ newStepEvent(), // the next normal turn → msg_4
+ ]);
+
+ const created = steps
+ .flatMap((s) => ofKind(s, 'createAssistant'))
+ .map((c) => ({ messageId: c.messageId, parentId: c.parentId, signalType: c.signal?.type }));
+
+ expect(created).toEqual([
+ // The signal turn still MOUNTS on the source tool (its persisted anchor).
+ { messageId: 'msg_2', parentId: 'msg_1', signalType: 'tool-stdout' },
+ // …but because it emitted a tool_use, the spine advanced onto it, so the
+ // next normal turn chains off msg_2 — NOT the pre-signal spine A0. That
+ // linear chain is what keeps the read side from dropping the tail.
+ { messageId: 'msg_4', parentId: 'msg_2', signalType: undefined },
+ ]);
+ expect(state.lastSpineMessageId).toBe('msg_4');
+ });
+
it('falls back to the current assistant only before any tool exists', () => {
const { steps } = run([textEvent('hi'), newStepEvent()]); // no tool ever seen
expect(ofKind(steps[1], 'createAssistant')[0]).toMatchObject({
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
index 07c6fc02144..3f7974502b7 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
@@ -156,8 +156,11 @@ const openTurn = (state: MainAgentRunState, data: any, ctx: MainAgentReduceCtx):
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.
+ // spine assistant, not on the callback. But a signal turn that goes on to
+ // emit a tool_use is really back on the main chain: `reduceToolsChunk`
+ // promotes it onto the spine, gated on this flag.
if (!isSignalTurn) next.lastSpineMessageId = messageId;
+ next.currentTurnIsSignal = isSignalTurn;
next.currentMainMessageId = mainMessageId;
next.accContent = '';
next.accReasoning = '';
@@ -274,6 +277,16 @@ const reduceToolsChunk = (
const lastToolMsgId = newToolMsgIds.at(-1);
if (lastToolMsgId) next.lastToolMsgIdEver = lastToolMsgId;
+ // A signal/reactive turn that emits a tool_use is back on the main chain (the
+ // reactive-push phase is over — mirrors the adapter dropping its pending
+ // signal on the next tool_use). Promote it onto the spine so the NEXT normal
+ // turn chains off THIS turn, not the pre-signal spine assistant. Otherwise the
+ // wire forks and the read side drops everything after the fork. Consume once.
+ if (next.currentTurnIsSignal) {
+ next.lastSpineMessageId = next.currentAssistantId;
+ next.currentTurnIsSignal = false;
+ }
+
return { intents, state: next };
};
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
index 42454c0db0d..84ed5d0408c 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
@@ -79,6 +79,20 @@ export interface MainAgentRunState {
* host-seeded first turn (which never opens via `newStep`, so can't fork).
*/
currentMainMessageId: string | undefined;
+ /**
+ * True while the CURRENT turn was opened as a signal/reactive turn (parented
+ * off a tool via `lastToolMsgIdEver`, spine deliberately NOT advanced). The
+ * writer tags a turn `signal` at `stream_start`, BEFORE it knows the turn will
+ * use tools. A signal turn that then emits a `tool_use` is really back on the
+ * main chain — `reduceToolsChunk` advances the spine onto it so the NEXT
+ * normal turn chains off THIS turn instead of re-mounting on the pre-signal
+ * spine. Without this, the wire forks (`spine → {signal-turn-with-tools,
+ * next-normal-turn}`) and the read side, which picks the earliest continuation
+ * at a fork, walks into the signal branch and drops the post-fork tail — the
+ * "trace 和回复对不上 + 中间截断" render bug. Consumed on the first tool batch;
+ * reset per turn in `openTurn`.
+ */
+ currentTurnIsSignal: boolean;
/** Set once a terminal event has been reduced (idempotent finalize). */
ended: boolean;
/**
@@ -124,6 +138,7 @@ export const createMainAgentRunState = (seedAssistantId: string): MainAgentRunSt
accReasoning: '',
currentAssistantId: seedAssistantId,
currentMainMessageId: undefined,
+ currentTurnIsSignal: false,
ended: false,
lastSpineMessageId: seedAssistantId,
lastTextSnapshotSeq: 0,