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: coalesce Gateway tool state updates (#18969)

Arvin Xu5fcba413b3b1
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
index b09448ff0b3..826b98bb182 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.test.ts
@@ -17,6 +17,21 @@ const makeEvent = (
...overrides,
}) as AgentStreamEvent;
+const makeToolStateEvent = (toolCallId: string, snapshotSeq: number, operationId = 'op-1') =>
+ ({
+ data: {
+ chunkType: 'tool_state',
+ pluginState: { output: `snapshot-${snapshotSeq}` },
+ snapshotMode: 'replace',
+ snapshotSeq,
+ toolCallId,
+ },
+ operationId,
+ stepIndex: 1,
+ timestamp: 0,
+ type: 'stream_chunk',
+ }) as AgentStreamEvent;
+
describe('createGatewayEventBuffer', () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -111,6 +126,65 @@ describe('createGatewayEventBuffer', () => {
expect(listener.mock.calls[1][0].data).toMatchObject({ content: 'ABC', snapshotSeq: 3 });
});
+ it('coalesces tool-state snapshots by operation and tool call', () => {
+ const listener = vi.fn();
+ const buffer = createGatewayEventBuffer(listener);
+
+ for (let snapshotSeq = 1; snapshotSeq <= 100; snapshotSeq += 1) {
+ buffer.push(makeToolStateEvent('tool-1', snapshotSeq));
+ }
+ buffer.push(makeToolStateEvent('tool-1', 50));
+
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(listener.mock.calls[0][0].data).toMatchObject({ snapshotSeq: 1 });
+
+ vi.advanceTimersByTime(300);
+
+ expect(listener).toHaveBeenCalledTimes(2);
+ expect(listener.mock.calls[1][0].data).toMatchObject({ snapshotSeq: 100 });
+ });
+
+ it('buffers parallel tool calls independently', () => {
+ const listener = vi.fn();
+ const buffer = createGatewayEventBuffer(listener);
+
+ buffer.push(makeToolStateEvent('tool-1', 1));
+ buffer.push(makeToolStateEvent('tool-2', 1));
+ buffer.push(makeToolStateEvent('tool-1', 2));
+ buffer.push(makeToolStateEvent('tool-2', 2));
+
+ expect(listener).toHaveBeenCalledTimes(2);
+
+ vi.advanceTimersByTime(300);
+
+ expect(listener.mock.calls.slice(2).map(([event]) => event.data)).toEqual([
+ expect.objectContaining({ snapshotSeq: 2, toolCallId: 'tool-1' }),
+ expect.objectContaining({ snapshotSeq: 2, toolCallId: 'tool-2' }),
+ ]);
+ });
+
+ it('flushes the latest tool state before a semantic boundary', () => {
+ const listener = vi.fn();
+ const buffer = createGatewayEventBuffer(listener);
+ const toolEnd = {
+ data: { toolCallId: 'tool-1' },
+ operationId: 'op-1',
+ stepIndex: 1,
+ timestamp: 0,
+ type: 'tool_end',
+ } as AgentStreamEvent;
+
+ buffer.push(makeToolStateEvent('tool-1', 1));
+ buffer.push(makeToolStateEvent('tool-1', 2));
+ buffer.push(toolEnd);
+
+ expect(listener.mock.calls.map(([event]) => event)).toEqual([
+ expect.objectContaining({ data: expect.objectContaining({ snapshotSeq: 1 }) }),
+ expect.objectContaining({ data: expect.objectContaining({ snapshotSeq: 2 }) }),
+ toolEnd,
+ ]);
+ });
+
it('does not merge chunks across step or operation boundaries', () => {
const listener = vi.fn();
const buffer = createGatewayEventBuffer(listener);
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.ts
index f6501c4ec3e..21043f0006c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventBuffer.ts
@@ -1,4 +1,8 @@
-import type { AgentStreamEvent, StreamChunkData } from '@lobechat/agent-gateway-client';
+import type {
+ AgentStreamEvent,
+ StreamChunkData,
+ ToolStateChunkData,
+} from '@lobechat/agent-gateway-client';
const GATEWAY_STREAM_UPDATE_INTERVAL_MS = 300;
@@ -23,6 +27,16 @@ const getBufferedChunkKind = (event: AgentStreamEvent): BufferedChunkKind | unde
return chunkType === 'text' || chunkType === 'reasoning' ? chunkType : undefined;
};
+const getToolStateData = (event: AgentStreamEvent): ToolStateChunkData | undefined => {
+ if (event.type !== 'stream_chunk') return;
+
+ const data = event.data as ToolStateChunkData | undefined;
+ return data?.chunkType === 'tool_state' ? data : undefined;
+};
+
+const getToolStateKey = (event: AgentStreamEvent, data: ToolStateChunkData) =>
+ `${event.operationId ?? ''}:${data.toolCallId}`;
+
const toBufferedChunk = (event: AgentStreamEvent, kind: BufferedChunkKind): BufferedChunk => ({
data: event.data as StreamChunkData,
event,
@@ -101,6 +115,12 @@ export const createGatewayEventBuffer = (
let buffered: BufferedChunk | undefined;
let lastDeliveredAt = -Infinity;
let timer: ReturnType<typeof setTimeout> | undefined;
+ const bufferedToolStates = new Map<
+ string,
+ { data: ToolStateChunkData; event: AgentStreamEvent }
+ >();
+ const lastToolStateDeliveredAt = new Map<string, number>();
+ let toolStateTimer: ReturnType<typeof setTimeout> | undefined;
const clearTimer = () => {
if (timer === undefined) return;
@@ -124,7 +144,77 @@ export const createGatewayEventBuffer = (
timer = schedule(flush, Math.max(0, GATEWAY_STREAM_UPDATE_INTERVAL_MS - elapsed));
};
+ const clearToolStateTimer = () => {
+ if (toolStateTimer === undefined) return;
+ unschedule(toolStateTimer);
+ toolStateTimer = undefined;
+ };
+
+ const flushToolStates = (force = true) => {
+ clearToolStateTimer();
+ const currentTime = now();
+
+ for (const [key, pending] of bufferedToolStates) {
+ const deliveredAt = lastToolStateDeliveredAt.get(key) ?? -Infinity;
+ if (!force && currentTime - deliveredAt < GATEWAY_STREAM_UPDATE_INTERVAL_MS) continue;
+
+ bufferedToolStates.delete(key);
+ lastToolStateDeliveredAt.set(key, currentTime);
+ listener(pending.event);
+ }
+
+ if (!force && bufferedToolStates.size > 0) {
+ const nextDelay = Math.min(
+ ...[...bufferedToolStates.keys()].map((key) => {
+ const deliveredAt = lastToolStateDeliveredAt.get(key) ?? -Infinity;
+ return Math.max(0, GATEWAY_STREAM_UPDATE_INTERVAL_MS - (currentTime - deliveredAt));
+ }),
+ );
+ toolStateTimer = schedule(() => flushToolStates(false), nextDelay);
+ }
+ };
+
+ const scheduleToolStateFlush = () => {
+ if (toolStateTimer !== undefined) return;
+ const currentTime = now();
+ const nextDelay = Math.min(
+ ...[...bufferedToolStates.keys()].map((key) => {
+ const deliveredAt = lastToolStateDeliveredAt.get(key) ?? -Infinity;
+ return Math.max(0, GATEWAY_STREAM_UPDATE_INTERVAL_MS - (currentTime - deliveredAt));
+ }),
+ );
+ toolStateTimer = schedule(() => flushToolStates(false), nextDelay);
+ };
+
+ const pushToolState = (event: AgentStreamEvent, data: ToolStateChunkData) => {
+ flush();
+ const key = getToolStateKey(event, data);
+ const pending = bufferedToolStates.get(key);
+ if (pending && data.snapshotSeq <= pending.data.snapshotSeq) return;
+
+ const currentTime = now();
+ const deliveredAt = lastToolStateDeliveredAt.get(key) ?? -Infinity;
+ if (currentTime - deliveredAt >= GATEWAY_STREAM_UPDATE_INTERVAL_MS) {
+ bufferedToolStates.delete(key);
+ lastToolStateDeliveredAt.set(key, currentTime);
+ listener(event);
+ return;
+ }
+
+ bufferedToolStates.set(key, { data, event });
+ scheduleToolStateFlush();
+ };
+
const push = (event: AgentStreamEvent) => {
+ const toolStateData = getToolStateData(event);
+ if (toolStateData) {
+ pushToolState(event, toolStateData);
+ return;
+ }
+
+ // A prose chunk after a tool update is a semantic boundary too. Commit the
+ // latest state first so stream ordering remains observable in the renderer.
+ flushToolStates();
const kind = getBufferedChunkKind(event);
if (!kind) {
@@ -163,5 +253,11 @@ export const createGatewayEventBuffer = (
scheduleFlush();
};
- return { flush, push };
+ return {
+ flush: () => {
+ flush();
+ flushToolStates();
+ },
+ push,
+ };
};