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(gateway): buffer high-frequency stream updates (#18815)

Arvin Xu4cde5cb96b46
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 07dad443c1f..3c3a136d631 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -45,6 +45,7 @@ import { isTrpcErrorCode } from '@/utils/trpcError';
import { resolveNewThreadIntent } from '../../dispatch/newThreadIntent';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import type { RunScope } from '../../lifecycle/types';
+import { createGatewayEventBuffer } from './gatewayEventBuffer';
import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';
import { createGatewayEventRouter } from './gatewayEventRouter';
import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
@@ -256,9 +257,11 @@ export class GatewayActionImpl {
let receivedTerminalEvent = false;
let terminalSucceeded = false;
let sessionCompleted = false;
+ const eventBuffer = createGatewayEventBuffer((event) => onEvent?.(event));
const fireSessionComplete = (opts?: { authFailed?: boolean }) => {
if (sessionCompleted) return;
sessionCompleted = true;
+ eventBuffer.flush();
onSessionComplete?.({
authFailed: opts?.authFailed ?? false,
succeeded: terminalSucceeded,
@@ -289,7 +292,7 @@ export class GatewayActionImpl {
) {
terminalSucceeded = true;
}
- onEvent?.(event);
+ eventBuffer.push(event);
});
// Handle session completion
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.test.ts
new file mode 100644
index 00000000000..b09448ff0b3
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.test.ts
@@ -0,0 +1,130 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createGatewayEventBuffer } from './gatewayEventBuffer';
+
+const makeEvent = (
+ chunkType: 'reasoning' | 'text',
+ value: string,
+ overrides: Partial<AgentStreamEvent> = {},
+) =>
+ ({
+ data: chunkType === 'text' ? { chunkType, content: value } : { chunkType, reasoning: value },
+ operationId: 'op-1',
+ stepIndex: 1,
+ timestamp: 0,
+ type: 'stream_chunk',
+ ...overrides,
+ }) as AgentStreamEvent;
+
+describe('createGatewayEventBuffer', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1000);
+ });
+
+ it('delivers the first chunk immediately and coalesces a burst into one update', () => {
+ const listener = vi.fn();
+ const buffer = createGatewayEventBuffer(listener);
+
+ buffer.push(makeEvent('text', 'A'));
+ buffer.push(makeEvent('text', 'B'));
+ buffer.push(makeEvent('text', 'C'));
+
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(listener.mock.calls[0][0].data).toMatchObject({ content: 'A' });
+
+ vi.advanceTimersByTime(299);
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(1);
+
+ expect(listener).toHaveBeenCalledTimes(2);
+ expect(listener.mock.calls[1][0].data).toMatchObject({ content: 'BC' });
+ });
+
+ it('flushes merged deltas in order when a delayed timer is already overdue', () => {
+ const listener = vi.fn();
+ const unschedule = vi.fn();
+ let now = 0;
+ let scheduledFlush: (() => void) | undefined;
+ const buffer = createGatewayEventBuffer(listener, {
+ now: () => now,
+ schedule: (callback) => {
+ scheduledFlush = callback;
+ return 1 as unknown as ReturnType<typeof setTimeout>;
+ },
+ unschedule,
+ });
+
+ buffer.push(makeEvent('text', 'A'));
+ buffer.push(makeEvent('text', 'B'));
+ now = 301;
+ buffer.push(makeEvent('text', 'C'));
+
+ expect(listener.mock.calls.map(([event]) => event.data)).toEqual([
+ expect.objectContaining({ content: 'A' }),
+ expect.objectContaining({ content: 'BC' }),
+ ]);
+ expect(unschedule).toHaveBeenCalledTimes(1);
+
+ scheduledFlush?.();
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+
+ it('flushes pending prose before a semantic boundary', () => {
+ const listener = vi.fn();
+ const buffer = createGatewayEventBuffer(listener);
+ const toolEvent = {
+ data: { chunkType: 'tools_calling', toolsCalling: [{ id: 'tool-1' }] },
+ operationId: 'op-1',
+ stepIndex: 1,
+ timestamp: 0,
+ type: 'stream_chunk',
+ } as AgentStreamEvent;
+
+ buffer.push(makeEvent('text', 'A'));
+ buffer.push(makeEvent('text', 'B'));
+ buffer.push(toolEvent);
+
+ expect(listener.mock.calls.map(([event]) => event.data)).toEqual([
+ expect.objectContaining({ content: 'A' }),
+ expect.objectContaining({ content: 'B' }),
+ toolEvent.data,
+ ]);
+ });
+
+ it('keeps only the latest replace snapshot inside an update window', () => {
+ const listener = vi.fn();
+ const buffer = createGatewayEventBuffer(listener);
+ const snapshot = (content: string, snapshotSeq: number) =>
+ makeEvent('text', content, {
+ data: { chunkType: 'text', content, snapshotMode: 'replace', snapshotSeq },
+ });
+
+ buffer.push(snapshot('A', 1));
+ buffer.push(snapshot('ABC', 3));
+ buffer.push(snapshot('AB', 2));
+ vi.advanceTimersByTime(300);
+
+ expect(listener).toHaveBeenCalledTimes(2);
+ expect(listener.mock.calls[1][0].data).toMatchObject({ content: 'ABC', snapshotSeq: 3 });
+ });
+
+ it('does not merge chunks across step or operation boundaries', () => {
+ const listener = vi.fn();
+ const buffer = createGatewayEventBuffer(listener);
+
+ buffer.push(makeEvent('reasoning', 'step one'));
+ buffer.push(makeEvent('reasoning', 'step two', { stepIndex: 2 }));
+ buffer.push(makeEvent('reasoning', 'other op', { operationId: 'op-2', stepIndex: 2 }));
+
+ expect(listener.mock.calls.map(([event]) => event.data)).toEqual([
+ expect.objectContaining({ reasoning: 'step one' }),
+ expect.objectContaining({ reasoning: 'step two' }),
+ ]);
+
+ buffer.flush();
+ expect(listener.mock.calls[2][0].data).toMatchObject({ reasoning: 'other op' });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.ts
new file mode 100644
index 00000000000..f6501c4ec3e
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.ts
@@ -0,0 +1,167 @@
+import type { AgentStreamEvent, StreamChunkData } from '@lobechat/agent-gateway-client';
+
+const GATEWAY_STREAM_UPDATE_INTERVAL_MS = 300;
+
+type BufferedChunkKind = 'reasoning' | 'text';
+
+interface BufferedChunk {
+ data: StreamChunkData;
+ event: AgentStreamEvent;
+ kind: BufferedChunkKind;
+}
+
+interface GatewayEventBufferOptions {
+ now?: () => number;
+ schedule?: (callback: () => void, delay: number) => ReturnType<typeof setTimeout>;
+ unschedule?: (timer: ReturnType<typeof setTimeout>) => void;
+}
+
+const getBufferedChunkKind = (event: AgentStreamEvent): BufferedChunkKind | undefined => {
+ if (event.type !== 'stream_chunk') return;
+
+ const chunkType = (event.data as StreamChunkData | undefined)?.chunkType;
+ return chunkType === 'text' || chunkType === 'reasoning' ? chunkType : undefined;
+};
+
+const toBufferedChunk = (event: AgentStreamEvent, kind: BufferedChunkKind): BufferedChunk => ({
+ data: event.data as StreamChunkData,
+ event,
+ kind,
+});
+
+const mergeBufferedChunk = (
+ current: BufferedChunk,
+ incomingEvent: AgentStreamEvent,
+ incomingData: StreamChunkData,
+): BufferedChunk => {
+ if (current.data.snapshotMode === 'replace') {
+ const currentSequence = current.data.snapshotSeq;
+ const incomingSequence = incomingData.snapshotSeq;
+ if (
+ typeof currentSequence === 'number' &&
+ typeof incomingSequence === 'number' &&
+ incomingSequence <= currentSequence
+ ) {
+ return current;
+ }
+
+ return toBufferedChunk(incomingEvent, current.kind);
+ }
+
+ if (current.kind === 'text') {
+ return {
+ data: {
+ ...incomingData,
+ content: `${current.data.content ?? ''}${incomingData.content ?? ''}`,
+ },
+ event: {
+ ...incomingEvent,
+ data: {
+ ...incomingData,
+ content: `${current.data.content ?? ''}${incomingData.content ?? ''}`,
+ },
+ } as AgentStreamEvent,
+ kind: current.kind,
+ };
+ }
+
+ return {
+ data: {
+ ...incomingData,
+ reasoning: `${current.data.reasoning ?? ''}${incomingData.reasoning ?? ''}`,
+ },
+ event: {
+ ...incomingEvent,
+ data: {
+ ...incomingData,
+ reasoning: `${current.data.reasoning ?? ''}${incomingData.reasoning ?? ''}`,
+ },
+ } as AgentStreamEvent,
+ kind: current.kind,
+ };
+};
+
+/**
+ * Bounds renderer work caused by high-frequency Gateway text deltas.
+ *
+ * The first chunk is delivered immediately for low time-to-first-token. Further
+ * consecutive chunks of the same operation, step, and kind are merged until the
+ * update interval expires. Any semantic boundary flushes first, preserving the
+ * exact ordering between prose/reasoning, tools, step transitions, and terminal
+ * events.
+ */
+export const createGatewayEventBuffer = (
+ listener: (event: AgentStreamEvent) => void,
+ options: GatewayEventBufferOptions = {},
+) => {
+ const now = options.now ?? Date.now;
+ const schedule = options.schedule ?? setTimeout;
+ const unschedule = options.unschedule ?? clearTimeout;
+
+ let buffered: BufferedChunk | undefined;
+ let lastDeliveredAt = -Infinity;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const clearTimer = () => {
+ if (timer === undefined) return;
+ unschedule(timer);
+ timer = undefined;
+ };
+
+ const flush = () => {
+ clearTimer();
+ if (!buffered) return;
+
+ const event = buffered.event;
+ buffered = undefined;
+ lastDeliveredAt = now();
+ listener(event);
+ };
+
+ const scheduleFlush = () => {
+ if (timer !== undefined) return;
+ const elapsed = now() - lastDeliveredAt;
+ timer = schedule(flush, Math.max(0, GATEWAY_STREAM_UPDATE_INTERVAL_MS - elapsed));
+ };
+
+ const push = (event: AgentStreamEvent) => {
+ const kind = getBufferedChunkKind(event);
+
+ if (!kind) {
+ flush();
+ listener(event);
+ return;
+ }
+
+ const data = event.data as StreamChunkData;
+
+ const canMerge =
+ buffered?.kind === kind &&
+ buffered.event.operationId === event.operationId &&
+ buffered.event.stepIndex === event.stepIndex &&
+ buffered.data.snapshotMode === data.snapshotMode;
+
+ if (buffered && canMerge) {
+ buffered = mergeBufferedChunk(buffered, event, data);
+ if (now() - lastDeliveredAt >= GATEWAY_STREAM_UPDATE_INTERVAL_MS) {
+ flush();
+ } else {
+ scheduleFlush();
+ }
+ return;
+ }
+
+ if (buffered) flush();
+
+ if (now() - lastDeliveredAt >= GATEWAY_STREAM_UPDATE_INTERVAL_MS) {
+ listener(event);
+ lastDeliveredAt = now();
+ return;
+ }
+
+ buffered = toBufferedChunk(event, kind);
+ scheduleFlush();
+ };
+
+ return { flush, push };
+};