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.

⚑️ perf(cli): batch hetero server ingest with text-snapshot coalescing (#17309)

AmAzing-a9283480e66a
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 1ecc81a3e6f..94f6594d20e 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -888,11 +888,12 @@ describe('hetero exec command', () => {
});
});
- it('sends full text snapshots before tools and waits for finish until all server ingests ack', async () => {
+ it('batches snapshot + tool + terminal events into ordered ingest calls and finishes after the ack', async () => {
const callOrder: string[] = [];
mockHeteroIngestMutate.mockImplementation(async ({ events }: any) => {
- const first = events[0];
- callOrder.push(`ingest:${first.type}:${first.data?.chunkType ?? 'terminal'}`);
+ for (const event of events) {
+ callOrder.push(`ingest:${event.type}:${event.data?.chunkType ?? 'terminal'}`);
+ }
return { ack: true };
});
mockHeteroFinishMutate.mockImplementation(async () => {
@@ -962,13 +963,17 @@ describe('hetero exec command', () => {
'none',
]);
- expect(mockHeteroIngestMutate).toHaveBeenCalledTimes(3);
+ // The whole run fits one batched ingest call (3 events β‰ͺ MAX_BATCH) β€”
+ // NOT one serial round-trip per event as before.
+ expect(mockHeteroIngestMutate).toHaveBeenCalledTimes(1);
expect(mockHeteroIngestMutate.mock.calls[0][0].events[0].data).toMatchObject({
chunkType: 'text',
content: 'hello world',
snapshotMode: 'replace',
snapshotSeq: 1,
});
+ // Within-batch order preserved (server processes a batch sequentially),
+ // and finish is only sent after every ingest acked.
expect(callOrder).toEqual([
'ingest:stream_chunk:text',
'ingest:stream_chunk:tools_calling',
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 1ac39d9ac22..88dbb40aebb 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -24,6 +24,7 @@ import {
import type { Command } from 'commander';
import { getTrpcClient } from '../api/client';
+import { CoalescingBatchIngester } from '../utils/CoalescingBatchIngester';
import { log } from '../utils/logger';
import { TrpcIngestSink } from '../utils/TrpcIngestSink';
@@ -252,111 +253,6 @@ const resolvePrompt = async (options: ExecOptions): Promise<ResolvedPrompt> => {
return buildPromptFromText(raw, images);
};
-class SerialServerIngester {
- private accumulatedText = '';
- private fatalError: Error | null = null;
- private inflight: Promise<void> = Promise.resolve();
- private nextSnapshotSeq = 0;
- private pendingTextEvent: AgentStreamEvent | undefined;
- private timer: ReturnType<typeof setTimeout> | null = null;
-
- constructor(
- private readonly sink: TrpcIngestSink,
- private readonly snapshotFlushMs = 200,
- ) {}
-
- push(event: AgentStreamEvent): void {
- if (this.fatalError) return;
-
- // Text-snapshot coalescing is a MAIN-AGENT-ONLY transport optimization:
- // it debounces the main agent's token-level text *deltas* into one
- // `replace` snapshot to cut ingest calls. Subagent text is explicitly
- // excluded (`!event.data?.subagent`) for two reasons:
- // 1. Subagent text is emitted as ONE full block per turn (see
- // claudeCode adapter `handleSubagentAssistant` β€” "the full block IS
- // the only emission"), so there is nothing to coalesce.
- // 2. `accumulatedText` is a single shared accumulator with no subagent
- // scope. Folding subagent blocks in would (a) splice main-agent text
- // into the subagent message via the shared buffer, and (b) emit a
- // `replace` snapshot that the server's subagent path *appends*
- // (`persistSubagentText` has no snapshot semantics) β†’ duplicated /
- // cross-scope content. Forwarding the raw block straight through lets
- // the server append it exactly once, correctly.
- if (
- event.type === 'stream_chunk' &&
- event.data?.chunkType === 'text' &&
- typeof event.data?.content === 'string' &&
- !event.data?.subagent
- ) {
- this.accumulatedText += event.data.content;
- this.pendingTextEvent = event;
- if (this.timer) clearTimeout(this.timer);
- this.timer = setTimeout(() => {
- this.timer = null;
- this.queuePendingTextSnapshot();
- }, this.snapshotFlushMs);
- return;
- }
-
- this.queuePendingTextSnapshot();
- // `accumulatedText` is a PER-MESSAGE accumulator: it coalesces the text
- // deltas of the current assistant message into one `replace` snapshot.
- // A new message boundary (`stream_start` / `stream_end`, emitted by the
- // adapter's `openMainMessage`) must reset it β€” otherwise it spans the
- // whole run and every later message's snapshot re-emits all prior
- // messages' text verbatim, which the server then persists into the new
- // DB message: cross-message text duplication. Reset
- // AFTER flushing the just-ended message's pending snapshot above.
- if (event.type === 'stream_start' || event.type === 'stream_end') {
- this.accumulatedText = '';
- }
- this.enqueue(async () => {
- await this.sink.ingest([event]);
- });
- }
-
- async drain(): Promise<void> {
- this.queuePendingTextSnapshot();
- try {
- await this.inflight;
- } catch {
- // `fatalError` is re-thrown below.
- }
- if (this.fatalError) throw this.fatalError;
- }
-
- private enqueue(task: () => Promise<void>) {
- this.inflight = this.inflight.then(task).catch((err) => {
- this.fatalError = err instanceof Error ? err : new Error(String(err));
- throw this.fatalError;
- });
- }
-
- private queuePendingTextSnapshot() {
- if (!this.pendingTextEvent || this.fatalError) return;
- if (this.timer) {
- clearTimeout(this.timer);
- this.timer = null;
- }
-
- const baseEvent = this.pendingTextEvent;
- this.pendingTextEvent = undefined;
- const snapshotEvent: AgentStreamEvent = {
- ...baseEvent,
- data: {
- ...baseEvent.data,
- content: this.accumulatedText,
- snapshotMode: 'replace',
- snapshotSeq: ++this.nextSnapshotSeq,
- },
- };
-
- this.enqueue(async () => {
- await this.sink.ingest([snapshotEvent]);
- });
- }
-}
-
interface RawStreamDumpAttempt {
/** Flush + close both file streams. Resolves once the bytes are on disk. */
close: () => Promise<void>;
@@ -483,7 +379,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
// JWT injected by the server) for authentication.
const agentType = options.type as 'amp' | 'claude-code' | 'codex';
let sink: TrpcIngestSink | undefined;
- let serverIngester: SerialServerIngester | undefined;
+ let serverIngester: CoalescingBatchIngester | undefined;
// Uploader for tool_result images (CC `Read` on an image file). Reuses the
// CLI's authenticated lambda client so the persisted event carries a
// `{ fileId, url }` reference instead of heavy base64. Only wired in
@@ -500,7 +396,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
options.topic!,
process.env.LOBEHUB_ASSISTANT_MESSAGE_ID,
);
- serverIngester = new SerialServerIngester(sink);
+ serverIngester = new CoalescingBatchIngester(sink);
uploadImage = createFileStoreImageUploader(async () => {
const lambda = await getTrpcClient();
diff --git a/apps/cli/src/utils/BatchIngester.test.ts b/apps/cli/src/utils/BatchIngester.test.ts
new file mode 100644
index 00000000000..faed50af52d
--- /dev/null
+++ b/apps/cli/src/utils/BatchIngester.test.ts
@@ -0,0 +1,112 @@
+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BatchIngester, type IngestSink } from './BatchIngester';
+
+const makeEvent = (n: number): AgentStreamEvent =>
+ ({
+ data: { n },
+ operationId: 'op-1',
+ stepIndex: n,
+ timestamp: 1_700_000_000_000 + n,
+ type: 'tool_start',
+ }) as AgentStreamEvent;
+
+const numbers = (events: AgentStreamEvent[]) => events.map((event) => (event.data as any).n);
+
+describe('BatchIngester', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('coalesces events that arrive during a slow in-flight request into one follow-up batch', async () => {
+ // Regression: the batch used to be spliced when a flush was SCHEDULED, so
+ // events arriving while a slow request was in flight fragmented into
+ // per-250ms micro-batches queued serially β€” throughput stayed ~one tiny
+ // batch per RTT and the backlog never caught up. Splicing at send time
+ // must ship everything that accumulated behind the slow request as a
+ // single batch.
+ const batches: number[][] = [];
+ let releaseFirst!: () => void;
+ const firstAck = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ const sink: IngestSink = {
+ finish: vi.fn(async () => {}),
+ ingest: vi.fn(async (events) => {
+ batches.push(numbers(events));
+ if (batches.length === 1) await firstAck; // slow first round-trip
+ }),
+ };
+ const ingester = new BatchIngester(sink);
+
+ ingester.push(makeEvent(1));
+ await vi.advanceTimersByTimeAsync(250); // flush timer β†’ [1] starts sending, blocked
+
+ ingester.push(makeEvent(2));
+ await vi.advanceTimersByTimeAsync(300);
+ ingester.push(makeEvent(3));
+ await vi.advanceTimersByTimeAsync(300);
+
+ releaseFirst();
+ await ingester.drain();
+
+ expect(batches).toEqual([[1], [2, 3]]);
+ });
+
+ it('never sends later batches once an earlier batch has exhausted its retries', async () => {
+ // Regression: queued follow-up batches used to keep sending after the
+ // first batch was permanently lost β€” if the server recovered mid-window,
+ // it received a gapped stream (e.g. a tool_end whose tool_start never
+ // arrived). After a fatal error the worker must stop and drop everything
+ // still buffered.
+ const batches: number[][] = [];
+ const sink: IngestSink = {
+ finish: vi.fn(async () => {}),
+ ingest: vi.fn(async (events) => {
+ batches.push(numbers(events));
+ throw new Error('server down');
+ }),
+ };
+ const ingester = new BatchIngester(sink);
+
+ // Batch 1 fills to MAX_BATCH and starts sending (then keeps retrying)…
+ for (let i = 1; i <= 50; i++) ingester.push(makeEvent(i));
+ // …while a second batch's worth of events arrives during the retry window.
+ for (let i = 51; i <= 100; i++) ingester.push(makeEvent(i));
+
+ const drained = ingester.drain();
+ const assertion = expect(drained).rejects.toThrow('server down');
+ // Back-off schedule: 500 + 1000 + 2000 + 4000 + 8000 ms.
+ await vi.advanceTimersByTimeAsync(20_000);
+ await assertion;
+
+ expect(sink.ingest).toHaveBeenCalledTimes(6); // batch 1: initial + 5 retries
+ for (const batch of batches) {
+ expect(batch[0]).toBe(1); // every call was batch 1 β€” [51..100] never sent
+ expect(batch).toHaveLength(50);
+ }
+ });
+
+ it('splits a synchronous burst into MAX_BATCH-sized batches in order', async () => {
+ const batches: number[][] = [];
+ const sink: IngestSink = {
+ finish: vi.fn(async () => {}),
+ ingest: vi.fn(async (events) => {
+ batches.push(numbers(events));
+ }),
+ };
+ const ingester = new BatchIngester(sink);
+
+ const all = Array.from({ length: 120 }, (_, i) => i + 1);
+ for (const n of all) ingester.push(makeEvent(n));
+ await ingester.drain();
+
+ expect(batches.map((batch) => batch.length)).toEqual([50, 50, 20]);
+ expect(batches.flat()).toEqual(all);
+ });
+});
diff --git a/apps/cli/src/utils/BatchIngester.ts b/apps/cli/src/utils/BatchIngester.ts
index 3b7d9307bc8..e08afe0b881 100644
--- a/apps/cli/src/utils/BatchIngester.ts
+++ b/apps/cli/src/utils/BatchIngester.ts
@@ -33,53 +33,98 @@ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
/**
* Buffers `AgentStreamEvent`s and flushes them in batches to an `IngestSink`.
*
- * Flush triggers:
- * - Buffer reaches MAX_BATCH (50) β†’ immediate flush
- * - FLUSH_INTERVAL_MS (250ms) timer fires β†’ flush whatever is buffered
+ * A single send worker pumps the buffer: it splices at most MAX_BATCH (50)
+ * events **at send time** β€” not when a flush is scheduled β€” so everything
+ * that arrives while a slow request is in flight coalesces into the next
+ * batch instead of fragmenting into per-interval micro-batches queued behind
+ * it. Consumption per round-trip therefore scales with the backlog, which is
+ * what lets ingest catch up to a producer that briefly outpaces the server.
+ *
+ * Pump triggers:
+ * - Buffer reaches MAX_BATCH (50) β†’ start the worker immediately
+ * - FLUSH_INTERVAL_MS (250ms) timer fires β†’ start the worker
+ * - drain() β†’ start the worker and await it
*
* Each batch is retried up to MAX_RETRIES (5) times with exponential back-off
- * starting at 500ms, doubling up to 8s. After the final retry the error is
- * stored and re-thrown by `drain()`, allowing the caller to call
- * `sink.finish({ result: 'error' })` and exit(1).
+ * starting at 500ms, doubling up to 8s. After the final retry the error is
+ * stored, the worker stops, and every event still buffered (or pushed later)
+ * is dropped β€” later batches must never be sent once an earlier one is
+ * permanently lost, or the server would see a gapped stream (a `tool_end`
+ * whose `tool_start` never arrived). `drain()` rethrows the stored error,
+ * allowing the caller to call `sink.finish({ result: 'error' })` and exit(1).
*
* Call order: push() repeatedly β†’ drain() once (before finish()).
*/
export class BatchIngester {
private buffer: AgentStreamEvent[] = [];
private fatalError: Error | null = null;
- private inflightFlush: Promise<void> = Promise.resolve();
+ private pumping = false;
private timer: ReturnType<typeof setTimeout> | null = null;
+ private worker: Promise<void> = Promise.resolve();
constructor(private readonly sink: IngestSink) {}
+ /** True once a batch has exhausted its retries β€” every later push is a no-op
+ * and `drain()` rethrows the stored error. Lets wrappers stop buffering
+ * work (e.g. text coalescing) that can never be delivered. */
+ get failed(): boolean {
+ return this.fatalError !== null;
+ }
+
push(event: AgentStreamEvent): void {
if (this.fatalError) return;
this.buffer.push(event);
+ if (this.pumping) return; // the worker picks the event up after its current send
if (this.buffer.length >= MAX_BATCH) {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
- this.triggerFlush();
+ this.startPump();
} else if (!this.timer) {
this.timer = setTimeout(() => {
this.timer = null;
- this.triggerFlush();
+ this.startPump();
}, FLUSH_INTERVAL_MS);
}
}
- /** Flush remaining buffer and wait for all in-flight sends to settle. */
+ /** Flush remaining buffer and wait for the worker to settle. */
async drain(): Promise<void> {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
- this.triggerFlush();
- await this.inflightFlush;
+ this.startPump();
+ await this.worker;
if (this.fatalError) throw this.fatalError;
}
+ private startPump(): void {
+ if (this.pumping || this.fatalError || this.buffer.length === 0) return;
+ this.pumping = true;
+ this.worker = this.pump();
+ }
+
+ /**
+ * Single-worker send loop. The batch is spliced right before each send, so
+ * the buffer keeps growing while a request is in flight and the backlog
+ * ships as few large batches. A fatal error (retries exhausted) breaks the
+ * loop with the remaining buffer unsent β€” dropped, never gapped.
+ */
+ private async pump(): Promise<void> {
+ try {
+ while (!this.fatalError && this.buffer.length > 0) {
+ const batch = this.buffer.splice(0, MAX_BATCH);
+ await this.sendWithRetry(batch);
+ }
+ } catch {
+ // fatalError is already set; drain() re-throws it.
+ } finally {
+ this.pumping = false;
+ }
+ }
+
private async sendWithRetry(batch: AgentStreamEvent[]): Promise<void> {
let delay = 500;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
@@ -96,14 +141,4 @@ export class BatchIngester {
}
}
}
-
- private triggerFlush(): void {
- if (this.fatalError || this.buffer.length === 0) return;
- const batch = this.buffer.splice(0);
- this.inflightFlush = this.inflightFlush
- .then(() => this.sendWithRetry(batch))
- .catch(() => {
- // fatalError is already set; drain() re-throws it
- });
- }
}
diff --git a/apps/cli/src/utils/CoalescingBatchIngester.test.ts b/apps/cli/src/utils/CoalescingBatchIngester.test.ts
new file mode 100644
index 00000000000..1ea0f1ad157
--- /dev/null
+++ b/apps/cli/src/utils/CoalescingBatchIngester.test.ts
@@ -0,0 +1,278 @@
+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { IngestSink } from './BatchIngester';
+import { CoalescingBatchIngester } from './CoalescingBatchIngester';
+
+const makeEvent = (type: string, data: Record<string, unknown> = {}): AgentStreamEvent =>
+ ({ data, operationId: 'op-1', stepIndex: 0, timestamp: 1, type }) as AgentStreamEvent;
+
+const textEvent = (content: string, extra: Record<string, unknown> = {}) =>
+ makeEvent('stream_chunk', { chunkType: 'text', content, ...extra });
+
+const reasoningEvent = (reasoning: string, extra: Record<string, unknown> = {}) =>
+ makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning, ...extra });
+
+const toolEvent = (i: number) => makeEvent('tool_start', { toolCallId: `tc-${i}` });
+
+const createSink = () => {
+ const batches: AgentStreamEvent[][] = [];
+ const ingest = vi.fn(async (events: AgentStreamEvent[]) => {
+ batches.push([...events]);
+ });
+ const sink: IngestSink = { finish: vi.fn(async () => {}), ingest };
+ return { batches, ingest, sink };
+};
+
+describe('CoalescingBatchIngester', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('batches a tool-heavy run into ≀50-event calls instead of one call per event', async () => {
+ // Regression for the serial single-event ingester (#15197 β†’ this change):
+ // a 178-command Codex run produced ~700 events, each a separate serial
+ // tRPC round-trip β€” the upload queue kept draining for ~13 minutes AFTER
+ // the agent had already finished. Batching must collapse call count by
+ // ~MAX_BATCH while preserving completeness and order.
+ const { batches, ingest, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ const events = Array.from({ length: 120 }, (_, i) => toolEvent(i));
+ for (const event of events) ingester.push(event);
+ await ingester.drain();
+
+ expect(ingest).toHaveBeenCalledTimes(3); // 50 + 50 + 20, NOT 120
+ expect(batches.map((batch) => batch.length)).toEqual([50, 50, 20]);
+ expect(batches.flat().map((event) => (event.data as any).toolCallId)).toEqual(
+ events.map((event) => (event.data as any).toolCallId),
+ );
+ });
+
+ it('coalesces main-agent text deltas into one replace snapshot ordered before the next event', async () => {
+ const { batches, ingest, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ ingester.push(textEvent('hello '));
+ ingester.push(textEvent('world'));
+ ingester.push(makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling: [] }));
+ await ingester.drain();
+
+ // One batch: [snapshot, tools_calling] β€” the snapshot must not be
+ // overtaken by the event that followed it (the server processes a batch
+ // sequentially, so within-batch order IS the wire order).
+ expect(ingest).toHaveBeenCalledTimes(1);
+ const [batch] = batches;
+ expect(batch.map((event) => (event.data as any).chunkType)).toEqual(['text', 'tools_calling']);
+ expect(batch[0].data).toMatchObject({
+ content: 'hello world',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ });
+ });
+
+ it('flushes a pending snapshot on the debounce timer without needing a following event', async () => {
+ const { batches, ingest, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ ingester.push(textEvent('streaming…'));
+ await vi.advanceTimersByTimeAsync(200); // snapshot debounce
+ await vi.advanceTimersByTimeAsync(250); // batch flush interval
+
+ expect(ingest).toHaveBeenCalledTimes(1);
+ expect(batches[0][0].data).toMatchObject({
+ content: 'streaming…',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ });
+ });
+
+ it('resets the per-message accumulator at stream boundaries (no cross-message duplication)', async () => {
+ const { batches, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ ingester.push(textEvent('first message'));
+ ingester.push(makeEvent('stream_end'));
+ ingester.push(makeEvent('stream_start', { newStep: true }));
+ ingester.push(textEvent('second message'));
+ await ingester.drain();
+
+ const batch = batches.flat();
+ expect(batch.map((event) => event.type)).toEqual([
+ 'stream_chunk',
+ 'stream_end',
+ 'stream_start',
+ 'stream_chunk',
+ ]);
+ // Second snapshot carries ONLY its own message, with a fresh seq.
+ expect(batch[0].data).toMatchObject({ content: 'first message', snapshotSeq: 1 });
+ expect(batch[3].data).toMatchObject({ content: 'second message', snapshotSeq: 2 });
+ });
+
+ it('coalesces reasoning deltas into a replace snapshot ordered before the text snapshot', async () => {
+ // Reasoning gets the same snapshot treatment as text: `replace` is
+ // idempotent under batch redelivery, whereas raw deltas re-append and
+ // durably duplicate the thinking content on a cold-replica retry.
+ const { batches, ingest, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ ingester.push(reasoningEvent('thinking '));
+ ingester.push(reasoningEvent('hard'));
+ ingester.push(textEvent('the answer'));
+ ingester.push(makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling: [] }));
+ await ingester.drain();
+
+ expect(ingest).toHaveBeenCalledTimes(1);
+ const [batch] = batches;
+ // Emission order preserved: reasoning β†’ text β†’ tools.
+ expect(batch.map((event) => (event.data as any).chunkType)).toEqual([
+ 'reasoning',
+ 'text',
+ 'tools_calling',
+ ]);
+ expect(batch[0].data).toMatchObject({
+ reasoning: 'thinking hard',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ });
+ expect(batch[1].data).toMatchObject({
+ content: 'the answer',
+ snapshotMode: 'replace',
+ snapshotSeq: 1, // per-kind counters are independent
+ });
+ });
+
+ it('resets the reasoning accumulator at stream boundaries', async () => {
+ const { batches, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ ingester.push(reasoningEvent('first thought'));
+ ingester.push(makeEvent('stream_end'));
+ ingester.push(makeEvent('stream_start', { newStep: true }));
+ ingester.push(reasoningEvent('second thought'));
+ await ingester.drain();
+
+ const batch = batches.flat();
+ expect(batch[0].data).toMatchObject({ reasoning: 'first thought', snapshotSeq: 1 });
+ expect(batch[3].data).toMatchObject({ reasoning: 'second thought', snapshotSeq: 2 });
+ });
+
+ it('forwards subagent reasoning verbatim without snapshot conversion', async () => {
+ const { batches, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ const subagent = { parentToolCallId: 'task-1', subagentMessageId: 'msg-sub-1' };
+ ingester.push(reasoningEvent('main think '));
+ ingester.push(reasoningEvent('sub think', { subagent }));
+ await ingester.drain();
+
+ const batch = batches.flat();
+ expect(batch[0].data).toMatchObject({ reasoning: 'main think ', snapshotMode: 'replace' });
+ expect(batch[1].data).toMatchObject({ reasoning: 'sub think', subagent });
+ expect((batch[1].data as any).snapshotMode).toBeUndefined();
+ });
+
+ it('forwards subagent text verbatim β€” no snapshot conversion, no accumulator pollution', async () => {
+ const { batches, sink } = createSink();
+ const ingester = new CoalescingBatchIngester(sink);
+
+ const subagent = { parentToolCallId: 'task-1', subagentMessageId: 'msg-sub-1' };
+ ingester.push(textEvent('main '));
+ ingester.push(textEvent('I checked the files.', { subagent }));
+ await ingester.drain();
+
+ const batch = batches.flat();
+ // Main snapshot flushed first (order preserved), untainted by the block.
+ expect(batch[0].data).toMatchObject({ content: 'main ', snapshotMode: 'replace' });
+ // Subagent block passes through untouched: same content, no snapshot
+ // fields (the server's subagent path appends β€” replace semantics would
+ // duplicate content there).
+ expect(batch[1].data).toMatchObject({ content: 'I checked the files.', subagent });
+ expect((batch[1].data as any).snapshotMode).toBeUndefined();
+ expect((batch[1].data as any).snapshotSeq).toBeUndefined();
+ });
+
+ it('retries a failed batch with an identical payload, then keeps delivering later events', async () => {
+ // Same-batch redelivery contract: `HeterogeneousPersistenceHandler.ingest`
+ // marks events processed only on success and dedupes redelivered ones, so
+ // the producer MUST re-send the failed batch as-is. The serial ingester
+ // had dropped this retry entirely β€” one transient failure discarded every
+ // subsequent event of the run.
+ const batches: AgentStreamEvent[][] = [];
+ const ingest = vi
+ .fn(async (events: AgentStreamEvent[]) => {
+ batches.push([...events]);
+ })
+ .mockRejectedValueOnce(new Error('ECONNRESET'));
+ const ingester = new CoalescingBatchIngester({ finish: vi.fn(), ingest });
+
+ ingester.push(toolEvent(1));
+ ingester.push(toolEvent(2));
+ const drained = ingester.drain();
+ await vi.advanceTimersByTimeAsync(500); // first retry back-off
+ await drained;
+
+ expect(ingest).toHaveBeenCalledTimes(2);
+ expect(ingest.mock.calls[1][0]).toEqual(ingest.mock.calls[0][0]);
+
+ ingester.push(toolEvent(3));
+ await ingester.drain();
+ expect(batches.flat().map((event) => (event.data as any).toolCallId)).toEqual([
+ 'tc-1',
+ 'tc-2',
+ 'tc-3',
+ ]);
+ });
+
+ it('drain rethrows once retries are exhausted so the CLI can finish(result: error)', async () => {
+ const ingest = vi.fn(async () => {
+ throw new Error('server down');
+ });
+ const ingester = new CoalescingBatchIngester({ finish: vi.fn(), ingest });
+
+ ingester.push(toolEvent(1));
+ const drained = ingester.drain();
+ const assertion = expect(drained).rejects.toThrow('server down');
+ // Back-off schedule: 500 + 1000 + 2000 + 4000 + 8000 ms.
+ await vi.advanceTimersByTimeAsync(20_000);
+ await assertion;
+
+ expect(ingest).toHaveBeenCalledTimes(6); // initial + 5 retries
+ });
+
+ it('stops accumulating text once the batcher has failed (no undeliverable retention)', async () => {
+ // Mirrors the serial ingester's fatal short-circuit: after retries are
+ // exhausted nothing can be delivered, so later text deltas must be
+ // dropped instead of retained in `accumulatedText` until process exit.
+ const ingest = vi.fn(async () => {
+ throw new Error('server down');
+ });
+ const ingester = new CoalescingBatchIngester({ finish: vi.fn(), ingest });
+
+ ingester.push(toolEvent(1));
+ const drained = ingester.drain();
+ const assertion = expect(drained).rejects.toThrow('server down');
+ await vi.advanceTimersByTimeAsync(20_000);
+ await assertion;
+
+ ingester.push(textEvent('undeliverable '));
+ ingester.push(textEvent('response'));
+ await vi.advanceTimersByTimeAsync(1000);
+
+ // White-box on purpose β€” the regression IS the internal retention: the
+ // accumulator stays empty, no snapshot is pending, no debounce armed.
+ expect((ingester as any).accumulatedText).toBe('');
+ expect((ingester as any).pendingTextEvent).toBeUndefined();
+ expect((ingester as any).timer).toBeNull();
+
+ // And nothing new ever reaches the sink; drain keeps rethrowing.
+ const redrained = expect(ingester.drain()).rejects.toThrow('server down');
+ await vi.advanceTimersByTimeAsync(20_000);
+ await redrained;
+ expect(ingest).toHaveBeenCalledTimes(6); // unchanged after the failure
+ });
+});
diff --git a/apps/cli/src/utils/CoalescingBatchIngester.ts b/apps/cli/src/utils/CoalescingBatchIngester.ts
new file mode 100644
index 00000000000..0d56e22b656
--- /dev/null
+++ b/apps/cli/src/utils/CoalescingBatchIngester.ts
@@ -0,0 +1,184 @@
+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
+
+import { BatchIngester, type IngestSink } from './BatchIngester';
+
+/**
+ * Server ingester for `lh hetero exec`: coalesces main-agent text and
+ * reasoning deltas into `replace` snapshots, then ships every event through
+ * `BatchIngester` (≀50 events/batch, lazy-splice worker, 5-retry back-off)
+ * instead of one serial tRPC round-trip per event.
+ *
+ * History: #15197 replaced the original `BatchIngester` wiring with a
+ * single-event serial ingester while introducing the snapshot semantics. That
+ * made ingest throughput ~1 event per server round-trip β€” slower than agents
+ * emit events β€” so long tool-heavy runs kept uploading for many minutes after
+ * the CLI agent had already finished (`drain()` must clear the queue before
+ * `heteroFinish`). Batching restores throughput; the snapshot coalescing and
+ * its ordering/reset semantics are preserved here, and the server contract
+ * (`HeterogeneousPersistenceHandler.ingest`) has always accepted ordered
+ * event arrays and expected a retrying batch producer.
+ *
+ * Reasoning gets the same snapshot treatment as text (this change): `replace`
+ * snapshots are idempotent under batch redelivery β€” including a retry landing
+ * on a cold replica whose in-memory publish/persistence latches are empty β€”
+ * whereas raw deltas re-append and durably duplicate content.
+ */
+export class CoalescingBatchIngester {
+ private accumulatedReasoning = '';
+ private accumulatedText = '';
+ private readonly batcher: BatchIngester;
+ private nextReasoningSnapshotSeq = 0;
+ private nextTextSnapshotSeq = 0;
+ private pendingReasoningEvent: AgentStreamEvent | undefined;
+ private pendingTextEvent: AgentStreamEvent | undefined;
+ // Shared debounce: at most ONE kind is pending at a time β€” a delta of the
+ // other kind flushes it first (see push) β€” so one timer covers both.
+ private timer: ReturnType<typeof setTimeout> | null = null;
+
+ constructor(
+ sink: IngestSink,
+ private readonly snapshotFlushMs = 200,
+ ) {
+ this.batcher = new BatchIngester(sink);
+ }
+
+ push(event: AgentStreamEvent): void {
+ // Mirror the previous serial ingester's fatal short-circuit: once the
+ // batcher has exhausted its retries nothing can ever be delivered, so
+ // drop later events β€” including text/reasoning deltas β€” instead of
+ // retaining an undeliverable response in memory until the process exits.
+ if (this.batcher.failed) {
+ this.accumulatedReasoning = '';
+ this.accumulatedText = '';
+ this.pendingReasoningEvent = undefined;
+ this.pendingTextEvent = undefined;
+ this.clearTimer();
+ return;
+ }
+
+ // Snapshot coalescing is a MAIN-AGENT-ONLY transport optimization: it
+ // debounces the main agent's token-level text/reasoning *deltas* into one
+ // `replace` snapshot to cut ingest volume β€” and `replace` makes the
+ // content idempotent under batch redelivery. Subagent chunks are
+ // explicitly excluded (`!event.data?.subagent`) for two reasons:
+ // 1. Subagent text is emitted as ONE full block per turn (see
+ // claudeCode adapter `handleSubagentAssistant` β€” "the full block IS
+ // the only emission"), so there is nothing to coalesce.
+ // 2. The accumulators are single shared buffers with no subagent
+ // scope. Folding subagent blocks in would (a) splice main-agent text
+ // into the subagent message via the shared buffer, and (b) emit a
+ // `replace` snapshot that the server's subagent path *appends*
+ // (`persistSubagentText` has no snapshot semantics) β†’ duplicated /
+ // cross-scope content. Forwarding the raw block straight through lets
+ // the server append it exactly once, correctly.
+ if (this.isMainDelta(event, 'text')) {
+ // Reasoning precedes text within a message β€” flush a pending reasoning
+ // snapshot first so within-batch order matches emission order.
+ this.flushPendingReasoningSnapshot();
+ this.accumulatedText += event.data.content;
+ this.pendingTextEvent = event;
+ this.armTimer();
+ return;
+ }
+
+ if (this.isMainDelta(event, 'reasoning')) {
+ this.flushPendingTextSnapshot();
+ this.accumulatedReasoning += event.data.reasoning;
+ this.pendingReasoningEvent = event;
+ this.armTimer();
+ return;
+ }
+
+ // Flush pending snapshots BEFORE the incoming event enters the batch,
+ // so within-batch order matches emission order (the server processes a
+ // batch sequentially β€” a boundary or tool event must not overtake the
+ // snapshot that preceded it). Reasoning first: it precedes text in the
+ // adapters' emission order, and the two land in separate message fields
+ // so the relative order between them cannot corrupt state.
+ this.flushPendingReasoningSnapshot();
+ this.flushPendingTextSnapshot();
+ // The accumulators are PER-MESSAGE: they coalesce the deltas of the
+ // current assistant message into one `replace` snapshot each. A new
+ // message boundary (`stream_start` / `stream_end`, emitted by the
+ // adapter's `openMainMessage`) must reset them β€” otherwise they span the
+ // whole run and every later message's snapshot re-emits all prior
+ // messages' content verbatim, which the server then persists into the new
+ // DB message: cross-message duplication. Reset AFTER flushing the
+ // just-ended message's pending snapshots above.
+ if (event.type === 'stream_start' || event.type === 'stream_end') {
+ this.accumulatedReasoning = '';
+ this.accumulatedText = '';
+ }
+ this.batcher.push(event);
+ }
+
+ /** Flush any pending snapshots + buffered batches; rethrows the batcher's
+ * fatal error after its retries are exhausted. Call before `sink.finish`. */
+ async drain(): Promise<void> {
+ this.flushPendingReasoningSnapshot();
+ this.flushPendingTextSnapshot();
+ await this.batcher.drain();
+ }
+
+ private isMainDelta(
+ event: AgentStreamEvent,
+ kind: 'reasoning' | 'text',
+ ): event is AgentStreamEvent & { data: Record<string, any> } {
+ return (
+ event.type === 'stream_chunk' &&
+ event.data?.chunkType === kind &&
+ typeof event.data?.[kind === 'text' ? 'content' : 'reasoning'] === 'string' &&
+ !event.data?.subagent
+ );
+ }
+
+ private armTimer(): void {
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = setTimeout(() => {
+ this.timer = null;
+ this.flushPendingReasoningSnapshot();
+ this.flushPendingTextSnapshot();
+ }, this.snapshotFlushMs);
+ }
+
+ private clearTimer(): void {
+ if (this.timer) {
+ clearTimeout(this.timer);
+ this.timer = null;
+ }
+ }
+
+ private flushPendingTextSnapshot() {
+ if (!this.pendingTextEvent) return;
+ this.clearTimer();
+
+ const baseEvent = this.pendingTextEvent;
+ this.pendingTextEvent = undefined;
+ this.batcher.push({
+ ...baseEvent,
+ data: {
+ ...baseEvent.data,
+ content: this.accumulatedText,
+ snapshotMode: 'replace',
+ snapshotSeq: ++this.nextTextSnapshotSeq,
+ },
+ });
+ }
+
+ private flushPendingReasoningSnapshot() {
+ if (!this.pendingReasoningEvent) return;
+ this.clearTimer();
+
+ const baseEvent = this.pendingReasoningEvent;
+ this.pendingReasoningEvent = undefined;
+ this.batcher.push({
+ ...baseEvent,
+ data: {
+ ...baseEvent.data,
+ reasoning: this.accumulatedReasoning,
+ snapshotMode: 'replace',
+ snapshotSeq: ++this.nextReasoningSnapshotSeq,
+ },
+ });
+ }
+}
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index ac1c514d91e..0c1c7f1d5f1 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -85,6 +85,7 @@ interface AssistantDbSnapshot {
parentId: string | null | undefined;
provider: string | undefined;
reasoning: string;
+ reasoningSnapshotSeq: number;
textSnapshotSeq: number;
tools: ChatToolPayload[];
}
@@ -120,6 +121,15 @@ interface OperationState {
main: MainAgentRunState;
operationId: string;
processedKeys: Set<string>;
+ /**
+ * Publish gate, peer of `processedKeys` but for the live-stream sink.
+ * Persistence and publish fail independently: a batch can persist fully
+ * yet die inside the publish loop β€” its retry must republish ONLY the
+ * unpublished tail β€” while a batch whose tRPC response was lost after
+ * full success must republish nothing. Keyed by `eventKey`, latched only
+ * after the event's XADD succeeds.
+ */
+ publishedKeys: Set<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;
@@ -253,6 +263,29 @@ export class HeterogeneousPersistenceHandler {
await this.flushBatchContent(state);
}
+ /**
+ * Events of the batch not yet successfully published to the live stream.
+ * See `OperationState.publishedKeys` for why this gate is separate from
+ * the persistence dedupe. Without state (already finished, or a retry on
+ * a cold replica) every event is treated as unpublished β€” degrading to
+ * republish-all. Main-agent text/reasoning survive that via their
+ * `replace`-snapshot seq guards; the accepted cross-replica residuals are
+ * subagent text (append semantics), tool lifecycle replays (benign client
+ * upserts), and a duplicate trace fold β€” closing those needs a durable
+ * publish identity (tracked follow-up), not a bigger in-memory map.
+ */
+ filterUnpublishedEvents(operationId: string, events: AgentStreamEvent[]): AgentStreamEvent[] {
+ const state = operationStates.get(operationId);
+ if (!state) return events;
+
+ return events.filter((event) => !state.publishedKeys.has(eventKey(event)));
+ }
+
+ /** Latch an event as published so a batch retry skips its XADD. */
+ markEventPublished(operationId: string, event: AgentStreamEvent): void {
+ operationStates.get(operationId)?.publishedKeys.add(eventKey(event));
+ }
+
/**
* Flush trailing accumulators, persist the CLI's native session id (when
* present) for next-turn resume, and drop the per-operation state.
@@ -428,6 +461,7 @@ export class HeterogeneousPersistenceHandler {
main: createMainAgentRunState(currentAssistantMessageId),
operationId,
processedKeys: new Set(),
+ publishedKeys: new Set(),
toolMsgIdByCallId: new Map(),
topicId,
};
@@ -459,6 +493,7 @@ export class HeterogeneousPersistenceHandler {
any
>;
const textSnapshotSeq = Number(metadata.heteroTextSnapshotSeq ?? 0);
+ const reasoningSnapshotSeq = Number(metadata.heteroReasoningSnapshotSeq ?? 0);
return {
content: rawContent === LOADING_FLAT ? '' : rawContent,
metadata,
@@ -466,6 +501,7 @@ export class HeterogeneousPersistenceHandler {
parentId: message?.parentId,
provider: message?.provider,
reasoning: (message?.reasoning as { content?: string } | null)?.content ?? '',
+ reasoningSnapshotSeq: Number.isFinite(reasoningSnapshotSeq) ? reasoningSnapshotSeq : 0,
textSnapshotSeq: Number.isFinite(textSnapshotSeq) ? textSnapshotSeq : 0,
tools: (message?.tools ?? []) as ChatToolPayload[],
};
@@ -550,7 +586,12 @@ export class HeterogeneousPersistenceHandler {
}
}
- if (snapshot.reasoning.length > state.main.accReasoning.length) {
+ // Seq-guarded reasoning restore mirrors the text path above; the length
+ // heuristic stays as the fallback for legacy rows without a stamped seq.
+ if (snapshot.reasoningSnapshotSeq > state.main.lastReasoningSnapshotSeq) {
+ state.main.accReasoning = snapshot.reasoning;
+ state.main.lastReasoningSnapshotSeq = snapshot.reasoningSnapshotSeq;
+ } else if (snapshot.reasoning.length > state.main.accReasoning.length) {
state.main.accReasoning = snapshot.reasoning;
}
@@ -740,6 +781,7 @@ export class HeterogeneousPersistenceHandler {
accContent: '',
accReasoning: '',
currentAssistantId: authoritativeAssistantMessageId,
+ lastReasoningSnapshotSeq: 0,
lastTextSnapshotSeq: 0,
toolState: this.createEmptyMainToolState(),
turnMetadata: {},
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index ffd050cc385..1058268cd20 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -361,6 +361,53 @@ describe('HeterogeneousPersistenceHandler', () => {
expect(asst.metadata?.heteroTextSnapshotSeq).toBe(2);
});
+ it('replaces reasoning snapshots idempotently instead of re-appending on redelivery', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'reasoning',
+ reasoning: 'thinking hard',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Redelivery reaching the reducer (a cold replica has an empty
+ // processedKeys map β€” simulated here with a different timestamp so the
+ // in-memory dedupe does not swallow the event first). A raw delta would
+ // re-append and durably double the reasoning; the snapshot must not.
+ await h.handler.ingest({
+ events: [
+ buildEvent(
+ 'stream_chunk',
+ 0,
+ {
+ chunkType: 'reasoning',
+ reasoning: 'thinking hard',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ },
+ 1_700_000_000_999,
+ ),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.reasoning?.content).toBe('thinking hard'); // NOT doubled
+ expect(asst.metadata?.heteroReasoningSnapshotSeq).toBe(1);
+ });
+
it('drops events with the same (stepIndex, type, timestamp, dataFingerprint) key', async () => {
const h = createHarness({
assistantMessageId: 'asst-1',
@@ -391,6 +438,35 @@ describe('HeterogeneousPersistenceHandler', () => {
expect(h.messageModel.create.mock.calls.length).toBe(createCallsAfterFirst);
});
+ it('gates publishing per operation and releases the gate when the operation finishes', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ const first = buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' });
+ const second = buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'y' });
+
+ // Without operation state (nothing ingested yet, or a cold replica):
+ // treat everything as unpublished and latch nothing β€” degraded
+ // republish-all rather than silently dropping events.
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
+ h.handler.markEventPublished('op-1', first);
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
+
+ await h.handler.ingest({ events: [first, second], operationId: 'op-1', topicId: 'topic-1' });
+
+ // Latch per event: only unlatched events remain.
+ h.handler.markEventPublished('op-1', first);
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([second]);
+ h.handler.markEventPublished('op-1', second);
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([]);
+
+ // finish() drops the per-operation state β€” the gate goes with it.
+ await h.handler.finish({ operationId: 'op-1', result: 'success' });
+ expect(h.handler.filterUnpublishedEvents('op-1', [first, second])).toEqual([first, second]);
+ });
+
it('does NOT collide bursty events sharing (stepIndex, type, timestamp) when their data differs', async () => {
// Producer-side reality: CC adapters stamp every event with `Date.now()`,
// so multiple `stream_chunk` events within the same step burst through
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index 13e056f0458..2646feda5a2 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -41,9 +41,21 @@ const createFakeStreamManager = () => {
};
const createFakePersistenceHandler = () => {
+ // Faithful publish-gate fake: same latch semantics as the real handler
+ // (filter by event identity, latch per event) so batch-retry tests exercise
+ // the real skip/resume behavior instead of a stub that returns everything.
+ const publishedKeys = new Set<string>();
+ const gateKey = (event: AgentStreamEvent) =>
+ `${event.stepIndex}:${event.type}:${event.timestamp}`;
const handler = {
+ filterUnpublishedEvents: vi.fn((_operationId: string, events: AgentStreamEvent[]) =>
+ events.filter((event) => !publishedKeys.has(gateKey(event))),
+ ),
finish: vi.fn(async () => {}),
ingest: vi.fn(async () => {}),
+ markEventPublished: vi.fn((_operationId: string, event: AgentStreamEvent) => {
+ publishedKeys.add(gateKey(event));
+ }),
};
return handler as unknown as HeterogeneousPersistenceHandler & typeof handler;
};
@@ -145,6 +157,99 @@ describe('HeterogeneousAgentService', () => {
).rejects.toThrow('redis down');
});
+ it('republishes nothing and skips the trace fold when an identical batch is redelivered', async () => {
+ // Response lost after a fully successful attempt β†’ the CLI BatchIngester
+ // redelivers the same batch. Live subscribers must not see duplicates,
+ // and the execution-trace snapshot must not double-fold.
+ const appendBatch = vi
+ .spyOn(HeteroTraceRecorder.prototype, 'appendBatch')
+ .mockResolvedValue();
+ const { manager, published, service } = createService();
+ const events: AgentStreamEvent[] = [
+ buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'hi' }),
+ buildEvent('tool_start', 1, { toolCallId: 'tc-1' }),
+ ];
+
+ await service.heteroIngest({
+ agentType: 'codex',
+ events,
+ operationId: 'op-test',
+ topicId: 'topic-1',
+ });
+ expect(published).toHaveLength(2);
+
+ await service.heteroIngest({
+ agentType: 'codex',
+ events,
+ operationId: 'op-test',
+ topicId: 'topic-1',
+ });
+
+ expect(manager.publishStreamEvent).toHaveBeenCalledTimes(2);
+ expect(published).toHaveLength(2);
+ expect(appendBatch).toHaveBeenCalledTimes(1);
+ appendBatch.mockRestore();
+ });
+
+ it('a retried batch resumes publishing from the first unpublished event (no duplicates, no loss)', async () => {
+ // Publish dies mid-loop on the first attempt: the head is delivered and
+ // latched, the tail is not. The retry must publish ONLY the tail β€”
+ // republishing the head would duplicate live events, skipping the tail
+ // would lose them.
+ const appendBatch = vi
+ .spyOn(HeteroTraceRecorder.prototype, 'appendBatch')
+ .mockResolvedValue();
+ const published: any[] = [];
+ let failOnSecondPublish = true;
+ const manager: Partial<IStreamEventManager> = {
+ publishStreamEvent: vi.fn(async (_operationId, event) => {
+ if (failOnSecondPublish && published.length === 1) {
+ failOnSecondPublish = false;
+ throw new Error('redis down');
+ }
+ published.push(event);
+ return `id-${published.length}`;
+ }),
+ };
+ const persistenceHandler = createFakePersistenceHandler();
+ const service = new HeterogeneousAgentService({} as any, 'user-test', {
+ persistenceHandler,
+ streamEventManager: manager as IStreamEventManager,
+ });
+ const events: AgentStreamEvent[] = [
+ buildEvent('stream_start', 0, { assistantMessage: { id: 'asst-1' } }),
+ buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'hello' }),
+ buildEvent('agent_runtime_end', 2, { reason: 'success' }),
+ ];
+
+ await expect(
+ service.heteroIngest({
+ agentType: 'codex',
+ events,
+ operationId: 'op-test',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow('redis down');
+ expect(published.map((event) => event.type)).toEqual(['stream_start']);
+
+ await service.heteroIngest({
+ agentType: 'codex',
+ events,
+ operationId: 'op-test',
+ topicId: 'topic-1',
+ });
+
+ // Every event delivered exactly once across both attempts.
+ expect(published.map((event) => event.type)).toEqual([
+ 'stream_start',
+ 'stream_chunk',
+ 'agent_runtime_end',
+ ]);
+ // The recorder folds once β€” on the attempt that delivered new events.
+ expect(appendBatch).toHaveBeenCalledTimes(1);
+ appendBatch.mockRestore();
+ });
+
it('persists before publishing β€” DB is the source of truth fetchAndReplace reads', async () => {
const callOrder: string[] = [];
const manager: Partial<IStreamEventManager> = {
@@ -154,10 +259,14 @@ describe('HeterogeneousAgentService', () => {
}),
};
const persistenceHandler = {
+ filterUnpublishedEvents: vi.fn(
+ (_operationId: string, events: AgentStreamEvent[]) => events,
+ ),
finish: vi.fn(async () => {}),
ingest: vi.fn(async () => {
callOrder.push('persist');
}),
+ markEventPublished: vi.fn(),
} as unknown as HeterogeneousPersistenceHandler;
const service = new HeterogeneousAgentService({} as any, 'user-test', {
persistenceHandler,
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 437cd39f05f..d87a266a40c 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -150,10 +150,24 @@ export class HeterogeneousAgentService {
throw err;
}
- // Sequential publish preserves stepIndex ordering β€” Redis XADD itself is
- // serialized but awaiting in-order avoids interleaving with concurrent
- // ingest batches sharing the same operationId.
- for (const event of events) {
+ // Publish only events not yet delivered to the stream. The publish gate
+ // (`publishedKeys`, peer of the persistence dedupe) makes a BatchIngester
+ // retry invisible to live subscribers: a batch that fully succeeded but
+ // lost its tRPC response republishes nothing, while one that died
+ // mid-publish resumes from the first unpublished event β€” each event is
+ // latched only after its own XADD succeeds. Sequential publish preserves
+ // stepIndex ordering β€” Redis XADD itself is serialized but awaiting
+ // in-order avoids interleaving with concurrent ingest batches sharing the
+ // same operationId.
+ const unpublished = this.persistenceHandler.filterUnpublishedEvents(operationId, events);
+ if (unpublished.length < events.length) {
+ log(
+ 'heteroIngest: skip %d already-published events op=%s',
+ events.length - unpublished.length,
+ operationId,
+ );
+ }
+ for (const event of unpublished) {
// Each event already carries operationId; pass through unchanged so the
// wire shape on the WS side is identical to gateway-driven runs.
await this.streamEventManager.publishStreamEvent(operationId, {
@@ -161,15 +175,18 @@ export class HeterogeneousAgentService {
stepIndex: event.stepIndex,
type: event.type,
});
+ this.persistenceHandler.markEventPublished(operationId, event);
}
// Accumulate the execution-trace snapshot LAST. The recorder has no
// per-event idempotency, so it must run only after every step that can throw
// and trigger a BatchIngester retry of this same batch β€” otherwise a publish
// failure above would re-fold these events and double-count the snapshot.
- // It's the final statement and best-effort (never throws), so it folds each
- // batch exactly once (on the attempt that gets this far).
- await this.traceRecorder.appendBatch(operationId, events);
+ // Gating on the publish gate also skips the pure-redelivery batch (full
+ // success whose response was lost), which would otherwise double-fold here.
+ if (unpublished.length > 0) {
+ await this.traceRecorder.appendBatch(operationId, events);
+ }
}
async heteroFinish(params: HeterogeneousFinishParams): Promise<void> {
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index a6613838be9..9fdb9d5a25d 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -78,6 +78,18 @@ export interface StreamChunkData {
images?: any[];
reasoning?: string;
reasoningParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;
+ /**
+ * `lh hetero exec` coalesces main-agent text deltas into full-text
+ * snapshots: `content` carries the WHOLE message so far and must replace
+ * the accumulated text, not append to it. Absent on plain deltas.
+ */
+ snapshotMode?: 'replace';
+ /**
+ * Operation-monotonic sequence for `replace` snapshots. Consumers drop a
+ * snapshot whose seq is ≀ the last applied one β€” that is a redelivery
+ * (producer batch retry) or an out-of-order duplicate.
+ */
+ snapshotSeq?: number;
toolsCalling?: any[];
}
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
index e9104639feb..1f15c663c9a 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts
@@ -121,6 +121,31 @@ describe('main agent reducer', () => {
expect(state.lastTextSnapshotSeq).toBe(3);
});
+ it('replaces reasoning snapshots and drops stale or redelivered seqs', () => {
+ const snapshot = (reasoning: string, snapshotSeq: number) => ({
+ data: { chunkType: 'reasoning', reasoning, snapshotMode: 'replace', snapshotSeq },
+ type: 'stream_chunk',
+ });
+ const { state, steps } = run([
+ snapshot('thinking', 1),
+ snapshot('thinking done', 2),
+ // Redelivered seq 2 (batch retry on a cold replica) β€” must be a no-op,
+ // not an append: appending would duplicate the reasoning durably.
+ snapshot('thinking done', 2),
+ // Stale out-of-order snapshot β€” dropped.
+ snapshot('thinking', 1),
+ ]);
+
+ expect(steps[1]).toEqual([
+ { kind: 'streamContent', messageId: 'A0', reasoning: 'thinking done' },
+ ]);
+ expect(steps[2]).toEqual([]);
+ expect(steps[3]).toEqual([]);
+ expect(state.accReasoning).toBe('thinking done');
+ expect(state.lastReasoningSnapshotSeq).toBe(2);
+ expect(state.turnMetadata.heteroReasoningSnapshotSeq).toBe(2);
+ });
+
it('accumulates reasoning separately', () => {
const { steps, state } = run([reasoningEvent('think '), reasoningEvent('more')]);
expect(steps[1]).toEqual([{ kind: 'streamContent', messageId: 'A0', reasoning: 'think more' }]);
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
index f895eb71588..94c763a6258 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
@@ -163,6 +163,7 @@ const openTurn = (state: MainAgentRunState, data: any, ctx: MainAgentReduceCtx):
next.currentMainMessageId = mainMessageId;
next.accContent = '';
next.accReasoning = '';
+ next.lastReasoningSnapshotSeq = 0;
next.lastTextSnapshotSeq = 0;
next.turnMetadata = {};
next.toolState = emptyToolState();
@@ -222,9 +223,23 @@ const reduceTextChunk = (state: MainAgentRunState, data: any): ReduceResult => {
};
const reduceReasoningChunk = (state: MainAgentRunState, data: any): ReduceResult => {
- if (!data?.reasoning) return { intents: [], state };
const next = copyState(state);
- next.accReasoning = state.accReasoning + data.reasoning;
+ const snapshotMode = data?.snapshotMode;
+ const snapshotSeq = typeof data?.snapshotSeq === 'number' ? data.snapshotSeq : undefined;
+
+ // Mirrors `reduceTextChunk`: `replace` snapshots are idempotent under batch
+ // redelivery (a raw delta re-append would durably duplicate reasoning on a
+ // cold-replica retry), and the seq guard drops stale/out-of-order ones.
+ if (snapshotMode === 'replace' && snapshotSeq !== undefined) {
+ if (snapshotSeq <= state.lastReasoningSnapshotSeq) return { intents: [], state }; // stale snapshot
+ next.lastReasoningSnapshotSeq = snapshotSeq;
+ next.turnMetadata = { ...next.turnMetadata, heteroReasoningSnapshotSeq: snapshotSeq };
+ next.accReasoning = data.reasoning;
+ } else {
+ if (!data?.reasoning) return { intents: [], state };
+ next.accReasoning = state.accReasoning + data.reasoning;
+ }
+
return {
intents: [
{ kind: 'streamContent', messageId: next.currentAssistantId, reasoning: next.accReasoning },
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
index 42454c0db0d..9928939564a 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts
@@ -81,6 +81,8 @@ export interface MainAgentRunState {
currentMainMessageId: string | undefined;
/** Set once a terminal event has been reduced (idempotent finalize). */
ended: boolean;
+ /** Highest seen reasoning snapshot sequence (replace-mode de-dup). */
+ lastReasoningSnapshotSeq: number;
/**
* Chain rule: the most recent NON-tool, NON-signal
* main-thread message β€” the run's spine. The next NORMAL turn's assistant
@@ -126,6 +128,7 @@ export const createMainAgentRunState = (seedAssistantId: string): MainAgentRunSt
currentMainMessageId: undefined,
ended: false,
lastSpineMessageId: seedAssistantId,
+ lastReasoningSnapshotSeq: 0,
lastTextSnapshotSeq: 0,
lastToolMsgIdEver: undefined,
subagents: createSubagentRunsState(),
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
index d868788eda4..48f6dd57cfc 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
@@ -237,6 +237,120 @@ describe('createGatewayEventHandler', () => {
);
});
+ it('applies replace snapshots and drops redelivered snapshot seqs', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ // `lh hetero exec` sends full-text snapshots: each carries the WHOLE
+ // message so far and must replace, not append.
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'text',
+ content: 'Hello',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ }),
+ );
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'text',
+ content: 'Hello world',
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ }),
+ );
+ // Redelivery of seq 2 (server-side batch retry) β€” must be dropped, not
+ // appended: appending would render "Hello worldHello world".
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'text',
+ content: 'Hello world',
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ }),
+ );
+ await flush();
+
+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(
+ {
+ id: 'msg-initial',
+ type: 'updateMessage',
+ value: { content: 'Hello world' },
+ },
+ { operationId: 'op-1' },
+ );
+ const textDispatches = store.internal_dispatchMessage.mock.calls.filter(
+ ([action]: any[]) => action.type === 'updateMessage' && 'content' in action.value,
+ );
+ expect(textDispatches).toHaveLength(2); // the redelivered snapshot dispatched nothing
+ });
+
+ it('applies reasoning replace snapshots and drops redelivered seqs', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'reasoning',
+ reasoning: 'thinking',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ }),
+ );
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'reasoning',
+ reasoning: 'thinking done',
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ }),
+ );
+ // Redelivered seq 2 β€” appending it would render "thinking donethinking done".
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'reasoning',
+ reasoning: 'thinking done',
+ snapshotMode: 'replace',
+ snapshotSeq: 2,
+ }),
+ );
+ await flush();
+
+ const reasoningDispatches = store.internal_dispatchMessage.mock.calls.filter(
+ ([action]: any[]) => action.type === 'updateMessage' && 'reasoning' in action.value,
+ );
+ expect(reasoningDispatches).toHaveLength(2); // duplicate dropped
+ expect(reasoningDispatches.at(-1)?.[0].value).toEqual({
+ reasoning: { content: 'thinking done' },
+ });
+ });
+
+ it('a snapshot replaces text accumulated from plain deltas', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Hel' }));
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'text',
+ content: 'Hello world',
+ snapshotMode: 'replace',
+ snapshotSeq: 1,
+ }),
+ );
+ await flush();
+
+ // Replace, not append β€” appending would render "HelHello world".
+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(
+ {
+ id: 'msg-initial',
+ type: 'updateMessage',
+ value: { content: 'Hello world' },
+ },
+ { operationId: 'op-1' },
+ );
+ });
+
it('should accumulate reasoning content', async () => {
const store = createMockStore();
const handler = createHandler(store);
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index 03bd41077cc..c3b696dd7b1 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -416,6 +416,11 @@ export const createGatewayEventHandler = (
// Accumulated content from stream chunks (reset on each stream_start)
let accumulatedContent = '';
let accumulatedReasoning = '';
+ // Last applied `replace`-snapshot seqs. Operation-monotonic (the producer
+ // never resets them across messages), so unlike the accumulators they are
+ // NOT reset on stream boundaries β€” a seq ≀ these is a redelivered duplicate.
+ let lastTextSnapshotSeq = 0;
+ let lastReasoningSnapshotSeq = 0;
// Tracks whether any server-confirmed state has actually arrived
// (server-assigned assistant id, streamed text/reasoning/tools, or a SoT
@@ -599,33 +604,68 @@ export const createGatewayEventHandler = (
if (!data) return;
if (data.chunkType === 'text' && data.content) {
- // Text after reasoning marks the end of the thinking pass β€” see
- // `StreamingHandler.handleText` for the same transition.
- endReasoningIfNeeded();
- accumulatedContent += data.content;
- hasStreamedContent = true;
- get().internal_dispatchMessage(
- {
- id: currentAssistantMessageId,
- type: 'updateMessage',
- value: { content: accumulatedContent },
- },
- dispatchContext,
- );
+ // `lh hetero exec` coalesces main-agent text into full-text
+ // `replace` snapshots; native gateway runs stream plain deltas.
+ const snapshotSeq =
+ data.snapshotMode === 'replace' && typeof data.snapshotSeq === 'number'
+ ? data.snapshotSeq
+ : undefined;
+
+ if (snapshotSeq !== undefined && snapshotSeq <= lastTextSnapshotSeq) {
+ // Redelivered snapshot (producer batch retry / duplicate on the
+ // stream) β€” already applied, appending it would duplicate text.
+ } else {
+ // Text after reasoning marks the end of the thinking pass β€” see
+ // `StreamingHandler.handleText` for the same transition.
+ endReasoningIfNeeded();
+ if (snapshotSeq === undefined) {
+ accumulatedContent += data.content;
+ } else {
+ lastTextSnapshotSeq = snapshotSeq;
+ accumulatedContent = data.content;
+ }
+ hasStreamedContent = true;
+ get().internal_dispatchMessage(
+ {
+ id: currentAssistantMessageId,
+ type: 'updateMessage',
+ value: { content: accumulatedContent },
+ },
+ dispatchContext,
+ );
+ }
}
if (data.chunkType === 'reasoning' && data.reasoning) {
- startReasoningIfNeeded();
- accumulatedReasoning += data.reasoning;
- hasStreamedContent = true;
- get().internal_dispatchMessage(
- {
- id: currentAssistantMessageId,
- type: 'updateMessage',
- value: { reasoning: { content: accumulatedReasoning } },
- },
- dispatchContext,
- );
+ // Same snapshot semantics as text above: `lh hetero exec`
+ // coalesces reasoning into `replace` snapshots; redelivered seqs
+ // are dropped instead of appended (which would duplicate the
+ // thinking text on a server-side batch retry).
+ const snapshotSeq =
+ data.snapshotMode === 'replace' && typeof data.snapshotSeq === 'number'
+ ? data.snapshotSeq
+ : undefined;
+
+ if (snapshotSeq !== undefined && snapshotSeq <= lastReasoningSnapshotSeq) {
+ // Redelivered snapshot β€” already applied.
+ } else {
+ startReasoningIfNeeded();
+ if (snapshotSeq === undefined) {
+ accumulatedReasoning += data.reasoning;
+ } else {
+ lastReasoningSnapshotSeq = snapshotSeq;
+ accumulatedReasoning = data.reasoning;
+ }
+ hasStreamedContent = true;
+ get().internal_dispatchMessage(
+ {
+ id: currentAssistantMessageId,
+ type: 'updateMessage',
+ value: { reasoning: { content: accumulatedReasoning } },
+ },
+ dispatchContext,
+ );
+ }
}
if (data.chunkType === 'tools_calling' && data.toolsCalling) {