Repository navigation
Studio: keep long thinking streams responsive - #9477
wasimysaid wants to merge 24 commits into
Conversation
# Conflicts: # studio/frontend/src/components/assistant-ui/reasoning.tsx
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e13d481af5
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ? prepareOversizedCodeHighlight | ||
| : undefined | ||
| } | ||
| source={exactCodeSource ?? streamingCodeFence.source} |
There was a problem hiding this comment.
Keep the rendered code page bounded
When a long reasoning page is cut inside a giant fenced block, exactCodeSource contains the complete fence from canonicalCodeSources, and reasoning always selects the plain-code branch. Passing that complete source here causes every nominally 8 KiB page to mount the entire fence, so a hundreds-of-kilobytes reasoning fence can still create the DOM workload and UI stall that pagination is intended to prevent. Keep the complete canonical source for copy/download actions, but render streamingCodeFence.source, which is the bounded page slice.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 380d496. The rendered OversizedStreamingCodeBlock now receives only the bounded page-local streamingCodeFence.source; the canonical full-fence source is retained solely by Copy/Download actions. The pagination and throttled Chromium regressions pass.
| if ( | ||
| terminal && | ||
| !hasVisibleText && | ||
| reasoning.length === delta.length && | ||
| reasoning === delta | ||
| ) { | ||
| return ""; |
There was a problem hiding this comment.
Scope mirror suppression to affected providers
When any provider legitimately emits structured reasoning and a terminal visible answer whose text happens to equal that reasoning—for example, a short answer such as 42—this equality check discards the entire answer. The guard is applied to every OpenAI-compatible stream, while text equality alone cannot distinguish the documented local-server mirror from a genuine answer; gate this workaround on the affected backend or an explicit mirror signal.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 380d496. Mirror suppression is now enabled only for Studio local-model requests, requires a >=256-character terminal mirror, and preserves short equal answers plus all external-provider answers. Focused guard regressions and the full frontend suite pass.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 380d496229
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (openingState.rawHtml) { | ||
| pageMarkdown = `<${openingState.rawHtml.tag}>\n${pageMarkdown}`; | ||
| } else if (openingState.fence) { | ||
| pageMarkdown = `${syntheticFenceOpening(openingState.fence)}\n${pageMarkdown}`; |
There was a problem hiding this comment.
Preserve display-math state across page cuts
When a $$...$$ display-math block spans more than the reasoning page budget without a nearby blank line, pageStart cuts inside it, but the boundary state and synthetic wrappers here handle only raw HTML and fenced code. The resulting page lacks the opening or closing math delimiter, so the KaTeX plugin renders the affected derivation as plain or malformed Markdown when users navigate these pages. Track display-math state as well, or ensure page boundaries cannot fall inside such a block.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2e60333. Pagination now tracks display-math delimiters, including marker length and nested container prefixes, and adds bounded synthetic open/close markers when a page cuts through the block. The consolidated pagination regression and full frontend suite pass.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c9512e171e
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const newline = markdown.indexOf("\n", target); | ||
| const nextLine = newline < 0 ? target : newline + 1; | ||
| return nextLine < end ? nextLine : target; |
There was a problem hiding this comment.
Preserve GFM table context across page cuts
When a reasoning response contains a table longer than the page budget without blank lines, this fallback starts later pages at an arbitrary body row. Those slices no longer contain the table header and delimiter row, so the GFM parser renders the remaining rows as plain pipe-delimited text rather than a table. Avoid cutting inside a table or synthesize the required header context for each affected page.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bb24e6e. Pagination now carries GFM table state and prepends the original header and delimiter when a bounded page starts inside a long table. The consolidated regression verifies newest and earlier pages remain bounded and parse with table context; the full frontend suite and throttled browser fixture pass.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bb24e6e729
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const nextLine = newline < 0 ? target : newline + 1; | ||
| return nextLine < end ? nextLine : target; |
There was a problem hiding this comment.
Keep page cuts outside surrogate pairs
When a reasoning page falls back to the exact character budget because the current line has no later newline, target can land between the UTF-16 halves of an emoji or another supplementary Unicode character. Both adjacent pages then render a dangling surrogate as a replacement character, corrupting the reasoning text during navigation. Adjust the fallback boundary to avoid splitting a surrogate pair.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 4351502. Exact-budget fallback boundaries now advance past a UTF-16 surrogate pair instead of splitting it. The consolidated giant-line regression covers the supplementary-character boundary, and the focused/full frontend suites pass.
| if (line.startsWith(prefix)) return line.slice(prefix.length); | ||
| return line === prefix.trimEnd() || line.trim().length === 0 ? "" : null; |
There was a problem hiding this comment.
Normalize block-quote prefixes before comparing containers
For a long fenced block inside a block quote, valid lines may alternate between > text and >text because the space after > is optional. Storing the opener's exact prefix and requiring startsWith(prefix) makes the latter form terminate the tracked container; later pages then lose the synthetic fence and render code as quoted prose, while canonical copy source may stop at the first differently spaced line. Compare parsed container structure rather than the literal prefix spelling.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 4351502. Container matching now parses block-quote structure instead of comparing the opener’s literal spacing, so valid alternating > / > lines remain in the same fence. The regression verifies exact canonical code plus bounded wrappers; focused/full frontend and throttled browser checks pass.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 33d65ce99b
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } else if (openingState.table) { | ||
| pageMarkdown = `${openingState.table.markdown}\n${openingState.table.delimiter}\n${pageMarkdown}`; |
There was a problem hiding this comment.
Cap synthesized table context to the page budget
When a valid GFM table has an unusually large header or delimiter line, every page that starts in its body prepends both complete lines after the 8 KiB slice is selected. A generated 100 KiB single-cell header therefore mounts more than 100 KiB on each affected page and defeats the DOM bound that pagination is intended to enforce; truncate or otherwise bound the synthesized table context.
Useful? React with 👍 / 👎.
| const lineEnd = | ||
| rawLineEnd > lineStart && markdown[rawLineEnd - 1] === "\r" | ||
| ? rawLineEnd - 1 | ||
| : rawLineEnd; |
There was a problem hiding this comment.
Preserve CRLF in canonical fence sources
When pagination cuts through a reasoning fence whose body uses CRLF, this removes every carriage return before rebuilding the canonical source with \n. The canonical value is subsequently used by Copy/Download, so users receive different code bytes from those emitted by the model; retain the original line separators while removing only Markdown container prefixes.
Useful? React with 👍 / 👎.
| const content = containerContent(line, current.list); | ||
| if (content === null) { | ||
| current = { ...current, atBlockBoundary: true, list: null }; |
There was a problem hiding this comment.
Retain list state across lazy continuation lines
For a long list item using valid lazy continuation lines, such as - lead\ncontinuation ..., the first unindented continuation fails containerContent and clears the list state even though CommonMark still treats it as part of the item's paragraph. If pagination later cuts within that paragraph, the affected page receives no synthetic list context and renders the continuation as top-level prose; preserve lazy paragraph continuation state or avoid cutting inside it.
Useful? React with 👍 / 👎.
|
Thanks for this, and sorry it took a while to come back. It deserved a real evaluation rather than a quick opinion, so I built a long-live-reply rig for it, ran it against a concurrent same-commit null control, and ablated the PR into its parts. The short version is that you found a real and severe bug that our own benchmarks could not see, and your fix works. My recommendation is still to split it rather than land it whole, and the ablation below is why. You are right about the problem, and our harness was wrongChromium cannot see this bug at all. At 250K streamed reasoning characters our base build never drops a frame, and the pooled p5 fps ratio is 1.012 against a null moving 0.994 to 1.012. That is a flat null. This is also why the studiobench 100K rung could not answer the question: the rung grows the pre-existing conversation while the streamed tail stays pinned near 7,300 characters, so it never measures a long live reasoning stream at all. On WebKitGTK 2.50.4, which is what Tauri embeds and what our AppImage ships, it appears immediately. It is not low frame rate. Median is 62.5 fps and p5 is 58.8 on every arm. It is a small number of multi-second total main-thread freezes. Worst frame gap over the streaming windows, your merge base against your head, with the concurrent null's own delta beside every treatment delta:
The null's ratio is 0.997 to 1.067 in every wave; yours is 11.6x to 75.9x. An independent timer-lag channel agrees with the rAF gap to within 50 ms, so the thread really is blocked. The instrumentation-off row matters because a change that mounts less also makes a DOM-reading instrument cheaper, which can masquerade as an app win. It does not here: the win is 6157 to 78 ms with instrumentation removed entirely. And to answer the question you would reasonably ask next: #9517 did not already fix this. Today's main measures 5710 to 5813 ms at 250K against your merge base at 6151 to 6211 ms, which is inside the null's own band. #9517 solved a different quadratic in the open-fence repair path and solved it well. #9511 and #9462 attack highlight cost, not mounted-content cost. The ablation, which is the whole argumentFour arms at 250K, all run concurrently:
With the pane's DOM identical to base, the streaming-render rewrite alone removes 87 percent of the freeze. The one-line plain-code policy removes another 10. Pagination removes the final 2 percent, and it is the only part that costs selection, find-in-page, print and screen-reader access. Where I was wrong and you were rightI had been treating the loss of syntax colouring in the reasoning pane as a real cost. It is close to vacuous, and our own fixture is what misled me. Measured over 12,000 real traces and 221.9M reasoning characters, fenced code is 0.032 percent of reasoning characters, and exactly zero across 7,825 OpenThoughts and Qwen3-32B traces. In OpenThoughts, 0 of 3,072 thinking segments contain a fence while 3,072 of 3,072 of the same full messages do. Code lives in the answer, not in the thinking. Our studiobench fixture is 39.4 percent fenced code by construction, roughly 1,800-fold unrepresentative on this axis. Your instinct was correct and my objection was not. Your boundary work is also genuinely good and I want that on the record. The partition invariant holds perfectly: 1,080 of 1,080 cases across 815 pages, 23 fixtures and four page budgets, concatenating canonical slices reproduces the source byte for byte with no missing or duplicated bytes. Your own suite is 4,326 of 4,326 green. That is the hard part. Compatibility is your strongest result. A pre-change 300,000-character trace opens on your build as 38 pages with all 1,968 block sentinels in exact source order, the same for a 150,000-character legacy IndexedDB thread including when your build performs the Dexie import itself, the schema is untouched, and downgrading back to main opens both old and new-written threads complete and in order across 14 sessions with zero page errors. What is blocking, and it is the copy path rather than the pagination ideaPagination is on screen, so our off-screen exemption does not reach it, and the pre-registered bar it would have to clear instead is not met. But the part I would not merge regardless of any performance number is content loss:
There is byte corruption too: a fence with an LF opener and a CRLF body copies 6,979 LF characters where the source held 7,378 CRLF, while the unpaginated path copies exactly. That contradicts the exact-byte provenance claim the design rests on. The root cause of the CRLF cases is one regex: Five more boundary defects beyond the three already noted: nested lists at depth 3 or more re-open as On accessibility: the pane controls carry no Two of these are not your fault and I want to say so. Selection collapsing inside a removed subtree is spec behaviour under the DOM Standard's live range pre-remove steps, reproduced identically on all four engines. And find-in-page over unmounted content works on no engine and cannot be made to work by any amount of care. One regression worth fixing regardless of what we decideYour
Attribution is exact: 8.40 plus 8.89 equals 17.29 ms of measured parse cost against a 17.23 ms measured chunk. That is 10x more per-chunk work on the exact workload #9517 was written to fix, and it lands in the ordinary assistant answer, which gets no pagination, so your own bounding does not protect it. In fairness, #9517 landed after this branch was written, so this is a collision rather than something you introduced. Related: What I would like to doSplit it, because that keeps 97 percent of your win and drops all of the cost:
If you would rather I took the split on myself and credited you on the commits, I am happy to do that. If you want to do it, I will review quickly. Either way the streaming-render rewrite is the real find here and I want it in. Two notes on what I could not check, so you know the limits of the above. There is no macOS or Windows on my machine, so Safari, WKWebView, Edge and WebView2 are untested; Playwright's WebKit is built from trunk and is not branded Safari, so I have not treated it as one, and the row that decides this for Desktop on Linux is the WebKitGTK 2.50.4 one driven through python-gi. And Studio's print is already broken independent of your PR, since Chromium's PDF is one page on both arms because scroll containers clip. What your change does is remove the text from the DOM as well. |
…echanisms unslothai#9462's off-screen fence deferral and this branch's streaming code policy both wanted the fence branch's wrapper in markdown-text.tsx. Taking either side alone leaves the other dead: FenceBlock, DeferredFenceShell, fenceMode and useFenceReached lose every caller, tsc stays clean, and deferral silently stops. FenceBlock now owns the wrapper, the reach latch and the action bar, and takes the streaming policy's already-plain body as renderPlainBody. That body carries no spans to defer, so the gate is switched off for it and every other fence keeps deferral exactly as before. Also normalises the info string before the oversized highlighter sees it, which is the invariant unslothai#9462's guard test was written to hold, and moves unslothai#9517's open-fence test onto this branch's render shape.
A fence that has opened and not closed is the whole live tail, and the tail is re-lexed on every token. unslothai#9517 took one whole-tail pass out of the repair path; two more remained, one listing the block's completed fences and one locating the terminal fence, and both run a whole-document CommonMark parse per chunk. That is 10x main's per-chunk work on the exact workload unslothai#9517 was written to fix, and it lands in the ordinary assistant answer, which gets no pagination. While a fence is open neither answer can change: CommonMark ends a fenced code block only at a matching closing line or the end of the document, so every earlier fence is settled, the terminal fence's offset cannot move, and the appended characters can only extend one body. Carry both forward and re-parse when a closing line actually arrives, which is once per fence. Last-chunk cost on an unterminated fence, medians over 7 runs: lines 45 90 180 360 720 main (with unslothai#9517) 0.97 1.78 1.75 1.79 1.87 ms this branch 1.54 2.69 3.35 4.87 7.75 ms with this change 0.93 1.71 1.73 1.72 1.93 ms
FENCE_LINE_RE could not match a CRLF fence line, because `.` does not match CR
and `$` without /m does not match before it. So on a CRLF document no fence was
ever re-opened on a continuation page, interior pages rendered fence source as
prose, canonicalCodeSources came back empty, and copy returned 354 of 14,179
characters. DISPLAY_MATH_LINE_RE had the identical defect.
Three more CR-blind assumptions sat behind it. boundaryStateAt split on "\n"
only, so every line still carried its CR. getCompletedCodeFences rejected a
CRLF opening line for the same reason, so the canonical source array stayed
empty even once pagination recognised the fence. And canonicalFenceSource
rebuilt its result with lines.join("\n"), discarding each line's own ending,
which is the byte corruption: an LF opener over a CRLF body copied 6,979 LF
where the source held 7,378 CRLF.
Synthetic scaffolding now joins in the document's own line ending, so a
re-opened fence is homogeneous with the body it re-opens.
On a nine-page CRLF fence document: fence re-opened on 0 of 8 continuation
pages before, 8 of 8 after; canonicalCodeSources empty before, the exact
18,178-character body on every page after.
Ablated at 250K streamed reasoning characters on WebKitGTK 2.50.4, against a concurrent same-commit null control: base 6821 ms worst main-thread freeze, null 6878, the streaming-render rewrite alone 869, plus the plain-code policy 211, plus pagination 79. Pagination is the last 1.9%, and it is the only part with a user-visible cost: selecting the pane returns 4,808 characters with it on against 183,259 with it off, and find-in-page, print, screen-reader access and deep links all lose the unmounted pages. So the module stays, fully wired and tested, and ships off. Off, selectReasoningMarkdownPage returns before pageStart and both boundaryStateAt calls, so the per-publish walk that made total streaming work grow with the square of the trace is not reachable either. Parity with a pagination-free renderer, measured rather than read, by scripts/reasoning-pagination-parity.mjs: 40 cases over ten markdown shapes crossed with streaming/settled and with and without persisted fence provenance. 40 of 40 identical on HTML bytes and on every IncrementalMarkdownCache.update call, which is where pageIsStreaming and pageUsesSourceSlice are consumed and is the only view of the block ids that become React keys. With the flag forced on the same run gives 16 of 40, the 24 failures diverging at byte 55 on the Show more control, so the equality is produced by the flag and not by the harness. Three limits. The control is a reconstruction that shares this tree's real renderers with the pagination control flow removed, not a pre-pagination build; the pre-PR tree also lacks the streaming-render rewrite, so it is the wrong comparand. The canonical-source provider contributes no DOM and is not covered for value identity. And this is react-dom/server static markup, so no hydration, no effects, no CSS, and the pane chrome above MarkdownText is outside it.
|
Took the split on myself as offered, on your branch, so you keep the commits. Four commits now sit on top of Merged main, and resolved the #9462 collision so both mechanisms survive
Checked with The check is sensitive, not decorative. Resolving the same conflict mechanically instead gives One thing fell out of this: Fixed the per-chunk regression on #9517's workload
Neither answer can change while the fence is open. CommonMark ends a fenced code block only at a matching closing line or at the end of the document, so every earlier fence is settled, the terminal fence's offset cannot move, and the appended characters can only extend one body. Both are now carried forward and re-parsed when a closing line actually arrives, which is once per fence. Last-chunk cost on an unterminated fence, medians of 7 runs, same harness driving every tree:
Flat, and on top of main. Fixed the CRLF fence path, which was the data loss
On a nine-page CRLF fence document: the fence re-opened on 0 of 8 continuation pages before and 8 of 8 after, and The Mermaid case turned out to be the same root cause and is covered by the same fix. Put pagination behind a flag, defaulting off
I would rather this landed off than not at all, and off it is genuinely off: Parity with a pagination-free renderer, measured rather than argued, by Three limits worth stating. The control is a reconstruction sharing this tree's real renderers with the pagination control flow removed, not a pre-pagination build, because the pre-PR tree also lacks the streaming-render rewrite and so is the wrong comparand. The canonical-source provider contributes no DOM and is not covered for value identity. And it is What the split actually deliversFresh wave, three arms run concurrently at 250K streamed reasoning characters on WebKitGTK 2.50.4, distinct bundle hashes, same minutes on the same machine:
The null moved 0.05%. The split removes 98.1% of the freeze, slightly better than the 211 ms the ablation predicted, and the pane's DOM is the plain-code-policy shape (3,114 elements, 0 spans) rather than the paginated one. Ctrl+A is fully back: 183,308 characters against base's 183,236, where the full PR carried 4,808. So the split keeps essentially all of your win and drops all of the cost. Known and deferredWith pagination off these are not reachable by users, so I have deliberately not fixed them. They are the list to work through before the flag can be turned on, alongside rebuilding on
I have left the mirror-suppression and provenance commits alone. Splitting those out is your call, not mine. Verification
Thank you for this, genuinely. You found a severe bug that our own benchmarks were structurally unable to see, on the engine our users actually run, and your fix works. Happy to review quickly if you want to change anything in what I pushed. |
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
Lines 1665 to 1667 in 6adc583
When a long open code fence contains footnote-shaped code—such as the common regex literal /[^a-z]/—this context-free test treats it as a Markdown footnote and calls renderFullDocument. That makes fullDocumentMode sticky, so every subsequent token runs remend and parseMarkdownIntoBlocks over the entire growing fence, bypassing the bounded open-fence path and restoring the quadratic parsing/UI stalls this change is intended to prevent. Detect footnotes from parsed Markdown context or exclude fenced-code ranges before switching modes.
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
All three fail identically at 33d65ce, this branch's own head before I merged main into it, so none of them came from the merge. The line-number gutter used text-[13px], which ignores the UI font size preference. text-ui-13 is calc(0.8125rem * var(--ui-font-scale, 1)), so the generated rule is 13.0px at the default root and the gutter does not change, but it now follows the preference like the rest of the UI. getCodeFenceFilename moved out of markdown-text.tsx into streaming-code-policy.ts, where it gained the info-string normalisation, so the download contract stopped finding the extension map in the file it scans. It now asserts the map where the map lives and asserts that the save button still routes through it, which is strictly more than the old pair of substring checks. The queue contract spelled out where the formatter happened to wrap two expressions. This branch's formatter rewrapped both, in opposite directions, without changing a token. Those assertions now compare through a whitespace- collapsed view, so they pin the expression rather than its layout. Five more assertions in the same test have the same brittleness and are left alone; that cleanup should not ride on this PR.
A character class in ordinary code is shaped exactly like a footnote reference: `/[^a-z]/` matches FOOTNOTE_REFERENCE_RE. That test ran over the repaired tail as one string, so a regex literal inside an open code fence was read as a footnote and switched the cache to full-document mode. That mode is sticky, so every later token re-repaired and re-lexed the whole growing reply, which is the quadratic the open-fence path exists to remove, restored by one line of the reply's own code. Fenced code is not Markdown, so the scan now skips fenced lines. Neither pattern can span a newline, so testing per line is exactly the whole-string test with the fenced lines removed, and real footnotes outside a fence still switch modes. Last-chunk cost on an unterminated JavaScript fence, medians of 5, where the only difference between the two corpora is one body line holding a character class: lines 45 90 180 360 720 plain fence 0.81 1.96 1.89 2.01 2.09 ms one character class 0.70 2.02 7.81 31.15 123.83 ms the same, after this 0.76 1.98 1.93 1.90 1.97 ms Reported by Codex review on the pushed branch. The check predates my changes but it defeats them, so it belongs here.
|
Confirmed and fixed in Reproduced before assuming it.
Quadratic, exactly as described, and one line of the reply's own code was enough to trigger it. Fixed by scanning lines and skipping fenced ones rather than testing the repaired tail as one string. Neither pattern can contain a newline, so testing per line is exactly the whole-string test with the fenced lines removed; real footnotes outside a fence still switch to full-document mode. Three tests, all red before the change: the character-class cases, the real-footnote cases, and a streaming test asserting the render epoch stays flat, since entering full-document mode resets the incremental state and bumps it. One limit I have not closed: an inline code span in prose, |
There was a problem hiding this comment.
💡 Codex Review
When a response uses a valid link-reference definition with a label longer than 200 characters and the later reference arrives after enough blocks to be committed, this regex misses the definition. The incremental cache can then move the definition into an independently parsed committed block, so the later reference in the live tail renders as literal text instead of a link. Detect definitions through the parser or support CommonMark's full label limit before allowing the prefix to commit.
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| candidate.phase = "marker"; | ||
| return; | ||
| } | ||
| candidate.invalid = true; |
There was a problem hiding this comment.
Track fenced code inside Markdown containers
When a streamed fence is nested in a block quote or list, its opening line starts with > or a list marker, so this branch immediately invalidates the candidate and never records the published trailing-LF ownership. The renderer still discovers the nested code node through mdast, but after closure or reload its source falls back to the semantic value without that final LF; Copy and Download therefore return different code from the streamed source. Parse container prefixes before evaluating the fence marker.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it reproduces. One correction to the scope: it is block quotes, not containers generally.
Streaming each document a character at a time through AssistantFencedCodeProvenanceTracker, then replaying the recorded record through the cache to get what Copy would return after a reload:
| nesting | ordinals recorded | Copy ends |
|---|---|---|
| top level | [0] |
;\n\n |
block quote, > ```ts |
[] |
;\n |
list marker line, - ```ts |
[] |
;\n |
| indented list content | [0] |
;\n\n |
So the trailing LF really is lost, and Copy and Download return different bytes from the stream. Indented list content is fine, because appendCandidateCharacter already allows up to three spaces of indent; what breaks it is a non-space, non-marker character in the indent phase, which is > and a list marker on the opening line itself.
I am not fixing it here, and I want to be plain about why rather than leave it looking like an oversight. The provenance work is one of the commits I asked publicly to be split out of this PR, and that is @wasimysaid's call, not mine. It also is not a one-line change: making the scanner accept > means the recorded openingOffset and bodyWithSeparator have to keep agreeing with mdast's own node offsets, which is what overlayPersistedFenceProvenance matches on, so a careless widening restores the wrong LF onto the wrong fence. That deserves its own change with its own tests.
Not a performance issue, for the record: this path does not touch the commit boundary or the full-document mode, so unlike the fenced-regex item there is no quadratic hiding behind it.
|
Triage of the ten review items, reacted individually. Everything below was reproduced before I formed a verdict; I have not taken any of them on description alone.
Keep the rendered code page bounded. The separation this asks for is already the code. A 201,801-character single-fence trace at the 8,192 budget gives 25 pages; the worst mounted fence source on any page is 8,175 characters, while the canonical source held for Copy and Download is the full 201,779. The rendered body takes Keep page cuts outside surrogate pairs. Verified as fixed rather than assumed. Display math: a 1,200-line Deferred deliberately. The oversized synthesized table header and the lazy-continuation list state are both real and both still open. They sit in the deferred list in my previous comment, because pagination now ships behind Mirror suppression. The concern is reasonable: text equality alone cannot separate a local-server mirror from a genuine short answer, and |
|
Second item from the latest review, the one in the review body rather than on a line: Recognize full-length CommonMark definition labels, on Correct, and it reproduces. A definition whose label exceeds the regex's 200-character limit, followed by enough prose to clear the rollback window, then a reference:
CommonMark's actual limit is 999 characters, so labels from 201 to 999 are valid and missed, and the reference renders as literal text. This one is not from this PR. There is also a reason to be careful with it beyond scope. Neither of the two new items touches the cache-mode path. The commit boundary and the sticky full-document mode are untouched by both, so there is no second instance of the quadratic that the fenced-regex item turned out to be. |
|
Thanks for the very thorough work here, and sorry for the slow turnaround. I built the merge base ( The parse fix is a real, severe, pre-existing bug
Median of 9, per document size in lines, synthetic stream:
Whole-stream on the pathological arm grows at exponent 2.99 on the merge base and 1.24 on the head. That is 68x at 720 lines and 252x at 1440. I confirmed the sticky The finding:
|
| merge base | head | |
|---|---|---|
| Reasoning fences highlighted, settled after streaming | 60 of 60 | 0 of 60 |
| Shiki spans in the reasoning pane | 4,639 | 0 |
| Mid-stream, on a genuinely unterminated fence | 41 of 41 | 0 of 41 |
| After a cold reload from persisted history | 60 of 60 | 0 of 60 |
| Answer body | 1 of 1 fence, 15 spans | 1 of 1 fence, 15 spans |
The answer body is untouched, exactly as documented. Reverting that one token makes the head content-identical to the merge base across a 1,046,455 character DOM signature, so the entire visible delta in this branch is that single policy. reasoningText differs by exactly 420 newlines and nothing else. A concurrent same-commit null run agreed with itself everywhere except a generation timer, and a deliberate one-byte plain to syntax mutant and a one-pixel padding mutant both score as differences, so the comparator is not blind.
Separate, smaller point
On a fence-free prose reply, where fullDocumentMode never raises on any arm, the head costs about 3.5x to 4.0x the merge base per chunk:
| Whole-stream ms, prose | 90 | 180 | 360 | 720 |
|---|---|---|---|---|
| merge base | 4.58 | 10.17 | 18.56 | 35.47 |
| head | 18.42 | 36.14 | 70.10 | 135.05 |
| ratio | 4.02x | 3.55x | 3.78x | 3.81x |
Head, the baa4c3224 ablation and the null all agree within 2 percent, so this is not the parse fix, it is the rest of the streaming-render-schedule rewrite. Both arms scale linearly, so it is a constant factor and not a complexity change, and in absolute terms it is 0.19 ms against 0.05 ms per chunk, which is very likely invisible. I am flagging it only because nobody has looked at it yet, not as a blocker.
Proposal
Could codeHighlighting sit behind its own flag, separate from REASONING_PAGINATION_ENABLED? That would let us split this cleanly:
- The parse fix and the bounded streaming work, which have no downside I can find. I am happy to take these immediately.
- The plain-code-in-reasoning policy, which is a product decision with a visible cost, gated on its own flag so we can turn it on together with pagination when that is ready.
If you would rather keep it as one PR, that is fine too, but I would want the highlighting flag to exist and to default to the current behaviour until pagination is enabled. Really nice work on the regex bound, that one would have bitten us for a long time.
|
I measured this against its merge base rather than main, on production bundles, with a concurrent null control. Summary first: nothing that sank #9066 is present here, and there is one on-screen change I would block on. CleanNo dependency bump. No content loss. Streaming one turn of 123,206 characters of reasoning plus 34,214 of answer, rendered output is identical between base and head to the character on both channels. A deliberate 15% drop injected into the same rig moves the detector from 0.9929 to 0.8432, so a #9066-style shortfall would have been caught. The completed reasoning pane is unchanged. The one thing I would block onThe summary says normal assistant answers still highlight. Above 16 KiB they do not, and it is permanent rather than deferred. Four answer fences, settled, re-censused after a further 20 seconds of quiet with identical results:
Putting MeasurementThe reasoning-pane mechanism reproduces cleanly against a flat null. At the settled reasoning toggle, mounted elements fall 8,653 to 4,577 at 45K streamed and 19,733 to 7,869 at 250K, with reasoning highlight spans going to exactly zero, while the base-versus-base null is identical to the element. Content is preserved throughout. On the shipped ladder, What I cannot tell you from this: whether it fixes the freeze. studiobench drives Chromium and the freeze is a WebKitGTK phenomenon that was already shown flat on Chromium, so a flat result here is evidence about the instrument, not about the fix. That needs the WebKitGTK rig before any freeze number is quoted. Worth noting #9567 has since landed on main in the same fence branch, so the conflict will want resolving against that. |
|
Merged current
The related boundary and code-fence tests were updated for the combined structure. A follow-up merge also brought in main's duplicate-definition lint changes without conflicts. Verified with the full frontend suite, TypeScript typecheck, 139 focused Python tests, the strict i18n check, and the pagination parity script. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e48dab1386
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const incrementalRender = incrementalCache.update( | ||
| reasoningPage.markdown, | ||
| pageIsStreaming, | ||
| pageUsesSourceSlice ? EMPTY_FENCE_PROVENANCE : persistedTrailingLfOrdinals, | ||
| ); |
There was a problem hiding this comment.
Keep late reference definitions with their references
When a long completed or cold-loaded message places a reference such as [docs][guide] more than eight blocks before its later [guide]: https://... definition, this unconditional cache path commits the reference into a separately parsed block while leaving the definition in the mutable tail. Because PartitionedStreamdownShell renders those blocks independently, the earlier reference can no longer resolve and remains plain text even after completion; previously completed messages bypassed the incremental cache and were parsed as a full document. Either force globally scoped reference-link documents through the full-document path or keep unresolved reference-bearing blocks together with their definitions.
Useful? React with 👍 / 👎.
| continueAfterChunk, | ||
| ); | ||
| if (result) continueAfterChunk(result); |
There was a problem hiding this comment.
Wait for the exact final highlight result
For completed oversized fences whose 512-character preparation steps finish within the code plugin's 250 ms refresh window—commonly the 4–8 KiB range—code.highlight returns an approximate result synchronously while scheduling the exact result through the callback. Treating that approximate value as final calls onReady; the resulting state change then cleans up this effect and sets cancelled, so the later exact callback is ignored and the fence's final tail remains permanently plain rather than highlighted. Only publish the final-prefix result after the exact callback, or distinguish approximate synchronous results from settled ones.
Useful? React with 👍 / 👎.
| const oversized = [...codeFences] | ||
| .filter((fence) => isOversizedStreamingCode(fence.source.length)) |
There was a problem hiding this comment.
Preserve Mermaid rendering for oversized fences
When a completed Mermaid fence reaches the 4 KiB oversized threshold, this unconditional filter rewrites its language to unsloth-oversized-code. Although StreamdownBlockContent still enters the Mermaid branch based on the original content, the <Block> receives the rewritten Markdown, so Streamdown invokes PersistentOversizedCodeRenderer instead of the Mermaid plugin and the user gets a plain code block rather than the diagram. Exclude Mermaid fences from this rewrite or provide a bounded Mermaid-specific path.
Useful? React with 👍 / 👎.
|
Status update, since this has been open a while and most of the work on it has been happening on our side rather than yours. Where it stands. We split the branch four ways to score each part against scope:
The part I owe you a correction on. Piece 2 was held on the grounds that our benchmark venue could not load the main thread, so a flat result there was uninformative. That reasoning was wrong. The venue could not load the thread in its streaming windows, and I generalised that to the whole venue. The action windows load fine and always did: on today's main at 100K, toggling the reasoning pane still measures 26.4 fps with 80.4% of the main thread busy, 942 ms blocked and a 475 ms worst frame. That is the exact symptom this PR set out to fix, and it is still there. So piece 2 is being re-scored against that window now, on the current corpus rather than the older heavier one. If it moves that number it lands, and the hold was simply my error costing you time. One measurement note in case it is useful to you. An apparent 45K regression we saw at 4 reps (1.136, confidence interval excluding 1.0) reversed sign at 8 reps to 0.984. It was a single 112.5 ms outlier in one cell. Worth knowing if you were seeing similar noise. Separately, thank you for #9473, which is merged. Nothing is needed from you here. I will report the piece 2 result either way, and whatever lands will credit you. |
|
Final measurement result, and a clear answer rather than another hold. Piece 2 does not show a benefit. Three independent measurements, the last one in the engine Studio actually ships on Linux, at the rung where the defect demonstrably exists. The last run is the one that matters, because the earlier two could fairly have been dismissed as the wrong venue:
Real WebKitGTK 2.52.3 on an AMD gfx1151, r500K. Scroll rep spreads were 0.1 and 0.2 fps, so 1.069x is flat against the floor. The base arm sits at 2.4 fps at 94% busy, which means this is not a vacuous pass: the defect is present in the base and the change does not move it. Method, so you can check it rather than take my word. Both arms are your merge base One number I am deliberately not claiming: the stream phase read 0.589x, and that is not a regression. The base arm's own two reps disagree by 3.6 fps (5.4 and 1.8), a spread far wider than the gap between arms. That phase is too noisy at this rung to support a claim in either direction. Why this result is consistent rather than surprising. We attributed the long-context collapse while this was running. The dominant cost at 500K is style and layout over offscreen settled content: roughly 335 deferred code fences, each upgrade forcing a style recalc across a 357,000-element document, 718 recalc passes against 37 with the deferral disabled. Piece 2 partitions streaming from settled rendering. It is aimed at a real thing, but not at the thing that dominates this rung. On the rest of the branch, so you know where it stands:
I am going to close this. Not because the work was poor, and not because you were slow: the branch spent five days with us while we took it over, split it, and measured it, and one of those holds was on a premise of mine that turned out to be wrong. If you want to take any single piece forward on its own, particularly the fidelity work, I will review it properly and quickly. Thank you for the branch and for #9473, which is merged. |
|
Correcting my close-out on this, because it was wrong in a way that matters. I closed this as having no measured benefit. That claim covered all four pieces, but every test behind it measured only the streaming render schedule, on scroll and streaming windows. Reasoning pagination was never in any arm. I dropped it on the grounds that it ships behind a disabled flag and had no measurement, which is circular: the flag is a one-line constant and can be flipped for a measurement arm. Since then I have measured it on a self-hosted gfx1151 runner, real WebKitGTK 2.52.3, production bundles, one pinned instrument across all arms, corpus fixed, arms interleaved, jam control resolving at 75%. On
Repetition spread 0.2 fps. Reasoning characters mounted drop 210,629 to 45,747. At 500K the worst frame goes 15,778 to 1,979 ms. Two notes on why this read flat for so long, both my fault rather than yours. Your ablation in 6adc583 got there before I did, and it is better work than my first pass at the same question. Base 6821 ms, the streaming render rewrite alone 869, plus the plain code policy 211, plus pagination 79, against a concurrent same-commit null. Your parity harness reporting 40 of 40 identical with the flag off and 16 of 40 with it forced on is a positive control, and it is what makes the equality claim mean something. Your reason for defaulting it off also holds up independently. I measured find-in-page finding 2 of 21 probe strings with pagination on, against 21 of 21 off, and copy carrying 224,866 of 394,060 characters. That matches your 4,808 against 183,259 on selection, and you named print, screen-reader access and deep links, which I had not tested. So the feature is not shippable enabled as written, and you were right to ship it off. What I am chasing now, which your commit message pointed me at: the win may not come from dropping syntax highlighting at all. Setting I should not have closed this on a verdict that quantified over pieces I had not tested, and I should not have left it closed while you were still pushing to it. Happy to reopen if you want to keep going, or to carry the work forward with credit to you if you would rather not. Either way the analysis in 6adc583 stands on its own. |
* fix(studio): bound long reasoning without changing short traces Adapt the reasoning-only windowing direction validated in #9477. Keep full canonical copy and ordinary assistant rendering, with stable latest/earlier page navigation and a bounded oversized-fence fallback. * fix(studio): keep reasoning navigation clear of scrolling text * fix(studio): scope reasoning selection and preserve HTML tool context * fix(studio): preserve reasoning documents and return to live tail * Fix retained reasoning content when changing pages --------- Co-authored-by: Etherll <[email protected]>

Summary
Long thinking traces eventually made Studio's real Tauri/WebKit UI effectively unusable: the live reasoning DOM and repeated Markdown work grew with the entire trace, dropping to single-digit FPS and multi-second click latency. This PR keeps the rich-thinking UX while putting hard bounds on work per publish and work mounted in the DOM.
The final design:
Show more/Show lessnavigation instead of mounting the full traceApproaches tried
Show morestill mounted 100K+ characters and reintroduced a freeze.LibreChat/OpenWebUI-style throttling and
ox-contentwere considered. Their ideas informed cadence/windowing, but replacing Streamdown was not adopted because Studio also depends on assistant-ui integration, KaTeX, Mermaid, HTML artifacts, code actions, and persisted message semantics.Native performance evidence
Real desktop run through
tauri-driver+WebKitWebDriver:UD-Q2_K_XLFive backward and five forward reasoning-page transitions completed in 20–81 ms, stayed within the DOM budget, invoked no Shiki work, and returned to the exact latest page.
Rendered reasoning page (rich Markdown, plain fenced code, bounded page)
Real native Tauri/WebKit stream
Channel-integrity check
The final persisted real-inference message contained separate channels:
Full reasoning Copy continues to use the complete canonical thought even though only one page is mounted.
Verification
LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 npm test— 4,143/4,143 passednpm run typecheck— passednpm run i18n:check:strict— passedCI=false npx tauri build --debug --no-bundle— passedCommit structure
fix(studio): preserve streamed assistant channel fidelityperf(studio): bound streamed markdown rendering worktest(studio): add long-stream performance coverage