Skip to content

feat: add browser-side function waits to the extension - #3179

Merged
miguelg719 merged 6 commits into
mainfrom
amel/wait-for-function-extension
Oct 19, 2026
Merged

miguelg719 merged 6 commits into
mainfrom
amel/wait-for-function-extension

Conversation

@supremeboxlogos

@supremeboxlogos supremeboxlogos commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

why

Add browser-side function waiting without repeatedly evaluating over the SDK transport.

This is PR1 of the waitForFunction() stack. Follow-up #3183 targets this branch to register the RPC and expose it in TypeScript, Python, and Go.

what changed

  • Poll an expression in the main world immediately, then on animation frames or a positive interval; await asynchronous predicates without overlapping calls.
  • Return a detached JSON value and surface predicate/serialization errors directly.
  • Reuse the selector-wait handle lifecycle through one shared browser-wait helper, including disposal and late-result cleanup.
  • Keep one Progress deadline across navigation retries. Timeout zero remains unlimited, but closed pages/transports stop retries.
  • Distinguish browser predicate exceptions from transient CDP errors so a matching error message never triggers accidental retries.
  • Refresh the required embedded extension ZIP. No protocol/RPC or public SDK API changes.

Reviewed with the requested Thermo-Nuclear Code Quality Review skill: shared resource ownership replaces duplicated cleanup, and browser-side polling stays out of the transport and SDK layers.

test plan

  • 79 focused extension tests passed, including the existing selector-wait regressions.
  • Covers async predicates, errors, invalid polling, timeout/late cleanup, context/root-frame replacement, and closure during readiness/retry with timeout zero.
  • Extension build/typecheck, embedded ZIP regeneration, formatting, and git diff --check passed.
  • Public real-Chrome integration coverage is in the SDK follow-up.

@changeset-bot

changeset-bot Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 5b75bd8

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review completed against the latest diff

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 7 files

Architecture diagram
sequenceDiagram
    participant SDK as SDK (TS/Python/Go)
    participant PAGE as Page
    participant FW as functionWait.ts
    participant BW as browserWait.ts
    participant CTRL as ExecutionContexts
    participant CDP as CDP Session
    participant BROW as Browser (Main World)
    participant JS as createFunctionWait (Injected)

    Note over SDK,BROW: waitForFunction: Browser-Side Polling

    SDK->>PAGE: waitForFunction(expression, {polling, timeout})
    PAGE->>FW: waitForFunction(expression, options)

    FW->>FW: Validate polling (raf or positive int)
    FW->>FW: Create Progress with single deadline

    loop Until resolved (single deadline)
        FW->>CTRL: getMainWorldExecutionContextId(progress)

        alt Context not ready
            CTRL-->>FW: "main world not ready" error
            FW->>FW: delay(25ms) and retry
        else Context ready
            CTRL-->>FW: contextId
            FW->>PAGE: getFrame() - verify page/transport alive
            FW->>BW: browserWait(session, progress, installFn)

            BW->>CDP: Runtime.evaluate (createFunctionWait + expression)
            CDP->>BROW: Evaluate in main world context
            BROW-->>CDP: Return { objectId: "wait-handle" }
            CDP-->>BW: EvaluateResponse

            BW->>CDP: Runtime.callFunctionOn (await this.promise)
            CDP->>BROW: Await injected promise
            BROW->>JS: Poll predicate

            loop On each poll (raf or interval)
                JS->>JS: Run predicate in main world
                alt Truthy result
                    JS->>JS: JSON.stringify + parse (detached value)
                    JS-->>BW: Resolve with JSON value
                else Falsy result
                    JS->>JS: Schedule next poll (raf/timer)
                end
            end

            alt Predicate throws or non-JSON result
                JS-->>BW: Reject with predicate error
                BW->>BW: BrowserWaitError (not retried)
            else CDP transient error
                CDP-->>BW: "Context destroyed/navigated" error
                BW->>BW: Cleanup/dispose handle
                FW->>FW: Retry with fresh context (same deadline)
            end

            alt Success
                BW-->>FW: JSON value
                FW-->>PAGE: Return value
                PAGE-->>SDK: Return value
            else Timeout (single deadline)
                FW->>FW: TimeoutError
                FW-->>PAGE: Reject
                PAGE-->>SDK: Reject
            end
        end
    end

    Note over BW,BROW: Cleanup paths
    BW->>CDP: Runtime.releaseObject (on success/completion)
    alt Disposal or failure
        BW->>CDP: Runtime.callFunctionOn (this.dispose())
        BW->>CDP: Runtime.releaseObject
    else Late result after disposal
        CDP-->>BW: Late objectId (predicate resolved after dispose)
        BW->>CDP: Dispose late handle
    end
Loading

Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

@miguelg719
miguelg719 added this pull request to stack #3255 October 19, 2026 18:30
# Conflicts:
#	packages/sdk-go/internal/extensionassets/stagehand-extension.zip
# Conflicts:
#	packages/sdk-go/internal/extensionassets/stagehand-extension.zip
@miguelg719
miguelg719 merged commit 0804f6b into main Oct 19, 2026
63 checks passed
@miguelg719
miguelg719 deleted the amel/wait-for-function-extension branch October 19, 2026 23:38
miguelg719 added a commit that referenced this pull request Oct 19, 2026
# why

Expose browser-side predicate waiting consistently across Stagehand
SDKs, without transport polling.

This is PR2 of 2, stacked directly on #3179
(`amel/wait-for-function-extension`). Polling, navigation recovery, and
cleanup live in the parent; merge it first using the repository’s
stacked-PR handoff rules.

# what changed

- Register `page.wait_for_function` and connect the extension
controller/runtime to the internal implementation.
- Add TypeScript `waitForFunction(expression, arg?, options?)`, Python
`wait_for_function(expression, *, arg, polling, timeout)`, and Go
`WaitForFunction`. As in Playwright, an expression that evaluates to a
function is invoked on each poll and receives the optional JSON `arg`.
- Preserve JSON result keys through opaque wire metadata, with roundtrip
coverage for own `toString`, `constructor`, and `hasOwnProperty` keys in
nested payloads. No browser-handle API is introduced.
- Provide RAF/interval polling and no deadline by default in all three
SDKs; pass `timeout` to bound a wait. An omitted or zero timeout also
drops the client response deadline.
- Derive internal wait options from the canonical protocol contract.
Reuse the TypeScript argument serializer. Model Go’s string-or-number
polling option through its existing typed-union generator extension
point.
- Regenerate protocol/models/final ZIP and include docs plus minor
release entries for all five packages.

Reviewed with the requested Thermo-Nuclear Code Quality Review skill,
including an independent cross-review of SDK boundaries. No SDK polling
loops, duplicated serializer, broad generator abstraction, or new
1,000-line file crossing.

# test plan

- 9 real-Chrome tests passed, including main-world access, async
predicates, custom intervals, error propagation, navigation recovery,
concurrent waits, and timeout-zero closure.
- 79 extension/selector tests and 788 protocol/docs/SDK/architecture
guards passed.
- 184 Python tests plus Ruff/type checks passed; Go SDK package tests
passed.
- Follow-up review: 26 wire tests passed; canonical option types emit
unchanged JavaScript, and the rebuilt extension ZIP remains identical.
- Extension/SDK/protocol typechecks, dependency-ordered build,
generated-model/ZIP checks, formatting, lint, and `git diff --check`
passed.

---------

Co-authored-by: miguel <[email protected]>
miguelg719 added a commit that referenced this pull request Oct 21, 2026
…nction

page.waitForFunction (#3179, #3183) polls in the page and reinstalls its
predicate after a navigation, so the quiet wait is one in-page wait per call
instead of a page.evaluate round trip every 100 ms. The cap still runs on the
host clock, a failed wait sleeps out the rest, and pages without
waitForFunction fall back to the plain sleep.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants