Skip to content

Commit 497662f

Browse files
authored
perf(ui): batch streaming chat renders (#106353)
1 parent c5aa739 commit 497662f

5 files changed

Lines changed: 259 additions & 15 deletions

File tree

‎ui/src/pages/chat/chat-state.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ import {
1414
} from "./chat-queue.ts";
1515
import {
1616
ChatStateController,
17+
handlePageGatewayEvent,
1718
refreshChatMetadata,
19+
requestChatPageUpdate,
1820
resetChatStateForRouteSession,
1921
retryChatComposerMemoryFallback,
2022
resolveChatAvatarUrl,
@@ -45,6 +47,75 @@ afterEach(() => {
4547
});
4648

4749
describe("ChatStateController render lifecycle", () => {
50+
it("coalesces stream invalidations into one animation frame", () => {
51+
let nextFrame = 1;
52+
const frames = new Map<number, FrameRequestCallback>();
53+
vi.spyOn(globalThis, "requestAnimationFrame").mockImplementation((callback) => {
54+
const id = nextFrame++;
55+
frames.set(id, callback);
56+
return id;
57+
});
58+
const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation((id) => {
59+
frames.delete(id);
60+
});
61+
const requestUpdate = vi.fn();
62+
const state = { chatStreamRenderFrame: null, requestUpdate };
63+
64+
requestChatPageUpdate(state, "animation-frame");
65+
requestChatPageUpdate(state, "animation-frame");
66+
requestChatPageUpdate(state, "animation-frame");
67+
68+
expect(frames.size).toBe(1);
69+
expect(requestUpdate).not.toHaveBeenCalled();
70+
const firstFrame = frames.get(1);
71+
frames.delete(1);
72+
firstFrame?.(0);
73+
expect(requestUpdate).toHaveBeenCalledOnce();
74+
expect(state.chatStreamRenderFrame).toBeNull();
75+
76+
requestChatPageUpdate(state, "animation-frame");
77+
const staleFrame = frames.get(2);
78+
requestChatPageUpdate(state);
79+
staleFrame?.(0);
80+
81+
expect(cancelFrame).toHaveBeenCalledWith(2);
82+
expect(requestUpdate).toHaveBeenCalledTimes(2);
83+
expect(state.chatStreamRenderFrame).toBeNull();
84+
});
85+
86+
it("keeps every chat delta while batching their render", () => {
87+
let scheduledFrame: FrameRequestCallback | undefined;
88+
vi.spyOn(globalThis, "requestAnimationFrame").mockImplementation((callback) => {
89+
scheduledFrame = callback;
90+
return 1;
91+
});
92+
const requestUpdate = vi.fn();
93+
const state = {
94+
chatMessages: [],
95+
chatMessagesBySession: new Map(),
96+
chatRunId: "run-1",
97+
chatStream: null,
98+
chatStreamRenderFrame: null,
99+
chatStreamStartedAt: 1,
100+
lastError: null,
101+
pendingSessionMessageReloadSessionKey: null,
102+
requestUpdate,
103+
sessionKey: "main",
104+
} as unknown as ChatPageHost;
105+
106+
for (const deltaText of ["A", "B", "C"]) {
107+
handlePageGatewayEvent(state, {
108+
event: "chat",
109+
payload: { state: "delta", runId: "run-1", sessionKey: "main", deltaText },
110+
});
111+
}
112+
113+
expect(state.chatStream).toBe("ABC");
114+
expect(requestUpdate).not.toHaveBeenCalled();
115+
scheduledFrame?.(0);
116+
expect(requestUpdate).toHaveBeenCalledOnce();
117+
});
118+
48119
it("requests a render before selecting the commit promise", async () => {
49120
let resolveCommit: (value: boolean) => void = () => {};
50121
const nextCommit = new Promise<boolean>((resolve) => {

‎ui/src/pages/chat/chat-state.ts‎

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,7 @@ export type ChatPageHost = ChatHost &
234234
chatInputHistoryIndex: number;
235235
chatDraftBeforeHistory: string | null;
236236
chatScrollCommitCleanup: (() => void) | null;
237+
chatStreamRenderFrame: number | null;
237238
chatScrollFrame: number | null;
238239
chatScrollGuardFrame: number | null;
239240
chatScrollTimeout: number | null;
@@ -454,6 +455,7 @@ export function resetChatStateForRouteSession(
454455
previousComposerScope?: StoredChatOutboxScope;
455456
} = {},
456457
): ChatComposerRouteResetResult {
458+
cancelChatStreamRenderFrame(state);
457459
const previousSessionKey = state.sessionKey;
458460
const previousComposerScopeKey = storedChatOutboxScopeKey(
459461
options.previousComposerScope ?? resolveStoredChatOutboxScope(state, previousSessionKey),
@@ -1263,6 +1265,7 @@ export function createPageState(
12631265
chatInputHistoryIndex: -1,
12641266
chatDraftBeforeHistory: null,
12651267
chatScrollCommitCleanup: null,
1268+
chatStreamRenderFrame: null,
12661269
chatScrollFrame: null,
12671270
chatScrollGuardFrame: null,
12681271
chatScrollTimeout: null,
@@ -1387,23 +1390,23 @@ export function handlePageGatewayEvent(state: ChatPageHost, event: GatewayEventF
13871390
removeDeliveredQueuedChatSendForRun(state, payload?.runId);
13881391
void resumeStoredChatOutboxes(state);
13891392
}
1390-
requestPageUpdate(state);
1393+
requestChatPageUpdate(state, payload?.state === "delta" ? "animation-frame" : "immediate");
13911394
return;
13921395
}
13931396
if (event.event === "chat.side_result") {
13941397
if (handleChatSideResultGatewayEvent(state as unknown as ChatState, event.payload)) {
1395-
requestPageUpdate(state);
1398+
requestChatPageUpdate(state);
13961399
}
13971400
return;
13981401
}
13991402
if (event.event === "agent" || event.event === "session.tool") {
14001403
handleAgentEvent(state as never, event.payload as never);
1401-
requestPageUpdate(state);
1404+
requestChatPageUpdate(state);
14021405
return;
14031406
}
14041407
if (event.event === "session.operation") {
14051408
handleSessionOperationEvent(state as never, event.payload as never);
1406-
requestPageUpdate(state);
1409+
requestChatPageUpdate(state);
14071410
return;
14081411
}
14091412
if (event.event === "chat.send_timing") {
@@ -1413,13 +1416,13 @@ export function handlePageGatewayEvent(state: ChatPageHost, event: GatewayEventF
14131416
if (event.event === "session.message") {
14141417
handleSessionMessageEvent(state, event.payload);
14151418
void resumeStoredChatOutboxes(state);
1416-
requestPageUpdate(state);
1419+
requestChatPageUpdate(state);
14171420
return;
14181421
}
14191422
if (event.event === "sessions.changed") {
14201423
handleSessionsChangedEvent(state, event.payload);
14211424
void resumeStoredChatOutboxes(state);
1422-
requestPageUpdate(state);
1425+
requestChatPageUpdate(state);
14231426
return;
14241427
}
14251428
if (event.event === "task") {
@@ -1518,8 +1521,42 @@ function preserveDeliveredQueuedUserTurn(state: ChatPageHost, item: ChatQueueIte
15181521
}
15191522
}
15201523

1521-
function requestPageUpdate(state: ChatPageHost) {
1522-
state.requestUpdate?.();
1524+
type ChatPageUpdateMode = "immediate" | "animation-frame";
1525+
1526+
function cancelChatStreamRenderFrame(state: Pick<ChatPageHost, "chatStreamRenderFrame">): void {
1527+
const frame = state.chatStreamRenderFrame;
1528+
if (frame == null) {
1529+
return;
1530+
}
1531+
state.chatStreamRenderFrame = null;
1532+
if (typeof globalThis.cancelAnimationFrame === "function") {
1533+
globalThis.cancelAnimationFrame(frame);
1534+
}
1535+
}
1536+
1537+
export function requestChatPageUpdate(
1538+
state: Pick<ChatPageHost, "chatStreamRenderFrame" | "requestUpdate">,
1539+
mode: ChatPageUpdateMode = "immediate",
1540+
): void {
1541+
if (mode === "immediate" || typeof globalThis.requestAnimationFrame !== "function") {
1542+
cancelChatStreamRenderFrame(state);
1543+
state.requestUpdate?.();
1544+
return;
1545+
}
1546+
if (state.chatStreamRenderFrame != null) {
1547+
return;
1548+
}
1549+
// Deltas still mutate the canonical stream immediately. One frame owns the
1550+
// paint; terminal/non-stream events cancel it so stale partial UI cannot win.
1551+
let frame = 0;
1552+
frame = globalThis.requestAnimationFrame(() => {
1553+
if (state.chatStreamRenderFrame !== frame) {
1554+
return;
1555+
}
1556+
state.chatStreamRenderFrame = null;
1557+
state.requestUpdate?.();
1558+
});
1559+
state.chatStreamRenderFrame = frame;
15231560
}
15241561

15251562
type ChatRenderLifecycleScope = {
@@ -1578,6 +1615,7 @@ export class ChatStateController<TState extends ChatPageHost> implements Reactiv
15781615
attach(state: TState) {
15791616
if (this.stateValue && this.stateValue !== state) {
15801617
this.composerPersistence.stop();
1618+
cancelChatStreamRenderFrame(this.stateValue);
15811619
cancelChatScroll(this.stateValue);
15821620
}
15831621
this.stateValue = state;
@@ -1859,6 +1897,7 @@ export class ChatStateController<TState extends ChatPageHost> implements Reactiv
18591897
}
18601898
const state = this.stateValue;
18611899
if (state) {
1900+
cancelChatStreamRenderFrame(state);
18621901
cancelChatScroll(state);
18631902
clearSessionWorkspaceTimers(state);
18641903
}

‎ui/src/pages/chat/chat-thread.test.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2258,7 +2258,7 @@ describe("tool expansion state", () => {
22582258
});
22592259

22602260
describe("thread item cache", () => {
2261-
it("reuses transcript items when thread inputs keep the same references", () => {
2261+
it("preserves stable transcript rows while the live stream changes", () => {
22622262
resetChatThreadState();
22632263
const messages = [{ role: "assistant", content: "ready" }];
22642264
const toolMessages: unknown[] = [];
@@ -2268,7 +2268,22 @@ describe("thread item cache", () => {
22682268

22692269
const first = buildCachedChatItems(input);
22702270
expect(buildCachedChatItems({ ...input })).toBe(first);
2271-
expect(buildCachedChatItems({ ...input, messages: [...messages] })).not.toBe(first);
2271+
expect(buildCachedChatItems({ ...input, messages: [...messages] })).toBe(first);
2272+
2273+
const streaming = buildCachedChatItems({
2274+
...input,
2275+
stream: "partial reply",
2276+
streamStartedAt: 10,
2277+
});
2278+
expect(streaming).not.toBe(first);
2279+
expect(streaming.find((item) => item.key === first[0]?.key)).toBe(first[0]);
2280+
2281+
expect(
2282+
buildCachedChatItems({
2283+
...input,
2284+
messages: [{ role: "assistant", content: "changed" }],
2285+
}),
2286+
).not.toBe(first);
22722287
});
22732288
});
22742289

‎ui/src/pages/chat/chat-thread.ts‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1595,6 +1595,80 @@ export function buildChatItems(props: BuildChatItemsProps): Array<ChatItem | Mes
15951595
);
15961596
}
15971597

1598+
function sameMessageGroup(previous: MessageGroup, next: MessageGroup): boolean {
1599+
// Source message identity owns the row timestamp too: normalization supplies
1600+
// Date.now() for missing timestamps, which must not churn stable rows.
1601+
return (
1602+
previous.role === next.role &&
1603+
previous.senderLabel === next.senderLabel &&
1604+
previous.isStreaming === next.isStreaming &&
1605+
previous.turnSucceeded === next.turnSucceeded &&
1606+
previous.messages.length === next.messages.length &&
1607+
previous.messages.every((entry, index) => {
1608+
const candidate = next.messages[index];
1609+
return (
1610+
candidate !== undefined &&
1611+
entry.key === candidate.key &&
1612+
entry.message === candidate.message &&
1613+
entry.duplicateCount === candidate.duplicateCount
1614+
);
1615+
})
1616+
);
1617+
}
1618+
1619+
function sameChatItem(previous: RenderChatItem, next: RenderChatItem): boolean {
1620+
if (previous.kind !== next.kind || previous.key !== next.key) {
1621+
return false;
1622+
}
1623+
switch (next.kind) {
1624+
case "group":
1625+
return previous.kind === "group" && sameMessageGroup(previous, next);
1626+
case "message":
1627+
return (
1628+
previous.kind === "message" &&
1629+
previous.message === next.message &&
1630+
previous.duplicateCount === next.duplicateCount
1631+
);
1632+
case "divider":
1633+
return (
1634+
previous.kind === "divider" &&
1635+
previous.label === next.label &&
1636+
previous.description === next.description &&
1637+
previous.timestamp === next.timestamp &&
1638+
previous.action?.kind === next.action?.kind &&
1639+
previous.action?.label === next.action?.label
1640+
);
1641+
case "stream":
1642+
return (
1643+
previous.kind === "stream" &&
1644+
previous.text === next.text &&
1645+
previous.startedAt === next.startedAt &&
1646+
previous.isStreaming === next.isStreaming
1647+
);
1648+
case "reading-indicator":
1649+
return previous.kind === "reading-indicator";
1650+
}
1651+
return false;
1652+
}
1653+
1654+
function stabilizeChatItems(
1655+
previous: ReturnType<typeof buildChatItems>,
1656+
next: ReturnType<typeof buildChatItems>,
1657+
): ReturnType<typeof buildChatItems> {
1658+
if (previous.length === 0 || next.length === 0) {
1659+
return next;
1660+
}
1661+
const previousByKey = new Map(previous.map((item) => [`${item.kind}\u0000${item.key}`, item]));
1662+
const stabilized = next.map((item) => {
1663+
const prior = previousByKey.get(`${item.kind}\u0000${item.key}`);
1664+
return prior && sameChatItem(prior, item) ? prior : item;
1665+
});
1666+
return stabilized.length === previous.length &&
1667+
stabilized.every((item, index) => item === previous[index])
1668+
? previous
1669+
: stabilized;
1670+
}
1671+
15981672
function sameChatItemsInput(previous: BuildChatItemsProps, next: BuildChatItemsProps): boolean {
15991673
return (
16001674
previous.sessionKey === next.sessionKey &&
@@ -1625,7 +1699,7 @@ export function buildCachedChatItems(
16251699
if (cached.input && sameChatItemsInput(cached.input, input)) {
16261700
return cached.items;
16271701
}
1628-
const items = buildChatItems(input);
1702+
const items = stabilizeChatItems(cached.items, buildChatItems(input));
16291703
cached.input = input;
16301704
cached.items = items;
16311705
return items;

0 commit comments

Comments
 (0)