# Browser automation V2

## Desktop first, CLI compatible

Desktop owns a browser session/profile and displays its headless Chromium page
through `browserBridge` / `BrowserStream` in `BrowserPanel`. This is the embedded
browser, not the user's default browser window or profile. CLI uses the same
automation engine without a viewer. Tests must use unique sessions/profiles,
explicit headless mode, and stop only their own daemon; never `close --all`.

`WebBrowser` routes observation, verification, navigation and supported semantic
actions through `BrowserBatch`. The legacy daemon adapter remains for coordinate
and advanced commands not implemented by the structured engine. `BrowserCDP` is
an explicitly powerful debugging escape hatch, not a read-only sandbox. Host
task grants still apply. Do not retry mutations whose outcome is unknown.

## Observation and references

Use `observe` (or `snapshot`) for schemaVersion 2 records. States preserve false,
zero, mixed, description, focus, disabled, checked and selected values. Observe
specific frames separately; coverage states unobserved children and fallback
limitations. Capture is best-effort within one document, not an atomic page lock.

- `snapshotId` identifies immutable data. Follow `nextCursor` until delivery is
  complete; never infer no changes from a partial page.
- `baseSnapshotId` explicitly requests a diff against a completely delivered,
  compatible snapshot. Missing/expired/partial baselines reset to a full result.
- Clipped fields advertise `fieldLengths` and `clippedFields`. `readField` takes
  `snapshotId`, `fieldNodeId`, `field` and `offset`; follow `nextOffset`.
- `locator: { by: 'ref', value: elementRef }` resolves the observed DOM node in
  its original target/frame/document. Reloading even the same URL invalidates
  it. Detached nodes fail; there is no name/index fallback to another element.
- Old AX IDs and numeric AX-index locators are deliberately rejected. Legacy
  daemon `@eN` handles are not interchangeable with V2 `elementRef`.

References and snapshots expire after 15 minutes or eviction. Snapshots have a
128-entry / 24 MB memory budget; references have a 12,000-entry bound. Cursors
are scoped to their owner. Re-observe after expiry, document change or takeover.

## Business verification

`probe` captures named, bounded semantic/media values and a `baselineId`.
`verify` takes the same probe definitions plus assertions:

```json
{
  "action": "verify",
  "verification": {
    "probes": [{"name":"time","selector":"video","field":"currentTime"}],
    "assertions": [{"probe":"time","operator":"advances","minIncrease":0.5}],
    "durationMs": 2000,
    "intervalMs": 200
  }
}
```

Use `equals`, `approx`, `relation`, `advances`, or `preserved`. Preservation needs
a compatible baseline from `probe`. Baselines bind both top and sampled-frame
documents. Progress checks sample for the entire window and detect backwards
time, media replacement/source changes and observed seeking. Sampling is not
continuous: transitions between samples cannot be ruled out. Excessive gaps,
missing data, changed documents or unavailable values are `inconclusive`, never
successful verification. Aborts are `cancelled`; measured assertion failures are
`failed`. Execution success is separate from all these outcomes. A passing
window is not human acceptance or a claim of permanent application correctness.

Desktop receives only verification status and ID for its status banner, not the
private probe values. Batch stops on a non-passing check by default. Human
takeover must not silently replay writes or continue on stale observations.

## Evidence, privacy and context transfer

Results are valid JSON envelopes; large results advertise incomplete delivery
and `readEvidence` continuation rather than slicing JSON. Evidence lives under
the selected local state root, scoped by session/conversation. It expires after
7 days with bounded files per owner (128, at most 8 MB each). Reading it requires
the same owner; it is not automatically published to a group or server.

Sensitive input values and known credential fields/URL parameters are redacted.
This is defense in depth, not a guarantee that arbitrary page text or raw CDP
output is free of private information. Do not publish it without authorization.

Advisor, fork handoff and compaction retain outcome, evidence ID, document/time
scope, coverage gaps and uncertainty—not a claim that an evidence ID has been
read. Live references/cursors are temporary and are not portable agent context.

## Validation

- `bun test test/browserObservationV2.test.ts`: states, immutable pagination,
  partial diffs, field continuation, error semantics, schema and redaction.
- `bun run test:bench`: isolated real-browser legacy and V2 fixtures, including
  Desktop frame/pointer streaming, same-URL invalidation, media progress,
  preservation, last-intent wins, takeover and CLI compatibility.
- Desktop `bun run typecheck` / `bun run build:web` checks local dependency
  freshness. After source edits, copied installs need `bun install --force`.

Real bridge tests do not replace a final native Tauri panel visual check.

## 浏览器动作输入契约

`WebBrowser` 是单动作入口，`BrowserBatch` 的 `steps` 是批量入口。两者复用导航、定位、输入、观察、验证动作与参数校验（`browserActionContract.ts`）。单动作旧字段及坐标回退保留；批量专用步骤不因此获得单动作权限。批量输入在执行第一步前完成校验；页面变化、授权、目标存在性和验证结论仍由浏览器执行层判断。

两个入口的模型参数均是独立的对象 schema。重复的定位器、frame 链与探针形状通过本工具内部的 `$defs` / `$ref` 复用（`browserParameters.ts`），不引用另一个工具。运行 `bun test test/browserActionContract.test.ts` 可比较展开等价性、字段大小与固定合法/非法输入样本；这些比率是契约回归数据，不代表真实模型的工具选择正确率。

### 恢复、重试与产物

- 使用旧版 CLI 命令的单步动作没有跨连接的页面身份证明。若标签失效或连接断开，停止该动作并清除失效认领；不会拿旧编号重新发送命令。重新确认目标后再继续。
- 批量下载和导出的 `artifact.save_as` 必须是工作区中的新文件名。在动作开始前检查，发布时仍禁止覆盖（包括其他进程刚写的文件）。同一批次多次声明完全相同的文件名时，前面的步骤标为延迟交付，只有最后声明它的步骤能发布；最后一步未执行或发布失败则没有该具名交付物。需保留每一版时请指定不同名称。发布要求工作区支持硬链接，不支持时会报错而不会降级为覆盖写。

- 新建标签时，只有前后两次完整列表能唯一确定新增标签，才会认领并操作。遇到多个新标签或列表不完整时停止，不猜测当前活动页。调试事件属于原连接；读取旧事件不会为了返回空列表而重启浏览器。
- 批量步骤分开记录动作执行和后续验证。点击已执行但观察超时，不代表没有点击；先在所属标签页观察当前状态，再决定是否重试，不要直接重放整批。持续状态验证从第一次有效采样开始计时。
- 资产包相对路径以调用方工作区为准；已有 `manifest.json` 或 `assets/` 的目录不能复用。单个资源体上限 8 MiB，一次最多复制 32 MiB；检查返回的 `files` 和 `failures` 判断哪些资源真正落盘。取消时可能留下已复制的资源，未完成的打包不会发布新的完成清单。

`bun run audit:tools --browser-size` 对三个实际协议构造器做配对测量：同一模型、空历史、相同描述，分别保留两个浏览器工具及完整内置目录，唯一变量是是否展开这两个工具的子结构。结果单位为序列化请求体 UTF-8 字节，不是模型 token、网络压缩后的流量或账单。
