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): correct cold-replica main-turn idempotency and mark topic failed on terminal errors (#15838)

Arvin Xu542197d8ab89
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 92c087e7f36..db26c8637b6 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -649,6 +649,53 @@ describe('hetero exec command', () => {
]);
});
+ it('finishes with result "error" when a terminal error event is pushed despite a clean exit', async () => {
+ // CC relays an API/rate-limit error as an in-stream `error` event but still
+ // exits 0. The finish result must NOT be derived from the exit code alone,
+ // otherwise the topic/task is wrongly marked completed.
+ mockSpawnAgent.mockReturnValue(
+ createFakeHandle({
+ events: [
+ {
+ data: {
+ error: 'API Error: Server is temporarily limiting requests Β· Rate limited',
+ message: 'API Error: Server is temporarily limiting requests Β· Rate limited',
+ },
+ operationId: 'op-err',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'error',
+ },
+ ],
+ exitCode: 0,
+ }),
+ );
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-err',
+ '--render',
+ 'none',
+ ]);
+
+ expect(mockHeteroFinishMutate).toHaveBeenCalledTimes(1);
+ expect(mockHeteroFinishMutate.mock.calls[0][0]).toMatchObject({
+ error: {
+ message: 'API Error: Server is temporarily limiting requests Β· Rate limited',
+ type: 'AgentRuntimeError',
+ },
+ result: 'error',
+ });
+ });
+
it('resets the per-message text accumulator at message boundaries (no cross-message duplication)', async () => {
// The `replace` snapshot accumulator must not span
// message boundaries. Two assistant messages separated by a
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index d65b17b2c51..4b2f87dba1b 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -467,6 +467,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
* sessionId β€” CC session id from `system.init` (undefined on resume failure)
* ingestError β€” true when a batch could not be flushed after retries
* resumeNotFound β€” true when a resume-not-found error was intercepted
+ * sawTerminalError β€” true when a terminal `error` event was pushed to the
+ * ingester (CC can relay an API/rate-limit error this way
+ * and still exit 0, so the exit code alone is not enough)
+ * terminalErrorMessage β€” the message from that terminal `error` event, used
+ * as the task-level error detail in the finish payload
* stderrContent β€” accumulated stderr (only when interceptResumeErrors=true)
*/
const runOneAgent = async (
@@ -477,9 +482,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
code: number | null;
ingestError: boolean;
resumeNotFound: boolean;
+ sawTerminalError: boolean;
sessionId: string | undefined;
signal: NodeJS.Signals | null;
stderrContent: string;
+ terminalErrorMessage: string | undefined;
}> => {
// One raw-dump file pair per spawn attempt (the resume retry is a second
// attempt). The stdout tee runs inside `spawnAgent` before the adapter.
@@ -549,6 +556,8 @@ const exec = async (options: ExecOptions): Promise<void> => {
// into the ingester. When intercepting resume errors, a matching
// `error` event is withheld from the ingester and flags a retry instead.
let resumeNotFound = false;
+ let sawTerminalError = false;
+ let terminalErrorMessage: string | undefined;
const ingestError = false;
try {
for await (const event of handle.events) {
@@ -563,6 +572,16 @@ const exec = async (options: ExecOptions): Promise<void> => {
continue;
}
}
+ // A terminal `error` event (e.g. an API/rate-limit error relayed by CC)
+ // must mark the run as failed even when the child exits 0 β€” track it so
+ // the finish result is not derived from the exit code alone. Capture the
+ // message too, so the finish payload can surface it as the task-level
+ // error detail (CC relays these on stdout, not stderr).
+ if (event.type === 'error') {
+ sawTerminalError = true;
+ const data = event.data as Record<string, unknown> | undefined;
+ terminalErrorMessage = String(data?.message ?? data?.error ?? '') || undefined;
+ }
if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
serverIngester?.push(event);
}
@@ -608,9 +627,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
code,
ingestError,
resumeNotFound,
+ sawTerminalError,
sessionId: handle.sessionId,
signal,
stderrContent,
+ terminalErrorMessage,
};
};
@@ -675,16 +696,23 @@ const exec = async (options: ExecOptions): Promise<void> => {
result = { ...result, ingestError: true };
}
- const exitedClean = !result.ingestError && (code === 0 || signal === 'SIGTERM');
-
- // When the run failed, pass stderr as the error detail so the server can
- // surface a useful message instead of the generic "Agent execution failed"
- // fallback. Trim to the last 1 KB β€” the tail is most informative and
- // keeps the tRPC payload small.
+ // CC relays API/rate-limit errors as an in-stream terminal `error` event but
+ // still exits 0, so the exit code alone would report `success`. Treat any
+ // pushed terminal error as a failed run so the topic/task is marked failed.
+ const exitedClean =
+ !result.ingestError && !result.sawTerminalError && (code === 0 || signal === 'SIGTERM');
+
+ // When the run failed, pass an error detail so the server surfaces a useful
+ // message instead of the generic "Agent execution failed" fallback. Prefer
+ // the in-stream terminal error (CC relays API/rate-limit errors here while
+ // exiting 0, so stderr is empty); otherwise fall back to the stderr tail.
+ // Trim to the last 1 KB β€” the tail is most informative and keeps the tRPC
+ // payload small.
const stderrTail = result.stderrContent.trim();
+ const errorDetail = result.terminalErrorMessage || stderrTail;
const finishError =
- !exitedClean && stderrTail
- ? { message: stderrTail.slice(-1024), type: 'AgentRuntimeError' }
+ !exitedClean && errorDetail
+ ? { message: errorDetail.slice(-1024), type: 'AgentRuntimeError' }
: undefined;
try {
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index aee05532221..d780a75b425 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -502,6 +502,14 @@ export class HeterogeneousPersistenceHandler {
const currentMsg = await this.deps.messageModel.findById(state.main.currentAssistantId);
const snapshot = this.toAssistantSnapshot(currentMsg);
+ // Recover the in-flight turn's CC message.id so a replayed `newStep` (cold
+ // replica retry) is recognized as the SAME turn β€” no duplicate assistant,
+ // no usage-only empty shell. Mirrors the subagent path's recovery of
+ // `currentSubagentMessageId` from `metadata.subagentMessageId`.
+ if (typeof snapshot.metadata.mainMessageId === 'string') {
+ state.main.currentMainMessageId = snapshot.metadata.mainMessageId;
+ }
+
if (snapshot.textSnapshotSeq > state.main.lastTextSnapshotSeq) {
state.main.accContent = snapshot.content;
state.main.lastTextSnapshotSeq = snapshot.textSnapshotSeq;
@@ -740,11 +748,17 @@ export class HeterogeneousPersistenceHandler {
private async applyMainIntent(state: OperationState, intent: MainAgentIntent) {
switch (intent.kind) {
case 'createAssistant': {
+ const createMetadata: Record<string, any> = {};
+ if (intent.signal) createMetadata.signal = intent.signal;
+ // Persist the turn's CC message.id so a cold replica can recover
+ // `currentMainMessageId` (via refreshMainStateFromDb) and dedupe a
+ // replayed `newStep` instead of forking a duplicate + empty shell.
+ if (intent.mainMessageId) createMetadata.mainMessageId = intent.mainMessageId;
await this.deps.messageModel.create(
{
agentId: intent.agentId ?? undefined,
content: '',
- ...(intent.signal ? { metadata: { signal: intent.signal } } : {}),
+ ...(Object.keys(createMetadata).length > 0 ? { metadata: createMetadata } : {}),
model: intent.model,
parentId: intent.parentId,
provider: intent.provider,
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
new file mode 100644
index 00000000000..fe05163e01d
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
@@ -0,0 +1,261 @@
+// @vitest-environment node
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ __resetOperationStatesForTesting,
+ HeterogeneousPersistenceHandler,
+} from '../HeterogeneousPersistenceHandler';
+
+/**
+ * Regression for the MAIN-chain analog of #15808 (which only fixed the SUBAGENT
+ * coordinator).
+ *
+ * The main-agent reducer (`packages/heterogeneous-agents/src/mainAgentCoordinator`)
+ * cuts a turn purely on the adapter's `stream_start { newStep: true }` signal β€”
+ * it tracks NO CC `message.id` and `openTurn` mints a fresh random assistant id
+ * via `ctx.newId('message')`. So unlike the subagent path (which now persists the
+ * turn's CC message.id on `metadata.subagentMessageId` and dedupes a replayed
+ * turn), the main chain has NO DB-homed idempotency key for a turn.
+ *
+ * The serverless failure mode:
+ * - `processedKeys` (the per-event dedupe set) lives ONLY in the in-memory
+ * `operationStates` map. On a cold replica it is empty.
+ * - The ingest contract (see `ingest()` doc) is: a handler that throws leaves
+ * its event unmarked, the throw bubbles to the producer, and the producer
+ * re-sends the WHOLE batch. Already-applied events are skipped "via the
+ * dedupe map" β€” but that map is in-memory, so on a cold replica retry every
+ * event (including the `newStep`) is reprocessed.
+ * - Reprocessing `newStep` re-runs `openTurn`, which mints a SECOND assistant.
+ * The first one (created before the throw, already carrying the turn's usage
+ * but no flushed content) is orphaned as an empty shell β€” content empty,
+ * tools 0, usage present. Exactly the "空壳村" in the reported triad.
+ *
+ * This test simulates a mid-batch DB failure on replica A, then a cold replica
+ * (`__resetOperationStatesForTesting()`) processing the producer's resend.
+ */
+
+interface FakeMessage {
+ agentId: string | null;
+ content: string;
+ id: string;
+ metadata?: any;
+ model?: string;
+ parentId?: string | null;
+ plugin?: any;
+ reasoning?: any;
+ role: 'user' | 'assistant' | 'tool' | 'task' | 'system';
+ threadId?: string | null;
+ tool_call_id?: string;
+ tools?: any[];
+ topicId: string | null;
+}
+
+const SEED = 'asst-seed';
+const OP = 'op-1';
+const TOPIC = 'topic-1';
+
+const createHarness = () => {
+ let nextMsgIdSeq = 0;
+ const messages = new Map<string, FakeMessage>();
+
+ // Faithful topic-metadata store: the real TopicModel.updateMetadata DEEP-MERGES
+ // into the JSONB column. The main-chain cold-replica recovery reads
+ // `heteroCurrentMsgId` from here, so a no-op mock (as in the subagent test)
+ // would not exercise the path under test.
+ let topicMetadata: Record<string, any> = {
+ runningOperation: { assistantMessageId: SEED, operationId: OP },
+ };
+
+ // Trip a single mid-batch DB failure: the Nth `messageModel.update` throws once.
+ let updateCalls = 0;
+ let failUpdateAtCall = -1;
+
+ // Seed the run's first-turn assistant (already has content, like a real run
+ // where `newStep` opens the SECOND turn).
+ messages.set(SEED, {
+ agentId: null,
+ content: 'first turn answer',
+ id: SEED,
+ role: 'assistant',
+ topicId: TOPIC,
+ });
+
+ const messageModel = {
+ create: vi.fn(async (input: Partial<FakeMessage>, id?: string) => {
+ nextMsgIdSeq += 1;
+ const msgId = id ?? `msg_${nextMsgIdSeq}`;
+ const msg = {
+ agentId: input.agentId ?? null,
+ content: input.content ?? '',
+ id: msgId,
+ metadata: input.metadata,
+ model: input.model,
+ parentId: input.parentId ?? null,
+ plugin: input.plugin,
+ reasoning: input.reasoning,
+ role: input.role!,
+ threadId: input.threadId ?? null,
+ tool_call_id: input.tool_call_id,
+ tools: input.tools,
+ topicId: input.topicId ?? null,
+ } as FakeMessage;
+ messages.set(msgId, msg);
+ return msg;
+ }),
+ update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {
+ updateCalls += 1;
+ if (updateCalls === failUpdateAtCall) {
+ throw new Error('simulated mid-batch DB failure');
+ }
+ const existing = messages.get(id);
+ if (!existing) return { success: false };
+ const next = { ...existing, ...patch };
+ if (patch.metadata && existing.metadata) {
+ next.metadata = { ...existing.metadata, ...patch.metadata };
+ }
+ messages.set(id, next);
+ return { success: true };
+ }),
+ updateToolMessage: vi.fn(async (id: string, patch: any) => {
+ const existing = messages.get(id);
+ if (!existing) return { success: false };
+ messages.set(id, { ...existing, content: patch.content ?? existing.content });
+ return { success: true };
+ }),
+ findById: vi.fn(async (id: string) => messages.get(id) ?? null),
+ query: vi.fn(async (params: { threadId?: string; topicId?: string }) => {
+ if (params?.threadId)
+ 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()].findLast(
+ (m) => m.role === 'tool' && m.parentId === assistantMessageId && !m.threadId,
+ );
+ return match?.id;
+ }),
+ listMessagePluginsByTopic: vi.fn(async () =>
+ [...messages.values()]
+ .filter((m) => m.role === 'tool' && m.tool_call_id)
+ .map((m) => ({ id: m.id, toolCallId: m.tool_call_id! })),
+ ),
+ };
+
+ const topicModel = {
+ findById: vi.fn(async (id: string) => {
+ if (id !== TOPIC) return null;
+ return { agentId: null, id, metadata: topicMetadata };
+ }),
+ updateMetadata: vi.fn(async (_id: string, patch: Record<string, any>) => {
+ // Deep-merge top-level keys, matching the real model.
+ topicMetadata = { ...topicMetadata, ...patch };
+ }),
+ };
+
+ const threadModel = {
+ create: vi.fn(async () => {}),
+ findById: vi.fn(async () => null),
+ queryByTopicId: vi.fn(async () => []),
+ update: vi.fn(async () => {}),
+ };
+
+ const handler = new HeterogeneousPersistenceHandler({
+ messageModel: messageModel as any,
+ threadModel: threadModel as any,
+ topicModel: topicModel as any,
+ });
+
+ return {
+ handler,
+ messages,
+ setFailUpdateAtCall: (n: number) => {
+ failUpdateAtCall = n;
+ },
+ };
+};
+
+const buildEvent = (
+ type: AgentStreamEvent['type'],
+ stepIndex: number,
+ data: Record<string, unknown>,
+): AgentStreamEvent => ({
+ data,
+ operationId: OP,
+ stepIndex,
+ timestamp: 1_700_000_000_000 + stepIndex,
+ type,
+});
+
+describe('HeterogeneousPersistenceHandler β€” main turn survives a cold-replica retry', () => {
+ beforeEach(() => __resetOperationStatesForTesting());
+ afterEach(() => __resetOperationStatesForTesting());
+
+ it('does NOT fork one main turn into a duplicate + empty shell when a batch is retried on a cold replica', async () => {
+ const h = createHarness();
+
+ // The producer's batch for a turn boundary: open a new turn, record its
+ // usage, then a tool batch. We trip the DB to fail on the tool-batch
+ // Phase-1 update, AFTER the turn's usage has already been written to the
+ // new assistant β€” so the orphan left behind is a true usage-bearing empty
+ // shell. `update` call order on replica A: #1 = openTurn flush of the seed's
+ // first-turn content, #2 = recordUsage on the new assistant, #3 = tools[]
+ // Phase 1 (← throws).
+ const batch = [
+ buildEvent('stream_start', 1, {
+ messageId: 'cc-msg-2',
+ newStep: true,
+ provider: 'claude-code',
+ }),
+ buildEvent('step_complete', 1, {
+ phase: 'turn_metadata',
+ usage: { totalInputTokens: 64_700, totalTokens: 64_700 },
+ }),
+ buildEvent('stream_chunk', 1, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ { apiName: 'Bash', arguments: '{}', id: 'tc-1', identifier: 'bash', type: 'default' },
+ ],
+ }),
+ ];
+
+ // ── Replica A: processes newStep (creates the turn assistant) + usage, then
+ // THROWS on the tool-batch write. The batch is left un-acked. ──
+ h.setFailUpdateAtCall(3);
+ await expect(
+ h.handler.ingest({
+ assistantMessageId: SEED,
+ events: batch,
+ operationId: OP,
+ topicId: TOPIC,
+ }),
+ ).rejects.toThrow('simulated mid-batch DB failure');
+
+ // ── Cold replica: warm operation state (incl. processedKeys) is gone; the DB
+ // persists. The producer re-sends the SAME batch. ──
+ __resetOperationStatesForTesting();
+
+ // ── Replica B: full batch succeeds this time. ──
+ await h.handler.ingest({
+ assistantMessageId: SEED,
+ events: batch,
+ operationId: OP,
+ topicId: TOPIC,
+ });
+
+ // One `newStep` must yield exactly ONE new turn assistant (besides the seed).
+ const turnAssistants = [...h.messages.values()].filter(
+ (m) => m.role === 'assistant' && m.id !== SEED,
+ );
+
+ // Empty-shell detector: an assistant with usage but no content and no child tools.
+ const childToolsOf = (asstId: string) =>
+ [...h.messages.values()].filter((m) => m.role === 'tool' && m.parentId === asstId);
+ const emptyShells = turnAssistants.filter(
+ (m) => !m.content && childToolsOf(m.id).length === 0 && !!m.metadata?.usage,
+ );
+
+ expect(emptyShells).toHaveLength(0);
+ expect(turnAssistants).toHaveLength(1);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index fb7e7562555..64a14d4cfc0 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -1453,6 +1453,11 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
this.makeEvent('stream_end', {}),
this.makeEvent('stream_start', {
externalSignal: this.pendingExternalSignal,
+ // The turn's CC message.id β€” the server stamps it on the new assistant
+ // (`metadata.mainMessageId`) as a turn idempotency key, so a cold-replica
+ // batch retry that reprocesses this `newStep` recognizes the same turn
+ // instead of forking a duplicate + usage-only empty shell.
+ messageId,
model,
newStep: true,
provider: 'claude-code',
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
index 1a7e925abcc..f0615c34177 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
@@ -331,3 +331,47 @@ describe('main agent reducer', () => {
expect(after).toBe(before);
});
});
+
+// A `newStep` carries the turn's CC message.id; the reducer records it as the
+// turn idempotency key and dedupes a replay (cold-replica BatchIngester retry).
+const newStepWithId = (messageId?: string) => ({
+ data: { messageId, newStep: true },
+ type: 'stream_start',
+});
+
+describe('reduceMainAgent β€” newStep idempotency key', () => {
+ it('opens a turn on a new message.id and records it as currentMainMessageId', () => {
+ const { state, steps } = run([textEvent('first'), newStepWithId('M2')]);
+ const created = ofKind(steps[1], 'createAssistant');
+ expect(created).toHaveLength(1);
+ expect(created[0].mainMessageId).toBe('M2');
+ expect(state.currentMainMessageId).toBe('M2');
+ expect(state.currentAssistantId).toBe('msg_1');
+ });
+
+ it('does NOT open a second assistant when the SAME message.id newStep is replayed', () => {
+ const { state, steps } = run([
+ textEvent('first'),
+ newStepWithId('M2'), // opens msg_1
+ newStepWithId('M2'), // replay (cold-replica retry) β†’ must be a no-op
+ ]);
+ expect(ofKind(steps[1], 'createAssistant')).toHaveLength(1);
+ expect(ofKind(steps[2], 'createAssistant')).toHaveLength(0);
+ expect(steps[2]).toEqual([]);
+ // Still anchored on the single turn assistant β€” no fork.
+ expect(state.currentAssistantId).toBe('msg_1');
+ });
+
+ it('still opens a genuine new turn when the message.id changes', () => {
+ const { state, steps } = run([textEvent('first'), newStepWithId('M2'), newStepWithId('M3')]);
+ expect(ofKind(steps[1], 'createAssistant')).toHaveLength(1);
+ expect(ofKind(steps[2], 'createAssistant')).toHaveLength(1);
+ expect(state.currentMainMessageId).toBe('M3');
+ expect(state.currentAssistantId).toBe('msg_2');
+ });
+
+ it('falls back to opening a turn when no message.id is present (legacy events)', () => {
+ const { steps } = run([textEvent('first'), newStepWithId(undefined)]);
+ expect(ofKind(steps[1], 'createAssistant')).toHaveLength(1);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
index 38a968d6521..a7c25cebb0a 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
@@ -125,9 +125,11 @@ const openTurn = (state: MainAgentRunState, data: any, ctx: MainAgentReduceCtx):
// 2. Open the new turn's assistant, chained off the last tool (chain rule).
const messageId = ctx.newId('message');
+ const mainMessageId = typeof data?.messageId === 'string' ? data.messageId : undefined;
intents.push({
agentId: ctx.agentId,
kind: 'createAssistant',
+ mainMessageId,
messageId,
model: state.turnModel,
parentId: computeTurnParentId(state),
@@ -139,6 +141,7 @@ 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;
+ next.currentMainMessageId = mainMessageId;
next.accContent = '';
next.accReasoning = '';
next.lastTextSnapshotSeq = 0;
@@ -359,7 +362,17 @@ export const reduce = (
const data = event.data ?? {};
switch (event.type) {
case 'stream_start': {
- return data?.newStep ? openTurn(state, data, ctx) : streamInit(state, data);
+ if (!data?.newStep) return streamInit(state, data);
+ // Idempotency: a `newStep` whose CC message.id matches the turn already
+ // open is a REPLAY (BatchIngester retry reprocessed on a cold replica
+ // with an empty in-memory `processedKeys`). Opening again would mint a
+ // duplicate assistant and orphan the first as a usage-only empty shell.
+ // The adapter only emits `newStep` when message.id CHANGES, so a genuine
+ // new turn never collides with the current id.
+ if (typeof data.messageId === 'string' && data.messageId === state.currentMainMessageId) {
+ return { intents: [], state };
+ }
+ return openTurn(state, data, ctx);
}
case 'stream_chunk': {
return reduceStreamChunk(state, data, ctx);
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
index e23def3269f..49527f184a3 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
@@ -63,6 +63,16 @@ export interface MainAgentRunState {
accReasoning: string;
/** The main-agent assistant message currently being appended to. */
currentAssistantId: string;
+ /**
+ * CC `message.id` of the turn currently open on `currentAssistantId`. The
+ * turn's idempotency key: a `stream_start { newStep }` whose `messageId`
+ * EQUALS this is a replay of an already-opened turn (e.g. a BatchIngester
+ * retry reprocessed on a cold serverless replica, where `processedKeys` is
+ * empty) and must NOT mint a second assistant. Recovered on a cold replica
+ * from the current assistant's `metadata.mainMessageId`. Undefined for the
+ * host-seeded first turn (which never opens via `newStep`, so can't fork).
+ */
+ currentMainMessageId: string | undefined;
/** Set once a terminal event has been reduced (idempotent finalize). */
ended: boolean;
/** Highest seen text snapshot sequence (replace-mode de-dup). */
@@ -97,6 +107,7 @@ export const createMainAgentRunState = (seedAssistantId: string): MainAgentRunSt
accContent: '',
accReasoning: '',
currentAssistantId: seedAssistantId,
+ currentMainMessageId: undefined,
ended: false,
lastTextSnapshotSeq: 0,
lastToolMsgIdEver: undefined,
@@ -148,6 +159,13 @@ export type MainAgentIntent =
export interface CreateAssistantIntent {
agentId?: string | null;
kind: 'createAssistant';
+ /**
+ * CC `message.id` of the turn this assistant represents. The interpreter
+ * stamps it on `metadata.mainMessageId` so a cold replica can recover
+ * {@link MainAgentRunState.currentMainMessageId} and dedupe a replayed
+ * `newStep` (mirrors the subagent path's `metadata.subagentMessageId`).
+ */
+ mainMessageId?: string;
messageId: string;
/** Last known model carried from the prior turn (real model lands via usage). */
model?: string;