Skip to content

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.

feat(ego-browser): refine page lifecycle APIs

Aute7ff0f6f700f6
diff --git a/AGENTS.md b/AGENTS.md
index 661778a..8cf8804 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,15 +1,19 @@
# Repository Guidelines
## Project Overview
+
`ego-browser` is a Node.js CDP browser-automation harness for AI agents. It drives the ego lite browser through `globalThis.ego` bindings (provided by the closed-source ego lite app), exposes a compact snapshot/ref workflow, and layers reusable site-specific knowledge ("learnings") on top of the browser runtime.
This repo contains the open-source harness and the agent skill package — **not** the browser itself. The ego lite app bundles its own `ego-browser` binary that embeds this runtime; `skills/ego-browser/SKILL.md` documents that binary's usage (`ego-browser nodejs <<'EOF' ... EOF`). The repo CLI built here takes the heredoc directly on stdin with no subcommand.
## Architecture & Data Flow
+
- `package/ego-browser/src/index.ts` is the entrypoint with two startup paths:
- Executed directly as a CLI → `runMain()` (reads JavaScript from stdin, executes it).
- Imported as a module (how the app embeds it) → `installEgoSdk(globalThis)`.
-- Both paths expose the same helper surface, built by `helperContext()` in `src/helpers.ts` — the single source of truth for what agents can call (including `help()` and `agent_helpers.js` extensions).
+- Both paths expose the same helper surface. `public-api-schema.ts` is the
+ source of truth for the v2 API shown by `help()` and the generated reference;
+ `helpers.ts` combines it with the frozen v1 compatibility surface.
- `src/run.ts` executes stdin JavaScript inside an async function with the helpers injected as parameters.
- `src/browser-runtime.ts` owns CDP transport over `ego.sendCDPMessage`, session attach/caching (2s TTL, auto re-attach on session loss), the buffered event queue (10k cap), and JS dialog tracking.
- `src/cdp-eval.ts` provides `cdp()` and `js()` (string-expression evaluation; top-level `return` is auto-wrapped in an IIFE).
@@ -23,38 +27,57 @@ This repo contains the open-source harness and the agent skill package — **not
Data flow: `stdin JS` → `runMain()` → `helperContext()` helpers → browser runtime/CDP → snapshot or DOM/AX resolution → optional site tools → `cliLog(...)`.
## Task Spaces
+
Task spaces are isolated browsing contexts with an ownership model (`agent` / `user`):
-- `useOrCreateTaskSpace(nameOrId)` reuses an agent-owned space or creates a new one; it no longer auto-claims user-owned spaces. Use `claimTaskSpace(nameOrId)` to take ownership of a user-owned space. Ids are numeric; prefer `task.id` over names across rounds.
-- `switchTaskSpace` requires agent ownership; `newTaskSpace` creates; `completeTaskSpace(nameOrId, { keep })` finishes (`keep` is mandatory).
-- Control handoff: `handOffTaskSpace` / `takeOverTaskSpace` / `waitForAgentControl`.
+
+- New scripts use `taskSpace(nameOrId)` and operate through the returned
+ `TaskSpace` and labeled `Page` objects.
+- `task.pages()` returns managed Page handles; `task.tabs()` returns the full
+ managed and unmanaged tab inventory.
+- Control handoff uses `task.handOff()` and `takeOverTaskSpace(spaceId)`.
+- The old global helpers remain available only for v1 script compatibility.
## Key Directories
+
- `package/ego-browser/src/` — runtime, helpers, resolver, drivers, learning subsystem.
- `package/ego-browser/src/**/*.test.mjs` — tests are colocated with the code (there is no separate `test/` directory).
-- `package/ego-browser/scripts/` — `build.mjs` (esbuild per-file → `dist/src`, rollup bundle → `dist/out/index.js`, copies `skills/ego-browser` → `dist/out/ego-browser`), `validate-site-skills.ts`, `run-e2e.sh`.
+- `package/ego-browser/scripts/` — `build.mjs` (esbuild per-file → `dist/src`, rollup bundle → `dist/out/index.js`, copies `skills/ego-browser` → `dist/out/ego-browser`), `validate-site-skills.ts`, and the real-browser E2E runner.
- `skills/ego-browser/` — agent skill package: `SKILL.md` (canonical agent-facing usage guide), `references/install.md`, `scripts/install.sh`.
- `skills/ego-browser/learnings/` — reusable per-site experience packs (`manifest.json` + `notes/` + `tools/` + `browser-tools/`).
## Development Commands
+
Run from `package/ego-browser/`:
+
- `npm test` — build, typecheck, then `node --test` over `src/**/*.test.mjs`.
-- `npm run e2e` — task-space e2e suite (`src/taskspace-e2e.test.mjs`).
+- `npm run e2e` — self-contained real-browser E2E suite using the current
+ checkout through `--sdk-path`.
- `npm run validate:site-skills` (alias `validate:learnings`) — validate learned site skills.
- `node dist/out/index.js <<'JS' ... JS` — run the built CLI from this checkout (requires an `ego` runtime for real browser work; `--doctor`, `--reload`, `-h` also supported).
## Code Conventions & Common Patterns
+
- ESM only (`"type": "module"`); Node 22+.
- Public helpers are camelCase, verb-first for async actions (`ensureSession`, `runSiteTool`).
-- Time parameters are in seconds unless the name ends in `Ms`.
+- V2 `TaskSpace` and `Page` time parameters are milliseconds. The v1
+ compatibility helpers keep their original units.
- Helpers are injected into the script scope, not imported by agent scripts.
-- New public helpers go through `helperContext()` in `src/helpers.ts` and need JSDoc (it feeds `help()`); keep `SKILL.md` in sync.
+- New v2 APIs go through `public-api-schema.ts`; keep runtime validation,
+ generated reference, architecture, and `SKILL.md` in sync.
- Snapshot refs (`@N`) are short-lived; re-snapshot after navigation or DOM changes and prefer stable `loc=...` values for reuse.
- Element-resolution failures should use `ElementResolutionError` with an honest `transient`/`permanent` kind — wait loops rely on it.
- The code prefers the small shared state singleton (`src/state.ts`) over threading connection state through call sites.
- Site skills must stay site-shaped and verifiable: stable URLs, durable selectors, no pixel coordinates, no secrets.
## Testing & QA
+
- Framework: Node's built-in runner (`node --test`), assertions via `node:assert/strict`.
- Tests run against the build output (`dist/src/...`) — `npm test` builds first.
-- Behavior-focused tests inject overrides (`__testing.setOverrides`) or a `FakeEgo` double (see `src/helpers.test.mjs`, `src/taskspace-e2e.test.mjs`).
+- 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.
+ Do not link another runtime, reuse a prior E2E space, or manually take control
+ while the suite is running.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c9dd324..0c7d711 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,7 +2,7 @@
Thanks for your interest in contributing to **ego-browser (ego-lite)**! This guide is aimed at developers who want to build on top of the project or submit patches upstream. It covers the architecture, local development workflow, code conventions, and PR process.
-> For the project vision, see [`README.md`](./README.md). For the agent-facing runbook, see [`skills/ego-browser/SKILL.md`](./skills/ego-browser/SKILL.md) (or [`SKILL.zh.md`](./skills/ego-browser/SKILL.zh.md)). For repo-level guidance, see [`AGENTS.md`](./AGENTS.md).
+> For the project vision, see [`README.md`](./README.md). For the agent-facing runbook, see [`skills/ego-browser/SKILL.md`](./skills/ego-browser/SKILL.md). For repo-level guidance, see [`AGENTS.md`](./AGENTS.md).
---
@@ -42,8 +42,10 @@ ego-lite/
│ │ ├── index.ts # SDK / CLI bootstrap
│ │ ├── run.ts # stdin executor, CLI entry
│ │ ├── helpers.ts # Public helper surface composition
+│ │ ├── page-model.ts # TaskSpace / Page lifecycle and operations
+│ │ ├── public-api-schema.ts# v2 validation, help, and reference source
│ │ ├── browser-runtime.ts # CDP transport and session cache
-│ │ ├── element-resolver.ts # @eN / CSS / XPath / ARIA resolution
+│ │ ├── element-resolver.ts # @N / CSS / XPath / ARIA resolution
│ │ ├── cdp-eval.ts # cdp() / js() helpers
│ │ ├── state.ts # Shared mutable runtime state (singleton)
│ │ ├── env.ts # Environment variables
@@ -58,13 +60,13 @@ ego-lite/
│ ├── scripts/
│ │ ├── build.mjs # esbuild + rollup bundler
│ │ └── validate-site-skills.ts
-│ ├── test/ # node --test suites
-│ ├── artifacts/ # Build output (published to GitHub Release by CI)
-│ ├── dist/ # tsc output (gitignored)
+│ ├── test/real-browser-e2e/ # Real-browser fixtures and harness tests
+│ ├── dist/ # Build output (gitignored)
│ ├── package.json
│ └── tsconfig.json
├── skills/ego-browser/ # Agent skill package
-│ ├── SKILL.md / SKILL.zh.md # Agent usage guide
+│ ├── SKILL.md # Canonical agent usage guide
+│ ├── references/api.md # Generated v2 API reference
│ └── learnings/<site>/ # Per-site knowledge packs (github / google / x-com ...)
├── spec/ # Spec references
├── public/ # Demo assets
@@ -78,14 +80,14 @@ ego-lite/
## 3. Tech Stack & Runtime
-| Item | Choice |
-| --- | --- |
-| Language | TypeScript (`tsc --noEmit` for typecheck only) |
-| Runtime | Node.js **>= 22**, ESM only (`"type": "module"`) |
-| Package manager | npm (commit `package-lock.json`) |
-| Bundler | esbuild + rollup (output: `artifacts/ego-browser/index.js`) |
-| Tests | Node built-in `node --test` + `node:assert/strict` |
-| Runtime deps | Only `acorn` (lightweight parsing) |
+| Item | Choice |
+| ----------------- | ----------------------------------------------------------------------- |
+| Language | TypeScript (`tsc --noEmit` for typecheck only) |
+| Runtime | Node.js **>= 22**, ESM only (`"type": "module"`) |
+| Package manager | npm (commit `package-lock.json`) |
+| Bundler | esbuild + rollup (output: `dist/out/index.js`) |
+| Tests | Node built-in `node --test` + `node:assert/strict` |
+| Runtime deps | Only `acorn` (lightweight parsing) |
| Browser transport | Chrome DevTools Protocol (CDP) directly — **no Puppeteer / Playwright** |
---
@@ -99,7 +101,7 @@ ego-lite/
cd package/ego-browser
npm ci
-# 2. Build (produces dist/ and artifacts/ego-browser/index.js)
+# 2. Build (produces dist/out/index.js and dist/src/)
npm run build
# 3. Typecheck
@@ -115,9 +117,8 @@ npm run validate:site-skills # alias: validate:learnings
**Calling the CLI directly** (for local debugging):
```bash
-node artifacts/ego-browser/index.js <<'JS'
-await waitForLoad()
-cliLog(await pageInfo())
+node dist/out/index.js <<'JS'
+console.log(await help())
JS
```
@@ -130,11 +131,11 @@ JS
**Key environment variables**:
-| Variable | Purpose |
-| --- | --- |
+| Variable | Purpose |
+| ----------------------------- | -------------------------------------------------------------------------------- |
| `EGO_BROWSER_AGENT_WORKSPACE` | Override skill workspace root (defaults to `skills/ego-browser` inside the repo) |
-| `EGO_BROWSER_NAME` | Browser instance name (default `default`) |
-| `EGO_BROWSER_DEBUG_CLICKS` | Enable click debug logging |
+| `EGO_BROWSER_NAME` | Browser instance name (default `default`) |
+| `EGO_BROWSER_DEBUG_CLICKS` | Enable click debug logging |
---
@@ -181,27 +182,33 @@ stdin JS → runMain() → injected helpers → CDP / DOM / AX resolution → op
### Task Space Model
A `Task Space` is an isolated browsing context provided by ego-browser: it owns its own tab set but inherits the user's login state.
-Because every heredoc runs in a fresh Node process, **the agent must call `useOrCreateTaskSpace(name)` at the start of every heredoc to re-attach to the same task space**, and end with `completeTaskSpace(name, { keep })` in the final round.
+Because every heredoc runs in a fresh Node process, new scripts call
+`taskSpace(nameOrId)` in each round, restore Pages by durable label, and end with
+`task.finish()` or `task.close()`.
-Control (`agent` ↔ `user`) is handed off via the `handOffTaskSpace` / `takeOverTaskSpace` / `waitForAgentControl` protocol — for example, when the user needs to log in manually or solve a CAPTCHA.
+Control is handed to the user with `task.handOff()` and resumed, after user
+approval, with `takeOverTaskSpace(spaceId)`. The old global helpers remain a v1
+compatibility surface; see `docs/legacy-api-compatibility.md`.
---
## 6. Key Modules
-| File | Responsibility |
-| --- | --- |
-| `src/index.ts` | SDK injection (`installEgoSdk`); decides whether to run as CLI or be imported as a library |
-| `src/run.ts` | Reads stdin, builds an `AsyncFunction`, and invokes it with helpers as named arguments |
-| `src/helpers.ts` | Composes and exports the helper set exposed to heredocs |
-| `src/browser-runtime.ts` | Maintains the CDP connection, session cache, and event buffer for the browser's ego runtime |
-| `src/element-resolver.ts` | Resolves `@eN` refs, CSS, XPath, and ARIA/role to backend nodeIds |
-| `src/cdp-eval.ts` | `cdp()` raw CDP calls + `js()` in-page evaluation |
-| `src/state.ts` | Shared mutable state singleton (`send`, `platform`, `agentWorkspace`, session caches). Tests can inject stubs via `setOverrides()` |
-| `src/driver/*` | Minimal-dependency primitives per capability; only call into `cdp()` |
-| `src/learning/index.ts` | Discovers and loads `learnings/<site>/`, exposes `runSiteTool` / `runSiteBrowserTool` |
-| `src/learning/validate-learning-format.ts` | Site manifest validator |
-| `scripts/build.mjs` | Uses `.build.lock` to prevent concurrent builds; esbuild transform + rollup bundle into a single file |
+| File | Responsibility |
+| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
+| `src/index.ts` | SDK injection (`installEgoSdk`); decides whether to run as CLI or be imported as a library |
+| `src/run.ts` | Reads stdin, builds an `AsyncFunction`, and invokes it with helpers as named arguments |
+| `src/helpers.ts` | Composes and exports the helper set exposed to heredocs |
+| `src/page-model.ts` | Implements the v2 TaskSpace/Page lifecycle and operations |
+| `src/public-api-schema.ts` | Defines v2 validation, default help, and the generated API reference |
+| `src/browser-runtime.ts` | Maintains the CDP connection, session cache, and event buffer for the browser's ego runtime |
+| `src/element-resolver.ts` | Resolves `@N` refs, CSS, XPath, and ARIA/role to backend nodeIds |
+| `src/cdp-eval.ts` | `cdp()` raw CDP calls + `js()` in-page evaluation |
+| `src/state.ts` | Shared mutable state singleton (`send`, `platform`, `agentWorkspace`, session caches). Tests can inject stubs via `setOverrides()` |
+| `src/driver/*` | Minimal-dependency primitives per capability; only call into `cdp()` |
+| `src/learning/index.ts` | Discovers and loads `learnings/<site>/`, exposes `runSiteTool` / `runSiteBrowserTool` |
+| `src/learning/validate-learning-format.ts` | Site manifest validator |
+| `scripts/build.mjs` | Uses `.build.lock` to prevent concurrent builds; esbuild transform + rollup bundle into a single file |
> Historical note: the repo is migrating from `.js` to `.ts`. If `AGENTS.md` still mentions `.js` files, defer to the current `src/*.ts`.
@@ -235,15 +242,19 @@ learnings/<site>/
- Use **stable URLs** and **stable selectors** (CSS / ARIA / text) only
- Never write **pixel coordinates**, **secrets/tokens**, or **task narration**
-- Capture the *shape* of the site, not your task — a "map", not a "diary"
+- Capture the _shape_ of the site, not your task — a "map", not a "diary"
---
## 8. Testing & Quality
- Test framework: `node --test` with `node:assert/strict`
-- Test files: `package/ego-browser/test/*.test.js`, split by responsibility (runtime / helpers / resolver / nav-driver / site-skills / build / state ...)
-- Style: behavior-driven, using **temp workspaces + `setOverrides()`** for stub injection — no real browser launches
+- Tests are colocated in `package/ego-browser/src/**/*.test.mjs`, with a small
+ set of package tests in `package/ego-browser/test/*.test.js`.
+- Unit tests use temporary workspaces, overrides, or a fake Ego binding.
+- `npm run e2e` is the self-contained real-browser suite. It builds the current
+ checkout, launches it through `--sdk-path`, uses a unique temporary space,
+ and cleans up without manual browser interaction.
**Minimum pre-submit bar**:
@@ -251,14 +262,18 @@ learnings/<site>/
cd package/ego-browser
npm test # must pass
npm run validate:site-skills # if learnings changed
+npm run e2e # for real browser or task-space behavior
```
**When to add/extend tests**:
-- Changes to session / connection handling → add cases in `browser-runtime.test.js` / `session-injection.test.js`
-- Changes to the resolver → `element-resolver.test.js`
-- New helper → `helpers.test.js` or the matching driver test
-- Changes to learning loading → `site-skills.test.js` / `validate-site-skills.test.js`
+- Changes to session or connection handling → `src/browser-runtime.test.mjs`
+- Changes to the resolver → `src/element-resolver.test.mjs`
+- Changes to the v2 Page surface → `src/page-model.test.mjs`,
+ `src/public-api-schema.test.mjs`, and the relevant real-browser E2E case
+- New public v2 API → update `src/public-api-schema.ts`, regenerate
+ `skills/ego-browser/references/api.md`, and update the Skill and architecture
+- Changes to learning loading → the matching `src/**/*.test.mjs` suite
---
@@ -271,8 +286,8 @@ npm run validate:site-skills # if learnings changed
- **TypeScript non-strict mode**: `strict: false`, but keep explicit type signatures
- **Shared state goes through the `state.ts` singleton** — do not thread `connection` / `send` through function parameters
- **Helpers are injected, not imported**: agent scripts do not `import`; all helpers are placed in scope by `run.ts`
-- **Snapshot refs (`@eN`) are short-lived**: re-snapshot after any DOM mutation; for long-lived values use `loc=...` or stable CSS / ARIA
-- **No lint / prettier**: style is enforced by convention and code review. When editing, blend in with the surrounding code instead of introducing a new style
+- **Snapshot refs (`@N`) are short-lived**: re-snapshot after navigation or DOM changes; for long-lived values use `loc=...` or stable CSS / ARIA
+- **Formatting**: run `npm run style:check`; keep edits consistent with the surrounding code
---
@@ -305,10 +320,11 @@ Add at least one release-note label so generated releases are grouped correctly:
- [ ] `npm test` is green
- [ ] Typecheck passes (`npm run typecheck`)
+- [ ] `npm run e2e` is green when real browser or task-space behavior changed
- [ ] If learnings changed, `npm run validate:site-skills` passes
- [ ] Change is "minimal surgical edit" (see §12)
- [ ] No undeclared runtime dependencies introduced
-- [ ] Public helper names / docs are kept in sync (update both `SKILL.md` and `SKILL.zh.md`)
+- [ ] Public API schema, generated reference, `SKILL.md`, and architecture docs are kept in sync
---
@@ -329,12 +345,12 @@ Add at least one release-note label so generated releases are grouped correctly:
This repo strongly endorses the four principles below (see [`AGENTS.md`](./AGENTS.md)). Both human contributors and AI agents should apply them on every change:
-| Principle | Meaning |
-| --- | --- |
-| **Think Before Coding** | Don't assume, don't paper over confusion; surface trade-offs explicitly and push back when needed |
-| **Simplicity First** | The smallest amount of code that solves the problem; no speculative abstractions or configuration |
-| **Surgical Changes** | Change only what needs to change; preserve the existing style; do not opportunistically "improve" unrelated code |
-| **Goal-Driven Execution** | Translate the task into a verifiable goal; write the check first, then iterate until it passes |
+| Principle | Meaning |
+| ------------------------- | ---------------------------------------------------------------------------------------------------------------- |
+| **Think Before Coding** | Don't assume, don't paper over confusion; surface trade-offs explicitly and push back when needed |
+| **Simplicity First** | The smallest amount of code that solves the problem; no speculative abstractions or configuration |
+| **Surgical Changes** | Change only what needs to change; preserve the existing style; do not opportunistically "improve" unrelated code |
+| **Goal-Driven Execution** | Translate the task into a verifiable goal; write the check first, then iterate until it passes |
> "Every changed line should trace back to the requirement of this task."
diff --git a/docs/legacy-api-compatibility.md b/docs/legacy-api-compatibility.md
index 5636119..5076ecd 100644
--- a/docs/legacy-api-compatibility.md
+++ b/docs/legacy-api-compatibility.md
@@ -11,6 +11,10 @@ ego-browser 2.x 会为 Agent 提供新的 `TaskSpace` / `Page` API,但不会
因此,“旧接口不可见”只针对 Agent 文档和发现机制,不表示运行时删除。
+这里的兼容范围只包括 1.2.3 公共接口,不包括 2.0 beta 开发期间出现过的新版
+方法。比如旧版 beta 的 `task.listPages()` 已拆成 `task.pages()` 和
+`task.tabs()`,不会保留别名。
+
## 兼容承诺
1. 1.2.3 已有 helper 保持原来的参数、错误语义和副作用。
diff --git a/docs/local-runtime-development.md b/docs/local-runtime-development.md
index 7c27ea7..0b7a0b9 100644
--- a/docs/local-runtime-development.md
+++ b/docs/local-runtime-development.md
@@ -63,6 +63,12 @@ installed CLI with `--sdk-path`. This is the preferred end-to-end compatibility
check. `npm test` remains useful for repository tests but does not replace the
real-browser check.
+The command is self-contained: it starts its own local fixture server, creates a
+uniquely named temporary task space, and cleans both up. No manual SDK linking,
+task-space selection, takeover, or browser interaction is part of a successful
+run. A fresh agent can use this command without any context from an earlier
+debugging session.
+
## Keep the Skill aligned
The Skill describes the APIs implemented by the runtime. When an agent is used,
diff --git a/docs/runtime-v2-architecture.md b/docs/runtime-v2-architecture.md
index bce6a95..878355c 100644
--- a/docs/runtime-v2-architecture.md
+++ b/docs/runtime-v2-architecture.md
@@ -127,7 +127,7 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target
### 4.3 浏览器事实与账本事实
浏览器决定一个 tab 是否仍存在;账本决定它是否受 Page 模型管理。
-`listPages()`、`openPage()` 等盘点入口会用 `listTabs()` 对账:
+`pages()`、`tabs()`、`openPage()` 等盘点入口会用原生 `listTabs()` 对账:
- 浏览器中已经消失的受管页面从账本移除,但标签仍保持已使用状态。
- 第一次观察一个 space 时,已有 tab 记为 `unknown`,不会猜测它们由谁创建。
@@ -169,14 +169,18 @@ placeholder 文档当成新页面。创建成功但文档仍未稳定时,标
### 5.3 Adopt 和 release
-`task.listPages()` 同时返回受管 Page 和只读 `UnmanagedPage`:
+`task.pages()` 返回所有受管 Page。`task.tabs()` 返回完整 tab 清单,其中既有受管
+Page,也有只读 `UnmanagedPage`:
```js
-const pages = await task.listPages();
-const unknown = pages.find((item) => !item.label);
+const pages = await task.pages();
+const tabs = await task.tabs();
+const unknown = tabs.find((item) => !item.label);
const adopted = await task.adopt(unknown.page, { as: "reference" });
```
+两个方法都是异步的,因为返回前会先把浏览器中的 tab 与页面账本对齐。
+
`UnmanagedPage` 只有身份信息,不能直接导航、点击或关闭。调用 `adopt()` 后才
获得完整 Page。
@@ -186,7 +190,7 @@ Agent 创建的页面不能 release,必须显式 close,避免制造无人管
### 5.4 Popup
高层页面动作会在动作前后比较 tab 列表。立即出现的新 tab 会自动获得标签,
-并进入动作回执。传播较慢的 popup 会在下一次 `listPages()`、`openPage()` 或
+并进入动作回执。传播较慢的 popup 会在下一次 `pages()`、`tabs()`、`openPage()` 或
下一轮盘点时收编。
当 space 从未交给用户控制时,新出现的 tab 可以归因于 Agent 或 Agent 触发的
@@ -218,7 +222,8 @@ task.ownership;
task.page(label);
task.userPage();
-await task.listPages();
+await task.pages();
+await task.tabs();
await task.openPage(url, { as, timeout });
await task.adopt(unmanagedPage, { as });
await task.release(label);
@@ -251,6 +256,7 @@ await page.snapshot(options)
await page.screenshot({ path, fullPage, clip, raw })
await page.url()
await page.waitForURL(urlOrRegExp, { timeout })
+await page.waitForTimeout(timeout)
await page.title()
await page.info()
await page.evaluate(fnOrString, arg?)
@@ -278,6 +284,9 @@ await page.close()
options 中;`fullPage` 表示捕获完整页面。`waitForSelector()` 的 `state` 支持
`attached`、`detached`、`visible` 和 `hidden`,默认是 `visible`。
`waitForURL()` 接受完整 URL 字符串或正则表达式,默认等待 10,000ms。
+`waitForTimeout()` 只等待指定毫秒数,不激活 Page,也不占用 native operation
+gate。它主要用于调试和短暂的视觉稳定;正常流程优先等待 URL、selector 或
+load state。
CSS selector 会在 document 和每一层 open shadow root 中查找,因而 Shadow DOM
节点也可以通过 `loc=css:` 或 raw CSS 操作。selector 应描述元素在自身 tree scope
@@ -348,11 +357,12 @@ Ego Lite 更新 Agent 光标。`fill()` 只更新可见光标,不会额外向
下面的操作会先激活目标 Page:
- snapshot、screenshot
-- goto、evaluate、fetch、page.cdp
+- goto、evaluate、fetch、page.cdp(处理已打开的 JavaScript dialog 除外)
- selector action 和 wait
- mouse、keyboard、scrollBy
-`url()`、`waitForURL()`、`title()`、`info()` 和 `events()` 不改变当前激活页。
+`url()`、`waitForURL()`、`waitForTimeout()`、`title()`、`info()` 和 `events()`
+不改变当前激活页。
激活目标页是有意行为。真实 Ego Lite 测试中,后台页输入曾出现 CDP 超时并
退化为 `isTrusted=false` 的合成事件;激活后可保持正常 CDP Input 路径。
@@ -378,6 +388,8 @@ popup 回执:
`Page.javascriptDialogOpening` 后会中断该输入等待,让高层动作立即返回
`{ dialog }`;dialog 本身保持打开,由调用方随后 accept 或 dismiss。这样不会依赖
15 秒 CDP 超时,也不会让双击或连续输入在 dialog 关闭后继续执行剩余步骤。
+`Page.handleJavaScriptDialog` 直接使用该 Page 已有的 session,不会在 dialog 打开时
+重复激活页面;Ego Lite 可能把这种重复激活解释为用户接管。
底层原语不安装动作探针,也不等待 50ms 反馈窗口:
@@ -492,6 +504,8 @@ surface,不属于本阶段。
- 多个 Page 的 session、事件和同号 ref 不串页。
- 跨 space 操作按 gate 串行并落到正确 space。
- 页面预算在创建前拒绝,错误给出可执行的 close/goto 建议。
+- `pages()` 只返回受管 Page;`tabs()` 还返回未受管 tab,二者都会先完成盘点。
+- `waitForTimeout()` 校验毫秒参数,不激活 Page,也不阻塞其他 space 的操作。
- 首次存在的 unknown tab 不被自动收编;Agent 控制期间的新 tab 会被收编。
- handoff 期间用户新开的 tab 在 takeover 后保持 unknown;`userPage()` 返回边界
时激活的 tab。
diff --git a/package/ego-browser/README.md b/package/ego-browser/README.md
index b0d9f48..ae980d1 100644
--- a/package/ego-browser/README.md
+++ b/package/ego-browser/README.md
@@ -14,13 +14,13 @@ npm run build # bundle to dist/out/index.js
npm test # build + tsc --noEmit + node --test
```
-The build emits a single ESM file `dist/out/index.js`. The ego-browser browser dispatches `ego-browser nodejs <<'EOF' ... EOF` heredocs to that bundle. Inside the heredoc, all helpers (`snapshotText`, `click`, `useOrCreateTaskSpace`, ...) are pre-imported in camelCase.
+The build emits a single ESM file `dist/out/index.js`. The ego-browser browser dispatches `ego-browser nodejs <<'EOF' ... EOF` heredocs to that bundle. The v2 `TaskSpace` and `Page` APIs are preloaded; the v1 global helpers remain available only for existing scripts.
```bash
ego-browser nodejs <<'EOF'
-await useOrCreateTaskSpace('demo')
-await openOrReuseTab('https://example.com', { wait: true })
-cliLog(await snapshotText())
+const task = await taskSpace('demo')
+const page = await task.openPage('https://example.com', { as: 'main' })
+console.log(await page.snapshot())
EOF
```
@@ -28,7 +28,7 @@ Local invocation without the browser (for debugging the helper bundle itself) re
```bash
node dist/out/index.js <<'JS'
-cliLog(await pageInfo())
+console.log(await help())
JS
```
@@ -62,8 +62,10 @@ npm run validate:site-skills # alias: validate:learnings
src/
run.ts CLI entry; reads stdin, injects helpers, executes
helpers.ts public helper surface (re-exports + glue)
+ page-model.ts TaskSpace/Page lifecycle and operations
+ public-api-schema.ts v2 validation, help, and reference source
browser-runtime.ts bridge to globalThis.ego (CDP, sessions, events)
- element-resolver.ts resolves @eN / CSS / XPath / ARIA targets
+ element-resolver.ts resolves @N / CSS / XPath / ARIA targets
driver/
pointer.ts click, hover, drag, scroll, scrollBy
observe.ts snapshot, captureScreenshot, elementCenter
@@ -79,13 +81,17 @@ scripts/
build.mjs esbuild bundling
```
-The top-level repo README has the full helper inventory and the task-space / control-handoff protocol. See also `../../skills/ego-browser/SKILL.md` for the agent-facing contract.
+See `../../skills/ego-browser/SKILL.md` for the agent-facing workflow and
+`../../skills/ego-browser/references/api.md` for the generated v2 API reference.
+The v1 compatibility contract is documented in
+`../../docs/legacy-api-compatibility.md`.
## Design constraints
- The browser runtime owns tabs, task spaces, CDP transport, snapshots, and event delivery. This package keeps only agent-facing ergonomics.
- Snapshot helpers use the browser runtime contract: `ego.snapshot({ scope, includeActionMarks, includeStableLocator })`.
-- Public helpers are camelCase only.
+- New public APIs must be added to `public-api-schema.ts`; runtime validation,
+ default `help()`, the generated reference, and the Skill must remain aligned.
- Site-specific reusable experience belongs under `skills/ego-browser/learnings/`, not in this package.
## License
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
index 3b6fa0a..5d79b9d 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs
@@ -55,6 +55,14 @@ export function helperSurfaceCase() {
assertEqual(typeof globalThis.newTab, "undefined", "internal newTab is not exposed");
const defaultHelp = help();
assertIncludes(defaultHelp, "TaskSpace.openPage", "default help presents the v2 object API");
+ assertIncludes(defaultHelp, "TaskSpace.pages", "default help presents managed Pages");
+ assertIncludes(defaultHelp, "TaskSpace.tabs", "default help presents tab inventory");
+ assertIncludes(defaultHelp, "Page.waitForTimeout", "default help presents fixed waits");
+ assertIncludes(
+ help("TaskSpace.listPages"),
+ "Unknown helper",
+ "removed v2 methods do not remain as help aliases"
+ );
assertIncludes(
help("click"),
"Legacy helper hidden from default help",
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
index d2ab377..864b12f 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs
@@ -57,13 +57,23 @@ export function pageJavaScriptDialogsCase() {
return receipt.dialog;
}
+ async function assertAgentStillControls(stage) {
+ const pages = await task.pages();
+ assert(
+ pages.some((candidate) => candidate.label === page.label),
+ stage + " keeps the E2E task space under Agent control"
+ );
+ }
+
await openDialog("#dialog-alert", "alert", "Alert from real E2E");
await page.cdp("Page.handleJavaScriptDialog", { accept: true });
await page.waitForSelector('[data-value="alert:continued"]', { timeout: 2_000 });
+ await assertAgentStillControls("handling alert");
await openDialog("#dialog-confirm", "confirm", "Confirm from real E2E");
await page.cdp("Page.handleJavaScriptDialog", { accept: false });
await page.waitForSelector('[data-value="confirm:false"]', { timeout: 2_000 });
+ await assertAgentStillControls("handling confirm");
const promptDialog = await openDialog(
"#dialog-prompt",
@@ -82,6 +92,7 @@ export function pageJavaScriptDialogsCase() {
await page.waitForSelector('[data-value="prompt:replacement answer"]', {
timeout: 2_000,
});
+ await assertAgentStillControls("handling prompt");
assertEqual(
await page.evaluate("document.querySelector('#dialog-result').textContent"),
"prompt:replacement answer",
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
index 7acc4ef..5b43b69 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
@@ -11,13 +11,18 @@ export function pageLabelCreateCase() {
const refLine = snapshot.split("\\n").find((line) => line.includes("Increment counter"));
const refMatch = refLine && refLine.match(/\\[ref=([0-9]+)/);
assert(refMatch, "snapshot exposes a ref for the cross-round action");
- const inventory = await task.listPages();
+ const inventory = await task.tabs();
const managed = inventory.find((item) => item.label === page.label);
- assertEqual(managed.page.targetId, page.targetId, "listPages returns the managed Page handle");
- assertEqual(managed.openedBy, "agent", "listPages identifies managed page origin");
+ const managedPages = await task.pages();
+ assertEqual(managed.page.targetId, page.targetId, "tabs returns the managed Page handle");
+ assertEqual(managed.openedBy, "agent", "tabs identifies managed page origin");
+ assertEqual(managedPages.length, 1, "pages excludes unmanaged tabs");
+ assertEqual(managedPages[0].label, page.label, "pages returns the managed Page directly");
+ assertEqual(typeof managedPages[0].url, "function", "pages returns Page methods");
+ assertEqual(typeof task.listPages, "undefined", "the replaced listPages method is absent");
assert(
inventory.some((item) => item.label === undefined && item.openedBy === "unknown"),
- "listPages preserves untracked browser tabs as unknown"
+ "tabs preserves untracked browser tabs as unknown"
);
await writeFile(
join(tempDir, "managed-page.json"),
@@ -73,10 +78,10 @@ export function pageLabelCloseCase() {
if (!(await listTabs()).some((tab) => tab.targetId === next.targetId)) break;
await wait(0.05);
}
- const reconciled = await task.listPages();
+ const reconciled = await task.tabs();
assert(
!reconciled.some((item) => item.label === "p2"),
- "listPages removes a managed page closed outside the object API"
+ "tabs removes a managed page closed outside the object API"
);
await assertRejects(
() => task.page("p2").snapshot(),
@@ -120,7 +125,7 @@ export function pageBudgetCase() {
const managed = [];
for (let index = 0; index < 3; index += 1) {
managed.push(await task.openPage(baseUrl + "/secondary?budget=" + index));
- const inventory = await task.listPages();
+ const inventory = await task.tabs();
assertEqual(
inventory.filter((item) => item.label !== undefined).length,
index + 1,
@@ -135,11 +140,11 @@ export function pageBudgetCase() {
);
const afterReject = await listTabs();
assertEqual(afterReject.length, beforeReject.length, "budget rejects before creating a browser tab");
- const inventory = await task.listPages();
+ const inventory = await task.tabs();
assertEqual(
inventory.filter((item) => item.label !== undefined).length,
3,
- "listPages reports every managed page at the budget limit"
+ "tabs reports every managed page at the budget limit"
);
for (const page of managed) await page.close();
`;
@@ -148,9 +153,9 @@ export function pageBudgetCase() {
export function pageAdoptionCase() {
return `
const task = await taskSpace(taskName);
- const beforeAdopt = await task.listPages();
+ const beforeAdopt = await task.tabs();
const untracked = beforeAdopt.find((item) => item.label === undefined);
- assert(Boolean(untracked), "listPages preserves a tab from before the control boundary");
+ assert(Boolean(untracked), "tabs preserves a tab from before the control boundary");
const source = untracked.page;
assertEqual(untracked.page.targetId, source.targetId, "untracked handle keeps the target id");
assertEqual(untracked.page.snapshot, undefined, "untracked handle cannot snapshot directly");
@@ -170,7 +175,7 @@ export function pageAdoptionCase() {
"release leaves the browser tab open"
);
assertEqual(
- (await task.listPages()).find((item) => item.targetId === source.targetId).label,
+ (await task.tabs()).find((item) => item.targetId === source.targetId).label,
undefined,
"release removes the durable label"
);
@@ -213,6 +218,14 @@ export function pageBasicOperationsCase() {
assertIncludes(info.url, "page-api=first", "page.info reads its own URL");
assert(info.w > 0 && info.h > 0, "page.info reports a usable viewport");
assertEqual((await currentTab()).targetId, second.targetId, "metadata reads do not activate their page");
+ const waitStartedAt = Date.now();
+ await first.waitForTimeout(25);
+ assert(Date.now() - waitStartedAt >= 20, "waitForTimeout waits in milliseconds");
+ assertEqual(
+ (await currentTab()).targetId,
+ second.targetId,
+ "waitForTimeout does not activate its Page"
+ );
const baselineSnapshot = await first.snapshot();
assertIncludes(baselineSnapshot, 'page-api-first', "snapshot identifies its source Page");
assertIncludes(baselineSnapshot, 'space "' + taskName + '"', "snapshot identifies its task space");
@@ -365,7 +378,7 @@ export function pageBasicOperationsCase() {
export function pageActionsAndPopupCase() {
return `
const task = await taskSpace(taskName);
- const unknownBefore = (await task.listPages())
+ const unknownBefore = (await task.tabs())
.filter((item) => item.label === undefined)
.map((item) => item.targetId);
assert(unknownBefore.length > 0, "the control-boundary inventory keeps pre-existing tabs untracked");
@@ -575,7 +588,7 @@ export function pageActionsAndPopupCase() {
"page-actions=popup",
"the receipt label resolves the popup Page"
);
- const inventory = await task.listPages();
+ const inventory = await task.tabs();
assertEqual(
inventory.find((item) => item.targetId === popup.targetId).openedBy,
"agent",
@@ -583,7 +596,7 @@ export function pageActionsAndPopupCase() {
);
// Simulate the action-receipt window missing this otherwise real popup.
- // listPages must discover the live target independently and restore a
+ // tabs must discover the live target independently and restore a
// managed label; popup lifecycle cannot depend on the short receipt diff.
const ledgerPath = join(
process.env.EGO_BROWSER_STATE_DIR,
@@ -592,9 +605,9 @@ export function pageActionsAndPopupCase() {
const ledger = JSON.parse(await readFile(ledgerPath, "utf8"));
delete ledger.pages[popup.label];
await writeFile(ledgerPath, JSON.stringify(ledger));
- const afterReconcile = await task.listPages();
+ const afterReconcile = await task.tabs();
const reconciledPopup = afterReconcile.find((item) => item.targetId === popup.targetId);
- assert(Boolean(reconciledPopup?.label), "listPages adopts a popup missed by action receipts");
+ assert(Boolean(reconciledPopup?.label), "tabs adopts a popup missed by action receipts");
assertEqual(reconciledPopup.openedBy, "agent", "the reconciled popup keeps Agent origin");
assert(
unknownBefore.every(
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 3c3888c..70df008 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -139,7 +139,9 @@ test("taskSpace returns the new object model for a resolved space", async () =>
assert.equal(typeof task.openPage, "function");
assert.equal(task.newPage, undefined);
assert.equal(typeof task.page, "function");
- assert.equal(typeof task.listPages, "function");
+ assert.equal(typeof task.pages, "function");
+ assert.equal(typeof task.tabs, "function");
+ assert.equal(task.listPages, undefined);
assert.equal(typeof task.adopt, "function");
assert.equal(typeof task.release, "function");
assert.equal(typeof task.handOff, "function");
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index c5fcea6..feac453 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -575,6 +575,32 @@ test("TaskSpace.waitForControl times out in milliseconds and validates options",
});
});
+test("Page.waitForTimeout validates and waits in milliseconds without activating the Page", async () => {
+ await withFixture(async (fixture) => {
+ const waits = [];
+ const task = taskForRound(fixture, "round-a", {
+ async sleep(ms) {
+ waits.push(ms);
+ },
+ });
+ const page = await task.openPage("https://example.test/timer");
+ fixture.calls.length = 0;
+
+ await page.waitForTimeout(125);
+
+ assert.deepEqual(waits, [125]);
+ assert.deepEqual(fixture.calls, []);
+ await assert.rejects(
+ () => page.waitForTimeout(-1),
+ /page\.waitForTimeout requires a non-negative number of milliseconds/,
+ );
+ await assert.rejects(
+ () => page.waitForTimeout(Number.POSITIVE_INFINITY),
+ /page\.waitForTimeout requires a non-negative number of milliseconds/,
+ );
+ });
+});
+
test("v2 methods reject option fields that are absent from the public schema", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -654,13 +680,13 @@ test("handoff preserves user-created tabs as unknown and captures the active use
assert.equal(userPage.targetId, "target-user");
assert.equal(userPage.openedBy, "unknown");
- const inventory = await afterTakeover.listPages();
+ const inventory = await afterTakeover.tabs();
const userItem = inventory.find((item) => item.targetId === "target-user");
assert.equal(userItem.label, undefined);
assert.equal(userItem.openedBy, "unknown");
fixture.addExternalTab("target-popup", "https://example.test/agent-popup");
- const reconciled = await afterTakeover.listPages();
+ const reconciled = await afterTakeover.tabs();
assert.equal(
reconciled.find((item) => item.targetId === "target-popup").openedBy,
"agent",
@@ -1030,7 +1056,7 @@ test("Page click fails closed when native mouse dispatch times out", async () =>
() => first.click("#open-popup"),
/CDP request timed out: Input\.dispatchMouseEvent/,
);
- const inventory = await task.listPages();
+ const inventory = await task.tabs();
assert.equal(
inventory.find((item) => item.targetId === "target-user").label,
undefined,
@@ -1077,7 +1103,26 @@ test("Page click returns a pending JavaScript dialog without waiting for input c
},
});
+ const activationsBeforeHandle = fixture.calls.filter(
+ ([kind, method]) => kind === "cdp" && method === "Target.activateTarget",
+ ).length;
await page.cdp("Page.handleJavaScriptDialog", { accept: true });
+ assert.equal(
+ fixture.calls.filter(
+ ([kind, method]) =>
+ kind === "cdp" && method === "Target.activateTarget",
+ ).length,
+ activationsBeforeHandle,
+ "handling a modal dialog must not re-activate its already active Page",
+ );
+ assert(
+ fixture.calls.some(
+ ([kind, method, , sessionId]) =>
+ kind === "cdp" &&
+ method === "Page.handleJavaScriptDialog" &&
+ sessionId === "session:target-1",
+ ),
+ );
assert.equal((await page.info()).url, "https://example.test/dialog");
});
});
@@ -2293,7 +2338,7 @@ test("close keeps the page managed when the target never disappears", async () =
await assert.rejects(() => page.close(), /did not close within 2000ms/);
- const inventory = await task.listPages();
+ const inventory = await task.tabs();
assert.equal(inventory[0].label, page.label);
assert.equal(await page.title(), "https://example.test/first");
});
@@ -2329,7 +2374,7 @@ test("a ledger failure closes the newly created uncommitted tab", async () => {
});
});
-test("listPages combines managed labels with live browser information", async () => {
+test("pages returns managed Page handles while tabs returns the complete inventory", async () => {
await withFixture(async (fixture) => {
fixture.tabs.set("target-user", {
targetId: "target-user",
@@ -2339,15 +2384,34 @@ test("listPages combines managed labels with live browser information", async ()
});
const task = taskForRound(fixture, "round-a");
const managed = await task.openPage("https://example.test/managed");
+ fixture.tabs.set("target-popup", {
+ targetId: "target-popup",
+ url: "https://example.test/popup",
+ title: "Late popup",
+ active: false,
+ });
- const pages = await task.listPages();
- const managedItem = pages.find((item) => item.label === "p1");
- const unknownItem = pages.find((item) => item.targetId === "target-user");
+ const pages = await task.pages();
+ const tabs = await task.tabs();
+ const managedItem = tabs.find((item) => item.label === "p1");
+ const popupItem = tabs.find((item) => item.label === "p2");
+ const unknownItem = tabs.find((item) => item.targetId === "target-user");
+ assert.deepEqual(
+ pages.map((page) => page.label),
+ ["p1", "p2"],
+ );
+ assert(pages.every((page) => typeof page.url === "function"));
+ assert.equal(
+ pages.some((page) => page.targetId === "target-user"),
+ false,
+ );
assert.equal(managedItem.page.label, "p1");
assert.equal(managedItem.page.targetId, managed.targetId);
assert.equal(managedItem.title, "https://example.test/managed");
assert.equal(managedItem.openedBy, "agent");
+ assert.equal(popupItem.page.label, "p2");
+ assert.equal(popupItem.openedBy, "agent");
assert.equal(unknownItem.label, undefined);
assert.equal(unknownItem.page.targetId, "target-user");
assert.equal(unknownItem.page.spaceId, 7);
@@ -2357,10 +2421,11 @@ test("listPages combines managed labels with live browser information", async ()
assert.equal(unknownItem.page.close, undefined);
assert.equal(unknownItem.title, "User page");
assert.equal(unknownItem.openedBy, "unknown");
+ assert.equal(task.listPages, undefined);
});
});
-test("listPages automatically manages a tab created during agent control", async () => {
+test("tabs automatically manages a tab created during agent control", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
await task.openPage("https://example.test/managed");
@@ -2371,7 +2436,7 @@ test("listPages automatically manages a tab created during agent control", async
active: false,
});
- const popup = (await task.listPages()).find(
+ const popup = (await task.tabs()).find(
(item) => item.targetId === "target-popup",
);
@@ -2390,7 +2455,7 @@ test("adopt turns a live untracked page into a managed page", async () => {
active: true,
});
const task = taskForRound(fixture, "round-a");
- const [{ page: untracked }] = await task.listPages();
+ const [{ page: untracked }] = await task.tabs();
const adopted = await task.adopt(untracked, { as: "notes" });
@@ -2402,7 +2467,7 @@ test("adopt turns a live untracked page into a managed page", async () => {
/\[notes .*space "research"\(7\).*\]\nsnapshot:https:\/\/example\.test\/user/,
);
assert.deepEqual(
- (await task.listPages()).map(({ label, openedBy }) => ({
+ (await task.tabs()).map(({ label, openedBy }) => ({
label,
openedBy,
})),
@@ -2420,7 +2485,7 @@ test("adopt rejects stale, cross-space, and already managed handles", async () =
active: true,
});
const task = taskForRound(fixture, "round-a");
- const [{ page: untracked }] = await task.listPages();
+ const [{ page: untracked }] = await task.tabs();
const otherTask = createTaskSpaceHandle(
{ id: 8, name: "other", ownership: "agent" },
{
@@ -2440,7 +2505,7 @@ test("adopt rejects stale, cross-space, and already managed handles", async () =
/target target-user is already page p1/,
);
- const inventory = await task.listPages();
+ const inventory = await task.tabs();
assert.equal(inventory[0].page.label, adopted.label);
fixture.tabs.delete("target-user");
const stale = untracked;
@@ -2461,7 +2526,7 @@ test("adopt applies the managed-page budget before changing the ledger", async (
});
const task = taskForRound(fixture, "round-a", { pageBudget: 1 });
await task.openPage("https://example.test/managed");
- const untracked = (await task.listPages()).find(
+ const untracked = (await task.tabs()).find(
(item) => item.targetId === "target-user",
).page;
@@ -2469,7 +2534,7 @@ test("adopt applies the managed-page budget before changing the ledger", async (
() => task.adopt(untracked),
/Page budget reached \(1\/1\)/,
);
- const after = await task.listPages();
+ const after = await task.tabs();
assert.equal(
after.find((item) => item.targetId === "target-user").label,
undefined,
@@ -2486,14 +2551,14 @@ test("release leaves an adopted page open and retires its label", async () => {
active: true,
});
const task = taskForRound(fixture, "round-a");
- const untracked = (await task.listPages())[0].page;
+ const untracked = (await task.tabs())[0].page;
const adopted = await task.adopt(untracked);
const released = await task.release(adopted.label);
assert.equal(released.targetId, "target-user");
assert.equal(fixture.tabs.has("target-user"), true);
- assert.equal((await task.listPages())[0].label, undefined);
+ assert.equal((await task.tabs())[0].label, undefined);
await assert.rejects(() => adopted.snapshot(), /page p1 was released/);
const adoptedAgain = await task.adopt(released);
assert.equal(adoptedAgain.label, "p2");
@@ -2510,17 +2575,17 @@ test("release refuses to orphan a page created by the agent", async () => {
/page p1 was created by the agent; close it instead/,
);
assert.equal(fixture.tabs.has(created.targetId), true);
- assert.equal((await task.listPages())[0].label, "p1");
+ assert.equal((await task.tabs())[0].label, "p1");
});
});
-test("listPages retires a managed label when its browser tab disappeared", async () => {
+test("tabs retires a managed label when its browser tab disappeared", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
const page = await task.openPage("https://example.test/managed");
fixture.tabs.delete(page.targetId);
- assert.deepEqual(await task.listPages(), []);
+ assert.deepEqual(await task.tabs(), []);
await assert.rejects(
() => task.page("p1").snapshot(),
/page p1 was closed/,
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 67dbfa5..b9371a8 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -242,7 +242,7 @@ type PageModelServices = {
pageBudget: number;
};
-export type PageInventoryItem = {
+export type TabInventoryItem = {
targetId: string;
label?: string;
page: Page | UnmanagedPage;
@@ -630,17 +630,26 @@ class TaskSpace {
);
const active = tabs.find((tab) => tab.active);
this.#userPage = active
- ? pageInventory(this, this.#services, ledger, tabs).find(
+ ? tabInventory(this, this.#services, ledger, tabs).find(
(item) => item.targetId === active.targetId,
)?.page
: undefined;
});
}
- async listPages(): Promise<PageInventoryItem[]> {
+ /** Return managed Page handles after reconciling the browser tab list. */
+ async pages(): Promise<Page[]> {
+ const tabs = await this.tabs();
+ return tabs
+ .filter((item) => item.page instanceof Page)
+ .map((item) => item.page as Page);
+ }
+
+ /** Return managed and unmanaged tabs after reconciling browser state. */
+ async tabs(): Promise<TabInventoryItem[]> {
return this.#services.gate.withSpace(this.id, async () => {
const { ledger, tabs } = await this.#reconcilePages();
- return pageInventory(this, this.#services, ledger, tabs);
+ return tabInventory(this, this.#services, ledger, tabs);
});
}
@@ -859,7 +868,7 @@ class TaskSpace {
/**
* A read-only identity for a live tab that is not managed by the Page model.
- * Obtain one from TaskSpace.listPages(), then call TaskSpace.adopt() before
+ * Obtain one from TaskSpace.tabs(), then call TaskSpace.adopt() before
* navigating, observing, or closing the tab.
*/
class UnmanagedPage {
@@ -875,7 +884,7 @@ class UnmanagedPage {
) {
if (token !== unmanagedPageConstructorToken) {
throw new TypeError(
- "UnmanagedPage handles can only be obtained from task.listPages()",
+ "UnmanagedPage handles can only be obtained from task.tabs()",
);
}
this.spaceId = task.id;
@@ -1046,6 +1055,21 @@ class Page {
);
}
+ /** Wait without activating this Page or occupying the native operation gate. */
+ async waitForTimeout(timeout: number): Promise<void> {
+ if (
+ typeof timeout !== "number" ||
+ !Number.isFinite(timeout) ||
+ timeout < 0
+ ) {
+ throw new TypeError(
+ "page.waitForTimeout requires a non-negative number of milliseconds",
+ );
+ }
+ await this.#resolve();
+ await this.#services.sleep(timeout);
+ }
+
async title(): Promise<string> {
return this.#evaluate("document.title", false);
}
@@ -1106,7 +1130,12 @@ class Page {
assertCdpCall("Page.cdp", method, params, options);
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
- await this.#activate(page.targetId);
+ // A modal dialog already belongs to the active Page. Re-activating it
+ // can hand browser control to the user before CDP gets a chance to close
+ // the dialog, so send this one command directly to its existing session.
+ if (method !== "Page.handleJavaScriptDialog") {
+ await this.#activate(page.targetId);
+ }
try {
return await this.#services.cdp(
method,
@@ -1963,12 +1992,12 @@ async function waitForTargetToDisappear(
}
}
-function pageInventory(
+function tabInventory(
task: TaskSpace,
services: PageModelServices,
ledger: PageLedger,
tabs: RuntimeTab[],
-): PageInventoryItem[] {
+): TabInventoryItem[] {
const managedByTarget = new Map(
Object.entries(ledger.pages).map(([label, entry]) => [
entry.targetId,
@@ -2009,7 +2038,7 @@ function pageInventory(
function assertUnmanagedPage(page: unknown): asserts page is UnmanagedPage {
if (!(page instanceof UnmanagedPage)) {
throw new TypeError(
- "task.adopt requires an untracked page returned by task.listPages()",
+ "task.adopt requires an untracked page returned by task.tabs()",
);
}
}
diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjs
index def002c..62edfc2 100644
--- a/package/ego-browser/src/public-api-schema.test.mjs
+++ b/package/ego-browser/src/public-api-schema.test.mjs
@@ -15,14 +15,18 @@ test("the public API schema contains the v2 entry points and object methods", ()
"takeOverTaskSpace",
"TaskSpace.spaceId",
"TaskSpace.userPage",
+ "TaskSpace.pages",
+ "TaskSpace.tabs",
"TaskSpace.openPage",
"Page.snapshot",
"Page.targetId",
"Page.waitForURL",
+ "Page.waitForTimeout",
"Page.keyboard.press",
]) {
assert(names.has(name), `missing public API schema entry: ${name}`);
}
+ assert.equal(names.has("TaskSpace.listPages"), false);
});
test("schema-driven option validation rejects unknown and invalid fields", () => {
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 6dff393..22c73f4 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -89,8 +89,13 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
"Return the tab active at the claim/takeover boundary, when one was captured.",
},
{
- name: "TaskSpace.listPages",
- signature: "await task.listPages()",
+ name: "TaskSpace.pages",
+ signature: "await task.pages()",
+ summary: "List the managed Page handles in this space.",
+ },
+ {
+ name: "TaskSpace.tabs",
+ signature: "await task.tabs()",
summary: "List managed Pages and unmanaged tabs in this space.",
},
{
@@ -209,6 +214,12 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
summary: "Wait for an exact URL or regular-expression match.",
options: { timeout },
},
+ {
+ name: "Page.waitForTimeout",
+ signature: "await page.waitForTimeout(timeout)",
+ summary:
+ "Wait a fixed number of milliseconds without activating this Page.",
+ },
{
name: "Page.title",
signature: "await page.title()",
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 49c5dcc..b220410 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -66,7 +66,8 @@ task.ownership;
task.page(label);
task.userPage();
-await task.listPages();
+await task.pages();
+await task.tabs();
await task.openPage(url, { as, timeout });
await task.adopt(unmanagedPage, { as });
await task.release(label);
@@ -82,7 +83,8 @@ Follow these page-management rules:
- Reuse an existing Page by default. Call `page.goto()` to open another URL in the same Page. Call `task.openPage()` only when pages truly need to remain side by side.
- Pages receive permanent `p1`, `p2`, and similar labels automatically. Pass `{ as }` to choose a label. Closed labels are never reused.
- Each space manages at most eight pages by default. On `EGO_PAGE_BUDGET_REACHED`, close temporary pages or reuse an existing Page with `goto()`; do not bypass the budget.
-- `task.listPages()` returns managed and unmanaged tabs. An `UnmanagedPage` without a `label` exposes identity information only. Call `task.adopt(item.page, { as })` before observing or operating it.
+- `task.pages()` returns only managed Page handles. It is async because it reconciles live browser tabs before returning.
+- `task.tabs()` returns the complete tab inventory, including managed Pages and unmanaged tabs. An `UnmanagedPage` without a `label` exposes identity information only. Call `task.adopt(item.page, { as })` before observing or operating it.
- Use `task.release(label)` only to return an unknown-origin page to the user while keeping its tab open. Close Agent-created pages with `page.close()`.
- `page.close()` resolves only after the tab has actually disappeared. If close fails, the Page label remains valid and the operation can be retried safely.
@@ -90,10 +92,10 @@ Follow these page-management rules:
`task.ownership` is the ownership captured when the TaskSpace handle was created. `page.openedBy` is `"agent"` or `"unknown"`; treat `"unknown"` as user-owned for lifecycle decisions.
-Each `listPages()` item has `{ label?, page, targetId, title, url, active, openedBy }`. Use `task.page(label)` to resume a known Page; use `listPages()` to discover active or unmanaged tabs:
+Each `tabs()` item has `{ label?, page, targetId, title, url, active, openedBy }`. Use `task.page(label)` to resume a known Page, `pages()` to iterate managed Pages, and `tabs()` to discover active or unmanaged tabs:
```js
-const items = await task.listPages();
+const items = await task.tabs();
const active = items.find((item) => item.active);
if (active && !active.label) {
const adopted = await task.adopt(active.page, { as: "user" });
@@ -114,8 +116,8 @@ for (const popup of receipt.popups ?? []) {
The receipt confirms that the popup target was adopted; its first navigation may
still be at `about:blank`. Use `waitForURL()` when the destination matters. A
-popup that propagates slowly will be discovered by the next `listPages()` or
-`openPage()` call, or when the task resumes in a later round.
+popup that propagates slowly will be discovered by the next `pages()`, `tabs()`,
+or `openPage()` call, or when the task resumes in a later round.
## Choose an interaction path
@@ -226,6 +228,7 @@ await page.evaluate(fnOrString, argument);
await page.fetch(url, options);
await page.cdp(method, params, { timeout });
await page.waitForURL(urlOrRegExp, { timeout });
+await page.waitForTimeout(timeout);
await page.waitForSelector(selector, { timeout, state });
await page.waitForLoadState(state, { timeout, idleMs });
await page.setInputFiles(selector, pathOrPaths);
@@ -240,6 +243,9 @@ await page.close();
- `goto()` defaults to `timeout: 15_000`.
- `waitForURL()` accepts an exact URL string or a `RegExp`, defaults to
`timeout: 10_000`, and does not activate the Page.
+- `waitForTimeout()` waits a fixed number of milliseconds without activating
+ the Page. Use it only for debugging or brief visual stabilization; prefer a
+ URL, selector, load-state, or application-state wait in normal flows.
- `snapshot()` defaults to `{ scope: "full_page", includeActionMarks: true, includeStableLocator: true }`. `scope` is `"full_page"` or `"only_within_viewport"`; there is no `diff` option.
- Omit `screenshot()`'s `path` to receive a temporary PNG path; provided paths should be absolute. `clip.scale` is optional and positive. `raw` defaults to `false`; set it only for uncorrected device-pixel output.
- `evaluate()` accepts a function with at most one JSON-serializable argument, or a string expression with no argument. Its return value must also be JSON-serializable.
@@ -280,9 +286,10 @@ console.log(receipt.popups ?? []);
Receipts report newly opened Pages and synchronous JavaScript dialogs. A dialog
receipt has `{ dialog }`; handle it with
`page.cdp("Page.handleJavaScriptDialog", { accept: true })` or `accept: false`
-before continuing. After any other action, confirm navigation and page changes
-with `url()`, `waitForSelector()`, `info()`, `snapshot()`, a screenshot, an
-export, or a readback.
+before continuing. The dialog command uses the existing Page session without
+activating the Page again. After any other action, confirm navigation and page
+changes with `url()`, `waitForSelector()`, `info()`, `snapshot()`, a screenshot,
+an export, or a readback.
Mouse and keyboard primitives:
@@ -340,7 +347,7 @@ Use the standard Node.js `fetch()` for background requests that do not need Page
## Wait, recover, and verify
-- Decide how to verify the result before triggering an action. Verify with `waitForSelector()`, `waitForLoadState()`, action receipts, `page.url()`, `page.info()`, or the target page's state. Do not invent other wait methods or use a fixed sleep instead of checking state.
+- Decide how to verify the result before triggering an action. Verify with `waitForSelector()`, `waitForLoadState()`, action receipts, `page.url()`, `page.info()`, or the target page's state. Do not use `waitForTimeout()` instead of checking a state the Page can expose.
- When page structure is unknown, observe it in one focused pass, then perform related actions in one script round. Do not retry similar selectors across many rounds.
- A single-element action must identify one clear target. On zero matches, inspect the page, overlays, dialogs, and load state. On multiple matches, use a more specific locator.
- After a failure, take one targeted snapshot, screenshot, or state reading before changing approach. Do not repeat nearly identical actions.
@@ -359,7 +366,7 @@ const task = await takeOverTaskSpace(spaceId);
const userPage = task.userPage();
```
-`task.userPage()` is the tab that was active when claim/takeover completed. It may be an unmanaged user tab; adopt it before operating it. Use `listPages()` for the current active state after Agent actions begin.
+`task.userPage()` is the tab that was active when claim/takeover completed. It may be an unmanaged user tab; adopt it before operating it. Use `tabs()` for the current active state after Agent actions begin.
Use `task.waitForControl({ interval, timeout })` only when the user already knows what to do and the current script must wait in place. It waits for control but never takes it.
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 7618b12..01297c2 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -23,7 +23,8 @@ High-level Page actions return a receipt that may contain `popups` or a synchron
| `task.ownership` | — | Ownership state captured when this TaskSpace was created. |
| `task.page(label)` | — | Create a lazy Page handle for a durable page label. |
| `task.userPage()` | — | Return the tab active at the claim/takeover boundary, when one was captured. |
-| `await task.listPages()` | — | List managed Pages and unmanaged tabs in this space. |
+| `await task.pages()` | — | List the managed Page handles in this space. |
+| `await task.tabs()` | — | List managed Pages and unmanaged tabs in this space. |
| `await task.openPage(url, { as?, timeout? })` | `as` — Permanent Page label.<br>`timeout` — Maximum duration in milliseconds. | Open and durably label a new Page. |
| `await task.adopt(unmanagedPage, { as? })` | `as` — Permanent Page label. | Bring an unmanaged tab under the Page lifecycle. |
| `await task.release(label)` | — | Stop managing an unknown-origin Page without closing it. |
@@ -46,6 +47,7 @@ High-level Page actions return a receipt that may contain `popups` or a synchron
| `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Absolute output path.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |
| `await page.url()` | — | Read this Page's current URL. |
| `await page.waitForURL(urlOrRegExp, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL or regular-expression match. |
+| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |
| `await page.title()` | — | Read this Page's current title. |
| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |
| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page with JSON-serializable data. |