Repository navigation
test(modal): wait for Radix's focus restore before asserting it - #479
Conversation
Radix's `FocusScope` dispatches its unmount auto-focus from a `setTimeout(…, 0)`, and nothing makes that timer run before the `act()` that closed the dialog returns: `act`'s async form yields through `setImmediate`, so a pending 0 ms timer sometimes runs inside it and sometimes does not. The assertion then read a focus trace the restore had not reached, and failed `expected undefined to be <button>` — reddening the lean gate and CI's `test:run` at random on any PR. `close()` now waits that timer out, after the closing `act` returns and not inside it. The cleanup that queues Radix's timer runs during that `act`, so a wait queued in the same scope is the earlier of the two and fires first: measured 7 failures in 20, worse than no wait at all. Measured on 4 cores: three dialog cases in one file failed 5 runs in 15 without the wait, every failure an empty trace, and 0 in 20 with it. That retires one dialog per file, which read those same failures as a sibling case's teardown moving focus, and whose per-case-count gradient is what an independent dice roll per case produces. So the opener property moves back beside the first case, and the caller-wins path that had no spec anywhere joins them. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjZVAjRMEL1AWhDok7k
…is not The section on asserting a dialog's focus restore published two claims the measurements do not support: that `act` never reaches a macrotask, and that sharing a jsdom file between dialogs is what made those cases flake. Both now read as measured — the timer, the one ordering that must not be collapsed, and the gradient that reads as evidence for the timer rather than against it. The lane config said no spec waits on a timer. One now does, for a tick it queues itself, which still cannot hang. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjZVAjRMEL1AWhDok7k
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff is smaller than its ticket: 87 lines added, 164 removed, one file and one rule gone. The merge is argued from measurement, not tidiness, and the wait, the merge and the two doc corrections share one root cause, so nothing is smuggled. The ticket's four criteria are met — the fourth by retiring the rule rather than confirming it. One docs point: the new docs/testing.md section keeps the retired rule's history and figures, which nothing now reads.
Findings
should-fix—docs/testing.md:689— the retired one-dialog-per-file rule is described rather than warned about. Keep the ⚠, drop the history and the figures. See thread.consider—Modal.focus.test.tsx:13-16— the docblock restatesuse-opener-restore.ts's own:Dialog.Trigger, the<body>landing, the Chromium measurement. A pointer would do. Outside a diff hunk, so no thread.
What was checked
- Read whole on the branch: the spec,
Modal.tsx'sonCloseAutoFocuschain,use-opener-restore.ts,vitest.config.ts, the doc section; and the deleted spec onmain. new-pieces.mjs:NONE, so no streamliner. Ladder walked by hand: no new dependency, andvi.waitForand an in-actwait are both declined with figures. Fake timers not raised — vitest fakessetImmediate, which asyncactyields through.- Non-vacuity re-derived: with the stand-down gone,
opener.currentis inside the root, sorestoreFocusruns and the caller-wins case fails.chosensitting outside the root is load-bearing. - The pin claim holds:
patchedDependencieskeys@radix-ui/[email protected],overridespins 1.3.1. - Whole-file pass: the four helpers each have three callers; only the docblock.
- No reference to the deleted spec survives, and nothing host-facing changes.
- Not re-run: the 20 and 5 run counts. CI's three checks are green.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The five lines described the system #475 removes: how the old failures were read, where the opener property used to live, and the 1-in-5 / 1-in-8 figures. Nothing reads any of it — `git grep "one dialog per"` finds no other mention and no spec asserts the figures — and the paragraph above already carries the measurement that retires the rule, so the wait fixing the race is the proof. The warning is what a future author needs, and it stays. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjXHrXcKoDeMEx4TYYg
The paragraph restated `use-opener-restore.ts` almost sentence for sentence — the missing `Dialog.Trigger`, the `<body>` landing, the Chromium measurement. Two copies of one mechanism drift apart, and the spec is what a future author reads first, so the copy that goes false is the one that matters. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjXHrXcKoDeMEx4TYYg
|
Both review points are built, on Adopted — the retired one-dialog rule is one ⚠ line (b97f0db). The wait fixing the race is what retires it, so the gradient figures had nothing left to prove, and the PR body keeps them. Adopted — the docblock at Lean gate green on the merged result: 188 files, 2383 tests. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
sahajatlas-design | c9cf184 | Nov 24 2026, 07:11 PM |
One conflict, a modify/delete on `Modal.focus-opener.test.tsx`. #479 deleted that file: it existed to keep one dialog per jsdom file, and once the Radix focus race behind those failures was waited out, its single case moved back beside its siblings in `Modal.focus.test.tsx`. This branch had only renamed the file's docblock reference from `CompactEmbedView` to `InlineEmbedView`. So the deletion stands and the rename moves onto the surviving comment, which still named a component this branch removes. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5RfikrPBecdVUK8s
Summary
close()waits out Radix's unmount focus-restore timer, so the Modal focus cases stop racing it.docs/testing.mdandvitest.config.tseach stated something this makes false (joined: they publish the rule and the no-timer claim this diff retires).Change outline
Flow — what
close()waits for, and why the order mattersThe restore the cases assert on is dispatched from a timer that is queued by the unmount the first
actperforms.close(host) src/components/atoms/Modal/Modal.focus.test.tsx act(() => dismiss.click()) # unmounts; FocusScope's cleanup QUEUES the timer + await new Promise(r => setTimeout(r, 0)) # queued after it, so it runs after it FocusScope's timer fires # @radix-ui/react-focus-scope AUTOFOCUS_ON_UNMOUNT → ModalContent.onClose caller's onCloseAutoFocus, else restoreFocus() → opening.focus() expect(asked.at(-1)) # had read an empty trace before the waitFiles — one file holds the three focus cases
Preview
Test results
test:run(188 files, 2383 tests), withorigin/mainmerged inModal.focus.test.tsx20 consecutive runs green after the final shape, and 5 more after the review commitsManual verification
Notes for reviewer
expected undefinedin the ticket, not focus settling on the wrong element. The rule's own gradient (3 cases 1-in-5, 2 cases 1-in-8, 1 case 15/15) is what an independent dice roll per case produces, so it reads as evidence for the timer. The merge also pays for itself: the caller-wins case the deleted file called "no case anywhere" only existed as a comment because the rule would have made it a third file.act's async form yields throughsetImmediate, a macrotask, so "flushes microtasks but not a macrotask" cannot be right — it would have failed 15 of 15. What is true is that nothing guarantees a pending 0 ms timer has run inside it.actscopes to be collapsed into one. Measured and declined: 7 failures in 20, worse than no wait. The cleanup that queues Radix's timer runs during the closingact, so a wait queued in the same scope fires first. The⚠comment on the wait carries that.ModalContent's stand-down removed: the recorder'sfocusinlistener adopts it as the opener, and both ends of the chain then ask for the same element. Measured, reverted, and commented.vi.waitForaround each assertion — it costs ≥50 ms per case (its poll interval) and moves the wait from one helper into three assertions, and the timer is pinned by the keyed focus-scope patch pluspnpm.overrides, so it cannot move under us silently. Declined: a sharedsettle()drained inafterEachtoo — one call site, and the hazard is a future case that leaves a dialog open. Declined:it.eachover the first two cases, and an extra non-empty assertion on the trace, whichexpected undefined to be <button>already says.src/hooks/use-opener-restore.tsselects no spec per edit, because the selection does not follow a second module.docs/testing.mdalready documents that limit; the lean gate and CI still cover the hook.Detail
Non-vacuity, re-checked against the final shape. With
opening.focus()commented out inuseOpenerRestore.restoreFocus, the opener and had-focus cases fail. WithModalContent'sif (event.defaultPrevented) returnremoved, the caller-wins case fails — the atom asks for the opener after the caller's own choice. Both mutations were reverted.The flake does not reproduce on this runner in its shipped shape: the two single-case files passed 12 of 12 alone and 10 of 10 under four-way CPU load. A probe showed why — React's async
acthappens to cross a timer boundary here more often than not. All the measurements above therefore come from the three-case shape, which does reproduce it (5 in 15).The timer.
@radix-ui/[email protected]dispatchesAUTOFOCUS_ON_UNMOUNTfrom asetTimeout(…, 0)in its effect cleanup (dist/index.mjs), which is what reachesuseOpenerRestore.restoreFocus. The product code is unchanged:DialogContentcomposespreventDefault(); triggerRef.current?.focus()after the caller's handler, soonCloseAutoFocusis the only seam, and the repo's patch of that package touches only its shadow-boundary reads.No sibling spec has this shape. Only the unmount auto-focus is deferred; the mount one dispatches synchronously. The Drawer specs mount open and assert classes, the
CompactEmbedViewspecs assert after opening, andRegistrationForm.submit.test.tsx'sactiveElementreads come from react-hook-form'sshouldFocusError. So the wait stays in this one helper rather than becoming shared machinery.Closes #475