Repository navigation
perf(studio): take chat menus off the body modal layer - #9051
danielhanchen wants to merge 50 commits into
Conversation
…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.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3d92b381e2
ℹ️ 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 frame = () => { | ||
| const now = performance.now(); | ||
| this.frames.push(now - lastFrame); | ||
| lastFrame = now; | ||
| if (this.running) nativeRaf(frame); |
There was a problem hiding this comment.
Isolate each recorder run from pending callbacks
Callbacks queued by a completed action can fire after the next begin() sets the shared running flag back to true, at which point the old rAF loop schedules itself again alongside the new loop; the timeout loop has the same race. In consecutive run_action calls—especially when a heavy page delays the next frame—later measurements therefore accumulate duplicate recorders and can include the idle interval between actions in worst_frame_ms or longest_stall_ms, corrupting the reported performance curve. Associate callbacks with a per-run generation or explicitly cancel them when ending a run.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The code observation is right and the impact claim is wrong, so this is a thumbs down rather than a fix.
The race is real in isolation. end() only clears running, and a loop notices that on its next callback, so a callback still in flight when the next begin() arrives would see running true again. Provoked deliberately on a blank page with this harness's own recorder and the two calls back to back, window two inherited 36 frame samples and 49 stall samples and ran four live rAF loops and two live timer loops. So the mechanism is exactly as described.
It does not happen in this harness, on any engine. Generation-tagging every sample across 252 measured action windows, which is 6 chromium arms times 2 sizes times 3 repetitions times 6 actions, plus 18 firefox and 18 webkit:
- foreign, stale-generation frame samples: 0
- foreign stall samples: 0
- max live rAF loops and max live timer loops: (1, 1) in 252 of 252 windows
The reason is that run_action puts a CDP Performance.getMetrics, a page.evaluate that awaits setTimeout(0) inside long_task_summary, and a reset_long_tasks between end() and the next begin(). That is always longer than a frame and than the timer clamp, so the stale loops always observe running === false and retire. Firefox and WebKit have no CDP session at all and still showed zero, so the margin does not depend on it.
The specific harm does not occur even when provoked: in that blank-page run worst_frame_ms was 17.0 against 16.9 with the foreign samples excluded. A stale callback's lastFrame is one frame old, not one idle-gap old, so it pushes about 16.7 ms rather than the interval between actions. worst_frame_ms and longest_stall_ms in this PR are unaffected.
I wrote the generation guard and then took it back out. Adding two lines to a test harness to close a hole that 252 windows say cannot open is maintenance we would carry forever for no reachable defect.
A guard armed from Radix's onPointerDownOutside and disarmed by a fixed 300 ms timer misses three of the four ways a person dismisses a menu. Measured on the heavy-thread smoke page by pressing the adjacent unconfirmed Delete message button with the action bar menu open: gesture pre-PR before after quick press and release safe safe safe press held 600 ms safe DELETED safe press, busy main thread safe DELETED safe touch tap safe DELETED safe held reproduces on chromium, webkit and firefox; touch on chromium and webkit (Playwright Firefox has no touch support). The pre-PR column is the same tree with the action bar menu back on the body modal layer. Two causes. The timer is gone before the browser synthesises click on release, and a press can be held for as long as the user likes. And on touch, usePointerDownOutside in react-dismissable-layer 1.1.11 defers to the resulting click and listens on ownerDocument in the bubble phase, so React's root container has already run the control's onClick before Radix calls us; a guard armed there cannot swallow the click that armed it. So watch pointerdown directly, on document, in the capture phase, which is ahead of both. Arm state is module level because the dismissing pointerdown unmounts the content synchronously, so anything torn down in the effect cleanup would be gone before the click arrives. Disarmed by that click, a pointercancel, a keydown, or the next gesture, never by a deadline. Adds the four dismissal variants plus two over-swallow checks (a menu item selection and an unrelated second click must still land) as a CI gate.
Three defects in the harness that produced this PR's numbers, all of which
make the table claim more than it measured.
Re-seed between repetitions. The delete action removes the last assistant
message from the runtime and the re-open path deliberately preserves that
runtime, so repetition N measured a thread N-1 messages shorter than the one
the pre-action census passed, and a different content mix, because the message
it takes is a different kind each time. Measured on chromium: 300K went
220 to 219 to 218 messages and 35086 to 34438 highlighted tokens over the
default three repetitions; 25K, where one cycle is the whole fixture, went
20 to 19 to 18 messages and 3216 to 2520 tokens, losing 22 percent of the
highlighting by repetition two and 2 of its 3 images by repetition three. The
harness's own expectedPerCycle image gate would have failed on repetition
three at both sizes, but it is only ever evaluated once, before repetition one.
Re-seeding is not free and the effect is larger than the shrinkage it fixes:
the 300K menu open and close median moves from 71.9 ms to 352.0 ms, because
without it repetitions two and three open a menu on a thread that has already
been through one. Both are honest numbers; only the second is the one the
table says it is reporting.
Stub the fork-count endpoint as {"count":0}. getForkCount reads data.count,
so {} set the count to undefined, and undefined <= 0 is false, so the badge
rendered a pill and a git-branch icon on every message with a mounted action
bar. 110 of them at 300K, which real Studio never shows for an unforked
message. Timing effect is inside the noise floor; the reason to fix it is that
the harness page was not showing the UI it claims to.
Count the repetitions that produced no timing. median() drops None, so an
action that timed out in one repetition was silently dropped and the summary
still reported a median of three. harness_failures only ever read the summary,
so that passed. Record dropped_repetitions and fail on it, and fail when the
per-repetition census disagrees about how many messages were on screen.
…dismissal Two defects in the guard as first written, both found by attacking it rather than by re-running the case it already passed. The armed window had no upper bound. Plenty of dismissing gestures never become a click: measured on chromium, a right click outside an open menu raises contextmenu instead, and the swallower survived to eat the user's next real left click 900 ms later. That is worse than the fixed deadline it replaced, because a bounded window that occasionally misses is at least attributable, while an unbounded one swallows a click with nothing to associate it with. The window now opens at pointerup rather than at pointerdown, so a press held for a minute is still covered and a gesture that produces no click is still bounded, plus a drop on pointercancel, keydown and window blur. And on touch the guard denied Radix its own dismissal. Radix defers touch dismissal to a once click listener on document in the bubble phase, which the capture-phase swallow is exactly what stops. A tap on a focusable control still closed the menu, via useFocusOutside, which is why the first version looked correct; a tap on plain thread background left the menu open on chromium and webkit. Radix's deferred handler takes no arguments and ignores the click entirely, so re-raising a bare non-bubbling click at document releases it. The probe now covers nine cases and asserts the menu actually closed, which it previously recorded and ignored. Its neutral spot is grid-searched for a genuinely non-focusable element and it fails rather than falling back if none exists: the first run of the touch case silently landed on a button and reported a pass for a case it had not tested.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f4d9f636bb
ℹ️ 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 (api.messageCount() >= before) { ms = performance.now() - reopenStarted; break; } | ||
| await window.__nextPaint(); | ||
| } | ||
| const settleMsTaken = await window.__hv.quiet(settleMs); |
There was a problem hiding this comment.
Wait for highlighting before ending the reopen measurement
When the reopened thread contains async Shiki blocks, __hv.quiet() can declare the page settled after only three clean frames. This file's own wait_for_highlighting_settled() documents that short rAF-based lulls can release at 577 of 3216 tokens and therefore requires five stable reads 250 ms apart. Ending the recorder here leaves the remaining highlighting outside the measured region, so the reopen wall, stall, and frame metrics systematically omit much of the rebuild cost the action claims to measure; keep the recorder running until highlighting is actually stable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The mechanism is real and the re-open window cannot reach it, so this is a thumbs down rather than a change.
The gate is as weak as you say. Measured by reading highlightedTokenCount() at the instant __hv.quiet() releases, on a thread whose fences are being highlighted for the first time:
| engine and size | tokens at the gate | final | highlighting continued for |
|---|---|---|---|
| chromium 25K | 577 | 3216 | 675 to 745 ms |
| chromium 100K | 2312 | 12804 | about 1010 ms |
| webkit 25K | 577 | 3213 | 2.5 to 2.7 s |
That is the same 577 of 3216 wait_for_highlighting_settled cites, arrived at from the other direction.
reopen never presents that condition. It remounts a thread whose fences were already highlighted once, and the token count is back at its final value in the same frame the messages are, before quiet() is called at all. Chromium at 25K, 100K and 300K and WebKit at 25K and 100K: tokens at the gate equal the final count in 10 of 10 windows, and the last token landed 1.6 to 21 ms past the gate.
That holds for the rest of the file as well. Every other measured action runs after wait_for_highlighting_settled, and the re-seed added in a7dda8d for the fixture item on this same file is followed by that same gate, so no measured window in this harness contains cold highlighting.
…and keep the settings preset menu modal on mobile Two more breaks, both found by attacking the change rather than re-running what already passed. A right click outside an open menu raises contextmenu and never a click, so arming for it could only ever eat the user's next left click. Measured on chromium, webkit and firefox: the click after a right-click dismissal was suppressed. The release-anchored bound added in the previous commit shortened that from forever to 500 ms, which is a smaller bug and still a bug; not arming for a gesture that cannot produce a click is the answer. The bound stays, for the cases nobody has enumerated. And the chat settings preset menu could not be opened at all below the mobile breakpoint, where the panel is a Sheet. Its trigger is asChild over a div that contains an input, so with no modal shield the release-click of the opening press lands on that input, focus leaves the portalled content, and a non-modal Radix layer dismisses on focus-outside. Traced on chromium at 420x900 with a MutationObserver and the pointer never moving: the menu mounted at t=33 ms and was gone by t=208 ms. It is modal there again. That costs nothing, because the Sheet has already parked pointer-events:none on the body and there is no second invalidation to save; on desktop the panel renders inline and the menu stays non-modal. The probe's right-click case now fires inside the grace window rather than after it. The version that waited it out passed on a tree that was still eating the click, because it only asked whether a bound existed and not whether the guard should have armed at all.
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
Confirmed on real Unsloth Desktop hardware, not just CIEverything above this comment was Playwright on a CI-class box. This is the same headline re-measured on real Desktop hardware against a frozen upstream control, which is the number I actually wanted before merging. Subjects, frozen: baseline Environment: Linux WebKitGTK 2.52.5, Tauri, RTX PRO 6000, CachyOS, Wayland. CPU throttling disabled, so these are real wall times and not a throttle multiple. Chromium and Firefox ran natively on the host; WebKit could not load ICU 74 natively so all WebKit cells ran serially in one pinned Playwright 1.58.0 Noble container on the same hardware, and are reported in their own lane rather than pooled with the native two. 300K menu open and close, median
Samples are non-overlapping on both natively measured engines. Firefox crossed the study's predeclared spread trigger on the first triplicate, so two extra paired samples were run in reversed order and its comparison is a median of five rather than three. That is why its n is 5 and not 3, and it is the reason the Firefox figure is quotable at all. Smaller sizes, chromium: 25K 228.3 -> 60.7 ms, 100K 764.3 -> 59.7 ms. The non-modal cost is flat in thread size, which is the point of the change: Nothing else movedThe same run measured five other actions at 300K. Reading candidate against baseline, this is the check that the win is not paid for somewhere else:
No regression on any action on any engine. The delete and reopen improvements are small and I am not claiming them; they sit inside the run-to-run spread and this PR has no mechanism that should touch either. Two caveats I am not hiding
|
The five red checks are all inherited from
|
main at bfcaea465 |
#9051 at 9ec6ca630 |
|
|---|---|---|
| Frontend build + bundle sanity | not ok 239 |
not ok 240 |
| Frontend unit tests (Windows) | not ok 239 |
not ok 240 |
| total failing | # fail 1 |
# fail 1 |
The index moves by one only because this branch adds a test file earlier in the ordering. The failure itself is ERR_MODULE_NOT_FOUND resolving the extensionless import ./mmproj-fallback at src/features/chat/utils/image-input-support.ts:7. That import line is byte for byte identical on the merge base, mmproj-fallback.ts is present in the tree, and the last commit to touch that file was #6532. This branch touches neither the file, nor mmproj-fallback.ts, nor queued-model-capabilities.test.ts.
What I am not claiming
I am not claiming these are unimportant, only that they are not this PR's to fix and that fixing them here would hide which branch owns them. The earlier note on this PR attributed the backend red to test_multi_chat_prompt_queue_contract.py; that is now stale. That file passes 11/11 locally at this head, and the real backend failures are the 74 above.
…dio scrubber Two pointers can be down at once, a finger and a mouse on a touchscreen laptop, and only one of them owes the click swallowClick exists to eat. The pointerdown handler already filtered a second pointer's press. Its release was not filtered: startGrace took no event, so a second pointer's pointerup marked the FIRST pointer's gesture as released and started its 500ms bound, and once that expired the held finger's own compatibility click reached the button underneath. Measured on chromium with real CDP touch: holding the unconfirmed Delete message button, pressing and releasing inside the menu with the mouse, then lifting the finger, deleted the message. pointercancel had the same gap. The audio scrubber is a native <input type=range>, which commits on pointerdown, so the press that dismisses a non-modal menu seeks the audio before any click swallow runs. Measured with the composer menu open: currentTime 0 to 4.08s, read before the release. Same shape and same answer as Radix Slider and Select, which were already shielded. useDismissingClickGuard's effect body is extracted to installDismissingClickGuard so the state machine can be driven against a fake document without a renderer, the same reason markNonModalMenuOpen is already exported.
Coordination: the three unreached sidebar menus are a FOLLOW-UP, not part of this PRStating this plainly because I gather the same finding has come up independently in a wider UI performance sweep, and it should not get done twice. I am not fixing these here. They are filed as #9168 with the measurements below, and that issue is the place to do the work. The sites, re-confirmed on this branch at head:
On the packaged production build, same 220-message thread, same run: the patched More menu opens and closes in 38.6 ms, the unpatched "Chat options" menu in 382.6 ms. 9.9x, with modality the only difference between them. So the most expensive menu measured is one this PR does not touch. Why it is deliberately out of scope rather than a two-line addition: the guard is mounted per menu content, not globally, so each additional non-modal menu needs its own Separately, and already in the description: |
Dismissal-guard simulation, re-run at head
|
| cell | result |
|---|---|
touch_hold_second_pointer on firefox, webkit |
SKIP |
touch_hold_second_pointer_grace on firefox, webkit |
SKIP |
A skip is not a pass, and these are 4 absent measurements out of 57. Both cases need a finger held down while a second pointer of a different type acts, and Playwright's Touchscreen exposes only an atomic tap(), so a held finger needs CDP and is chromium-only.
At the merge base, 11 of 19 cases delete a message on chromium, 9 on firefox, 9 on webkit. All 19 are green at head. Eight cases pass on both trees, so they are controls rather than padding.
Correcting a claim I made earlier in this PR
I previously wrote that Playwright has no touch emulation for Firefox and that those rows were absent. That is wrong. touch, touch_neutral and touch_trigger all ran and returned real verdicts on firefox and webkit. hasTouch works on all three engines; the option Firefox rejects is isMobile, and the probe passes hasTouch. Only the two CDP-only cases above are genuinely absent.
Mutant sweep: 26 mutants, 26 dedicated worktrees
One break each, every one in its own worktree with its own server, never applied-and-reverted in a measured tree. Five inherited anchors had gone stale against the 479-line file and were re-validated before use.
"No guard at all", measured twice by two independent breaks (neutering the pointerdown handler, and separately emptying MenuDismissGuard), which produce the identical list:
| engine | dismissing gestures that delete a message |
|---|---|
| chromium | 11 |
| firefox | 9 |
| webkit | 9 |
An earlier pass reported "seven gestures across all three engines". That is wrong at this head and I am not repeating it.
16 mutants killed, including moving the bound's anchor from release back to the press (red on all three), capture to bubble phase (red 11/9/9), the primary-button check, the menu-surface exemption, the text-entry exemption and the touch re-raise.
The startGrace armed-pointer filter added in 36486d9c4 is killed — by exactly one case on exactly one engine, touch_hold_second_pointer_grace on chromium, and that case deletes a message. It is the only thing in the whole 19x3 matrix that catches it, which is why the case was added alongside the fix.
Four "kills" withdrawn, because the noise floor was measured
touch_neutral on webkit fails at 19% at head over 21 observations — and at 23% at the merge base, which has no guard at all. Tree-independent, so it is a harness flake, not a regression. Four mutants whose only red was a single webkit hit on touch_neutral or rightclick_then_click were re-run in their own worktrees and came back green 4-5 out of 5. They are reported as not killed, not as kills.
Two protections that could NOT be proven red
- The 500 ms
CLICK_GRACE_MSbound. Green at 1 ms, 250 ms, 900 ms and one hour, on all three engines. Four orders of magnitude, no red, from the probe or the unit tests. What is defended is the bound's anchor, not its value: moving the deadline back to the press is red on all three engines includingheldandbusy, the two cases this PR is built on. Deleting the bound entirely was also not reliably killed, so I cannot show it is worthless either. - The Space /
keyboardOnlystate machine, 91 of 479 lines (42 of 166 non-comment). Removing it alone is green everywhere. Removing the focus release alone is red everywhere. Removing both is red everywhere and red on one extra firefox case. So the focus release alone already defends everything the Space machine defends; its only distinct contribution isheld_spaceon Gecko once the focus release is gone. Redundant as far as this probe can see, but a second independent mechanism rather than dead code.
Twelve extra pre-registered cases: 72 executions, 72 completed, 0 skipped
repeat_open_close fails on all three engines at the merge base (10 assistant messages down to 8 on chromium) and passes on all three at head.
One of the two head failures was a false alarm and one is real:
middleclick_then_clickis a false alarm. Every observation where the later click was swallowed also had the menu still open after the middle press, so that click was the dismissal and eating it is correct. The case cannot distinguish the two orderings; that is a limit of the case.dblclick_outsideis a genuine, head-only, webkit-only over-swallow. In 10 of 20 observations both clicks of a double click outside the menu were eaten. Head chromium 12/12 and head firefox 5/5 land exactly one; merge base webkit 16/16 land two. Nothing is deleted and nothing is unreachable, but it is a real "swallowed too much" finding on one engine and I have not diagnosed the cause.
Integrity
47 before/after source checksum pairs recorded across probe runs, 46 held; the one exception has no .after because I stopped that batch by hand, and no result from it is used. 25 of 25 mutant sweeps and 11 of 11 verify runs reported their checksums held. Both trees clean against git at the end.
What I could not prove
Whether the 500 ms bound has any value the probe can see, or whether its existence is defended at all. Whether the audio scrubber shield does anything: no case in either probe touches an audio player, so that mutant surviving measures coverage, not the shield. Whether pointercancel's armed-pointer filter is load-bearing, since nothing drives a second pointer's cancel. The cause of the webkit dblclick_outside over-swallow, and the cause of the webkit touch_neutral flake beyond showing it is tree-independent.
Gates at this head
npm run typecheck exit 0, npm run build exit 0, npm test 3795 of 3796. The one failure is tests/queued-model-capabilities.test.ts, which passes standalone at head (4/4) and standalone at the merge base (4/4), and whose merge base full suite fails the same single file. Pre-existing whole-suite interaction, not this branch.
CI addendum at head
|
|
@codex review |
|
Confirmed main already has the action menu non-modal at studio/frontend/src/components/assistant-ui/thread.tsx:7188, and this extends the same fix to the composer and permission-mode dropdowns that are opened constantly in the normal chat flow. |
|
Closing this. It has conflicted with main since 19 August with no prepared rebase, so it was never measurable on its own. The one sweep that reached it measured the 9051 plus #9229 stack, and every metric landed inside the run's own floor at the 100K rung. Taking chat menus off the body modal layer is still a reasonable thing to want. If it comes back it should come back rebased and measured on its own. |
Summary
A modal Radix menu parks
pointer-events: noneon<body>for as long as it is open.pointer-eventsis an inherited property, so that single write invalidates computed style for the entire mounted subtree underneath it. On a long chat thread that subtree is the thread, so opening a menu costs a full-document style recalculation whose cost scales with the thread rather than with the menu.Eleven menus move to
modal={false}. A twelfth was reverted to modal in review, for a functional reason given below. Dialogs, alert dialogs and sheets are untouched: modal semantics are correct and wanted there.Read that count as eight. Two of the eleven are in
thread-sidebar.tsx, which nothing imports, so vite tree-shakes it out and they never mount; one more is thePermissionModeDropdownthat went back to modal. Eight menus change behaviour in the running app. The detail, and the more expensive menus this PR does NOT reach, are in "Not verified, and follow-ups" below.One more shield came back in review, deliberately narrow. Radix Slider commits in
onPointerDownand Radix Select opens inonPointerDown, so the click swallower never sees them. With the Run settings panel co-visible on desktop, one dismissing press moved Temperature 0.6 to 1.7 and persisted it tostudio.db. A ref-counteddata-nonmodal-menu-openattribute on<html>now takes just those two control types out of the hit test while a non-modal menu is open. It is the old shield's job with the rightmost compound naming the control rather than<body>, so the invalidation is bounded by the sliders on the page instead of the length of the thread. The sidebar's "More" destinations menu, the onemodal={false}menu on the branch with noMenuDismissGuardand the one mounted on every route, now has the guard, and a test sweeps the tree so the next one cannot be missed.The strongest single fact: on the PR 9016 heavy-thread harness the message action menu's growth verdict flips from 10.44x DISCRIMINATES to flat. The menu stops being a function of thread size.
Numbers
Message action menu, 9016 harness (
tests/studio/playwright_heavy_thread.py), 25K to 300K characters (20 to 220 messages), medians of 3.Chromium style recalculation during that action: 2820.8 ms across 10 recalcs -> 4.2 ms across 8.
bodyPointerEventswhile the menu is open goesnone -> auto, which is the mechanism confirming itself.Per repetition, chromium: before 25K
[404.4, 340, 345.2], before 300K[3409.3, 3235.7, 3291], after 300K[73.8, 74.9, 72.1]. WebKit after, 300K:[169, 279, 157].WebKit at 300K has no before number here. The baseline build crashed with
TargetClosedErroron both attempts, 2 of 2, on this shared box; both patched runs completed. That is a reproducible observation, not a measured ratio, and it is reported as such. For a reference point, an independent run of the unmodified harness on an idle 48-core machine measured WebKit's baseline at 3133 ms, the worst of the three engines: chromium 265 -> 2565 ms (9.7x), firefox 166 -> 1330 ms (8.0x), webkit 336 -> 3133 ms (9.3x). That run also reproduced the attribution, 2158 of 2565 ms in style recalculation on chromium, on a second machine.That ordering matters for this PR: WebKit is the worst engine on this bottleneck, and WebKit is what Desktop ships on macOS and Linux, so the Chromium-only picture was understating the problem for Desktop users rather than overstating it.
Measurement caveats
Stated so nobody reads more into these numbers than they carry.
none -> autoflip ondocument.bodyis measured on all three.studio/src-tauri/src/linux_webkit.rsadditionally appliesWEBKIT_DMABUF_RENDERER_FORCE_SHM(orWEBKIT_DISABLE_DMABUF_RENDERERbelow WebKitGTK 2.44), a shared-memory transport, so real Desktop Linux on Wayland is likely worse than measured here. On X11 it preserves the environment, so this is Wayland-conditional rather than unconditional.tests/studio/_playwright_robust.py'schromium_launch_args()includes--disable-gpuin_BASE_CHROMIUM_ARGS, and the harness passes those args to Chromium only. The ratios reproduced on a second, idle machine, so they are not an artefact of that. But none of these numbers describe GPU compositing, and a win that was partly a compositing effect would not show up in this harness at all.The expansion is worth more than the original fix
The action menu was found first, but the cost belongs to the mechanism, not to that menu. Measured with
tests/studio/probe_menus_growth.py, chromium, medians of 3:Both composer dropdowns were worse at 300K than the action menu ever was, and unlike the action menu they are opened constantly in the ordinary flow. Growth with thread size goes 9.33x -> 1.10x and 9.48x -> 0.99x.
Why not just upgrade Radix
radix-ui1.6.2 carries #3991, which is genuinely useful but does not address this. It reduces the count of forced reflows by replacing agetComputedStyleancestor loop inFocusScope.isHidden()and cachinganimationNameinPresence. Our cost is 2804 ms across only 10 recalcs, roughly 280 ms each: that is invalidation scope, not flush count. The PR says so itself, listing "react-remove-scroll writing inherited CSS vars on body, aria-hidden walking the DOM" as remaining. Thebody.style.pointerEvents = 'none'write is still on Radixmaintoday indismissable-layer.tsx.Upgrading is also not currently free: #4093 is open, and since
@radix-ui/react-dialog1.1.19 dialog content is not clickable for the first painted frame in production builds. It fails deterministically in interaction runners withUnable to perform pointer interaction as the element has 'pointer-events: none', which is exactly this harness's pointer shape.modal={false}is already an established pattern in this tree, atsrc/components/app-sidebar.tsx:3121.Behaviour changes, stated plainly
Dropping
modaldrops four things. Three are accepted tradeoffs. The fourth was a realbug, and the first attempt to fix it was wrong in four separate ways.
The destructive click, and four failed guards
Radix's outside-pointerdown handler dismisses but never cancels the event, so without the
body shield the click reaches whatever is underneath. The assistant action bar is one flex
row ordered Copy, Edit, Refresh, ForkCount, Delete message, Speak, More, and the
menu opens directly beneath the trigger, so Delete sits two 32 px buttons away with no
confirmation step.
The original guard armed a
oncecaptureclicklistener fromonPointerDownOutsideanddisarmed it on a fixed 300 ms timer. It passed the only gesture it was tested with. Every
other way a person dismisses a menu got through. Pressing "Delete message" with the menu
open, message count before and after, real hit tests via
page.mouse/page.touchscreen:heldreproduces on chromium, webkit and firefox.Correcting an earlier claim in this description. It previously said the touch rows were
chromium and webkit only because "Playwright has no touch emulation for Firefox". That is
wrong, and I am striking it rather than quietly deleting it. Tested directly on this head:
new_context(has_touch=True)thenpage.touchscreen.tap(), with capture listeners on thepage, gives
navigator.maxTouchPointspointerdown:touch,touchstart,touchend,click:touchpointerdown:touch,touchstart,touchend,click:touchpointerdown:touch,touchstart,touchend,click:mouseFirefox dispatches real touch events, so the plain touch rows are genuine measurements on all
three engines. The option that Firefox does not support is
isMobile, which throws;hasTouchis a separate option and is what the probe passes.
What IS an absent measurement is narrower:
touch_hold_second_pointerandtouch_hold_second_pointer_graceare chromium only, because Playwright'sTouchscreenexposes an atomic
tap()and nothing else, so holding a finger down while a second pointer actsneeds CDP. Those two report themselves skipped on firefox and on webkit, and a skip is not a
pass.
Two root causes, both confirmed against the pinned
@radix-ui/[email protected]source rather than inferred. A deadline anchoredat the press is gone before the browser synthesises
clickon release, and a personcan hold a button as long as they like; blocking the main thread reproduces the same
outcome from a normal-length press, which is what a 300K thread does on its own. And
usePointerDownOutsidedefers to the resultingclickwhenpointerType === "touch",on
ownerDocument, bubble phase, so React's root-container delegation has already run thecontrol's
onClickby the time Radix calls us. A guard armed there cannot swallow theclick that armed it.
So the guard now watches
pointerdownondocumentin the capture phase, ahead ofboth. Attacking that version then found three more defects, each fixed and each with a
regression case:
contextmenuand never aclick, so theswallower survived and ate the user's next real left click, on all three engines. The
window now opens at
pointerup, and non-primary buttons do not arm at all.deferred
clicklistener was waiting for. A tap on a focusable control still closed themenu via
useFocusOutside, which is why this looked correct; a tap on plain threadbackground left the menu open on chromium and webkit. Radix's deferred handler
ignores the click entirely, so a bare non-bubbling
clickre-raised atdocumentreleases it.
the time, and releasing still synthesises the click.
keydownnow only disarms a gesturethat has already been released.
tests/studio/probe_dismiss_guard.pyruns nineteen cases in CI and exits non-zero on anyfailure. Each was checked against a deliberately broken tree before its green was
trusted. Two of its own assertions were wrong when first written: one failed on every tree
including the base, and one silently landed on a focusable button and reported a pass for a
case it had never tested. The neutral target is now grid-searched for a genuinely
non-focusable element and the probe fails rather than falling back if none exists.
One of the twelve had to stay modal
The chat settings preset menu is
modal={true}, unconditionally. Not a perf judgement:non-modal breaks it outright, at every viewport.
Its trigger is
asChildover a plain div inside anInputGroup, andInputGroupAddon'sonClickfocuses the sibling input for any target that is not a button. A div is not abutton, so the release-click of the opening press moves focus to that input, focus leaves
the portalled content, and a non-modal layer dismisses itself on focus-outside. The menu
opens on
pointerdownand closes on the same gesture'sclick.Measured at both viewports, because a first pass at this saw only the mobile half and
wrongly concluded it was mobile-only. At 420x900, traced with a MutationObserver and the
pointer never moving: mounted t=33 ms, gone by t=208 ms. At 1440x900 on a production
build the trace reads
pointerdown-> open ->pointerup->click->focusoutof thecontent ->
focusinon the input -> closed. Sampling the whole 225x36 trigger box withelementFromPointfinds no point that behaves otherwise: every point is either the input,whose own
onPointerDownstopPropagationmeans the menu never opens, or the addon, whichopens it and closes it. So on desktop it could not be opened by any real gesture ending on
the trigger.
This also closes the one reachable case of a dismissing press committing a value. Radix
Slidercommits onpointerdown, not onclick, so the guard's click swallow cannot helpit. This menu is as wide as the settings column and grows 36-38 px per saved preset, so at
eight saved presets its bottom edge sits 1 px above the Temperature track. Measured on
head before this fix: a press there took temperature 0.6 -> 1.0, and it persisted through a
panel close, a page reload, and into
chat_settingsinstudio.db. On the merge base theidentical press is absorbed by the shield. With the shield back, it is again.
The alternative was to
stopPropagationthe dismissingpointerdownand re-dispatch it forRadix. That was built and measured, and rejected: it removes the press from React's
delegation entirely, so with a menu open the panel resize handle stopped dragging (272 px ->
272 px, against 272 -> 396 without it) and pressing another menu's trigger opened nothing.
Trading a rare mis-click for "the press that dismisses a menu can never start a drag" is a
worse deal.
Independently re-measured after the fix, by a separate pass that also found the desktop
failure on its own before the fix landed: on the current head the menu opens and stays
open at both 1280x900 and 420x900, on chromium, webkit and firefox. Before the fix it
self-closed 12 attempts out of 12 at desktop width on all three engines, roughly 110 to
180 ms after opening.
Cost of staying modal: one menu's worth of style invalidation, on a settings panel that is
not the path this PR is about.
Accepted tradeoffs
RemoveScroll). A real wheel gesture movesit about 2400 px with the menu open; previously 0.
aria-hidden. Body children go 4 -> 1. ARIA doesnot require hiding the page behind a menu; that is dialog semantics, and dialogs are
untouched.
FocusScopetrapdoes go away with
modal. That is not what stops Tab, so nothing observable changes.Keyboard reachability: measured, and unchanged
Tab and Shift-Tab were driven with real key presses on every reachable menu, on chromium,
webkit and firefox, at 1280x900 and 420x900, from two starting focus positions (the content
role="menu"Radix focuses on open, and the firstrole="menuitem"after one ArrowDown).564 key presses. Zero moved focus. Zero closed a menu. Identical on the merge base and
on this branch.
So Tab-out is trapped on both trees: an unchanged pre-existing limitation, not something
this PR grants and not something it takes away. The cause is in
@radix-ui/react-menu1.4.3,
MenuContentImpl:No
modalbranch.MenuRootContentModalandMenuRootContentNonModaldiffer only intrapFocus,disableOutsidePointerEvents,disableOutsideScrollandonFocusOutside, andboth render this same component, so
modalcannot reach the Tab handler at all. Upstreamradix-ui/primitives#1308, open since
2022-04-05, says the same from the other direction: "This has the same behavior whether or
not
modal={false}or not, and same about when<Portal>is wrapped around the<DropdownMenu.Content>or not."Escape, arrow keys, typeahead and Enter are untouched by
modal. Across all 564measurements the only field that differed anywhere between the two trees was
document.body's computedpointer-events,noneon base andautohere, which is thisPR's mechanism confirming itself and nothing else.
Two scope notes. None of the twelve is a Radix
Dialog(eleven areDropdownMenuPrimitive,and
ActionBarMorePrimitive.Rootis an assistant-ui wrapper that renders one and forwardsmodaluntouched), so#3811, which is Dialog-plus-WebKit,
does not apply. And this is Linux Playwright throughout; there is no Windows keyboard data
here.
Measurement corrections
The harness that produced the numbers above had three defects, found in review and fixed on
this branch.
deleteremoved the last assistant messageand the reopen path preserved the mutated runtime, so 300K went 220 -> 219 -> 218
messages and 25K lost 22% of its highlighting by repetition two. The harness's own image
gate would have failed repetition three at both sizes, but it is only evaluated once.
{}, soundefined <= 0is false and a fork badgerendered on all 110 assistant messages, which real Studio never shows for an unforked
message. Timing effect is inside the noise floor; it is fixed because the harness page was
not showing the UI it claims to.
median()silently droppedNone, so a timed-out repetition still reported a median"of three".
Re-running this PR's headline on the corrected harness: 300K chromium menu open and close,
median of 3, 3993.5 ms modal to 51.6 ms non-modal, 77.4x, against the 3279.0 -> 62.2 ms and
52.7x quoted above, with the census now stable at 219 across all three repetitions. The
defects were real and the conclusion survived them.
Not verified, and follow-ups
Listed rather than implied.
ThreadSidebaris imported by nothing.grep -rn "ThreadSidebar\|thread-sidebar"returns only the definition, so 2 of the 12 menus never mount in the running app,
including the only submenu and the only menu whose items open a Dialog. Those two are
unexercised, not passing.
PermissionModeDropdownatchat-settings-sheet.tsx:1865was not reached.Five menus need application state that could not be constructed in the harness.
31
DropdownMenuroots remain modal, and the three the user actually opens from thesidebar are among them:
components/app-sidebar.tsx:2234("Organize chats"),app-sidebar.tsx:2578("Chat options") andfeatures/chat/chat-page.tsx:1666. None istouched here, and all three are still modal on the packaged head build.
This matters more than a count, because the most expensive menu measured is one of them.
On the packaged production build, same 220-message thread, same run: the patched More
menu opens and closes in 38.6ms, the unpatched "Chat options" menu in 382.6ms.
9.9x, with modality the only difference between them. So the mechanism this PR fixes is
still live on the sidebar, and the biggest single win is left on the table.
Deliberately not taken in this PR. Each additional non-modal menu needs its own
MenuDismissGuardinside the content and its own pass through the 16-case dismissal matrix,because the guard is mounted per menu content rather than globally. Every data-loss bug found
in review on this branch lived in exactly that gap, so converting three more menus without
that matrix is the one thing this PR should not do at the end of review. Tracked as Studio: the sidebar menus users actually open are still on the body modal layer, 382.6ms against 38.6ms #9168,
with the numbers above as its justification. On mobile that sidebar renders inside a Sheet
(
components/ui/sidebar.tsxswitches onisMobile), the same menu-inside-a-Sheet shape thatbroke chore(studio): give Radix portals a container that is not document.body #9061, so it needs its own three-engine evidence rather than riding in on this PR's.
This PR should not be read as "chat menus are fixed".
Scope
Menus and selects only.
Dialog,AlertDialogandSheetkeep modal semantics: focus trapping, scroll lock and page hiding are the point of a dialog, and making them non-modal would be a real accessibility regression. Verified by diff: noDialog,AlertDialog,Sheet,DialogContentorSheetContentline is touched.Twelve menus converted, twelve dismissal guards added, across:
assistant-ui/thread.tsx(action menu, reasoning dropdown, tools and attachments),shared-composer.tsx(2),mcp-composer-button.tsx,thread-sidebar.tsx(2),permission-mode-select.tsx(2),project-switcher.tsx,chat-settings-sheet.tsx(the dropdown at 1099, not the Dialog at 1501 or the Sheet at 1648).Testing
npm run typecheckcleannpm test2936 passed, 0 failednpm run buildcleanbiome checkon the changed files: 18 errors, byte for byte the same 18 that are onmainfor those files. Zero added. An earlier attempt usedbiome check --write, which reformatted whole files into a 1838 line diff; that was reverted and the imports were placed by hand so the diff stays at the change itself.prepush_gate.py --worktree wt_radix-modal: PASSStaging CI (
danielhanchen/unsloth-staging-2, Linux + macOS + Windows + Playwright): Frontend CI, Unsloth API CI, Unsloth GGUF CI, Unsloth Tauri CI, Mac Studio GGUF CI, Mac Studio UI + API + Update CI, Windows Unsloth API CI, Windows Unsloth GGUF CI, Windows Unsloth UI CI and Workflow trigger lint all green. Three non-green results, all triaged as not caused by this branch:test_multi_chat_prompt_queue_contract.py::test_composer_only_queues_behind_the_current_chat, 1 failed of 8084. This is a source-text contract test overthread.tsx, so it was worth ruling in. It fails identically on the merge base with this branch's changes absent, verified locally on both. Pre-existing.copy-to-clipboard.test.tsanddesktop-stop-intent.test.ts. Both files pass 20/20 on Linux on this branch, both exercise Windows path handling (fileURLToPath,URL.pathname,?bust=dynamic imports), and this branch touches neithercopy-to-clipboard.tsnorapi-base.ts. The one test that walks all ofsrc/**checks for a marker key that the newmenu-dismiss.tsdoes not contain. Pre-existing Windows-only.probe_menus_growth.pywith no arguments while--labelwas required. Fixed in this branch by defaulting it; not a product failure.Two probes are added under
tests/studio/because the claims above should be re-runnable:probe_menu_behaviour.pyfor the four behaviour deltas andprobe_menus_growth.pyfor the per-menu growth curve.The visible behaviour change, stated rather than left to be discovered
A non-modal menu does not lock scroll. So with a menu open, a wheel gesture now scrolls the
thread and carries the menu off screen with it. Measured, base to head, one wheel gesture with
the More menu open:
bodypointer-eventsnonearia-hiddensiblingsThe menu does not close. It tracks its trigger out of the viewport and stays open and
focused, so ArrowDown keeps moving through items the user can no longer see. Escape still
closes it and scrolling back brings it into view, so nothing is unreachable, but this is the
accessibility-facing half of the change and it should be read as part of the trade rather than
found later.
Not treated as a blocker, for two reasons:
app-sidebar.tsx:3121already ships amodal={false}menu with exactly this behaviour today, so it is not new to the product; andmodal={false}is Radix's documented escape hatch for this, not a misuse. If parity is wanted,the fix is to close the menu on the thread viewport's
scroll.hideWhenDetachedis thewrong fix, because it hides a menu that still holds focus, which is strictly worse for a
screen-reader user than one that is merely off screen.
Pre-existing WebKit defects this fixes as a side effect
Claimed nowhere until now. On the merge base, WebKit fails four dismissal cases that head
passes: a touch tap outside does not dismiss the menu; a click into the composer neither
dismisses it nor lands the caret; and
dismiss_then_spaceleaves it open. These arepre-existing WebKit behaviours, not regressions this PR repairs in its own work.
Related, and it undercuts the premise the modal shield was ever doing this job: on the merge
base a click on the composer
+with the More menu open leaves two menus open at once onall three engines, because the composer dock already escapes the shield through a
pointer-events: autowrapper. So "the shield absorbs the dismissing click" was already falsefor half the chat UI before this PR.
Two protections that could not be proven red
Stated because a green that was never made red measures nothing, and both of these are green.
The 500ms
CLICK_GRACE_MSbound has no assertion covering it. Re-checked at this head:setting it to 250 and to 900 leaves every frontend unit test green. The new second-pointer test
advances a clock past the bound by hand, but it reads the constant rather than pinning it, so it
fixes the BEHAVIOUR and not the number. It remains a constant nothing defends.
The Space /
keyboardOnlystate machine is redundant with the focus release. Removing itentirely left every case green, because blurring the button in the same branch already removes
the pending activation at its source on Gecko. It is retained as belt and braces for engines
that would still dispatch the keyup click, but it was not independently load-bearing on any
engine measured.
Re-measured on this head, and the ablation re-run rather than carried forward. The size was
given as "roughly 60 of 332 lines". The file is 479 lines and the machine is 91 of them
(42 of the 166 non-comment non-blank lines), counting its state, its two dedicated key
handlers, the
isActivationKeyhelper and the keyboard branch in the swallower.The ablation now separates two mechanisms that were being conflated. Removing the Space machine
alone is green on all three engines; removing the focus release alone is red on all three;
removing both is red on all three and red on one extra case on firefox. So the focus release
alone defends everything the Space machine defends, and the Space machine's only distinct
contribution is
held_spaceon Gecko once the focus release is also gone. It is redundant withrespect to what this probe can see, but it is not dead code: it is the second of two independent
mechanisms covering the same Gecko behaviour.