Skip to content

chore(studio): give Radix portals a container that is not document.body - #9061

Closed
danielhanchen wants to merge 14 commits into
mainfrom
perf-portal-host
Closed

danielhanchen wants to merge 14 commits into
mainfrom
perf-portal-host

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What

Radix's Portal defaults its container to document.body. React attaches its full delegated event listener set to the container of every portal, the first time a portal targets it, and never removes it. So the first time any menu, tooltip, popover, dialog or select opens, document.body acquires a second React event root, and because <body> is an ancestor of the whole application, every event anywhere in the app is dispatched twice from then on: once at #root and once at <body>.

Measured on a 300K character chat thread, document.body goes from 1 event listener type to 85 the first time a menu opens, and stays there for the life of the tab.

This routes every portal at one shared display: contents div appended to <body> instead. The host generates no box, so its children participate in the body stacking context exactly as they did when Radix appended them to <body> directly, and React attaches its listener set to the div rather than to <body>.

The action bar menu is assistant-ui's, not components/ui/dropdown-menu.tsx's, so routing Studio's own wrappers does not reach it. It accepts portalProps, which is spread straight onto its Portal.

This is not a performance change, and it was measured

It was built as one. It is not one, and the PR should not be read as one.

Chromium, 300K characters of thread (43,422 DOM nodes, 110 assistant messages), fresh page per arm, medians of 3, identical 20-step scroll gesture after a menu:

gesture ms frames over 33 ms long tasks
without this change 1543.6 11 11
with this change 1527.0 11 11

The trace's caller attribution is the same on both sides: 36 React commits at react-dom_client.js:9077. The census does move, 85 listener types back to 1, so the change does what it says. The cost simply was not coming from there.

The scroll cost on a heavy thread is driven by the element under a stationary cursor changing as content scrolls past it, one pointerover per scroll step at about 63 ms of React work apiece. That is live work and has nothing to do with which container a portal uses. A separate change corrects the harness that made this look like a menu problem.

So the case here is hygiene: one app-wide React event root instead of two, and floating surfaces that stop double-dispatching every event in the application.

Behaviour, not just listener counts

This is event plumbing, so a regression would be invisible in a screenshot and very visible in use. tests/studio/portal_host_behaviour.py asserts, per engine:

control this branch
menu content inside the portal host false true
popper wrapper's parent is <body> true false
document.body listener types after a menu 1 to 85 1 to 1
menu rect (chromium) x470 y689 w187 h120 identical
all menu items hit testable via elementFromPoint true true
Escape dismisses true true
one outside click dismisses without firing the neighbour button true true

Confirmed on chromium, webkit and firefox. That last row is #9051's swallowDismissingClick contract, which this must not break, and does not.

Not covered

The tooltip arm of the behaviour test reports appeared: false on all three engines on both the control and this branch, because synthetic pointer events do not satisfy Radix's tooltip open delay. It is equally uninformative on both sides, so it neither supports nor contradicts this change. Tooltips are the most frequently opened portal in the app and are worth a real-pointer check before this is relied on.

danielhanchen and others added 14 commits August 16, 2026 15:48
…ontent

Users report Studio and Desktop going sluggish after long generations with
code cells and text. That is a statement about content volume, so the new
harness varies characters of thread content rather than message count, and
the fixture carries the mix the report names: prose, large code fences, tool
calls with collapsible output, code-execution result panes, HTML and canvas
artifacts, and inline images.

The primary metrics are DOM-observable and wall-clock, because Unsloth
Desktop is a Tauri webview and not Chromium. PerformanceObserver accepts
type longtask on WebKit 26.5 and Firefox 153 without throwing and then never
fires, so support is read from supportedEntryTypes; CDP counters are recorded
alongside and labelled Chromium-only.
…ne chatter

Re-opening the thread throws away every highlighted fence, so repetitions 2
and 3 were measuring a thread that was still building itself: on Chromium at
300K the scroll gesture read 667ms on the first repetition and 1100ms on the
two after it, and the difference was the re-highlighting.

Firefox 153 emits exactly two scroll-anchoring notices per run at every size.
A warning count that grows with the thread still fails; a constant one does
not, or the harness could never report a Gecko number.
…ng floored metrics

Measured from the end of the gesture, time to settle reads ~50ms at every
size on every engine, because the answer is then three frames, which is the
minimum the loop can return. From the start of the action it is what a user
waits.

A count that goes 0 to 4 has answered the question and counts as
discriminating. A floored timing that is zero or negative at the smallest
size has not: it says the action resolves inside one frame there, which is a
metric with no room to move.
A WebKit page that ran out of memory at 300K on a loaded machine took eight
good measurements down with it. The cell is now recorded as crashed, the run
continues, and the verdict still fails on it.
…cess can

On a macos-14 runner Chromium finished all three sizes in 90 seconds and then
Playwright's WebKit wedged at the smallest size and never came back, which
cost the whole matrix. page.evaluate and browser.new_page have no timeout,
and SIGALRM does not help: the sync API blocks the main thread inside a
greenlet, so the exception lands in the driver and the caller never resumes.
The process boundary is the only bound that works, so the docstring says to
drive one engine per invocation under an external timeout.
A modal Radix menu parks pointer-events: none on <body> while it is open.
pointer-events is inherited, so that single write invalidates computed style
for the whole mounted subtree underneath it. On a long chat thread that
subtree is the thread, so opening a menu costs a full-document style
recalculation that scales with the thread rather than with the menu.

Ten menus move to modal={false}. Dialogs, alert dialogs and sheets keep
modal semantics, which are correct and wanted there.

Dropping the shield also drops the click it used to absorb, so a single
click on a control beside an open menu would both dismiss the menu and fire
that control. In the assistant action bar the neighbours are Refresh and an
unconfirmed Delete message. swallowDismissingClick restores just the
absorbed click, so dismissal still costs exactly one click.

Message action menu, chromium, 25K to 300K characters, medians of 3:
open+close 345.2 -> 3291 ms becomes 62.2 -> 73.8 ms, and the harness growth
verdict goes from 10.44x DISCRIMINATES to flat.
React attaches its full delegated event listener set to the container of every
portal, the first time a portal targets it, and never removes it. Radix's Portal
defaults that container to document.body, so the first time any menu, tooltip,
popover, dialog or select opens, document.body acquires a second React event root.
Because body is an ancestor of the whole application, every event anywhere in the
app is dispatched twice from then on, once at #root and once at body.

Measured on the chat thread, document.body goes from 1 event listener type to 85
the first time a menu opens, and stays there for the life of the tab. This routes
every portal at one shared `display: contents` div instead, which keeps the
floating surface at the same position in the box tree and takes the census back
to 1.

This was built as a performance fix and it is not one. Measured for exactly that
and found to buy nothing: see the file comment and the PR body for the numbers.
It is kept on hygiene grounds only and must not be cited in a performance claim.

The action bar menu is assistant-ui's rather than components/ui/dropdown-menu.tsx's,
so routing Studio's own wrappers does not reach it; it takes portalProps, which is
spread onto its Portal.

tests/studio/portal_host_behaviour.py asserts the things a screenshot cannot: that
every menu item is hit testable via elementFromPoint, that Escape dismisses, and
that one outside click dismisses without actuating the control underneath, which is
the swallowDismissingClick contract from #9051.

@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: ebb963974b

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

Comment on lines +440 to +443
const watcher = new MutationObserver(() => {
open = Boolean(document.querySelector(".aui-action-bar-more-content"));
});
watcher.observe(document.body, { childList: true, subtree: false });

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 menu mutations beneath the portal host

With this commit, .aui-action-bar-more-content is inserted and removed beneath #unsloth-portal-host, not as a direct child of document.body. Because the host is created during ordinary wrapper rendering, this subtree: false observer receives neither mutation, so open remains false, settle(true) runs until the 120-second timeout, and the newly added CI smoke reports openMs: null and fails. Observe the portal host itself (or otherwise detect its child mutations) instead.

Useful? React with 👍 / 👎.

Comment on lines +735 to +738
page.locator('[data-role="assistant"]').last.hover(timeout = ACTION_TIMEOUT_MS)
rep["delete"] = run_action(page, cdp, "delete", DELETE_JS, SETTLE_TIMEOUT_MS)

rep["reopen"] = run_action(

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 Restore the seeded thread between repetitions

When the default SMOKE_HEAVY_REPEATS=3 is used, this permanently deletes the last assistant message from the local runtime before reopen merely remounts that now-smaller repository. Repetitions two and three therefore measure progressively smaller threads with the final content kind missing, while the fixture census is only taken before the loop; the reported medians and growth curves no longer represent repeated measurements of the requested fixture. Re-import or otherwise restore the seeded repository before each repetition.

Useful? React with 👍 / 👎.

Comment on lines +40 to +41
container={getPortalHost()}
{...props}

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 Preserve the portal-host fallback when container is undefined

The later {...props} overrides this fallback, and DialogContent always invokes the wrapper as <DialogPortal container={resolvedContainer ?? undefined}>; consequently the common no-container case explicitly replaces getPortalHost() with undefined and Radix still portals dialogs to document.body. SheetPortal has the same issue because SheetContent always passes container={container ?? undefined}. Resolve props.container ?? getPortalHost() or spread props before assigning the fallback so these surfaces actually use the shared host.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Closing this. It buys nothing measurable and it breaks a control, so it does not clear the bar.

What broke

Chat UI Tests, run 31993319977, job 95280549461:

FAIL: Voice model picker did not wheel-scroll: Locator.click timeout 60000ms
waiting for get_by_test_id("dictation-engine-model")
locator resolved to <div role="option" data-slot="select-item" data-testid="dictation-engine-model" ...>
element is visible, enabled and stable
<div data-state="open" aria-hidden="true" data-slot="dialog-overlay"
     class="... inset-0 isolate z-50 fixed bg-black/30 ..."> intercepts pointer events

119 retries over 60 seconds, every one blocked by the same overlay. Visible, enabled, stable and unclickable is the signature of a hit test eaten by an overlay, not of a hidden node. A Select inside the settings surface becomes unusable. That is user-visible and it is not a test artefact.

The path is components/ui/select.tsx, which resolves its container as container ?? dialogContainer ?? .... useDialogPortalContainer() returns null outside a DialogContent, so this Select previously fell through to undefined, which is document.body, and landed after dialog-overlay in DOM order. Both carry z-50, so DOM order was what put the Select on top. Routing it into the shared host changed that order and the overlay now wins.

Why not just fix the stacking

Because the benefit on the other side of the ledger is zero, measured, and already stated in the description: 1543.6 ms against 1527.0 ms, same 11 frames over 33 ms, same 11 long tasks, same 36 React commits. The scroll cost it was built to remove turned out to be driven by the element under a stationary cursor changing as content scrolls, which has nothing to do with portal containers.

And the change cannot be usefully narrowed. React attaches its delegated listener set to document.body the first time ANY portal targets it, so leaving dialogs, sheets or selects on body to avoid the stacking problem puts the census straight back to 85 listener types and gives up the only thing this was for. It is all portals or no benefit at all.

So the choice is between fighting z-index and isolate across every dialog, sheet and popover in the app for a null result, or closing it. Closing it.

Worth keeping from this

The stacking that broke was already fragile before this branch. dialog-overlay is fixed inset-0 isolate z-50 and the Select content is also z-50, so today a Select opened outside a DialogContent paints above the overlay only because it happens to be appended to document.body later. Nothing expresses that ordering; it is an accident of insertion order between two equal z-index elements, and anything that reorders body's children re-breaks it. This branch was just the thing that perturbed it first. That is worth a separate look on its own terms.

Two things for whoever picks up portal work later:

  1. A three-engine behaviour matrix over the message action menu, which is what this branch shipped, is not sufficient coverage. The menu is not inside a Dialog, and the container swap only changes the answer where an overlay is involved. Any future change here needs a portal opened from inside a Dialog or Sheet in the matrix.
  2. An intentionally null-result change still found a live bug in the app's portal stacking. That is the useful part of having opened it.

tests/studio/portal_host_behaviour.py on this branch is the part worth salvaging if anyone returns to this: it asserts hit-testability via elementFromPoint, dismissal, and that one outside click does not actuate the control underneath, which is the swallowDismissingClick contract from #9051.

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.

1 participant