Skip to content

feat(browser-run): add Cloudflare hosted browsers - #1634

Merged
okwasniewski merged 33 commits into
e2e-inc:mainfrom
irvinebroque:prototype/browser-run
Nov 13, 2026
Merged

okwasniewski merged 33 commits into
e2e-inc:mainfrom
irvinebroque:prototype/browser-run

Conversation

@irvinebroque

@irvinebroque irvinebroque commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Cloudflare Browser Run runs headless Chromium on Cloudflare's network. @e2e-dev/browser-run connects existing web tests to it.

import { web } from '@e2e-dev/web';
import { browserRun } from '@e2e-dev/browser-run';

web({ browser: browserRun() });
web({ browser: browserRun({ scope: 'attempt' }) });
  • Set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN with Browser Rendering - Edit permission. The app URL must be reachable from Cloudflare.
  • Worker scope reuses a browser with an isolated context per attempt. Attempt scope leases a fresh browser per attempt and retry. The default inactivity timeout is ten minutes.
  • CDP endpoints and handshake headers resolve together. Providers derive headers inside workers; credentials stay outside lease handoffs and page requests. connect also accepts { endpoint, headers }.
  • Screenshots, traces, and WebM screencasts work when enabled. Remote downloads and Cloudflare-native recording attachments are unsupported. History navigation can fail waiting for load; the separate navigation fix remains outside this PR.
flowchart LR
  R[e2e runner] --> P[browserRun provider]
  P -->|create and delete sessions| C[Cloudflare Browser Run]
  R <-->|authenticated CDP| C
  C --> A[Public HTTPS app]
Loading

Verified

Ran it locally: yes

  • Built CLI against an HTTPS deployment of the actual testbed pages, with real Browser Run sessions, two workers, traces, and video. Ran both provider scopes with node ../../packages/e2e/dist/cli/bin.js run --config e2e.browser-run.config.ts; set BROWSER_RUN_SCOPE=attempt for the second run.
  • Unfiltered runs: worker 21 passed, 1 failed; attempt 14 passed, 1 failed. Both failures are browser.back() waiting for load, followed by video cleanup on the closed page. This limitation is documented. Rerunning with --grep-invert 'navigation verbs' passed every selected test:
worker:  Test Files  4 passed (4)   Tests  21 passed (21)
attempt: Test Files  3 passed (3)   Tests  14 passed (14)
  • Observed forms, cookies/storage isolation, network routes, dialogs, frames, viewport/media settings, reload/init scripts, and worker-scope session persistence. The Cloudflare session list was empty after teardown. Scanned generated artifacts for the actual API token: no matches. Remote WebM videos were generated in both scopes; GitHub attachment upload requires repository write access and was denied for this account.
  • Built CLI local testbed: 588 passed, 1 skipped. Web benchmark: 91 passed. The main/branch A/B run matched every step outcome and counter across two pairs; timing was unresolved on the busy host, so no performance claim.
Regression Before review fixes This branch
Errored 429 response body Stream cancellation masks the retry Regression passes; the rejected request retries
Journal write and DELETE both fail Cleanup error replaces the journal error Both errors and session ID retained
Attempt-scope reconnect No regression covered reconnect credentials Reconnect tests require headers for explicit and fallback endpoints

Maintainer verification on 2026-11-12 after rebasing onto main:

  • pnpm check passed, including the build, public type checks, and docs checks.
  • Built CLI: pnpm --filter @e2e-dev/testbed test passed 588 tests, 1 skipped; pnpm --filter @e2e-dev/web-benchmark test passed 93 tests.
  • Browser Run provider: 35 tests passed. Full web suite: 825 tests passed, 1 skipped. Fresh-context review found no critical or important findings.
  • Cloudflare credentials were unavailable on the maintainer's machine. The live hosted results above are the contributor's earlier verification, before the endpoint changed to the documented /browser-run/devtools/browser path.
  • Fork workflows have been approved for the rebased head. Human re-review is requested.

@github-actions github-actions Bot added needs:compliance Community PR fails CONTRIBUTING.md#pull-requests, closed after 72h if not fixed size:XL Up to 999 changed lines, not counting tests, fixtures, translated docs, or the lockfile labels Nov 8, 2026

@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 43 files

Tip: cubic used a learning from your PR history. Let your coding agent read cubic learnings directly with the cubic MCP.

View guided diff | Re-trigger cubic

Comment thread packages/browser-run/NOTICE Resolved
Comment thread docs/integrations/browser-run.mdx Resolved
Comment thread docs/reference/web.mdx Resolved
Comment thread .github/filters.yml Resolved
Comment thread packages/web/src/provider.ts Resolved
Comment thread packages/browser-run/src/http.ts Resolved
@okwasniewski okwasniewski removed the needs:compliance Community PR fails CONTRIBUTING.md#pull-requests, closed after 72h if not fixed label Nov 8, 2026
@okwasniewski

Copy link
Copy Markdown
Member

nice, thanks for opening the PR!

@okwasniewski okwasniewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Automated review.

Thanks for this. Overall the design is right: CDP handshake headers are a general primitive, and nothing changes for existing users unless a provider sets headers. Unit tests pass (browser-run 22/22, web unit 347, real-Chrome cdp-headers integration 2/2), and tsc, oxlint, peer-range and changeset checks are clean. Mutation testing: 27 of 34 mutations caught.

Must fix

  1. Docs describe the removed history fix. a4eaf7e put back/forward navigation back on load, but two lines still describe the commit behavior: docs/integrations/browser-run.mdx:76 ("History navigation finishes at commit...") and docs/reference/web.mdx:483. Delete both.

  2. The live test can't pass. apps/testbed/tests-browser-run/browser-run.e2e.ts:6 fetches /echo-headers, which the testbed server doesn't serve. The test also proves nothing, because CDP headers are never sent on page requests. Drop it; packages/web/tests/integration/cdp-headers.test.ts already proves this with a real browser.

  3. Headers reach the connection through a side channel.

    • surface.ts:433 reads leases.cdpHeaders() after leases.endpoint(), so it depends on call order and on "current lease" state (provider.ts:508).
    • attachPersistent gets a 4th positional parameter (called with undefined at attempt-session.ts:142).
    • persistent.headers is kept as a separate field.

    Fix: make the resolver return one value, CdpTarget = { endpoint, headers? }, and thread it through connectCdp(target, timeout), attachPersistent(resolve, budget, previous?) and the persistent binding. This also lets connect config accept headers with no extra work.

  4. The API token ends up in worker env. In worker scope, encodeHandoff puts Authorization: Bearer <token> into the E2E_WEB_BROWSERS_* env var, so every worker and every process it spawns inherits the token.

    Fix: add an optional provider method cdpHeaders?(lease, context) that runs inside the worker, against the worker's own env. The secret never enters lease JSON, and the new handoff header validation (isCdpHeaders / isCdpHeader, the isBrowserLease rewrite) can go.

  5. onPage is a new public core API whose only use is a log line that is off by default. It adds BrowserProvider.onPage, BrowserPageContext, LeasedBrowsers.pageObserver, a two-flag branch at attempt-session.ts:261-268, and docs. It also blocks page open (up to 5s per attempt with liveView), and a throwing onPage fails the attempt even though the docs call it a notification.

    Please move liveView to a follow-up PR. If it stays here, run the hook best-effort: don't await it, and log its errors instead of throwing.

  6. Docs and changeset explain internals. Users don't need to know about the journal, the retries or the hook (changeset paragraph 2). Also cut:

    • browser-run.mdx:62-64, :80 ("prototype") and :86-87
    • docs/browser.mdx:297 ("incur no additional page identity lookup")
    • the "Live verification" section of the package README, which is maintainer-only and ships to npm
  7. Add a ## Verified section to the PR body. pr-policy closes the PR after 72h without it. Please include a real run against Browser Run, in both worker and attempt scope.

Should fix

  • browser-run/src/provider.ts:96-101: if the journal write fails and release throws too, the DELETE error replaces the journal error, and the lease leaks without any trace. Keep both errors. No test covers this.
  • http.ts:47-50: if the Retry-After delay is longer than the remaining budget, the user gets a bare TimeoutError instead of the 429. Throw the 429 right away when delay >= remaining.
  • attempt-session.ts:182: dropping persistent.headers on reconnect would break attempt-scope reconnect (Cloudflare returns 401), and no test catches it. Add one.
  • provider.ts:56: journal() uses CLOUDFLARE_ACCOUNT_ID! and only works because credentials() ran first. Return account from credentials() and pass it in.
  • browser-connection.ts:121-129:
    • The Bearer|Basic stripping is a special case in core.
    • Replacing every occurrence of a header value can mangle the message when the value is short.
    • Rethrowing as a plain Error loses Playwright's error name (TimeoutError). Keep name.
  • sweep (provider.ts:120) runs sequentially. Use Promise.allSettled like the kernel provider, and report which IDs failed and why.

Mutations that survived, each needs a test:

  • no release when the journal write fails
  • reconnect without headers
  • pageObserver without its abort race
  • no typeof onPage === 'function' check
  • a token containing line breaks
  • the journal path guard
  • prune

Nits

  • packages/browser-run/NOTICE says @e2e-dev/kernel.
  • The skill note is appended under the Codex section (skills/e2e/references/setup.md:447, same in plugins). Add browserRun() to the hosted browser list in the browser row instead.
  • The isBrowserLease restyle is unrelated to this PR, and the blank lines inside functions (surface.ts, attempt-session.ts, browser-connection.ts) don't match repo style.
  • scope: undefined is set on the provider; spread it conditionally, like kernel does.
  • keepAlive defaults to 60s (kernel: 600s). Fine if an open CDP connection counts as activity; please confirm.
  • Optional follow-up: LeasedBrowsers sees every acquire, so the engine could journal lease IDs itself and give every provider without tags a crash sweep.

CI

Neither failure comes from this PR. check fails on the screenshot-while-navigating test, which #1614 fixed on main, so rebase onto main to pick it up. The test (22.22.3) failure is a kill ESRCH in packages/acp / packages/decision executor.test.ts, which this PR doesn't touch.

For maintainers

  • Should onPage / live view land in core at all, or in a follow-up?
  • Should connect config get public headers with the CdpTarget shape?
  • Should the engine own lease journaling?

@github-actions github-actions Bot added the needs:compliance Community PR fails CONTRIBUTING.md#pull-requests, closed after 72h if not fixed label Nov 11, 2026
@irvinebroque

Copy link
Copy Markdown
Contributor Author

[gpt-6] responding on behalf of irvinebroque

Addressed the summary review, with separate commits for the findings:

Must fix:

  1. Removed the stale history-navigation claims: e3add731.
  2. Dropped the redundant broken live authorization test: ead6c368.
  3. Resolvers, persistent bindings, reconnects, and public connect config now use one CDP target containing endpoint and optional headers: 289ed561.
  4. Added worker-side cdpHeaders(lease, context); lease JSON carries no credentials, and the header handoff validation/restyle is gone: 2d397634.
  5. Removed Live View and the page hook API for a follow-up. Their abort/type-check mutation cases no longer apply: 748d34a5.
  6. Removed implementation details and prototype wording from the guide, README, and changeset: fb4d69ac.
  7. Added real worker/attempt results to ## Verified and moved maintainer run instructions to the testbed README: 3a1887e6. This also addresses the Verified policy comment.

Should fix:

  • Journal failure plus failed release preserves both errors and the session ID, with regressions for successful and failed cleanup: 44795a55.
  • A Retry-After delay beyond the request budget returns the HTTP 429 immediately: 654b4d5b.
  • Attempt reconnect tests require credentials with both explicit and fallback endpoints and verify no replacement lease: 42aaf8cf.
  • Credentials return the validated account, passed explicitly to the journal: 7857861e.
  • Authenticated CDP failures use a fixed safe message, preserve the original error name, and have no Bearer/Basic or short-value replacement heuristic: 7b3ede14.
  • Sweep runs releases concurrently with per-session failure reasons and receipts retained for retry: c27342a7.

Remaining mutation coverage:

  • Tokens containing line breaks, including leading/trailing line breaks: cfec0c51.
  • Journal path guard: 55ac10ae.
  • Prune removes empty journal directories and preserves outstanding receipts: eb972cc5.

Nits:

  • Correct package NOTICE: ac4abe7f.
  • Browser Run is in the hosted-browser row, with the published guide link: 8030ca71 and a850291d.
  • Removed unrelated formatting changes: fde19b66.
  • Unspecified scope is omitted with a conditional spread: cb34ce58.
  • Cloudflare counts time without CDP commands even with an open connection. Raised the default to ten minutes and documented this: 98bc412a. Cloudflare inactivity behavior.

The optional engine-owned lease journal remains follow-up work. The branch is rebased onto current main; full local checks passed, as did the fresh-context review. The web package passed 796 tests, provider 34, built CLI testbed 588 (one skipped), and deterministic web benchmark 91.

Live Browser Run: worker 21/22 and attempt 14/15 unfiltered. Both hit the known browser.back() load-wait failure, also causing video cleanup failure on that closed page; this is now documented. With only that test excluded, worker 21/21 and attempt 14/14 passed. No Cloudflare sessions remained after teardown, and the API token was absent from all 235 generated artifacts scanned.

All nine inline threads have commit-linked replies and are resolved. GitHub rejected both fork-workflow approval (repository-admin permission required) and the review re-request (insufficient repository permission). A maintainer needs to approve the pending workflows and arrange the next review; the PR is ready for that re-review.

@github-actions github-actions Bot removed the needs:compliance Community PR fails CONTRIBUTING.md#pull-requests, closed after 72h if not fixed label Nov 11, 2026

@okwasniewski okwasniewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[claude-opus-5-5] automated review on behalf of @okwasniewski

Re-reviewed at 3a1887e. I checked every item from the last review in code, and all are fixed. CdpTarget plus a worker-side cdpHeaders is the right shape, and core has no Cloudflare-specific code. Local results: browser-run 34/34, web unit 53/53, cdp-headers integration 3/3. tsc, oxlint, fallow, peer-range and changeset checks are clean. 6 of 7 mutations were caught.

Must fix:

  1. packages/browser-run/package.json:18,22,24: repository, bugs and homepage still point at tester-army/e2e. Every sibling moved to e2e-inc/e2e, and npm provenance checks repository.url against the publishing repo.
  2. docs/reference/web.mdx:94: the "Either resolver can return { endpoint, headers }" paragraph splits the browser bullet list and repeats :151. Delete the first copy.

Should fix:

  • browser-run/src/provider.ts:51: response.body?.cancel() needs .catch(() => undefined) like http.ts. Otherwise a body stream error after a successful DELETE keeps the receipt and makes release throw.
  • asBrowserProvider rejecting a non-function cdpHeaders (web/src/provider.ts:194) is untested. Removing it from the list leaves all tests passing.
  • Cloudflare's CDP docs show /accounts/{id}/browser-run/devtools/browser, and the provider uses /browser-rendering/devtools/browser. Which one is canonical? If the old path is a legacy alias, please switch.

Nits: stray blank lines in docs/browser.mdx:276,292 and browser-provider.test.ts:927.

@okwasniewski
okwasniewski self-requested a review November 12, 2026 18:04
@okwasniewski

okwasniewski commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

[gpt-6-astra] responding on behalf of okwasniewski

Addressed the latest review in 166c3f0 after rebasing onto main:

  • Package metadata now points to e2e-inc/e2e.
  • Removed the duplicate CDP paragraph and stray blank lines.
  • Successful DELETE cleanup tolerates a failed response body; a regression checks that the receipt is removed.
  • Added coverage rejecting non-function cdpHeaders.
  • Switched to /browser-run/devtools/browser, as documented in https://developers.cloudflare.com/browser-run/cdp/.
  • Aligned the new package's Vitest lockfile reference with main.

Local static checks, 35 provider tests, 59 focused web/CDP tests, the built testbed (588 passed, 1 skipped), and web benchmark (93 passed) pass. Fresh-context review found no critical or important findings. The full web package suite also passed: 825 tests, 1 skipped.

Approved the four fork workflows and requested human re-review. I could not repeat hosted Cloudflare verification because this machine has no Cloudflare credentials; the PR body preserves and attributes the contributor's earlier results.

@okwasniewski
okwasniewski dismissed stale reviews from themself November 12, 2026 22:18

Asks addressed (automated review)

@okwasniewski

Copy link
Copy Markdown
Member

[claude-opus-5-5] automated review on behalf of @okwasniewski

Re-reviewed 166c3f0. All previous asks verified:

  • repo URLs point to e2e-inc/e2e
  • duplicate CdpTarget paragraph gone
  • DELETE body cancel tolerates stream errors, test fails when the catch is removed
  • non-function cdpHeaders rejected, test fails when the guard is removed
  • /browser-run/devtools/browser matches the Cloudflare CDP docs

Rebase clean, lockfile diff minimal, CI green, web 825 + provider 35 tests pass locally. Labeling Ready for Human Review.

Nit: docs/browser.mdx:383 has an overlong line in the sweep paragraph.

Open for maintainers: history navigation load wait limit, generic CDP error with headers, testbed live setup, and whether the run-local lease journal should move into @e2e-dev/web (#1726 adds a near-identical ledger with different failure policy).

@okwasniewski okwasniewski added the Ready for Human Review Green, conflict-free, every thread handled. Waiting on a maintainer. label Nov 12, 2026

@okwasniewski okwasniewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ready for Human Review Green, conflict-free, every thread handled. Waiting on a maintainer. size:XL Up to 999 changed lines, not counting tests, fixtures, translated docs, or the lockfile

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants