Skip to content

Studio: render code blocks far from the viewport as plain text, behind a flag defaulting off - #9386

Closed
danielhanchen wants to merge 1 commit into
mainfrom
studio/viewport-gated-highlight
Closed

danielhanchen wants to merge 1 commit into
mainfrom
studio/viewport-gated-highlight

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What is actually in the DOM

At the 100K rung a Studio thread is 63,180 elements, and 42,077 of them are Shiki syntax-highlight token spans. That is 67% of the whole document, produced by only 57 code blocks, at 4.69 characters per span.

Interactions against that standing DOM collapse:

Interaction fps
reasoning_toggle 2.7
select_all_copy 5.6
streaming ~60

Streaming is fine. It is the standing document that is slow, and two thirds of it is colour on code the user is not looking at.

The change

A code block far from the viewport renders as plain text, one token per line. A block inside the viewport plus a 2,000 px buffer gets its full set of Shiki tokens, and a block that comes back into that band is re-highlighted.

Plain is not a new render mode. plainLine was already in code-plugin.ts, already used for the tail of a streaming fence, so this reuses the drawing path the plugin has always had for uncoloured code.

Three new files, all under studio/frontend/src/components/assistant-ui/:

  • code-highlight-gate.ts, the decision, pure. No DOM, no React, no timers: geometry is pushed in, now is passed in. Both early returns fail open towards colour, so a block that is streaming or that nothing has measured yet stays highlighted.
  • code-highlight-viewport.ts, the DOM half. It only measures and reports positions.
  • thread-feature-flags.ts, the flag.

code-plugin.ts gains an optional gate option. With no gate it takes the exact path it always had, every return is the object it always returned, and no attribute is stamped on any token.

Layout neutrality, measured

Measured on the real 57-fence corpus in Chromium at 1280x900, swapping every block to plain:

Highlighted Plain
Token spans 42,134 2,793 (-93.4%)
Document height 30,650 px 30,650 px (delta 0)
Max block height delta 0.0 px
Max block top delta 0 px
Blocks moved or resized 0 of 57

Line element counts identical, code text identical. This holds by construction rather than by luck: the plain lines are derived from the tokenized result, not re-split from the source, so the line count and the per-line text are equal, and <pre> does not wrap, so a block's height is its line count times its line height.

Selection text is byte-identical across both arms: 102,394 characters, sha 3050450b0f4c82eb on each side. window.find returns exactly 1 hit on both arms for five needles, including ones Shiki splits across several coloured spans.

Why the buffer is 2,000 px

Sized from the measured re-highlight latency rather than picked round. Re-highlighting one fence, over all 57 content fences at the 100K rung:

median   12.65 ms
p90      28.54 ms
max      39.39 ms

2,000 px holds about 3.5 blocks, so refilling the buffer costs about 100 ms at p90. Crossing 2,000 px takes 400 ms at 5,000 px/s, a hard trackpad flick. Raising the buffer hides uncoloured code under faster scrolling and stands more spans in the document. Lowering it does the reverse. Nothing else in the mechanism trades those two against each other.

Limitations, stated plainly

Every block is highlighted once before it can be downgraded. highlight() receives only {code, language, themes}, and the element has to exist before its position can be measured. So this removes standing spans and saves no tokenization work. If the cost you care about is the tokenizer, this is not the change for it.

Fence identity is per content, not per element. Two identical code blocks share one fence and are therefore gated together.

No A/B has been run yet. There is no interaction-timing result here and this PR does not claim one. Every number above is a DOM and geometry measurement. The A/B is running separately and will be posted as a follow-up comment on this PR.

That last point is why the flag ships off:

export const VIEWPORT_GATED_CODE_HIGHLIGHTING_ENABLED = false;

While it is false no gate is built, createCodePlugin is called with no gate at all, and the flag-off DOM is unchanged down to the absence of a single attribute. Flipping that one constant is the only edit needed to enable it.

Tests

npm test in studio/frontend: 4,108 pass, 0 fail, 0 skipped. That includes 21 new tests (11 in tests/code-highlight-gate.test.ts, 10 in tests/code-plugin-viewport-gating.test.ts) and all 39 pre-existing code-plugin tests, unchanged.

The new decision tests are written against ways of getting the rule backwards that were reachable while this was built, since a block decoloured under a scrolling user would be a worse bug than the slow DOM this exists to shrink. The plugin tests assert line count and per-line text equal on every swap, which is the property that makes the swap layout-neutral.

npm run typecheck and npm run build are green on this branch.

A code block far from the viewport renders as plain text, one token per line,
and is re-highlighted when it comes back within CODE_HIGHLIGHT_BUFFER_PX. Plain
is the render mode the plugin already had for a streaming tail; nothing new is
invented to draw it.

At the 100K rung 42,134 of the thread's standing spans come from 57 code blocks.
Measured in chromium over the same 57 fences, swapping every one of them to
plain takes that to 2,793 with the document height unchanged at 30,650px, no
block moving or resizing by any amount, and the selected text byte-identical.

The mechanism is off by default: with the flag false no gate is built, the
plugin takes the path it always had, and nothing is stamped into the DOM.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7753643b64

ℹ️ 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".

Comment on lines +328 to +330
for (const subscriber of fence.subscribers)
subscriberOwners.delete(subscriber);
fence.subscribers.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep mounted subscribers alive across cache eviction

When viewport gating is enabled and a mounted fence is evicted after exceeding MAX_FENCES or MAX_CACHED_CHARACTERS, clearing its subscribers and removing fencesById permanently disconnects that block from gate updates. This is especially visible if the block was plain when evicted: scrolling it back into view causes gate.place transitions, but the plugin can no longer publish highlighted tokens, so it remains uncoloured until some unrelated code change invokes highlight() again. Cache eviction must discard tokenization state without discarding the update channel for still-mounted blocks.

Useful? React with 👍 / 👎.

gate.place(id, { top: box.top, bottom: box.bottom });
}
},
{ root: null, rootMargin: `${gate.bufferPx}px 0px`, threshold: 0 },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Observe the actual thread scroll viewport

The inspected Studio thread scrolls inside the nested .aui-thread-viewport element (thread.tsx:1726-1734), but this observer uses the document viewport as its root. rootMargin expands only the root intersection rectangle; the intervening overflow-y-auto scrollport still clips the target, so after an initial far-away measurement no callback is emitted when a block crosses the intended 2,000 px buffer. The callback arrives only as the block enters the visible scrollport, making re-tokenization happen on screen and defeating the buffer intended to prevent plain-code flashes and scrolling stalls.

Useful? React with 👍 / 👎.

Comment on lines +190 to +193
markStreaming: (id, at = now()) => {
const entry = entryFor(id);
entry.lastGrowthAt = at;
settle(id, entry, at);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Notify subscribers when the streaming grace expires

If a user scrolls away while a code block is streaming, markStreaming transitions the already-measured far block to highlighted, but nothing calls settle when the grace period later expires. Reading the clock inside mode() is insufficient because a completed Streamdown block does not call highlight() again, and an offscreen observer target need not produce another geometry event. Such blocks therefore retain all Shiki spans indefinitely, undermining the DOM reduction for long generated replies; expiry needs to schedule a transition notification rather than relying on a future read.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Measured: negative result, the prediction was wrong

Protocol: studiobench standard tier, 100K rung, 4 repetitions split into 2 shards, with an in-band null control running concurrently under the same load, scored through the three gates (per-metric detection floor = max(|null delta|, null spread), sign consistency across every paired ratio, and the effect must exceed its own scatter).

Predicted from the dose-response ablation: reasoning_toggle.close_ms 812 -> 365 ms, about -55%.

Measured with the flag on, same protocol:

Metric Predicted Measured Spread Floor
reasoning_toggle.close_ms -55% +12.7% SLOWER 2.9% 4.7%

That is a regression, not a null. It clears the floor and it is sign consistent across every paired ratio.

Why the prediction failed

This is the useful part. The ablation and this implementation are not the same intervention.

The ablation coalesced spans permanently. This PR re-gates blocks as they enter and leave the viewport. Closing a reasoning pane makes blocks leave view, so on this implementation closing a pane generates gating and re-highlighting work rather than saving it. The mechanism that produced the ablation's win is not the mechanism that is built here, and treating the two as interchangeable is what produced a -55% prediction for a change that measures +12.7%.

What the ablation did establish

That result stands on its own and is unaffected by the above. Span coalescing is causal for close_ms and for copy, and is a measured null for open_ms:

Finding Evidence
Causal for close_ms R2 0.997, +11.31 ms per 1,000 spans (note 339 ms of the 812 ms is intercept)
Causal for copy 2,676 -> 912 ms, 2.9x
Measured NULL for open_ms flat while resting span count fell 15x; bound on any per-span term under 0.00426 ms/span

The open_ms null is worth keeping in view: open_ms is 2,067 ms of a 2,873 ms action and the only superlinear metric in the benchmark, so it is the one most worth attacking, and span count is not what drives it.

Conclusion

The flag stays off. The mechanism as built is not a performance improvement on the metric it was aimed at, and it needs rework before it is worth measuring again.

The geometry results in the PR body are unaffected and still stand: spans 42,134 -> 2,793, document height delta 0, 0 of 57 blocks moved or resized, selection byte-identical, find-in-page unaffected.

@danielhanchen

Copy link
Copy Markdown
Member Author

Closing this. The measurement came back against it.

Standard tier, 100K rung, 4 repetitions in 2 shards, with an in-band null control running
concurrently under the same load, scored through the three gates:

metric delta spread floor
reasoning_toggle.close_ms +12.7% SLOWER 2.9% 4.7%

That is the one metric this change was built to improve, and it clears the floor in the wrong
direction with consistent sign.

Why the prediction failed, since that is the part worth keeping. The dose-response ablation that
motivated this coalesced spans permanently. This PR instead re-gates blocks as they enter and
leave the viewport, so collapsing a reasoning pane pushes blocks out of view and generates gating
and re-highlighting work rather than saving it. The ablation and the implementation are not the
same intervention and I should not have treated them as interchangeable.

What the ablation did establish still stands on its own, and is worth recording for whoever picks
this up next:

  • Span coalescing is causal for close_ms: R2 0.997, +11.31 ms per 1,000 spans, though 339 ms of
    the 812 ms is intercept, so no amount of span removal takes that action below about a third of a
    second.
  • It is causal for copy: 2,676 ms to 912 ms, 2.9x.
  • It is a measured null for open_ms, which is 2,067 ms of a 2,873 ms action and the only
    superlinear metric in the benchmark. Flat while resting span count fell 15x, with the bound on
    any per-span term under 0.00426 ms/span.

The geometry results in the description are unaffected and remain correct: spans 42,134 to 2,793,
document height delta 0, 0 of 57 blocks moved or resized, selection byte-identical, find-in-page
unaffected.

The mechanism the profile actually names for this action is a synchronous full-document layout,
355.9 ms with 67 dirty objects against 195,631 total, because Blink lays out every object rather
than only the dirty ones. That is a different fix and it is being worked separately.

Reopen if the re-gating cost can be removed; the branch is kept.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants