fix(browser): align BrowserSkill 0.3.0 and repair task lifecycle

main
wizardchen 2026-09-17 10:00:21 +08:00 committed by lyingbug
parent f2606629b3
commit 84c9871d16
35 changed files with 3179 additions and 4007 deletions

View File

@ -781,7 +781,7 @@ CONCURRENCY_POOL_SIZE=5
# 单应用实例共用一个 daemon;最多保留的用户配对记录数(默认 32,非实测承载量)。
# BROWSERSKILL_MAX_CONNECTIONS=32
# 供个人设置下载的配套扩展 ZIP(服务器本地绝对路径,Docker 已预设)。
# BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.2.1.zip
# BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.3.0.zip
# 多副本:每个节点填写可被其他节点直接访问的地址,不要使用负载均衡地址。
# BROWSERSKILL_INTERNAL_URL=http://10.0.0.12:8080
# 所有副本使用相同的随机密钥(至少 32 字符),从 Secret 注入,不提交到仓库。

View File

@ -1,10 +1,12 @@
# Build the paired extension and fetch the checksum-pinned native daemon.
# Node runs on the builder architecture; only bsk targets the runtime image.
FROM --platform=$BUILDPLATFORM node:24-bookworm-slim@sha256:ba849c60be29959425b8734d57b8b4b7d56f98edd9504c9af091d5281095a71e AS browserskill
# Build extension and daemon from the same pinned source on the runtime architecture.
FROM --platform=$TARGETPLATFORM node:24-bookworm-slim@sha256:ba849c60be29959425b8734d57b8b4b7d56f98edd9504c9af091d5281095a71e AS browserskill
WORKDIR /build
RUN apt-get update && \
apt-get install -y --no-install-recommends git python3 ca-certificates && \
apt-get install -y --no-install-recommends git python3 ca-certificates curl build-essential cmake pkg-config && \
rm -rf /var/lib/apt/lists/*
ENV RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo
ENV PATH=/usr/local/cargo/bin:$PATH
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
COPY scripts/build_browserskill.sh scripts/browserskill-release.json ./scripts/
COPY patches/browserskill ./patches/browserskill
ARG TARGETOS
@ -92,7 +94,7 @@ ARG APK_MIRROR_ARG
# Pairing derives the gateway URL from the user's page origin by default.
ENV BROWSERSKILL_BINARY=/opt/weknora/browserskill/bsk \
BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.2.1.zip
BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.3.0.zip
COPY --from=browserskill /opt/weknora/browserskill /opt/weknora/browserskill
# Create a non-root user first

View File

@ -1,22 +1,28 @@
# BrowserSkill 本机浏览器接入
WeKnora 使用 Tencent/BrowserSkill 的官方 daemon 和扩展执行浏览器操作,通过 `local_browser` 薄工具适配接入,无需沙箱、浏览器技能包或用户运行本机命令。
WeKnora 使用 Tencent/BrowserSkill 的官方 daemon 和基于官方源码的配套扩展执行浏览器操作,通过 `local_browser` 薄工具适配接入,无需沙箱、浏览器技能包或用户运行本机命令。
## 使用流程
1. Docker 部署使用包含 BrowserSkill 的 app 和 frontend 镜像,默认从用户当前页面生成连接地址。原生部署需先运行 `./scripts/build_browserskill.sh`,配置下面的两个文件路径并重启服务。
2. 用户在个人设置 → 浏览器连接下载配套扩展,解压后在 Chrome 扩展程序页面加载。当前没有商店发布版本。
3. 在设置页复制一次性配对链接,粘贴到扩展的「远程连接」,核对服务器并连接。同一空间内多个对话共用设备授权。
4. 回到对话描述浏览器任务。首次工具调用默认打开独立任务窗口,后续仅切换该窗口内的任务标签。可在扩展中改用后台标签组,此时在现有 Chrome 窗口创建绿色「WeKnora」标签组,模型切换目标标签不会切走用户正在看的页面。
5. 主对话小预览可按住标题栏上下、左右拖动,也可定位任务标签、暂停操作、继续操作或结束浏览器任务。暂停中断当前浏览器调用并保留页面,结束会关闭任务新建标签、归还借用标签;这些按钮只控制当前对话的浏览器,不会停止整段对话或撤销浏览器配对。请求人工帮助时先显示提示;不会自动激活标签或窗口。借用已有标签必须经过原生确认,归还时解除控制,保留原位置。
2. 用户在个人设置 → 浏览器连接下载配套扩展,解压后在 Chrome 扩展程序页面加载。WeKnora 配套扩展通过此 ZIP 分发,官方原版扩展不包含全部任务控制接口。
3. 在设置页复制一次性配对链接,打开扩展「连接设置」,选择「远程连接」,粘贴链接并保存。同一空间内多个对话共用设备授权。
4. 回到对话描述浏览器任务。首次工具调用打开独立 Agent Window(请求不抢前台焦点),后续在该窗口中操作明确授权的标签。扩展不再提供后台标签组模式。
5. 主对话小预览可按住标题栏上下、左右拖动,也可定位任务标签、暂停操作、继续操作或结束浏览器任务。暂停中断当前浏览器调用并保留页面,结束会关闭任务新建标签、归还借用标签;这些按钮只控制当前对话的浏览器,不会停止整段对话或撤销浏览器配对。人工帮助和标签借用沿用官方交互,可能聚焦任务窗口或展示确认;借用标签会移入任务窗口,归还时恢复原位置。
浏览器操作期间,从当前任务页通过新窗口链接(包括 `rel=noopener`)或 `window.open` 打开的标签,会按来源登记到当前任务,移入任务窗口或标签组,并在结束时一起回收。后台标签组模式下,若 Chrome 默认激活新标签,扩展会恢复此前查看的标签;浏览器原生激活可能带来短暂切换。任务空闲时手动新建或拖入标签组的页面不会自动获得任务归属。
自动化操作期间,从已授权页面通过 `target="_blank"`、`window.open` 等直接打开的新标签,只有 Chrome 导航事件能确认来源时才归当前任务管理,支持继续读取、切换、关闭及任务结束时清理。手动新建、拖入或无法确认来源的标签仍需借用确认;`tab_borrow` 可以在当前任务窗口内完成授权,无需先拖到普通窗口。拒绝借用后不能反复尝试读取或关闭;借用页面通过 `tab_return` 归还并保留。
授权只覆盖任务创建的标签和用户明确批准借用的标签;标签组仅提供视觉标识,不作为权限依据。即使用户把其他标签拖入组内,模型也不会获得其控制权。结束任务只清理任务创建的标签,不关闭共用窗口及其他对话的标签。上游的本机 daemon 连接模式仍使用原有独立窗口。
`tab_list` 中 `scope: user` 的页面不属于当前任务,必须先借用成功再选择、读取或请求人工协助。普通网站查询优先在任务页打开,同一 Chrome 的登录 Cookie 可复用。借用确认默认等待五分钟,小窗提示到目标网页点击允许;确认超时后需先恢复任务,再重新发起一次借用,恢复本身不授予标签权限。
模型通过 `tab_close` 关闭任务最后一页时,扩展会临时保留一个归当前任务所有的空白标签,随后由任务结束流程统一回收。这样不会把 Chrome 随之关闭窗口误判为人工中断;用户主动关闭任务窗口仍会暂停任务,需显式继续。
授权只覆盖任务显式创建或借用的标签;窗口归属不作为授权依据。手动移入任务窗口的页面仍不可读取或操作。结束或断线清理会归还借用标签、关闭任务创建的标签,并保留用户页面。
## 人工参与与恢复
遇到登录、短信验证码、验证码挑战或授权时,Agent 应调用 `request_help`,说明需要用户完成的步骤。对话小预览显示具体提示,点击预览定位浏览器,完成操作后在浏览器帮助提示中确认完成;原工具调用收到完成结果后,Agent 重新观察页面再继续。人工帮助默认等待 5 分钟,上限也是 5 分钟;Agent、网关 RPC 和跨节点转发为结果返回预留额外时间。
遇到登录、短信验证码、验证码挑战或授权时,Agent 应调用 `request_help`,说明需要用户完成的步骤。对话小预览显示具体提示,小窗自动展开并突出操作说明和定位按钮,长提示可滚动;点击定位按钮或预览进入浏览器,完成操作后在浏览器帮助提示中确认完成;原工具调用收到完成结果后,Agent 重新观察页面再继续。人工步骤只由用户在浏览器帮助提示中明确确认结束;不向模型暴露自动完成条件,网关也移除旧调用中的 `completion_criteria`,避免页面已有文字提前触发完成。帮助调用成功不代表登录成功,Agent 必须重新观察验证,仍未完成时再次请求人工协助。人工帮助默认等待 5 分钟,上限也是 5 分钟;Agent、网关 RPC 和跨节点转发为结果返回预留额外时间。
人工接管必须由工具调用触发。模型仅回复「请登录后告诉我」不会显示接管提示,也不会自动保留任务页面。系统级浏览器指引和工具说明要求先打开登录页,再调用 `request_help`;登录完成后继续原任务。排查「没有提示」时,先确认执行记录是否实际调用了该方法;如果返回 `disabled`,再检查扩展的人工帮助开关。提示词修改需要重新部署后端才会用于后续模型请求。
取消或超时会保留页面并暂停任务。浏览器窗口里的“中断”和对话预览里的“暂停”都由网关管理暂停状态,并取消正在执行的调用。点击预览“继续操作”后可在同一对话、同一浏览器任务中继续;如果 Agent 已结束本轮,再发送继续指令。恢复前重新读取页面,不自动重放中断的点击或提交。已连接但暂停时无需重新配对;只有设备连接确实断开时才提示等待重连。
@ -28,15 +34,15 @@ WeKnora 使用 Tencent/BrowserSkill 的官方 daemon 和扩展执行浏览器操
后台任务标签在调试连接期间启用 CDP `Emulation.setFocusEmulationEnabled`,让页面的可见性/焦点与绘制回调继续工作,不激活 Chrome 标签或窗口。仅任务新建或明确借用的标签启用此行为,释放调试连接时由 Chrome 恢复。否则依赖 `requestAnimationFrame` 或可见性事件加载内容的页面可能停在 Loading,直到用户切到该标签。
扩展对截图命令设置 3 秒等待上限,对 DOM 快照、无障碍树等读取命令设置 10 秒上限;读取超时立即终止本次快照,不继续走同一页面的回退读取。错误保留具体 CDP 命令,扩展后台控制台记录超过 2 秒的命令及耗时。此保护不等于取消已经交给 Chrome 的命令,也不自动重放点击或提交。截图超时后仍保留在途标记,直到 Chrome 实际返回或调试连接释放;期间预览不再发送重复截图。框架自动附加配置按调试会话复用,断开后重建,失败后可重试。
扩展对截图命令设置 3 秒等待上限,对 DOM 快照、无障碍树等读取命令设置 10 秒上限;读取超时会终止对应采集路径,避免同一页面继续走回退读取。错误保留具体 CDP 命令,扩展后台控制台记录超过 2 秒的命令及耗时。此保护不等于取消已经交给 Chrome 的命令,也不自动重放点击或提交。截图超时后仍保留在途标记,直到 Chrome 实际返回或调试连接释放;期间预览不再发送重复截图。框架自动附加配置按调试会话复用,断开后重建,失败后可重试。
上述上限针对单条 CDP 命令,并非整个 `observe`。复杂页面还要在扩展中进行语义树转换和文本渲染;重复操作按钮的上下文收集复用已扫描的兄弟节点前缀,避免逐按钮重复扫描整个列表。缓存仅存在于本次渲染,按作用域、目标名称和已有上下文隔离,每个父节点最多保留 64 种缓存项。慢观察会以 `[bsk observe] slow observation completed` 输出总耗时和分阶段耗时(不含页面内容);CDP 超过 2 秒时的提示是等待中告警,`slow command settled` 记录 Chrome 实际返回的耗时,`outcome` 区分返回和失败,`late: true` 表示扩展已经超时但 Chrome 此时才完成;本地超时单独记录为 `command failed`。
上述上限针对单条 CDP 命令,并非整个 `observe`。复杂页面还要在扩展中进行语义树转换和文本渲染;重复操作按钮的上下文收集复用已扫描的兄弟节点前缀,避免逐按钮重复扫描整个列表。缓存仅存在于本次渲染,按作用域、目标名称和已有上下文隔离,每个父节点最多保留 64 种缓存项。CDP 等待超过 2 秒时记录方法与耗时,不记录页面内容。
本轮 Agent 执行结束时,通过工具清理钩子释放当前任务的 Chrome 调试连接。成功完成的普通查询默认关闭任务创建的页面并归还借用标签,避免每轮留下任务分组;输入框的本机浏览器选择偏好仍保留。调用时可设置顶层 `keep_open: true`,为用户要求保留的页面、交付结果或未完成的人工步骤保留整项任务;该标记仅对本轮有效。`request_help` 自动保留任务,人工步骤完成后可通过后续调用的 `keep_open: false` 恢复自动回收。报错、取消、暂停的任务保留现场,不自动关闭。扩展先阻止新截图,再等待在途截图和操作完成,最后释放连接;结束任务也使用同一截图屏障。空闲时服务端只返回缓存画面,卡片显示「已保留最后画面」,不重复截图,下一次浏览器调用恢复连接。Chrome 提示条的消失可能晚于连接释放;同一扩展有其他活动任务时,提示仍可能保留。
本轮 Agent 执行结束时,通过工具清理钩子释放当前任务的 Chrome 调试连接。成功完成的普通查询默认关闭任务创建的页面并归还借用标签,避免每轮留下任务窗口;输入框的本机浏览器选择偏好仍保留。调用时可设置顶层 `keep_open: true`,为用户要求保留的页面、交付结果或未完成的人工步骤保留整项任务;该标记仅对本轮有效。`request_help` 自动保留任务,人工步骤完成后可通过后续调用的 `keep_open: false` 恢复自动回收。报错、取消、暂停的任务保留现场,不自动关闭。扩展先阻止新截图,再等待在途截图和操作完成,最后释放连接;结束任务也使用同一截图屏障。空闲时服务端只返回缓存画面,卡片显示「已保留最后画面」,不重复截图,下一次浏览器调用恢复连接。Chrome 提示条的消失可能晚于连接释放;同一扩展有其他活动任务时,提示仍可能保留。
导航默认等待 `domcontentloaded`,避免已经可读的页面被慢图片等资源拖住;需要完整加载或网络空闲时可显式指定 `wait_until: "load"` 或 `"networkidle"`。文档就绪不代表异步应用内容已加载,操作前仍需观察目标内容是否出现。
导航返回 `reached: "timeout"` 时,即使 RPC 成功返回,也会标记该次操作未完成并保留任务现场。模型应先重新观察页面,再决定下一步,不能因等待超时自动重放导航。用户点击“结束任务”时会先阻止后续命令、取消正在执行的操作(包括创建任务),再清理任务标签;归还标签失败或清理超时会保留暂停状态,可再次点击结束重试。
页面显示错误内容和导航生命周期超时是两种不同状态:HTTP 错误页加载完成后仍可正常观察;已显示内容也可能仍在等待文档加载事件。扩展跟随主框架已提交的跳转文档,忽略旧文档及子框架事件,避免一直等跳转前文档的完成事件。daemon 为导航结果额外预留 2 秒传输时间,避免与扩展的同期限等待竞争,导致普通导航等待超时被升级为 RPC 中断。导航返回 `reached: "timeout"` 时,即使 RPC 成功返回,也会标记该次操作未完成并保留任务现场。模型应先重新观察页面,再决定下一步,不能因等待超时自动重放导航。用户点击“结束任务”时会先阻止后续命令、取消正在执行的操作(包括创建任务),再清理任务标签;归还标签失败或清理超时会保留暂停状态,可再次点击结束重试。
模型可调用 `{"method":"screenshot"}` 截取当前视口,或使用最近观察中的元素引用,例如 `{"method":"screenshot","ref":"e3"}` 截取元素区域;可选 `tab_id` 限定到任务内标签。截图通过独立图片内容传给支持视觉的对话模型;非视觉模型使用已配置的图片描述模型,未配置或描述失败时明确告知模型无法查看图片。Base64 不进入工具文本,结果卡片和历史消息保留截图。预览的小尺寸 JPEG 仅用于用户查看,与模型截图分开。
@ -46,13 +52,13 @@ WeKnora 使用 Tencent/BrowserSkill 的官方 daemon 和扩展执行浏览器操
模型调用采用扁平参数,例如 `{"method":"navigate","url":"https://example.com"}`、`{"method":"click","ref":"e3"}`、`{"method":"observe"}`。Schema 不再提供 `params` 字段,旧的嵌套格式直接拒绝。服务端校验所选动作的必填字段、字段类型及定位条件,再将参数转换为 BrowserSkill 原生 RPC 信封;会话和设备 ID 始终由服务端绑定。
`wait_ms` 的外层参数为 `duration_ms`,范围 0–10000 毫秒;工具描述、参数 schema 和执行前校验保持一致。命令超时或中断后暂停任务,不自动重放点击/提交。前端显示具体浏览器动作与可读错误,结果卡片分别展示网页内容、截图或标签列表,不展示原始协议 JSON。标签组统一显示 WeKnora,不再附带内部任务 ID。
`wait_ms` 的外层参数为 `duration_ms`,范围 0–10000 毫秒;工具描述、参数 schema 和执行前校验保持一致。命令超时或中断后暂停任务,不自动重放点击/提交。前端显示具体浏览器动作与可读错误,结果卡片分别展示网页内容、截图或标签列表,不展示原始协议 JSON。任务窗口沿用官方实现,标签归属及窗口内借用由配套补丁补充。
## 构建与部署
固定源码提交 `5aaa36bf79a201ec40b277ce6c24f2ce23ce37ca`、官方 daemon v0.2.1、协议 v1.1。构建脚本应用 `patches/browserskill/remote-extension-connection.patch`,以冻结依赖构建扩展,并验证 daemon 下载包 SHA-256。产物位于 `artifacts/browserskill/`,不提交二进制。
扩展和 daemon 均从官方 `ext-v0.3.0` 对应提交 `75e2c64abaf4b7cc75682d94b0c1fd5db0cbd5e5` 构建(协议 v1.3),固定于 `scripts/browserskill-release.json`。官方 CLI v0.2.1 二进制缺少 `scroll_to`、`wheel`、`focus`、`blur`,不能与当前工具集合搭配使用。构建按文件名顺序应用 `patches/browserskill/*.patch`,使用冻结的 pnpm 依赖和 Cargo.lock;本机构建需 Rust/Cargo、C 编译器,Linux 还需 CMake。可设置 `CARGO_TARGET_DIR` 复用编译缓存;Docker 构建阶段在目标架构运行,原生脚本不静默生成其他架构的二进制。详见 `patches/browserskill/README.md`。产物位于 `artifacts/browserskill/`,不提交二进制。
后台页面绘制和读取超时的修复位于扩展中。更新服务端后,已有用户仍需下载新的配套 ZIP,覆盖原解压目录并在 Chrome 扩展程序页面重新加载;仅重启服务端不会更新已安装的扩展。
已有用户需下载 0.3.0 配套 ZIP,覆盖原解压目录并在 Chrome 扩展程序页面重新加载;仅重启服务端不会更新扩展。保持原扩展 ID 时,上游会将旧的本地凭据迁移到扩展源 IndexedDB;重新安装导致 ID 改变时需要重新配对。
### Docker 部署
@ -76,14 +82,14 @@ BROWSERSKILL_PUBLIC_URL=wss://weknora.example.com/api/v1/local-browser/extension
```dotenv
BROWSERSKILL_BINARY=/opt/weknora/browserskill/bsk
BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.2.1.zip
BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.3.0.zip
```
构建脚本第二个参数可指定目标平台,例如 `./scripts/build_browserskill.sh ./artifacts/browserskill-linux linux/amd64`;不传时按宿主机系统和架构下载。
本机调试可用 `ws://localhost:8080/api/v1/local-browser/extension`;远程部署要求 WSS,内网可使用受浏览器信任的企业 CA。详细授权、重连、多副本路由、迁移及容量边界见 [生产部署链路](browser-skill-production.md)。
扩展使用官方 MIT 许可,分发时保留 `BrowserSkill-LICENSE`。配对、UI 定位和预览属于本次提出的网关协议约定,并非已经发布的 BrowserSkill 稳定接口。
扩展使用官方 MIT 许可,分发时保留 `BrowserSkill-LICENSE`。配对授权遵循上游第三方网关协议;`gateway.task_preview`、`gateway.task_focus`、`gateway.task_idle` 仍是配套补丁接口。不要直接替换为官方 ZIP。遇到不支持的收尾接口时,已完成的普通任务可走原生停止;需要保留页面并释放控制的任务仍要求配套扩展。
## 验证
@ -100,10 +106,9 @@ BROWSERSKILL_TEST_EXTENSION=/absolute/path/to/unpacked-extension
BROWSERSKILL_TEST_CHROMIUM=/absolute/path/to/Chromium
BROWSERSKILL_TEST_PLAYWRIGHT=/absolute/path/to/playwright-core/index.mjs
BROWSERSKILL_TEST_HEADED=1
BROWSERSKILL_TEST_TASK_WINDOW=0 # 可选:通过扩展界面切换后台标签组;不设置时验证默认独立窗口
```
测试使用独立浏览器资料目录,覆盖配对、后台标签组、导航/输入/点击、目标标签截图、人工等待期间预览、显式定位、暂停/继续/结束、任务隔离、授权持久化和双节点路由。目标部署网络、真实模型任务与规模容量仍须现场验收;本机浏览器不保证免除网站验证或 403。
测试使用独立浏览器资料目录,覆盖配对、独立窗口、任务弹窗完整操作、窗口内借用确认与权限释放、导航/输入/点击、目标标签截图、人工等待期间预览、显式定位、暂停/继续/结束、任务隔离、授权持久化和双节点路由。目标部署网络、真实模型任务与规模容量仍须现场验收;本机浏览器不保证免除网站验证或 403。
补丁中的 `task-focus.browser.test.ts` 使用独立 Chrome 与原生 CDP 验证后台绘制、内容读取、截图和释放后的可见性恢复,避免 Playwright 默认的焦点模拟掩盖问题。在应用补丁后的 BrowserSkill 源码中,设置 `BSK_GEOMETRY_CHROME` 为测试 Chrome 路径,再执行 `pnpm --filter @browser-skill/extension exec vitest run src/browser-driver/__tests__/task-focus.browser.test.ts`(Node 20 另需 `NODE_OPTIONS=--experimental-websocket`)。
@ -119,14 +124,12 @@ node frontend/scripts/verify-browser-preview-pip.mjs
### 输入框选择本机浏览器
扩展弹窗中的“任务打开方式”提供“独立窗口(默认,保持可见)”和“后台标签组”。未保存偏好时默认使用独立窗口,已主动选择后台标签组的用户保持原设置。设置保存在本机扩展中,仅对新浏览器任务生效;已有任务需要先结束,或使用新对话。独立窗口不额外创建 Chrome 标签组,开始时会打开到前台,后续创建、选择任务标签只在该窗口内切换;请手动与聊天窗口并排放置。完全遮挡或最小化仍可能导致读取变慢,因此此模式不是不可见后台运行的性能保证。结束任务只清理明确归属于任务的标签,用户后来移入窗口的页面会保留。
任务统一使用上游独立 Agent Window;旧的“后台标签组”设置不再生效。升级前结束已有任务。后台绘制保护只作用于明确授权的标签;完全遮挡或最小化时仍需按目标站点验收性能。
Agent 模式的输入框提供“本机浏览器”开关,可与联网搜索同时开启。选中后,请求携带 `local_browser_enabled: true`;本轮提示词明确要求使用 `local_browser` 完成适用的网页查询与操作,而不是把设备已配对当作使用意图。知识库、MCP、Skill、Shell 等工具仍按智能体配置和本轮选择正常提供,可以配合检索、处理内容及生成文件。联网搜索与浏览器同时开启时,可以先搜索发现链接,再用浏览器读取和操作网页。
浏览器不可用时必须说明原因,不能隐瞒失败或声称已通过浏览器读取。该选择不缩减工具注册范围,实际调用由模型遵循提示词和用户任务安排。选择状态随会话最近一次输入设置恢复,切换智能体会清除;关闭浏览器选择不会改变其他开关。此功能需要使用 Agent 接口,普通问答接口拒绝该字段为 true 的请求。
### 标签组回收
### 旧标签组清理
后台标签组模式在结束任务时,先将明确归属于任务的标签移出分组,再关闭这些标签;不会按名称清理所有 WeKnora 分组,也不会移出用户后来加入的标签。取消分组失败时保留任务供重试,不报告清理成功。独立窗口模式不创建标签组。旧版本已经保存且关闭的历史分组不会追溯删除,需要用户在 Chrome 中选择“删除分组”;关闭书签栏显示仅隐藏入口,不等于删除。
Chrome 公开扩展 API 不提供直接删除历史已保存分组的接口。移出分组再关闭利用的是本地分组成员变更路径,参见 [Chromium LocalTabGroupListener](https://chromium.googlesource.com/chromium/src/+/f4e2f70d6dd6d88f0ccb887c1935f0cba9fb802f/chrome/browser/ui/tabs/saved_tab_groups/local_tab_group_listener.cc)。跨设备同步和用户已有历史分组仍需真实 Chrome 验收。
新版不创建标签组。旧版遗留的已保存分组不会自动删除,需要用户在 Chrome 中手动删除。

View File

@ -32,7 +32,7 @@ sequenceDiagram
- 配对链接仅供激活,5 分钟有效。生成新链接不会断开现有设备,成功激活新设备后才替换旧授权。
- 当前每个「空间+用户」保留一个设备授权;更换浏览器会替换旧设备。多个对话共用授权,各自创建任务窗口。
- 扩展生成 256 位随机设备令牌,仅放在可信扩展上下文的本地存储;服务器保存 SHA-256 哈希。设备令牌有效期 90 天,30 天后自动轮换。
- 扩展生成 256 位随机设备令牌,仅放在扩展源 IndexedDB;服务器保存 SHA-256 哈希。设备令牌有效期 90 天,30 天后自动轮换。
- 轮换前扩展先保存候选令牌;响应丢失时使用同一候选重试,不会因客户端或服务器重启丢失新凭据。旧令牌提供 5 分钟连接宽限。相同设备的令牌轮换不重启活动的浏览器任务。
- 首次激活响应丢失时,重新生成配对链接激活即可;一次性配对凭据不能再次创建授权。
- 设备撤销、用户停用、成员资格暂停/移除都会阻止后续调用。活动连接在下一次授权检查时关闭;在途操作的取消不能撤销网页上已经发生的动作。
@ -60,17 +60,17 @@ flowchart LR
设备自动重连与任务继续是两回事。开始原生任务前先写入持久化中断标记;连接或进程丢失后,旧任务一律显示暂停。用户点击对话小预览中的「继续任务」后才允许新调用。恢复后需重新观察页面,不能自动重放原来的点击、付款、发送或提交。
任务标签由 BrowserSkill 管理,断线清理会关闭任务创建的标签并解除借用标签的控制,共用窗口保持打开。当前不承诺恢复之前的页面、DOM 引用、窗口布局或在途命令结果。小预览的「定位到浏览器」仅定位已存在的任务标签,不启动任务、不恢复自动化。这个 UI 操作通过网关传给扩展,复用上游 SessionManager 查找标签;模型不具备该 UI 控制入口。
任务使用上游独立 Agent Window。断线清理会关闭任务创建的标签并归还借用标签,保留用户后来加入的页面。当前不承诺恢复之前的页面、DOM 引用、窗口布局或在途命令结果。小预览的「定位到浏览器」仅定位已存在的任务标签,不启动任务、不恢复自动化。这个 UI 操作通过网关传给扩展,复用上游 SessionManager 查找标签;模型不具备该 UI 控制入口。
## 配置
Docker app 镜像已内置匹配目标架构的官方 bsk、配套扩展和许可证,并预设两个文件路径;单实例默认无需额外环境变量,配对地址从用户当前页面的 origin 生成,保留外部域名和端口。`BROWSERSKILL_PUBLIC_URL` 仅作为独立网关域名/路径等特殊部署的优先覆盖项。原生部署各节点需自行安装产物。配置示例如下:
Docker app 镜像已内置匹配目标架构的配套 bsk、扩展和许可证,并预设两个文件路径;单实例默认无需额外环境变量,配对地址从用户当前页面的 origin 生成,保留外部域名和端口。`BROWSERSKILL_PUBLIC_URL` 仅作为独立网关域名/路径等特殊部署的优先覆盖项。原生部署各节点需自行安装产物。配置示例如下:
```dotenv
BROWSERSKILL_BINARY=/opt/weknora/browserskill/bsk
# 可选覆盖;省略时从页面自动生成。
# BROWSERSKILL_PUBLIC_URL=wss://weknora.example.com/api/v1/local-browser/extension
BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.2.1.zip
BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.3.0.zip
BROWSERSKILL_MAX_CONNECTIONS=32
```
@ -89,7 +89,7 @@ Kubernetes 可通过 Downward API 获取 Pod IP,再设置节点直连地址。
迁移:PostgreSQL `000093_browser_authorization`,SQLite `000014_browser_authorization`。默认自动迁移;若关闭 `AUTO_MIGRATE`,须先执行迁移。数据库只持久化授权/租约/中断标记,不存浏览器 Cookie 或截图。
扩展必须更新到本次配套构建;旧版把配对令牌直接用于 WSS 的方式不再接受。开发测试可下载 ZIP 后在 Chrome 扩展程序页面加载已解压目录。商店分发尚未发布。
扩展必须更新到 WeKnora 配套 0.3.0 构建。官方 0.3.0 原版缺少预览、定位和释放控制接口,不能直接替换配套 ZIP。升级前结束任务;在原解压目录覆盖文件后重新加载扩展,可沿用原扩展 ID 并迁移授权凭据。重新安装导致 ID 改变时重新配对。服务端必须同步升级 bsk:从与扩展相同的固定 0.3.0 源码构建,然后重启后端以释放旧 daemon。官方 CLI 0.2.1 不支持当前滚动等工具方法。
## 容量与验收

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View File

@ -59,6 +59,7 @@ export default {
"previewIdle": "Last preview retained",
"previewLive": "Preview syncing",
"previewLoading": "Fetching preview",
"borrowHint": "Switch to the page being borrowed and choose Allow or Deny in the BrowserSkill confirmation. Approval continues automatically. Continue operation only resumes a paused task; it does not approve borrowing.",
"helpHint": "Open the browser from the preview, complete the requested step, then confirm completion in the browser help overlay.",
"settingsTitle": "Browser connection",

View File

@ -59,6 +59,7 @@ export default {
"previewIdle": "最後の画面を保持しています",
"previewLive": "画面を同期中",
"previewLoading": "画面を取得中",
"borrowHint": "借用するページに切り替え、BrowserSkill の確認で許可または拒否を選択してください。許可後は自動で続行します。「操作を続行」は一時停止の解除のみで、借用の許可にはなりません。",
"helpHint": "確認または許可が必要です。プレビューをクリックして移動してください。",
"settingsTitle": "ブラウザー接続",

View File

@ -59,6 +59,7 @@ export default {
"previewIdle": "마지막 화면 유지 중",
"previewLive": "화면 동기화 중",
"previewLoading": "화면 가져오는 중",
"borrowHint": "사용하려는 페이지로 전환하여 BrowserSkill 확인 창에서 허용 또는 거부를 선택하세요. 허용하면 자동으로 계속됩니다. 작업 계속은 일시 중지만 해제하며 탭 사용을 승인하지 않습니다.",
"helpHint": "인증 또는 권한 승인이 필요합니다. 미리보기를 클릭하여 이동하세요.",
"settingsTitle": "브라우저 연결",

View File

@ -59,6 +59,7 @@ export default {
"previewIdle": "Сохранено последнее изображение",
"previewLive": "Изображение обновляется",
"previewLoading": "Получение изображения",
"borrowHint": "Перейдите на запрашиваемую вкладку и выберите «Разрешить» или «Отклонить» в окне BrowserSkill. После разрешения работа продолжится автоматически. Продолжение приостановленной задачи не даёт разрешения на доступ к вкладке.",
"helpHint": "Требуется проверка или разрешение. Нажмите предпросмотр для перехода.",
"settingsTitle": "Подключение браузера",

View File

@ -59,6 +59,7 @@ export default {
"previewIdle": "已保留最后画面",
"previewLive": "画面同步中",
"previewLoading": "正在获取画面",
"borrowHint": "请切换到要借用的网页,在 BrowserSkill 授权提示中选择「允许」或「拒绝」。授权通过后会自动继续;「继续操作」只恢复暂停的任务,不代替借用授权。",
"helpHint": "点击预览前往浏览器,完成上述步骤后,在浏览器帮助提示中确认完成。",
"settingsTitle": "浏览器连接",

View File

@ -0,0 +1,85 @@
// Run with BROWSERSKILL_TEST_CHROMIUM and BROWSERSKILL_TEST_PLAYWRIGHT.
import assert from 'node:assert/strict'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { createServer } from 'vite'
import vue from '@vitejs/plugin-vue'
const enabled = process.env.BROWSERSKILL_TEST_CHROMIUM && process.env.BROWSERSKILL_TEST_PLAYWRIGHT
test('human handoff expands, stays reachable on narrow screens, focuses the browser, and collapses after completion', { skip: !enabled }, async () => {
const root = fileURLToPath(new URL('../../../../', import.meta.url))
const server = await createServer({
root, cacheDir: root+'/node_modules/.vite-browser-preview-test', configFile: false, plugins: [vue(), {
name: 'preview-fixture',
enforce: 'pre',
transform(code, id) {
if (id.split('?')[0].endsWith('/BrowserTaskPreview.vue')) return code.replaceAll("'@/utils/request'", "'/fixture-api.js'")
},
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.url === '/fixture') {
res.setHeader('Content-Type', 'text/html')
res.end('<div id="app"></div><script type="module" src="/fixture-entry.js"></script>')
} else next()
})
},
resolveId(id) { if (id === '/fixture-api.js' || id === '/fixture-entry.js') return '\0'+id },
load(id) {
if (id === '\0/fixture-api.js') return `
export async function get() { return {data:{...window.fixtureStatus}} }
export async function post(_, {action}) {
window.fixtureActions.push(action);
return {data: action === 'preview' ? {image_base64:'',format:'jpeg'} : {...window.fixtureStatus}};
}`
if (id === '\0/fixture-entry.js') return `
import {createApp} from 'vue'; import {createPinia} from 'pinia';
import {createI18n} from 'vue-i18n'; import TDesign from 'tdesign-vue-next';
import 'tdesign-vue-next/es/style/index.css';
import Preview from '/src/views/chat/components/BrowserTaskPreview.vue';
import zh from '/src/i18n/locales/zh-CN.ts';
window.fixtureActions=[];
window.fixtureStatus={enabled:true,selected:true,connected:true,task_id:'fixture',needs_help:false};
createApp(Preview,{sessionId:'fixture'}).use(createPinia()).use(TDesign).use(createI18n({legacy:false,locale:'zh-CN',messages:{'zh-CN':zh}})).mount('#app');`
},
}], resolve: {alias: {'@': root+'/src'}}, server: {host:'127.0.0.1',port:0},
})
const { chromium } = await import(pathToFileURL(process.env.BROWSERSKILL_TEST_PLAYWRIGHT).href)
let browser
try {
await server.listen()
browser = await chromium.launch({executablePath:process.env.BROWSERSKILL_TEST_CHROMIUM,headless:true})
const page = await browser.newPage({viewport:{width:1100,height:800}})
page.on('pageerror', error => console.error(error.message))
page.on('console', message => { if (message.type() === 'error') console.error(message.text()) })
await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/fixture`)
const card = page.locator('.browser-task-preview')
await card.waitFor()
assert.equal(Math.round((await card.boundingBox()).width),240)
await page.evaluate(() => {
window.fixtureStatus.needs_help=true
window.fixtureStatus.help_prompt='请在浏览器中扫码登录,完成后确认。'.repeat(18)
})
await page.waitForSelector('.needs-help .preview-handoff')
assert.equal(Math.round((await card.boundingBox()).width),420)
const focus = page.locator('.preview-handoff button')
await focus.click()
assert.ok(await page.evaluate(() => window.fixtureActions.includes('focus')))
await page.setViewportSize({width:320,height:480})
await page.waitForTimeout(200)
const bounds = await card.boundingBox()
assert.ok(bounds.x >= 0 && bounds.x+bounds.width <= 320)
await focus.click()
const buttonBounds = await focus.boundingBox()
assert.ok(buttonBounds.y >= 0 && buttonBounds.y+buttonBounds.height <= 480)
if (process.env.BROWSERSKILL_TEST_PREVIEW_FILE) await page.screenshot({path:process.env.BROWSERSKILL_TEST_PREVIEW_FILE})
await page.evaluate(() => { window.fixtureStatus.action='tab_borrow'; window.fixtureStatus.help_prompt='' })
await page.waitForFunction(() => document.querySelector('.preview-handoff')?.textContent.includes('不代替借用授权'))
assert.equal(await page.locator('.preview-handoff button').count(),0)
assert.equal(await page.locator('.preview-image').count(),0,'do not focus the unrelated task blank tab during borrow confirmation')
await page.evaluate(() => { window.fixtureStatus.needs_help=false; window.fixtureStatus.help_prompt='' })
await page.waitForFunction(() => !document.querySelector('.needs-help'))
assert.equal(await page.locator('.preview-handoff').count(),0)
assert.equal(Math.round((await card.boundingBox()).width),200)
} finally { await browser?.close(); await server.close() }
})

View File

@ -1,10 +1,16 @@
<template>
<Teleport :to="pipTarget || 'body'" :disabled="!pipTarget">
<aside v-if="status.selected" ref="previewElement" class="browser-task-preview" :class="{ 'is-dragging': dragging, 'is-pip': !!pipTarget }" :style="pipTarget ? {} : positionStyle" :aria-label="t('localBrowser.preview')">
<aside v-if="status.selected" ref="previewElement" class="browser-task-preview" :class="{ 'is-dragging': dragging, 'is-pip': !!pipTarget, 'needs-help': status.needs_help }" :style="pipTarget ? {} : positionStyle" :aria-label="t('localBrowser.preview')">
<div class="preview-heading" @pointerdown="!pipTarget && startDrag($event)" @pointermove="moveDrag" @pointerup="stopDrag" @pointercancel="stopDrag" @lostpointercapture="stopDrag"><BrowserIcon class="preview-browser-icon" width="20" height="20" /><strong>{{ t('localBrowser.local') }}</strong><span>{{ t(!status.connected ? 'localBrowser.offline' : status.stopping ? 'localBrowser.stopping' : status.paused ? 'localBrowser.paused' : status.needs_help ? 'localBrowser.needHelp' : status.task_id ? 'localBrowser.connected' : 'localBrowser.waiting') }}</span>
<button v-if="pipSupported" class="preview-popout" :disabled="pipOpening" :title="t(pipTarget ? 'localBrowser.pipReturn' : 'localBrowser.pipOpen')" :aria-label="t(pipTarget ? 'localBrowser.pipReturn' : 'localBrowser.pipOpen')" @pointerdown.stop @click="togglePictureInPicture"><t-icon :name="pipTarget ? 'fullscreen-exit' : 'fullscreen'" size="16px" /></button>
</div>
<button class="preview-image" :disabled="!status.connected || !status.task_id || busy || status.stopping" :aria-label="t('localBrowser.locateWindow')" @click="act('focus')">
<section v-if="status.needs_help" class="preview-handoff" role="status" aria-live="polite">
<strong>{{ t('localBrowser.needHelp') }}</strong>
<p v-if="status.help_prompt" class="handoff-prompt">{{ status.help_prompt }}</p>
<p>{{ t(status.action === 'tab_borrow' ? 'localBrowser.borrowHint' : 'localBrowser.helpHint') }}</p>
<t-button v-if="status.action !== 'tab_borrow'" theme="primary" :disabled="!status.connected || !status.task_id || busy || status.stopping" @click="act('focus')"><t-icon name="jump" />{{ t('localBrowser.locateWindow') }}</t-button>
</section>
<button v-if="!(status.needs_help && status.action === 'tab_borrow')" class="preview-image" :disabled="!status.connected || !status.task_id || busy || status.stopping" :aria-label="t('localBrowser.locateWindow')" @click="act('focus')">
<img v-if="preview" :src="preview" :alt="t('localBrowser.preview')" />
<span v-else>{{ t(status.connected ? 'localBrowser.waiting' : 'localBrowser.reconnectShort') }}</span>
<span v-if="status.connected && status.task_id" class="locate"><t-icon name="jump" size="13px" />{{ t('localBrowser.locateWindow') }}</span>
@ -13,7 +19,6 @@
<p v-if="browserPageAddress(status.page_url)" class="preview-address">{{ browserPageAddress(status.page_url) }}</p>
<p v-if="status.last_error" class="preview-error">{{ status.last_error }}</p>
<p class="preview-sync" role="status">{{ t(!status.connected ? 'localBrowser.reconnectShort' : status.idle ? 'localBrowser.previewIdle' : previewStale ? 'localBrowser.previewStale' : preview ? 'localBrowser.previewLive' : 'localBrowser.previewLoading') }}</p>
<p v-if="status.needs_help" class="preview-help"><span v-if="status.help_prompt">{{ status.help_prompt }}<br /></span>{{ t('localBrowser.helpHint') }}</p>
<p v-if="pipFailed" class="preview-error" role="alert">{{ t('localBrowser.pipFailed') }}</p>
<p v-if="error" class="preview-error" role="alert">{{ error }}</p>
<p class="preview-scope">{{ t('localBrowser.controlScope') }}</p>
@ -117,4 +122,14 @@ onBeforeUnmount(() => { alive = false; document.removeEventListener('visibilityc
.browser-task-preview.is-pip { position: static; width: 100%; max-width: none; min-height: 100%; max-height: none; border: 0; border-radius: 0; box-shadow: none; }
.is-pip .preview-heading { cursor: default; }
.is-pip .preview-image { height: clamp(126px, 45vh, 480px); }
.browser-task-preview.needs-help { width: 420px; border-color: var(--td-brand-color); }
.preview-handoff { padding: 12px; background: var(--td-brand-color-light); overflow-wrap: anywhere; }
.preview-handoff strong { font-size: 14px; color: var(--td-brand-color); }
.preview-handoff p { font-size: 12px; line-height: 1.6; margin: 8px 0; white-space: pre-wrap; }
.preview-handoff .handoff-prompt { max-height: 22vh; overflow-y: auto; }
.preview-handoff .t-button { width: 100%; }
.needs-help .preview-image { height: clamp(140px, 30vh, 260px); }
.needs-help .preview-heading { flex-wrap: wrap; }
.browser-task-preview.is-pip.needs-help { width: 100%; }
@media(max-width:480px) { .browser-task-preview.needs-help { width: calc(100% - 24px); max-width: calc(100% - 24px); } .browser-task-preview.is-pip.needs-help { width: 100%; max-width: none; } }
</style>

View File

@ -18,6 +18,15 @@ Respect their configured permissions and the user's explicit source selections.
Do not enumerate MCP services or load a browser Skill just to open a website that
local_browser can access. Generic retrieval-first guidance must not skip the user's
explicit browser request.
When the requested work requires signing in, scanning a login QR code, an SMS code,
CAPTCHA, or account authorization, open the relevant page and call local_browser
with method="request_help", the observed tab_id, and a clear prompt for the manual
step. Do this before ending the turn or asking the user to report back after login.
The call displays the handoff UI and retains the task page while waiting; a chat
message alone does neither. Keep credentials in the user's browser. After a
continued/completed result, observe the page and continue the original task.
If help is disabled, cancelled, or times out, explain that outcome and the required
resume action; do not claim that a handoff is active. Respect an existing pause.
If the browser is unpaired, offline, paused, or fails, explain the specific issue and
how to restore access. Do not silently skip the requested browser step or claim to
have read a page without a successful browser observation. Distinguish any information

View File

@ -19,8 +19,8 @@ func browserDescription(instructions []string) string {
}
// The local_browser operating contract is maintained here, not in editable agent
// templates or the upstream CLI skill. Adapted from BrowserSkill 0.2.1's pinned
// skill/SKILL.md (5aaa36bf79a201ec40b277ce6c24f2ce23ce37ca).
// templates or the upstream CLI skill. Uses the paired CLI/extension 0.3.0
// source baseline, remote ownership contract and WeKnora task controls.
const browserToolDescription = `Control the user's connected Chrome through local_browser; no shell, installation or CLI
session commands are needed. Arguments are top-level beside method; sessions are server-managed.
@ -37,6 +37,9 @@ Workflow:
- Prefer refs for iframe/shadow-root targets; selectors search the main document. Use snapshot
or get_html for missing structure. Reserve evaluate for a specific gap and return bounded
serializable data. Follow the parameter descriptions and recovery hints in tool results.
- Use wheel with delta_y to scroll the viewport; scroll_to brings an observed ref or
selector into view. evaluate accepts a JavaScript expression/script; put return inside
an IIFE such as (() => { return document.title; })(), never at the top level.
- Action acknowledgement does not prove the intended effect; observe if ambiguous. Navigation
defaults to domcontentloaded, which does not guarantee application readiness. Inspect before
waiting. wait_for_navigation waits for navigation, not arbitrary content.
@ -45,10 +48,18 @@ Workflow:
Human control:
- Use request_help for human-only steps such as login, SMS codes, CAPTCHA or authorization.
First open the relevant login/challenge page, then call request_help with its observed
tab_id and a concrete prompt (e.g. scan the login QR code, then confirm in the overlay).
Issue this call before ending the turn with a request for manual login. Merely saying
"log in and tell me when done" does not show a handoff or retain the page.
Explain the exact manual step in prompt; it appears in the conversation preview. The user
locates the browser and confirms completion in the browser help overlay. Allow up to five
minutes (timeout_ms defaults to 300000 and is capped there). Resume only on
continued/completed, then observe; never attempt to solve a CAPTCHA yourself.
minutes (timeout_ms defaults to 300000 and is capped there). Completion requires
the user's explicit confirmation; automatic completion_criteria are not supported.
Resume only on continued/completed, then observe and verify the requested step actually
succeeded. A successful help RPC only acknowledges handoff completion, not login success.
If the login/challenge remains, call request_help again to let the user finish; never
claim login succeeded from generic page text or solve a CAPTCHA yourself.
Cancellation, disabled/timed-out help or a pause requires user intervention. Never bypass
a pause or challenge via another engine/tool. A connected but paused task is NOT offline:
ask the user to click Continue operation in the conversation preview, then continue in
@ -57,9 +68,22 @@ Human control:
with Chrome open; do not pair again. Users locate/resume tasks from the conversation preview.
Task tabs:
- The extension chooses a separate task window by default or a background tab group. Do not
activate the user's window yourself. List actual user tabs before borrowing; borrowing needs
extension confirmation. Return borrowed tabs when finished.
- Tasks use a separate Agent Window. For a website lookup, navigate in the current task;
Chrome shares the user's login cookies. Reuse an existing user tab only when its live
page state is needed or the user asked to use that tab. A previous conversation's tab
is not automatically controlled by this task, even if you originally created it.
- tab_list scope=user means not authorized for this task. Call tab_borrow before
tab_select, reading, request_help or other operations on such a tab. Listing a tab
does not authorize it. Follow extension confirmation and return borrowed tabs when done.
- New tabs opened directly by your action on a controlled page belong to this task when
the extension can verify their source. List tabs and use the returned tab_id to continue.
- If a tab is unauthorized, call tab_borrow once and let the extension request approval;
this also works inside the task window. Never ask the user to move it out merely to borrow.
During borrowing, the user must approve in the target page's BrowserSkill confirmation.
A denied or timed-out borrow requires user intervention, not repeated select/read/close
or request_help attempts. Continue operation only resumes a paused task; it does not
approve borrowing. After explicit resume, a fresh borrow still needs browser approval.
Return borrowed tabs instead of closing them. Window membership alone grants no access.
- Successful turns close created tabs and return borrowed tabs. keep_open:true retains the
task for a requested open page, deliverable or unfinished form. request_help retains it
automatically; clear keep_open after resolution if unnecessary. Retention applies per turn.

View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/browserskill"
"github.com/Tencent/WeKnora/internal/types"
@ -28,6 +29,22 @@ func browserRecoveryHint(method string, err *browserskill.RPCError) string {
Effect string `json:"effect_state"`
}
_ = json.Unmarshal(err.Data, &data)
if method == "tab_borrow" && (data.Reason == "confirmation_timeout" ||
err.Code == "timeout" || err.Code == "cancelled" || err.Code == "user_aborted") {
return "Stop browser actions: tab borrowing was not approved. The confirmation is no longer pending. " +
"Ask the user to click Continue operation in the conversation preview " +
"before continuing in this same conversation. " +
"Continue operation only resumes the task; it does not grant tab access. After explicit resume, " +
"request tab_borrow once again and wait for Allow in the target page's BrowserSkill confirmation. " +
"Do not call request_help on the unapproved tab or reconnect/pair again."
}
if err.Code == "permission_denied" && (strings.Contains(err.Message, "borrow this tab before") ||
strings.Contains(err.Message, "Authorize this tab with tab_borrow")) {
return "This tab is not authorized for the current task. If its existing page state is needed, " +
"call tab_borrow once and wait for the user's approval in the target page. " +
"Do not retry tab_select/read/close or call request_help before borrowing succeeds. " +
"For an ordinary website lookup that does not need this tab's state, navigate in the task's own tab."
}
if err.Code == "user_aborted" || err.Code == "cancelled" || err.Code == "task_paused" || err.Code == "timeout" {
return "Stop browser actions. Ask the user to complete any manual step and click Continue operation " +
"in the conversation browser preview, then continue in the same conversation. " +
@ -112,6 +129,17 @@ func (t *BrowserSkillTool) interpretResult(method string, raw json.RawMessage) *
}
result.Error = "Browser evaluate failed or returned an invalid result. Inspect ok/error; " +
"return bounded serializable data, not DOM nodes. Observe before retrying."
var detail struct {
Error struct {
Text string `json:"text"`
} `json:"error"`
}
if json.Unmarshal(raw, &detail) == nil && strings.Contains(detail.Error.Text, "Illegal return statement") {
result.Error = "evaluate received a top-level return. Use an expression or an IIFE, " +
"for example (() => { return document.title; })(). " +
"Correct the syntax and inspect page state before repeating mutations. " +
"For scrolling, use wheel with delta_y or scroll_to with an observed ref."
}
} else {
if err == nil && (envelope.Outcome == "continued" || envelope.Outcome == "completed") {
return result

View File

@ -131,3 +131,35 @@ func TestNavigationTimeoutRetainsTask(t *testing.T) {
require.False(t, result.Success, "navigation that did not reach requested phase must not count as completed")
require.Equal(t, []bool{true}, manager.retained, "unfinished navigation should retain pages")
}
func TestEvaluateTopLevelReturnRecovery(t *testing.T) {
tool := NewBrowserSkillTool(nil, browserskill.Scope{}, "chat")
raw := json.RawMessage(`{"ok":false,"error":{"text":"SyntaxError: Illegal return statement"}}`)
result := tool.interpretResult("evaluate", raw)
require.False(t, result.Success)
require.Contains(t, result.Error, "IIFE")
require.Contains(t, result.Error, "before repeating mutations")
require.JSONEq(t, string(raw), result.Output)
}
func TestBorrowRecoveryDoesNotConfuseResumeWithApproval(t *testing.T) {
for _, message := range []string{
"tab_select: borrow this tab before controlling it remotely",
"Authorize this tab with tab_borrow before reading or operating it",
} {
hint := browserRecoveryHint("tab_select", &browserskill.RPCError{Code: "permission_denied", Message: message})
require.Contains(t, hint, "call tab_borrow once")
require.Contains(t, hint, "before borrowing succeeds")
}
hint := browserRecoveryHint("tab_borrow", &browserskill.RPCError{
Code: "timeout", Message: "Timed out waiting for tab borrow confirmation",
Data: json.RawMessage(`{"reason":"confirmation_timeout"}`),
})
require.Contains(t, hint, "confirmation is no longer pending")
require.Contains(t, hint, "does not grant tab access")
require.Contains(t, hint, "After explicit resume")
require.Contains(t, hint, "Do not call request_help")
// Unrelated permission denials must not suggest a way to borrow around them.
hint = browserRecoveryHint("click", &browserskill.RPCError{Code: "permission_denied", Message: "policy denied"})
require.NotContains(t, hint, "call tab_borrow")
}

View File

@ -11,8 +11,8 @@ import (
"github.com/santhosh-tekuri/jsonschema/v6"
)
// Flat argument fields follow BrowserSkill 0.2.1, source revision
// 5aaa36bf79a201ec40b277ce6c24f2ce23ce37ca. Session identity is server-owned.
// Flat argument fields use the paired CLI/extension 0.3.0 source baseline.
// Session identity is server-owned.
// Method-specific requirements are also described to the model on each field.
const browserToolParameters = `{
"type": "object",
@ -200,8 +200,11 @@ const browserToolParameters = `{
"expression": {
"type": "string",
"minLength": 1,
"description": "Required for evaluate. Use only for a specific gap after observation; ` +
`return bounded JSON-serializable values, not DOM nodes. Inspect result ok/error."
"description": "Required for evaluate: JavaScript evaluated as a script, not a function body. ` +
`Use an expression such as document.title, or wrap statements and return in an IIFE: ` +
`(() => { return document.title; })(). A top-level return is a syntax error. ` +
`Use only for a specific gap after observation; return bounded JSON-serializable values, ` +
`not DOM nodes. Inspect result ok/error."
},
"return_by_value": {
"type": "boolean"
@ -317,68 +320,6 @@ const browserToolParameters = `{
},
"description": "For emulate: required unless off is true."
},
"completion_criteria": {
"type": "object",
"properties": {
"all": {
"type": "array",
"items": {
"type": "object",
"properties": {
"selector_exists": {
"type": "string"
},
"selector_missing": {
"type": "string"
},
"text_exists": {
"type": "string"
},
"text_missing": {
"type": "string"
},
"url_contains": {
"type": "string"
},
"url_matches": {
"type": "string"
}
}
}
},
"any": {
"type": "array",
"items": {
"type": "object",
"properties": {
"selector_exists": {
"type": "string"
},
"selector_missing": {
"type": "string"
},
"text_exists": {
"type": "string"
},
"text_missing": {
"type": "string"
},
"url_contains": {
"type": "string"
},
"url_matches": {
"type": "string"
}
}
}
},
"stable_for_ms": {
"type": "integer",
"minimum": 0.0
}
},
"description": "For request_help: optional detector for when the user has completed the step."
},
"prompt": {
"type": "string",
"minLength": 1,
@ -529,7 +470,7 @@ var browserArgumentRules = map[string]browserArgumentRule{
required: []string{},
},
"request_help": {
fields: []string{"completion_criteria", "prompt", "tab_id", "targets", "timeout_ms", "title"},
fields: []string{"prompt", "tab_id", "targets", "timeout_ms", "title"},
required: []string{"prompt"},
},
}

View File

@ -17,6 +17,7 @@ func TestBrowserFlatSchemaCoversEveryMethod(t *testing.T) {
require.NoError(t, json.Unmarshal(tool.Parameters(), &schema))
require.NotContains(t, schema.Properties, "params")
require.NotContains(t, schema.Properties, "session_id")
require.NotContains(t, schema.Properties, "completion_criteria")
require.Equal(t, []string{"method"}, schema.Required)
var method struct {
Enum []string `json:"enum"`
@ -76,6 +77,7 @@ func TestBrowserFlatArgumentsRejectBeforeDispatch(t *testing.T) {
`{"method":"window_resize","width":800}`, `{"method":"window_resize","width":1,"height":600}`,
`{"method":"emulate"}`, `{"method":"emulate","off":true,"overrides":{"width":800}}`,
`{"method":"emulate","overrides":"{}"}`, `{"method":"request_help","prompt":null}`,
`{"method":"request_help","prompt":"Sign in","completion_criteria":{"any":[{"text_exists":"看过"}]}}`,
} {
t.Run(raw, func(t *testing.T) { require.Error(t, tool.ValidateArguments(json.RawMessage(raw))) })
}

View File

@ -43,7 +43,7 @@ func validToken(token string) bool {
}
// AuthorizeHTTP is extension-only, independent of browser cookies. Device
// tokens stay in chrome.storage.local; only hashes are committed to the DB.
// tokens stay in extension-origin storage; only hashes are committed to the DB.
func (m *Manager) AuthorizeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
if !m.Enabled() || m.store == nil {

View File

@ -58,3 +58,68 @@ func TestRPCErrorBoundsLargeDetails(t *testing.T) {
rpcErr.BoundDetails()
require.JSONEq(t, `{"reason":"fill_failed","effect_state":"unknown","truncated":true}`, string(rpcErr.Data))
}
// Exercise the actual daemon parser, rather than assuming that a successful
// handshake means every advertised extension tool is supported by the binary.
func TestNativeDaemonSupportsAdvertisedMethods(t *testing.T) {
binary := os.Getenv("BROWSERSKILL_TEST_BINARY")
if binary == "" {
t.Skip("set BROWSERSKILL_TEST_BINARY for native protocol coverage")
}
m := NewManager()
m.binary = binary
runtime, err := m.start(t.Context())
require.NoError(t, err)
t.Cleanup(runtime.stop)
for method := range methods {
t.Run(method, func(t *testing.T) {
_, err := rpc(t.Context(), &device{runtime: runtime}, "tool."+method,
map[string]any{"session_id": "missing-protocol-test-session"})
if err == nil {
return
}
var rpcErr *RPCError
require.ErrorAs(t, err, &rpcErr)
require.NotEqual(t, "daemon_incompatible", rpcErr.Code)
require.NotEqual(t, "protocol_error", rpcErr.Code)
})
}
}
func TestRPCRejectsUnsupportedMethodAndMismatchedResponse(t *testing.T) {
for _, tc := range []struct{ id, code, want string }{
{"0", "protocol_error", "daemon_incompatible"},
{"other", "protocol_error", "invalid BrowserSkill response ID"},
{"0", "permission_denied", "invalid BrowserSkill response ID"},
} {
t.Run(tc.id+tc.code, func(t *testing.T) {
home, err := os.MkdirTemp("", "bsk-wire-")
require.NoError(t, err)
t.Cleanup(func() { _ = os.RemoveAll(home) })
require.NoError(t, os.Mkdir(filepath.Join(home, "run"), 0o700))
listener, err := net.Listen("unix", filepath.Join(home, "run", "daemon.sock"))
require.NoError(t, err)
t.Cleanup(func() { _ = listener.Close() })
done := make(chan error, 1)
go func() {
conn, err := listener.Accept()
if err != nil {
done <- err
return
}
defer func() { _ = conn.Close() }()
var request map[string]any
if err = json.NewDecoder(conn).Decode(&request); err == nil {
err = json.NewEncoder(conn).Encode(rpcReply{
ID: tc.id, Error: &RPCError{Code: tc.code, Message: "unsupported request"},
})
}
done <- err
}()
_, err = rpc(t.Context(), &device{runtime: &daemon{home: home}},
"tool.wheel", map[string]any{"delta_y": 500})
require.ErrorContains(t, err, tc.want)
require.NoError(t, <-done)
})
}
}

View File

@ -36,6 +36,49 @@ func TestRealExtension(t *testing.T) {
t.Cleanup(m.Close)
m.publicURL = "ws" + strings.TrimPrefix(server.URL, "http") + "/extension"
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/slow-error-page" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = io.WriteString(w, "<!doctype html><title>Fixture slow error</title>"+
"<p>Visible error while response is loading</p>")
w.(http.Flusher).Flush()
select {
case <-time.After(time.Second):
case <-r.Context().Done():
}
return
}
if r.URL.Path == "/error-page" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
_, _ = io.WriteString(w, "<!doctype html><title>Fixture error</title><p>Requested page does not exist</p>")
return
}
if r.URL.Path == "/redirect-error" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, `<!doctype html><script>location.replace('/error-page')</script>`)
return
}
if r.URL.Path == "/login" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, `<!doctype html><title>Fixture login</title>
<button>看过</button>
<form action="/login-complete" method="post">
<label>Account <input id="login-account" name="account"></label>
<label>Password <input id="login-password" type="password" name="password"></label>
<button id="login-submit" type="submit">Sign in</button></form>`)
return
}
if r.URL.Path == "/login-complete" {
if r.Method != http.MethodPost || r.FormValue("account") != "fixture-user" ||
r.FormValue("password") != "fixture-password" {
http.Error(w, "Fixture login failed", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, "<!doctype html><title>Fixture signed in</title><p>Fixture login complete</p>")
return
}
if r.URL.Path == "/large-page" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, "<!doctype html><title>Large task fixture</title><p>Ready</p>"+
@ -66,7 +109,8 @@ func TestRealExtension(t *testing.T) {
onclick="document.querySelector('#result').textContent='你好 '+document.querySelector('#name').value">Save</button>
<p id="result"></p>
<a id="new-tab" href="/linked" target="_blank" rel="noopener">Open linked page</a>
<button id="popup" onclick="window.open('/popup', '_blank')">Open popup</button>`,
<button id="popup" onclick="window.open('/popup', '_blank', 'width=480,height=320')">Open popup</button>
<p id="scroll-target" style="margin-top:2400px">Scroll destination</p>`,
)
}))
defer fixture.Close()
@ -217,6 +261,40 @@ func TestRealExtension(t *testing.T) {
t.Fatal("element screenshot was not cropped")
}
}
if _, err = call(ctx, scope, "chat", "scroll_to", map[string]any{"selector": "#scroll-target"}); err != nil {
t.Fatal(err)
}
position, err := call(ctx, scope, "chat", "evaluate", map[string]any{"expression": "window.scrollY"})
var scroll struct {
Value float64 `json:"value"`
}
if err != nil || json.Unmarshal(position, &scroll) != nil || scroll.Value < 1000 {
t.Fatalf("scroll_to did not move viewport: %s, %v", position, err)
}
if _, err = call(ctx, scope, "chat", "wheel", map[string]any{"delta_y": -600}); err != nil {
t.Fatal(err)
}
startY := scroll.Value
scrollDeadline := time.Now().Add(3 * time.Second)
for {
position, err = call(ctx, scope, "chat", "evaluate",
map[string]any{"expression": "(() => { return window.scrollY; })()"})
if err != nil || json.Unmarshal(position, &scroll) != nil {
t.Fatalf("scroll position unavailable: %s, %v", position, err)
}
if scroll.Value < startY {
break
}
if time.Now().After(scrollDeadline) {
t.Fatal("wheel did not move viewport")
}
time.Sleep(50 * time.Millisecond)
}
for _, method := range []string{"scroll_to", "focus", "blur"} {
if _, err = call(ctx, scope, "chat", method, map[string]any{"selector": "#name"}); err != nil {
t.Fatal(err)
}
}
if _, err = call(ctx, scope, "chat", "fill", map[string]any{"selector": "#name", "value": "世界"}); err != nil {
t.Fatal(err)
}
@ -231,28 +309,127 @@ func TestRealExtension(t *testing.T) {
t.Fatalf("action result missing: %s", snap)
}
checkBackground()
// Both target=_blank (including noopener) and window.open must become
// background task-owned tabs, not leaked foreground user tabs.
for i, selector := range []string{"#new-tab", "#popup"} {
if i > 0 {
if _, err = call(ctx, scope, "chat", "navigate", map[string]any{"url": fixture.URL}); err != nil {
t.Fatal(err)
}
}
// Agent-created navigation targets remain usable throughout their lifecycle.
// Cover both noopener links and script-created popup windows.
for _, selector := range []string{"#new-tab", "#popup"} {
if _, err = call(ctx, scope, "chat", "click", map[string]any{"selector": selector}); err != nil {
t.Fatal(err)
}
listed, e := call(ctx, scope, "chat", "tab_list", map[string]any{"scope": "agent"})
if e != nil {
popupID := 0
var e error
deadline := time.NewTimer(3 * time.Second)
waitPopup:
for popupID == 0 {
listed, listErr := call(ctx, scope, "chat", "tab_list", map[string]any{"scope": "all"})
if listErr != nil {
t.Fatal(listErr)
}
var result struct {
Tabs []struct {
ID int `json:"tab_id"`
URL string `json:"url"`
} `json:"tabs"`
}
if e = json.Unmarshal(listed, &result); e != nil {
t.Fatal(e)
}
for _, tab := range result.Tabs {
if strings.HasSuffix(tab.URL, "/linked") || strings.HasSuffix(tab.URL, "/popup") {
popupID = tab.ID
}
}
if popupID != 0 {
break waitPopup
}
select {
case <-tick.C:
case <-deadline.C:
t.Fatalf("fixture popup missing: %s", listed)
case <-ctx.Done():
t.Fatal(ctx.Err())
}
}
deadline.Stop()
if _, e = call(ctx, scope, "chat", "tab_select", map[string]any{"tab_id": popupID}); e != nil {
t.Fatal(e)
}
var result struct {
Tabs []json.RawMessage `json:"tabs"`
if _, e = call(ctx, scope, "chat", "snapshot", map[string]any{"tab_id": popupID}); e != nil {
t.Fatal(e)
}
if json.Unmarshal(listed, &result) != nil || len(result.Tabs) != i+2 {
t.Fatalf("page-created tab was not claimed: %s", listed)
if _, e = call(ctx, scope, "chat", "tab_close", map[string]any{"tab_id": popupID}); e != nil {
t.Fatal(e)
}
checkBackground()
}
// A genuine user-created tab inside the task window remains unauthorized,
// but can be borrowed there with an actual browser confirmation.
_, _ = io.WriteString(input, "create-unowned-tab\n")
var userTab struct {
ID int `json:"tab_id"`
}
select {
case line := <-hostLines:
if err = json.Unmarshal([]byte(line), &userTab); err != nil || userTab.ID == 0 {
t.Fatalf("create fixture tab: %s", line)
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
for _, method := range []string{"snapshot", "tab_select", "tab_close"} {
if _, err = call(ctx, scope, "chat", method, map[string]any{"tab_id": userTab.ID}); err == nil ||
!strings.Contains(err.Error(), "permission_denied") {
t.Fatalf("unowned user tab accepted %s: %v", method, err)
}
}
borrowDone := make(chan error, 1)
go func() {
_, borrowErr := call(ctx, scope, "chat", "tab_borrow", map[string]any{"tab_id": userTab.ID})
borrowDone <- borrowErr
}()
for !m.Status(scope, "chat").NeedsHelp {
select {
case <-tick.C:
case <-ctx.Done():
t.Fatal(ctx.Err())
}
}
if m.Status(scope, "chat").Action != "tab_borrow" {
t.Fatal("borrow confirmation must identify its handoff separately from login help")
}
_, _ = io.WriteString(input, "approve-borrow\n")
select {
case line := <-hostLines:
if line != "approve-borrow-done" {
t.Fatalf("borrow confirmation: %s", line)
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
select {
case err = <-borrowDone:
if err != nil {
t.Fatal(err)
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
if _, err = call(ctx, scope, "chat", "snapshot", map[string]any{"tab_id": userTab.ID}); err != nil {
t.Fatal(err)
}
if _, err = call(ctx, scope, "chat", "tab_return", map[string]any{"tab_id": userTab.ID}); err != nil {
t.Fatal(err)
}
if _, err = call(ctx, scope, "chat", "snapshot", map[string]any{"tab_id": userTab.ID}); err == nil ||
!strings.Contains(err.Error(), "permission_denied") {
t.Fatalf("returned tab remained readable: %v", err)
}
_, _ = fmt.Fprintf(input, "remove-fixture-tab %d\n", userTab.ID)
select {
case line := <-hostLines:
if line != "fixture-tab-removed" {
t.Fatalf("fixture cleanup: %s", line)
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
if _, err = call(ctx, scope, "chat", "tab_create", map[string]any{"url": fixture.URL}); err != nil {
t.Fatal(err)
@ -299,20 +476,77 @@ func TestRealExtension(t *testing.T) {
if err = m.Control(ctx, scope, "chat", "resume"); err != nil {
t.Fatal(err)
}
// Completing the real extension help overlay releases the same pending RPC.
// A fully loaded HTTP error is still a completed navigation. Inline redirects
// may replace the initial loader before its DOMContentLoaded event.
for _, path := range []string{"/error-page", "/redirect-error"} {
result, navErr := call(ctx, scope, "chat", "navigate", map[string]any{
"url": fixture.URL + path, "timeout_ms": 2000,
})
if navErr != nil || !strings.Contains(string(result), `"reached":"domcontentloaded"`) {
t.Fatalf("loaded error-page navigation %s: %s, %v", path, result, navErr)
}
observed, observeErr := call(ctx, scope, "chat", "snapshot", nil)
if observeErr != nil || !strings.Contains(string(observed), "Requested page does not exist") {
t.Fatalf("error page must remain readable: %s, %v", observed, observeErr)
}
}
// Rendering an error message does not imply DOMContentLoaded. The extension
// must report its own lifecycle timeout before the outer RPC deadline, leaving
// observation available to inspect the displayed error instead of pausing.
slowError, navErr := call(ctx, scope, "chat", "navigate", map[string]any{
"url": fixture.URL + "/slow-error-page", "timeout_ms": 200,
})
if navErr != nil || !NavigationIncomplete("navigate", slowError) {
t.Fatalf("expected inspectable navigation timeout, got %s, %v", slowError, navErr)
}
if m.Status(scope, "chat").Paused {
t.Fatal("a reported navigation wait timeout must not block page observation")
}
errorPage, observeErr := call(ctx, scope, "chat", "snapshot", nil)
if observeErr != nil || !strings.Contains(string(errorPage), "Visible error while response is loading") {
t.Fatalf("cannot inspect error page after navigation timeout: %s, %v", errorPage, observeErr)
}
// The human can fill a login form and navigate; help reappears in the new
// document and its completion releases the same pending RPC.
if _, err = call(ctx, scope, "chat", "navigate", map[string]any{"url": fixture.URL + "/login"}); err != nil {
t.Fatal(err)
}
go func() {
result, e := call(ctx, scope, "chat", "request_help", map[string]any{
"prompt": "Confirm this fixture step", "timeout_ms": 10000,
// This text exists before login. Legacy criteria must not complete
// the help RPC before the human confirms the actual login.
"completion_criteria": map[string]any{"any": []map[string]string{{"text_exists": "看过"}}},
})
if e == nil && !strings.Contains(string(result), `"continued"`) {
e = fmt.Errorf("unexpected help outcome: %s", result)
}
helpDone <- e
}()
_, _ = io.WriteString(input, "complete-help\n")
for !m.Status(scope, "chat").NeedsHelp {
select {
case err := <-helpDone:
t.Fatalf("help completed before handoff: %v", err)
case <-tick.C:
case <-ctx.Done():
t.Fatal(ctx.Err())
}
}
// Give the upstream automatic detector time to run. No human has acted.
select {
case err := <-helpDone:
t.Fatalf("help completed without manual confirmation: %v", err)
case <-time.After(2500 * time.Millisecond):
case <-ctx.Done():
t.Fatal(ctx.Err())
}
if !m.Status(scope, "chat").NeedsHelp {
t.Fatal("help prompt disappeared before the user completed login")
}
_, _ = io.WriteString(input, "complete-login\n")
select {
case line := <-hostLines:
if line != "complete-help-done" {
if line != "complete-login-done" {
t.Fatalf("complete help: %s", line)
}
case <-ctx.Done():
@ -329,6 +563,13 @@ func TestRealExtension(t *testing.T) {
if m.Status(scope, "chat").Paused || m.Status(scope, "chat").NeedsHelp {
t.Fatal("completed help did not release automation")
}
loggedIn, err := call(ctx, scope, "chat", "snapshot", nil)
if err != nil || !strings.Contains(string(loggedIn), "Fixture login complete") {
t.Fatalf("agent could not resume after manual login: %s, %v", loggedIn, err)
}
if _, err = call(ctx, scope, "chat", "navigate", map[string]any{"url": fixture.URL}); err != nil {
t.Fatal(err)
}
checkBackground()
if err = m.Focus(ctx, scope, "chat"); err != nil {
t.Fatal(err)
@ -502,6 +743,72 @@ func TestRealExtension(t *testing.T) {
}
}
checkCleanup()
// Closing the final page through the agent is normal cleanup, not a user
// interrupt. The following turn must start without a manual Resume click.
if err = m.Control(ctx, scope, "chat", "select"); err != nil {
t.Fatal(err)
}
lastPage, err := call(ctx, scope, "chat", "navigate", map[string]any{"url": fixture.URL})
var lastTab struct {
ID int `json:"tab_id"`
}
if err != nil || json.Unmarshal(lastPage, &lastTab) != nil || lastTab.ID == 0 {
t.Fatalf("last tab fixture: %s, %v", lastPage, err)
}
if _, err = call(ctx, scope, "chat", "tab_close", map[string]any{"tab_id": lastTab.ID}); err != nil {
t.Fatal(err)
}
// The model streams its answer before turn cleanup. Let Chrome's queued
// window-removal event arrive instead of racing it with session.stop.
time.Sleep(250 * time.Millisecond)
if m.Status(scope, "chat").Paused {
t.Fatal("agent tab_close was reported as a user interrupt")
}
if err = m.FinishTurn(ctx, scope, "chat", false); err != nil {
t.Fatal(err)
}
if m.Status(scope, "chat").Paused {
t.Fatal("agent closing the final tab incorrectly paused the task")
}
checkCleanup()
// Closing a window outside the agent command must still pause the task.
if err = m.Control(ctx, scope, "chat", "select"); err != nil {
t.Fatal(err)
}
lastPage, err = call(ctx, scope, "chat", "navigate", map[string]any{"url": fixture.URL})
if err != nil || json.Unmarshal(lastPage, &lastTab) != nil || lastTab.ID == 0 {
t.Fatalf("manual close fixture: %s, %v", lastPage, err)
}
_, _ = fmt.Fprintf(input, "close-fixture-window %d\n", lastTab.ID)
select {
case line := <-hostLines:
if line != "fixture-window-closed" {
t.Fatalf("manual window closure: %s", line)
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
closeDeadline := time.After(5 * time.Second)
for !m.Status(scope, "chat").Paused {
select {
case <-tick.C:
case <-closeDeadline:
t.Fatal("manual window closure did not pause task")
case <-ctx.Done():
t.Fatal(ctx.Err())
}
}
if _, err = call(ctx, scope, "chat", "navigate", map[string]any{"url": fixture.URL}); err == nil ||
!strings.Contains(err.Error(), "task_paused") {
t.Fatalf("manual window closure did not block automation: %v", err)
}
if err = m.Control(ctx, scope, "chat", "resume"); err != nil {
t.Fatal(err)
}
if err = m.FinishTurn(ctx, scope, "chat", false); err != nil {
t.Fatal(err)
}
checkCleanup()
// Repeated successful turns must return to the original user tabs, with
// no live task groups left over. The next turn can start without Resume.
for round := range 3 {

View File

@ -12,6 +12,11 @@ type uiReply struct {
err error
}
var errGatewayUIUnsupported = &RPCError{
Code: "gateway_ui_unsupported",
Message: "BrowserSkill extension lacks WeKnora task controls; install the companion extension",
}
// Focus is user initiated. Only the server-owned task ID is sent to Chrome.
func (m *Manager) Focus(ctx context.Context, s Scope, session string) error {
if _, remote, err := m.route(ctx, s, session, "focus", "", nil); remote || err != nil {
@ -96,6 +101,10 @@ func (m *Manager) receiveUI(d *device, data []byte) bool {
var err error
if len(frame.Error) > 0 && string(frame.Error) != "null" {
err = errors.New("browser task tab unavailable")
var rpcErr RPCError
if json.Unmarshal(frame.Error, &rpcErr) == nil && rpcErr.Code == "unknown_method" {
err = errGatewayUIUnsupported
}
}
reply <- uiReply{frame.Result, err}
return true
@ -153,8 +162,20 @@ func (m *Manager) Idle(ctx context.Context, s Scope, session string) error {
// retained or interrupted tasks stay available for user handoff. The browser
// source preference lives in the client settings, independently of this task.
func (m *Manager) FinishTurn(ctx context.Context, s Scope, session string, keepOpen bool) error {
// An unmodified official extension can still stop a completed task through
// native RPC. Retained tasks require the companion extension's idle barrier.
if err := m.Idle(ctx, s, session); err != nil {
return err
var rpcErr *RPCError
if keepOpen || !errors.As(err, &rpcErr) || rpcErr.Code != errGatewayUIUnsupported.Code {
return err
}
status, statusErr := m.GetStatus(ctx, s, session)
if statusErr != nil {
return statusErr
}
if status.Paused {
return err
}
}
if keepOpen {
return nil

View File

@ -625,9 +625,22 @@ func rpc(ctx context.Context, d *device, method string, params any) (json.RawMes
return nil, errors.New("browser command interrupted or timed out; do not replay actions automatically")
}
var reply rpcReply
if json.Unmarshal(line, &reply) != nil || reply.ID != id {
if json.Unmarshal(line, &reply) != nil {
return nil, errors.New("invalid BrowserSkill response")
}
if reply.ID != id {
// The daemon answers unrecognized request methods with an uncorrelated
// protocol error. This socket carries only one request; preserve the
// actionable version mismatch without accepting other mismatched replies.
if reply.ID == "0" && reply.Error != nil && reply.Error.Code == "protocol_error" {
return nil, &RPCError{
Code: "daemon_incompatible",
Message: "BrowserSkill daemon rejected the request protocol; " +
"rebuild bsk and the extension from the same pinned source baseline",
}
}
return nil, errors.New("invalid BrowserSkill response ID")
}
if reply.Error != nil {
reply.Error.BoundDetails()
return nil, reply.Error
@ -735,6 +748,10 @@ func (m *Manager) Call(
}
t.idle = false
t.action, t.actionStarted, t.actionFinished, t.lastError = method, time.Now(), time.Time{}, ""
if method == "navigate" {
requestedURL, _ := params["url"].(string)
t.pageURL = statusPageURL(requestedURL)
}
if method == "tab_select" || method == "tab_close" || method == "tab_return" {
t.pageURL = ""
}
@ -776,10 +793,23 @@ func (m *Manager) Call(
clean["wait_until"] = "domcontentloaded"
}
}
if method == "request_help" {
// A model-proposed page predicate is not evidence that the human step
// finished (e.g. login pages can already contain "History"). Require
// the user's explicit Continue action, including for legacy callers.
delete(clean, "completion_criteria")
}
clean["session_id"] = id
if helping {
// Keep all transports inside the same bounded human-wait budget.
clean["timeout_ms"] = humanTimeoutMS(clean["timeout_ms"])
if method == "tab_borrow" {
// Borrow confirmation uses a distinct protocol field. timeout_ms is
// ignored by this method, leaving the extension's shorter default.
clean["confirmation_timeout_ms"] = humanTimeoutMS(clean["confirmation_timeout_ms"])
delete(clean, "timeout_ms")
} else {
clean["timeout_ms"] = humanTimeoutMS(clean["timeout_ms"])
}
}
result, err := rpc(callCtx, d, "tool."+method, clean)
if method == "request_help" && err == nil {

View File

@ -91,8 +91,8 @@ func connectSharedFixture(
require.NoError(
t,
ws.WriteJSON(map[string]any{"id": "handshake", "method": "system.handshake", "params": map[string]any{
"client": "browser-skill-extension", "version": "0.2.1",
"protocol_version": "1.1", "min_compatible_protocol": "1.0",
"client": "browser-skill-extension", "version": "0.3.0",
"protocol_version": "1.3", "min_compatible_protocol": "1.0",
"instance_id": claimedID, "label": scope.User,
"browser": map[string]string{"name": "chrome", "version": "125"},
}}),
@ -226,7 +226,9 @@ func TestScreenshotUsesNativeTaskAndPreservesCrop(t *testing.T) {
func TestProgressReportsNavigationFailureAndFreezesElapsedTime(t *testing.T) {
m, ctx := sharedTestManager(t)
s := Scope{1, "progress"}
connectSharedFixture(ctx, t, m, s, "", "browser", func(f *sharedFixture, id, method string, _ map[string]any) bool {
connectSharedFixture(ctx, t, m, s, "", "browser", func(
f *sharedFixture, id, method string, _ map[string]any,
) bool {
if method != "tool.navigate" {
return false
}
@ -654,3 +656,112 @@ func TestFinishTurnClosesResearchButRetainsHandoffsAndPausedTasks(t *testing.T)
})
}
}
func TestFinishTurnWithOfficialExtensionStillStopsCompletedTask(t *testing.T) {
for _, remote := range []bool{false, true} {
t.Run(fmt.Sprintf("remote=%t", remote), func(t *testing.T) {
owner, ctx := sharedTestManager(t)
caller := owner
if remote {
owner.clusterSecret = strings.Repeat("cluster-secret-", 3)
server := httptest.NewServer(http.HandlerFunc(owner.InternalHTTP))
defer server.Close()
owner.internalURL = server.URL
caller = NewManager(owner.store)
caller.binary = owner.binary
caller.clusterSecret = owner.clusterSecret
t.Cleanup(caller.Close)
}
scope := Scope{1, "official-extension"}
connectSharedFixture(ctx, t, owner, scope, "", "browser", func(
f *sharedFixture, id, method string, _ map[string]any,
) bool {
if !strings.HasPrefix(method, "gateway.") {
return false
}
_ = f.send(map[string]any{"id": id, "error": map[string]string{"code": "unknown_method"}})
return true
})
require.NoError(t, caller.Control(ctx, scope, "research", "start"))
require.NoError(t, caller.FinishTurn(ctx, scope, "research", false))
require.Empty(t, owner.Status(scope, "research").SessionID)
for _, keep := range []bool{false, true} {
session := fmt.Sprintf("retained-%t", keep)
require.NoError(t, caller.Control(ctx, scope, session, "start"))
if !keep {
require.NoError(t, caller.Control(ctx, scope, session, "pause"))
}
var rpcErr *RPCError
require.ErrorAs(t, caller.FinishTurn(ctx, scope, session, keep), &rpcErr)
require.Equal(t, errGatewayUIUnsupported.Code, rpcErr.Code)
require.NotEmpty(t, owner.Status(scope, session).SessionID)
}
})
}
}
// Inspect the actual parameters forwarded by the native daemon, not just a
// timeout helper: tab_borrow ignores request_help's timeout_ms field.
func TestBorrowConfirmationBudgetReachesExtension(t *testing.T) {
m, ctx := sharedTestManager(t)
s := Scope{1, "borrow-budget"}
type pendingBorrow struct {
fixture *sharedFixture
id string
params map[string]any
}
pending := make(chan pendingBorrow, 1)
connectSharedFixture(ctx, t, m, s, "", "browser", func(
f *sharedFixture, id, method string, params map[string]any,
) bool {
if method != "tool.tab_borrow" {
return false
}
pending <- pendingBorrow{f, id, params}
return true
})
require.NoError(t, m.Control(ctx, s, "chat", "start"))
for _, tc := range []struct {
name string
value any
want float64
}{
{"default", nil, 300000},
{"explicit", 10000, 10000},
{"bounded", 600000, 300000},
} {
t.Run(tc.name, func(t *testing.T) {
params := map[string]any{"tab_id": 7}
if tc.value != nil {
params["confirmation_timeout_ms"] = tc.value
}
done := make(chan error, 1)
go func() {
_, err := m.Call(ctx, s, "chat", "tab_borrow", params)
done <- err
}()
var request pendingBorrow
select {
case request = <-pending:
case err := <-done:
t.Fatalf("borrow returned before extension confirmation: %v", err)
case <-ctx.Done():
t.Fatal(ctx.Err())
}
require.Equal(t, tc.want, request.params["confirmation_timeout_ms"])
require.NotContains(t, request.params, "timeout_ms")
require.True(t, m.Status(s, "chat").NeedsHelp)
require.Equal(t, "tab_borrow", m.Status(s, "chat").Action)
require.NoError(t, request.fixture.send(map[string]any{"id": request.id, "result": map[string]any{
"tab_id": 7, "original_window_id": 200, "agent_window_id": 100,
}}))
select {
case err := <-done:
require.NoError(t, err)
case <-ctx.Done():
t.Fatal(ctx.Err())
}
require.False(t, m.Status(s, "chat").NeedsHelp)
})
}
}

View File

@ -0,0 +1,674 @@
diff --git a/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts b/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts
index c901e49..2368337 100644
--- a/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts
+++ b/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts
@@ -30,6 +30,103 @@ function fakeApi() {
}
describe("ChromiumCdp", () => {
+ it("configures frame auto-attach once per debugger session and reapplies after detach", async () => {
+ const { api, onDetach } = fakeApi();
+ vi.mocked(api.sendCommand).mockResolvedValue({ frameTree: { frame: { id: "main" } } });
+ const cdp = new ChromiumCdp(api);
+ const calls = () =>
+ vi.mocked(api.sendCommand).mock.calls.filter((c) => c[1] === "Target.setAutoAttach");
+ await cdp.ensureAttached(4);
+ await Promise.all([cdp.getFrameGraph(4), cdp.getFrameGraph(4)]);
+ await cdp.getFrameGraph(4);
+ expect(calls()).toHaveLength(1);
+ onDetach.fire({ tabId: 4 }, "canceled_by_user");
+ await cdp.getFrameGraph(4);
+ expect(calls()).toHaveLength(2);
+ await cdp.detachAll();
+ await cdp.getFrameGraph(4);
+ expect(calls()).toHaveLength(3);
+ cdp.dispose();
+ });
+
+ it("retries frame discovery after a failed configuration", async () => {
+ const { api } = fakeApi();
+ let attempts = 0;
+ vi.mocked(api.sendCommand).mockImplementation(async (_target, method) => {
+ if (method === "Target.setAutoAttach" && ++attempts === 1) throw new Error("transient");
+ return { frameTree: { frame: { id: "main" } } };
+ });
+ const cdp = new ChromiumCdp(api);
+ await cdp.ensureAttached(4);
+ await cdp.getFrameGraph(4);
+ await cdp.getFrameGraph(4);
+ expect(attempts).toBe(2);
+ cdp.dispose();
+ });
+
+ it("does not send another screenshot after a local timeout while Chrome is still working", async () => {
+ vi.useFakeTimers();
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { api } = fakeApi();
+ let finish!: (value: unknown) => void;
+ vi.mocked(api.sendCommand).mockImplementation(async (_target, method) => {
+ if (method === "Page.captureScreenshot")
+ return new Promise((resolve) => {
+ finish = resolve;
+ });
+ return {};
+ });
+ const cdp = new ChromiumCdp(api);
+ try {
+ await cdp.ensureAttached(4);
+ const first = expect(cdp.send(4, "Page.captureScreenshot")).rejects.toThrow("timed out");
+ await vi.advanceTimersByTimeAsync(3000);
+ await first;
+ expect(cdp.hasPendingScreenshot(4)).toBe(true);
+ await expect(cdp.send(4, "Page.captureScreenshot")).rejects.toThrow("still running");
+ expect(
+ vi.mocked(api.sendCommand).mock.calls.filter((c) => c[1] === "Page.captureScreenshot"),
+ ).toHaveLength(1);
+ finish({ data: "late" });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(cdp.hasPendingScreenshot(4)).toBe(false);
+ const next = cdp.send(4, "Page.captureScreenshot");
+ await vi.advanceTimersByTimeAsync(0);
+ finish({ data: "new" });
+ await expect(next).resolves.toEqual({ data: "new" });
+ } finally {
+ cdp.dispose();
+ warning.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ it("emulates activity only for owned task tabs and reapplies after detach", async () => {
+ const { api, onDetach } = fakeApi();
+ const owned = new Set([4]);
+ const cdp = new ChromiumCdp(api, { shouldKeepTaskActive: (id) => owned.has(id) });
+ await Promise.all([cdp.ensureAttached(4), cdp.ensureAttached(4)]);
+ await cdp.ensureAttached(5);
+ const focusCalls = () =>
+ vi
+ .mocked(api.sendCommand)
+ .mock.calls.filter((call) => call[1] === "Emulation.setFocusEmulationEnabled");
+ expect(focusCalls()).toEqual([
+ [{ tabId: 4 }, "Emulation.setFocusEmulationEnabled", { enabled: true }],
+ ]);
+ // A previously observed user tab becomes eligible only once explicitly borrowed.
+ owned.add(5);
+ await cdp.send(5, "Page.getLayoutMetrics");
+ expect(focusCalls()).toHaveLength(2);
+ onDetach.fire({ tabId: 4 }, "canceled_by_user");
+ await cdp.ensureAttached(4);
+ expect(focusCalls()).toHaveLength(3);
+ await cdp.detach(4);
+ await cdp.ensureAttached(4);
+ expect(focusCalls()).toHaveLength(4);
+ cdp.dispose();
+ });
+
it("changes attachment identity only across real debugger attachments", async () => {
const { api, onEvent, onDetach } = fakeApi();
const cdp = new ChromiumCdp(api);
@@ -430,6 +527,7 @@ describe("ChromiumCdp", () => {
expect(api.sendCommand).toHaveBeenCalledWith({ tabId: 3 }, "Page.handleJavaScriptDialog", {
accept: true,
});
+ await vi.waitFor(() => expect(cdp.dialogsSince(3, cursor)).toHaveLength(1));
const dialogs = cdp.dialogsSince(3, cursor);
expect(dialogs).toHaveLength(1);
expect(dialogs[0]).toMatchObject({
@@ -479,7 +577,7 @@ describe("ChromiumCdp", () => {
url: "https://example.com/",
});
await Promise.resolve();
- expect(cdp.dialogsSince(11, 0)).toHaveLength(1);
+ await vi.waitFor(() => expect(cdp.dialogsSince(11, 0)).toHaveLength(1));
await cdp.detach(11);
expect(cdp.dialogsSince(11, 0)).toHaveLength(0);
});
diff --git a/apps/extension/src/browser-driver/__tests__/command-deadline.test.ts b/apps/extension/src/browser-driver/__tests__/command-deadline.test.ts
new file mode 100644
index 0000000..7c1dd61
--- /dev/null
+++ b/apps/extension/src/browser-driver/__tests__/command-deadline.test.ts
@@ -0,0 +1,76 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { captureObservationFacts } from "@/tools/vom/capture-coordinator";
+import { CdpReadTimeoutError, runCdpCommand } from "../command-deadline";
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+it("times out stuck snapshots with the actual method and stops fallback reads", async () => {
+ vi.useFakeTimers();
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ vi.spyOn(console, "debug").mockImplementation(() => {});
+ const send = vi.fn(async (_tab: number, method: string) =>
+ runCdpCommand({ tabId: 4 }, method, () =>
+ method === "DOMSnapshot.captureSnapshot" ? new Promise<never>(() => {}) : Promise.resolve({}),
+ ),
+ );
+ const work = captureObservationFacts({ send: send as never }, 4);
+ const checked = expect(work).rejects.toThrow(
+ "DOMSnapshot.captureSnapshot timed out after 10000ms (tab 4)",
+ );
+ await vi.advanceTimersByTimeAsync(10_000);
+ await checked;
+ expect(send.mock.calls.map((call) => call[1])).toEqual([
+ "DOMSnapshot.enable",
+ "DOMSnapshot.captureSnapshot",
+ ]);
+ expect(vi.getTimerCount()).toBe(0);
+});
+it("bounds screenshots and ignores their late reply", async () => {
+ vi.useFakeTimers();
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ vi.spyOn(console, "debug").mockImplementation(() => {});
+ let finish!: (value: string) => void;
+ const work = runCdpCommand(
+ { tabId: 4 },
+ "Page.captureScreenshot",
+ () =>
+ new Promise<string>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const checked = expect(work).rejects.toBeInstanceOf(CdpReadTimeoutError);
+ await vi.advanceTimersByTimeAsync(3_000);
+ await checked;
+ finish("late image");
+ await Promise.resolve();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it("distinguishes caller timeout from a late Chrome completion", async () => {
+ vi.useFakeTimers();
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
+ let finish!: (value: string) => void;
+ const work = runCdpCommand(
+ { tabId: 4 },
+ "Page.captureScreenshot",
+ () =>
+ new Promise<string>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const checked = expect(work).rejects.toBeInstanceOf(CdpReadTimeoutError);
+ await vi.advanceTimersByTimeAsync(3000);
+ await checked;
+ expect(warning.mock.calls.filter((c) => c[0] === "[bsk cdp] slow command settled")).toHaveLength(
+ 0,
+ );
+ await vi.advanceTimersByTimeAsync(5000);
+ finish("image");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(warning).toHaveBeenCalledWith(
+ "[bsk cdp] slow command settled",
+ expect.objectContaining({ elapsedMs: 8000, outcome: "returned", late: true }),
+ );
+});
diff --git a/apps/extension/src/browser-driver/__tests__/task-focus.browser.test.ts b/apps/extension/src/browser-driver/__tests__/task-focus.browser.test.ts
new file mode 100644
index 0000000..deed38f
--- /dev/null
+++ b/apps/extension/src/browser-driver/__tests__/task-focus.browser.test.ts
@@ -0,0 +1,94 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { captureVomObservation } from "@/tools/observation";
+import { type CdpDebuggerApi, ChromiumCdp } from "../chromium-cdp";
+
+describe.skipIf(!process.env.BSK_GEOMETRY_CHROME)("real background task rendering", () => {
+ it.each([
+ 0, 2000,
+ ])("renders a background page with %i repeated controls and restores visibility on detach", async (controlCount) => {
+ // Raw CDP deliberately avoids Playwright, which enables focus emulation by default
+ // and would mask this exact regression even when a Chrome tab is inactive.
+ const { withChrome } = await import(
+ new URL(
+ "../../../../../evals/browser/cases/regression/snapshot-coordinates/chrome.mjs",
+ import.meta.url,
+ ).href
+ );
+ await withChrome(
+ { executable: process.env.BSK_GEOMETRY_CHROME, deviceScale: 1, zoom: 1 },
+ async (send: any) => {
+ const foreground = (await send("Target.getTargets")).targetInfos.find(
+ (t: any) => t.type === "page",
+ );
+ const { sessionId: foregroundSession } = await send("Target.attachToTarget", {
+ targetId: foreground.targetId,
+ flatten: true,
+ });
+ const url =
+ "data:text/html," +
+ encodeURIComponent(
+ '<title>Background task</title><p>Loading</p><script>requestAnimationFrame(()=>document.querySelector("p").textContent="Rendered")</script>' +
+ "<section><h2>Entry</h2><button>Open</button><p>Sample page content</p></section>".repeat(
+ controlCount,
+ ),
+ );
+ const { targetId } = await send("Target.createTarget", { url, background: true });
+ let sessionId = (await send("Target.attachToTarget", { targetId, flatten: true }))
+ .sessionId;
+ const evaluate = async (expression: string, session = sessionId) =>
+ (
+ await send(
+ "Runtime.evaluate",
+ { expression, awaitPromise: true, returnByValue: true },
+ session,
+ )
+ ).result.value;
+ await expect.poll(() => evaluate("document.readyState")).toBe("complete");
+ expect(
+ await evaluate(
+ '({visibility:document.visibilityState,text:document.querySelector("p").textContent})',
+ ),
+ ).toEqual({ visibility: "hidden", text: "Loading" });
+ await send("Target.detachFromTarget", { sessionId });
+ const event = { addListener() {}, removeListener() {} };
+ const api = {
+ attach: async () => {
+ sessionId = (await send("Target.attachToTarget", { targetId, flatten: true }))
+ .sessionId;
+ },
+ detach: async () => {
+ await send("Target.detachFromTarget", { sessionId });
+ },
+ sendCommand: (_target: unknown, method: string, params: object) =>
+ send(method, params, sessionId),
+ onEvent: event,
+ onDetach: event,
+ } as unknown as CdpDebuggerApi;
+ const cdp = new ChromiumCdp(api, { shouldKeepTaskActive: () => true });
+ try {
+ await cdp.ensureAttached(4);
+ expect(
+ await evaluate(
+ 'new Promise(resolve=>requestAnimationFrame(()=>resolve(document.querySelector("p").textContent)))',
+ ),
+ ).toBe("Rendered");
+ const observation = await captureVomObservation(cdp, 4, url);
+ expect(observation.text).toContain("Rendered");
+ expect(observation.refs).toHaveLength(controlCount);
+ const image = await cdp.send<{ data: string }>(4, "Page.captureScreenshot", {
+ format: "jpeg",
+ fromSurface: true,
+ });
+ expect(image.data.length).toBeGreaterThan(100);
+ expect(await evaluate("document.visibilityState", foregroundSession)).toBe("visible");
+ await cdp.detach(4);
+ sessionId = (await send("Target.attachToTarget", { targetId, flatten: true })).sessionId;
+ expect(await evaluate("document.visibilityState")).toBe("hidden");
+ } finally {
+ cdp.dispose();
+ }
+ },
+ );
+ }, 20_000);
+});
diff --git a/apps/extension/src/browser-driver/chromium-cdp.ts b/apps/extension/src/browser-driver/chromium-cdp.ts
index d40325c..720f87a 100644
--- a/apps/extension/src/browser-driver/chromium-cdp.ts
+++ b/apps/extension/src/browser-driver/chromium-cdp.ts
@@ -31,6 +31,7 @@ import type {
NetworkEntryKind,
NetworkResult,
} from "@/transport/types";
+import { runCdpCommand } from "./command-deadline";
import {
buildFrameGraph,
type CdpFrameGraph,
@@ -140,6 +141,7 @@ interface FrameDiscoveryState {
sessions: Set<string>;
pending: Set<Promise<void>>;
generation: number;
+ enabled: Map<string, Promise<void>>;
}
async function settleBeforeDeadline(promises: Promise<void>[], deadline: number): Promise<boolean> {
@@ -164,6 +166,8 @@ async function settleBeforeDeadline(promises: Promise<void>[], deadline: number)
export class ChromiumCdp {
private readonly api: CdpDebuggerApi;
private readonly attachedTabs = new Set<number>();
+ private readonly pendingScreenshots = new Map<number, Promise<unknown>>();
+ private readonly taskFocus = new Map<number, Promise<void>>();
private readonly attachmentIds = new Map<number, string>();
private readonly attachInFlight = new Map<number, Promise<void>>();
private readonly detachInFlight = new Map<number, Promise<void>>();
@@ -191,6 +195,8 @@ export class ChromiumCdp {
shouldAutoAcceptDialog?: (tabId: number) => boolean | Promise<boolean>;
/** Invalidate tab refs when the root document or debugger attachment changes. */
onDocumentChanged?: (tabId: number) => void;
+ /** Only explicitly controlled task tabs may emulate foreground page activity. */
+ shouldKeepTaskActive?: (tabId: number) => boolean;
} = {},
) {
this.api = api;
@@ -212,7 +218,10 @@ export class ChromiumCdp {
// New observers must wait before opening the next connection to that tab.
const detaching = this.detachInFlight.get(tabId);
if (detaching) await detaching;
- if (this.attachedTabs.has(tabId)) return;
+ if (this.attachedTabs.has(tabId)) {
+ await this.keepTaskActive(tabId);
+ return;
+ }
const existing = this.attachInFlight.get(tabId);
if (existing) {
await existing;
@@ -221,6 +230,7 @@ export class ChromiumCdp {
const attach = (async () => {
await this.api.attach({ tabId }, CDP_PROTOCOL_VERSION);
try {
+ await this.keepTaskActive(tabId);
await this.enablePageDomain(tabId);
await this.enableConsoleDomains(tabId);
await this.enableNetworkDomainBestEffort(tabId);
@@ -242,6 +252,7 @@ export class ChromiumCdp {
await this.api.detach({ tabId }).catch((detachErr) => {
console.debug("[bsk cdp] rollback detach failed", { tabId, detachErr });
});
+ this.taskFocus.delete(tabId);
throw err;
}
})()
@@ -263,11 +274,16 @@ export class ChromiumCdp {
* `chrome.runtime.lastError`.
*/
async send<T = unknown>(tabId: number, method: string, params?: object): Promise<T> {
- if (!this.attachedTabs.has(tabId)) {
- await this.ensureAttached(tabId);
- }
+ await this.ensureAttached(tabId);
try {
- const result = await this.api.sendCommand({ tabId }, method, params ?? {});
+ const result = await this.command({ tabId }, method, params ?? {});
+ // Upstream input readiness temporarily restores focus emulation. Reapply
+ // the task policy on the next command instead of trusting a stale cache.
+ if (
+ method === "Emulation.setFocusEmulationEnabled" &&
+ (params as { enabled?: boolean } | undefined)?.enabled === false
+ )
+ this.taskFocus.delete(tabId);
return result as T;
} catch (err) {
throw normalizeError(err);
@@ -275,11 +291,9 @@ export class ChromiumCdp {
}
async sendToTarget<T = unknown>(target: CdpTarget, method: string, params?: object): Promise<T> {
- if (!this.attachedTabs.has(target.tabId)) {
- await this.ensureAttached(target.tabId);
- }
+ await this.ensureAttached(target.tabId);
try {
- return (await this.api.sendCommand(target, method, params ?? {})) as T;
+ return (await this.command(target, method, params ?? {})) as T;
} catch (err) {
throw normalizeError(err);
}
@@ -455,6 +469,7 @@ export class ChromiumCdp {
this.attachedTabs.delete(tabId);
this.attachmentIds.delete(tabId);
this.options.onDocumentChanged?.(tabId);
+ this.taskFocus.delete(tabId);
this.clearDialogState(tabId);
this.clearConsoleState(tabId);
this.clearNetworkState(tabId);
@@ -515,6 +530,7 @@ export class ChromiumCdp {
this.attachedTabs.clear();
this.attachmentIds.clear();
for (const tabId of tabs) this.options.onDocumentChanged?.(tabId);
+ this.taskFocus.clear();
this.dialogBuffers.clear();
this.dialogSequences.clear();
this.consoleBuffers.clear();
@@ -525,6 +541,7 @@ export class ChromiumCdp {
this.networkDomainsEnabledTabs.clear();
this.networkRequestMeta.clear();
this.frameDiscovery.clear();
+ this.pendingScreenshots.clear();
await Promise.all(
tabs.map(async (tabId) => {
try {
@@ -536,8 +553,48 @@ export class ChromiumCdp {
);
}
+ hasPendingScreenshot(tabId: number): boolean {
+ return this.pendingScreenshots.has(tabId);
+ }
+
+ private command(target: CdpDebuggee, method: string, params: object): Promise<unknown> {
+ return runCdpCommand(target, method, () => {
+ const tabId = target.tabId;
+ if (method !== "Page.captureScreenshot" || tabId === undefined)
+ return this.api.sendCommand(target, method, params);
+ // A local deadline cannot cancel a Chrome command. Keep this fence until
+ // Chrome actually replies (or detaches), so polling cannot pile up captures.
+ if (this.pendingScreenshots.has(tabId))
+ throw new Error("Previous screenshot is still running in Chrome");
+ const pending = this.api.sendCommand(target, method, params);
+ this.pendingScreenshots.set(tabId, pending);
+ const clear = () => {
+ if (this.pendingScreenshots.get(tabId) === pending) this.pendingScreenshots.delete(tabId);
+ };
+ void pending.then(clear, clear);
+ return pending;
+ });
+ }
+
+ private async keepTaskActive(tabId: number): Promise<void> {
+ if (!this.options.shouldKeepTaskActive?.(tabId)) return;
+ let work = this.taskFocus.get(tabId);
+ if (!work) {
+ // Emulate page visibility/focus without activating a Chrome tab or window.
+ // Chrome resets this per-debugger override when we detach at turn end.
+ work = this.command({ tabId }, "Emulation.setFocusEmulationEnabled", { enabled: true })
+ .then(() => {})
+ .catch((error) => {
+ this.taskFocus.delete(tabId);
+ throw error;
+ });
+ this.taskFocus.set(tabId, work);
+ }
+ await work;
+ }
+
private async enablePageDomain(tabId: number): Promise<void> {
- await this.api.sendCommand({ tabId }, "Page.enable", {});
+ await this.command({ tabId }, "Page.enable", {});
}
private async enableConsoleDomains(tabId: number): Promise<void> {
@@ -550,7 +607,7 @@ export class ChromiumCdp {
let failed = false;
for (const method of ["Runtime.enable", "Log.enable"]) {
try {
- await this.api.sendCommand({ tabId }, method, {});
+ await this.command({ tabId }, method, {});
} catch (err) {
failed = true;
console.debug("[bsk cdp] console domain enable failed", { tabId, method, err });
@@ -563,7 +620,7 @@ export class ChromiumCdp {
private async enableNetworkDomain(tabId: number): Promise<void> {
if (this.networkDomainsEnabledTabs.has(tabId)) return;
- await this.api.sendCommand({ tabId }, "Network.enable", {});
+ await this.command({ tabId }, "Network.enable", {});
this.networkDomainsEnabledTabs.add(tabId);
}
@@ -575,13 +632,27 @@ export class ChromiumCdp {
}
}
- private async enableFrameDiscovery(target: CdpTarget): Promise<void> {
- await this.api.sendCommand(target, "Target.setAutoAttach", {
+ private enableFrameDiscovery(target: CdpTarget): Promise<void> {
+ const state = this.frameDiscoveryState(target.tabId);
+ const key = target.sessionId ?? "root";
+ const existing = state.enabled.get(key);
+ if (existing) return existing;
+ // Auto-attach remains enabled for this debugger session, including later
+ // navigation and new iframes. Reconfiguring it on every observation adds a
+ // browser round trip and needlessly repeats child-target discovery.
+ const work = this.command(target, "Target.setAutoAttach", {
autoAttach: true,
waitForDebuggerOnStart: false,
flatten: true,
filter: [{ type: "iframe", exclude: false }],
- });
+ })
+ .then(() => {})
+ .catch((error) => {
+ if (state.enabled.get(key) === work) state.enabled.delete(key);
+ throw error;
+ });
+ state.enabled.set(key, work);
+ return work;
}
private bindFrameTargetHandler(): void {
@@ -608,6 +679,7 @@ export class ChromiumCdp {
if (method === "Target.detachedFromTarget") {
const state = this.frameDiscovery.get(tabId);
+ state?.enabled.delete(sessionId);
if (state?.sessions.delete(sessionId)) state.generation += 1;
return;
}
@@ -674,6 +746,7 @@ export class ChromiumCdp {
sessions: new Set(),
pending: new Set(),
generation: 0,
+ enabled: new Map(),
};
this.frameDiscovery.set(tabId, created);
return created;
@@ -681,6 +754,7 @@ export class ChromiumCdp {
private clearFrameState(tabId: number): void {
this.frameDiscovery.delete(tabId);
+ this.pendingScreenshots.delete(tabId);
}
private bindDialogHandler(): void {
@@ -713,7 +787,7 @@ export class ChromiumCdp {
if (parsed.type === "prompt") {
handleParams.promptText = parsed.defaultPrompt ?? "";
}
- await this.api.sendCommand({ tabId }, "Page.handleJavaScriptDialog", handleParams);
+ await this.command({ tabId }, "Page.handleJavaScriptDialog", handleParams);
if (!this.attachedTabs.has(tabId) && !this.attachInFlight.has(tabId)) return;
const sequence = (this.dialogSequences.get(tabId) ?? 0) + 1;
this.dialogSequences.set(tabId, sequence);
@@ -876,6 +950,7 @@ export class ChromiumCdp {
this.options.onDocumentChanged?.(source.tabId);
this.attachedTabs.delete(source.tabId);
this.attachmentIds.delete(source.tabId);
+ this.taskFocus.delete(source.tabId);
this.attachInFlight.delete(source.tabId);
this.tabOwners.delete(source.tabId);
this.clearDialogState(source.tabId);
diff --git a/apps/extension/src/browser-driver/command-deadline.ts b/apps/extension/src/browser-driver/command-deadline.ts
new file mode 100644
index 0000000..540d804
--- /dev/null
+++ b/apps/extension/src/browser-driver/command-deadline.ts
@@ -0,0 +1,78 @@
+import type { CdpDebuggee } from "./chromium-cdp";
+
+// Bound renderer reads, not user-requested waits or mutations. An expired
+// CDP read cannot be cancelled individually; its late reply is ignored and
+// observation must stop rather than issue fallback reads against the same page.
+const READ_COMMANDS = new Set([
+ "Target.setAutoAttach",
+ "DOMSnapshot.enable",
+ "DOMSnapshot.captureSnapshot",
+ "Accessibility.enable",
+ "Accessibility.getFullAXTree",
+ "Page.getLayoutMetrics",
+ "Page.getFrameTree",
+ "DOM.getFrameOwner",
+ "Page.captureScreenshot",
+ "Emulation.setFocusEmulationEnabled",
+]);
+export class CdpReadTimeoutError extends Error {
+ constructor(method: string, tabId: number | undefined, timeout: number) {
+ super(
+ `Browser read ${method} timed out after ${timeout}ms (tab ${tabId}). Do not repeat the same read in a loop; report the timeout and let the browser task release control before retrying.`,
+ );
+ this.name = "CdpReadTimeoutError";
+ }
+}
+
+export async function runCdpCommand<T>(
+ target: CdpDebuggee,
+ method: string,
+ run: () => Promise<T>,
+): Promise<T> {
+ const started = Date.now();
+ const details = () => ({
+ tabId: target.tabId,
+ frameSessionId: target.sessionId,
+ method,
+ elapsedMs: Date.now() - started,
+ });
+ const slow = setTimeout(() => console.warn("[bsk cdp] slow command", details()), 2_000);
+ let deadline: ReturnType<typeof setTimeout> | undefined;
+ let timedOut = false;
+ const settled = (outcome: "returned" | "failed") => {
+ if (Date.now() - started >= 2_000)
+ console.warn("[bsk cdp] slow command settled", { ...details(), outcome, late: timedOut });
+ };
+ try {
+ const pending = run().then(
+ (value) => {
+ settled("returned");
+ return value;
+ },
+ (error) => {
+ settled("failed");
+ throw error;
+ },
+ );
+ if (!READ_COMMANDS.has(method)) return await pending;
+ const timeout = method === "Page.captureScreenshot" ? 3_000 : 10_000;
+ return await Promise.race([
+ pending,
+ new Promise<never>((_, reject) => {
+ deadline = setTimeout(() => {
+ timedOut = true;
+ reject(new CdpReadTimeoutError(method, target.tabId, timeout));
+ }, timeout);
+ }),
+ ]);
+ } catch (error) {
+ console.warn("[bsk cdp] command failed", {
+ ...details(),
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw error;
+ } finally {
+ clearTimeout(slow);
+ clearTimeout(deadline);
+ }
+}
diff --git a/apps/extension/src/tools/vom/capture-abort.ts b/apps/extension/src/tools/vom/capture-abort.ts
index 7ca65bf..429c373 100644
--- a/apps/extension/src/tools/vom/capture-abort.ts
+++ b/apps/extension/src/tools/vom/capture-abort.ts
@@ -4,10 +4,12 @@ function captureAbortError(): Error {
return error;
}
+// Timed-out renderer reads are terminal too: AX/geometry fallback must not
+// keep issuing reads after the renderer has stopped answering.
export function isAbortError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
- (error as { name?: string }).name === "AbortError"
+ ["AbortError", "CdpReadTimeoutError"].includes((error as { name?: string }).name ?? "")
);
}

View File

@ -0,0 +1,716 @@
diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts
index 830bbbe..1a9a788 100644
--- a/apps/extension/src/entrypoints/background.ts
+++ b/apps/extension/src/entrypoints/background.ts
@@ -4,6 +4,7 @@ import { getAuditEnabled } from "@/lib/audit";
import { attachAuditBridge } from "@/lib/audit-bridge";
import { ConnectionController } from "@/lib/connection-controller";
import { watchDaemonConnection } from "@/lib/daemon-connection-preference";
+import { attachGatewayUI } from "@/lib/gateway-ui";
import { startHeartbeat } from "@/lib/heartbeat";
import {
getConnectionEnabled,
@@ -27,6 +28,8 @@ import {
import { POPUP_PORT_NAME, type PopupInbound, type PopupOutbound } from "@/lib/popup-bridge";
import { recordFrameCoordinator } from "@/lib/recording/frame-coordinator";
import { attachSessionsLiveFlag } from "@/lib/sessions-live-flag";
+import { TaskActivity } from "@/lib/task-activity";
+import { captureTaskPreview, taskTarget } from "@/lib/task-preview";
import { attachLongScreenshot } from "@/long-screenshot/background";
import { createDisconnectCleanup } from "@/session-manager/disconnect-cleanup";
import { attachSessionEventHandler } from "@/session-manager/event-handler";
@@ -63,7 +66,27 @@ export default defineBackground(() => {
url: __BSK_DAEMON_WS_URL__,
webSocketFactory: (url) => {
if (!connectionPreferenceValid) throw new Error("Connection settings are unavailable");
- return remoteSocket(url, remoteEndpoint);
+ const socket = remoteSocket(url, remoteEndpoint);
+ if (remoteEndpoint)
+ attachGatewayUI(socket, {
+ focus: async (sessionId) => {
+ const tabId = await taskTarget(sessions, sessionId);
+ const task = sessions.get(sessionId);
+ const tab = await chrome.tabs.get(tabId);
+ if (!task || !isAgentControlledTab(task, tabId)) throw new Error("Task unavailable");
+ await chrome.tabs.update(tabId, { active: true });
+ await chrome.windows.update(tab.windowId, { focused: true });
+ return { focused: true };
+ },
+ preview: (sessionId) =>
+ taskActivity.preview(sessionId, () => captureTaskPreview(sessions, cdp, sessionId)),
+ idle: async (sessionId) => {
+ if (!sessions.get(sessionId)?.remote) throw new Error("Task unavailable");
+ await taskActivity.release(sessionId);
+ return { released: true };
+ },
+ });
+ return socket;
},
});
const sessions = new SessionManager({ remote: () => remoteEndpoint !== null });
@@ -72,6 +95,8 @@ export default defineBackground(() => {
});
attachAuditBridge(controller, transport);
const cdp = new ChromiumCdp(undefined, {
+ shouldKeepTaskActive: (tabId) =>
+ sessions.list().some((task) => task.remote && isAgentControlledTab(task, tabId)),
onDocumentChanged: (tabId) => sessions.invalidateTabRefs(tabId),
shouldAutoAcceptDialog: async (tabId) => {
const tab = await chrome.tabs.get(tabId);
@@ -79,6 +104,9 @@ export default defineBackground(() => {
return session !== null && (!session.remote || isAgentControlledTab(session, tabId));
},
});
+ const taskActivity: TaskActivity = new TaskActivity(sessions, (id) =>
+ dispatcher.releaseTaskControl(id),
+ );
const sessionsLive = attachSessionsLiveFlag({ manager: sessions });
let overlayGeneration = 0;
const controlModes = new Map<string, OverlayMode>();
@@ -290,6 +318,7 @@ export default defineBackground(() => {
});
void interactionPreferences.readyOrFallback();
const dispatcher = new ToolDispatcher({
+ taskActivity,
interactionPreferences,
transport,
sessions,
diff --git a/apps/extension/src/lib/__tests__/gateway-ui.test.ts b/apps/extension/src/lib/__tests__/gateway-ui.test.ts
new file mode 100644
index 0000000..eda0a0e
--- /dev/null
+++ b/apps/extension/src/lib/__tests__/gateway-ui.test.ts
@@ -0,0 +1,52 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { attachGatewayUI } from "../gateway-ui";
+
+afterEach(() => vi.unstubAllGlobals());
+function fixture() {
+ vi.stubGlobal("WebSocket", { OPEN: 1 });
+ const socket = Object.assign(new EventTarget(), { readyState: 1, send: vi.fn() });
+ const ui = {
+ focus: vi.fn(async () => ({ focused: true })),
+ preview: vi.fn(async () => ({ image_base64: "jpeg" })),
+ idle: vi.fn(async () => ({ released: true })),
+ };
+ attachGatewayUI(socket as unknown as WebSocket, ui);
+ const native = vi.fn();
+ socket.addEventListener("message", native);
+ const request = async (body: unknown) => {
+ socket.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(body) }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ };
+ return { socket, ui, native, request };
+}
+describe("gateway UI side channel", () => {
+ it("routes UI requests independently and leaves native RPC untouched", async () => {
+ const f = fixture();
+ for (const name of ["preview", "focus", "idle"] as const) {
+ await f.request({ id: name, method: `gateway.task_${name}`, params: { session_id: "task" } });
+ expect(f.ui[name]).toHaveBeenCalledWith("task");
+ }
+ expect(f.native).not.toHaveBeenCalled();
+ await f.request({ id: "native", method: "tool.snapshot", params: {} });
+ expect(f.native).toHaveBeenCalledOnce();
+ });
+ it("rejects invalid session IDs without invoking browser work", async () => {
+ const f = fixture();
+ await f.request({ id: "bad", method: "gateway.task_focus", params: { session_id: 42 } });
+ expect(f.ui.focus).not.toHaveBeenCalled();
+ expect(JSON.parse(f.socket.send.mock.calls[0]![0])).toMatchObject({
+ error: { code: "invalid_params" },
+ });
+ });
+ it("reports failures and drops late replies on closed sockets", async () => {
+ const f = fixture();
+ f.ui.idle.mockRejectedValueOnce(new Error("unavailable"));
+ await f.request({ id: "idle", method: "gateway.task_idle", params: { session_id: "task" } });
+ expect(JSON.parse(f.socket.send.mock.calls[0]![0])).toMatchObject({
+ error: { code: "task_unavailable" },
+ });
+ f.socket.readyState = 3;
+ await f.request({ id: "late", method: "gateway.task_preview", params: { session_id: "task" } });
+ expect(f.socket.send).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/extension/src/lib/__tests__/task-activity.test.ts b/apps/extension/src/lib/__tests__/task-activity.test.ts
new file mode 100644
index 0000000..7eae50f
--- /dev/null
+++ b/apps/extension/src/lib/__tests__/task-activity.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it, vi } from "vitest";
+import type { SessionManager } from "@/session-manager/manager";
+import { TaskActivity } from "../task-activity";
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+function fixture() {
+ const tasks = new Map<string, object>([
+ ["one", { remote: true }],
+ ["two", { remote: true }],
+ ]);
+ const manager = { get: (id: string) => tasks.get(id) } as unknown as SessionManager;
+ const detach = vi.fn(async (_id: string) => {});
+ return { tasks, detach, activity: new TaskActivity(manager, detach) };
+}
+describe("task debugging lifecycle", () => {
+ it("drains an in-flight screenshot before detach and rejects later preview attachment", async () => {
+ const { activity, detach, tasks } = fixture();
+ const shot = deferred();
+ const capture = activity.preview("one", () => shot.promise);
+ const release = activity.release("one");
+ await expect(activity.preview("one", async () => {})).rejects.toThrow("idle");
+ await Promise.resolve();
+ expect(detach).not.toHaveBeenCalled();
+ shot.resolve();
+ await Promise.all([capture, release]);
+ expect(detach).toHaveBeenCalledWith("one");
+ expect(tasks.has("one")).toBe(true);
+ await expect(activity.preview("one", async () => {})).rejects.toThrow("idle");
+ });
+ it("waits for automation even if turn end arrives before the operation begins", async () => {
+ const { activity, detach } = fixture();
+ const op = deferred();
+ const running = activity.run("one", false, () => op.promise);
+ const release = activity.release("one");
+ await Promise.resolve();
+ expect(detach).not.toHaveBeenCalled();
+ op.resolve();
+ await Promise.all([running, release]);
+ expect(detach).toHaveBeenCalledTimes(1);
+ });
+ it("a new turn waits for detach then resumes capture without deleting tabs", async () => {
+ const { activity, detach } = fixture();
+ const gate = deferred();
+ detach.mockImplementationOnce(() => gate.promise);
+ const release = activity.release("one");
+ const op = vi.fn(async () => {});
+ const next = activity.run("one", false, op);
+ await Promise.resolve();
+ expect(op).not.toHaveBeenCalled();
+ gate.resolve();
+ await Promise.all([release, next]);
+ expect(op).toHaveBeenCalledOnce();
+ await expect(activity.preview("one", async () => "frame")).resolves.toBe("frame");
+ });
+ it("stop fences previews before closing tabs", async () => {
+ const { activity, detach } = fixture();
+ await activity.run("one", true, async () => {
+ expect(detach).toHaveBeenCalledWith("one");
+ await expect(activity.preview("one", async () => {})).rejects.toThrow("idle");
+ });
+ await expect(activity.preview("one", async () => {})).rejects.toThrow("idle");
+ });
+ it("failed captures do not prevent release or interfere with another task", async () => {
+ const { activity, detach } = fixture();
+ const capture = activity.preview("one", async () => {
+ throw new Error("failed capture");
+ });
+ const release = activity.release("one");
+ await expect(capture).rejects.toThrow("failed capture");
+ await release;
+ await expect(activity.preview("two", async () => "live")).resolves.toBe("live");
+ expect(detach).toHaveBeenCalledTimes(1);
+ });
+ it("does not resume a deleted session after waiting for release", async () => {
+ const { activity, tasks, detach } = fixture();
+ const gate = deferred();
+ detach.mockImplementationOnce(() => gate.promise);
+ const release = activity.release("one");
+ const op = vi.fn(async () => {});
+ const next = activity.run("one", false, op);
+ tasks.delete("one");
+ gate.resolve();
+ await release;
+ await expect(next).rejects.toThrow("Task ended");
+ expect(op).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/extension/src/lib/__tests__/task-preview.test.ts b/apps/extension/src/lib/__tests__/task-preview.test.ts
new file mode 100644
index 0000000..88fe91e
--- /dev/null
+++ b/apps/extension/src/lib/__tests__/task-preview.test.ts
@@ -0,0 +1,157 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ChromiumCdp } from "@/browser-driver/chromium-cdp";
+import { runCdpCommand } from "@/browser-driver/command-deadline";
+import type { SessionManager } from "@/session-manager/manager";
+import { TaskActivity } from "../task-activity";
+import { captureTaskPreview } from "../task-preview";
+
+vi.mock("@/lib/capture-suppress-bridge", () => ({
+ withExtensionOverlayHidden: (_tab: number, run: () => unknown) => run(),
+}));
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+function fixture() {
+ const task = {
+ remote: true,
+ agentWindowId: 10,
+ refStore: { documentRevision: () => 1 },
+ agentCreatedTabs: new Set([5]),
+ borrowedTabs: new Map(),
+ };
+ const manager = { get: () => task } as unknown as SessionManager;
+ const cdp = {
+ getAttachmentId: vi.fn(() => "attachment"),
+ trackSessionTab: vi.fn(),
+ hasPendingScreenshot: vi.fn(() => false),
+ ensureAttached: vi.fn(async () => {}),
+ send: vi.fn(async (_tab, method) =>
+ method === "Page.getLayoutMetrics"
+ ? { cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 1280, clientHeight: 720 } }
+ : { data: btoa("jpeg") },
+ ),
+ } as unknown as ChromiumCdp;
+ const draw = vi.fn();
+ const close = vi.fn();
+ const sizes: number[] = [];
+ vi.stubGlobal("chrome", {
+ tabs: {
+ query: vi.fn(async () => [{ id: 5, windowId: 10, active: true }]),
+ get: vi.fn(async () => ({ id: 5, windowId: 10, title: "task" })),
+ },
+ });
+ vi.stubGlobal(
+ "createImageBitmap",
+ vi.fn(async () => ({ width: 1280, height: 720, close })),
+ );
+ vi.stubGlobal(
+ "OffscreenCanvas",
+ class {
+ width: number;
+ height: number;
+ constructor(w: number, h: number) {
+ this.width = w;
+ this.height = h;
+ sizes.push(w, h);
+ }
+ getContext() {
+ return { drawImage: draw };
+ }
+ async convertToBlob() {
+ return new Blob(["thumbnail"]);
+ }
+ },
+ );
+ return { task, manager, cdp, sizes, close };
+}
+describe("independent task preview", () => {
+ it("lets turn-end release finish after a stuck screenshot times out", async () => {
+ vi.useFakeTimers();
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ vi.spyOn(console, "debug").mockImplementation(() => {});
+ const f = fixture();
+ const original = vi.mocked(f.cdp.send).getMockImplementation()!;
+ vi.mocked(f.cdp.send).mockImplementation((tab, method, params) =>
+ method === "Page.captureScreenshot"
+ ? runCdpCommand({ tabId: tab }, method, () => new Promise<never>(() => {}))
+ : original(tab, method, params),
+ );
+ const detach = vi.fn(async () => {});
+ const activity = new TaskActivity(f.manager, detach);
+ const frame = activity.preview("stuck", () => captureTaskPreview(f.manager, f.cdp, "stuck"));
+ const checked = expect(frame).rejects.toThrow("Page.captureScreenshot timed out");
+ const released = activity.release("stuck");
+ await vi.advanceTimersByTimeAsync(3_000);
+ await checked;
+ await released;
+ expect(detach).toHaveBeenCalledWith("stuck");
+ expect(vi.getTimerCount()).toBe(0);
+ vi.mocked(f.cdp.send).mockImplementation(original);
+ await expect(
+ activity.run("stuck", false, () => captureTaskPreview(f.manager, f.cdp, "stuck")),
+ ).resolves.toMatchObject({ tab_id: 5 });
+ });
+
+ it("coalesces captures and bounds the physical bitmap on HiDPI screens", async () => {
+ const f = fixture();
+ const first = captureTaskPreview(f.manager, f.cdp, "one");
+ expect(captureTaskPreview(f.manager, f.cdp, "one")).toBe(first);
+ const frame = await first;
+ expect(frame).toMatchObject({ tab_id: 5, format: "jpeg", image_base64: btoa("thumbnail") });
+ expect(f.sizes).toEqual([640, 360]);
+ expect(f.close).toHaveBeenCalled();
+ expect(f.cdp.send).toHaveBeenCalledExactlyOnceWith(5, "Page.captureScreenshot", {
+ format: "jpeg",
+ quality: 50,
+ fromSurface: true,
+ captureBeyondViewport: false,
+ });
+ });
+ it("skips polling before any browser work when Chrome still has a screenshot pending", async () => {
+ const f = fixture();
+ vi.mocked(f.cdp.hasPendingScreenshot).mockReturnValue(true);
+ await expect(captureTaskPreview(f.manager, f.cdp, "pending")).rejects.toThrow("still running");
+ expect(f.cdp.ensureAttached).not.toHaveBeenCalled();
+ expect(f.cdp.send).not.toHaveBeenCalled();
+ });
+ it("does not capture an unowned active user tab", async () => {
+ const f = fixture();
+ f.task.agentCreatedTabs.clear();
+ await expect(captureTaskPreview(f.manager, f.cdp, "empty")).rejects.toThrow(
+ "Task tab unavailable",
+ );
+ expect(f.cdp.send).not.toHaveBeenCalled();
+ });
+ it("discards the result if authorization ends during capture", async () => {
+ const f = fixture();
+ vi.mocked(f.cdp.ensureAttached).mockImplementation(async () => {
+ f.task.agentCreatedTabs.clear();
+ });
+ await expect(captureTaskPreview(f.manager, f.cdp, "ended")).rejects.toThrow(
+ "Task ended during capture",
+ );
+ });
+ it("uses an owned tab when an unauthorized user tab is active", async () => {
+ const f = fixture();
+ vi.mocked(chrome.tabs.query).mockResolvedValue([
+ { id: 9, windowId: 10, active: true },
+ { id: 5, windowId: 10, active: false },
+ ] as chrome.tabs.Tab[]);
+ await expect(captureTaskPreview(f.manager, f.cdp, "user-active")).resolves.toMatchObject({
+ tab_id: 5,
+ });
+ expect(f.cdp.send).toHaveBeenCalledWith(5, "Page.captureScreenshot", expect.anything());
+ });
+ it("discards a frame after the debugger attachment changes", async () => {
+ const f = fixture();
+ vi.mocked(f.cdp.send).mockImplementation(async () => {
+ vi.mocked(f.cdp.getAttachmentId).mockReturnValue("replacement");
+ return { data: btoa("jpeg") } as never;
+ });
+ await expect(captureTaskPreview(f.manager, f.cdp, "replaced")).rejects.toThrow(
+ "Task ended during capture",
+ );
+ });
+});
diff --git a/apps/extension/src/lib/gateway-ui.ts b/apps/extension/src/lib/gateway-ui.ts
new file mode 100644
index 0000000..a020db8
--- /dev/null
+++ b/apps/extension/src/lib/gateway-ui.ts
@@ -0,0 +1,42 @@
+interface GatewayUI {
+ focus(sessionId: string): Promise<unknown>;
+ preview(sessionId: string): Promise<unknown>;
+ idle(sessionId: string): Promise<unknown>;
+}
+
+/** WeKnora's optional UI protocol, attached only to authenticated remote sockets.
+ * Register before WSTransport so these requests bypass native automation. */
+export function attachGatewayUI(socket: WebSocket, ui: GatewayUI): void {
+ socket.addEventListener("message", (event) => {
+ let request: { id?: unknown; method?: unknown; params?: { session_id?: unknown } };
+ try {
+ request = JSON.parse(event.data);
+ if (!request || typeof request !== "object") return;
+ } catch {
+ return;
+ }
+ const methods: Record<string, (sessionId: string) => Promise<unknown>> = {
+ "gateway.task_focus": (id) => ui.focus(id),
+ "gateway.task_preview": (id) => ui.preview(id),
+ "gateway.task_idle": (id) => ui.idle(id),
+ };
+ if (typeof request.method !== "string" || !Object.hasOwn(methods, request.method)) return;
+ event.stopImmediatePropagation();
+ if (typeof request.id !== "string" || !request.id) return;
+ const id = request.id;
+ const sessionId = request.params?.session_id;
+ const send = (body: object) => {
+ if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ id, ...body }));
+ };
+ if (typeof sessionId !== "string" || !sessionId) {
+ send({ error: { code: "invalid_params", message: "session_id is required" } });
+ return;
+ }
+ void Promise.resolve()
+ .then(() => methods[request.method as string]!(sessionId))
+ .then(
+ (result) => send({ result }),
+ () => send({ error: { code: "task_unavailable", message: "Browser task unavailable" } }),
+ );
+ });
+}
diff --git a/apps/extension/src/lib/task-activity.ts b/apps/extension/src/lib/task-activity.ts
new file mode 100644
index 0000000..91bc85a
--- /dev/null
+++ b/apps/extension/src/lib/task-activity.ts
@@ -0,0 +1,86 @@
+import type { SessionManager } from "@/session-manager/manager";
+
+interface Activity {
+ idle: boolean;
+ pending: Set<Promise<unknown>>;
+ releasing?: Promise<void>;
+}
+
+/** Coordinates UI captures with turn-end release and native session stop.
+ * State follows the session object, so deleted sessions cannot retain frames or fences. */
+export class TaskActivity {
+ private readonly states = new WeakMap<object, Activity>();
+ constructor(
+ private readonly manager: SessionManager,
+ private readonly detach: (sessionId: string) => Promise<void>,
+ ) {}
+
+ private state(sessionId: string): Activity | undefined {
+ const task = this.manager.get(sessionId);
+ if (!task?.remote) return undefined;
+ let state = this.states.get(task);
+ if (!state) {
+ state = { idle: false, pending: new Set() };
+ this.states.set(task, state);
+ }
+ return state;
+ }
+
+ private track<T>(state: Activity, run: () => Promise<T>): Promise<T> {
+ const work = Promise.resolve().then(run);
+ state.pending.add(work);
+ void work.then(
+ () => state.pending.delete(work),
+ () => state.pending.delete(work),
+ );
+ return work;
+ }
+
+ preview<T>(sessionId: string, run: () => Promise<T>): Promise<T> {
+ const state = this.state(sessionId);
+ if (!state || state.idle) return Promise.reject(new Error("Task preview is idle"));
+ return this.track(state, run);
+ }
+
+ async run<T>(
+ sessionId: string | undefined,
+ stopping: boolean,
+ run: () => Promise<T>,
+ ): Promise<T> {
+ if (!sessionId) return run();
+ const task = this.manager.get(sessionId);
+ const state = this.state(sessionId);
+ if (!state) return run();
+ if (stopping) {
+ await this.release(sessionId);
+ return run();
+ }
+ if (state.releasing) await state.releasing;
+ if (this.manager.get(sessionId) !== task) throw new Error("Task ended before operation");
+ state.idle = false;
+ return this.track(state, run);
+ }
+
+ release(sessionId: string): Promise<void> {
+ const state = this.state(sessionId);
+ if (!state) return Promise.resolve();
+ if (state.releasing) return state.releasing;
+ state.idle = true;
+ const work = (async () => {
+ // A screenshot's send() can auto-attach. Let every in-flight operation
+ // finish before detaching, and reject new previews throughout release.
+ await Promise.allSettled([...state.pending]);
+ await this.detach(sessionId);
+ })();
+ state.releasing = work;
+ void work.then(
+ () => {
+ state.releasing = undefined;
+ },
+ () => {
+ state.releasing = undefined;
+ },
+ );
+ return work;
+ }
+}
diff --git a/apps/extension/src/lib/task-preview.ts b/apps/extension/src/lib/task-preview.ts
new file mode 100644
index 0000000..3a1a361
--- /dev/null
+++ b/apps/extension/src/lib/task-preview.ts
@@ -0,0 +1,109 @@
+import type { ChromiumCdp } from "@/browser-driver/chromium-cdp";
+import { withExtensionOverlayHidden } from "@/lib/capture-suppress-bridge";
+import { isAgentControlledTab, type SessionManager } from "@/session-manager/manager";
+
+const captures = new Map<string, Promise<unknown>>();
+/** UI-only capture, outside the automation queue (including human-help waits).
+ * Captures only the task's concrete tab; never activates it or reads a user tab. */
+export function captureTaskPreview(
+ manager: SessionManager,
+ cdp: ChromiumCdp,
+ sessionId: string,
+): Promise<unknown> {
+ const pending = captures.get(sessionId);
+ if (pending) return pending;
+ const work = capture(manager, cdp, sessionId).finally(() => captures.delete(sessionId));
+ captures.set(sessionId, work);
+ return work;
+}
+async function capture(manager: SessionManager, cdp: ChromiumCdp, sessionId: string) {
+ const task = manager.get(sessionId);
+ if (!task?.remote) throw new Error("Task unavailable");
+ const tabId = await taskTarget(manager, sessionId);
+ if (tabId === undefined || !isAgentControlledTab(task, tabId))
+ throw new Error("Task tab unavailable");
+ if (cdp.hasPendingScreenshot(tabId))
+ throw new Error("Previous screenshot is still running in Chrome");
+ const tab = await chrome.tabs.get(tabId);
+ cdp.trackSessionTab(sessionId, tabId);
+ await cdp.ensureAttached(tabId);
+ if (manager.get(sessionId) !== task || !isAgentControlledTab(task, tabId))
+ throw new Error("Task ended during capture");
+ const attachment = cdp.getAttachmentId(tabId);
+ const revision = task.refStore.documentRevision(tabId);
+ const shot = await withExtensionOverlayHidden(
+ tabId,
+ async () => {
+ // captureBeyondViewport=false already limits the image to the viewport.
+ // Avoid a separate layout read on every UI poll; resize the bitmap below.
+ return cdp.send<{ data: string }>(tabId, "Page.captureScreenshot", {
+ format: "jpeg",
+ quality: 50,
+ fromSurface: true,
+ captureBeyondViewport: false,
+ });
+ },
+ (id, message) => chrome.tabs.sendMessage(id, message),
+ );
+ if (
+ manager.get(sessionId) !== task ||
+ !isAgentControlledTab(task, tabId) ||
+ cdp.getAttachmentId(tabId) !== attachment ||
+ task.refStore.documentRevision(tabId) !== revision
+ )
+ throw new Error("Task ended during capture");
+ // Viewport screenshots may use physical display pixels; HiDPI displays can
+ // return larger bitmaps. Bound the actual encoded image to the preview width.
+ let data = shot.data;
+ const bitmap = await createImageBitmap(
+ new Blob([Uint8Array.from(atob(data), (c) => c.charCodeAt(0))], { type: "image/jpeg" }),
+ );
+ try {
+ if (bitmap.width > 640) {
+ const canvas = new OffscreenCanvas(
+ 640,
+ Math.max(1, Math.round((bitmap.height * 640) / bitmap.width)),
+ );
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Preview canvas unavailable");
+ context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
+ const jpeg = await canvas.convertToBlob({ type: "image/jpeg", quality: 0.5 });
+ data = btoa(
+ Array.from(new Uint8Array(await jpeg.arrayBuffer()), (b) => String.fromCharCode(b)).join(
+ "",
+ ),
+ );
+ }
+ } finally {
+ bitmap.close();
+ }
+ if (
+ manager.get(sessionId) !== task ||
+ !isAgentControlledTab(task, tabId) ||
+ cdp.getAttachmentId(tabId) !== attachment ||
+ task.refStore.documentRevision(tabId) !== revision
+ )
+ throw new Error("Task ended during capture");
+ return {
+ image_base64: data,
+ format: "jpeg",
+ tab_id: tabId,
+ title: tab.title ?? "",
+ captured_at: new Date().toISOString(),
+ };
+}
+
+/** Use the active owned tab, or another owned tab when the user has selected
+ * an unauthorized page. Window membership alone never grants access. */
+export async function taskTarget(manager: SessionManager, sessionId: string): Promise<number> {
+ const task = manager.get(sessionId);
+ if (!task?.remote) throw new Error("Task unavailable");
+ const tabs = await chrome.tabs.query({ windowId: task.agentWindowId });
+ if (manager.get(sessionId) !== task) throw new Error("Task unavailable");
+ const owned = tabs.filter(
+ (tab) => typeof tab.id === "number" && isAgentControlledTab(task, tab.id),
+ );
+ const tabId = (owned.find((tab) => tab.active) ?? owned[0])?.id;
+ if (tabId === undefined) throw new Error("Task tab unavailable");
+ return tabId;
+}
diff --git a/apps/extension/src/tools/dispatcher.ts b/apps/extension/src/tools/dispatcher.ts
index fdac85d..0726f27 100644
--- a/apps/extension/src/tools/dispatcher.ts
+++ b/apps/extension/src/tools/dispatcher.ts
@@ -1,5 +1,6 @@
import type { InteractionPreferenceStore } from "@/lib/interaction-preferences";
import { OVERLAY_AUTOMATION_BYPASS } from "@/lib/overlay-bridge";
+import type { TaskActivity } from "@/lib/task-activity";
import { ScreenshotExports } from "@/long-screenshot/exports";
import type { SessionManager } from "@/session-manager/manager";
import type { Transport } from "@/transport/transport";
@@ -129,6 +130,7 @@ interface HoverLatchScope {
}
export interface DispatcherDeps {
+ taskActivity?: TaskActivity;
transport: Transport;
sessions: SessionManager;
cdp?: DispatcherCdpRunner;
@@ -168,6 +170,7 @@ export interface DispatcherDeps {
* takes the fast path.
*/
export class ToolDispatcher {
+ private readonly taskActivity?: TaskActivity;
private readonly transport: Transport;
private readonly sessions: SessionManager;
private screenshotExports: ScreenshotExports;
@@ -191,6 +194,7 @@ export class ToolDispatcher {
readonly inflightAbortControllers = new Map<string, AbortController>();
constructor(deps: DispatcherDeps) {
+ this.taskActivity = deps.taskActivity;
this.transport = deps.transport;
this.sessions = deps.sessions;
this.screenshotExports = new ScreenshotExports((id) => this.sessions.has(id));
@@ -275,7 +279,14 @@ export class ToolDispatcher {
} catch {
/* The daemon still has the original operation metadata. */
}
- const result = await this.invoke(req, ac.signal);
+ const invoke = () => this.invoke(req, ac.signal);
+ const result = this.taskActivity
+ ? await this.taskActivity.run(
+ (req.params as { session_id?: string } | undefined)?.session_id,
+ req.method === "tool.session_stop",
+ invoke,
+ )
+ : await invoke();
if (isRpcError(result)) {
body = { id: req.id, error: classifyCdpError(result) };
} else {
@@ -854,6 +865,12 @@ export class ToolDispatcher {
);
}
+ async releaseTaskControl(sessionId: string): Promise<void> {
+ await this.releaseHoverLatch(sessionId);
+ this.sessions.get(sessionId)?.refStore.clear();
+ await this.cdp?.detachSession(sessionId);
+ }
+
private async releaseHoverLatch(sessionId?: string, tabId?: number): Promise<void> {
const matchesScope = (entrySessionId: string, entryTabId: number): boolean => {
if (sessionId !== undefined && entrySessionId !== sessionId) return false;

View File

@ -0,0 +1,102 @@
diff --git a/packages/vom/src/__tests__/render.test.ts b/packages/vom/src/__tests__/render.test.ts
index 0223a80..9554cf6 100644
--- a/packages/vom/src/__tests__/render.test.ts
+++ b/packages/vom/src/__tests__/render.test.ts
@@ -52,6 +52,31 @@ describe("renderVom single-layer page", () => {
expect(out.text).toContain('@e1 checkbox "Subscribe"' + marker + ' ="on"');
expect(out.refs).toHaveLength(1);
});
+ it("does not rescan every earlier row for repeated action context", () => {
+ const count = 600;
+ let nameReads = 0;
+ const nodes = [node({ id: 1, role: "RootWebArea" })];
+ for (let i = 0; i < count; i++) {
+ const label = node({ id: 2 + i * 2, parentId: 1, role: "StaticText" });
+ Object.defineProperty(label, "name", {
+ enumerable: true,
+ get() {
+ nameReads++;
+ return `Record ${i}`;
+ },
+ });
+ nodes.push(
+ label,
+ node({ id: 3 + i * 2, parentId: 1, tag: "button", role: "button", name: "Open" }),
+ );
+ }
+ const out = renderVom(scene(nodes));
+ expect(out.refs).toHaveLength(count);
+ expect(out.refs[0].ctx).toBe("Record 0");
+ expect(out.refs[count - 1].ctx).toBe(`Record ${count - 3}`);
+ // Count semantic reads rather than asserting a machine-dependent duration.
+ expect(nameReads).toBeLessThan(count * 100);
+ });
it("does not derive handle context across frame scopes", () => {
const out = renderVom(
diff --git a/packages/vom/src/render.ts b/packages/vom/src/render.ts
index 77c10c6..c66e65d 100644
--- a/packages/vom/src/render.ts
+++ b/packages/vom/src/render.ts
@@ -614,11 +614,32 @@ function collectSameContainerContext(
let guard = 0;
while (parentId !== null && guard <= state.parentMap.size) {
const siblings = state.children.get(parentId) ?? [];
- for (const sibling of siblings) {
- if (sibling.id === childId) break;
- collectWeakLabelsFromSubtree(sibling, node, nodeName, state, labels);
- while (labels.length > MAX_HANDLE_CONTEXT_ITEMS) labels.shift();
+ const end = state.siblingIndex.get(childId) ?? siblings.length;
+ let cache = state.siblingContextCache.get(parentId);
+ if (!cache) {
+ cache = new Map();
+ state.siblingContextCache.set(parentId, cache);
}
+ // The subtree collector depends on scope, target name and incoming labels.
+ // Include all three so descendants arriving from different containers retain
+ // the original context semantics. DFS visits sibling prefixes in order.
+ const key = JSON.stringify([node.contextScopeId, nodeName, labels]);
+ let prefix = cache.get(key);
+ if (!prefix || prefix.nextIndex > end) prefix = { nextIndex: 0, labels: [...labels] };
+ for (; prefix.nextIndex < end; prefix.nextIndex++) {
+ collectWeakLabelsFromSubtree(
+ siblings[prefix.nextIndex],
+ node,
+ nodeName,
+ state,
+ prefix.labels,
+ );
+ while (prefix.labels.length > MAX_HANDLE_CONTEXT_ITEMS) prefix.labels.shift();
+ }
+ labels.splice(0, labels.length, ...prefix.labels);
+ // Bound retained variants on pages with many distinct action names.
+ if (!cache.has(key) && cache.size >= 64) cache.delete(cache.keys().next().value!);
+ cache.set(key, prefix);
const parent = state.nodesById.get(parentId);
if (!parent || !sharesContextScope(node, parent) || isContextBoundary(parent)) break;
@@ -791,6 +812,8 @@ interface RenderState {
redactValues: boolean;
truncated: boolean;
children: Map<number | null, VomNode[]>;
+ siblingIndex: Map<number, number>;
+ siblingContextCache: Map<number, Map<string, { nextIndex: number; labels: string[] }>>;
parentMap: Map<number, number | null>;
nodesById: Map<number, VomNode>;
domContextIndex: DomContextIndex;
@@ -907,8 +930,15 @@ function createRenderState(
activeScopeBlocks: ActiveScopeBlock[],
): RenderState {
const children = buildChildren(nodes);
+ const siblingIndex = new Map<number, number>();
+ for (const siblings of children.values()) {
+ for (let index = 0; index < siblings.length; index++)
+ siblingIndex.set(siblings[index].id, index);
+ }
const state: RenderState = {
visualAncestors: new Set(),
+ siblingIndex,
+ siblingContextCache: new Map(),
lines: [...initialLines],
refs: [],
nextRef: 1,

View File

@ -0,0 +1,338 @@
diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts
index 1a9a788..5a2f0ef 100644
--- a/apps/extension/src/entrypoints/background.ts
+++ b/apps/extension/src/entrypoints/background.ts
@@ -339,10 +339,12 @@ export default defineBackground(() => {
},
...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),
deps: {
- // Skip every Agent Window when choosing where to render the
- // overlay — Agent Windows boot on about:blank, which has no
- // content script, so they cannot surface an authorization decision.
- isAgentWindowId: (windowId) => sessions.findByWindowId(windowId) !== null,
+ // The requesting window may host consent for an in-place borrow.
+ // Candidate selection still excludes about:blank/restricted pages.
+ isAgentWindowId: (windowId) => {
+ const owner = sessions.findByWindowId(windowId);
+ return owner !== null && owner.sessionId !== ctx.sessionId;
+ },
// Resolve i18n strings per-borrow so language switches take effect
// without re-creating the dispatcher.
notificationCopy: makeBorrowNotificationCopy(),
diff --git a/apps/extension/src/session-manager/__tests__/task-popups.test.ts b/apps/extension/src/session-manager/__tests__/task-popups.test.ts
new file mode 100644
index 0000000..f859bdc
--- /dev/null
+++ b/apps/extension/src/session-manager/__tests__/task-popups.test.ts
@@ -0,0 +1,79 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { SessionManager } from "../manager";
+import { withTaskPopups } from "../task-popups";
+
+afterEach(() => vi.unstubAllGlobals());
+async function fixture() {
+ let next = 10;
+ const manager = new SessionManager({
+ remote: () => true,
+ agentWindow: {
+ create: async () => next++,
+ remove: vi.fn(async () => {}),
+ ensureActiveTab: async (id) => id,
+ },
+ });
+ const task = await manager.start("one");
+ const other = await manager.start("two");
+ const tabs = new Map<number, { id: number; windowId: number; active?: boolean }>([
+ [10, { id: 10, windowId: 10, active: true }],
+ [11, { id: 11, windowId: 11, active: true }],
+ ]);
+ const listeners = new Set<(event: { sourceTabId: number; tabId: number }) => void>();
+ const move = vi.fn(async (id: number, props: { windowId: number }) =>
+ Object.assign(tabs.get(id)!, props),
+ );
+ vi.stubGlobal("chrome", {
+ tabs: { query: async () => [tabs.get(10)], get: async (id: number) => tabs.get(id), move },
+ webNavigation: {
+ onCreatedNavigationTarget: {
+ addListener: (fn: (event: { sourceTabId: number; tabId: number }) => void) =>
+ listeners.add(fn),
+ removeListener: (fn: (event: { sourceTabId: number; tabId: number }) => void) =>
+ listeners.delete(fn),
+ },
+ },
+ });
+ const create = (sourceTabId: number, tabId: number, windowId = 10) => {
+ tabs.set(tabId, { id: tabId, windowId });
+ for (const fn of listeners) fn({ sourceTabId, tabId });
+ };
+ return { manager, task, other, tabs, listeners, create, move };
+}
+describe("action-scoped popup ownership", () => {
+ it("claims noopener/nested targets and moves a popup window into its task", async () => {
+ const f = await fixture();
+ await withTaskPopups(f.manager, { session_id: "one" }, async () => {
+ f.create(10, 20);
+ f.create(20, 21, 200);
+ f.create(11, 22); // Another task's source.
+ f.tabs.set(23, { id: 23, windowId: 10 }); // User-created/moved tab, no navigation event.
+ });
+ expect(f.task.agentCreatedTabs).toEqual(new Set([10, 20, 21]));
+ expect(f.move).toHaveBeenCalledWith(21, { windowId: 10, index: -1 });
+ expect(f.listeners.size).toBe(0);
+ f.create(10, 24); // Outside an agent action.
+ expect(f.task.agentCreatedTabs.has(24)).toBe(false);
+ });
+ it("cannot take a tab from another task or use an unauthorized source", async () => {
+ const f = await fixture();
+ await withTaskPopups(f.manager, { session_id: "one", tab_id: 11 }, async () =>
+ f.create(11, 30),
+ );
+ await withTaskPopups(f.manager, { session_id: "one" }, async () => f.create(10, 11, 11));
+ expect(f.task.agentCreatedTabs).toEqual(new Set([10]));
+ expect(f.other.agentCreatedTabs).toEqual(new Set([11]));
+ });
+ it("cleans listeners on failure and rejects targets after source authorization ends", async () => {
+ const f = await fixture();
+ await expect(
+ withTaskPopups(f.manager, { session_id: "one" }, async () => {
+ f.task.agentCreatedTabs.delete(10);
+ f.create(10, 20);
+ throw new Error("input failed");
+ }),
+ ).rejects.toThrow("input failed");
+ expect(f.task.agentCreatedTabs.size).toBe(0);
+ expect(f.listeners.size).toBe(0);
+ });
+});
diff --git a/apps/extension/src/session-manager/task-popups.ts b/apps/extension/src/session-manager/task-popups.ts
new file mode 100644
index 0000000..53db1bf
--- /dev/null
+++ b/apps/extension/src/session-manager/task-popups.ts
@@ -0,0 +1,72 @@
+import { isAgentControlledTab, type SessionManager } from "./manager";
+
+/** Attribute only Chrome-reported navigation targets created during an agent
+ * action on an owned source. Window membership and openerTabId are insufficient.
+ * Delayed/unattributed popups can still use the ordinary consent-based borrow. */
+export async function withTaskPopups<T>(
+ manager: SessionManager,
+ params: { session_id?: string; tab_id?: number },
+ run: () => Promise<T>,
+ onClaimed?: (tabId: number, windowId: number) => void,
+): Promise<T> {
+ const task = params.session_id ? manager.get(params.session_id) : null;
+ const events = globalThis.chrome?.webNavigation?.onCreatedNavigationTarget;
+ if (!task?.remote || !events) return run();
+ const source =
+ params.tab_id ??
+ (
+ await chrome.tabs.query({
+ windowId: task.agentWindowId,
+ active: true,
+ })
+ )[0]?.id;
+ if (source === undefined || !isAgentControlledTab(task, source)) return run();
+ const sources = new Set([source]);
+ const pending = new Set<Promise<void>>();
+ const live = () => manager.get(task.sessionId) === task && !manager.isWindowCloseExpected(task);
+ const created = ({ sourceTabId, tabId }: { sourceTabId: number; tabId: number }) => {
+ if (
+ !live() ||
+ !sources.has(sourceTabId) ||
+ !isAgentControlledTab(task, sourceTabId) ||
+ manager.list().some((other) => isAgentControlledTab(other, tabId))
+ )
+ return;
+ // Record ownership synchronously so a nested popup and cleanup see it.
+ task.agentCreatedTabs.add(tabId);
+ sources.add(tabId);
+ const work = (async () => {
+ try {
+ let tab = await chrome.tabs.get(tabId);
+ if (!live() || !isAgentControlledTab(task, tabId)) return;
+ const other = manager.findByWindowId(tab.windowId);
+ if (other && other !== task) {
+ task.agentCreatedTabs.delete(tabId);
+ sources.delete(tabId);
+ return;
+ }
+ if (tab.windowId !== task.agentWindowId) {
+ await chrome.tabs.move(tabId, { windowId: task.agentWindowId, index: -1 });
+ tab = await chrome.tabs.get(tabId);
+ }
+ if (!live() || !isAgentControlledTab(task, tabId)) return;
+ onClaimed?.(tabId, tab.windowId);
+ } catch (error) {
+ // Preserve a live tab's ownership if moving it failed, so stop can clean
+ // it up; Chrome's removal event forgets tabs that have already closed.
+ console.warn("[bsk] task popup setup failed", error);
+ }
+ })();
+ pending.add(work);
+ void work.then(() => pending.delete(work));
+ };
+ events.addListener(created);
+ try {
+ return await run();
+ } finally {
+ // Chrome can deliver this event just after the CDP input acknowledgement.
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ events.removeListener(created);
+ await Promise.all(pending);
+ }
+}
diff --git a/apps/extension/src/tools/__tests__/tabs.test.ts b/apps/extension/src/tools/__tests__/tabs.test.ts
index dc9fdb5..ae9534d 100644
--- a/apps/extension/src/tools/__tests__/tabs.test.ts
+++ b/apps/extension/src/tools/__tests__/tabs.test.ts
@@ -297,7 +297,7 @@ describe("handleTabCreate", () => {
});
describe("handleTabClose", () => {
- it("does not infer remote popup ownership from its opener and explains how to borrow it", async () => {
+ it("does not infer ownership from opener metadata but permits an approved in-place borrow", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]), remote: () => true });
const ctx = await sm.start("aa11");
const state: FakeTabState = {
@@ -309,6 +309,15 @@ describe("handleTabClose", () => {
expect(
await handleTabClose(sm, { session_id: "aa11", tab_id: 5 }, { tabs: api }),
).toMatchObject({ code: "permission_denied" });
+ expect(
+ await handleTabBorrow(
+ sm,
+ { session_id: "aa11", tab_id: 5 },
+ { tabs: api, approveBorrow: async () => false },
+ ),
+ ).toMatchObject({ code: "cancelled" });
+ expect(ctx.borrowedTabs.has(5)).toBe(false);
+ expect(ctx.agentCreatedTabs.has(5)).toBe(false);
const approval = vi.fn(async () => true);
expect(
await handleTabBorrow(
@@ -316,13 +325,32 @@ describe("handleTabClose", () => {
{ session_id: "aa11", tab_id: 5 },
{ tabs: api, approveBorrow: approval },
),
- ).toMatchObject({
- code: "invalid_params",
- message: expect.stringContaining("regular browser window"),
- });
+ ).toMatchObject({ tab_id: 5, original_window_id: 100, agent_window_id: 100 });
expect(ctx.agentCreatedTabs.has(5)).toBe(false);
+ expect(ctx.borrowedTabs.has(5)).toBe(true);
expect(spies.remove).not.toHaveBeenCalled();
- expect(approval).not.toHaveBeenCalled();
+ expect(spies.move).not.toHaveBeenCalled();
+ expect(approval).toHaveBeenCalledOnce();
+ const windows = makeWindowsApi(state).api;
+ const release = vi.fn(async () => {});
+ expect(
+ await handleTabReturn(
+ sm,
+ { session_id: "aa11", tab_id: 5 },
+ {
+ tabs: api,
+ windows,
+ cdp: { releaseSessionTab: release },
+ agentOverlayReset: { resetAgentOverlays: vi.fn(async () => {}) },
+ },
+ ),
+ ).toMatchObject({ tab_id: 5, returned_to_window_id: 100 });
+ expect(release).toHaveBeenCalledWith("aa11", 5);
+ expect(ctx.borrowedTabs.has(5)).toBe(false);
+ expect(state.tabs.has(5)).toBe(true);
+ expect(
+ await handleTabSelect(sm, { session_id: "aa11", tab_id: 5 }, { tabs: api }),
+ ).toMatchObject({ code: "permission_denied" });
});
it("removes a tab inside the Agent Window", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
diff --git a/apps/extension/src/tools/dispatcher.ts b/apps/extension/src/tools/dispatcher.ts
index 0726f27..8afdedf 100644
--- a/apps/extension/src/tools/dispatcher.ts
+++ b/apps/extension/src/tools/dispatcher.ts
@@ -3,6 +3,7 @@ import { OVERLAY_AUTOMATION_BYPASS } from "@/lib/overlay-bridge";
import type { TaskActivity } from "@/lib/task-activity";
import { ScreenshotExports } from "@/long-screenshot/exports";
import type { SessionManager } from "@/session-manager/manager";
+import { withTaskPopups } from "@/session-manager/task-popups";
import type { Transport } from "@/transport/transport";
import type {
BlurParams,
@@ -279,7 +280,25 @@ export class ToolDispatcher {
} catch {
/* The daemon still has the original operation metadata. */
}
- const invoke = () => this.invoke(req, ac.signal);
+ const createsPopup = [
+ "tool.click",
+ "tool.press_key",
+ "tool.evaluate",
+ "tool.navigate",
+ "tool.navigate_back",
+ "tool.navigate_forward",
+ "tool.fill",
+ "tool.select",
+ ].includes(req.method);
+ const invoke = () =>
+ createsPopup
+ ? withTaskPopups(
+ this.sessions,
+ (req.params ?? {}) as { session_id?: string; tab_id?: number },
+ () => this.invoke(req, ac.signal),
+ this.onAgentTabClaimed,
+ )
+ : this.invoke(req, ac.signal);
const result = this.taskActivity
? await this.taskActivity.run(
(req.params as { session_id?: string } | undefined)?.session_id,
diff --git a/apps/extension/src/tools/tabs.ts b/apps/extension/src/tools/tabs.ts
index 5e90e6b..2570c74 100644
--- a/apps/extension/src/tools/tabs.ts
+++ b/apps/extension/src/tools/tabs.ts
@@ -646,13 +646,12 @@ async function validateBorrowTarget(
if (typeof tab.id !== "number" || typeof tab.windowId !== "number") {
return { code: "not_found", message: `tab ${tabId} not found` };
}
- if (tab.windowId === ctx.agentWindowId) {
+ // Remote unowned tabs can request normal approval in place. Merely moving
+ // a tab into this window never authorizes it; confirmation still runs below.
+ if (tab.windowId === ctx.agentWindowId && (!ctx.remote || isAgentControlledTab(ctx, tabId))) {
return {
code: "invalid_params",
- message:
- ctx.remote && !isAgentControlledTab(ctx, tabId)
- ? `tab_borrow: tab ${tabId} is not authorized and already lives in the Agent Window; move it to a regular browser window, then borrow it`
- : `tab_borrow: tab ${tabId} already lives in the Agent Window`,
+ message: `tab_borrow: tab ${tabId} already lives in the Agent Window`,
};
}
for (const s of manager.list()) {
@@ -772,14 +771,17 @@ async function executeBorrowCore(
const originalWindowId = currentTab.windowId;
const originalIndex = typeof currentTab.index === "number" ? currentTab.index : 0;
- const moveErr = await moveTabForBorrow(
- p.tabsApi,
- p.tabId,
- p.ctx.agentWindowId,
- originalWindowId,
- originalIndex,
- p.signal,
- );
+ const moveErr =
+ originalWindowId === p.ctx.agentWindowId
+ ? null
+ : await moveTabForBorrow(
+ p.tabsApi,
+ p.tabId,
+ p.ctx.agentWindowId,
+ originalWindowId,
+ originalIndex,
+ p.signal,
+ );
if (moveErr) return moveErr;
return { originalWindowId, originalIndex };

View File

@ -0,0 +1,174 @@
diff --git a/apps/extension/src/tools/__tests__/tabs.test.ts b/apps/extension/src/tools/__tests__/tabs.test.ts
index ae9534d..71a0d56 100644
--- a/apps/extension/src/tools/__tests__/tabs.test.ts
+++ b/apps/extension/src/tools/__tests__/tabs.test.ts
@@ -297,6 +297,99 @@ describe("handleTabCreate", () => {
});
describe("handleTabClose", () => {
+ async function remoteCloseFixture() {
+ const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]), remote: () => true });
+ const ctx = await sm.start("aa11");
+ ctx.agentCreatedTabs.clear();
+ ctx.agentCreatedTabs.add(5);
+ const state: FakeTabState = {
+ tabs: new Map([[5, { id: 5, windowId: 100 } as chrome.tabs.Tab]]),
+ nextTabId: 50,
+ windowsClosed: new Set(),
+ };
+ const { api, spies } = makeTabMutationApi(state);
+ const query = vi.fn(async (info: chrome.tabs.QueryInfo) =>
+ [...state.tabs.values()].filter((tab) => tab.windowId === info.windowId),
+ );
+ const claimed = vi.fn();
+ const deps = { tabs: api, tabsQuery: { query }, onAgentTabClaimed: claimed };
+ const close = (signal?: AbortSignal) =>
+ handleTabClose(sm, { session_id: "aa11", tab_id: 5 }, { ...deps, signal });
+ return { ctx, state, spies, query, claimed, close };
+ }
+
+ it("keeps the remote window alive when the agent closes its last tab", async () => {
+ const { ctx, state, spies, claimed, close } = await remoteCloseFixture();
+ spies.remove.mockImplementation(async (id: number) => {
+ state.tabs.delete(id);
+ if (state.tabs.size === 0) state.windowsClosed.add(100);
+ });
+ expect(await close()).toEqual({ tab_id: 5 });
+ expect(state.windowsClosed.size).toBe(0);
+ expect([...state.tabs.keys()]).toEqual([50]);
+ expect([...ctx.agentCreatedTabs]).toEqual([50]);
+ expect(spies.create).toHaveBeenCalledWith({ windowId: 100, url: "about:blank", active: false });
+ expect(claimed).toHaveBeenCalledWith(50, 100);
+ });
+
+ it("does not create a placeholder when another, even unowned, tab keeps the window open", async () => {
+ const { ctx, state, spies, close } = await remoteCloseFixture();
+ state.tabs.set(6, { id: 6, windowId: 100 } as chrome.tabs.Tab);
+ expect(await close()).toEqual({ tab_id: 5 });
+ expect(spies.create).not.toHaveBeenCalled();
+ expect([...state.tabs.keys()]).toEqual([6]);
+ expect(ctx.agentCreatedTabs.has(6)).toBe(false);
+ });
+
+ it("does not close the last tab if creating its replacement fails", async () => {
+ const { ctx, state, spies, close } = await remoteCloseFixture();
+ spies.create.mockRejectedValueOnce(new Error("cannot create"));
+ expect(await close()).toMatchObject({ code: "protocol_error", message: "cannot create" });
+ expect(spies.remove).not.toHaveBeenCalled();
+ expect([...state.tabs.keys()]).toEqual([5]);
+ expect([...ctx.agentCreatedTabs]).toEqual([5]);
+ });
+
+ it("honors a human interrupt while querying the remote window", async () => {
+ const { state, spies, query, close } = await remoteCloseFixture();
+ const controller = new AbortController();
+ query.mockImplementationOnce(async () => {
+ controller.abort();
+ return [...state.tabs.values()];
+ });
+ expect(await close(controller.signal)).toMatchObject({ code: "cancelled" });
+ expect(spies.create).not.toHaveBeenCalled();
+ expect(spies.remove).not.toHaveBeenCalled();
+ });
+
+ it("cleans the replacement and preserves the original on interruption during creation", async () => {
+ const { ctx, state, spies, claimed, close } = await remoteCloseFixture();
+ const controller = new AbortController();
+ spies.create.mockImplementationOnce(async () => {
+ const tab = { id: 50, windowId: 100 } as chrome.tabs.Tab;
+ state.tabs.set(50, tab);
+ controller.abort();
+ return tab;
+ });
+ expect(await close(controller.signal)).toMatchObject({ code: "cancelled" });
+ expect([...state.tabs.keys()]).toEqual([5]);
+ expect([...ctx.agentCreatedTabs]).toEqual([5]);
+ expect(claimed).not.toHaveBeenCalled();
+ expect(spies.remove).toHaveBeenCalledExactlyOnceWith(50);
+ });
+
+ it.each([
+ false,
+ true,
+ ])("handles failed close with failed placeholder cleanup=%s", async (cleanupFails) => {
+ const { ctx, state, spies, close } = await remoteCloseFixture();
+ spies.remove.mockRejectedValueOnce(new Error("cannot close"));
+ if (cleanupFails) spies.remove.mockRejectedValueOnce(new Error("cannot clean up"));
+ expect(await close()).toMatchObject({ code: "protocol_error", message: "cannot close" });
+ expect([...state.tabs.keys()]).toEqual(cleanupFails ? [5, 50] : [5]);
+ expect([...ctx.agentCreatedTabs]).toEqual(cleanupFails ? [5, 50] : [5]);
+ });
+
it("does not infer ownership from opener metadata but permits an approved in-place borrow", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]), remote: () => true });
const ctx = await sm.start("aa11");
diff --git a/apps/extension/src/tools/dispatcher.ts b/apps/extension/src/tools/dispatcher.ts
index 8afdedf..3e167b1 100644
--- a/apps/extension/src/tools/dispatcher.ts
+++ b/apps/extension/src/tools/dispatcher.ts
@@ -414,7 +414,11 @@ export class ToolDispatcher {
case "tool.tab_close":
return this.withHoverReleaseForRequest(
req.params as TabCloseParams,
- () => handleTabClose(this.sessions, req.params as TabCloseParams, { signal }),
+ () =>
+ handleTabClose(this.sessions, req.params as TabCloseParams, {
+ signal,
+ onAgentTabClaimed: this.onAgentTabClaimed,
+ }),
signal,
);
case "tool.tab_select":
diff --git a/apps/extension/src/tools/tabs.ts b/apps/extension/src/tools/tabs.ts
index 2570c74..43cfb12 100644
--- a/apps/extension/src/tools/tabs.ts
+++ b/apps/extension/src/tools/tabs.ts
@@ -282,6 +282,8 @@ export async function handleTabList(
export interface TabManagementDeps {
tabs?: TabMutationApi;
+ tabsQuery?: Pick<ChromeTabsApi, "query">;
+ onAgentTabClaimed?: (tabId: number, windowId: number) => void;
windows?: ChromeWindowsApi;
/** Abort hook (M10 will wire the full chain). */
signal?: AbortSignal;
@@ -540,12 +542,39 @@ export async function handleTabClose(
if (aborted(deps.signal, "tab_close")) {
return { code: "cancelled", message: "tab_close aborted" };
}
+ let placeholder: number | undefined;
try {
+ if (ctx.remote) {
+ const tabs = await (deps.tabsQuery ?? chromeTabsApi).query({ windowId: ctx.agentWindowId });
+ if (aborted(deps.signal, "tab_close"))
+ return { code: "cancelled", message: "tab_close aborted" };
+ if (tabs.length === 1 && tabs[0]?.id === params.tab_id) {
+ // Keep the session window alive until session.stop. Otherwise Chrome
+ // reports the agent's last-tab removal as a user-closed window, which
+ // pauses the next turn. This concrete tab is owned and cleaned normally.
+ const replacement = await createTabAndCleanup(ctx, deps, {
+ windowId: ctx.agentWindowId,
+ url: "about:blank",
+ active: false,
+ });
+ if (isRpcError(replacement)) return replacement;
+ placeholder = replacement.id;
+ deps.onAgentTabClaimed?.(placeholder, ctx.agentWindowId);
+ }
+ }
await getTabsApi(deps).remove(params.tab_id);
// Keep the tracking set accurate so session_stop won't try to close a
// tab that's already gone (design §3.1).
ctx.agentCreatedTabs.delete(params.tab_id);
} catch (err) {
+ if (placeholder !== undefined) {
+ try {
+ await getTabsApi(deps).remove(placeholder);
+ ctx.agentCreatedTabs.delete(placeholder);
+ } catch {
+ /* Retain the claim so session.stop can retry cleanup. */
+ }
+ }
return {
code: "protocol_error",
message: err instanceof Error ? err.message : String(err),

View File

@ -0,0 +1,156 @@
diff --git a/apps/extension/src/tools/__tests__/navigation.test.ts b/apps/extension/src/tools/__tests__/navigation.test.ts
index 921771e..ca82df7 100644
--- a/apps/extension/src/tools/__tests__/navigation.test.ts
+++ b/apps/extension/src/tools/__tests__/navigation.test.ts
@@ -376,6 +376,43 @@ describe("handleNavigate", () => {
expect(res.reached).toBe("load");
});
+ it("follows a committed main-frame redirect without accepting stale or child-frame events", async () => {
+ const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
+ await sm.start("aa11");
+ const fake = makeFakeCdp({ beforeLoaderId: "old", navigateLoaderId: "initial" });
+ let finished = false;
+ const navP = handleNavigate(
+ sm,
+ {
+ session_id: "aa11",
+ url: "https://example.com/redirect",
+ wait_until: "domcontentloaded",
+ timeout_ms: 1000,
+ },
+ { cdp: fake.cdp, tabsApi: fake.tabsApi },
+ ).then((result) => {
+ finished = true;
+ return result;
+ });
+ await vi.waitFor(() =>
+ expect(fake.sent.some((call) => call.method === "Page.navigate")).toBe(true),
+ );
+ fake.fireFrameNavigated("child", "child-loader");
+ fake.fireLifecycle("DOMContentLoaded", "frame-1", "child-loader");
+ fake.fireLifecycle("DOMContentLoaded", "frame-1", "redirect");
+ await Promise.resolve();
+ expect(finished).toBe(false);
+ fake.fireFrameNavigated("frame-1", "redirect");
+ fake.fireLifecycle("DOMContentLoaded", "frame-1", "initial");
+ fake.fireFrameNavigated("frame-1", "old");
+ fake.fireLifecycle("DOMContentLoaded", "frame-1", "old");
+ await Promise.resolve();
+ expect(finished).toBe(false);
+ fake.fireLifecycle("DOMContentLoaded", "frame-1", "redirect");
+ expect(await navP).toMatchObject({ reached: "domcontentloaded" });
+ expect(fake.listeners).toHaveLength(0);
+ });
+
it("returns reached=timeout when no matching lifecycle fires", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
await sm.start("aa11");
diff --git a/apps/extension/src/tools/navigation.ts b/apps/extension/src/tools/navigation.ts
index e40d724..58d3ea6 100644
--- a/apps/extension/src/tools/navigation.ts
+++ b/apps/extension/src/tools/navigation.ts
@@ -236,6 +236,13 @@ function startLifecycleWait(
const promise = new Promise<WaitOutcome>((resolve) => {
let settled = false;
let sawRelevantLifecycle = false;
+ // The Page.navigate reply describes the initial loader. A client-side
+ // redirect may commit a different document before that loader finishes.
+ // Only a top-level frameNavigated event may advance the expected loader.
+ let committedLoaderId = "";
+ const activeGuard = guard
+ ? { ...guard, loaderId: () => committedLoaderId || currentLoaderId(guard) }
+ : undefined;
let lastLifecycle: string | undefined;
let pendingLifecycle: { name: string; frameId?: string; loaderId?: string } | null = null;
let listenerSub: { dispose(): void } | null = null;
@@ -260,7 +267,7 @@ function startLifecycleWait(
eventFrameId?: string,
eventLoaderId?: string,
): boolean => {
- if (!eventLoaderIsRelevant(eventLoaderId, guard)) return false;
+ if (!eventLoaderIsRelevant(eventLoaderId, activeGuard)) return false;
if (!lifecycleEventMatchesFrame(eventFrameId)) return false;
noteRelevantLifecycle(name);
return true;
@@ -331,16 +338,19 @@ function startLifecycleWait(
if (settled) return;
if (source.tabId !== expectedTabId) return;
- if (targetName === "commit" && method === "Page.frameNavigated") {
+ if (method === "Page.frameNavigated") {
const p = params as { frame?: { id?: string; parentId?: string; loaderId?: string } };
+ if (p.frame?.parentId) return;
const expectedFrameId = currentFrameId();
if (expectedFrameId.length > 0) {
if (p.frame?.id !== expectedFrameId) return;
- } else if (p.frame?.parentId) {
- return;
+ }
+ if (guard && p.frame?.loaderId) {
+ if (p.frame.loaderId === guard.beforeLoaderId) return;
+ committedLoaderId = p.frame.loaderId;
}
if (!acceptLifecycleEvent("commit", p.frame?.id, p.frame?.loaderId)) return;
- finish({ reached: "match", lastLifecycle: "commit" });
+ if (targetName === "commit") finish({ reached: "match", lastLifecycle: "commit" });
return;
}
@@ -362,7 +372,7 @@ function startLifecycleWait(
}
return;
}
- if (!eventLoaderIsRelevant(p.loaderId, guard)) return;
+ if (!eventLoaderIsRelevant(p.loaderId, activeGuard)) return;
if (!lifecycleEventMatchesFrame(p.frameId)) return;
pendingLifecycle = { name: p.name, frameId: p.frameId, loaderId: p.loaderId };
return;
diff --git a/crates/bsk-cli/src/daemon/ipc.rs b/crates/bsk-cli/src/daemon/ipc.rs
index 69daf58..4695d48 100644
--- a/crates/bsk-cli/src/daemon/ipc.rs
+++ b/crates/bsk-cli/src/daemon/ipc.rs
@@ -793,7 +793,14 @@ fn tool_dispatch_transport_timeout(method: &Method, params: &Value) -> Result<Du
timeout.map(|timeout| {
if matches!(
method,
- Method::ToolUpload | Method::ToolDownload | Method::ToolRequestHelp
+ Method::ToolUpload
+ | Method::ToolDownload
+ | Method::ToolRequestHelp
+ | Method::ToolNavigate
+ | Method::ToolNavigateBack
+ | Method::ToolNavigateForward
+ | Method::ToolReload
+ | Method::ToolWaitForNavigation
) {
timeout.saturating_add(EXTENSION_RESPONSE_GRACE)
} else {
@@ -1820,12 +1827,27 @@ mod tests {
Method::ToolUpload,
Method::ToolDownload,
Method::ToolRequestHelp,
+ Method::ToolNavigate,
+ Method::ToolNavigateBack,
+ Method::ToolNavigateForward,
+ Method::ToolReload,
+ Method::ToolWaitForNavigation,
] {
let dispatch_timeout = tool_dispatch_transport_timeout(&method, &params).unwrap();
assert_eq!(dispatch_timeout, Duration::from_secs(62));
}
}
+ #[test]
+ fn default_navigation_deadline_allows_extension_timeout_response() {
+ for method in [Method::ToolNavigate, Method::ToolWaitForNavigation] {
+ assert_eq!(
+ tool_dispatch_transport_timeout(&method, &serde_json::json!({})).unwrap(),
+ DEFAULT_TOOL_TIMEOUT + EXTENSION_RESPONSE_GRACE
+ );
+ }
+ }
+
#[test]
fn extension_response_grace_does_not_change_other_tools() {
let params = serde_json::json!({

View File

@ -0,0 +1,99 @@
# BrowserSkill downstream patches
The extension is based on the official `ext-v0.3.0` release at
`75e2c64abaf4b7cc75682d94b0c1fd5db0cbd5e5`. The daemon is built with
`cargo build --locked --release -p bsk` from the same commit, recorded in `scripts/browserskill-release.json`. The published CLI 0.2.1
binary lacks `scroll_to`, `wheel`, `focus`, and `blur`; protocol handshake success
does not establish command compatibility. Native builds require Rust/Cargo and a C
compiler (plus CMake on Linux). Docker builds on the target architecture.
The patches include extension fixes and a daemon navigation-response deadline fix.
`scripts/build_browserskill.sh` applies the following patches in lexical order:
| Patch | Purpose | Removal condition |
| --- | --- | --- |
| `01-browser-read-reliability.patch` | Bound CDP reads, prevent overlapping timed-out screenshots, keep explicitly controlled remote pages rendering, reuse frame discovery configuration | Equivalent upstream behavior passes the background rendering and timeout regressions |
| `02-gateway-task-controls.patch` | WeKnora preview, focus, and idle side channel; coordinate screenshots and automation before releasing debugger attachments | Upstream provides equivalent UI and lifecycle APIs and WeKnora migrates to them |
| `03-vom-render-performance.patch` | Bound repeated sibling-context scans on pages with many repeated action buttons | Equivalent upstream rendering passes the semantic and work-count regression |
| `04-task-popup-ownership.patch` | Attribute navigation targets to the active agent action; allow consent-based in-place borrowing inside the task window | Upstream supports this popup lifecycle without weakening per-tab authorization |
| `05-last-tab-lifecycle.patch` | Keep a temporary owned blank tab when an agent closes the last remote task tab; normal session stop removes it | Upstream distinguishes agent last-tab cleanup from user window closure |
| `06-navigation-lifecycle.patch` | Follow committed main-frame redirect loaders; allow navigation lifecycle timeout results to arrive before the daemon transport deadline | Upstream passes redirect, stale-loader and visible-error timeout regressions |
Remote authentication, credential storage/migration, renewal, connection settings,
and dedicated Agent Windows use upstream code. The fourth patch extends the
upstream borrow/return flow while preserving explicit consent and per-tab isolation.
Do not restore the old `remote-extension-connection.patch`: upstream PR #227
already incorporates its remote connection support with different ownership and
window semantics.
## Companion UI contract
Only authenticated remote sockets handle these extra request frames. They do not
enter the native daemon's automation queue:
```json
{"id":"wk-ui-unique","method":"gateway.task_preview","params":{"session_id":"server-owned-session"}}
```
- `gateway.task_preview`: returns `image_base64`, `format: "jpeg"`, `tab_id`,
`title`, and `captured_at`. The encoded image is at most 640 pixels wide.
Captures are coalesced and restricted to a concrete owned tab. Authorization,
document revision and debugger identity are checked before returning a frame.
- `gateway.task_focus`: explicitly activates an existing owned tab and its window;
returns `{ "focused": true }`. It never creates a session.
- `gateway.task_idle`: prevents further UI captures, waits for in-flight work,
clears references and detaches the session debugger without closing tabs;
returns `{ "released": true }`. A subsequent native operation resumes capture.
Native session stop uses the same barrier.
Errors use the native-shaped `{ "id": "…", "error": { "code": "…", "message": "…" } }`
envelope. These three methods are downstream APIs, not official BrowserSkill RPCs.
The official unmodified extension returns `unknown_method`: WeKnora can still
stop completed tasks with native RPC, but retaining a task while releasing control
requires this companion build. Keep serving the companion ZIP in WeKnora settings.
## Intentional behavior changes
- Remote tasks use official dedicated Agent Windows. The old background-tab-group
preference is no longer used; no `tabGroups` permission is added.
- Only Chrome navigation-target events from an owned source during an agent action
grant popup ownership (including `rel=noopener`). A bounded 100 ms event tail
follows the input acknowledgement. Window membership/opener metadata alone do
not authorize tabs; delayed or unattributed targets use the borrow flow.
- Unowned tabs already inside the task window can be borrowed with normal browser
approval. They remain borrowed user tabs, are returned without being closed,
and lose access immediately on return. Other task windows remain isolated.
- Closing the last owned tab through `tab_close` keeps a temporary owned blank tab
until session stop, preventing Chrome window removal from being misreported as
a human interruption. Actual user window closure still pauses the task.
- Human help and borrowing follow the upstream focus/confirmation behavior.
- Remote upload/download remain unsupported, as defined upstream.
Upgrade users by replacing the existing unpacked extension directory and reloading
it after ending active tasks. Keeping the extension ID allows upstream migration
from legacy Chrome storage into extension-origin IndexedDB. Installing under a new
ID requires pairing again. Old saved tab groups are not removed automatically.
## Validation
Apply patches to a clean pinned checkout, install frozen dependencies and run:
```sh
pnpm --filter @browser-skill/extension exec wxt prepare
pnpm --filter @browser-skill/extension compile
pnpm --filter @browser-skill/extension test
pnpm --filter @browser-skill/vom test
pnpm ext:build:zip
BSK_GEOMETRY_CHROME=/path/to/test-chrome pnpm --filter @browser-skill/extension exec vitest run src/browser-driver/__tests__/task-focus.browser.test.ts
```
Run WeKnora's `TestRealExtension` with the built extension, pinned daemon and an
isolated Chromium profile; environment variables are documented in
`docs/browser-skill-integration.md`. It exercises actual pairing, screenshot and
input RPC, agent popup selection/read/close and in-place borrow approval/revocation, independent preview during help waits,
focus, pause/resume, retained-task debugger release and completed-task cleanup.
It separately verifies that agent last-tab closure permits the next turn and
manual window closure blocks automation until explicit resume.
Upstream references: [PR #227](https://github.com/Tencent/BrowserSkill/pull/227),
[remote connection contract](https://github.com/Tencent/BrowserSkill/blob/75e2c64abaf4b7cc75682d94b0c1fd5db0cbd5e5/docs/remote-extension-connection.md).

File diff suppressed because it is too large Load Diff

View File

@ -1,25 +1,12 @@
{
"version": "0.2.1",
"assets": {
"darwin-arm64": {
"url": "https://github.com/Tencent/BrowserSkill/releases/download/cli-v0.2.1/bsk-v0.2.1-aarch64-apple-darwin.tar.gz",
"sha256": "a2e7d03f7f9aa4d1f0cc977dae71099b9ee4805a5c06cdefde3919afbecf06ad"
},
"darwin-x64": {
"url": "https://github.com/Tencent/BrowserSkill/releases/download/cli-v0.2.1/bsk-v0.2.1-x86_64-apple-darwin.tar.gz",
"sha256": "3181f7010e12e2b9a395d26690a21abc4cacc1cf5c705930baea2ed2efcae7e2"
},
"linux-x64": {
"url": "https://github.com/Tencent/BrowserSkill/releases/download/cli-v0.2.1/bsk-v0.2.1-x86_64-unknown-linux-musl.tar.gz",
"sha256": "a533cbf532fe9848332d72c2b92e92e0d76626765417ca5f374914385731265f"
},
"linux-arm64": {
"url": "https://github.com/Tencent/BrowserSkill/releases/download/cli-v0.2.1/bsk-v0.2.1-aarch64-unknown-linux-musl.tar.gz",
"sha256": "d30f301fe64ea4784899d0cba3e8991d6b59017173bf83258a161a64c94a42f5"
},
"windows-x64": {
"url": "https://github.com/Tencent/BrowserSkill/releases/download/cli-v0.2.1/bsk-v0.2.1-x86_64-pc-windows-msvc.zip",
"sha256": "98539807febcaca0442024b289ce2df5691e71bdc8d6568aa98e38054fd2a04e"
}
"version": "0.3.0",
"extension": {
"version": "0.3.0",
"source_commit": "75e2c64abaf4b7cc75682d94b0c1fd5db0cbd5e5",
"upstream_tag": "ext-v0.3.0"
},
"daemon": {
"source_commit": "75e2c64abaf4b7cc75682d94b0c1fd5db0cbd5e5",
"build": "cargo build --locked --release -p bsk"
}
}

View File

@ -9,7 +9,24 @@ case "$target_platform" in
""|linux/amd64|linux/arm64|darwin/amd64|darwin/arm64) ;;
*) echo "Unsupported BrowserSkill target: $target_platform" >&2; exit 1 ;;
esac
source_commit=5aaa36bf79a201ec40b277ce6c24f2ce23ce37ca
# Build both ends from the same pinned protocol baseline.
source_commit="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["extension"]["source_commit"])' "$repo_root/scripts/browserskill-release.json")"
extension_version="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["extension"]["version"])' "$repo_root/scripts/browserskill-release.json")"
# Native builds only. Docker runs this stage on TARGETPLATFORM so C/Rust
# dependencies and the produced daemon match the final image architecture.
host_os="$(uname -s | tr '[:upper:]' '[:lower:]')"
host_arch="$(uname -m)"
case "$host_arch" in arm64|aarch64) host_arch=arm64 ;; x86_64) host_arch=amd64 ;; esac
if [ -n "$target_platform" ] && [ "$target_platform" != "$host_os/$host_arch" ]; then
echo "Run the BrowserSkill build on $target_platform (host is $host_os/$host_arch)" >&2
exit 1
fi
if ! command -v cargo >/dev/null && [ -x "${CARGO_HOME:-$HOME/.cargo}/bin/cargo" ]; then
export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH"
fi
command -v cargo >/dev/null || { echo "Rust/Cargo is required to build the matching BrowserSkill daemon" >&2; exit 1; }
daemon_commit="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["daemon"]["source_commit"])' "$repo_root/scripts/browserskill-release.json")"
[ "$daemon_commit" = "$source_commit" ] || { echo "BrowserSkill daemon/extension baseline mismatch" >&2; exit 1; }
mkdir -p "$output_dir"
output_dir="$(cd "$output_dir" && pwd)"
build_dir="$(mktemp -d /tmp/weknora-bsk-build.XXXXXX)"
@ -17,45 +34,31 @@ trap 'rm -rf "$build_dir"' EXIT
git clone --no-checkout https://github.com/Tencent/BrowserSkill.git "$build_dir/source"
git -C "$build_dir/source" checkout --detach "$source_commit"
git -C "$build_dir/source" apply --check "$repo_root/patches/browserskill/remote-extension-connection.patch"
git -C "$build_dir/source" apply "$repo_root/patches/browserskill/remote-extension-connection.patch"
for patch in "$repo_root"/patches/browserskill/*.patch; do
git -C "$build_dir/source" apply --check "$patch"
git -C "$build_dir/source" apply "$patch"
done
(
cd "$build_dir/source"
npx --yes pnpm@10.17.0 install --frozen-lockfile
npx --yes pnpm@10.17.0 ext:build:zip
)
cp "$build_dir/source/apps/extension/dist/browser-skillextension-0.2.1-chrome.zip" "$output_dir/browser-skill-weknora-0.2.1.zip"
cp "$build_dir/source/apps/extension/dist/browser-skillextension-${extension_version}-chrome.zip" "$output_dir/browser-skill-weknora-${extension_version}.zip"
cp "$build_dir/source/LICENSE" "$output_dir/BrowserSkill-LICENSE"
# Download the server's native daemon using the release's pinned checksums.
python3 - "$repo_root/scripts/browserskill-release.json" "$output_dir" "$target_platform" <<'PY'
import hashlib, io, json, os, pathlib, platform, sys, tarfile, tempfile, urllib.request
release = json.loads(pathlib.Path(sys.argv[1]).read_text())
os_name = {'Darwin': 'darwin', 'Linux': 'linux'}.get(platform.system())
arch = {'arm64': 'arm64', 'aarch64': 'arm64', 'x86_64': 'x64', 'AMD64': 'x64'}.get(platform.machine())
if sys.argv[3]:
os_name, target_arch = sys.argv[3].split('/')
arch = {'amd64': 'x64', 'arm64': 'arm64'}[target_arch]
key = f'{os_name}-{arch}'
if key not in release['assets']:
raise SystemExit('The WeKnora daemon adapter currently requires macOS or Linux')
asset = release['assets'][key]
with urllib.request.urlopen(asset['url'], timeout=60) as response:
data = response.read()
if hashlib.sha256(data).hexdigest() != asset['sha256']:
raise SystemExit('BrowserSkill archive checksum mismatch')
with tarfile.open(fileobj=io.BytesIO(data), mode='r:gz') as archive:
member = next(m for m in archive.getmembers() if pathlib.PurePosixPath(m.name).name == 'bsk' and m.isfile())
target = pathlib.Path(sys.argv[2]) / 'bsk'
# Never overwrite the inode of an executing daemon. On macOS this can
# invalidate executable pages even when the replacement bytes are identical.
with tempfile.NamedTemporaryFile(dir=target.parent, prefix='.bsk-', delete=False) as output:
staged = pathlib.Path(output.name)
output.write(archive.extractfile(member).read())
try:
staged.chmod(0o755)
os.replace(staged, target)
finally:
staged.unlink(missing_ok=True)
print(f'BrowserSkill {release["version"]} artifacts: {sys.argv[2]}')
PY
# Build the daemon from the same source: CLI 0.2.1 releases do not support
# scroll_to, wheel, focus, or blur even though newer extension sources do.
cargo_target_dir="${CARGO_TARGET_DIR:-$build_dir/target}"
mkdir -p "$cargo_target_dir"
cargo_target_dir="$(cd "$cargo_target_dir" && pwd)"
(
cd "$build_dir/source"
# Use the installed toolchain; do not let the checkout's moving "stable"
# override force a network update during each application build.
RUSTUP_TOOLCHAIN="${RUSTUP_TOOLCHAIN:-stable}" cargo build --locked --release -p bsk --target-dir "$cargo_target_dir"
)
# Replace atomically: overwriting an executing inode can invalidate macOS code pages.
staged_binary="$(mktemp "$output_dir/.bsk-XXXXXX")"
install -m 755 "$cargo_target_dir/release/bsk" "$staged_binary"
mv -f "$staged_binary" "$output_dir/bsk"
echo "BrowserSkill $extension_version extension and daemon: $output_dir"

View File

@ -25,37 +25,15 @@ try {
args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`],
});
const worker = browser.serviceWorkers()[0] ?? await browser.waitForEvent('serviceworker');
const taskWindow = process.env.BROWSERSKILL_TEST_TASK_WINDOW !== '0';
const popup = await browser.newPage();
await popup.goto(new URL('popup.html', worker.url()).href);
await popup.locator('details summary').click();
// Official 0.3.0 unifies local/remote connection settings.
await popup.locator('[role="group"] button').nth(1).click();
await popup.locator('#remote-pairing').fill(pairing);
await popup.locator('details button').first().click();
try {
await popup.waitForFunction(() => document.querySelector('#remote-pairing')?.value === '' || document.querySelector('details [role=alert]'));
} catch (error) {
// Never include the password input or pairing credential in diagnostics.
console.error('Extension pairing UI:', await popup.locator('body').innerText());
console.error('Pairing form state:', await popup.evaluate(() => ({
length: document.querySelector('#remote-pairing')?.value.length,
disabled: document.querySelector('#remote-pairing')?.disabled,
buttons: [...document.querySelectorAll('details button')].map(b => ({text:b.textContent,disabled:b.disabled})),
})));
throw error;
}
if (await popup.locator('details [role=alert]').count()) throw new Error('Extension authorization failed before browser tests');
if (!taskWindow) {
await popup.locator('#bsk-task-window-mode').selectOption('tabs');
await popup.waitForFunction(() => {
const select = document.querySelector('#bsk-task-window-mode');
return select?.value === 'tabs' && !select.disabled;
});
} else {
await popup.waitForFunction(() => {
const select = document.querySelector('#bsk-task-window-mode');
return select?.value === 'window' && !select.disabled;
});
}
await popup.locator('form button[type="submit"]').click();
await popup.waitForFunction(() => document.querySelector('#remote-pairing')?.value === '' || document.querySelector('form [role=alert]'));
if (await popup.locator('form [role=alert]').count()) throw new Error('Extension authorization failed before browser tests');
const initial = await worker.evaluate(async () => {
const window = await chrome.windows.getLastFocused();
const tabs = await chrome.tabs.query({windowId:window.id,active:true});
@ -65,20 +43,29 @@ try {
process.stdout.write('ready\n');
for await (const command of lines) {
if (command === 'close') break;
if (command === 'complete-help' || command === 'interrupt-window') {
const selector = command === 'complete-help'
if (command === 'complete-login' || command === 'interrupt-window' || command === 'approve-borrow') {
const selector = command === 'complete-login'
? '[data-slot="help-request-banner"][data-display-mode="full"] [data-slot="help-continue-button"]'
: command === 'approve-borrow' ? '[data-slot="borrow-confirmation-allow-button"]'
: '[data-slot="control-overlay-stop-all"]';
// Click the actual extension overlay in an isolated fixture browser.
let clicked = false;
const deadline = Date.now() + 5000;
while (!clicked && Date.now() < deadline) {
for (const page of browser.pages().filter(page => page !== popup).reverse()) {
const button = command === 'complete-help'
const button = command === 'complete-login'
? page.locator('[data-slot="help-request-banner"][data-display-mode="full"]')
.filter({hasText:'Confirm this fixture step'}).locator('[data-slot="help-continue-button"]').first()
: page.locator(selector).first();
if (!await button.isVisible()) continue;
if (command === 'complete-login') {
// Only synthetic fixture credentials, entered through the page UI.
await page.locator('#login-account').fill('fixture-user');
await page.locator('#login-password').fill('fixture-password');
await page.locator('#login-submit').click();
await page.waitForURL('**/login-complete');
await button.waitFor({state:'visible',timeout:5000});
}
await button.click({timeout:5000});
clicked = true;
break;
@ -107,8 +94,8 @@ try {
process.stdout.write(JSON.stringify({detached:attached.length===0})+'\n');
}
if (command === 'check-cleanup') {
const state = await worker.evaluate(async () => ({ids:(await chrome.tabs.query({})).map(t=>t.id), groups:await chrome.tabGroups.query({})}));
process.stdout.write(JSON.stringify({cleaned:state.groups.length===0 && state.ids.length===initial.tabIds.length && state.ids.every(id=>initial.tabIds.includes(id))})+'\n');
const state = await worker.evaluate(async () => ({ids:(await chrome.tabs.query({})).map(t=>t.id)}));
process.stdout.write(JSON.stringify({cleaned:state.ids.length===initial.tabIds.length && state.ids.every(id=>initial.tabIds.includes(id))})+'\n');
}
if (command === 'remember-foreground') {
const foreground = await worker.evaluate(async () => {
@ -119,28 +106,42 @@ try {
Object.assign(initial, foreground);
process.stdout.write('remembered\n');
}
if (command === 'create-unowned-tab') {
const createdPage = browser.waitForEvent('page', {predicate:p => p !== popup});
const tab = await worker.evaluate(async (initialIds) => {
const source = (await chrome.tabs.query({})).find(t => !initialIds.includes(t.id) && t.url?.startsWith('http://127.0.0.1:'));
if (!source) throw new Error('Fixture task page unavailable');
// Extension API creation simulates a user-created tab: no navigation
// source event, even though it is inside the Agent Window.
return chrome.tabs.create({windowId:source.windowId,url:source.url+'?user-tab=1',active:true});
}, initial.tabIds);
const page = await createdPage;
await page.waitForURL('**/*?user-tab=1');
await page.locator('browser-skill-overlay').waitFor({state:'attached'});
process.stdout.write(JSON.stringify({tab_id:tab.id})+'\n');
}
if (command.startsWith('close-fixture-window ')) {
const id = Number(command.split(' ')[1]);
await worker.evaluate(async (tabId) => {
const tab = await chrome.tabs.get(tabId);
await chrome.windows.remove(tab.windowId);
}, id);
process.stdout.write('fixture-window-closed\n');
}
if (command.startsWith('remove-fixture-tab ')) {
const id = Number(command.split(' ')[1]);
await worker.evaluate(async (tabId) => chrome.tabs.remove(tabId), id);
process.stdout.write('fixture-tab-removed\n');
}
if (command === 'check-background') {
if (taskWindow) {
const valid = await worker.evaluate(async (original) => {
const tabs = await chrome.tabs.query({});
const groups = await chrome.tabGroups.query({});
const taskWindows = [...new Set(tabs.filter(t => t.windowId !== original.windowId).map(t => t.windowId))];
return tabs.find(t => t.id === original.tabId)?.active === true &&
groups.length === 0 && taskWindows.length > 0 && taskWindows.every(id =>
tabs.filter(t => t.windowId === id && t.active).length === 1);
}, originalWindow);
process.stdout.write(JSON.stringify({background:valid})+'\n');
continue;
}
const current = await worker.evaluate(async () => {
const window=await chrome.windows.getLastFocused();
const tabs=await chrome.tabs.query({windowId:window.id,active:true});
const windows=await chrome.windows.getAll({windowTypes:['normal']});
const groups=await chrome.tabGroups.query({windowId:window.id});
return {windowId:window.id,tabId:tabs[0].id,windowCount:windows.length,labeled:groups.some(g=>g.title?.startsWith('WeKnora'))};
});
const background = current.windowId === initial.windowId && current.tabId === initial.tabId && current.windowCount === 1 && current.labeled;
process.stdout.write(JSON.stringify(background ? {background} : {background, initial, current}) + '\n');
const valid = await worker.evaluate(async (original) => {
const tabs = await chrome.tabs.query({});
const taskWindows = [...new Set(tabs.filter(t => t.windowId !== original.windowId).map(t => t.windowId))];
return tabs.find(t => t.id === original.tabId)?.active === true &&
taskWindows.length > 0 && taskWindows.every(id =>
tabs.filter(t => t.windowId === id && t.active).length === 1);
}, originalWindow);
process.stdout.write(JSON.stringify({background:valid})+'\n');
}
}
} finally {