TypeScript
perf(web): streamed assistant text re-renders only its own row (#27419)
Julius Marminge3cbc98241d33
diff --git a/apps/web/src/components/chat/ThreadTimeline.tsx b/apps/web/src/components/chat/ThreadTimeline.tsxindex 7d1db86178c..a68d494d8b0 100644--- a/apps/web/src/components/chat/ThreadTimeline.tsx+++ b/apps/web/src/components/chat/ThreadTimeline.tsx@@ -2,7 +2,7 @@ import type { ScopedThreadRef } from "@t3tools/contracts";import { type ComponentProps, useLayoutEffect } from "react";import { useIncrementalTimelineEntries } from "../../hooks/useIncrementalTimelineEntries";import type { TimelineEntriesInput, TimelineEntry } from "../../session-logic";-import { useThreadVisibleTurnItems } from "../../state/entities";+import { useTimelineVisibleTurnItems } from "../../state/entities";import {peekRememberedThreadTimeline,rememberReadyThreadTimeline,@@ -14,7 +14,8 @@ import { MessagesTimeline } from "./MessagesTimeline";/*** The timeline with the streamed text. ChatView reads the thread through its quiet* atoms, which hold through text deltas; this reads the live turn items, so a- * delta re-renders the timeline without re-rendering ChatView.+ * reasoning delta re-renders the timeline without re-rendering ChatView. Streamed+ * assistant text reaches only its own row, through useAssistantMessageText.*/export function ThreadTimeline({threadDetailRef,@@ -34,7 +35,7 @@ export function ThreadTimeline({syncing: boolean;detailLoading: boolean;}) {- const visibleTurnItems = useThreadVisibleTurnItems(threadDetailRef);+ const visibleTurnItems = useTimelineVisibleTurnItems(threadDetailRef);const serverEntries = useIncrementalTimelineEntries(activeThreadKey, {...entriesInput,visibleTurnItems,diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsxindex 228eb6f79b9..458d84b9e98 100644--- a/apps/web/src/components/chat/TimelineAssistantRows.tsx+++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx@@ -12,7 +12,7 @@ import { McpAppFrame } from "./McpAppFrame";import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints";import { ChangedFilesCard } from "./ChangedFilesTree";import { useFileContextMenuHandler } from "../../fileContextMenu";-import { useProject, useThreadShell } from "../../state/entities";+import { useAssistantMessageText, useProject, useThreadShell } from "../../state/entities";import { MessageCopyButton } from "./MessageCopyButton";import { AssistantCitationSource } from "./AssistantCitationSource";import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic";@@ -26,7 +26,13 @@ import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {const ctx = use(TimelineRowCtx);- const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");+ // The timeline holds a streaming message's row while only its text grows.+ const liveText = useAssistantMessageText(+ row.message.streaming ? ctx.threadRef : null,+ row.projectedItem?.item.id,+ );+ const text = liveText ?? row.message.text;+ const messageText = text || (row.message.streaming ? "" : "(empty response)");return (<>diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.tsindex 54b367df15b..0f94280768d 100644--- a/apps/web/src/state/entities.ts+++ b/apps/web/src/state/entities.ts@@ -65,6 +65,9 @@ const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe(const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>(Object.freeze([]),).pipe(Atom.withLabel("web-thread-checkpoint-summaries:empty"));+const EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM = Atom.make<string | null>(null).pipe(+ Atom.withLabel("web-assistant-message-text:empty"),+);const EMPTY_LAST_VISITED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(Atom.withLabel("web-thread-last-visited:empty"),);@@ -212,6 +215,29 @@ export function useThreadVisibleTurnItems();}+/** Visible turn items held through streamed assistant text; see useAssistantMessageText. */+export function useTimelineVisibleTurnItems(+ ref: ScopedThreadRef | null,+): ReadonlyArray<OrchestrationV2ProjectedTurnItem> {+ return useAtomValue(+ ref === null+ ? EMPTY_VISIBLE_TURN_ITEMS_ATOM+ : environmentThreadDetails.timelineVisibleTurnItemsAtom(ref),+ );+}++/** One assistant message's live text, or null when the thread does not hold the item. */+export function useAssistantMessageText(+ ref: ScopedThreadRef | null,+ itemId: string | undefined,+): string | null {+ return useAtomValue(+ ref === null || itemId === undefined+ ? EMPTY_ASSISTANT_MESSAGE_TEXT_ATOM+ : environmentThreadDetails.assistantMessageTextAtom(ref, itemId),+ );+}+/** Visible turn items without their streamed text; see ThreadStructure. */export function useQuietThreadVisibleTurnItems(ref: ScopedThreadRef | null,diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsxindex 5bb6836dd04..459f3b9791d 100644--- a/apps/web/test/appScenarios.renders.tsx+++ b/apps/web/test/appScenarios.renders.tsx@@ -201,7 +201,9 @@ it("app-stream-assistant-turn", async () => {.element(page.getByText(`word${STREAM_DELTAS - 1}`, { exact: false })).toBeVisible();});- // Only the streaming row changes; history rows must not re-render with it.+ // Only the streaming row changes. The timeline renders for the new item and its layout, not+ // per delta, and history rows not at all.+ expect(counted.components.ConversationTimeline).toBeLessThanOrEqual(3);expect(counted.components.UserTimelineRow).toBeUndefined();expect(counted.components.AssistantTimelineRow).toBe(STREAM_DELTAS);// Each delta adds a paragraph; finished blocks keep their render.diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.tsindex 8fc01839183..3e66202d0bb 100644--- a/packages/client-runtime/src/state/threadDetail.test.ts+++ b/packages/client-runtime/src/state/threadDetail.test.ts@@ -197,6 +197,42 @@ describe("quietThreadAtom", () => {});});+describe("timelineVisibleTurnItemsAtom", () => {+ const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };++ it("holds through streamed assistant text while the message reads its own text", () => {+ const stateAtom = Atom.make(+ AsyncResult.success({+ ...EMPTY_ENVIRONMENT_THREAD_STATE,+ data: Option.some<OrchestrationV2ThreadProjection>(withItem(assistant)),+ }),+ );+ const details = createEnvironmentThreadDetailAtoms(() => stateAtom);+ const timelineAtom = details.timelineVisibleTurnItemsAtom(ref);+ const textAtom = details.assistantMessageTextAtom(ref, assistant.id);+ const registry = AtomRegistry.make();+ registry.mount(timelineAtom);+ registry.mount(textAtom);+ const push = (item: OrchestrationV2TurnItem) =>+ registry.set(+ stateAtom,+ AsyncResult.success({+ ...EMPTY_ENVIRONMENT_THREAD_STATE,+ data: Option.some(withItem(item, later)),+ }),+ );+ const first = registry.get(timelineAtom);++ push({ ...assistant, text: "Hello", updatedAt: later });+ expect(registry.get(timelineAtom)).toBe(first);+ expect(registry.get(textAtom)).toBe("Hello");++ push({ ...assistant, text: "Hello", streaming: false, status: "completed" });+ expect(registry.get(timelineAtom)[0]?.item).toMatchObject({ text: "Hello", streaming: false });+ registry.dispose();+ });+});+it("only compares replaced entries in a streamed reducer delta", () => {const size = 100;let slotReads = 0;diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.tsindex 3819c5d92ba..eeeda6a2f34 100644--- a/packages/client-runtime/src/state/threadDetail.ts+++ b/packages/client-runtime/src/state/threadDetail.ts@@ -148,6 +148,26 @@ function sameVisibleTurnItemStructure(before: VisibleTurnItem, after: VisibleTur);}+function isStreamingAssistantMessage(visibleItem: VisibleTurnItem): boolean {+ return visibleItem.item.type === "assistant_message" && visibleItem.item.streaming;+}++/** Whether `next` only streams more text into assistant messages that were already streaming. */+function sameApartFromStreamedAssistantText(+ previous: OrchestrationV2ThreadProjection["visibleTurnItems"],+ next: OrchestrationV2ThreadProjection["visibleTurnItems"],+): boolean {+ return sameProjectionArray(+ previous,+ next,+ (before, after) =>+ before === after ||+ (isStreamingAssistantMessage(before) &&+ isStreamingAssistantMessage(after) &&+ sameVisibleTurnItemStructure(before, after)),+ );+}+/*** Whether `previous` and `next` have the same ThreadStructure: they differ* only by text streamed into existing assistant and reasoning items or by a@@ -267,6 +287,32 @@ export function createEnvironmentThreadDetailAtoms<E>();});+ // Holds while only streamed assistant text moves, so the timeline re-renders on structure;+ // each streaming message reads its text through assistantMessageTextAtom.+ const timelineVisibleTurnItemsAtomFamily = Atom.family((key: string) => {+ let previous = EMPTY_VISIBLE_TURN_ITEMS;+ return Atom.make((get) => {+ const next = get(visibleTurnItemsAtomFamily(key));+ if (!sameApartFromStreamedAssistantText(previous, next)) previous = next;+ return previous;+ }).pipe(+ Atom.setIdleTTL(0),+ Atom.withLabel(`environment-thread-timeline-visible-turn-items:${key}`),+ );+ });++ const assistantMessageTextAtomFamily = Atom.family((key: string) => {+ const separator = key.lastIndexOf("\u0000");+ const thread = key.slice(0, separator);+ const itemId = key.slice(separator + 1);+ return Atom.make((get) => {+ const item = get(visibleTurnItemsAtomFamily(thread)).find(+ (visibleItem) => visibleItem.item.id === itemId,+ )?.item;+ return item?.type === "assistant_message" ? item.text : null;+ }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-assistant-message-text:${key}`));+ });+const queueWorkflowAtomFamily = Atom.family((key: string) => {let previous: Pick<OrchestrationV2ThreadProjection,@@ -472,6 +518,10 @@ export function createEnvironmentThreadDetailAtoms<E>(visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),quietVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>quietVisibleTurnItemsAtomFamily(threadKey(ref)),+ timelineVisibleTurnItemsAtom: (ref: ScopedThreadRef) =>+ timelineVisibleTurnItemsAtomFamily(threadKey(ref)),+ assistantMessageTextAtom: (ref: ScopedThreadRef, itemId: string) =>+ assistantMessageTextAtomFamily(`${threadKey(ref)}\u0000${itemId}`),statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)),sequenceAtom: (ref: ScopedThreadRef) => sequenceAtomFamily(threadKey(ref)),errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)),