fix(extension): initialize selectors after DOM ready

AB
2mo ago
+137-24

why

waitForSelector() registers a DOMContentLoaded handler when the document root is not ready, but that handler referenced setupObservers before its const initializer could execute. The handler therefore threw a temporal-dead-zone ReferenceError and left the selector wait to time out.

Fixes #2731

what changed

  • Initialize the observer setup closure before the early document-ready branch.
  • Skip observer installation when the DOM-ready recheck already satisfies the selector.
  • Add focused coverage for immediate matches, matches present at DOM ready, and matches delivered by a later mutation.
  • Add patch Changesets for the extension and the SDKs that embed it.

test plan

  • vitest run packages/extension/tests/wait-for-selector.test.ts --reporter=verbose (3 passed)
  • vitest run packages/extension/tests packages/extension/understudy --reporter=dot (46 files passed; 336 passed, 10 existing TODOs)
  • vite build --config packages/extension/vite.config.ts
  • oxfmt --check on changed files
  • oxlint on changed TypeScript files
  • tsx scripts/release/check-changesets.ts
  • Go SDK tests excluding the intentionally separate examples package (passed)
  • Go generator tests (passed)
  • Full Python suite attempted: 455 passed, 2 skipped; only the two pre-existing Windows path assertions tracked by #2733 failed
  • Full JavaScript suite attempted: stopped on the pre-existing Windows CRLF/path failures tracked by #2734/#2735 and the existing protocol smoke C:\C:\... path construction

Summary by cubic

Fixes a temporal-dead-zone crash in waitForSelector() when the document root is not ready. Previously the DOMContentLoaded handler referenced an uninitialized closure, throwing and causing waits to time out; now it initializes the observer setup earlier and rechecks on DOM ready, installing observers only if still needed.

  • Define the observer setup before the early DOM-ready branch; on DOMContentLoaded, recheck the selector and skip observers when already satisfied.
  • Add focused tests for immediate matches, DOM-ready matches, and mutation-driven matches.
  • Publish patch releases for @browserbasehq/stagehand, @browserbasehq/stagehand-go, @browserbasehq/stagehand-python, and @browserbasehq/stagehand-extension; no API changes or migration required.