Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

perf(chat): stop a streaming turn re-deriving what has not changed

Bingxi Zhao (Frank)edb779c1b007
diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsx
index a7ee54d5e..6d1f9b5b7 100644
--- a/web/features/chat/messages/ChatMessageList.tsx
+++ b/web/features/chat/messages/ChatMessageList.tsx
@@ -127,6 +127,7 @@ const VisualizationViewer = dynamic(
{ ssr: false },
);
+
interface ChatMessageItem {
id?: number;
role: "user" | "assistant" | "system";
@@ -165,6 +166,110 @@ const MODE_BADGE_LABELS: Record<string, string> = {
// A capability with no entry is title-cased rather than printed raw: an
// unlisted mode used to surface its internal id ("immersive_reading") in the
// conversation, which reads as a bug to everyone who sees it.
+/**
+ * What a run of working-out actually contains, for the memo below.
+ *
+ * Prose is identified by its length rather than its text because a streamed
+ * segment only ever grows; a run of steps by how many events it holds.
+ *
+ * ``settled`` says a turn has moved on to writing its answer, and then only
+ * the shape matters. The region a turn is working in stays open in the event
+ * stream and keeps absorbing everything that arrives, so a finished run of
+ * steps went on counting the answer's own deltas — 3300 events for a trace
+ * drawing two rows — and reported itself as changed on every one of them.
+ * Nothing below the answer can alter the working-out above it: a new round
+ * would take the answer back into the process, which moves the shape.
+ */
+function processContentKey(
+ segments: MessageSegment[],
+ settled: boolean,
+): string {
+ return segments
+ .map((seg) =>
+ settled
+ ? seg.key
+ : seg.kind === "text"
+ ? `t${seg.key}:${seg.text.length}`
+ : seg.kind === "trace"
+ ? `r${seg.key}:${seg.events.length}`
+ : seg.key,
+ )
+ .join("|");
+}
+
+/**
+ * Prose and the steps it introduced, in the order they were written.
+ *
+ * Spacing is owned here rather than left to each piece. Markdown carries a
+ * bottom margin and the trace rows carried only a top one, so a row sat 24px
+ * below the sentence that introduced it and flush against the one that
+ * followed — reading as a heading for the next paragraph instead of as the
+ * step between them. Both margins are stripped and one gap governs the whole
+ * column, so the rhythm is even whichever way you read it.
+ *
+ * Memoized on what it holds rather than on the props it is handed.
+ * ``messageSegments`` is rebuilt from scratch on every streamed delta, so the
+ * working-out — which stops changing the moment a turn starts writing its
+ * answer — arrived as a brand-new element tree on every frame of that answer.
+ * React cannot skip a subtree whose elements it has never seen, so the whole
+ * trace re-rendered for the answer's full length: profiled over one 35s turn,
+ * 2905 renders costing 10.3s, none of which changed a pixel.
+ *
+ * ``events`` is deliberately left out of the comparison. It is read only to
+ * verify reading-material locators, and anything that could verify one is a
+ * tool call — which lands in a run of steps and moves the key on its own.
+ */
+const ProcessBody = memo(
+ function ProcessBody({
+ segments,
+ events,
+ language,
+ isStreaming,
+ readingMaterialId,
+ readingMaterialRevision,
+ }: {
+ segments: MessageSegment[];
+ events: StreamEvent[];
+ /** The turn has moved on to its answer, so this run is finished. */
+ settled: boolean;
+ language?: string;
+ isStreaming?: boolean;
+ readingMaterialId?: string;
+ readingMaterialRevision?: number;
+ }) {
+ return (
+ <div className="flex flex-col gap-3 border-l border-[var(--border)] pl-3.5">
+ {segments.map((seg) =>
+ seg.kind === "text" ? (
+ <div key={seg.key} className="[&_.md-renderer>*:last-child]:mb-0">
+ <AssistantResponse
+ content={seg.text}
+ language={language}
+ isStreaming={isStreaming}
+ readingMaterialId={readingMaterialId}
+ readingMaterialRevision={readingMaterialRevision}
+ events={events}
+ />
+ </div>
+ ) : seg.kind === "trace" ? (
+ <div key={seg.key} className="[&>div]:mb-0">
+ <TraceFlow events={seg.events} isStreaming={isStreaming} />
+ </div>
+ ) : null,
+ )}
+ </div>
+ );
+ },
+ (a, b) =>
+ a.language === b.language &&
+ a.isStreaming === b.isStreaming &&
+ a.settled === b.settled &&
+ a.readingMaterialId === b.readingMaterialId &&
+ a.readingMaterialRevision === b.readingMaterialRevision &&
+ processContentKey(a.segments, a.settled) ===
+ processContentKey(b.segments, b.settled),
+);
+
/**
* A run of working-out that folds itself away.
*
@@ -496,7 +601,9 @@ export const AssistantMessage = memo(function AssistantMessage({
sessionId?: string | null;
language?: string;
researchRequestSnapshot?: MessageRequestSnapshot | null;
- onTraceToggle?: (open: boolean) => void;
+ /** Notified when a persisted trace is opened or collapsed. Takes the id so
+ * the list can hand one callback to every row — see ``handleTraceToggle``. */
+ onTraceToggle?: (messageId: number, open: boolean) => void;
onConfirmOutline?: (
outline: Array<{ title: string; overview: string }>,
topic: string,
@@ -763,9 +870,14 @@ export const AssistantMessage = memo(function AssistantMessage({
while (idx > 0 && messageSegments[idx - 1].kind === "text") idx -= 1;
return idx;
}, [messageSegments]);
- // Separately: whether the working-out folds itself away. This is the one
- // thing that does need the terminal-round signal, since it is the claim
- // that there is no more work coming.
+ // A turn that has started writing its answer is no longer changing the
+ // working-out above it, which is what lets that whole subtree stop
+ // re-deriving itself on every delta. Structural, like the boundary: if a new
+ // round starts, the answer goes back into the process and this goes false.
+ const processSettled = answerStart < messageSegments.length;
+ // Separately again: whether the working-out folds itself away. This is the
+ // one thing that does need the terminal-round signal, since it is the claim
+ // that there is no more work coming at all.
const settledIntoAnswer = !isStreaming || hasSettledFinalRound(events);
// Cards are not process: a question the reader was asked (and answered) is
// part of the exchange, not working-out to be folded away. So they break
@@ -786,41 +898,17 @@ export const AssistantMessage = memo(function AssistantMessage({
: null;
const bodyBlocks = headerProcess ? messageBlocks.slice(1) : messageBlocks;
- /**
- * Prose and the steps it introduced, in the order they were written.
- *
- * Spacing is owned here rather than left to each piece. Markdown carries a
- * bottom margin and the trace rows carried only a top one, so a row sat 24px
- * below the sentence that introduced it and flush against the one that
- * followed — reading as a heading for the next paragraph instead of as the
- * step between them. Both margins are stripped and one gap governs the
- * whole column, so the rhythm is even whichever way you read it.
- */
const renderSegments = useCallback(
(segments: MessageSegment[]) => (
- <div className="flex flex-col gap-3 border-l border-[var(--border)] pl-3.5">
- {segments.map((seg) =>
- seg.kind === "text" ? (
- <div
- key={seg.key}
- className="[&_.md-renderer>*:last-child]:mb-0"
- >
- <AssistantResponse
- content={seg.text}
- language={language}
- isStreaming={isStreaming}
- readingMaterialId={readingMaterialId}
- readingMaterialRevision={readingMaterialRevision}
- events={events}
- />
- </div>
- ) : seg.kind === "trace" ? (
- <div key={seg.key} className="[&>div]:mb-0">
- <TraceFlow events={seg.events} isStreaming={isStreaming} />
- </div>
- ) : null,
- )}
- </div>
+ <ProcessBody
+ segments={segments}
+ events={events}
+ settled={processSettled}
+ language={language}
+ isStreaming={isStreaming}
+ readingMaterialId={readingMaterialId}
+ readingMaterialRevision={readingMaterialRevision}
+ />
),
[
language,
@@ -828,6 +916,7 @@ export const AssistantMessage = memo(function AssistantMessage({
readingMaterialId,
readingMaterialRevision,
events,
+ processSettled,
],
);
const headerProcessSummary = useMemo(() => {
@@ -871,7 +960,7 @@ export const AssistantMessage = memo(function AssistantMessage({
className="mb-3"
onTraceToggle={
msg.id != null && msg.trace?.turn_id
- ? (open) => onTraceToggle?.(open)
+ ? (open) => onTraceToggle?.(msg.id as number, open)
: undefined
}
// The turn's working-out, folded behind this same header. One line of
@@ -1790,6 +1879,21 @@ export const ChatMessageList = memo(function ChatMessageList({
//
// The followup is dropped from the visible row list so only the
// merged bubble renders.
+ // One callback for every row rather than a closure per row per render.
+ // ``AssistantMessage`` is memoized, and a fresh function defeats that
+ // outright: every message in the conversation re-rendered on every streamed
+ // delta of the turn at the bottom.
+ const handleTraceToggle = useCallback(
+ (messageId: number, open: boolean) => {
+ if (open) {
+ void onLoadMessageTrace?.(messageId);
+ } else {
+ onReleaseMessageTrace?.(messageId);
+ }
+ },
+ [onLoadMessageTrace, onReleaseMessageTrace],
+ );
+
const deepResearchMergeMap = useMemo(() => {
const map = new Map<
number,
@@ -2025,14 +2129,7 @@ export const ChatMessageList = memo(function ChatMessageList({
researchRequestSnapshot={
pairedUserMessage?.requestSnapshot ?? null
}
- onTraceToggle={(open) => {
- if (msg.id == null) return;
- if (open) {
- void onLoadMessageTrace?.(msg.id);
- } else {
- onReleaseMessageTrace?.(msg.id);
- }
- }}
+ onTraceToggle={handleTraceToggle}
masteryGrades={masteryGrades}
masterySkips={masterySkips}
/>
diff --git a/web/hooks/useSmoothStreamText.ts b/web/hooks/useSmoothStreamText.ts
index 3b305d8ec..322e588dd 100644
--- a/web/hooks/useSmoothStreamText.ts
+++ b/web/hooks/useSmoothStreamText.ts
@@ -15,6 +15,25 @@ interface SmoothStreamOptions {
minCharsPerFrame?: number;
/** Larger = slower reveal relative to backlog. ~5 feels natural. */
catchUpDivisor?: number;
+ /**
+ * Characters of message per millisecond of enforced gap between reveals.
+ *
+ * Every reveal re-renders the consumer, and a markdown consumer re-parses
+ * the *entire* document when it does — so a turn costs (reveals × length).
+ * Revealing on every frame therefore makes a long answer quadratic in its
+ * own length, which is the exact shape of "it streams fine at first and
+ * gets choppier the longer it runs".
+ *
+ * The cap cannot be expressed in characters: a model that sends three
+ * characters at a time sets the pace, and there is no text to reveal ahead
+ * of it. So the gap is in time. At this default a 1KB reply still reveals on
+ * every frame, a 5KB one drops to 20fps and a 12KB one to the cap — all of
+ * which still read as continuous text arriving, because what the eye follows
+ * here is words appearing, not motion.
+ */
+ revealGapCharsPerMs?: number;
+ /** Longest gap the rate cap will impose, however long the message runs. */
+ maxRevealGapMs?: number;
/**
* When ``false``, the hook is a pass-through: the smoother is disabled
* and ``displayContent`` always equals ``content``. Useful so callers
@@ -23,6 +42,45 @@ interface SmoothStreamOptions {
enabled?: boolean;
}
+/**
+ * How many characters the next reveal advances by.
+ *
+ * Pure, and exported, because the pacing is the whole behaviour of this hook
+ * and is the part worth pinning down without a renderer.
+ */
+export function revealStep(
+ current: number,
+ target: number,
+ {
+ maxCharsPerFrame = 120,
+ minCharsPerFrame = 2,
+ catchUpDivisor = 5,
+ }: SmoothStreamOptions = {},
+): number {
+ const backlog = target - current;
+ if (backlog <= 0) return 0;
+ return Math.min(
+ maxCharsPerFrame,
+ Math.max(minCharsPerFrame, Math.ceil(backlog / catchUpDivisor)),
+ );
+}
+
+/**
+ * The shortest time allowed between two reveals of a message this long.
+ *
+ * Zero for anything short enough that re-parsing it is free; rising with
+ * length so the work per second stays flat instead of growing with the
+ * answer. See ``revealGapCharsPerMs``.
+ */
+export function revealGapMs(
+ length: number,
+ { revealGapCharsPerMs = 100, maxRevealGapMs = 120 }: SmoothStreamOptions = {},
+): number {
+ const gap = Math.floor(length / revealGapCharsPerMs);
+ // Below a frame it is not a cap at all — rAF is already the floor.
+ return gap <= 16 ? 0 : Math.min(maxRevealGapMs, gap);
+}
+
/**
* Decouples the visible markdown growth rate from the WebSocket delta
* cadence so the user perceives smooth, "typewriter"-style streaming
@@ -32,6 +90,8 @@ interface SmoothStreamOptions {
* - While ``isStreaming`` is true and the incoming ``content`` is
* longer than what we've shown, a single ``requestAnimationFrame``
* loop advances the cursor towards ``content.length``.
+ * - Frames are skipped once the message is long enough that re-rendering it
+ * on every one costs more than it shows — see ``revealGapCharsPerMs``.
* - When ``isStreaming`` flips false, we snap to the full ``content``
* on the next frame so the finished message lands instantly. This
* also handles short messages where the smoother would otherwise
@@ -53,12 +113,17 @@ export function useSmoothStreamText(
maxCharsPerFrame = 120,
minCharsPerFrame = 2,
catchUpDivisor = 5,
+ revealGapCharsPerMs = 100,
+ maxRevealGapMs = 120,
enabled = true,
} = options;
const [shown, setShown] = useState<string>(content);
const shownLenRef = useRef<number>(content.length);
const rafRef = useRef<number>(0);
+ // Survives the cancel/re-arm that every delta puts the rAF chain through,
+ // so the rate cap is a property of the message rather than of one chain.
+ const lastRevealRef = useRef<number>(0);
useEffect(() => {
if (!enabled) {
@@ -97,18 +162,26 @@ export function useSmoothStreamText(
return;
}
- const step = () => {
+ const step = (now: number) => {
rafRef.current = 0;
const target = content.length;
const current = shownLenRef.current;
if (current >= target) return;
- const backlog = target - current;
- const advance = Math.min(
+ const gap = revealGapMs(target, { revealGapCharsPerMs, maxRevealGapMs });
+ if (gap > 0 && now - lastRevealRef.current < gap) {
+ // Too soon to pay for another full re-parse. Keep waiting rather than
+ // rendering; the text arriving meanwhile rides on the next reveal.
+ rafRef.current = requestAnimationFrame(step);
+ return;
+ }
+ const advance = revealStep(current, target, {
maxCharsPerFrame,
- Math.max(minCharsPerFrame, Math.ceil(backlog / catchUpDivisor)),
- );
+ minCharsPerFrame,
+ catchUpDivisor,
+ });
const next = Math.min(target, current + advance);
shownLenRef.current = next;
+ lastRevealRef.current = now;
setShown(content.slice(0, next));
if (next < target) {
rafRef.current = requestAnimationFrame(step);
@@ -135,6 +208,8 @@ export function useSmoothStreamText(
maxCharsPerFrame,
minCharsPerFrame,
catchUpDivisor,
+ revealGapCharsPerMs,
+ maxRevealGapMs,
]);
return shown;
diff --git a/web/tests/smooth-stream.test.ts b/web/tests/smooth-stream.test.ts
new file mode 100644
index 000000000..d8b736439
--- /dev/null
+++ b/web/tests/smooth-stream.test.ts
@@ -0,0 +1,93 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { revealGapMs, revealStep } from "../hooks/useSmoothStreamText";
+
+/**
+ * Runs a whole message through the pacing at 60fps and counts the reveals.
+ *
+ * Each reveal is one re-render of the consumer, and a markdown consumer
+ * re-parses the entire document on each — so this count, times the length, is
+ * what a turn actually costs.
+ */
+function costOf(
+ length: number,
+ charsPerFrame: number,
+ { paced = true } = {},
+): { reveals: number; charsParsed: number } {
+ let shown = 0;
+ let arrived = 0;
+ let reveals = 0;
+ let charsParsed = 0;
+ let lastReveal = -Infinity;
+ for (let frame = 0; shown < length && frame < 200_000; frame += 1) {
+ const now = frame * 16.7;
+ arrived = Math.min(length, arrived + charsPerFrame);
+ if (paced && now - lastReveal < revealGapMs(arrived)) continue;
+ const step = revealStep(shown, arrived);
+ if (step === 0) continue;
+ shown = Math.min(arrived, shown + step);
+ lastReveal = now;
+ reveals += 1;
+ // One re-parse of everything revealed so far.
+ charsParsed += shown;
+ }
+ return { reveals, charsParsed };
+}
+
+test("a short reply still types out character by character", () => {
+ // The typewriter is the point at this size, and re-parsing a page of text
+ // is free, so nothing is paced away.
+ assert.equal(revealGapMs(200), 0);
+ assert.equal(revealGapMs(1000), 0);
+ // A couple of characters on the wire reveals a couple of characters; a
+ // bigger backlog is caught up at a fifth of it per frame.
+ assert.equal(revealStep(198, 200), 2);
+ assert.equal(revealStep(100, 140), 8);
+});
+
+test("a long reply stops re-parsing itself on every frame", () => {
+ // Re-rendering is what costs, and the cost of one render grows with the
+ // answer — so the rate has to fall as the answer grows or the turn is
+ // quadratic in its own length.
+ assert.equal(revealGapMs(5000), 50); // 20fps
+ assert.equal(revealGapMs(12000), 120); // the cap
+ assert.equal(revealGapMs(40000), 120); // still the cap
+});
+
+test("a long answer stops paying for its own length twice", () => {
+ // Three characters a frame is about what a model streams, and at that pace
+ // the reveal count used to track arrival exactly: one full re-parse per
+ // delta. What matters is the product — reveals times the length re-parsed
+ // each time — which is what grew quadratically.
+ const paced = costOf(8000, 3);
+ const unpaced = costOf(8000, 3, { paced: false });
+ assert.ok(
+ paced.charsParsed < unpaced.charsParsed / 2,
+ `pacing should more than halve the parsing work, got ${paced.charsParsed} against ${unpaced.charsParsed}`,
+ );
+ // The cap is what makes this hold at length; without it the ratio tends to 1.
+ assert.ok(
+ paced.reveals < unpaced.reveals / 2,
+ `expected fewer than half the reveals, got ${paced.reveals} against ${unpaced.reveals}`,
+ );
+});
+
+test("a page-length answer is left alone", () => {
+ // Short messages are where the typewriter reads as a typewriter, and
+ // re-parsing them is free, so pacing must not touch them at all.
+ const paced = costOf(900, 3);
+ const unpaced = costOf(900, 3, { paced: false });
+ assert.deepEqual(paced, unpaced);
+});
+
+test("a burst still catches up rather than typing for half a minute", () => {
+ // The original guarantee: 2KB landing at once is revealed by backlog/5 a
+ // frame, capped — not by the per-character floor.
+ assert.equal(revealStep(0, 2000), 120);
+});
+
+test("nothing is revealed once the cursor has caught up", () => {
+ assert.equal(revealStep(500, 500), 0);
+ assert.equal(revealStep(500, 400), 0);
+});