Skip to content

test(modal): wait for Radix's focus restore before asserting it - #479

Merged
sydevs-dispatcher[bot] merged 5 commits into
mainfrom
claude/test-475-modal-focus-restore
Nov 25, 2026
Merged

sydevs-dispatcher[bot] merged 5 commits into
mainfrom
claude/test-475-modal-focus-restore

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • close() waits out Radix's unmount focus-restore timer, so the Modal focus cases stop racing it.
  • One dialog per jsdom file was that same timer: the cases share one file, and the caller-wins path gets its first spec.
  • docs/testing.md and vitest.config.ts each 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 matters

The restore the cases assert on is dispatched from a timer that is queued by the unmount the first act performs.

 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 wait

Files — one file holds the three focus cases

 src/components/atoms/Modal/
-├── Modal.focus.test.tsx         # the opener case; carried the one-dialog-per-file rule
-├── Modal.focus-opener.test.tsx  # the had-focus case, its own file for that rule
+├── Modal.focus.test.tsx         # opener, had-focus, and caller-wins
 └── Modal.tsx

Preview

  • No rendered surface changes — specs and docs only.

Test results

  • Lean gate: ✓ lint, typecheck, test:run (188 files, 2383 tests), with origin/main merged in
  • Targeted specs: Modal.focus.test.tsx 20 consecutive runs green after the final shape, and 5 more after the review commits
  • Full lane: 5 consecutive runs green
  • Build: N/A — CI runs it

Manual verification

  1. In the component library, open the Modal story and close it with × and with Escape. Focus should return to the control that opened it. The cases assert the focus call; only a browser settles where focus lands.

Notes for reviewer

  • The merge is the measurement, not tidiness. Three cases in one file failed 5 runs in 15 without the wait and 0 in 20 with it, and every failure was an empty focus trace — the expected undefined in 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.
  • The ticket's stated mechanism is slightly wrong, and the docs now say so. act's async form yields through setImmediate, 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.
  • Two reviewers asked for the two act scopes 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 closing act, so a wait queued in the same scope fires first. The ⚠ comment on the wait carries that.
  • The caller's target must sit outside the widget root, which is the opposite of what fidelity suggests. Moving it inside made the case pass with ModalContent's stand-down removed: the recorder's focusin listener adopts it as the opener, and both ends of the chain then ask for the same element. Measured, reverted, and commented.
  • Declined: vi.waitFor around 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 plus pnpm.overrides, so it cannot move under us silently. Declined: a shared settle() drained in afterEach too — one call site, and the hazard is a future case that leaves a dialog open. Declined: it.each over the first two cases, and an extra non-empty assertion on the trace, which expected undefined to be <button> already says.
  • Not touched, and not new: editing src/hooks/use-opener-restore.ts selects no spec per edit, because the selection does not follow a second module. docs/testing.md already 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 in useOpenerRestore.restoreFocus, the opener and had-focus cases fail. With ModalContent's if (event.defaultPrevented) return removed, 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 act happens 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] dispatches AUTOFOCUS_ON_UNMOUNT from a setTimeout(…, 0) in its effect cleanup (dist/index.mjs), which is what reaches useOpenerRestore.restoreFocus. The product code is unchanged: DialogContent composes preventDefault(); triggerRef.current?.focus() after the caller's handler, so onCloseAutoFocus is 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 CompactEmbedView specs assert after opening, and RegistrationForm.submit.test.tsx's activeElement reads come from react-hook-form's shouldFocusError. So the wait stays in this one helper rather than becoming shared machinery.

Closes #475

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-dispatcher

sydevs-dispatcher Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

🤖 no session running

recent dispatches
  • 19:04Z address-review · attempt 1 · session · done
  • 19:04Z address-review · attempt 1 · session
  • 18:55Z review-pr · attempt 1 · session · done
  • 18:55Z review-pr · attempt 1 · session

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-dispatcher sydevs-dispatcher Bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 24, 2026
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 24, 2026

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🧐 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 restates use-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's onCloseAutoFocus chain, use-opener-restore.ts, vitest.config.ts, the doc section; and the deleted spec on main.
  • new-pieces.mjs: NONE, so no streamliner. Ladder walked by hand: no new dependency, and vi.waitFor and an in-act wait are both declined with figures. Fake timers not raised — vitest fakes setImmediate, which async act yields through.
  • Non-vacuity re-derived: with the stand-down gone, opener.current is inside the root, so restoreFocus runs and the caller-wins case fails. chosen sitting outside the root is load-bearing.
  • The pin claim holds: patchedDependencies keys @radix-ui/[email protected], overrides pins 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

Comment thread docs/testing.md Resolved
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 24, 2026
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 24, 2026
@sydevs-dispatcher sydevs-dispatcher Bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 24, 2026
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 24, 2026
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
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Both review points are built, on origin/main merged in cleanly.

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 Modal.focus.test.tsx:11 restated use-opener-restore.ts sentence for sentence. It is a pointer now (c9cf184): two copies of one mechanism drift, and the spec is what a future author reads first.

Lean gate green on the merged result: 188 files, 2383 tests. Modal.focus.test.tsx 5 of 5 after both commits.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 24, 2026
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 24, 2026
@sydevs-dispatcher
sydevs-dispatcher Bot marked this pull request as ready for review November 24, 2026 19:13
@sydevs-dispatcher
sydevs-dispatcher Bot requested a review from Ardnived November 24, 2026 19:13
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Pending to Awaiting in SYDevelopers Technical Roadmap Nov 24, 2026
@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
sahajatlas-design c9cf184 Nov 24 2026, 07:11 PM

@sydevs-dispatcher
sydevs-dispatcher Bot added this pull request to the merge queue Nov 25, 2026
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Awaiting to Pending in SYDevelopers Technical Roadmap Nov 25, 2026
Merged via the queue into main with commit ca9ff4f Nov 25, 2026
48 checks passed
@sydevs-dispatcher
sydevs-dispatcher Bot deleted the claude/test-475-modal-focus-restore branch November 25, 2026 20:27
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Pending to Done in SYDevelopers Technical Roadmap Nov 25, 2026
sydevs-bot pushed a commit that referenced this pull request Nov 25, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

test(modal): wait for Radix's focus restore before asserting it

3 participants