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): split post-tool answer into its own step when CC reuses the tool message.id (#16127)

Arvin Xu3432707dc9bb
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index d810593dcc1..8b1e54969c1 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -1320,6 +1320,113 @@ describe('ClaudeCodeAdapter', () => {
expect(types).not.toContain('stream_end');
expect(types).not.toContain('stream_start');
});
+
+ // ── Regression: post-tool text must not coalesce onto the tool-issuing turn ──
+ // Observed on a DEVICE (batch / `lh hetero exec`) Claude Code run β€” topic
+ // tpc_58GZ5d8NGPLx, assistant msg_orSJYzAH9HEL9Gb4k3. That run persisted the
+ // final answer text AND the 2 Bash `tool_use` blocks onto a SINGLE assistant
+ // message (the tool-issuing seed, no `metadata.mainMessageId`), while a
+ // trailing EMPTY assistant shell (msg_MUtsnMCWkbtBwcLlAH β€” content_len=0,
+ // `metadata.mainMessageId` set) was spawned. Downstream the renderer then
+ // drops the "Bash (2)" block BELOW the answer because text + tool_use share
+ // one message.
+ //
+ // Proximate cause: when CC reuses a `message.id` to stream the post-tool
+ // continuation (the model answering after a `tool_result`), the
+ // `messageId === this.currentMessageId` short-circuit in `openMainMessage`
+ // returns `[]` β†’ no `newStep` β†’ the text anchors to the same assistant that
+ // issued the tool calls. A turn that has ALREADY emitted `tool_use` must open
+ // a new step before absorbing post-tool text, so the answer lands on its own
+ // assistant (chained after the tool results).
+ //
+ // Fixed in `openMainMessage` / `handleAssistant`: a text-only event on the
+ // in-flight message.id that already emitted a tool_use now forces a step
+ // boundary so the answer anchors to its own assistant.
+ it('opens a new step for post-tool text that reuses the tool_use message.id (regression: tpc_58GZ5d8NGPLx)', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt({ subtype: 'init', type: 'system' });
+
+ // 1. Assistant issues a tool_use under msg_1.
+ adapter.adapt({
+ message: {
+ id: 'msg_1',
+ content: [
+ { id: 'tu_1', input: { command: 'mock command' }, name: 'Bash', type: 'tool_use' },
+ ],
+ },
+ type: 'assistant',
+ });
+
+ // 2. Tool returns.
+ adapter.adapt({
+ message: {
+ content: [{ content: 'mock tool output', tool_use_id: 'tu_1', type: 'tool_result' }],
+ },
+ type: 'user',
+ });
+
+ // 3. Model continues with the final answer β€” CC REUSES msg_1 for this
+ // post-tool text instead of minting a fresh message.id.
+ const events = adapter.adapt({
+ message: { id: 'msg_1', content: [{ text: 'mock post-tool answer', type: 'text' }] },
+ type: 'assistant',
+ });
+
+ // Desired: a step boundary precedes the post-tool text so it anchors to a
+ // NEW assistant, not the tool-issuing turn.
+ const newStep = events.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ expect(newStep).toBeDefined();
+ });
+
+ // The forced split above must NOT reuse the tool turn's message.id as the
+ // newStep id: the main-agent reducer drops a `newStep` whose id equals the
+ // already-open turn's `currentMainMessageId` (replay idempotency). For any
+ // tool turn that was itself opened by a prior newStep, that id IS
+ // currentMainMessageId β€” reusing it would get the split dropped and the text
+ // would coalesce anyway. The first reused-id regression above only escaped
+ // this because the seed turn has no mainMessageId. Here the tool turn (msg_2)
+ // is opened by a real newStep, so the split must carry a DISTINCT key.
+ it('uses a key distinct from the tool turn id when forcing a post-tool split on a non-seed turn', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt({ subtype: 'init', type: 'system' });
+
+ // First turn after init (records msg_1, no step boundary).
+ adapter.adapt({
+ message: { id: 'msg_1', content: [{ text: 'mock first turn', type: 'text' }] },
+ type: 'assistant',
+ });
+
+ // Second turn (NEW id) β€” opened by a real newStep, so the reducer's
+ // currentMainMessageId becomes msg_2. This turn issues a tool_use.
+ adapter.adapt({
+ message: {
+ id: 'msg_2',
+ content: [
+ { id: 'tu_1', input: { command: 'mock command' }, name: 'Bash', type: 'tool_use' },
+ ],
+ },
+ type: 'assistant',
+ });
+ adapter.adapt({
+ message: {
+ content: [{ content: 'mock tool output', tool_use_id: 'tu_1', type: 'tool_result' }],
+ },
+ type: 'user',
+ });
+
+ // Post-tool answer reuses msg_2.
+ const events = adapter.adapt({
+ message: { id: 'msg_2', content: [{ text: 'mock post-tool answer', type: 'text' }] },
+ type: 'assistant',
+ });
+
+ const newStep = events.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ expect(newStep).toBeDefined();
+ // Distinct from the reused id (else the reducer drops it as a replay)…
+ expect(newStep!.data.messageId).not.toBe('msg_2');
+ // …but derived from it, so the key stays traceable + replay-stable.
+ expect(newStep!.data.messageId).toMatch(/^msg_2:/);
+ });
});
describe('usage and model extraction', () => {
@@ -2517,6 +2624,60 @@ describe('ClaudeCodeAdapter', () => {
});
});
+ // Regression (P2): on the BATCH path, when the post-tool confirmation REUSES
+ // the Monitor tool's message.id, the forced split must still consume
+ // `hasUnhandledUserInput` (armed by the tool_result). Otherwise the stale
+ // flag survives and the next callback turn β€” opened while the task is active
+ // with no new user input β€” fails the `!hasUnhandledUserInput` signal check,
+ // leaving the first stdout callback untagged.
+ it('still tags the next callback after a forced post-tool split reuses the tool id (batch Monitor flow)', () => {
+ const adapter = new ClaudeCodeAdapter();
+ init(adapter);
+
+ // Monitor tool_use under msg_01 (batch: an `assistant` event, not a delta).
+ adapter.adapt({
+ message: {
+ content: [
+ { id: 'toolu_mon', input: { shell: 'every 1s' }, name: 'Monitor', type: 'tool_use' },
+ ],
+ id: 'msg_01',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt(ccTaskStarted('task_1', 'toolu_mon'));
+ // tool_result β†’ arms hasUnhandledUserInput.
+ adapter.adapt(ccUser('toolu_mon', 'Monitor started'));
+
+ // Confirmation turn REUSES msg_01 β†’ forced post-tool split. It is the
+ // natural follow-up to the tool_result, so it carries no signal AND must
+ // consume hasUnhandledUserInput.
+ const confirm = adapter.adapt({
+ message: {
+ id: 'msg_01',
+ content: [{ text: 'mock monitoring confirmation', type: 'text' }],
+ },
+ type: 'assistant',
+ });
+ const confirmStart = confirm.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ expect(confirmStart).toBeDefined();
+ expect(confirmStart!.data.externalSignal).toBeUndefined();
+
+ // Monitor pushes an event β†’ CC re-invokes with a NEW id and no new user
+ // input. This callback must be signal-tagged β€” only true once the forced
+ // split cleared the stale flag.
+ const cb1 = adapter.adapt({
+ message: { id: 'msg_02', content: [{ text: 'mock callback turn', type: 'text' }] },
+ type: 'assistant',
+ });
+ const cb1Start = cb1.find((e) => e.type === 'stream_start' && e.data?.newStep);
+ expect(cb1Start!.data.externalSignal).toEqual({
+ sequence: 1,
+ sourceToolCallId: 'toolu_mon',
+ sourceToolName: 'Monitor',
+ type: 'tool-stdout',
+ });
+ });
+
it('keeps tagging consecutive signal callbacks with incrementing sequence', () => {
const adapter = new ClaudeCodeAdapter();
init(adapter);
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index b10780cffd5..b35d6e984ba 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -474,6 +474,17 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
private sawStreamEvent = false;
/** Track current message.id to detect step boundaries */
private currentMessageId: string | undefined;
+ /**
+ * Whether the current turn (the in-flight `currentMessageId`) has already
+ * emitted a `tool_use`. When CC reuses the SAME `message.id` to stream the
+ * model's post-tool answer (it continues after the `tool_result` without
+ * minting a fresh id β€” seen on device/batch `lh hetero exec` runs), that
+ * trailing text must NOT coalesce onto the tool-issuing assistant. We force a
+ * step boundary so the answer anchors to its own assistant, chained after the
+ * tool results β€” otherwise text + `tool_use` share one message and the
+ * renderer drops the tool block below the answer.
+ */
+ private currentTurnHadToolUse = false;
/** message.id of the stream_event delta flow currently in flight */
private currentStreamEventMessageId: string | undefined;
/**
@@ -731,7 +742,22 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
const events: HeterogeneousAgentEvent[] = [];
const messageId = raw.message?.id;
- events.push(...this.openMainMessage(messageId, raw.message?.model));
+ // Detect a post-tool answer that REUSES the tool turn's message.id: a
+ // text-only continuation (no tool_use of its own) on the in-flight id that
+ // already emitted a tool_use. CC does this on device/batch runs where the
+ // model keeps the same id after a tool_result; left unsplit, the answer text
+ // lands on the tool-issuing assistant. An event carrying its OWN tool_use is
+ // a normal preamble-then-tool turn and must stay on the same step.
+ const hasTextBlock = content.some((b: any) => b?.type === 'text' && b.text);
+ const hasToolUseBlock = content.some((b: any) => b?.type === 'tool_use');
+ const isPostToolTextReusingId =
+ hasTextBlock &&
+ !hasToolUseBlock &&
+ messageId !== undefined &&
+ messageId === this.currentMessageId &&
+ this.currentTurnHadToolUse;
+
+ events.push(...this.openMainMessage(messageId, raw.message?.model, isPostToolTextReusingId));
// Track the latest model β€” emitted alongside authoritative usage on the
// matching `message_delta`. We deliberately do NOT emit turn_metadata
@@ -810,7 +836,12 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
// (since it fires on `message_start`, before tool_use blocks
// arrive); MessageCollector ignores `metadata.signal` on messages
// with `tools.length > 0` so that mismatch is benign.
- if (newToolCalls.length > 0) this.pendingExternalSignal = undefined;
+ if (newToolCalls.length > 0) {
+ this.pendingExternalSignal = undefined;
+ // Mark the in-flight turn so a later same-id text-only event is recognized
+ // as a post-tool answer and split into its own step (see openMainMessage).
+ this.currentTurnHadToolUse = true;
+ }
// Under `--include-partial-messages`, CC may emit deltas first and then a
// final full assistant block for the SAME message.id. If the full block is
@@ -1412,24 +1443,63 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
private openMainMessage(
messageId: string | undefined,
model: string | undefined,
+ forcePostToolBoundary = false,
): HeterogeneousAgentEvent[] {
if (!messageId) return [];
if (!this.started) {
this.started = true;
this.currentMessageId = messageId;
+ this.currentTurnHadToolUse = false;
return [this.makeEvent('stream_start', { model, provider: 'claude-code' })];
}
- if (messageId === this.currentMessageId) return [];
+ if (messageId === this.currentMessageId) {
+ // Same message.id β‡’ normally the same step (CC streams a turn's blocks
+ // across several assistant events). EXCEPT when the model answers AFTER
+ // its tools while reusing the id: that post-tool text must get its own
+ // step, or it coalesces onto the tool-issuing assistant and the renderer
+ // drops the tool block below the answer. This is a natural main-chain
+ // continuation, NOT a signal callback, so emit a plain boundary without
+ // the task-callback / external-signal tagging below.
+ if (!forcePostToolBoundary) return [];
+ this.stepIndex++;
+ this.currentTurnHadToolUse = false;
+ // The post-tool answer is the natural follow-up to the preceding
+ // tool_result β€” consume the user-input flag exactly like the normal turn
+ // boundary does (below), or a later signal callback (e.g. a Monitor stdout
+ // turn opened while a task is active) would see a stale `true` and skip
+ // its external-signal tag.
+ this.hasUnhandledUserInput = false;
+ this.pendingExternalSignal = undefined;
+ // Reusing the tool turn's message.id as the newStep id would make the
+ // reducer treat this as a REPLAY and drop it (it ignores a `newStep` whose
+ // id === currentMainMessageId). For any tool turn opened by a prior
+ // newStep that id already IS currentMainMessageId, so the split would be
+ // dropped and the text would coalesce anyway. Stamp a DISTINCT,
+ // replay-stable idempotency key β€” suffixed by stepIndex, so it is unique
+ // per split and deterministic across cold-replica reprocessing β€” so a
+ // fresh assistant is actually opened.
+ return [
+ this.makeEvent('stream_end', {}),
+ this.makeEvent('stream_start', {
+ messageId: `${messageId}:s${this.stepIndex}`,
+ model,
+ newStep: true,
+ provider: 'claude-code',
+ }),
+ ];
+ }
if (this.currentMessageId === undefined) {
// First assistant/delta after system init β€” record without step boundary.
this.currentMessageId = messageId;
+ this.currentTurnHadToolUse = false;
return [];
}
this.currentMessageId = messageId;
+ this.currentTurnHadToolUse = false;
this.stepIndex++;
// Signal-callback detection (): if this turn opened
// WITHOUT a preceding `user` event AND a long-running task is