Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(browser): align BrowserSkill 0.3.0 and repair task lifecycle
wizardchen84c9871d16f9
diff --git a/.env.example b/.env.exampleindex 5dc3fe6a1..493a6894c 100644--- a/.env.example+++ b/.env.example@@ -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 注入,不提交到仓库。diff --git a/docker/Dockerfile.app b/docker/Dockerfile.appindex e79cb0c05..f767ef568 100644--- a/docker/Dockerfile.app+++ b/docker/Dockerfile.app@@ -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 browserskillWORKDIR /buildRUN 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 stableCOPY scripts/build_browserskill.sh scripts/browserskill-release.json ./scripts/COPY patches/browserskill ./patches/browserskillARG 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.zipCOPY --from=browserskill /opt/weknora/browserskill /opt/weknora/browserskill# Create a non-root user firstdiff --git a/docs/browser-skill-integration.md b/docs/browser-skill-integration.mdindex b0e476b99..3b84871b4 100644--- a/docs/browser-skill-integration.md+++ b/docs/browser-skill-integration.md@@ -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```dotenvBROWSERSKILL_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-extensionBROWSERSKILL_TEST_CHROMIUM=/absolute/path/to/ChromiumBROWSERSKILL_TEST_PLAYWRIGHT=/absolute/path/to/playwright-core/index.mjsBROWSERSKILL_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 中手动删除。diff --git a/docs/browser-skill-production.md b/docs/browser-skill-production.mdindex 7db5da5ba..da2d173f7 100644--- a/docs/browser-skill-production.md+++ b/docs/browser-skill-production.md@@ -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` 仅作为独立网关域名/路径等特殊部署的优先覆盖项。原生部署各节点需自行安装产物。配置示例如下:```dotenvBROWSERSKILL_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.zipBROWSERSKILL_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 不支持当前滚动等工具方法。## 容量与验收diff --git a/docs/images/browser-task-handoff.png b/docs/images/browser-task-handoff.pngnew file mode 100644index 000000000..d654d8cb2Binary files /dev/null and b/docs/images/browser-task-handoff.png differdiff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 1dc7bfeaa..c30ec61b3 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -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",diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex bdc107850..e6e909954 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -59,6 +59,7 @@ export default {"previewIdle": "最後の画面を保持しています","previewLive": "画面を同期中","previewLoading": "画面を取得中",+ "borrowHint": "借用するページに切り替え、BrowserSkill の確認で許可または拒否を選択してください。許可後は自動で続行します。「操作を続行」は一時停止の解除のみで、借用の許可にはなりません。","helpHint": "確認または許可が必要です。プレビューをクリックして移動してください。","settingsTitle": "ブラウザー接続",diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 9b2541154..f545c0ba7 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -59,6 +59,7 @@ export default {"previewIdle": "마지막 화면 유지 중","previewLive": "화면 동기화 중","previewLoading": "화면 가져오는 중",+ "borrowHint": "사용하려는 페이지로 전환하여 BrowserSkill 확인 창에서 허용 또는 거부를 선택하세요. 허용하면 자동으로 계속됩니다. 작업 계속은 일시 중지만 해제하며 탭 사용을 승인하지 않습니다.","helpHint": "인증 또는 권한 승인이 필요합니다. 미리보기를 클릭하여 이동하세요.","settingsTitle": "브라우저 연결",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 68dd6ed6f..6145ae28c 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -59,6 +59,7 @@ export default {"previewIdle": "Сохранено последнее изображение","previewLive": "Изображение обновляется","previewLoading": "Получение изображения",+ "borrowHint": "Перейдите на запрашиваемую вкладку и выберите «Разрешить» или «Отклонить» в окне BrowserSkill. После разрешения работа продолжится автоматически. Продолжение приостановленной задачи не даёт разрешения на доступ к вкладке.","helpHint": "Требуется проверка или разрешение. Нажмите предпросмотр для перехода.","settingsTitle": "Подключение браузера",diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 725d2aa58..ad2435e86 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -59,6 +59,7 @@ export default {"previewIdle": "已保留最后画面","previewLive": "画面同步中","previewLoading": "正在获取画面",+ "borrowHint": "请切换到要借用的网页,在 BrowserSkill 授权提示中选择「允许」或「拒绝」。授权通过后会自动继续;「继续操作」只恢复暂停的任务,不代替借用授权。","helpHint": "点击预览前往浏览器,完成上述步骤后,在浏览器帮助提示中确认完成。","settingsTitle": "浏览器连接",diff --git a/frontend/src/views/chat/components/BrowserTaskPreview.browser.test.mjs b/frontend/src/views/chat/components/BrowserTaskPreview.browser.test.mjsnew file mode 100644index 000000000..38203339b--- /dev/null+++ b/frontend/src/views/chat/components/BrowserTaskPreview.browser.test.mjs@@ -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() }+})diff --git a/frontend/src/views/chat/components/BrowserTaskPreview.vue b/frontend/src/views/chat/components/BrowserTaskPreview.vueindex 3b62fecda..423b99d07 100644--- a/frontend/src/views/chat/components/BrowserTaskPreview.vue+++ b/frontend/src/views/chat/components/BrowserTaskPreview.vue@@ -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>diff --git a/internal/agent/prompts_browser.go b/internal/agent/prompts_browser.goindex 0b90307f3..c3510e1de 100644--- a/internal/agent/prompts_browser.go+++ b/internal/agent/prompts_browser.go@@ -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 thatlocal_browser can access. Generic retrieval-first guidance must not skip the user'sexplicit 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 andhow to restore access. Do not silently skip the requested browser step or claim tohave read a page without a successful browser observation. Distinguish any informationdiff --git a/internal/agent/tools/browserskill_prompt.go b/internal/agent/tools/browserskill_prompt.goindex 5bb9b1b3c..63f5dae2f 100644--- a/internal/agent/tools/browserskill_prompt.go+++ b/internal/agent/tools/browserskill_prompt.go@@ -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 CLIsession 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 snapshotor get_html for missing structure. Reserve evaluate for a specific gap and return boundedserializable 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. Navigationdefaults to domcontentloaded, which does not guarantee application readiness. Inspect beforewaiting. 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 userlocates 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 bypassa 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 thetask for a requested open page, deliverable or unfinished form. request_help retains itautomatically; clear keep_open after resolution if unnecessary. Retention applies per turn.diff --git a/internal/agent/tools/browserskill_result.go b/internal/agent/tools/browserskill_result.goindex 343ef2e63..0677b8010 100644--- a/internal/agent/tools/browserskill_result.go+++ b/internal/agent/tools/browserskill_result.go@@ -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 resultdiff --git a/internal/agent/tools/browserskill_result_test.go b/internal/agent/tools/browserskill_result_test.goindex b69bdaebd..43c124c08 100644--- a/internal/agent/tools/browserskill_result_test.go+++ b/internal/agent/tools/browserskill_result_test.go@@ -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")+}diff --git a/internal/agent/tools/browserskill_schema.go b/internal/agent/tools/browserskill_schema.goindex 24cb86f8c..3933e694c 100644--- a/internal/agent/tools/browserskill_schema.go+++ b/internal/agent/tools/browserskill_schema.go@@ -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"},},}diff --git a/internal/agent/tools/browserskill_schema_test.go b/internal/agent/tools/browserskill_schema_test.goindex 0bcad1c6b..f71d07416 100644--- a/internal/agent/tools/browserskill_schema_test.go+++ b/internal/agent/tools/browserskill_schema_test.go@@ -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))) })}diff --git a/internal/browserskill/authorization.go b/internal/browserskill/authorization.goindex 6364841c8..1d26f4b95 100644--- a/internal/browserskill/authorization.go+++ b/internal/browserskill/authorization.go@@ -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 {diff --git a/internal/browserskill/errors_test.go b/internal/browserskill/errors_test.goindex b1c8588bc..31d68d30b 100644--- a/internal/browserskill/errors_test.go+++ b/internal/browserskill/errors_test.go@@ -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)+ })+ }+}diff --git a/internal/browserskill/extension_test.go b/internal/browserskill/extension_test.goindex 0e7c5dc7b..bf168ea9c 100644--- a/internal/browserskill/extension_test.go+++ b/internal/browserskill/extension_test.go@@ -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)+ }+ if _, e = call(ctx, scope, "chat", "snapshot", map[string]any{"tab_id": popupID}); e != nil {+ t.Fatal(e)+ }+ if _, e = call(ctx, scope, "chat", "tab_close", map[string]any{"tab_id": popupID}); e != nil {t.Fatal(e)}- var result struct {- Tabs []json.RawMessage `json:"tabs"`+ }+ // 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)}- if json.Unmarshal(listed, &result) != nil || len(result.Tabs) != i+2 {- t.Fatalf("page-created tab was not claimed: %s", listed)+ 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)}- checkBackground()+ 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 {diff --git a/internal/browserskill/focus.go b/internal/browserskill/focus.goindex 80cc91918..b514118b9 100644--- a/internal/browserskill/focus.go+++ b/internal/browserskill/focus.go@@ -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 errorif 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 nildiff --git a/internal/browserskill/manager.go b/internal/browserskill/manager.goindex 2ca6744c7..99bc8b52e 100644--- a/internal/browserskill/manager.go+++ b/internal/browserskill/manager.go@@ -625,9 +625,22 @@ func rpc(ctx context.Context, d *device, method string, params any) (json.RawMesreturn 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 = falset.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"] = idif 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 {diff --git a/internal/browserskill/shared_test.go b/internal/browserskill/shared_test.goindex fb5cebe9e..32c7ec1c3 100644--- a/internal/browserskill/shared_test.go+++ b/internal/browserskill/shared_test.go@@ -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)+ })+ }+}diff --git a/patches/browserskill/01-browser-read-reliability.patch b/patches/browserskill/01-browser-read-reliability.patchnew file mode 100644index 000000000..be6a8fc47--- /dev/null+++ b/patches/browserskill/01-browser-read-reliability.patch@@ -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 ?? "")+ );+ }diff --git a/patches/browserskill/02-gateway-task-controls.patch b/patches/browserskill/02-gateway-task-controls.patchnew file mode 100644index 000000000..1980bfb39--- /dev/null+++ b/patches/browserskill/02-gateway-task-controls.patch@@ -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;diff --git a/patches/browserskill/03-vom-render-performance.patch b/patches/browserskill/03-vom-render-performance.patchnew file mode 100644index 000000000..5327c461c--- /dev/null+++ b/patches/browserskill/03-vom-render-performance.patch@@ -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,diff --git a/patches/browserskill/04-task-popup-ownership.patch b/patches/browserskill/04-task-popup-ownership.patchnew file mode 100644index 000000000..a3b98de5b--- /dev/null+++ b/patches/browserskill/04-task-popup-ownership.patch@@ -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 };diff --git a/patches/browserskill/05-last-tab-lifecycle.patch b/patches/browserskill/05-last-tab-lifecycle.patchnew file mode 100644index 000000000..dcdfa5e46--- /dev/null+++ b/patches/browserskill/05-last-tab-lifecycle.patch@@ -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),diff --git a/patches/browserskill/06-navigation-lifecycle.patch b/patches/browserskill/06-navigation-lifecycle.patchnew file mode 100644index 000000000..fd2ad2a48--- /dev/null+++ b/patches/browserskill/06-navigation-lifecycle.patch@@ -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, ¶ms).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!({diff --git a/patches/browserskill/README.md b/patches/browserskill/README.mdnew file mode 100644index 000000000..35ca36d02--- /dev/null+++ b/patches/browserskill/README.md@@ -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).diff --git a/patches/browserskill/remote-extension-connection.patch b/patches/browserskill/remote-extension-connection.patchdeleted file mode 100644index 58467f33c..000000000--- a/patches/browserskill/remote-extension-connection.patch+++ /dev/null@@ -1,3758 +0,0 @@-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 41b6719..ffa4a0b 100644---- a/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts-+++ b/apps/extension/src/browser-driver/__tests__/chromium-cdp.test.ts-@@ -29,6 +29,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);-@@ -429,6 +526,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({-@@ -478,7 +576,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..796cf76---- /dev/null-+++ b/apps/extension/src/browser-driver/__tests__/command-deadline.test.ts-@@ -0,0 +1,75 @@-+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.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 ddbf5ee..a602adb 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>>();-@@ -189,6 +193,8 @@ export class ChromiumCdp {- private readonly options: {- /** CDP observation alone does not authorize dismissing user dialogs. */- shouldAutoAcceptDialog?: (tabId: number) => boolean | Promise<boolean>;-+ /** Only explicitly controlled task tabs may emulate foreground page activity. */-+ shouldKeepTaskActive?: (tabId: number) => boolean;- } = {},- ) {- this.api = api;-@@ -210,7 +216,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;-@@ -219,6 +228,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);-@@ -240,6 +250,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;- }- })()-@@ -261,11 +272,9 @@ 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 ?? {});- return result as T;- } catch (err) {- throw normalizeError(err);-@@ -273,11 +282,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);- }-@@ -452,6 +459,7 @@ export class ChromiumCdp {- if (!this.attachedTabs.has(tabId)) return;- this.attachedTabs.delete(tabId);- this.attachmentIds.delete(tabId);-+ this.taskFocus.delete(tabId);- this.clearDialogState(tabId);- this.clearConsoleState(tabId);- this.clearNetworkState(tabId);-@@ -511,6 +519,7 @@ export class ChromiumCdp {- this.tabOwners.clear();- this.attachedTabs.clear();- this.attachmentIds.clear();-+ this.taskFocus.clear();- this.dialogBuffers.clear();- this.dialogSequences.clear();- this.consoleBuffers.clear();-@@ -521,6 +530,7 @@ export class ChromiumCdp {- this.networkDomainsEnabledTabs.clear();- this.networkRequestMeta.clear();- this.frameDiscovery.clear();-+ this.pendingScreenshots.clear();- await Promise.all(- tabs.map(async (tabId) => {- try {-@@ -532,8 +542,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> {-@@ -546,7 +596,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 });-@@ -559,7 +609,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);- }--@@ -571,13 +621,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 {-@@ -591,6 +655,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;- }-@@ -657,6 +722,7 @@ export class ChromiumCdp {- sessions: new Set(),- pending: new Set(),- generation: 0,-+ enabled: new Map(),- };- this.frameDiscovery.set(tabId, created);- return created;-@@ -664,6 +730,7 @@ export class ChromiumCdp {-- private clearFrameState(tabId: number): void {- this.frameDiscovery.delete(tabId);-+ this.pendingScreenshots.delete(tabId);- }-- private bindDialogHandler(): void {-@@ -696,7 +763,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);-@@ -858,6 +925,7 @@ export class ChromiumCdp {- if (typeof source.tabId === "number") {- 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/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts-index 72819fa..ec6e0ac 100644---- a/apps/extension/src/entrypoints/background.ts-+++ b/apps/extension/src/entrypoints/background.ts-@@ -1,7 +1,8 @@-+import { TaskActivity } from "@/lib/task-activity";- import { i18n } from "@browser-skill/i18n";- import { ChromiumCdp } from "@/browser-driver/chromium-cdp";- import { ConnectionController } from "@/lib/connection-controller";--import { watchDaemonPort } from "@/lib/daemon-port-preference";-+import { watchDaemonConnection } from "@/lib/daemon-connection-preference";- import { startHeartbeat } from "@/lib/heartbeat";- import {- getConnectionEnabled,-@@ -24,6 +25,7 @@ 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 { captureTaskPreview } from "@/lib/task-preview";- import { createDisconnectCleanup } from "@/session-manager/disconnect-cleanup";- import { attachSessionEventHandler } from "@/session-manager/event-handler";- import { isAgentControlledTab, SessionManager } from "@/session-manager/manager";-@@ -44,28 +46,80 @@ import {- } from "@/tools/record";- import { chromeTabsApi } from "@/tools/shared";- import { chromeTabMutationApi } from "@/tools/tabs";--import { resolveDaemonWsUrl } from "@/transport/daemon-endpoint";- import { detectBrowserMeta } from "@/transport/handshake";-+import { watchRemoteAuthorization } from "@/transport/remote-authorization";-+import { type RemoteEndpoint, remoteSocket } from "@/transport/remote-endpoint";-+import { getTaskWindowEnabled } from "@/lib/task-window-preference";- import type { Transport } from "@/transport/transport";- import { WSTransport } from "@/transport/ws-transport";-- export default defineBackground(() => {- const controller = new ConnectionController();-- const transport = new WSTransport({ url: __BSK_DAEMON_WS_URL__ });-- const sessions = new SessionManager();-+ let remoteEndpoint: RemoteEndpoint | null = null;-+ const transport = new WSTransport({-+ url: __BSK_DAEMON_WS_URL__,-+ webSocketFactory: (url) =>-+ remoteSocket(-+ url,-+ remoteEndpoint,-+ async (sessionId) => {-+ const task = sessions.get(sessionId);-+ if (!task) throw new Error("Browser task unavailable");-+ const tabId =-+ task.activeTabId !== undefined && isAgentControlledTab(task, task.activeTabId)-+ ? task.activeTabId-+ : [...task.agentCreatedTabs, ...task.borrowedTabs.keys()][0];-+ if (tabId === undefined || !isAgentControlledTab(task, tabId))-+ throw new Error("Task tab unavailable");-+ const tab = await chrome.tabs.get(tabId);-+ await chrome.tabs.update(tabId, { active: true });-+ await chrome.windows.update(tab.windowId, { focused: true });-+ },-+ (sessionId) =>-+ taskActivity.preview(sessionId, () => captureTaskPreview(sessions, cdp, sessionId)),-+ async (sessionId) => {-+ if (!sessions.get(sessionId)) throw new Error("Browser task unavailable");-+ await taskActivity.release(sessionId);-+ return { released: true };-+ },-+ ),-+ });-+ const sessions = new SessionManager({-+ taskTabs: () => remoteEndpoint !== null,-+ taskWindow: getTaskWindowEnabled,-+ taskLabel: () => remoteEndpoint?.serviceName ?? "BrowserSkill",-+ });- const cdp = new ChromiumCdp(undefined, {-+ shouldKeepTaskActive: (tabId) => sessions.findByTabId(tabId)?.tabMode === true,- shouldAutoAcceptDialog: async (tabId) => {- const tab = await chrome.tabs.get(tabId);-- return sessions.findByWindowId(tab.windowId) !== null;-+ return (-+ (typeof tab.id === "number" && sessions.findByTabId(tab.id) !== null) ||-+ sessions.findByWindowId(tab.windowId) !== null-+ );- },- });-+ const taskActivity: TaskActivity = new TaskActivity(sessions, (id) =>-+ dispatcher.releaseTaskControl(id),-+ );- const sessionsLive = attachSessionsLiveFlag({ manager: sessions });- let overlayGeneration = 0;- const controlModes = new Map<string, OverlayMode>();--- const daemonPort = watchDaemonPort((port) => {-- const url = resolveDaemonWsUrl(port);-- void controller.reconfigureTransport(url, () => {-+ const remoteAuthorization = watchRemoteAuthorization();-+ const daemonPort = watchDaemonConnection((url, remote) => {-+ remoteAuthorization.changed();-+ // Token rotation for the same device must not interrupt a running task.-+ if (-+ remote?.deviceId &&-+ remoteEndpoint?.deviceId === remote.deviceId &&-+ remoteEndpoint.url === remote.url-+ ) {-+ remoteEndpoint = remote;-+ return;-+ }-+ void controller.reconfigureTransport(JSON.stringify([url, remote]), () => {-+ remoteEndpoint = remote;- transport.setUrl(url);- });- });-@@ -104,8 +158,14 @@ export default defineBackground(() => {- */- function overlayStateForTab(tabId?: number, windowId?: number): OverlayAgentStateMessage {- if (typeof tabId === "number" && typeof windowId === "number") {-- const ctx = sessions.findByWindowId(windowId);-- if (ctx && isAgentControlledTab(ctx, tabId)) return overlayStateForWindow(windowId);-+ const ctx = sessions.findByTabId(tabId) ?? sessions.findByWindowId(windowId);-+ if (ctx && isAgentControlledTab(ctx, tabId))-+ return {-+ type: OVERLAY_AGENT_STATE,-+ sessionId: ctx.sessionId,-+ mode: controlModes.get(ctx.sessionId) ?? "control",-+ generation: overlayGeneration,-+ };- }- return {- type: OVERLAY_AGENT_STATE,-@@ -165,7 +225,7 @@ export default defineBackground(() => {- }-- function pushOverlayStateForAgentWindow(windowId: number): void {-- if (!sessions.findByWindowId(windowId)) return;-+ if (!sessions.list().some((ctx) => ctx.agentWindowId === windowId)) return;- void pushOverlayStateForWindow(windowId);- }- chrome.tabs.onActivated.addListener((activeInfo) => {-@@ -181,11 +241,32 @@ export default defineBackground(() => {- // state; it never infers or mutates ownership from event ordering.- chrome.tabs.onCreated.addListener((tab) => {- if (typeof tab.windowId !== "number" || typeof tab.id !== "number") return;-- if (!sessions.findByWindowId(tab.windowId)) return;-+ if (!sessions.list().some((ctx) => ctx.agentWindowId === tab.windowId)) return;- void pushOverlayStateForTab(tab.id, tab.windowId);- });-+ chrome.tabs.onAttached.addListener((tabId, info) => {-+ const task = sessions.findByTabId(tabId);-+ if (task?.tabMode) void pushOverlayStateForTab(tabId, info.newWindowId);-+ });- chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {-+ const task = sessions.findByTabId(tabId);- sessions.forgetClosedTab(tabId, { isWindowClosing: removeInfo.isWindowClosing });-+ if (task?.tabMode && !task.stopping && !task.agentCreatedTabs.size && !task.borrowedTabs.size) {-+ task.stopping = true;-+ void cdp-+ .detachSession(task.sessionId)-+ .then(() => sessions.stop(task.sessionId, { dropOnly: true }))-+ .then(() => {-+ onOverlaySessionStateChanged();-+ transport.send({-+ event: "session.window_closed",-+ payload: { session_id: task.sessionId, reason: "user_closed_window" },-+ });-+ })-+ .catch(() => {-+ /* Connection cleanup also drops the task if disconnected. */-+ });-+ }- });- // Re-sync the storage.session flag on SW startup so a previous SW's- // stale `true` does not keep waking us on every page load until the-@@ -227,6 +308,7 @@ export default defineBackground(() => {- attachRecordQueryListener(recordDeps);-- const dispatcher = new ToolDispatcher({-+ taskActivity,- transport,- sessions,- cdp,-@@ -247,6 +329,7 @@ export default defineBackground(() => {- // Resolve i18n strings per-borrow so language switches take effect- // without re-creating the dispatcher.- notificationCopy: makeBorrowNotificationCopy(),-+ focusOnRequest: !remoteEndpoint,- },- }),- helpNotificationCopy: () => ({-@@ -355,7 +438,7 @@ export default defineBackground(() => {-- if (msg.kind === OVERLAY_MSG_WHO_AM_I) {- const windowId = sender.tab?.windowId;-- const ctx = typeof windowId === "number" ? sessions.findByWindowId(windowId) : null;-+ const ctx = sender.tab?.id !== undefined ? sessions.findByTabId(sender.tab.id) : null;- sendResponse({ sessionId: ctx?.sessionId ?? null });- return false;- }-@@ -372,7 +455,11 @@ export default defineBackground(() => {- if (msg.kind === OVERLAY_MSG_INTERRUPT) {- const req = msg as OverlayInterruptRequest;- const ctx = sessions.get(req.sessionId);-- if (ctx) setControlMode(req.sessionId, "interrupting");-+ if (!ctx || sender.tab?.id === undefined || !isAgentControlledTab(ctx, sender.tab.id)) {-+ sendResponse({ ok: false, error: "Task tab is not authorized" });-+ return false;-+ }-+ setControlMode(req.sessionId, "interrupting");- void handleOverlayInterrupt(transport, req.sessionId).then((reply) => {- if (reply.ok && sessions.get(req.sessionId)) {- setControlMode(req.sessionId, "paused");-diff --git a/apps/extension/src/entrypoints/popup/App.tsx b/apps/extension/src/entrypoints/popup/App.tsx-index 29ee388..2ea435f 100644---- a/apps/extension/src/entrypoints/popup/App.tsx-+++ b/apps/extension/src/entrypoints/popup/App.tsx-@@ -13,6 +13,8 @@ import { PROTOCOL_VERSION } from "@/transport/handshake";- import functionIconUrl from "../../../assets/function.svg";- import { ConnectionStatusIndicator } from "./connection-status-indicator";- import { POPUP_FEATURES, type PopupView } from "./features";-+import { RemoteConnection } from "./remote-connection";-+import { TaskWindowMode } from "./task-window-mode";- import { Switch } from "./switch";- import { type PopupStatusState, useConnectionState } from "./use-connection-state";- import { useControlHintsHidden } from "./use-control-hints-hidden";-@@ -54,6 +56,7 @@ export function App() {- dirty: daemonPortDirty,- error: daemonPortError,- } = useDaemonPort();-+ const [remoteConfigured, setRemoteConfigured] = useState(false);- const [view, setView] = useState<PopupView>("main");- const [copiedInstanceId, setCopiedInstanceId] = useState(false);- const [purposeDraft, setPurposeDraft] = useState("");-@@ -275,9 +278,12 @@ export function App() {- </div>- </section>--+ <RemoteConnection onRemoteChange={setRemoteConfigured} />-+ {remoteConfigured && <TaskWindowMode />}- <section- className="rounded-xl border border-border/80 bg-card/60 px-3 py-2.5"- data-slot="popup-daemon-port-card"-+ hidden={remoteConfigured}- >- <div className="flex items-center justify-between gap-2">- <span className="flex min-w-0 items-center gap-1">-diff --git a/apps/extension/src/entrypoints/popup/remote-connection.tsx b/apps/extension/src/entrypoints/popup/remote-connection.tsx-new file mode 100644-index 0000000..c9085ec---- /dev/null-+++ b/apps/extension/src/entrypoints/popup/remote-connection.tsx-@@ -0,0 +1,113 @@-+import { useTranslation } from "@browser-skill/i18n/react";-+import { Button, Input, Label } from "@browser-skill/ui";-+import { useEffect, useState } from "react";-+import {-+ parseRemoteEndpoint,-+ REMOTE_ENDPOINT_KEY,-+ readRemoteEndpoint,-+} from "@/transport/remote-endpoint";-+-+export function RemoteConnection({-+ onRemoteChange,-+}: {-+ onRemoteChange?: (remote: boolean) => void;-+}) {-+ const { t } = useTranslation("extension");-+ const [draft, setDraft] = useState("");-+ const [server, setServer] = useState<string | null>(null);-+ const [ready, setReady] = useState(false);-+ const [busy, setBusy] = useState(false);-+ const [error, setError] = useState(false);-+ useEffect(() => {-+ let alive = true;-+ let revision = 0;-+ const read = async () => {-+ const current = ++revision;-+ const values = await chrome.storage.local.get(REMOTE_ENDPOINT_KEY);-+ if (!alive || current !== revision) return;-+ const remote = readRemoteEndpoint(values[REMOTE_ENDPOINT_KEY]);-+ setServer(remote?.url ?? null);-+ onRemoteChange?.(remote !== null);-+ setReady(true);-+ };-+ const changed = (changes: Record<string, chrome.storage.StorageChange>, area: string) => {-+ if (area === "local" && changes[REMOTE_ENDPOINT_KEY])-+ void read().catch(() => alive && setError(true));-+ };-+ if (typeof chrome === "undefined" || !chrome.storage?.local) return;-+ chrome.storage.onChanged.addListener(changed);-+ void read().catch(() => {-+ if (alive) {-+ setError(true);-+ setReady(true);-+ }-+ });-+ return () => {-+ alive = false;-+ chrome.storage.onChanged.removeListener(changed);-+ };-+ }, [onRemoteChange]);-+ async function save(disconnect = false) {-+ if (busy) return;-+ setBusy(true);-+ setError(false);-+ try {-+ const reply = (await chrome.runtime.sendMessage({-+ kind: "bsk-remote-authorization",-+ pairing: disconnect ? null : draft,-+ })) as { url: string | null; error?: string };-+ if (reply.error) throw new Error(reply.error);-+ setServer(reply.url);-+ onRemoteChange?.(reply.url !== null);-+ setDraft("");-+ } catch {-+ setError(true);-+ } finally {-+ setBusy(false);-+ }-+ }-+ let destination = server;-+ try {-+ if (draft.trim()) destination = parseRemoteEndpoint(draft).url;-+ } catch {-+ /* Invalid drafts cannot be saved. */-+ }-+ return (-+ <details className="rounded-xl border border-border/80 bg-card/60 px-3 py-2.5">-+ <summary className="cursor-pointer text-sm font-medium">{t("popup.remoteTitle")}</summary>-+ <div className="mt-3 space-y-2">-+ <p className="break-all text-xs text-muted-foreground">-+ {destination ?? t("popup.remoteLocal")}-+ </p>-+ <Label htmlFor="remote-pairing">{t("popup.remotePairing")}</Label>-+ <Input-+ id="remote-pairing"-+ type="password"-+ autoComplete="off"-+ value={draft}-+ disabled={!ready || busy}-+ onChange={(e) => setDraft(e.target.value)}-+ />-+ <p className="text-xs text-muted-foreground">{t("popup.remoteHint")}</p>-+ <div className="flex gap-2">-+ <Button size="sm" disabled={!ready || busy || !draft.trim()} onClick={() => void save()}>-+ {t("popup.remoteSave")}-+ </Button>-+ <Button-+ size="sm"-+ variant="outline"-+ disabled={!ready || busy || (!server && !error)}-+ onClick={() => void save(true)}-+ >-+ {t("popup.remoteLocal")}-+ </Button>-+ </div>-+ {error && (-+ <p role="alert" className="text-xs text-destructive">-+ {t("popup.remoteError")}-+ </p>-+ )}-+ </div>-+ </details>-+ );-+}-diff --git a/apps/extension/src/entrypoints/popup/task-window-mode.test.tsx b/apps/extension/src/entrypoints/popup/task-window-mode.test.tsx-new file mode 100644-index 0000000..bfcf50e---- /dev/null-+++ b/apps/extension/src/entrypoints/popup/task-window-mode.test.tsx-@@ -0,0 +1,55 @@-+import { i18n } from "@browser-skill/i18n";-+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-+import { afterEach, beforeEach, expect, it, vi } from "vitest";-+import { getTaskWindowEnabled, TASK_WINDOW_KEY } from "@/lib/task-window-preference";-+import { TaskWindowMode } from "./task-window-mode";-+-+let data: Record<string, unknown>;-+let write: ReturnType<typeof vi.fn>;-+beforeEach(async () => {-+ await i18n.changeLanguage("zh-CN");-+ data = {};-+ write = vi.fn(async (values: object) => {-+ Object.assign(data, values);-+ });-+ vi.stubGlobal("chrome", { storage: { local: { get: async () => ({ ...data }), set: write } } });-+});-+afterEach(() => {-+ cleanup();-+ vi.unstubAllGlobals();-+});-+it("defaults to a separate window and preserves an explicit tab preference across popup remounts", async () => {-+ const view = render(<TaskWindowMode />);-+ const select = screen.getByRole("combobox") as HTMLSelectElement;-+ await waitFor(() => expect(select.disabled).toBe(false));-+ expect(select.value).toBe("window");-+ fireEvent.change(select, { target: { value: "tabs" } });-+ await waitFor(() => expect(select.value).toBe("tabs"));-+ expect(await getTaskWindowEnabled()).toBe(false);-+ expect(write).toHaveBeenCalledWith({ [TASK_WINDOW_KEY]: false });-+ view.unmount();-+ render(<TaskWindowMode />);-+ await waitFor(() =>-+ expect((screen.getByRole("combobox") as HTMLSelectElement).value).toBe("tabs"),-+ );-+});-+it("retains the default mode and exposes a failed write", async () => {-+ render(<TaskWindowMode />);-+ const select = screen.getByRole("combobox") as HTMLSelectElement;-+ await waitFor(() => expect(select.disabled).toBe(false));-+ write.mockRejectedValueOnce(new Error("storage unavailable"));-+ fireEvent.change(select, { target: { value: "tabs" } });-+ await screen.findByRole("alert");-+ expect(select.value).toBe("window");-+ expect(await getTaskWindowEnabled()).toBe(true);-+});-+-+it("loads an explicitly saved separate-window preference", async () => {-+ data[TASK_WINDOW_KEY] = true;-+ render(<TaskWindowMode />);-+ const select = screen.getByRole("combobox") as HTMLSelectElement;-+ await waitFor(() => expect(select.disabled).toBe(false));-+ expect(select.value).toBe("window");-+ expect(await getTaskWindowEnabled()).toBe(true);-+ expect(write).not.toHaveBeenCalled();-+});-diff --git a/apps/extension/src/entrypoints/popup/task-window-mode.tsx b/apps/extension/src/entrypoints/popup/task-window-mode.tsx-new file mode 100644-index 0000000..7894c9b---- /dev/null-+++ b/apps/extension/src/entrypoints/popup/task-window-mode.tsx-@@ -0,0 +1,62 @@-+import { useTranslation } from "@browser-skill/i18n/react";-+import { useEffect, useState } from "react";-+import { getTaskWindowEnabled, setTaskWindowEnabled } from "@/lib/task-window-preference";-+-+export function TaskWindowMode() {-+ const { t } = useTranslation("extension");-+ const [enabled, setEnabled] = useState(true);-+ const [loaded, setLoaded] = useState(false);-+ const [saving, setSaving] = useState(false);-+ const [error, setError] = useState(false);-+ useEffect(() => {-+ let cancelled = false;-+ getTaskWindowEnabled()-+ .then((value) => {-+ if (!cancelled) {-+ setEnabled(value);-+ setLoaded(true);-+ }-+ })-+ .catch(() => {-+ if (!cancelled) setError(true);-+ });-+ return () => {-+ cancelled = true;-+ };-+ }, []);-+ async function update(value: boolean) {-+ setSaving(true);-+ setError(false);-+ try {-+ await setTaskWindowEnabled(value);-+ setEnabled(value);-+ } catch {-+ setError(true);-+ } finally {-+ setSaving(false);-+ }-+ }-+ return (-+ <section className="rounded-xl border border-border/80 bg-card/60 px-3 py-2.5">-+ <label htmlFor="bsk-task-window-mode" className="text-sm font-medium">-+ {t("popup.taskWindowTitle")}-+ </label>-+ <select-+ id="bsk-task-window-mode"-+ value={enabled ? "window" : "tabs"}-+ disabled={!loaded || saving}-+ onChange={(event) => void update(event.target.value === "window")}-+ className="mt-2 w-full rounded-md border border-border bg-background px-2 py-1.5 text-sm"-+ >-+ <option value="window">{t("popup.taskWindowVisible")}</option>-+ <option value="tabs">{t("popup.taskWindowTabs")}</option>-+ </select>-+ <p className="mt-2 text-xs leading-snug text-muted-foreground">{t("popup.taskWindowHint")}</p>-+ {error && (-+ <p role="alert" className="mt-2 text-xs text-destructive">-+ {t("popup.taskWindowError")}-+ </p>-+ )}-+ </section>-+ );-+}-diff --git a/apps/extension/src/lib/__tests__/daemon-connection-preference.test.ts b/apps/extension/src/lib/__tests__/daemon-connection-preference.test.ts-new file mode 100644-index 0000000..5c61936---- /dev/null-+++ b/apps/extension/src/lib/__tests__/daemon-connection-preference.test.ts-@@ -0,0 +1,50 @@-+import { afterEach, expect, it, vi } from "vitest";-+import { watchDaemonConnection } from "../daemon-connection-preference";-+-+afterEach(() => vi.unstubAllGlobals());-+it("a late startup read cannot overwrite newer credentials", async () => {-+ let changed: (values: unknown, area: string) => void = () => {};-+ const resolvers: Array<(value: unknown) => void> = [];-+ vi.stubGlobal("chrome", {-+ storage: {-+ local: { get: () => new Promise((resolve) => resolvers.push(resolve)) },-+ onChanged: {-+ addListener: (fn: typeof changed) => {-+ changed = fn;-+ },-+ removeListener: vi.fn(),-+ },-+ },-+ });-+ const callback = vi.fn();-+ const watch = watchDaemonConnection(callback);-+ changed({ bsk_remote_endpoint: {} }, "local");-+ const remote = { url: "wss://example.com/bsk", token: "a".repeat(43) };-+ resolvers[1]({ bsk_remote_endpoint: remote });-+ await Promise.resolve();-+ resolvers[0]({ bsk_daemon_port: 1234 });-+ await watch.ready;-+ expect(callback).toHaveBeenCalledTimes(1);-+ expect(callback).toHaveBeenCalledWith(remote.url, remote);-+ watch.dispose();-+});-+it("disposal prevents pending reads from configuring a connection", async () => {-+ let finish: (value: unknown) => void = () => {};-+ vi.stubGlobal("chrome", {-+ storage: {-+ local: {-+ get: () =>-+ new Promise((resolve) => {-+ finish = resolve;-+ }),-+ },-+ onChanged: { addListener: vi.fn(), removeListener: vi.fn() },-+ },-+ });-+ const callback = vi.fn();-+ const watch = watchDaemonConnection(callback);-+ watch.dispose();-+ finish({});-+ await watch.ready;-+ expect(callback).not.toHaveBeenCalled();-+});-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..5fe54f2---- /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", { tabMode: true }],-+ ["two", { tabMode: 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..fc0b8d3---- /dev/null-+++ b/apps/extension/src/lib/__tests__/task-preview.test.ts-@@ -0,0 +1,131 @@-+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 = {-+ tabMode: true,-+ activeTabId: 5,-+ agentCreatedTabs: new Set([5]),-+ borrowedTabs: new Map(),-+ };-+ const manager = { get: () => task } as unknown as SessionManager;-+ const cdp = {-+ 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: { 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",-+ );-+ });-+});-diff --git a/apps/extension/src/lib/daemon-connection-preference.ts b/apps/extension/src/lib/daemon-connection-preference.ts-new file mode 100644-index 0000000..f021fe8---- /dev/null-+++ b/apps/extension/src/lib/daemon-connection-preference.ts-@@ -0,0 +1,39 @@-+import { normalizeDaemonPort, resolveDaemonWsUrl } from "@/transport/daemon-endpoint";-+import {-+ REMOTE_ENDPOINT_KEY,-+ type RemoteEndpoint,-+ readRemoteEndpoint,-+} from "@/transport/remote-endpoint";-+import { STORAGE_KEYS } from "./instance-id";-+-+/** Keep the port and remote credential in one snapshot. Invalid remote state never falls back locally. */-+export function watchDaemonConnection(-+ onChange: (url: string, remote: RemoteEndpoint | null) => void,-+) {-+ let disposed = false;-+ let revision = 0;-+ const read = async () => {-+ const current = ++revision;-+ const values = await chrome.storage.local.get([STORAGE_KEYS.DAEMON_PORT, REMOTE_ENDPOINT_KEY]);-+ if (disposed || revision !== current) return;-+ const remote = readRemoteEndpoint(values[REMOTE_ENDPOINT_KEY]);-+ onChange(-+ remote?.url ?? resolveDaemonWsUrl(normalizeDaemonPort(values[STORAGE_KEYS.DAEMON_PORT])),-+ remote,-+ );-+ };-+ const changed = (changes: Record<string, chrome.storage.StorageChange>, area: string) => {-+ if (area === "local" && (changes[STORAGE_KEYS.DAEMON_PORT] || changes[REMOTE_ENDPOINT_KEY])) {-+ // Invalid writes are not supported; do not redirect the active connection to localhost.-+ void read().catch(() => console.error("[connection] invalid connection preference"));-+ }-+ };-+ chrome.storage.onChanged.addListener(changed);-+ return {-+ ready: read(),-+ dispose: () => {-+ disposed = true;-+ chrome.storage.onChanged.removeListener(changed);-+ },-+ };-+}-diff --git a/apps/extension/src/lib/task-activity.ts b/apps/extension/src/lib/task-activity.ts-new file mode 100644-index 0000000..3f5018d---- /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?.tabMode) 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..8f8331d---- /dev/null-+++ b/apps/extension/src/lib/task-preview.ts-@@ -0,0 +1,83 @@-+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) throw new Error("Task unavailable");-+ const tabId =-+ task.activeTabId !== undefined && isAgentControlledTab(task, task.activeTabId)-+ ? task.activeTabId-+ : [...task.agentCreatedTabs, ...task.borrowedTabs.keys()][0];-+ 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);-+ 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))-+ 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))-+ throw new Error("Task ended during capture");-+ return {-+ image_base64: data,-+ format: "jpeg",-+ tab_id: tabId,-+ title: tab.title ?? "",-+ captured_at: new Date().toISOString(),-+ };-+}-diff --git a/apps/extension/src/lib/task-window-preference.ts b/apps/extension/src/lib/task-window-preference.ts-new file mode 100644-index 0000000..09a4eef---- /dev/null-+++ b/apps/extension/src/lib/task-window-preference.ts-@@ -0,0 +1,11 @@-+export const TASK_WINDOW_KEY = "bsk.remoteTaskWindowEnabled";-+-+/** Read when a new remote task starts; existing tasks keep their original mode. */-+export async function getTaskWindowEnabled(): Promise<boolean> {-+ const stored = await chrome.storage.local.get(TASK_WINDOW_KEY);-+ return stored[TASK_WINDOW_KEY] !== false;-+}-+-+export async function setTaskWindowEnabled(enabled: boolean): Promise<void> {-+ await chrome.storage.local.set({ [TASK_WINDOW_KEY]: enabled });-+}-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..ce40618---- /dev/null-+++ b/apps/extension/src/session-manager/__tests__/task-popups.test.ts-@@ -0,0 +1,135 @@-+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-+import { SessionManager } from "../manager";-+import { withTaskPopups } from "../task-popups";-+-+describe("page-created task tabs", () => {-+ let manager: SessionManager;-+ let tabs: Map<number, any>;-+ let listeners: Set<(event: { sourceTabId: number; tabId: number }) => void>;-+ let api: any;-+ let activations: Set<(event: { tabId: number }) => void>;-+ beforeEach(() => {-+ listeners = new Set();-+ activations = new Set();-+ tabs = new Map([-+ [1, { id: 1, windowId: 10, active: true }],-+ [2, { id: 2, windowId: 10, active: false }],-+ ]);-+ let id = 10;-+ api = {-+ onActivated: {-+ addListener: (fn: any) => activations.add(fn),-+ removeListener: (fn: any) => activations.delete(fn),-+ },-+ query: vi.fn(async () => [...tabs.values()].filter((t) => t.active)),-+ get: vi.fn(async (id: number) => {-+ if (!tabs.has(id)) throw new Error("closed");-+ return tabs.get(id);-+ }),-+ create: vi.fn(async (props: any) => {-+ const tab = { id: ++id, ...props };-+ tabs.set(tab.id, tab);-+ return tab;-+ }),-+ update: vi.fn(async (id: number, props: any) => {-+ if (props.active) for (const tab of tabs.values()) tab.active = false;-+ return Object.assign(tabs.get(id), props);-+ }),-+ group: vi.fn(async () => 7),-+ ungroup: vi.fn(async (id: number) => { tabs.get(id).groupId = -1; }),-+ move: vi.fn(async (id: number, props: any) => Object.assign(tabs.get(id), props)),-+ remove: vi.fn(async (id: number) => {-+ tabs.delete(id);-+ manager.forgetClosedTab(id);-+ }),-+ };-+ vi.stubGlobal("chrome", {-+ tabs: api,-+ tabGroups: { update: vi.fn() },-+ windows: { getAll: vi.fn(async () => [{ id: 10, focused: true }]), remove: vi.fn() },-+ webNavigation: {-+ onCreatedNavigationTarget: {-+ addListener: (fn: any) => listeners.add(fn),-+ removeListener: (fn: any) => listeners.delete(fn),-+ },-+ },-+ });-+ manager = new SessionManager({ taskTabs: () => true });-+ });-+ afterEach(() => vi.unstubAllGlobals());-+ const notify = (sourceTabId: number, tabId: number) => {-+ for (const fn of listeners) fn({ sourceTabId, tabId });-+ };-+ it("claims noopener and nested popups and closes every owned tab, preserving user and other-task tabs", async () => {-+ const task = await manager.start("one"),-+ other = await manager.start("two");-+ const start = task.activeTabId!;-+ await withTaskPopups(manager, { session_id: task.sessionId }, async () => {-+ // No openerTabId: webNavigation is the authoritative source link.-+ tabs.set(20, { id: 20, windowId: 10, active: true, groupId: 7 });-+ notify(start, 20);-+ tabs.set(21, { id: 21, windowId: 10, active: false });-+ notify(20, 21);-+ // Being dragged into the same group must not grant ownership.-+ tabs.set(22, { id: 22, windowId: 10, active: false, groupId: 7 });-+ notify(1, 22);-+ });-+ expect(task.agentCreatedTabs).toEqual(new Set([start, 20, 21]));-+ expect(task.activeTabId).toBe(21);-+ expect(tabs.get(1).active).toBe(true);-+ expect(api.group).toHaveBeenCalledWith({ tabIds: [20], groupId: 7 });-+ expect(listeners.size).toBe(0);-+ await manager.stop(task.sessionId);-+ expect([...tabs.keys()].sort((a, b) => a - b)).toEqual([1, 2, other.activeTabId!, 22]);-+ expect(chrome.windows.remove).not.toHaveBeenCalled();-+ });-+ it("does not take tabs from other tasks or override a user's later tab switch", async () => {-+ const task = await manager.start("one"),-+ other = await manager.start("two");-+ await withTaskPopups(manager, { session_id: task.sessionId }, async () => {-+ tabs.set(20, { id: 20, windowId: 10, active: false });-+ notify(task.activeTabId!, 20);-+ tabs.get(1).active = false;-+ tabs.get(2).active = true;-+ notify(other.activeTabId!, other.activeTabId!);-+ });-+ expect(api.update).not.toHaveBeenCalled();-+ expect(task.agentCreatedTabs.has(other.activeTabId!)).toBe(false);-+ expect(tabs.get(2).active).toBe(true);-+ });-+ it("restores focus even when Chrome activates after the navigation event", async () => {-+ const task = await manager.start("one");-+ await withTaskPopups(manager, { session_id: task.sessionId }, async () => {-+ tabs.set(20, { id: 20, windowId: 10, active: false });-+ notify(task.activeTabId!, 20);-+ await new Promise((resolve) => setTimeout(resolve, 10));-+ tabs.get(1).active = false;-+ tabs.get(20).active = true;-+ for (const fn of activations) fn({ tabId: 20 });-+ });-+ expect(tabs.get(1).active).toBe(true);-+ expect(activations.size).toBe(0);-+ });-+ it("keeps a popup claim when its visual group is removed and drains events after cancelled input", async () => {-+ const task = await manager.start("one");-+ api.group.mockRejectedValueOnce(new Error("group removed"));-+ await expect(-+ withTaskPopups(manager, { session_id: task.sessionId }, async () => {-+ tabs.set(20, { id: 20, windowId: 10, active: false });-+ notify(task.activeTabId!, 20);-+ throw new Error("input cancelled");-+ }),-+ ).rejects.toThrow("input cancelled");-+ expect(listeners.size).toBe(0);-+ expect(task.agentCreatedTabs.has(20)).toBe(true);-+ await manager.stop(task.sessionId);-+ expect(tabs.has(20)).toBe(false);-+ });-+ it("does not attribute later manual navigation to completed input", async () => {-+ const task = await manager.start("one");-+ await withTaskPopups(manager, { session_id: task.sessionId }, async () => {});-+ tabs.set(20, { id: 20, windowId: 10, active: true });-+ notify(task.activeTabId!, 20);-+ expect(task.agentCreatedTabs.has(20)).toBe(false);-+ });-+});-diff --git a/apps/extension/src/session-manager/__tests__/task-tabs.test.ts b/apps/extension/src/session-manager/__tests__/task-tabs.test.ts-new file mode 100644-index 0000000..6b65d8a---- /dev/null-+++ b/apps/extension/src/session-manager/__tests__/task-tabs.test.ts-@@ -0,0 +1,201 @@-+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-+import { enforceAgentWindow, resolveTargetTab } from "@/tools/shared";-+import {-+ handleTabBorrow,-+ handleTabCreate,-+ handleTabList,-+ handleTabReturn,-+ handleTabSelect,-+} from "@/tools/tabs";-+import { SessionManager } from "../manager";-+-+describe("remote task tabs", () => {-+ let manager: SessionManager;-+ let tabs: Map<number, any>;-+ let api: any;-+ beforeEach(() => {-+ tabs = new Map([-+ [1, { id: 1, windowId: 10, active: true, index: 0, url: "https://chat.example" }],-+ ]);-+ let id = 10;-+ api = {-+ get: vi.fn(async (id: number) => {-+ if (!tabs.has(id)) throw new Error("missing");-+ return tabs.get(id);-+ }),-+ query: vi.fn(async () => [...tabs.values()]),-+ create: vi.fn(async (props: any) => {-+ const tab = { id: ++id, index: tabs.size, ...props };-+ tabs.set(tab.id, tab);-+ return tab;-+ }),-+ update: vi.fn(async (id: number, props: any) => Object.assign(tabs.get(id), props)),-+ remove: vi.fn(async (id: number) => {-+ tabs.delete(id);-+ }),-+ move: vi.fn(),-+ group: vi.fn(async ({ tabIds }: { tabIds: number[] }) => {-+ for (const tabId of tabIds) tabs.get(tabId).groupId = 7;-+ return 7;-+ }),-+ ungroup: vi.fn(async (tabId: number) => { tabs.get(tabId).groupId = -1; }),-+ };-+ vi.stubGlobal("chrome", {-+ tabs: api,-+ windows: {-+ getAll: vi.fn(async () => [{ id: 10, focused: true, type: "normal" }]),-+ create: vi.fn(async () => ({ id: 20, tabs: [await api.create({ windowId: 20, active: true })] })),-+ remove: vi.fn(),-+ },-+ tabGroups: { update: vi.fn() },-+ });-+ manager = new SessionManager({ taskTabs: () => true, taskLabel: () => "WeKnora" });-+ });-+ afterEach(() => vi.unstubAllGlobals());-+ it("opens opted-in tasks in a visible window and only selects tabs inside it", async () => {-+ manager = new SessionManager({ taskTabs: () => true, taskWindow: async () => true });-+ const task = await manager.start("visible");-+ expect(chrome.windows.create).toHaveBeenCalledWith(expect.objectContaining({ focused: true }));-+ expect(task).toMatchObject({ taskWindow: true, tabMode: true, agentWindowId: 20 });-+ expect(task.taskGroupId).toBeUndefined();-+ expect(api.group).not.toHaveBeenCalled();-+ const home = task.activeTabId!;-+ await handleTabCreate(manager, { session_id: task.sessionId }, { tabs: api });-+ expect(api.create).toHaveBeenLastCalledWith(expect.objectContaining({ windowId: 20, active: true }));-+ await handleTabSelect(manager, { session_id: task.sessionId, tab_id: home }, { tabs: api });-+ expect(api.update).toHaveBeenCalledWith(home, { active: true });-+ // A tab explicitly borrowed from the chat window must never be activated.-+ task.borrowedTabs.set(1, { originalWindowId: 10, originalIndex: 0 } as never);-+ api.update.mockClear();-+ await handleTabSelect(manager, { session_id: task.sessionId, tab_id: 1 }, { tabs: api });-+ expect(api.update).not.toHaveBeenCalled();-+ // User tabs moved into the task window are not owned by the task.-+ tabs.set(99, { id: 99, windowId: 20, active: false });-+ await manager.stop(task.sessionId);-+ expect([...tabs.keys()].sort()).toEqual([1, 99]);-+ expect(chrome.windows.remove).not.toHaveBeenCalled();-+ });-+ it("reads the preference for new tasks without moving existing tasks", async () => {-+ let visible = false;-+ manager = new SessionManager({ taskTabs: () => true, taskWindow: async () => visible });-+ const first = await manager.start("first");-+ visible = true;-+ expect(manager.get("first")).toBe(first);-+ const second = await manager.start("second");-+ expect(first.agentWindowId).toBe(10);-+ expect(second.agentWindowId).toBe(20);-+ });-+ it("cleans up only its own tab when visible-window startup fails", async () => {-+ manager = new SessionManager({ taskTabs: () => true, taskWindow: () => true });-+ const controller = new AbortController();-+ chrome.windows.create = vi.fn(async () => {-+ const home = await api.create({ windowId: 20, active: true });-+ tabs.set(99, { id: 99, windowId: 20 });-+ controller.abort();-+ return { id: 20, tabs: [home], focused: true, alwaysOnTop: false, incognito: false };-+ });-+ await expect(manager.start("failed", { signal: controller.signal })).rejects.toThrow();-+ expect([...tabs.keys()].sort()).toEqual([1, 99]);-+ expect(chrome.windows.remove).not.toHaveBeenCalled();-+ });-+ it("shares a host window, labels owned tabs, and never closes chat or another task", async () => {-+ const a = await manager.start("task-a"),-+ b = await manager.start("task-b");-+ expect(a.agentWindowId).toBe(b.agentWindowId);-+ expect(api.create).toHaveBeenCalledWith(-+ expect.objectContaining({ active: false, windowId: 10 }),-+ );-+ expect(chrome.tabGroups.update).toHaveBeenCalledWith(-+ 7,-+ expect.objectContaining({ title: "WeKnora" }),-+ );-+ expect(manager.findByWindowId(10)).toBeNull();-+ expect(manager.findByTabId(a.activeTabId!)).toBe(a);-+ expect(await resolveTargetTab(manager, a, 1, api)).toMatchObject({ code: "permission_denied" });-+ expect(await resolveTargetTab(manager, a, b.activeTabId, api)).toMatchObject({-+ code: "not_found",-+ });-+ expect(enforceAgentWindow(a, { tabId: 1, windowId: 10 }, "click")).toMatchObject({-+ code: "permission_denied",-+ });-+ await manager.stop(a.sessionId);-+ expect(tabs.has(1)).toBe(true);-+ expect(tabs.has(b.activeTabId!)).toBe(true);-+ expect(chrome.windows.remove).not.toHaveBeenCalled();-+ });-+ it("ungroups owned tabs before closing and preserves user tabs in the same group", async () => {-+ const task = await manager.start("cleanup");-+ const owned = task.activeTabId!;-+ tabs.set(99, { id: 99, windowId: 10, groupId: task.taskGroupId });-+ await manager.stop(task.sessionId);-+ expect(api.ungroup).toHaveBeenCalledExactlyOnceWith(owned);-+ expect(api.ungroup.mock.invocationCallOrder[0]).toBeLessThan(api.remove.mock.invocationCallOrder[0]);-+ expect(tabs.get(99).groupId).toBe(7);-+ expect(tabs.has(1)).toBe(true);-+ });-+ it("ungroups the startup tab if labeling the group fails", async () => {-+ vi.mocked(chrome.tabGroups.update).mockRejectedValueOnce(new Error("label failed"));-+ await expect(manager.start("failed-label")).rejects.toThrow("label failed");-+ expect(api.ungroup).toHaveBeenCalledTimes(1);-+ expect([...tabs.keys()]).toEqual([1]);-+ });-+ it("keeps failed cleanup retryable instead of reporting the task stopped", async () => {-+ const task = await manager.start("retry");-+ api.ungroup.mockRejectedValueOnce(new Error("busy"));-+ await expect(manager.stop(task.sessionId)).rejects.toThrow("busy");-+ expect(manager.get(task.sessionId)).toBe(task);-+ expect(api.remove).not.toHaveBeenCalled();-+ await manager.stop(task.sessionId);-+ expect(manager.get(task.sessionId)).toBeNull();-+ });-+ it("selects task tabs logically without activating the user tab bar", async () => {-+ const task = await manager.start("task-a");-+ const made = await handleTabCreate(-+ manager,-+ { session_id: task.sessionId, url: "https://example.com" },-+ { tabs: api },-+ );-+ expect(made).toHaveProperty("tab_id");-+ await handleTabSelect(-+ manager,-+ { session_id: task.sessionId, tab_id: task.activeTabId! },-+ { tabs: api },-+ );-+ expect(api.update).not.toHaveBeenCalled();-+ const target = await resolveTargetTab(manager, task, undefined, api);-+ expect(target).toMatchObject({ tabId: task.activeTabId, active: false });-+ const listed = await handleTabList(manager, { session_id: task.sessionId, scope: "user" }, api);-+ expect(listed).toMatchObject({ tabs: [expect.objectContaining({ tab_id: 1, scope: "user" })] });-+ });-+ it("requires approval for an existing tab and returns it without moving it", async () => {-+ const task = await manager.start("task-a");-+ const deny = await handleTabBorrow(-+ manager,-+ { session_id: task.sessionId, tab_id: 1 },-+ { tabs: api, approveBorrow: async () => false },-+ );-+ expect(deny).toHaveProperty("code");-+ expect(task.borrowedTabs.has(1)).toBe(false);-+ const allowed = await handleTabBorrow(-+ manager,-+ { session_id: task.sessionId, tab_id: 1 },-+ { tabs: api, approveBorrow: async () => true },-+ );-+ expect(allowed).toHaveProperty("tab_id", 1);-+ expect(api.move).not.toHaveBeenCalled();-+ expect(api.update).not.toHaveBeenCalled();-+ expect(enforceAgentWindow(task, { tabId: 1, windowId: 10 }, "click")).toBeNull();-+ await handleTabReturn(-+ manager,-+ { session_id: task.sessionId, tab_id: 1 },-+ {-+ tabs: api,-+ agentOverlayReset: { resetAgentOverlays: async () => {} },-+ cdp: { releaseSessionTab: async () => {} },-+ },-+ );-+ expect(api.move).not.toHaveBeenCalled();-+ expect(task.borrowedTabs.has(1)).toBe(false);-+ expect(tabs.get(1).active).toBe(true);-+ });-+});-diff --git a/apps/extension/src/session-manager/event-handler.ts b/apps/extension/src/session-manager/event-handler.ts-index 5afe53c..7709ba3 100644---- a/apps/extension/src/session-manager/event-handler.ts-+++ b/apps/extension/src/session-manager/event-handler.ts-@@ -49,45 +49,46 @@ export function attachSessionEventHandler(options: SessionEventHandlerOptions):- const events = options.windowEvents ?? chromeWindowEvents();-- const onRemoved = (windowId: number): void => {-- const ctx = manager.findByWindowId(windowId);-- if (!ctx) return;-- const returnFailures = Array.from(ctx.borrowedTabs.keys()).map((tabId) => ({-- tab_id: tabId,-- code: "cdp_failed",-- message: "Agent Window was closed before borrowed tab could be returned",-- }));-- if (returnFailures.length > 0) {-- console.warn(-- `[bh] Agent Window ${windowId} closed with borrowed tabs that could not be returned`,-- returnFailures,-- );-- }-- const detach = options.cdp-- ? options.cdp.detachSession(ctx.sessionId).catch((err) => {-- console.debug("[bh] session-event cdp detach failed", err);-+ const affected = manager.list().filter((ctx) => !ctx.tabMode && ctx.agentWindowId === windowId);-+ for (const ctx of affected) {-+ const returnFailures = Array.from(ctx.borrowedTabs.keys()).map((tabId) => ({-+ tab_id: tabId,-+ code: "cdp_failed",-+ message: "Agent Window was closed before borrowed tab could be returned",-+ }));-+ if (returnFailures.length > 0) {-+ console.warn(-+ `[bh] Agent Window ${windowId} closed with borrowed tabs that could not be returned`,-+ returnFailures,-+ );-+ }-+ const detach = options.cdp-+ ? options.cdp.detachSession(ctx.sessionId).catch((err) => {-+ console.debug("[bh] session-event cdp detach failed", err);-+ })-+ : Promise.resolve();-+ void detach-+ .then(() => manager.stop(ctx.sessionId, { dropOnly: true }))-+ .then(() => {-+ onSessionsChanged?.();-+ const event: EventFrame = {-+ event: "session.window_closed",-+ payload: {-+ session_id: ctx.sessionId,-+ reason: "user_closed_window",-+ ...(returnFailures.length > 0 ? { return_failures: returnFailures } : {}),-+ },-+ };-+ try {-+ transport.send(event);-+ } catch (err) {-+ console.warn("[bh] could not push session.window_closed event", err);-+ }- })-- : Promise.resolve();-- void detach-- .then(() => manager.stop(ctx.sessionId, { dropOnly: true }))-- .then(() => {-- onSessionsChanged?.();-- const event: EventFrame = {-- event: "session.window_closed",-- payload: {-- session_id: ctx.sessionId,-- reason: "user_closed_window",-- ...(returnFailures.length > 0 ? { return_failures: returnFailures } : {}),-- },-- };-- try {-- transport.send(event);-- } catch (err) {-- console.warn("[bh] could not push session.window_closed event", err);-- }-- })-- .catch((err) => {-- console.warn("[bh] session-event handler failed", err);-- });-+ .catch((err) => {-+ console.warn("[bh] session-event handler failed", err);-+ });-+ }- };-- events.addListener(onRemoved);-diff --git a/apps/extension/src/session-manager/manager.ts b/apps/extension/src/session-manager/manager.ts-index 97982e3..f62e500 100644---- a/apps/extension/src/session-manager/manager.ts-+++ b/apps/extension/src/session-manager/manager.ts-@@ -4,6 +4,13 @@ import { RefStore } from "./ref-store";- export interface SessionContext {- sessionId: string;- agentWindowId: number;-+ /** Remote tasks retain explicit per-tab ownership, including in a dedicated window. */-+ tabMode?: boolean;-+ /** A dedicated task window may select its own tabs without focusing the window. */-+ taskWindow?: boolean;-+ stopping?: boolean;-+ activeTabId?: number;-+ taskGroupId?: number;- refStore: RefStore;- borrowedTabs: Map<number, BorrowedTab>;- /**-@@ -24,6 +31,7 @@ export interface BorrowedTab {- tabId: number;- originalWindowId: number;- originalIndex: number;-+ stationary?: boolean;- }-- export interface BorrowReservation {-@@ -34,6 +42,9 @@ export interface BorrowReservation {- export interface SessionManagerOptions {- agentWindow?: AgentWindowApi;- now?: () => number;-+ taskTabs?: () => boolean;-+ taskWindow?: () => boolean | Promise<boolean>;-+ taskLabel?: () => string;- }-- /** Options for starting a session's Agent Window. */-@@ -94,10 +105,16 @@ export class SessionManager {- private readonly borrowReservations = new Map<number, string>();- private readonly agentWindow: AgentWindowApi;- private readonly now: () => number;-+ private readonly taskTabs: () => boolean;-+ private readonly taskWindow: () => boolean | Promise<boolean>;-+ private readonly taskLabel: () => string;-- constructor(options: SessionManagerOptions = {}) {- this.agentWindow = options.agentWindow ?? chromeAgentWindowApi;- this.now = options.now ?? Date.now;-+ this.taskTabs = options.taskTabs ?? (() => false);-+ this.taskWindow = options.taskWindow ?? (() => false);-+ this.taskLabel = options.taskLabel ?? (() => "BrowserSkill");- }-- has(sessionId: string): boolean {-@@ -113,6 +130,10 @@ export class SessionManager {- return id ? (this.sessions.get(id) ?? null) : null;- }--+ findByTabId(tabId: number): SessionContext | null {-+ return this.list().find((ctx) => isAgentControlledTab(ctx, tabId)) ?? null;-+ }-+- list(): SessionContext[] {- return Array.from(this.sessions.values());- }-@@ -126,7 +147,7 @@ export class SessionManager {- this.borrowReservations.delete(tabId);- for (const ctx of this.sessions.values()) {- ctx.agentCreatedTabs.delete(tabId);-- if (!isWindowClosing) ctx.borrowedTabs.delete(tabId);-+ if (ctx.tabMode || !isWindowClosing) ctx.borrowedTabs.delete(tabId);- }- }--@@ -198,6 +219,78 @@ export class SessionManager {- }- throwIfSessionStartAborted(opts.signal);--+ if (this.taskTabs()) {-+ const dedicated = await this.taskWindow();-+ throwIfSessionStartAborted(opts.signal);-+ let hostId: number;-+ let home: chrome.tabs.Tab;-+ if (dedicated) {-+ // Explicitly opted-in visible mode. Bring the new window forward once;-+ // later task-tab changes must not focus the window or the user's tabs.-+ const host = await chrome.windows.create({-+ url: AGENT_WINDOW_HOME,-+ type: "normal",-+ focused: true,-+ width: opts.size?.width ?? 1100,-+ height: opts.size?.height ?? 800,-+ });-+ if (host.id === undefined) throw new Error("Could not create task window");-+ hostId = host.id;-+ const initial = host.tabs?.[0];-+ if (initial?.id === undefined) {-+ await chrome.windows.remove(hostId);-+ throw new Error("Could not create task tab");-+ }-+ home = initial;-+ } else {-+ const windows = await chrome.windows.getAll({ windowTypes: ["normal"] });-+ const host =-+ windows.find((w) => w.focused && !w.incognito) ?? windows.find((w) => !w.incognito);-+ if (host?.id === undefined)-+ throw new Error("Open a normal Chrome window before starting a browser task");-+ hostId = host.id;-+ home = await chrome.tabs.create({-+ windowId: hostId,-+ url: AGENT_WINDOW_HOME,-+ active: false,-+ });-+ }-+ if (home.id === undefined) throw new Error("Could not create task tab");-+ try {-+ throwIfSessionStartAborted(opts.signal);-+ // A dedicated window already groups the task visually. Avoid creating-+ // another Chrome group that can be auto-saved to the bookmarks bar.-+ let groupId: number | undefined;-+ if (!dedicated) {-+ groupId = await chrome.tabs.group({ tabIds: [home.id] });-+ await chrome.tabGroups.update(groupId, {-+ title: this.taskLabel().slice(0, 48),-+ color: "green",-+ collapsed: false,-+ });-+ }-+ throwIfSessionStartAborted(opts.signal);-+ const ctx: SessionContext = {-+ sessionId,-+ agentWindowId: hostId,-+ tabMode: true,-+ ...(dedicated ? { taskWindow: true } : {}),-+ activeTabId: home.id,-+ taskGroupId: groupId,-+ refStore: new RefStore(),-+ borrowedTabs: new Map(),-+ agentCreatedTabs: new Set([home.id]),-+ createdAtMs: this.now(),-+ };-+ this.sessions.set(sessionId, ctx);-+ return ctx;-+ } catch (err) {-+ // Only remove our tab: a user may have moved other tabs into the window-+ // while startup was in progress. Chrome closes an empty window itself.-+ await this.closeTaskTab(home.id);-+ throw err;-+ }-+ }- let windowId: number | null = null;- try {- const { signal: _signal, ...createOptions } = opts;-@@ -246,13 +339,35 @@ export class SessionManager {- const ctx = this.sessions.get(sessionId);- if (!ctx) return null;- if (!options.dropOnly) {-- await this.agentWindow.remove(ctx.agentWindowId);-+ ctx.stopping = true;-+ if (ctx.tabMode) {-+ // Never close the shared user window, even when queries/cleanup fail.-+ for (const tabId of ctx.agentCreatedTabs) {-+ await this.closeTaskTab(tabId);-+ }-+ } else await this.agentWindow.remove(ctx.agentWindowId);- }- this.sessions.delete(sessionId);-- this.windowIndex.delete(ctx.agentWindowId);-+ if (!ctx.tabMode) this.windowIndex.delete(ctx.agentWindowId);- return ctx;- }--+ private async closeTaskTab(tabId: number): Promise<void> {-+ let tab: chrome.tabs.Tab;-+ try {-+ tab = await chrome.tabs.get(tabId);-+ } catch {-+ return;-+ }-+ // Remove only owned tabs from their group before closing. Closing a-+ // saved group directly can keep it in Chrome's saved-group menu.-+ // Never ungroup the whole group: the user may have added their tabs.-+ if (tab.groupId !== undefined && tab.groupId >= 0) {-+ await chrome.tabs.ungroup(tabId);-+ }-+ await chrome.tabs.remove(tabId);-+ }-+- /**- * Best-effort cleanup of every live session (emergency brake / SW- * shutdown). Returns the set of `session_id`s that were removed.-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..c089468---- /dev/null-+++ b/apps/extension/src/session-manager/task-popups.ts-@@ -0,0 +1,96 @@-+import { isAgentControlledTab, type SessionManager } from "./manager";-+-+/** Track page-created tabs only while dispatching input to a known task tab.-+ * Group membership and tabs.onCreated alone are never ownership evidence.-+ * webNavigation also supplies sourceTabId for rel=noopener links.-+ */-+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 source = params.tab_id ?? task?.activeTabId;-+ if (-+ !task?.tabMode ||-+ task.stopping ||-+ source === undefined ||-+ !isAgentControlledTab(task, source)-+ )-+ return run();-+-+ const [foreground] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });-+ const sources = new Set([source]);-+ const pending = new Set<Promise<void>>();-+ const popups = new Set<number>();-+ const track = (work: Promise<void>) => {-+ pending.add(work);-+ void work.finally(() => pending.delete(work));-+ };-+ const restore = async (tabId: number) => {-+ try {-+ const tab = await chrome.tabs.get(tabId);-+ if (task.taskWindow && tab.windowId === task.agentWindowId) return;-+ if (foreground?.id !== undefined && tab.active)-+ await chrome.tabs.update(foreground.id, { active: true });-+ } catch {-+ /* The popup or previous foreground tab may have closed. */-+ }-+ };-+ const activated = ({ tabId }: { tabId: number }) => {-+ if (popups.has(tabId)) track(restore(tabId));-+ };-+ const created = ({ sourceTabId, tabId }: { sourceTabId: number; tabId: number }) => {-+ if (-+ !sources.has(sourceTabId) ||-+ task.stopping ||-+ manager.get(task.sessionId) !== task ||-+ manager.findByTabId(tabId)-+ )-+ return;-+ // Claim synchronously, before grouping/focus work or a concurrent stop.-+ task.agentCreatedTabs.add(tabId);-+ task.activeTabId = tabId;-+ sources.add(tabId);-+ popups.add(tabId);-+ const work = (async () => {-+ try {-+ let tab = await chrome.tabs.get(tabId);-+ // Chrome activates renderer-created tabs before extension events. Restore-+ // only if that popup still owns focus; never override a later user switch.-+ await restore(tabId);-+ if (task.stopping || manager.get(task.sessionId) !== task) return;-+ if (tab.windowId !== task.agentWindowId) {-+ await chrome.tabs.move(tabId, { windowId: task.agentWindowId, index: -1 });-+ tab = await chrome.tabs.get(tabId);-+ }-+ if (task.taskGroupId !== undefined) {-+ try {-+ await chrome.tabs.group({ tabIds: [tabId], groupId: task.taskGroupId });-+ } catch {-+ /* A removed group never releases the ownership claim. */-+ }-+ }-+ if (task.taskWindow) await chrome.tabs.update(tabId, { active: true });-+ onClaimed?.(tabId, tab.windowId);-+ } catch (error) {-+ // Preserve ownership if Chrome races with cleanup so stop can retry.-+ console.warn("[bsk] task popup setup failed", error);-+ }-+ })();-+ track(work);-+ };-+ chrome.tabs.onActivated.addListener(activated);-+ chrome.webNavigation.onCreatedNavigationTarget.addListener(created);-+ try {-+ return await run();-+ } finally {-+ // Renderer navigation events can follow the CDP input acknowledgement.-+ // Drain that bounded tail before releasing this input's source attribution.-+ await new Promise((resolve) => setTimeout(resolve, 100));-+ chrome.webNavigation.onCreatedNavigationTarget.removeListener(created);-+ while (pending.size) await Promise.all(pending);-+ chrome.tabs.onActivated.removeListener(activated);-+ }-+}-diff --git a/apps/extension/src/tools/__tests__/human-loop.test.ts b/apps/extension/src/tools/__tests__/human-loop.test.ts-index d695233..74c18db 100644---- a/apps/extension/src/tools/__tests__/human-loop.test.ts-+++ b/apps/extension/src/tools/__tests__/human-loop.test.ts-@@ -86,6 +86,22 @@ describe("handleRequestHelp", () => {- vi.unstubAllGlobals();- });--+ it("remote task help never activates a tab or window", async () => {-+ const manager = fakeManager("abcd", 99, 5);-+ const ctx = {-+ ...manager.get("abcd")!,-+ tabMode: true,-+ activeTabId: 5,-+ agentCreatedTabs: new Set([5]),-+ };-+ manager.get = (id) => (id === "abcd" ? ctx : null);-+ const deps = baseDeps();-+ const result = await handleRequestHelp(manager, baseParams({ tab_id: 5 }), deps);-+ expect(result).toMatchObject({ outcome: "continued" });-+ expect(deps.windows.update).not.toHaveBeenCalled();-+ expect(deps.activateTab).not.toHaveBeenCalled();-+ });-+- it("rejects unknown session", async () => {- const res = await handleRequestHelp(- fakeManager("abcd", 99, 5),-diff --git a/apps/extension/src/tools/borrow-confirmation.ts b/apps/extension/src/tools/borrow-confirmation.ts-index b575084..066bd2f 100644---- a/apps/extension/src/tools/borrow-confirmation.ts-+++ b/apps/extension/src/tools/borrow-confirmation.ts-@@ -89,6 +89,7 @@ export interface RequestBorrowConfirmationDeps {- /** Returns `true` when `windowId` belongs to *any* live session's Agent Window. */- isAgentWindowId?: (windowId: number) => boolean;- notificationCopy?: BorrowNotificationCopy;-+ focusOnRequest?: boolean;- }-- export interface RequestBorrowConfirmationOptions {-@@ -483,9 +484,10 @@ export async function requestBorrowConfirmation(- // Bring the user window to the front so the overlay is visible even- // when the Agent Window has stolen focus. This is fire-and-forget: if- // it fails the overlay / OS notification still give the user a path.-- void windowsApi.update(notificationAnchor.windowId, { focused: true }).catch((err) => {-- console.debug("[bsk borrow] proactive focus of user window failed", err);-- });-+ if (options.deps?.focusOnRequest !== false)-+ void windowsApi.update(notificationAnchor.windowId, { focused: true }).catch((err) => {-+ console.debug("[bsk borrow] proactive focus of user window failed", err);-+ });-- // Surface the OS notification *before* messaging any candidate so the- // user has a parallel signal even if every content script is missing.-diff --git a/apps/extension/src/tools/dispatcher.ts b/apps/extension/src/tools/dispatcher.ts-index f29ed5e..54604da 100644---- a/apps/extension/src/tools/dispatcher.ts-+++ b/apps/extension/src/tools/dispatcher.ts-@@ -1,3 +1,5 @@-+import type { TaskActivity } from "@/lib/task-activity";-+import { withTaskPopups } from "@/session-manager/task-popups";- import { OVERLAY_AUTOMATION_BYPASS } from "@/lib/overlay-bridge";- import type { SessionManager } from "@/session-manager/manager";- import type { Transport } from "@/transport/transport";-@@ -121,6 +123,7 @@ interface HoverLatchScope {- }-- export interface DispatcherDeps {-+ taskActivity?: TaskActivity;- transport: Transport;- sessions: SessionManager;- cdp?: DispatcherCdpRunner;-@@ -159,6 +162,7 @@ export interface DispatcherDeps {- * takes the fast path.- */- export class ToolDispatcher {-+ private readonly taskActivity?: TaskActivity;- private readonly transport: Transport;- private readonly sessions: SessionManager;- private readonly cdp?: DispatcherCdpRunner;-@@ -180,6 +184,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.cdp = deps.cdp;-@@ -252,7 +257,33 @@ export class ToolDispatcher {- try {- const sessionId = sessionIdForBrowserControlMethod(req);- if (sessionId) this.onBrowserControlResumed?.(sessionId);-- const result = await this.invoke(req, ac.signal);-+ const popupInput = new Set([-+ "tool.click",-+ "tool.press",-+ "tool.evaluate",-+ "tool.navigate",-+ "tool.reload",-+ "tool.navigate_back",-+ "tool.navigate_forward",-+ "tool.fill",-+ "tool.select",-+ ]).has(req.method);-+ const invoke = () =>-+ popupInput-+ ? 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,-+ req.method === "tool.session_stop",-+ invoke,-+ )-+ : await invoke();- if (isRpcError(result)) {- body = { id: req.id, error: classifyCdpError(result) };- } else {-@@ -794,6 +825,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;-diff --git a/apps/extension/src/tools/human-loop.ts b/apps/extension/src/tools/human-loop.ts-index c50916e..ce8d829 100644---- a/apps/extension/src/tools/human-loop.ts-+++ b/apps/extension/src/tools/human-loop.ts-@@ -331,7 +331,7 @@ async function findHelpForTab(- const windowId = tab.windowId;- if (typeof windowId !== "number") return null;- for (const help of activeHelpRequests.values()) {-- if (!help.settled && help.ctx.agentWindowId === windowId) return help;-+ if (!help.settled && !help.ctx.tabMode && help.ctx.agentWindowId === windowId) return help;- }- } catch {- return null;-@@ -681,8 +681,10 @@ export async function handleRequestHelp(- { scrollIntoView: true },- );--- await deps.windows.update(target.windowId, { focused: true }).catch(() => {});-- await deps.activateTab(tabId).catch(() => {});-+ if (!ctx.tabMode) {-+ await deps.windows.update(target.windowId, { focused: true }).catch(() => {});-+ await deps.activateTab(tabId).catch(() => {});-+ }-- const requestId = makeRequestId(tabId);- const notificationId = `bsk-help:${requestId}`;-diff --git a/apps/extension/src/tools/observation.ts b/apps/extension/src/tools/observation.ts-index ea99ddf..bea0029 100644---- a/apps/extension/src/tools/observation.ts-+++ b/apps/extension/src/tools/observation.ts-@@ -242,6 +242,16 @@ async function captureFullTabPng(- signal?: AbortSignal,- ): Promise<string | RpcError> {- if (signal?.aborted) return cancelled("screenshot");-+ if (ctx.tabMode) {-+ if (!deps.cdp) return { code: "unsupported", message: "Task tab preview requires CDP" };-+ deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);-+ await deps.cdp.ensureAttachedToUrl?.(target.tabId, target.url);-+ const shot = await deps.cdp.send<{ data: string }>(target.tabId, "Page.captureScreenshot", {-+ format: "png",-+ fromSurface: true,-+ });-+ return shot.data;-+ }- try {- const dataUrl = await deps.captureApi.captureVisibleTab(target.windowId, { format: "png" });- if (signal?.aborted) return cancelled("screenshot");-@@ -343,7 +353,7 @@ export async function handleScreenshot(- });- }--- if (!target.active) {-+ if (!target.active && !ctx.tabMode) {- return rpcError(- "invalid_params",- "tab_not_active",-@@ -891,10 +901,19 @@ export async function captureVomObservation(- url: string | undefined,- options: CaptureVomObservationOptions = {},- ): Promise<CaptureVomObservationResult> {-+ const startedAt = performance.now();-+ let stageStartedAt = startedAt;-+ const timings: Record<string, number> = {};-+ const stage = (name: string) => {-+ const now = performance.now();-+ timings[name] = Math.round(now - stageStartedAt);-+ stageStartedAt = now;-+ };- throwIfAborted(options.signal, "observation");- await cdp.ensureAttachedToUrl?.(tabId, url);- throwIfAborted(options.signal, "observation");- const facts = await captureObservationFacts<CdpAxNode>(cdp, tabId, options.signal, url);-+ stage("capture");- const { captured, documents: normalizedDocuments } = semanticCapture(facts);- throwIfAborted(options.signal, "observation");- const semanticGraph = buildSemanticGraph({-@@ -904,6 +923,7 @@ export async function captureVomObservation(- excludedBackendNodeIds: captured.excludedBackendNodeIds,- });- const staticSemantics = resolveSemanticGraph(semanticGraph, { identifierFallback: false });-+ stage("semantic_graph");- const hoverProbes = await runHoverProbes(- cdp,- tabId,-@@ -913,6 +933,7 @@ export async function captureVomObservation(- options,- );- throwIfAborted(options.signal, "observation");-+ stage("hover");- const scene = projectSemanticGraph(- normalizeSemanticStructure(- resolveSemanticGraph(semanticGraph, { supplementalNames: hoverProbes.tooltipNames }),-@@ -924,6 +945,7 @@ export async function captureVomObservation(- captured,- hoverProbes.surfaceProbes,- );-+ stage("projection");- // Reserve space using the renderer's character-based token estimate. Like VOM- // headers, this integrity notice remains visible even under a tiny token budget.- const notices: string[] = [];-@@ -960,9 +982,10 @@ export async function captureVomObservation(- redactValues: options.redactValues,- activeRegionPolicy: options.activeRegionPolicy,- });-+ stage("render");- if (captureNotice) rendered.text += `\n${captureNotice}`;- throwIfAborted(options.signal, "observation");-- return projectRecordSafeObservation({-+ const result = projectRecordSafeObservation({- rootFrameId: captured.rootFrameId ?? normalizedDocuments[0]?.frameId ?? "root",- frameDocuments: normalizedDocuments,- rendered,-@@ -972,6 +995,18 @@ export async function captureVomObservation(- revealedContent: hoverProbes.revealedContent,- },- });-+ stage("record_projection");-+ const elapsedMs = Math.round(performance.now() - startedAt);-+ if (elapsedMs >= 2_000) {-+ console.warn("[bsk observe] slow observation completed", {-+ tabId,-+ elapsedMs,-+ timings,-+ nodes: semanticGraph.nodes.size,-+ refs: result.refs.length,-+ });-+ }-+ return result;- }-- async function handleVomObservation(-diff --git a/apps/extension/src/tools/session.ts b/apps/extension/src/tools/session.ts-index b6fe38f..4c2d94b 100644---- a/apps/extension/src/tools/session.ts-+++ b/apps/extension/src/tools/session.ts-@@ -281,6 +281,8 @@ export async function handleSessionStop(- return { code: "cancelled", message: "session_stop aborted before window close" };- }--+ ctx.stopping = true;-+- // Step 4: close every tab explicitly created by the agent, including the- // home tab. `tabsApi` is a- // TabMutationApi (remove only); `queryApi` is a separate read-only-@@ -303,6 +305,13 @@ export async function handleSessionStop(- }- }--+ if (ctx.tabMode) {-+ // Finish closing explicitly owned tabs, surfacing failures. The shared-+ // host window and every user/other-task tab must always survive cleanup.-+ await manager.stop(params.session_id);-+ return result;-+ }-+- // Step 5: decide whether to release (keep) the window or close it.- let shouldRelease = false;- if (queryApi) {-diff --git a/apps/extension/src/tools/shared.ts b/apps/extension/src/tools/shared.ts-index 7ae9fda..096b21f 100644---- a/apps/extension/src/tools/shared.ts-+++ b/apps/extension/src/tools/shared.ts-@@ -8,7 +8,11 @@-- import type { CdpDebuggee, DialogCursor } from "@/browser-driver/chromium-cdp";- import type { CdpFrameGraph, CdpTarget } from "@/browser-driver/frame-graph";--import type { SessionContext, SessionManager } from "@/session-manager/manager";-+import {-+ isAgentControlledTab,-+ type SessionContext,-+ type SessionManager,-+} from "@/session-manager/manager";- import { normaliseRef } from "@/session-manager/ref-store";- import type { ConsoleResult, JavaScriptDialogInfo, RpcError } from "@/transport/types";- import { rpcError } from "./errors";-@@ -180,6 +184,15 @@ export async function resolveTargetTab(- tabId: number | undefined,- api: ChromeTabsApi,- ): Promise<ResolvedTargetTab | RpcError> {-+ if (tabId === undefined && ctx.tabMode) {-+ const owned = [...ctx.agentCreatedTabs, ...ctx.borrowedTabs.keys()];-+ tabId =-+ ctx.activeTabId !== undefined && isAgentControlledTab(ctx, ctx.activeTabId)-+ ? ctx.activeTabId-+ : owned[0];-+ if (tabId === undefined)-+ return { code: "not_found", message: "No task tab remains; create a tab to continue" };-+ }- if (tabId !== undefined) {- if (!Number.isSafeInteger(tabId) || tabId <= 0) {- return {-@@ -202,13 +215,18 @@ export async function resolveTargetTab(- message: `tab ${tabId} not found`,- };- }-- const owner = manager.findByWindowId(tab.windowId);-+ const owner = manager.findByTabId?.(tab.id) ?? manager.findByWindowId(tab.windowId);- if (owner && owner.sessionId !== ctx.sessionId) {- return {- code: "not_found",- message: `tab ${tabId} not found in session scope`,- };- }-+ if (ctx.tabMode && !isAgentControlledTab(ctx, tab.id))-+ return {-+ code: "permission_denied",-+ message: "Authorize this tab with tab_borrow before reading or operating it",-+ };- return { tabId: tab.id, windowId: tab.windowId, active: tab.active === true, url: tab.url };- }- const tabs = await api.query({ active: true, windowId: ctx.agentWindowId });-@@ -318,6 +336,7 @@ export async function resolveCdpAccessibleTargetTab(-- const tabs = await api.query({ windowId: ctx.agentWindowId });- for (const tab of tabs) {-+ if (ctx.tabMode && (tab.id === undefined || !isAgentControlledTab(ctx, tab.id))) continue;- const candidate = resolvedTargetFromChromeTab(tab, ctx.agentWindowId);- if (!candidate) continue;- if (!enforceCdpAccessibleTarget(candidate, toolName)) return candidate;-@@ -338,7 +357,9 @@ export function enforceAgentWindow(- target: { tabId: number; windowId: number },- toolName: string,- ): RpcError | null {-- if (target.windowId !== ctx.agentWindowId) {-+ if (-+ ctx.tabMode ? !isAgentControlledTab(ctx, target.tabId) : target.windowId !== ctx.agentWindowId-+ ) {- return rpcError(- "permission_denied",- "agent_window_scope",-@@ -358,6 +379,6 @@ export function enforceToolTargetScope(- effect: ToolEffect,- toolName: string,- ): RpcError | null {-- if (effect === "passive_read") return null;-+ if (effect === "passive_read" && !ctx.tabMode) return null;- return enforceAgentWindow(ctx, target, toolName);- }-diff --git a/apps/extension/src/tools/tabs.ts b/apps/extension/src/tools/tabs.ts-index feb9763..e6dd265 100644---- a/apps/extension/src/tools/tabs.ts-+++ b/apps/extension/src/tools/tabs.ts-@@ -246,7 +246,7 @@ export async function handleTabList(- // per-tab classification is O(1).- const otherAgentWindowIds = new Set<number>();- for (const s of manager.list()) {-- if (s.sessionId !== params.session_id) {-+ if (s.sessionId !== params.session_id && !s.tabMode) {- otherAgentWindowIds.add(s.agentWindowId);- }- }-@@ -258,8 +258,16 @@ export async function handleTabList(- for (const t of allTabs) {- if (typeof t.id !== "number") continue;- const winId = typeof t.windowId === "number" ? t.windowId : -1;-+ const owner = manager.findByTabId?.(t.id);-+ if (owner && owner.sessionId !== ctx.sessionId) continue;- if (otherAgentWindowIds.has(winId)) continue;-- const tabScope: "user" | "agent" = winId === myAgentWindowId ? "agent" : "user";-+ const tabScope: "user" | "agent" = (-+ ctx.tabMode-+ ? ctx.agentCreatedTabs.has(t.id) || ctx.borrowedTabs.has(t.id)-+ : winId === myAgentWindowId-+ )-+ ? "agent"-+ : "user";- if (scope === "user" && tabScope !== "user") continue;- if (scope === "agent" && tabScope !== "agent") continue;- tabs.push({-@@ -361,7 +369,7 @@ function buildCreateProps(- const createProps: chrome.tabs.CreateProperties = {- windowId: ctx.agentWindowId,- url: params.url ?? NEW_TAB_DEFAULT_URL,-- active: params.active ?? true,-+ active: ctx.tabMode ? ctx.taskWindow === true : (params.active ?? true),- };- if (params.index !== undefined) createProps.index = params.index;- return createProps;-@@ -392,6 +400,15 @@ async function createTabAndCleanup(- // Claim the concrete id returned by Chrome. Ownership never depends on- // matching this request to an asynchronous onCreated event.- ctx.agentCreatedTabs.add(tab.id);-+ if (ctx.tabMode) {-+ ctx.activeTabId = tab.id;-+ try {-+ if (ctx.taskGroupId !== undefined)-+ await chrome.tabs.group({ tabIds: [tab.id], groupId: ctx.taskGroupId });-+ } catch {-+ /* Group may have been removed by the user; tab ownership still applies. */-+ }-+ }- if (aborted(deps.signal, "tab_create")) {- try {- await getTabsApi(deps).remove(tab.id);-@@ -485,7 +502,11 @@ async function authoriseAgentTab(- `${toolName}: tab ${tabId} is borrowed by session ${otherBorrower}`,- );- }-- if (tab.windowId === ctx.agentWindowId) {-+ if (-+ ctx.tabMode-+ ? ctx.agentCreatedTabs.has(tabId) || ctx.borrowedTabs.has(tabId)-+ : tab.windowId === ctx.agentWindowId-+ ) {- return tab;- }- return rpcError(-@@ -575,7 +596,12 @@ export async function handleTabSelect(- return { code: "cancelled", message: "tab_select aborted" };- }- try {-- await getTabsApi(deps).update(params.tab_id, { active: true });-+ if (ctx.tabMode) {-+ // Borrowed/user-moved tabs retain their original foreground behavior.-+ if (ctx.taskWindow && tabOrErr.windowId === ctx.agentWindowId)-+ await getTabsApi(deps).update(params.tab_id, { active: true });-+ ctx.activeTabId = params.tab_id;-+ } else await getTabsApi(deps).update(params.tab_id, { active: true });- } catch (err) {- return {- code: "protocol_error",-@@ -638,14 +664,19 @@ 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) {-+ if (ctx.tabMode ? ctx.agentCreatedTabs.has(tabId) : tab.windowId === ctx.agentWindowId) {- return {- code: "invalid_params",- message: `tab_borrow: tab ${tabId} already lives in the Agent Window`,- };- }- for (const s of manager.list()) {-- if (s.sessionId !== ctx.sessionId && s.agentWindowId === tab.windowId) {-+ if (-+ s.sessionId !== ctx.sessionId &&-+ (s.tabMode-+ ? s.agentCreatedTabs.has(tabId) || s.borrowedTabs.has(tabId)-+ : s.agentWindowId === tab.windowId)-+ ) {- return rpcError(- "permission_denied",- "agent_window_scope",-@@ -754,6 +785,8 @@ async function executeBorrowCore(- );- if (approvalErr) return approvalErr;--+ if (p.ctx.tabMode) return { originalWindowId, originalIndex };-+- const moveErr = await moveTabForBorrow(- p.tabsApi,- p.tabId,-@@ -816,6 +849,7 @@ export async function handleTabBorrow(-- try {- reservation.commit({-+ ...(ctx.tabMode ? { stationary: true } : {}),- tabId: params.tab_id,- originalWindowId: coreResult.originalWindowId,- originalIndex: coreResult.originalIndex,-@@ -829,7 +863,8 @@ export async function handleTabBorrow(- }- // Activate after commit so overlay/event observers see the tab as claimed.- try {-- await tabsApi.update(params.tab_id, { active: true });-+ if (ctx.tabMode) ctx.activeTabId = params.tab_id;-+ else await tabsApi.update(params.tab_id, { active: true });- } catch (err) {- console.debug("[bsk tab_borrow] activate after move failed", err);- }-@@ -994,6 +1029,15 @@ export async function returnBorrowedTab(- const alreadyCancelled = aborted(deps.signal, "tab_return");- if (alreadyCancelled) return alreadyCancelled;--+ if (entry.stationary) {-+ await releaseReturnedTabState(ctx, tabId, deps);-+ return {-+ tabId,-+ toWindowId: entry.originalWindowId,-+ toIndex: entry.originalIndex,-+ fallback: false,-+ };-+ }- let targetWindowId = entry.originalWindowId;- let targetIndex = entry.originalIndex;- let fallback = false;-diff --git a/apps/extension/src/tools/vom/__tests__/capture.test.ts b/apps/extension/src/tools/vom/__tests__/capture.test.ts-index 503dd21..5f9f4a5 100644---- a/apps/extension/src/tools/vom/__tests__/capture.test.ts-+++ b/apps/extension/src/tools/vom/__tests__/capture.test.ts-@@ -212,7 +212,7 @@ function nestedHoverTriggerSnapshotReply() {- function makeCdp(snapshot: unknown) {- return {- send: vi.fn(async (_tab: number, method: string) => {-- if (method === "DOMSnapshot.enable") return {};-+ if (method === "DOMSnapshot.enable") throw new Error("DOM mutation tracking must stay disabled");- if (method === "DOMSnapshot.captureSnapshot") return snapshot;- if (method === "Page.getLayoutMetrics") {- return {-@@ -254,9 +254,11 @@ function makeCdp(snapshot: unknown) {-- describe("snapshot capture and hover", () => {- it("parses nodes, attrs, rects, paint order and styles", async () => {-+ const cdp = makeCdp(fakeSnapshotReply());- const { nodes, viewport } = semanticCapture(-- await captureObservationFacts(makeCdp(fakeSnapshotReply()), 4),-+ await captureObservationFacts(cdp, 4),- ).captured;-+ expect(cdp.send).not.toHaveBeenCalledWith(4, "DOMSnapshot.enable", expect.anything());- expect(viewport).toEqual({ width: 1000, height: 800 });- const div = nodes.find((n) => n.backendNodeId === 12);- expect(div).toMatchObject({ tag: "div", position: "fixed", parentBackendNodeId: 11 });-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,11 +4,13 @@ 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 ?? "")- );- }--diff --git a/apps/extension/src/tools/vom/capture-coordinator.ts b/apps/extension/src/tools/vom/capture-coordinator.ts-index c5ecf53..a5dbc19 100644---- a/apps/extension/src/tools/vom/capture-coordinator.ts-+++ b/apps/extension/src/tools/vom/capture-coordinator.ts-@@ -121,8 +121,10 @@ export async function captureObservationFacts<T extends FrameOwnedAxNode>(- const scoped = cdpRunnerForTarget(cdp, batch.target);- try {- throwCaptureAborted(signal);-- await scoped.send(tabId, "DOMSnapshot.enable", {});-- throwCaptureAborted(signal);-+ // captureSnapshot works without enabling the DOMSnapshot domain. Enabling-+ // it installs persistent DOM mutation instrumentation (including script-+ // origin stack collection), which we do not need for a one-shot read.-+ // It also adds a renderer round trip before every snapshot.- batch.snapshotAttachmentId = cdp.getAttachmentId?.(tabId);- const snapshot = await scoped.send<SnapshotReply>(tabId, "DOMSnapshot.captureSnapshot", {- computedStyles: REQUESTED_STYLES,-diff --git a/apps/extension/src/tools/window.ts b/apps/extension/src/tools/window.ts-index ccec54e..773d252 100755---- a/apps/extension/src/tools/window.ts-+++ b/apps/extension/src/tools/window.ts-@@ -53,6 +53,8 @@ export async function handleWindowResize(- const ctxOrErr = lookupSession(manager, params, "window_resize");- if (isRpcError(ctxOrErr)) return ctxOrErr;- const ctx = ctxOrErr;-+ if (ctx.tabMode)-+ return { code: "unsupported", message: "Task tabs cannot resize the user window" };-- const sizeOrErr = validateWindowSize(params.width, params.height);- if (isRpcError(sizeOrErr)) return sizeOrErr;-diff --git a/apps/extension/src/transport/__tests__/remote-authorization.test.ts b/apps/extension/src/transport/__tests__/remote-authorization.test.ts-new file mode 100644-index 0000000..ac613dd---- /dev/null-+++ b/apps/extension/src/transport/__tests__/remote-authorization.test.ts-@@ -0,0 +1,91 @@-+import { beforeEach, describe, expect, it, vi } from "vitest";-+import {-+ activateRemoteEndpoint,-+ renewRemoteAuthorization,-+ updateRemoteConnection,-+} from "../remote-authorization";-+import { REMOTE_ENDPOINT_KEY, type RemoteEndpoint } from "../remote-endpoint";-+-+let values: Record<string, unknown>;-+const endpoint: RemoteEndpoint = {-+ url: "wss://gateway.example/api/v1/local-browser/extension",-+ token: "a".repeat(43),-+ deviceId: "a".repeat(32),-+ expiresAt: "2099-01-01T00:00:00Z",-+ renewAfter: "2020-01-01T00:00:00Z",-+};-+const response = () =>-+ new Response(-+ JSON.stringify({-+ device_id: endpoint.deviceId,-+ expires_at: "2099-02-01T00:00:00Z",-+ renew_after: "2099-01-01T00:00:00Z",-+ }),-+ { status: 200 },-+ );-+beforeEach(() => {-+ values = { [REMOTE_ENDPOINT_KEY]: { ...endpoint } };-+ vi.stubGlobal("chrome", {-+ storage: {-+ local: {-+ get: vi.fn(async () => ({ ...values })),-+ set: vi.fn(async (next) => {-+ Object.assign(values, next);-+ }),-+ },-+ },-+ });-+ vi.stubGlobal(-+ "fetch",-+ vi.fn(async () => response()),-+ );-+});-+describe("durable remote authorization", () => {-+ it("exchanges a pairing link over HTTPS without putting credentials in the URL", async () => {-+ const result = await activateRemoteEndpoint({ url: endpoint.url, token: endpoint.token });-+ const [url, options] = vi.mocked(fetch).mock.calls[0];-+ expect(String(url)).toBe("https://gateway.example/api/v1/local-browser/extension/authorize");-+ expect(options?.redirect).toBe("error");-+ expect(options?.credentials).toBe("omit");-+ expect(options?.headers).toEqual(-+ expect.objectContaining({ Authorization: `Bearer ${endpoint.token}` }),-+ );-+ expect(result.token).not.toBe(endpoint.token);-+ expect(result.deviceId).toBe(endpoint.deviceId);-+ expect(JSON.parse(String(options?.body)).next_token).toBe(result.token);-+ });-+ it("retains the candidate after a lost response and retries the same rotation", async () => {-+ vi.mocked(fetch).mockRejectedValueOnce(new Error("connection lost"));-+ await expect(renewRemoteAuthorization()).rejects.toThrow("connection lost");-+ const pending = values[REMOTE_ENDPOINT_KEY] as RemoteEndpoint;-+ expect(pending.token).toBe(endpoint.token);-+ expect(pending.pendingToken).toHaveLength(43);-+ await renewRemoteAuthorization();-+ expect((values[REMOTE_ENDPOINT_KEY] as RemoteEndpoint).token).toBe(pending.pendingToken);-+ expect((values[REMOTE_ENDPOINT_KEY] as RemoteEndpoint).pendingToken).toBeUndefined();-+ expect(JSON.parse(String(vi.mocked(fetch).mock.calls[0][1]?.body)).next_token).toBe(-+ JSON.parse(String(vi.mocked(fetch).mock.calls[1][1]?.body)).next_token,-+ );-+ });-+ it("does not renew a current authorization", async () => {-+ values[REMOTE_ENDPOINT_KEY] = { ...endpoint, renewAfter: "2099-01-01T00:00:00Z" };-+ await renewRemoteAuthorization();-+ expect(fetch).not.toHaveBeenCalled();-+ });-+ it("serializes disconnect with rotation so an old response cannot restore credentials", async () => {-+ let resolve!: (value: Response) => void;-+ vi.mocked(fetch).mockImplementationOnce(-+ () =>-+ new Promise<Response>((r) => {-+ resolve = r;-+ }),-+ );-+ const renewing = renewRemoteAuthorization();-+ await vi.waitFor(() => expect(fetch).toHaveBeenCalled());-+ const disconnecting = updateRemoteConnection(null);-+ resolve(response());-+ await renewing;-+ await disconnecting;-+ expect(values[REMOTE_ENDPOINT_KEY]).toBeNull();-+ });-+});-diff --git a/apps/extension/src/transport/__tests__/remote-endpoint.test.ts b/apps/extension/src/transport/__tests__/remote-endpoint.test.ts-new file mode 100644-index 0000000..3877ab1---- /dev/null-+++ b/apps/extension/src/transport/__tests__/remote-endpoint.test.ts-@@ -0,0 +1,46 @@-+import { afterEach, describe, expect, it, vi } from "vitest";-+import { parseRemoteEndpoint, readRemoteEndpoint, remoteSocket } from "../remote-endpoint";-+-+const token = "a".repeat(43);-+afterEach(() => vi.unstubAllGlobals());-+describe("remote pairing boundary", () => {-+ it("strips the pairing credential from the network URL", () => {-+ expect(parseRemoteEndpoint(`wss://gateway.example/bsk#${token}`)).toEqual({-+ url: "wss://gateway.example/bsk",-+ token,-+ });-+ });-+ it.each([-+ `ws://example.com/bsk#${token}`,-+ `https://example.com/#${token}`,-+ `wss://user:[email protected]/#${token}`,-+ `wss://example.com/?token=secret#${token}`,-+ "wss://example.com/#short",-+ ])("rejects unsafe pairing %s", (input) => {-+ expect(() => parseRemoteEndpoint(input)).toThrow();-+ });-+ it.each(["localhost", "127.0.0.1", "[::1]"])("permits local development on %s", (host) => {-+ expect(parseRemoteEndpoint(`ws://${host}:8080/bsk#${token}`).url).toBe(`ws://${host}:8080/bsk`);-+ });-+ it("does not turn a corrupt remote preference into a local connection", () => {-+ expect(readRemoteEndpoint(null)).toBeNull();-+ expect(() => readRemoteEndpoint({ url: "ws://public.example", token })).toThrow();-+ });-+ it("sends credentials only to the paired endpoint via the subprotocol", () => {-+ const calls: unknown[][] = [];-+ vi.stubGlobal(-+ "WebSocket",-+ class {-+ constructor(...args: unknown[]) {-+ calls.push(args);-+ }-+ },-+ );-+ const remote = parseRemoteEndpoint(`wss://gateway.example/bsk#${token}`);-+ remoteSocket(remote.url, remote);-+ remoteSocket("ws://localhost:52800", null);-+ expect(calls).toEqual([[remote.url, [`bsk-auth.${token}`]], ["ws://localhost:52800"]]);-+ expect(() => remoteSocket("wss://other.example/bsk", remote)).toThrow();-+ expect(calls).toHaveLength(2);-+ });-+});-diff --git a/apps/extension/src/transport/remote-authorization.ts b/apps/extension/src/transport/remote-authorization.ts-new file mode 100644-index 0000000..438893d---- /dev/null-+++ b/apps/extension/src/transport/remote-authorization.ts-@@ -0,0 +1,149 @@-+import {-+ parseRemoteEndpoint,-+ REMOTE_ENDPOINT_KEY,-+ type RemoteEndpoint,-+ readRemoteEndpoint,-+} from "./remote-endpoint";-+-+function newToken(): string {-+ const bytes = crypto.getRandomValues(new Uint8Array(32));-+ return btoa(String.fromCharCode(...bytes))-+ .replaceAll("+", "-")-+ .replaceAll("/", "_")-+ .replaceAll("=", "");-+}-+-+async function authorize(-+ endpoint: RemoteEndpoint,-+ action: "pair" | "renew",-+ nextToken: string,-+): Promise<RemoteEndpoint> {-+ const url = new URL(endpoint.url);-+ url.protocol = url.protocol === "wss:" ? "https:" : "http:";-+ url.pathname = url.pathname.replace(/\/$/, "") + "/authorize";-+ const response = await fetch(url, {-+ method: "POST",-+ redirect: "error",-+ credentials: "omit",-+ cache: "no-store",-+ headers: { Authorization: `Bearer ${endpoint.token}`, "Content-Type": "application/json" },-+ body: JSON.stringify({ action, next_token: nextToken, label: "Chrome · BrowserSkill" }),-+ signal: AbortSignal.timeout(10000),-+ });-+ if (!response.ok) throw new Error("Browser authorization failed; reconnect or pair again");-+ const data = (await response.json()) as {-+ device_id: string;-+ service_name?: string;-+ expires_at: string;-+ renew_after: string;-+ };-+ if (-+ typeof data.device_id !== "string" ||-+ !data.device_id ||-+ !Number.isFinite(Date.parse(data.expires_at)) ||-+ !Number.isFinite(Date.parse(data.renew_after))-+ ) {-+ throw new Error("Invalid browser authorization response");-+ }-+ return {-+ url: endpoint.url,-+ token: nextToken,-+ deviceId: data.device_id,-+ serviceName:-+ typeof data.service_name === "string" ? data.service_name.slice(0, 48) : endpoint.serviceName,-+ expiresAt: data.expires_at,-+ renewAfter: data.renew_after,-+ };-+}-+-+export async function activateRemoteEndpoint(endpoint: RemoteEndpoint): Promise<RemoteEndpoint> {-+ return authorize(endpoint, "pair", newToken());-+}-+-+let writes: Promise<unknown> = Promise.resolve();-+function serialized<T>(action: () => Promise<T>): Promise<T> {-+ const result = writes.then(action, action);-+ writes = result.catch(() => undefined);-+ return result;-+}-+export function updateRemoteConnection(pairing: string | null): Promise<string | null> {-+ return serialized(async () => {-+ const endpoint =-+ pairing === null ? null : await activateRemoteEndpoint(parseRemoteEndpoint(pairing));-+ await chrome.storage.local.set({ [REMOTE_ENDPOINT_KEY]: endpoint });-+ return endpoint?.url ?? null;-+ });-+}-+let renewing = false;-+/** Persist the candidate before rotating. A lost HTTP response can be retried-+ * using the same old/new pair after service-worker or server restart. */-+export async function renewRemoteAuthorization(): Promise<void> {-+ if (renewing) return;-+ renewing = true;-+ try {-+ await serialized(renewRemote);-+ } finally {-+ renewing = false;-+ }-+}-+async function renewRemote(): Promise<void> {-+ {-+ const stored = await chrome.storage.local.get(REMOTE_ENDPOINT_KEY);-+ const endpoint = readRemoteEndpoint(stored[REMOTE_ENDPOINT_KEY]);-+ if (-+ !endpoint?.deviceId ||-+ !endpoint.renewAfter ||-+ (!endpoint.pendingToken && Date.now() < Date.parse(endpoint.renewAfter))-+ )-+ return;-+ const nextToken = endpoint.pendingToken ?? newToken();-+ const pending = { ...endpoint, pendingToken: nextToken };-+ await chrome.storage.local.set({ [REMOTE_ENDPOINT_KEY]: pending });-+ const updated = await authorize(endpoint, "renew", nextToken);-+ const latest = readRemoteEndpoint(-+ (await chrome.storage.local.get(REMOTE_ENDPOINT_KEY))[REMOTE_ENDPOINT_KEY],-+ );-+ // A settings change during the request must not resurrect an old connection.-+ if (-+ latest?.url === endpoint.url &&-+ latest.token === endpoint.token &&-+ latest.deviceId === endpoint.deviceId &&-+ latest.pendingToken === nextToken-+ ) {-+ await chrome.storage.local.set({ [REMOTE_ENDPOINT_KEY]: updated });-+ }-+ }-+}-+-+export function watchRemoteAuthorization() {-+ // Content scripts do not need the gateway credential.-+ void chrome.storage.local.setAccessLevel({ accessLevel: "TRUSTED_CONTEXTS" });-+ chrome.runtime.onMessage.addListener((message, sender, reply) => {-+ if (message?.kind !== "bsk-remote-authorization") return false;-+ if (-+ sender.url !== chrome.runtime.getURL("popup.html") ||-+ sender.id !== chrome.runtime.id ||-+ (message.pairing !== null && typeof message.pairing !== "string")-+ ) {-+ reply({ error: "Invalid authorization request" });-+ return false;-+ }-+ void updateRemoteConnection(message.pairing).then(-+ (url) => reply({ url }),-+ () => reply({ error: "Unable to pair; copy a new pairing link and try again" }),-+ );-+ return true;-+ });-+ const run = () => {-+ void renewRemoteAuthorization().catch(() => {-+ /* Retry the same candidate on the next alarm; never log credentials. */-+ });-+ };-+ const listener = (alarm: chrome.alarms.Alarm) => {-+ if (alarm.name === "bsk-remote-authorization") run();-+ };-+ chrome.alarms.onAlarm.addListener(listener);-+ void chrome.alarms.create("bsk-remote-authorization", { periodInMinutes: 1 });-+ run();-+ return { changed: run, dispose: () => chrome.alarms.onAlarm.removeListener(listener) };-+}-diff --git a/apps/extension/src/transport/remote-endpoint.ts b/apps/extension/src/transport/remote-endpoint.ts-new file mode 100644-index 0000000..f87604c---- /dev/null-+++ b/apps/extension/src/transport/remote-endpoint.ts-@@ -0,0 +1,114 @@-+/** A gateway issues a pairing URL; the fragment never becomes part of the request URL. */-+export interface RemoteEndpoint {-+ url: string;-+ token: string;-+ deviceId?: string;-+ serviceName?: string;-+ expiresAt?: string;-+ renewAfter?: string;-+ pendingToken?: string;-+}-+-+export const REMOTE_ENDPOINT_KEY = "bsk_remote_endpoint";-+export const REMOTE_AUTH_PROTOCOL_PREFIX = "bsk-auth.";-+-+export function parseRemoteEndpoint(input: string): RemoteEndpoint {-+ const url = new URL(input.trim());-+ const loopback = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);-+ if (url.protocol !== "wss:" && !(url.protocol === "ws:" && loopback)) {-+ throw new Error("Remote connections require WSS (WS is allowed only on loopback)");-+ }-+ if (url.username || url.password || url.search) {-+ throw new Error("Credentials and query parameters are not allowed in the server URL");-+ }-+ const token = url.hash.slice(1);-+ if (!/^[A-Za-z0-9_-]{32,256}$/.test(token)) {-+ throw new Error("A pairing credential of 32–256 base64url characters is required");-+ }-+ url.hash = "";-+ return { url: url.toString(), token };-+}-+-+export function readRemoteEndpoint(value: unknown): RemoteEndpoint | null {-+ if (value === undefined || value === null) return null;-+ if (typeof value !== "object") throw new Error("Invalid stored remote connection");-+ const { url, token } = value as Partial<RemoteEndpoint>;-+ if (typeof url !== "string" || typeof token !== "string") {-+ throw new Error("Invalid stored remote connection");-+ }-+ const endpoint = parseRemoteEndpoint(`${url}#${token}`);-+ const extra = value as Partial<RemoteEndpoint>;-+ if (extra.deviceId !== undefined) {-+ if (-+ typeof extra.deviceId !== "string" ||-+ !/^[a-f0-9]{32}$/.test(extra.deviceId) ||-+ typeof extra.expiresAt !== "string" ||-+ typeof extra.renewAfter !== "string" ||-+ !Number.isFinite(Date.parse(extra.expiresAt)) ||-+ !Number.isFinite(Date.parse(extra.renewAfter))-+ )-+ throw new Error("Invalid stored device authorization");-+ endpoint.deviceId = extra.deviceId;-+ endpoint.expiresAt = extra.expiresAt;-+ endpoint.renewAfter = extra.renewAfter;-+ }-+ if (typeof extra.serviceName === "string") endpoint.serviceName = extra.serviceName.slice(0, 48);-+ if (extra.pendingToken !== undefined) {-+ if (typeof extra.pendingToken !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(extra.pendingToken))-+ throw new Error("Invalid pending device credential");-+ endpoint.pendingToken = extra.pendingToken;-+ }-+ return endpoint;-+}-+-+export function remoteSocket(-+ url: string,-+ endpoint: RemoteEndpoint | null,-+ focusWindow?: (sessionId: string) => Promise<void>,-+ preview?: (sessionId: string) => Promise<unknown>,-+ idle?: (sessionId: string) => Promise<unknown>,-+): WebSocket {-+ // Never attach a remote credential to a different endpoint, including a local fallback.-+ if (endpoint && endpoint.url !== url) throw new Error("Remote endpoint changed");-+ const socket = endpoint-+ ? new WebSocket(url, [REMOTE_AUTH_PROTOCOL_PREFIX + endpoint.token])-+ : new WebSocket(url);-+ if (endpoint && focusWindow)-+ socket.addEventListener("message", (event) => {-+ let request: { id?: string; method?: string; params?: { session_id?: string } };-+ try {-+ request = JSON.parse(event.data);-+ } catch {-+ return;-+ }-+ if (-+ !["gateway.task_focus", "gateway.task_preview", "gateway.task_idle"].includes(-+ request.method ?? "",-+ )-+ )-+ return;-+ event.stopImmediatePropagation();-+ if (!request.id || !request.params?.session_id) return;-+ const work =-+ request.method === "gateway.task_idle"-+ ? idle-+ ? idle(request.params.session_id)-+ : Promise.reject(new Error("Idle unavailable"))-+ : request.method === "gateway.task_preview"-+ ? preview-+ ? preview(request.params.session_id)-+ : Promise.reject(new Error("Preview unavailable"))-+ : focusWindow(request.params.session_id).then(() => ({ focused: true }));-+ void work.then(-+ (result) => {-+ if (socket.readyState === WebSocket.OPEN)-+ socket.send(JSON.stringify({ id: request.id, result }));-+ },-+ () => {-+ if (socket.readyState === WebSocket.OPEN)-+ socket.send(JSON.stringify({ id: request.id, error: { code: "window_unavailable" } }));-+ },-+ );-+ });-+ return socket;-+}-diff --git a/apps/extension/wxt.config.ts b/apps/extension/wxt.config.ts-index ff4fc53..4ae452c 100644---- a/apps/extension/wxt.config.ts-+++ b/apps/extension/wxt.config.ts-@@ -34,6 +34,7 @@ export default defineConfig({- "idle",- "notifications",- "tabs",-+ "tabGroups",- "storage",- "webNavigation",- "windows",-diff --git a/docs/remote-extension-connection.md b/docs/remote-extension-connection.md-new file mode 100644-index 0000000..f279d80---- /dev/null-+++ b/docs/remote-extension-connection.md-@@ -0,0 +1,123 @@-+# Connecting an extension through an authenticated gateway-+-+This opt-in extension mode addresses the browser-side connection portion of-+[issue #50](https://github.com/Tencent/BrowserSkill/issues/50). The default remains-+the local daemon and its configurable port. This does not expose the daemon to-+the internet or implement a remote CLI server.-+-+Open the extension popup, expand **Remote connection**, and paste a gateway-issued-+pairing link:-+-+```text-+wss://gateway.example/browser/extension#<base64url-credential>-+```-+-+The destination is shown before saving. Saving uses the existing connection-+controller: finish session cleanup and return borrowed tabs before switching the-+transport. If cleanup fails, the controller retains the failure rather than-+silently abandoning borrowed tabs. **Use local daemon** removes the remote-+preference and goes through the same cleanup path.-+-+## Gateway authorization contract-+-+This consumer patch adds a proposed HTTP exchange before the native handshake.-+Saving a pairing link sends POST to the WebSocket path plus `/authorize` (HTTPS-+for WSS), using `Authorization: Bearer <pairing-token>` and JSON-+`{ "action": "pair", "next_token": "<client-generated-256-bit-token>", "label": "Chrome · BrowserSkill" }`.-+The gateway atomically consumes the one-use pairing token and returns-+`device_id`, `expires_at` and `renew_after` (ISO date strings), plus an optional-+`service_name` used for the visible task-group label (up to 48 characters; defaults-+to BrowserSkill). It stores only a-+hash of the next token. HTTP redirects are rejected; cookies are omitted.-+-+The extension stores device metadata and its token in trusted extension-local-+storage. At renewal time it persists a candidate token, then uses the same-+endpoint with action `renew` and the current device token as Bearer authorization.-+The gateway must handle repeated old/new token pairs idempotently, allowing a-+lost response to be retried after restart. The consumer gateway uses a 5-minute-+pairing lifetime, 90-day device lifetime and renewal after 30 days. First-time-+activation response loss requires a new pairing link. Renewal of the same device-+does not tear down active sessions.-+-+## WebSocket contract-+-+- The extension strips the fragment before opening the WebSocket. It offers one-+ subprotocol, `bsk-auth.<credential>`. The credential must be 32–256 base64url-+ characters. A gateway must validate it before forwarding any browser traffic,-+ and select the offered subprotocol when accepting the WebSocket.-+- Non-loopback connections require WSS. Query parameters and URL userinfo are-+ rejected. Do not log WebSocket subprotocol headers: this is a bearer credential.-+- After upgrade, the first application frame remains `system.handshake`. Native-+ BrowserSkill automation RPC methods and payloads remain unchanged. Forward the native handshake and-+ frames to the authorized daemon connection without the credential subprotocol.-+- Authenticate and isolate each user's daemon/routing context. The BrowserSkill-+ compatibility handshake is not account authentication.-+- Expiry and revocation are gateway responsibilities; renewal follows the HTTP contract above. Close an existing-+ connection on revocation. Never replay commands on reconnect.-+- A token authorizes the server to create and operate background task tabs. Existing-+ user tabs still use BrowserSkill's original borrow confirmation and return flow.-+-+The stored remote endpoint uses `chrome.storage.local`, not sync storage. The-+popup displays the server URL, not the saved credential. A configured remote-+connection never silently falls back to localhost after a transport failure.-+-+For local gateway development only, `ws://127.0.0.1`, `ws://localhost`, and-+`ws://[::1]` are accepted. This exception does not allow plaintext LAN endpoints.-+-+## Validation-+-+The extension tests cover unsafe endpoint rejection, credential destination-+binding, out-of-order storage reads and disposal. Existing controller tests cover-+session teardown and reconnect generations. An integration consumer additionally-+tested a released v0.2.1 daemon and the built extension in isolated Chromium:-+popup pairing, session start, navigation, Chinese text input, click, snapshot,-+screenshot, pause/resume and session stop. The gateway is external to this patch.-+-+The subprotocol convention is proposed for upstream review; it is not an existing-+published BrowserSkill remote-auth standard.-+-+## Optional gateway UI messages-+-+The extension intercepts `gateway.task_focus` and `gateway.task_preview` before-+native transport dispatch. These are proposed optional gateway messages, not-+published native BrowserSkill RPCs. Both require an existing `session_id` from-+the authenticated gateway's own task mapping. Focus locates that task's current-+tab; it cannot start or resume a task or select an arbitrary browser tab.-+Preview is described below. A gateway should expose focus only as a user action.-+-+## Remote task tabs and preview-+-+Remote gateway sessions use background task tabs in an existing non-incognito-+Chrome window, grouped and labeled for the integration. The local-daemon mode-+retains dedicated Agent Windows. Tab groups are visual only: explicit created-+and borrowed tab IDs define ownership. A shared window is never a permission-+boundary for remote tasks; other sessions' tabs remain invisible and even passive-+page reads require an owned/borrowed tab. Existing tabs are borrowed in place-+after the original confirmation, then released without moving or closing them.-+Stopping a remote task closes only its created tabs, never the shared user window.-+-+Logical task-tab selection does not activate Chrome's visible tab. Remote human-+help and borrow requests preserve the original confirmation/notification UI but-+do not proactively focus a window. Explicit user notification clicks and the-+consumer's `gateway.task_focus` message can locate the task tab.-+-+The optional `gateway.task_preview` UI message captures the authorized task tab through-+CDP outside the automation queue. It returns a JPEG (`image_base64`, `format`,-+`tab_id`, `title`, `captured_at`); final bitmap width is limited to 640 pixels,-+including on HiDPI screens. Concurrent captures for the same task are coalesced.-+The gateway consumer should rate-limit, authenticate, and scope preview requests,-+and the viewer should stop requesting images while hidden. This is low-frame-rate-+preview, not a video streaming API. Both UI messages are optional gateway-+proposals and must not be represented as published native BrowserSkill RPCs.-+-+Validation includes task-tab ownership/cleanup, rejected unapproved reads,-+borrowing without moving user tabs, non-focusing human help, preview capture-+coalescing/HiDPI bounds, and an external integration test using the released-+v0.2.1 daemon plus headed Chromium. No cloud gateway implementation is shipped-+in this repository.-+-+`gateway.task_idle` releases the task's debugger attachments after an agent turn-+without closing its tabs. It fences new previews and waits for already-started-+operations and captures before detaching. The next native tool operation resumes-+control. Session stop uses the same preview fence. The gateway retains the last-+preview while idle rather than causing background screenshots to reattach CDP.-diff --git a/packages/i18n/src/locales/en-US/extension.json b/packages/i18n/src/locales/en-US/extension.json-index fe51cc8..8af2c72 100644---- a/packages/i18n/src/locales/en-US/extension.json-+++ b/packages/i18n/src/locales/en-US/extension.json-@@ -23,6 +23,11 @@- "disabled": "Off"- },- "connectionToggleTitle": "BrowserSkill connection",-+ "taskWindowTitle": "Task display",-+ "taskWindowTabs": "Background tab group",-+ "taskWindowVisible": "Separate window (default, keep visible)",-+ "taskWindowHint": "Applies to the next new task. A separate window opens in front; later tab changes stay within it. Keep it alongside chat: covering or minimizing it may still slow reads.",-+ "taskWindowError": "Could not load or save this setting. Reopen the extension and try again.",- "controlHintsToggleTitle": "Control hints",- "controlHintsToggleHint": "Show the status pill and orange glow while the Agent controls a page.",- "controlHintsInfoLabel": "About control hints",-@@ -66,7 +71,13 @@- "copied": "Copied",- "hintDisconnected": "Available when connected",- "promptTemplate": "Use BrowserSkill's `bsk` CLI to record the browser actions I'm about to demonstrate.\n\nSteps:\n1. Run: {{command}}\n2. Once you confirm it's started, I'll operate in the opened window myself.\n3. After I click Finish, read the written `./trace` bundle (`trace.json` + `states/`) and summarize what I did."-- }-+ },-+ "remoteTitle": "Remote connection",-+ "remoteLocal": "Use local daemon",-+ "remotePairing": "Pairing link",-+ "remoteHint": "Paste a pairing link from a trusted server. Saving switches connections and ends existing sessions. The server can operate Agent Windows; borrowing existing tabs still requires your confirmation.",-+ "remoteSave": "Connect",-+ "remoteError": "Could not save. Check the pairing link and storage access."- },- "controlOverlay": {- "status": "Agent controlling",-diff --git a/packages/i18n/src/locales/ko-KR/extension.json b/packages/i18n/src/locales/ko-KR/extension.json-index c6870bc..5c7ac30 100644---- a/packages/i18n/src/locales/ko-KR/extension.json-+++ b/packages/i18n/src/locales/ko-KR/extension.json-@@ -23,6 +23,11 @@- "disabled": "꺼짐"- },- "connectionToggleTitle": "BrowserSkill 연결",-+ "taskWindowTitle": "작업 표시 방식",-+ "taskWindowTabs": "백그라운드 탭 그룹",-+ "taskWindowVisible": "별도 창 (기본값, 보이도록 유지)",-+ "taskWindowHint": "다음 새 작업부터 적용됩니다. 별도 창이 앞으로 열리고 이후에는 작업 창 안의 탭만 전환합니다. 채팅 창 옆에 두세요. 완전히 가리거나 최소화하면 여전히 느려질 수 있습니다.",-+ "taskWindowError": "설정을 읽거나 저장하지 못했습니다. 확장 프로그램을 다시 열고 재시도하세요.",- "controlHintsToggleTitle": "제어 표시",- "controlHintsToggleHint": "에이전트가 페이지를 제어하는 동안 상태 표시와 주황색 테두리를 표시합니다.",- "controlHintsInfoLabel": "제어 표시에 관하여",-@@ -66,7 +71,13 @@- "copied": "복사됨",- "hintDisconnected": "연결 후 사용할 수 있습니다",- "promptTemplate": "BrowserSkill의 `bsk` CLI를 사용해 지금부터 제가 수행할 브라우저 작업을 기록하세요.\n\n단계:\n1. 다음을 실행하세요: {{command}}\n2. 기록이 시작됐다고 알려주면, 열린 창에서 제가 직접 작업하겠습니다.\n3. 제가 완료를 누른 후 생성된 `./trace` 번들(`trace.json` + `states/`)을 읽고 제가 수행한 작업을 요약하세요."-- }-+ },-+ "remoteTitle": "원격 연결",-+ "remoteLocal": "로컬 데몬 사용",-+ "remotePairing": "페어링 링크",-+ "remoteHint": "신뢰하는 서버의 페어링 링크를 붙여 넣으세요. 저장하면 연결이 전환되고 기존 세션이 종료됩니다. 기존 탭을 빌리려면 여전히 확인이 필요합니다.",-+ "remoteSave": "연결",-+ "remoteError": "저장하지 못했습니다. 페어링 링크와 저장소 접근을 확인하세요."- },- "controlOverlay": {- "status": "에이전트가 제어 중",-diff --git a/packages/i18n/src/locales/zh-CN/extension.json b/packages/i18n/src/locales/zh-CN/extension.json-index 46c56fa..201dde0 100644---- a/packages/i18n/src/locales/zh-CN/extension.json-+++ b/packages/i18n/src/locales/zh-CN/extension.json-@@ -23,6 +23,11 @@- "disabled": "Off"- },- "connectionToggleTitle": "BrowserSkill 连接",-+ "taskWindowTitle": "任务打开方式",-+ "taskWindowTabs": "后台标签组",-+ "taskWindowVisible": "独立窗口(默认,保持可见)",-+ "taskWindowHint": "下一个新任务生效。独立窗口会打开到前台,之后仅切换窗口内的任务标签。请与聊天窗口并排放置;完全遮挡或最小化仍可能变慢。",-+ "taskWindowError": "设置读写失败,请重新打开扩展后再试。",- "controlHintsToggleTitle": "控制提示",- "controlHintsToggleHint": "Agent 控制页面时显示提示条和橙色闪光。",- "controlHintsInfoLabel": "控制提示说明",-@@ -66,7 +71,13 @@- "copied": "已复制",- "hintDisconnected": "连接后可用",- "promptTemplate": "用 BrowserSkill 的 `bsk` CLI 录制我接下来的浏览器操作。\n\n步骤:\n1. 执行:{{command}}\n2. 你确认已开始后,我会在打开的窗口里自己操作。\n3. 我点“结束”后,读取写出的 `./trace` 目录包(`trace.json` + `states/`),总结我做了什么。"-- }-+ },-+ "remoteTitle": "远程连接",-+ "remoteLocal": "使用本机服务",-+ "remotePairing": "配对链接",-+ "remoteHint": "粘贴可信服务器提供的配对链接。保存后会切换连接并结束现有任务。服务器可操作 Agent Window;借用已有标签页仍需你确认。",-+ "remoteSave": "连接",-+ "remoteError": "保存失败,请检查配对链接及存储权限。"- },- "controlOverlay": {- "status": "Agent 正在控制",-diff --git a/packages/vom/src/__tests__/render.test.ts b/packages/vom/src/__tests__/render.test.ts-index a064df6..34e835a 100644---- a/packages/vom/src/__tests__/render.test.ts-+++ b/packages/vom/src/__tests__/render.test.ts-@@ -29,6 +29,32 @@ function coreRefs(refs: ReturnType<typeof renderVom>["refs"]) {- }-- describe("renderVom single-layer page", () => {-+ 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(- scene([-diff --git a/packages/vom/src/render.ts b/packages/vom/src/render.ts-index c7c4164..af63b75 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;-@@ -787,6 +808,8 @@ interface RenderState {- truncated: boolean;- stopped: 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;-@@ -896,7 +919,14 @@ function renderNodes(- 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 = {-+ siblingIndex,-+ siblingContextCache: new Map(),- lines: [...initialLines],- refs: [],- nextRef: 1,diff --git a/scripts/browserskill-release.json b/scripts/browserskill-release.jsonindex 0b6a4b85a..4c05af7de 100644--- a/scripts/browserskill-release.json+++ b/scripts/browserskill-release.json@@ -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"}}diff --git a/scripts/build_browserskill.sh b/scripts/build_browserskill.shindex fbe3846d6..04acc5d85 100755--- a/scripts/build_browserskill.sh+++ b/scripts/build_browserskill.sh@@ -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"' EXITgit 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 [email protected] install --frozen-lockfilenpx --yes [email protected] 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"diff --git a/scripts/test_browserskill_extension.mjs b/scripts/test_browserskill_extension.mjsindex 7500f723d..693e86f12 100644--- a/scripts/test_browserskill_extension.mjs+++ b/scripts/test_browserskill_extension.mjs@@ -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 {