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.

align v2 page APIs with Playwright conventions

Autedbd371fad9a2
diff --git a/docs/runtime-v2-architecture.md b/docs/runtime-v2-architecture.md
index d191fca..252faba 100644
--- a/docs/runtime-v2-architecture.md
+++ b/docs/runtime-v2-architecture.md
@@ -106,7 +106,7 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target
}
```
-`newPage()`、`adopt()`、`release()` 和 `close()` 在 await 返回前完成写入。写入
+`openPage()`、`adopt()`、`release()` 和 `close()` 在 await 返回前完成写入。写入
使用临时文件和 atomic rename,避免留下半个 JSON 文件。
旧开发版本写入的 `version`、`writerRound`、`openedAt`、`lastUsedAt` 和
@@ -115,7 +115,7 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target
### 4.2 标签
- 自动标签依次为 `p1`、`p2`……
-- `newPage(url, { as })` 和 `adopt(page, { as })` 可以指定标签。
+- `openPage(url, { as })` 和 `adopt(page, { as })` 可以指定标签。
- 标签在一个 space 的生命周期内永不复用。
- 已关闭标签报 `page pN was closed`。
- 已 release 标签报 `page pN was released`。
@@ -124,7 +124,7 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target
### 4.3 浏览器事实与账本事实
浏览器决定一个 tab 是否仍存在;账本决定它是否受 Page 模型管理。
-`listPages()`、`newPage()` 等盘点入口会用 `listTabs()` 对账:
+`listPages()`、`openPage()` 等盘点入口会用 `listTabs()` 对账:
- 浏览器中已经消失的受管页面从账本移除,但标签仍保持已使用状态。
- 第一次观察一个 space 时,已有 tab 记为 `unknown`,不会猜测它们由谁创建。
@@ -140,22 +140,22 @@ last-writer-wins。如果未来需要支持,必须使用文件锁或 CAS;不
### 5.1 创建与复用
```js
-const task = await taskSpace('research')
-const page = await task.newPage('https://example.com')
+const task = await taskSpace("research");
+const page = await task.openPage("https://example.com");
// 下一轮
-const samePage = (await taskSpace('research')).page(page.label)
-await samePage.goto('https://example.org')
+const samePage = (await taskSpace("research")).page(page.label);
+await samePage.goto("https://example.org");
```
-`newPage()` 在返回前确认请求的页面文档已经创建,避免把 Ego Lite 暂时复用的
+`openPage()` 在返回前确认请求的页面文档已经创建,避免把 Ego Lite 暂时复用的
placeholder 文档当成新页面。创建成功但文档仍未稳定时,标签仍然保留,错误
会提示调用方下一轮如何取回页面。
### 5.2 预算
每个 space 默认最多管理 8 个页面,可用 `EGO_BROWSER_PAGE_BUDGET` 调整。
-达到上限时,`newPage()` 和 `adopt()` 在改变浏览器前抛出
+达到上限时,`openPage()` 和 `adopt()` 在改变浏览器前抛出
`EGO_PAGE_BUDGET_REACHED`,错误中列出已有标签,并给出 `close()` 和
`goto()` 示例。
@@ -166,9 +166,9 @@ placeholder 文档当成新页面。创建成功但文档仍未稳定时,标
`task.listPages()` 同时返回受管 Page 和只读 `UnmanagedPage`:
```js
-const pages = await task.listPages()
-const unknown = pages.find(item => !item.label)
-const adopted = await task.adopt(unknown.page, { as: 'reference' })
+const pages = await task.listPages();
+const unknown = pages.find((item) => !item.label);
+const adopted = await task.adopt(unknown.page, { as: "reference" });
```
`UnmanagedPage` 只有身份信息,不能直接导航、点击或关闭。调用 `adopt()` 后才
@@ -180,7 +180,7 @@ Agent 创建的页面不能 release,必须显式 close,避免制造无人管
### 5.4 Popup
高层页面动作会在动作前后比较 tab 列表。立即出现的新 tab 会自动获得标签,
-并进入动作回执。传播较慢的 popup 会在下一次 `listPages()`、`newPage()` 或
+并进入动作回执。传播较慢的 popup 会在下一次 `listPages()`、`openPage()` 或
下一轮盘点时收编。
当 space 从未交给用户控制时,新出现的 tab 可以归因于 Agent 或 Agent 触发的
@@ -204,18 +204,18 @@ Agent 创建的页面不能 release,必须显式 close,避免制造无人管
### 6.1 TaskSpace
```js
-const task = await taskSpace(nameOrId)
-
-task.id
-task.name
-task.ownership
-task.page(label)
-
-await task.listPages()
-await task.newPage(url, { as, timeout })
-await task.adopt(unmanagedPage, { as })
-await task.release(label)
-await task.cdp(method, params, { timeout })
+const task = await taskSpace(nameOrId);
+
+task.id;
+task.name;
+task.ownership;
+task.page(label);
+
+await task.listPages();
+await task.openPage(url, { as, timeout });
+await task.adopt(unmanagedPage, { as });
+await task.release(label);
+await task.cdp(method, params, { timeout });
```
`task.cdp()` 只接受 Target 和 Browser domain 命令。Page domain 命令应通过
@@ -231,14 +231,14 @@ page.openedBy
await page.goto(url, { timeout })
await page.snapshot(options)
-await page.screenshot(path?, options)
+await page.screenshot({ path, fullPage, clip, raw })
await page.url()
await page.title()
await page.info()
await page.evaluate(fnOrString, arg?)
await page.fetch(url, options)
await page.cdp(method, params, { timeout })
-await page.waitForSelector(selector, { timeout, visible })
+await page.waitForSelector(selector, { timeout, state })
await page.waitForLoadState('load' | 'networkidle', { timeout, idleMs })
await page.events()
@@ -252,12 +252,18 @@ await page.scrollBy(deltaY, { deltaX, behavior })
await page.close()
```
+`screenshot()` 和 `waitForSelector()` 使用 Playwright 风格的参数。截图路径放在
+options 中;`fullPage` 表示捕获完整页面。`waitForSelector()` 的 `state` 支持
+`attached`、`detached`、`visible` 和 `hidden`,默认是 `visible`。
+
`page.fetch()` 是 Ego 提供的便利扩展,不是 Playwright 方法。它在目标页面内
执行 `window.fetch()`,因此使用该页面的相对 URL、Cookie、CORS 和 service
worker。返回值为:
```js
-{ ok, status, statusText, url, headers, body }
+{
+ (ok, status, statusText, url, headers, body);
+}
```
后台 Node 请求直接使用标准 `fetch()`;旧 `serverFetch()` 只为 v1 脚本保留。
@@ -265,17 +271,17 @@ worker。返回值为:
### 6.3 Mouse 和 keyboard
```js
-await page.mouse.click(x, y, options)
-await page.mouse.move(x, y, { steps })
-await page.mouse.down(options)
-await page.mouse.up(options)
-await page.mouse.wheel(deltaX, deltaY)
-
-await page.keyboard.down(key)
-await page.keyboard.up(key)
-await page.keyboard.press(chord, { delay })
-await page.keyboard.type(text, { delay })
-await page.keyboard.insertText(text)
+await page.mouse.click(x, y, options);
+await page.mouse.move(x, y, { steps });
+await page.mouse.down(options);
+await page.mouse.up(options);
+await page.mouse.wheel(deltaX, deltaY);
+
+await page.keyboard.down(key);
+await page.keyboard.up(key);
+await page.keyboard.press(chord, { delay });
+await page.keyboard.type(text, { delay });
+await page.keyboard.insertText(text);
```
键盘和鼠标状态保存在 Page 对象中。`ControlOrMeta` 会按当前平台映射;macOS
@@ -351,10 +357,13 @@ snapshot 每次返回全量内容。当前不提供 `diff`:一轮一个短进
`page.evaluate()` 接受字符串表达式,或者函数和一个可选 JSON 参数:
```js
-await page.evaluate(({ selector, value }) => {
- document.querySelector(selector).textContent = value
- return document.title
-}, { selector: '#status', value: 'done' })
+await page.evaluate(
+ ({ selector, value }) => {
+ document.querySelector(selector).textContent = value;
+ return document.title;
+ },
+ { selector: "#status", value: "done" },
+);
```
函数参数和返回值限定为 JSON 可序列化子集。函数通过
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 1202ce4..a769835 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
@@ -2,7 +2,7 @@ export function pageLabelCreateCase() {
return `
const task = await taskSpace(taskName);
await openOrReuseTab(baseUrl + "/?inventory=unknown", { wait: true, timeout: 10 });
- const page = await task.newPage(baseUrl + "/?managed=p1");
+ const page = await task.openPage(baseUrl + "/?managed=p1");
assertEqual(page.label, "p1", "first managed page receives p1");
assertEqual(page.spaceId, task.id, "page carries its task-space id");
assertEqual(typeof page.targetId, "string", "new page exposes its target id");
@@ -66,7 +66,7 @@ export function pageLabelCloseCase() {
"a closed label fails closed"
);
- const next = await task.newPage(baseUrl + "/secondary?managed=p2");
+ const next = await task.openPage(baseUrl + "/secondary?managed=p2");
assertEqual(next.label, "p2", "closed labels are never reused");
await closeTab(next.targetId);
for (let attempt = 0; attempt < 20; attempt += 1) {
@@ -83,7 +83,7 @@ export function pageLabelCloseCase() {
"page p2 was closed",
"reconciliation permanently retires an externally closed label"
);
- const afterExternalClose = await task.newPage(baseUrl + "/secondary?managed=p3");
+ const afterExternalClose = await task.openPage(baseUrl + "/secondary?managed=p3");
assertEqual(afterExternalClose.label, "p3", "reconciliation frees budget without reusing labels");
await afterExternalClose.close();
`;
@@ -92,7 +92,7 @@ export function pageLabelCloseCase() {
export function pageLabelHardStopCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.newPage(baseUrl + "/secondary?managed=hard-stop");
+ const page = await task.openPage(baseUrl + "/secondary?managed=hard-stop");
await writeFile(
join(tempDir, "hard-stop-page.json"),
JSON.stringify({ label: page.label, targetId: page.targetId })
@@ -119,19 +119,19 @@ export function pageBudgetCase() {
const task = await taskSpace(taskName);
const managed = [];
for (let index = 0; index < 3; index += 1) {
- managed.push(await task.newPage(baseUrl + "/secondary?budget=" + index));
+ managed.push(await task.openPage(baseUrl + "/secondary?budget=" + index));
const inventory = await task.listPages();
assertEqual(
inventory.filter((item) => item.label !== undefined).length,
index + 1,
- "each newPage is visible to managed-page inventory"
+ "each openPage is visible to managed-page inventory"
);
}
const beforeReject = await listTabs();
await assertRejects(
- () => task.newPage(baseUrl + "/secondary?budget=blocked"),
+ () => task.openPage(baseUrl + "/secondary?budget=blocked"),
"Page budget reached (3/3)",
- "newPage applies managed-page backpressure"
+ "openPage applies managed-page backpressure"
);
const afterReject = await listTabs();
assertEqual(afterReject.length, beforeReject.length, "budget rejects before creating a browser tab");
@@ -184,7 +184,7 @@ export function pageAdoptionCase() {
assertEqual(adoptedAgain.targetId, source.targetId, "a released tab can be adopted again");
await task.release(adoptedAgain.label);
- const agentPage = await task.newPage(baseUrl + "/secondary?release=agent", {
+ const agentPage = await task.openPage(baseUrl + "/secondary?release=agent", {
as: "agent-owned",
});
await assertRejects(
@@ -199,10 +199,10 @@ export function pageAdoptionCase() {
export function pageBasicOperationsCase() {
return `
const task = await taskSpace(taskName);
- const first = await task.newPage(baseUrl + "/?page-api=first", {
+ const first = await task.openPage(baseUrl + "/?page-api=first", {
as: "page-api-first",
});
- const second = await task.newPage(baseUrl + "/secondary?page-api=second", {
+ const second = await task.openPage(baseUrl + "/secondary?page-api=second", {
as: "page-api-second",
});
assertEqual((await currentTab()).targetId, second.targetId, "second page starts active");
@@ -264,7 +264,10 @@ export function pageBasicOperationsCase() {
}, 75);
});
assertEqual(
- await first.waitForSelector("#page-wait-ready", { timeout: 2_000, visible: true }),
+ await first.waitForSelector("#page-wait-ready", {
+ timeout: 2_000,
+ state: "visible",
+ }),
true,
"page.waitForSelector uses milliseconds and the addressed Page"
);
@@ -311,7 +314,7 @@ export function pageBasicOperationsCase() {
const screenshotPath = join(tempDir, "page-api-first.png");
assertEqual(
- await first.screenshot(screenshotPath, { full: false }),
+ await first.screenshot({ path: screenshotPath, fullPage: false }),
screenshotPath,
"page.screenshot returns its explicit path"
);
@@ -339,13 +342,13 @@ export function pageActionsAndPopupCase() {
.filter((item) => item.label === undefined)
.map((item) => item.targetId);
assert(unknownBefore.length > 0, "the control-boundary inventory keeps pre-existing tabs untracked");
- const source = await task.newPage(baseUrl + "/?page-actions=source", {
+ const source = await task.openPage(baseUrl + "/?page-actions=source", {
as: "page-actions-source",
});
- const comparison = await task.newPage(baseUrl + "/secondary?page-actions=comparison", {
+ const comparison = await task.openPage(baseUrl + "/secondary?page-actions=comparison", {
as: "page-actions-comparison",
});
- const budgetFiller = await task.newPage(baseUrl + "/secondary?page-actions=budget", {
+ const budgetFiller = await task.openPage(baseUrl + "/secondary?page-actions=budget", {
as: "page-actions-budget",
});
@@ -554,9 +557,9 @@ export function pageActionsAndPopupCase() {
"tabs that existed before the action remain untracked"
);
await assertRejects(
- () => task.newPage(baseUrl + "/secondary?page-actions=blocked"),
+ () => task.openPage(baseUrl + "/secondary?page-actions=blocked"),
"Page budget reached (4/3)",
- "an adopted popup can exceed the budget and backpressure later newPage calls"
+ "an adopted popup can exceed the budget and backpressure later openPage calls"
);
await task.page(popup.label).close();
@@ -569,10 +572,10 @@ export function pageActionsAndPopupCase() {
export function pageComplexEvaluateCase() {
return `
const task = await taskSpace(taskName);
- const source = await task.newPage(baseUrl + "/?page-evaluate=complex", {
+ const source = await task.openPage(baseUrl + "/?page-evaluate=complex", {
as: "complex-evaluate-source",
});
- const comparison = await task.newPage(baseUrl + "/secondary?page-evaluate=comparison", {
+ const comparison = await task.openPage(baseUrl + "/secondary?page-evaluate=comparison", {
as: "complex-evaluate-comparison",
});
assertEqual((await currentTab()).targetId, comparison.targetId, "comparison page starts active");
@@ -746,10 +749,10 @@ export function pageComplexEvaluateCase() {
export function pageFetchCase() {
return `
const task = await taskSpace(taskName);
- const source = await task.newPage(baseUrl + "/nested/page-fetch/source", {
+ const source = await task.openPage(baseUrl + "/nested/page-fetch/source", {
as: "page-fetch-source",
});
- const comparison = await task.newPage(baseUrl + "/secondary?page-fetch=comparison", {
+ const comparison = await task.openPage(baseUrl + "/secondary?page-fetch=comparison", {
as: "page-fetch-comparison",
});
await source.evaluate(() => {
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs
index c4b932d..3a8b80e 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/workflow-chains.mjs
@@ -1,7 +1,7 @@
export function v1V2ActionParityCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.newPage(baseUrl + "/?workflow=parity", {
+ const page = await task.openPage(baseUrl + "/?workflow=parity", {
as: "workflow-parity",
});
@@ -111,7 +111,7 @@ export function v1V2ActionParityCase() {
export function portableKeyboardWorkflowCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.newPage(baseUrl + "/?workflow=keyboard", {
+ const page = await task.openPage(baseUrl + "/?workflow=keyboard", {
as: "workflow-keyboard",
});
@@ -165,7 +165,7 @@ export function portableKeyboardWorkflowCase() {
export function pureCdpWorkflowCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.newPage("about:blank", { as: "workflow-cdp" });
+ const page = await task.openPage("about:blank", { as: "workflow-cdp" });
const destination = baseUrl + "/?workflow=cdp";
await page.cdp("Page.navigate", { url: destination }, { timeout: 5_000 });
@@ -249,10 +249,10 @@ export function pureCdpWorkflowCase() {
export function snapshotWorkflowCase() {
return `
const task = await taskSpace(taskName);
- const first = await task.newPage(baseUrl + "/?workflow=snapshot-a", {
+ const first = await task.openPage(baseUrl + "/?workflow=snapshot-a", {
as: "workflow-snapshot-a",
});
- const second = await task.newPage(baseUrl + "/?workflow=snapshot-b", {
+ const second = await task.openPage(baseUrl + "/?workflow=snapshot-b", {
as: "workflow-snapshot-b",
});
@@ -287,7 +287,7 @@ export function snapshotWorkflowCase() {
export function visualWorkflowCase() {
return `
const task = await taskSpace(taskName);
- const page = await task.newPage(baseUrl + "/visual", { as: "workflow-visual" });
+ const page = await task.openPage(baseUrl + "/visual", { as: "workflow-visual" });
const snapshot = await page.snapshot();
assert(
!snapshot.includes("CLICK") && !snapshot.includes("DONE"),
@@ -296,10 +296,10 @@ export function visualWorkflowCase() {
const beforePath = join(artifactDir, "visual-before.png");
const afterPath = join(artifactDir, "visual-after.png");
- await page.screenshot(beforePath, { full: false });
+ await page.screenshot({ path: beforePath, fullPage: false });
await page.mouse.move(160, 150);
await page.mouse.click(160, 150);
- await page.screenshot(afterPath, { full: false });
+ await page.screenshot({ path: afterPath, fullPage: false });
const before = await readFile(beforePath);
const after = await readFile(afterPath);
diff --git a/package/ego-browser/scripts/real-browser-e2e/runner.mjs b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
index 9d0a805..402c0eb 100644
--- a/package/ego-browser/scripts/real-browser-e2e/runner.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/runner.mjs
@@ -101,7 +101,7 @@ export async function runRealBrowserE2e() {
if (!commandError) {
throw new Error("the browser script completed instead of terminating");
}
- // The marker is written only after newPage() has returned. Its presence
+ // The marker is written only after openPage() has returned. Its presence
// distinguishes the intended hard stop from an unrelated startup error.
await stat(join(tempDir, markerName));
recordResult(name, "pass", durationMs, 1);
diff --git a/package/ego-browser/src/driver/page-waits.ts b/package/ego-browser/src/driver/page-waits.ts
index 231bf87..878e6e5 100644
--- a/package/ego-browser/src/driver/page-waits.ts
+++ b/package/ego-browser/src/driver/page-waits.ts
@@ -19,7 +19,7 @@ type PageWaitServices = {
export type PageWaitForSelectorOptions = {
timeout?: number;
- visible?: boolean;
+ state?: "attached" | "detached" | "visible" | "hidden";
};
export type PageWaitForLoadStateOptions = {
@@ -45,8 +45,11 @@ export async function waitForSelectorInPage(
}
const timeoutMs = options.timeout ?? 10_000;
assertPositiveMilliseconds(timeoutMs);
- if (options.visible !== undefined && typeof options.visible !== "boolean") {
- throw new TypeError("page.waitForSelector visible must be a boolean");
+ const state = options.state ?? "visible";
+ if (!["attached", "detached", "visible", "hidden"].includes(state)) {
+ throw new TypeError(
+ "page.waitForSelector state must be one of attached, detached, visible, or hidden",
+ );
}
const deadline = services.now() + timeoutMs;
@@ -59,18 +62,21 @@ export async function waitForSelectorInPage(
refMap,
selector,
);
- if (!options.visible) return true;
- const response = await services.cdp(
- "Runtime.callFunctionOn",
- {
- functionDeclaration: VISIBILITY_FUNCTION,
- objectId: resolved.objectId,
- returnByValue: true,
- awaitPromise: false,
- },
- resolved.sessionId,
- );
- if (response?.result?.value) return true;
+ if (state === "attached") return true;
+ if (state !== "detached") {
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: VISIBILITY_FUNCTION,
+ objectId: resolved.objectId,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ resolved.sessionId,
+ );
+ const visible = response?.result?.value === true;
+ if (state === "visible" ? visible : !visible) return true;
+ }
} catch (error) {
if (
!(error instanceof ElementResolutionError) ||
@@ -78,6 +84,7 @@ export async function waitForSelectorInPage(
) {
throw error;
}
+ if (state === "detached" || state === "hidden") return true;
} finally {
if (resolved?.objectId) {
await services
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 139e5c5..d86ad02 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -134,7 +134,8 @@ test("taskSpace returns the new object model for a resolved space", async () =>
assert.equal(task.id, 7);
assert.equal(task.name, "Research");
assert.equal(task.ownership, "agent");
- assert.equal(typeof task.newPage, "function");
+ 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.adopt, "function");
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 11c9c52..f93f246 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -28,6 +28,8 @@ function createFixture(rootDir) {
let timeoutNextMouseDispatch = false;
let rejectNextClickPoint = false;
let navigateOnNextClickUrl = null;
+ let elementPresent = true;
+ let elementVisible = true;
let nowMs = 1_000;
const pageEvents = new Map();
const networkSessions = new Set();
@@ -143,6 +145,9 @@ function createFixture(rootDir) {
};
}
if (params.returnByValue === false) {
+ if (!elementPresent) {
+ return { result: { type: "undefined" } };
+ }
return {
result: {
type: "object",
@@ -157,7 +162,7 @@ function createFixture(rootDir) {
return { result: { type: "string", value: "needsinput" } };
}
if (params.functionDeclaration.includes("checkVisibility")) {
- return { result: { type: "boolean", value: true } };
+ return { result: { type: "boolean", value: elementVisible } };
}
if (params.functionDeclaration.includes("window.scrollBy")) {
return {
@@ -335,6 +340,10 @@ function createFixture(rootDir) {
navigateOnNextClick(url) {
navigateOnNextClickUrl = url;
},
+ setElementState({ present = true, visible = true }) {
+ elementPresent = present;
+ elementVisible = visible;
+ },
emitPageEvent(targetId, method, params = {}) {
const sessionId = `session:${targetId}`;
const events = pageEvents.get(sessionId) || [];
@@ -358,7 +367,7 @@ function taskForRound(fixture, roundId, overrides = {}) {
test("a page label restores in a new round and goto reuses its target", async () => {
await withFixture(async (fixture) => {
const firstRound = taskForRound(fixture, "round-a");
- const created = await firstRound.newPage("https://example.test/first");
+ const created = await firstRound.openPage("https://example.test/first");
assert.equal(created.label, "p1");
assert.equal(created.spaceId, 7);
@@ -390,7 +399,7 @@ test("a page label restores in a new round and goto reuses its target", async ()
});
});
-test("newPage waits for the document created by this call, not an already-complete placeholder", async () => {
+test("openPage waits for the document created by this call, not an already-complete placeholder", async () => {
await withFixture(async (fixture) => {
const requestedUrl = "https://example.test/created-document";
const baseCreateTab = fixture.services.createTab;
@@ -434,7 +443,7 @@ test("newPage waits for the document created by this call, not an already-comple
},
});
- const page = await task.newPage(requestedUrl);
+ const page = await task.openPage(requestedUrl);
assert.equal(page.targetId, targetId);
assert.equal(sleepCount, 1);
@@ -445,8 +454,8 @@ test("newPage waits for the document created by this call, not an already-comple
test("snapshot activates the addressed page, not whichever tab was current", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
assert.equal(fixture.activeTarget(), "target-2");
assert.match(
@@ -460,7 +469,7 @@ test("snapshot activates the addressed page, not whichever tab was current", asy
test("snapshot reports its source and rejects the removed round-local diff option", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/before");
+ const page = await task.openPage("https://example.test/before");
assert.match(
await page.snapshot(),
@@ -476,8 +485,8 @@ test("snapshot reports its source and rejects the removed round-local diff optio
test("metadata reads stay target-scoped while evaluate and screenshot activate their Page", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
assert.equal(fixture.activeTarget(), "target-2");
assert.equal(await first.url(), "https://example.test/first");
@@ -507,9 +516,24 @@ test("metadata reads stay target-scoped while evaluate and screenshot activate t
"page.evaluate must activate the page whose JavaScript it runs",
);
assert.equal(
- await first.screenshot("/tmp/first.png", { full: true }),
+ await first.screenshot({ path: "/tmp/first.png", fullPage: true }),
"/tmp/first.png",
);
+ assert(
+ fixture.calls.some(
+ ([kind, path, options, sessionId]) =>
+ kind === "screenshot" &&
+ path === "/tmp/first.png" &&
+ options.full === true &&
+ !Object.hasOwn(options, "fullPage") &&
+ sessionId === "session:target-1",
+ ),
+ "page.screenshot must map Playwright-style options to the v1 capture driver",
+ );
+ await assert.rejects(
+ () => first.screenshot("/tmp/legacy.png"),
+ /options must be an object/,
+ );
assert.equal(
fixture.activeTarget(),
"target-1",
@@ -538,7 +562,7 @@ test("metadata reads stay target-scoped while evaluate and screenshot activate t
test("Page evaluate rejects ambiguous or non-serializable arguments", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/evaluate");
+ const page = await task.openPage("https://example.test/evaluate");
const cyclic = {};
cyclic.self = cyclic;
@@ -560,7 +584,7 @@ test("Page evaluate rejects ambiguous or non-serializable arguments", async () =
test("Page evaluate preserves a large nested JSON argument", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/evaluate-complex");
+ const page = await task.openPage("https://example.test/evaluate-complex");
const argument = {
marker: "复杂 input 😀 quotes: \" ' ` and a newline\n",
config: {
@@ -587,8 +611,8 @@ test("Page evaluate preserves a large nested JSON argument", async () => {
test("Page fetch activates its target and returns a structured non-2xx response", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
const response = await first.fetch("/api/teapot", {
method: "POST",
@@ -636,7 +660,7 @@ test("Page fetch activates its target and returns a structured non-2xx response"
test("Page fetch validates its JSON options and millisecond timeout", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/fetch");
+ const page = await task.openPage("https://example.test/fetch");
const cyclic = {};
cyclic.self = cyclic;
@@ -664,8 +688,8 @@ test("Page click fails closed when native mouse dispatch times out", async () =>
active: false,
});
const task = taskForRound(fixture, "round-a", { pageBudget: 2 });
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
fixture.openPopupOnNextClick("https://example.test/popup");
fixture.timeoutNextMouseDispatch();
@@ -702,8 +726,8 @@ test("Page click fails closed when native mouse dispatch times out", async () =>
test("Page fill uses its target session and reports no popup when none opened", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
assert.deepEqual(await first.fill("#text-input", "filled"), {});
const insertText = fixture.calls.find(
@@ -745,7 +769,7 @@ test("Page fill uses its target session and reports no popup when none opened",
test("Page action receipts report navigation and obvious document changes", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/before");
+ const page = await task.openPage("https://example.test/before");
fixture.navigateOnNextClick("https://example.test/after");
assert.deepEqual(await page.click("#navigate"), {
@@ -761,8 +785,8 @@ test("Page action receipts report navigation and obvious document changes", asyn
test("Page pointer methods dispatch through the addressed target session", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
await first.dblclick("button.primary");
await first.hover("button.primary");
@@ -810,7 +834,7 @@ test("Page pointer methods dispatch through the addressed target session", async
test("Page mouse movement updates the Ego Lite agent cursor", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.click("button.primary");
await page.hover("button.primary");
@@ -844,7 +868,7 @@ test("agent cursor rendering failures do not make successful page input retryabl
throw new Error("agent cursor overlay unavailable");
},
});
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.click("button.primary");
@@ -871,7 +895,7 @@ test("agent cursor animation does not delay page input completion", async () =>
return animation;
},
});
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
const outcome = await Promise.race([
page.mouse.move(20, 30).then(() => "action-complete"),
@@ -888,8 +912,8 @@ test("agent cursor animation does not delay page input completion", async () =>
test("Page mouse primitives preserve button state on one target", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
await first.mouse.move(20, 30);
await first.mouse.down();
@@ -927,7 +951,7 @@ test("Page mouse primitives preserve button state on one target", async () => {
test("Page mouse mirrors Playwright state, steps, and keyboard modifiers", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.keyboard.down("Shift");
await page.mouse.move(30, 20, { steps: 3 });
@@ -984,8 +1008,8 @@ test("Page mouse mirrors Playwright state, steps, and keyboard modifiers", async
test("Page scrollBy evaluates in the addressed page", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
assert.deepEqual(await first.scrollBy(450), { x: 0, y: 450 });
@@ -1003,8 +1027,8 @@ test("Page scrollBy evaluates in the addressed page", async () => {
test("Page keyboard press and type use the addressed target session", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
await first.keyboard.press("Meta+A");
await first.keyboard.type("hello 世界");
@@ -1045,7 +1069,7 @@ test("Page keyboard press and type use the addressed target session", async () =
test("Page keyboard mirrors Playwright key state and the US layout", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.keyboard.down("Shift");
await page.keyboard.down("a");
@@ -1094,7 +1118,7 @@ test("Page keyboard mirrors Playwright key state and the US layout", async () =>
test("Page keyboard maps portable editing shortcuts on macOS", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.press("ControlOrMeta+C");
@@ -1132,7 +1156,7 @@ test("Page keyboard maps portable editing shortcuts on macOS", async () => {
test("Page keyboard maps portable editing shortcuts on Windows", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "win32" });
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.press("ControlOrMeta+C");
@@ -1165,7 +1189,7 @@ test("Page keyboard maps portable editing shortcuts on Windows", async () => {
test("Page keyboard type emits physical keys when possible and inserts unsupported text", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.keyboard.type("Aé", { delay: 12 });
@@ -1195,7 +1219,7 @@ test("Page keyboard type emits physical keys when possible and inserts unsupport
test("low-level Page input skips action observers and returns no receipt", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
fixture.calls.length = 0;
assert.equal(await page.mouse.move(10, 20), undefined);
@@ -1224,8 +1248,8 @@ test("low-level Page input skips action observers and returns no receipt", async
test("Page keyboard omits synthetic dispatch while file input stays target-scoped", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
assert.equal(first.keyboard.dispatch, undefined);
await first.setInputFiles("#upload", ["/tmp/one.txt", "/tmp/two.txt"]);
@@ -1242,8 +1266,8 @@ test("Page keyboard omits synthetic dispatch while file input stays target-scope
test("Page and TaskSpace CDP commands preserve their intended scope", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
const pageResult = await first.cdp(
"Runtime.evaluate",
@@ -1284,11 +1308,14 @@ test("Page and TaskSpace CDP commands preserve their intended scope", async () =
test("Page waits and events remain isolated to the addressed target", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- const second = await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ const second = await task.openPage("https://example.test/second");
assert.equal(
- await first.waitForSelector("#ready", { timeout: 250, visible: true }),
+ await first.waitForSelector("#ready", {
+ timeout: 250,
+ state: "visible",
+ }),
true,
);
await first.waitForLoadState("load", { timeout: 250 });
@@ -1330,10 +1357,43 @@ test("Page waits and events remain isolated to the addressed target", async () =
});
});
+test("Page waitForSelector supports Playwright-style element states", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/first");
+
+ fixture.setElementState({ present: true, visible: false });
+ assert.equal(
+ await page.waitForSelector("#ready", { state: "attached" }),
+ true,
+ );
+ assert.equal(
+ await page.waitForSelector("#ready", { state: "hidden" }),
+ true,
+ );
+
+ fixture.setElementState({ present: false });
+ assert.equal(
+ await page.waitForSelector("#ready", { state: "detached" }),
+ true,
+ );
+ assert.equal(
+ await page.waitForSelector("#ready", { state: "hidden" }),
+ true,
+ );
+
+ fixture.setElementState({ present: true, visible: true });
+ assert.equal(
+ await page.waitForSelector("#ready", { state: "visible" }),
+ true,
+ );
+ });
+});
+
test("Page wait methods reject invalid states and millisecond timeouts", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await assert.rejects(
() => page.waitForLoadState("domcontentloaded"),
@@ -1343,6 +1403,10 @@ test("Page wait methods reject invalid states and millisecond timeouts", async (
() => page.waitForSelector("#ready", { timeout: 0 }),
/positive number of milliseconds/,
);
+ await assert.rejects(
+ () => page.waitForSelector("#ready", { state: "stable" }),
+ /state must be one of/,
+ );
await assert.rejects(
() => task.cdp("Page.navigate"),
/only supports Target\. and Browser\. commands/,
@@ -1353,8 +1417,8 @@ test("Page wait methods reject invalid states and millisecond timeouts", async (
test("Page actions resolve snapshot refs inside the addressed page", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
- const second = await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ const second = await task.openPage("https://example.test/second");
await first.snapshot();
await second.snapshot();
@@ -1390,7 +1454,7 @@ test("Page actions resolve snapshot refs inside the addressed page", async () =>
test("a new round refreshes the addressed Page before resolving a ref", async () => {
await withFixture(async (fixture) => {
const firstRound = taskForRound(fixture, "round-a");
- const created = await firstRound.newPage("https://example.test/first");
+ const created = await firstRound.openPage("https://example.test/first");
await created.snapshot();
const snapshotsBefore = fixture.calls.filter(
([kind]) => kind === "snapshot",
@@ -1416,7 +1480,7 @@ test("a new round refreshes the addressed Page before resolving a ref", async ()
test("an unknown Page ref fails after one target-scoped refresh", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await assert.rejects(() => page.click("@99"), /Unknown ref: 99/);
assert.deepEqual(
@@ -1429,7 +1493,7 @@ test("an unknown Page ref fails after one target-scoped refresh", async () => {
test("Page click scrolls the element into view before computing its point", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.click("#offscreen");
@@ -1446,7 +1510,7 @@ test("Page click scrolls the element into view before computing its point", asyn
test("Page click does not dispatch input when scrolling cannot make the element visible", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
fixture.rejectNextClickPoint();
await assert.rejects(
@@ -1466,7 +1530,7 @@ test("Page click does not dispatch input when scrolling cannot make the element
test("close leaves an anchor tab and the next page gets a new label", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const first = await task.newPage("https://example.test/first");
+ const first = await task.openPage("https://example.test/first");
await first.close();
assert.equal(fixture.tabs.has("target-1"), false);
@@ -1480,7 +1544,7 @@ test("close leaves an anchor tab and the next page gets a new label", async () =
/page p1 was closed/,
);
- const second = await task.newPage("https://example.test/second");
+ const second = await task.openPage("https://example.test/second");
assert.equal(second.label, "p2");
assert.equal(second.targetId, "target-3");
});
@@ -1506,7 +1570,7 @@ test("close waits for the target to disappear before retiring its label", async
return [...fixture.tabs.values()];
},
});
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await page.close();
@@ -1526,7 +1590,7 @@ test("close keeps the page managed when the target never disappears", async () =
return fixture.services.cdp(method, params, sessionId, timeoutMs);
},
});
- const page = await task.newPage("https://example.test/first");
+ const page = await task.openPage("https://example.test/first");
await assert.rejects(() => page.close(), /did not close within 2000ms/);
@@ -1554,7 +1618,7 @@ test("a ledger failure closes the newly created uncommitted tab", async () => {
);
await assert.rejects(
- () => task.newPage("https://example.test/uncommitted"),
+ () => task.openPage("https://example.test/uncommitted"),
/ledger unavailable/,
);
assert.equal(fixture.tabs.size, 0);
@@ -1575,7 +1639,7 @@ test("listPages combines managed labels with live browser information", async ()
active: false,
});
const task = taskForRound(fixture, "round-a");
- const managed = await task.newPage("https://example.test/managed");
+ const managed = await task.openPage("https://example.test/managed");
const pages = await task.listPages();
const managedItem = pages.find((item) => item.label === "p1");
@@ -1600,7 +1664,7 @@ test("listPages combines managed labels with live browser information", async ()
test("listPages automatically manages a tab created during agent control", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- await task.newPage("https://example.test/managed");
+ await task.openPage("https://example.test/managed");
fixture.tabs.set("target-popup", {
targetId: "target-popup",
url: "https://example.test/popup",
@@ -1697,7 +1761,7 @@ test("adopt applies the managed-page budget before changing the ledger", async (
active: false,
});
const task = taskForRound(fixture, "round-a", { pageBudget: 1 });
- await task.newPage("https://example.test/managed");
+ await task.openPage("https://example.test/managed");
const untracked = (await task.listPages()).find(
(item) => item.targetId === "target-user",
).page;
@@ -1740,7 +1804,7 @@ test("release leaves an adopted page open and retires its label", async () => {
test("release refuses to orphan a page created by the agent", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const created = await task.newPage("https://example.test/agent");
+ const created = await task.openPage("https://example.test/agent");
await assert.rejects(
() => task.release(created.label),
@@ -1754,7 +1818,7 @@ test("release refuses to orphan a page created by the agent", async () => {
test("listPages retires a managed label when its browser tab disappeared", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
- const page = await task.newPage("https://example.test/managed");
+ const page = await task.openPage("https://example.test/managed");
fixture.tabs.delete(page.targetId);
assert.deepEqual(await task.listPages(), []);
@@ -1765,14 +1829,14 @@ test("listPages retires a managed label when its browser tab disappeared", async
});
});
-test("newPage rejects before creating a tab when the managed budget is full", async () => {
+test("openPage rejects before creating a tab when the managed budget is full", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { pageBudget: 2 });
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
await assert.rejects(
- () => task.newPage("https://example.test/third"),
+ () => task.openPage("https://example.test/third"),
(error) => {
assert.match(
error.message,
@@ -1797,20 +1861,20 @@ test("newPage rejects before creating a tab when the managed budget is full", as
);
await first.close();
- const replacement = await task.newPage("https://example.test/third");
+ const replacement = await task.openPage("https://example.test/third");
assert.equal(replacement.label, "p3");
assert.equal(fixture.tabs.size, 2);
});
});
-test("a tab closed outside the runtime frees budget on the next newPage", async () => {
+test("a tab closed outside the runtime frees budget on the next openPage", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { pageBudget: 2 });
- const first = await task.newPage("https://example.test/first");
- await task.newPage("https://example.test/second");
+ const first = await task.openPage("https://example.test/first");
+ await task.openPage("https://example.test/second");
fixture.tabs.delete(first.targetId);
- const replacement = await task.newPage("https://example.test/third");
+ const replacement = await task.openPage("https://example.test/third");
assert.equal(replacement.label, "p3");
assert.equal(fixture.tabs.size, 2);
@@ -1821,10 +1885,10 @@ test("a tab closed outside the runtime frees budget on the next newPage", async
});
});
-test("newPage never closes a managed page when native returns its target again", async () => {
+test("openPage never closes a managed page when native returns its target again", async () => {
await withFixture(async (fixture) => {
const firstTask = taskForRound(fixture, "round-a");
- const first = await firstTask.newPage("https://example.test/first");
+ const first = await firstTask.openPage("https://example.test/first");
const closeCallsBefore = fixture.calls.filter(
([kind, method]) => kind === "cdp" && method === "Target.closeTarget",
).length;
@@ -1835,7 +1899,7 @@ test("newPage never closes a managed page when native returns its target again",
});
await assert.rejects(
- () => secondTask.newPage("https://example.test/second"),
+ () => secondTask.openPage("https://example.test/second"),
/did not create a distinct tab.*already page p1/,
);
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index c4fd5df..3b16a72 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -67,7 +67,7 @@ type TaskSpaceDescriptor = {
ownership?: string;
};
-type NewPageOptions = {
+type OpenPageOptions = {
as?: string;
timeout?: number;
};
@@ -82,6 +82,11 @@ type PageGotoOptions = {
type PageSnapshotOptions = Record<string, unknown>;
+type PageScreenshotOptions = Omit<CaptureScreenshotOptions, "full"> & {
+ path?: string;
+ fullPage?: boolean;
+};
+
type CdpOptions = {
timeout?: number;
};
@@ -417,11 +422,11 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {
async createTab(url) {
const result = assertNoEgoError(
await browserEgo().createTab(url),
- "task.newPage",
+ "task.openPage",
);
const targetId = result?.targetId || result?.result?.targetId;
if (typeof targetId !== "string" || targetId.length === 0) {
- throw new Error("task.newPage returned no targetId");
+ throw new Error("task.openPage returned no targetId");
}
return targetId;
},
@@ -593,9 +598,9 @@ class TaskSpace {
});
}
- async newPage(
+ async openPage(
url = "about:blank",
- options: NewPageOptions = {},
+ options: OpenPageOptions = {},
): Promise<Page> {
assertUrl(url);
const timeoutMs = options.timeout ?? 15_000;
@@ -614,7 +619,7 @@ class TaskSpace {
);
if (existingManaged) {
throw new Error(
- `task.newPage did not create a distinct tab; target ${targetId} is already page ${existingManaged[0]}`,
+ `task.openPage did not create a distinct tab; target ${targetId} is already page ${existingManaged[0]}`,
);
}
const existedBeforeCreate = tabs.some((tab) => tab.targetId === targetId);
@@ -922,17 +927,32 @@ class Page {
);
}
- async screenshot(
- path?: string,
- options: CaptureScreenshotOptions = {},
- ): Promise<string> {
+ async screenshot(options: PageScreenshotOptions = {}): Promise<string> {
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
+ throw new TypeError("page.screenshot options must be an object");
+ }
+ if (Object.hasOwn(options, "full")) {
+ throw new TypeError(
+ "page.screenshot uses fullPage instead of the v1 full option",
+ );
+ }
+ const { path, fullPage, ...captureOptions } = options;
if (path !== undefined && (typeof path !== "string" || path.length === 0)) {
throw new TypeError("page.screenshot path must be a non-empty string");
}
+ if (fullPage !== undefined && typeof fullPage !== "boolean") {
+ throw new TypeError("page.screenshot fullPage must be a boolean");
+ }
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
- return this.#services.screenshot(path, options, sessionId);
+ return this.#services.screenshot(
+ path,
+ fullPage === undefined
+ ? captureOptions
+ : { ...captureOptions, full: fullPage },
+ sessionId,
+ );
});
}
@@ -1661,7 +1681,7 @@ async function waitForCreatedDocument(
{
// createTab() can return while the target still exposes an already
// complete Chrome placeholder document. Read all three values in one
- // evaluation so newPage resolves only after the requested navigation
+ // evaluation so openPage resolves only after the requested navigation
// has committed a document created during this call.
expression:
"({readyState:document.readyState,url:location.href,timeOrigin:performance.timeOrigin})",
@@ -1678,7 +1698,7 @@ async function waitForCreatedDocument(
}
await services.sleep(Math.min(100, remaining));
}
- throw new Error(`task.newPage timed out after ${timeoutMs}ms`);
+ throw new Error(`task.openPage timed out after ${timeoutMs}ms`);
}
function isCreatedDocumentReady(