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.

fix page interaction and screenshot regressions

Aute280ff2894978
diff --git a/docs/runtime-v2-architecture.md b/docs/runtime-v2-architecture.md
index 53be704..ee09516 100644
--- a/docs/runtime-v2-architecture.md
+++ b/docs/runtime-v2-architecture.md
@@ -328,8 +328,10 @@ Page 对象只在当前脚本轮次内存在,因此鼠标位置不会跨轮保
`KeyboardEvent`,`isTrusted=false`,也不能可靠触发剪贴板和浏览器默认行为。
确实需要合成事件时,调用方可以显式使用 `page.evaluate()`。
-每次成功的 `mouseMoved` 也会非阻塞地通知 Ego Lite 更新 Agent 光标。光标
-动画失败不会让已经完成的网页动作失败。
+每次成功的 `mouseMoved`,以及有明确目标元素的 `fill()`,都会非阻塞地通知
+Ego Lite 更新 Agent 光标。`fill()` 只更新可见光标,不会额外向网页发送鼠标事件。
+光标动画失败不会让已经完成的网页动作失败。`page.keyboard` 没有目标元素信息,
+因此不会自行移动光标。
## 7. Page 操作语义
diff --git a/docs/runtime-v2-real-world-test-log.md b/docs/runtime-v2-real-world-test-log.md
new file mode 100644
index 0000000..fad0602
--- /dev/null
+++ b/docs/runtime-v2-real-world-test-log.md
@@ -0,0 +1,318 @@
+# Runtime v2 真实网站测试记录
+
+这份文档记录使用项目内最新版 Skill 和本地编译 Runtime 进行真实网站测试时的
+结果。这里只记录能够复现、值得后续处理的问题,不把网站本身的限制直接算作
+Runtime 缺陷。
+
+问题分为两类:
+
+- **A:工具缺陷**——实际行为错误、数据丢失或与方法承诺不一致。
+- **B:API 与使用体验**——行为可能有合理解释,但不符合常见预期、缺少说明,
+ 或使用起来容易踩坑。
+
+## 测试环境
+
+- 日期:2026-08-19
+- 分支:`2.0.0-beta-dev`
+- Commit:`220c2a4`
+- Runtime:`package/ego-browser/dist/out/index.js`
+- Skill:`skills/ego-browser/SKILL.md`
+- 加载方式:`ego-browser nodejs --sdk-path <local-runtime>`
+
+## 已完成测试
+
+| 编号 | 网站 | 主要覆盖 | 结果 |
+| ----- | -------------- | ------------------------------------------------------------------------------------- | ------------------------------ |
+| T-001 | Google Docs | Page 跨轮恢复、页面激活、snapshot、截图、标题与正文输入、快捷键、云端保存 | 完成,发现 A-001、A-005、B-001 |
+| T-002 | Google Sheets | canvas 坐标操作、单元格编辑、数字与公式输入、拖拽选区、工具栏操作、跨轮恢复、云端保存 | 完成,再次复现 A-001 |
+| T-003 | NASA Worldview | 重型地图渲染、地点搜索、日期输入、canvas 缩放与拖拽、视觉验证、跨轮恢复 | 完成,发现 A-006 |
+| T-004 | BBC News | 长页面 snapshot、生成 locator、文章导航、浮层、滚动、截图、跨轮恢复 | 完成,发现 A-002、A-003、A-004 |
+| T-005 | Excalidraw | 多 canvas、工具栏操作、鼠标绘制、文本输入、撤销/重做、重新加载、跨轮恢复 | 通过,未发现新问题 |
+| T-006 | 2048 | canvas 游戏、高频方向键、动画状态、DOM 分数、跨轮续玩 | 通过,未发现新问题 |
+
+## A:工具缺陷
+
+### A-001 `Page.keyboard.type()` 在 Google Web 应用中丢失数字并错放符号
+
+**重要程度:高**
+
+**状态:已修复并验证(2026-08-19)**
+
+在已聚焦的 Google Docs 标题输入框和正文编辑区中,英文与空格可以正常输入,
+但数字会丢失,连字符可能出现在错误位置。
+
+复现代码:
+
+```js
+await page.click('input[aria-label="重命名"]');
+await page.keyboard.press("ControlOrMeta+A");
+await page.keyboard.type("Ego Runtime v2 Google Docs Test 2026-08-19", {
+ delay: 5,
+});
+await page.keyboard.press("Enter");
+```
+
+预期标题:
+
+```text
+Ego Runtime v2 Google Docs Test 2026-08-19
+```
+
+实际标题:
+
+```text
+-Ego Runtime v Google Docs Test 0-09
+```
+
+正文中的 `v2` 同样变成了 `v`。作为对照,在相同 Page 和焦点条件下使用:
+
+```js
+await page.keyboard.insertText("Ego Runtime v2 Google Docs Test 2026-08-19");
+```
+
+数字和连字符可以完整保存。因此问题更可能位于 `keyboard.type()` 的物理按键映射
+或事件序列,而不是 Page 路由、页面激活、焦点或 Google Docs 保存。
+
+Google Sheets 中也能稳定复现。向 A1 输入:
+
+```js
+await page.keyboard.type("SKU-2026", { delay: 10 });
+```
+
+单元格实际只得到 `SKU-`。同一张表中,先双击进入单元格编辑态,再使用
+`keyboard.insertText()`,`2`、`4`、`12.50`、`3.25` 和公式均可完整保存。这说明
+问题不是 Google Docs 特例。
+
+根因不在 Google:普通 `<input>` 和 `contenteditable` 也能稳定复现。数字字符被
+错误映射成了 `Numpad0` 至 `Numpad9`;部分小键盘事件没有产生 `beforeinput`,所以
+字符丢失。`NumpadDecimal` 还会覆盖主键盘的 `.`。
+
+我们的键盘布局构造漏掉了 Playwright 的一项规则:带非零 `location` 的数字小键盘
+定义只能通过 `NumpadX` 这类物理键名访问,不能参与字符到物理键的反向映射。修复后
+数字使用 `Digit0` 至 `Digit9`,句点使用 `Period`。
+
+验证结果:
+
+- 新增单元回归,固定数字与句点的 `code` 和 `location`,并验证组合键失败后会释放
+ modifier;完整测试 184/184 通过。
+- 真实 Chromium 中,普通输入框完整得到 `SKU-2026 = 12.50`。
+- Google Docs 标题完整保存为 `Ego keyboard regression 2026-08-19`。
+- 95 个可打印 ASCII 字符逐一输入,实际值与预期值完全一致。
+- 新增 `Page keyboard interface` 真实浏览器 E2E,覆盖 `down()`、`up()`、`press()`、
+ `type()`、`insertText()`、可信事件、按键重复、编辑键、显式小键盘和错误后的状态
+ 恢复;全量真实 E2E 29/29、600 项断言通过。
+
+### A-002 `Page.click()` 会点击被浮层遮挡的目标坐标
+
+**重要程度:高**
+
+**状态:已修复并验证(2026-08-20)**
+
+BBC 文章页同时显示了底部 cookie 提示和位于上层的登录弹窗。snapshot 中
+`@12521` 是底部的 “Reject additional cookies”。调用:
+
+```js
+await page.click("@12521");
+```
+
+没有报错,但 cookie 提示仍在,上层 “Maybe later” 弹窗反而消失。弹窗消失后再次
+点击当前 snapshot 中同一个 `@12521`,cookie 提示才正常关闭。
+
+这说明元素解析正确,但实际指针事件被覆盖在目标上方的浮层接收了。高层
+`click()` 应在点击前确认目标中心的 hit target,遇到遮挡时重试或稳定报错,不能
+静默触发另一个控件。低层 `mouse.click()` 不需要提供这项保证。
+
+根因是 `resolveElementPoint()` 只检查目标尺寸、坐标和 viewport,没有检查该坐标
+实际会命中哪个元素。修复参考 Playwright 的 hit-target 判断:命中元素必须是目标
+本身或它在 composed tree 中的后代,因而也能正确处理普通子元素、slot 和 shadow
+root。高层点击在计算坐标时检查一次,移动鼠标后、每次按下前再检查一次;遮挡时
+抛出 `intercepts pointer events`,不派发按下或点击事件。
+
+这项修复没有增加自动等待。临时浮层仍存在时,调用方会立即得到稳定错误;移除或
+等待浮层消失后可以再次调用。`page.mouse.click(x, y)` 是低层坐标接口,仍会点击该
+坐标上最上层的元素。
+
+验证结果:
+
+- 新增单元回归,确保被遮挡的高层点击不会派发鼠标输入。
+- 新增独立 `Page click hit target` 真实浏览器 E2E,覆盖静态遮挡、鼠标移动后才出现
+ 的遮挡、合法子元素命中、移除浮层后恢复,以及低层坐标点击的原有语义。
+- 完整测试 185/185 通过;全量真实 E2E 30/30、611 项断言通过。
+
+### A-003 页面滚动后,默认 `Page.screenshot()` 返回白图
+
+**重要程度:高**
+
+**状态:已修复并验证(2026-08-20)**
+
+BBC 文章页在顶部截图正常。执行:
+
+```js
+await page.scrollBy(1800, { behavior: "instant" });
+await page.screenshot({ path: "/tmp/default.png" });
+```
+
+得到整张白图。此时页面事实仍正常:`scrollY === 1800`、`scrollHeight === 6402`,
+DOM 中也有文章内容。等待三秒后重试仍为白图;滚回顶部后截图立即恢复。
+
+对照调用可以正确截到滚动位置:
+
+```js
+await page.screenshot({ path: "/tmp/raw.png", raw: true });
+```
+
+根因是默认实现构造 clip 时固定使用 `x: 0, y: 0`,没有包含
+`scrollX/scrollY`;同时非 full screenshot 又关闭了 `captureBeyondViewport`。
+CDP 把 clip 解释为文档坐标,所以页面滚动后实际截取的仍是文档顶部。
+
+修复后,普通 viewport 截图以当前 `scrollX/scrollY` 作为 clip 起点;完整页面截图
+仍从 `(0, 0)` 开始,显式 clip 和 raw 模式保持原样。
+
+验证结果:
+
+- 新增单元回归,固定横向和纵向滚动、viewport 尺寸及 DPR,检查最终发送给 CDP
+ 的 clip 坐标和 scale。
+- 新增 `Page scrolled screenshot` 真实浏览器 E2E。测试页面在文档顶部放白色区域,
+ 滚动后的 viewport 放高对比度图案,并直接解码 PNG 取样;默认截图与 raw 截图的
+ 25 个取样点都正确落在彩色区域。
+- 完整测试 186/186 通过;全量真实 E2E 31/31、624 项断言通过。
+
+### A-004 snapshot 生成的 `loc=href:` 可能立即不可用
+
+BBC 首页 snapshot 为一篇文章给出了:
+
+```text
+loc=href:/news/articles/c235dmndylzo
+```
+
+直接调用 `page.click()` 时,Runtime 报该 locator 命中 5 个元素。改用包含完整文章
+标题的 role locator 后导航正常。页面为了响应式布局重复同一链接很常见;如果
+snapshot 将 `loc=` 作为可复用 locator 输出,生成阶段应验证它在当前页面唯一,
+否则应标为 `loc=ambiguous` 或只给 ref。
+
+### A-005 Ego Lite 启动器没有转发 Runtime 配置环境变量
+
+以下调用在 SDK Node 进程中读到的值是 `undefined`:
+
+```bash
+EGO_BROWSER_AGENT_WORKSPACE=/path/to/skill \
+ ego-browser nodejs --sdk-path <local-runtime> <<'EOF'
+console.log(process.env.EGO_BROWSER_AGENT_WORKSPACE)
+EOF
+```
+
+这不是 Runtime 主动删除变量。真实浏览器 E2E 已明确注明 Ego Lite launcher 不会
+向 SDK Node 进程转发任意环境变量,并通过在 heredoc 内修改 `process.env` 绕过。
+但 Runtime README 同时要求用户从 shell 设置 `EGO_BROWSER_AGENT_WORKSPACE`,两者
+互相矛盾。
+
+启动器至少应转发受支持的 `EGO_BROWSER_*` 白名单,或者提供明确的启动参数和配置
+对象。否则 Runtime 已公开的 workspace、状态目录、页面预算等配置无法按文档使用。
+
+### A-006 `Page.waitForLoadState()` 缺少 `domcontentloaded`
+
+下面的常见调用会直接抛错:
+
+```js
+await page.waitForLoadState("domcontentloaded", { timeout: 45_000 });
+```
+
+当前类型、实现和测试都只接受 `load` 与 `networkidle`。这是此前主动缩小的实现
+范围,不是底层无法支持;可以通过 `document.readyState !== 'loading'` 或 CDP 的
+DOMContentLoaded 事件实现。
+
+既然 API 使用了 Playwright 同名方法和参数形状,应补齐 `domcontentloaded`,而不
+只是依赖文档提醒用户这是一个子集。
+
+## B:API 与使用体验
+
+### B-001 snapshot 展示的是语义角色,不是 HTML 标签名
+
+Google Docs 的 snapshot 显示了保存状态按钮,例如:
+
+```text
+button "文档状态:已保存到云端硬盘。"
+```
+
+使用者很容易把这里的 `button` 理解为 HTML `<button>`,进而写出:
+
+```js
+await page.waitForSelector('button[aria-label*="已保存"]', {
+ state: "visible",
+});
+```
+
+实际元素是带有 `role="button"` 的 `<div>`。下面两种等待均已在同一文档中验证
+通过:
+
+```js
+await page.waitForSelector('[role="button"][aria-label*="已保存"]');
+await page.waitForSelector(
+ 'loc=role:button[name="文档状态:已保存到云端硬盘。"]',
+);
+```
+
+这不是 selector 实现错误,但 snapshot 的树形表示容易让人混淆语义角色与 DOM
+标签。Skill 应明确这一点,并优先建议直接使用 snapshot 给出的 `@N` 或
+`loc=role:`,不要根据显示的角色名称自行拼接 CSS 标签选择器。
+
+建议在 Skill 中同时说明三种定位方式的适用范围:
+
+- 当前 snapshot 后立即操作时,使用 `@N`。
+- 需要语义稳定性时,优先使用 snapshot 给出的 `loc=role:`。
+- 只有确认了真实 DOM 结构后才使用 CSS;不要把 snapshot 中显示的语义角色直接
+ 当作 HTML 标签名。
+
+可以使用下面这段简短说明:
+
+```md
+Snapshot node names such as `button` and `textbox` are accessibility roles,
+not necessarily HTML tag names. Use `@ref` for immediate actions, prefer the
+generated `loc=role:` for semantic reuse, and use CSS only when the actual DOM
+structure is known.
+```
+
+这项说明不能代替 A-004 的修复。Runtime 仍应保证生成的 `loc=` 在当前页面可用,
+不能只依靠 Skill 让 Agent 避开不唯一的 locator。
+
+### B-002 输入动作没有同步移动可见 Agent 光标
+
+**状态:已修复(2026-08-20)**
+
+此前可见 Agent 光标只跟随 `mouseMoved`。`page.fill(selector, value)` 会直接聚焦
+输入元素并输入内容,因此旁观者能看到文字出现,却看不到 Agent 当前在操作哪个
+输入框。
+
+现在 `fill()` 聚焦成功后会取目标元素当前可见部分的中心,并非阻塞地更新 Ego Lite
+光标。这个提示不会向网页额外发送 `mousemove`,也不会改变输入事件序列;光标动画
+失败或目标没有可见区域时,填入本身仍正常完成。
+
+纯 `page.keyboard` 调用没有 selector,也无法可靠知道调用方想表达哪个视觉目标,
+所以不会自行移动光标。需要明确视觉上下文时,应先 `click()` 或 `fill()` 一个具体
+元素。单元回归已确认 `fill()` 会更新可见光标,同时不会增加网页鼠标事件。
+
+## 已确认不是问题的现象
+
+- Google Docs 正文主要由 canvas 和隐藏输入入口实现,snapshot 没有完整返回
+ 正文,但截图可以正确观察。这符合 Skill 对富文本和 canvas 页面优先使用视觉
+ 路径的说明。
+- 通过 `spaceId + Page label` 在多个 heredoc 中找回同一 Google Docs Page 正常。
+- `keyboard.insertText()`、一级标题快捷键、项目符号、粗体、截图和云端保存正常。
+- Google Sheets 中通过双击进入编辑态后,逐格输入、公式计算、拖拽选择、工具栏
+ 加粗和跨轮 Page 恢复均正常;`SUMPRODUCT(B4:B5,C4:C5)` 正确得到 `38`。
+- NASA Worldview 的 WebGL/canvas 卫星图能正常截图;地点搜索、日期表单、按钮缩放、
+ 低层鼠标拖拽和跨轮恢复均正常。拖拽后 URL 中的视野坐标与截图同步变化。
+- BBC News 的约 59 KB 首页 snapshot 和约 39 KB 文章 snapshot 均完整可读;使用
+ 唯一 role locator 导航、长文滚动、`raw` 截图和跨轮恢复正常。
+- Excalidraw 中的矩形、椭圆、箭头和文本均可正常创建;文本中的 `v2`、日期和
+ 连字符由 `insertText()` 完整保留。撤销、重做、同 Page 重新加载后的浏览器存储
+ 恢复,以及跨轮 Page 恢复均正常。canvas 内容不进入语义 snapshot,使用截图
+ 验证,符合 Skill 指引。
+- 2048 中连续 24 次方向键操作后分数从 0 增至 144;换一个 heredoc 找回同一
+ Page 后继续 16 次操作,分数增至 272。键盘事件、canvas 动画、DOM 分数与视觉
+ 状态一致。
+
+## 后续记录格式
+
+新增问题时至少写明:网站与任务、调用方式、预期结果、实际结果、对照实验、证据
+以及当前判断。尚未稳定复现的问题应明确标记,避免把一次网站波动写成确定缺陷。
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
index 591165d..de92dba 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -6,6 +6,9 @@ import { observationCase } from "./observation.mjs";
import { pointerCase } from "./pointer.mjs";
import { keyboardCase } from "./keyboard.mjs";
import { keyboardRegressionCase } from "./keyboard-regression.mjs";
+import { pageKeyboardInterfaceCase } from "./page-keyboard.mjs";
+import { pageClickHitTargetCase } from "./page-click-hit-target.mjs";
+import { pageScrolledScreenshotCase } from "./page-screenshot.mjs";
import { runtimeCase } from "./runtime.mjs";
import { runtimeRegressionCase } from "./runtime-regression.mjs";
import { eventIsolationCase } from "./event-isolation.mjs";
@@ -62,8 +65,11 @@ export const e2eCases = [
{ name: "page complex evaluate", body: pageComplexEvaluateCase },
{ name: "page fetch", body: pageFetchCase },
{ name: "page actions and popup adoption", body: pageActionsAndPopupCase },
+ { name: "Page click hit target", body: pageClickHitTargetCase },
+ { name: "Page scrolled screenshot", body: pageScrolledScreenshotCase },
{ name: "v1 and v2 action parity", body: v1V2ActionParityCase },
{ name: "portable keyboard workflow", body: portableKeyboardWorkflowCase },
+ { name: "Page keyboard interface", body: pageKeyboardInterfaceCase },
{ name: "pure CDP workflow", body: pureCdpWorkflowCase },
{ name: "snapshot workflow", body: snapshotWorkflowCase },
{ name: "visual workflow", body: visualWorkflowCase },
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs
new file mode 100644
index 0000000..e2ae158
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-click-hit-target.mjs
@@ -0,0 +1,108 @@
+export function pageClickHitTargetCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await task.openPage(baseUrl + "/?workflow=page-click-hit-target", {
+ as: "page-click-hit-target",
+ });
+
+ await page.evaluate(() => {
+ const target = document.createElement("button");
+ target.id = "covered-target";
+ target.textContent = "Covered target";
+ target.style.cssText =
+ "position:fixed;left:100px;top:100px;width:240px;height:80px;z-index:10";
+ const overlay = document.createElement("button");
+ overlay.id = "click-overlay";
+ overlay.textContent = "Overlay";
+ overlay.style.cssText =
+ "position:fixed;left:80px;top:80px;width:280px;height:120px;z-index:20";
+ window.__hitTargetClicks = { target: 0, overlay: 0 };
+ target.addEventListener("click", () => window.__hitTargetClicks.target++);
+ overlay.addEventListener("click", () => window.__hitTargetClicks.overlay++);
+ document.body.append(target, overlay);
+ });
+
+ await assertRejects(
+ () => page.click("#covered-target"),
+ "intercepts pointer events",
+ "high-level click rejects when another element covers its action point"
+ );
+ assertEqual(
+ JSON.stringify(await page.evaluate("window.__hitTargetClicks")),
+ JSON.stringify({ target: 0, overlay: 0 }),
+ "an intercepted high-level click reaches neither element"
+ );
+
+ const coveredPoint = await page.evaluate(() => {
+ const rect = document.querySelector("#covered-target").getBoundingClientRect();
+ return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
+ });
+ await page.mouse.click(coveredPoint.x, coveredPoint.y);
+ assertEqual(
+ (await page.evaluate("window.__hitTargetClicks")).overlay,
+ 1,
+ "low-level coordinate click still targets the topmost element"
+ );
+
+ await page.evaluate("document.querySelector('#click-overlay').remove()");
+ await page.click("#covered-target");
+ assertEqual(
+ (await page.evaluate("window.__hitTargetClicks")).target,
+ 1,
+ "the target becomes clickable after the overlay is removed"
+ );
+
+ await page.evaluate(() => {
+ document.querySelector("#covered-target").remove();
+ const target = document.createElement("button");
+ target.id = "hover-covered-target";
+ target.textContent = "Covered after hover";
+ target.style.cssText =
+ "position:fixed;left:100px;top:240px;width:240px;height:80px;z-index:10";
+ window.__hoverCoveredClicks = { target: 0, overlay: 0 };
+ target.addEventListener("mouseenter", () => {
+ if (document.querySelector("#hover-overlay")) return;
+ const overlay = document.createElement("button");
+ overlay.id = "hover-overlay";
+ overlay.textContent = "Appeared on hover";
+ overlay.style.cssText =
+ "position:fixed;left:80px;top:220px;width:280px;height:120px;z-index:20";
+ overlay.addEventListener("click", () => window.__hoverCoveredClicks.overlay++);
+ document.body.append(overlay);
+ });
+ target.addEventListener("click", () => window.__hoverCoveredClicks.target++);
+ document.body.append(target);
+ });
+ await assertRejects(
+ () => page.click("#hover-covered-target"),
+ "intercepts pointer events",
+ "click rechecks the hit target after mouse movement"
+ );
+ assertEqual(
+ JSON.stringify(await page.evaluate("window.__hoverCoveredClicks")),
+ JSON.stringify({ target: 0, overlay: 0 }),
+ "an overlay created by hover receives no click"
+ );
+
+ await page.evaluate(() => {
+ document.querySelector("#hover-overlay").remove();
+ document.querySelector("#hover-covered-target").remove();
+ const button = document.createElement("button");
+ button.id = "descendant-target";
+ button.style.cssText =
+ "position:fixed;left:100px;top:380px;width:240px;height:80px;z-index:10";
+ button.innerHTML = '<span id="target-child">Child content</span>';
+ window.__descendantClicks = 0;
+ button.addEventListener("click", () => window.__descendantClicks++);
+ document.body.append(button);
+ });
+ await page.click("#descendant-target");
+ assertEqual(
+ await page.evaluate("window.__descendantClicks"),
+ 1,
+ "a descendant at the action point is a valid hit target"
+ );
+
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs
new file mode 100644
index 0000000..7823ee2
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs
@@ -0,0 +1,154 @@
+export function pageKeyboardInterfaceCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await task.openPage(baseUrl + "/?workflow=page-keyboard-interface", {
+ as: "page-keyboard-interface",
+ });
+
+ await page.evaluate(() => {
+ const input = document.querySelector("#text-area");
+ input.value = "";
+ input.focus();
+ window.__pageKeyboardContractEvents = [];
+ for (const type of ["keydown", "keyup", "beforeinput", "input"]) {
+ input.addEventListener(type, (event) => {
+ window.__pageKeyboardContractEvents.push({
+ type,
+ key: event.key ?? null,
+ code: event.code ?? null,
+ location: event.location ?? null,
+ repeat: event.repeat ?? false,
+ shiftKey: event.shiftKey ?? false,
+ data: event.data ?? null,
+ trusted: event.isTrusted,
+ });
+ });
+ }
+ });
+
+ // U+0020 through U+007E covers every printable ASCII character.
+ const printable = Array.from(
+ { length: 95 },
+ (_, index) => String.fromCharCode(32 + index),
+ ).join("");
+ await page.keyboard.type(printable);
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ printable,
+ "page.keyboard.type preserves every printable ASCII character"
+ );
+
+ const printableEvents = await page.evaluate("window.__pageKeyboardContractEvents");
+ const printableDowns = printableEvents.filter((event) => event.type === "keydown");
+ assertEqual(printableDowns.length, 95, "printable ASCII uses one keydown per character");
+ assert(
+ printableDowns.every((event) => event.trusted === true),
+ "printable ASCII reaches the page as trusted keyboard input"
+ );
+ assertEqual(
+ printableDowns
+ .filter((event) => /^[0-9]$/.test(event.key))
+ .map((event) => event.code)
+ .join(","),
+ Array.from({ length: 10 }, (_, digit) => "Digit" + digit).join(","),
+ "digit characters use the main number row"
+ );
+ assertEqual(
+ printableDowns.find((event) => event.key === ".")?.code,
+ "Period",
+ "period uses the main keyboard key"
+ );
+ assert(
+ printableDowns.every((event) => !String(event.code).startsWith("Numpad")),
+ "ordinary character typing never resolves to the numpad"
+ );
+
+ await page.evaluate(() => {
+ const input = document.querySelector("#text-area");
+ input.value = "";
+ input.focus();
+ window.__pageKeyboardContractEvents = [];
+ });
+ await page.keyboard.down("Shift");
+ await page.keyboard.down("a");
+ await page.keyboard.down("a");
+ await page.keyboard.up("a");
+ await page.keyboard.up("Shift");
+ await page.keyboard.type("a");
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ "AAa",
+ "down and up preserve then release modifier state"
+ );
+ const repeatedA = (await page.evaluate("window.__pageKeyboardContractEvents"))
+ .filter((event) => event.type === "keydown" && event.code === "KeyA");
+ assertEqual(repeatedA[0].repeat, false, "the first keydown is not a repeat");
+ assertEqual(repeatedA[1].repeat, true, "a second down without up is a repeat");
+ assertEqual(repeatedA[0].shiftKey, true, "held Shift modifies following keys");
+
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.type("replaced");
+ await page.keyboard.press("ArrowLeft");
+ await page.keyboard.press("Backspace");
+ await page.keyboard.press("Delete");
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ "replac",
+ "press drives native selection, arrow, Backspace, and Delete behavior"
+ );
+ await page.keyboard.press("Enter");
+ await page.keyboard.type("next");
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ "replac\\nnext",
+ "named Enter inserts a line break"
+ );
+
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.type("A世界🙂");
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ "A世界🙂",
+ "type falls back to native text insertion for non-US characters"
+ );
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.insertText("direct 世界🙂");
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ "direct 世界🙂",
+ "insertText inserts one native text payload"
+ );
+
+ await page.evaluate("window.__pageKeyboardContractEvents = []");
+ await page.keyboard.press("Numpad1");
+ const numpadEvent = (await page.evaluate("window.__pageKeyboardContractEvents"))
+ .find((event) => event.type === "keydown");
+ assertEqual(numpadEvent.code, "Numpad1", "explicit numpad keys retain their physical code");
+ assertEqual(numpadEvent.location, 3, "explicit numpad keys retain keypad location");
+ assertEqual(numpadEvent.trusted, true, "explicit numpad keys remain trusted input");
+
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.type("state");
+ await assertRejects(
+ () => page.keyboard.press("Shift+DefinitelyUnknown"),
+ "Unknown key",
+ "unknown keys reject"
+ );
+ await page.keyboard.type("a");
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ "statea",
+ "a failed chord releases modifiers before the next action"
+ );
+
+ await page.keyboard.press("ControlOrMeta+A");
+ await page.keyboard.press("+");
+ assertEqual(
+ await page.evaluate("document.querySelector('#text-area').value"),
+ "+",
+ "a literal plus key is not mistaken for a chord separator"
+ );
+
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs
new file mode 100644
index 0000000..8c9b959
--- /dev/null
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-screenshot.mjs
@@ -0,0 +1,51 @@
+export function pageScrolledScreenshotCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const page = await task.openPage(baseUrl + "/?workflow=page-scrolled-screenshot", {
+ as: "page-scrolled-screenshot",
+ });
+
+ await page.evaluate(() => {
+ document.documentElement.style.cssText = "margin:0;padding:0";
+ document.body.style.cssText = "margin:0;padding:0;width:2200px";
+ document.body.innerHTML =
+ '<div style="width:2200px;height:1400px;background:white"></div>' +
+ '<div id="screenshot-marker" style="width:2200px;height:1200px;' +
+ 'background:repeating-conic-gradient(#e11d48 0 12deg,#2563eb 12deg 24deg,#16a34a 24deg 36deg) 0 0/96px 96px"></div>';
+ scrollTo(240, 1600);
+ });
+ const scrollPosition = await page.evaluate(() => ({
+ x: scrollX,
+ y: scrollY,
+ width: innerWidth,
+ height: innerHeight,
+ }));
+ assert(scrollPosition.x > 0 && scrollPosition.y >= 1400, "fixture is scrolled in both axes");
+
+ const defaultPath = join(artifactDir, "scrolled-default.png");
+ const rawPath = join(artifactDir, "scrolled-raw.png");
+ await page.screenshot({ path: defaultPath, fullPage: false });
+ await page.screenshot({ path: rawPath, fullPage: false, raw: true });
+
+ const defaultImage = await readFile(defaultPath);
+ const rawImage = await readFile(rawPath);
+ assert(defaultImage.length > 100, "default scrolled screenshot is non-empty");
+ assert(rawImage.length > 100, "raw scrolled screenshot is non-empty");
+ const defaultSamples = countColorfulPngSamples(defaultImage);
+ const rawSamples = countColorfulPngSamples(rawImage);
+ cliLog(JSON.stringify({
+ screenshotBytes: { default: defaultImage.length, raw: rawImage.length },
+ screenshotSamples: { default: defaultSamples, raw: rawSamples },
+ }));
+ assert(
+ rawSamples.colorful >= 20,
+ "raw CDP capture confirms that the visible viewport contains the colored marker"
+ );
+ assert(
+ defaultSamples.colorful >= 20,
+ "default screenshot captures the colored marker at the current scroll position"
+ );
+
+ await page.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
index 7c3b1eb..5c1ed21 100644
--- a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs
@@ -14,6 +14,7 @@ export function egoSource(body, context) {
return `
const { readFile, stat, writeFile } = await import("node:fs/promises");
const { join } = await import("node:path");
+ const { inflateSync } = await import("node:zlib");
const taskName = ${JSON.stringify(taskName)};
const baseUrl = ${JSON.stringify(baseUrl)};
const artifactDir = ${JSON.stringify(artifactDir)};
@@ -55,6 +56,88 @@ export function egoSource(body, context) {
);
}
+ function countColorfulPngSamples(png) {
+ const signature = "89504e470d0a1a0a";
+ assertEqual(png.subarray(0, 8).toString("hex"), signature, "artifact is a PNG");
+ let width = 0;
+ let height = 0;
+ let bitDepth = 0;
+ let colorType = 0;
+ let interlace = 0;
+ const imageData = [];
+ for (let offset = 8; offset < png.length; ) {
+ const length = png.readUInt32BE(offset);
+ const type = png.subarray(offset + 4, offset + 8).toString("ascii");
+ const data = png.subarray(offset + 8, offset + 8 + length);
+ if (type === "IHDR") {
+ width = data.readUInt32BE(0);
+ height = data.readUInt32BE(4);
+ bitDepth = data[8];
+ colorType = data[9];
+ interlace = data[12];
+ } else if (type === "IDAT") {
+ imageData.push(data);
+ }
+ offset += length + 12;
+ if (type === "IEND") break;
+ }
+ assertEqual(bitDepth, 8, "PNG sampler supports 8-bit screenshots");
+ assertEqual(interlace, 0, "PNG sampler supports non-interlaced screenshots");
+ const channels = ({ 0: 1, 2: 3, 4: 2, 6: 4 })[colorType];
+ assert(channels, "PNG sampler supports the screenshot color type");
+ const inflated = inflateSync(Buffer.concat(imageData));
+ const stride = width * channels;
+ const pixels = Buffer.alloc(stride * height);
+ let sourceOffset = 0;
+ for (let y = 0; y < height; y++) {
+ const filter = inflated[sourceOffset++];
+ const rowOffset = y * stride;
+ const previousOffset = (y - 1) * stride;
+ for (let x = 0; x < stride; x++) {
+ const raw = inflated[sourceOffset++];
+ const left = x >= channels ? pixels[rowOffset + x - channels] : 0;
+ const up = y > 0 ? pixels[previousOffset + x] : 0;
+ const upperLeft = y > 0 && x >= channels
+ ? pixels[previousOffset + x - channels]
+ : 0;
+ let predictor = 0;
+ if (filter === 1) predictor = left;
+ else if (filter === 2) predictor = up;
+ else if (filter === 3) predictor = Math.floor((left + up) / 2);
+ else if (filter === 4) {
+ const estimate = left + up - upperLeft;
+ const leftDistance = Math.abs(estimate - left);
+ const upDistance = Math.abs(estimate - up);
+ const upperLeftDistance = Math.abs(estimate - upperLeft);
+ predictor = leftDistance <= upDistance && leftDistance <= upperLeftDistance
+ ? left
+ : upDistance <= upperLeftDistance
+ ? up
+ : upperLeft;
+ } else if (filter !== 0) {
+ throw new Error("Unsupported PNG filter " + filter);
+ }
+ pixels[rowOffset + x] = (raw + predictor) & 255;
+ }
+ }
+
+ let colorful = 0;
+ let sampled = 0;
+ for (let row = 1; row <= 5; row++) {
+ for (let column = 1; column <= 5; column++) {
+ const x = Math.floor((width * column) / 6);
+ const y = Math.floor((height * row) / 6);
+ const offset = y * stride + x * channels;
+ const red = pixels[offset];
+ const green = colorType === 0 || colorType === 4 ? red : pixels[offset + 1];
+ const blue = colorType === 0 || colorType === 4 ? red : pixels[offset + 2];
+ sampled++;
+ if (Math.max(red, green, blue) - Math.min(red, green, blue) > 30) colorful++;
+ }
+ }
+ return { colorful, sampled, width, height };
+ }
+
async function assertRejects(fn, expected, message) {
__assertionCount++;
try {
diff --git a/package/ego-browser/src/driver/observe.test.mjs b/package/ego-browser/src/driver/observe.test.mjs
index 7bc9837..02a69b7 100644
--- a/package/ego-browser/src/driver/observe.test.mjs
+++ b/package/ego-browser/src/driver/observe.test.mjs
@@ -33,7 +33,21 @@ function withCdpRuntime(fn) {
} else if (request.method === "Page.captureScreenshot") {
result = { data: Buffer.from("png").toString("base64") };
} else if (request.method === "Runtime.evaluate") {
- result = { result: { value: "1" } };
+ result = {
+ result: {
+ value:
+ request.params.expression === "window.devicePixelRatio"
+ ? 2
+ : {
+ w: 800,
+ h: 600,
+ sx: 24,
+ sy: 1200,
+ pw: 1600,
+ ph: 3000,
+ },
+ },
+ };
}
queueMicrotask(() =>
runtime.onCDPMessage(JSON.stringify({ id: request.id, result })),
@@ -97,3 +111,31 @@ test("captureScreenshot skips page metric JavaScript while a native dialog is pe
assert.equal(writes.length, 1);
assert.equal(writes[0].path, "/tmp/ego-browser-dialog-shot.png");
});
+
+test("captureScreenshot clips the currently visible scrolled viewport", async () => {
+ const restore = setOverrides({
+ async writeFile() {},
+ });
+ try {
+ await withCdpRuntime(async ({ sent }) => {
+ await captureScreenshot("/tmp/ego-browser-scrolled-shot.png");
+
+ const screenshot = sent.find(
+ (request) => request.method === "Page.captureScreenshot",
+ );
+ assert.deepEqual(screenshot.params, {
+ format: "png",
+ captureBeyondViewport: false,
+ clip: {
+ x: 24,
+ y: 1200,
+ width: 800,
+ height: 600,
+ scale: 0.5,
+ },
+ });
+ });
+ } finally {
+ restore();
+ }
+});
diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.ts
index bf01001..b7a1305 100644
--- a/package/ego-browser/src/driver/observe.ts
+++ b/package/ego-browser/src/driver/observe.ts
@@ -158,8 +158,12 @@ export async function captureScreenshotForSession(
infoExpression,
);
params.clip = {
- x: 0,
- y: 0,
+ // CDP interprets clip coordinates in the page's document coordinate
+ // space. A viewport screenshot therefore starts at the current scroll
+ // offset, while a full-page screenshot still starts at the document
+ // origin.
+ x: full ? 0 : info.sx,
+ y: full ? 0 : info.sy,
width: full ? info.pw : info.w,
height: full ? info.ph : info.h,
scale: cssScale,
diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.ts
index 49e3448..6c004f5 100644
--- a/package/ego-browser/src/driver/page-actions.ts
+++ b/package/ego-browser/src/driver/page-actions.ts
@@ -95,6 +95,14 @@ export async function clickInPage(
modifiers,
});
for (let count = 1; count <= clickCount; count += 1) {
+ // Moving the pointer or completing an earlier click can change layout.
+ // Recheck before every press so hover-created overlays fail closed.
+ await assertElementReceivesPointerEvents(
+ services,
+ target.sessionId,
+ target.objectId,
+ point,
+ );
await dispatchMouseEvent(services, target.sessionId, {
type: "mousePressed",
x: point.x,
@@ -153,6 +161,17 @@ export async function fillInPage(
try {
const preparationSource = `function fillPreparation(value, clearFirst) {
if (!this.isConnected) return { error: "element is not connected" };
+ const visibleCursorPoint = () => {
+ const rect = this.getBoundingClientRect();
+ const view = this.ownerDocument.defaultView;
+ if (!view || rect.width <= 0 || rect.height <= 0) return null;
+ const left = Math.max(0, rect.left);
+ const top = Math.max(0, rect.top);
+ const right = Math.min(view.innerWidth, rect.right);
+ const bottom = Math.min(view.innerHeight, rect.bottom);
+ if (right <= left || bottom <= top) return null;
+ return { x: (left + right) / 2, y: (top + bottom) / 2 };
+ };
const tag = this.nodeName.toLowerCase();
if (this.disabled) return { error: "element is disabled" };
if (this.readOnly) return { error: "element is read only" };
@@ -174,14 +193,15 @@ export async function fillInPage(
if (this.value !== nextValue) return { error: "malformed value" };
this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
this.dispatchEvent(new Event("change", { bubbles: true }));
- return "done";
+ return { status: "done", cursorPoint: visibleCursorPoint() };
}
} else if (tag !== "textarea" && !this.isContentEditable) {
return { error: "element is not an input, textarea, or contenteditable element" };
}
this.focus();
- if (!clearFirst) return "needsinput";
+ const cursorPoint = visibleCursorPoint();
+ if (!clearFirst) return { status: "needsinput", cursorPoint };
if (tag === "input" || tag === "textarea") {
this.select();
} else {
@@ -191,7 +211,7 @@ export async function fillInPage(
selection?.removeAllRanges();
selection?.addRange(range);
}
- return "needsinput";
+ return { status: "needsinput", cursorPoint };
}`;
const preparation = await services.cdp(
"Runtime.callFunctionOn",
@@ -208,7 +228,12 @@ export async function fillInPage(
if (typeof result?.error === "string") {
throw new Error(`page.fill failed: ${result.error}`);
}
- if (result === "done") return;
+ showAgentCursor(services, result?.cursorPoint);
+ const status = typeof result === "string" ? result : result?.status;
+ if (status === "done") return;
+ if (status !== "needsinput") {
+ throw new Error("page.fill received an invalid preparation result");
+ }
if (clearFirst && value.length === 0) {
const keyDown: Record<string, unknown> = {
@@ -510,6 +535,7 @@ async function resolveElementPoint(
? "({x:rect.x+position.x,y:rect.y+position.y})"
: "({x:rect.x+rect.width/2,y:rect.y+rect.height/2})";
const expression = `function(${position ? "position" : ""}) {
+ ${HIT_TARGET_HELPERS}
let rect = this.getBoundingClientRect();
let point = ${pointExpression};
const outsideViewport =
@@ -528,6 +554,10 @@ async function resolveElementPoint(
) {
return { error: "element is not visible in the viewport" };
}
+ const interceptor = interceptingElementAtPoint(this, point);
+ if (interceptor) {
+ return { error: describeHitTarget(interceptor) + " intercepts pointer events" };
+ }
return point;
}`;
const response = await services.cdp(
@@ -551,6 +581,79 @@ async function resolveElementPoint(
return point;
}
+async function assertElementReceivesPointerEvents(
+ services: PageActionServices,
+ sessionId: string,
+ objectId: string,
+ point: { x: number; y: number },
+): Promise<void> {
+ const expression = `function(point) {
+ ${HIT_TARGET_HELPERS}
+ if (!this.isConnected) return { error: "element is not connected" };
+ const interceptor = interceptingElementAtPoint(this, point);
+ return interceptor
+ ? { error: describeHitTarget(interceptor) + " intercepts pointer events" }
+ : { ok: true };
+ }`;
+ const response = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: expression,
+ objectId,
+ arguments: [{ value: point }],
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
+ const result = runtimeValue(response, expression);
+ if (typeof result?.error === "string") {
+ throw new Error(`page.click failed: ${result.error}`);
+ }
+}
+
+// This is a compact adaptation of Playwright's composed-tree hit-target check.
+// It handles ordinary descendants, slots, and nested shadow roots without
+// exposing an injected helper or trusting only document.elementFromPoint().
+const HIT_TARGET_HELPERS = `
+ function composedParent(element) {
+ if (element.assignedSlot) return element.assignedSlot;
+ if (element.parentElement) return element.parentElement;
+ const root = element.getRootNode ? element.getRootNode() : null;
+ return root && root.nodeType === 11 ? root.host : null;
+ }
+ function interceptingElementAtPoint(target, point) {
+ const roots = [];
+ let parent = target;
+ while (parent) {
+ const root = parent.getRootNode ? parent.getRootNode() : null;
+ if (!root || typeof root.elementsFromPoint !== "function") break;
+ roots.push(root);
+ if (root.nodeType === 9) break;
+ parent = root.host;
+ }
+ let hitElement;
+ for (let index = roots.length - 1; index >= 0; index -= 1) {
+ const root = roots[index];
+ const elements = root.elementsFromPoint(point.x, point.y);
+ const innerElement = elements[0] || root.elementFromPoint(point.x, point.y);
+ if (!innerElement) break;
+ hitElement = innerElement;
+ if (index > 0 && innerElement !== roots[index - 1].host) break;
+ }
+ let current = hitElement;
+ while (current && current !== target) current = composedParent(current);
+ return current === target ? null : hitElement || document.documentElement;
+ }
+ function describeHitTarget(element) {
+ const tag = String(element.tagName || "unknown").toLowerCase();
+ const id = element.id
+ ? ' id="' + String(element.id).slice(0, 80).replaceAll('"', '&quot;') + '"'
+ : "";
+ return "<" + tag + id + ">";
+ }
+`;
+
function assertPageSelector(selector: unknown): asserts selector is string {
if (typeof selector !== "string" || selector.trim().length === 0) {
throw new TypeError("Page actions require a non-empty selector string");
@@ -578,16 +681,30 @@ async function dispatchMouseEvent(
) {
return;
}
+ showAgentCursor(services, { x: params.x, y: params.y });
+}
+
+function showAgentCursor(
+ services: PageActionServices,
+ point: { x?: unknown; y?: unknown } | null | undefined,
+): void {
+ const x = point?.x;
+ const y = point?.y;
+ if (
+ typeof x !== "number" ||
+ !Number.isFinite(x) ||
+ typeof y !== "number" ||
+ !Number.isFinite(y)
+ ) {
+ return;
+ }
try {
- // Ego Lite's visible agent cursor is separate from renderer input. Update
- // it only after the page accepted the move, and start the native request
- // while the Page gate still owns the correct task space. Do not wait for
- // the animation: the legacy helpers also treat this as display-only work,
- // and a completed website action must never look retryable because its
- // cursor animation is slow or unavailable.
- void services.showAgentMousePosition(params.x, params.y).catch(() => {});
+ // The native cursor is a display-only hint. Start it while the Page gate
+ // still owns the correct task space, but never let rendering latency or an
+ // unavailable overlay affect a completed website action.
+ void services.showAgentMousePosition(x, y).catch(() => {});
} catch {
- // Also tolerate an invalid test adapter that throws before returning a Promise.
+ // Also tolerate an invalid adapter that throws before returning a Promise.
}
}
diff --git a/package/ego-browser/src/driver/page-keyboard.ts b/package/ego-browser/src/driver/page-keyboard.ts
index 81a6c49..ff46d04 100644
--- a/package/ego-browser/src/driver/page-keyboard.ts
+++ b/package/ego-browser/src/driver/page-keyboard.ts
@@ -424,7 +424,10 @@ function buildKeyboardLayout(): Map<string, KeyDefinition> {
};
}
layout.set(code, definition);
- if (definition.location === 0 && definition.key.length === 1) {
+ // Character input should resolve to the main keyboard, never to the numpad.
+ // Numpad shifted keys expose digits, so indexing them would overwrite Digit0-9.
+ if (definition.location !== 0) continue;
+ if (definition.key.length === 1) {
layout.set(definition.key, definition);
}
if (definition.shifted) {
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 3f32fb4..32cc84d 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -33,6 +33,7 @@ function createFixture(rootDir) {
let systemFileChooserOpened = false;
let timeoutNextMouseDispatch = false;
let rejectNextClickPoint = false;
+ let interceptNextClickPoint = false;
let navigateOnNextClickUrl = null;
let elementPresent = true;
let elementVisible = true;
@@ -168,7 +169,15 @@ function createFixture(rootDir) {
};
}
if (params.functionDeclaration.includes("fillPreparation")) {
- return { result: { type: "string", value: "needsinput" } };
+ return {
+ result: {
+ type: "object",
+ value: {
+ status: "needsinput",
+ cursorPoint: { x: 40, y: 60 },
+ },
+ },
+ };
}
if (params.functionDeclaration.includes("checkVisibility")) {
return { result: { type: "boolean", value: elementVisible } };
@@ -203,6 +212,20 @@ function createFixture(rootDir) {
};
}
if (params.functionDeclaration.includes("getBoundingClientRect")) {
+ if (
+ interceptNextClickPoint &&
+ params.functionDeclaration.includes("elementFromPoint")
+ ) {
+ interceptNextClickPoint = false;
+ return {
+ result: {
+ type: "object",
+ value: {
+ error: '<button id="overlay"> intercepts pointer events',
+ },
+ },
+ };
+ }
if (rejectNextClickPoint) {
rejectNextClickPoint = false;
return {
@@ -394,6 +417,9 @@ function createFixture(rootDir) {
rejectNextClickPoint() {
rejectNextClickPoint = true;
},
+ interceptNextClickPoint() {
+ interceptNextClickPoint = true;
+ },
navigateOnNextClick(url) {
navigateOnNextClickUrl = url;
},
@@ -987,6 +1013,19 @@ test("Page fill uses its target session and reports no popup when none opened",
params.functionDeclaration.includes("fillPreparation"),
);
assert(fillPreparation, "fill must validate and select the target element");
+ assert.deepEqual(
+ fixture.calls.find(([kind]) => kind === "showAgentMousePosition"),
+ ["showAgentMousePosition", 40, 60],
+ "fill must move the visible agent cursor to its focused element",
+ );
+ assert.equal(
+ fixture.calls.some(
+ ([kind, method]) =>
+ kind === "cdp" && method === "Input.dispatchMouseEvent",
+ ),
+ false,
+ "the fill cursor hint must not synthesize a website mouse event",
+ );
assert.equal(
fixture.calls.some(
([kind, method, params]) =>
@@ -1312,6 +1351,35 @@ test("Page keyboard press and type use the addressed target session", async () =
});
});
+test("Page keyboard type uses the main keyboard for digits and period", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/first");
+
+ await page.keyboard.type("0123456789.");
+
+ const keyDowns = fixture.calls
+ .filter(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchKeyEvent" &&
+ params.type === "keyDown",
+ )
+ .map(([, , params]) => params);
+ assert.deepEqual(
+ keyDowns.map(({ key, code, location }) => ({ key, code, location })),
+ [
+ ...Array.from({ length: 10 }, (_, digit) => ({
+ key: String(digit),
+ code: `Digit${digit}`,
+ location: 0,
+ })),
+ { key: ".", code: "Period", location: 0 },
+ ],
+ );
+ });
+});
+
test("Page keyboard mirrors Playwright key state and the US layout", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { platform: "darwin" });
@@ -1462,6 +1530,30 @@ test("Page keyboard type emits physical keys when possible and inserts unsupport
});
});
+test("Page keyboard releases pressed modifiers when a chord fails", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a", { platform: "darwin" });
+ const page = await task.openPage("https://example.test/first");
+
+ await assert.rejects(
+ () => page.keyboard.press("Shift+DefinitelyUnknown"),
+ /Unknown key/,
+ );
+ await page.keyboard.type("a");
+
+ const aDown = fixture.calls.find(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Input.dispatchKeyEvent" &&
+ params.type === "keyDown" &&
+ params.code === "KeyA",
+ );
+ assert.equal(aDown[2].key, "a");
+ assert.equal(aDown[2].text, "a");
+ assert.equal(aDown[2].modifiers, 0);
+ });
+});
+
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" });
@@ -1888,6 +1980,27 @@ test("Page click does not dispatch input when scrolling cannot make the element
});
});
+test("Page click fails closed when another element intercepts the point", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/first");
+ fixture.interceptNextClickPoint();
+
+ await assert.rejects(
+ () => page.click("#covered"),
+ /overlay.*intercepts pointer events/,
+ );
+ assert.equal(
+ fixture.calls.some(
+ ([kind, method]) =>
+ kind === "cdp" && method === "Input.dispatchMouseEvent",
+ ),
+ false,
+ "an intercepted high-level click must not dispatch any mouse input",
+ );
+ });
+});
+
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");
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 11bee69..84922df 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -248,6 +248,12 @@ await page.dragAndDrop(source, target, {
await page.fill(selector, value, { clearFirst });
```
+Pointer actions and `fill()` update Ego Lite's visible Agent cursor. `fill()`
+does not synthesize a mouse event just for the cursor hint. Bare
+`page.keyboard` calls do not move the cursor because they have no target
+element; click or fill an explicit element first when that visual context
+matters.
+
High-level `goto()`, selector actions, `mouse.click()`, and `keyboard.press()` return lightweight receipts:
```js