The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
ci(ego-browser): move the real-browser E2E gate to pre-push and shorten it
Zhuowei Wang074d430664c3
diff --git a/AGENTS.md b/AGENTS.mdindex a167709..e0fb767 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -77,8 +77,12 @@ Run from `package/ego-browser/`:- Behavior-focused tests inject overrides (`__testing.setOverrides`) or a`FakeEgo` double (see `src/helpers.test.mjs` and `src/page-model.test.mjs`).- Cover session handling, locator resolution, helper behavior, and site-skill validation when changing runtime code; run `npm run validate:site-skills` for learning changes.-- `npm run e2e` is the self-contained real-browser gate. It builds the current- checkout, passes the resulting absolute bundle through `--sdk-path`, starts a- local fixture server, uses a unique temporary task space, and cleans it up.+- `npm run e2e` is the self-contained real-browser gate, run by the pre-push+ hook (pre-commit runs only the fast checks against one shared build). It+ builds the current checkout, passes the resulting absolute bundle through+ `--sdk-path`, starts a local fixture server, uses a unique temporary task+ space, and cleans it up. A full pass records a fingerprint of `dist/out`, the+ suite and the CLI under `node_modules/.cache/`; an unchanged rerun skips, and+ `EGO_BROWSER_REAL_E2E_FORCE=1` overrides that.Do not link another runtime, reuse a prior E2E space, or manually take controlwhile the suite is running.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 036951a..59fe56c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -145,7 +145,7 @@ For additional CLI setup and troubleshooting, see| `npm test` | Builds the SDK, checks any local Skill translation, typechecks, then runs `src/**/*.test.mjs` with Node's test runner. || `npm run style:check` | Checks formatting of runtime source, build scripts, and package documentation. || `npm run validate:site-skills` | Builds and validates the site-learning packs. Run this when changing their manifests, tools, notes, or validation code. |-| `npm run e2e` | Builds the current checkout and runs the complete real-browser suite with its SDK. |+| `npm run e2e` | Builds the current checkout and runs the complete real-browser suite with its SDK. See the skip rule below. |Tests live next to the runtime source and use `node:assert/strict`, injectedservice overrides, or fake native bindings. Add a regression that demonstrates a@@ -159,6 +159,23 @@ space, take control, or change the SDK while it is running. On macOS it selectsthe ego lite app's CLI; use `EGO_BROWSER_REAL_E2E_CLI` to select another installedego lite CLI explicitly.+After a full pass the suite records a fingerprint of its inputs (`dist/out`,+the suite under `scripts/real-browser-e2e/`, and the selected CLI's size and+mtime) in `node_modules/.cache/ego-browser-real-e2e/`. A later `npm run e2e`+with the same fingerprint reports that it is skipping and exits successfully.+Set `EGO_BROWSER_REAL_E2E_FORCE=1` to run the suite anyway; a run limited with+`EGO_BROWSER_REAL_E2E_ONLY` neither skips nor records a pass.++Three of its cases wait out the runtime's response timeout on purpose (a+blocked `page.evaluate`, a navigation that never commits). They shorten it for+their own process with `EGO_BROWSER_RESPONSE_TIMEOUT_MS`, which the SDK reads+per call; it is a test aid, and agents keep the 15 s default.++Every build-first command starts with `npm run build`. Set+`EGO_BROWSER_REUSE_BUILD=1` to keep the existing `dist/` instead, which is how+the pre-commit hooks build once and run the checks in parallel. Leave it unset+when running commands by hand so they test the current source.+## Find the code to change| Location | Responsibility |@@ -195,18 +212,27 @@ input actions`. In the PR, explain the problem, the resulting behavior, and howyou verified it. Call out public API or Skill changes, and add an appropriaterelease-note label such as `fix`, `feat`, `docs`, or `ci`.-The pre-commit hooks select checks based on the staged files. Their freshness-check currently compares against `origin/dev`. For a beta-targeted PR, verify-that the latest `origin/2.0.0-beta-dev` is an ancestor of your branch; if the dev-check is inapplicable, exclude only `branch-up-to-date` with+The pre-commit hooks select checks based on the staged files: after the+branch-freshness check and one SDK build, the style check, `npm test`,+site-skill validation and plugin tests run in parallel against that build. The+freshness check currently compares against `origin/dev`. For a beta-targeted+PR, verify that the latest `origin/2.0.0-beta-dev` is an ancestor of your+branch; if the dev check is inapplicable, exclude only `branch-up-to-date` with`LEFTHOOK_EXCLUDE=branch-up-to-date` for that commit. Keep the other checks enabled.+The real-browser E2E suite is a pre-push hook rather than a pre-commit one: it+runs when the commits being pushed touch `package/ego-browser/` or+`skills/ego-browser/`, and it skips itself when nothing it tests changed since+the last full pass (see "Verify a change"). Run `npm run e2e` yourself before+pushing browser-behavior changes if you want the result earlier.+## CI and releases[CI](.github/workflows/ci.yml) runs on pull requests, pushes to `dev` and `main`,and version tags. It installs dependencies, checks formatting and dependency-vulnerabilities, runs `npm test`, and validates site learnings. The real-browser-E2E suite is a local gate and is not run by this GitHub-hosted workflow.+vulnerabilities (`npm audit` runs only here, not in the Git hooks), runs+`npm test`, and validates site learnings. The real-browser E2E suite is a local+pre-push gate and is not run by this GitHub-hosted workflow.The current release behavior is:diff --git a/docs/local-runtime-development.md b/docs/local-runtime-development.mdindex 526e4b6..86fd497 100644--- a/docs/local-runtime-development.md+++ b/docs/local-runtime-development.md@@ -71,6 +71,11 @@ task-space selection, takeover, or browser interaction is part of a successfulrun. A fresh agent can use this command without any context from an earlierdebugging session.+A full pass is remembered: when the build output, the suite and the CLI binary+are unchanged, the next `npm run e2e` reports that it is skipping and exits 0.+Set `EGO_BROWSER_REAL_E2E_FORCE=1` to rerun it regardless. The pre-push Git hook+runs this command for pushes that touch the package or the entry Skill.+## Keep the Skill alignedThe usage guide describes the APIs implemented by the runtime. `ego-browser skill`diff --git a/lefthook.yml b/lefthook.ymlindex e55a884..979140c 100644--- a/lefthook.yml+++ b/lefthook.yml@@ -8,54 +8,78 @@## The git root is the repository root, while the JS package lives in# package/ego-browser. Commands cd into that package when needed.+#+# pre-commit keeps the fast checks: it builds the SDK once, then runs the+# style check, repository tests, site-skill validation and plugin tests in+# parallel against that build (EGO_BROWSER_REUSE_BUILD). Dependency auditing+# runs in CI only. The real-browser E2E suite runs on pre-push, and its runner+# skips itself when the build, the suite and the ego lite CLI are unchanged+# since the last full pass (EGO_BROWSER_REAL_E2E_FORCE=1 reruns it).pre-commit:- parallel: false- commands:- branch-up-to-date:- run: |- git fetch --quiet origin dev 2>/dev/null || { echo "⚠ skip branch-freshness check: cannot fetch origin/dev (offline?)"; exit 0; }- if git merge-base --is-ancestor FETCH_HEAD HEAD; then- exit 0- fi- echo "✗ Your branch is behind origin/dev — sync before committing:"- echo " git fetch origin dev && git rebase origin/dev # or: git merge origin/dev"- exit 1- style-check:- run: |- files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^(package/ego-browser|plugins)/.*\.(ts|mjs|js|json|md)$' | grep -v '^skills/ego-browser/learnings/' || true)- [ -z "$files" ] && exit 0- package/ego-browser/node_modules/.bin/prettier --check $files- vulnerability-audit:- run: |- git diff --cached --name-only --diff-filter=ACMR | grep -q '^package/ego-browser/' || exit 0- cd package/ego-browser && npm audit --registry=https://registry.npmjs.org --audit-level=moderate- smoke-test:- run: |- git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/|skills/ego-browser/)' || exit 0- cd package/ego-browser && npm test- site-skill-validation:- run: |- git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/(src/learning/|scripts/validate-site-skills\.ts)|skills/ego-browser/learnings/)' || exit 0- cd package/ego-browser && npm run validate:site-skills- plugin-skill-sync:- # Lefthook runs commands in name order, so this refreshes the plugin's- # copy of the entry Skill before plugin-tests checks it.+ jobs:+ - name: plugin-skill-sync+ # Refreshes the plugin's copy of the entry Skill before plugin-tests+ # checks it. It writes the index, so it runs before the parallel jobs.run: |git diff --cached --name-only | grep -q '^skills/ego-browser/' || exit 0node plugins/scripts/sync-skills.mjs ego --staged- plugin-tests:- run: |- git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(plugins/|skills/ego-browser/|package/ego-browser/skill-body/|\.agents/plugins/|\.claude-plugin/|\.cursor-plugin/)' || exit 0- npm --prefix plugins/ego test- e2e-test:+ - group:+ parallel: true+ jobs:+ - name: branch-up-to-date+ run: |+ git fetch --quiet origin dev 2>/dev/null || { echo "⚠ skip branch-freshness check: cannot fetch origin/dev (offline?)"; exit 0; }+ if git merge-base --is-ancestor FETCH_HEAD HEAD; then+ exit 0+ fi+ echo "✗ Your branch is behind origin/dev — sync before committing:"+ echo " git fetch origin dev && git rebase origin/dev # or: git merge origin/dev"+ exit 1+ - name: build+ run: |+ git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/|skills/ego-browser/)' || exit 0+ cd package/ego-browser && npm run build+ - group:+ parallel: true+ jobs:+ - name: style-check+ run: |+ files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^(package/ego-browser|plugins)/.*\.(ts|mjs|js|json|md)$' | grep -v '^skills/ego-browser/learnings/' || true)+ [ -z "$files" ] && exit 0+ package/ego-browser/node_modules/.bin/prettier --check $files+ - name: smoke-test+ env:+ EGO_BROWSER_REUSE_BUILD: "1"+ run: |+ git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/|skills/ego-browser/)' || exit 0+ cd package/ego-browser && npm test+ - name: site-skill-validation+ env:+ EGO_BROWSER_REUSE_BUILD: "1"+ run: |+ git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/(src/learning/|scripts/validate-site-skills\.ts)|skills/ego-browser/learnings/)' || exit 0+ cd package/ego-browser && npm run validate:site-skills+ - name: plugin-tests+ run: |+ git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(plugins/|skills/ego-browser/|package/ego-browser/skill-body/|\.agents/plugins/|\.claude-plugin/|\.cursor-plugin/)' || exit 0+ npm --prefix plugins/ego test++pre-push:+ jobs:+ - name: e2e-testrun: |- git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/|skills/ego-browser/)' || exit 0+ # Only the commits being pushed matter. branch-up-to-date keeps+ # origin/dev an ancestor of HEAD, so the merge-base diff lists them;+ # without origin/dev (offline, fresh clone) run the suite anyway.+ if git rev-parse --verify --quiet origin/dev >/dev/null; then+ git diff --name-only origin/dev...HEAD | grep -Eq '^(package/ego-browser/|skills/ego-browser/)' || exit 0+ ficd package/ego-browser && npm run e2epost-commit:- commands:- plugin-skill-index:+ jobs:+ - name: plugin-skill-index# `git commit <paths>` commits plugin-skill-sync's copy from a temporary# index, so the real index keeps the old copy. Point it back at HEAD.run: |diff --git a/package/ego-browser/scripts/build.mjs b/package/ego-browser/scripts/build.mjsindex 3b7e4d6..93bf641 100644--- a/package/ego-browser/scripts/build.mjs+++ b/package/ego-browser/scripts/build.mjs@@ -6,6 +6,7 @@ import {readdir,readFile,rm,+ stat,writeFile,} from "node:fs/promises";import { builtinModules } from "node:module";@@ -42,6 +43,18 @@ const entrySkillEntries = [];const buildLock = join(root, ".build.lock");+// The pre-commit hooks build once and then run several checks that each start+// with `npm run build`. They set this flag so those checks reuse that output.+if (isTruthy(process.env.EGO_BROWSER_REUSE_BUILD)) {+ if (await exists(bundledCli)) {+ console.log(+ `reusing the existing build at ${bundledCli} (EGO_BROWSER_REUSE_BUILD)`,+ );+ process.exit(0);+ }+ console.log("EGO_BROWSER_REUSE_BUILD is set but no build exists; building");+}+let lock;try {lock = await open(buildLock, "wx");@@ -144,3 +157,16 @@ async function collectTsFiles(absDir, relativeDir) {}return files;}++function isTruthy(value) {+ return value === "1" || value === "true";+}++async function exists(path) {+ try {+ await stat(path);+ return true;+ } catch {+ return false;+ }+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-evaluate-timeout.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-evaluate-timeout.mjsindex c3664b4..3a10118 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-evaluate-timeout.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-evaluate-timeout.mjs@@ -1,18 +1,25 @@+// Each recovery path below waits out the runtime's response timeout before+// the harness can react, so this process shortens that timeout (the SDK reads+// it per call) and scales the page-side delays with it. The default stays+// 15 s for agents; the unit tests pin that.export function pageEvaluateTimeoutCase() {return `+ const transportMs = 4_000;+ const executionMs = transportMs - 1_000;+ process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS = String(transportMs);const task = await taskSpace(taskName);const page = await newPageAt(task, baseUrl + "/?page-evaluate-timeout=" + Date.now());const syncStartedAt = Date.now();let syncError;try {- await page.evaluate(() => {+ await page.evaluate(({ executionMs, transportMs }) => {setTimeout(() => {window.__scheduledBeforeEvaluateTimeout = "finished";- }, 15_500);- const deadline = Date.now() + 20_000;+ }, executionMs + 1_000);+ const deadline = Date.now() + transportMs + 4_000;while (Date.now() < deadline) {}- });+ }, { executionMs, transportMs });} catch (error) {syncError = error;}@@ -29,8 +36,8 @@ export function pageEvaluateTimeoutCase() {);assertEqual(syncError?.pageResponsive, true, "the Page recovers from synchronous execution");assert(- Date.now() - syncStartedAt < 18_000,- "the execution safety deadline fires before the callback's own 20 second loop"+ Date.now() - syncStartedAt < transportMs + 3_000,+ "the execution safety deadline fires before the callback's own loop ends");const quickStartedAt = Date.now();assertEqual(await page.evaluate("1 + 1"), 2, "the next evaluation succeeds");@@ -88,18 +95,18 @@ export function pageEvaluateTimeoutCase() {const fallbackStartedAt = Date.now();let fallbackError;try {- await page.evaluate(async () => {+ await page.evaluate(async ({ executionMs, transportMs }) => {setTimeout(() => {window.__fallbackBlockStarted = true;- const deadline = Date.now() + 5_000;+ const deadline = Date.now() + transportMs + 2_000;while (Date.now() < deadline) {}window.__fallbackBlockCompleted = true;- }, 13_500);+ }, executionMs - 500);// Keep the evaluated Promise live past the transport timeout. An// unreferenced never-settling Promise may be collected by Chromium// before the scheduled blocking task starts.- await new Promise((resolve) => setTimeout(resolve, 20_000));- });+ await new Promise((resolve) => setTimeout(resolve, transportMs + 6_000));+ }, { executionMs, transportMs });} catch (error) {fallbackError = error;}@@ -119,8 +126,8 @@ export function pageEvaluateTimeoutCase() {"the fallback health probe confirms that the Page recovered");assert(- Date.now() - fallbackStartedAt < 18_000,- "the fallback interrupts the finite five-second block instead of waiting for it to finish"+ Date.now() - fallbackStartedAt < transportMs + 3_000,+ "the fallback interrupts the finite block instead of waiting for it to finish");assertEqual(await page.evaluate("window.__fallbackBlockStarted"),@@ -141,10 +148,10 @@ export function pageEvaluateTimeoutCase() {await page.evaluate("delete window.__lateEvaluateSideEffect");let asyncError;try {- await page.evaluate(async () => {- await new Promise((resolve) => setTimeout(resolve, 16_000));+ await page.evaluate(async (transportMs) => {+ await new Promise((resolve) => setTimeout(resolve, transportMs + 1_000));window.__lateEvaluateSideEffect = "finished";- });+ }, transportMs);} catch (error) {asyncError = error;}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-pending-navigation.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-pending-navigation.mjsindex a831281..6bfbd24 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-pending-navigation.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-pending-navigation.mjs@@ -3,8 +3,16 @@// stops. These cases pin the harness behavior on such a Page: public calls// stay inside one bounded wait, then stop the navigation and say which// document the Page shows, so the next call answers at once.+//+// That bounded wait is the runtime's response timeout. Both processes shorten+// it (the SDK reads it per call) so the cases prove "one wait, not one per+// setup command" in seconds instead of waiting out the 15 s default.+const PENDING_NAVIGATION_RESPONSE_TIMEOUT_MS = 5_000;+export function pagePendingNavigationCase() {return `+ const transportMs = ${PENDING_NAVIGATION_RESPONSE_TIMEOUT_MS};+ process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS = String(transportMs);const task = await taskSpace(taskName);const page = await newPageAt(task,@@ -106,7 +114,7 @@ export function pagePendingNavigationCase() {"the error tells the agent how to load the pending document");assert(- snapshotElapsed < 20_000,+ snapshotElapsed < transportMs + 3_500,"snapshot gives up after one bounded wait, not one per setup command: " +snapshotElapsed);@@ -173,6 +181,8 @@ export function pagePendingNavigationCase() {export function pagePendingNavigationFreshProcessCase() {return `+ const transportMs = ${PENDING_NAVIGATION_RESPONSE_TIMEOUT_MS};+ process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS = String(transportMs);const task = await taskSpace(taskName);const saved = JSON.parse(await readFile(join(tempDir, "pending-navigation-state.json"), "utf8")@@ -194,7 +204,7 @@ export function pagePendingNavigationFreshProcessCase() {error?.message);assert(- elapsed < 20_000,+ elapsed < transportMs + 3_500,"a new process does not wait a full transport timeout per setup command: " +elapsed);diff --git a/package/ego-browser/scripts/real-browser-e2e/fingerprint.mjs b/package/ego-browser/scripts/real-browser-e2e/fingerprint.mjsnew file mode 100644index 0000000..1f7d7c8--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/fingerprint.mjs@@ -0,0 +1,68 @@+import { createHash } from "node:crypto";+import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";+import { join, relative, sep } from "node:path";++/**+ * A full real-browser E2E run only tells something new when its inputs+ * changed: the built SDK (`dist/out`), the suite itself, or the ego lite CLI+ * that drives it. The fingerprint hashes those so an unchanged checkout can+ * skip the suite after one full pass.+ */+export async function computeE2eFingerprint({+ inputDirs,+ cliPath,+ statFile = stat,+}) {+ const hash = createHash("sha256");+ for (const dir of inputDirs) {+ for (const file of await listFiles(dir)) {+ hash.update(`${toPosix(relative(dir, file))}\0`);+ hash.update(await readFile(file));+ hash.update("\0");+ }+ }+ hash.update(`cli:${cliPath}\0`);+ // The CLI is a binary outside this checkout; size and mtime are enough to+ // notice an app update without hashing it.+ try {+ const info = await statFile(cliPath);+ hash.update(`${info.size}:${info.mtimeMs}\0`);+ } catch {+ hash.update("unstat\0");+ }+ return hash.digest("hex");+}++export async function readLastPass(recordPath) {+ try {+ const parsed = JSON.parse(await readFile(recordPath, "utf8"));+ if (typeof parsed?.fingerprint !== "string") return null;+ return parsed;+ } catch {+ return null;+ }+}++export async function writeLastPass(recordPath, record) {+ await mkdir(join(recordPath, ".."), { recursive: true });+ await writeFile(recordPath, `${JSON.stringify(record, null, 2)}\n`, "utf8");+}++export function isTruthyFlag(value) {+ return value === "1" || value === "true";+}++async function listFiles(dir) {+ const entries = await readdir(dir, { withFileTypes: true });+ const files = [];+ for (const entry of entries) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) files.push(...(await listFiles(path)));+ else if (entry.isFile()) files.push(path);+ }+ return files.sort();+}++function toPosix(path) {+ return sep === "/" ? path : path.split(sep).join("/");+}diff --git a/package/ego-browser/scripts/real-browser-e2e/runner.mjs b/package/ego-browser/scripts/real-browser-e2e/runner.mjsindex 313f643..2e497d1 100644--- a/package/ego-browser/scripts/real-browser-e2e/runner.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/runner.mjs@@ -6,6 +6,12 @@ import { fileURLToPath } from "node:url";import { e2eCases } from "./cases/index.mjs";import { resolveEgoBrowserCli } from "./ego-browser-cli.mjs";import { egoSource } from "./ego-source.mjs";+import {+ computeE2eFingerprint,+ isTruthyFlag,+ readLastPass,+ writeLastPass,+} from "./fingerprint.mjs";import { closeFixtureServer, startFixtureServer } from "./fixture.mjs";import { runCommand } from "./run-command.mjs";@@ -13,6 +19,16 @@ const runnerDir = dirname(fileURLToPath(import.meta.url));const packageDir = join(runnerDir, "..", "..");const egoBrowserSdkPath = join(packageDir, "dist", "out", "index.js");const egoBrowserArgs = ["nodejs", "--sdk-path", egoBrowserSdkPath];+const sdkOutDir = join(packageDir, "dist", "out");+// Last full pass, keyed by the inputs' fingerprint. Lives under node_modules so+// `npm ci` and `npm run clean` never leave a stale record behind.+const lastPassRecordPath = join(+ packageDir,+ "node_modules",+ ".cache",+ "ego-browser-real-e2e",+ "last-pass.json",+);export function parseOnlyCases(configured, availableCaseNames) {const raw = typeof configured === "string" ? configured.trim() : "";@@ -67,9 +83,8 @@ export function parseOnlyCases(configured, availableCaseNames) {export async function runRealBrowserE2e() {const egoBrowserCli = resolveEgoBrowserCli();- const keepTaskSpace =- process.env.EGO_BROWSER_REAL_E2E_KEEP === "1" ||- process.env.EGO_BROWSER_REAL_E2E_KEEP === "true";+ const keepTaskSpace = isTruthyFlag(process.env.EGO_BROWSER_REAL_E2E_KEEP);+ const forceRun = isTruthyFlag(process.env.EGO_BROWSER_REAL_E2E_FORCE);const onlyCases = parseOnlyCases(process.env.EGO_BROWSER_REAL_E2E_ONLY,e2eCases.map((testCase) => testCase.name),@@ -256,6 +271,22 @@ export async function runRealBrowserE2e() {await runCommand("npm", ["run", "build"], { cwd: packageDir });await stat(egoBrowserSdkPath);+ const fingerprint = await computeE2eFingerprint({+ inputDirs: [sdkOutDir, runnerDir],+ cliPath: egoBrowserCli,+ });+ const isFullRun = onlyCases.size === 0;+ if (isFullRun && !forceRun) {+ const lastPass = await readLastPass(lastPassRecordPath);+ if (lastPass?.fingerprint === fingerprint) {+ console.log(+ `== E2E skipped: the build, the suite, and the CLI are unchanged since the full pass at ${lastPass.passedAt} ==`,+ );+ console.log("set EGO_BROWSER_REAL_E2E_FORCE=1 to run it anyway");+ return;+ }+ }+tempDir = await mkdtemp(join(tmpdir(), "ego-browser-real-e2e-"));const artifactDir = join(tempDir, "artifacts");const uploadPath = join(tempDir, "fixture-upload.txt");@@ -300,6 +331,12 @@ export async function runRealBrowserE2e() {if (!passed) {process.exitCode = 1;+ } else if (isFullRun) {+ await writeLastPass(lastPassRecordPath, {+ fingerprint,+ passedAt: new Date().toISOString(),+ cli: egoBrowserCli,+ });}} catch (error) {console.error(error?.stack || error?.message || String(error));diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjsindex 0f7387e..a795bf7 100644--- a/package/ego-browser/src/browser-runtime.test.mjs+++ b/package/ego-browser/src/browser-runtime.test.mjs@@ -15,6 +15,7 @@ import {prepareFileChooser,subscribeBrowserEvents,subscribePageEvents,+ responseTimeoutMs,} from "../dist/src/browser-runtime.js";test("browserCdp exposes a typed transport timeout", async () => {@@ -2378,3 +2379,25 @@ test("ensureFrameSessions reports an unanswered frame tree as an unresponsive Paelse globalThis.ego = previous;}});++test("the runtime response timeout defaults to 15 s and honors a test override", () => {+ const previous = process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS;+ try {+ delete process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS;+ assert.equal(responseTimeoutMs(), 15_000);+ process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS = "4000";+ assert.equal(responseTimeoutMs(), 4_000);+ for (const invalid of ["0", "-1", "abc", "1.5", ""]) {+ process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS = invalid;+ assert.equal(+ responseTimeoutMs(),+ 15_000,+ `ignores ${JSON.stringify(invalid)}`,+ );+ }+ } finally {+ if (previous === undefined)+ delete process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS;+ else process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS = previous;+ }+});diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.tsindex be15359..d3bf29b 100644--- a/package/ego-browser/src/browser-runtime.ts+++ b/package/ego-browser/src/browser-runtime.ts@@ -5,7 +5,19 @@ import {isEgoUserControlError,} from "./ego-errors.js";-const RESPONSE_TIMEOUT_MS = 15000;+const DEFAULT_RESPONSE_TIMEOUT_MS = 15000;++/**+ * How long one renderer-bound CDP command may go unanswered before the+ * runtime gives up on it. Read per call so a test process can shorten the+ * wait with EGO_BROWSER_RESPONSE_TIMEOUT_MS; agents keep the default.+ */+export function responseTimeoutMs(): number {+ const configured = Number(process.env.EGO_BROWSER_RESPONSE_TIMEOUT_MS);+ return Number.isInteger(configured) && configured > 0+ ? configured+ : DEFAULT_RESPONSE_TIMEOUT_MS;+}// Page.enable, Network.enable, and Target.setAutoAttach answer within// milliseconds on a responsive Page. A Page whose main-frame navigation has// started but not committed, or whose renderer hangs, answers none of them@@ -507,7 +519,7 @@ function rawCdp(method,params: any = {},sessionId = undefined,- timeoutMs = RESPONSE_TIMEOUT_MS,+ timeoutMs = responseTimeoutMs(),) {const runtime = browserEgo();bindRuntimeCallbacks(runtime);@@ -561,7 +573,7 @@ export async function browserCdp(method,params: any = {},sessionId = undefined,- timeoutMs = RESPONSE_TIMEOUT_MS,+ timeoutMs = responseTimeoutMs(),) {// Test mock: cdpOverride bypasses everything including session injection.// Include the effective timeout so tests can verify timing contracts without@@ -639,7 +651,7 @@ function recordCommandState(method, params, sessionId, response) {export async function ensureSession(requestedTargetId = undefined,- timeoutMs = RESPONSE_TIMEOUT_MS,+ timeoutMs = responseTimeoutMs(),) {const cachedTargetId =requestedTargetId || state.preferredTargetId || defaultTargetId;@@ -718,7 +730,7 @@ export async function ensureSession(*/export async function ensureFrameSessions(pageTargetId: string,- timeoutMs = RESPONSE_TIMEOUT_MS,+ timeoutMs = responseTimeoutMs(),) {if (typeof pageTargetId !== "string" || pageTargetId.length === 0) {throw new TypeError("ensureFrameSessions requires a non-empty targetId");@@ -985,7 +997,7 @@ export function isNetworkDomainEnabled(sessionId) {/** Ensure Network events are available on every selected Page/OOPIF session. */export async function ensureNetworkTracking(sessionIds: string[],- timeoutMs = RESPONSE_TIMEOUT_MS,+ timeoutMs = responseTimeoutMs(),): Promise<void> {const unique = [...new Set(sessionIds.filter(Boolean))];await Promise.all(@@ -1041,7 +1053,7 @@ export function networkActivity(sessionIds: string[]): {/** Refresh and return the main and known OOPIF sessions for one Page. */export async function pageNetworkSessions(sessionId: string,- timeoutMs = RESPONSE_TIMEOUT_MS,+ timeoutMs = responseTimeoutMs(),): Promise<string[]> {const targetId = sessionTargets.get(sessionId);if (!targetId) {@@ -1185,7 +1197,7 @@ function enableEgoAutomation(sessionId: string): void {void rawCdp("egoAutomated.enable", {}, sessionId).catch(() => {});}-async function enablePageEvents(sessionId, timeoutMs = RESPONSE_TIMEOUT_MS) {+async function enablePageEvents(sessionId, timeoutMs = responseTimeoutMs()) {const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;const target = targetId ? targetStates.get(targetId) : undefined;if (!target || target.sessionId !== sessionId || target.pageEventsEnabled) {@@ -1213,7 +1225,7 @@ async function enablePageEvents(sessionId, timeoutMs = RESPONSE_TIMEOUT_MS) {async function enableNetworkTrackingForSession(sessionId: string,required = false,- timeoutMs = RESPONSE_TIMEOUT_MS,+ timeoutMs = responseTimeoutMs(),): Promise<void> {const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;const target = targetId ? targetStates.get(targetId) : undefined;@@ -1258,7 +1270,7 @@ async function enableNetworkTrackingForSession(async function enableOopifAutoAttach(sessionId: string,- timeoutMs = RESPONSE_TIMEOUT_MS,+ timeoutMs = responseTimeoutMs(),): Promise<void> {const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;const target = targetId ? targetStates.get(targetId) : undefined;diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex fba745a..13f9fe0 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -8,6 +8,7 @@ import {ensureNetworkTracking,ensureSession,ensureFrameSessions,+ responseTimeoutMs,invalidateSession,isCdpRequestTimeoutError,isPageUnresponsiveError,@@ -649,8 +650,19 @@ const SNAPSHOT_DOCUMENT_CHANGE_RETRIES = 2;const FILE_CHOOSER_OPEN_WAIT_MS = 1_000;const FILE_CHOOSER_SETTLE_MS = 50;const CONTROL_POLL_INTERVAL_MS = 20_000;-const PAGE_EVALUATE_EXECUTION_TIMEOUT_MS = 14_000;-const PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS = 15_000;+// page.evaluate waits one runtime response timeout for the transport and+// asks Chromium to stop the script one second earlier, so a long synchronous+// callback is reported as stopped rather than as an unanswered command.+const PAGE_EVALUATE_EXECUTION_MARGIN_MS = 1_000;+function pageEvaluateTransportTimeoutMs(): number {+ return responseTimeoutMs();+}+function pageEvaluateExecutionTimeoutMs(): number {+ return Math.max(+ PAGE_EVALUATE_EXECUTION_MARGIN_MS,+ pageEvaluateTransportTimeoutMs() - PAGE_EVALUATE_EXECUTION_MARGIN_MS,+ );+}const PAGE_EVALUATE_HEALTH_TIMEOUT_MS = 250;const PAGE_EVALUATE_HEALTH_EXECUTION_TIMEOUT_MS = 200;const PAGE_EVALUATE_TERMINATE_TIMEOUT_MS = 1_000;@@ -2847,14 +2859,14 @@ class Page {expression,hasArgument,serializedArgument,- PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS,- PAGE_EVALUATE_EXECUTION_TIMEOUT_MS,+ pageEvaluateTransportTimeoutMs(),+ pageEvaluateExecutionTimeoutMs(),);} catch (error) {if (isEvaluationExecutionDeadlineError(error)) {throw evaluationExecutionDeadlineError("page.evaluate",- PAGE_EVALUATE_EXECUTION_TIMEOUT_MS,+ pageEvaluateExecutionTimeoutMs(),);}if (isRuntimeEvaluateTransportTimeout(error)) {@@ -2862,7 +2874,7 @@ class Page {this.#services,sessionId,"page.evaluate",- PAGE_EVALUATE_TRANSPORT_TIMEOUT_MS,+ pageEvaluateTransportTimeoutMs(),);}if (typeof expression === "function") {diff --git a/package/ego-browser/src/real-browser-fingerprint.test.mjs b/package/ego-browser/src/real-browser-fingerprint.test.mjsnew file mode 100644index 0000000..bab11fa--- /dev/null+++ b/package/ego-browser/src/real-browser-fingerprint.test.mjs@@ -0,0 +1,94 @@+import test from "node:test";+import assert from "node:assert/strict";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ computeE2eFingerprint,+ readLastPass,+ writeLastPass,+} from "../scripts/real-browser-e2e/fingerprint.mjs";++async function withInputDir(run) {+ const dir = await mkdtemp(join(tmpdir(), "ego-browser-e2e-fingerprint-"));+ try {+ await mkdir(join(dir, "nested"), { recursive: true });+ await writeFile(join(dir, "index.js"), "export const sdk = 1;\n");+ await writeFile(join(dir, "nested", "case.mjs"), "export const c = 1;\n");+ await run(dir);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+}++const fakeStat = async () => ({ size: 10, mtimeMs: 1000 });++test("real-browser E2E fingerprint is stable for unchanged inputs", async () => {+ await withInputDir(async (dir) => {+ const options = { inputDirs: [dir], cliPath: "/cli", statFile: fakeStat };+ assert.equal(+ await computeE2eFingerprint(options),+ await computeE2eFingerprint(options),+ );+ });+});++test("real-browser E2E fingerprint changes with any input file", async () => {+ await withInputDir(async (dir) => {+ const options = { inputDirs: [dir], cliPath: "/cli", statFile: fakeStat };+ const before = await computeE2eFingerprint(options);+ await writeFile(join(dir, "nested", "case.mjs"), "export const c = 2;\n");+ assert.notEqual(await computeE2eFingerprint(options), before);+ });+});++test("real-browser E2E fingerprint changes when the CLI binary changes", async () => {+ await withInputDir(async (dir) => {+ const before = await computeE2eFingerprint({+ inputDirs: [dir],+ cliPath: "/cli",+ statFile: fakeStat,+ });+ const updatedCli = await computeE2eFingerprint({+ inputDirs: [dir],+ cliPath: "/cli",+ statFile: async () => ({ size: 10, mtimeMs: 2000 }),+ });+ const otherCli = await computeE2eFingerprint({+ inputDirs: [dir],+ cliPath: "/other-cli",+ statFile: fakeStat,+ });+ const missingCli = await computeE2eFingerprint({+ inputDirs: [dir],+ cliPath: "/cli",+ statFile: async () => {+ throw new Error("ENOENT");+ },+ });+ assert.notEqual(updatedCli, before);+ assert.notEqual(otherCli, before);+ assert.notEqual(missingCli, before);+ });+});++test("real-browser E2E last-pass record round-trips and tolerates absence", async () => {+ const dir = await mkdtemp(join(tmpdir(), "ego-browser-e2e-last-pass-"));+ try {+ const recordPath = join(dir, "cache", "last-pass.json");+ assert.equal(await readLastPass(recordPath), null);+ await writeLastPass(recordPath, {+ fingerprint: "abc",+ passedAt: "2026-10-30T00:00:00.000Z",+ });+ assert.deepEqual(await readLastPass(recordPath), {+ fingerprint: "abc",+ passedAt: "2026-10-30T00:00:00.000Z",+ });+ await writeFile(recordPath, "{not json");+ assert.equal(await readLastPass(recordPath), null);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});