Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🎞️ perf: Coalesce Streaming Delta Cache Writes Per Animation Frame (#14332)

Danny Avila3171b864130f
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index 73795d48ce..129bccd626 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -158,6 +158,7 @@ jest.mock('~/hooks/SSE/useEventHandlers', () => {
resetContentHandler: jest.fn(),
syncStepMessage: jest.fn(),
clearStepMaps: mockClearStepMaps,
+ flushPendingDeltas: jest.fn(),
messageHandler: jest.fn(),
setIsSubmitting: mockSetIsSubmitting,
setShowStopButton: jest.fn(),
diff --git a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
index fe773109b1..288e82ad3c 100644
--- a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
@@ -153,10 +153,22 @@ describe('useStepHandler', () => {
...overrides,
});
+ /** Delta cache flushes are rAF-coalesced; run them synchronously so the
+ * merged-output assertions below observe the flushed state. The dedicated
+ * coalescing test overrides this with a manual queue. */
beforeEach(() => {
jest.clearAllMocks();
mockLastAnnouncementTimeRef.current = 0;
mockGetMessages.mockReturnValue([]);
+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {
+ cb(0);
+ return 0;
+ });
+ jest.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
});
describe('initialization', () => {
@@ -1185,6 +1197,101 @@ describe('useStepHandler', () => {
);
});
+ it('coalesces multiple deltas into a single flush per animation frame', () => {
+ const rafQueue: FrameRequestCallback[] = [];
+ (window.requestAnimationFrame as jest.Mock).mockImplementation((cb: FrameRequestCallback) => {
+ rafQueue.push(cb);
+ return rafQueue.length;
+ });
+
+ const responseMessage = createResponseMessage();
+ mockGetMessages.mockReturnValue([responseMessage]);
+
+ const { result } = renderHook(() => useStepHandler(createHookParams()));
+
+ const runStep = createRunStep();
+ const submission = createSubmission();
+
+ act(() => {
+ result.current.stepHandler({ event: StepEvents.ON_RUN_STEP, data: runStep }, submission);
+ });
+ mockSetMessages.mockClear();
+
+ act(() => {
+ result.current.stepHandler(
+ { event: StepEvents.ON_MESSAGE_DELTA, data: createMessageDelta('step-1', 'Hello ') },
+ submission,
+ );
+ result.current.stepHandler(
+ { event: StepEvents.ON_MESSAGE_DELTA, data: createMessageDelta('step-1', 'World') },
+ submission,
+ );
+ });
+
+ expect(mockSetMessages).not.toHaveBeenCalled();
+ expect(rafQueue).toHaveLength(1);
+
+ act(() => {
+ rafQueue.forEach((cb) => cb(0));
+ });
+
+ expect(mockSetMessages).toHaveBeenCalledTimes(1);
+ const flushed = mockSetMessages.mock.calls[0][0];
+ const responseMsg = flushed[flushed.length - 1];
+ expect(responseMsg.content).toContainEqual(
+ expect.objectContaining({ type: ContentTypes.TEXT, text: 'Hello World' }),
+ );
+ });
+
+ it('flushPendingDeltas applies queued tokens synchronously and voids the frame', () => {
+ const rafQueue: FrameRequestCallback[] = [];
+ (window.requestAnimationFrame as jest.Mock).mockImplementation((cb: FrameRequestCallback) => {
+ rafQueue.push(cb);
+ return rafQueue.length;
+ });
+
+ const responseMessage = createResponseMessage();
+ mockGetMessages.mockReturnValue([responseMessage]);
+
+ const { result } = renderHook(() => useStepHandler(createHookParams()));
+
+ const runStep = createRunStep();
+ const submission = createSubmission();
+
+ act(() => {
+ result.current.stepHandler({ event: StepEvents.ON_RUN_STEP, data: runStep }, submission);
+ });
+ mockSetMessages.mockClear();
+
+ act(() => {
+ result.current.stepHandler(
+ { event: StepEvents.ON_MESSAGE_DELTA, data: createMessageDelta('step-1', 'Hello ') },
+ submission,
+ );
+ result.current.stepHandler(
+ { event: StepEvents.ON_MESSAGE_DELTA, data: createMessageDelta('step-1', 'World') },
+ submission,
+ );
+ });
+ expect(mockSetMessages).not.toHaveBeenCalled();
+
+ act(() => {
+ result.current.flushPendingDeltas();
+ });
+
+ expect(mockSetMessages).toHaveBeenCalledTimes(1);
+ const flushed = mockSetMessages.mock.calls[0][0];
+ const responseMsg = flushed[flushed.length - 1];
+ expect(responseMsg.content).toContainEqual(
+ expect.objectContaining({ type: ContentTypes.TEXT, text: 'Hello World' }),
+ );
+
+ act(() => {
+ rafQueue.forEach((cb) => cb(0));
+ });
+ expect(mockSetMessages).toHaveBeenCalledTimes(1);
+ });
+
it('should return early when contentPart is null', () => {
const responseMessage = createResponseMessage();
mockGetMessages.mockReturnValue([responseMessage]);
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index 6dc1501408..394c52dcd1 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -310,7 +310,14 @@ export default function useEventHandlers({
queryClient.invalidateQueries({ queryKey: [key], refetchType: 'all' });
}
}, [queryClient]);
- const { stepHandler, clearStepMaps, resetSubagentAtoms, syncStepMessage } = useStepHandler({
+ const {
+ stepHandler,
+ clearStepMaps,
+ resetSubagentAtoms,
+ syncStepMessage,
+ cancelPendingDeltaFlush,
+ flushPendingDeltas,
+ } = useStepHandler({
setMessages,
getMessages,
announcePolite,
@@ -1119,6 +1126,8 @@ export default function useEventHandlers({
createdHandler,
titleHandler,
syncStepMessage,
+ cancelPendingDeltaFlush,
+ flushPendingDeltas,
attachmentHandler,
abortConversation,
resetContentHandler,
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 6891819454..aadb6c9474 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -625,6 +625,7 @@ export default function useResumableSSE(
syncStepMessage,
attachmentHandler,
resetContentHandler,
+ flushPendingDeltas,
} = useEventHandlers({
setMessages,
getMessages,
@@ -697,6 +698,11 @@ export default function useResumableSSE(
);
}
};
+ /** The pause card must attach to the same message state the stream
+ * produced — apply any queued delta before reading the cache, or the
+ * later flush would clobber the card (and `syncStepMessage` below
+ * would sync a pre-delta copy). */
+ flushPendingDeltas();
const messages = getMessages() ?? [];
const index = findPendingActionMessageIndex(messages, pendingAction);
if (index < 0) {
@@ -741,6 +747,9 @@ export default function useResumableSSE(
);
}
};
+ /** Same boundary as pending actions: land queued deltas before the
+ * steer part is placed and synced. */
+ flushPendingDeltas();
const messages = getMessages() ?? [];
const index = findSteerMessageIndex(messages, event);
if (index < 0) {
@@ -1281,6 +1290,10 @@ export default function useResumableSSE(
if (responseCode == null && e.data) {
logger.log('ResumableSSE', 'Server-sent error event received:', e.data);
sse.close();
+ /** FLUSH (not cancel): the error card below is built from the cache
+ * tail, so queued tokens must land first — and a stale trailing
+ * frame must never overwrite the error write. */
+ flushPendingDeltas();
removeActiveJob(currentStreamId);
resetLive({ ...currentSubmission, userMessage });
if (
@@ -1377,6 +1390,7 @@ export default function useResumableSSE(
} else {
logger.error('ResumableSSE', 'Max reconnect attempts reached');
sse.close();
+ flushPendingDeltas();
errorHandler({ data: undefined, submission: currentSubmission as EventSubmission });
/** Terminal: clear the in-flight live estimate like the other
* stop-reconnecting paths so the gauge doesn't show stale tokens */
@@ -1478,6 +1492,7 @@ export default function useResumableSSE(
clearStepMaps,
messageHandler,
errorHandler,
+ flushPendingDeltas,
setIsSubmitting,
getMessages,
setMessages,
diff --git a/client/src/hooks/SSE/useSSE.ts b/client/src/hooks/SSE/useSSE.ts
index f1f17eaee1..a8c4a40cd7 100644
--- a/client/src/hooks/SSE/useSSE.ts
+++ b/client/src/hooks/SSE/useSSE.ts
@@ -59,6 +59,8 @@ export default function useSSE(
titleHandler,
attachmentHandler,
abortConversation,
+ cancelPendingDeltaFlush,
+ flushPendingDeltas,
} = useEventHandlers({
setMessages,
getMessages,
@@ -116,6 +118,9 @@ export default function useSSE(
const data = JSON.parse(e.data);
if (data.final != null) {
+ /** A queued delta flush reading the older streaming copy must never
+ * land on top of the server-final write. */
+ cancelPendingDeltaFlush();
clearAllDrafts(submission.conversation?.conversationId);
try {
finalHandler(data, submission as EventSubmission);
@@ -145,6 +150,9 @@ export default function useSSE(
} else if (data.event === UsageEvents.ON_TOKEN_USAGE) {
usageHandler(data.data, { ...submission, userMessage });
} else if (data.event === ApprovalEvents.ON_PENDING_ACTION) {
+ /** The pause card must attach to the same message state the stream
+ * produced — apply any queued delta before reading the cache. */
+ flushPendingDeltas();
const pendingAction = data.data as Agents.PendingAction;
const messages = getMessages() ?? [];
const index = findPendingActionMessageIndex(messages, pendingAction);
@@ -201,6 +209,9 @@ export default function useSSE(
});
sse.addEventListener('cancel', async () => {
+ /** FLUSH (not cancel): the abort below synthesizes the partial response
+ * from the cache, so the last queued tokens must land first. */
+ flushPendingDeltas();
const streamKey = (submission as TSubmission | null)?.['initialResponse']?.messageId;
if (completed.has(streamKey)) {
setIsSubmitting(false);
@@ -274,6 +285,9 @@ export default function useSSE(
setIsSubmitting(false);
}
+ /** FLUSH (not cancel): the error card is built from the cache tail, so
+ * the last queued tokens must land before it is synthesized. */
+ flushPendingDeltas();
errorHandler({ data, submission: { ...submission, userMessage } as EventSubmission });
});
diff --git a/client/src/hooks/SSE/useStepHandler.ts b/client/src/hooks/SSE/useStepHandler.ts
index b6e97c6743..2969501a62 100644
--- a/client/src/hooks/SSE/useStepHandler.ts
+++ b/client/src/hooks/SSE/useStepHandler.ts
@@ -126,6 +126,14 @@ export default function useStepHandler({
const pendingDeltaBuffer = useRef(new Map<string, TStepEvent[]>());
/** Coalesces rapid-fire summarize delta renders into a single rAF frame */
const summarizeDeltaRaf = useRef<number | null>(null);
+ /** Coalesces per-token message/reasoning delta cache writes into one rAF frame.
+ * `deltaFlushScheduled` (not the handle) gates scheduling: the handle is
+ * assigned after `requestAnimationFrame` returns, which would race a
+ * synchronously-invoked callback. */
+ const messageDeltaRaf = useRef<number | null>(null);
+ const deltaFlushScheduled = useRef(false);
+ const pendingDeltaFlushIds = useRef(new Set<string>());
+ const pendingDeltaFlushRef = useRef<(() => void) | null>(null);
/**
* Maps `SubagentUpdateEvent.subagentRunId` → parent `tool_call_id`.
* Preferred source is `payload.parentToolCallId` (threaded through by the
@@ -642,6 +650,41 @@ export default function useStepHandler({
)
: [...currentMessages, updatedResponse];
};
+ /**
+ * Per-token deltas fold into `messageMap` immediately (authoritative), but
+ * the cache write — and the buildTree + message-tree walk it triggers —
+ * flushes at most once per frame. Non-delta events keep writing
+ * synchronously from `messageMap`, so a trailing flush after them merges
+ * the same authoritative state; `clearStepMaps` cancels the flush at run
+ * boundaries (same lifecycle as the summarize coalescing above).
+ */
+ const scheduleCoalescedMessagesFlush = (responseMessageId: string) => {
+ pendingDeltaFlushIds.current.add(responseMessageId);
+ const flush = () => {
+ deltaFlushScheduled.current = false;
+ messageDeltaRaf.current = null;
+ pendingDeltaFlushRef.current = null;
+ const ids = pendingDeltaFlushIds.current;
+ pendingDeltaFlushIds.current = new Set();
+ let candidate = messages;
+ for (const id of ids) {
+ const latest = messageMap.current.get(id);
+ if (!latest) {
+ continue;
+ }
+ candidate = mergeResponseMessage(candidate, latest, id, { ensureUserMessage: true });
+ setMessages(candidate);
+ }
+ };
+ /** Exposed so terminal/read boundaries (abort, error, pending-action)
+ * can apply the queued tokens synchronously via `flushPendingDeltas`. */
+ pendingDeltaFlushRef.current = flush;
+ if (deltaFlushScheduled.current) {
+ return;
+ }
+ deltaFlushScheduled.current = true;
+ messageDeltaRaf.current = requestAnimationFrame(flush);
+ };
let parentMessageId =
submission.isRegenerate && submission.initialResponse?.parentMessageId
? submission.initialResponse.parentMessageId
@@ -873,11 +916,7 @@ export default function useStepHandler({
getStepMetadata(runStep),
);
messageMap.current.set(responseMessageId, updatedResponse);
- setMessages(
- mergeResponseMessage(messages, updatedResponse, responseMessageId, {
- ensureUserMessage: true,
- }),
- );
+ scheduleCoalescedMessagesFlush(responseMessageId);
}
} else if (stepEvent.event === StepEvents.ON_REASONING_DELTA) {
const reasoningDelta = stepEvent.data;
@@ -919,11 +958,7 @@ export default function useStepHandler({
getStepMetadata(runStep),
);
messageMap.current.set(responseMessageId, updatedResponse);
- setMessages(
- mergeResponseMessage(messages, updatedResponse, responseMessageId, {
- ensureUserMessage: true,
- }),
- );
+ scheduleCoalescedMessagesFlush(responseMessageId);
}
} else if (stepEvent.event === StepEvents.ON_RUN_STEP_DELTA) {
const runStepDelta = stepEvent.data;
@@ -1145,11 +1180,43 @@ export default function useStepHandler({
],
);
+ /** Cancels a queued delta flush so it can't overwrite a terminal write:
+ * once a final handler has written the server's authoritative message, a
+ * trailing frame reading the older streaming copy from `messageMap` must
+ * never land on top of it. */
+ const cancelPendingDeltaFlush = useCallback(() => {
+ if (messageDeltaRaf.current != null) {
+ cancelAnimationFrame(messageDeltaRaf.current);
+ messageDeltaRaf.current = null;
+ }
+ deltaFlushScheduled.current = false;
+ pendingDeltaFlushRef.current = null;
+ pendingDeltaFlushIds.current.clear();
+ }, []);
+
+ /** Applies a queued delta flush synchronously (then cancels the frame).
+ * For boundaries that READ the cache or synthesize from it — abort's
+ * partial-response capture, error cards, pending-action application — the
+ * queued tokens must land first or the stopped/errored message loses them. */
+ const flushPendingDeltas = useCallback(() => {
+ if (messageDeltaRaf.current != null) {
+ cancelAnimationFrame(messageDeltaRaf.current);
+ messageDeltaRaf.current = null;
+ }
+ const flush = pendingDeltaFlushRef.current;
+ pendingDeltaFlushRef.current = null;
+ deltaFlushScheduled.current = false;
+ if (flush) {
+ flush();
+ }
+ }, []);
+
const clearStepMaps = useCallback(() => {
if (summarizeDeltaRaf.current != null) {
cancelAnimationFrame(summarizeDeltaRaf.current);
summarizeDeltaRaf.current = null;
}
+ cancelPendingDeltaFlush();
toolCallIdMap.current.clear();
messageMap.current.clear();
stepMap.current.clear();
@@ -1170,7 +1237,7 @@ export default function useStepHandler({
* persisted `subagent_content` takes over for historical messages
* once the conversation is saved, and we prevent unbounded
* atomFamily growth across multi-conversation sessions. */
- }, [resetSandboxAtoms]);
+ }, [cancelPendingDeltaFlush, resetSandboxAtoms]);
/**
* Sync a message into the step handler's messageMap.
@@ -1183,5 +1250,12 @@ export default function useStepHandler({
}
}, []);
- return { stepHandler, clearStepMaps, resetSubagentAtoms, syncStepMessage };
+ return {
+ stepHandler,
+ clearStepMaps,
+ resetSubagentAtoms,
+ syncStepMessage,
+ cancelPendingDeltaFlush,
+ flushPendingDeltas,
+ };
}