Repository navigation
Studio: bound what a streaming thinking block keeps mounted - #9073
danielhanchen wants to merge 22 commits into
Conversation
Every existing harness measures a FINISHED thread. A finished reasoning group resolves to closed, Radix unmounts closed CollapsibleContent, and the reasoning part therefore contributes no DOM at all, so adding thinking content to a seeded fixture measures nothing while looking like it measures something. The cost exists only while the block streams, so this fixture streams. smoke-reasoning-pane.html mounts the real Thread and streams one reasoning part to the size a reported generation reached, with the fence-free opening stretch that generation had, because the onset is at the first CLOSED fence rather than at any particular reasoning length. Two preconditions are written into the module docstring because both were got wrong first and each hid the effect. The arrival rate has to be the user's: a 2ms gap saturates the renderer from the first chunk, so the run opens at 45 fps instead of 60 and the measured spread collapses from 3x to 1.19x. And on an idle machine frame rate is not sensitive enough to see this at all, so the headline is calibrated main-thread busy time, with CPU throttling available to show the frame rate collapse directly.
While a thinking block streams, the pane is 256px tall and scrolls, and it mounts the whole body inside that window. A long generation therefore accumulates tens of thousands of syntax-highlighting spans that nobody can see, and the page's frame rate tracks that node count. Render a bounded tail of the body while it streams instead. The window start only moves in coarse steps and always lands on a block boundary outside a fence: moving it per chunk would hand the renderer a string that is not an extension of the last one every time, which drops the incremental Markdown cache's retained blocks and remounts the whole body, once per token. The full text replaces the window shortly after the stream ends. In the ordinary case the group has already collapsed and unmounted by then, so the whole body never mounts, which also removes the completion freeze. The reader who opened the block by hand still gets all of it.
…eader The window has to be reversible or it is a correctness bug rather than a performance trade. Three states, and they are different problems. Streaming with the reader at the end mounts a tail window; the reader cannot see what is above, so the start may advance. Streaming with the reader scrolled back stops advancing and WIDENS when they reach the top: content is only ever added, never removed from above them, because unmounting above a reader is what produces scroll jumps. Widening remounts the body, because handing the incremental Markdown cache a string that is not an extension of the last one drops its retained blocks and re-keys Streamdown. So PR 9058's anchor, a mounted row held still in viewport space, cannot be reused here: the row it would measure no longer exists by the time a layout effect could read it. The reader's place is held as a distance from the BOTTOM instead, which survives a remount because widening changes nothing below them, and the tail is frozen while they are detached so that the bottom they are measured against stops moving. Without that freeze the anchor drifts: measured, the reader's distance from the bottom walked 17,042px to 46,125px across eight widens. A finished block that the reader expands mounts from the head and grows downward a step per frame. It is not a tail window: a finished group has no height cap, so it is not a 256px scroller at all, and a reader opening it wants its beginning. Growing downward also needs no anchoring, since appending below cannot move what is above. Every path terminates at the whole body, and the tests are about reachability rather than about cost.
…not be cheap
Windowing a suffix of BLOCKS rather than of characters would let a reader scroll
back for the cost of the blocks actually added. It is not reachable from here.
Streamdown 2.5.0 keys blocks positionally, `Rn = J.map((k, A) => `${_}-${A}`)`
with `_` a useId(), applied as `jsx(f, {...}, Rn[A])`, and it also passes
`index: A` and compares `e.index !== t.index` in the Block memo. Prepending
shifts both for every block already mounted, so a widen remounts the whole body
however little it adds, and neither the key nor the index is reachable through
`BlockComponent` or `parseMarkdownIntoBlocksFn`, the only seams the package
exposes. Appending is free; prepending is a full remount.
So the window now covers exactly the case it was justified by, and nothing else:
a block that is streaming into a pane the reader is following. Scrolling back
restores the whole body once and turns the window off for the rest of the round,
and a finished block is never windowed, so expanding one mounts what it mounts
today.
Measured against the widen-on-scroll version this replaces: scroll back was four
gestures costing 207, 280, 646 and 846ms, and is now one costing 394ms, after
which the pane is at 26 to 105ms, which is where the unwindowed pane already is.
Expanding a finished block is 1ms to first paint and 759ms to complete, against
1ms and 750ms without the change.
This also deletes the two mechanisms the probe caught bugs in. There is no widen
loop to re-enter, so the settle correction cannot re-trigger itself, and the tail
no longer has to be frozen to keep the anchor valid.
…lly wrote Two defects found by diffing the pane's text against an unwindowed tree character for character, rather than by looking at it. STALE BLOCKS AT A REUSED POSITION Streamdown 2.5.0 memoises its default Markdown components on the source POSITION of the node: `sameNodePosition` compares only start and end line and column (vercel/streamdown#570, open). Handing it a string that is not an extension of the last one moves different text into the same line and column span, and every block whose span happens to match keeps the output it already had. Windowing does exactly that, twice a round: once per 6,000 characters as the start advances, and again on the restore. Measured on a 60,000-character fixture, Chromium, against the merge base: arm mounted text is a suffix of the base stale blocks before this commit no 4 streaming, 2 after restore after this commit yes 0 The stale blocks show reasoning from elsewhere in the same body at a place the model never wrote it, so this was worse than the missing text a window is supposed to trade for speed. Keying the renderer on the window start remounts it whenever the string stops being an extension, which is the only seam that reaches the memo: neither the block key nor the comparator is reachable through the props Streamdown exposes. FENCES THAT THE SLICE GUARD DID NOT SEE `isOutsideFence` counted bare ``` at column zero. CommonMark opens a fence on up to three leading spaces and on ~~~ as well, and a blank line inside a fence is legal and ordinary in code, so a fence indented inside a list item or written with tildes had block boundaries in the middle of it that the guard called safe. The slice then began mid-code with the closing marker ahead of the reader, which the renderer reads as an opening one and highlights the rest of the thinking block as code. Replaced with a line scanner that follows CommonMark: a fence is closed only by a marker of the same character, at least as long, with no info string. Six new tests, each of which fails on the previous implementation. Also: pass encoding = "utf-8" at the two write_text call sites, which tests/test_source_read_encoding.py requires and which was failing Repo tests (CPU), and bring the probe's wording in line with the restore-in-one-step design it now measures.
65d5c94 to
aee3504
Compare
Three separate cases where the window applied when its own rule says it should
not, all found in review of the streaming path.
THE WINDOW SURVIVED A THREAD SWITCH
Message parts are keyed by index and nothing else, in assistant-ui's own
`MessagePartsGrouped` (`_jsx(Component, {...}, partIndex)`), which is why
markdown-text.tsx already re-keys its caches on the message id. `ReasoningBody`
did not, so switching to another thread handed the same instance a different
message with the previous window start still set. A start left over from a long
reasoning part is past the end of a shorter one, and `text.slice` then renders an
EMPTY pane until the new round grows past the old offset. Reset on the message id.
THE COMPLETION FRAME PARSED THE WHOLE BODY TO THROW IT AWAY
`ReasoningGroupImpl` closes the collapsible on the same transition that ends the
round, and Radix keeps a closing `CollapsibleContent` mounted for its 200ms exit
animation. Dropping the window on the completion frame therefore handed Streamdown
the entire body to parse and highlight immediately before that body was unmounted
unseen. That is work the unwindowed tree never does, at the one moment the reader
is waiting for their answer. The window now survives the collapse, so the usual
case pays nothing and a block the reader has pinned open fills out one animation
later.
THE PLACE-HOLDING LOOP FOUGHT THE READER
`holdPlace` rewrote `scrollTop` every frame for 400ms regardless of what the
reader did in the meantime. A trackpad flick produces scroll events for well
longer than that, so every one of them was undone on the next frame. It now reads
back what it wrote and stops the moment `scrollTop` is something else, which is
the reader. Two writers on one scrollTop is a fight the reader always loses.
…lled back The window's own rule is that it applies while the block streams AND the reader is pinned to the bottom. Only the first half was ever checked before engaging one. The second half was used to END a window, never to decide whether to start one, so a reader who scrolled back BEFORE the window first engaged was protected by nothing: the scroll-back handler ignores them while the start is still zero, and the first advance then unmounts the text they are reading from above them. They are not rescued afterwards either, because removing content above a reader who is not at the bottom does not have to move scrollTop and so does not have to fire a scroll event at all. Measured on the 60,000-character fixture, Chromium: scrolling back at 14,000 characters and then waiting left the pane windowed to 15,730 characters with the reader stranded above the window, and it stayed that way. Track whether the reader is at the bottom and gate the advance on it. The pane starts pinned, so the ordinary case is unchanged; a reader who scrolls back early simply never gets a window this round, which is what the rule already said should happen.
tests/studio/test_playwright_suites_run_in_ci.py was failing on this branch, and it was right: this PR adds tests/studio/playwright_reasoning_pane.py and no workflow named it, so the suite would have sat in the repo looking like coverage while running on no PR at all. That gate exists because five suites were already in that state. Wired into Frontend CI beside the other browser smokes, at 22,500 characters and chromium only: about 70 seconds of streaming, and deliberately above the 18,000 character point where the window engages, so CI exercises the WINDOWED path rather than only the short case. Measured locally: exit 0, peak 2,589 spans over 17,423 mounted characters. SMOKE_RP_EXPECT_SPANS=0 is set, and it is a recorded debt rather than a shrug. The harness's span floor of 11,000 asserts the tree still builds highlight spans; a windowed pane holds a bounded number of them by construction, so the floor cannot be met and, more to the point, cannot tell "windowed" from "highlighting broke". Restoring that guard needs the floor expressed against the pane's own mounted character count rather than against the whole body. probe_reasoning_window.py stays out of CI, which the gate does not currently ask about either way since it globs playwright_*.py only. It is a probe: it reports numbers and asserts only that it measured them. Said so in its docstring, along with the note that it is the first probe_*.py in the tree, so covering probes is a change to that gate rather than a rename here.
…t are not fences The fence guard got the shapes it knew about right and was quadratic about it. ONE PASS, NOT ONE PER CANDIDATE `alignWindowStart` walked the blank lines and asked `isOutsideFence` about each, and that helper rescanned from byte zero every time. The case where that bites is the exact case the window exists for: inside a still-open fence containing blank lines, NO candidate is ever safe, so every blank line paid a full prefix scan and the whole quadratic sum repeated on every streamed token. Measured on a 140,000 character unfinished fence, twenty aligns: 217,674ms before, under 4,000ms after. That is a frame or more per chunk given back, in a change whose entire purpose is to stop spending frames. THREE MORE WAYS TO LAND INSIDE SOMETHING A fence opened on the list marker line, `- ```js`. CommonMark opens a fence there exactly as it does on an indented line. Matching only the indented form caught such a block's CLOSING marker and not its opener, which is worse than matching neither: the scanner then believes a fence opens where one closes. Container prefixes, list markers and blockquote markers alike, are stripped before the marker is read. Display math. A `$$` block with a blank line in it was a safe boundary as far as a fence-only scanner could tell, and the slice then began inside the equation with its closing `$$` ahead of it, which reads as an opening one. `streaming-render-schedule.ts` already refuses to commit a block on non-neutral display-math parity for this reason; the window now applies the same rule. Link-reference definitions. `[spec]: https://...` is document-wide and invisible, so slicing it away turned a `[spec]` left in the window into literal text. `IncrementalMarkdownCache` retains definitions for exactly this reason and cannot recover ones the slice already removed, so they are carried across the window instead. They render to nothing, so the visible text is unchanged. AND A CORRECTION LEFT RUNNING ACROSS A THREAD SWITCH `holdPlace` resolves the scroller afresh every frame, so a settle still in flight when the message changed would find the NEW thread's pane and drive it to the old thread's distance from the bottom. Cancelled with the rest of the window state. Nine new tests, each verified to FAIL against the previous implementation.
CommonMark lets a reference label carry a backslash-escaped bracket, so `[spec\]]: /url` is one definition rather than a label ending at the first `]`. The label pattern stopped there and did not carry it, and a `[spec\]]` left in the window then rendered as literal text. The alternation now allows an escape. A destination is still required, and a control test holds that widening the label cannot start hoisting a bare `[spec]:` again, which is the failure the destination requirement exists for.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 08921a0b6a
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const aligned = alignWindowStart(text, text.length - windowChars); | ||
| return Math.max(currentStart, aligned); |
There was a problem hiding this comment.
Keep footnote-bearing streams bounded
When a GFM footnote is appended after the window has already engaged, Streamdown switches to its deliberate single-block mode for footnote-bearing documents (see IncrementalMarkdownCache.update in streaming-render-schedule.ts). alignWindowStart then returns 0, but this Math.max preserves the previous nonzero start; every subsequent scan has the same result, so the mounted suffix grows without limit for the rest of a long generation and recreates the performance problem this window is intended to prevent. Handle the footnote transition explicitly rather than retaining a start that can never advance.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and I had this filed as an intended safe failure. I was wrong, and it is a regression my own redesign introduced two rounds ago. Two measurements changed my mind.
The premise first, checked rather than assumed: parseMarkdownIntoBlocks returns the entire document as one block once a footnote definition is appended. On my fixture, 163 blocks become 1. So alignWindowStart returns 0, as you say.
Then the consequence, with the window engaged at 6,000 characters and the text grown to 37,729: Math.max held the start at 6,000, leaving 31,729 characters mounted from a window that is supposed to cap at 18,000, and never able to move again.
The unbounded growth is the smaller half of it. Retaining that start carries it across the moment the renderer stops treating the document as divisible, so the slice point is no longer a boundary the renderer chose. That is the exact property the whole design rests on, and violating it is the same class as the stale text this review turned up earlier.
Fixed by treating a failed alignment as "turn the window off" rather than "keep what you had". nextReasoningWindowStart returns 0, and advanceReasoningWindow drops the carried definitions with it so they cannot be duplicated on screen. It is bounded and happens once: at most 18,000 characters after the footnote arrives, because that is when the alignment is next asked.
The honest cost is that reasoning containing a GFM footnote now gets no benefit from this change at all. That is going in the PR body rather than staying here.
| // Once set, the whole body is mounted for the rest of this round. Seeded from the round rather | ||
| // than from false, so it survives the group being collapsed and reopened. | ||
| const restoredRef = useRef(RESTORED_ROUNDS.has(messageId)); |
There was a problem hiding this comment.
Key restored state by reasoning round
When one assistant message contains multiple reasoning rounds, scrolling back in the first long round records only the shared messageId; if a later reasoning group in that same still-running message mounts, this initializer treats the new group as already restored and permanently mounts its entire body. Alternating reasoning and visible text can produce separate groups within one message, so a long later round loses the optimization even though the reader never requested its history; include the part/group identity in this persisted key.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. RESTORED_ROUNDS was keyed on the message id alone, so a message that thinks, answers, then thinks again gave its second reasoning group a key the first group had already set. The second group started already restored and never windowed at all.
I did not want to take this one on reading, so I built the case. The fixture now emits two reasoning parts in one assistant message: stream round one, scroll back to restore it, then stream round two to 40,000 characters and read the open pane.
| key | round two pane |
|---|---|
| message id | 38,813 of 40,000, never windowed |
| message id plus round | 17,059 of 40,000, windowed |
Keyed now on the message plus the first 64 characters of that round's own text, which is stable because a part only ever grows at the end, and which two groups in one message cannot share. A regenerate also takes back the entry this instance actually wrote rather than recomputing a key against the new round's text, which would have deleted something never added.
…not a definition A LITERAL \[ IN CODE SILENTLY TURNED THE WINDOW OFF FOR THE WHOLE STREAM `preprocessLaTeX` skips code when it looks for display math, and the bracket guard did not. So a `\[` inside a fence or inside inline code, which is ordinary in reasoning that discusses LaTeX, opened an equation that never closed, and `alignWindowStart` then returned 0 for the rest of the round. The pane simply never became windowed and the whole change quietly did nothing. Reproduced both ways before fixing: before fenced \[: window engages false inline \[: false after fenced \[: window engages true inline \[: true Code is now skipped, fenced and inline alike, for the same reason and by the same rule the preprocessing pass uses. While in there, the bracket state is accumulated in the SAME pass that walks the blocks. Asking about each candidate separately re-walked the whole prefix per candidate, which is the quadratic shape this file has already had to remove twice, reintroduced by me in the rewrite two commits ago. A PARAGRAPH THAT LOOKS LIKE A DEFINITION IS NOT ONE The prefix-only pattern accepted anything shaped like `[label]: something`, and carrying one of those puts text the reader has already read back at the top of the pane. Destinations are now validated, conservatively and failing toward NOT carrying, because refusing a real definition only costs a link its styling inside the window while accepting a fake one is a visible artefact. The example in review does not fail, and it is worth recording why. Checked against remark, the parser in this very pipeline: [spec]: <invalid destination> -> definition (spaces inside <> are legal) [spec]: /url not a title -> PARAGRAPH (this is the real case) [spec]: https://example.com/spec -> definition [spec]: -> paragraph So the angle form is carried and the trailing-junk form is not, with a control test for each so a future tightening cannot start dropping real definitions.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 477cd17698
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (next === "[") depth += 1; | ||
| else if (next === "]") depth -= 1; |
There was a problem hiding this comment.
Match the preprocessor's bracket-span limit
When streaming reasoning contains an unclosed \[ or a matching \] more than 4,096 characters later, this increments depth even though preprocessLaTeX only rewrites bracket spans whose bodies are at most 4,096 characters (src/lib/latex.ts). The source is therefore rendered as ordinary text, but alignWindowStart keeps returning 0; before initial engagement the whole pane remains mounted, and after engagement the existing suffix grows without bound. Apply the same span-validity rules as the preprocessor so literal or over-limit delimiters do not disable windowing.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. preprocessLaTeX caps the body at 4,096 characters, (?<!\\)\\\[([\s\S]{0,4096}?)\\\], and leaves anything longer as ordinary text. Treating a longer opener as live math meant alignWindowStart returned 0 for the rest of the stream and the pane silently never windowed, which is the same quiet total failure a \[ inside a code sample used to cause.
Rewritten from a running parity count to explicit spans: an opener only counts if an unescaped \] follows within 4,096 characters, outside code, matching the preprocessor exactly including that the closer may sit at the limit.
One thing the rewrite forced. The direct form re-scanned every code region for every delimiter, and a body that alternates an inline code span with a \[ gives as many regions as delimiters. Measured, four times the input:
| lookup | 4,000 units | 16,000 units |
|---|---|---|
| linear scan | 45.8ms | 377.1ms |
| sorted, merged, binary search | 22.7ms | 93.7ms |
So the regions are sorted and merged once and searched, and the span cursor in alignWindowStart only moves forward. Three tests: the over-cap case, an under-cap control, and the ratio. The first two fail on the previous tree.
Worth recording that the ratio test did not, in its first form. I had written it as an absolute bound with a floor, and it passed against a deliberately quadratic implementation, so it was measuring nothing. It only became discriminating once it compared two input sizes.
| if (trimmed.startsWith("<")) { | ||
| const close = trimmed.indexOf(">"); | ||
| // An angle destination may not contain a newline, an unescaped `<`, or spaces past the `>`. | ||
| if (close === -1) return false; | ||
| const inside = trimmed.slice(1, close); | ||
| return !/[<\n]/.test(inside); |
There was a problem hiding this comment.
Reject trailing junk after angle-bracket destinations
For an invalid definition such as [spec]: <https://example.com> not-a-title, this branch validates only the text inside <...> and returns true without checking what follows >. Markdown renders that source as a visible paragraph rather than a reference definition, so once the window advances linkDefinitionsBefore prepends an already-read line at the top of the mounted suffix. Validate the remainder as either empty or a valid optional title before carrying the block.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it was my own bug. hasValidDestination accepted anything after the closing >, so [spec]: <https://example.com/spec> junk here was carried as a definition when it renders as a visible paragraph, putting text the reader had already read back at the top of the pane. That is precisely the artefact this carrying exists to avoid.
Ground truth from remark, the parser in this pipeline:
| line | remark |
|---|---|
[spec]: <https://example.com/spec> "Title" |
definition |
[spec]: <https://example.com/spec> junk here |
paragraph |
[spec]: <https://example.com/spec>extra |
paragraph |
Both the angle form and the bare form now go through one isTitle, so whatever follows the destination must be empty or a quoted or parenthesised title. Test added over all three lines; it fails on the previous tree.
Reject trailing junk after an angle-bracket destination. `[spec]: <url> junk` and `[spec]: <url>extra` are paragraphs to remark, not definitions, so carrying them put text the reader had already read back at the top of the pane. Both forms now go through one title check. Match the preprocessor's bracket-span limit. `preprocessLaTeX` caps a `\[ ... \]` body at 4,096 characters and leaves anything longer as ordinary text, so a long opener was treated as math the preprocessor never forms and `alignWindowStart` then returned 0 for the rest of the stream, silently disabling the window. Rewritten from a parity count to explicit spans, with sorted and merged code regions, a binary search and a forward-only cursor, because the direct form is quadratic on a body that alternates an inline code span with a `\[`. Key the restored state by round rather than by message. A message that thinks, answers, then thinks again gave its second reasoning group a key the first had already set, so the second group started restored and never windowed: measured at 38,813 of 40,000 characters mounted against 17,059 with the round key. A regenerate now takes back its own entry rather than recomputing one against the new text. Turn the window off when no boundary exists, rather than keeping the last one. A GFM footnote makes `parseMarkdownIntoBlocks` return the whole document as one block, 163 becoming 1, so a start that was a real boundary a chunk ago is not one now. Keeping it both sliced a document the renderer treats as indivisible and froze the start while the text grew, measured at 31,729 mounted characters from a window that caps at 18,000. Reasoning containing a footnote now gets no windowing at all, which is correct and merely as slow as today. Also corrects a claim in the design comment: the block index IS reachable through `BlockComponent`, only the key is not.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ca84dc35c6
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| function bracketMathSpans(text: string): Array<[number, number]> { | ||
| const regions = codeRegions(text); | ||
| const spans: Array<[number, number]> = []; | ||
| let index = text.indexOf("\\["); |
There was a problem hiding this comment.
Track inline LaTeX spans before choosing a boundary
When a long reasoning stream contains a \(...\) span that crosses a Markdown block boundary near the cutoff, this scan ignores it because it searches only for \[. preprocessLaTeX rewrites both delimiter forms before Streamdown splits the document, so alignWindowStart can select a raw block boundary inside the inline span; preprocessing the resulting suffix then sees only the orphaned closer, changing the rendered reasoning until the full body is restored. Track parenthesized spans with the same span and skip-zone rules.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and the premise checks out against preprocessLaTeX itself rather than against my reading of it. The pass is a dotall regex over the whole string, so an inline span crosses a paragraph break without complaint:
some prose \(a + b+ blank line +c + d\) and moreis rewritten tosome prose $a + b+ blank line +c + d$ and more- the suffix on its own,
c + d\) and more, comes back with no$at all, carrying a literal closer
The renderer splits that span into two blocks, so a boundary genuinely exists inside one equation, which is exactly the case the \[ guard existed for.
Both pairs are now walked together in a single left-to-right pass rather than once per pair, because that is what the preprocessor's alternation does: the earliest live opener wins and its own closer ends it, so an interleaved \( ... \[ ... \) ... \] forms one span from the \( and not two overlapping ones. The same skip rules apply to both, including the 4,096 character reach, so an inline opener with no closer in range still cannot disable the window.
Two tests, and the first fails on the previous tree at the boundary inside the span.
| if (messageIdRef.current !== messageId) { | ||
| messageIdRef.current = messageId; | ||
| windowRef.current = freshReasoningWindow(); | ||
| atBottomRef.current = true; | ||
| restoredRef.current = RESTORED_ROUNDS.has(roundKey(messageId, text)); |
There was a problem hiding this comment.
Reset restore ownership when switching messages
When the reused part instance switches from a restored, still-running message A to a finished message B, this block resets the window state but leaves markedKeyRef pointing at A. If B is then regenerated, the finished-to-running branch deletes that stale key from RESTORED_ROUNDS; returning to A and reopening its collapsed reasoning pane therefore windows it again even though the reader already requested its full history. Clear or otherwise re-scope markedKeyRef during the message-id transition.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and rather than clear the ref I have removed the thing it was bookkeeping for.
Your two findings this round and the one before it are the same finding: the module-level set needed an identity for a reasoning round, and every identity invented for it was wrong in a different way. Keyed by message id, a second reasoning group inherited the first group's answer. Keyed by message id plus the opening 64 characters, two groups that begin alike still alias, which is your other item. And the ref remembering which key this instance wrote goes stale when the part instance is reused, which is this one.
ReasoningGroupImpl already has exactly the lifetime that was being reconstructed. It owns the open and dismissed state, so it survives the collapse that unmounts the body, which is the only reason the flag had to outlive the component; and there is one instance per reasoning group, so two groups in one message cannot share it. So the flag lives there now and the body reads it through context. No key, no eviction cap, and nothing that outlives what it describes.
The reset folds into the existing startsNewReasoningRound transition, which was already the single definition of "a new round started" in that component, plus a message-id guard for instance reuse.
Measured on a fixture that emits two reasoning parts in one message: the restore survives a collapse and reopen mid-stream, 38,832 characters before and after, and round two still windows at 17,059 of 40,000.
| const roundKey = (messageId: string, text: string): string => | ||
| `${messageId}:${text.slice(0, 64)}`; |
There was a problem hiding this comment.
Use an actual reasoning-part identity for restored rounds
Fresh evidence in this revision is that the replacement key distinguishes rounds only by text.slice(0, 64). If a later reasoning group in the same message first mounts or reopens after 64 characters and shares that opening prefix with an earlier restored group, RESTORED_ROUNDS.has aliases the two and permanently disables windowing for the later group even though the reader never requested its history. Key this state by the part/group identity rather than content.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct on both the aliasing and the diagnosis. The prefix key was a narrower version of the bug you reported last round rather than a fix for its cause, and two groups in one message that open with the same 64 characters is not a contrived case: reasoning rounds in one answer often start the same way.
Rather than look for a better key, there is now no key. The restored flag lives in ReasoningGroupImpl, which is one instance per reasoning group and which survives the collapse that unmounts the body, so it already is the identity that a key was standing in for. The body reads and sets it through context. Details and the measurement are in the reply on the sibling item.
Recorded in the code as well, because the count of attempts is the finding: three separate identities, three separate ways of being wrong, all removed by using the one the component tree already had.
This PR gives `MarkdownTextImpl` an optional `text` override, and the test located the function by its exact empty argument list, so it failed with 'is gone; this test needs rewriting' rather than on anything it was measuring. Anchored on the declaration instead. Confirmed it still bites: replacing the provider value with a constant fails it.
Track `\( ... \)` as well as `\[ ... \]`. `preprocessLaTeX` rewrites both forms before Streamdown splits the document, and because it is a dotall regex over the whole string an inline span crosses a paragraph break happily: `some prose \(a + b\n\nc + d\) and more` is rewritten as one equation, verified against the function itself. The renderer splits that into two blocks, so a boundary exists inside it, and the mounted suffix would reach the preprocessor carrying a bare closer that renders literally. Both pairs are now walked together in one left-to-right pass, which is what the preprocessor's own alternation does. Move the restored flag out of a module-level set and into the reasoning group. The set needed an identity for a round, and every identity invented for it was wrong in a different way: the message id told a second reasoning group that the reader had already asked for its history, the message id plus the opening 64 characters still aliased two groups that begin alike, and the ref remembering which key this instance had written went stale when the part instance was reused for another message. `ReasoningGroupImpl` already has exactly the lifetime wanted. It owns the open state, so it survives the collapse that unmounts the body, and there is one instance per group, so no key is needed at all. The reset folds into the existing `startsNewReasoningRound` transition, which was already the one definition of a new round in that component. Measured on the two-group fixture: the restore survives a collapse and reopen mid-stream, 38,832 characters both sides, and round two still windows at 17,059 of 40,000. Reachability re-checked on Chromium, Firefox and an adversarial corpus after merging current main: exact suffix while windowed, and character for character identical to the unwindowed tree both after a scroll back and when finished.
Parking thisClosing rather than reworking. The reasoning stays here so it survives the closure, and it is recoverable under either of the two measurements below. The decision rests on a pattern, not on any single item. Seven consecutive review rounds each needed another correction to the boundary rule or the restore bookkeeping. That count is the evidence. Windowing by character budget forces the window to predict the renderer's judgement about where a document may be divided, and the footnote case shows that judgement can change retroactively for text already scanned: appending a GFM footnote definition collapses 163 blocks to 1, Worth recording plainly: that item was filed as a reject first, and the reject was wrong. It was wrong about a bug this redesign introduced two rounds earlier, and it is the same class as the stale-text corruption found earlier on this branch. Silent, plausible looking, and invisible to a screenshot. What was fixed along the way is worth keeping in mind if this is revisited. Trailing junk after an angle-bracket destination, a 4,096 character bracket-span cap that silently disabled windowing for the rest of a stream, and a restore key that measured 38,813 of 40,000 characters mounted against 17,059 with the correct key. The last three items collapsed into one fix by moving the restore flag into the component that already owns the open state, removing three invented identities at once. Recoverable under either of these, neither of which anyone has taken:
If a fix is still wanted afterwards, the cheaper correct option is the one #9058 demonstrates is safe: never unmount, and reduce per node cost instead. Dropping syntax highlighting inside the streaming pane measured better than this design does, 26.6% busy and 785 elements against 2,932, and was set aside only because it changes something visible. A transient loss of syntax colour in a thinking pane is a smaller visible change than the reader's scroll position landing mid body, which this design does today. A correction to something said about this work elsewhere. #9058 is not visibility driven culling. It is a widen only progressive mount: bound the first commit to the last 16 messages, mount 32 per frame, then drop the restriction. Nothing ever unmounts. Its cost is one time, so converging to the full tree ends it. The reasoning pane's cost is standing, tracking the node count that exists at all times, so progressive widening converges to exactly the pane that is slow. The two problems have opposite shapes and the approach does not transfer. Whole block, visibility driven windowing does look feasible and is cleaner in kind, because |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5e7d6a9fb7
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const rendered = text.length - currentStart; | ||
| if (rendered <= windowChars * (1 + slack)) return currentStart; | ||
| const aligned = alignWindowStart(text, text.length - windowChars); |
There was a problem hiding this comment.
Revalidate the current cut when Markdown blocks merge
When a footnote definition arrives after the window has engaged but the mounted suffix is still within the slack limit, this early return preserves the old start without checking whether it remains a block boundary. Streamdown retroactively merges such a document into one block (as the new footnote test itself demonstrates), so the pane continues slicing inside that block and can display incorrectly parsed or stale reasoning until another roughly 18,000 characters arrive or the round completes. The current boundary must be invalidated as soon as an append changes the splitter's block structure, rather than only when the size threshold requests a new start.
Useful? React with 👍 / 👎.
| assert.ok(start > 0); | ||
| const carried = linkDefinitionsBefore(text, start); | ||
| if (carried !== "") { | ||
| assert.ok(carried.includes("https://example.com/spec"), carried); |
| const start = alignWindowStart(text, 100); | ||
| assert.ok(start > 0); | ||
| assert.ok( | ||
| linkDefinitionsBefore(text, start).includes("https://example.com/spec"), |
| test("a real definition with a title is still carried", () => { | ||
| const text = `[spec]: https://example.com/spec "The Spec"\n\n${"filler\n\n".repeat(50)}`; | ||
| const start = alignWindowStart(text, 100); | ||
| assert.ok(linkDefinitionsBefore(text, start).includes("https://example.com/spec")); |
| test("a real definition in angle brackets is still carried", () => { | ||
| const text = `[spec]: <https://example.com/spec>\n\n${"filler\n\n".repeat(50)}`; | ||
| const start = alignWindowStart(text, 100); | ||
| assert.ok(linkDefinitionsBefore(text, start).includes("https://example.com/spec")); |
Studio goes sluggish during a long generation that has a thinking block in it, and gets its frame rate back the instant that block collapses. This bounds what the thinking pane keeps mounted while it streams, and gives all of it back whenever the reader asks for it.
Read the prior art section before the measurements. Two projects with the same symptom shipped something like this and backed it out, and that is the strongest argument against this change. It is answered below rather than left for a reviewer to find.
What the field capture shows
One generation, sampled every 5s. The first 90 seconds hold 60.0 fps and exactly 0 highlight spans across 33,348 characters of thinking. Frames start being lost at the first closed code fence, not at any particular reasoning length, and from there the frame rate decays to 11.8 fps as the pane fills.
totalElements - reasoningElementsis a constant 578 for every sample the pane is mounted: every node the page gains is the thinking pane and nothing else in the app grows at all. When the round ends the group collapses and the frame rate recovers in the next sample window.Prose costs 8.3 pane elements per 1,000 characters. Fenced code costs 169, twenty times as much, and 90% of the pane's elements are syntax-highlighting spans.
Why unmounting rather than skipping paint
Filter the capture to sample windows where almost nothing is mutating:
Around ten DOM mutations a second, and
avgFrameMsa uniform ~68ms rather than spiky. The frame rate tracks mounted node count with r = -0.88 over 62 samples.content-visibility: autoon the pane's code blocks was measured on the same fixture and did nothing: 60.2% late main-thread busy against the baseline's 57.4%, node count unchanged at 17,440 against 17,482. One run, Firefox.The original version of this section drew the wrong conclusion from that, and the corrected reasoning matters because it is what the design rests on. It argued that the cost is "the nodes existing", i.e. standing layout and paint, and that
content-visibilitytherefore cannot help. That does not follow: skipping layout and paint for offscreen content is exactly whatcontent-visibilitydoes, so if the cost were standing layout and paint it should have helped. Firefox has supported the property since 125, so the null is not missing support.The reading that fits all of the evidence is the opposite one: the cost that scales is in JavaScript over the mounted set, not in layout or paint. That is consistent with the null result, because
content-visibilitydoes not touch script. It is consistent with r = -0.88 against node count. And it is consistent with the low mutation counts, because a mutation counter counts DOM writes, not React work: a render that reconciles several hundred blocks and writes three nodes is three mutations and a great deal of script.This is a hypothesis, not a measurement. Nobody has profiled where the late-stream main-thread time actually goes, and that profile is the single thing that would settle whether this change is the right shape. It is named as an open question in the prior art section rather than papered over.
What is not in doubt is the consequence: only unmounting removes work that scales with the mounted set. Containment cannot, and the measurement agrees.
The change
While a reasoning group streams,
ReasoningTextismax-h-64andoverflow-y-auto: a 256px window over a body that reaches tens of thousands of pixels, with the whole body mounted inside it and the pane auto-following its own bottom. So the window applies in exactly one situation: the block is streaming and the reader is watching the end of it, where everything above them is pure cost.Three things end it, and all of them restore the body whole and leave it whole:
The window start advances in coarse steps at block boundaries, once per 6,000 characters, because handing
IncrementalMarkdownCachea string that is not an extension of the last one drops its retained blocks.What review changed, and one thing it caught that a green check would not have
The version first opened here rendered text the model never wrote at that place. Diffing the pane's full text against an unwindowed tree character for character, on a 60,000-character fixture: four stale fences while windowed, and two stale paragraphs after the restore, showing reasoning from elsewhere in the same body. Reproduced on two runs and two content fixtures, zero on the merge base.
The cause is not in this repository. Streamdown 2.5.0 memoises its default Markdown components on the position of the node,
sameNodePositioncomparing start and end line and column only (vercel/streamdown#570, open). Handing it a string that is not an extension of the last one moves different text into the same span, and every block whose span happens to match keeps the output it already had. Re-keying the renderer on each window move is the only seam that reaches it.A related claim in the original description was simply false, and is corrected in the code comments. "Prepending is a full remount" is not true. Prepend to a positionally keyed list and the keys are unchanged for every existing block, so React matches them and only the
contentprop changes. Measured against the shipped dist with a mount-countingBlockComponent: prepending costs 2 mounts and zero unmounts, identical to appending. What prepending really costs is that every block's content changes, so every memo misses and every block re-parses, plus the stale-output problem above. The design is unchanged; the explanation was wrong.Also found and fixed under review, each with a regression test verified to fail on the previous tree:
And the boundary rule was rewritten, because the count of its bugs was the finding
Five consecutive review rounds each found another CommonMark corner in one
hand-written function: indented fences, tilde fences, fences opened on a list marker,
fences opened in a quote, longer-run closers, info-string closers, container markers
that stop applying inside a fence, display math in two syntaxes, dollars inside inline
code, loose list continuations, the five HTML block types a blank line does not end,
an ordered-list fence whose closer is indented four spaces, and a quoted fence followed
by a top-level one. Several produced a wrong boundary rather than a missed one.
That is not an incomplete implementation, it is the wrong shape of answer, so the
boundary now comes from the renderer instead. Streamdown splits with
parseMarkdownIntoBlocksand renders each block independently, which is whatBlockComponentand the block memo exist for. If block N is already parsed withoutreference to blocks 0 to N-1, then dropping those blocks cannot change how block N
renders. Slicing on a block boundary is safe by construction, and safe in the sense
that matters here: the mounted output matches the unwindowed tree even where
Streamdown's own splitting is imperfect, because then the window is imperfect in
exactly the same way.
131 insertions against 275 deletions. One guard survives, because one transform runs
before the split:
preprocessLaTeXrewrites\[ ... \]into$$ ... $$on the wholestring, so a raw-source slice can still land inside one and meet an orphan
\].Prior art, and the case against this change
Three projects have been down this road, and none of them ended up here.
open-webui shipped JS culling of offscreen messages and reverted it in about ten days, after cross-engine scroll regressions, replacing it with
content-visibility. That is the most uncomfortable data point, and it is not made less so by the fact that three of the defects listed above were scroll defects. Their revert is evidence that this shape of change is easy to get wrong in exactly the way it was got wrong here.LibreChat measured 18,000 characters of contiguous reasoning at one 96ms long task in 13.4 seconds, using rAF coalescing plus per-block memoisation, and concluded that splitting or windowing was not needed.
assistant-ui's own guidance is "do you need this? probably not", recommending
content-visibilityfirst and virtualization only later.The honest counter, and it is a real one:
useCoalescedStreamingTextis the rAF coalescer andIncrementalMarkdownCacheis the per-block memoisation. The field capture above was taken with both of them in place. Their fix is not an untried option here; it is the status quo that is failing.content-visibility.content-visibilityis the thing that did nothing on this fixture.So the two cheap alternatives are, respectively, already shipped and already measured as doing nothing. That is what distinguishes this from the reverts, and I think it is enough not to abandon the approach on prior art alone.
What it is not enough for is merging this as it stands. Two measurements would settle it, and neither has been taken:
content-visibilityshould have worked, the null result needs re-examining on Chromium rather than only Firefox, and open-webui's ending is the better guide.I would rather this waited for those two numbers than shipped on the ones below.
Measured
Firefox, the fixture at the capture's own 130,000 characters and 325 characters a second, medians over n=5 with full ranges. Taken on the version first opened here.
content-visibility: autoNon-overlapping ranges against the baseline, -40%.
The review fixes did not cost that, and improved it. Chromium at 6x CPU throttle, 90,000 characters, n=1 per arm, same box, back to back:
The collapse figure is the completion-frame fix. A baseline arm for this table was attempted and failed to run; it is missing rather than omitted.
Reachability, which is the part a screenshot cannot show
The pane's full text extracted from both trees and compared character for character, not eyeballed:
Same result on a second fixture carrying indented fences, tilde fences, CJK, RTL and emoji. Playwright WebKit is a proxy for the webviews Desktop embeds, not those webviews.
Behaviour that genuinely differs
Three things, stated here rather than discovered later.
This does nothing at short context. The window needs about 18,000 characters of thinking to engage, which is roughly 4,500 tokens. A 4,096-token context cannot hold that. This helps long-context generations only, and it also means a 4,096-token test model cannot exercise this code at all, which is worth knowing when reading any number on this PR: every measurement here comes from a fixture, not from a live model.
A scroll-to-top gesture no longer reaches the top in one go. After a restore the reader's place is held as a distance from the bottom, so the restored content appears above them and they scroll again to reach the start. Nothing is unreachable. It is visible in the before/after images posted on this PR.
While windowed, select-all, find-in-page and the accessibility tree reach only the window. 13,706 characters against 60,084 at the moment sampled. Scrolling back restores all of it. The Copy button is unaffected in either case: it reads from the message parts rather than the DOM, and only renders on a finished block.
Limits
content-visibility, on Firefox only. Reported as "no effect", not as a precise number, and see the open question above about re-running it on Chromium.display: contentshost element, 20,816 to 20,817.Rust unit testsandTauri Linux debug buildreds on this branch are not from this change. The one genuine failure wasstale_blank_observer_cannot_delete_a_competing_callers_idinstudio/src-tauri/src/desktop_backend_owner.rs, a file this PR does not touch; the rest were cancelled by supersession.Round 16, and four more bugs
All four were real and all four are fixed on this branch.
[spec]: <url> junkis a paragraph to remark, not a definition, and carrying it put text the reader had already read back at the top of the pane.preprocessLaTeXcaps a\[ ... \]body at 4,096 characters, so a longer opener was treated as math that is never formed, and the alignment then returned 0 for the rest of the stream, silently disabling the window. The rewrite also had to stop being quadratic: 4x the input cost 11.1x with a region scan against 4.1x with a search.parseMarkdownIntoBlocksreturns the whole document as ONE block once a footnote definition arrives, 163 becoming 1, so the alignment fails;Math.maxthen retained a start that is no longer a boundary the renderer recognises. That both froze the window while the text grew, 31,729 characters mounted from a cap of 18,000, and sliced a document the renderer treats as indivisible, which is the same class as the stale-text corruption this review caught earlier. Fixed by turning the window OFF when alignment fails. Reasoning containing a GFM footnote therefore gets no benefit from this change at all.Reachability was re-verified on the fixed tree against a merge base refreshed to current
main, on Chromium, Firefox and WebKit plus an adversarial corpus. All three properties hold on all four arms: the mid-stream pane is an exact suffix, the restored pane is character-for-character identical to the unwindowed tree, and the finished pane is character-for-character identical. The only structural difference anywhere is onedisplay: contentshost, which accounts for the entire innerHTML delta exactly, 28 bytes on a 3.4MB tree, and generates no box.One CI note: the
Backend CIred istest_stream_completion_timeout_is_absolute_despite_keepalives, a timing-sensitive backend test in a file this PR does not touch.Round 17, and three more
Two of them were the same finding as round 16's restore-key item, arriving from different angles: a content-prefix key still aliases two reasoning groups that begin alike, and the ref remembering which key an instance wrote goes stale when the part instance is reused. Rather than look for a third key, the flag now lives in
ReasoningGroupImpl, which owns the open state and so already survives the collapse that unmounts the body, and which is one instance per group. There is no key, no eviction cap and nothing outliving what it describes. Measured: the restore survives a collapse and reopen mid-stream at 38,832 characters, and a second group in the same message still windows at 17,059 of 40,000.The third was
\( ... \).preprocessLaTeXrewrites both delimiter forms, and being a dotall regex over the whole string it spans a paragraph break, so the renderer splits one equation into two blocks and a slice can land inside it. Both pairs are now walked together in the one left-to-right pass the preprocessor's own alternation performs.That is eight review items over two rounds, seven of them mine, and it is the reason for the section below.
Why this is being parked
The four bugs above, the stale-text corruption before them, and the boundary rewrite before that all have one cause. This design windows by CHARACTER BUDGET and must then find a legal place to cut inside a markdown document. Every failure has been a failure to predict the renderer's own judgement about where a document may be divided, and the footnote case shows why that is not a matter of trying harder: "indivisible" is a decision Streamdown makes from content the window cannot see coming, and it can change retroactively for text already scanned.
The shape that does not have this failure mode is mounting whole blocks driven by what is visible, with no character budget and no alignment at all. Streamdown's
BlockPropscarriescontent,indexandisIncomplete, and the shipped build passes all three to a customBlockComponent, so a block can be withheld without touching the string handed to the renderer. That last part matters: because the input string never changes, the position-only memo behind vercel/streamdown#570 cannot fire, and the corruption class becomes structurally impossible rather than merely fixed.I have not built it and I am not claiming its numbers. What the measurements here do say is that the ceiling is higher, not lower: the pane is 256px over a body that reaches 30,226px at 20,817 elements, about 0.69 elements per pixel, so a visible-plus-overscan window would mount several hundred elements against this design's 2,932, and frame rate tracks mounted node count at r = -0.88. The
content-visibilitynull result does not argue against it either, and I had that backwards before: containment did nothing precisely BECAUSE the nodes stayed mounted, which is an argument for removing them, not for keeping them.This could be reconsidered if either of the two open measurements comes back the other way: a profile showing where late-stream main-thread time actually goes, and the pane measured with #8935 applied. If #8935 alone fixes the field symptom, none of this is needed.