fix(web): keep closed shadow roots tracked on pages that replace WeakMap

Merged
KR
17d ago
+35-9

A page that replaces the global WeakMap, as some polyfills do, breaks app.screenshot with ENGINE_FAILURE: closed-shadow root tracking is unavailable for this document. Assertions before the screenshot still pass. Reported through e2e feedback on 0.17.0 and still present on main.

  • The context init script stores closed shadow roots in a WeakMap under Symbol.for('e2e.closedShadowRoots') before any page script runs.
  • The code that reads the record checked it with roots instanceof WeakMap. instanceof compares against the page's current WeakMap, so once the page replaced it, the record looked missing even though it was intact.
  • Effects on such a page:
    • The e2e-closed mask engine refuses (packages/web/src/closed-shadow.ts:118), so screenshot masking fails. This is the reported bug.
    • e2e-roots quietly stops searching closed roots, so locators miss elements inside them.
    • CDP recovery refuses to reconnect (packages/web/src/cdp-selectors.ts:53).
  • The fix checks key in globalThis, which calls nothing the page can replace. Only the init script defines that key, and it does so before page code runs. A document where the script never ran still has no record, so masking still fails closed.
  • The caret hiding in screenshot-caret.ts and the focus check in surface.ts read the map with ?.get(), like the reader in read-semantics.ts already did.

Issue

Fixes ENG-1030

Verified

Ran it locally: yes

  • testbed, built CLI, with a scratch test (not committed): an init script replaces WeakMap with Map, then a password field and a button are attached in a closed shadow root, followed by getByRole('button', { name: 'Pay now' }) and app.screenshot.
  • The new unit test (tests/unit/closed-shadow.test.ts) and the changed CDP masking test (tests/integration/cdp-recovery.test.ts) both fail on main and pass here.
mainthis branch
locator: observed: no node (match count 0)
screenshot: ENGINE_FAILURE: screenshot failed: page.screenshot: Error: closed-shadow root tracking is unavailable for this document
both pass, closed-root password field masked:
branch
main:
 × a page that replaced WeakMap keeps closed shadow roots reachable 5.20s
   → expect.toBeVisible failed
 × a screenshot masks a closed-root password field on a page that replaced WeakMap 126ms
   → screenshot failed: page.screenshot: Error: closed-shadow root tracking i…

this branch:
 ✓ a page that replaced WeakMap keeps closed shadow roots reachable 216ms
 ✓ a screenshot masks a closed-root password field on a page that replaced WeakMap 148ms

No test covers the screenshot-caret.ts and surface.ts hunks. Both are the same one-line read the reader already uses.


Made with Claude Opus 5.5 (claude-opus-5-5) in Claude Code, running in T3 Code.