fix(browser): rebase BrowserSkill patches and use native session lifecycle
parent
7ea5bf4349
commit
640e356e31
|
|
@ -32,13 +32,13 @@ WeKnora 使用 Tencent/BrowserSkill 的官方 daemon 和基于官方源码的配
|
|||
|
||||
预览获取当前任务标签的 CDP 画面,不调用激活窗口/标签 API。JPEG 宽度最多 640 像素。预览直接截取视口,再缩小实际位图,不在每次轮询前额外调用布局查询。任务活动期间,前端每次获取画面后间隔 1 秒刷新;服务端短缓存和扩展在途合并限制重复截图。页面隐藏时停止刷新,回到页面后立即更新。它是约 1 fps 的低帧率截图同步,不是视频流;失败超过 5 秒会提示画面暂未更新。
|
||||
|
||||
后台任务标签在调试连接期间启用 CDP `Emulation.setFocusEmulationEnabled`,让页面的可见性/焦点与绘制回调继续工作,不激活 Chrome 标签或窗口。仅任务新建或明确借用的标签启用此行为,释放调试连接时由 Chrome 恢复。否则依赖 `requestAnimationFrame` 或可见性事件加载内容的页面可能停在 Loading,直到用户切到该标签。
|
||||
后台任务标签在调试连接期间启用 CDP `Emulation.setFocusEmulationEnabled`,让页面的可见性/焦点与绘制回调继续工作,不激活 Chrome 标签或窗口。仅任务新建或明确借用的标签启用此行为,由官方会话控制接口管理;独立预览也显式获取同一控制权,由官方会话结束或标签归还流程释放。否则依赖 `requestAnimationFrame` 或可见性事件加载内容的页面可能停在 Loading,直到用户切到该标签。
|
||||
|
||||
扩展对截图命令设置 3 秒等待上限,对 DOM 快照、无障碍树等读取命令设置 10 秒上限;读取超时会终止对应采集路径,避免同一页面继续走回退读取。错误保留具体 CDP 命令,扩展后台控制台记录超过 2 秒的命令及耗时。此保护不等于取消已经交给 Chrome 的命令,也不自动重放点击或提交。截图超时后仍保留在途标记,直到 Chrome 实际返回或调试连接释放;期间预览不再发送重复截图。框架自动附加配置按调试会话复用,断开后重建,失败后可重试。
|
||||
|
||||
上述上限针对单条 CDP 命令,并非整个 `observe`。复杂页面还要在扩展中进行语义树转换和文本渲染;重复操作按钮的上下文收集复用已扫描的兄弟节点前缀,避免逐按钮重复扫描整个列表。缓存仅存在于本次渲染,按作用域、目标名称和已有上下文隔离,每个父节点最多保留 64 种缓存项。CDP 等待超过 2 秒时记录方法与耗时,不记录页面内容。
|
||||
|
||||
本轮 Agent 执行结束时,通过工具清理钩子释放当前任务的 Chrome 调试连接。成功完成的普通查询默认关闭任务创建的页面并归还借用标签,避免每轮留下任务窗口;输入框的本机浏览器选择偏好仍保留。调用时可设置顶层 `keep_open: true`,为用户要求保留的页面、交付结果或未完成的人工步骤保留整项任务;该标记仅对本轮有效。`request_help` 自动保留任务,人工步骤完成后可通过后续调用的 `keep_open: false` 恢复自动回收。报错、取消、暂停的任务保留现场,不自动关闭。扩展先阻止新截图,再等待在途截图和操作完成,最后释放连接;结束任务也使用同一截图屏障。空闲时服务端只返回缓存画面,卡片显示「已保留最后画面」,不重复截图,下一次浏览器调用恢复连接。Chrome 提示条的消失可能晚于连接释放;同一扩展有其他活动任务时,提示仍可能保留。
|
||||
本轮 Agent 执行结束时,沿用官方会话生命周期:成功完成的普通查询调用 `session_stop`,关闭任务创建的页面、归还借用标签并释放调试连接;输入框的本机浏览器选择偏好仍保留。调用时可设置顶层 `keep_open: true`,为用户要求保留的页面、交付结果或未完成的人工步骤保留整项任务;该标记仅对本轮有效。`request_help` 自动保留任务,人工步骤完成后可通过后续调用的 `keep_open: false` 恢复自动回收。报错、取消、暂停的任务保留现场,不自动关闭。保留任务时不主动断开调试连接或清除元素引用,下一轮继续使用同一官方会话,并重新观察页面。轮次结束后,WeKnora 停止预览轮询并返回缓存画面,卡片显示「已保留最后画面」;下一次浏览器调用恢复轮询。此空闲标记仅用于服务端收尾和预览状态,不表示浏览器已释放控制。真正结束任务时,扩展先阻止新预览并等待在途截图结束,再执行官方停止流程,避免截图重新附加到正在关闭的标签。
|
||||
|
||||
导航默认等待 `domcontentloaded`,避免已经可读的页面被慢图片等资源拖住;需要完整加载或网络空闲时可显式指定 `wait_until: "load"` 或 `"networkidle"`。文档就绪不代表异步应用内容已加载,操作前仍需观察目标内容是否出现。
|
||||
|
||||
|
|
@ -56,13 +56,13 @@ WeKnora 使用 Tencent/BrowserSkill 的官方 daemon 和基于官方源码的配
|
|||
|
||||
## 构建与部署
|
||||
|
||||
扩展和 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/`,不提交二进制。
|
||||
扩展和 daemon 均从官方 `main` 固定提交 `fa953dc6fcd868827b93164e3bea26198e691224` 构建(位于 `ext-v0.3.0` 之后,版本号仍为 0.3.0,协议 v1.3),固定于 `scripts/browserskill-release.json`。后台执行、后台截图、VOM 性能优化和导航重定向跟踪已采用官方实现;仍保留读取保护、任务控制、弹窗归属、末页生命周期及 daemon 导航响应宽限补丁。官方 CLI 0.3.0 二进制不包含最后一项修复,不能直接替代配套 daemon。构建按文件名顺序应用 `patches/browserskill/*.patch`,使用冻结的 pnpm 依赖和 Cargo.lock;本机构建需 Rust/Cargo、C 编译器,Linux 还需 CMake。可设置 `CARGO_TARGET_DIR` 复用编译缓存;Docker 构建阶段在目标架构运行,原生脚本不静默生成其他架构的二进制。详见 `patches/browserskill/README.md`。产物位于 `artifacts/browserskill/`,不提交二进制。
|
||||
|
||||
已有用户需下载 0.3.0 配套 ZIP,覆盖原解压目录并在 Chrome 扩展程序页面重新加载;仅重启服务端不会更新扩展。保持原扩展 ID 时,上游会将旧的本地凭据迁移到扩展源 IndexedDB;重新安装导致 ID 改变时需要重新配对。
|
||||
虽然扩展显示版本号仍为 0.3.0,已有用户仍需下载本次重新构建的配套 ZIP,覆盖原解压目录并在 Chrome 扩展程序页面重新加载;仅重启服务端不会更新扩展。保持原扩展 ID 时,上游会将旧的本地凭据迁移到扩展源 IndexedDB;重新安装导致 ID 改变时需要重新配对。
|
||||
|
||||
### Docker 部署
|
||||
|
||||
`docker/Dockerfile.app` 在独立 Node 构建阶段生成配套扩展,按目标 `linux/amd64` 或 `linux/arm64` 下载 daemon,并将 `bsk`、扩展 ZIP 和许可证复制到运行镜像的 `/opt/weknora/browserskill/`。镜像已预设 `BROWSERSKILL_BINARY` 和 `BROWSERSKILL_EXTENSION_PATH`,无需安装 Chrome 或启用沙箱。不要用宿主机的 macOS `bsk` 替换容器中的 Linux 文件。
|
||||
`docker/Dockerfile.app` 在独立 Node 构建阶段生成配套扩展,按目标 `linux/amd64` 或 `linux/arm64` 从同一固定源码构建 daemon,并将 `bsk`、扩展 ZIP 和许可证复制到运行镜像的 `/opt/weknora/browserskill/`。镜像已预设 `BROWSERSKILL_BINARY` 和 `BROWSERSKILL_EXTENSION_PATH`,无需安装 Chrome 或启用沙箱。不要用宿主机的 macOS `bsk` 替换容器中的 Linux 文件。
|
||||
|
||||
默认无需设置 `BROWSERSKILL_PUBLIC_URL`。设置页在申请配对时提交 `window.location.origin`,服务端保留域名和端口,将 HTTPS 转为 WSS(本机 HTTP 转为 WS),追加 `/api/v1/local-browser/extension`。例如访问 `https://weknora.example.com:8443`,自动生成 `wss://weknora.example.com:8443/api/v1/local-browser/extension`。地址不依赖反向代理传递的内部 Host 或协议。
|
||||
|
||||
|
|
@ -78,18 +78,18 @@ BROWSERSKILL_PUBLIC_URL=wss://weknora.example.com/api/v1/local-browser/extension
|
|||
|
||||
### 原生部署
|
||||
|
||||
构建需要 Git、Node.js(镜像使用 Node 24)和 Python 3,以及访问固定的上游源码、npm 依赖和发行包的网络。执行 `./scripts/build_browserskill.sh` 后,将产物复制到下列路径,或将变量改为产物的实际绝对路径。连接地址同样默认从页面自动生成:
|
||||
构建需要 Git、Node.js(镜像使用 Node 24)、Python 3、Rust/Cargo 和 C 编译器,以及访问固定的上游源码、npm 和 Cargo 依赖的网络。执行 `./scripts/build_browserskill.sh` 后,将产物复制到下列路径,或将变量改为产物的实际绝对路径。连接地址同样默认从页面自动生成:
|
||||
|
||||
```dotenv
|
||||
BROWSERSKILL_BINARY=/opt/weknora/browserskill/bsk
|
||||
BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.3.0.zip
|
||||
```
|
||||
|
||||
构建脚本第二个参数可指定目标平台,例如 `./scripts/build_browserskill.sh ./artifacts/browserskill-linux linux/amd64`;不传时按宿主机系统和架构下载。
|
||||
构建脚本第二个参数可指定目标平台,例如 `./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`。配对授权遵循上游第三方网关协议;`gateway.task_preview`、`gateway.task_focus`、`gateway.task_idle` 仍是配套补丁接口。不要直接替换为官方 ZIP。遇到不支持的收尾接口时,已完成的普通任务可走原生停止;需要保留页面并释放控制的任务仍要求配套扩展。
|
||||
扩展使用官方 MIT 许可,分发时保留 `BrowserSkill-LICENSE`。配对授权遵循上游第三方网关协议;`gateway.task_preview`、`gateway.task_focus` 仍是配套补丁接口。预览和定位需要配套 ZIP;保留会话及任务收尾均采用官方机制,不依赖定制收尾接口。
|
||||
|
||||
## 验证
|
||||
|
||||
|
|
|
|||
|
|
@ -89,7 +89,7 @@ Kubernetes 可通过 Downward API 获取 Pod IP,再设置节点直连地址。
|
|||
|
||||
迁移:PostgreSQL `000093_browser_authorization`,SQLite `000014_browser_authorization`。默认自动迁移;若关闭 `AUTO_MIGRATE`,须先执行迁移。数据库只持久化授权/租约/中断标记,不存浏览器 Cookie 或截图。
|
||||
|
||||
扩展必须更新到 WeKnora 配套 0.3.0 构建。官方 0.3.0 原版缺少预览、定位和释放控制接口,不能直接替换配套 ZIP。升级前结束任务;在原解压目录覆盖文件后重新加载扩展,可沿用原扩展 ID 并迁移授权凭据。重新安装导致 ID 改变时重新配对。服务端必须同步升级 bsk:从与扩展相同的固定 0.3.0 源码构建,然后重启后端以释放旧 daemon。官方 CLI 0.2.1 不支持当前滚动等工具方法。
|
||||
扩展必须更新到 WeKnora 配套 0.3.0 构建。官方 0.3.0 原版缺少预览和定位接口,不能直接替换配套 ZIP。升级前结束任务;在原解压目录覆盖文件后重新加载扩展,可沿用原扩展 ID 并迁移授权凭据。重新安装导致 ID 改变时重新配对。服务端必须同步升级 bsk:从与扩展相同的固定源码提交 `fa953dc6fcd868827b93164e3bea26198e691224` 构建(版本号仍为 0.3.0,需重新构建并更新扩展),然后重启后端以释放旧 daemon。官方 CLI 0.3.0 不包含配套 daemon 的导航响应宽限补丁。
|
||||
|
||||
## 容量与验收
|
||||
|
||||
|
|
|
|||
|
|
@ -233,8 +233,13 @@ func (m *Manager) InternalHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
case "preview":
|
||||
result.Data, err = m.Preview(ctx, input.Scope, input.Session)
|
||||
case "idle":
|
||||
err = m.Idle(ctx, input.Scope, input.Session)
|
||||
case "finish_turn":
|
||||
keepOpen, valid := input.Params["keep_open"].(bool)
|
||||
if !valid {
|
||||
err = errors.New("keep_open must be a boolean")
|
||||
} else {
|
||||
err = m.FinishTurn(ctx, input.Scope, input.Session, keepOpen)
|
||||
}
|
||||
case "focus":
|
||||
err = m.Focus(ctx, input.Scope, input.Session)
|
||||
case "forget":
|
||||
|
|
|
|||
|
|
@ -96,7 +96,7 @@ func TestRequestsRouteToBrowserOwnerAcrossReplicas(t *testing.T) {
|
|||
require.True(t, owner.Status(scope, "chat").Paused)
|
||||
require.NoError(t, follower.Focus(ctx, scope, "chat"))
|
||||
require.True(t, owner.Status(scope, "chat").Paused, "locating a window must not resume automation")
|
||||
require.NoError(t, follower.Idle(ctx, scope, "chat"))
|
||||
require.NoError(t, follower.FinishTurn(ctx, scope, "chat", true))
|
||||
require.True(t, owner.Status(scope, "chat").Idle)
|
||||
require.NoError(t, follower.Revoke(ctx, scope))
|
||||
_, err = owner.Call(ctx, scope, "chat", "snapshot", nil)
|
||||
|
|
|
|||
|
|
@ -620,7 +620,7 @@ func TestRealExtension(t *testing.T) {
|
|||
t.Fatal(err)
|
||||
}
|
||||
if status := m.Status(scope, "chat"); !status.Idle || status.SessionID != taskID {
|
||||
t.Fatalf("idle lost task: %+v", status)
|
||||
t.Fatalf("turn completion lost retained task: %+v", status)
|
||||
}
|
||||
checkDetached := func() {
|
||||
t.Helper()
|
||||
|
|
@ -634,16 +634,23 @@ func TestRealExtension(t *testing.T) {
|
|||
t.Fatal(ctx.Err())
|
||||
}
|
||||
}
|
||||
checkDetached()
|
||||
_, _ = io.WriteString(input, "check-detached\n")
|
||||
select {
|
||||
case line := <-hostLines:
|
||||
if line != `{"detached":false}` {
|
||||
t.Fatalf("retained official session unexpectedly detached: %s", line)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
if _, err = m.Preview(ctx, scope, "chat"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checkDetached()
|
||||
if _, err = call(ctx, scope, "chat", "snapshot", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Status(scope, "chat").Idle {
|
||||
t.Fatal("next operation did not resume control")
|
||||
t.Fatal("next operation did not resume preview polling")
|
||||
}
|
||||
if err = m.Control(ctx, scope, "chat", "pause"); err != nil {
|
||||
t.Fatal(err)
|
||||
|
|
|
|||
|
|
@ -110,10 +110,12 @@ func (m *Manager) receiveUI(d *device, data []byte) bool {
|
|||
return true
|
||||
}
|
||||
|
||||
// Idle releases debugging without closing tabs or deselecting the conversation.
|
||||
// Serialize against automation so an earlier turn cannot detach a command midway.
|
||||
func (m *Manager) Idle(ctx context.Context, s Scope, session string) error {
|
||||
if _, remote, err := m.route(ctx, s, session, "idle", "", nil); remote || err != nil {
|
||||
// FinishTurn retains the official session for unfinished work, or stops a
|
||||
// completed task through native RPC. Idle is only a host-side preview/turn
|
||||
// marker: retaining a session does not detach its debugger or clear its refs.
|
||||
func (m *Manager) FinishTurn(ctx context.Context, s Scope, session string, keepOpen bool) error {
|
||||
params := map[string]any{"keep_open": keepOpen}
|
||||
if _, remote, err := m.route(ctx, s, session, "finish_turn", "", params); remote || err != nil {
|
||||
return err
|
||||
}
|
||||
d := m.get(s)
|
||||
|
|
@ -122,7 +124,7 @@ func (m *Manager) Idle(ctx context.Context, s Scope, session string) error {
|
|||
}
|
||||
d.mu.Lock()
|
||||
target := d.tasks[session]
|
||||
if target == nil || target.id == "" || !d.ready || d.conn == nil {
|
||||
if target == nil || target.id == "" || target.stopping {
|
||||
d.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
|
@ -137,48 +139,17 @@ func (m *Manager) Idle(ctx context.Context, s Scope, session string) error {
|
|||
return ctx.Err()
|
||||
}
|
||||
defer func() { <-gate }()
|
||||
|
||||
d.mu.Lock()
|
||||
if d.tasks[session] != target || target.id == "" || target.stopping {
|
||||
d.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
// Stop new preview requests before waiting for an in-flight capture in Chrome.
|
||||
// Stop polling between turns; keep the browser session itself unchanged.
|
||||
target.idle = true
|
||||
d.mu.Unlock()
|
||||
data, err := m.callUI(ctx, s, session, "gateway.task_idle")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var result struct {
|
||||
Released bool `json:"released"`
|
||||
}
|
||||
if json.Unmarshal(data, &result) != nil || !result.Released {
|
||||
return errors.New("browser control was not released")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FinishTurn releases debugging first. Completed research tasks then close;
|
||||
// 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 {
|
||||
var rpcErr *RPCError
|
||||
if keepOpen || !errors.As(err, &rpcErr) || rpcErr.Code != errGatewayUIUnsupported.Code {
|
||||
return err
|
||||
}
|
||||
status, statusErr := m.GetStatus(ctx, s, session)
|
||||
if statusErr != nil {
|
||||
return statusErr
|
||||
}
|
||||
if status.Paused {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if keepOpen {
|
||||
return nil
|
||||
}
|
||||
return m.Control(ctx, s, session, "finish")
|
||||
return m.stopTask(ctx, s, session, d, true)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ type Status struct {
|
|||
LastError string `json:"last_error,omitempty"`
|
||||
Stopping bool `json:"stopping"`
|
||||
HelpPrompt string `json:"help_prompt,omitempty"`
|
||||
Idle bool `json:"idle"`
|
||||
Idle bool `json:"idle"` // Between turns; does not imply debugger release.
|
||||
NeedsHelp bool `json:"needs_help"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Selected bool `json:"selected"`
|
||||
|
|
@ -912,9 +912,6 @@ func (m *Manager) Control(ctx context.Context, s Scope, session, action string)
|
|||
return err
|
||||
}
|
||||
}
|
||||
if d == nil && action == "finish" {
|
||||
return nil
|
||||
}
|
||||
if d == nil && action == "stop" && m.store != nil {
|
||||
return m.store.clearTask(ctx, s, session)
|
||||
}
|
||||
|
|
@ -926,16 +923,6 @@ func (m *Manager) Control(ctx context.Context, s Scope, session, action string)
|
|||
}
|
||||
d.mu.Lock()
|
||||
t := d.tasks[session]
|
||||
if action == "finish" {
|
||||
// Automatic cleanup must not resume or discard interrupted work, nor
|
||||
// interrupt a new command/start that raced with turn completion.
|
||||
if t == nil || t.paused || t.starting || t.stopping || len(t.calls) > 0 || !t.idle {
|
||||
d.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
d.mu.Unlock()
|
||||
return m.stopTask(ctx, s, session, d, true)
|
||||
}
|
||||
if action == "auto_start" && (t == nil || !t.selected || t.paused || t.forgotten) {
|
||||
d.mu.Unlock()
|
||||
return errors.New("local browser is not selected or is paused; ask the user to resume")
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -162,8 +163,6 @@ func connectSharedFixture(
|
|||
result = map[string]any{"cancelled": true}
|
||||
case "gateway.task_preview":
|
||||
result = map[string]any{"image_base64": "dGVzdA==", "format": "jpeg"}
|
||||
case "gateway.task_idle":
|
||||
result = map[string]any{"released": true}
|
||||
case "gateway.task_focus":
|
||||
result = map[string]any{"focused": true}
|
||||
case "system.ping":
|
||||
|
|
@ -573,7 +572,7 @@ func TestHumanHelpOutcomeControlsPause(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestIdleRetainsTaskAndCachedPreviewUntilNextCall(t *testing.T) {
|
||||
func TestFinishTurnRetainsTaskAndCachedPreviewUntilNextCall(t *testing.T) {
|
||||
m, ctx := sharedTestManager(t)
|
||||
s := Scope{1, "idle-user"}
|
||||
f := connectSharedFixture(ctx, t, m, s, "", "browser")
|
||||
|
|
@ -582,7 +581,7 @@ func TestIdleRetainsTaskAndCachedPreviewUntilNextCall(t *testing.T) {
|
|||
before := m.Status(s, "chat")
|
||||
frame, err := m.Preview(ctx, s, "chat")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, m.Idle(ctx, s, "chat"))
|
||||
require.NoError(t, m.FinishTurn(ctx, s, "chat", true))
|
||||
after := m.Status(s, "chat")
|
||||
require.True(t, after.Idle)
|
||||
require.Equal(t, before.SessionID, after.SessionID)
|
||||
|
|
@ -599,7 +598,7 @@ func TestIdleRetainsTaskAndCachedPreviewUntilNextCall(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
require.False(t, m.Status(s, "chat").Idle)
|
||||
require.NoError(t, m.Control(ctx, s, "chat", "stop"))
|
||||
require.NoError(t, m.Idle(ctx, s, "chat"))
|
||||
require.NoError(t, m.FinishTurn(ctx, s, "chat", true))
|
||||
}
|
||||
|
||||
func TestNavigationDefaultsToDocumentReadyAndPreservesExplicitWait(t *testing.T) {
|
||||
|
|
@ -657,7 +656,7 @@ func TestFinishTurnClosesResearchButRetainsHandoffsAndPausedTasks(t *testing.T)
|
|||
}
|
||||
}
|
||||
|
||||
func TestFinishTurnWithOfficialExtensionStillStopsCompletedTask(t *testing.T) {
|
||||
func TestFinishTurnUsesOfficialLifecycleWithoutGatewayCalls(t *testing.T) {
|
||||
for _, remote := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("remote=%t", remote), func(t *testing.T) {
|
||||
owner, ctx := sharedTestManager(t)
|
||||
|
|
@ -673,12 +672,14 @@ func TestFinishTurnWithOfficialExtensionStillStopsCompletedTask(t *testing.T) {
|
|||
t.Cleanup(caller.Close)
|
||||
}
|
||||
scope := Scope{1, "official-extension"}
|
||||
var gatewayCalls atomic.Int32
|
||||
connectSharedFixture(ctx, t, owner, scope, "", "browser", func(
|
||||
f *sharedFixture, id, method string, _ map[string]any,
|
||||
) bool {
|
||||
if !strings.HasPrefix(method, "gateway.") {
|
||||
return false
|
||||
}
|
||||
gatewayCalls.Add(1)
|
||||
_ = f.send(map[string]any{"id": id, "error": map[string]string{"code": "unknown_method"}})
|
||||
return true
|
||||
})
|
||||
|
|
@ -691,11 +692,16 @@ func TestFinishTurnWithOfficialExtensionStillStopsCompletedTask(t *testing.T) {
|
|||
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)
|
||||
id := owner.Status(scope, session).SessionID
|
||||
require.NoError(t, caller.FinishTurn(ctx, scope, session, keep))
|
||||
require.Equal(t, id, owner.Status(scope, session).SessionID)
|
||||
if keep {
|
||||
_, err := caller.Call(ctx, scope, session, "snapshot", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, id, owner.Status(scope, session).SessionID)
|
||||
}
|
||||
}
|
||||
require.Zero(t, gatewayCalls.Load(), "turn cleanup must not send custom gateway RPC")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
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
|
||||
index 8f99c94..16f7499 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() {
|
||||
@@ -30,6 +30,77 @@ function fakeApi() {
|
||||
}
|
||||
|
||||
describe("ChromiumCdp", () => {
|
||||
|
|
@ -76,37 +76,11 @@ index c901e49..2368337 100644
|
|||
+ 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", () => {
|
||||
@@ -430,6 +501,7 @@ describe("ChromiumCdp", () => {
|
||||
expect(api.sendCommand).toHaveBeenCalledWith({ tabId: 3 }, "Page.handleJavaScriptDialog", {
|
||||
accept: true,
|
||||
});
|
||||
|
|
@ -114,7 +88,7 @@ index c901e49..2368337 100644
|
|||
const dialogs = cdp.dialogsSince(3, cursor);
|
||||
expect(dialogs).toHaveLength(1);
|
||||
expect(dialogs[0]).toMatchObject({
|
||||
@@ -479,7 +577,7 @@ describe("ChromiumCdp", () => {
|
||||
@@ -479,7 +551,7 @@ describe("ChromiumCdp", () => {
|
||||
url: "https://example.com/",
|
||||
});
|
||||
await Promise.resolve();
|
||||
|
|
@ -207,10 +181,10 @@ index 0000000..7c1dd61
|
|||
+});
|
||||
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
|
||||
index 0000000..fe79f2a
|
||||
--- /dev/null
|
||||
+++ b/apps/extension/src/browser-driver/__tests__/task-focus.browser.test.ts
|
||||
@@ -0,0 +1,94 @@
|
||||
@@ -0,0 +1,96 @@
|
||||
+// @vitest-environment node
|
||||
+import { describe, expect, it } from "vitest";
|
||||
+import { captureVomObservation } from "@/tools/observation";
|
||||
|
|
@ -257,6 +231,8 @@ index 0000000..deed38f
|
|||
+ session,
|
||||
+ )
|
||||
+ ).result.value;
|
||||
+ // A newly created target may still expose the initial complete about:blank.
|
||||
+ await expect.poll(() => evaluate("document.title")).toBe("Background task");
|
||||
+ await expect.poll(() => evaluate("document.readyState")).toBe("complete");
|
||||
+ expect(
|
||||
+ await evaluate(
|
||||
|
|
@ -278,9 +254,9 @@ index 0000000..deed38f
|
|||
+ onEvent: event,
|
||||
+ onDetach: event,
|
||||
+ } as unknown as CdpDebuggerApi;
|
||||
+ const cdp = new ChromiumCdp(api, { shouldKeepTaskActive: () => true });
|
||||
+ const cdp = new ChromiumCdp(api);
|
||||
+ try {
|
||||
+ await cdp.ensureAttached(4);
|
||||
+ await cdp.acquireBackgroundExecution("task", 4);
|
||||
+ expect(
|
||||
+ await evaluate(
|
||||
+ 'new Promise(resolve=>requestAnimationFrame(()=>resolve(document.querySelector("p").textContent)))',
|
||||
|
|
@ -295,7 +271,7 @@ index 0000000..deed38f
|
|||
+ });
|
||||
+ expect(image.data.length).toBeGreaterThan(100);
|
||||
+ expect(await evaluate("document.visibilityState", foregroundSession)).toBe("visible");
|
||||
+ await cdp.detach(4);
|
||||
+ await cdp.releaseSessionTab("task", 4);
|
||||
+ sessionId = (await send("Target.attachToTarget", { targetId, flatten: true })).sessionId;
|
||||
+ expect(await evaluate("document.visibilityState")).toBe("hidden");
|
||||
+ } finally {
|
||||
|
|
@ -306,18 +282,18 @@ index 0000000..deed38f
|
|||
+ }, 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
|
||||
index 2779da7..eebb362 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,
|
||||
@@ -32,6 +32,7 @@ import type {
|
||||
NetworkResult,
|
||||
} from "@/transport/types";
|
||||
import { BackgroundExecution } from "./background-execution";
|
||||
+import { runCdpCommand } from "./command-deadline";
|
||||
import {
|
||||
buildFrameGraph,
|
||||
type CdpFrameGraph,
|
||||
@@ -140,6 +141,7 @@ interface FrameDiscoveryState {
|
||||
@@ -141,6 +142,7 @@ interface FrameDiscoveryState {
|
||||
sessions: Set<string>;
|
||||
pending: Set<Promise<void>>;
|
||||
generation: number;
|
||||
|
|
@ -325,104 +301,41 @@ index d40325c..720f87a 100644
|
|||
}
|
||||
|
||||
async function settleBeforeDeadline(promises: Promise<void>[], deadline: number): Promise<boolean> {
|
||||
@@ -164,6 +166,8 @@ async function settleBeforeDeadline(promises: Promise<void>[], deadline: number)
|
||||
@@ -165,13 +167,14 @@ 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`.
|
||||
*/
|
||||
private readonly backgroundExecution = new BackgroundExecution(
|
||||
(tabId) => this.attachmentIds.get(tabId),
|
||||
(tabId, enabled) =>
|
||||
- this.api.sendCommand({ tabId }, "Emulation.setFocusEmulationEnabled", { enabled }),
|
||||
+ this.command({ tabId }, "Emulation.setFocusEmulationEnabled", { enabled }),
|
||||
);
|
||||
private readonly tabOwners = new Map<number, Set<string>>();
|
||||
private readonly dialogBuffers = new Map<number, JavaScriptDialogInfo[]>();
|
||||
@@ -295,7 +298,7 @@ export class ChromiumCdp {
|
||||
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);
|
||||
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 {
|
||||
}
|
||||
|
||||
@@ -305,7 +308,7 @@ 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);
|
||||
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 {
|
||||
@@ -563,6 +566,7 @@ export class ChromiumCdp {
|
||||
this.networkDomainsEnabledTabs.clear();
|
||||
this.networkRequestMeta.clear();
|
||||
this.frameDiscovery.clear();
|
||||
|
|
@ -430,7 +343,7 @@ index d40325c..720f87a 100644
|
|||
await Promise.all(
|
||||
tabs.map(async (tabId) => {
|
||||
try {
|
||||
@@ -536,8 +553,48 @@ export class ChromiumCdp {
|
||||
@@ -574,8 +578,31 @@ export class ChromiumCdp {
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -456,23 +369,6 @@ index d40325c..720f87a 100644
|
|||
+ 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", {});
|
||||
|
|
@ -480,7 +376,7 @@ index d40325c..720f87a 100644
|
|||
}
|
||||
|
||||
private async enableConsoleDomains(tabId: number): Promise<void> {
|
||||
@@ -550,7 +607,7 @@ export class ChromiumCdp {
|
||||
@@ -588,7 +615,7 @@ export class ChromiumCdp {
|
||||
let failed = false;
|
||||
for (const method of ["Runtime.enable", "Log.enable"]) {
|
||||
try {
|
||||
|
|
@ -489,7 +385,7 @@ index d40325c..720f87a 100644
|
|||
} catch (err) {
|
||||
failed = true;
|
||||
console.debug("[bsk cdp] console domain enable failed", { tabId, method, err });
|
||||
@@ -563,7 +620,7 @@ export class ChromiumCdp {
|
||||
@@ -601,7 +628,7 @@ export class ChromiumCdp {
|
||||
|
||||
private async enableNetworkDomain(tabId: number): Promise<void> {
|
||||
if (this.networkDomainsEnabledTabs.has(tabId)) return;
|
||||
|
|
@ -498,7 +394,7 @@ index d40325c..720f87a 100644
|
|||
this.networkDomainsEnabledTabs.add(tabId);
|
||||
}
|
||||
|
||||
@@ -575,13 +632,27 @@ export class ChromiumCdp {
|
||||
@@ -613,13 +640,27 @@ export class ChromiumCdp {
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -529,7 +425,7 @@ index d40325c..720f87a 100644
|
|||
}
|
||||
|
||||
private bindFrameTargetHandler(): void {
|
||||
@@ -608,6 +679,7 @@ export class ChromiumCdp {
|
||||
@@ -646,6 +687,7 @@ export class ChromiumCdp {
|
||||
|
||||
if (method === "Target.detachedFromTarget") {
|
||||
const state = this.frameDiscovery.get(tabId);
|
||||
|
|
@ -537,7 +433,7 @@ index d40325c..720f87a 100644
|
|||
if (state?.sessions.delete(sessionId)) state.generation += 1;
|
||||
return;
|
||||
}
|
||||
@@ -674,6 +746,7 @@ export class ChromiumCdp {
|
||||
@@ -712,6 +754,7 @@ export class ChromiumCdp {
|
||||
sessions: new Set(),
|
||||
pending: new Set(),
|
||||
generation: 0,
|
||||
|
|
@ -545,7 +441,7 @@ index d40325c..720f87a 100644
|
|||
};
|
||||
this.frameDiscovery.set(tabId, created);
|
||||
return created;
|
||||
@@ -681,6 +754,7 @@ export class ChromiumCdp {
|
||||
@@ -719,6 +762,7 @@ export class ChromiumCdp {
|
||||
|
||||
private clearFrameState(tabId: number): void {
|
||||
this.frameDiscovery.delete(tabId);
|
||||
|
|
@ -553,7 +449,7 @@ index d40325c..720f87a 100644
|
|||
}
|
||||
|
||||
private bindDialogHandler(): void {
|
||||
@@ -713,7 +787,7 @@ export class ChromiumCdp {
|
||||
@@ -751,7 +795,7 @@ export class ChromiumCdp {
|
||||
if (parsed.type === "prompt") {
|
||||
handleParams.promptText = parsed.defaultPrompt ?? "";
|
||||
}
|
||||
|
|
@ -562,14 +458,6 @@ index d40325c..720f87a 100644
|
|||
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
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts
|
||||
index 830bbbe..1a9a788 100644
|
||||
index 830bbbe..cb88179 100644
|
||||
--- a/apps/extension/src/entrypoints/background.ts
|
||||
+++ b/apps/extension/src/entrypoints/background.ts
|
||||
@@ -4,6 +4,7 @@ import { getAuditEnabled } from "@/lib/audit";
|
||||
|
|
@ -10,16 +10,15 @@ index 830bbbe..1a9a788 100644
|
|||
import { startHeartbeat } from "@/lib/heartbeat";
|
||||
import {
|
||||
getConnectionEnabled,
|
||||
@@ -27,6 +28,8 @@ import {
|
||||
@@ -27,6 +28,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 { 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(() => {
|
||||
@@ -63,7 +65,21 @@ export default defineBackground(() => {
|
||||
url: __BSK_DAEMON_WS_URL__,
|
||||
webSocketFactory: (url) => {
|
||||
if (!connectionPreferenceValid) throw new Error("Connection settings are unavailable");
|
||||
|
|
@ -36,51 +35,18 @@ index 830bbbe..1a9a788 100644
|
|||
+ 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 };
|
||||
+ },
|
||||
+ preview: (sessionId) => captureTaskPreview(sessions, cdp, sessionId),
|
||||
+ });
|
||||
+ 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
|
||||
index 0000000..273c15b
|
||||
--- /dev/null
|
||||
+++ b/apps/extension/src/lib/__tests__/gateway-ui.test.ts
|
||||
@@ -0,0 +1,52 @@
|
||||
@@ -0,0 +1,51 @@
|
||||
+import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
+import { attachGatewayUI } from "../gateway-ui";
|
||||
+
|
||||
|
|
@ -91,7 +57,6 @@ index 0000000..eda0a0e
|
|||
+ 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();
|
||||
|
|
@ -105,7 +70,7 @@ index 0000000..eda0a0e
|
|||
+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) {
|
||||
+ for (const name of ["preview", "focus"] as const) {
|
||||
+ await f.request({ id: name, method: `gateway.task_${name}`, params: { session_id: "task" } });
|
||||
+ expect(f.ui[name]).toHaveBeenCalledWith("task");
|
||||
+ }
|
||||
|
|
@ -123,8 +88,8 @@ index 0000000..eda0a0e
|
|||
+ });
|
||||
+ 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" } });
|
||||
+ f.ui.focus.mockRejectedValueOnce(new Error("unavailable"));
|
||||
+ await f.request({ id: "focus", method: "gateway.task_focus", params: { session_id: "task" } });
|
||||
+ expect(JSON.parse(f.socket.send.mock.calls[0]![0])).toMatchObject({
|
||||
+ error: { code: "task_unavailable" },
|
||||
+ });
|
||||
|
|
@ -133,117 +98,17 @@ index 0000000..eda0a0e
|
|||
+ 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..49d1e24
|
||||
index 0000000..3939bae
|
||||
--- /dev/null
|
||||
+++ b/apps/extension/src/lib/__tests__/task-preview.test.ts
|
||||
@@ -0,0 +1,167 @@
|
||||
@@ -0,0 +1,180 @@
|
||||
+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";
|
||||
+import { captureTaskPreview, withTaskPreviewStop } from "../task-preview";
|
||||
+
|
||||
+afterEach(() => {
|
||||
+ vi.unstubAllGlobals();
|
||||
|
|
@ -261,9 +126,8 @@ index 0000000..49d1e24
|
|||
+ 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 () => {}),
|
||||
+ acquireBackgroundExecution: vi.fn(async () => {}),
|
||||
+ send: vi.fn(async (_tab, method) =>
|
||||
+ method === "Page.getLayoutMetrics"
|
||||
+ ? { cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 1280, clientHeight: 720 } }
|
||||
|
|
@ -313,11 +177,12 @@ index 0000000..49d1e24
|
|||
+ image_base64: btoa("thumbnail"),
|
||||
+ });
|
||||
+ }
|
||||
+ expect(f.cdp.acquireBackgroundExecution).toHaveBeenCalledWith("visible", 5);
|
||||
+ expect(f.cdp.send).toHaveBeenCalledTimes(3);
|
||||
+ expect(chrome.tabs.sendMessage).not.toHaveBeenCalled();
|
||||
+ });
|
||||
+
|
||||
+ it("lets turn-end release finish after a stuck screenshot times out", async () => {
|
||||
+ it("lets native stop proceed after a stuck screenshot times out", async () => {
|
||||
+ vi.useFakeTimers();
|
||||
+ vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
+ vi.spyOn(console, "debug").mockImplementation(() => {});
|
||||
|
|
@ -328,22 +193,36 @@ index 0000000..49d1e24
|
|||
+ ? 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 stop = vi.fn(async () => {});
|
||||
+ const frame = captureTaskPreview(f.manager, f.cdp, "stuck");
|
||||
+ const checked = expect(frame).rejects.toThrow("Page.captureScreenshot timed out");
|
||||
+ const released = activity.release("stuck");
|
||||
+ const released = withTaskPreviewStop(f.manager, "stuck", stop);
|
||||
+ await expect(captureTaskPreview(f.manager, f.cdp, "stuck")).rejects.toThrow("stopping");
|
||||
+ expect(stop).not.toHaveBeenCalled();
|
||||
+ await vi.advanceTimersByTimeAsync(3_000);
|
||||
+ await checked;
|
||||
+ await released;
|
||||
+ expect(detach).toHaveBeenCalledWith("stuck");
|
||||
+ expect(stop).toHaveBeenCalledOnce();
|
||||
+ expect(vi.getTimerCount()).toBe(0);
|
||||
+ vi.mocked(f.cdp.send).mockImplementation(original);
|
||||
+ await expect(
|
||||
+ activity.run("stuck", false, () => captureTaskPreview(f.manager, f.cdp, "stuck")),
|
||||
+ captureTaskPreview(f.manager, f.cdp, "stuck"),
|
||||
+ ).resolves.toMatchObject({ tab_id: 5 });
|
||||
+ });
|
||||
+
|
||||
+ it("blocks previews throughout native cleanup and restores them after a failed stop", async () => {
|
||||
+ const f = fixture();
|
||||
+ let reject!: (error: Error) => void;
|
||||
+ const pending = new Promise<never>((_, fail) => { reject = fail; });
|
||||
+ const stopping = withTaskPreviewStop(f.manager, "retry", () => pending);
|
||||
+ const checked = expect(stopping).rejects.toThrow("return failed");
|
||||
+ await expect(captureTaskPreview(f.manager, f.cdp, "retry")).rejects.toThrow("stopping");
|
||||
+ expect(f.cdp.acquireBackgroundExecution).not.toHaveBeenCalled();
|
||||
+ reject(new Error("return failed"));
|
||||
+ await checked;
|
||||
+ await expect(captureTaskPreview(f.manager, f.cdp, "retry")).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");
|
||||
|
|
@ -363,7 +242,7 @@ index 0000000..49d1e24
|
|||
+ 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.acquireBackgroundExecution).not.toHaveBeenCalled();
|
||||
+ expect(f.cdp.send).not.toHaveBeenCalled();
|
||||
+ });
|
||||
+ it("does not capture an unowned active user tab", async () => {
|
||||
|
|
@ -376,7 +255,7 @@ index 0000000..49d1e24
|
|||
+ });
|
||||
+ it("discards the result if authorization ends during capture", async () => {
|
||||
+ const f = fixture();
|
||||
+ vi.mocked(f.cdp.ensureAttached).mockImplementation(async () => {
|
||||
+ vi.mocked(f.cdp.acquireBackgroundExecution).mockImplementation(async () => {
|
||||
+ f.task.agentCreatedTabs.clear();
|
||||
+ });
|
||||
+ await expect(captureTaskPreview(f.manager, f.cdp, "ended")).rejects.toThrow(
|
||||
|
|
@ -407,14 +286,13 @@ index 0000000..49d1e24
|
|||
+});
|
||||
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
|
||||
index 0000000..ef0443f
|
||||
--- /dev/null
|
||||
+++ b/apps/extension/src/lib/gateway-ui.ts
|
||||
@@ -0,0 +1,42 @@
|
||||
@@ -0,0 +1,40 @@
|
||||
+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.
|
||||
|
|
@ -431,7 +309,6 @@ index 0000000..a020db8
|
|||
+ 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();
|
||||
|
|
@ -453,121 +330,67 @@ index 0000000..a020db8
|
|||
+ );
|
||||
+ });
|
||||
+}
|
||||
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..38d1917
|
||||
index 0000000..a6d2532
|
||||
--- /dev/null
|
||||
+++ b/apps/extension/src/lib/task-preview.ts
|
||||
@@ -0,0 +1,103 @@
|
||||
@@ -0,0 +1,143 @@
|
||||
+import type { ChromiumCdp } from "@/browser-driver/chromium-cdp";
|
||||
+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. */
|
||||
+interface PreviewState {
|
||||
+ pending?: Promise<unknown>;
|
||||
+ stopping: number;
|
||||
+}
|
||||
+const previews = new WeakMap<object, PreviewState>();
|
||||
+function previewState(task: object): PreviewState {
|
||||
+ let state = previews.get(task);
|
||||
+ if (!state) {
|
||||
+ state = { stopping: 0 };
|
||||
+ previews.set(task, state);
|
||||
+ }
|
||||
+ return state;
|
||||
+}
|
||||
+
|
||||
+/** UI-only capture outside the automation queue, including human-help waits. */
|
||||
+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);
|
||||
+ const task = manager.get(sessionId);
|
||||
+ if (!task?.remote) return Promise.reject(new Error("Task unavailable"));
|
||||
+ const state = previewState(task);
|
||||
+ if (state.stopping) return Promise.reject(new Error("Task is stopping"));
|
||||
+ if (state.pending) return state.pending;
|
||||
+ const work = capture(manager, cdp, sessionId).finally(() => {
|
||||
+ if (state.pending === work) state.pending = undefined;
|
||||
+ });
|
||||
+ state.pending = work;
|
||||
+ return work;
|
||||
+}
|
||||
+
|
||||
+/** Drain side-channel screenshots before the official stop handler detaches
|
||||
+ * and closes tabs. No turn-end detach or custom session state is introduced. */
|
||||
+export async function withTaskPreviewStop<T>(
|
||||
+ manager: SessionManager,
|
||||
+ sessionId: string | undefined,
|
||||
+ stop: () => Promise<T>,
|
||||
+): Promise<T> {
|
||||
+ const task = sessionId ? manager.get(sessionId) : undefined;
|
||||
+ if (!task?.remote) return stop();
|
||||
+ const state = previewState(task);
|
||||
+ state.stopping++;
|
||||
+ try {
|
||||
+ await state.pending?.catch(() => {});
|
||||
+ return await stop();
|
||||
+ } finally {
|
||||
+ // A failed native stop can be retried; it must not permanently disable previews.
|
||||
+ state.stopping--;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+async function capture(manager: SessionManager, cdp: ChromiumCdp, sessionId: string) {
|
||||
+ const task = manager.get(sessionId);
|
||||
+ if (!task?.remote) throw new Error("Task unavailable");
|
||||
|
|
@ -577,8 +400,10 @@ index 0000000..38d1917
|
|||
+ 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);
|
||||
+ // Preview bypasses the automation dispatcher, so acquire the same explicit
|
||||
+ // control policy before reading a background page. Native session stop drains
|
||||
+ // this capture before releasing the claim and closing tabs.
|
||||
+ await cdp.acquireBackgroundExecution(sessionId, tabId);
|
||||
+ if (manager.get(sessionId) !== task || !isAgentControlledTab(task, tabId))
|
||||
+ throw new Error("Task ended during capture");
|
||||
+ const attachment = cdp.getAttachmentId(tabId);
|
||||
|
|
@ -654,67 +479,27 @@ index 0000000..38d1917
|
|||
+ 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);
|
||||
+ }
|
||||
diff --git a/apps/extension/src/tools/session.ts b/apps/extension/src/tools/session.ts
|
||||
index 4e0220b..ce13827 100644
|
||||
--- a/apps/extension/src/tools/session.ts
|
||||
+++ b/apps/extension/src/tools/session.ts
|
||||
@@ -1,3 +1,4 @@
|
||||
+import { withTaskPreviewStop } from "@/lib/task-preview";
|
||||
import {
|
||||
DEFAULT_INTERACTION_PREFERENCES,
|
||||
type InteractionPreferenceStore,
|
||||
@@ -196,6 +197,14 @@ export async function handleSessionStop(
|
||||
manager: SessionManager,
|
||||
params: SessionStopParams,
|
||||
deps: SessionStopDeps = {},
|
||||
+): Promise<SessionStopResult | RpcError> {
|
||||
+ return withTaskPreviewStop(manager, params?.session_id, () => stopSession(manager, params, deps));
|
||||
+}
|
||||
+
|
||||
private async releaseHoverLatch(sessionId?: string, tabId?: number): Promise<void> {
|
||||
const matchesScope = (entrySessionId: string, entryTabId: number): boolean => {
|
||||
if (sessionId !== undefined && entrySessionId !== sessionId) return false;
|
||||
+async function stopSession(
|
||||
+ manager: SessionManager,
|
||||
+ params: SessionStopParams,
|
||||
+ deps: SessionStopDeps,
|
||||
): Promise<SessionStopResult | RpcError> {
|
||||
if (!params?.session_id) {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,102 +0,0 @@
|
|||
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,
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts
|
||||
index 1a9a788..5a2f0ef 100644
|
||||
index cb88179..cba98b8 100644
|
||||
--- a/apps/extension/src/entrypoints/background.ts
|
||||
+++ b/apps/extension/src/entrypoints/background.ts
|
||||
@@ -339,10 +339,12 @@ export default defineBackground(() => {
|
||||
@@ -326,10 +326,12 @@ export default defineBackground(() => {
|
||||
},
|
||||
...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),
|
||||
deps: {
|
||||
|
|
@ -183,10 +183,10 @@ index 0000000..53db1bf
|
|||
+ }
|
||||
+}
|
||||
diff --git a/apps/extension/src/tools/__tests__/tabs.test.ts b/apps/extension/src/tools/__tests__/tabs.test.ts
|
||||
index dc9fdb5..ae9534d 100644
|
||||
index 5a7239e..b48a15e 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", () => {
|
||||
@@ -298,7 +298,7 @@ describe("handleTabCreate", () => {
|
||||
});
|
||||
|
||||
describe("handleTabClose", () => {
|
||||
|
|
@ -195,7 +195,7 @@ index dc9fdb5..ae9534d 100644
|
|||
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]), remote: () => true });
|
||||
const ctx = await sm.start("aa11");
|
||||
const state: FakeTabState = {
|
||||
@@ -309,6 +309,15 @@ describe("handleTabClose", () => {
|
||||
@@ -310,6 +310,15 @@ describe("handleTabClose", () => {
|
||||
expect(
|
||||
await handleTabClose(sm, { session_id: "aa11", tab_id: 5 }, { tabs: api }),
|
||||
).toMatchObject({ code: "permission_denied" });
|
||||
|
|
@ -211,7 +211,7 @@ index dc9fdb5..ae9534d 100644
|
|||
const approval = vi.fn(async () => true);
|
||||
expect(
|
||||
await handleTabBorrow(
|
||||
@@ -316,13 +325,32 @@ describe("handleTabClose", () => {
|
||||
@@ -317,13 +326,32 @@ describe("handleTabClose", () => {
|
||||
{ session_id: "aa11", tab_id: 5 },
|
||||
{ tabs: api, approveBorrow: approval },
|
||||
),
|
||||
|
|
@ -250,22 +250,22 @@ index dc9fdb5..ae9534d 100644
|
|||
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
|
||||
index b713f2f..93908bc 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";
|
||||
@@ -2,6 +2,7 @@ import type { InteractionPreferenceStore } from "@/lib/interaction-preferences";
|
||||
import { OVERLAY_AUTOMATION_BYPASS } from "@/lib/overlay-bridge";
|
||||
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 {
|
||||
@@ -276,7 +277,24 @@ export class ToolDispatcher {
|
||||
} catch {
|
||||
/* The daemon still has the original operation metadata. */
|
||||
}
|
||||
- const invoke = () => this.invoke(req, ac.signal);
|
||||
- const result = await this.invoke(req, ac.signal);
|
||||
+ const createsPopup = [
|
||||
+ "tool.click",
|
||||
+ "tool.press_key",
|
||||
|
|
@ -276,23 +276,22 @@ index 0726f27..8afdedf 100644
|
|||
+ "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,
|
||||
+ const result = createsPopup
|
||||
+ ? await withTaskPopups(
|
||||
+ this.sessions,
|
||||
+ (req.params ?? {}) as { session_id?: string; tab_id?: number },
|
||||
+ () => this.invoke(req, ac.signal),
|
||||
+ this.onAgentTabClaimed,
|
||||
+ )
|
||||
+ : await this.invoke(req, ac.signal);
|
||||
if (isRpcError(result)) {
|
||||
body = { id: req.id, error: classifyCdpError(result) };
|
||||
} else {
|
||||
diff --git a/apps/extension/src/tools/tabs.ts b/apps/extension/src/tools/tabs.ts
|
||||
index 5e90e6b..2570c74 100644
|
||||
index 4130ca4..86b5cfa 100644
|
||||
--- a/apps/extension/src/tools/tabs.ts
|
||||
+++ b/apps/extension/src/tools/tabs.ts
|
||||
@@ -646,13 +646,12 @@ async function validateBorrowTarget(
|
||||
@@ -697,13 +697,12 @@ async function validateBorrowTarget(
|
||||
if (typeof tab.id !== "number" || typeof tab.windowId !== "number") {
|
||||
return { code: "not_found", message: `tab ${tabId} not found` };
|
||||
}
|
||||
|
|
@ -310,7 +309,7 @@ index 5e90e6b..2570c74 100644
|
|||
};
|
||||
}
|
||||
for (const s of manager.list()) {
|
||||
@@ -772,14 +771,17 @@ async function executeBorrowCore(
|
||||
@@ -823,14 +822,17 @@ async function executeBorrowCore(
|
||||
|
||||
const originalWindowId = currentTab.windowId;
|
||||
const originalIndex = typeof currentTab.index === "number" ? currentTab.index : 0;
|
||||
|
|
|
|||
|
|
@ -1,156 +0,0 @@
|
|||
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!({
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
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!({
|
||||
|
|
@ -1,26 +1,40 @@
|
|||
# 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 extension and daemon are based on official `main` commit
|
||||
`fa953dc6fcd868827b93164e3bea26198e691224` (after `ext-v0.3.0`). Both still
|
||||
report version `0.3.0`; the exact source baseline is recorded in
|
||||
`scripts/browserskill-release.json`. The daemon is built with
|
||||
`cargo build --locked --release -p bsk` and includes our navigation-response
|
||||
deadline patch, so the official CLI 0.3.0 binary is not an equivalent replacement.
|
||||
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 |
|
||||
| `01-browser-read-reliability.patch` | Bound CDP reads, prevent overlapping timed-out screenshots, reuse frame discovery configuration | Equivalent upstream behavior passes the background rendering and timeout regressions |
|
||||
| `02-gateway-task-controls.patch` | WeKnora preview and focus side channel; drain previews before native session stop | Upstream provides equivalent UI APIs and WeKnora migrates to them |
|
||||
| `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 |
|
||||
| `06-navigation-response-deadline.patch` | Allow navigation lifecycle timeout results to arrive before the daemon transport deadline | Upstream adds equivalent navigation response grace |
|
||||
|
||||
Background execution and viewport/full-page screenshot support use upstream
|
||||
PRs #249, #250 and #253. VOM sibling-context caching is upstream PR #271, so
|
||||
patch 03 was removed. Redirect document tracking and cancelled-navigation
|
||||
reconciliation also use upstream code (including PR #280); patch 06 now changes
|
||||
only the daemon deadline. The numbering gaps preserve existing patch identities.
|
||||
|
||||
The preview side channel explicitly acquires upstream background execution
|
||||
because it bypasses the automation dispatcher. Native session stop drains
|
||||
in-flight previews before the official handler releases control and closes tabs.
|
||||
Retained tasks keep the official session and debugger; turn completion only
|
||||
stops preview polling in WeKnora. Do not restore the old
|
||||
`shouldKeepTaskActive` callback or a second focus-emulation cache.
|
||||
|
||||
Remote authentication, credential storage/migration, renewal, connection settings,
|
||||
and dedicated Agent Windows use upstream code. The fourth patch extends the
|
||||
and dedicated Agent Windows use upstream code. Patch 04 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
|
||||
|
|
@ -44,16 +58,12 @@ enter the native daemon's automation queue:
|
|||
still suppress overlays to preserve unobstructed page content.
|
||||
- `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.
|
||||
envelope. These two methods are downstream APIs, not official BrowserSkill RPCs.
|
||||
The official unmodified extension returns `unknown_method` for these UI requests.
|
||||
Turn cleanup needs no custom RPC: retained tasks keep their session, and completed
|
||||
tasks use native session stop. Keep serving the companion ZIP for preview/focus.
|
||||
|
||||
## Intentional behavior changes
|
||||
|
||||
|
|
@ -72,6 +82,7 @@ requires this companion build. Keep serving the companion ZIP in WeKnora setting
|
|||
- Human help and borrowing follow the upstream focus/confirmation behavior.
|
||||
- Remote upload/download remain unsupported, as defined upstream.
|
||||
|
||||
Even though the version remains 0.3.0, users must install the rebuilt ZIP.
|
||||
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
|
||||
|
|
@ -87,16 +98,22 @@ 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
|
||||
BSK_GEOMETRY_CHROME=/path/to/test-chrome BSK_BACKGROUND_CHROME=/path/to/test-chrome \
|
||||
pnpm --filter @browser-skill/extension exec vitest run --maxWorkers=1 \
|
||||
src/browser-driver/__tests__/task-focus.browser.test.ts \
|
||||
src/tools/__tests__/background-execution.browser.test.ts \
|
||||
src/tools/__tests__/background-screenshot.browser.test.ts \
|
||||
src/tools/__tests__/background-full-page.browser.test.ts
|
||||
cargo test --locked -p bsk daemon::ipc::tests
|
||||
```
|
||||
|
||||
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.
|
||||
focus, pause/resume, retained-session continuity 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).
|
||||
[remote connection contract](https://github.com/Tencent/BrowserSkill/blob/fa953dc6fcd868827b93164e3bea26198e691224/docs/remote-extension-connection.md).
|
||||
|
|
|
|||
|
|
@ -2,11 +2,10 @@
|
|||
"version": "0.3.0",
|
||||
"extension": {
|
||||
"version": "0.3.0",
|
||||
"source_commit": "75e2c64abaf4b7cc75682d94b0c1fd5db0cbd5e5",
|
||||
"upstream_tag": "ext-v0.3.0"
|
||||
"source_commit": "fa953dc6fcd868827b93164e3bea26198e691224"
|
||||
},
|
||||
"daemon": {
|
||||
"source_commit": "75e2c64abaf4b7cc75682d94b0c1fd5db0cbd5e5",
|
||||
"source_commit": "fa953dc6fcd868827b93164e3bea26198e691224",
|
||||
"build": "cargo build --locked --release -p bsk"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,8 +46,8 @@ done
|
|||
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"
|
||||
|
||||
# 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.
|
||||
# Build the daemon from the same source and apply our navigation-response
|
||||
# deadline fix; published CLI binaries do not include this downstream patch.
|
||||
cargo_target_dir="${CARGO_TARGET_DIR:-$build_dir/target}"
|
||||
mkdir -p "$cargo_target_dir"
|
||||
cargo_target_dir="$(cd "$cargo_target_dir" && pwd)"
|
||||
|
|
|
|||
Loading…
Reference in New Issue