diff --git a/cmake/acecode_source_paths.cmake b/cmake/acecode_source_paths.cmake index 4497e8053..2e1425626 100644 --- a/cmake/acecode_source_paths.cmake +++ b/cmake/acecode_source_paths.cmake @@ -6,6 +6,8 @@ set(ACECODE_WINPTY_AGENT_LOCATION_SOURCE "${CMAKE_SOURCE_DIR}/src/base/pty/winpt set(ACECODE_DEEPIN_WINDOW_EFFECTS_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/deepin_window_effects.cpp") set(ACECODE_DESKTOP_MAIN_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/main.cpp" "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_cookie_bridge.cpp" + "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_state_json.cpp" + "${CMAKE_SOURCE_DIR}/src/apps/desktop/page_annotation_bridge.cpp" "${CMAKE_SOURCE_DIR}/src/apps/desktop/open_in_explorer_bridge.cpp") set(ACECODE_MACOS_CLI_LAUNCHER_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/macos_cli_launcher.cpp") set(ACECODE_DESKTOP_SPLASH_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/splash_screen.cpp") @@ -15,9 +17,13 @@ set(ACECODE_DESKTOP_PET_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/desktop_pet set(ACECODE_DESKTOP_PET_MAC_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/desktop_pet_mac.mm") set(ACECODE_DESKTOP_LINUX_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/linux_desktop.cpp") set(ACECODE_AGENT_BROWSER_HOST_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_host.cpp" + "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_capture_cdp.cpp" + "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_capture_layout.cpp" + "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_native_commands_win.cpp" "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_windows_helpers.cpp" "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_host_common.cpp") set(ACECODE_AGENT_BROWSER_HOST_MAC_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_host_mac.mm" + "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_capture_mac.mm" "${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_macos_helpers.mm") set(ACECODE_IOS_SIMULATOR_VIEW_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/ios_simulator_view.cpp") set(ACECODE_IOS_SIMULATOR_VIEW_MAC_SOURCE "${CMAKE_SOURCE_DIR}/src/apps/desktop/ios_simulator_view_mac.mm") diff --git a/docs/agent-browser.md b/docs/agent-browser.md index 810f0b629..0a9148161 100644 --- a/docs/agent-browser.md +++ b/docs/agent-browser.md @@ -103,6 +103,41 @@ CSS 缩放或 Browser 面板宽高影响,返回同样的图片附件与文件 像素、总计最多 32 兆像素、PNG 最多 16 MiB。无效、未就绪或不可见的画板会报错, 不会改用页面截图。 +### Explicit full-page capture + +`browser_screenshot(full_page: true)` uses the existing screenshot/attachment path. +At the authenticated native proxy boundary, send `Page.captureScreenshot` with +`{"fullPage":true}` (the existing `captureBeyondViewport:true` spelling is also +supported). Omitted/false flags retain the existing viewport behavior. Conflicting +flags, a crop/quality override, or a non-PNG full-page request are rejected rather +than silently downgraded. This adds no webpage messaging or conversation capability. + +Windows uses CDP document CSS bounds and an explicit beyond-viewport clip, normalized +to one PNG pixel per CSS pixel without changing device emulation or viewport size. +macOS uses WebKit's full-document PDF capture boundary and rasterizes its single +complete page in memory, without resizing the view or scrolling/stitching viewport +snapshots. The original viewport snapshot path remains unchanged. WebKit PDF rendering +is not a promise to capture protected media or every accelerated/video surface. + +Full-page success returns one base64 PNG, `fullPage:true`, `captureBeyondViewport:true`, +`width`, `height`, and an opaque `documentId`. Callers may supply that returned +`documentId` to reject a later capture of a replaced document; it is a capture-backend +token, not an annotation-runtime document identifier. The selected native page/view, +navigation, sharing permission, document identity and full bounds are checked across +capture. Changed documents/layouts fail instead of returning an image of another page. +The dimensions and PNG chunk integrity are checked before publishing success. + +Limits are 32768 pixels per side, 32 Mi pixels total and 32 MiB encoded PNG (before +base64). Invalid bounds, resource exhaustion, missing/incomplete native output, +navigation/close, timeout or shutdown fail; no clipped/viewport substitute is returned. +Capture-operation errors carry `ok:false`, `recoverable:true`, `page_id`, and a +`capture_*` error (for example `capture_resource_limit`, `capture_document_changed`, +`capture_incomplete_image`, `capture_native_failed`, or `capture_timeout`). Existing +proxy authentication/page-resolution errors keep their existing response contract. +Keep the pending batch on failure and retry explicitly. Real Windows/macOS long-page +pixel acceptance remains a separate required check; automated contract tests alone +do not establish native rendering fidelity. + macOS 的交互工具(click/fill/type/press/hover/drag/scroll)额外暴露 `input_mode: "synthetic" | "native"`,由 Agent 按页面需要显式选择: @@ -269,8 +304,8 @@ Agent 浏览器」都能切换三档,默认**共享**: - 只在 macOS 14+ 激活;更低系统版本、Linux 或没有完整 Desktop bridge 时前端不会把它 视为可用 backend。 -- `browser_screenshot` 使用 `takeSnapshotWithConfiguration`,当前返回可见 viewport 的 - PNG,不承诺 CDP `captureBeyondViewport` 的整页语义。 +- `browser_screenshot` 默认使用 `takeSnapshotWithConfiguration` 返回可见 viewport; + 显式整页请求使用上述 PDF 捕获/PNG 栅格化边界,失败时不降级为 viewport。 - 页面理解和 synthetic 输入依赖 DOM,可访问当前文档和同源 frame;跨源 iframe、浏览器 原生弹层以及站点封闭的实现细节不保证可操作。遇到 trusted-event 检查可显式改用 `native`,但 native 仍不能绕过网页权限、系统安全提示或不可见页面约束。 @@ -347,6 +382,159 @@ ctest --test-dir build -C Release --output-on-failure 原生空白 WebView、导航失败不闪出 WebView2 错误文档、重试可恢复,以及模拟 OOM/ renderer failure 时显示对应 ACECode 状态并隐藏 controller。 +## 网页描述批注(#194) + +已加载网页的地址栏提供仅图标的批注入口。开启后点击一个元素,再点选框旁的 Annotate +按钮,在覆盖原生浏览器的宿主浮窗中填写描述并保存。关闭浮窗取消当前草稿;退出模式 +隐藏选框和控制按钮,但保留已保存的编号图钉。底部显示待发送数量。保存记录不可编辑或 +删除,编号持续递增;没有会话也可保存。此步骤只在当前 Desktop 运行期保留数据, +不会发送消息、写 HTML/CSS 文件或持久化记录。源码元素引用仍使用原有“将元素添加到聊天” +入口,两种模式不共用事件或草稿。 + +### 实现与扩展接口 + +- `src/apps/desktop/page_annotation_bridge.{hpp,cpp}` 注册唯一的可信入口 + `aceDesktop_agentBrowserAnnotationCommand({page_id, command})`。安装返回的生命周期 + token 在 browser 析构前撤销。网页没有该 bridge。 +- `AgentBrowserHost::annotation_command` 只接受 `start/read/exit/cancel/save`,由 + `PageAnnotationSession::prepare/complete/fail` 串行处理。命令必须带 `document_id`, + 首次 start 可传空字符串;save 还必须带当前 `target_id` 与有界 `description`。 + 未知动作/字段、旧文档、旧回调和不匹配的目标被拒绝。 +- `src/apps/desktop/page_annotation_runtime.hpp` 由宿主执行,Windows 使用主框架的 + CDP isolated world,macOS 使用 `WKContentWorld`。运行时保存精确 DOM 引用及 + document 身份,仅返回选框/浮窗意图、目标摘要和视口;描述不会注入网页。 + 闭合 shadow root 只有选框、控制按钮及图钉,没有第二套描述编辑器或消息通道。 +- `PageAnnotationSession::snapshot()` 返回 `document_id/active/popup/target/viewport/records/ + pending_count/revision`;记录包含稳定 `id/number/page_id/document_id`、`description`、 + `targets`、`differences`、`region`、`status`、`valid`。描述批注的真实属性差异为 + 空数组、region 为 null、status 为 pending。返回值是快照,不授予修改已保存记录的能力。 + 文档替换使旧记录失效,不按 locator 重新匹配。 +- `web/src/lib/pageAnnotations.js` 的 `createPageAnnotationController` 串行调用可信 + bridge,绑定入队时的文档/目标身份,丢弃旧 revision 和卸载后的结果。 + `web/src/components/PageAnnotations.jsx` 的 `PageAnnotationPopup` 使用现有 + `data-ace-native-overlay="overlap"` 局部遮挡协议,在 Windows window region / macOS + layer mask 与 hit-test 路径上露出可信表单,不是聊天栏替代。遮挡孔按浮窗圆角挖出, + 但被 Browser 边界裁掉的那一侧角落必须保持直角(`occlusion_rects[].square_corners`): + 给裁切边补圆角会在浮窗与网页交界处画出一段四分之一圆的接缝。选择状态通过宿主发起的 + read 读取,不接受网页主动发来的特权请求。 + +遮挡孔按浮窗自己的像素网格对齐:`CreateRoundRectRgn` 这类 native region 只能到整设备 +像素,用 `Math.round` 取整会把浮窗边缘那一条(正好带 1px 外框线)整条丢掉,表现为右下 +两边没有框线。所以孔的近边(左/上)取包住浮窗的像素,远边(右/下)再多留 1 个设备像素 +(`HOLE_FAR_EDGE_GUARD`)。孔不再向外扩宽:多出来的每一像素都会把 WebUI 的底色漏在浮窗 +外面,网页不是白底时就是一圈发白的锯齿。只有 `role="menu" | "listbox" | "tooltip"` 这类 +隐式浮窗还保留 1px(`NATIVE_SURFACE_IMPLICIT_OVERLAY_BLEED`)给自己的投影;注解卡片不自 +己外扩,靠对齐已经足够。需要显式控制的浮窗可写 `data-ace-native-overlay-bleed`,`"0"` +表示完全对齐 border box。 + +代价要说清楚:window region 是 1 bit 的,浮窗圆角在网页上永远是一条 1 设备像素的硬边, +做不到 CSS 那样的抗锯齿。要真正消除这条硬边,只能换掉"原生 WebView 挖洞"这套结构 +(例如 per-pixel alpha 的合成层),不属于本次范围。 + +后续样式、文本、多目标/区域功能分别扩展上述运行时、原生草稿模型及可信浮窗,不要改走 +`selected_element`(它仍会创建聊天上下文)。截图、批量发送及完整导航确认由其他票负责; +#194 未改动 `capture_screenshot`。 + +### #194 验证范围 + +自动化覆盖实际嵌入的 JavaScript 运行时选择/打开/取消/保存/退出、synthetic 输入拒绝、 +DOM 原样保留、精确目标失效、文档重新绑定、宿主命令序列、迟到结果、不可变记录和编号, +以及原有源码选择回归。验证命令为 `node web/src/lib/pageAnnotations.test.js`、 +`pnpm --dir web test`、`pnpm --dir web build` 和原生 +`PageAnnotationSessionTest.*`。Windows 还单独编译了 host、main 和 annotation bridge +翻译单元;这不等于完整 Desktop 链接或运行验收。 + +2026-11-18 在 #194 独立工作树的结果:运行时/控制器定向测试通过,原生模型 6/6 +通过,完整 `pnpm test`、`pnpm build`(含 regex compatibility 检查)通过,三个 +Windows 翻译单元编译通过,`openspec validate add-html-page-annotations --strict` +和 `git diff --check` 通过。Web build 仍有大 chunk 提示;未因此更改无关打包策略。 + +**尚未执行:** Windows 真正 Desktop 中的浮窗重叠、点击穿透/焦点、缩放/DPR、切页和 +进程故障交互;macOS 编译及同类真实交互;完整原生 CMake/ctest。两个平台的完整工作流 +验收仍待 #201,不能用 Node 的模拟 DOM 或单文件编译代替。 + +### #195 样式扩展与验证范围 + +样式入口仍为可信浮窗,不复用源码选择。`page_annotation_style_runtime.hpp` 的 +`kPageAnnotationStyleRuntime` 通过运行时第三参数注入,第二参数留给文本 helper。 +接口为 `select/preview/describe/differences/save/cancel/setOriginal/dispose`; +`preview(target,id,styles,ratioLock?)` 接受 CSS 属性和值,`save()` 返回真实差异数组。 +每个目标分别保留已保存声明、当前草稿、计算值基线和默认关闭的当前比例锁。 +多目标接入时应保留各目标草稿,不沿用单目标选择入口的全局 cancel。 + +可信命令新增 `preview_style {target_id,styles,ratio_lock?}`、`original {enabled}`。 +快照新增 `original/differences`,目标的 `style_preview` 包含 +`values/styles/ratio_locked/ratio/errors`。控制器在入队时绑定目标和文档,浮窗保存前 +刷新尚未失焦的编辑;失败保留输入以便重试。样式差异使用展开后的 CSS 属性与实际 +计算值,原始输入的等价写法不形成差异。边框原为 none 时,宽度编辑派生 solid, +该真实变化也进入差异。没有 HTML/CSS 磁盘写入或页面可访问的会话 bridge。 + +样式层采用各 Document/ShadowRoot 的独立 constructed stylesheet,不改原行内声明; +取消仅撤当前草稿,模式退出保留已保存层。原始页面比较临时停用两层,保留图钉; +恢复时草稿与已保存预览重现。原页面长过渡在取消/比较时即时结算后恢复原声明。 + +**已批准的层叠行为:** 按 Codex 处理。预览写在未分层的作者样式表里,声明带 +`!important`,不改原内联样式。内联 `!important` 或更具体的分层作者 `!important` +胜出时,不报错、不记录未生效差异、不上用户层扩展;`style_preview.errors` 保持空数组。 +任务 2.1 仍未完成:这不是任意页面的完整层叠覆盖,Windows / macOS 桌面人工验收也未完成。 + +**批注卡片与工具栏:** 外观对齐 Codex 桌面控件,不拷贝其源码。开启批注后,悬停页面 +元素会显示外框和包含标签、渲染尺寸、颜色、字体的信息卡;单击元素会立即打开批注卡片。 +卡片收起 294px、打开最多 380px。左上 `调整` 使用 `aria-expanded`,没有 `aria-pressed`。 +卡片头部和底部操作区固定,属性编辑区最多滚动 230px;卡片内不再重复目标元素标签。 +属性标签按文字内容左对齐,数值与单位分开,字体和字重提供下拉选择,已修改值提供恢复 +按钮,任何有效修改都会实时预览。不透明度使用 `0..100%` 输入并夹取越界值。宽高及 +上下/左右内、外边距的锁定按钮显示在上下两条 T 形连线之间;按钮有默认、悬停和锁定 +状态,同组锁定会同步各自的成对值。折叠的内边距、外边距保留四个可编辑值。 +属性值列保持 176px 宽,两个间隙值的 `px` 在未编辑与编辑后都留在输入框内;四联 +内、外边距的每个输入框至少保留 45px,可用宽度不足时自动换行。比例锁使用清晰居中的 +链形图标,并以加粗中段区分锁定状态。 + +工具栏是深色圆角条:可拖动握把、`正在批注 · {count}`、截图并复制、隐藏标记、按住 +查看原页面、丢弃全部、蓝色 `发送`、退出。计数列宽度固定。丢弃前询问 +`丢弃所有待处理标注?`,正文为 `页面上的所有编辑都将被移除` 和 +`放弃后所有标记和修改都被清空`,操作为 `取消` / `放弃。`。卡片或选区模式打开时 +工具栏隐藏,退出批注后也不保留孤立发送按钮。点击卡片外会取消当前草稿但保留批注模式。 +`调整` 和提交按钮都有气泡说明,提交气泡同时显示 `Enter 发送 · Ctrl+Enter`。 + +送给模型的正文仍是 `Page annotations` 加结构化 JSON,并附整页截图。会话里不铺开 +JSON:只显示卡片,顶部是整页图裁切,下面是页面标题和有内容的描述;多条才显示编号。 +地址栏按钮固定 30×30,开启后不追加“批注”文字,避免工具栏宽度变化。 + +新增验证:`pnpm --dir web test:annotations:browser` 启动独立临时 headless Chromium +profile,覆盖全部属性、简写展开、真实差异、比例锁、同目标保存/取消、原始比较、 +过渡、克隆清理、ShadowRoot、trusted 鼠标输入与实际隔离运行时。可通过 +`ACECODE_TEST_BROWSER` 指定 Chromium 可执行文件。浮窗 JSX 行为由 +`node web/src/lib/pageAnnotationPopup.test.js` 覆盖,原生模型测试为 +`PageAnnotationSessionTest.*`。新增测试不使用共享原生 build 输出目录。 + +2026-11-19 在 #195 独立工作树:原生模型 10/10、运行时/控制器、浮窗 JSX 4 项、 +真实 Chromium 样式/隔离运行时测试通过;完整 `pnpm --dir web test` 最终通过。 +较早完整测试曾出现测试结束后的异步断言失败,未修改无关基线测试;带诊断监听的 +完整重跑及最终 pnpm 重跑均通过。`pnpm --dir web build`(含 regex compatibility)、 +`openspec validate add-html-page-annotations --strict` 与 `git diff --check` 通过。 +构建仍有既有大 chunk 提示。原生测试直接编译到系统临时目录,只读借用已安装依赖, +未触及集成工作树、原始工作树或共享原生 build 的输出。 + +未执行真实 Windows/macOS Desktop 浮窗、焦点、遮挡和全部属性交互验收,未执行 +macOS 编译、完整原生链接或 CTest;这些检查不能由 headless CSS 测试代替。 + +2026-11-19 交互对齐收尾:重新生成 i18n source catalog 后,完整 +`pnpm --dir web test`、`pnpm --dir web build`(含 regex compatibility)、 +`openspec validate add-html-page-annotations --strict` 与 `git diff --check` +通过。真实 Chrome headless 生命周期 smoke 报告 +`PASS: exact DOM/shadow identity, queued removal, multi-target previews, regions +and root replacement`;重新链接独立 native driver 后,dedicated annotation +integration 全部通过,覆盖 trusted 输入、目标/区域保存、HTTP 序列化、队列回执、 +租约释放、拒绝后重试和最终 DOM 差异。Windows 开发桌面人工检查确认 hover +外框与信息卡、单击开卡、卡片外取消、固定头尾、230px 滚动属性区、折叠四值、 +展开锁定控件、工具栏隐藏和圆角卡片。完整 Windows 工作流与 macOS +原生/人工验收仍未完成。 + +2026-11-20 样式编辑现场复核:开发桌面中的两个间隙值在 `0px` 与编辑后出现恢复按钮的 +两种状态下均完整显示单位;宽高比例锁在解锁与锁定状态的图标均居中可辨。浮窗 JSX +回归测试同时约束恢复区的默认/编辑态布局。 + ## 常见故障 - “Open ACECode Desktop”:工具运行在 daemon,但没有兼容的 Windows Desktop 或 diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.md new file mode 100644 index 000000000..afab22458 --- /dev/null +++ b/docs/agents/issue-tracker.md @@ -0,0 +1,26 @@ +# Issue tracker: GitHub + +Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations. + +## Conventions + +- **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies. +- **Read an issue**: `gh issue view --comments`, filtering comments by `jq` and also fetching labels. +- **List issues**: `gh issue list --state open --json number,title,body,labels,comments` +- **Comment on an issue**: `gh issue comment --body "..."` +- **Apply / remove labels**: `gh issue edit --add-label "..."` / `--remove-label "..."` +- **Close**: `gh issue close --comment "..."` + +Infer the repo from `git remote -v`; `gh` does this automatically when run inside a clone. + +## Pull requests as a triage surface + +**PRs as a request surface: no.** + +## When a skill says "publish to the issue tracker" + +Create a GitHub issue. + +## When a skill says "fetch the relevant ticket" + +Run `gh issue view --comments`. diff --git a/docs/daemon-api.md b/docs/daemon-api.md index 00b10f2a7..a14f725a1 100644 --- a/docs/daemon-api.md +++ b/docs/daemon-api.md @@ -1850,6 +1850,118 @@ whether a paste stayed inline or became a file. Expansion is also skipped when the first non-empty composer piece is an inline pasted block. Returns `202 {"queued":true}`. +#### Annotation batch receipt + +Trusted annotation senders may opt into receiver idempotency by adding +`annotation_batch_id` (`[A-Za-z0-9_-]{1,128}`) to this ordinary messages endpoint: + +```json +{ + "annotation_batch_id": "annotation-batch-uuid", + "text": "Numbered targets, descriptions and old/new differences", + "attachments": [{"id": "att-prepared-full-page-image"}], + "client_message_id": "optional-client-message-id" +} +``` + +Only these four fields are allowed for a batch. Non-empty `text` is required; +the sender prepares and freezes the attachment before submitting. Batch IDs +are rejected on steer, interrupt and question-interjection paths. Ordinary +messages without `annotation_batch_id`, including source selections and +`client_message_id` reconciliation, retain their existing behavior. + +First acceptance returns `202` with +`{"queued":true,"annotation_batch_id":"annotation-batch-uuid","duplicate":false}`. +An identical retry returns the same accepted ID and `duplicate:true`, with no +additional user turn or auto-title request. The sender must match the returned +ID to its frozen batch before acknowledging it. This acknowledges queue +admission, not model completion or a durable transcript write. + +Identity is scoped to the receiving session's live AgentLoop. The receiver hashes +the complete parsed JSON request using SHA-256 (object key order and whitespace +do not matter; array order, field omission and all values do). Reuse the exact +original payload and attachment references on retry; changed payload under an +accepted ID returns `409 {"error":"annotation_batch_conflict"}`. Checking the ID, +remembering its fingerprint and enqueueing the ordinary Chat task share the +existing queue admission lock, including concurrent requests and busy turns. +Failed admission does not remember an ID. The fingerprint is computed before +prompt expansion, so retry comparison does not depend on changing workspace +context. Existing authentication, migration, attachment and mesh checks remain +in force before acceptance. + +Each live receiver retains at most 1024 accepted batch fingerprints, including +completed turns. Records are never evicted to make room for new batches: +`503 {"error":"annotation_batch_capacity"}` rejects a new ID at the limit while +known identical retries still succeed. Other admission failures return +`503 {"error":"annotation_batch_unavailable"}` without a success receipt; +normal parse/security errors retain their existing status. Receipt state is +runtime-only and is lost when the receiving session is destroyed or the daemon +restarts; there is no restart-recovery guarantee. Do not retry an uncertain +batch against a recreated receiver as though its earlier receipt survived. + +For an uncertain HTTP outcome, query only the existing receipt using +`POST /api/sessions/:id/messages?annotation_reconcile_only=1`. The query accepts +only literal `1`, and requires a valid annotation batch identity and payload as +defined above; other values, an ordinary non-batch body or malformed batch return +`400` (invalid query usage reports `invalid annotation_reconcile_only`). Send the +same frozen batch ID and exact original payload, including attachment references +and optional client identity. The query is transport metadata, not part of the +payload fingerprint. It is parsed before request side effects; existing +authentication, migration, attachment, mesh and receiver-lifetime checks still apply. + +This mode never admits a new task or consumes an unknown ID, even at receipt +capacity. Within the existing queue admission lock: + +- A known ID with the same fingerprint returns `202` with + `{"queued":true,"annotation_batch_id":"annotation-batch-uuid","duplicate":true}`. +- An unknown ID returns `404 {"error":"annotation_batch_not_accepted"}` without + a receipt ID, enqueueing work or remembering that identity. +- A known ID with a changed fingerprint returns + `409 {"error":"annotation_batch_conflict"}`. +- An unavailable receiver returns `503 {"error":"annotation_batch_unavailable"}`; + normal parse/security errors retain their existing status. + +Ordinary POST without this query remains an admission attempt, not a safe +receipt-only lookup. The sender first reconciles every uncertain attempt. A +matching accepted receipt may be acknowledged even if the old target is now +invalid. Only an exact `404` with `annotation_batch_not_accepted` permits native +document/target revalidation followed, if valid, by a possible first ordinary +admission. Ambiguous lookup errors, malformed receipts and mismatched receipt IDs +must not authorize admission. Explicit original refusals +(`annotation_batch_unavailable`, `annotation_batch_capacity`, +`annotation_batch_conflict`) clear sender uncertainty and require native +revalidation before another ordinary attempt. All retries keep the frozen session, +connection, batch ID and payload; none recapture or reupload. + +The desktop annotation sender freezes the initiating conversation, daemon connection, +sendable saved record IDs and serialized message before submission. It captures one +full-page PNG through the trusted native annotation command and uploads it with +`POST /api/sessions/:id/attachments`; the message references the returned attachment +ID, never a screenshot path. Description-only and differences-only records are +sendable; empty records are excluded. New annotations belong to the next batch. +The sender does not read, clear or replace composer text/attachments, and uses this +ordinary messages endpoint even while the conversation is busy, never steer. + +Trusted desktop annotation commands `capture` and `validate` accept only +`{action, document_id, record_ids}`. Native-owned records bind that membership to +the current annotation document. The native host verifies the isolated runtime's +exact document and saved target references before and after full-page capture, +alongside capture's existing page/view/navigation/bounds guards. The successful +response includes `annotation_document_id` and the independent capture +`result.documentId`; these tokens are not equal or interchangeable. This trusted +user capture does not require sharing the page with the agent; automation proxy +sharing/security gates remain unchanged. A final native validation before the first +HTTP attempt rejects target removal or document replacement during upload. + +Capture/upload/validation failures preserve pending records. Once an HTTP attempt +has occurred, uncertain retries keep the original session, exact payload, batch ID +and attachment reference without recapture/reupload; switching conversations does +not redirect them. A matching `queued:true` receipt alone authorizes trusted native +`acknowledge` for the frozen record IDs. An acknowledgement failure retries only that +step, not submission. Accepted records retain their pins, previews and numbers; +concurrent additions remain pending. Failed/in-flight batches survive panel remounts +in memory, bounded by the owning browser page lifetime, not application restart. + ### `POST /api/sessions/:id/turn/steer` Appends structured user input to the currently running regular agent turn. diff --git a/docs/desktop-shell/html-page-annotations-acceptance.md b/docs/desktop-shell/html-page-annotations-acceptance.md new file mode 100644 index 000000000..f6b05a075 --- /dev/null +++ b/docs/desktop-shell/html-page-annotations-acceptance.md @@ -0,0 +1,103 @@ +# HTML page annotation acceptance + +Specification: [#193](https://github.com/tmoonlight/acecode/issues/193). Implementation tickets: #194–201. OpenSpec: `add-html-page-annotations`. Integration baseline: `0155a863`. + +Superseded: the 2026-11-22 session-record redesign ([#207–#220](https://github.com/tmoonlight/acecode/issues/210), OpenSpec `redesign-html-page-annotations`) replaced the batch sender, native send leases and their test driver with pending session records sent through the composer. Rows below that still describe batch semantics are historical evidence for the previous design; the workflow checklist has been updated where the redesign changed a step. + +This is the execution checklist, not a claim that the feature is complete. Keep the pull request draft until both platform workflows and required automated checks have passed. Reference-app screenshots and source inspection do not qualify as ACECode acceptance. + +## Automated checks + +| Check | Result | +| --- | --- | +| OpenSpec strict validation | Passed at 39cd01db, 2026-11-19; documentation follow-up revalidated separately below | +| Annotation interaction through conversation submission | Fresh directly compiled native driver and dedicated Chromium integration passed at 39cd01db; injected capture/HTTP boundaries remain distinct from a complete manual desktop workflow | +| All property previews, text-node identity and saved/draft layering | Dedicated integration passed at 39cd01db, including actual-DOM differences and exact restoration; earlier F2 red retained below; original inline important cascade limitation remains open | +| Batch freeze, queue, receipt, receiver deduplication and failures | Dedicated integration and focused native tests passed at 39cd01db, including new linked HTTP and MessagePayload tests; earlier F1 and Linux CI red retained below | +| Navigation, removed target, document ownership and untrusted commands | Edge lifecycle, dedicated integration and focused native tests passed at 39cd01db; automated identity/lifetime coverage, not full manual navigation acceptance | +| Source-selection annotation regressions | Full frontend suite, dedicated source/composer seam and focused native run passed at 39cd01db | +| Full frontend test suite and production build | Complete pnpm test, pnpm build and regex compatibility passed at 39cd01db | +| Windows native build and focused tests | Coordinator rebuilt desktop/unit/smoke targets and verified dependencies at fixed clean 39cd01db; focused native and CTest each passed 107/107. Real visible integrated smoke and ownership passed, including below-viewport pixel/layout/state probes; complete manual workflow remains open | +| macOS native build and focused tests | Not executed; macOS environment required | +| Standards and specification code review | Final dual-axis review pinned to 39cd01db reports no open code findings; layers/size/ownership/OpenSpec/diff passed. Documentation-path prose failure corrected without baseline exemption in the documentation follow-up | + +## High-seam automated regression (#201, retired) + +The batch sender, native navigation leases and the test-only native integration +driver documented here were removed by the 2026-11-22 session-record redesign; +`pnpm test:annotations:integration` no longer exists. The seams that driver +covered now live in the ordinary suites: + +- `annotationOutbox.test.js` and `annotationSubmission.test.js` cover submission + assembly, retry and the settle/timeout self-check. +- `pageAnnotationMessage.test.js` covers the multi-page sent payload. +- `pageAnnotations.test.js`, `pageAnnotationPopup.test.js` and + `pageAnnotationPollRetryArchitecture.test.js` cover the popup, the + Enter/Shift+Enter/Ctrl+Enter semantics and poll retry. +- `tests/desktop/page_annotation_session_test.cpp` and + `tests/desktop/session_annotation_store_test.cpp` cover the session store, + orphan retention and removal. + +The execution records below are retained as-is; they describe the superseded +design and are not acceptance for the redesign. + +## Real desktop workflow + +Run the following independently on Windows and macOS against the integrated build. Record build commit, OS, commands, observations and evidence paths. Use an already-loaded local-service page and a remote page, with nested text elements and a long page containing recognizable content below the viewport. A runtime test or successful native API return is not sufficient proof of screenshot pixels. + +The local fixture is `tests/desktop/helpers/html_annotation_fixture.html`. Serve that directory over HTTP and open the page in ACECode Agent Browser, not standalone file preview. Its orange middle and green `FULL-PAGE-CAPTURE-END` section distinguish full-page pixels from a viewport capture. `window.annotationFixture.childIdentityPreserved()` checks the original nested element identity; the counter button checks retained listener behavior. The two identical lifecycle paragraphs test that removing the original never relocates an annotation to its sibling. Record a fixture file hash before and after previewing to check that no source file was written. + +| Step | Windows | macOS | +| --- | --- | --- | +| Toolbar enables mode; element click outlines; control opens trusted popup above browser | Not executed | Not executed | +| Text editing preserves nested child elements and their event behavior | Not executed | Not executed | +| Text color, background, opacity, font, font size and weight preview | Not executed | Not executed | +| Radius, border color and width, width, height, spacing, padding and margin preview | Not executed | Not executed | +| Ratio lock starts off and captures current ratio when enabled | Not executed | Not executed | +| Unchanged values produce no differences; cancel preserves previous saved preview on same element | Not executed | Not executed | +| Multiple elements and one replaceable region share description and pin; region has no property editing | Not executed | Not executed | +| Save produces pin/count but no model work and no HTML/CSS file writes | Not executed | Not executed | +| Original comparison keeps pins; restoring previews and leaving mode retain saved work | Not executed | Not executed | +| Sending from the composer along with pending records yields one message with exactly one full-page image containing below-viewport pixels | Not executed | Not executed | +| Busy model receives queued new turn, not steering; composer draft and attachments remain | Not executed | Not executed | +| Session switching cannot retarget a submission already assembled; records added during the send stay pending | Not executed | Not executed | +| Accepted submission removes only the sent records, keeps the page shot, and subsequent numbers do not reuse a removed id | Not executed | Not executed | +| Capture or upload failure sends nothing and leaves the record editable; an uncertain response settles under the same client message id without duplicate work | Not executed | Not executed | +| Navigation/refresh defaults to staying; replacement/removal invalidates without relocation | Not executed | Not executed | +| No usable conversation permits annotation but blocks sending without creating a conversation | Not executed | Not executed | +| Existing source-selection annotation workflow remains functional | Not executed | Not executed | + +## Recording failures + +Keep failed and unavailable checks explicit. Do not mark a task complete because a platform implementation exists or because another platform passed. Invalid saved annotation records cannot be repaired by introducing an unapproved edit/delete UI. Capture resource limits must report failure rather than silently truncate. Runtime retention does not imply restart recovery. + +## Execution record + +- 2026-11-19, documentation-only follow-up to 39cd: strict documentation-path validation passed with zero findings (TEMP `acecode-annotations-final-docsonly-docpaths.json`), `openspec validate add-html-page-annotations --strict` passed, and `git diff --check` passed. No product source, test implementation or baseline exemption changed; no product build or test suite was rerun by the merger. + +- 2026-11-19, final coordinator verification at fixed clean start/end HEAD `39cd01dbbd97d1d7bd8ee4dc288020e835287821`: native script session 37596 passed configuration, desktop/unit/smoke target builds and dependency validation. Fresh linked focused native tests passed 107/107, including the new HTTP receipt and MessagePayload regressions; CTest passed 107/107. Real visible integrated smoke emitted `SMOKE_OK` and `SMOKE_OWNERSHIP_OK`; the coordinator confirms the capture probe exercised bottom-green pixels, layout/style/viewport/scroll preservation, stale/resource rejection and retry. TEMP evidence: `acecode-annotations-current-native-{configure,build,deps,focused,smoke}.log` and `acecode-annotations-current-ctest.log`. This validates Windows native capture task 5.1, not the all-fields/manual desktop workflow or macOS. +- 2026-11-19, same `39cd01db` coordinator verification: complete `pnpm test`, `pnpm build` and regex compatibility passed; the native integration driver was directly recompiled and the dedicated Chromium integration plus Edge lifecycle suite passed. TEMP `acecode-annotations-current-{web-test,web-build,driver-build,integration,lifecycle}.log`. Layers, size, ownership, OpenSpec strict and diff checks passed; final Standards/Spec review pinned to this HEAD reports no open code findings. Automated integration 8.1 and dual review 8.2 are complete on this evidence, not the whole feature. Documentation-path validation alone failed on path-like prose; the documentation-only follow-up replaces it with natural language without adding a baseline exemption and reruns strict documentation paths, OpenSpec and diff checks. Product tests and builds are evidence for 39cd, not newly executed on the documentation-only commit. +- Historical failures remain recorded: Linux CI `44369114282` had one failing receipt test among 7,058 tests; a fresh Linux CI rerun is not established by the passing Windows linked regression. The earlier 11-failure native full-suite run was not repeated by these focused runs. Earlier F1/F2, readiness failures, stale-dependency builds and the hidden-launch harness failure below are not erased or reclassified as passes. Task 2.1 cascade, 5.2 macOS capture, and 8.3/8.4 complete Windows/macOS manual workflows remain open; the pull request remains draft. + +- 2026-11-19, coordinator reliable integrated verification, fixed start/end HEAD `4b0c00c4d1dca96372ddd4bcc2db1458f84c6d2c`: full native rebuild session 50005 passed after correcting the generated compiler dependency prefix; representative `routes_ws` dependency count was 747 (VALID). Focused native tests passed 90/90 in TEMP `acecode-annotations-reliable-native-focused.log`; CTest passed 90/90 in TEMP `acecode-annotations-reliable-ctest.log`. Real integrated visible-window smoke emitted `SMOKE_OK` and `SMOKE_OWNERSHIP_OK` in TEMP `acecode-annotations-reliable-native-smoke-visible.log`. The initial `Start-Process Hidden` attempt failed the active-visible-window check because of the hidden-launch harness; retain that failed attempt rather than representing it as a passing smoke. These results apply only to 4b0, not the later S2/S3/S4 or CI-test changes, and do not complete all-fields/manual Windows, macOS or cascade acceptance. Earlier failed and unreliable incremental observations remain historical records below. +- 2026-11-19, integration follow-up: S4 `5752ff65`, lifecycle S2/S3 `67a0a021`, and CI assertion fix `d298130f` were cherry-picked without conflicts, preserving prior 测试和文档 and product behavior. S2/S3 worker evidence is isolated TEMP compilation and injected-boundary testing, not a reliable integrated build of the merged source. Linux CI run `44369114282` had one failing receipt test among 7,058 tests, not a successful CI run: internal execution-context user records were incorrectly counted as real admissions. The two-file test fix reuses protocol deserialization and `is_real_user_message`, seeds typed internal context on every platform, and retains exactly-one real input plus exact text/identity assertions. Worker extracted-loop/payload tests passed 12/12 (300/300 shuffled repetitions), receiver tests passed 11/11, duplicate/missing-metadata mutations still failed, and the changed HTTP test translation unit compiled independently. TEMP `acecode-annotation-ci-44369114282-fix-report.md` records the boundary: fresh linked full HTTP execution and Linux CI rerun remained pending at that checkpoint. No merged-HEAD frontend, driver or native rerun was claimed by that historical integration record; see the later 39cd verification above. + +- 2026-11-19, #201 lease follow-up verification on `4b0c00c4` plus test/docs changes: the dedicated integration suite and separate Node runs of `pageAnnotationBatches`, `pageAnnotations`, `pageAnnotationText`, `pageAnnotationPopup`, `api`, `dialogKeyboard` and `agentBrowser` passed. `pnpm build` passed, including regex compatibility, with the existing large-chunk advisory. Strict layers, file-size, ownership-final and doc-path checks returned zero findings; OpenSpec strict validation and `git diff --check` passed. Full `pnpm test` **failed**, and a diagnostic rerun also exited 1: `agentBrowser.test.js:40` expected readiness `true` but received `undefined`, reported as asynchronous activity after the five Node-runner tests ended. A TEMP-only `uncaughtExceptionMonitor` preload captured that stack; the same file subsequently passed standalone. The polling helper has a real-time deadline, but resource contention or baseline causation is not established by this evidence. No assertion was removed, skipped or weakened. Logs: TEMP `acecode-201-lease-web-test.log`, `acecode-201-lease-web-diagnostic.log`, `acecode-201-lease-agentBrowser.log`, `acecode-201-lease-web-build.log`, `acecode-201-lease-check_{layers,file_size,ownership,doc_paths}.{json,log}`. This checkpoint is not a passing full frontend gate, and no shared native graph was modified. +- 2026-11-19, #201 lease adapter follow-up based on integrated `4b0c00c4`: coordinator's TEMP `acecode-annotations-final-integration.log` caught a real test-adapter regression (`Annotation navigation is pending`): `release` incorrectly entered `prepare`, leaving the new #200 submission lease held. The test-only adapter now routes `release` through `submission`, observes production session lifecycle results after runtime validation, and releases the matching lease on validation failure as the real host does. The driver exposes `navigation.sending()` for assertions. Recompiled the standalone TEMP MSVC driver and passed the dedicated Chromium/native-driver suite, including held-then-released lease state, failed-validation cleanup, original F1 explicit/uncertain retry no-admission checks, exact HTTP payload, real busy queue and final-DOM diffs. TEMP `acecode-201-lease-driver-build.log`, `acecode-201-lease-integration.log`. No product or shared-build edits; this does not establish native host deadline/navigation behavior or platform capture pixels. +- 2026-11-19, coordinator native dependency diagnosis: 1,674 old object files had zero recorded dependencies. The `7aeb4e9f` incremental link referenced a stale three-parameter request-parser ABI despite the current four-parameter declaration/definition. Generated Ninja/CMake rules contained a mojibake MSVC showIncludes prefix; an independent minimal probe using the correct Chinese UTF-8 prefix recorded its local header dependency. Evidence: TEMP `acecode-annotation-ninja-deps-diagnosis.md`, `acecode-annotations-reviewfix-native-build.log` and `acecode-deps-probe/build.ninja`. Earlier incremental build exits and native test executions below remain historical observations of those binaries, not proof that all headers at the stated source HEAD were compiled. Reliable recompilation and representative nonzero project-header dependency inspection are pending coordinator work; no corrected integrated build is claimed here. #201's directly compiled TEMP driver does not use this shared Ninja graph and is not a substitute for that rebuild. +- 2026-11-19, #201 final test/docs checkpoint: strict `check_layers --layout final`, `check_file_size`, `check_ownership --final` and `check_doc_paths` all exited 0 with zero findings; TEMP `acecode-201-reconciled-check_{layers,file_size,ownership,doc_paths}.json`. `git diff --check` and `openspec validate add-html-page-annotations --strict` passed. No baseline exception, shared native build or platform acceptance was added. +- 2026-11-19, #201 verification against `7aeb4e9f` plus test/docs changes: full `pnpm test` exited 0 (TEMP `acecode-201-reconciled-web-test.log`); `pnpm build` exited 0 with the existing large-chunk advisory and regex-compatibility check passing (TEMP `acecode-201-reconciled-web-build.log`). Separate Node runs of `pageAnnotationBatches`, `pageAnnotationText`, `pageAnnotationPopup`, `api`, `dialogKeyboard`, `pageAnnotations` and `agentBrowserArchitecture` all passed (TEMP `acecode-201-reconciled-.log`). The final dedicated integration rerun also passed after correcting overly prescriptive parent/child expectations: the parent owns its changed prefix, not the unchanged descendant, so this fixture composes `Hi Earth!`. Assertions require both literal per-target old/new differences, independently compare every new value to final DOM, check original comparison and cancel, and retain exact restoration. This is test expectation calibration to the owned-node contract, not a product change or a waived DOM/diff mismatch. API and design documentation now describe the production reconciliation query and revalidation conditions. +- 2026-11-19, #201 rebased its clean branch to coordinator-provided `7aeb4e9f15c9dd2c37be5a32ff2077b8ee4b3ae9`, without replaying previously integrated patches. Rebuilt the TEMP-only MSVC integration driver against the real reconciliation parser/queue and updated the HTTP test adapter to honor `annotation_reconcile_only=1`. The complete dedicated real-Chromium/native-driver integration suite passed, including F1 explicit refusal, uncertain unknown-receipt lookup then invalid-target rejection, frozen exact payload/connection, F2 final DOM differences, exact original node/markup restoration, and previous source/composer/security seams. TEMP `acecode-201-browser-reconciled.log`, `acecode-201-native-driver-build.log`. An initial browser startup hit transient `EBUSY` reading `DevToolsActivePort`; the bounded readiness loop now retries only missing/locked/unfinished port files, with no assertion weakening. These tests still inject native capture/HTTP transport boundaries; #200 lifecycle and real native host callback deadlines remain outside this result. +- 2026-11-19, coordinator-provided integration evidence at `6f6b491c`: full `pnpm test` exited 0 after the three ownership-path assertion fixes were integrated; TEMP `acecode-annotations-pathfix-web-test.log`. The coordinator reports this head pushed to draft #202 with a new CI run in progress; no result for that run is claimed here. Product review-fixes and #200/#201 integration still require fresh frontend/native verification. The earlier `8f2e060e` macOS installer CI pass does not establish macOS native build or runtime acceptance. +- 2026-11-19, #201 additional high-seam red test at `1c627535` plus test-only work: a real API HTTP `503 annotation_batch_unavailable`, followed by replacing the annotated node with an identical clone, reproduces review finding F1. Native validation independently rejects the clone, but the old sender retry returns success and first-admits the invalid batch. TEMP `acecode-201-browser-f1.log`. This latest run stops at F1; the earlier separate run reached and reproduced F2 below. Neither failure is waived or changed to a skip, and both fixes remain assigned to the product review-fixer. +- 2026-11-19, coordinator final full-native result: exit 1, 7,119 tests in 999 suites, 1,283,696 ms; 7,088 passed, 20 skipped, 11 failed and one disabled. TEMP `acecode-annotations-native-full-suite.log`. Failures: `ComputerUsePointerOverlay.ShowsWithoutActivationOrInterceptingHitTests` (Shell_SystemDim hit), `TcpProbe.TimeoutOnUnreachableHost`, `HookRunner.BoundedOptionsStopAtStdoutLineLimit`, `DefaultSkillSeedRegistryTest.HerdrTitleHookKeepsExactTabAndTitleAndSkipsEmptyOrMissingEnvironment`, six `BashToolPowerShellEncodingTest` cases (`ReadsUtf8FileWithoutBomAsUtf8`, `RoundTripThroughWriteAllTextPreservesBytes`, `CapturedNativeOutputDecodesAsUtf8`, `SetContentWritesUtf8`, `ExitCodeIsPreserved`, `LeadingAttributedParamStillRuns`), and `WebServerHttp.TurnInterruptAbortsAndStartsPriorityReplacementTurn`. This used the `8f2e060e` compiled artifacts; sources changed during execution but were not relinked. Neither reproduced baseline failures nor causation by later product changes is established. The focused 58-test pass does not replace this failed broader run or the required final integrated rerun. +- 2026-11-19, coordinator-provided CMake harness evidence at `8f2e060e` (not independently rerun by #201): `ctest --test-dir build/windows-x64-desktop-release --output-on-failure -j4 -R '(PageAnnotation|AgentBrowserCapture|AgentBrowserNativeBoundaries|AnnotationSubmission|SelectionContextAnnotation|WebServerHttp.AnnotationBatch)'` passed all 58 tests in 9.08 seconds; TEMP `acecode-annotations-integrated-ctest.log`. This confirms discovery/execution through the integrated CMake harness, not native screenshot pixels or Windows/macOS manual acceptance. Rerun after all worker changes merge. +- 2026-11-19, coordinator-provided evidence at `8f2e060e` (not independently rerun by #201): MSVC incremental targets `acecode_unit_tests`, `acecode-desktop`, `agent_browser_host_smoke` exited 0; TEMP `acecode-annotations-native-integrated-build.log`. Filter `*Annotation*:*AgentBrowserCapture*:*AgentBrowserNativeBoundaries*` passed 58 tests in eight suites (1705 ms), including two actual `WebServerHttp` annotation receiver tests and seven source-selection tests; TEMP `acecode-annotations-integrated-native-tests.log`. Running the native smoke took 3.8 seconds and explicitly **failed** with `capture_document_changed`, without the former abort; TEMP `acecode-annotations-integrated-native-smoke.log`. This supersedes neither complete Windows manual acceptance nor the required all-worker integrated rerun. Coordinator also reports strict layer/file-size/ownership-final/doc-path/OpenSpec checks and all 104 refactor Python tests passed at this base; those reports are baseline evidence, not #200/#201 acceptance. +- 2026-11-19, #201 worker based on `8f2e060e`: own-worktree `pnpm test` passed (including the native extraction ownership-path fixes, source-selection and composer callback regressions); `pnpm build` and regex compatibility passed. Non-fatal Node local-storage and large-chunk warnings remain. Test-only native integration driver compiled with x64 MSVC 14.44, using the existing `x64-windows-static/include` dependency prefix read-only and TEMP outputs; no shared native build was used. `pnpm test:annotations:integration` passed the existing real CSS browser cases and the new interaction/save, frozen batch/API/queue/receipt, and ownership/stale-callback seams, then **failed** its overlapping text assertion: child diff `Earth` versus actual DOM `world` (review finding F2, separately assigned for product correction). Evidence: TEMP `acecode-201-{web-test,web-build,native-driver-build,browser}.log`. This is a recorded regression, not a passing integration result; #200 and the product seam fixes require a fresh integrated rerun. No platform manual row is changed. +- 2026-11-18, Windows, edd093ae: `pnpm install --frozen-lockfile`, `pnpm test` and `pnpm build` completed successfully in the integration worktree. The test log contains 3,672 `[pass]` lines plus the Node test-runner summary. Non-fatal warnings: Node local-storage file setting and existing large frontend chunks. These are baseline results before product implementation, not annotation acceptance. +- 2026-11-18, Windows, 02920365: integrated the single-element annotation loop, explicit full-page capture and receiver-side batch receipts. `pnpm test` passed with 3,677 `[pass]` lines plus five Node test-runner tests; `pnpm build` and regex compatibility checks passed. `agent_browser_host_smoke` compiled and linked using the x64 MSVC desktop preset with the vcpkg `tests` feature. These checks do not establish the remaining annotation features or real desktop acceptance. +- 2026-11-18, Windows, 02920365: strict static checks found new native-host line-budget overruns, a misplaced shared test helper, an ambiguous bridge capture and a lexical ownership false positive for the `` header. Fixes are in progress; documentation-path validation passed. Do not treat the combined command's final exit status as proof that all earlier checks passed. +- 2026-11-18, Windows, 02920365: executing `agent_browser_host_smoke.exe` aborted with exit status `0xc0000409` before emitting a smoke result. Windows Application events 1000/1001 report `abort` in the executable. Native capture pixels and interaction acceptance remain unverified; a temporary debugger harness outside the repository is collecting the failure stack. +- 2026-11-19, Windows, be66b007: an isolated MSVC/GoogleTest executable passed all 20 focused tests: six annotation-session tests, eleven full-page capture contract tests and three annotation-submission request tests. This does not replace native capture or complete desktop acceptance. +- 2026-11-19, Windows, be66b007: the native smoke abort reproduced without a debugger. A lightweight temporary debugger identified an uncaught `nlohmann::json::type_error` in the smoke capture probe: the full-page command returned a non-object, and the probe called `.value("data", "")` before checking the native error. The test helper must preserve and report that capture failure instead of terminating its worker thread. Slower debugger runs also encountered the external example-page navigation prerequisite timeout; neither outcome establishes native capture success. Full native compilation remains in progress. +- 2026-11-19, Windows WebView2 157.0.4341.60, isolated capture candidate on 8f2e060e: the original capture reproducibly changed root layout width from 845 to 860 CSS pixels. An owned inspector-stylesheet guard now preserves strict bounds and root client dimensions; the independently compiled/linked native smoke passes with a real 845-by-2400 PNG containing bottom green pixels, unchanged viewport/scroll, original inline styles and author stylesheet count. Stable, stable-both-edges, thin-scrollbar and horizontal-overflow variants also pass. An inline important gutter that blocks the workaround returns `capture_layout_unsupported` before screenshot; a real follow-up probe verifies original layout/styles remain unchanged. WIC was correct: the original example-page fixture constrained the body to 416 pixels, placing the center sample outside its green section. The fixture now resets max-width and restores retry height with CSS pixel units. Thirty-seven isolated native seam/contract/probe tests pass, including native failure, cancellation and cleanup paths. Reproduction scripts, rejected parameters and logs are recorded in the TEMP `acecode-capture-investigation` directory. No shared build graph was run. Integrated rebuild/rerun, full Windows annotation workflow and macOS acceptance remain outstanding. diff --git a/docs/specs/2026-11-21-html-page-annotations-rewrite-requirements.md b/docs/specs/2026-11-21-html-page-annotations-rewrite-requirements.md new file mode 100644 index 000000000..931e7f5af --- /dev/null +++ b/docs/specs/2026-11-21-html-page-annotations-rewrite-requirements.md @@ -0,0 +1,250 @@ +# HTML 网页批注精确修改需求规格(重审版) + +**日期:** 2026-11-21(2026-11-22 按技术方案裁决对齐:3.2 / 3.3 / 3.4 / 3.5 / 3.7 / 3.8 与第 4、6 章) +**状态:** 需求已确认;与 `docs/specs/2026-11-21-html-page-annotations-technical-design.md`(Q1–Q36 / U1–U5 / D1–D8)一致 +**来源:** 工作树现状(`codex/html-page-annotations-194` 的 #194;`codex/html-page-annotations` 集成分支的 #195–201)规格不清晰,重审业务流程后的结论。竞品依据来自 t3code 源码与 Cursor / Codex(ChatGPT)/ Claude Desktop / Pinta / Pinpoint / PigeonDeck / Loupe / Agentation / Drawbridge 的公开实现。第 8 章为针对开放技术决策的竞品事实调研,仅陈述事实,不构成决策依据。 + +## 1. 目标与问题 + +Desktop 用户想精确修改 agent 生成的 HTML 页面,现在只能写文字描述让模型猜。要让用户在浏览器里圈出目标,同时表达两类意图: + +- **文字批注**:模糊意图("这里太大了"),模型改完才知道对不对,靠迭代收敛。 +- **改值指令**:直接调出目标效果,产生 `property: 旧值 → 新值` 的精确差异,模型照着改,遵从度高。 + +两类意图属于**同一条批注**,一起写、一起发。 + +本规格取代 `openspec/changes/add-html-page-annotations/specs/html-page-annotations/spec.md` 作为需求基线;原 spec 描述的是被重审推翻的路线(预览为主、整页截图、不可变记录、收据去重、导航确认)。原 change 已部分实现,代码全在 `codex/html-page-annotations` 分支上(**未进主干**;#194–#201 等分支只是同一份代码的递进快照,内容已被该分支吸收),后续按本规格重新对齐。 + +## 2. 核心模型 + +一条批注是一份"意图包",包含: + +| 组成 | 内容 | +|---|---| +| 文字描述 | `comment`,用户写的修改要求 | +| 改值记录 | 每条 `{目标, 属性, 旧值, 新值}`,只记录实际变化 | +| 目标定位 | selector / 组件名 / 源文件行号 / HTML 片段 / 计算样式 | +| 目标类型 | 元素(div / input / button 等)、框选区域、手绘标注 | +| 编号 | 本轮内的展示序号:按创建顺序连续,删除后前移重排、无空档;整批发送清空后下一轮从 1 重新开始 | + +页面上的**编号图钉**与聊天输入框里的**批注卡片**是同一份批注的两个视图,始终同步。 + +## 3. 功能需求 + +### 3.1 批注创建与双轨输入 + +- 用户在已加载页面进入批注模式,圈选一个或多个元素、框选区域或手绘标注后创建批注,获得一个编号图钉。编号是本轮内的展示序号,按创建顺序从 1 连续递增。 +- 同一条批注内,用户既能写文字描述,也能通过样式面板直接改属性(字体、字号、字重、颜色、背景、透明度、圆角、边框、宽高、间距、padding、margin 等)。 +- 改值实时作用于页面 DOM,用户所见即所得;**保存后改后效果留在页面上**。 +- 改值只记录实际发生变化的属性:`旧值 → 新值`。原样保留的文本/样式不进记录。 +- 元素定位信息随批注一起记录(selector、组件名、源文件行号、HTML 片段、计算样式),与截图一起交给模型。 + +### 3.2 原图对比 + +- **按住**查看原图(不是开关):**只认工具栏按钮的按下/抬起,不设键盘快捷键**(空格、Enter 都不触发)。按住时所有改值效果关闭、编号图钉隐藏;松手恢复改后效果与图钉。 +- 对比不改变批注记录本身,只切换预览呈现;松手后图钉留在原位,不重算坐标。 +- 「原图」的基准是**所有批注发生前的首次值**,不是上一次修改前的值——多次改同一属性时,按住看到的是页面原始状态。 +- 失焦兜底:`blur` / `visibilitychange` / `pointercancel` 任一触发即强制释放,避免卡在"按住"状态。 +- 与「隐藏标记」正交:隐藏标记是点击锁存的持久偏好(只隐藏批注层,不还原用户改的值),两者可同时生效。 + +### 3.3 批注卡片(聊天输入框) + +- 聊天输入框上方展示一张待发卡片,聚合**该会话内所有页签**尚未发送的批注,按页签分组(组头是页面标题)。 +- 每条显示:按保存时裁剪的缩略图、元素标签(div / input / button …)、文字描述;右侧是铅笔与垃圾桶。 +- 卡片最多展示 5 条,超出部分在卡片内部滚动,不把会话挤走;底部有 `N 条注释` 可折叠整卡。 +- **点铅笔 = 回到该条继续改**: + - 页签还在 → 切到该页签、页面回到批注模式、打开该条批注框,描述回填且光标定位在输入框末尾;「调整」(样式面板)可用。 + - 页签已关 → 弹窗只改文字;「调整」不出现(没有页面可比对原始样式),目标定位信息只读。 +- **点垃圾桶 = 删除该条**:立即生效,5 秒内可撤销。 +- 卡片的编辑/删除与页面图钉同步:删一条 → 对应图钉消失、后续编号前移;改文字 → 卡片与图钉同步。 +- 已发送的消息卡片**只读**:卡片主体是该页的**整屏截屏**(单击看大图),下方一行是页面标题与「N 条注释」;指针悬停标签时浮出明细,每条一行「元素标签(div / input / p…)+ 描述」,最多 5 条,超出时列表内部滚动。不提供编辑、删除、复制或"回到页面修改"。 + +### 3.4 批量发送 + +- 多条批注可攒成一批一次提交(保留页面编号图钉与待发计数)。 +- **消息只在输入框组装一次,触发有三处**:输入框的发送按钮、页内工具栏的发送按钮、浮窗内 `Ctrl+Enter`。三者等价,都是"把输入框里的内容和所有待发批注批量提交到当前会话";工具栏发送的提交范围是**会话内全部待发批注**(含其他页签与已关闭页签),按钮上显示总条数。 +- 输入框里同时有用户自己敲的话时,**合并成一条消息**发出(用户文本 + 空行 + 批注载荷),不拆成两条——拆开会触发两轮对话,模型分两次读同一批批注。 +- 发送内容:每条的文字描述 + 精确差异 + 元素定位 + **按目标外接矩形裁剪的截图**(非整页)。截图在**保存批注时**就已截好,发送阶段只做上传,不再捕获。 +- 保存时同时留一张**该页整屏图**(每页只保留最新一张),仅用于已发送消息卡片的展示,**不进消息载荷、不发给模型**——模型只收每条的目标裁剪图,避免整屏图挤占上下文。 +- 发送走现有会话消息链路,不自建复杂状态机。 +- **等确认再清空**:接口返回 202 只代表入队,不算成功;收到这条消息的确认事件后才清空这批图钉与卡片。 +- 40 秒仍未收到确认时,先按客户端消息标识核对这条消息是否真的入库:已入库按成功收尾;确实没入库才把批注放回待发、重排编号并提示重试。 +- 发送成功后这批图钉清空,下一轮编号从 1 重新开始,不跨轮累计。 + +### 3.5 导航行为 + +- 砍掉导航确认弹窗,不拦截用户操作。 +- **导航/刷新不作废未发批注**:页面重新加载后,按记录的目标定位在新文档上重放预览,编号沿用原值。 +- 重放只写"实时值仍等于原始值"的属性——用户或页面自己改过的值不覆盖,也不猜,直接标为已失效。 +- 页签关闭也**不**丢弃未发批注:它们转为"页面已关闭",仍可改文字、删除、发送(图沿用保存时那张,只是不能再调整样式)。 + +### 3.7 发送中的状态 + +- 点发送后批注立刻从页面与卡片上消失(用户看到"发出去了"),进入"发送中"。 +- 发送中的批注不参与页面渲染、不计入待发数、不可编辑。 +- 确认到达即彻底丢弃;失败则回到待发集合末尾、重排编号、恢复图钉,并提示可重试。 +- 截图上传失败不阻塞发送:该条无图,消息照发。 + +### 3.6 编号规则 + +- 图钉编号是**本轮内的展示序号**,不是持久身份:按创建顺序从 1 连续递增。 +- 删除一条批注后,其后所有批注的编号前移重排,始终保持 1..N 连续、无空档。 +- 整批发送成功清空后,下一轮的第一条批注编号重新从 1 开始,不与上一轮累计。 +- 编号仅在单批消息内用于指代"第几条修改",不跨批引用。 + +## 4. 明确不做(非目标) + +| 项 | 说明 | +|---|---| +| 整页截图 | 改为按批注目标裁剪;不做视口外全页捕获。视口内的整屏图只用于消息卡片展示,不进消息载荷、不发给模型 | +| 逐条状态机 | 只有"发送中"一个中间态;不做 pending/sending/sent 三态消费方 | +| 接收端收据去重 | 不改接收端;走现有消息投递语义 | +| 导航确认弹窗 | 不拦截、不清空;改为重放 | +| 已存记录不可编辑/不可删除 | 发送前可编辑、可删除(卡片和图钉同步);发送后只读 | +| 重启持久化 | 仅当前 Desktop 运行期保留,重启清空,不写磁盘 | +| 自建发送/重试通道 | 复用现有会话消息链路 | +| 编辑已发送的消息 | 不做。消息是对话记录,模型已按当时描述执行过;改历史会让对话与执行结果对不上 | + +已知取舍:发送失败后的重发**先自查**(按客户端消息标识核对是否已入库),但仍不保证模型端去重——极端情况下(自查也失败)可能重复执行同一修改。这是砍掉收据机制后明确接受的代价。 + +## 5. 安全与兼容约束 + +- 批注桥接只在可信 WebUI 侧注册,网页侧不可访问;网页 DOM 与特权发送严格隔离。 +- 页面提供的任意消息不得当作特权命令。 +- 保留现有"将元素添加到聊天"(source selection)入口,两种模式不共用事件或草稿。 +- 遵循仓库 UI 文案强约束:只保留完成操作所需的标题、标签、内容、操作,不加冗余说明。 + +## 6. 验收标准 + +1. 用户圈选元素后可同时写文字并改多个属性,保存后页面保持改后效果,图钉编号按创建顺序从 1 连续递增。 +2. 按住"看原图"时所有改值效果关闭、图钉隐藏;松手后改后效果与图钉完整恢复,切走窗口失焦也能释放;全程用键盘不触发该效果。 +3. 聊天框待发卡片显示正确 N 条,每个页签一组;每行可见缩略图、元素标签与描述;超过 5 条时卡片内部滚动。 +4. 在卡片中编辑某条,对应批注框弹出且输入框聚焦;修改后页面图钉同步更新。 +5. 在卡片中删除某条,页面对应图钉同步消失,剩余批注的编号前移重排、保持 1..N 连续无空档。 +6. 多条批注一次发送,模型收到每条的文字 + `属性: 旧值 → 新值` 精确差异 + 元素定位 + 裁剪截图;无整页截图。整屏图只出现在 UI 卡片上,不出现在消息载荷里。 +7. 收到发送确认后这批图钉清空、待发计数归零;下一轮创建的第一条批注编号重新从 1 开始。40 秒无确认但消息实际已入库时,不得回滚、不得产生重复消息。 +8. 页面刷新/导航后未发批注仍保留,预览按记录重放到新文档上,编号沿用原值;重启 Desktop 后清空。 +9. 网页侧无法调用批注桥接或触发会话发送。 +10. 现有"将元素添加到聊天"入口行为不变,与批注互不干扰。 +11. 关闭某个页签后,该页的未发批注仍出现在卡片上(标注"页面已关闭"),可改文字、可删除、可发送,且消息里仍带保存时那张截图。 +12. 输入框里有文字且有批注时点发送,只产生一条消息;已发送的消息卡片是整屏截屏 + 「N 条注释」,卡片上没有任何编辑入口,单击截屏可看大图。 +13. 悬停「N 条注释」浮出明细,每条一行「元素标签 + 描述」;7 条时浮层显示 5 行、可内部滚动。 + +## 7. 竞品调研依据 + +| 决策 | 竞品事实 | +|---|---| +| 双轨合一(文字 + 改值) | Cursor Design Mode 的 note 可同时带文字、CSS 属性编辑、语音;Pinta "captures the diff as a structured CSS payload";PigeonDeck 导出"CSS 选择器和变更对照表" | +| 图钉 + 批量 | Cursor "Batch edits on → notes collect as numbered pins, Send button with count sends all as one message";Drawbridge 有 to do/doing/done 任务状态 | +| 裁剪截图 | t3code 按目标外接矩形裁剪;Pinpoint "cropped screenshot";Agentation "screenshots of surrounding elements";Loupe 是少数整页派 | +| 无三态/收据 | Cursor 发送即清空;t3code 一次提交一张 chip;Pinpoint 即时对话(可反问、before/after、Accept);均无自建幂等去重 | +| 卡片入口 + 可编辑删除 | Cursor "Open the list next to Send to review pending notes, or remove them all with Clear All",note 发送前可改;Pinpoint 对话式修改;t3code chip 可编辑可删 | +| 导航不清空无弹窗 | t3code 导航直接取消当前批注;PigeonDeck 会话级清空;Pinpoint 用持久化 pins 而非弹窗 | +| 运行期清空 | PigeonDeck "所有数据仅存在于当前标签页会话,关闭标签即清除" | +| 原图对比(本次保留,竞品少有) | Cursor 用 Cmd+Z 撤销 markup、Esc 还原文本编辑;t3code 退出即还原;PigeonDeck 有撤销/重做但无全局对比开关。此为本项目明确差异点 | +| 编号重排、清空后重置 | WariPixel "deleting one renumbers the rest — no gaps";CobaltCapture "Delete one and the rest renumber themselves";Maxisnap "Delete a middle pin and the rest re-sequence";shadcn/Calloutly "removing a pin renumbers the rest"。展示序号是位置序号,非持久身份;Annotaitr 用 UUID 派生稳定 handle 与位置序号分离 | + +## 8. 开放技术决策的竞品事实调研 + +本章针对第 9 章的 9 个开放技术决策,逐条陈述竞品的公开做法。**仅陈述可核实的事实,不构成决策依据,不含推荐或取舍判断。** 事实来源分三类:官方产品文档 / API 文档、公开源码、第三方扩展与社区文档,表中逐条标注。需特别说明:Anthropic 官方(Claude in Chrome / Claude Desktop 内置浏览器)公开文档未记录元素级页面批注能力,Claude 生态的批注流程由第三方 MCP 扩展提供;Codex / ChatGPT 则有官方 Annotate、Adjust 与 Browser Annotation API。 + +### 8.1 状态与双视图同步(对应决策 1) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| Cursor Design Mode | Batch edits 开启时,pending notes 在页面上以 numbered pins 呈现;Send 按钮旁的 list 可查看 pending notes,Clear All 清空全部;已发送 notes 不能从队列清除;带 pending notes 退出 Design Mode 时 Send 按钮保留在工具栏,直到发送或清除。文档未公开 pin 的稳定身份字段。 | Cursor 官方 Design Mode 文档 | +| Codex / ChatGPT | Browser Annotation API 的 `request()` 返回 `accepted`,仅表示请求被浏览器接收并校验,不代表编辑器已打开、已保存或已发送;保存的 annotations 可在 composer attachment preview 中重开、编辑;退出 Annotation mode 关闭编辑器并保留 saved annotations,不自动提交、不移动到 composer。Canvas 虚拟对象要求 `id` 在 surface 内稳定,控件事件携带 `surfaceId` + `targetId`。 | ChatGPT 官方 Browser Annotation API 文档、Help Center | +| t3code | 一条 annotation 带内部 id(`element__`);提交后进 composer draft 成为一张 chip;chip 在发送前可编辑、可删除。 | 源码 `AnnotationIds.ts`、`PickPreload.ts`、`composerContextRecords.ts` | +| Vibe Annotations | annotations 存于本机 `~/.vibe-annotations/annotations.json`,每条带 annotation ID;Claude Code 插件把新 annotations 汇总显示在 prompt 上方并提供 Implement 按钮;agent 实现后通过 `delete_annotation` 工具删除已完成项。 | 扩展商店页、MCP 文档 | +| Loupe | 每条 annotation bundle 写为 `~/.loupe/annotations/` 下独立 JSON 文件,可通过 MCP 寻址;键盘 `1-9` 选择编号 pin,`Del` 删除选中 pin。 | Loupe 官方 manifesto、扩展说明 | + +### 8.2 原图对比与改值留存(对应决策 2) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| Codex / ChatGPT | Adjust 预览通过 `oaiannotationcontrolchange` 事件传递三种 action:`preview`(显示请求的变化)、`preview-original`(临时显示原始状态用于比较)、`reset`(清除预览时恢复原始状态);文档要求 handler 可逆且可安全重复调用,并要求把普通草稿、未完成输入与 preview 状态分开,避免无关编辑覆盖预览;preview 本身不构成永久修改,永久保存走应用正常 save flow;`dispose()` 只移除控件注册,不撤销 preview 变化,移除集成时需手动恢复渲染状态。Help Center 原文:"A preview helps communicate the change you want. It does not, by itself, save a permanent change to the website." | ChatGPT 官方 Browser Annotation API 文档、Help Center | +| Cursor | 双击文本可就地编辑,Enter 保存、Esc 还原;Cmd/Ctrl+Z 撤销 markup;CSS inspector 改值随 note 发送,官方未描述实时 DOM 写入与还原细节。 | Cursor 官方 Design Mode 文档 | +| t3code | `setStyleForSelected()` 以 `!important` 写入真实元素 inline style,同时记录 computed style 旧值到新值;teardown 时 `restoreStyles()` 按 baselineStyles 全部还原。 | 源码 `PickPreload.ts` | +| Vibe Annotations | 提供 live preview 的 CSS 属性调整(font size / colors / layout / spacing),变化被捕获为 annotations,交给 agent 在源码中实现。 | 扩展商店页 | +| Loupe | 可在页面拖拽手柄 resize、就地编辑文案、换色、删除 section、调整兄弟节点顺序,改动持续到 pin 提交。 | Loupe 官方 manifesto | + +### 8.3 元素定位信息获取(对应决策 3) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| Cursor | 每个元素提供 tag、id、classes、attributes、CSS 选择器路径、前 200 字可见文本、尺寸与位置,以及 6 项 computed styles(color / background-color / font-size / font-family / display / position);React / Vue / Svelte 应用附带 component name 与 component stack;文档明确不承诺 full DOM dump、完整样式表、全部祖先 computed styles、完整应用状态或全页截图。 | Cursor 官方 Design Mode 文档 | +| t3code | `getElementContext` 提供 selector、componentName、source(file / line / column)、htmlPreview、styles;5 秒超时,失败回退到 outerHTML 前 500 字。 | 源码 `PickPreload.ts` | +| Vibe Annotations | 捕获 CSS selectors、styles、positioning、viewport,以及从页面 fiber tree 读取的 React / Vue component 与其源文件。 | 扩展商店页 | +| Loupe | 每条 bundle 含 CSS selector、20 项 computed styles、父级 HTML、会话期间 console errors、URL、viewport、语言、active framework、breakpoint。 | Loupe 官方 manifesto、扩展说明 | +| Codex / ChatGPT | 网站可通过 `oai-annotation-metadata` 附加结构化上下文(最多 6 个属性、序列化后不超过 2048 bytes),随 annotation 进入对话;Canvas 对象可带 name / role / metadata / rect;文档要求只附加愿意同时展示给用户和模型的信息;内置浏览器把页面内容视为 untrusted。 | ChatGPT 官方 Browser Annotation API 文档、Help Center | +| Inspector Jake | `inspector_get_selected_element` 返回 tagName / id / className / selector / innerText / attributes / rect;`inspector_snapshot` 返回 ARIA 可访问性树;`inspector_get_page_info` 返回 URL / title / viewport。 | 第三方 MCP 扩展文档 | + +### 8.4 裁剪截图生成(对应决策 4) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| Cursor | 保存 note 时把截图裁剪到所选元素,或裁剪到带 markup 的框选区域;文档不承诺全页截图。 | Cursor 官方 Design Mode 文档 | +| t3code | 先 `capturePageWithRetry` 截全页,再 `cropAnnotationScreenshot` 按 CSS 坐标乘以 devicePixelRatio 裁剪,裁剪矩形为所有目标外接矩形并集加 20px padding,忽略滚动出视口的目标;截图失败降级为纯文字批注并 toast。 | 源码 `Manager.ts`、`PreviewView.tsx` | +| Loupe | 生成滚动拼接的全页标注截图(pin 烧录其上),同时为每条 annotation 生成聚焦裁剪图。 | Loupe 官方 manifesto、扩展说明 | +| Codex / ChatGPT | `request()` 的 `omitScreenshot` 可省略自动截图;截图作为 composer attachment;官方测试指南要求验证移除附件时同步清除 preview。 | ChatGPT 官方 Browser Annotation API 文档 | +| Pinpoint / Agentation | Pinpoint 为 cropped screenshot;Agentation 为 screenshots of surrounding elements(第 7 章已记)。 | 第 7 章调研记录 | + +### 8.5 改值指令格式(对应决策 5) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| t3code | 文本投影为 `requested visual changes:` 下的 `- property: prev → value` 列表,同时保留 `styleChangeDetails` 完整结构用于复制 / 粘贴还原。 | 源码 `composerContextReferences.ts`、`composerContextRecords.ts` | +| Codex / ChatGPT | 自定义控件记录 label、reference、old value、new value、callback;select 控件发送给模型的是可见 option label 而非内部 value;metadata 与 requested values 随注释进入对话。 | ChatGPT 官方 Browser Annotation API 文档 | +| Cursor | 官方描述为 "Cursor sends your CSS edits with the note",未公开具体文本格式。 | Cursor 官方 Design Mode 文档 | +| PigeonDeck | 导出为 CSS 选择器与变更对照表(第 7 章已记)。 | 第 7 章调研记录 | + +### 8.6 批注卡片与 composer 集成(对应决策 6) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| Codex / ChatGPT | 保存的 annotations 以 composer attachment preview 形式存在,可重开、编辑;发送时随消息一起提交;`request()` 只打开编辑器,不发送消息。 | ChatGPT 官方 Browser Annotation API 文档、Help Center | +| Cursor | Cmd/Ctrl+L 把 note 或 text edit 的内容放进 chat input 而非发送;Option/Alt+click 元素直接加入 chat input;Batch edits 下工具栏 Send 按钮显示 pending 计数。 | Cursor 官方 Design Mode 文档 | +| t3code | Enter = attach(批注进入 composer draft 成为 chip),Cmd/Ctrl+Enter = send;chip 可编辑、可删除。 | 源码 `AnnotationKeyboard.ts`、`PickPreload.ts` | +| Vibe Annotations | Claude Code 插件把新 annotations 显示在 prompt 上方并以一个请求发送;`/vibe list` 打开列表,`/vibe auto on/off` 切换自动发送。 | MCP 文档 | +| Inspector Jake | 一键打开 chat 并把所有 capture(含 selector、styles 与 note)发送到 agent 会话。 | 第三方 MCP 扩展文档 | + +### 8.7 批量发送提交语义(对应决策 7) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| Cursor | Batch edits 开启时一次 Send 把所有 pending notes 作为一条消息发送并退出 Design Mode;已发送 notes 不能从队列清除;官方文档说明批量不保证模型正确实现每条指令。 | Cursor 官方 Design Mode 文档 | +| Codex / ChatGPT | 只有用户可以提交 annotation;`accepted` 仅表示请求被接收校验;退出 Annotation mode 不自动提交。 | ChatGPT 官方 Browser Annotation API 文档 | +| t3code | submission 取 attach 或 send 两种,即时提交;一次批注对应一条 chip,无独立待发池;接收端无收据去重机制。 | 源码 `PickPreload.ts`、`Manager.ts` | +| Vibe Annotations | agent 读取并实现后通过 `delete_annotation` 删除已完成 annotation;另有 watch mode 长轮询新 annotation。 | 扩展商店页、MCP 文档 | +| Drawbridge | 任务状态以 to do / doing / done 写入任务文件(第 7 章已记)。 | 第 7 章调研记录 | + +### 8.8 导航清空触发面(对应决策 8) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| t3code | 监听 `did-start-navigation`(main frame)时 `settle(null)` 丢弃进行中的 pick;tab 切换 / 组件 unmount 也取消;Esc 取消当前 overlay。 | 源码 `Manager.ts`、`PreviewView.tsx` | +| Cursor | dev server hot reload 时 agent 的改动出现在运行页面;带 pending notes 退出 Design Mode 时 Send 按钮保留,而非清空。 | Cursor 官方 Design Mode 文档 | +| Codex / ChatGPT | 退出 Annotation mode 关闭编辑器并保留 saved annotations,不自动提交、不移动到 composer。 | ChatGPT 官方 Browser Annotation API 文档 | +| Vibe Annotations / Loupe | annotations 写入本机磁盘(`~/.vibe-annotations/`、`~/.loupe/annotations/`),跨标签页与导航保留;Vibe 明确支持多路由的 multi-page annotations。 | 扩展商店页、Loupe 官方 manifesto | + +### 8.9 测试与验收(对应决策 9) + +| 竞品 | 公开事实 | 来源 | +|---|---|---| +| Codex / ChatGPT | Browser Annotation API 文档给出测试项:用户可保存、重开、编辑 composer attachment preview 中的 annotation;发送后 ChatGPT 收到选中内容、metadata 与 requested values;移除附件时清除 preview;编辑器加载期间需检查 `request().accepted`,同期最多持有一个 accepted request。 | ChatGPT 官方 Browser Annotation API 文档 | +| Cursor | 公开文档以快捷键表、上下文清单与工作流说明为主,未公开自动化测试或双平台真机验收流程。 | Cursor 官方 Design Mode 文档 | +| t3code / Vibe Annotations / Loupe / Inspector Jake | 公开文档描述功能与本地运行方式,未公开针对批注流程的自动化测试覆盖范围,也未公开 Windows / macOS 双平台真机验收清单。 | 各项目公开文档与源码 | + +## 9. 开放技术决策(交给 grilling) + +以下决策项不在本章给出结论;第 8 章的竞品事实仅作参考信息,不作为决策依据。 + +1. **批注状态与视图同步机制**:页面图钉和聊天卡片是同一份批注的两个视图,如何保证编辑/删除双向同步?状态放在哪一侧(可信 WebUI / 原生宿主)?编号是可重排的展示序号,同步/寻址所需的稳定身份如何单独承载(如内部 ID),避免与编号混为一谈? +2. **原图对比层与改值留存的共存**:对比开关需要独立样式层 + 文本层做可逆切换,而"改后效果留页面 + 图钉同步"要求状态持久。两层机制如何组织,切换时如何保证恢复无残留(尤其多次编辑同一目标、文本子节点保真)? +3. **元素定位信息的获取**:selector / 组件名 / 源文件行号 / HTML 片段 / 计算样式分别从什么边界取,如何在不可信页面与可信宿主间安全传递?与现有 `selected_element` 的源码定位是否共用? +4. **裁剪截图的生成**:按目标外接矩形裁剪的捕获边界在哪(Windows WebView2 / macOS WKWebView)?跨元素、跨区域如何取外接矩形?捕获失败时的降级行为? +5. **改值指令的格式**:`{目标, 属性, 旧值, 新值}` 如何编码进现有会话消息,模型端如何解读"照着改"?是否复用 t3code 的 `requested visual changes: - property: old → new` 文本格式? +6. **批注卡片与现有 composer 的集成**:卡片挂在哪个组件,如何与草稿、附件、队列/steer 语义共存?编辑时弹出批注框的焦点/键盘处理? +7. **批量发送的提交语义**:"发送即清空"是发送前清空还是收到确认后清空?失败时如何整批重发(接受无去重风险)?与现有会话发送链路的 ack 如何衔接? +8. **导航清空的触发面**:哪些入口算"导航/刷新"(页面内跳转、host 主动跳转、刷新、关闭标签)?各自如何触发清空? +9. **测试与验收**:行为自动化覆盖到哪一层(前端交互 / 原生模型 / 端到端)?Windows/macOS 真实桌面验收的范围与未验证项如何记录? diff --git a/docs/specs/2026-11-21-html-page-annotations-technical-design.md b/docs/specs/2026-11-21-html-page-annotations-technical-design.md new file mode 100644 index 000000000..6b012e59d --- /dev/null +++ b/docs/specs/2026-11-21-html-page-annotations-technical-design.md @@ -0,0 +1,734 @@ +# HTML 网页批注 —— 技术方案(v2) + +- 状态:待评审(决策已清零:Q/U 见 §1,细节 D1–D8 见 §1.1) +- 日期:2026-11-21 +- 基线:worktree `C:/Users/Administrator/.codex/worktrees/html-page-annotations/acecode`(分支 `codex/html-page-annotations`,`bc10d7f0` + 未提交 WIP) +- 取代:`openspec/changes/add-html-page-annotations/`(设计路线:预览为主 / 整页截图 / 不可变记录 / 收据去重 / 导航确认) +- 需求:`docs/specs/2026-11-21-html-page-annotations-rewrite-requirements.md` + +--- + +## 0. 一句话方案 + +页面侧的批注运行时(样式层 / 文本层 / 区域框选)保留,**记录权威上提到会话级 `SessionAnnotationStore`**,页签降级为渲染/编辑端点(关了也不丢记录);待发批注以一张卡片挂在会话输入框上方,**逐条可编辑、可删除**;**消息组装只有一处(composer),触发点三处**(输入框发送、页内工具栏发送、浮窗 `Ctrl+Enter`),三处调同一个提交动作,发出即一条自包含消息(用户文本 + `Page annotations` + JSON,无二次确认);「按住看原图」「隐藏标记」「刷新后重放」「源文件定位」按本文档的约束补齐。 + +--- + +## 1. 决策记录 + +保留拷问过程里的结论,作为后续变更的对照基线。 + +| # | 问题 | 裁决 | +|---|---|---| +| Q1 | 原图对比是开关还是按住 | **按住**。纯同步,只增删 class,禁止重渲染/截图实现 | +| Q2 | 按住什么键 | **只有工具栏按钮的按下/抬起(纯指针)**,不设键盘快捷键;`pointercancel`/`pointerleave` 兜底 | +| Q3 | 原图与隐藏标记的关系 | **两个独立控件**,投影正交 | +| Q4 | 「原图」的基准 | **所有批注发生前**(首次触碰值),不是上一次修改前 | +| Q5 | 文本编辑 | 在范围内(#196 已实现,逐 Text 节点写 `node.data`) | +| Q7 | 隐藏标记隐藏到什么程度 | **整层隐藏**(图钉、描边、选中框、hover 卡全不见) | +| Q8 | 原图态图钉 | **不显示**;松手后图钉留在原位(不需要重算 rect) | +| Q9 | 隐藏标记是按住还是锁存 | **点击锁存**(持久视觉偏好) | +| Q10 | 按住时样式面板 | **整体隐藏**(视觉隐藏 + `inert`,不卸载) | +| Q14 | 按住是否与轮询排队 | **不排**。preview 类命令是 quiet 命令,不占 `busy_` | +| Q15 | 编号与记录权威 | **原生权威**;页内只接收 `sync` 全量下发的图钉列表 | +| Q16 | 隐藏标记交互 | 保留点击锁存 | +| Q17 | 失焦兜底 | **补**:`window blur` / `visibilitychange` / `pointercancel` 强制释放 | +| Q18 | 浮窗打开时工具栏 | **消失**(沿用 Codex 行为,规避丢草稿与挖洞几何抖动) | +| Q19 | 隐藏标记范围 | 改实现为整层 `visibility:hidden` | +| Q20 | `old_value` 语义 | **真 baseline**(首次触碰值),中间态不进记录 | +| Q21 | 失效批注能否发送 | **能**,标 `target_invalid` | +| Q22 | 清空点 | 只剩两个:**消息确认** + 手动丢弃。(导航/刷新/重启不清) | +| Q23 | URL 粒度 | **每条记录自带** `page_url` / `page_title` | +| Q24 | 清空时机 | **等 WS `message` 事件按 `client_message_id` 确认**,不是 202 | +| Q25/Q28 | 截图 | **保存批注时按 rect 裁剪**,每条一张,供待发卡片缩略图;同一时刻另存该页**整屏图**给已发消息卡片,每页只留最新一张。发送时**复用不再捕获**(§4.8)。两张图用途不同,不是同一张 | +| Q26 | 批次回执 | **删干净**(`annotation_batch_id`、`reconcileOnly`、服务端对账分支) | +| Q27 | 失效与有效混批 | **全部放行**,逐条标状态 | +| Q29 | 源文件定位 | **零注入**:主 world 读 `__reactFiber$`,dev 给 file:line,否则给组件栈;定位不到必须问 | +| Q30 | 刷新后保留 | **要**:声明式重放(selector + 差异),带「值相等」闸 | +| Q31 | mac 视口外目标截图 | 接受降级(保存时即无图),UI 明示 | +| Q32 | 重放闪烁 | 接受(与 Codex 同级) | +| Q33 | 记录归属 | **修订为会话**:记录归属会话的待发集合,页签只是渲染/编辑端点;**关页签不销毁**,降级为 `orphan`(§4.11) | +| Q34 | 半打字描述 | 内存暂存,**key 用 `page_id + target_locator`**(不含 `document_id`,理由见 §4.10) | +| Q35 | 「发送」的语义 | **直发,无二次确认**。**组装唯一、触发三处**:消息只在 composer 组装一次;输入框发送按钮 / 页内工具栏发送按钮 / 浮窗 `Ctrl+Enter` 都调同一个提交动作,效果等价于「把输入框内容和所有批注批量提交到当前会话」 | +| Q36 | 浮窗 `Enter` | **添加**(保存当前批注、生成图钉等待发送),不发送;`Shift+Enter` 换行 | +| U1 | 已发卡片的落点 | **消息历史**;否掉「发送后仍挂在输入框等待确认」方案。注意这与 U3 的**待发卡片**是两回事:发送前才在输入框上方有一张待发卡 | +| U2 | `reapply` 时机 | **立即 + 观察窗口**(3s / 节流 300ms / 最多 10 次);否掉「延迟到首次用户操作」 | +| U3 | 待发批注卡片 | 逐条 **编辑 + 删除**。编辑 → 激活页签 + 打开该条浮窗 + 描述框聚焦;**页签已关 → 弹窗只改文本,「调整」隐藏**。已发消息卡片**只读**(§4.11) | +| U4 | `Ctrl+Enter` | **保存当前 + 发送整批**(a);发送走 composer 同一条链路 | +| U5 | 40s 未确认 | **先按 `client_message_id` 自查再回滚**:已落库 → 正常收尾;未落库 → 才回滚 | + +额外裁决(本轮补充): + +- 会话归档**不关闭**其浏览器页签 → 页签与批注保留,重新打开会话可继续。 +- **待发批注卡片挂在会话输入框上方**,跨页签聚合(数据源见 §4.11);发送目标 = 卡片所属会话,不提供会话选择器。 +- **已发消息卡片只读**:整屏截屏 + 「页面标题 + `N 条注释`」,明细收进悬停;不给「回到页面修改」「复制」「重发」。批注能改的前提是尚未发送进会话。 +- 页签关闭 ≠ 记录消失:记录降级为 `orphan`,仍可改文本、删除、发送;**图还在**(保存时截的),只是不可调整、不可重放。 +- 消息载荷**自包含**:移入 `in_flight` 时即生成副本,发送过程中页签关闭不影响发送。 + +### 1.1 细节裁决(D1–D8,全部已定) + +| # | 问题 | 裁决 | 影响 | +|---|---|---|---| +| D1 | `orphan` 记录在重开同 URL 页签时是否「重新定位」回 `live` | **不做**。`orphan` 是终态,只能改文本 / 删除 / 发送 | 关页签后预览不可恢复;agent 仍可按 locator 找元素。留 action 位,后置可加 | +| D2 | 待发卡片每行的 24px 缩略图从哪来 | **保存批注时按 rect 裁剪的那张图**(只给待发卡片);另存一张**该页整屏图**给已发消息卡片,每页只留最新一张 | 捕获时机从「发送时」前移到「每次 save」;发送时不再捕获。**`orphan` 记录因此仍有图**。删除批注不重截,配图保留删除前画面 | +| D3 | 卡片最多展示几条 | **5 条**,超出后卡片内部滚动 | 不是折叠成 chip,而是 `max-height` + `overflow:auto` | +| D4 | 删除后撤销窗口 | **5s** | 定时器,可调 | +| D5 | 跨页签混批的载荷形态 | **`page` 单值(第一条记录所在页)+ 每条自带 `page_url`** | 解析层零破坏;模型与卡片按 `annotations[].page_url` 分组 | +| D6 | 已发卡片要不要「复制文本」 | **不给**。已发卡片一个按钮都没有 | 与 U3 一致:只读到极致,避免任何"能改"的暗示 | +| D7 | 编辑中页签被关闭 | **存进 draftStore,卡片行转 `orphan`**,下次点铅笔接着改 | 不打断输入、不弹窗、不假装页面还在 | +| D8 | 编辑态要不要把页面拉进批注模式 | **要拉回**:隐式 `start()`,页面进入批注模式 | 用户从卡片点铅笔本就是来改批注的,之后的点击自然就是批注意图;`start` 复位 `original`/`markers_hidden` 也符合"重新进入"的心理预期 | +| D9 | 记录标识是否与文档绑定(#208 结论) | **不绑定**。`record.id` = `:annotation:`,`document_id` 降为记录属性,另存跨文档可用的 `locator` | 现行 `:annotation:` 在刷新后结构性失效(§4.12);#209 的存储主键照此落 | +| D10 | 保存时捕获是同步还是异步(#208 结论) | **异步补图**:`save` 立即入库广播,捕获 + 裁剪在后台完成后回写 `thumbnail` / `page_shot`;2s 超时判 `screenshot_unavailable` | 页面侧裁剪实测 P95 ≤ 37 ms(做了 `scale=1/dpr`),性能不是瓶颈;异步是为了不让直接操作动作等 CDP 往返,也为了让捕获失败不阻塞保存 | + +--- + +## 2. 领域模型 + +``` +Session (会话) + ├── SessionAnnotationStore (原生, 内存) ← 待发记录的权威 + │ ├── records[] 每条自带 page_id / page_url / page_title + │ ├── in_flight[] + │ └── next_number 按 page_id 分组各自递增 + └── Page (浏览器页签) ← 渲染与编辑的端点 + ├── AgentBrowserState + └── PageAnnotationSession (原生, 内存) ← 页签存活时才存在 + ├── active / original / markers_hidden / modal_suspended + ├── selection_mode: null | element | region + ├── targets[] / region + └── document_id / epoch ← 只负责选区、预览、样式层 +``` + +**为什么权威从 Page 上提到 Session**:U3 要求「页签关了,卡片还在,还能改文本、还能发送」。只要记录的生命周期短于卡片,`pages.erase(page_id)` 就会把用户写到一半的描述一起析构。反过来把记录挂在会话上,页签只剩三件可失效的东西:DOM(预览/样式/调整)、`document_id`(重放)、`executionContextId`(下发命令)。这三样都在页签关闭时失效,正好对应 `orphan` 态。 + +**核心不变量** + +1. 记录属于 **Session 的待发集合**,不属于页签。关页签 → 记录转 `orphan`,**不删除**。 +2. 导航(含刷新、前进后退、跳转)**不作废记录**,只把它从 `live` 转成 `replayable`。 +3. 记录编号是**页内展示序号**,等于该 `page_id` 分组内位置 + 1;删除即重排。跨页签混批时编号会重复,靠 `page_url` 消歧(Q23)。 +4. 差异(`differences`)的 `old_value` 永远是该属性的**页面原始值**,与「按住看原图」看到的一致。 +5. 已发送的消息**不可变**:没有任何入口能改写它(无「编辑消息」API,transcript 只追加)。 + +--- + +## 3. 状态机 + +### 3.1 批注模式(每个 Page 独立) + +``` +idle + └─(start)─> annotating + ├─(pointer 单击元素)─> popup_open(target) + │ ├─(编辑样式/文本)─> popup_open(dirty) + │ └─(save)─> annotating(records+1) + ├─(add_region + drag)─> popup_open(region) + ├─(open_record_popup)─> popup_open(edit) // 卡片铅笔,回填已有记录 + ├─(exit)─> idle // 记录保留,工具栏隐藏 + └─(discard)─> idle // 记录清空,next_number=1 +``` + +- `exit` / `start` 不销毁记录(Q22)。 +- `start` 复位 `original` / `markers_hidden` / `modal_suspended`。 + +### 3.2 记录四态(替代当前 `valid: bool`) + +| 态 | 含义 | 可发送 | 画图钉 | 可重放 | 可调整样式 | +|---|---|---|---|---|---| +| `live` | 目标仍在当前文档且有效 | 是 | 是 | — | 是 | +| `replayable` | 文档已替换,等待在新文档上重放 | 是(标 `target_invalid`) | 否 | 是 | 否(等重放成功) | +| `stale` | 重放失败 / 目标值已被改动 / 目标被移除 | 是(标 `target_invalid`) | 否 | 否 | 否 | +| `orphan` | **页签已关闭**,没有任何 DOM 可操作 | 是(标 `target_invalid`;图沿用保存时截的) | 否 | 否 | 否 | + +转换: + +``` +live --(document replaced)--> replayable +replayable --(定位成功 且 实时值==old_value)--> live +replayable --(定位失败 / 值不等 / 文本节点结构变化)--> stale +任意 --(页签关闭)--> orphan // 记录保留,仍可改文本/删/发 +orphan --(重开同 URL 页签)--> 仍为 orphan(不自动重放,需用户显式"重新定位") +任意 --(点发送)--> 移出 records, 进 in_flight(不再画图钉,见 §3.4) +in_flight --(WS 确认)--> 删除 +in_flight --(失败)--> 并回 records 尾部,恢复原态 +任意 --(手动删除单条)--> 删除 +``` + +`next_number` 只在 `discard`(全清)时重置为 1;`replace_document` **不重置**,但重排时按该 `page_id` 分组内的数组顺序重新编号(见 §4.2)。`orphan` 记录不参与页内 `sync`(它没有页签),但**仍出现在待发卡片上**。 + +### 3.3 拦截式预览(按住原图) + +``` +released --(pointerdown)--> held +held --(pointerup / pointercancel / pointerleave / window.blur / visibilitychange hidden)--> released +``` + +- **纯指针,零键盘。** 不注册 `keydown`/`keyup`,空格与 Enter 在工具栏上不触发「按住原图」(Enter 对聚焦按钮的默认激活行为要 `preventDefault` 掉,否则会变成一次点击——而点击对「按住」没有语义)。 +- 进入 `held` 只做一件事:`original{enabled:true}`。 +- 退出 `held`:`original{enabled:false}`。 +- `held` 期间 `preview_style` / `preview_text` / `save` 在页内短路返回 `original_view_active`(已实现),原生侧也要拒绝,避免英文错误码外泄。 +- 强制释放的优先级高于「用户主动松手」:重复发 `enabled:false` 是幂等的。 + +### 3.4 批次与发送 + +**组装唯一,触发三处。** 消息只在 composer 组装一次(`submitWithAnnotations()`),三处都调它: + +| 触发点 | 语义 | +|---|---| +| 会话输入框的发送按钮 | 原生入口 | +| 页内工具栏的发送按钮 | 等价于点输入框发送:**输入框现有内容 + 会话内全部待发批注**一起提交 | +| 浮窗 `Ctrl+Enter` | 先 `save` 当前这条,再触发同一个提交 | + +工具栏按钮不是第二条发送链路——它不自己组装 payload、不自己 POST,只在原生侧确认 webview 存活后把「提交」这件事交给 WebUI 的同一个动作。这样「输入框里有半句话 + 3 条批注」无论从哪触发,都只产生一条消息、只触发一轮 turn。 + +三点约束: + +- **提交范围是会话全量**,不是「当前页签那几条」。工具栏挂在页签 A 上,点它也会把页签 B 与 `orphan` 的记录一起发出去——因为待发集合本身就是会话级的(Q33)。按钮上必须显示总条数(`N 条待发`),否则用户会以为只发现在这页。 +- **输入框草稿会一并发出**。用户可能正在输入框里写话,随后回页面点工具栏发送——那半句话会作为消息前缀一起提交。这是有意为之(用户要的就是「把聊天框里的内容和所有批注批量提交」),不做「工具栏发送时丢弃草稿」的分支。 +- **回执反馈收敛到一处**:成功/失败/40s 自查结果统一由 composer 的发送状态机广播,工具栏与输入框显示同一个状态,不各写一份 toast。 + +``` +pending(会话内全部 live / replayable / stale / orphan 记录) + └─(任一触发点 → submitWithAnnotations)─> sending + ├─(WS message 按 client_message_id 确认)─> 清空该批,各 page 分组编号归 1 + └─(POST 失败 / 40s 未确认)─> 自查 → 真失败才 in_flight 并回 records 尾部, 重排编号, toast +``` + +- 进入 `sending` 的瞬间,`records` 里所有 `pending` 记录**移入 `in_flight`**;`sync` 后存活页签的图钉立即消失,待发卡片立即清空(用户看到「发出去了」)。 +- `in_flight` 不参与 `sync`、不参与重放、不计入 `pending_count`、不可编辑、不在卡片上显示(否则用户会以为没发出去)。 +- 成功:丢弃 `in_flight`;期间没有新记录则卡片与工具栏一起消失。 +- 失败:`in_flight` 并回 `records` 尾部、按 page 分组重排编号、`sync` 让图钉回来、卡片回填,toast 提示可重试。 +- 发送阶段**没有截图步骤**:图在 `save` 时已经截好挂在记录上(§4.8、D2),发送只做上传。上传失败不阻塞发送——该条标 `screenshot_unavailable`,消息照发。 +- `orphan` 记录**有图**(保存时截的),发送时和活着页签的记录一视同仁,只是不再有新的图可更新。 +- 记录副本(`annotations`)在移入 `in_flight` 时就已从原生快照生成,页签此后关闭不影响发送(Q33)。 +- 没有「卡片在输入框等待」这一态——那是被否掉的 U1 方案 A。 + +**用户文本与批注合并成一条消息** + +composer 里可能同时有用户敲的话和一批批注。合并成**一条**消息,避免两次 POST 触发两轮 turn: + +| 用户文本 | 消息 `text` | +|---|---| +| 空 | `Page annotations\n{json}`(与基线一致) | +| 非空 | `{用户文本}\n\nPage annotations\n{json}` | + +解析层相应放宽:不再要求 `startsWith(HEADER)`,改为「文本末尾存在 `\nPage annotations\n` 分隔段」。卡片渲染时只展示用户文本 + 批注卡片,JSON 段被遮蔽。 + +**快捷键语义** + +| 位置 | 按键 | 行为 | +|---|---|---| +| 浮窗描述框 | `Enter` | **添加**:保存当前批注,生成图钉挂在页面,等待发送 | +| 浮窗描述框 | `Ctrl+Enter` | **保存当前 + 触发整批发送**(U4 = a),等同于「添加完再从任一触发点提交」 | +| 浮窗描述框 | `Shift+Enter` | 换行(批注描述是多行文本) | +| composer | 发送按钮 / 既有发送快捷键 | 发送(用户文本 + 整批批注,合并一条) | + +- 空描述不允许「添加」:`save` 仍是必填(现状 `description` 非空、≤16384)。 +- `Ctrl+Enter` 时若当前浮窗描述为空,则**只发送已有整批**,不报错(等价于用户直接点工具栏或输入框的发送)。 + +--- + +## 4. 关键机制 + +### 4.1 命令面:quiet vs busy + +现状 `PageAnnotationSession::prepare()` 对**所有** action 统一置 `busy_ = true`(`page_annotation_session.hpp:300`),连 `read` 都占闸;而 `design.md:365-366` 明写这些是 quiet 命令。这是实现偏离设计,按住原图的手感直接受害(Windows 每命令 3 跳 CDP)。 + +拆成两档: + +| 档 | action | 闸门 | +|---|---|---| +| quiet | `read` `preview_text` `preview_style` `original` `hide_markers` `set_modal_suspended` `sync` | 无 `busy_`;只做 `document_id` / `epoch` / 目标校验;允许并发、允许覆盖 | +| 事务 | `start` `exit` `cancel` `save` `add_target` `add_region` `select_target` `select_region` `discard` `reapply` `open_record_popup` `update_description` `delete_record` | `busy_` 串行 + `sequence` 防迟到 | + +quiet 命令的返回值仍走快照路径,但**失败不得中断 WebUI 的 read 循环**(现状 `PageAnnotations.jsx:43-46` 一次 `ok:false` 就 `return`,定时器不再排,导致页面点击永久不回传)。 + +### 4.2 `sync`:原生全量下发图钉 + +页内 runtime 不再自己决定「画哪些图钉、编号是几」。每次记录集合变化(save / **update_description** / delete / reorder / discard / reapply 成功),原生向**该记录所属页签**下发: + +```json +{"action":"sync","document_id":"...","pins":[ + {"record_id":"...","number":1,"state":"live","target_locator":"...","region":null,"bounds":{"x":0,"y":0,"width":0,"height":0}} +]} +``` + +页内按列表整体替换 `pins`(幂等)。删除一条 → 原生重排 `number` → 下一次 `sync` 全量刷新。这条同时解决了「删了记录图钉还在」的现存缺陷(当前 runtime 没有 `remove`)。 + +### 4.3 baseline 语义 + +必须改成「首次触碰值」,否则两个消费方看到的世界不一致: + +- 现状样式:`select()` 里 `baseline = computed(target)`,而 adopted sheet 已含上轮 saved 声明(`page_annotation_style_runtime.hpp:102-110`)→ 白→红→蓝 会记成 `红 → 蓝`。 +- 现状文本:`old_value = originals + saved`(`page_annotation_text_runtime.hpp:161-165`)→ 同理。 + +改法: + +- 样式层 `baseline` 改为 **per-property、只在 saved/draft 之外取值**:`baselineOf(target, field)` 读取时先临时忽略本层构造样式表,或用「首次 select 时快照 + 之后不再覆盖」。 +- 文本层 `old_value` 的基准改为 `originals`,不叠加 `saved`。 +- **baseline 必须写进记录**,不只留在页内(重放与「按住原图」都要用):`differences[]` 增加 `baseline_value`,或记录级 `targets[].baseline`。考虑到 `differences` 已经承载 `old_value`,且 Q20 后 `old_value` 就等于 baseline,**不再加字段**,但要在文档与测试中把语义钉死:`old_value` = 页面原始值,永不为中间态。 + +### 4.4 按住原图 + +页内已实现 `markersVisible = !markersHidden && !original`(`page_annotation_runtime.hpp:171`),原图态图钉与选区框自动隐藏、记录与编号保留。要补的只有前端时序: + +1. `pointerdown` 立即 `original{enabled:true}`,不节流、不等 Promise。**不接键盘**:工具栏按钮吃掉 Enter 的默认激活(`preventDefault`),Space 不绑定;无障碍维度上它是 `aria-pressed` 之外的瞬时动作,靠按钮的 `title`/`aria-label` 说明「按住查看原图」。 +2. 释放事件三路(`pointerup` / `pointercancel` / `pointerleave`)+ 两路兜底(`blur`、`visibilitychange`),任一触发即 `enabled:false`。 +3. 按住期间: + - 工具栏按钮置 `data-held`(不用 `aria-pressed`,那是切换语义); + - 浮窗与样式面板 `visibility:hidden` + `pointer-events:none` + `inert`(**不卸载**,不触发 `notifyNativeSurfaceOverlayChange()`); + - 原生侧拒绝 `preview_*` / `save`。 +4. 样式层 `setOriginal(0→1)` 时把当前 draft 的差异快照进 `comparison`,释放后原样恢复(已实现)。 + +### 4.5 隐藏标记 + +改成整层隐藏,不再逐元素挑可见性: + +```js +case 'hide_markers': overlayRoot.style.visibility = next.enabled ? 'hidden' : 'visible'; +``` + +理由:现有实现逐个判断 `marker` / `pin.outline`,新加任何 overlay 元素(hover 卡就是这样漏掉的)都必须记得加条件。整层隐藏从结构上免疫。 + +锁存语义,图标 `aria-pressed` 反映状态;与按住原图正交,可组合。 + +### 4.6 重放(reapply) + +触发:`NavigationCompleted`(Windows)/ `didFinish`(mac)后,若存在 `replayable` 记录且 `page_url` 精确匹配,启动一轮**带观察窗口的重放周期**。 + +算法(页内执行,原生给数据): + +``` +attempt(records): // 每个窗口 tick 跑一次 +for record in replayable: + el = locate(record.locator) // CSS 路径 → testid → aria-label → 文本指纹 → 同级索引 + if !el: mark pending, continue // 还没渲染出来,不是 stale + for each difference: + if difference.property == "text": + if liveText(el) != difference.old_value: stale; continue + applyTextDiff(el, difference.old_value, difference.new_value) + else: + if computed(el)[property] != difference.old_value: stale; continue + styles.apply(el, property, difference.new_value) + record.state = live +sync() // 全量刷新图钉,编号沿用 record.number +``` + +**观察窗口**(U2 裁决):`didFinish` 后立即 `attempt()` 一次;此后用 `MutationObserver`(节流 300ms)驱动重试,窗口 3 秒,最多 10 次。 +窗口内「元素还不存在」不算失败,只是继续等;窗口结束仍未定位到,才判 `stale`。 + +四条硬约束: + +1. **值相等闸**:实时值必须等于 `old_value` 才写。否则会盖住 agent 已改好的代码结果,让页面说谎——这比不重放严重得多。 +2. **编号沿用**,不重新分配。 +3. **不做跨 URL 重放**。`page_url` 精确匹配(含 query),SPA 路由变化视为不同页面,记录留在 `replayable` 等用户回去。 +4. **`in_flight` 不参与重放**(已点发送,正在等 WS 确认)。 + +为什么要有窗口而不是「一次定生死」:`didFinish` 不等于 DOM 就绪。React/Vue 的 SPA 在这个时刻常常只有骨架屏或空容器,数据还在接口里。一次定位失败就把记录判死,用户会看到「刷新后我的修改没回来」,而且看不出来为什么。 + +闪烁:接受(Q32)。就绪后一次 CDP 往返的延迟,与 Codex 同级。若要消除,改 document-start 注入 + 元素插入时微任务套用,但会引入「页面 CSS 未加载导致 `getComputedStyle` 读到默认值」的误判,本期不做。窗口机制让「元素晚到」也能补上,这是 (b) 相对一次性的主要收益。 + +**stale 的可见性**:页面上画不出图钉(没有坐标),但工具栏必须显示「N 条已失效」,记录在批注列表里置灰、可查看、可发送(带 `target_invalid`)。静默隐藏会让用户以为批注丢了,然后重改一遍 → 重复记录 → agent 改两遍。 + +### 4.7 元素定位 → 源文件 + +**零注入**,只在 `save` 时读一次。 + +1. 隔离世界给目标打随机属性 `data-ace-hit-`(样式层已有同款手法 `data-ace-preview-*`)。 +2. 主 world 执行: + +```js +const el = document.querySelector('[data-ace-hit-]'); +const f = el[Object.keys(el).find(k => k.startsWith('__reactFiber$'))]; +let n = f, stack = []; +while (n) { if (n.type?.name) stack.push(n.type.name); if (n._debugSource) break; n = n.return; } +return {source: n?._debugSource ?? null, components: stack.slice(0, 8)}; +``` + +依据:`__reactFiber$` 键在 dev/prod 构建都存在(`react-dom.development.js:11481`,production 构建同样命中);`_debugSource` 仅 dev(`react-dom.development.js:13288/13942/13963`)。 + +3. 路径归一化(原生或消息构造侧):剥 `?t=` / `?vue&type=`;`/src/x.tsx` → 尝试 `/src/x.tsx`;`/_next/static/chunks/**` 直接丢弃。 +4. Vue 3 dev:`el.__vueParentComponent.type.__file`;Svelte dev:`el.__svelte_meta.loc`。 +5. **拿不到 file:line 时给组件栈**(Cursor 同款),它不是空信息,agent 可以按名字 grep。 +6. 硬约束:定位只作提示,路径必须落在 workspace 内且文件存在;改动前必须先说「我改的是 X」;定位不到必须停下来问。 + +### 4.8 截图(保存时裁剪,D2) + +**时机前移**:不是发送时截,而是**每次 `save` 截一张**。保存那一刻页面正停在目标上,是坐标最准的时刻;等到发送时页面可能已经导航、重放、或干脆关了。 + +``` +save(同步返回,不等捕获) + → 记录立刻入库并广播(thumbnail 为空,screenshot_pending:true) + → 后台:视口捕获一次(Windows Page.captureScreenshot 视口,scale = 1/dpr;mac takeSnapshot 视口) + → 后台:按目标 rect(并集 + padding)裁剪(坐标即 CSS 像素,不乘 DPR) + → 后台:缩到宽 ≤ 512px → record.thumbnail(PNG data URL) + → 后台:同一张视口原图另存为该页的 page_shot(每页只留最新一张,供已发消息卡片) + → 回写记录 + bump revision + 广播(卡片缩略图与已发卡片配图就位) + → 失败 / 2s 超时:screenshot_unavailable:true,不重试,save 本身不受影响 +``` + +- **异步(D10)**:`save` 是直接操作动作,用户对它的感知是「立刻」。捕获串在返回路径上会让图钉出现时间取决于 CDP 往返,而缩略图并不紧急。异步也让「捕获失败」退化为一次字段更新,而不是一次交互失败。 +- **`scale = 1/dpr` 是硬要求(#208 实测)**:DPR2 下不做修正,捕获图是 5120×2880(4.6 MB PNG),保存路径 P95 达 238 ms;做了修正是 2560×1440、P95 37 ms。见 `2026-11-22-html-page-annotations-t0-findings.md`。 + +- 一次捕获出两张图,分工固定: + - `record.thumbnail`(局部,≤512px)——待发卡片的 24px 缩略图 + 发送时该条的 attachment; + - `page_shot`(整屏,按 `page_id` 存在会话级 store,后来覆盖前者)——**只**给已发消息卡片做配图,**不进消息载荷**。整屏图若逐条随消息发出去,既会挤占模型上下文,也会把同一页重复传 N 次。 +- **发送时不再重复捕获**(D2)。 +- 目标在视口外 / 捕获失败 / mac 拿不到快照 → `screenshot_unavailable: true`,卡片退化为 `tag` + 元素文本片段(D2 的降级形态),发送时该条无附件;此时 `page_shot` 仍可能是好的,消息卡片照常出图。 +- `orphan` 记录**仍有图**——两张图都是保存时留下的,与页签在不在无关。这消掉了「页签关了就没图」的老问题。 +- 删除批注不触发重截:`page_shot` 保留删除前的画面,直到该页下一次 save。这是可接受的已知偏差(PRD §11)。 +- 不再需要 `captureBeyondViewport` + `cssContentSize` 的整页捕获:视口够用,目标在视口外本来也没有坐标能裁。 +- 上传仍在发送阶段,base64 → attachment,失败降级不影响消息。 + +**代价**:每次 save 多一次视口捕获(Windows 一次 CDP 调用,`executionContextId` 已缓存)。用户保存批注是低频动作,可接受;换来的是「发送时零捕获」和「关页签仍有图」。 + +### 4.9 发送链路 + +**基线现状**:`PageAnnotationSendBar.jsx` 点「发送」直接调 `sender.send({snapshot, sessionId, api, page})`,消息立即进会话——**已经是直发,没有待确认卡片**。所以本节的工作量是「换入口 + 砍回执」,不是「改交互」。 + +砍掉: + +- `annotation_batch_id` 与批次冻结、`reconcileOnly` 重试对账、服务端 `annotation_batch_not_accepted`(404 协议) +- 批次级整页截图 + `fullPage === true` 断言(mac 上必失败) +- 原生 `acknowledge` / `capture` / `validate` / `release`(租约机制) +- `PageAnnotationSendBar` 的「重试」三态(`idle/working/error` 保留,但失败即回滚记录,用户重按一次) +- **工具栏发送按钮里的发送链路**(不是按钮本身):`capture`/回执/租约全部删,按钮改为调用 `submitWithAnnotations()` + +新链路: + +``` +任一触发点(输入框发送 / 工具栏发送 / 浮窗 Ctrl+Enter 先 save 再触发) + → submitWithAnnotations():一次性取「composer 文本 + 会话内全部待发记录」 + → records 全部移入 in_flight → sync(存活的页签图钉立即消失,待发卡片立即清空) + → 上传每条记录的 thumbnail(save 时已截,这里只上传,不捕获)→ attachment + → 组装消息:text = 用户文本 + "\n\nPage annotations\n" + payload JSON,attachments = [截图 id] + → POST /api/sessions/:id/messages(不带 annotation_batch_id) + → 202 只表示入队,不算成功 + → WS message 事件按 client_message_id 确认 + → 丢弃 in_flight;若 records 为空,各 page 分组编号归 1、卡片与工具栏隐藏 + (40s 内未确认 → 见下「超时自查」) +``` + +**超时自查(U5)**:40s 没等到 WS `message` 时,**不要直接回滚**——先查一次这条消息到底有没有落库: + +``` +自查 GET /api/sessions/:id/messages?client_message_id= + ├─ 查到 → 视为成功:丢弃 in_flight,正常收尾(说明只是 WS 事件丢了) + └─ 查不到 → 才回滚:in_flight 并回 records 尾部、重排编号、sync 恢复图钉、toast「发送失败,可重试」 +``` + +理由:`client_message_id` 已经写进消息 `metadata` 落库(`routes_sessions.cpp:524`),WS 回推时也带回来(`:734-738`)。没有自查的话,一次 WS 抖动就会让用户重发,agent 收到两条一样的批注、把同一处代码改两遍。服务端需要补一个按 `client_message_id` 的查询(读 `metadata`,不需要新列)。 + +**消息载体沿用基线的「文本内嵌 JSON」**(`web/src/lib/pageAnnotationMessage.js:3` 的 `"Page annotations\n"` 头 + payload),不新增 `contexts` 类型。理由: + +- 基线已跑通,前端已有 `parsePageAnnotationMessage` 解析并渲染成卡片、`contentPartsWithoutAnnotationScreenshot` 剥截图,改 `contexts` 等于把可工作链路推倒重写。 +- 模型直接读结构化 JSON,字段边界比 prompt 文本块清晰。 +- 零后端改动(除删 `annotation_batch_id` 校验、加超时自查查询)。 + +代价(写进风险):消息 `text` 里存的是 JSON,导出/搜索/其他客户端会看到原文。主 UI 由解析层遮蔽,可接受。 + +- 发送目标 = 卡片所属会话,**不提供会话选择器**。 +- 误发不可逆(Q35)。缓解只靠位置与视觉:它就是用户熟悉的那个发送按钮,不做长按/双击等隐藏手势;发送前卡片上能看清这次要发几条、发往哪些页面。 +- 页签在发送途中关闭:payload 已冻结成副本,发送不受影响。 + +**消息历史里的卡片**(`PageAnnotationMessageCard.jsx`)——**只读**: + +- 结构:**页面整屏截屏**(单击看大图)+ 下方一行「页面标题 + `N 条注释`」。 +- `N 条注释` 是悬停入口:浮出该页明细,每条一行「元素标签(`div`/`input`/`p`)+ 描述」,最多 5 条,超出时列表内部滚动。 +- 一条批注有多个目标时,元素标签取主目标;一条消息涉及多页时按页面堆叠「截屏 + 标题 + 标签」,每张图只展开本页条目。 +- 不给铅笔、不给垃圾桶、不给「回到页面修改」。已发消息是 transcript,agent 已按当时描述执行;能改等于改历史,且系统没有任何编辑消息的 API。 +- **刻意不再逐条平铺描述与缩略图**:待发卡片要回答「这条是不是我想发的」,所以逐条、带缩略图;已发卡片要回答「当时页面长什么样」,所以整页一图、明细收进悬停。两者不是同一套布局的两种状态。 +- 想做新一轮修改 → 回页面重新批注(新记录),这是显式且留痕的路径。 + +### 4.10 草稿暂存 + +浮窗的 `description` 按 **`page_id + target_locator`** 存进 WebUI 内存 store(`Map`),组件卸载、文档替换(含 HMR 重载)都不丢。 + +- 不用 `document_id` 做 key:HMR 在开发时频繁触发,`document_id` 一变草稿就没了,而这恰恰是用户正在打字的时候。 +- 兜底:重载后若 target 定位不到,草稿保留但不绑定元素,浮窗以「草稿(未绑定)」形态可继续编辑或丢弃。 +- 仅内存,不落盘,不进原生。 + +### 4.11 待发批注卡片与逐条编辑(U3) + +**卡片是什么**:会话输入框上方的一条卡片,列出**该会话所有页签**尚未发送的批注。它不是消息、不占 transcript,数据源是原生 `SessionAnnotationStore`,不是消息载荷。 + +**数据从哪来**:现状 `AGENT_BROWSER_STATE_EVENT` 只带当前面板页签的 `annotations`(`AgentBrowserPanel.jsx:83` 按 `page_id` 过滤),面板外的页签上报不到。要支持跨页签聚合: + +- 原生在**任一页签**的记录集合变化时都发状态事件 `{session_id, page_id, annotations}`,不再只发面板页签; +- WebUI 新增 `pageAnnotationPendingStore`,按 `session_id → page_id → records` 归并,并单独维护 `orphans[]`; +- 卡片订阅该 store。页签关闭时原生推 `{page_id, annotations: []}`,同时把该页记录挪进 `orphans[]`——卡片上一行都不少。 + +**一行长什么样**(对应设计稿): + +``` +[缩略图 24px] [tag: div] [铅笔] [垃圾桶] +描述文本 +``` + +缩略图就是 `record.thumbnail`——保存批注时按 rect 裁剪的那张(D2),与消息里那张附件是同一张。窗口宽度不够时缩略图先让位(保持 tag + 文本),不撑破卡片。 + +**条数与滚动**(D3):卡片最多展示 **5 行**,超出部分在卡片内部滚动(`max-height` + `overflow:auto`,不是分页、不是折叠成数字)。底部聚合 chip `N 条注释` 可把整卡折叠/展开。跨页签时按页签分组,组头是该页标题/URL(`orphan` 组标「页面已关闭」)。 + +**铅笔:两条路径** + +路径 A —— 页签还活着: + +``` +点铅笔 + → selectAgentBrowserPage(page_id) // 激活页签 + → 若该页不在批注模式,隐式 start() // D8:要拉回,页面进入批注模式 + → open_record_popup{record_id} // 新 action + → 页内:目标滚动进视口 → 浮窗以「编辑已有记录」态打开 + · 描述框 value = record.description,光标置于末尾并 focus() + · 差异从 record.differences 还原成 draft,样式面板可用(「调整」显示) + · 图钉高亮,不新增编号 + → 保存 → update_description{record_id, description}(改过样式则整条替换)→ sync + 卡片刷新,编号不变 + → 取消 → 丢弃 draft,记录恢复原状 +``` + +路径 B —— 页签已关闭(`orphan`): + +``` +点铅笔 + → 无页签可激活 → 弹居中 modal(PageAnnotationEditDialog,视觉沿用浮窗) + → 只有:描述框 + 删除 + 取消 / 保存 + → 「调整」隐藏(adjustable=false) + → 保存 → update_description{record_id, description} → 卡片就地更新 + → target 冻结:locator / region / differences 全部只读展示,不允许改 +``` + +**`adjustable` 的判定只有一条**(两个入口共用,禁止各写一份): + +``` +adjustable = record.state === 'live' && 页签存活 && document_id 匹配 +``` + +`replayable` 也一并隐藏——重放还没成功,样式面板打开会读到错的 baseline,改出来的 `old_value` 就是脏的。 + +**D8 的副作用要认**:隐式 `start()` 会把页面拉进批注模式,用户之后在页面上点任何地方都会新建一条批注。这是有意为之——从卡片点铅笔的人本来就是来改批注的;且 `start` 会复位 `original` / `markers_hidden`,视图从"上次的临时状态"回到"批注中"的正常状态,比只开浮窗更符合预期。 + +**路径 B 为什么只能改文本**:没有 document、没有 baseline、没有能挂 `adoptedStyleSheets` 的地方。硬留「调整」按钮只能点了报错,所以直接不给。 + +**编辑途中页签被关掉(D7)**:不弹窗、不打断输入。浮窗里已敲的内容写进 `pageAnnotationDraftStore`(key `page_id + target_locator`),记录转 `orphan`,卡片行标「页面已关闭」;用户下次点这行的铅笔,直接进路径 B 的弹窗,描述原样还在。 + +**删除** + +- 行上的垃圾桶 = 删除这条**待发**记录(`delete_record`),`sync` 重排编号。 +- 立即生效 + 5s 撤销 toast(撤销按原位置插回、重排编号)。不做二次确认弹窗:批注是轻量草稿,弹窗打断比误删更烦。 +- `orphan` 记录的删除不需要页签,直接改会话存储。 + +**保存后的一致性**:一次编辑同时落到三处,靠一个事件扇出,禁止各自维护副本—— + +1. 原生 `SessionAnnotationStore`(权威) +2. 存活页签的图钉与预览(`sync`) +3. 输入框上方的卡片(store 订阅) + +**已发消息卡片只读**:不给铅笔、不给垃圾桶、不给「复制」、不给「回到页面修改」(D6:一个按钮都不给)。卡片本身只有「整屏截屏 + 页面标题 + `N 条注释`」,明细在悬停浮层里,浮层内的条目同样不可编辑。消息是 transcript,agent 已按旧描述执行过,能改就等于改历史;留一个「复制」只会让人以为下一步能改。用户想「改完再让 agent 做一次」,就是在页面上重新批注一条新的——这件事必须是显式的、留痕的。 + +### 4.12 记录标识与定位符(D9) + +**结论**:`record.id` 不能和文档绑定。现行 `:annotation:` 在刷新后结构性失效——`document_id` 内含自增 epoch(`page_annotation_session.hpp:213`),替换时 epoch+1 且 `document_id_` 清空(`:143-168`),记录 id(`:381`)指向一个不存在的文档代;页内 runtime 按 `document_id` 建键,换文档即 `dispose()`(`page_annotation_runtime.hpp:9-12`),图钉随之消失(`:359-375`),元素标识 `target-N` 是新 runtime 里重新数出来的序号(`:28, 217`)。完整因果链与实测见 `2026-11-22-html-page-annotations-t0-findings.md`。 + +``` +record.id = :annotation: // 会话内稳定,n 按 page_id 分组连续 +record.page_id = 所属页签 +record.page_url = 保存时的 URL(重放要求精确匹配) +record.document_id = 保存时的文档代(只用于判定 live / replayable,不做主键) +record.locator = 跨文档可用的结构定位符 +``` + +**`locator` 是新增字段**,`save` 时生成一次,之后只读。此前 `targets[].locator` 只有 `tag#id`(`page_annotation_runtime.hpp:97`),对没有 `id` 的元素退化成 `div`,撑不起 §4.6 的 `locate()`。生成顺序(逐级降级,取第一个稳定命中的): + +1. `data-testid` / `data-test` / `aria-label` 唯一命中; +2. CSS 结构路径:从目标到 `documentElement` 的 `tag:nth-of-type(k)` 链(跳过 `data-ace-*` 注入节点与批注 overlay); +3. 文本指纹:`tag` + 归一化文本前 80 字符的滚动哈希; +4. 同级索引:父路径 + `nth-of-type`,最弱,只在 1~3 都失败时用。 + +**`target.id`(`target-N`)只在同一 runtime 内有效**,不跨文档、不进主键;跨文档一律走 `locator`。 + +**`stale` 的判定不依赖 locator 命中率**:定位不到、定位到但实时值 ≠ `old_value`、文本节点结构变化,三者都判 `stale`(§4.6 的四条硬约束不变)。 + +--- + +## 5. 数据契约 + +### 5.1 记录 + +```json +{ + "id": ":annotation:", + "number": 3, + "page_id": "page-...", + "page_url": "http://127.0.0.1:5173/pricing?tab=2", + "page_title": "Pricing", + "description": "这个标题太小了", + "targets": [{ + "locator": "body>div#root>main>section:nth-child(2)>h2", + "tag": "h2", + "text": "Order summary", + "source": {"file": "/src/components/Card.tsx", "line": 42, "column": 7}, + "components": ["CardTitle", "Card", "App"] + }], + "differences": [ + {"target_id": "...", "property": "font-size", "old_value": "14px", "new_value": "18px"}, + {"target_id": "...", "property": "text", "old_value": "Order summary", "new_value": "订单摘要"} + ], + "region": null, + "state": "live", + "thumbnail": "data:image/png;base64,...", + "screenshot_unavailable": false, + "status": "pending" +} +``` + +`state`: `live | replayable | stale | orphan`。`number` 是**页内序号**(同一 `page_id` 分组内 1..n),跨页签混批时会重复,靠 `page_url` 消歧。`status` 不落记录:发送中由 `in_flight` 数组单独表示,已发送即从 `records` 删除。 + +`thumbnail`:**保存批注时**按目标 rect 裁剪的小图(宽 ≤512px,D2;卡片按 24px 渲染,消息里保持可读),待发卡片缩略图与消息附件共用它;`screenshot_unavailable: true` 表示保存时就没截到(目标在视口外 / 捕获失败)。`orphan` 记录不影响这两个字段——图在保存时就定格了。记录本身序列化进消息时**去掉 `thumbnail` 的 base64**,只留 `screenshot_ref` 指向附件。 + +### 5.2 消息载荷(嵌在消息文本里) + +沿用基线的承载方式:消息 `text` = `"Page annotations\n"` + JSON(`web/src/lib/pageAnnotationMessage.js:3`),截图作为普通 attachment 随消息(`contentParts` 的 image part)。用户同时敲了话时,`text` = `{用户文本}\n\nPage annotations\n{json}`;解析层按**末尾分隔段**识别,不再要求 `startsWith`。 + +```json +{ + "page": {"url": "...", "title": "..."}, + "annotations": [ /* 记录全文,含 state / target_invalid 标记 */ ] +} +``` + +- 不加 `type`/`id`:消息本身就是批注批次,解析层按文本头识别。 +- `annotations` 是冻结副本:页签关闭后仍完整可读。 +- 跨页签混批时 `page` 取第一条记录所在页(向后兼容),**每条记录自带 `page_url` / `page_title`(Q23)才是权威**;卡片与模型都按 `page_url` 分组。 +- 截图**按条一张**(Q25/Q28 + D2):直接取 `record.thumbnail`(保存时按 rect 裁剪),文件名 `page-annotations-.png`,与记录用 `screenshot_ref` 关联;无图的记录标 `screenshot_unavailable`(`orphan` 记录**不在此列**,它保存时已经截过)。 +- 一条消息只发一次 POST:用户文本与批注不会拆成两条(拆开会让 agent 多跑一轮 turn)。 + +### 5.3 模型侧所见 + +模型读到的就是消息 `text` 原文,即 `Page annotations` + JSON。字段含义: + +``` +page.url / page.title 当前页面 +annotations[].number 本轮展示序号 +annotations[].description 用户写的批注 +annotations[].targets[].locator 唯一 CSS 路径(重放/定位用) +annotations[].targets[].source {file,line,column}(React dev 才有,可能为 null) +annotations[].targets[].components 组件栈(prod 也有) +annotations[].differences[] {property, old_value, new_value} +annotations[].state live | replayable | stale +annotations[].target_invalid true = 记录来自别的文档,不要按当前 DOM 找 +``` + +--- + +## 6. 改动清单 + +### 原生 + +| 文件 | 改动 | +|---|---| +| 新增 `session_annotation_store.hpp` | 会话级待发集合:`records[]`(每条带 `page_id`/`page_url`/`page_title`/`state`/`thumbnail`)、`in_flight[]`、按 `page_id` 分组的 `next_number`;提供 `delete_record` / `update_description` / `adopt_orphans` | +| `page_annotation_session.hpp` | 记录四态替代 `valid`;记录读写转发到 `SessionAnnotationStore`,自身只留选区/预览/`document_id`;quiet/事务两档闸门;删除单条 + 重排;`sync` payload;`reapply` 编排;新增 `open_record_popup` / `update_description` / `delete_record`;`replace_document` 转 `replayable` | +| `page_annotation_runtime.hpp` | 增加 `sync` / `remove` / `reapply` 分支;`hide_markers` 改整层;保存时输出扩展 locator;打 `data-ace-hit-*`;移除内部编号逻辑 | +| `page_annotation_style_runtime.hpp` | baseline 改首次值;`apply` 支持重放层(与 saved/draft 分离) | +| `page_annotation_text_runtime.hpp` | `old_value` 基准改 `originals`;重放用 diff 应用 | +| `page_annotation_host_adapter.hpp` | 删除 `capture` / `validate` / `acknowledge` / `release` 分支;`screenshot` 从**发送链路移到 `save`**(视口捕获 + 按 rect 裁剪 + 缩到 128px) | +| `agent_browser_native_commands_win.cpp` | 缓存 `executionContextId`(只在 `replace_document` 后重建),省掉每命令 3 跳里的前两跳 | +| `agent_browser_capture_cdp.cpp` | 去掉 `captureBeyondViewport` + `cssContentSize` 整页路径;改为**视口捕获 + 按 rect 本地裁剪**(save 时调用一次) | +| `agent_browser_host_mac.mm` / `_win` | 去掉批次相关;**`close_page` 不再析构记录**,把该页记录转入 `SessionAnnotationStore` 的 `orphans` 并广播;状态事件改为广播会话内**所有**页签的 `annotations`(不再只发面板页签);`close_page` 时若有在途发送直接失败 | + +### 前端 + +| 文件 | 改动 | +|---|---| +| `PageAnnotationSendBar.jsx` | **保留发送按钮,换掉实现**:不再走 `pageAnnotationBatchSender`,改为调 composer 的 `submitWithAnnotations()`(Q35);按钮显示会话级总条数,禁用条件与输入框一致(`!sessionId` / 空批注且无文本 / 发送中);按住原图补 `blur`/`visibilitychange`、删掉键盘 Space/Enter 路径(Q2 修订:纯指针);`aria-pressed` 只留给隐藏标记 | +| 新增 `PageAnnotationPendingCard.jsx` | 输入框上方的待发卡片:按页签分组、每行 缩略图 + tag + 铅笔 + 垃圾桶 + 描述、底部 `N 条注释` chip | +| 新增 `PageAnnotationEditDialog.jsx` | `orphan` 记录的编辑弹窗:只有描述框 + 删除 + 取消/保存,`adjustable=false` 时隐藏「调整」 | +| 新增 `pageAnnotationPendingStore.js` | `session_id → page_id → records` + `orphans[]`,订阅原生状态事件,供卡片与弹窗读取 | +| `PageAnnotations.jsx` | `read` 失败不终止轮询;按住期间浮窗 `inert`;草稿按 page+locator 暂存;挂载无条件 `read` 一次;`Enter`=添加 / `Shift+Enter` 换行;浮窗支持「编辑已有记录」态(描述回填 + `focus()` + 图钉高亮) | +| `pageAnnotations.js` | 去掉批次相关;新增 `reapply`;controller 支持 quiet 命令并发 | +| `pageAnnotationBatches.js` | **删除**,替换为 `pageAnnotationMessage.js`(载荷构造 + 解析 + 发送确认;截图在 save 时已由原生生成,此处不做裁剪) | +| `pageAnnotationMessage.js` | 解析放宽到「末尾 `\nPage annotations\n` 分隔段」;卡片按 `page_url` 分组;保留 `comments[]` 形状以兼容现有测试 | +| `PageAnnotationMessageCard.jsx` | **只读**:载荷解析 + 渲染「整屏截屏 + 页面标题 + `N 条注释`」;悬停标签浮出明细(元素标签 + 描述,最多 5 条,超出滚动);不加任何按钮 | +| 新增 `pageAnnotationDraftStore.js` | 内存 Map(`page_id + target_locator` → 描述草稿),跨 `document_id` 存活 | +| `lib/selectionChatContext.js` | 不改(`page_annotation` 不走 `contexts`) | +| `ChatView.jsx` | 消息卡片渲染分发(只读快照,不读写 composer 状态);**发送时把待发批注并入本次 POST**(用户文本 + payload 合并一条) | + +### 服务端 + +| 文件 | 改动 | +|---|---| +| `routes_sessions.cpp` | 删除 `annotation_batch_id` 字段校验与 `annotation_batch_not_accepted` 404 分支;新增 `GET /api/sessions/:id/messages?client_message_id=` 查询(读 `metadata`,供 40s 超时自查) | +| `openai_provider.cpp` / `anthropic_provider.cpp` | 不改(JSON 在消息 text 里,模型直接读) | + +--- + +## 7. 删除清单 + +- `annotation_batch_id` 全链路(前端、请求体、`metadata` 落库) +- `reconcileOnly`、`annotation_batch_not_accepted`(404 协议) +- 原生 `capture` / `validate` / `acknowledge` / `release` 与 `AnnotationNavigationGuard` 租约 +- `pageAnnotationBatches.js` 及其测试 +- `PageAnnotationSendBar` 里的「重试」按钮语义(失败就是失败,用户重按一次) +- 批次级整页截图 + `fullPage` 断言 +- 页内工具栏**旧发送链路上的** `pageAnnotationBatchSender` 调用与「发送中/重试」三态文案(按钮保留,改为触发 composer 提交) +- 消息卡片的**全部按钮**(「回到页面修改」「复制」「重发」)——已发消息只读 +- `PageAnnotationSession` 里的 `records` / `next_number` 成员(上提到 `SessionAnnotationStore`) +- `close_page` 里的 `pages.erase(page_id)` 记录析构路径 + +--- + +## 8. 测试矩阵 + +| 层 | 用例 | +|---|---| +| 原生模型 | 四态转换;删除后重排;`discard` 归 1;`replace_document` 转 `replayable` 且编号保留;quiet 命令不占 `busy_`;并发 `read` + `preview_style` 不互相拒绝;`in_flight` 不计入 `pending_count` 且不参与 `sync`/重放;**关页签 → 记录转 `orphan` 而非析构**;`orphan` 不参与 `sync`;按 `page_id` 分组编号 | +| 页内 runtime(node:test + vm) | `sync` 幂等;整层 `hide_markers`;原图态图钉隐藏、释放恢复;`reapply` 的值相等闸(相等写入 / 不等标 stale);**观察窗口内元素晚到仍能补上**;文本 diff 重放;`Enter`=save / `Shift+Enter` 换行;`open_record_popup` 回填描述 + `focus()` + 滚动进视口 | +| 前端 | 按住三路径(up/cancel/leave)+ 两路兜底(blur/visibilitychange)+ **键盘不触发**(空格与 Enter 均不进 `held`);read 失败后循环仍继续;草稿按 `page+locator` 跨 `document_id` 暂存;待发卡片跨页签聚合;`adjustable` 判定(live 才 true,replayable/stale/orphan 全 false);铅笔路径 A(激活页签 + 打开浮窗)/ 路径 B(弹窗,无「调整」);删除 + 5s 撤销;发送→`in_flight`→确认清空 / 40s 自查(查到即成功、查不到才回滚);**三触发点等价**(输入框 / 工具栏 / `Ctrl+Enter` 各触发一次,断言 `submitWithAnnotations` 调用参数完全一致,且只产生一次 POST) | +| 集成 | save → 导航 → reapply → 编号不变;**关页签 → 卡片仍在 → 弹窗改文本 → 仍可发送(有图,图是 save 时那张)**;跨页签混批发一条消息;多会话各自页签互不影响;发送中关页签不阻塞;用户文本 + 批注合并成一条消息且解析正确;**发送阶段零捕获**(断点确认不再调 `captureScreenshot`) | +| 契约 | `Page annotations` 文本头 + payload 的前后端解析一致(构造端与 `parsePageAnnotationMessage`,含「用户文本在前」的形态);`composer_content` 封闭枚举未被触碰;已发消息无任何可写入口 | +| 冒烟 | Windows 真实 WebView2:按住原图无闪烁、无卡死;mac:视口外目标发送不报错、明示未附图 | + +--- + +## 9. 风险与未决 + +### 9.1 风险 + +| 风险 | 说明 | 缓解 | +|---|---|---| +| 记录上提改动面大 | `records` 从 `PageAnnotationSession` 挪到会话级,牵动发送、重放、`sync`、编号、序列化 | 先做纯搬运(行为不变)一次性落地,再加 `orphan`;两批分开评审 | +| 跨页签编号重复 | 每页从 1 开始,混批后消息里出现多个 `#1` | 每条自带 `page_url`(Q23);卡片与模型都按页分组;`number` 只在页内唯一 | +| 重放盖住真实改动 | 值相等闸已覆盖「值变了」的情况,但整块结构重排仍可能误配 | 重放失败一律 stale,不猜 | +| 源文件定位失真 | dev 路径映射到 workspace 可能错文件;页面可伪造返回 | 只作提示 + 必须确认 + 定位不到就停 | +| mac 截图覆盖不足 | 保存时目标在视口外就拿不到快照(Q31 从"发送时降级"前移到"保存时降级") | UI 明示;卡片退化为 tag + 文本片段;发送时该条无附件 | +| `sync` 频率 | 每次增删一次全量下发,Windows 3 跳 CDP;现在还要广播给所有页签 | 缓存 `executionContextId`;quiet 档不排队;只给**有记录变化**的页签发事件 | +| 会话归档后的孤儿页 | 页签保留但会话不可见,记录长期占内存 | 本期接受(用户明确要求页签不随归档关闭) | +| 误发不可逆 | 直发无二次确认(Q35),误点即让 agent 开始改代码 | 三个触发点都是用户熟悉的发送动作;按钮上显示总条数;不做隐藏手势 | +| 发送重试可能重复 | 40s 超时后若实际已落库,会重发 | U5 自查兜住主要路径;`client_message_id` 查询本身失败时按「未知」处理——不回滚,只提示 | +| `orphan` 记录越积越多 | 页签关掉后记录留在内存,用户也没地方看见(卡片折叠时) | 卡片默认展开;会话关闭即清空;`orphan` 记录带「页面已关闭」标记 | + +### 9.2 未决问题:0 条 + +原先的 8 条细节问题(D1–D8)已全部裁决,按「问题 / 裁决 / 影响」记在 **§1.1**,不再单列。评审时若要翻旧账,看那里。 + +已定且刻意记录在案的(避免复评审时又被当成"还没想清楚"): + +| 曾经的问题 | 现在的位置 | +|---|---| +| 记录归属页签还是会话 | Q33 修订:归属会话,页签是渲染/编辑端点 | +| 发送入口在哪 | Q35 修订(二次):组装唯一在 composer,触发三处(输入框 / 工具栏 / 浮窗 Ctrl+Enter) | +| 已发消息能不能改 | U3:不能,卡片只读、一个按钮都没有 | +| 40s 无确认怎么办 | U5:先按 `client_message_id` 自查再回滚 | +| 浮窗 `Ctrl+Enter` 语义 | U4:保存当前 + 发送整批 | +| 用户文本与批注发几条 | §3.4:合并成一条 | +| 截图何时截 | Q25/Q28 + D2:保存时截,发送时只上传 | + +--- + +## 附录 A:竞品对照 + +| | 元素 → 源码 | 预览跨刷新 | 截图 | +|---|---|---|---| +| t3code | preload 主 world + `_debugSource` / `_debugStack`,输出 dev 路径但不归一化 | **不保留**(`teardown` 主动还原) | 视口捕获 + 本地裁剪,视口外返回 null | +| Agentation | `__reactFiber$` → `_debugSource`,dev-only | 不适用(无预览改值) | 无 | +| Cursor Design Mode | 组件名 + 组件栈 + xpath + fiber props(官方文档),不承诺 file:line | 文档:Apply 才写源码 | 保存时裁剪到元素 | +| Codex | 未公开 | **重放**(观察:刷新后旧值→新值闪烁) | 未公开 | diff --git a/docs/specs/2026-11-22-html-page-annotations-legacy-branch-map.md b/docs/specs/2026-11-22-html-page-annotations-legacy-branch-map.md new file mode 100644 index 000000000..4b722bac0 --- /dev/null +++ b/docs/specs/2026-11-22-html-page-annotations-legacy-branch-map.md @@ -0,0 +1,121 @@ +# HTML 网页批注 —— 已实现未合并代码 × 旧 spec 映射 + +- 日期:2026-11-22 +- 目的:回答「这批已写、未进主干的批注代码,对应哪份 spec、由哪个分支/文件实现、新方案下留还是弃」 +- 旧 spec:`openspec/changes/add-html-page-annotations/specs/html-page-annotations/spec.md`(11 条 Requirement,已标 Superseded) +- 新方案:`openspec/changes/redesign-html-page-annotations/`(10 条 Requirement) +- 对照基线:`docs/specs/2026-11-22-html-page-annotations-wip-alignment.md` + +--- + +## 0. 先纠正一个前提 + +**主干里一行批注代码都没有。** 实测: + +| 检查 | 结果 | +|---|---| +| `origin/master`(`0b862f32`)中 `page_annotation*` / `pageAnnotation*` 文件数 | **0** | +| `origin/master` 中 `openspec/changes/add-html-page-annotations/` | **不存在** | +| 当前分支 `codex/html-page-annotations`(`b5a2d5c4`)相对 master | **ahead 30 / behind 0** | +| 该分支中批注相关文件 | 29 个(另加工作区 4 个未跟踪模块) | + +所以「#194 已合入 master」只成立于 PR 层面的讨论,代码层面 master 是干净的。**整条批注功能是一次性、待合并的 30 个提交 + 51 个未提交改动。** + +## 1. 分支拓扑:十个分支是同一份代码的递进快照,不是可分别合并的十条线 + +十个分支全部从 `0155a863` 拉出,**内容上层层累积**:194 是地基,195/196/197 是三条互斥的能力增量,199 接发送链路,200 把 194–199 合流,201 再加截图布局,`annotation-send-seam-fixes` 是最终快照。 + +| 分支 | commit | 相对 194 的增量 | 主题 | 与当前 HEAD 的关系 | +|---|---|---|---|---| +| `…-194` | `c4e9a59a` | —(基线 +1680) | 工具栏入口、元素单击开卡、isolated world 注入、session 雏形 | 内容已吸收 | +| `…-195` | `a89c3338` | +1170 / −247 | 样式面板 + `page_annotation_style_runtime.hpp`(213) + popup 测试(163) | 内容已吸收 | +| `…-196` | `26917e51` | +727 / −242 | 文本预览 + `page_annotation_text_runtime.hpp`(148) + text smoke | 内容已吸收 | +| `…-197` | `3fa087b6` | +610 / −302 | 多目标 + 单区域 + `page_annotation_targets.hpp`(44) | 内容已吸收 | +| `…-199` | `f28429c6` | +2365 / −240 | 发送链路:`agent_browser_capture.hpp`(205)、`pageAnnotationBatches.js`(148)、服务端提交协议 | 内容已吸收 | +| `…-200` | `d4347848` | +7209 / −805 | 导航/轮询/host 适配器拆分(含 195–199 全部) | 内容已吸收 | +| `…-201` | `5752ff65` | +8815 / −827 | 截图布局、集成 driver、租约测试(201 ⊃ 200) | 内容已吸收 | +| `annotation-receiver` | `7a172eb5` | +793 / −1(纯服务端) | 服务端原子接收回执,无前端改动 | 内容已吸收 | +| `annotation-send-seam-fixes` | `d298130f` | +10398 / −348 | **全量最大快照**:capture layout(208)、session 测试(806)、回执分类 | 核心文件逐字一致 | +| `html-annotations-native-boundaries` | `c1b57f80` | +3701 / −277 | 原生捕获边界抽取 + standards gate | 内容已吸收 | + +验证方式: +- `git diff --numstat` 显示 194→200 的增量覆盖了 195/196/197/199 的全部产物,201 ⊃ 200,`annotation-send-seam-fixes` ⊃ 201; +- `git diff HEAD -- <核心文件>` 对 `page_annotation_session.hpp`、`page_annotation_host_adapter.hpp`、`page_annotation_poller.hpp`、`page_annotation_navigation.hpp`、`pageAnnotationBatches.js`、`pageAnnotations.test.js`、`page_annotation_session_test.cpp` 全部返回空; +- `comm` 比对显示这些分支**没有任何 HEAD 缺失的批注文件**。 + +**结论:十个分支都已经在内容上并入 `codex/html-page-annotations`,没有一条还有「待合并的独立工作」。** 它们只能当「某阶段代码长什么样」的只读参照;真正待处理的是当前分支那 30 个提交 + 51 个未提交改动。 + +## 2. 旧 spec 11 条 Requirement × 实现 × 新方案判定 + +判定口径:**保留**=新方案下行为不变;**改造**=代码留、行为改;**废弃**=删净。 + +| # | 旧 Requirement | 主要实现(文件 / 行数) | 判定 | 新 spec 对应 | ticket | +|---|---|---|---|---|---| +| R1 | Desktop page annotation controls | `page_annotation_bridge.cpp`(30)、`agent_browser_host.cpp` 注入、`PageAnnotations.jsx`、`AgentBrowserPanel.jsx` | **保留**(入口形态不变);工具栏按钮清单要改 | 「发送组单一、触发多路」 | #213 | +| R2 | Pointer-accurate annotation surface | `page_annotation_runtime.hpp` hover 段、`page_annotation_style_runtime.hpp`(213)、`pageAnnotationPopup.test.js`(163)、**工作区** `PageAnnotations.jsx` +1024 / `globals.css` +878 | **保留**(样式面板整块留,D8 要求);hover 需在 hidden/original 态抑制 | 「按住看原图只认指针」 | #220 | +| R3 | Reversible actual-change previews | `page_annotation_runtime.hpp` preview 段、`page_annotation_text_runtime.hpp`(148)、`PageAnnotationTextField.jsx` | **保留**;`original` 态改纯指针,删键盘路径 | 同上 | #220 | +| R4 | Multiple targets and one region | `page_annotation_targets.hpp`(44)、`PageAnnotationTargets.jsx`(26)、runtime +132/−25 | **改造**:多目标/单区域留;「已保存不可编辑不可删」被 Q36 推翻 | 「逐条编辑批注」 | #217 #218 | +| R5 | Acknowledged conversation batches | `pageAnnotationBatches.js`(148)、`page_annotation_submission.hpp`(47)、`agent_browser_capture.hpp`(205)、`annotation_submission_request.hpp`(55)、`routes_sessions.cpp`、`domain/session/annotation_submission.hpp`、agent worker/queue、`page_annotation_poller.hpp`(89) | **废弃**(整条链路);仅 `client_message_id` 自查可留 | 「发送超时自查」 | #214 #215 | +| R6 | Page lifecycle and invalidation safety | `page_annotation_navigation.hpp`(88)、`page_annotation_host_navigation.hpp`(101)、`page_annotation_requests.hpp`(61)、`page_annotation_navigation_test.cpp`(250) | **改造**:导航提示留;`valid:bool` → 四态;关页签转 orphan | 「记录状态」「关闭页签不丢批注」 | #209 #211 | +| R7 | Native overlay edge fidelity | **工作区** `agent_browser_host.cpp` +13、`_mac.mm` +110、`windows_helpers.cpp` +30、`agentBrowserSurfaceCoordinator.js` +209;`html-annotations-native-boundaries` 分支的边界抽取 | **保留**(纯几何) | 无对应条款(隐含能力) | — | +| R8 | Layered modal suspension / native input blocking | **工作区** `interaction_blocked` → `EnableWindow(FALSE)`、`annotationChromeSuspension.js`(新)、`Modal.jsx` +16 | **保留**(两套互补,见 wip-alignment §4.2) | 无对应条款 | — | +| R9 | Send feedback and error localisation | `localizedSendError`(在 batches 内)、i18n `sourceCatalog.generated.js`、`请先选择对话` 内联 | **改造**:错误映射要重挂到 `submitWithAnnotations`;「截图正在进行中」失效;「已复制截图」随按钮删 | 「发送组单一、触发多路」 | #213 | +| R10 | Annotation message presentation | **工作区** `PageAnnotationMessageCard.jsx`(新)、`pageAnnotationMessage.js`(新)、`Message.jsx` +31 | **改造**:卡片只读化;解析放宽为末尾分隔段;修 `Message.jsx:369-376` 吞文本 | 「已发消息只读」 | #219 | +| R11 | Acceptance and compatibility | `html-page-annotations-acceptance.md`、`capture_test.cpp`(272)、`native_boundaries_test.cpp`(198)、`navigation_test.cpp`(250)、`session_test.cpp`(531)、`integration_driver.cpp` | **改造**:框架与运行器留,用例按新流程重写 | — | #208 | + +### 汇总 + +| 判定 | 条数 | 说明 | +|---|---|---| +| 保留 | 5(R1/R2/R3/R7/R8;R2、R3 有局部改动) | 样式面板、表面几何、模态阻断、预览能力 | +| 改造 | 5(R4/R6/R9/R10/R11) | 幅度从「加四态」到「换错误挂点」不等 | +| 废弃 | 1(R5) | 整条批次/回执/租约链路,约 700 行 + 服务端 3 文件 | + +## 3. 只在未提交工作区里、分支上拿不到的 + +这几块是 201 之后才做的打磨,**十个分支里都没有**: + +| 文件 | 内容 | 为什么重要 | +|---|---|---| +| `PageAnnotations.jsx` +1024 | 间距锁、色板、字体建议、拖拽 `adjustBounds`、透明度 | 样式面板的完整实现,D8 要求保留 | +| `globals.css` +878 | 浮窗 / 工具栏 / 卡片视觉与动效 | 同上 | +| `agentBrowserSurfaceCoordinator.js` +209 | `occlusionSquareCorners`、`overlayBleed`、同半径合并 | R7 的实际实现 | +| `annotationChromeSuspension.js`(新) | WebUI 侧 chrome 暂停 | R8 的一半 | +| `pageAnnotationMessage.js`(新) | 解析 / 复制 / 截图剥离 | R10 的载体 | +| `PageAnnotationMessageCard.jsx`(新) | 已发消息卡片 | R10 | +| `agent_browser_host_mac.mm` +110 | 每角独立半径 | R7 mac 侧 | + +含义:**这批改动一旦丢弃,样式面板与表面几何要重写约 2600 行。** 这是「先把 WIP 提交为基线」(tasks.md P0)的实际理由。 + +## 4. 现成可复用 vs 必须放弃 + +### 可直接复用(新方案不改行为) + +- 原生遮挡孔:`radius` / `square_corners` 位掩码 / `overlayBleed` / 每角独立半径 +- 模态阻断:`interaction_blocked` → `EnableWindow(FALSE)` + `annotationChromeSuspension` 双套 +- 样式面板全部控件与测试(`pageAnnotationStyles.browser.test.js` 215 行) +- 文本预览与文本节点保留(`page_annotation_text_runtime.hpp`) +- 多目标 + 单区域数据结构(`targets[]`) +- 导航提示(`page_annotation_navigation.hpp`)—— 只要把「默认停留」与「从不自动发送」保留 +- 验收运行器与 fixture(`html_annotation_fixture.html`、`integration_driver.cpp`) + +### 必须放弃(新方案直接冲突) + +| 对象 | 冲突点 | +|---|---| +| `pageAnnotationBatches.js` + `.test.js` | Q26:批次状态机、截图、回执对账、`fullPage` 断言全部删 | +| `annotation_batch_id`(全仓 43 处) | 批次身份不再存在 | +| `reconcileOnly`(11 处) | 服务端 404 对账协议取消,改 `client_message_id` 自查 | +| 原生租约 `capture` / `validate` / `acknowledge` / `release` | 状态机已取消 | +| 工具栏「截取屏幕截图」按钮 | D2:截图在 save 时按 rect 裁剪 | +| 工具栏「发送中 / 重试」三态 | Q35:回执状态统一由 composer 广播 | +| 「已保存批注不可编辑不可删」 | Q36 | +| `page_annotation_session.hpp` 的 `records_` 归属 | Q33:上提到 `SessionAnnotationStore` | +| `valid: bool` | 四态 `live / replayable / stale / orphan` | + +## 5. 落地建议 + +1. **先 P0**:把当前 51 个改动提交成一条 `wip:` 提交(或推到 `wip/html-page-annotations` 分支)。否则 #209 的搬运 diff 会混在 4445 行里,评审无法分辨。 +2. **分支只读**:十个分支保留作历史参照,不合、不删、不再往上加东西。它们的内容都已在当前分支里,合过来只会产生空 commit 或冲突噪音。 +3. **按 ticket 重做,不按分支合**:#208 先出记录标识结论(`record_id` 在 HMR 换 `document_id` 后失配的隐患),再开 #209。 +4. **合入策略**:#209–#220 全部落在 `codex/html-page-annotations` 上,最后一个 PR 整体对 master。中间不要分十次 PR——它们互相依赖且会把 30 个提交的历史切成碎片。 diff --git a/docs/specs/2026-11-22-html-page-annotations-prd.md b/docs/specs/2026-11-22-html-page-annotations-prd.md new file mode 100644 index 000000000..4db5e7291 --- /dev/null +++ b/docs/specs/2026-11-22-html-page-annotations-prd.md @@ -0,0 +1,293 @@ +# HTML 网页批注 · 产品需求文档 + +| 项目 | 内容 | +|---|---| +| 版本 | v1.0(2026-11-22) | +| 状态 | 待评审 | +| 范围 | 桌面端 · Agent 浏览器内网页 | +| 关联 | 需求基线 `2026-11-21-...-rewrite-requirements.md`、技术设计 `2026-11-21-...-technical-design.md` | + +--- + +## 1. 一句话 + +让用户不用描述「那个标题再大一点」,而是**直接在网页上圈出来**,写完想怎么改,一次发给 AI。 + +## 2. 为什么做 + +现在用户想让 AI 改一个网页的样式或文案,只能用文字说。模型猜错一轮,用户要重新解释一遍,来回三四次才对齐。批注功能把「指哪里」和「改什么」变成可点选、可预览、可发送的一件事。 + +当前版本有三个具体的坑,用户已经在踩: + +**坑一:关掉页签,写到一半的批注全没了。** +用户常常一边看页面一边在对话里问问题,顺手关掉用不上的页签。回来发现批注和描述一起消失,只能从头再标一遍。 + +**坑二:两个发送按钮是两套东西。** +页面工具栏上的发送只发页面上的批注,看不见用户在输入框里刚敲的话;输入框的发送又不知道有批注在等。用户从哪头发、发出去的是什么,全凭记忆。 + +**坑三:发送失败会让 AI 把同一处改两遍。** +网络抖一下、确认消息丢一次,界面就回滚,用户以为没发出去又点一次。而消息其实已经入库,模型收到两条一样的批注,把同一处改了两遍。 + +## 3. 目标用户与场景 + +| 维度 | 说明 | +|---|---| +| 谁 | 在桌面端让 AI 修改网页(HTML / CSS)的用户 | +| 什么时候 | 看到页面某处不满意,想说清楚「就是这里」 | +| 前置条件 | 桌面端已打开一个网页预览,且处于某个对话会话中 | +| 成功的样子 | 用户标 2–3 处、写两三句话、按一次发送,AI 一次改对 | + +## 4. 三个核心概念 + +| 概念 | 含义 | +|---|---| +| **批注** | 页面上的一条标记:一个编号图钉 + 描述 + 可选的样式调整 | +| **待发** | 还没发出去的批注。集中在输入框上方的一张卡片里,跨页签可见 | +| **已发** | 变成聊天记录里的一张卡片,只读,不能再改 | + +## 5. 一次完整的使用(界面分镜) + +1. 用户在网页上点「批注」进入批注模式,页面出现工具栏。 +2. 鼠标滑过元素,元素出现轮廓,旁边浮出小卡片:标签名、尺寸、颜色、字体。**不点也能先看清是什么。** +3. 单击元素,弹出批注浮窗,可以写描述。 +4. 需要改样式时点「调整」,改字号、颜色、间距……**页面上立刻看到效果**,不是改完才知道。 +5. 点保存,元素上出现编号图钉,输入框上方出现这条待发批注。 +6. 继续标第二处、第三处,甚至切到另一个页签标。**关掉页签也不丢。** +7. 在输入框里写「这几处一起改」,按发送。三处批注 + 这句话作为**一条消息**发出。 +8. 聊天里出现批注卡片:页面标题、每条描述、每条的截图。AI 按图改。 + +## 6. 功能需求 + +### 6.1 批注模式与工具栏 + +- 进入批注模式后,页面上浮一个工具栏,随页面滚动保持可见,可拖动位置。 +- 工具栏提供五个动作:**发送、隐藏标记、按住看原图、丢弃全部、退出批注模式**。 +- 「隐藏标记」是开关:打开后所有图钉和预览效果隐藏,再点恢复。 +- 「按住看原图」:**按住按钮**时页面回到修改前的样子,松开恢复。只有按住这一种方式,没有快捷键。 +- 「丢弃全部」需要二次确认,确认后清空**当前页面**的批注(其他页签的不受影响),该页编号从 1 重新开始。 +- 「退出批注模式」只收起编辑控件,已保存的图钉和预览效果保留。 +- 浮窗打开时工具栏隐藏,避免挡视线。 + +### 6.2 选中与浮窗 + +- 单击元素即打开浮窗,不需要先点「批注」再点元素。 +- 鼠标移出页面、窗口失焦、切到后台时,悬停轮廓与信息卡立即消失,不会留在页面上。 +- 打开任何菜单或弹窗时,页面的轮廓与信息卡暂停显示,关闭后恢复,且只恢复一次。 +- 浮窗可以拖动;表头与底部按钮固定,中间属性区可滚动。 +- 描述最多 4096 字。 + +### 6.3 样式调整与实时预览 + +支持调整:文字内容、字体、字号、字重、字距、词距、文字颜色、背景色、透明度、圆角、边框颜色与粗细、宽高、内外边距、行间距与列间距。 + +- 所有调整**实时预览**,所见即所得。 +- 只记录真正发生变化的属性,没改的不写。 +- 取消只回滚这一次的改动,之前保存过的批注和预览不受影响。 +- 宽高锁定默认关闭;打开后按当前宽高比联动。 +- 内外边距支持四边分别设置,也支持上下、左右成对联动。 +- 每个改过的属性都可以单独恢复原值。 + +### 6.4 待发批注卡片 + +- 位置:输入框正上方。 +- 按页签分组,组头是页面标题;编号在组内连续。 +- 每条显示:截图缩略图、元素标签、描述。 +- 超过 5 条时卡片内部滚动,不把输入框顶走。 +- 每条右侧有铅笔(编辑)和垃圾桶(删除)。 +- 删除立即生效,**5 秒内可撤销**,撤销后恢复原编号。 + +### 6.5 编辑一条待发批注 + +- **页签还开着**:点铅笔 → 自动切到该页签、回到批注模式、打开这条的浮窗,描述回填、光标在末尾;「调整」可用,可以继续改样式。 +- **页签已关闭**:点铅笔 → 弹出只有描述框、删除、取消/保存的对话框;没有「调整」(页面没了,无法比对样式);目标定位信息只读。 +- **编辑途中页签被关**:已输入的内容保留为草稿,这条转为「页面已关闭」,下次点铅笔继续编辑。 + +### 6.6 发送 + +**只有一个发送动作,三个入口**: + +| 入口 | 触发 | +|---|---| +| 输入框的发送按钮 | 点击 | +| 页内工具栏的发送按钮 | 点击(按钮上显示会话级待发总条数) | +| 浮窗描述框 | `Ctrl+Enter`(先保存当前这条,再发送) | + +三者**完全等价**,都是「输入框里的文字 + 本会话全部待发批注」,发成**一条**消息。不会出现「工具栏只发批注、输入框只发文字」的情况。 + +- 提交范围是**整个会话**:包括其他页签的批注、已关闭页签的批注。 +- 输入框里没写的文字就空着,只发批注;两者都为空时发送按钮禁用。 +- 发送过程中用户切换页签、继续加批注,不影响已发出去的那批;新加的留到下一次。 + +**超时与重复**:发出后 40 秒没收到确认,系统先自己去查「这条消息到底进没进去」,再决定怎么办。 + +| 情况 | 处理 | +|---|---| +| 查到了 | 视为成功,清空待发,不产生重复消息 | +| 查不到 | 批注退回待发、重排编号、恢复图钉,提示可重试 | +| 查询本身失败 | 不回滚,提示「可能仍在发送」,由用户决定重试还是撤销 | + +### 6.7 已发消息 + +消息在聊天里是一张卡片,每张截屏配一行说明: + +``` +┌────────────────────────────────────┐ +│ │ +│ 页面截屏(单击看大图) │ +│ │ +└────────────────────────────────────┘ + 商品详情页 [ 3 条注释 ] +``` + +**卡片结构**: + +1. **页面截屏** —— 被批注页面(右侧预览区)的画面。单击打开大图。 +2. **截屏下方一行** —— 左边是页面标题(小字),右边是 `X 条注释` 标签。X 是这一页的批注数量。 + +卡片本身没有其他按钮,也没有逐条展开的列表,保持安静。 + +**悬停标签看明细**:鼠标停在 `X 条注释` 上,浮出这一页的注释列表。 + +- 每条一行:左边是 HTML 元素类型(`div`、`input`、`p` 等),右边是这条批注的意见。 +- 默认最多显示 5 条;超过 5 条时列表内部滚动,不把浮层撑高、不顶走聊天。 +- 一条批注标了多个目标时,元素类型取主目标。 + +其他规则: + +- 只有一条注释时标签写 `1 条注释`,悬停仍然显示那一行。 +- **一条消息涉及多个页面时**,卡片按页面依次堆叠「截屏 + 标题 + 标签」,每张图只显示自己那一页的注释,hover 也只展开该页的条目。 +- 截屏获取失败时,保留标题与标签,不放占位图或碎图。 +- 卡片内**没有任何操作按钮**:不能编辑、不能删除、不能回到页面修改。 +- 复制整条消息时得到纯文本摘要(页面标题 + 每条的元素类型与意见),不是原始数据。 + +### 6.8 异常与状态 + +每条批注有四种状态,决定它能做什么: + +| 状态 | 用户看到 | 能做什么 | +|---|---|---| +| 生效中 | 图钉正常显示,预览可见 | 改描述、改样式、发送 | +| 待恢复 | 页面刷新后暂时没画上图钉 | 系统自动重放;成功后回「生效中」 | +| 已失效 | 图钉标为失效 | 只能改描述、删除、发送(消息里标注目标已失效) | +| 页面已关闭 | 卡片上标「页面已关闭」 | 只能改描述、删除、发送(消息里标注目标已失效) | + +其他规则: + +- 页面要刷新或跳转时,如果还有没保存或没发送的批注,先提示,默认「留在当前页」,**从不自动发送**。 +- 页面刷新后,能重新定位到元素的批注自动恢复图钉;如果该元素当前的值已经被别人改过,标为「已失效」,不覆盖。 +- 元素被删除时,标为「已失效」,**不会去找一个长得像的元素替代**。 +- 没有可用会话时,发送按钮禁用并提示「请先选择对话」,而不是点了才报错。 +- 所有错误都显示中文产品文案,不出现英文报错或机器码。 + +## 7. 用户故事 + +1. 作为一个要改网页的用户,我想直接在页面上点出要改的元素,这样我不用描述「左边那个灰色的小字」。 +2. 作为一个要改网页的用户,我想在单击前就能看到元素是什么标签、多大、什么颜色,这样我点之前就知道有没有点错。 +3. 作为一个要改网页的用户,我想一次标好几处再一起发,这样 AI 能一次改完,不用来回三轮。 +4. 作为一个要改网页的用户,我想在标的同时写一句话说明整体意图,这样 AI 知道这几处是同一个诉求。 +5. 作为一个要改网页的用户,我想改完样式立刻看到效果,这样我不用发出去才发现不合适。 +6. 作为一个要改网页的用户,我想取消这次调整时不影响之前保存的批注,这样我敢反复试。 +7. 作为一个要改网页的用户,我想把改过的属性单独恢复原值,这样我不用重新调一遍。 +8. 作为一个要改网页的用户,我想按住按钮就能对比改前改后,这样我能判断改得对不对。 +9. 作为一个要改网页的用户,我想临时隐藏所有标记看干净效果,这样我能判断页面整体观感。 +10. 作为一个要改网页的用户,我想退出批注模式但保留已标的批注,这样我能正常浏览页面。 +11. 作为一个要改网页的用户,我想关掉页签后批注还在,这样我不用因为整理页签而重标一遍。 +12. 作为一个要改网页的用户,我想在输入框上方看到所有待发批注,这样我知道这次会发出去什么。 +13. 作为一个要改网页的用户,我想看到待发批注按页面分组,这样多个页面的批注不会混在一起。 +14. 作为一个要改网页的用户,我想在卡片上看到每条批注的缩略图,这样我能确认是哪一处。 +15. 作为一个要改网页的用户,我想点铅笔回到页面上继续改,这样我不用重新找到那个元素。 +16. 作为一个要改网页的用户,我想页签关掉后还能改描述,这样我发现写错了还能补救。 +17. 作为一个要改网页的用户,我想删除一条标错的批注,这样它不会跟着发出去。 +18. 作为一个要改网页的用户,我想删除后 5 秒内能撤销,这样误点不至于重标。 +19. 作为一个要改网页的用户,我想在输入框和工具栏上都能发送,且结果一样,这样我不用记哪个按钮发什么。 +20. 作为一个要改网页的用户,我想在写描述时按 `Ctrl+Enter` 直接发出去,这样我不用来回切鼠标。 +21. 作为一个要改网页的用户,我想发送按钮上显示还有几条没发,这样我不会漏发。 +22. 作为一个要改网页的用户,我想一次发出会话里所有批注(包括别的页签的),这样我不用逐个页签去发。 +23. 作为一个要改网页的用户,我想输入框里的文字和批注一起发出去,这样 AI 能同时看到「哪里」和「为什么」。 +24. 作为一个要改网页的用户,我想批注和文字只产生一条消息,这样对话记录不会被打断成两条。 +25. 作为一个要改网页的用户,我想发送时不用等截图,这样点发送就是立刻发出去。 +26. 作为一个要改网页的用户,我想每条批注都带自己的截图,这样 AI 看到的就是我指的那一处。 +27. 作为一个要改网页的用户,我想目标在屏幕外时也能保存批注,这样我不用为了截图先滚到那个位置。 +28. 作为一个要改网页的用户,我想发送卡住时系统先自己确认,这样我不会因为重发而让 AI 改两遍。 +29. 作为一个要改网页的用户,我想确认失败时能选择重试或撤销,这样我能控制结果。 +30. 作为一个要改网页的用户,我想在聊天里看到当时页面的截屏,这样我一眼能认出是哪个页面、改成了什么样。 +31. 作为一个要改网页的用户,我想单击截屏看大图,这样我能确认细节。 +32. 作为一个要改网页的用户,我想悬停「X 条注释」就看到每条的元素类型和意见(最多 5 条,多了滚动),这样我不展开一大块也能看清标了什么。 +33. 作为一个要改网页的用户,我想复制这条消息时得到干净的文本,这样我贴到别处不会带一堆符号。 +33. 作为一个要改网页的用户,我想已发送的批注不能被改,这样历史记录可信。 +34. 作为一个要改网页的用户,我想页面刷新后批注还能回到原位,这样我不怕误刷新。 +35. 作为一个要改网页的用户,我想元素被删掉时批注标为失效而不是乱指,这样 AI 不会改错地方。 +36. 作为一个要改网页的用户,我想没选会话时发送按钮是灰的并告诉我原因,这样我不会白点。 +37. 作为一个要改网页的用户,我想所有报错都是中文说人话,这样我知道下一步做什么。 +38. 作为一个要改网页的用户,我想丢弃全部前被问一次,这样不会一键清空我标了半天的东西。 +39. 作为一个要改网页的用户,我想页面上任何菜单或弹窗打开时轮廓不挡着,这样我能正常操作。 +40. 作为一个要改网页的用户,我想切到别的应用再回来时页面上没有残留的浮层,这样界面不会看起来坏掉。 + +## 8. 关键规则速查 + +| 主题 | 规则 | +|---|---| +| 编号 | 按页面分组,组内从 1 连续;删除后撤销可恢复原编号;丢弃全部后该页从 1 重来 | +| 截图 | 保存批注时按元素区域裁剪,宽度不超过 512px;发送阶段不再截图 | +| 消息卡片配图 | 每个页面一张截屏(不是逐条小图),下方一行「页面标题 + X 条注释」 | +| 注释明细 | 悬停 `X 条注释` 展开,每条「元素类型 + 意见」,最多 5 条,超出滚动 | +| 无图情况 | 目标不在可视区域时该条保存为「无图」,待发卡片用元素标签 + 文本片段代替 | +| 发送范围 | 整个会话的全部待发批注(跨页签 + 已关闭页签) | +| 发送内容 | 输入框文字 + 全部批注,合成一条消息 | +| 超时 | 40 秒未确认先自查,再决定成功 / 退回 / 提示 | +| 保留期限 | 只在本次应用运行期间保留,重启后不恢复 | +| 语言 | 全部中文产品文案,不暴露技术错误 | + +## 9. 验收标准 + +以下每条都能在一次演示里当场验证: + +1. 单击元素直接开浮窗,没有多余的「批注」按钮。 +2. 鼠标移出页面,悬停卡片立刻消失。 +3. 改字号,页面实时变化;取消后回到改前,之前保存的批注不受影响。 +4. 按住「看原图」,页面回到改前;松开恢复。按空格或回车不触发。 +5. 标 3 处,输入框上方出现 3 条,编号 1/2/3,各带缩略图。 +6. 关掉页签,批注仍在卡片里,标为「页面已关闭」。 +7. 点铅笔,页签还开着就回到页面浮窗;页签关了就只有描述框。 +8. 删除一条,5 秒内撤销,编号恢复。 +9. 输入框写「一起改」+ 3 条批注,点发送 → 只出现一条消息。 +10. 同一个场景改点工具栏发送,结果完全相同,按钮显示「3」。 +11. 发送后立刻切换页签再加一条,已发的 3 条不受影响,新的那条第 4 号留下次。 +12. 聊天卡片是一张页面截屏,下方一行显示页面标题与 `3 条注释`,卡片内无按钮;单击截屏可看大图。 +13. 悬停 `3 条注释` 浮出三行明细,每行是元素类型 + 意见;标 7 条时浮层显示 5 行并可滚动。 + +## 10. 不做什么 + +- 不做移动端、不做纯浏览器版(仅在桌面端 Agent 浏览器内)。 +- 不做多人协作批注、不做批注的评论回复。 +- 不做跨会话的批注(批注属于某一个会话)。 +- 不做批注持久化到磁盘(重启即清空)。 +- 不允许对已发送的批注做二次编辑。 +- 不自动发送、不自动跳转页面。 +- 不提供批注的键盘快捷键。输入框内的回车换行、`Ctrl+Enter` 发送属于输入习惯,不算快捷键。 + +## 11. 已知取舍 + +**纯键盘用户无法使用「按住看原图」。** +这个能力设计成瞬时按住指针动作,没有对应快捷键。对完全不使用鼠标的用户,这一项不可用;其他功能不受影响。此取舍已确认接受。 + +**待发批注不做持久化。** +应用重启后未发送的批注会丢失。理由是避免「上次没发的批注」在下次启动时突然出现造成困惑。如果后续有用户反馈,可作为 v2 议题。 + +**「丢弃全部」按当前页面生效。** +本稿采用的口径是:用户在哪个页面上点丢弃,就只清空该页的批注,其他页签的待发批注保留。理由是这个按钮长在页面工具栏上,用户的心理预期是「清掉这个页面上的标记」。如果希望它是「清空整个会话」,需要另行确认——那会让工具栏承担跨页面的破坏性操作,风险更高。 + +**消息卡片的页面截屏,在保存批注时生成,发送时直接取用。** +不能等到发送才截屏:发送那一刻页面可能已被关掉、跳到别的地址,或在 mac 上目标不在视口内,用户只会看到一个「发送成功但没图」或「发送失败」的结果。所以口径是:每保存一条批注,顺带更新该页面的一张整屏图,同一页面只保留最新一张;发送时零捕获。 +两点后果需要接受:一是删除最后几条批注后配图不会自动重截,仍显示删除前的画面;二是同一页面在两次发送之间多次保存,配图始终是最后一次保存时的样子。 + +## 12. 命名对照 + +给需要和工程对齐的同学: + +| 产品说法 | 工程术语 | +|---|---| +| 生效中 / 待恢复 / 已失效 / 页面已关闭 | `live` / `replayable` / `stale` / `orphan` | +| 待发批注卡片 | 待发卡片(composer 上方) | +| 统一的发送动作 | 一处组装、三处触发 | +| 看原图 | 原图态(纯指针) | diff --git a/docs/specs/2026-11-22-html-page-annotations-spec.md b/docs/specs/2026-11-22-html-page-annotations-spec.md new file mode 100644 index 000000000..1b91e736f --- /dev/null +++ b/docs/specs/2026-11-22-html-page-annotations-spec.md @@ -0,0 +1,112 @@ +## Problem Statement + +在桌面端让 agent 改 HTML 页面时,用户只能靠文字描述"那个标题再大一点",模型猜错一轮就要重来。批注功能本该解决这件事,但现在的实现把批注绑在浏览器页签上、把发送按钮放在页面工具栏里,于是用户撞上三个具体的坑: + +1. **关掉页签,写到一半的批注全没了。** 用户经常一边看页面一边在对话里问问题,顺手关掉用不上的页签,回来发现批注和描述一起消失。 +2. **两个发送按钮是两套东西。** 页面工具栏的发送只发页面上的批注、还带着批次回执与重试对账,完全看不见输入框里用户刚敲的话;输入框的发送又不知道有批注在等。用户从哪头发、发出去的是什么,全凭记忆。 +3. **发送失败会让 agent 把同一处改两遍。** 网络抖一下、确认事件丢一次,界面就回滚,用户以为没发出去又点一次;而消息其实已经入库,模型收到两条一样的批注,重复执行同一处修改。 + +另外两个小一点的坑:截图是发送时才截的,关掉页签就没有图;mac 上目标在视口外时截图必然拿不到,直到点发送那一刻才报错。 + +## Solution + +把批注从"页签的附属物"变成"会话里的一份待发清单": + +- **记录归会话**。关页签不丢批注,它们变成"页面已关闭",仍可改文字、删除、发送。 +- **待发清单就是输入框上方的一张卡片**。按页签分组,每条显示缩略图、元素标签和描述,右侧是铅笔和垃圾桶。点铅笔回到页面继续改(页签没了就弹窗只改文字),点垃圾桶删掉并给 5 秒反悔。 +- **组装一处,触发三处**。消息只在输入框组装一次;输入框发送、页内工具栏发送、浮窗 Ctrl+Enter 三者等价,都是「把输入框里的内容和所有待发批注批量提交」,用户敲的话与整批批注合并成一条消息,模型一次读全。 +- **截图在保存批注时就截好**,发送只上传。关页签、刷新都不会让图消失。 +- **失败不再靠猜**。40 秒没收到确认时,先按客户端消息标识核对消息是否真的入库:入库就当成功,没入库才回滚并提示重试。宁可让用户看到一条"可能已发出"的记录,也不制造重复。 +- **发送完成的消息只读**。消息是对话记录,模型已经按当时的描述执行过;能改就等于改历史。 + +## User Stories + +1. 作为一名在桌面端改页面的用户,我想圈出一个元素后直接调样式并写一句"这里太大了",这样我不必用文字描述元素在哪。 +2. 作为一名用户,我想在页面上看到带编号的图钉,这样我知道自己标了几处、分别在哪。 +3. 作为一名用户,我想按住工具栏上的按钮看到页面原本的样子,这样我能确认改动是不是过头了;这个动作不占用任何键盘快捷键。 +4. 作为一名用户,我想松手就回到改后的样子,这样对比不打断我的编辑节奏。 +5. 作为一名用户,我想这个对比只在我按住鼠标时生效,这样我在别处敲键盘不会莫名其妙让页面闪一下。 +6. 作为一名用户,我想在对比时看不到图钉和描边,这样原图是干净的原图。 +7. 作为一名用户,我想点一下就把所有批注标记藏起来,这样我能看清页面本身而不取消我的修改。 +8. 作为一名用户,我想"隐藏标记"保持我按下的状态,这样我不用一直按着。 +9. 作为一名用户,我希望按住看原图时看到的是页面最初的样子,而不是我上一次改之前的样子,这样多次调整同一个属性时基准不会漂。 +10. 作为一名用户,我想在浮窗里按 Enter 就把这条批注加进待发清单,这样我能连着标好几处。 +11. 作为一名用户,我想按 Shift+Enter 在描述里换行,这样我能写多行说明。 +12. 作为一名用户,我想按 Ctrl+Enter 就"保存这条并整批发出去",这样急的时候一步到位。 +13. 作为一名用户,我想在输入框上方看到一张待发卡片,这样我知道还有几条没发。 +14. 作为一名用户,我想在卡片上看到每条的缩略图,这样我不用回忆自己标的是哪一块。 +15. 作为一名用户,我想看到每条的元素标签(div / button / input),这样我能快速区分几条相似的批注。 +16. 作为一名用户,我想让卡片按页面分组,这样我在多个页签之间来回看时不会混。 +17. 作为一名用户,我想在批注很多时让卡片内部滚动而不是把对话挤走,这样我还能看见正在说的话。 +18. 作为一名用户,我想点卡片上的铅笔就回到那条批注继续改,这样不用重新圈一遍元素。 +19. 作为一名用户,我想回到页面时描述框是填好的、光标在末尾,这样我能直接接着打字。 +20. 作为一名用户,我想在页签已经关掉时仍能改这条的文字,这样我不会因为手滑关页签就丢掉想法。 +21. 作为一名用户,我不想在页签关掉后看到"调整样式"的按钮,因为那时它点了也没用。 +22. 作为一名用户,我想删掉某条批注后 5 秒内还能反悔,这样误点不至于毁掉一段描述。 +23. 作为一名用户,我想在关闭页签后仍能看到并发送那些批注,这样我不必为了发送而重新打开页面。 +24. 作为一名用户,我想在输入框里既写自己的话又带上批注,这样模型能同时理解我的指令和精准改动。 +25. 作为一名用户,我想点一次发送只产生一条消息,这样模型不会把同一批批注读两遍。 + +26. 作为一名用户,我想在页面上批注完直接点工具栏的发送,而不用先切回对话,这样我不丢掉刚在页面上形成的判断。 + +27. 作为一名用户,我想无论从工具栏还是从输入框发送,结果都完全一样,这样我不用记哪个按钮发什么。 +28. 作为一名用户,我想在发送后立刻看到图钉和卡片清空,这样我知道"发出去了"。 +29. 作为一名用户,我想在网络不稳时不被误判为失败,这样我不会重复发送、让模型改两遍。 +30. 作为一名用户,我想在真的没发出去时把批注找回来重发,这样我不用重标一遍。 +31. 作为一名用户,我想刷新页面后批注和预览还在,这样改完样式刷新看一眼不会丢。 +32. 作为一名用户,我想在页面结构变了以后,那些对不上的批注被标成"已失效"而不是偷偷改错元素。 +33. 作为一名用户,我想看到每条批注对应的大致源码位置(文件行号或组件名),这样我知道该让 agent 改哪个文件。 +34. 作为一名用户,我想在消息里看到每条批注的局部截图,这样我回看对话时知道当时指的是哪一块。 +35. 作为一名用户,我想让发出去的批注卡片只能看不能改,这样对话历史和实际执行不会对不上。 +36. 作为一名用户,我想在一个会话的多个页签之间自由切换,批注互不干扰。 +37. 作为一名用户,我想在重启应用后从干净状态开始,这样不会莫名其妙冒出一堆旧批注。 +38. 作为一名用户,我想在页面里没有批注时看不到那张卡片,这样界面保持干净。 + +## Implementation Decisions + +- **记录权威上提到会话级**。批注记录、发送中集合、按页签分组的编号,全部由一个新引入的会话级批注存储持有;每个页签的批注会话只保留选区、预览、文档标识与命令下发,不再持有记录。 +- **记录四态**:`live`(目标有效)、`replayable`(文档已替换、等待重放)、`stale`(重放失败或值已被改动)、`orphan`(页签已关闭)。四态决定能否画图钉、能否重放、能否调样式,但**都允许发送**(失效的标 `target_invalid`)。 +- **关页签 = 转 `orphan`,不销毁**。页签关闭时把该页记录迁到会话存储的孤立集合,并广播一次"该页已空"。 +- **命令面分两档**:查询/预览类命令(读取快照、预览样式、预览文本、按住原图、隐藏标记、模态挂起、下发图钉)不占串行闸门,可并发、可覆盖;编辑类命令(开始/退出/取消/保存/加目标/加区域/选择/丢弃/重放/打开已有记录/更新描述/删除记录)串行并带序号防迟到。此前所有命令共用一个闸门,按住原图的手感直接受害。 +- **图钉由原生全量下发**,页内运行时不再自己决定画哪些图钉、编号是几。每次记录集合变化都下发完整列表,页内整体替换(幂等),删一条后编号自动前移。 +- **原始值(baseline)必须是首次触碰值**。多次修改同一属性时,按住看原图看到的必须是页面最初的样子;中间态不得写进记录。样式层要能做到"忽略本层已声明的样式"取值,文本层不得把已保存的值叠加进基准。 +- **重放带观察窗口**:页面加载完成后立即重放一次,随后用 DOM 变更观察(节流 300ms)驱动重试,窗口 3 秒、最多 10 次;窗口内"元素还没渲染出来"不算失效。重放每个属性前先比对实时值是否仍等于原始值,不相等就标记失效、不写入。 +- **截图在保存批注时生成**:一次视口捕获,按目标外接矩形裁剪,缩到宽 ≤512px 存进记录。待发卡片的缩略图与消息附件是同一张图;发送阶段不再捕获。视口外或捕获失败时该条标记无图,卡片退化为标签 + 文本片段。 +- **组装唯一、触发三路**:消息只在会话输入框(composer)组装一次(`submitWithAnnotations()`)。输入框发送按钮、页内工具栏发送按钮、浮窗 Ctrl+Enter 都调它,参数与结果完全一致;工具栏按钮不自己组装 payload、不自己 POST。提交范围是会话全量(跨页签 + 已关闭页签),按钮上显示总条数;输入框草稿会一并发出。 +- **消息合并**:`{用户文本}\n\nPage annotations\n{JSON}`。无用户文本时保持现状(只发载荷)。解析从"文本以固定头开始"放宽为"末尾存在分隔段",卡片渲染时遮蔽 JSON 段、保留用户文本。 +- **发送状态只有一个中间态**:点发送即把记录移出待发集合并清空图钉与卡片;收到该消息的确认事件后彻底丢弃;失败或超时则放回集合并重排编号。 +- **超时自查**:40 秒未确认时,按客户端消息标识查询消息是否已入库。查到 → 视为成功;查不到 → 回滚;查询自身失败 → 不回滚,只提示"可能仍在发送"。 +- **待发卡片的数据来源**:原生在任一页签的记录变化时都广播该页签的记录快照,前端按"会话 → 页签"归并,并单独维护孤立记录集合。卡片订阅这份归并结果,不读消息载荷。 +- **可调整样式只有一条判定**:记录为 `live` 且页签存活且文档标识匹配。两个编辑入口共用这条判定,不得各写一份;`replayable` 也一律隐藏「调整」,因为重放未完成时基准是脏的。 +- **编辑入口两条路径**:页签存活时激活页签 → 让页面回到批注模式 → 打开该条批注框(回填描述、光标置末尾、高亮图钉、差异还原为草稿);页签已关时弹窗只改文字,目标定位信息只读。 +- **删除即时生效 + 5 秒撤销**,不做二次确认弹窗。 +- **已发送的消息卡片只读**:不提供编辑、删除、复制或"回到页面修改"。消息级的通用复制按钮保留,且复制出去的是人读文本而不是原始 JSON。 +- **导航不作废记录**:刷新/前进后退只把记录转成待重放,不清空。 + +## Testing Decisions + +好的测试只断言外部可观察的行为,不断言内部字段或实现细节。这个特性有四个天然边界: + +1. **原生批注存储与命令面**(既有单测缝)。断言"发出这些命令后,快照里能读到什么":新建/删除/丢弃后的编号连续性、关页签后记录仍可读、四态转换、查询类命令互不阻塞、发送中记录不计入待发数且不下发图钉。既有同类测试就是这个缝的范本,仍在同一个测试可执行体内跑。 +2. **端到端发送**(既有浏览器集成缝,最高点)。一条链路覆盖:保存(生成缩略图)→ 关页签 → 卡片仍可见 → 弹窗改文字 → 输入框带文字点发送 → 只产生一条消息 → 载荷可被解析出用户文本与各条批注 → 收到确认后清空。以及超时三分支:已入库按成功收尾、未入库回滚、查询失败不回滚。再补一条等价性用例:同一状态下分别从输入框与工具栏发送,产生的请求体与消息条数完全一致。 +3. **组件行为**(既有组件测试缝)。浮窗的按键语义(Enter 添加 / Shift+Enter 换行 / Ctrl+Enter 保存并发送)、按住原图与隐藏标记互不干扰、按住原图不响应空格与 Enter、`adjustable` 判定在四种状态下的取值、卡片 5 行封顶与滚动。 +4. **归并器**(新增的唯一一个缝)。待发卡片的数据来源是一个纯函数:输入"若干页签各自的记录快照 + 孤立集合",输出"按会话分组的展示列表"。它没有 DOM、没有异步,适合用表驱动测试覆盖空、单页、多页、孤立、同一页签反复更新这几种输入。 + +不新增其他缝。服务端只加一个按客户端消息标识查询的读接口,沿用现有 Web 冒烟测试的写法断言"建了消息能查到、没建查不到"。 + +## Out of Scope + +- 手绘标注(自由笔迹)本轮不做,只做元素与矩形区域。 +- 批注跨重启持久化:仍然只在当前运行期内存里,重启清空。 +- 编辑已发送的消息:不新增消息编辑能力。 +- 接收端按批次去重(收据机制):明确不做,超时只做前端自查。 +- 导航确认弹窗:不拦截用户操作。 +- mac 视口外目标的截图:接受降级为无图,只做 UI 明示。 +- 多人协作 / 批注共享给其他人。 + +## Further Notes + +- 完整决策记录(49 条:问题编号 Q1–Q36、交互编号 U1–U5、细节编号 D1–D8)在 `docs/specs/2026-11-21-html-page-annotations-technical-design.md`,本 spec 只挑用户可见与实现约束,不复述论证过程。 +- 现有未提交改动(51 个文件)是**旧路线**的完成度打磨,与本 spec 的关系已在 `docs/specs/2026-11-22-html-page-annotations-wip-alignment.md` 中逐文件定性(保留 / 改造 / 废弃),实现前先读它,否则会在旧骨架上继续加砖。 +- 三个尚未验证的假设(保存时捕获的耗时、跨页签广播的事件量、文档替换后能否定位到记录)及其退路见 `docs/specs/2026-11-22-html-page-annotations-validation-plan.md`。其中"定位"一项若失败,会反过来影响记录标识的设计,需在动记录层之前先测。 +- 需求基线见 `docs/specs/2026-11-21-html-page-annotations-rewrite-requirements.md`(已按本 spec 对齐 3.2 / 3.3 / 3.4 / 3.5 / 3.7 与验收标准)。 diff --git a/docs/specs/2026-11-22-html-page-annotations-t0-findings.md b/docs/specs/2026-11-22-html-page-annotations-t0-findings.md new file mode 100644 index 000000000..b2eab6a67 --- /dev/null +++ b/docs/specs/2026-11-22-html-page-annotations-t0-findings.md @@ -0,0 +1,102 @@ +# T0 技术验证结论(#208) + +> 日期:2026-11-22 · 对应工单:[#208](https://github.com/tmoonlight/acecode/issues/208) · 方案:[#207](https://github.com/tmoonlight/acecode/issues/207) +> 输入:`codex/html-page-annotations` @ `44c3fad4`(WIP 基线已提交) + +本文件回答两件事:**(一)文档被替换后还能不能按记录里的标识定位目标;(二)保存时做一次视口捕获 + 裁剪的耗时是否可接受。** + +两项都有结论,且都改变了后续实现:标识必须改(#209 的存储结构照此落),捕获必须走异步补图(#212 的实现形态照此落)。 + +--- + +## 一、记录标识:不是「成功率多少」,是结构上不可能 + +**结论:现行 `record.id` 在文档替换后 100% 失效,且不是实现 bug,是标识设计的结果。必须改成与文档无关的稳定 id。** + +原计划「HMR / 手动刷新各跑 10 次点铅笔定位,给成功率」。读代码后确认这个实验不必跑——失败是构造性的,跑出来必然是 0/10。下面是完整因果链,每一环都有行号: + +| # | 事实 | 位置 | +|---|---|---| +| 1 | `document_id` 由页签 id + **自增 epoch** 拼成 | `page_annotation_session.hpp:213` `document_id_ = page_id + ":document:" + std::to_string(epoch_)` | +| 2 | 文档替换时 `epoch_` 自增,`document_id_` 被**清空**;下次 `start` 生成新 id | `page_annotation_session.hpp:143-168` | +| 3 | 记录 id 由 `document_id` 拼成 | `page_annotation_session.hpp:381` `{"id", document_id_ + ":annotation:" + std::to_string(next_number_)}` | +| 4 | 替换时所有既有记录被标 `valid=false` / `invalid_reason=document_replaced` | `page_annotation_session.hpp:161-164` | +| 5 | 页内 runtime 以 `document_id` 为键,换文档即 `dispose()` | `page_annotation_runtime.hpp:9-12` | +| 6 | 元素标识是 runtime 内的 `WeakMap` + 自增序号 | `page_annotation_runtime.hpp:28, 217` `ids.set(target, \`target-${++sequence}\`)` | +| 7 | 脚本一旦发现 `documentElement` 换了就返回 `replaced_document` | `page_annotation_runtime.hpp:377-381` | +| 8 | 替换后图钉(`pins`)随 runtime 一起消失,没有 DOM 可指 | `page_annotation_runtime.hpp:359-375` | + +链条合起来:**刷新 → epoch+1 → 记录 id 指向一个不存在的文档代 → runtime 与图钉都已销毁 → 元素标识 `target-N` 在新 runtime 里从 1 重新数,语义完全不同。** 所以「按 record 里的标识定位」在数据层面就没有可解析的东西:`:document:1:annotation:3` 里的 `document:1` 已经是历史。 + +HMR 分两种情形,都不改变结论: + +- dev server 整页 reload(或框架重建 `documentElement`)→ 与手动刷新完全一致,`replaced_document`; +- HMR 原地替换 DOM 子树、`documentElement` 不变 → runtime 存活、`pins` 存活、记录仍是 `valid`,此时**根本不需要重新定位**(本来就没丢)。 + +也就是说:需要定位的场景一定是 runtime 已销毁的场景;而 runtime 一销毁,记录里除了 `page_url` 和文本,**没有任何跨文档可用的定位信息**——`target.id` 是内存序号,`record.targets[].locator` 只有 `tag#id`(`page_annotation_runtime.hpp:97`),对没有 `id` 的元素退化成 `div`。 + +### 决策 + +1. **`record.id` 改为与文档无关**:`:annotation:`。`n` 仍按 `page_id` 分组连续(编号语义不变),但不再嵌 `document_id`。 +2. **`record` 新增 `locator` 字段**,`save` 时生成:CSS 结构路径(`nth-of-type` 链)→ `data-testid` / `aria-label` → 文本指纹 → 同级索引,逐级降级。这是 §4.6 重放算法里 `locate(record.locator)` 的唯一输入,现有 `tag#id` 不足以支撑。 +3. **`target.id`(`target-N`)只在同一 runtime 内有效**,不作为跨文档标识,也不进记录的主键。 +4. 重放失败 / 定位不到 → `stale`,按 §4.6 的「stale 可见性」处理(工具栏显示「N 条已失效」,条目置灰可查可删)。 + +第 2 条是这次唯一新发现的缺口:此前设计把 `locator` 当成既有能力,实际它只是个 `tag#id`。 + +--- + +## 二、保存时捕获 + 裁剪的耗时:**取决于有没有做 scale 修正** + +测量方法:无头 Edge(`Edg/158`,`--headless=new --disable-gpu`,软件光栅),页面内用 canvas 复现保存路径——取一张视口大小的 PNG → 解码 → 按目标 rect 裁剪 → 缩到宽 512 → 编码回 data URL。每个变体 4 张不同的源图轮换,避免解码缓存命中;宽 512 缩略图,裁剪区 360×220 CSS px。 + +| 视口 | 捕获图尺寸 | 捕获 PNG | 解码 P50 | 裁剪 P50 | 编码 P50 | **总 P50** | **总 P95** | +|---|---|---|---|---|---|---|---| +| 1280×800 DPR1 | 1280×800 | 225 KB | 10.5 ms | 0.2 ms | 1.7 ms | **12.4 ms** | **16.0 ms** | +| 1920×1080 DPR1 | 1920×1080 | 900 KB | 20.7 ms | 0.4 ms | 1.5 ms | **22.5 ms** | **25.2 ms** | +| 2560×1440 DPR2(`scale=1/dpr`) | 2560×1440 | 463 KB | 29.2 ms | 0.2 ms | 1.2 ms | **30.3 ms** | **36.5 ms** | +| 2560×1440 DPR2(**没做** scale 修正) | 5120×2880 | 4602 KB | 154.1 ms | 0.2 ms | 10.5 ms | **163.3 ms** | **237.6 ms** | + +原始数据:`C:/Users/Administrator/AppData/Local/Temp/annotation-bench/`(`index.html` + `drive.mjs`,可重跑)。 + +**三条读法:** + +1. 做了 `scale = 1/dpr`,视口捕获图就是 CSS 像素尺寸,最大档 P95 也只有 37 ms,**远低于 150 ms 门槛**——保存路径里这一段的性能不是问题。 +2. **不做 scale 修正,DPR2 下 P95 是 237 ms,直接越线**(图大 4 倍、PNG 大 10 倍,解码 + 编码都翻倍)。所以 `scale = 1/dpr` 不是优化选项,是**硬要求**;这也决定了坐标换算:裁剪 rect 直接按 CSS 像素用,不用乘 DPR。 +3. 耗时几乎全在**解码**,裁剪本身 0.2 ms、编码 1~10 ms。想再快只能减少像素,而不是换裁剪算法。 + +**测不到的部分**:CDP `Page.captureScreenshot` 本身(含 base64 过 IPC)没测——那需要跑起桌面壳并连真实页面。上表是页面侧的成本,不是端到端。 + +### 决策:走异步补图,不把捕获塞进 save 的返回路径 + +理由不是「测出来超了」(没超),而是: + +- `save` 是直接操作动作(点「保存」→ 浮窗关闭 → 图钉出现),用户对它的感知是「立刻」。把一次 CDP 往返 + 上表 30 ms + base64 过 IPC 串在返回路径上,会让图钉出现的时间取决于捕获快慢,而这部分收益(立刻有缩略图)在待发卡片上并不紧急。 +- 捕获本身可能失败(视口外目标、mac 拿不到快照、文档中途变化),串行实现就得让失败路径也阻塞交互,或者加超时兜底——两种都更复杂。 +- 异步后,「图还在不在」与 `save` 成败彻底解耦,`screenshot_unavailable` 变成一个普通字段的更新,不是一次交互失败。 + +具体形态(#212 照此实现): + +``` +save → 记录立刻入库并广播(thumbnail 空,screenshot_pending:true) + ↘ 原生异步:视口捕获(scale=1/dpr) + → 页内裁剪(目标 rect,宽 ≤512)→ thumbnail + → 原图存 page_shot(按 page_id 覆盖) + → 回写记录 + bump revision + 广播(卡片缩略图 / 已发卡片配图就位) + ↘ 失败(视口外 / 文档已换 / 超时 2s)→ screenshot_unavailable:true,不重试 +``` + +超时 2s 是防守线:视口捕获正常是几十毫秒,2s 还没回来基本就是 CDP 挂了,继续等只会让记录长期停在「半成品」。 + +--- + +## 三、对下游工单的影响 + +| 工单 | 变化 | +|---|---| +| #209 记录上提 | 存储主键用 `:annotation:`;`document_id` 降为记录的一个属性(用于判断 `live` / `replayable`);新增 `locator` 字段 | +| #210 读路径迁移 | `record.document_id == snapshot.document_id` 不再是「有效性」判据,改判 `live` 与否 | +| #212 截图前移 | 走异步补图;强制 `scale=1/dpr`;裁剪坐标用 CSS 像素 | +| #217 铅笔路径 A | 依赖 `locator`:`live` 直接激活浮窗;`replayable` 先 `locate(locator)`;`stale`/`orphan` 走 #218 的弹窗 | + +设计文档已同步:§1.1 新增 D9(记录标识)、D10(捕获时机改异步);§4.8 换成异步流程;§4.2 记录模型更新。 diff --git a/docs/specs/2026-11-22-html-page-annotations-validation-plan.md b/docs/specs/2026-11-22-html-page-annotations-validation-plan.md new file mode 100644 index 000000000..048606748 --- /dev/null +++ b/docs/specs/2026-11-22-html-page-annotations-validation-plan.md @@ -0,0 +1,104 @@ +# HTML 网页批注 —— 技术验证清单 + +- 日期:2026-11-22 +- 目的:把新方案里**三个还没被任何代码证明过的假设**先测掉。它们一旦不成立,会反过来改设计,所以必须排在实现之前。 +- 判定原则:**能不改设计就不改**;只有通过标准明显不达标才走退路。 + +--- + +## 已静态确认的事实(不用测) + +| 事实 | 证据 | +|---|---| +| 现有捕获是「3 跳 CDP + 整页」 | `agent_browser_capture_cdp.cpp:30`(`cssContentSize`)、`:61`(读 device scale)、`:71-74`(`captureBeyondViewport:true` + `scale:1/dpr`) | +| 捕获参数可离线断言 | `tests/test_support/desktop/agent_browser_capture_probe_command.hpp` + `tests/desktop/agent_browser_capture_probe_test.cpp`(`FakeClient` 记 method/params) | +| 批注状态事件目前只带面板页签 | `AgentBrowserPanel.jsx:83`(`event.detail.page_id !== pageId` 直接 return) | +| 消息可写 `client_message_id` 到 metadata | `routes_sessions.cpp:524`,WS 回推 `:734-738` | +| 没有「编辑消息」的 API | 全仓无 `PATCH /messages`、无 `editMessage` | + +--- + +## V1 —— save 时捕获会不会拖垮「保存」手感 + +**假设**:`save` 时做一次视口捕获 + 本地裁剪,用户感知不到延迟。 + +**为什么重要**:D2 把截图从「发送时」前移到「每次 save」。Windows 每条命令本来要 3 跳 CDP(`agent_browser_host.cpp:2212-2258`,尚无 `executionContextId` 缓存),再加一次 `Page.captureScreenshot`,可能让"保存批注"从瞬时变成卡顿。 + +**方法** + +1. 在 `save` 分支的首尾各打一条 `LOG_INFO` 时间戳(或复用 `capture_probe` 的计时),跑 20 次保存; +2. 分别在三个尺寸下测:1280×800(笔记本)、1920×1080(外接屏)、2560×1440(高分 + DPR 2); +3. 记录 P50 / P95。 + +**通过标准**:P95 ≤ 150ms(一次点击的可感知阈值约 100–200ms)。若开了 `executionContextId` 缓存,目标 ≤ 120ms。 + +**退路(按代价排序)** + +1. **异步补图**:`save` 立即落记录(无图),捕获完成后回填 `thumbnail` 并推一次卡片刷新。用户点保存立刻看到图钉,缩略图后到。改动小,体验几乎无损。 +2. 捕获降到 `quality` 更低的 jpeg(体积小、编码快)。 +3. 退回「发送时截图」,接受 `orphan` 记录无图(D2 作废,Q25/Q28 恢复原样)。**最后才选这条**——它会重新引入"关页签就没图"。 + +--- + +## V2 —— 跨页签广播会不会刷爆 WebView2 通道 + +**假设**:把状态事件从「只发面板页签」改成「发会话内所有页签」,在多页签 + 多条批注时仍然可承受。 + +**为什么重要**:`sync` 已经是每次增删一次全量下发;广播面从 1 个页签扩到 N 个,事件量按页签数线性增长,而 WebView2 的 `postMessage` 是同步序列化。 + +**方法** + +1. 构造 5 个页签 × 每页 10 条批注; +2. 在一个页签上快速增删(连续 20 次 save + delete),统计 1 秒内的事件数与单事件字节数; +3. 同时观察另一端:另一个页签的浮窗是否出现掉帧或输入延迟。 + +**通过标准**:峰值 ≤ 20 事件/秒,单事件 ≤ 8KB,另一端无可感知卡顿。 + +**退路** + +1. 广播节流 50ms 合并(同一 `page_id` 的多次变化只发最后一次); +2. 只推 diff(新增/删除/改编号的 id 列表),由 WebUI 应用;`sync` 仍全量,但只发给**有图钉的页签**; +3. 极端情况:非面板页签不推送,卡片在被切到该页签时再拉一次全量。 + +--- + +## V3 —— `document_id` 变化后 `open_record_popup` 还能不能定位 + +**假设**:点铅笔时(尤其 dev 环境 HMR 之后)能可靠地把浮窗开在那条记录上。 + +**为什么重要**:`open_record_popup` 要拿 `record_id` 找到 DOM。但 `replace_document` 会换 `document_id`,`record.id` 目前是 `:annotation:`(见 §5.1),HMR 之后 id 就对不上了。 + +**方法** + +1. 打开一个 dev 页面(Vite HMR 可用),保存 2 条批注; +2. 改一次源码触发 HMR(不刷新); +3. 立刻从卡片点铅笔; +4. 再重复「手动刷新页面」这个变体。 + +**通过标准**:HMR 后能定位并回填描述(此时记录应已重放为 `live`);刷新后若重放未完成则**必须**降级为弹窗而不是报错。 + +**退路** + +1. `record_id` 改为与 `document_id` 无关的稳定 id(`page_id` + 创建序号),`document_id` 只作为"当前绑定"字段; +2. 定位失败一律走路径 B(弹窗改文本),并在卡片行标「目标已失效」; +3. 若 HMR 场景定位成功率低于 80%,就把「点铅笔」默认走弹窗,只在 `live` 且 `document_id` 匹配时才激活页签。 + +--- + +## 执行顺序与产出 + +| 顺序 | 项 | 需要什么 | 产出 | +|---|---|---|---| +| 1 | V1 | 能跑起来的桌面壳(`run_build.py` 编 desktop 目前缺 winrt 头,见本机笔记的绕行脚本) | 三个尺寸的 P50/P95 数字 + 是否走退路 | +| 2 | V3 | dev 服务器 + HMR | 定位成功率 + 降级是否触发 | +| 3 | V2 | 5 页签构造脚本 | 峰值事件数 / 单事件大小 | + +**V1 与 V3 可以并行**(一个测性能、一个测定位)。V2 依赖跨页签广播**已经实现**,所以它天然排在 P2 之后——如果不想等,可以先按「预计 5 页签 × 10 条」的量级做一次假数据压测(WebUI 内部模拟,不碰原生)。 + +--- + +## 结论怎么用 + +- V1 通过 → P3 按原计划;不通过 → 走退路 1(异步补图),设计只需补一句"缩略图可迟到"。 +- V3 通过 → `open_record_popup` 沿用 `record_id`;不通过 → 先做稳定 id 改造,它会顺带影响 P1 的 store 结构,**必须在 P1 之前定**。 +- V2 通过 → 广播方案照写;不通过 → 加节流,属于纯实现细节,不影响设计。 diff --git a/docs/specs/2026-11-22-html-page-annotations-wip-alignment.md b/docs/specs/2026-11-22-html-page-annotations-wip-alignment.md new file mode 100644 index 000000000..62942cc6a --- /dev/null +++ b/docs/specs/2026-11-22-html-page-annotations-wip-alignment.md @@ -0,0 +1,154 @@ +# HTML 网页批注 —— WIP 对齐清单 + +- 日期:2026-11-22 +- 对象:worktree `C:/Users/Administrator/.codex/worktrees/html-page-annotations/acecode`(分支 `codex/html-page-annotations`,`b5a2d5c4`) +- 对照基线:`docs/specs/2026-11-21-html-page-annotations-technical-design.md`(Q1–Q36 / U1–U5 / D1–D8) +- 规模:45 个跟踪文件(+4445 / −375)+ 6 个未跟踪新文件 = 51 个改动 +- 已合并 `origin/master`:`0b862f32`(3 个提交:ACEModel 配额错误处理),无冲突,WIP 原样保留 + +--- + +## 0. 一句话结论 + +**这批 WIP 是「旧路线的完成度打磨」,不是新方案的实现。** 它把 Codex 的视觉对齐、样式面板、原生表面几何(圆角挖洞 / 模态阻断输入)、已发消息卡片都做完了;而新方案推翻的三处骨架——**记录归属上提到会话(Q33)、发送链路换骨(Q35:组装收到 composer,触发点保留三处)、截图前移到 save(D2)**——一处都还没落地。 + +所以对齐不是"改改就行",而是:**几何与样式面板整块留下(约 2600 行),发送链路整条换骨(约 700 行),记录层重写(约 300 行)。** + +| 判定 | 文件数 | 行数量级 | 说明 | +|---|---|---|---| +| **保留**(不改或只加注释) | 19 | ~2100 | 样式面板、表面几何、模态阻断、i18n 文案、既有测试 | +| **改造**(同一份代码改行为) | 24 | ~1800 | 浮窗、工具栏、controller、消息卡片、记录层 | +| **废弃**(删) | 8 | ~500 | `pageAnnotationBatches.*`、截图通道、旧 openspec 文档 | + +--- + +## 1. 保留(19) + +这些改动服务的能力在新方案里没变,动了只会引入回归。 + +| 文件 | 改动量 | 内容 | 依据 | +|---|---|---|---| +| `web/src/components/PageAnnotations.jsx`(样式面板部分) | +1024 中的大头 | 间距锁 `spacingLockState`、色板 `colorSwatchValue`、字体建议 `fontSuggestions`、下拉菜单、tooltip、透明度、`adjustBounds` 拖拽 | 与新方案无关;是「调整」按钮的全部能力,D8 还要求保留它 | +| `web/src/styles/globals.css` | +878 | 浮窗 / 工具栏 / 卡片的视觉与动效 | 同上(卡片样式部分见 §2) | +| `web/src/lib/agentBrowserSurfaceCoordinator.js` + `.test.js` | +209 / +321 | 圆角挖洞(`occlusionSquareCorners`、`occlusionSquareCornerMask`)、`overlayBleed`、合并同半径矩形 | 纯表面几何,与批注数据模型无关 | +| `src/apps/desktop/agent_browser_host.hpp` / `.cpp` | +13 / +13 | `interaction_blocked`(模态期间 `EnableWindow(FALSE)` 阻断输入)、`radius` / `square_corners` 校验 | 服务 Q10「按住时样式面板整体隐藏」与模态弹窗,属于必须能力 | +| `src/apps/desktop/agent_browser_host_mac.mm` | +110 | `add_occlusion_cornered_hole` 每角独立半径 | 同上,mac 侧对应实现 | +| `src/apps/desktop/agent_browser_windows_helpers.cpp` | +30 | Windows 圆角窗口区域 | 同上 | +| `src/apps/desktop/main.cpp` | +3 | 解析 `interaction_blocked` / `radius` / `square_corners` | 同上 | +| `web/src/components/PageAnnotationTargets.jsx` | +21 | 目标标签渲染 | 记录结构里 `targets[]` 不变 | +| `web/src/components/PageAnnotationTextField.jsx` | +15 | 多行描述输入 | Q36 `Shift+Enter` 换行要用 | +| `web/src/components/Modal.jsx` | +16 | 模态呈现 | D7 / 路径 B 的弹窗要复用它 | +| `web/src/lib/annotationChromeSuspension.js` + `.test.js`(新) | 新文件 | 浮窗/工具栏悬浮时暂停 WebUI chrome,配合 `set_modal_suspended` | Q10 的实现基础 | +| `web/src/lib/pageAnnotationMessage.js` + `.test.js`(新) | 新文件 | `parsePageAnnotationMessage` / `pageAnnotationMessageCopyText` / 截图剥离 | 消息载体沿用(§4.9),只需放宽解析(见 §2) | +| `web/src/lib/pageAnnotationStyles.browser.test.js` | +212 | 样式层测试 | 跟样式面板保留 | +| `web/src/lib/pageAnnotationText.test.js` | +10 | 文本层测试 | — | +| `web/src/lib/pageAnnotationTextField.test.js` | +6 | 输入框测试 | — | +| `web/src/lib/agentBrowserArchitecture.test.js` | +30 | 表面架构断言 | 跟几何保留 | +| `web/src/lib/composerMessageRendering.test.js` / `htmlPageFrame.test.js` / `modalPresentationArchitecture.test.js` / `sessionStartMaskArchitecture.test.js` / `themeSurfaces.test.js` | 各 +2~4 | 架构守卫 | — | + +--- + +## 2. 改造(24) + +### 2.1 记录层:`page_annotation_session.hpp`(+48) + +**WIP 已经做对的**(保留): + +- 新增 `hide_markers` / `set_modal_suspended` / `discard` 三个 action 进入白名单(`:182-189`); +- `page_background_` 字段与 `markers_hidden_` / `modal_suspended_` 状态进入 `snapshot()`(`:68-75`); +- `discard` 清空 `records_` 并把 `next_number_` 归 1(`:385-388`)——Q22 的「手动丢弃」正好用它; +- `replace_document` 复位 `markers_hidden` / `modal_suspended`(`:149-152`)。 + +**必须改的**: + +| 问题 | 现状 | 新方案要求 | +|---|---|---| +| 记录归属 | `records_` 是 `PageAnnotationSession` 的成员,`close_page` 即析构 | Q33 修订:上提到会话级 `SessionAnnotationStore`,关页签转 `orphan` | +| 目标有效性 | `record["valid"] = false`(布尔) | 四态 `live / replayable / stale / orphan` | +| 命令面 | 所有 action 统一 `busy_ = true` | quiet 档(`read` `preview_*` `original` `hide_markers` `set_modal_suspended` `sync`)不占闸 | +| 缺失 action | 无 `sync` / `reapply` / `delete_record` / `update_description` / `open_record_popup` | 全部要加(§4.1 表) | +| `in_flight` | 不存在 | 发送中记录移出 `records_`,不画图钉、不计 `pending_count` | + +### 2.2 页内运行时:`page_annotation_runtime.hpp`(+209) + +保留:整层 `hide_markers`、原图态 `markersVisible = !markersHidden && !original`、`page_background` 注入。 +改造:内部编号逻辑要移出(改由 `sync` 全量下发)、新增 `sync` / `remove` / `reapply` 分支、保存时输出扩展 locator(`body>div#root>…` 之外补 testid / aria / 文本指纹)、打 `data-ace-hit-*`。 + +### 2.3 截图链路:`page_annotation_host_adapter.hpp`(+10) / `page_annotation_bridge.cpp`(+15) + +WIP 新增了 `screenshot` 命令 + `aceDesktop_agentBrowserAnnotationScreenshot` 绑定,**时机是发送时**(工具栏还有「截取屏幕截图」按钮)。 +D2 改为:`save` 时视口捕获 + 按 rect 裁剪 + 缩到 ≤512px 存 `record.thumbnail`;发送只上传。**命令保留、调用点前移、删掉工具栏截图按钮。** + +### 2.4 工具栏:`PageAnnotationSendBar.jsx`(+272) + +WIP 现状(`PageAnnotationSendBar.jsx:94-192`):发送(含「发送中/重试」三态)、截取屏幕截图、隐藏标记(`aria-pressed`)、按住原图、丢弃批注、退出批注模式、拖动把手、tooltip。 + +改动: + +- **保留「发送」按钮,换掉实现**(Q35 修订二次:组装唯一在 composer,触发三处)——按钮不再调 `pageAnnotationBatchSender`,改为调 composer 的 `submitWithAnnotations()`;连带删掉 `send()` 与 `sender` 依赖、删掉「发送中/重试」三态文案;按钮显示会话级总条数,禁用条件与输入框一致; +- **删「截取屏幕截图」按钮**(D2,图在 save 时就截好了); +- 保留:隐藏标记(锁存)、按住原图(补 `blur` / `visibilitychange` 兜底,**删掉键盘 Space/Enter 那条路径**,Q2 修订为纯指针)、丢弃、退出、拖动、tooltip; +- 新增:`N 条待发` 计数徽标(点击把焦点交给输入框上方的卡片)。 + +### 2.5 浮窗:`PageAnnotations.jsx`(结构部分,非样式面板) + +保留结构与样式;新增: + +- **「编辑已有记录」态**:`open_record_popup` 回填 `description`、光标置末尾、`focus()`、图钉高亮、差异还原成 draft; +- `Enter` = 添加 / `Shift+Enter` 换行 / `Ctrl+Enter` = 保存当前 + 触发整批发送(U4); +- `read` 失败**不终止**轮询(现 `:43-46` 一次 `ok:false` 就 `return`); +- `adjustable` 单点判定(`live` 且页签存活且 `document_id` 匹配),供路径 A / 路径 B 共用。 + +### 2.6 controller 与消息层 + +| 文件 | 改动 | +|---|---| +| `web/src/lib/pageAnnotations.js`(+25) | 支持 quiet 命令并发;新增 `reapply`;新增 `open_record_popup` / `update_description` / `delete_record` 的调用封装 | +| `web/src/components/Message.jsx`(+31) | **已接好 `PageAnnotationMessageCard`**,保留;`parsePageAnnotationMessage` 放宽为「末尾 `\nPage annotations\n` 分隔段」,以便承载「用户文本 + 批注」合并消息 | +| `web/src/lib/pageAnnotationMessage.js` | 解析放宽;按 `page_url` 分组;`copyText` 保留(见下) | +| `web/src/components/PageAnnotationMessageCard.jsx`(新) | 保持只读,但行布局改为「缩略图 + tag + 描述」,缩略图取 payload 里该记录的裁剪图 | +| `web/src/i18n/sourceCatalog.generated.js` / `i18n-en-overrides.mjs` | 随文案增删同步(删「发送中/重试/截取屏幕截图」,加「页面已关闭」「回到页面修改」等) | +| `web/src/lib/runTests.js` | 去掉 `pageAnnotationBatches`,加新模块 | +| `tests/desktop/page_annotation_session_test.cpp`(+74) | 四态、分组编号、关页签转 `orphan` | +| `tests/desktop/page_annotation_lifecycle_smoke.mjs`(+29) | 同上 | + +--- + +## 3. 废弃(8) + +| 文件 | 原因 | +|---|---| +| `web/src/lib/pageAnnotationBatches.js` | 整条批次链路:`createAnnotationBatchSender`(发送状态机 + 截图 + 回执对账 + `fullPage` 断言)、`formatAnnotationBatch`、`pageAnnotationBatchSender`、`localizedSendError`、`annotationIsSendable` —— Q26 要求删净 | +| `web/src/lib/pageAnnotationBatches.test.js` | 同上 | +| `openspec/changes/add-html-page-annotations/design.md`(+187) | 描述旧路线;WIP 还在往里加「screenshot bridge / message card」小节。整个 change 标 superseded,不再维护 | +| `openspec/changes/add-html-page-annotations/tasks.md`(+67) | 同上 | +| `openspec/changes/add-html-page-annotations/specs/html-page-annotations/spec.md`(+59) | 同上 | +| (连带)`annotation_batch_id` 全部 43 处引用 | 前端、请求体、`metadata` 落库 | +| (连带)`reconcileOnly` 全部 11 处引用 | 服务端 404 协议与前端重试 | +| (连带)原生租约 `capture` / `validate` / `acknowledge` / `release` | 状态机已取消 | + +**注意**:`pageAnnotationBatches.js` 的外部引用只有 5 处(`PageAnnotationSendBar.jsx`、两个测试、`pageAnnotationIntegration.browser.testHelper.js`、`runTests.js`),删除面可控。 + +--- + +## 4. 三个需要单独确认的点 + +1. **消息级「复制」按钮要留**。D6 说的是「卡片里不给复制按钮」,但 `Message.jsx:409` 那个是**所有消息共用的页脚操作**,且它调 `pageAnnotationMessageCopyText` 把 JSON 剥成干净文本。删了反而让用户复制到 JSON。**建议:保留,只在文档里注明"卡内无按钮"**。 +2. **`annotationChromeSuspension.js` 与新方案的模态阻断是两套**(一套在 WebUI 侧暂停 chrome,一套在原生侧 `EnableWindow(FALSE)`)。两者互补,都要留,但要在文档里写清边界,否则后面有人以为重复实现。 +3. **`page_annotation_bridge.cpp` 的 screenshot 通道**:可以保留同一个 binding、只把调用点从「点发送」挪到「save」。这比删掉重写省事,也避免 WebUI 侧再开一条 bridge。 + +--- + +## 5. 建议的落地顺序(每批独立可评审) + +| 批次 | 内容 | 依赖 | +|---|---|---| +| **P0** | 提交当前 WIP 作为基线(或标 `wip/` 分支),让后续 diff 可读 | — | +| **P1** | 记录上提:新增 `SessionAnnotationStore`,`PageAnnotationSession` 改为转发(**行为零变化**,纯搬运) | P0 | +| **P2** | 四态 + `orphan`:`close_page` 不再析构;会话广播所有页签 | P1 | +| **P3** | 截图前移:`save` 时捕获 → `thumbnail`;删工具栏截图按钮 | P1 | +| **P4** | 发送换骨:删 batches,三触发点(输入框 / 工具栏 / `Ctrl+Enter`)收口到 `submitWithAnnotations`,用户文本合流,40s 自查 | P1 / P3 | +| **P5** | 待发卡片 + 铅笔两条路径 | P2 / P4 | +| **P6** | 消息卡片只读化 + openspec 新 change 落地 + 测试补齐 | P4 / P5 | + +P1 之前的 WIP 建议**先提交**——否则记录上提的 diff 会混在 4445 行里,评审时谁也看不出哪些是搬运、哪些是新逻辑。 diff --git a/external/cpp-mcp b/external/cpp-mcp index 62a8c88da..3cd98f1be 160000 --- a/external/cpp-mcp +++ b/external/cpp-mcp @@ -1 +1 @@ -Subproject commit 62a8c88da46b3d3c540dd14191c8c39f27095fb0 +Subproject commit 3cd98f1becc49ca98ab82a8632d61f12da5a4e66 diff --git a/openspec/changes/add-html-page-annotations/.openspec.yaml b/openspec/changes/add-html-page-annotations/.openspec.yaml new file mode 100644 index 000000000..41484f318 --- /dev/null +++ b/openspec/changes/add-html-page-annotations/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-18 diff --git a/openspec/changes/add-html-page-annotations/design.md b/openspec/changes/add-html-page-annotations/design.md new file mode 100644 index 000000000..7fc7a75d4 --- /dev/null +++ b/openspec/changes/add-html-page-annotations/design.md @@ -0,0 +1,422 @@ +> **Superseded(2026-11-22)**:本文档描述的路线(预览为主 / 整页截图 / 不可变记录 / 收据去重 / 导航确认)已被 `openspec/changes/redesign-html-page-annotations/` 取代,不再维护。 +> 现行方案见 `docs/specs/2026-11-21-html-page-annotations-technical-design.md`,WIP 现状见 `docs/specs/2026-11-22-html-page-annotations-wip-alignment.md`。 + +# Design + +## Context + +See proposal.md for motivation and GitHub spec #193 for the complete approved contract. Native browser pages sit above the trusted WebUI; existing surface coordination supports local occlusion on Windows/macOS. Existing element selection and automation evaluation provide native-controlled page execution. Existing screenshot handling on macOS captures webview bounds, not a full page. Conversation submission supports queue/steer and client identities, but this is not proof of durable batch receipt/deduplication. + +## Goals / Non-Goals + +**Goals:** preserve page/host trust separation and existing submission ownership while adding one annotation lifecycle per page/document; make capture and receipt failures explicit and testable. + +**Non-Goals:** no page-accessible send bridge, no replacing source selection, no disk-writing preview, no saved-record editing/deletion, no restart persistence. Scope remains exactly #193. + +## Decisions + +1. Separate page runtime locating/markers/previews from trusted popup and batch state. Render the popup over the browser using host-controlled overlay/surface coordination (or native hosting where needed), never in the chat column. Reuse existing trusted desktop bridging, validate page/document identity on every command/result, and keep page execution incapable of submitting conversations. Arbitrary page messages are not privileged commands. +2. Store semantic records with stable IDs, monotonically increasing numbers, page/document identity, target summaries/locators, one optional page-coordinate region, shared description, per-target actual differences and pending/sending/sent state. Runtime DOM references do not cross transport. Preview stylesheet and reversible text-node records form independent layers; cancellation removes the current layer only. Original view disables previews and hides numbered pins while retaining their records. Preserve original inline styles and child-node identity. +3. Reuse supported native capture boundaries with an explicit full-page request, preserving current viewport defaults. Native adapters must capture beyond the viewport or report an error; bounded resource failures must not silently truncate. Tie capture to the same document snapshot used by the frozen batch. + + Capture implementation (#198): the existing authenticated `Page.captureScreenshot` + proxy accepts `fullPage:true` or `captureBeyondViewport:true`; omitted/false stays on + the viewport path. Windows measures CDP CSS content bounds and the top-frame loader, + reads device scale in an isolated world, and captures an explicit beyond-viewport + clip at CSS-pixel resolution. macOS measures in the existing isolated automation + world and uses `WKWebView.createPDF` with the entire document rect, validating a + single complete PDF page before in-memory PNG rasterization. Neither path resizes + the viewport, scrolls/stitches partial images, writes files or exposes a page bridge. + The async operation rechecks the native page/view, navigation, sharing permission, + document identity and bounds; changed documents/layouts, native errors, budget + overflow and incomplete PNG dimensions/chunks fail recoverably. An opaque returned + capture `documentId` can be passed back for a later capture, but is not implicitly + interchangeable with annotation-runtime document identities. Batch integration must + retain its initiating document binding rather than substitute tokens between the + two boundaries. Limits are 32768 pixels per side, 32 Mi pixels and 32 MiB PNG. + Platform long-page pixel acceptance remains required; WebKit PDF does not promise + protected-media/accelerated-video fidelity. +4. Batch controller freezes IDs/session, captures and prepares a single attachment, then invokes existing conversation submission with explicit queue behavior. Do not use composer state as a buffer. Reuse one batch identity for uncertain retries and implement receiving-side duplicate acceptance rather than relying only on a generated client ID. Receipt drives sent status; capture, upload and request failures do not erase records. +5. Navigation guards operate before host-directed transitions; document/target invalidation handles transitions that cannot be prevented. No locator fallback, no auto-send, no new saved-record deletion. Invalid batches remain blocked during the current application run. +6. Highest test seam is annotation interaction through conversation submission. Use existing frontend behavioral tests, native GoogleTests and browser runtime smoke helpers for supplemental state/DOM/capture tests. Windows/macOS complete desktop acceptance remains separate and cannot be checked off with source-only assertions. + +## Risks / Trade-offs + +- Native surface layering differs between platforms → reuse occlusion/overlay lifecycle and validate real desktop input/focus, not just JSX snapshots. +- Untrusted webpage can manipulate DOM → isolate privileged control, validate document generations, bound payloads, never expose send to page code. +- Dynamic DOM and concurrent previews → retain exact target/node identity, invalidate removed nodes, test overlapping saved/draft layers. +- Tall-page capture may exceed native limits → validate dimensions/resources and fail recoverably rather than truncate or crash. +- Busy submission/session changes/uncertain network results → explicit session-bound batch and receiver-side idempotency with receipt tests. +- No macOS environment on this Windows host → leave real macOS build/manual acceptance outstanding, keep PR draft until required results are available. + +## Migration Plan + +Additive APIs preserve existing viewport capture and source selection. Implement eight approved vertical tickets (#194–201) on one integration branch, with independent implementer worktrees and merger integration. Keep PR draft throughout incomplete acceptance. Rollback is removal of new annotation entry/handlers without rewriting persisted source-selection data. No new mandatory dependencies or persisted annotation migration are assumed. + +## #199 Sender Contracts + +`pageAnnotationBatches.js` owns runtime-only frozen batches, independent of composer +state and the annotation popup controller. Membership, descriptions/differences, +page metadata, initiating conversation and daemon credentials are snapshotted at +send time. One native full-page PNG is uploaded through the existing session +attachment API, then the exact ordinary-message payload is retained under one +`annotation_batch_id`. Busy conversations use ordinary queue admission, not steer. +Concurrent calls share one flight; additions remain eligible for a later batch. + +Native `PageAnnotationSession::submission` validates saved record membership and +document identity. Trusted host `capture` evaluates isolated `validate_batch` against +the exact saved DOM references before and after screenshot measurement. Native +page/view/navigation/current-annotation-document guards and the existing capture +document/bounds/PNG checks must all pass. Capture `documentId` is deliberately a +different identity from runtime `document_id`; only native validation establishes +their relationship. `validate` repeats the runtime check after upload before the +first HTTP attempt. User-initiated annotation capture is available without agent +sharing, without bypassing any automation proxy permission checks. + +Preparation failures retain the frozen membership; upload retries reuse a successful +capture. Uncertain HTTP retries first use +`POST /api/sessions/:id/messages?annotation_reconcile_only=1`, exposed by +`sendInput(sessionId, payload, {reconcileOnly:true})`. This lookup preserves the same +batch ID, exact frozen payload and connection, without recapture/reupload. Query +metadata is excluded from the payload fingerprint. Under the queue admission lock, +lookup returns only an existing matching receipt; an unknown ID returns +`404 annotation_batch_not_accepted` without enqueueing work or consuming the ID. +A matching receipt can therefore be recovered even after document/target invalidation. +Only that exact not-accepted result permits native target/document revalidation +followed by possible first admission; ambiguous lookup errors, malformed receipts +and mismatched IDs never authorize admission. Defined explicit original admission +refusals (`annotation_batch_unavailable`, `annotation_batch_capacity`, +`annotation_batch_conflict`) clear uncertainty and require native revalidation before +another normal submission. No retry is redirected to a newly selected conversation. +Only a matching `queued:true` batch receipt triggers native `acknowledge`; failure of +that final step retries acknowledgement alone. Saved records remain immutable except +their sent status, preserving pins/previews/numbering and retaining invalid records. +The page-scoped sender survives panel unmount; page closure ends its retention. +Neither sender nor receiver claims restart recovery. + +Automated coverage exercises freeze/additions/session changes, concurrent flights, +independent document tokens, capture/upload/validation/submission/ack failures, +malformed/mismatched/duplicate receipts, exact uncertain retries, native membership +validation and saved-pin retention. Full desktop interaction and platform screenshot +pixel acceptance remain section 8 work, not implied by these tests. + +## #194 Implementation Contracts + +The description-only slice uses `page_annotation_runtime.hpp` for exact document/element references, +`page_annotation_session.hpp` for native-owned immutable records, and `page_annotation_bridge.{hpp,cpp}` +for the trusted WebUI entry. Windows resolves the main frame and creates an isolated CDP world before +evaluation; macOS uses its existing automation `WKContentWorld`. There is no page message handler for +annotations and no description, conversation identity or file capability in runtime commands. + +`AgentBrowserHost::annotation_command(page_id, command_json, completion)` accepts only +`start/read/exit/cancel/save`. `PageAnnotationSession::prepare/sequence/complete/fail` serializes commands +and rejects stale completions; native callbacks additionally validate weak host/page identity and +controller incarnation. `replace_document` cancels the draft and invalidates retained records. Only +start accepts an empty initial document ID; save binds the current target ID. Saved records carry +`targets`, empty `differences`, null `region`, pending status and stable page/document/record identity. +Future tickets can extend these explicit fields without conflating actual differences with descriptions. + +`createPageAnnotationController` in `web/src/lib/pageAnnotations.js` binds queued document/target +identity and ignores stale revisions/disposed results. `PageAnnotationPopup` in +`web/src/components/PageAnnotations.jsx` is the trusted editor; its `snapshot/command/working/viewportRef` +interface and existing local native occlusion coordinator are the popup extension seam. The runtime's +closed shadow root contains only outline/control/pins, not a competing editor. Source selection's +`selected_element` event and chat-context behavior remain separate. + +Verification details and outstanding platform checks are recorded in `docs/agent-browser.md` under +“网页描述批注(#194)”. Automated behavioral coverage and Windows translation-unit compilation do not +establish actual Windows/macOS popup layering, focus, hit testing or complete desktop acceptance. +Section 8 platform tasks remain unchecked; capture/send/navigation-confirmation scope remains owned by +the subsequent tickets. + +## #196 Text Preview Contract + +`page_annotation_text_runtime.hpp` exports a factory injected as runtime argument 2 +(argument 3 remains available for styles). `preview_text {target_id,text}` is a +restricted document/target-bound command. The trusted popup uses the target's +`text_preview {value,editable,error}`; typing is serialized before save without +disabling the text field on each keystroke. Save acknowledgments carry only actual +`{target_id,property:"text",old_value,new_value}` differences, including text-only +annotations with an empty description. The baseline is the effective saved text, +not a previous unsaved draft or the temporarily displayed original. + +The helper retains original Text nodes/data and exact parents, applies a common +prefix/suffix replacement to eligible descendant text nodes, and never replaces +an element subtree. Hidden/script/style/form-control content is excluded. The +editor uses concatenated eligible text-node data, not CSS-generated content or +layout-generated line breaks. Empty elements use an owned temporary text node, +removed during original view/cancellation/disposal. Saved node layers and draft +layers are independent; original view disables both and hides pins without deleting their records. +Original inline styles and all existing child nodes/listeners remain untouched. +Text beyond 4096 UTF-16 code units is explicitly non-editable, not truncated; +changed node topology rejects preview/save without selector-based relocation. + +Verification: focused native session tests, production runtime/field JavaScript +behavior tests, and `node tests/desktop/page_annotation_text_smoke.mjs ` +(real DOM identity/listeners and independently toggled stylesheet composition). +Headless Chromium is not Windows WebView2 or macOS WKWebView desktop acceptance; +both full native interaction sequences remain unverified under section 8. + +The production web build and regex compatibility check pass. The full web runner +fails at `agentBrowser.test.js:40` when its readiness timer resumes after the +large static-import workload; the same failure reproduces with the unchanged +base-commit runner (without the new text suites). That suite passes standalone. +This unrelated full-suite scheduling failure remains unresolved, not a passed +acceptance check. +## #195 style implementation and extension contract + +`page_annotation_style_runtime.hpp` exports `kPageAnnotationStyleRuntime`, a +`rootDocument => helper` factory supplied as argument 3 to `kPageAnnotationRuntime`. +Argument 2 remains reserved for the text helper. The style helper exposes +`select(target,id)`, `preview(target,id,styles,ratioLock?)`, `describe(target,id)`, +`differences()`, `save()`, `cancel()`, `setOriginal(enabled)` and `dispose()`. +`save()` returns an array of actual `{target_id,property,old_value,new_value}` +differences. Each exact target has independent saved declarations and a draft +with its own computed baseline, touched properties and default-off current ratio. +The single-target selection adapter cancels its previous draft; the multi-target +adapter must retain those drafts instead. Text integration should validate its +save before committing styles and concatenate both helpers' difference arrays. + +The trusted command additions are `preview_style {target_id,styles,ratio_lock?}` +and `original {enabled}`. Native `PageAnnotationSession` validates fields and +acknowledged differences before storing an immutable record. Runtime snapshots +include `original`, `differences`, and per-target `style_preview` with `values`, +`styles`, `ratio_locked`, `ratio` and `errors`. Saved target summaries omit the +editor-only `style_preview`. The existing serialized controller binds document +and target at enqueue, including previews. The popup flushes dirty inputs before +save and retains edits made while another preview is in flight. + +Constructed stylesheets belong to each Document/ShadowRoot; original inline +declarations and author stylesheet membership remain untouched. Exact targets +receive random marker attributes; copied attributes are removed from clones. +Mode exit/cancel removes drafts only. Original view temporarily disables saved +and draft style declarations and hides numbered pins without deleting their records. Transition suppression is +settled before restoring author declarations so cancellation/comparison does not +leave a long-running transition. A requested border width on a border with style +`none` derives `solid`; actual per-side style/width changes are recorded too. + +**Approved cascade behavior:** follow Codex. Preview rules are unlayered author +stylesheet declarations with `!important` and never rewrite original inline styles. +When an inline `!important` declaration or a more specific layered author +`!important` rule wins, the preview does not report an error, does not record an +ineffective difference, and does not add a user-origin extension. +`style_preview.errors` stays an empty array. Task 2.1 stays open because this is +not arbitrary-page cascade coverage, and real Windows/macOS desktop acceptance is +still outstanding. + +**Codex annotation chrome:** the comment card and toolbar follow the observed +Codex desktop controls without copying Codex source. In annotation mode, pointer +hover shows an element outline and a compact card with tag, rendered size, color +and font; one unmodified primary click immediately opens the annotation card. +The collapsed card is 294px, the expanded card is at most 380px, and the +top-left `调整` control uses `aria-expanded`, not `aria-pressed`. The card header +stays fixed, the property editor scrolls inside a 230px ceiling, and the action +footer stays fixed. There is no longer a separate target-type row inside the +style stack: the target tag (e.g. `/p`, `/div`) sits on the same row as the drag +grip at the top of the expanded card, and the last field in the scrolling editor +keeps a 2px gap above the action-bar divider. +Rows align their labels by text content and put the value control in a stable +176px second column. Collapsed four-way spacing controls keep at least 45px of +usable width per input and wrap when the viewport cannot preserve that width. +Color rows include a swatch, font/weight rows use a picker, +numeric rows split the value from its unit, edited rows expose a restore action, +and every edit previews live. Opacity is entered as `0..100%` and clamped before +conversion to CSS `0..1`. Width/height and padding/margin pairs use centered +circular lock controls between upper and lower T-shaped guides; the controls have +default, hover, and locked states, and paired locks propagate values +independently. Collapsed padding/margin rows keep four editable values, and +expanded rows replace them with their vertical/horizontal pair controls. +The value grid reserves the leading reset area only when a reset is visible, and +the two-column gap pair uses a smaller reservation so edited values retain a +readable value-and-unit control. Width/height and spacing locks share one T-shaped +bracket (26×62 path `M4 3H23V21M23 41V59H4`) with a centered 16×16 circular lock +badge, replacing the earlier 14px link icon; the badge has default, hover and locked +states. The editor also exposes letter spacing, word spacing and row/column gap +fields, a font family picker (Inter/System/Arial/Serif/Mono plus in-page custom +values) with weights 100–900, spacing pairs inferred from equal non-zero values, +and a 20ms debounce with `CSS.supports` gating before a live preview is sent. + +The floating toolbar is a dark rounded bar with a draggable grip, +`正在批注 · {count}`, screenshot-copy, hide-marker toggle, hold-to-view-original, +discard-all, blue `发送`, and exit. The count column is width-stable. Discard asks +`丢弃所有待处理标注?` with the body lines `页面上的所有编辑都将被移除` and +`放弃后所有标记和修改都被清空` before the `取消` / `放弃` actions (no full stop). +The dialog uses `dismissOnBackdrop={false}`: clicking the backdrop does not close it, +and while it is open the native page stays painted but input is disabled and the +in-page chrome is suspended. Discard clears every saved record and resets numbering +to 1. The toolbar hides while a card or selection mode is active and when annotation +mode ends, so it cannot strand a lone send button. Clicking outside an open card +cancels that draft without leaving annotation mode. The adjust and submit buttons +show descriptive tooltips; submit also shows `Enter 发送 · Ctrl+Enter`. + +The toolbar is mounted inside the browser viewport as an overlay, defaults to +horizontally centered 16px above the bottom (52px tall, 14px radius, draggable via a +grip clamped inside the viewport), and switches to absolute positioning after a drag. +The send button has a stable width (min 64px); its label is `发送` / `发送中` / `重试` +for idle/working/retry states. With no conversation it shows an inline `请先选择对话` +note and disables send. Screenshot copy confirms with `已复制截图` for 1800ms and +falls back to `网页截图失败` / `无法复制截图`. The hold-original control also responds +to Space/Enter and restores the page when the pointer leaves the button. The annotation +entry in the browser toolbar is a 16px chat icon with tooltip `网页批注` / `退出网页批注`; +the former standalone `原始页面` button was removed. + +The model still receives `Page annotations` plus the structured JSON and the +full-page screenshot. The transcript renders that message as a card: the screenshot +crop, the page title, and non-empty descriptions. Numbers appear only when there is +more than one description. Bounds, locators, element text, and differences stay out +of the card. The address-bar control is a fixed 30×30 icon and does not gain a text +label while active. +### Focused native standards boundaries + +The hosts retain page membership, navigation/controller incarnation, sharing and annotation +sequence checks. `agent_browser_capture_cdp` owns full-page CDP measurement/clip orchestration +behind injected command/current/completion functions; `agent_browser_native_commands_win` +owns WebView2 transport and isolated annotation evaluation. `agent_browser_capture_mac` owns +WebKit snapshot/PDF/rasterization, with native-view retention and host-guarded evaluation. +`agent_browser_proxy_request` owns the existing authenticated request/deadline and exactly-once +completion/wait contract shared by both hosts. `agent_browser_state_json` owns browser-state +serialization without changing optional selected-element or annotations payload semantics. +These extractions preserve viewport defaults and full-page bounds/PNG/stale-document checks. + +The shared capture probe lives under `tests/test_support/desktop` and both native smoke +programs include that full prefix. The ownership scanner masks only actual include header +tokens before scanning allocations; preprocessor macro allocations remain counted. No size +or ownership baseline is changed. Native runtime/pixel acceptance remains separate from +the focused boundary tests and translation-unit compilation. + +The probe checks native errors and object shape before inspecting command/evaluation +results, validates capture metadata types, and retains the original native error on +failure. A platform-neutral checked-command seam has fake-client regressions for null +full-page responses, malformed results, and transport errors; it does not replace the +native pixel check or establish real capture acceptance. + +### Windows full-page scrollbar restoration + +WebView2 157.0.4341.60's surface screenshot hides the classic root scrollbar and can +leave the restored document laid out at the scrollbar-free width (845 to 860 CSS +pixels in the native fixture). Waiting for animation frames or forcing layout alone +does not restore it. Disabling beyond-viewport painting instead loses real bottom +pixels. Neither widening measured bounds nor accepting a viewport image is valid. + +`agent_browser_capture_layout` owns the narrow CDP workaround behind the existing +injected native-command/current/completion seam. It inspects root computed styles +in an isolated world. With a classic auto gutter, a distinct, forced inspector +stylesheet reserves the existing gutter during capture. An existing stable or +stable-both-edges gutter is not replaced: the owned sheet briefly flips overflowing +root `overflow-y` between auto and scroll and forces layout after capture. The +helper clears only its own sheet text before completion, including native failure +and stale-page paths; it never edits original inline declarations, scroll position +or viewport settings. It does not disable shared DOM/CSS domains. A preflight +computed-style check rejects author cascade priorities that block the workaround +with `capture_layout_unsupported` before taking a screenshot. Cleanup failures +cannot produce success, and an earlier native error is retained. + +The original document identity, strict pre/post bounds and scale comparisons, +resource budgets, complete-PNG validation and viewport-capture path remain intact. +The native probe removes the example page's external body max-width constraint +from its own fixture and uses explicit CSS pixel units when restoring fixture +height. Its pixel sample therefore tests green content, not the gray area outside +the body. It also checks root client dimensions, original inline styles and author +stylesheet count, in addition to scroll/viewport preservation. This is scoped +Windows capture evidence, not complete annotation workflow or macOS acceptance. + +## Native overlay geometry and edge fidelity (2026-11) + +`web/src/lib/agentBrowserSurfaceCoordinator.js` owns the occlusion geometry sent to +both hosts. `AgentBrowserOcclusionRect` carries `radius` and a `square_corners` bit +mask (1=TL, 2=TR, 4=BR, 8=BL, clamped to 0..15); a set bit means that corner stays +square because the browser viewport clipped that edge. Holes with differing radii +or any non-zero `square_corners` are not merged. The layout signature includes +`radius`, `square_corners` and `interaction_blocked` so a changed hole is not +dropped by deduplication. + +Conversion to surface pixels uses `Math.floor` for left/top and `Math.ceil` plus +`HOLE_FAR_EDGE_GUARD = 1` for right/bottom, clamped to the surface bounds. The extra +device pixel compensates for the native window region being a 1-bit mask whose far +(right/bottom) edge is open, which otherwise eats a 1px border. `radius` is clamped +to `floor(min(width,height)/2)` and to 0..32768; IPC parsing defaults `radius` and +`square_corners` to 0 and rejects out-of-range values with +`Agent Browser occlusion rectangle is invalid`. + +On Windows, `apply_agent_browser_widget_region` draws `CreateRoundRectRgn` with +`radius*2`, then for each set corner ORs back a `radius×radius` square before +`RGN_DIFF` subtraction, restoring that corner to a right angle. On macOS, +`square_corners == 0xF` draws a plain rect hole, `0` uses `CGPathAddRoundedRect` on +all corners, and mixed masks use `add_occlusion_cornered_hole` with +`CGPathAddArcToPoint` per corner (0 radius for a square corner); the mask uses +even-odd fill with edge antialiasing off. The radius clamp and mask clamp are applied +on both hosts. + +To avoid a white halo when an implicit overlay sits on a coloured page, +`NATIVE_SURFACE_IMPLICIT_OVERLAY_BLEED = 1` gives menu/listbox/tooltip overlays a +1 CSS-pixel default bleed, overridable by `data-ace-native-overlay-bleed` clamped to +0..8. The annotation card deliberately declares no bleed and snaps to its own pixel +grid; cards, toolbar and selection menus drop the earlier `0 0 0 1px` halo ring so +their edges stay consistent on any page colour. + +## Modal suspension and native input blocking (2026-11) + +The runtime accepts `set_modal_suspended {enabled}`: while suspended it hides all +selection/hover/region outlines and the hover card, clears `hovered`, and early-returns +from select/pointer handlers; `start` and `exit` reset it. The session permits this +action with a boolean `enabled` only (`Invalid modal suspension request` otherwise), +exposes `modal_suspended` in the snapshot, and clears it on discard/document replace. + +`annotationChromeSuspension.js` reference-counts named sources (menu, dialog) so the +feedback emit fires only on 0→1 and 1→0 edges. A visible WebUI `[role=menu]` under a +MutationObserver suspends chrome; the discard dialog calls `suspendDialogChrome`. +`preview_text`, `preview_style` and `set_modal_suspended` are quiet commands that do +not enter the busy state, so opening a menu cannot grey out the toolbar. + +`AgentBrowserBounds.interaction_blocked` keeps the native page painted but ignores +pointer/keyboard input: Windows calls `EnableWindow(widget, FALSE)` while shown and +restores it when hidden; macOS `hitTest:` returns `nil`. The WebUI writes this from a +visible overlapping `[data-ace-native-interaction="disabled"]` marker via +`nativeSurfaceInteractionBlockedByDocument`, and `Modal` supports `nativeOverlayMode` +(overlap/blocking) plus `nativeOverlayInteraction` (disabled/blocking) so a dialog can +keep the page visible while blocking its input. + +## Hover-card lifecycle (2026-11) + +The hover outline is 1px `Highlight` with a 2px radius; the info card is +168–260px wide with 8px padding and 10px radius, placed 6px below the target and +flipped above when space is short, with colour normalised to `#rrggbb` and alpha 0 +shown as `transparent`. It renders only when not modal-suspended, active, target +connected, not dragging, not in region mode, and (when a card is open) in element +selection mode. `pointerout` with no `relatedTarget` and window `blur` both call +`dropHover`, so the card dies on pointer-leave/focus-loss instead of staying pinned. + +## Screenshot bridge, localisation and message card (2026-11) + +A user-initiated viewport screenshot bridge +`aceDesktop_agentBrowserAnnotationScreenshot({page_id})` returns +`{ok, data, mimeType:'image/png'}` and reports `Invalid annotation screenshot request` +or `Browser closed`; the host adapter's `annotation_dispatch` accepts +`action:'screenshot'` on the viewport path (`{format:'png'}`), yielding +`Annotation capture is already running` when a capture is in flight. This is distinct +from the full-page capture used by the batch sender. + +`pageAnnotationBatches.js` localises native errors before display: +`annotation_target_or_document_changed` / `Annotation document or target is invalid` +→ `批注目标已失效,请重新选择元素后再发送`, `capture_document_changed` → +`网页内容已变化,请重新批注后再发送`, `Annotation page is unavailable` → +`批注页面不可用`, `Annotation capture is already running` → +`截图正在进行中,请稍后再试`; missing `sessionId` and missing `api` are now separate +`请先选择对话` / `批注页面不可用` errors. `PageAnnotationTextField` maps the two +English `text_preview.error` strings to Chinese copy. All these strings are in the +i18n catalog with English overrides. + +`pageAnnotationMessage.js` parses only payloads headed `Page annotations\n`, keeps +non-empty descriptions, and falls back to index+1 for non-positive numbers. +`pageAnnotationMessageCopyText` builds a title/description plain-text summary with +numbers only for multiple comments. `pageAnnotationScreenshot` recognises +`page-annotations-*.png` attachments; `contentPartsWithoutAnnotationScreenshot` +removes them from the generic attachment strip. `PageAnnotationMessageCard` renders +the title, a `{N} 条注释` footer and a click-to-enlarge screenshot, and is a tracked +production component (not a test helper). + +`page_background` (from body/documentElement computed `backgroundColor`, falling +back to `#ffffff`) and `style_preview.previous_values` are additional snapshot +fields used by the UI. `text`/`style` helpers gained `discardAll()`, and runtime +`discard` reverts all text/style layers, clears pins, resets `original`, +`markersHidden` and `modalSuspended`, and the session resets numbering to 1. diff --git a/openspec/changes/add-html-page-annotations/proposal.md b/openspec/changes/add-html-page-annotations/proposal.md new file mode 100644 index 000000000..a4b587375 --- /dev/null +++ b/openspec/changes/add-html-page-annotations/proposal.md @@ -0,0 +1,30 @@ +> **Superseded(2026-11-22)**:本文档描述的路线(预览为主 / 整页截图 / 不可变记录 / 收据去重 / 导航确认)已被 `openspec/changes/redesign-html-page-annotations/` 取代,不再维护。 +> 现行方案见 `docs/specs/2026-11-21-html-page-annotations-technical-design.md`,WIP 现状见 `docs/specs/2026-11-22-html-page-annotations-wip-alignment.md`。 + +# Proposal + +## Why + +Desktop users cannot point at rendered elements or regions when requesting HTML/CSS changes. Source-selection annotations cannot capture visual intent, reversible previews or a full-page visual reference. + +## What Changes + +- Add Windows/macOS Agent Browser page annotations with host-controlled popup, element markers and reversible text/style previews. +- Save immutable numbered pins with multiple element targets and at most one region per annotation; preserve previews and pins through original-view comparison and sending. +- Send pending annotations through the existing conversation boundary in one acknowledged, deduplicated batch with one full-page screenshot; protect drafts and navigate/refresh safely. +- Extend full-page capture on both native platforms without changing existing viewport capture defaults. +- Preserve source-selection annotation behavior and untrusted-page isolation. + +## Capabilities + +### New Capabilities + +- `html-page-annotations`: Desktop page selection, reversible preview, saved pins, guarded batch submission and failure handling. + +### Modified Capabilities + +None. The capability inventory has no existing main specs. + +## Impact + +Native desktop browser hosting/bridges and screenshot adapters, trusted WebUI browser surface coordination and conversation submission, submission receipt/deduplication, and corresponding tests/docs. No Linux/TUI, standalone HTML file rendering, vendored changes or new page-accessible conversation capabilities. Spec #193; tickets #194–201. diff --git a/openspec/changes/add-html-page-annotations/specs/html-page-annotations/spec.md b/openspec/changes/add-html-page-annotations/specs/html-page-annotations/spec.md new file mode 100644 index 000000000..cd3bb4e6c --- /dev/null +++ b/openspec/changes/add-html-page-annotations/specs/html-page-annotations/spec.md @@ -0,0 +1,119 @@ +> **Superseded(2026-11-22)**:本文档描述的路线(预览为主 / 整页截图 / 不可变记录 / 收据去重 / 导航确认)已被 `openspec/changes/redesign-html-page-annotations/` 取代,不再维护。 +> 现行方案见 `docs/specs/2026-11-21-html-page-annotations-technical-design.md`,WIP 现状见 `docs/specs/2026-11-22-html-page-annotations-wip-alignment.md`。 + +# HTML Page Annotations + +## Purpose + +Allow desktop users to communicate visual webpage changes through reversible previews, numbered target annotations and reliable conversation batches, without editing source files until they explicitly send the request to the model. + +## ADDED Requirements + +### Requirement: Desktop page annotation controls +The system SHALL support annotation mode on loaded Windows/macOS Agent Browser webpages, with toolbar entry, an element outline and a host-controlled popup above the browser. A single unmodified primary click on an element SHALL open the annotation card directly; the runtime renders no separate in-page "Annotate" control button. It MUST NOT replace the popup with chat-column controls or expose general host/conversation capabilities to webpages. + +#### Scenario: Save a description without sending +- **WHEN** the user selects an element, opens its control, enters a description and saves +- **THEN** one numbered pin and pending count appear, without a conversation message or HTML/CSS disk write +- **AND** closing annotation mode hides editing controls but keeps saved pins and previews + +### Requirement: Pointer-accurate annotation surface +While annotation mode is active and no popup is blocking selection, moving the pointer over a page element SHALL show a hover outline and a compact information card containing the target tag, rendered size, color and font. A single primary click SHALL open the host-controlled annotation card immediately. The hover outline and information card SHALL be suppressed while any WebUI menu is open or a modal dialog is active, and SHALL be removed when the pointer leaves the webview (`pointerout` with no related target) or the window loses focus, so the last card never stays pinned over the page. These feedback-only state changes MUST NOT mark the annotation session busy. + +The annotation card SHALL keep its header and action footer fixed, cap its scrolling property editor at 230px, omit a separate target-element type row, left-align property labels by text, split numeric values from units, expose a restore action for edited values, and preview property edits live. Opacity SHALL use a visible `0..100%` control and clamp out-of-range input. Width/height and vertical/horizontal padding/margin locks SHALL center a circular lock control between upper and lower T-shaped guides, distinguish default, hover and locked states, and propagate paired values independently. Collapsed padding and margin rows SHALL retain four editable values. + +Paired numeric controls SHALL keep each value and its unit fully inside the control before and after a restore action appears. Collapsed four-way spacing controls SHALL provide at least 45px of usable width per input and wrap rather than shrink below that width. Width/height and spacing pair locks SHALL use a shared T-shaped bracket with a centered circular lock badge in default, hover and locked states. In the expanded card the target tag (for example `/p` or `/div`) SHALL share the drag-handle row with the grip, and the scrolling editor's last visible-text field SHALL keep a 2px gap above the action-bar divider. + +The editor SHALL also support letter spacing, word spacing and separate row/column gaps, a font picker with preset families and nine weight steps (100–900), and inferred-and-propagating vertical/horizontal spacing pairs. The description field SHALL switch its placeholder between collapsed and adjusting states and cap input at 4096 characters. + +#### Scenario: Dismiss an open annotation card +- **WHEN** the annotation card is open and the user clicks an unmodified primary click outside it +- **THEN** the current unsaved card draft is cancelled and annotation mode remains active + +#### Scenario: Use the floating annotation toolbar +- **WHEN** annotation mode is active without an open card or active selection mode +- **THEN** the toolbar exposes screenshot copy, hide markers, hold-to-view-original, discard-all, send and exit with their defined tooltips and pressed states +- **AND** discard-all first shows the exact pending-annotation confirmation +- **AND** the toolbar is hidden while a card or selection mode is active + +### Requirement: Reversible actual-change previews +The system SHALL preview visible text, text color, background, opacity, font, font size/weight, letter spacing, word spacing, radius, border color/width, width/height, row/column gap, spacing, padding and margin. It SHALL record only actual old/new differences, preserve text child nodes and original inline styles, and revert only the current draft on cancel. Width/height lock SHALL default off and use the current aspect ratio when enabled. + +#### Scenario: Cancel a second edit of the same element +- **WHEN** a saved preview exists and the user modifies that target again then cancels +- **THEN** the earlier saved preview and child-node identities remain, and only the current draft is reverted + +#### Scenario: Compare with the original +- **WHEN** the user toggles original view +- **THEN** all preview modifications are temporarily disabled and numbered pins are hidden +- **AND** toggling back restores saved previews and numbered pins without deleting annotations + +### Requirement: Multiple targets and one region +The system SHALL allow multiple elements and at most one page-coordinate region per annotation, with one shared description and numbered pin. Regions SHALL NOT offer property/text editing. Saved annotations SHALL NOT be editable or deletable. + +#### Scenario: Replace a selected region +- **WHEN** the user adds another region to a draft already containing one +- **THEN** the new region replaces the old and retains the draft's other targets and shared description + +### Requirement: Acknowledged conversation batches +The system SHALL freeze pending sendable annotations into a batch bound to its initiating conversation and submit one user message containing numbered targets/descriptions/old-new differences and exactly one send-time full-page screenshot, including beyond the viewport. It SHALL prepare the screenshot/attachment before submission, preserve composer drafts/attachments, queue rather than steer busy model turns, and mark sent only after receipt. Retried batch identities MUST be deduplicated by the receiving boundary. + +#### Scenario: Send while switching conversation +- **WHEN** a batch is being sent and the user switches conversation and adds another annotation +- **THEN** the original batch is submitted to its initiating conversation and the addition remains for the next batch +- **AND** accepted records keep pins/previews, pending count clears only for those records, and new numbers continue increasing + +#### Scenario: Empty description and capture failure +- **WHEN** a batch has differences but no description +- **THEN** it is sendable, but capture/attachment failure prevents any partial submission and preserves retryable pending work +- **AND** records with neither description nor differences are not sent + +#### Scenario: Uncertain submission receipt +- **WHEN** submission fails or acceptance is uncertain +- **THEN** the same batch identity is retained for reconciliation/retry and duplicate model requests are prevented + +### Requirement: Page lifecycle and invalidation safety +The system SHALL prompt before active navigation/refresh with draft/pending work, default to staying, and never auto-send. Document replacement SHALL stop old previews and retain unsent invalid records without reattaching locators. Target removal SHALL invalidate the record and block its affected batch rather than matching similar elements. No usable conversation SHALL block send without creating or redirecting a conversation. Retention SHALL be limited to the current app run. + +#### Scenario: Target disappears before send +- **WHEN** an annotated element is removed or its document is replaced +- **THEN** its unsent record is retained as invalid, no similar/new target is modified, and its batch cannot send + +#### Scenario: Discard all pending annotations +- **WHEN** the user confirms discard-all +- **THEN** every saved record and pin is cleared and numbering restarts at 1, with the page's previews and drafts fully reverted + +### Requirement: Native overlay edge fidelity +Every floating surface introduced or touched this iteration — annotation cards, the floating toolbar, the element hover card, browser "more" and tab context menus, and font dropdowns — SHALL keep a complete 1px border and SHALL NOT show a white halo or jagged edge where it overlaps a colored webpage. Native occlusion holes SHALL follow each overlay's border radius, keep corners that are clipped by the browser viewport square, and extend just beyond the overlay border box so the native 1-bit region does not consume the border. Implicit menu/listbox/tooltip overlays SHALL use a small bounded default bleed that can be disabled per element. + +#### Scenario: Rounded overlay over a colored page +- **WHEN** a rounded menu or the annotation card overlaps a non-white page region +- **THEN** its border stays visible on all four sides with no white ring, and corners clipped by the viewport remain square + +### Requirement: Layered modal suspension and native input blocking +When a trusted WebUI menu is open or a modal dialog is active over the browser surface, the system SHALL suspend in-page annotation chrome (selection/hover outlines, hover card and region outlines) and, for modal dialogs that keep the page visible, SHALL keep the native page painted while blocking pointer and keyboard input to it. Suspension SHALL be reference-counted by named source so overlapping blockers resume exactly once. Discard confirmation SHALL keep the page visible and MUST NOT close when the backdrop is clicked. Feedback-only suspension MUST NOT mark the annotation session busy. + +#### Scenario: Menu or dialog covers the page +- **WHEN** a WebUI menu opens or the discard confirmation dialog is shown +- **THEN** in-page outlines and hover cards are hidden, native page input is blocked for the dialog, and closing every blocker restores chrome exactly once + +### Requirement: Send feedback and error localisation +The toolbar SHALL show `请先选择对话` inline and disable send when no conversation is selected, rather than failing only after a click. Native send failures and page-capture failures SHALL be mapped to Chinese product messages before display — including `批注目标已失效,请重新选择元素后再发送`, `网页内容已变化,请重新批注后再发送`, `截图正在进行中,请稍后再试`, `批注页面不可用`, `网页截图失败`, `无法复制截图` — and raw machine codes or English runtime text MUST NOT leak into the UI. The visible-text editor SHALL likewise map its native text-preview errors to Chinese copy. Screenshot copy SHALL confirm with `已复制截图` and clear the confirmation automatically. + +#### Scenario: Stale target or no conversation +- **WHEN** the annotated target changes before send, or no conversation is selected +- **THEN** the user sees a Chinese product message or the inline `请先选择对话` note, never a raw error code, and send is disabled when no conversation is selected + +### Requirement: Annotation message presentation +A submitted batch SHALL render as a message card showing the page title, non-empty descriptions and the full-page screenshot; numeric labels SHALL appear only when more than one description exists. Only a well-formed `Page annotations` JSON payload SHALL be parsed into the card. The card SHALL expose a `{N} 条注释` footer, allow the screenshot to be opened in an image viewer, and copy as a plain-text title/description summary rather than the raw JSON message. The batch screenshot attachment, named with a `page-annotations-*.png` prefix, SHALL be excluded from the generic attachment strip to avoid duplication. + +#### Scenario: View and copy an annotation message +- **WHEN** a sent batch appears in the transcript and the user opens its screenshot or copies the message +- **THEN** the screenshot opens in an image viewer and the copy is a plain-text title/description summary, with the screenshot shown only inside the card + +### Requirement: Acceptance and compatibility +The feature SHALL preserve existing source-selection annotations and require behavioral automated coverage plus real Windows and macOS complete-workflow acceptance, including full-page screenshot pixels beyond the viewport. Unexecuted checks MUST remain explicitly unverified. + +#### Scenario: Platform acceptance is unavailable +- **WHEN** a platform's real desktop acceptance cannot be executed +- **THEN** it is recorded as unverified, not substituted by automated or reference-app observations diff --git a/openspec/changes/add-html-page-annotations/tasks.md b/openspec/changes/add-html-page-annotations/tasks.md new file mode 100644 index 000000000..5214008c1 --- /dev/null +++ b/openspec/changes/add-html-page-annotations/tasks.md @@ -0,0 +1,273 @@ +> **Superseded(2026-11-22)**:本文档描述的路线(预览为主 / 整页截图 / 不可变记录 / 收据去重 / 导航确认)已被 `openspec/changes/redesign-html-page-annotations/` 取代,不再维护。 +> 现行方案见 `docs/specs/2026-11-21-html-page-annotations-technical-design.md`,WIP 现状见 `docs/specs/2026-11-22-html-page-annotations-wip-alignment.md`。 + +# Tasks + +## 1. Element annotation closed loop (#194) + +- [x] 1.1 Add document-bound annotation runtime and restricted native/trusted commands; verify stale-document and untrusted-command rejection. +- [x] 1.2 Add toolbar entry, element outline/control and host-controlled popup over the browser; verify save creates a numbered pin and pending count without submission or file writes. +- [x] 1.3 Preserve saved pins on mode exit and immutable saved records; verify behavior and existing source-selection regression tests. + +## 2. Reversible style previews (#195) + +- [ ] 2.1 Implement all approved style fields through independent stylesheet layers and actual-difference filtering; verify every property and untouched original inline styles. +- [x] 2.2 Add default-off current-ratio lock and draft-only cancellation over saved layers; verify repeated edits of the same target. +- [x] 2.3 Add original-view comparison hiding numbered pins and restoring previews; verify round trips and mode exit. + +## 3. Visible text previews (#196) + +- [x] 3.1 Implement reversible text-node previews preserving child-node identity; verify nested elements, text changes and exact restoration. +- [x] 3.2 Integrate saved/draft/original text layers and actual differences; verify cancellation retains earlier saved text. + +## 4. Multiple targets and region (#197) + +- [x] 4.1 Support adding multiple elements to one draft with shared description/pin; verify target switching and save. +- [x] 4.2 Support one page-coordinate region replaced by subsequent drags without property editing; verify scroll coordinates and replacement. + +Implementation contract (#197): `targets` contains at most 64 unique exact element identities; +`target` is the current element or null when the region is selected. `region` is null or one +finite, positive-size page-CSS-coordinate `{x,y,width,height}` rectangle. `selection_mode` is +null, `element` or `region`; the trusted popup stays mounted but hidden during picking, so its +single description survives target switching/replacement. `add_target`, `add_region`, `select_target` +and `select_region` are restricted native actions, not page message capabilities. Save binds the +document, current target, ordered `target_ids` and region; one record/number/pin covers the whole +draft. Required target summary/identity/bounds fields are validated while bounded target metadata +and the existing differences slots remain available to #195/#196; no text/style fields are added. +The shared native session and runtime retain the existing callback sequence/incarnation guards. + +Focused runtime/popup behavioral tests and eight native session GoogleTests cover deduplication, +switching, shared description/save/cancel, page-coordinate scrolling, reverse drag, region replacement, +untrusted/cancelled/zero-area drags, malformed arrays/regions, stale identity and immutable records. +Real Windows/macOS desktop interaction acceptance is not claimed by these automated tests; +section 8 remains unchanged. +Verification: standalone annotation JS tests, all eight native session tests (MSVC Release), +and `pnpm build` pass. Full `pnpm test` fails at the unchanged `agentBrowser.test.js:40` +native-page readiness assertion under the combined runner; that suite passes standalone. + +## 5. Full-page native screenshot (#198) + +- [x] 5.1 Add explicit full-page capture on Windows preserving viewport defaults; verify bounds/resource failures and beyond-viewport capture. +- [ ] 5.2 Add explicit full-page capture on macOS preserving viewport defaults; verify native implementation and capture contract tests. + +Ticket #198 implementation: explicit `fullPage`/`captureBeyondViewport` routing, +document/page-bound capture orchestration, bounds/PNG budgets and recoverable failures +are implemented. Windows uses CDP full-document bounds/clip; macOS uses WebKit PDF +capture plus complete-single-page PNG rasterization. Viewport paths remain separate. + +Verified locally on Windows: 11 focused `AgentBrowserCapture` GoogleTests pass using +an isolated MSVC build; `agent_browser_host.cpp` compiles independently against the +existing SDK headers without configuring/installing vcpkg. The Windows smoke source +also compiles, and WIC successfully decodes the tall PNG test fixture's bottom green +pixel. These tests cover request +defaults, malformed/conflicting requests, tall-image contract, resource/bounds limits, +truncated/corrupt PNG, stale page/document/layout/scale callbacks and retry after failure. +Native smoke helpers now include a deterministic tall-page probe that decodes PNG +pixels below the viewport, checks viewport/scroll preservation, rejects stale document +tokens/resource overflow and retries. The native probes have not been executed here. +Windows full native link/runtime acceptance and macOS compile/runtime/pixel acceptance +remained unverified at this historical checkpoint; see the final 39cd verification +below for Windows 5.1. macOS 5.2 remains unchecked. +`openspec validate add-html-page-annotations --strict` and `git diff --check` pass. + +## 6. Reliable batch send (#199) + +- [x] 6.1 Freeze sendable membership and initiating session, capture/upload one full-page image before submitting; verify composer preservation, differences-only requests and concurrent additions. +- [x] 6.2 Submit through existing conversation boundary with queue semantics, receipts and receiver-side batch deduplication; verify busy mode, switching sessions and uncertain retry. +- [x] 6.3 Retain pending data on preparation/submission failure and acknowledge only accepted records; verify pin retention, counts and increasing numbers. + +Ticket #199 sender: extracted page-scoped in-memory batch controller and send bar; +existing composer/source-selection paths are not used as buffers or modified. Native +trusted capture/validate/acknowledge commands validate owned membership and exact +runtime document/targets, without equating annotation and capture identity tokens. +Ordinary session message admission uses the already integrated bounded receiver +idempotency prerequisite; no new receiver work or steer path is introduced. + +Verified: batch-controller freeze/concurrency/additions/conversation/transport tests, +description/differences filtering, every capture/upload/validate/receipt/ack failure, +matching receipt before acknowledgement, exact payload retries and source/composer +boundary regressions; native session membership/acknowledgement and runtime exact +target tests; 19 isolated MSVC session/capture tests; Windows host syntax compile; +full `pnpm test`, `pnpm build` and regenerated source i18n catalog. The prior receiver +prerequisite separately verified concurrent duplicate acceptance/conflict/rejection +and ordinary/busy queue admission. Native full integration/link, actual Windows +workflow and macOS compile/runtime remain section 8 acceptance, not claimed here. +Sender/receiver retention is runtime-only with no restart-recovery guarantee. +Strict layer/ownership scans still report the inherited host/main size, capture +test-helper location, capture allocation and annotation-bridge capture findings. +The sender adds host lines but no new dependency/ownership findings. Native boundary +extraction is being implemented separately; no baseline exceptions are added here. + +## 7. Navigation and invalidation (#200) + +- [x] 7.1 Guard active navigation/refresh with default-stay confirmation and no auto-send; verify all host entry paths. +- [x] 7.2 Retain invalid unsent records on document replacement or target removal and block affected batches without relocation; verify stale callbacks and absent conversation. + +Ticket #200: document replacement retains invalid unsent records and numbering; exact +element/ancestor removal (including shadow roots and remove/reinsert in one turn) +invalidates the whole saved record without locator relocation and restores previews. +Page-coordinate regions survive scrolling and mode exit. Default-stay native confirmation +covers toolbar/address/history/reload, page navigation, destructive authenticated proxy +commands, cookie/controller replacement and clear-data reload. Frozen store transitions +reserve all affected pages before prompting; identity/revision/sequence/ticket checks +reject nested-modal and asynchronous stale continuations. Sending holds a bounded trusted +lease through receiver admission; page code receives no privileged messaging capability. +Passive polling is single-flight and does not advance ordinary command sequence. + +Verified: 37 isolated MSVC session/navigation/native-boundary GoogleTests, Windows +host/transport/bridge compilation, batch sender lease tests, real headless Chromium DOM +lifecycle smoke, pnpm build, all four strict layer/size/ownership/document-path gates +without baseline changes, and git diff --check. Full pnpm test remains blocked by the +8f2 native-extraction source-path assertions owned by #201 (favicon serialization and +isolated-world ownership); runtime behavioral cases run before the latter assertion. +Native Windows interactive acceptance and macOS compilation/runtime remain unverified. +R1 follow-up adds a bounded per-session pending registry shared with native transports +until completion. Document replacement, navigation suspension, page retirement and +shutdown settle held capture/validation/evaluation callbacks exactly once; the existing +UI-thread poller expires requests after 15 seconds even when the document is not pollable. +Callbacks run outside registry mutation and native completion locks; no detached timers +or page capabilities are added. Late success cannot reacquire/release a newer lease, +and cancelled Windows CDP evaluation cannot advance its remaining stages. Deterministic +fake-clock tests cover bounds, expiry, shutdown/reentrancy and retained old-document +receipt acknowledgement versus rejected new admission. Section 8 acceptance is unchanged. +Follow-up verification: 42 isolated native tests pass, Windows host/transport/bridge +compile passes, and all four strict gates remain clean with unchanged size baselines. + +## 8. Integration and acceptance (#201) + +- [x] 8.6 Restore Windows full-page capture's classic root scrollbar layout using an owned CDP helper; verify real beyond-viewport pixels, unchanged layout/scroll/viewport/styles, native error/cancellation cleanup, strict gates and independently linked native smoke without using the shared build graph. Verified 37 isolated native tests, normal/stable/both-edges/thin/horizontal-overflow real pixel smoke, safe unsupported-author-style failure with preserved state, and all four strict standards gates. Complete annotation workflow, integrated rebuild/rerun and macOS acceptance remain separate. + +- [x] 8.5 Extract focused native capture/annotation transport and state serialization boundaries, relocate shared smoke support, and correct ownership scanner header-token classification; verify strict standards gates and isolated native compilation/tests without changing capture behavior or baselines. Verified all four strict gates, 104 Python tests, 23 standalone native tests (including fake-client probe failure regressions), Windows host/transport/bridge/smoke translation-unit compilation, and OpenSpec validation. Probe null/error handling preserves native failures. No shared build, real native capture acceptance, or macOS compilation/runtime claimed. + +- [x] 8.1 Complete interaction-to-submission regressions, security/lifetime checks and source-selection regression; verify focused native tests, pnpm test, pnpm build and git diff --check. +- [x] 8.2 Review against baseline 0155a863 on standards and spec axes, fix findings and update API/acceptance documentation; verify final diff and review results. +- [ ] 8.3 Perform real Windows complete desktop workflow including all fields and long-page screenshot pixels; record observed results without substituting automated tests. +- [ ] 8.4 Build and perform real macOS complete desktop workflow including all fields and long-page screenshot pixels; record observed results and keep draft if unavailable. + +#201 automated checkpoint at base `7aeb4e9f`: the dedicated real-Chromium/native +driver suite passes after adapting its HTTP boundary to the production query-only +reconciliation contract. It preserves F1/F2 assertions and verifies explicit refusal +and unknown-receipt retries cannot newly admit invalid exact targets, while accepted +receipts recover with the identical payload. Parent/child differences match the +final real DOM, and disposal restores exact original markup/node identity. Existing +interaction/save, frozen membership/API, source/composer and ownership/stale-callback +seams also pass. Earlier red evidence remains in the acceptance record. Extraction +assertions retain serializer/native-command helper contracts and production wiring. +Own-worktree full `pnpm test`, `pnpm build` and seven focused frontend test files +pass at this checkpoint. API/design documentation includes query-only reconciliation +and the exact not-accepted/revalidation condition; no product files changed here. +All four strict gates (including final ownership) report zero findings; +OpenSpec strict validation and `git diff --check` pass. +8.1 remains unchecked pending #200/final integrated native verification; complete +review and both real desktop workflows are also unverified here. See the acceptance +document for runnable commands and injected-boundary limits. + +#201 follow-up at integrated base `4b0c00c4`: the dedicated browser/native-driver +suite passes with the #200 lease-aware test adapter. It asserts real native lease +acquisition, matching release after HTTP failure and lifecycle-validation failure, +while retaining exact-target retry/no-admission, real queue and actual-DOM diff +assertions. The TEMP driver was directly recompiled, outside the shared Ninja graph. +This test-only correction does not complete 8.1 or the real platform workflows; +reliable integrated native recompilation and final review remain pending. +The follow-up's four strict gates report zero findings, OpenSpec strict and diff +checks pass, and the frontend build plus seven focused Node files pass. Full +`pnpm test` and a diagnostic rerun fail at `agentBrowser.test.js:40` (readiness +`undefined` instead of `true`); that file passes standalone. The failure remains +recorded, not waived or attributed to a proven baseline. See acceptance execution +records and TEMP `acecode-201-lease-web-diagnostic.log` for the captured stack. + +Coordinator evidence update, 2026-11-19: reliable full native rebuild session 50005 +passed with start/end HEAD fixed at `4b0c00c4`; `routes_ws` recorded 747 dependencies. +Focused native and CTest each passed 90/90, and a real visible integrated smoke +emitted `SMOKE_OK` and `SMOKE_OWNERSHIP_OK`. The first hidden-launch attempt failed +the active-visible harness check and remains recorded in acceptance. These results +supersede the pending reliable-rebuild status only for 4b0, not later merged sources. +S4 `5752ff65`, S2/S3 `67a0a021` and the two-file CI assertion fix `d298130f` are now +integrated; fresh frontend/driver/native compilation and execution remain pending. +Linux CI `44369114282` had one receipt-test failure among 7,058 tests; the fix retains +exactly-one real admission and metadata checks while excluding typed internal context. +Worker replay/isolated compilation is not a passing fresh Linux HTTP/CI run. +At that checkpoint no completion boxes changed: 2.1 cascade, 5.1/5.2 platform capture +acceptance, 8.1/8.2 final integration/review and 8.3/8.4 manual workflows remained open. + +Final coordinator verification, 2026-11-19, fixed clean start/end HEAD +`39cd01dbbd97d1d7bd8ee4dc288020e835287821`: native session 37596 passed desktop/unit/smoke +builds and dependency validation; freshly linked focused native and CTest each passed +107/107, including new HTTP receipt and MessagePayload tests. Real visible integrated +smoke and ownership passed; the capture probe covered bottom-green pixels, preserved +layout/style/viewport/scroll, stale/resource rejection and retry. This completes 5.1. +Same-HEAD complete pnpm test/build and regex checks, directly rebuilt driver/dedicated +integration, Edge lifecycle, layers/size/ownership/OpenSpec/diff all passed. Final +Standards and Spec reviews pinned to 39cd report no open code findings. This completes +automated integration 8.1 and dual review 8.2, not the whole feature. The prose-only +documentation-path failure is corrected in this documentation-only follow-up, without +baseline exemption; strict doc paths, OpenSpec and diff are rerun separately. +Acceptance records exact TEMP logs and historical failures, including Linux CI +44369114282 (one receipt failure among 7,058 tests) and the earlier broader native +11-failure run. Neither is replaced by a passing focused Windows run or a claimed +Linux rerun. Tasks 2.1, 5.2, 8.3 and 8.4 remain open; keep the pull request draft. + +Codex chrome follow-up: the comment card and toolbar now match the observed Codex +controls, and the approved cascade behavior is Codex's unlayered `!important` +author preview. Ineffective inline or layered `!important` winners produce no +error and no difference. Tasks 2.1, 5.2, 8.3 and 8.4 stay open; the pull request +stays draft. Windows manual acceptance and macOS native/manual acceptance are +not claimed. + +Interaction parity follow-up, 2026-11-19: element and region picking can start +from the floating toolbar before a draft popup exists; the toolbar hides while +the user is picking, while a card is open, and after leaving annotation mode. +Native occlusion holes carry the overlay border radius, so rounded cards and the +toolbar no longer expose the WebUI background at their corners. The card keeps a +fixed header/footer with a 230px scrolling editor, omits the target tag row, +left-aligns labels, splits values from units, exposes font/weight menus, restore +actions and live previews, and uses a clamped 0-100% opacity control. Width, +height and paired padding/margin locks use centered circular buttons between +T-shaped guides with hover and locked states; collapsed spacing rows retain four +editable values. Hover shows the native outline and compact element information +card, one click opens the card, and an outside click cancels its draft. Toolbar +screenshot, hide-marker, hold-original, discard-all, send, and exit behavior, +the exact discard confirmation, stable count width, tooltips and empty-input +disabled submit state are covered by frontend tests. Windows development desktop +manual inspection confirmed hover, one-click open, outside dismissal, fixed +header/footer, 230px scrolling, collapsed four-value spacing, expanded pair +locks and rounded card rendering. The expanded editor is 380px wide; its value +column is 176px, and each collapsed spacing input keeps at least 45px of usable +width before wrapping. Tasks 2.1, 5.2, 8.3 and 8.4 remain open; the +pull request stays draft, and Windows complete-workflow plus macOS +native/manual acceptance are not claimed. + +Final interaction verification, 2026-11-19: the source catalog was regenerated +after the new annotation copy, and full `pnpm test` plus `pnpm build` (including +the regex compatibility scan) pass. Browser regression helpers now reflect the +one-click open behavior instead of the removed select-then-Annotate sequence. +Real Chrome headless lifecycle smoke passes exact DOM/shadow identity, queued +removal, multi-target previews, regions and root replacement. A freshly linked +standalone native driver passes dedicated annotation integration, including +trusted input, multi-target/region save, HTTP serialization, receipt handling, +lease release, refused-retry behavior and final-DOM differences. OpenSpec strict +validation and `git diff --check` pass. Windows development desktop manual +inspection is recorded above; tasks 2.1, 5.2, 8.3 and 8.4 remain open, Windows +complete-workflow and macOS native/manual acceptance are not claimed, and the +pull request stays draft. + +Style-control follow-up, 2026-11-20: paired numeric cells no longer reserve reset +space when no reset is visible, and the two-column gap pair uses a smaller reset +reservation after editing. The ratio-lock link icon is 14px with a centered, +stronger locked stroke. Windows development-desktop inspection confirmed both +gap units remain inside their controls in the default and edited states and the +lock icon is legible in both states. Tasks 2.1, 5.2, 8.3 and 8.4 remain open. + +Specification alignment, 2026-11-21: the spec/design documents were brought in line +with features already implemented in the worktree but not yet described there — +native occlusion geometry (`square_corners`, radius clamp, far-edge guard, implicit +bleed), modal chrome suspension and native input blocking, hover-card lifecycle, +send-error and i18n localisation, the screenshot bridge, annotation message parsing +and card presentation, the expanded editor field/lock set, target-tag row, 2px +editor gap and discard numbering reset. This is documentation only; no product code +or task checkboxes changed. The original-view pin discrepancy previously flagged +here was confirmed by the owner: hiding numbered pins in `original` view +(`markersVisible = !markersHidden && !original`) is intended. The spec scenario, +the three design statements and task 2.3 were aligned accordingly; pin records +remain intact and pins reappear when toggling back. No product code changed. +Tasks 2.1, 5.2, 8.3 and 8.4 and the draft PR state are unchanged. diff --git a/openspec/changes/redesign-html-page-annotations/.openspec.yaml b/openspec/changes/redesign-html-page-annotations/.openspec.yaml new file mode 100644 index 000000000..1b17417b0 --- /dev/null +++ b/openspec/changes/redesign-html-page-annotations/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-22 diff --git a/openspec/changes/redesign-html-page-annotations/design.md b/openspec/changes/redesign-html-page-annotations/design.md new file mode 100644 index 000000000..5c3c541d2 --- /dev/null +++ b/openspec/changes/redesign-html-page-annotations/design.md @@ -0,0 +1,141 @@ +## Context + +完整的决策记录(Q1–Q36 / U1–U5 / D1–D8,共 49 条裁决)在 +`docs/specs/2026-11-21-html-page-annotations-technical-design.md`, +WIP 现状与落地顺序在 `docs/specs/2026-11-22-html-page-annotations-wip-alignment.md`。 +本文只留评审时需要在这里读到的东西:模型、机制、取舍。 + +## Decisions + +### D-1 记录归属会话,页签只是端点 + +``` +Session + ├── SessionAnnotationStore ← records / in_flight / 按 page_id 分组的 next_number + └── Page + └── PageAnnotationSession ← 选区、预览、document_id;页签关闭即析构 +``` + +**为什么**:只要记录的生命周期短于「输入框上方的待发卡片」,`pages.erase(page_id)` 就会把用户写到一半的描述一起析构。反过来把记录挂在会话上,页签只剩三样会失效的东西:DOM(预览/调整)、`document_id`(重放)、`executionContextId`(下发命令)——正好对应 `orphan` 态。 + +**代价**:改动面大,`records` 的读写要穿过两层。缓解:先做纯搬运(行为零变化)一次性落地,再加 `orphan`,两批分开评审。 + +### D-2 四态 + +| 态 | 可发送 | 画图钉 | 可重放 | 可调整 | +|---|---|---|---|---| +| `live` | 是 | 是 | — | 是 | +| `replayable` | 是(标 `target_invalid`) | 否 | 是 | 否 | +| `stale` | 是(标 `target_invalid`) | 否 | 否 | 否 | +| `orphan` | 是(标 `target_invalid`,图沿用 save 时那张) | 否 | 否 | 否 | + +`replayable` 隐藏「调整」的原因:重放还没成功,样式面板读到的是错的 baseline,改出来的 `old_value` 是脏的。 + +### D-3 消息组装唯一,触发三处 + +消息只在 composer 组装一次(`submitWithAnnotations()`)。三处调它,效果完全等价:把输入框内容和会话内全部待发批注批量提交。 + +| 触发点 | 语义 | +|---|---| +| 会话输入框的发送按钮 | 原生入口 | +| 页内工具栏的发送按钮 | 等价于点输入框发送:输入框现有内容 + 会话内全部待发批注 | +| 浮窗 `Ctrl+Enter` | 先 `save` 当前这条,再触发同一个提交 | + +**为什么保留工具栏发送**:用户在页面上刚批注完,视线和鼠标都在页面上,让他切回对话再点发送是多余的一步。保留按钮不会带来「发到哪个会话」的歧义——提交动作恒定作用于「页签所属面板的那个会话」。 + +**为什么组装点只能有一个**:两个触发点各自组装 payload,就会出现「工具栏发一条、输入框又发一条」的双发路径,agent 会分两次读同一批批注、跑两轮 turn。所以工具栏按钮不自己组装、不自己 POST,只调同一个函数。 + +**约束**: + +- 提交范围是**会话全量**(跨页签 + `orphan`),不是当前页签那几条。页内工具栏 + 的数字仍只描述当前页签,避免别的页签的条数跑到这页工具栏上;会话总数由输入框 + 上方的待发卡片统一展示。 +- 输入框里的草稿文本**会一并发出**(用户明确要求「把聊天框里的内容和所有批注批量提交」),不做丢弃分支。 +- 回执状态(成功 / 失败 / 40s 自查结果)统一由 composer 的发送状态机广播,工具栏与输入框显示同一状态。 + +**合并成一条消息**:正文只放用户文本;批注结构作为 `contexts` 里的 +`{type:"page_annotations", version:2, pages:[...]}` 提交,服务端转成 +`browser_context` content part,既送给模型也持久化给只读卡片。拆成两条 POST +会触发两轮 turn。旧版正文内嵌 `Page annotations` 载荷的消息仍由解析层兼容。 + +**铅笔路径的页签解析**:编辑注册表只属于当前挂载的页签,不能据此判断其它页签 +是否还存在。先按 `page_id`、再按 `url` 在 App 级浏览器页面登记表中定位页面; +命中后激活该页签并等待新面板发布带 `document_id` 的编辑器,再执行 +`edit_record`。只有登记表和页签都不存在,或原生确认目标已失效时,才进入无页签 +弹窗。无页签弹窗的描述始终可编辑,按钮在「编辑」与「保存」间切换,保存后停留 +在弹窗内并更新待发卡片。 + +**页内浮层几何**:批注输入框、调整面板、工具栏和悬停气泡都叠在原生浏览器 +视图上。原生遮挡洞用矩形区域,圆角、边框和阴影全部交给 Chromium 绘制;洞口 +外扩 1 CSS px,并用当前页面背景色填底,避免 native `CreateRoundRectRgn` 的 +非抗锯齿边缘在黑底上露出锯齿。 + +### D-4 待发卡片 + +输入框上方,跨页签聚合(原生在任一页签记录变化时广播 `{session_id, page_id, annotations}`,WebUI 按 `session_id → page_id` 归并并单独维护 `orphans[]`)。最多展示 5 行,超出内部滚动。 + +铅笔两条路径: + +- 页签活着:激活页签 → 隐式 `start()`(D8:把页面拉回批注模式)→ `open_record_popup` → 描述回填 + 光标置末尾 + `focus()` + 图钉高亮 + 差异还原成 draft。「调整」可用。 +- 页签已关:居中弹窗,只有描述框 + 删除 + 取消/保存;`target` 冻结,locator / region / differences 只读。**「调整」隐藏**——没有 document、没有 baseline,硬留只会点了报错。 + +`adjustable = state === 'live' && 页签存活 && document_id 匹配`,两个入口共用这一条判定。 + +删除 = 立即生效 + 5s 撤销 toast,不做二次确认(批注是轻量草稿,弹窗打断比误删更烦)。 + +### D-5 截图在 save 时裁 + +``` +save → 视口捕获一次(scale = 1/dpr)→ 按目标 rect 裁剪 → 缩到宽 ≤512px → record.thumbnail +发送 → 只上传 thumbnail +``` + +**为什么**:保存那一刻页面正停在目标上,坐标最准;等到发送时可能已经导航、重放或关掉了。顺带解决「关页签就没图」:图在 save 时就定格,`orphan` 记录仍有图。 + +**代价**:每次 save 多一次捕获(Windows 一次 CDP 调用)。保存批注是低频动作,换来「发送时零捕获」。`captureBeyondViewport` + `cssContentSize` 的整页路径可以删掉——视口够用,视口外的目标本来也没有坐标能裁。 + +### D-6 超时自查 + +``` +40s 未收到 WS message + ├─ 按 client_message_id 查到 → 视为成功,丢弃 in_flight + └─ 查不到 → 回滚:并回 records 尾部、重排编号、sync、toast +``` + +`client_message_id` 已经写进消息 `metadata` 落库(`routes_sessions.cpp:524`),WS 回推也带回(`:734-738`)。没有自查的话,一次 WS 抖动就让用户重发,agent 收到两条一样的批注、把同一处改两遍。 + +**自查本身失败**时按「未知」处理:不回滚,只提示。宁可让用户看到一条"可能已发出"的记录,也不要制造重复。 + +### D-7 已发消息只读 + +没有编辑消息的 API,transcript 只追加。卡片不给铅笔、垃圾桶、复制、"回到页面修改"。想做新一轮修改 → 回页面重新批注一条新的(显式、留痕)。 + +### D-8 按住看原图只认指针 + +「按住看原图」是**纯指针动作**:`pointerdown` 进、`pointerup`/`pointercancel`/`pointerleave` 出,外加 `blur` 与 `visibilitychange` 两路兜底。**不注册任何键盘快捷键**——空格与 Enter 都不触发。 + +**为什么砍键盘**:这个动作的语义是「按住不放」,键盘上没有"按住"的对应物(按住空格会触发系统按键重复,`keydown` 连发、`keyup` 只在松开时来一次,但中间的用户感知是"按一下就开始、再按一下才停",与"按住"不是同一件事)。而且批注面板里已经有三个真快捷键(Enter / Shift+Enter / Ctrl+Enter),再加一个瞬时按键会让"Enter 是添加还是对比"变成需要记忆的事。 + +**代价**:纯键盘用户用不了对比。接受——对比是视觉辅助,不是完成批注的必要路径;按钮保留 `aria-label`「按住查看原图」说明它是瞬时动作。 + +**实现注意**:按钮要 `preventDefault` 掉 Enter 的默认激活,否则聚焦后按 Enter 会触发一次 `click`,而 click 对"按住"没有语义。 + +## Alternatives considered + +| 备选 | 否决理由 | +|---|---| +| 记录留在页签,关页签前弹窗问「要丢弃还是保留」 | 打断路径,且用户常在无感知时关页签 | +| 已发消息可就地编辑(新增消息编辑 API) | agent 已按旧描述执行,改历史会让 transcript 与执行结果对不上 | +| 发送时一次整页捕获 + 逐条裁剪 | mac 根本不返回整页;且发送时页面可能已经变化 | +| 待发卡片自己带发送按钮 | 卡片就贴在输入框上方,输入框发送按钮已在手边,再加一个是冗余 | +| 缩略图用 `tag` + 文本片段代替真图 | 用户明确要截图(D2),且 save 时已有捕获时机 | + +## Risks + +| 风险 | 缓解 | +|---|---| +| 记录上提改动面大 | 纯搬运与 `orphan` 分两批;P1 阶段行为零变化 | +| 跨页签编号重复(每页从 1 开始) | 每条自带 `page_url`,卡片与模型都按页分组;`number` 只在页内唯一 | +| `sync` 频率上升(还要广播所有页签) | 缓存 `executionContextId`;只给有记录变化的页签发事件 | +| `orphan` 记录长期占内存 | 会话关闭即清空;卡片行标「页面已关闭」 | +| 自查接口本身失败 | 不回滚、只提示(见 D-6) | diff --git a/openspec/changes/redesign-html-page-annotations/proposal.md b/openspec/changes/redesign-html-page-annotations/proposal.md new file mode 100644 index 000000000..cf6a1d390 --- /dev/null +++ b/openspec/changes/redesign-html-page-annotations/proposal.md @@ -0,0 +1,27 @@ +## Why + +现有的 `add-html-page-annotations` 变更按「预览为主 / 整页截图 / 不可变记录 / 收据去重 / 导航确认」实现,已经跑通了一部分(#194 合入,#195–201 散在多个分支)。它把批注记录绑在页签上、把工具栏发送做成与输入框发送并列的另一套链路,导致三件事做不到: + +1. 关掉页签,用户写到一半的批注连同描述一起消失; +2. 两个发送按钮各发各的:工具栏只发页面批注、看不见用户刚敲的话,输入框又不知道有批注在等; +3. 发送时才发现截图失败(mac 视口外),或者 40 秒没等到确认就回滚,用户重发一次就变成两条一样的批注,agent 把同一处改两遍。 + +本变更把这三点从根上改掉,其余能力(页内预览、按住看原图、隐藏标记、刷新重放、源文件定位)沿用。 + +## What Changes + +- **记录权威上提**:`records` / `next_number` 从 `PageAnnotationSession`(页签级)挪到会话级 `SessionAnnotationStore`;页签降级为渲染与编辑的端点。关页签 → 记录转 `orphan`,**不销毁**。 +- **记录四态**:`valid: bool` 换成 `live / replayable / stale / orphan`,每态的可发送、可画图钉、可重放、可调整都明确。 +- **发送组单一、触发多路**:消息只在 composer 组装一次(用户敲的字与整批批注**合并成一条消息**);输入框发送、页内工具栏发送、浮窗 `Ctrl+Enter` 三处都调同一个提交动作,效果等价于「把聊天框里的内容和所有批注批量提交」。 +- **待发批注卡片**:挂在输入框上方,跨页签聚合,逐条可编辑(回到页面浮窗 / 无页签时弹窗)可删除。 +- **截图前移**:从「发送时一次整页捕获 + 逐条裁剪」改为「保存批注时按 rect 裁剪,存 `record.thumbnail`」,发送只上传。 +- **超时自查**:40s 没等到 WS 确认时,先按 `client_message_id` 查一次是否已落库,落库则正常收尾,没落才回滚。 +- **删净批次链路**:`annotation_batch_id`、`reconcileOnly`、`annotation_batch_not_accepted`、原生租约(`capture`/`validate`/`acknowledge`/`release`)、`pageAnnotationBatches.js`。 + +## Impact + +- 原生:`page_annotation_session.hpp`(重写记录层)、新增 `session_annotation_store.hpp`、`agent_browser_host_*`(`close_page` 不再析构记录、状态事件改为广播会话内所有页签)、`page_annotation_host_adapter.hpp`(截图命令调用点前移)。 +- 前端:`PageAnnotationSendBar.jsx`(去发送/截图按钮)、`PageAnnotations.jsx`(编辑已有记录态)、新增 `PageAnnotationPendingCard.jsx` / `PageAnnotationEditDialog.jsx` / `pageAnnotationPendingStore.js`、删除 `pageAnnotationBatches.js`。 +- 服务端:`routes_sessions.cpp` 删 `annotation_batch_id` 校验与 404 分支;新增按 `client_message_id` 查询消息的接口(读 `metadata`,不需要新列)。 +- 契约:消息 `text` 允许「用户文本 + `\nPage annotations\n` + JSON」形态,解析层从 `startsWith` 放宽为末尾分隔段;`composer_content` 封闭枚举**不动**。 +- 取代:`openspec/changes/add-html-page-annotations/`(标记 superseded,不再维护)。 diff --git a/openspec/changes/redesign-html-page-annotations/specs/html-page-annotations/spec.md b/openspec/changes/redesign-html-page-annotations/specs/html-page-annotations/spec.md new file mode 100644 index 000000000..688a949f2 --- /dev/null +++ b/openspec/changes/redesign-html-page-annotations/specs/html-page-annotations/spec.md @@ -0,0 +1,171 @@ +## ADDED Requirements + +### Requirement: 待发批注卡片 + +会话 SHALL 在输入框上方展示该会话内尚未发送的批注,按页签分组,每条显示缩略图、元素标签与描述,并允许逐条编辑与删除。 + +#### Scenario: 跨页签聚合 +- **WHEN** 同一会话的两个页签各有未发送的批注 +- **THEN** 卡片同时显示两组,组头为各自页面标题,编号在组内连续 + +#### Scenario: 卡片总数与页内工具栏计数 +- **WHEN** 同一会话的两个浏览器页签分别有 2 条和 3 条待发批注 +- **THEN** 待发卡片显示总数 5,发送范围仍是会话内全部 5 条 +- **AND** 每个浏览器页签的页内工具栏只显示该页自己的 2 条或 3 条 + +#### Scenario: 超过五条 +- **WHEN** 待发批注超过 5 条 +- **THEN** 卡片展示 5 行并提供内部滚动,不把整卡撑高 + +#### Scenario: 删除后可撤销 +- **WHEN** 用户点击某条的垃圾桶图标 +- **THEN** 该条立即从卡片与页面图钉消失,5 秒内可撤销并恢复原编号 + +### Requirement: 逐条编辑批注 + +用户 SHALL 能从卡片回到该条批注继续修改描述;页签已关闭时 SHALL 提供不依赖页面的编辑入口。 + +#### Scenario: 页签仍然存在 +- **WHEN** 用户在卡片上点击某条的铅笔图标 +- **THEN** 激活对应页签、把页面拉回批注模式、打开该条浮窗,描述框回填并把光标置于末尾 +- **AND** 「调整」按钮可用,可继续改样式 + +#### Scenario: 页签存在但未聚焦 +- **WHEN** 同一会话有多个浏览器页签,批注所在页签不是当前焦点 +- **THEN** 按 `page_id`(必要时按 `url`)定位该页签并激活 +- **AND** 等新页签装载后再打开该条批注浮窗 +- **AND** 不显示「页面已关闭」或「这一页已经不再打开了」一类提示 + +#### Scenario: 页签已关闭 +- **WHEN** 该条批注所属页签已关闭,用户点击铅笔 +- **THEN** 弹出只含描述框、删除、取消/保存的对话框 +- **AND** 「调整」不出现(没有 DOM 与原始样式可比对) +- **AND** 目标定位信息只读,不可修改 +- **AND** 描述框保持可编辑;默认按钮为「编辑」,点击后变为「保存」 +- **AND** 保存后描述写回待发卡片,按钮恢复为「编辑」,弹窗不自行关闭 + +#### Scenario: 编辑途中页签被关闭 +- **WHEN** 浮窗打开期间页签被关闭 +- **THEN** 已输入内容保留为草稿,该条转为「页面已关闭」,下次点铅笔可继续编辑 + +### Requirement: 关闭页签不丢批注 + +关闭浏览器页签 SHALL NOT 丢弃该页签上未发送的批注;它们降级为「页面已关闭」,仍可修改描述、删除与发送。 + +#### Scenario: 关闭后仍可发送 +- **WHEN** 用户关闭页签后在卡片上点发送(会话输入框的发送按钮) +- **THEN** 这些批注照常随消息发出,并标注目标已失效 +- **AND** 消息中仍包含保存批注时截取的该条截图 + +### Requirement: 发送超时自查 + +发送后未在 40 秒内收到消息确认时,系统 SHALL 先按客户端消息标识核对消息是否已入库,再决定是否回滚。 + +#### Scenario: 消息实际已入库 +- **WHEN** 40 秒内未收到确认,但按 `client_message_id` 能查到该消息 +- **THEN** 视为发送成功,清空待发批注,不产生重复消息 + +#### Scenario: 确实未入库 +- **WHEN** 40 秒内未收到确认,且查不到该消息 +- **THEN** 批注并回待发集合、重排编号、恢复图钉,并提示可重试 + +#### Scenario: 核对请求自身失败 +- **WHEN** 核对请求超时或报错 +- **THEN** 不自动回滚,只提示「可能仍在发送」,由用户决定重试或撤销 + +### Requirement: 已发消息只读 + +已发送的批注消息 SHALL 只读,不提供任何修改入口。卡片 SHALL 以「页面截屏 + 页面标题 + `N 条注释` 标签」呈现,MUST NOT 逐条平铺描述或截图。 + +#### Scenario: 卡片结构与悬停明细 +- **WHEN** 用户查看已发送的批注消息卡片 +- **THEN** 卡片展示该页面的整屏截屏,下方一行是页面标题与「N 条注释」 +- **AND** 单击截屏打开大图 +- **AND** 指针悬停「N 条注释」时浮出明细,每条为「HTML 元素标签 + 描述」,最多 5 条,超出时列表内部滚动 + +#### Scenario: 多页面消息 +- **WHEN** 同一条消息包含多个页面的批注 +- **THEN** 卡片按页面堆叠「截屏 + 标题 + 标签」,每张图只展开本页条目 + +#### Scenario: 已发卡片无操作按钮 +- **WHEN** 用户查看已发送的批注消息卡片 +- **THEN** 不出现铅笔、垃圾桶或「回到页面修改」 + +## MODIFIED Requirements + +### Requirement: 记录归属 + +批注记录 MUST 归属会话而非浏览器页签;页签只是渲染与编辑的端点。 + +#### Scenario: 切换页签 +- **WHEN** 用户在同一会话的多个页签之间切换 +- **THEN** 各页签的批注互不干扰,待发卡片同时可见 + +### Requirement: 发送组单一、触发多路 + +消息 MUST 只在会话输入框(composer)组装一次;会话输入框的发送按钮、页内工具栏的发送按钮、浮窗 `Ctrl+Enter` MUST 等价,三者都提交「输入框内容 + 会话内全部待发批注」。 + +#### Scenario: 用户敲字同时有批注 +- **WHEN** 输入框里有文本且存在待发批注,用户点输入框的发送按钮 +- **THEN** 只发出一条消息,`text` 只保留用户输入的自然语言 +- **AND** 批注结构作为 `type:"page_annotations"` 的 browser context 随消息提交,由只读卡片渲染 +- **AND** 不额外产生第二条只含批注的消息 + +#### Scenario: 已发消息不展示原始载荷 +- **WHEN** 用户查看已发送的批注消息 +- **THEN** 消息正文只显示用户输入 +- **AND** 批注明细只出现在只读卡片中,不出现 `Page annotations` 或原始 JSON 文本 + +#### Scenario: 发送后重新批注 +- **WHEN** 一批批注发送成功且待发记录被清空,用户再次新增批注 +- **THEN** 新批注编号从 1 开始,页面图钉编号与待发数量一致 + +#### Scenario: 从页内工具栏发送 +- **WHEN** 输入框里有文本,用户在页面上点工具栏的发送按钮 +- **THEN** 提交内容与点输入框发送完全一致(同一条消息、同一批批注) +- **AND** 提交范围是会话内全部待发批注,含其他页签与已关闭页签的记录 +- **AND** 按钮上显示会话级待发总条数 + +#### Scenario: 浮窗内 Ctrl+Enter +- **WHEN** 用户在浮窗描述框按 Ctrl+Enter +- **THEN** 先保存当前批注,再触发与上面等价的提交 + +### Requirement: 截图时机 + +每条批注的截图 MUST 在保存批注时按目标外接矩形裁剪生成,发送阶段不得再次捕获。 + +#### Scenario: 保存时目标在视口外 +- **WHEN** 保存批注时目标不在视口内,无法裁剪 +- **THEN** 该条标记为无图,卡片以元素标签与文本片段代替缩略图,发送时不附带该条截图 + +#### Scenario: 保存时顺带生成页面整屏图 +- **WHEN** 任一批注保存成功 +- **THEN** 同时更新该页面的整屏截图,每页只保留最新一张 +- **AND** 发送时直接取用已存图,不做任何捕获 +- **AND** 页签已关闭时仍能用这张图构造消息卡片 + +### Requirement: 按住看原图只认指针 + +查看原图 MUST 是工具栏按钮上的瞬时按住动作,MUST NOT 绑定任何键盘快捷键。 + +#### Scenario: 鼠标按住与松开 +- **WHEN** 用户在工具栏按钮上 `pointerdown` +- **THEN** 页面立即关闭所有改值效果并隐藏图钉 +- **WHEN** 用户松开、指针移出、指针被取消,或窗口失焦 / 切到后台 +- **THEN** 改后效果与图钉恢复 + +#### Scenario: 键盘不触发 +- **WHEN** 焦点在工具栏按钮上,用户按空格或 Enter +- **THEN** 页面不进入原图态(按钮不因 Enter 触发点击而产生副作用) + +### Requirement: 记录状态 + +每条记录 MUST 处于 `live` / `replayable` / `stale` / `orphan` 四态之一,并据此决定是否绘制图钉、是否可重放、是否可调整样式。 + +#### Scenario: 重放成功 +- **WHEN** 页面重新加载后目标元素定位成功且实时值等于原始值 +- **THEN** 记录回到 `live`,图钉按原编号重新绘制 + +#### Scenario: 实时值已被改动 +- **WHEN** 重放时目标的实时值不等于记录的原始值 +- **THEN** 记录标为 `stale`,不写回预览,且仍可发送(标注目标已失效) diff --git a/openspec/changes/redesign-html-page-annotations/tasks.md b/openspec/changes/redesign-html-page-annotations/tasks.md new file mode 100644 index 000000000..a81f6669d --- /dev/null +++ b/openspec/changes/redesign-html-page-annotations/tasks.md @@ -0,0 +1,51 @@ +## 交付 + +> 顺序即依赖顺序。P1 必须行为零变化——它是纯搬运,任何行为差异都算 bug。 + +- [x] **P0 基线**:把当前 WIP(51 个改动)提交为一条 `wip:` 提交,让后续每批的 diff 可读。 + - 54 个改动落成两条提交:`9da82a61 docs: 批注重设计文档基线` + `44c3fad4 wip: codex visual parity, style panel, native overlay geometry` +- [x] **P1 记录上提(纯搬运)** + - [x] 新增 `src/apps/desktop/session_annotation_store.hpp`:`records` / `in_flight` / 按 `page_id` 分组的 `next_number` + - [x] `page_annotation_session.hpp` 的 `records_` / `next_number_` 改为转发到 store + - [x] 既有 49 条批注测试全绿(行为不变)+ 新增 5 条 store 契约测试 + - 偏差:记录标识按 #208 结论改为 `:annotation:`(原计划留给后续,但那会让 P1 之后再改一次主键,索性一次到位)。`locator` 生成仍留给 #210/#217。 + - 未做:host 层按 `owner.session_id` 共享 store —— 属 P2(#211 关页签不丢),此处每个页签仍自建。 +- [x] **P2 四态与 orphan** + - [x] 记录有效性按 `live / replayable / stale / orphan` 语义落地 + - [x] `close_page` 不再析构记录,记录留在会话级 store 并广播 + - [x] 状态事件广播会话内所有页签的 `annotations` + - [x] `discard` 只清当前页签分组,不动别的页签 +- [x] **P3 截图前移** + - [x] `save` 时视口捕获 + 按 rect 裁剪 + 缩到 ≤512px → `record.thumbnail` + - [x] 删 `captureBeyondViewport` / `cssContentSize` 整页路径 + - [x] 删工具栏「截取屏幕截图」按钮与 `send()` 里的截图步骤 + - [x] 视口外目标退化为标签 + 文本片段 +- [x] **P4 发送换骨** + - [x] 删 `web/src/lib/pageAnnotationBatches.js` 及其测试,清 `annotation_batch_id` / `reconcileOnly` + - [x] 服务端删 `annotation_batch_id` 校验与 `annotation_batch_not_accepted` 404 分支 + - [x] 删原生租约 `capture` / `validate` / `acknowledge` / `release` + - [x] 工具栏发送按钮改为调 `submitWithAnnotations()`(保留按钮,删三态) + - [x] 工具栏「按住看原图」只留指针路径 + `blur` / `visibilitychange` 兜底(D-8) + - [x] 用户文本 + 批注合并一条消息;批注结构走 `contexts` 的 `page_annotations` 上下文,正文只保留自然语言 + - [x] 旧版正文内嵌 `Page annotations` 载荷仍可解析,已发卡片统一只读渲染 + - [x] 40s 未确认 → 按 `client_message_id` 自查再决定回滚 +- [x] **P5 待发卡片与逐条编辑** + - [x] 会话级待发集合由会话 store 供给,关页签后仍可编辑/删除 + - [x] `PageAnnotationPendingCard.jsx`:缩略图 + tag + 铅笔 + 垃圾桶,5 行封顶内部滚动 + - [x] `PageAnnotationEditDialog.jsx`:页面已关闭时只改文本,无「调整」 + - [x] `open_record_popup` / `edit_record` / `remove` 三个 action + - [x] 删除后提供撤销窗口 +- [x] **P6 收口** + - [x] `PageAnnotationMessageCard.jsx` 只读化,行布局改为缩略图 + tag + 描述 + - [x] `read` 失败不终止轮询;浮窗 `Enter` / `Shift+Enter` / `Ctrl+Enter` 语义 + - [x] 旧 change `add-html-page-annotations` 标 superseded + - [x] 测试矩阵补齐(四态、orphan 发送、合并消息解析、超时自查三分支) + - [x] 发送链路修复:三入口等待同一提交的真实结果;正文不再被空 composer_content 覆盖;失败/未知保留待发记录;浮窗保存后先把新记录同步进会话待发箱;成功后同步清理页内图钉 + - [x] 发送成功后编号按存活记录重算:清空记录后下一次批注从 1 开始,部分删除时从当前最大存活编号继续 + - [x] 已发卡片悬停明细修复:卡片本身不再裁切浮层,圆角裁切只作用于页面截屏 + - [x] 文档刷新恢复:`stale_document` 与 `replaced_document` 统一回收旧代;旧快照的 start 不再卡住,校验失败的 start 不再预分配 document id + - [x] 铅笔路径按 `page_id` / `url` 定位未聚焦页签,先激活再等待新面板装载后编辑;只有页签确实不存在或目标失效才进入无页签弹窗 + - [x] 无页签弹窗描述保持可编辑,按钮在「编辑 / 保存」间切换,保存后写回待发卡片并停留在弹窗 + - [x] 页内工具栏按当前页签统计待发数,待发卡片仍按会话总数聚合 + - [x] 新建元素批注和从待发卡片进入编辑后,焦点落到批注描述框 + - [x] 页内批注浮层改用矩形 native 挖洞 + 页面背景色衬底,圆角由 Chromium 抗锯齿绘制,消除黑底锯齿 diff --git a/openspec/changes/redesign-html-page-annotations/tickets.md b/openspec/changes/redesign-html-page-annotations/tickets.md new file mode 100644 index 000000000..01c2e3aba --- /dev/null +++ b/openspec/changes/redesign-html-page-annotations/tickets.md @@ -0,0 +1,48 @@ +# Tickets —— redesign-html-page-annotations + +**这里只是索引。工单正文以 GitHub issue 为唯一事实来源**(验收清单、`Blocked by`、讨论都在 issue 上)。改口径请改 issue,回来同步这一页的标题。 + +- 方案:[#207](https://github.com/tmoonlight/acecode/issues/207) +- 决策记录:`docs/specs/2026-11-21-html-page-annotations-technical-design.md` +- WIP 现状:`docs/specs/2026-11-22-html-page-annotations-wip-alignment.md` + +## 仓库准备(不占工单) + +**提交当前 WIP 作为基线**:`git add -A && git commit -m "wip: codex visual parity, style panel, native overlay geometry"`。51 个改动里有 4445 行,不先落一条基线,后面「记录上提」的 diff 会混在旧路线代码里,评审分不出哪些是搬运、哪些是新逻辑。**这是 #209 开工的实际前提**(issue 里没有单独建单,因为它是仓库动作不是功能)。 + +--- + +## 工单 + +| # | 工单 | 阻塞于 | +|---|---|---| +| [#208](https://github.com/tmoonlight/acecode/issues/208) | T0 技术验证:定位与捕获耗时 | — | +| [#209](https://github.com/tmoonlight/acecode/issues/209) | T1 批注存储 expand(双写) | #208 | +| [#210](https://github.com/tmoonlight/acecode/issues/210) | T2 读路径迁移到存储 | #209 | +| [#211](https://github.com/tmoonlight/acecode/issues/211) | T3 contract:关页签不丢批注 | #210 | +| [#212](https://github.com/tmoonlight/acecode/issues/212) | T4 截图前移到保存 | — | +| [#213](https://github.com/tmoonlight/acecode/issues/213) | T5 发送组装收口到 `submitWithAnnotations`(工具栏按钮保留) | #212 | +| [#214](https://github.com/tmoonlight/acecode/issues/214) | T6 删净批次链路 | #213 | +| [#215](https://github.com/tmoonlight/acecode/issues/215) | T7 超时自查 | #213 | +| [#216](https://github.com/tmoonlight/acecode/issues/216) | T8 待发卡片完整化 | #211 | +| [#217](https://github.com/tmoonlight/acecode/issues/217) | T9 铅笔路径 A:回页面编辑 | #216, #210 | +| [#218](https://github.com/tmoonlight/acecode/issues/218) | T10 铅笔路径 B:无页签弹窗 | #216 | +| [#219](https://github.com/tmoonlight/acecode/issues/219) | T11 已发卡片只读化 | #213 | +| [#220](https://github.com/tmoonlight/acecode/issues/220) | T12 轮询容错与快捷键 | #217 | + +## 依赖图 + +``` +#208 ── #209 ── #210 ── #211 ── #216 ──┬── #217 ── #220 + └── #218 + +#212 ── #213 ──┬── #214 + ├── #215 + └── #219 +``` + +**前沿(现在就能开工)**:#208、#212。 + +**关键路径**:#208 → #209 → #210 → #211 → #216 → #217 → #220。 + +**注意**:#208 的结论可能改变记录标识(`record_id` 现为 `:annotation:`,HMR 换文档就失配)。若结论要改,**#209 的存储结构必须跟着改**,所以 #209 不能抢跑。 diff --git a/scripts/layers/check_ownership.py b/scripts/layers/check_ownership.py index bd176ef93..620b70a7f 100644 --- a/scripts/layers/check_ownership.py +++ b/scripts/layers/check_ownership.py @@ -11,7 +11,7 @@ import sys sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "refactor")) -from layout import load_policy, mask_cpp +from layout import INCLUDE, load_policy, mask_cpp from repo_files import SOURCE_SUFFIXES, emit_json, repo_root, tracked_files METRICS = ("raw_new", "raw_delete", "detach", "std_thread", "unsafe_capture", "delayed_injection", "raw_handle") @@ -89,6 +89,11 @@ def synchronous_capture(code: bytes, match, scopes: list[tuple[int, int, str]]) def scan(data: bytes, path: str, synchronous: list[dict] | None = None) -> list[dict]: code = mask_cpp(data) + masked = bytearray(code) + for include in INCLUDE.finditer(code): + start, end = include.span(2) + masked[start:end] = b" " * (end - start) + code = bytes(masked) scopes = named_scopes(code) occurrences = [] for metric, expression in PATTERNS.items(): diff --git a/scripts/refactor/tests/test_ownership_lifetimes.py b/scripts/refactor/tests/test_ownership_lifetimes.py index 335e099e6..e2ffb1ef8 100644 --- a/scripts/refactor/tests/test_ownership_lifetimes.py +++ b/scripts/refactor/tests/test_ownership_lifetimes.py @@ -8,6 +8,16 @@ class OwnershipLifetimesTest(unittest.TestCase): + def test_include_headers_are_not_allocations_and_keep_source_offsets(self): + source = b'#include \n # include \n#include "new.hpp"\n#define MAKE new Widget\nauto value = new Widget;\n' + found = scan(source, "x.cpp") + self.assertEqual([("raw_new", 4), ("raw_new", 5)], + [(item["metric"], item["line"]) for item in found]) + + def test_non_include_preprocessor_allocations_are_still_detected(self): + self.assertIn("raw_new", self.metrics("#define ALLOCATE new Widget")) + self.assertIn("raw_new", self.metrics("#if FEATURE\nauto value = new Widget;\n#endif")) + def metrics(self, source, path="x.cpp"): return [item["metric"] for item in scan(source.encode(), path)] diff --git a/src/apps/desktop/agent_browser_capture.hpp b/src/apps/desktop/agent_browser_capture.hpp new file mode 100644 index 000000000..7b6e7b60d --- /dev/null +++ b/src/apps/desktop/agent_browser_capture.hpp @@ -0,0 +1,221 @@ +#pragma once + +#include "utils/base64.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace acecode::desktop::browser_capture { + +inline constexpr std::uint32_t kMaxDimension = 32768; +inline constexpr std::uint64_t kMaxPixels = 32u * 1024u * 1024u; +inline constexpr std::size_t kMaxPngBytes = 32u * 1024u * 1024u; + +struct Bounds { + double x = 0; + double y = 0; + double width = 0; + double height = 0; + std::string document; + double device_scale = 1; +}; + +inline std::string request_mode(const nlohmann::json& params, bool& full_page) { + full_page = false; + if (!params.is_object()) return "capture_invalid_request"; + for (const auto* key : {"fullPage", "captureBeyondViewport"}) { + if (params.contains(key) && !params[key].is_boolean()) { + return "capture_invalid_request"; + } + } + if (params.contains("fullPage") && params.contains("captureBeyondViewport") && + params["fullPage"] != params["captureBeyondViewport"]) { + return "capture_invalid_request"; + } + full_page = params.value("fullPage", params.value("captureBeyondViewport", false)); + if (params.contains("documentId")) { + if (!params["documentId"].is_string() || + params["documentId"].get_ref().empty() || + params["documentId"].get_ref().size() > 256) { + return "capture_invalid_request"; + } + } + if (full_page && (params.contains("clip") || params.contains("quality") || + (params.contains("format") && params["format"] != "png"))) { + return "capture_invalid_request"; + } + return {}; +} + +inline std::string validate_bounds(const Bounds& bounds) { + if (bounds.document.empty() || !std::isfinite(bounds.x) || + !std::isfinite(bounds.y) || !std::isfinite(bounds.width) || + !std::isfinite(bounds.height) || bounds.width <= 0 || bounds.height <= 0 || + !std::isfinite(bounds.device_scale) || bounds.device_scale <= 0) { + return "capture_invalid_bounds"; + } + const double width = std::ceil(bounds.width); + const double height = std::ceil(bounds.height); + if (width > kMaxDimension || height > kMaxDimension || + width * height > kMaxPixels) return "capture_resource_limit"; + return {}; +} + +inline bool same_document_bounds(const Bounds& before, const Bounds& after) { + return before.document == after.document && before.x == after.x && + before.y == after.y && before.width == after.width && + before.height == after.height && before.device_scale == after.device_scale; +} + +inline std::string validate_png(const std::string& bytes, const Bounds& bounds) { + if (bytes.size() > kMaxPngBytes) return "capture_resource_limit"; + if (bytes.size() < 33 || bytes.compare(0, 8, "\x89PNG\r\n\x1a\n", 8) != 0 || + bytes.compare(8, 8, "\0\0\0\x0dIHDR", 8) != 0) { + return "capture_invalid_png"; + } + const auto read_dimension = [&bytes](std::size_t offset) { + std::uint32_t value = 0; + for (std::size_t index = offset; index < offset + 4; ++index) { + value = (value << 8) | static_cast(bytes[index]); + } + return value; + }; + if (read_dimension(16) != std::ceil(bounds.width) || + read_dimension(20) != std::ceil(bounds.height)) { + return "capture_incomplete_image"; + } + bool has_pixels = false; + for (std::size_t offset = 8; offset + 12 <= bytes.size();) { + const auto length = read_dimension(offset); + if (length > bytes.size() - offset - 12) return "capture_invalid_png"; + std::uint32_t crc = 0xffffffffu; + for (std::size_t index = offset + 4; index < offset + 8 + length; ++index) { + crc ^= static_cast(bytes[index]); + for (int bit = 0; bit < 8; ++bit) { + crc = (crc >> 1) ^ (0xedb88320u & (0u - (crc & 1u))); + } + } + if ((crc ^ 0xffffffffu) != read_dimension(offset + 8 + length)) { + return "capture_invalid_png"; + } + if (bytes.compare(offset + 4, 4, "IDAT") == 0 && length) has_pixels = true; + if (bytes.compare(offset + 4, 4, "IEND") == 0) { + return has_pixels && length == 0 && offset + 12 == bytes.size() + ? "" : "capture_invalid_png"; + } + offset += 12 + length; + } + return "capture_invalid_png"; +} + +using Measured = std::function; +using Captured = std::function; +using Measure = std::function; +using Capture = std::function; +using Current = std::function; +using Complete = std::function; +using Validate = std::function)>; +using RegisterCleanup = std::function)>; + +inline Measure validated_measure(Measure measure, Current current, Validate validate) { + if (!validate) return measure; + return [measure, current, validate](Measured done) { + if (!current()) { done({}, "capture_document_changed"); return; } + validate([measure, current, done](bool valid) { + if (!valid || !current()) { + done({}, "annotation_target_or_document_changed"); + return; + } + measure(done); + }); + }; +} + +class FullPageCapture : public std::enable_shared_from_this { +public: + FullPageCapture(std::string page_id, std::string expected_document, + Measure measure, Capture capture, Current current, + Complete complete) + : page_id_(std::move(page_id)), expected_document_(std::move(expected_document)), + measure_(std::move(measure)), capture_(std::move(capture)), + current_(std::move(current)), complete_(std::move(complete)) {} + + void start() { + if (!check_current()) return; + measure_([operation = shared_from_this()](Bounds bounds, std::string error) { + if (!operation->check_current()) return; + if (error.empty()) error = validate_bounds(bounds); + if (error.empty() && !operation->expected_document_.empty() && + operation->expected_document_ != bounds.document) { + error = "capture_document_changed"; + } + if (!error.empty()) { operation->fail(error); return; } + operation->bounds_ = bounds; + operation->capture_(bounds, + [operation](std::string bytes, std::string capture_error) { + if (!operation->check_current()) return; + if (capture_error.empty()) { + capture_error = validate_png(bytes, operation->bounds_); + } + if (!capture_error.empty()) { operation->fail(capture_error); return; } + operation->verify(std::move(bytes)); + }); + }); + } + +private: + bool check_current() { + if (finished_) return false; + if (current_()) return true; + fail("capture_document_changed"); + return false; + } + + void fail(const std::string& error) { + if (finished_) return; + finished_ = true; + complete_({{"ok", false}, {"page_id", page_id_}, + {"error", error}, {"recoverable", true}}); + } + + void verify(std::string bytes) { + measure_([operation = shared_from_this(), bytes = std::move(bytes)]( + Bounds after, std::string error) { + if (!operation->check_current()) return; + if (error.empty() && !same_document_bounds(operation->bounds_, after)) { + error = "capture_document_changed"; + } + if (!error.empty()) { operation->fail(error); return; } + try { + nlohmann::json response = {{"ok", true}, {"page_id", operation->page_id_}, + {"result", {{"data", acecode::base64_encode(bytes)}, + {"captureBeyondViewport", true}, {"fullPage", true}, + {"documentId", after.document}, + {"width", std::ceil(after.width)}, + {"height", std::ceil(after.height)}}}}; + operation->finished_ = true; + operation->complete_(std::move(response)); + } catch (const std::bad_alloc&) { + operation->fail("capture_resource_limit"); + } + }); + } + + std::string page_id_; + std::string expected_document_; + Bounds bounds_; + Measure measure_; + Capture capture_; + Current current_; + Complete complete_; + bool finished_ = false; +}; + +} diff --git a/src/apps/desktop/agent_browser_capture_cdp.cpp b/src/apps/desktop/agent_browser_capture_cdp.cpp new file mode 100644 index 000000000..00a2e414b --- /dev/null +++ b/src/apps/desktop/agent_browser_capture_cdp.cpp @@ -0,0 +1,94 @@ +#include "agent_browser_capture_cdp.hpp" +#include "agent_browser_capture_layout.hpp" + +namespace acecode::desktop::browser_capture { + +void capture_cdp(std::string page_id, const nlohmann::json& params, + Command command, Current current, Complete complete, Validate validate, + RegisterCleanup cleanup) { + const Measure measure = [command, current](Measured done) { + if (!current()) { done({}, "capture_document_changed"); return; } + command("Page.getFrameTree", nlohmann::json::object(), + [command, current, done](nlohmann::json tree, std::string error) { + if (!current()) { done({}, "capture_document_changed"); return; } + if (!error.empty()) { done({}, error); return; } + if (!tree.contains("frameTree") || !tree["frameTree"].is_object() || + !tree["frameTree"].contains("frame") || + !tree["frameTree"]["frame"].is_object()) { + done({}, "capture_invalid_bounds"); return; + } + const auto frame = tree["frameTree"]["frame"]; + if (!frame.contains("loaderId") || !frame["loaderId"].is_string() || + !frame.contains("id") || !frame["id"].is_string()) { + done({}, "capture_invalid_bounds"); return; + } + const std::string document = frame.value("loaderId", ""); + command("Page.getLayoutMetrics", nlohmann::json::object(), + [command, current, frame, document, done](nlohmann::json metrics, std::string metrics_error) { + if (!metrics_error.empty()) { done({}, metrics_error); return; } + if (!current()) { done({}, "capture_document_changed"); return; } + const auto size = metrics.value("cssContentSize", nlohmann::json::object()); + if (!size.contains("width") || !size["width"].is_number() || + !size.contains("height") || !size["height"].is_number() || + !size.contains("x") || !size["x"].is_number() || + !size.contains("y") || !size["y"].is_number()) { + done({}, "capture_invalid_bounds"); + return; + } + const Bounds bounds{size["x"].get(), + size["y"].get(), size["width"].get(), + size["height"].get(), document}; + command("Page.createIsolatedWorld", + {{"frameId", frame["id"]}, {"worldName", "acecode.full-page-capture"}}, + [command, current, bounds, done](nlohmann::json world, std::string world_error) { + if (!world_error.empty()) { done({}, world_error); return; } + if (!current()) { done({}, "capture_document_changed"); return; } + if (!world.contains("executionContextId") || + !world["executionContextId"].is_number_integer()) { + done({}, "capture_measure_failed"); return; + } + command("Runtime.evaluate", + {{"expression", "window.devicePixelRatio"}, + {"contextId", world["executionContextId"]}, {"returnByValue", true}}, + [bounds, done](nlohmann::json value, std::string value_error) mutable { + if (!value_error.empty()) { done({}, value_error); return; } + if (!value.contains("result") || !value["result"].is_object() || + !value["result"].contains("value") || + !value["result"]["value"].is_number()) { + done({}, "capture_measure_failed"); return; + } + auto measured = bounds; + measured.device_scale = value["result"]["value"].get(); + done(std::move(measured), {}); + }); + }); + }); + }); + }; + const Capture capture = [command, current, cleanup](const Bounds& bounds, Captured done) { + if (!current()) { done({}, "capture_document_changed"); return; } + capture_preserving_layout(command, current, + {{"format", "png"}, {"fromSurface", true}, {"captureBeyondViewport", true}, + {"clip", {{"x", bounds.x}, {"y", bounds.y}, + {"width", std::ceil(bounds.width)}, + {"height", std::ceil(bounds.height)}, {"scale", 1 / bounds.device_scale}}}}, + [done](nlohmann::json result, std::string error) { + if (!error.empty()) { done({}, error); return; } + const auto encoded = result.find("data"); + if (encoded == result.end() || !encoded->is_string()) { + done({}, "capture_invalid_png"); return; + } + if (encoded->get_ref().size() > + ((kMaxPngBytes + 2) / 3) * 4) { + done({}, "capture_resource_limit"); return; + } + const auto bytes = acecode::base64_decode(encoded->get_ref()); + done(bytes.value_or(""), bytes ? "" : "capture_invalid_png"); + }, cleanup); + }; + std::make_shared(std::move(page_id), params.value("documentId", ""), + validated_measure(measure, current, std::move(validate)), capture, + current, std::move(complete))->start(); +} + +} diff --git a/src/apps/desktop/agent_browser_capture_cdp.hpp b/src/apps/desktop/agent_browser_capture_cdp.hpp new file mode 100644 index 000000000..245c43d4f --- /dev/null +++ b/src/apps/desktop/agent_browser_capture_cdp.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include "agent_browser_capture.hpp" + +namespace acecode::desktop::browser_capture { + +using CommandResult = std::function; +using Command = std::function; + +void capture_cdp(std::string page_id, const nlohmann::json& params, + Command command, Current current, Complete complete, Validate validate = {}, + RegisterCleanup cleanup = {}); + +} diff --git a/src/apps/desktop/agent_browser_capture_layout.cpp b/src/apps/desktop/agent_browser_capture_layout.cpp new file mode 100644 index 000000000..374e9f7d7 --- /dev/null +++ b/src/apps/desktop/agent_browser_capture_layout.cpp @@ -0,0 +1,208 @@ +#include "agent_browser_capture_layout.hpp" + +namespace acecode::desktop::browser_capture { +namespace { + +constexpr const char* kGutterPlan = R"JS((() => { + const root = document.documentElement; + if (!root) return null; + const style = getComputedStyle(root); + const classic = innerWidth > root.clientWidth; + const stable = style.scrollbarGutter.startsWith('stable'); + return { + pin: classic && !stable ? ':root{scrollbar-gutter:stable!important}' : '', + refresh: classic && stable && root.scrollHeight > root.clientHeight + ? (style.overflowY === 'scroll' ? 'auto' : 'scroll') : '' + }; +})())JS"; + +class LayoutResource { +public: + explicit LayoutResource(Command command) : command_(std::move(command)) {} + bool retired() const { return retired_; } + const std::string& sheet() const { return sheet_; } + void own(std::string sheet) { + sheet_ = std::move(sheet); + if (retired_) clear([](nlohmann::json, std::string) {}); + } + void retire() { + retired_ = true; + clear([](nlohmann::json, std::string) {}); + } + void clear(CommandResult complete) { + if (sheet_.empty() || cleared_) { complete(nlohmann::json::object(), {}); return; } + cleared_ = true; + command_("CSS.setStyleSheetText", {{"styleSheetId", sheet_}, {"text", ""}}, std::move(complete)); + } +private: + Command command_; + std::string sheet_; + bool retired_ = false; + bool cleared_ = false; +}; + +class LayoutCapture : public std::enable_shared_from_this { +public: + LayoutCapture(Command command, Current current, nlohmann::json params, CommandResult complete, + const std::shared_ptr& resource) + : command_(std::move(command)), current_(std::move(current)), + params_(std::move(params)), complete_(std::move(complete)), resource_(resource) {} + + void start() { send(Stage::frame, "Page.getFrameTree", nlohmann::json::object()); } + +private: + enum class Stage { frame, world, plan, dom, css, sheet, pin, verify_pin, + probe_refresh, verify_refresh, prepared, capture }; + + void send(Stage stage, const std::string& method, const nlohmann::json& params) { + if (resource_->retired()) return; + if (!current_()) { restore({}, "capture_document_changed"); return; } + command_(method, params, + [operation = shared_from_this(), stage](nlohmann::json result, std::string error) { + operation->received(stage, std::move(result), std::move(error)); + }); + } + + void received(Stage stage, nlohmann::json result, std::string error) { + if (stage == Stage::sheet && result.is_object() && result.contains("styleSheetId") && + result["styleSheetId"].is_string()) resource_->own(result["styleSheetId"].get()); + if (resource_->retired()) return; + if (stage == Stage::capture) captured_ = true; + if (!error.empty()) { restore({}, std::move(error)); return; } + if (!current_()) { restore({}, "capture_document_changed"); return; } + if (!result.is_object()) { restore({}, "capture_layout_failed"); return; } + switch (stage) { + case Stage::frame: + if (!result.contains("frameTree") || !result["frameTree"].is_object() || + !result["frameTree"].contains("frame") || !result["frameTree"]["frame"].is_object() || + !result["frameTree"]["frame"].contains("id") || + !result["frameTree"]["frame"]["id"].is_string()) break; + frame_ = result["frameTree"]["frame"]["id"].get(); + send(Stage::world, "Page.createIsolatedWorld", + {{"frameId", frame_}, {"worldName", "acecode.full-page-capture"}}); + return; + case Stage::world: + if (!result.contains("executionContextId") || !result["executionContextId"].is_number_integer()) break; + context_ = result["executionContextId"]; + send(Stage::plan, "Runtime.evaluate", {{"expression", kGutterPlan}, + {"contextId", context_}, {"returnByValue", true}}); + return; + case Stage::plan: + if (!result.contains("result") || !result["result"].is_object() || + !result["result"].contains("value") || !result["result"]["value"].is_object()) break; + result = result["result"]["value"].get(); + if (!result.contains("pin") || !result["pin"].is_string() || + !result.contains("refresh") || !result["refresh"].is_string()) break; + pin_ = result["pin"].get(); + refresh_ = result["refresh"].get(); + if (!refresh_.empty() && refresh_ != "auto" && refresh_ != "scroll") break; + if (pin_.empty() && refresh_.empty()) take(); + else send(Stage::dom, "DOM.enable", nlohmann::json::object()); + return; + case Stage::dom: + send(Stage::css, "CSS.enable", nlohmann::json::object()); + return; + case Stage::css: + send(Stage::sheet, "CSS.createStyleSheet", {{"frameId", frame_}, {"force", true}}); + return; + case Stage::sheet: + if (resource_->sheet().empty()) break; + if (pin_.empty()) send(Stage::probe_refresh, "CSS.setStyleSheetText", + {{"styleSheetId", resource_->sheet()}, {"text", refresh_rule()}}); + else send(Stage::pin, "CSS.setStyleSheetText", {{"styleSheetId", resource_->sheet()}, {"text", pin_}}); + return; + case Stage::pin: + send(Stage::verify_pin, "Runtime.evaluate", + {{"expression", "getComputedStyle(document.documentElement).scrollbarGutter.startsWith('stable')"}, + {"contextId", context_}, {"returnByValue", true}}); + return; + case Stage::probe_refresh: + send(Stage::verify_refresh, "Runtime.evaluate", + {{"expression", "getComputedStyle(document.documentElement).overflowY === '" + refresh_ + "'"}, + {"contextId", context_}, {"returnByValue", true}}); + return; + case Stage::verify_pin: + case Stage::verify_refresh: + if (!result.contains("result") || !result["result"].is_object() || + !result["result"].contains("value") || result["result"]["value"] != true) { + restore({}, "capture_layout_unsupported"); + return; + } + if (stage == Stage::verify_refresh) { + send(Stage::prepared, "CSS.setStyleSheetText", {{"styleSheetId", resource_->sheet()}, {"text", ""}}); + return; + } + take(); + return; + case Stage::prepared: + take(); + return; + case Stage::capture: + restore(std::move(result), {}); + return; + } + restore({}, "capture_layout_failed"); + } + + void take() { send(Stage::capture, "Page.captureScreenshot", params_); } + + std::string refresh_rule() const { return ":root{overflow-y:" + refresh_ + "!important}"; } + + void restore(nlohmann::json result, std::string error) { + if (resource_->retired()) return; + if (resource_->sheet().empty()) { finish(std::move(result), std::move(error)); return; } + if (!captured_ || refresh_.empty()) { clear(std::move(result), std::move(error)); return; } + command_("CSS.setStyleSheetText", {{"styleSheetId", resource_->sheet()}, {"text", refresh_rule()}}, + [operation = shared_from_this(), result = std::move(result), error = std::move(error)] + (nlohmann::json, std::string refresh_error) mutable { + if (operation->resource_->retired()) return; + if (!refresh_error.empty()) { + operation->clear(std::move(result), error.empty() ? std::move(refresh_error) : std::move(error)); + return; + } + operation->command_("Runtime.evaluate", + {{"expression", "document.documentElement.clientWidth"}, + {"contextId", operation->context_}, {"returnByValue", true}}, + [operation, result = std::move(result), error = std::move(error)] + (nlohmann::json, std::string layout_error) mutable { + if (operation->resource_->retired()) return; + operation->clear(std::move(result), error.empty() ? std::move(layout_error) : std::move(error)); + }); + }); + } + + void clear(nlohmann::json result, std::string error) { + resource_->clear( + [operation = shared_from_this(), result = std::move(result), error = std::move(error)] + (nlohmann::json, std::string cleanup_error) mutable { + operation->finish(std::move(result), error.empty() ? std::move(cleanup_error) : std::move(error)); + }); + } + + void finish(nlohmann::json result, std::string error) { + if (resource_->retired()) return; + if (auto complete = std::move(complete_)) complete(std::move(result), std::move(error)); + } + + Command command_; + Current current_; + nlohmann::json params_; + CommandResult complete_; + // Shared with request retirement; the resource never retains this operation. + std::shared_ptr resource_; + nlohmann::json context_; + std::string frame_, pin_, refresh_; + bool captured_ = false; +}; + +} + +void capture_preserving_layout(Command command, Current current, + nlohmann::json params, CommandResult complete, RegisterCleanup cleanup) { + const auto resource = std::make_shared(command); + if (cleanup) cleanup([resource] { resource->retire(); }); + std::make_shared(std::move(command), std::move(current), + std::move(params), std::move(complete), resource)->start(); +} + +} diff --git a/src/apps/desktop/agent_browser_capture_layout.hpp b/src/apps/desktop/agent_browser_capture_layout.hpp new file mode 100644 index 000000000..41f2c5452 --- /dev/null +++ b/src/apps/desktop/agent_browser_capture_layout.hpp @@ -0,0 +1,11 @@ +#pragma once + +#include "agent_browser_capture_cdp.hpp" + +namespace acecode::desktop::browser_capture { + +void capture_preserving_layout(Command command, Current current, + nlohmann::json params, CommandResult complete, + RegisterCleanup cleanup = {}); + +} diff --git a/src/apps/desktop/agent_browser_capture_mac.hpp b/src/apps/desktop/agent_browser_capture_mac.hpp new file mode 100644 index 000000000..bd00c2547 --- /dev/null +++ b/src/apps/desktop/agent_browser_capture_mac.hpp @@ -0,0 +1,18 @@ +#pragma once + +#ifdef __APPLE__ +#include "agent_browser_capture.hpp" + +@class WKWebView; + +namespace acecode::desktop::browser_capture { + +using Evaluated = std::function; +using Evaluate = std::function; + +void capture_webkit(std::shared_ptr view, std::string page_id, + const nlohmann::json& params, Evaluate evaluate, + Current current, Complete complete, Validate validate = {}); + +} +#endif diff --git a/src/apps/desktop/agent_browser_capture_mac.mm b/src/apps/desktop/agent_browser_capture_mac.mm new file mode 100644 index 000000000..655a77b72 --- /dev/null +++ b/src/apps/desktop/agent_browser_capture_mac.mm @@ -0,0 +1,139 @@ +#include "agent_browser_capture_mac.hpp" + +#ifdef __APPLE__ +#include "agent_browser_macos_helpers.hpp" +#include "utils/uuid.hpp" + +#import +#import + +namespace acecode::desktop::browser_capture { +using nlohmann::json; + +void capture_webkit(std::shared_ptr view, std::string page_id, + const json& params, Evaluate evaluate, Current current, Complete complete, + Validate validate) { + bool full_page = false; + const auto request_error = request_mode(params, full_page); + if (!request_error.empty()) { + complete({{"ok", false}, {"page_id", page_id}, + {"error", request_error}, {"recoverable", true}}); + return; + } + if (full_page) { + const Measure measure = [evaluate, current](Measured done) { + if (!current()) { done({}, "capture_document_changed"); return; } + const auto expression = std::string(R"JS((() => { + const key = '__acecodeFullPageCaptureDocument'; + if (!globalThis[key] || globalThis[key].document !== document) { + globalThis[key] = { document, id: )JS") + + json(acecode::generate_uuid()).dump() + R"JS( }; + } + const root = document.documentElement; + const body = document.body; + return { document: globalThis[key].id, + width: Math.max(innerWidth, root?.scrollWidth || 0, + root?.offsetWidth || 0, body?.scrollWidth || 0, body?.offsetWidth || 0), + height: Math.max(innerHeight, root?.scrollHeight || 0, + root?.offsetHeight || 0, body?.scrollHeight || 0, body?.offsetHeight || 0) }; + })())JS"; + evaluate(expression, [done](bool ok, json value, std::string error) { + if (!ok) { done({}, "capture_measure_failed: " + error); return; } + if (!value.is_object() || !value.contains("width") || + !value["width"].is_number() || !value.contains("height") || + !value["height"].is_number() || !value.contains("document") || + !value["document"].is_string()) { + done({}, "capture_invalid_bounds"); return; + } + done({0, 0, value["width"].get(), value["height"].get(), + value["document"].get()}, {}); + }); + }; + const Capture capture = [view, current](const Bounds& bounds, Captured done) { + if (!current()) { done({}, "capture_document_changed"); return; } + WKPDFConfiguration* configuration = [[[WKPDFConfiguration alloc] init] autorelease]; + const auto width = static_cast(std::ceil(bounds.width)); + const auto height = static_cast(std::ceil(bounds.height)); + configuration.rect = CGRectMake(bounds.x, bounds.y, width, height); + [view.get() createPDFWithConfiguration:configuration + completionHandler:^(NSData* data, NSError* error) { + if (!current()) { done({}, "capture_document_changed"); return; } + if (error || !data) { done({}, "capture_native_failed"); return; } + if (data.length > kMaxPngBytes) { done({}, "capture_resource_limit"); return; } + const auto provider = std::unique_ptr( + CGDataProviderCreateWithCFData((CFDataRef)data), CGDataProviderRelease); + const auto pdf = std::unique_ptr( + provider ? CGPDFDocumentCreateWithProvider(provider.get()) : nullptr, + CGPDFDocumentRelease); + if (!pdf || CGPDFDocumentGetNumberOfPages(pdf.get()) != 1) { + done({}, "capture_incomplete_image"); return; + } + const auto pdf_page = CGPDFDocumentGetPage(pdf.get(), 1); + const CGRect box = CGPDFPageGetBoxRect(pdf_page, kCGPDFMediaBox); + if (std::abs(box.size.width - width) > 0.01 || + std::abs(box.size.height - height) > 0.01) { + done({}, "capture_incomplete_image"); return; + } + const auto color = std::unique_ptr( + CGColorSpaceCreateDeviceRGB(), CGColorSpaceRelease); + if (!color) { done({}, "capture_resource_limit"); return; } + const auto bitmap = std::unique_ptr( + CGBitmapContextCreate(nullptr, width, height, 8, width * 4, + color.get(), kCGImageAlphaPremultipliedLast), CGContextRelease); + if (!bitmap) { done({}, "capture_resource_limit"); return; } + CGContextSetRGBFillColor(bitmap.get(), 1, 1, 1, 1); + CGContextFillRect(bitmap.get(), CGRectMake(0, 0, width, height)); + CGContextConcatCTM(bitmap.get(), CGPDFPageGetDrawingTransform( + pdf_page, kCGPDFMediaBox, CGRectMake(0, 0, width, height), 0, false)); + CGContextDrawPDFPage(bitmap.get(), pdf_page); + const auto image = std::unique_ptr( + CGBitmapContextCreateImage(bitmap.get()), CGImageRelease); + if (!image) { done({}, "capture_native_failed"); return; } + NSBitmapImageRep* representation = [[[NSBitmapImageRep alloc] + initWithCGImage:image.get()] autorelease]; + NSData* png = [representation representationUsingType:NSBitmapImageFileTypePNG + properties:@{}]; + if (!png || png.length > kMaxPngBytes) { done({}, "capture_resource_limit"); return; } + try { + done(std::string(static_cast(png.bytes), png.length), {}); + } catch (const std::bad_alloc&) { + done({}, "capture_resource_limit"); + } + }]; + }; + std::make_shared(page_id, params.value("documentId", ""), + validated_measure(measure, current, std::move(validate)), capture, current, complete)->start(); + return; + } + WKSnapshotConfiguration* configuration = [[[WKSnapshotConfiguration alloc] init] autorelease]; + configuration.rect = [view.get() bounds]; + [view.get() takeSnapshotWithConfiguration:configuration + completionHandler:^(NSImage* image, NSError* error) { + if (error || !image) { + complete({{"ok", false}, {"page_id", page_id}, + {"error", error ? agent_browser_macos::utf8_string([error localizedDescription]) + : "WKWebView snapshot failed"}}); + return; + } + CGImageRef cg_image = [image CGImageForProposedRect:nil context:nil hints:nil]; + if (!cg_image) { + complete({{"ok", false}, {"page_id", page_id}, + {"error", "WKWebView snapshot returned no image"}}); + return; + } + NSBitmapImageRep* representation = [[[NSBitmapImageRep alloc] + initWithCGImage:cg_image] autorelease]; + NSData* data = [representation representationUsingType:NSBitmapImageFileTypePNG properties:@{}]; + if (!data || [data length] == 0) { + complete({{"ok", false}, {"page_id", page_id}, + {"error", "failed to encode WKWebView snapshot"}}); + return; + } + const std::string bytes(static_cast([data bytes]), [data length]); + complete({{"ok", true}, {"page_id", page_id}, + {"result", {{"data", acecode::base64_encode(bytes)}, {"captureBeyondViewport", false}}}}); + }]; +} + +} +#endif diff --git a/src/apps/desktop/agent_browser_host.cpp b/src/apps/desktop/agent_browser_host.cpp index 9d508f2e9..535821ee2 100644 --- a/src/apps/desktop/agent_browser_host.cpp +++ b/src/apps/desktop/agent_browser_host.cpp @@ -1,6 +1,11 @@ #include "agent_browser_host.hpp" +#include "page_annotation_session.hpp" +#include "page_annotation_host_submission.hpp" +#include "page_annotation_host_adapter.hpp" #include "agent_browser_cookie_jars.hpp" +#include "agent_browser_capture_cdp.hpp" +#include "agent_browser_proxy_request.hpp" #include "agent_browser_navigation_state.hpp" #include "ipc/agent_browser_runtime.hpp" #include "ipc/agent_browser_store_state.hpp" @@ -16,7 +21,6 @@ #include #include #include -#include #include #include #include @@ -46,6 +50,7 @@ #endif #include "agent_browser_windows_helpers.hpp" +#include "agent_browser_native_commands_win.hpp" #include "agent_browser_host_common.hpp" namespace acecode::desktop { @@ -55,14 +60,8 @@ using namespace agent_browser_windows; #endif struct AgentBrowserHost::Impl : public std::enable_shared_from_this { - struct PendingProxyCall { - std::mutex mutex; - std::condition_variable ready; - bool completed = false; - nlohmann::json response; - }; - void* parent_window = nullptr; + AnnotationPoller annotation_poller; std::int64_t desktop_pid = 0; std::string desktop_instance_id; std::string acecode_dir; @@ -74,6 +73,9 @@ struct AgentBrowserHost::Impl bool parent_surface_visible = true; // 「保留 Cookie」档位;启动时从状态文件读取,之后只在 UI 线程上改。 AgentBrowserCookieMode cookie_mode = AgentBrowserCookieMode::Shared; + // 会话级批注记录(Q33)。页签销毁不带走记录:关页签只让记录降级为 orphan, + // 所以存储挂在宿主上、按 owner.session_id 分桶,由 UI 线程读写。 + SessionAnnotationStoreRegistry annotation_store_registry; #ifdef _WIN32 struct QueuedCdpCall { @@ -84,6 +86,7 @@ struct AgentBrowserHost::Impl struct Page { std::string id; + PageAnnotationSession annotations; AgentBrowserState state; AgentBrowserBounds requested_bounds; bool creation_started = false; @@ -120,6 +123,7 @@ struct AgentBrowserHost::Impl std::uint64_t element_selection_generation = 0; std::uint64_t favicon_generation = 0; std::uint64_t current_navigation_id = 0; + bool annotation_certificate_retry = false; std::string content_state_before_navigation = kAgentBrowserContentStateEmpty; std::string favicon_before_navigation; @@ -373,18 +377,6 @@ struct AgentBrowserHost::Impl #endif } - static void finish_proxy_call( - const std::shared_ptr& pending, - nlohmann::json response) { - { - std::lock_guard lock(pending->mutex); - if (pending->completed) return; - pending->completed = true; - pending->response = std::move(response); - } - pending->ready.notify_all(); - } - #ifdef _WIN32 void start() { if (!parent_window || !::IsWindow(static_cast(parent_window))) { @@ -542,6 +534,8 @@ struct AgentBrowserHost::Impl page->state.supported = true; page->state.shared_with_agent = shared_with_agent; page->state.owner = owner; + // 同会话所有页签共享一个记录容器;页签关掉后记录仍在,转 orphan 继续可发。 + page->annotations.share_store(annotation_store_registry.for_session(owner.session_id)); std::vector changed; AgentBrowserState created; { @@ -743,13 +737,15 @@ struct AgentBrowserHost::Impl if (!page->restore_url.empty() && page->webview) { const std::string url = std::move(page->restore_url); page->restore_url.clear(); + page->annotations.navigation.arm(); const HRESULT navigated = page->webview->Navigate(acecode::utf8_to_wide(url).c_str()); if (FAILED(navigated)) { + page->annotations.navigation.finish(); LOG_WARN("[agent-browser] failed to restore " + page->id + " after cookie store change (" + hresult_text(navigated) + ")"); } - } + } else page->annotations.navigation.finish(); LOG_INFO("[agent-browser] page ready: " + page->id + " (store " + page->store.id() + ")"); } @@ -1220,6 +1216,7 @@ struct AgentBrowserHost::Impl void retry_navigation_after_certificate( const std::shared_ptr& page) { if (!page || !page->webview) return; + page->annotation_certificate_retry = true; std::string uri; { std::lock_guard lock(state_mutex); @@ -1315,17 +1312,18 @@ struct AgentBrowserHost::Impl install_permissive_certificate_events(page); page->webview->add_NavigationStarting( Microsoft::WRL::Callback( - [weak, page_id](ICoreWebView2*, + [weak, page_id](ICoreWebView2* source, ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT { const auto self = weak.lock(); const auto current = self ? self->find_page(page_id) : nullptr; - if (!self || !current || !args) return S_OK; + if (!current || current->closing || current->webview.Get() != source || !args) return S_OK; LPWSTR raw = nullptr; args->get_Uri(&raw); const std::string uri = raw ? acecode::wide_to_utf8(raw) : ""; ::CoTaskMemFree(raw); std::uint64_t navigation_id = 0; args->get_NavigationId(&navigation_id); + if (!annotation_start_navigation(*self, current, args, uri, navigation_id)) return S_OK; { std::lock_guard lock(self->state_mutex); if (current->current_navigation_id != navigation_id && @@ -1374,11 +1372,11 @@ struct AgentBrowserHost::Impl page->webview->add_NavigationCompleted( Microsoft::WRL::Callback( - [weak, page_id](ICoreWebView2*, + [weak, page_id](ICoreWebView2* sender, ICoreWebView2NavigationCompletedEventArgs* args) -> HRESULT { const auto self = weak.lock(); const auto current = self ? self->find_page(page_id) : nullptr; - if (!self || !current || !args) return S_OK; + if (!current || current->closing || current->webview.Get() != sender || !args) return S_OK; BOOL success = FALSE; COREWEBVIEW2_WEB_ERROR_STATUS status = COREWEBVIEW2_WEB_ERROR_STATUS_UNKNOWN; @@ -1423,6 +1421,7 @@ struct AgentBrowserHost::Impl self->retry_navigation_after_certificate(current); return S_OK; } + current->annotations.navigation.finish(); LPWSTR raw_source = nullptr; current->webview->get_Source(&raw_source); const std::string source = raw_source @@ -1475,15 +1474,24 @@ struct AgentBrowserHost::Impl page->webview->add_SourceChanged( Microsoft::WRL::Callback( - [weak, page_id](ICoreWebView2*, + [weak, page_id](ICoreWebView2* source, ICoreWebView2SourceChangedEventArgs* args) -> HRESULT { if (const auto self = weak.lock()) { - const auto current = self->find_page(page_id); + const auto current = annotation_event_page(*self, page_id, source); BOOL new_document = FALSE; if (args) args->get_IsNewDocument(&new_document); if (new_document) { + if (current) { + current->annotations.replace_document(); + const auto annotations = current->annotations.snapshot().dump(); + self->update_page(current, [annotations](AgentBrowserState& state) { + state.page_annotations_json = annotations; + }); + } self->clear_console_logs(current); self->invalidate_element_selection(current); + } else if (current && current->annotations.navigation.reserved() && current->annotations.navigation.armed()) { + current->annotations.navigation.finish(); } self->refresh_source_history_title(current); } @@ -1530,11 +1538,11 @@ struct AgentBrowserHost::Impl &page->new_window_token); page->webview->add_ProcessFailed( Microsoft::WRL::Callback( - [weak, page_id](ICoreWebView2*, + [weak, page_id](ICoreWebView2* source, ICoreWebView2ProcessFailedEventArgs* args) -> HRESULT { const auto self = weak.lock(); const auto current = self ? self->find_page(page_id) : nullptr; - if (!self || !current || !args) return S_OK; + if (!current || current->closing || current->webview.Get() != source || !args) return S_OK; COREWEBVIEW2_PROCESS_FAILED_KIND kind = COREWEBVIEW2_PROCESS_FAILED_KIND_UNKNOWN_PROCESS_EXITED; @@ -1560,8 +1568,11 @@ struct AgentBrowserHost::Impl current, "[browser] " + technical); if (failure_kind.empty()) return S_OK; + current->annotations.replace_document(); + current->annotations.navigation.finish(); self->invalidate_element_selection(current); self->update_page(current, [&](AgentBrowserState& state) { + state.page_annotations_json = current->annotations.snapshot().dump(); state.loading = false; state.content_state = kAgentBrowserContentStateProcessFailed; @@ -1639,7 +1650,7 @@ struct AgentBrowserHost::Impl } void teardown_page(const std::shared_ptr& page) { - if (!page) return; + if (!annotation_retire(page)) return; remove_events(page); if (page->controller) { page->controller->put_IsVisible(FALSE); @@ -1688,6 +1699,7 @@ struct AgentBrowserHost::Impl // 页面关闭后仍会有在途导航回调,标记之后一律忽略。 page->navigation.close(); teardown_page(page); + page->annotations.replace_document(); std::vector queued; queued.swap(page->queued_cdp); std::string next_active; @@ -1738,6 +1750,7 @@ struct AgentBrowserHost::Impl url = page->state.url; } teardown_page(page); + page->annotations.replace_document(); page->creation_started = false; page->store_prepared = false; page->navigation = AgentBrowserNavigationTracker{}; @@ -1747,7 +1760,8 @@ struct AgentBrowserHost::Impl ++page->favicon_generation; page->restore_url = (url.empty() || url == "about:blank") ? std::string() : url; const bool restoring = !page->restore_url.empty(); - update_page(page, [restoring](AgentBrowserState& state) { + update_page(page, [restoring, page](AgentBrowserState& state) { + state.page_annotations_json = page->annotations.snapshot().dump(); state.ready = false; state.loading = restoring; state.visible = false; @@ -1772,6 +1786,13 @@ struct AgentBrowserHost::Impl } const AgentBrowserCookieModeSwitch plan = plan_agent_browser_cookie_mode_switch(cookie_mode, *mode); + std::vector> affected; + if (plan.changed) { + for (const auto& id : agent_browser_pages_to_rebuild(page_store_bindings(), *mode)) { + if (const auto candidate = find_page(id)) affected.push_back(candidate); + } + if (!reserve_annotation_pages(affected, error, true)) return false; + } // 档位相同也写一次:状态里可能是空(从未选过)或别的版本写入的未知值。 const bool persisted = update_agent_browser_store_state( [&mode, &plan](AgentBrowserStoreState& state) { @@ -1785,6 +1806,7 @@ struct AgentBrowserHost::Impl return true; }); if (!persisted) { + for (const auto& candidate : affected) candidate->annotations.navigation.finish(); assign_error(error, "failed to save the Agent Browser cookie setting"); return false; } @@ -1794,9 +1816,9 @@ struct AgentBrowserHost::Impl cookie_mode = *mode; if (plan.mark_session_stores_for_wipe) prepared_session_stores.clear(); // 先把页面搬进新存储;清空走临时 controller,与页面互不影响。 - const auto rebuild = agent_browser_pages_to_rebuild(page_store_bindings(), cookie_mode); - for (const auto& page_id : rebuild) { - rebuild_page_on_ui(find_page(page_id)); + const auto rebuild = affected; + for (const auto& candidate : affected) { + rebuild_page_on_ui(candidate); } if (plan.clear_shared_now) clear_shared_store_and_mark_done(); if (plan.release_until_quit_store) release_until_quit_keepalive(); @@ -1823,22 +1845,16 @@ struct AgentBrowserHost::Impl } const AgentBrowserCookieStoreKey key = page->creation_started ? page->store : agent_browser_cookie_store_key(cookie_mode, page->state.owner); + const auto affected = annotation_store_pages(*this, key); + if (!reserve_annotation_pages(affected, error, true)) return false; + const auto reload = annotation_transition_tickets(affected); const auto weak = weak_from_this(); - clear_store(key, [weak, key, page_id](bool ok, const std::string& clear_error) { + clear_store(key, [weak, key, page_id, reload](bool ok, const std::string& clear_error) { const auto self = weak.lock(); if (!self) return; + annotation_reload_reserved(*self, reload, key, ok, + [](const auto& candidate) { return SUCCEEDED(candidate->webview->Reload()); }); if (ok) { - std::vector> reload; - { - std::lock_guard lock(self->state_mutex); - for (const auto& [id, candidate] : self->pages) { - if (!candidate->closing && candidate->webview && - candidate->store == key) { - reload.push_back(candidate); - } - } - } - for (const auto& candidate : reload) candidate->webview->Reload(); LOG_INFO("[agent-browser] browsing data cleared: " + key.id()); } else { LOG_WARN("[agent-browser] failed to clear browsing data for " + key.id() + @@ -1983,6 +1999,8 @@ struct AgentBrowserHost::Impl const HRESULT visible_result = page->controller->put_IsVisible(TRUE); show = SUCCEEDED(bounds_result) && SUCCEEDED(visible_result); + set_agent_browser_widget_input_enabled( + browser_widget, !page->requested_bounds.interaction_blocked); if (!show) { LOG_WARN("[agent-browser] failed to show native page " + page->id + " (bounds=" + @@ -1998,6 +2016,7 @@ struct AgentBrowserHost::Impl } } if (page->state.active && !show) { + set_agent_browser_widget_input_enabled(browser_widget, true); hide_agent_browser_widget(browser_widget); } if (page->state.visible != show) { @@ -2021,9 +2040,11 @@ struct AgentBrowserHost::Impl assign_error(error, normalize_error); return false; } + if (!annotation_fragment_navigation(page->state.url, *url) && !reserve_annotation_pages({page}, error)) return false; const HRESULT result = page->webview->Navigate( acecode::utf8_to_wide(*url).c_str()); if (FAILED(result)) { + page->annotations.navigation.finish(); assign_error(error, "WebView2 navigation failed (" + hresult_text(result) + ")"); return false; @@ -2031,6 +2052,10 @@ struct AgentBrowserHost::Impl return true; } + bool reserve_annotation_pages(const std::vector>& affected, std::string* error, bool hold = false) { + return annotation_reserve_pages(*this, affected, error, hold); + } + bool set_shared_with_agent_on_ui(const std::string& page_id, bool shared, std::string* error) { @@ -2051,24 +2076,7 @@ struct AgentBrowserHost::Impl LPCWSTR raw) { const auto page = find_page(page_id); if (!page) return; - nlohmann::json selected; - if (SUCCEEDED(result) && raw) { - auto response = nlohmann::json::parse( - acecode::wide_to_utf8(raw), nullptr, false); - if (!response.is_discarded() && response.is_object()) { - const auto remote = response.value( - "result", nlohmann::json::object()); - if (remote.is_object() && remote.contains("value") && - remote["value"].is_object()) { - const auto& value = remote["value"]; - if (!value.value("cancelled", true) && - value.contains("element") && - value["element"].is_object()) { - selected = value["element"]; - } - } - } - } + const auto selected = selected_element(result, raw); AgentBrowserState snapshot; { @@ -2164,6 +2172,25 @@ struct AgentBrowserHost::Impl return true; } + using AnnotationResult = std::function; + + void evaluate_annotation(const std::shared_ptr& page, + std::uint64_t sequence, std::string expression, + AnnotationResult completion, browser_capture::Current active = {}) { + const auto weak = weak_from_this(); + const std::weak_ptr weak_page = page; + const auto incarnation = page->controller_generation; + agent_browser_windows::evaluate_annotation(page->webview, + [weak, weak_page, incarnation, sequence, active] { + const auto self = weak.lock(); + const auto current = weak_page.lock(); + return self && current && !current->closing && + self->find_page(current->id) == current && + current->controller_generation == incarnation && + current->annotations.sequence() == sequence && (!active || active()); + }, std::move(expression), std::move(completion)); + } + bool open_developer_tools_on_ui(const std::string& page_id, std::string* error) { auto page = find_page(page_id); @@ -2171,13 +2198,43 @@ struct AgentBrowserHost::Impl assign_error(error, "Agent Browser page is still starting"); return false; } - const HRESULT result = page->webview->OpenDevToolsWindow(); - if (FAILED(result)) { - assign_error(error, "failed to open WebView2 developer tools (" + - hresult_text(result) + ")"); - return false; - } - return true; + return agent_browser_windows::open_developer_tools(page->webview, error); + } + + void capture_screenshot( + const std::shared_ptr& page, const nlohmann::json& params, + const std::shared_ptr& pending, + const std::string& annotation_validation = {}) { + const auto weak = weak_from_this(); + const auto webview = page->webview; + const auto navigation_id = page->navigation.current_navigation_id(); + const auto controller_generation = page->controller_generation; + const auto annotation_document = page->annotations.document_id(); + const auto current = [weak, page, webview, navigation_id, controller_generation, pending, + annotation_document, + trusted_annotation = !annotation_validation.empty()] { + const auto self = weak.lock(); + if (pending->completed()) return false; + return self && self->find_page(page->id) == page && !page->closing && + page->webview == webview && page->controller_generation == controller_generation && + page->navigation.current_navigation_id() == navigation_id && + !page->state.loading && + page->state.content_state == kAgentBrowserContentStateLive && + (!trusted_annotation || page->annotations.document_id() == annotation_document) && + (trusted_annotation || self->page_shared_with_agent(page)); + }; + browser_capture::capture_cdp(page->id, params, + [webview](const std::string& method, const nlohmann::json& arguments, + browser_capture::CommandResult done) { + agent_browser_windows::capture_command(webview, method, arguments, std::move(done)); + }, current, + [pending](nlohmann::json response) { finish_proxy_call(pending, std::move(response)); }, + annotation_capture_validation(annotation_validation, + [weak, page, current](const std::string& expression, AnnotationResult done) { + const auto self = weak.lock(); + if (!self || !current()) { done(false, {}); return; } + agent_browser_windows::evaluate_annotation(page->webview, current, expression, std::move(done)); + }), page->annotations.requests.cleanup(pending)); } void call_cdp_on_ui( @@ -2214,49 +2271,22 @@ struct AgentBrowserHost::Impl if (environment) begin_create_controller(page); return; } - const std::wstring wide_method = acecode::utf8_to_wide(method); - const std::wstring wide_params = acecode::utf8_to_wide( - (params.is_object() ? params : nlohmann::json::object()).dump()); - auto completed = Microsoft::WRL::Callback< - ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>( - [pending, page_id](HRESULT result, LPCWSTR raw) -> HRESULT { - if (FAILED(result)) { - finish_proxy_call( - pending, - {{"ok", false}, - {"page_id", page_id}, - {"error", "WebView2 CDP call failed (" + - hresult_text(result) + ")"}}); - return S_OK; - } - const std::string text = raw - ? acecode::wide_to_utf8(raw) : std::string("{}"); - auto value = nlohmann::json::parse(text, nullptr, false); - if (value.is_discarded()) { - finish_proxy_call( - pending, - {{"ok", false}, - {"page_id", page_id}, - {"error", "WebView2 returned malformed CDP JSON"}}); - return S_OK; - } - finish_proxy_call( - pending, - {{"ok", true}, - {"page_id", page_id}, - {"result", std::move(value)}}); - return S_OK; - }); - const HRESULT started = page->webview->CallDevToolsProtocolMethod( - wide_method.c_str(), wide_params.c_str(), completed.Get()); - if (FAILED(started)) { - finish_proxy_call( - pending, - {{"ok", false}, - {"page_id", page_id}, - {"error", "failed to dispatch WebView2 CDP call (" + - hresult_text(started) + ")"}}); + if (method == "Page.captureScreenshot") { + bool full_page = false; + const auto error = browser_capture::request_mode(params, full_page); + if (!error.empty()) { + finish_proxy_call(pending, {{"ok", false}, {"page_id", page_id}, + {"error", error}, {"recoverable", true}}); + return; + } + if (full_page) { + capture_screenshot(page, params, pending); + return; + } } + annotation_proxy_transition(*this, page, method, pending, [page, page_id, method, params](auto done) { + proxy_command(page->webview, page_id, method, params, std::move(done)); + }); } void execute_proxy_request_on_ui( @@ -2365,42 +2395,10 @@ struct AgentBrowserHost::Impl } nlohmann::json execute_proxy_request(const nlohmann::json& request) { - if (!request.is_object()) { - return {{"ok", false}, {"error", "proxy request must be an object"}}; - } - if (!request.contains("auth_token") || - !request["auth_token"].is_string() || - request["auth_token"].get_ref() != - proxy_auth_token) { - return {{"ok", false}, - {"error", "Agent Browser proxy authentication failed"}}; - } - const std::string operation = request.value("operation", "cdp"); - if (operation != "cdp" && operation != "create_page" && - operation != "claim_page" && - operation != "close_page" && operation != "select_page" && - operation != "drain_store_tasks") { - return {{"ok", false}, - {"error", "Agent Browser proxy operation is invalid"}}; - } - if (operation == "cdp") { - if (!request.contains("method") || !request["method"].is_string()) { - return {{"ok", false}, - {"error", "Agent Browser CDP method is invalid"}}; - } - const std::string method = request["method"].get(); - if (method.empty() || method.size() > 256) { - return {{"ok", false}, - {"error", "Agent Browser CDP method is invalid"}}; - } - } - const int requested_timeout = request.contains("timeout_ms") && - request["timeout_ms"].is_number_integer() - ? request["timeout_ms"].get() : 15000; - const int timeout_ms = (std::max)( - 100, (std::min)(120000, requested_timeout)); - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::milliseconds(timeout_ms); + const auto request_error = browser_proxy_request_error( + request, proxy_auth_token, "Agent Browser CDP method is invalid"); + if (!request_error.empty()) return {{"ok", false}, {"error", request_error}}; + const auto deadline = browser_proxy_deadline(request); auto pending = std::make_shared(); const auto weak = weak_from_this(); try { @@ -2419,17 +2417,7 @@ struct AgentBrowserHost::Impl error.what()}}; } - std::unique_lock lock(pending->mutex); - while (!pending->completed && !proxy_stopping.load() && - std::chrono::steady_clock::now() < deadline) { - pending->ready.wait_for(lock, std::chrono::milliseconds(50)); - } - if (pending->completed) return pending->response; - return {{"ok", false}, - {"page_id", request.value("page_id", "")}, - {"error", proxy_stopping.load() - ? "Agent Browser stopped" - : "WebView2 CDP call timed out"}}; + return pending->wait(request, proxy_stopping, deadline, "WebView2 CDP call timed out"); } void handle_proxy_connection(HANDLE pipe) { @@ -2602,23 +2590,7 @@ bool AgentBrowserHost::set_bounds(const std::string& page_id, assign_error(error, "Agent Browser is unavailable on this platform"); return false; } - if (bounds.x < 0 || bounds.y < 0 || bounds.width < 0 || bounds.height < 0 || - bounds.width > 32768 || bounds.height > 32768) { - assign_error(error, "Agent Browser bounds are invalid"); - return false; - } - if (bounds.occlusion_rects.size() > kAgentBrowserMaxOcclusionRects) { - assign_error(error, "Agent Browser has too many occlusion rectangles"); - return false; - } - for (const auto& rect : bounds.occlusion_rects) { - if (rect.x < 0 || rect.y < 0 || rect.width <= 0 || rect.height <= 0 || - rect.x > 32768 || rect.y > 32768 || - rect.width > 32768 || rect.height > 32768) { - assign_error(error, "Agent Browser occlusion rectangle is invalid"); - return false; - } - } + if (!valid_agent_browser_bounds(bounds, error)) return false; #ifdef _WIN32 auto page = impl_->find_page(page_id); if (!page) { @@ -2653,8 +2625,11 @@ bool AgentBrowserHost::go_back(const std::string& page_id, std::string* error) { #ifdef _WIN32 auto page = impl_ ? impl_->find_page(page_id) : nullptr; - if (page && page->webview && page->state.can_go_back && - SUCCEEDED(page->webview->GoBack())) return true; + if (page && page->webview && page->state.can_go_back) { + if (!impl_->reserve_annotation_pages({page}, error)) return false; + if (SUCCEEDED(page->webview->GoBack())) return true; + page->annotations.navigation.finish(); + } assign_error(error, "Agent Browser cannot go back"); #else (void)page_id; @@ -2667,8 +2642,11 @@ bool AgentBrowserHost::go_forward(const std::string& page_id, std::string* error) { #ifdef _WIN32 auto page = impl_ ? impl_->find_page(page_id) : nullptr; - if (page && page->webview && page->state.can_go_forward && - SUCCEEDED(page->webview->GoForward())) return true; + if (page && page->webview && page->state.can_go_forward) { + if (!impl_->reserve_annotation_pages({page}, error)) return false; + if (SUCCEEDED(page->webview->GoForward())) return true; + page->annotations.navigation.finish(); + } assign_error(error, "Agent Browser cannot go forward"); #else (void)page_id; @@ -2681,7 +2659,11 @@ bool AgentBrowserHost::reload(const std::string& page_id, std::string* error) { #ifdef _WIN32 auto page = impl_ ? impl_->find_page(page_id) : nullptr; - if (page && page->webview && SUCCEEDED(page->webview->Reload())) return true; + if (page && page->webview) { + if (!impl_->reserve_annotation_pages({page}, error)) return false; + if (SUCCEEDED(page->webview->Reload())) return true; + page->annotations.navigation.finish(); + } assign_error(error, "Agent Browser page is still starting"); #else (void)page_id; @@ -2729,6 +2711,18 @@ bool AgentBrowserHost::toggle_element_selection(const std::string& page_id, #endif } +void AgentBrowserHost::annotation_command( + const std::string& page_id, const std::string& command_json, + std::function completion) { +#ifdef _WIN32 + annotation_dispatch(impl_, page_id, command_json, std::move(completion)); +#else + (void)page_id; + (void)command_json; + completion("{\"ok\":false,\"error\":\"Annotations unavailable\"}"); +#endif +} + std::string AgentBrowserHost::console_logs(const std::string& page_id, std::string* error) const { #ifdef _WIN32 diff --git a/src/apps/desktop/agent_browser_host.hpp b/src/apps/desktop/agent_browser_host.hpp index 8d3aa049e..9d7f6c6cb 100644 --- a/src/apps/desktop/agent_browser_host.hpp +++ b/src/apps/desktop/agent_browser_host.hpp @@ -26,6 +26,15 @@ struct AgentBrowserOcclusionRect { int y = 0; int width = 0; int height = 0; + // Corner radius in surface pixels. Overlay cards and toolbars are rounded, + // so a plain rectangular hole would expose the WebUI background at their + // corners. 0 keeps the legacy rectangular hole. + int radius = 0; + // Bitmask of corners that the surface edge cut instead of the overlay + // (1 top-left, 2 top-right, 4 bottom-right, 8 bottom-left). Rounding a cut + // corner paints a quarter circle of Browser content across the overlay, so + // those corners are squared off on the native side. + int square_corners = 0; }; struct AgentBrowserBounds { @@ -34,6 +43,10 @@ struct AgentBrowserBounds { int width = 0; int height = 0; bool visible = false; + // Keep the native page painted, but make it ignore pointer/keyboard input + // while a WebUI modal dialog sits above it. Implemented as EnableWindow(FALSE) + // on Windows and an input-ignoring surface view on macOS. + bool interaction_blocked = false; std::uint64_t layout_revision = 0; std::vector occlusion_rects; }; @@ -67,6 +80,7 @@ struct AgentBrowserState { // Transient event payload. It is populated only on the state snapshot that // completes a user element pick and is not retained in the page state. std::string selected_element_json; + std::string page_annotations_json; }; // cookie 存储相关的异步结果(切档、清除浏览数据、删除会话存储)。清除 / 删除是 @@ -136,6 +150,9 @@ class AgentBrowserHost { std::string* error = nullptr); bool toggle_element_selection(const std::string& page_id, std::string* error = nullptr); + void annotation_command(const std::string& page_id, + const std::string& command_json, + std::function completion); std::string console_logs(const std::string& page_id, std::string* error = nullptr) const; bool open_developer_tools(const std::string& page_id, diff --git a/src/apps/desktop/agent_browser_host_common.cpp b/src/apps/desktop/agent_browser_host_common.cpp index 4fe1a8511..184bab1a7 100644 --- a/src/apps/desktop/agent_browser_host_common.cpp +++ b/src/apps/desktop/agent_browser_host_common.cpp @@ -19,4 +19,27 @@ std::string agent_browser_title_or_default(std::string title) { : std::move(title); } +bool valid_agent_browser_bounds(const AgentBrowserBounds& bounds, + std::string* error) { + if (bounds.x < 0 || bounds.y < 0 || bounds.width < 0 || bounds.height < 0 || + bounds.width > 32768 || bounds.height > 32768) { + assign_error(error, "Agent Browser bounds are invalid"); + return false; + } + if (bounds.occlusion_rects.size() > kAgentBrowserMaxOcclusionRects) { + assign_error(error, "Agent Browser has too many occlusion rectangles"); + return false; + } + for (const auto& rect : bounds.occlusion_rects) { + if (rect.x < 0 || rect.y < 0 || rect.width <= 0 || rect.height <= 0 || + rect.x > 32768 || rect.y > 32768 || rect.width > 32768 || + rect.height > 32768 || rect.radius < 0 || rect.radius > 32768 || + rect.square_corners < 0 || rect.square_corners > 0xF) { + assign_error(error, "Agent Browser occlusion rectangle is invalid"); + return false; + } + } + return true; +} + } // namespace acecode::desktop::agent_browser_common diff --git a/src/apps/desktop/agent_browser_host_common.hpp b/src/apps/desktop/agent_browser_host_common.hpp index 30795da6f..26a6d3c4d 100644 --- a/src/apps/desktop/agent_browser_host_common.hpp +++ b/src/apps/desktop/agent_browser_host_common.hpp @@ -1,8 +1,15 @@ #pragma once #include #include +namespace acecode::desktop { +struct AgentBrowserBounds; +} namespace acecode::desktop::agent_browser_common { std::int64_t now_unix_ms(); void assign_error(std::string* target, const std::string& value); std::string agent_browser_title_or_default(std::string title); +// set_bounds 的入参校验。两个平台的宿主各写了一遍同样的判定,收在这里避免 +// 一边加了字段另一边漏校验。失败时写 error 并返回 false。 +bool valid_agent_browser_bounds(const AgentBrowserBounds& bounds, + std::string* error); } // namespace acecode::desktop::agent_browser_common diff --git a/src/apps/desktop/agent_browser_host_mac.mm b/src/apps/desktop/agent_browser_host_mac.mm index 298dcb8cf..7ccf22eff 100644 --- a/src/apps/desktop/agent_browser_host_mac.mm +++ b/src/apps/desktop/agent_browser_host_mac.mm @@ -1,8 +1,15 @@ #include "agent_browser_host.hpp" +#include "agent_browser_host_common.hpp" +#include "page_annotation_session.hpp" +#include "page_annotation_host_submission.hpp" +#include "page_annotation_host_adapter.hpp" #ifdef __APPLE__ #include "agent_browser_cookie_jars.hpp" +#include "agent_browser_capture.hpp" +#include "agent_browser_capture_mac.hpp" +#include "agent_browser_proxy_request.hpp" #include "agent_browser_macos_helpers.hpp" #include "agent_browser_navigation_state.hpp" #include "ipc/agent_browser_runtime.hpp" @@ -66,6 +73,7 @@ virtual void navigation_failed(const std::string&, WKWebView*, NSError*, const std::string&, std::uint64_t) = 0; virtual void navigation_policy_decided( const std::string&, WKWebView*, WKNavigationAction*, bool, bool) = 0; + virtual bool annotation_navigation_allowed(const std::string&, WKWebView*, WKNavigationAction*) = 0; // 把系统已注册的外部 URI/SSO scheme 交给操作系统。返回 true 表示已交接, // 随后 WebView 的取消回调按「已处理」对待而不是导航失败。 virtual bool handoff_external_url(const std::string&, WKWebView*, @@ -85,11 +93,47 @@ virtual void store_prompt(const std::string&, NSString*, NSString*, } // namespace } // namespace acecode::desktop +namespace { + +// Adds one occlusion hole with an independent radius per DOM corner +// (top-left, top-right, bottom-right, bottom-left). A radius of 0 draws that +// corner square, which is what the surface edge needs: `hole` is already +// expressed in the target layer's coordinates, so the DOM corner order maps +// straight onto the rectangle. +void add_occlusion_cornered_hole(CGMutablePathRef path, + CGRect hole, + CGFloat top_left, + CGFloat top_right, + CGFloat bottom_right, + CGFloat bottom_left) { + const CGFloat min_x = CGRectGetMinX(hole); + const CGFloat min_y = CGRectGetMinY(hole); + const CGFloat max_x = CGRectGetMaxX(hole); + const CGFloat max_y = CGRectGetMaxY(hole); + CGPathMoveToPoint(path, nullptr, min_x + bottom_left, min_y); + CGPathAddArcToPoint(path, nullptr, min_x, min_y, min_x, min_y + bottom_left, + bottom_left); + CGPathAddArcToPoint(path, nullptr, min_x, max_y, min_x + top_left, max_y, + top_left); + CGPathAddArcToPoint(path, nullptr, max_x, max_y, max_x, max_y - top_right, + top_right); + CGPathAddArcToPoint(path, nullptr, max_x, min_y, max_x - bottom_right, min_y, + bottom_right); + CGPathCloseSubpath(path); +} + +} // namespace + @interface ACECodeAgentBrowserSurfaceView : NSView { @private - NSArray* occlusion_rects_; -} -- (BOOL)setOcclusionRects:(NSArray*)rects; + NSArray* occlusion_rects_; NSArray* occlusion_radii_; + NSArray* occlusion_square_corners_; + BOOL interaction_blocked_; +} +- (BOOL)setOcclusionRects:(NSArray*)rects + radii:(NSArray*)radii + squareCorners:(NSArray*)squareCorners; +- (void)setInteractionBlocked:(BOOL)blocked; @end @implementation ACECodeAgentBrowserSurfaceView @@ -97,14 +141,17 @@ @implementation ACECodeAgentBrowserSurfaceView - (instancetype)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { - occlusion_rects_ = [[NSArray alloc] init]; + occlusion_rects_ = [[NSArray alloc] init]; occlusion_radii_ = [[NSArray alloc] init]; + occlusion_square_corners_ = [[NSArray alloc] init]; + interaction_blocked_ = NO; [self setWantsLayer:YES]; } return self; } - (void)dealloc { - [occlusion_rects_ release]; + [occlusion_rects_ release]; [occlusion_radii_ release]; + [occlusion_square_corners_ release]; [super dealloc]; } @@ -119,8 +166,11 @@ - (CAShapeLayer*)newOcclusionMaskForView:(NSView*)target_view { const CGFloat height = NSHeight(bounds); CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, nullptr, CGRectMake(0, 0, width, height)); - for (NSValue* value in occlusion_rects_) { - const NSRect rect = [value rectValue]; + for (NSUInteger index = 0; index < [occlusion_rects_ count]; index += 1) { + const NSRect rect = [[occlusion_rects_ objectAtIndex:index] rectValue]; + const CGFloat radius = std::clamp(index < [occlusion_radii_ count] + ? [[occlusion_radii_ objectAtIndex:index] doubleValue] : 0.0, 0.0, + (std::min)(NSWidth(rect), NSHeight(rect)) / 2.0); // Occlusion rectangles use the DOM's top-left Browser contract. // Backing layers for flipped AppKit views already use that orientation; // converting them again mirrors top overlays to the bottom. Convert Y @@ -130,8 +180,26 @@ - (CAShapeLayer*)newOcclusionMaskForView:(NSView*)target_view { const CGFloat y = [target_view isFlipped] ? top : height - top - NSHeight(rect); - CGPathAddRect(path, nullptr, - CGRectMake(x, y, NSWidth(rect), NSHeight(rect))); + const CGRect hole = CGRectMake(x, y, NSWidth(rect), NSHeight(rect)); + const int square_corners = radius > 0 && index < [occlusion_square_corners_ count] + ? [[occlusion_square_corners_ objectAtIndex:index] intValue] & 0xF + : 0; + if (radius <= 0 || square_corners == 0xF) { + CGPathAddRect(path, nullptr, hole); + } else if (square_corners == 0) { + CGPathAddRoundedRect(path, nullptr, hole, radius, radius); + } else { + // A corner the surface cut must stay square; rounding it would cut a + // quarter circle out of the overlay where the page begins. The hole + // rect already carries the DOM orientation, so the corner order maps + // straight onto the target layer. + add_occlusion_cornered_hole( + path, hole, + (square_corners & 1) ? 0 : radius, + (square_corners & 2) ? 0 : radius, + (square_corners & 4) ? 0 : radius, + (square_corners & 8) ? 0 : radius); + } } CAShapeLayer* mask = [[CAShapeLayer alloc] init]; @@ -190,14 +258,22 @@ - (void)setFrameSize:(NSSize)newSize { [self updateOcclusionMask]; } -- (BOOL)setOcclusionRects:(NSArray*)rects { - NSArray* next = rects ? [rects copy] : [[NSArray alloc] init]; - [occlusion_rects_ release]; - occlusion_rects_ = next; +- (BOOL)setOcclusionRects:(NSArray*)rects + radii:(NSArray*)radii + squareCorners:(NSArray*)squareCorners { + [occlusion_rects_ release]; occlusion_rects_ = rects ? [rects copy] : [[NSArray alloc] init]; + [occlusion_radii_ release]; occlusion_radii_ = radii ? [radii copy] : [[NSArray alloc] init]; + [occlusion_square_corners_ release]; + occlusion_square_corners_ = squareCorners ? [squareCorners copy] : [[NSArray alloc] init]; return [self updateOcclusionMask]; } +- (void)setInteractionBlocked:(BOOL)blocked { + interaction_blocked_ = blocked; +} + - (NSView*)hitTest:(NSPoint)point { + if (interaction_blocked_) return nil; NSView* superview = [self superview]; const NSPoint local = superview ? [self convertPoint:point fromView:superview] @@ -352,7 +428,7 @@ - (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSURL* url = navigationAction.request.URL; - const bool allowed = acecode::desktop::safe_navigation_url(url); + bool allowed = acecode::desktop::safe_navigation_url(url); bool handed_off = false; if (!allowed && owner_ && acecode::desktop::external_handoff_candidate_url(url)) { @@ -360,6 +436,7 @@ - (void)webView:(WKWebView*)webView [self pageIDValue], webView, url); } if (owner_) { + if (allowed) allowed = owner_->annotation_navigation_allowed([self pageIDValue], webView, navigationAction); owner_->navigation_policy_decided( [self pageIDValue], webView, navigationAction, allowed, handed_off); } @@ -432,16 +509,13 @@ - (void)webView:(WKWebView*)webView : public MacAgentBrowserDelegateSink, public std::enable_shared_from_this { bool parent_surface_visible = true; - - struct PendingProxyCall { - std::mutex mutex; - std::condition_variable ready; - bool completed = false; - json response; - }; + // 会话级批注记录(Q33):页签销毁不带走记录。 + SessionAnnotationStoreRegistry annotation_store_registry; struct Page { std::string id; + PageAnnotationSession annotations; + std::uint64_t annotation_incarnation = 0; AgentBrowserState state; AgentBrowserBounds requested_bounds; ACECodeAgentBrowserSurfaceView* surface = nil; @@ -475,6 +549,7 @@ - (void)webView:(WKWebView*)webView using StoreDone = std::function; void* parent_window = nullptr; + AnnotationPoller annotation_poller; std::int64_t desktop_pid = 0; std::string desktop_instance_id; std::string acecode_dir; @@ -665,18 +740,6 @@ void fail(const std::string& message) { }); } - static void finish_proxy_call( - const std::shared_ptr& pending, - json response) { - { - std::lock_guard lock(pending->mutex); - if (pending->completed) return; - pending->completed = true; - pending->response = std::move(response); - } - pending->ready.notify_all(); - } - void start() { if (!host_state.supported) return; NSWindow* window = static_cast(parent_window); @@ -955,6 +1018,7 @@ void finish_page_store(const std::shared_ptr& page, auto waiters = std::move(page->ready_waiters); page->ready_waiters.clear(); if (!ok) { + page->annotations.navigation.finish(); update_page(page, [&error](AgentBrowserState& value) { value.ready = false; value.error = error; @@ -972,11 +1036,13 @@ void finish_page_store(const std::shared_ptr& page, const std::string url = page->restore_url; page->restore_url.clear(); std::string navigate_error; - if (!navigate_on_ui(page->id, url, &navigate_error)) { + page->annotations.navigation.arm(); + if (!navigate_on_ui(page->id, url, &navigate_error, true)) { + page->annotations.navigation.finish(); LOG_WARN("[agent-browser][macos] failed to restore " + page->id + " after cookie store change: " + navigate_error); } - } + } else page->annotations.navigation.finish(); apply_bounds(page); } @@ -1010,7 +1076,7 @@ void clear_history(const std::shared_ptr& page) { } void teardown_page(const std::shared_ptr& page) { - if (!page) return; + if (!annotation_retire(page)) return; clear_dialog(page, true); clear_history(page); if (page->webview) { @@ -1128,6 +1194,8 @@ void attach_webview(const std::shared_ptr& page) { page->state.supported = true; page->state.shared_with_agent = shared_with_agent; page->state.owner = owner; + // 同会话所有页签共享一个记录容器;页签关掉后记录仍在,转 orphan 继续可发。 + page->annotations.share_store(annotation_store_registry.for_session(owner.session_id)); attach_webview(page); std::vector changed; @@ -1177,8 +1245,9 @@ bool apply_bounds(const std::shared_ptr& page) { bounds.x, y, bounds.width, bounds.height)]; [page->webview setFrame:[page->surface bounds]]; - NSMutableArray* occlusion_rects = - [NSMutableArray arrayWithCapacity:bounds.occlusion_rects.size()]; + NSMutableArray* occlusion_rects = [NSMutableArray arrayWithCapacity:bounds.occlusion_rects.size()]; + NSMutableArray* occlusion_radii = [NSMutableArray arrayWithCapacity:bounds.occlusion_rects.size()]; + NSMutableArray* occlusion_square_corners = [NSMutableArray arrayWithCapacity:bounds.occlusion_rects.size()]; for (const auto& occlusion : bounds.occlusion_rects) { const int left = std::max(0, std::min(bounds.width, occlusion.x)); const int top = std::max(0, std::min(bounds.height, occlusion.y)); @@ -1189,10 +1258,16 @@ bool apply_bounds(const std::shared_ptr& page) { if (right > left && bottom > top) { [occlusion_rects addObject:[NSValue valueWithRect:NSMakeRect( left, top, right - left, bottom - top)]]; + [occlusion_radii addObject:@((std::max)(0, (std::min)( + occlusion.radius, (std::min)(right - left, bottom - top) / 2)))]; + [occlusion_square_corners addObject:@(occlusion.square_corners & 0xF)]; } } const bool occlusion_ready = - [page->surface setOcclusionRects:occlusion_rects] == YES; + [page->surface setOcclusionRects:occlusion_rects + radii:occlusion_radii + squareCorners:occlusion_square_corners] == YES; + [page->surface setInteractionBlocked:bounds.interaction_blocked ? YES : NO]; const AgentBrowserState snapshot = state(page->id); const bool show = parent_surface_visible && bounds.visible && snapshot.active && @@ -1263,6 +1338,7 @@ bool close_page_on_ui(const std::string& requested_page, changed = sync_agent_target_flags_locked(); } teardown_page(page); + page->annotations.replace_document(); page->state.closed = true; page->state.ready = false; page->state.visible = false; @@ -1304,12 +1380,14 @@ void rebuild_page_on_ui(const std::shared_ptr& page) { url = page->state.url; } teardown_page(page); + page->annotations.replace_document(); page->navigation = AgentBrowserNavigationTracker{}; ++page->element_selection_generation; page->console_logs.clear(); page->restore_url = (url.empty() || url == "about:blank") ? std::string() : url; const bool restoring = !page->restore_url.empty(); - update_page(page, [restoring](AgentBrowserState& value) { + update_page(page, [restoring, page](AgentBrowserState& value) { + value.page_annotations_json = page->annotations.snapshot().dump(); value.ready = false; value.loading = restoring; value.visible = false; @@ -1344,6 +1422,13 @@ bool set_cookie_mode_on_ui(const std::string& name, std::string* error) { } const AgentBrowserCookieModeSwitch plan = plan_agent_browser_cookie_mode_switch(cookie_mode, *mode); + std::vector> affected; + if (plan.changed) { + for (const auto& id : agent_browser_pages_to_rebuild(page_store_bindings(), *mode)) { + if (const auto candidate = find_page(id)) affected.push_back(candidate); + } + if (!reserve_annotation_pages(affected, error, true)) return false; + } const bool persisted = update_agent_browser_store_state( [&mode, &plan](AgentBrowserStoreState& state) { state.cookie_mode = agent_browser_cookie_mode_name(*mode); @@ -1356,6 +1441,7 @@ bool set_cookie_mode_on_ui(const std::string& name, std::string* error) { return true; }); if (!persisted) { + for (const auto& candidate : affected) candidate->annotations.navigation.finish(); assign_error(error, "failed to save the Agent Browser cookie setting"); return false; } @@ -1364,8 +1450,8 @@ bool set_cookie_mode_on_ui(const std::string& name, std::string* error) { const AgentBrowserCookieMode previous = cookie_mode; cookie_mode = *mode; if (plan.mark_session_stores_for_wipe) prepared_session_stores.clear(); - const auto rebuild = agent_browser_pages_to_rebuild(page_store_bindings(), cookie_mode); - for (const auto& page_id : rebuild) rebuild_page_on_ui(find_page(page_id)); + const auto rebuild = affected; + for (const auto& candidate : affected) rebuild_page_on_ui(candidate); if (plan.clear_shared_now) clear_shared_store_and_mark_done(); if (plan.release_until_quit_store) { [until_quit_store release]; @@ -1389,24 +1475,18 @@ bool clear_browsing_data_on_ui(const std::string& page_id, std::string* error) { return false; } const AgentBrowserCookieStoreKey key = page->store; + const auto affected = annotation_store_pages(*this, key); + if (!reserve_annotation_pages(affected, error, true)) return false; + const auto reload = annotation_transition_tickets(affected); const auto weak = weak_from_this(); const std::string requested_page = page_id; clear_data_store(store_for_key(key), - [weak, key, requested_page](bool ok, const std::string& clear_error) { + [weak, key, requested_page, reload](bool ok, const std::string& clear_error) { const auto self = weak.lock(); if (!self) return; + annotation_reload_reserved(*self, reload, key, ok, + [](const auto& candidate) { return [candidate->webview reload] != nil; }); if (ok) { - std::vector> reload; - { - std::lock_guard lock(self->state_mutex); - for (const auto& item : self->pages) { - if (!item.second->closing && item.second->webview && - item.second->store == key) { - reload.push_back(item.second); - } - } - } - for (const auto& candidate : reload) [candidate->webview reload]; LOG_INFO("[agent-browser][macos] browsing data cleared: " + key.id()); } else { LOG_WARN("[agent-browser][macos] failed to clear browsing data for " + @@ -1470,7 +1550,7 @@ bool set_shared_with_agent_on_ui(const std::string& page_id, bool navigate_on_ui(const std::string& page_id, const std::string& input, - std::string* error) { + std::string* error, bool approved = false) { auto page = find_page(page_id); if (!page || !page->webview || page->closing || !page->store_prepared) { assign_error(error, "Agent Browser page is still starting"); @@ -1486,6 +1566,8 @@ bool navigate_on_ui(const std::string& page_id, }.dump())); return false; } + if (!approved && !annotation_fragment_navigation(page->state.url, *normalized) && + !reserve_annotation_pages({page}, error)) return false; LOG_INFO(("[agent-browser][macos] " + json{ {"event", "navigation_requested"}, {"page_id", page_id}, @@ -1496,6 +1578,7 @@ bool navigate_on_ui(const std::string& page_id, } else { NSURL* url = [NSURL URLWithString:ns_string(*normalized)]; if (!url) { + page->annotations.navigation.finish(); assign_error(error, "Agent Browser URL is invalid"); return false; } @@ -1505,6 +1588,17 @@ bool navigate_on_ui(const std::string& page_id, return true; } + bool reserve_annotation_pages(const std::vector>& affected, std::string* error, bool hold = false) { + return annotation_reserve_pages(*this, affected, error, hold); + } + + bool annotation_navigation_allowed(const std::string& page_id, WKWebView* webview, + WKNavigationAction* action) override { + const auto page = find_page(page_id); + if (!page || page->webview != webview) return false; + return annotation_allow_action(*this, page, action); + } + bool page_shared_with_agent(const std::shared_ptr& page) const { if (!page) return false; std::lock_guard lock(state_mutex); @@ -1527,6 +1621,8 @@ void navigation_started(const std::string& page_id, std::uint64_t navigation_id) override { auto page = find_page(page_id); if (!page || page->webview != webview) return; + if (!page->annotations.navigation.start(page->annotations.navigation.navigating())) return; + page->annotations.suspend(); { std::lock_guard lock(state_mutex); if (page->state.content_state != @@ -1573,6 +1669,10 @@ void navigation_committed(const std::string& page_id, WKWebView* webview) override { auto page = find_page(page_id); if (!page || page->webview != webview) return; + page->annotations.replace_document(); + update_page(page, [page](AgentBrowserState& value) { + value.page_annotations_json = page->annotations.snapshot().dump(); + }); LOG_INFO(("[agent-browser][macos] " + json{ {"event", "navigation_committed"}, {"page_id", page_id}, @@ -1789,6 +1889,7 @@ void navigation_finished(const std::string& page_id, return; } refresh_page_identity(page); + page->annotations.navigation.finish(); update_page(page, [](AgentBrowserState& value) { value.loading = false; value.content_state = kAgentBrowserContentStateLive; @@ -1846,6 +1947,7 @@ void navigation_failed(const std::string& page_id, return; } + page->annotations.navigation.finish(); if (decision == BrowserNavigationDecision::kRestorePrevious) { // 被新导航取代、重定向替换或已交给操作系统的外部 scheme。这些是引擎 // 内部的中间取消,不是这次浏览的最终结果 —— 发布错误页只会造成录屏里 @@ -1902,6 +2004,10 @@ void page_identity_changed(const std::string& page_id, WKWebView* webview) override { auto page = find_page(page_id); if (page && page->webview == webview && !page->closing) { + if (page->annotations.navigation.reserved() && page->annotations.navigation.armed() && + !webview.loading && annotation_fragment_navigation(page->state.url, utf8_string(webview.URL.absoluteString))) { + page->annotations.navigation.finish(); + } refresh_page_identity(page); } } @@ -1909,12 +2015,15 @@ void page_identity_changed(const std::string& page_id, void process_terminated(const std::string& page_id) override { auto page = find_page(page_id); if (!page) return; + page->annotations.replace_document(); + page->annotations.navigation.finish(); LOG_ERROR(("[agent-browser][macos] " + json{ {"event", "web_content_process_terminated"}, {"page_id", page_id}, {"url", page->state.url}, }.dump())); - update_page(page, [](AgentBrowserState& value) { + update_page(page, [page](AgentBrowserState& value) { + value.page_annotations_json = page->annotations.snapshot().dump(); value.loading = false; value.visible = false; value.content_state = kAgentBrowserContentStateProcessFailed; @@ -1956,6 +2065,7 @@ void load_popup_in_page(const std::string& page_id, {"decision", allowed ? "load_in_page" : "cancel"}, }.dump(); if (allowed) { + if (!reserve_annotation_pages({page}, nullptr)) return; LOG_INFO(log_line); load_agent_browser_request(page->webview, request); } else { @@ -2010,7 +2120,7 @@ void run_native_input( const std::shared_ptr&); void capture_screenshot( const std::shared_ptr&, const json&, - const std::shared_ptr&); + const std::shared_ptr&, const std::string& = {}); bool prepare_native_input( const std::shared_ptr&, std::string&); CGPoint native_screen_point( @@ -2027,95 +2137,6 @@ void execute_proxy_request_on_ui( void proxy_loop(); }; -namespace { - -std::string synthetic_mouse_expression(const json& parameters) { - json payload = parameters.is_object() ? parameters : json::object(); - payload.erase("acecodeInputMode"); - return "(() => {\n" - " const p=" + payload.dump() + ";\n" - " const x=Number(p.x||0),y=Number(p.y||0);\n" - " const target=document.elementFromPoint(x,y)||document.documentElement;\n" - " if(!target)return {ok:false,message:'No element at input coordinates'};\n" - " const key='__acecodeSyntheticPointerV1';const state=globalThis[key]||(globalThis[key]={pressed:null,dragging:false,data:null});\n" - " const names={mouseMoved:'mousemove',mousePressed:'mousedown',mouseReleased:'mouseup',mouseWheel:'wheel'};\n" - " const button={left:0,middle:1,right:2}[String(p.button||'left')]??0;\n" - " const buttons=Number(p.buttons==null?(p.type==='mousePressed'?1:0):p.buttons);\n" - " const init={bubbles:true,cancelable:true,composed:true,clientX:x,clientY:y,screenX:x,screenY:y,button,buttons,detail:Number(p.clickCount||1)};\n" - " if(p.type==='mouseWheel'){const event=new WheelEvent('wheel',{...init,deltaX:Number(p.deltaX||0),deltaY:Number(p.deltaY||0),deltaMode:0});target.dispatchEvent(event);if(!event.defaultPrevented)window.scrollBy({left:Number(p.deltaX||0),top:Number(p.deltaY||0),behavior:'instant'});return {ok:true};}\n" - " if(p.type==='mousePressed'){target.focus?.({preventScroll:true});state.pressed=target;state.dragging=false;state.data=null;target.dispatchEvent(new MouseEvent('mousedown',init));return {ok:true};}\n" - " if(p.type==='mouseMoved'){target.dispatchEvent(new MouseEvent('mousemove',init));if(state.pressed&&buttons){try{if(!state.dragging){state.data=new DataTransfer();state.pressed.dispatchEvent(new DragEvent('dragstart',{...init,dataTransfer:state.data}));state.dragging=true;}target.dispatchEvent(new DragEvent('dragenter',{...init,dataTransfer:state.data}));target.dispatchEvent(new DragEvent('dragover',{...init,dataTransfer:state.data}));}catch(_){}}return {ok:true};}\n" - " if(p.type==='mouseReleased'){target.dispatchEvent(new MouseEvent('mouseup',init));if(state.dragging){try{target.dispatchEvent(new DragEvent('drop',{...init,dataTransfer:state.data}));state.pressed?.dispatchEvent(new DragEvent('dragend',{...init,dataTransfer:state.data}));}catch(_){}}else if(state.pressed){const clickTarget=state.pressed.isConnected?state.pressed:target;if(button===0&&typeof clickTarget.click==='function')clickTarget.click();else clickTarget.dispatchEvent(new MouseEvent('contextmenu',init));if(Number(p.clickCount||1)>1)clickTarget.dispatchEvent(new MouseEvent('dblclick',init));}state.pressed=null;state.dragging=false;state.data=null;return {ok:true};}\n" - " target.dispatchEvent(new MouseEvent(names[p.type]||String(p.type||'mousemove'),init));return {ok:true};\n" - "})()"; -} - -std::string synthetic_text_expression(const json& parameters) { - json payload = parameters.is_object() ? parameters : json::object(); - payload.erase("acecodeInputMode"); - return "(() => {\n" - " const p=" + payload.dump() + ";const text=String(p.text==null?'':p.text);const el=document.activeElement;\n" - " if(!el||el===document.body)return {ok:false,message:'No focused editable element'};\n" - " const before=new InputEvent('beforeinput',{bubbles:true,cancelable:true,composed:true,inputType:'insertText',data:text});if(!el.dispatchEvent(before))return {ok:true,cancelled:true};\n" - " if(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement){const start=Number.isInteger(el.selectionStart)?el.selectionStart:el.value.length;const end=Number.isInteger(el.selectionEnd)?el.selectionEnd:start;el.setRangeText(text,start,end,'end');}\n" - " else if(el.isContentEditable){const selection=getSelection();if(selection&&selection.rangeCount){selection.deleteFromDocument();selection.getRangeAt(0).insertNode(document.createTextNode(text));selection.collapseToEnd();}else el.textContent=(el.textContent||'')+text;}\n" - " else if('value'in el){el.value=String(el.value||'')+text;}else return {ok:false,message:'Focused element is not editable'};\n" - " el.dispatchEvent(new InputEvent('input',{bubbles:true,composed:true,inputType:'insertText',data:text}));return {ok:true};\n" - "})()"; -} - -std::string synthetic_key_expression(const json& parameters) { - json payload = parameters.is_object() ? parameters : json::object(); - payload.erase("acecodeInputMode"); - return "(() => {\n" - " const p=" + payload.dump() + ";const el=document.activeElement||document.body;const key=String(p.key||'');const down=p.type==='keyDown'||p.type==='rawKeyDown';const mods=Number(p.modifiers||0);\n" - " const init={key,code:String(p.code||key),bubbles:true,cancelable:true,composed:true,altKey:!!(mods&1),ctrlKey:!!(mods&2),metaKey:!!(mods&4),shiftKey:!!(mods&8),repeat:false};\n" - " const event=new KeyboardEvent(down?'keydown':'keyup',init);const proceed=el.dispatchEvent(event);if(!down||!proceed)return {ok:true};\n" - " if((init.metaKey||init.ctrlKey)&&key.toLowerCase()==='a'&&typeof el.select==='function'){el.select();return {ok:true};}\n" - " if(key==='Tab'){const nodes=[...document.querySelectorAll('a[href],button,input,textarea,select,[tabindex]:not([tabindex=\"-1\"])')].filter(n=>!n.disabled&&n.getClientRects().length);const index=nodes.indexOf(el);const delta=init.shiftKey?-1:1;const next=nodes[(index+delta+nodes.length)%nodes.length];next?.focus();return {ok:true};}\n" - " if(key==='Enter'){if(el instanceof HTMLTextAreaElement){el.setRangeText('\\n',el.selectionStart,el.selectionEnd,'end');el.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertLineBreak',data:'\\n'}));}else if(el.form&&typeof el.form.requestSubmit==='function'){el.form.requestSubmit();}else if(typeof el.click==='function'){el.click();}return {ok:true};}\n" - " if((key==='Backspace'||key==='Delete')&&(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement)){const start=el.selectionStart??el.value.length;const end=el.selectionEnd??start;const left=key==='Backspace'&&start===end?Math.max(0,start-1):start;const right=key==='Delete'&&start===end?Math.min(el.value.length,end+1):end;el.setRangeText('',left,right,'end');el.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'deleteContentBackward',data:null}));}\n" - " return {ok:true};\n" - "})()"; -} - -std::string remote_type(const json& value) { - if (value.is_null()) return "object"; - if (value.is_boolean()) return "boolean"; - if (value.is_number()) return "number"; - if (value.is_string()) return "string"; - return "object"; -} - -CGMouseButton cg_mouse_button(const std::string& button) { - if (button == "right") return kCGMouseButtonRight; - if (button == "middle") return kCGMouseButtonCenter; - return kCGMouseButtonLeft; -} - -CGEventType cg_mouse_event_type(const std::string& type, - CGMouseButton button, - bool dragging) { - if (type == "mousePressed") { - return button == kCGMouseButtonRight ? kCGEventRightMouseDown - : button == kCGMouseButtonCenter ? kCGEventOtherMouseDown - : kCGEventLeftMouseDown; - } - if (type == "mouseReleased") { - return button == kCGMouseButtonRight ? kCGEventRightMouseUp - : button == kCGMouseButtonCenter ? kCGEventOtherMouseUp - : kCGEventLeftMouseUp; - } - if (dragging) { - return button == kCGMouseButtonRight ? kCGEventRightMouseDragged - : button == kCGMouseButtonCenter ? kCGEventOtherMouseDragged - : kCGEventLeftMouseDragged; - } - return kCGEventMouseMoved; -} - -} // namespace - CGPoint AgentBrowserHost::Impl::native_screen_point( const std::shared_ptr& page, double x, @@ -2301,52 +2322,38 @@ CGEventType cg_mouse_event_type(const std::string& type, void AgentBrowserHost::Impl::capture_screenshot( const std::shared_ptr& page, const json& params, - const std::shared_ptr& pending) { - (void)params; - // Objective-C blocks retain C++ values, but a reference parameter would - // otherwise leave the asynchronous callback pointing at the caller's - // short-lived shared_ptr object. - const auto target_page = page; - const auto completion = pending; - WKSnapshotConfiguration* configuration = - [[[WKSnapshotConfiguration alloc] init] autorelease]; - configuration.rect = [target_page->webview bounds]; - [target_page->webview takeSnapshotWithConfiguration:configuration - completionHandler:^(NSImage* image, NSError* error) { - if (error || !image) { - finish_proxy_call(completion, - {{"ok", false}, {"page_id", target_page->id}, - {"error", error - ? utf8_string([error localizedDescription]) - : "WKWebView snapshot failed"}}); - return; - } - CGImageRef cg_image = [image CGImageForProposedRect:nil - context:nil - hints:nil]; - if (!cg_image) { - finish_proxy_call(completion, - {{"ok", false}, {"page_id", target_page->id}, - {"error", "WKWebView snapshot returned no image"}}); - return; - } - NSBitmapImageRep* representation = [[[NSBitmapImageRep alloc] - initWithCGImage:cg_image] autorelease]; - NSData* data = [representation - representationUsingType:NSBitmapImageFileTypePNG properties:@{}]; - if (!data || [data length] == 0) { - finish_proxy_call(completion, - {{"ok", false}, {"page_id", target_page->id}, - {"error", "failed to encode WKWebView snapshot"}}); - return; - } - const std::string bytes( - static_cast([data bytes]), [data length]); - finish_proxy_call(completion, - {{"ok", true}, {"page_id", target_page->id}, - {"result", {{"data", acecode::base64_encode(bytes)}, - {"captureBeyondViewport", false}}}}); - }]; + const std::shared_ptr& pending, + const std::string& annotation_validation) { + const auto weak = weak_from_this(); + const auto navigation_id = page->navigation.current_navigation_id(); + const auto view = std::shared_ptr([page->webview retain], + [](WKWebView* value) { [value release]; }); + const auto annotation_document = page->annotations.document_id(); + const auto current = [weak, page, view, navigation_id, pending, annotation_document, + trusted_annotation = !annotation_validation.empty()] { + const auto self = weak.lock(); + if (pending->completed()) return false; + return self && self->find_page(page->id) == page && !page->closing && + page->webview == view.get() && !page->state.loading && + page->navigation.current_navigation_id() == navigation_id && + page->state.content_state == kAgentBrowserContentStateLive && + (!trusted_annotation || page->annotations.document_id() == annotation_document) && + (trusted_annotation || self->page_shared_with_agent(page)); + }; + browser_capture::capture_webkit(view, page->id, params, + [weak, page, current](const std::string& expression, browser_capture::Evaluated done) { + const auto self = weak.lock(); + if (!self || !current()) { done(false, {}, "capture_document_changed"); return; } + self->evaluate_value(page, expression, std::move(done)); + }, current, + [pending](json response) { finish_proxy_call(pending, std::move(response)); }, + annotation_capture_validation(annotation_validation, + [weak, page, current](const std::string& expression, std::function done) { + const auto self = weak.lock(); + if (!self || !current()) { done(false, {}); return; } + self->evaluate_value(page, expression, + [done](bool ok, json value, std::string) { done(ok, std::move(value)); }); + })); } bool AgentBrowserHost::Impl::handle_dialog_on_ui( @@ -2433,7 +2440,7 @@ CGEventType cg_mouse_event_type(const std::string& type, finish_proxy_call(pending, {{"ok", true}, {"page_id", page->id}, {"result", {{"result", { - {"type", remote_type(value)}, {"value", value}, + {"type", remote_object_type(value)}, {"value", value}, }}}}}); }); return; @@ -2452,6 +2459,10 @@ CGEventType cg_mouse_event_type(const std::string& type, return; } if (method == "Page.reload") { + if (!reserve_annotation_pages({page}, nullptr)) { + finish_proxy_call(pending, {{"ok", false}, {"page_id", page_id}, {"error", "Navigation cancelled"}}); + return; + } [page->webview reload]; finish_proxy_call(pending, {{"ok", true}, {"page_id", page_id}, @@ -2500,6 +2511,10 @@ CGEventType cg_mouse_event_type(const std::string& type, {{"ok", false}, {"page_id", page_id}, {"error", "Browser history entry is invalid"}}); } else { + if (!reserve_annotation_pages({page}, nullptr)) { + finish_proxy_call(pending, {{"ok", false}, {"page_id", page_id}, {"error", "Navigation cancelled"}}); + return; + } [page->webview goToBackForwardListItem: page->history_items[static_cast(entry_id - 1)]]; finish_proxy_call(pending, @@ -2639,38 +2654,10 @@ CGEventType cg_mouse_event_type(const std::string& type, } json AgentBrowserHost::Impl::execute_proxy_request(const json& request) { - if (!request.is_object()) { - return {{"ok", false}, {"error", "proxy request must be an object"}}; - } - if (!request.contains("auth_token") || - !request["auth_token"].is_string() || - request["auth_token"].get_ref() != - proxy_auth_token) { - return {{"ok", false}, - {"error", "Agent Browser proxy authentication failed"}}; - } - const std::string operation = request.value("operation", "cdp"); - if (operation != "cdp" && operation != "create_page" && - operation != "claim_page" && operation != "close_page" && - operation != "select_page" && operation != "drain_store_tasks") { - return {{"ok", false}, - {"error", "Agent Browser proxy operation is invalid"}}; - } - if (operation == "cdp") { - if (!request.contains("method") || !request["method"].is_string() || - request["method"].get_ref().empty() || - request["method"].get_ref().size() > 256) { - return {{"ok", false}, - {"error", "Agent Browser command method is invalid"}}; - } - } - const int requested_timeout = - request.contains("timeout_ms") && request["timeout_ms"].is_number_integer() - ? request["timeout_ms"].get() : 15000; - const int timeout_ms = (std::max)( - 100, (std::min)(120000, requested_timeout)); - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::milliseconds(timeout_ms); + const auto request_error = browser_proxy_request_error( + request, proxy_auth_token, "Agent Browser command method is invalid"); + if (!request_error.empty()) return {{"ok", false}, {"error", request_error}}; + const auto deadline = browser_proxy_deadline(request); auto pending = std::make_shared(); const auto weak = weak_from_this(); try { @@ -2688,17 +2675,7 @@ CGEventType cg_mouse_event_type(const std::string& type, std::string(error.what())}}; } - std::unique_lock lock(pending->mutex); - while (!pending->completed && !proxy_stopping.load() && - std::chrono::steady_clock::now() < deadline) { - pending->ready.wait_for(lock, std::chrono::milliseconds(50)); - } - if (pending->completed) return pending->response; - return {{"ok", false}, - {"page_id", request.value("page_id", "")}, - {"error", proxy_stopping.load() - ? "Agent Browser stopped" - : "WKWebView command timed out"}}; + return pending->wait(request, proxy_stopping, deadline, "WKWebView command timed out"); } void AgentBrowserHost::Impl::handle_proxy_connection(int connection) { @@ -2959,23 +2936,9 @@ CGEventType cg_mouse_event_type(const std::string& type, assign_error(error, "Agent Browser is unavailable on this platform"); return false; } - if (bounds.x < 0 || bounds.y < 0 || bounds.width < 0 || bounds.height < 0 || - bounds.width > 32768 || bounds.height > 32768) { - assign_error(error, "Agent Browser bounds are invalid"); - return false; - } - if (bounds.occlusion_rects.size() > kAgentBrowserMaxOcclusionRects) { - assign_error(error, "Agent Browser has too many occlusion rectangles"); + if (!agent_browser_common::valid_agent_browser_bounds(bounds, error)) { return false; } - for (const auto& rect : bounds.occlusion_rects) { - if (rect.x < 0 || rect.y < 0 || rect.width <= 0 || rect.height <= 0 || - rect.x > 32768 || rect.y > 32768 || - rect.width > 32768 || rect.height > 32768) { - assign_error(error, "Agent Browser occlusion rectangle is invalid"); - return false; - } - } auto page = impl_->find_page(page_id); if (!page) { assign_error(error, "Agent Browser page was not found"); @@ -3004,6 +2967,7 @@ CGEventType cg_mouse_event_type(const std::string& type, std::string* error) { auto page = impl_ ? impl_->find_page(page_id) : nullptr; if (page && page->webview && page->webview.canGoBack) { + if (!impl_->reserve_annotation_pages({page}, error)) return false; [page->webview goBack]; return true; } @@ -3015,6 +2979,7 @@ CGEventType cg_mouse_event_type(const std::string& type, std::string* error) { auto page = impl_ ? impl_->find_page(page_id) : nullptr; if (page && page->webview && page->webview.canGoForward) { + if (!impl_->reserve_annotation_pages({page}, error)) return false; [page->webview goForward]; return true; } @@ -3026,6 +2991,7 @@ CGEventType cg_mouse_event_type(const std::string& type, std::string* error) { auto page = impl_ ? impl_->find_page(page_id) : nullptr; if (page && page->webview) { + if (!impl_->reserve_annotation_pages({page}, error)) return false; [page->webview reload]; return true; } @@ -3055,6 +3021,12 @@ CGEventType cg_mouse_event_type(const std::string& type, return impl_ && impl_->toggle_element_selection_on_ui(page_id, error); } +void AgentBrowserHost::annotation_command( + const std::string& page_id, const std::string& command_json, + std::function completion) { + annotation_dispatch(impl_, page_id, command_json, std::move(completion)); +} + std::string AgentBrowserHost::console_logs(const std::string& page_id, std::string* error) const { auto page = impl_ ? impl_->find_page(page_id) : nullptr; diff --git a/src/apps/desktop/agent_browser_macos_helpers.hpp b/src/apps/desktop/agent_browser_macos_helpers.hpp index 14b4f6fd9..2274e0d98 100644 --- a/src/apps/desktop/agent_browser_macos_helpers.hpp +++ b/src/apps/desktop/agent_browser_macos_helpers.hpp @@ -40,6 +40,15 @@ NSString* safari_compatible_application_name(); const char* favicon_expression(); const char* console_capture_script(); const char* element_picker_expression(); +// 原生输入合成:把 WebView2 风格的 mouse/text/key 参数翻成页面内执行的 JS。 +std::string synthetic_mouse_expression(const json& parameters); +std::string synthetic_text_expression(const json& parameters); +std::string synthetic_key_expression(const json& parameters); +std::string remote_object_type(const json& value); +CGMouseButton cg_mouse_button(const std::string& button); +CGEventType cg_mouse_event_type(const std::string& type, + CGMouseButton button, + bool dragging); std::string navigation_failure_kind(NSError* error, bool proxy_authentication_challenge); const char* navigation_type_name(WKNavigationType type); diff --git a/src/apps/desktop/agent_browser_macos_helpers.mm b/src/apps/desktop/agent_browser_macos_helpers.mm index 8f22e9c98..9b9dd6590 100644 --- a/src/apps/desktop/agent_browser_macos_helpers.mm +++ b/src/apps/desktop/agent_browser_macos_helpers.mm @@ -371,6 +371,91 @@ bool valid_favicon(const std::string& value) { })())JS"; } +std::string synthetic_mouse_expression(const json& parameters) { + json payload = parameters.is_object() ? parameters : json::object(); + payload.erase("acecodeInputMode"); + return "(() => {\n" + " const p=" + payload.dump() + ";\n" + " const x=Number(p.x||0),y=Number(p.y||0);\n" + " const target=document.elementFromPoint(x,y)||document.documentElement;\n" + " if(!target)return {ok:false,message:'No element at input coordinates'};\n" + " const key='__acecodeSyntheticPointerV1';const state=globalThis[key]||(globalThis[key]={pressed:null,dragging:false,data:null});\n" + " const names={mouseMoved:'mousemove',mousePressed:'mousedown',mouseReleased:'mouseup',mouseWheel:'wheel'};\n" + " const button={left:0,middle:1,right:2}[String(p.button||'left')]??0;\n" + " const buttons=Number(p.buttons==null?(p.type==='mousePressed'?1:0):p.buttons);\n" + " const init={bubbles:true,cancelable:true,composed:true,clientX:x,clientY:y,screenX:x,screenY:y,button,buttons,detail:Number(p.clickCount||1)};\n" + " if(p.type==='mouseWheel'){const event=new WheelEvent('wheel',{...init,deltaX:Number(p.deltaX||0),deltaY:Number(p.deltaY||0),deltaMode:0});target.dispatchEvent(event);if(!event.defaultPrevented)window.scrollBy({left:Number(p.deltaX||0),top:Number(p.deltaY||0),behavior:'instant'});return {ok:true};}\n" + " if(p.type==='mousePressed'){target.focus?.({preventScroll:true});state.pressed=target;state.dragging=false;state.data=null;target.dispatchEvent(new MouseEvent('mousedown',init));return {ok:true};}\n" + " if(p.type==='mouseMoved'){target.dispatchEvent(new MouseEvent('mousemove',init));if(state.pressed&&buttons){try{if(!state.dragging){state.data=new DataTransfer();state.pressed.dispatchEvent(new DragEvent('dragstart',{...init,dataTransfer:state.data}));state.dragging=true;}target.dispatchEvent(new DragEvent('dragenter',{...init,dataTransfer:state.data}));target.dispatchEvent(new DragEvent('dragover',{...init,dataTransfer:state.data}));}catch(_){}}return {ok:true};}\n" + " if(p.type==='mouseReleased'){target.dispatchEvent(new MouseEvent('mouseup',init));if(state.dragging){try{target.dispatchEvent(new DragEvent('drop',{...init,dataTransfer:state.data}));state.pressed?.dispatchEvent(new DragEvent('dragend',{...init,dataTransfer:state.data}));}catch(_){}}else if(state.pressed){const clickTarget=state.pressed.isConnected?state.pressed:target;if(button===0&&typeof clickTarget.click==='function')clickTarget.click();else clickTarget.dispatchEvent(new MouseEvent('contextmenu',init));if(Number(p.clickCount||1)>1)clickTarget.dispatchEvent(new MouseEvent('dblclick',init));}state.pressed=null;state.dragging=false;state.data=null;return {ok:true};}\n" + " target.dispatchEvent(new MouseEvent(names[p.type]||String(p.type||'mousemove'),init));return {ok:true};\n" + "})()"; +} + +std::string synthetic_text_expression(const json& parameters) { + json payload = parameters.is_object() ? parameters : json::object(); + payload.erase("acecodeInputMode"); + return "(() => {\n" + " const p=" + payload.dump() + ";const text=String(p.text==null?'':p.text);const el=document.activeElement;\n" + " if(!el||el===document.body)return {ok:false,message:'No focused editable element'};\n" + " const before=new InputEvent('beforeinput',{bubbles:true,cancelable:true,composed:true,inputType:'insertText',data:text});if(!el.dispatchEvent(before))return {ok:true,cancelled:true};\n" + " if(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement){const start=Number.isInteger(el.selectionStart)?el.selectionStart:el.value.length;const end=Number.isInteger(el.selectionEnd)?el.selectionEnd:start;el.setRangeText(text,start,end,'end');}\n" + " else if(el.isContentEditable){const selection=getSelection();if(selection&&selection.rangeCount){selection.deleteFromDocument();selection.getRangeAt(0).insertNode(document.createTextNode(text));selection.collapseToEnd();}else el.textContent=(el.textContent||'')+text;}\n" + " else if('value'in el){el.value=String(el.value||'')+text;}else return {ok:false,message:'Focused element is not editable'};\n" + " el.dispatchEvent(new InputEvent('input',{bubbles:true,composed:true,inputType:'insertText',data:text}));return {ok:true};\n" + "})()"; +} + +std::string synthetic_key_expression(const json& parameters) { + json payload = parameters.is_object() ? parameters : json::object(); + payload.erase("acecodeInputMode"); + return "(() => {\n" + " const p=" + payload.dump() + ";const el=document.activeElement||document.body;const key=String(p.key||'');const down=p.type==='keyDown'||p.type==='rawKeyDown';const mods=Number(p.modifiers||0);\n" + " const init={key,code:String(p.code||key),bubbles:true,cancelable:true,composed:true,altKey:!!(mods&1),ctrlKey:!!(mods&2),metaKey:!!(mods&4),shiftKey:!!(mods&8),repeat:false};\n" + " const event=new KeyboardEvent(down?'keydown':'keyup',init);const proceed=el.dispatchEvent(event);if(!down||!proceed)return {ok:true};\n" + " if((init.metaKey||init.ctrlKey)&&key.toLowerCase()==='a'&&typeof el.select==='function'){el.select();return {ok:true};}\n" + " if(key==='Tab'){const nodes=[...document.querySelectorAll('a[href],button,input,textarea,select,[tabindex]:not([tabindex=\"-1\"])')].filter(n=>!n.disabled&&n.getClientRects().length);const index=nodes.indexOf(el);const delta=init.shiftKey?-1:1;const next=nodes[(index+delta+nodes.length)%nodes.length];next?.focus();return {ok:true};}\n" + " if(key==='Enter'){if(el instanceof HTMLTextAreaElement){el.setRangeText('\\n',el.selectionStart,el.selectionEnd,'end');el.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertLineBreak',data:'\\n'}));}else if(el.form&&typeof el.form.requestSubmit==='function'){el.form.requestSubmit();}else if(typeof el.click==='function'){el.click();}return {ok:true};}\n" + " if((key==='Backspace'||key==='Delete')&&(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement)){const start=el.selectionStart??el.value.length;const end=el.selectionEnd??start;const left=key==='Backspace'&&start===end?Math.max(0,start-1):start;const right=key==='Delete'&&start===end?Math.min(el.value.length,end+1):end;el.setRangeText('',left,right,'end');el.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'deleteContentBackward',data:null}));}\n" + " return {ok:true};\n" + "})()"; +} + +std::string remote_object_type(const json& value) { + if (value.is_null()) return "object"; + if (value.is_boolean()) return "boolean"; + if (value.is_number()) return "number"; + if (value.is_string()) return "string"; + return "object"; +} + +CGMouseButton cg_mouse_button(const std::string& button) { + if (button == "right") return kCGMouseButtonRight; + if (button == "middle") return kCGMouseButtonCenter; + return kCGMouseButtonLeft; +} + +CGEventType cg_mouse_event_type(const std::string& type, + CGMouseButton button, + bool dragging) { + if (type == "mousePressed") { + return button == kCGMouseButtonRight ? kCGEventRightMouseDown + : button == kCGMouseButtonCenter ? kCGEventOtherMouseDown + : kCGEventLeftMouseDown; + } + if (type == "mouseReleased") { + return button == kCGMouseButtonRight ? kCGEventRightMouseUp + : button == kCGMouseButtonCenter ? kCGEventOtherMouseUp + : kCGEventLeftMouseUp; + } + if (dragging) { + return button == kCGMouseButtonRight ? kCGEventRightMouseDragged + : button == kCGMouseButtonCenter ? kCGEventOtherMouseDragged + : kCGEventLeftMouseDragged; + } + return kCGEventMouseMoved; +} + std::string navigation_failure_kind(NSError* error, bool proxy_authentication_challenge) { error = url_loading_error(error); diff --git a/src/apps/desktop/agent_browser_native_commands_win.cpp b/src/apps/desktop/agent_browser_native_commands_win.cpp new file mode 100644 index 000000000..83305cc30 --- /dev/null +++ b/src/apps/desktop/agent_browser_native_commands_win.cpp @@ -0,0 +1,171 @@ +#include "agent_browser_native_commands_win.hpp" +#include "agent_browser_host_common.hpp" + +#ifdef _WIN32 +#include "utils/encoding.hpp" + +#include + +namespace acecode::desktop::agent_browser_windows { +bool open_developer_tools(const NativeView& webview, std::string* error) { + const HRESULT result = webview->OpenDevToolsWindow(); + if (FAILED(result)) { + agent_browser_common::assign_error(error, "failed to open WebView2 developer tools (" + + hresult_text(result) + ")"); + return false; + } + return true; +} + +namespace { + +void annotation_cdp(const NativeView& webview, const browser_capture::Current& current, + const wchar_t* method, const nlohmann::json& params, + AnnotationResult completion) { + const auto serialized = acecode::utf8_to_wide(params.dump()); + auto callback = Microsoft::WRL::Callback< + ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>( + [current, completion](HRESULT status, LPCWSTR raw) -> HRESULT { + if (!current()) { + completion(false, nullptr); + return S_OK; + } + const auto result = raw ? nlohmann::json::parse( + acecode::wide_to_utf8(raw), nullptr, false) : nlohmann::json(); + completion(SUCCEEDED(status) && result.is_object(), result); + return S_OK; + }); + const auto status = webview->CallDevToolsProtocolMethod( + method, serialized.c_str(), callback.Get()); + if (FAILED(status)) completion(false, nullptr); +} + +} + +void evaluate_annotation(NativeView webview, browser_capture::Current current, + std::string expression, AnnotationResult completion) { + annotation_cdp(webview, current, L"Page.getFrameTree", nlohmann::json::object(), + [webview, current, expression, completion](bool ok, nlohmann::json result) { + if (!ok || !current() || + !result.contains("frameTree") || !result["frameTree"].is_object() || + !result["frameTree"].contains("frame") || !result["frameTree"]["frame"].is_object() || + !result["frameTree"]["frame"].contains("id") || + !result["frameTree"]["frame"]["id"].is_string()) { + completion(false, nullptr); + return; + } + const nlohmann::json params{ + {"frameId", result["frameTree"]["frame"]["id"]}, + {"worldName", "acecode-page-annotations-v1"}, + {"grantUniveralAccess", false}, + }; + annotation_cdp(webview, current, L"Page.createIsolatedWorld", params, + [webview, current, expression, completion](bool created, nlohmann::json world) { + if (!created || !current() || + !world.contains("executionContextId") || + !world["executionContextId"].is_number_integer()) { + completion(false, nullptr); + return; + } + annotation_cdp(webview, current, L"Runtime.evaluate", { + {"expression", expression}, {"contextId", world["executionContextId"]}, + {"returnByValue", true}, {"awaitPromise", true}, + }, [completion](bool evaluated, nlohmann::json response) { + if (!evaluated || response.contains("exceptionDetails") || + !response.contains("result") || !response["result"].is_object()) { + completion(false, nullptr); + return; + } + completion(true, response["result"].value("value", nlohmann::json())); + }); + }); + }); +} + +void capture_command(const NativeView& webview, const std::string& method, + const nlohmann::json& params, browser_capture::CommandResult completion) { + const bool screenshot = method == "Page.captureScreenshot"; + const auto callback = Microsoft::WRL::Callback< + ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>( + [completion, screenshot](HRESULT result, LPCWSTR raw) -> HRESULT { + if (FAILED(result)) { + completion({}, "capture_native_failed: " + hresult_text(result)); + return S_OK; + } + constexpr auto max_response = ((browser_capture::kMaxPngBytes + 2) / 3) * 4 + 1024; + if (screenshot && raw && wcsnlen(raw, max_response + 1) > max_response) { + completion({}, "capture_resource_limit"); + return S_OK; + } + try { + auto value = nlohmann::json::parse( + raw ? acecode::wide_to_utf8(raw) : "", nullptr, false); + if (!value.is_object() || value.contains("error")) { + completion({}, "capture_native_failed"); + } else { + completion(std::move(value), {}); + } + } catch (const std::bad_alloc&) { + completion({}, "capture_resource_limit"); + } + return S_OK; + }); + const auto wide_method = acecode::utf8_to_wide(method); + const auto wide_params = acecode::utf8_to_wide(params.dump()); + const HRESULT started = webview->CallDevToolsProtocolMethod( + wide_method.c_str(), wide_params.c_str(), callback.Get()); + if (FAILED(started)) completion({}, "capture_dispatch_failed"); +} + +void proxy_command(const NativeView& webview, std::string page_id, + const std::string& method, const nlohmann::json& params, + browser_capture::Complete completion) { + const std::wstring wide_method = acecode::utf8_to_wide(method); + const std::wstring wide_params = acecode::utf8_to_wide( + (params.is_object() ? params : nlohmann::json::object()).dump()); + auto completed = Microsoft::WRL::Callback< + ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>( + [completion, page_id](HRESULT result, LPCWSTR raw) -> HRESULT { + if (FAILED(result)) { + completion({{"ok", false}, {"page_id", page_id}, + {"error", "WebView2 CDP call failed (" + hresult_text(result) + ")"}}); + return S_OK; + } + const std::string text = raw ? acecode::wide_to_utf8(raw) : std::string("{}"); + auto value = nlohmann::json::parse(text, nullptr, false); + if (value.is_discarded()) { + completion({{"ok", false}, {"page_id", page_id}, + {"error", "WebView2 returned malformed CDP JSON"}}); + return S_OK; + } + completion({{"ok", true}, {"page_id", page_id}, {"result", std::move(value)}}); + return S_OK; + }); + const HRESULT started = webview->CallDevToolsProtocolMethod( + wide_method.c_str(), wide_params.c_str(), completed.Get()); + if (FAILED(started)) { + completion({{"ok", false}, {"page_id", page_id}, + {"error", "failed to dispatch WebView2 CDP call (" + hresult_text(started) + ")"}}); + } +} + +nlohmann::json selected_element(HRESULT result, LPCWSTR raw) { + nlohmann::json selected; + if (SUCCEEDED(result) && raw) { + auto response = nlohmann::json::parse(acecode::wide_to_utf8(raw), nullptr, false); + if (!response.is_discarded() && response.is_object()) { + const auto remote = response.value("result", nlohmann::json::object()); + if (remote.is_object() && remote.contains("value") && remote["value"].is_object()) { + const auto& value = remote["value"]; + if (!value.value("cancelled", true) && value.contains("element") && + value["element"].is_object()) { + selected = value["element"]; + } + } + } + } + return selected; +} + +} +#endif diff --git a/src/apps/desktop/agent_browser_native_commands_win.hpp b/src/apps/desktop/agent_browser_native_commands_win.hpp new file mode 100644 index 000000000..1fcedd8fe --- /dev/null +++ b/src/apps/desktop/agent_browser_native_commands_win.hpp @@ -0,0 +1,23 @@ +#pragma once + +#ifdef _WIN32 +#include "agent_browser_windows_helpers.hpp" +#include "agent_browser_capture_cdp.hpp" + +namespace acecode::desktop::agent_browser_windows { + +using NativeView = Microsoft::WRL::ComPtr; +using AnnotationResult = std::function; + +void capture_command(const NativeView& webview, const std::string& method, + const nlohmann::json& params, browser_capture::CommandResult completion); +void evaluate_annotation(NativeView webview, browser_capture::Current current, + std::string expression, AnnotationResult completion); +void proxy_command(const NativeView& webview, std::string page_id, + const std::string& method, const nlohmann::json& params, + browser_capture::Complete completion); +nlohmann::json selected_element(HRESULT result, LPCWSTR raw); +bool open_developer_tools(const NativeView& webview, std::string* error); + +} +#endif diff --git a/src/apps/desktop/agent_browser_proxy_request.hpp b/src/apps/desktop/agent_browser_proxy_request.hpp new file mode 100644 index 000000000..38dae9277 --- /dev/null +++ b/src/apps/desktop/agent_browser_proxy_request.hpp @@ -0,0 +1,99 @@ +#pragma once + +#include "agent_browser_capture.hpp" + +#include +#include +#include +#include +#include + +namespace acecode::desktop { + +inline std::string browser_proxy_request_error(const nlohmann::json& request, + const std::string& auth_token, + const char* method_error) { + if (!request.is_object()) return "proxy request must be an object"; + if (!request.contains("auth_token") || !request["auth_token"].is_string() || + request["auth_token"].get_ref() != auth_token) { + return "Agent Browser proxy authentication failed"; + } + const std::string operation = request.value("operation", "cdp"); + if (operation != "cdp" && operation != "create_page" && operation != "claim_page" && + operation != "close_page" && operation != "select_page" && operation != "drain_store_tasks") { + return "Agent Browser proxy operation is invalid"; + } + if (operation == "cdp" && (!request.contains("method") || !request["method"].is_string() || + request["method"].get_ref().empty() || + request["method"].get_ref().size() > 256)) { + return method_error; + } + return {}; +} + +inline std::chrono::steady_clock::time_point browser_proxy_deadline(const nlohmann::json& request) { + const int requested_timeout = request.contains("timeout_ms") && request["timeout_ms"].is_number_integer() + ? request["timeout_ms"].get() : 15000; + const int timeout_ms = (std::max)(100, (std::min)(120000, requested_timeout)); + return std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); +} + +class PendingProxyCall { +public: + explicit PendingProxyCall(std::function completion = {}) + : completion_(std::move(completion)) {} + + void finish(nlohmann::json response) { + std::function completion; + { + std::lock_guard lock(mutex_); + if (completed_) return; + completed_ = true; + completion = std::move(completion_); + if (!completion) response_ = std::move(response); + } + ready_.notify_all(); + if (completion) completion(std::move(response)); + } + + bool completed() const { + std::lock_guard lock(mutex_); + return completed_; + } + + nlohmann::json wait(const nlohmann::json& request, const std::atomic& stopping, + std::chrono::steady_clock::time_point deadline, + const char* timeout_error) { + std::unique_lock lock(mutex_); + while (!completed_ && !stopping.load() && std::chrono::steady_clock::now() < deadline) { + ready_.wait_for(lock, std::chrono::milliseconds(50)); + } + if (completed_) return response_; + bool full_page = false; + if (request.value("method", "") == "Page.captureScreenshot" && + browser_capture::request_mode(request.value("params", nlohmann::json::object()), full_page).empty() && + full_page) { + completed_ = true; + response_ = {{"ok", false}, {"page_id", request.value("page_id", "")}, + {"error", stopping.load() ? "capture_stopped" : "capture_timeout"}, + {"recoverable", true}}; + return response_; + } + return {{"ok", false}, {"page_id", request.value("page_id", "")}, + {"error", stopping.load() ? "Agent Browser stopped" : timeout_error}}; + } + +private: + mutable std::mutex mutex_; + std::condition_variable ready_; + bool completed_ = false; + nlohmann::json response_; + std::function completion_; +}; + +inline void finish_proxy_call(const std::shared_ptr& pending, + nlohmann::json response) { + pending->finish(std::move(response)); +} + +} diff --git a/src/apps/desktop/agent_browser_state_json.cpp b/src/apps/desktop/agent_browser_state_json.cpp new file mode 100644 index 000000000..9debfcc07 --- /dev/null +++ b/src/apps/desktop/agent_browser_state_json.cpp @@ -0,0 +1,41 @@ +#include "agent_browser_state_json.hpp" + +namespace acecode::desktop { + +nlohmann::json agent_browser_state_json(const AgentBrowserState& state) { + nlohmann::json result{ + {"supported", state.supported}, + {"ready", state.ready}, + {"loading", state.loading}, + {"visible", state.visible}, + {"active", state.active}, + {"closed", state.closed}, + {"can_go_back", state.can_go_back}, + {"can_go_forward", state.can_go_forward}, + {"shared_with_agent", state.shared_with_agent}, + {"element_selection_active", state.element_selection_active}, + {"element_selection_serial", state.element_selection_serial}, + {"url", state.url}, + {"title", state.title}, + {"favicon", state.favicon}, + {"content_state", state.content_state}, + {"failure_kind", state.failure_kind}, + {"error", state.error}, + {"diagnostic", state.diagnostic}, + {"page_id", state.page_id}, + {"owner", agent_browser_page_owner_json(state.owner)}, + {"agent_target", state.agent_target}, + }; + if (!state.selected_element_json.empty()) { + const auto selected = nlohmann::json::parse( + state.selected_element_json, nullptr, false); + if (!selected.is_discarded()) result["selected_element"] = selected; + } + if (!state.page_annotations_json.empty()) { + const auto annotations = nlohmann::json::parse(state.page_annotations_json, nullptr, false); + if (annotations.is_object()) result["annotations"] = annotations; + } + return result; +} + +} diff --git a/src/apps/desktop/agent_browser_state_json.hpp b/src/apps/desktop/agent_browser_state_json.hpp new file mode 100644 index 000000000..72849db45 --- /dev/null +++ b/src/apps/desktop/agent_browser_state_json.hpp @@ -0,0 +1,11 @@ +#pragma once + +#include "agent_browser_host.hpp" + +#include + +namespace acecode::desktop { + +nlohmann::json agent_browser_state_json(const AgentBrowserState& state); + +} diff --git a/src/apps/desktop/agent_browser_windows_helpers.cpp b/src/apps/desktop/agent_browser_windows_helpers.cpp index 6dc2da6f3..9717a2654 100644 --- a/src/apps/desktop/agent_browser_windows_helpers.cpp +++ b/src/apps/desktop/agent_browser_windows_helpers.cpp @@ -466,6 +466,14 @@ void hide_agent_browser_widget(HWND widget) { SWP_NOZORDER | SWP_HIDEWINDOW); } +// A modal WebUI dialog keeps the page painted but must stop it from receiving +// pointer/keyboard input (no hover outlines or clicks leaking through). +void set_agent_browser_widget_input_enabled(HWND widget, bool enabled) { + if (!widget || !::IsWindow(widget)) return; + if ((::IsWindowEnabled(widget) != FALSE) == enabled) return; + ::EnableWindow(widget, enabled ? TRUE : FALSE); +} + // 页面给的 bounds 是主 WebView 视口坐标,而 Agent Browser 子窗口挂在宿主窗口 // 上。两者原点通常重合;Win10 非最大化时主 WebView 下移了 1px 给自绘顶边线 // (web_host.cpp resize_webview_widget),这里要把偏移加回来,否则整块往上错位。 @@ -501,11 +509,39 @@ bool apply_agent_browser_widget_region( height, occlusion.y + occlusion.height)); if (right <= left || bottom <= top) continue; - HRGN hole = ::CreateRectRgn(left, top, right, bottom); + // Match the overlay's rounded corners so the WebUI background cannot + // peek through the native rectangle at the corners. Corners the + // surface cut stay square: rounding them would paint a curve of + // Browser content across the overlay at the surface edge. + const int radius = (std::max)(0, (std::min)( + occlusion.radius, (std::min)(right - left, bottom - top) / 2)); + HRGN hole = radius > 0 + ? ::CreateRoundRectRgn(left, top, right, bottom, radius * 2, radius * 2) + : ::CreateRectRgn(left, top, right, bottom); if (!hole) { ::DeleteObject(visible_region); return false; } + const int cut_corners = radius > 0 ? (occlusion.square_corners & 0xF) : 0; + if (cut_corners) { + // RGN_OR of the corner quarter squares turns each clipped corner of + // the rounded hole back into a right angle. + const RECT corners[4] = { + {left, top, left + radius, top + radius}, + {right - radius, top, right, top + radius}, + {right - radius, bottom - radius, right, bottom}, + {left, bottom - radius, left + radius, bottom}, + }; + for (int index = 0; index < 4; ++index) { + if (!(cut_corners & (1 << index))) continue; + const RECT& corner = corners[index]; + HRGN square = ::CreateRectRgn(corner.left, corner.top, corner.right, + corner.bottom); + if (!square) continue; + ::CombineRgn(hole, hole, square, RGN_OR); + ::DeleteObject(square); + } + } const int combine_result = ::CombineRgn(visible_region, visible_region, hole, RGN_DIFF); ::DeleteObject(hole); diff --git a/src/apps/desktop/agent_browser_windows_helpers.hpp b/src/apps/desktop/agent_browser_windows_helpers.hpp index bdd9b5db3..7463117a7 100644 --- a/src/apps/desktop/agent_browser_windows_helpers.hpp +++ b/src/apps/desktop/agent_browser_windows_helpers.hpp @@ -63,6 +63,7 @@ const char* agent_browser_element_picker_expression(); HWND create_agent_browser_widget(HWND parent); void park_agent_browser_widget(HWND widget); void hide_agent_browser_widget(HWND widget); +void set_agent_browser_widget_input_enabled(HWND widget, bool enabled); POINT main_web_content_origin(HWND parent); bool apply_agent_browser_widget_region( HWND widget, diff --git a/src/apps/desktop/main.cpp b/src/apps/desktop/main.cpp index 1f822dd55..908f952cc 100644 --- a/src/apps/desktop/main.cpp +++ b/src/apps/desktop/main.cpp @@ -15,7 +15,9 @@ #include "daemon_pool.hpp" #include "agent_browser_host.hpp" +#include "agent_browser_state_json.hpp" #include "agent_browser_cookie_bridge.hpp" +#include "page_annotation_bridge.hpp" #include "ios_simulator_view.hpp" #include "ipc/agent_browser_runtime.hpp" #include "context_items.hpp" @@ -110,40 +112,6 @@ constexpr const char* kSharedDaemonContextId = "default"; constexpr const char* kDesktopCloseRequestEvent = "acecode:desktop-close-requested"; -nlohmann::json agent_browser_state_json( - const acecode::desktop::AgentBrowserState& state) { - nlohmann::json result{ - {"supported", state.supported}, - {"ready", state.ready}, - {"loading", state.loading}, - {"visible", state.visible}, - {"active", state.active}, - {"closed", state.closed}, - {"can_go_back", state.can_go_back}, - {"can_go_forward", state.can_go_forward}, - {"shared_with_agent", state.shared_with_agent}, - {"element_selection_active", state.element_selection_active}, - {"element_selection_serial", state.element_selection_serial}, - {"url", state.url}, - {"title", state.title}, - {"favicon", state.favicon}, - {"content_state", state.content_state}, - {"failure_kind", state.failure_kind}, - {"error", state.error}, - {"diagnostic", state.diagnostic}, - {"page_id", state.page_id}, - // 页面归属:前端按 owner.session_id 把页面归到会话页签;null = 未绑定。 - {"owner", acecode::desktop::agent_browser_page_owner_json(state.owner)}, - {"agent_target", state.agent_target}, - }; - if (!state.selected_element_json.empty()) { - const auto selected = nlohmann::json::parse( - state.selected_element_json, nullptr, false); - if (!selected.is_discarded()) result["selected_element"] = selected; - } - return result; -} - struct ContextPickerFolderReference { std::string path; std::optional relative_path; @@ -1082,6 +1050,7 @@ int main(int argc, char** argv) { }, [&host](std::function task) { host.dispatch(std::move(task)); }); acecode::desktop::install_agent_browser_cookie_bridge(host, agent_browser); + const auto annotation_bridge = acecode::desktop::install_page_annotation_bridge(host, agent_browser); const auto ios_simulator_view = install_ios_simulator_view(host); DesktopRestartRequest restart_request; // 主 WebView 失效后无法就地修复:保留 daemon、重启桌面壳(web_host_health.hpp)。 @@ -1676,6 +1645,7 @@ int main(int argc, char** argv) { bounds.width = value.value("width", 0); bounds.height = value.value("height", 0); bounds.visible = value.value("visible", false); + bounds.interaction_blocked = value.value("interaction_blocked", false); if (const auto occlusions = value.find("occlusion_rects"); occlusions != value.end()) { if (!occlusions->is_array() || @@ -1698,6 +1668,8 @@ int main(int argc, char** argv) { rect.y = item.value("y", -1); rect.width = item.value("width", 0); rect.height = item.value("height", 0); + rect.radius = item.value("radius", 0); + rect.square_corners = item.value("square_corners", 0); bounds.occlusion_rects.push_back(rect); } } diff --git a/src/apps/desktop/page_annotation_bridge.cpp b/src/apps/desktop/page_annotation_bridge.cpp new file mode 100644 index 000000000..03a9ca846 --- /dev/null +++ b/src/apps/desktop/page_annotation_bridge.cpp @@ -0,0 +1,46 @@ +#include "page_annotation_bridge.hpp" +#include "agent_browser_host.hpp" +#include "web_host.hpp" + +#include + +namespace acecode::desktop { + +acecode::LifetimeToken install_page_annotation_bridge(WebHost& host, AgentBrowserHost& browser) { + acecode::LifetimeToken lifetime; + host.bind_async("aceDesktop_agentBrowserAnnotationCommand", + [browser = lifetime.ref(browser)]( + const std::string& req, WebHost::BindingReply reply) { + const auto args = nlohmann::json::parse(req, nullptr, false); + if (!args.is_array() || args.size() != 1 || !args[0].is_object() || + !args[0].contains("page_id") || !args[0]["page_id"].is_string() || + !args[0].contains("command") || !args[0]["command"].is_object()) { + reply("{\"ok\":false,\"error\":\"Invalid annotation request\"}"); + return; + } + const std::string page_id = args[0]["page_id"].get(); + const std::string command = args[0]["command"].dump(); + const bool delivered = browser.with([page_id, command, reply](AgentBrowserHost& current) { + current.annotation_command(page_id, command, reply); + }); + if (!delivered) reply("{\"ok\":false,\"error\":\"Browser closed\"}"); + }); + host.bind_async("aceDesktop_agentBrowserAnnotationScreenshot", + [browser = lifetime.ref(browser)]( + const std::string& req, WebHost::BindingReply reply) { + const auto args = nlohmann::json::parse(req, nullptr, false); + if (!args.is_array() || args.size() != 1 || !args[0].is_object() || + !args[0].contains("page_id") || !args[0]["page_id"].is_string()) { + reply("{\"ok\":false,\"error\":\"Invalid annotation screenshot request\"}"); + return; + } + const std::string page_id = args[0]["page_id"].get(); + const bool delivered = browser.with([page_id, reply](AgentBrowserHost& current) { + current.annotation_command(page_id, R"({"action":"screenshot"})", reply); + }); + if (!delivered) reply("{\"ok\":false,\"error\":\"Browser closed\"}"); + }); + return lifetime; +} + +} // namespace acecode::desktop diff --git a/src/apps/desktop/page_annotation_bridge.hpp b/src/apps/desktop/page_annotation_bridge.hpp new file mode 100644 index 000000000..85d76fd9b --- /dev/null +++ b/src/apps/desktop/page_annotation_bridge.hpp @@ -0,0 +1,13 @@ +#pragma once + +#include "utils/lifetime_token.hpp" + +namespace acecode::desktop { + +class WebHost; +class AgentBrowserHost; + +[[nodiscard]] acecode::LifetimeToken install_page_annotation_bridge( + WebHost& host, AgentBrowserHost& browser); + +} // namespace acecode::desktop diff --git a/src/apps/desktop/page_annotation_host_adapter.hpp b/src/apps/desktop/page_annotation_host_adapter.hpp new file mode 100644 index 000000000..181217074 --- /dev/null +++ b/src/apps/desktop/page_annotation_host_adapter.hpp @@ -0,0 +1,185 @@ +#pragma once + +#include "page_annotation_host_navigation.hpp" +#ifdef _WIN32 +#include "agent_browser_windows_helpers.hpp" +#endif +#ifdef __APPLE__ +#import +#import +#include "agent_browser_macos_helpers.hpp" +#endif + +namespace acecode::desktop { + +using AnnotationCompletion = std::function; + +template +bool annotation_retire(const std::shared_ptr& page) { + if (!page) return false; + page->annotations.requests.stop(); + page->annotations.suspend(); +#ifdef __APPLE__ + ++page->annotation_incarnation; +#endif + return true; +} + +#ifdef _WIN32 +template +auto annotation_event_page(Host& host, const std::string& id, ICoreWebView2* source) { + const auto page = host.find_page(id); + return page && !page->closing && page->webview.Get() == source ? page : nullptr; +} + +template +bool annotation_start_navigation(Host& host, const std::shared_ptr& page, + ICoreWebView2NavigationStartingEventArgs* args, const std::string& uri, std::uint64_t navigation_id) { + if (!normalize_agent_browser_url(uri, nullptr) || annotation_fragment_navigation(page->state.url, uri)) return true; + BOOL redirected = FALSE; + args->get_IsRedirected(&redirected); + const bool continuation = page->annotations.navigation.navigating() && + (navigation_id == page->current_navigation_id || redirected || page->annotation_certificate_retry); + page->annotation_certificate_retry = false; + if ((!page->annotations.navigation.blocked() && !host.reserve_annotation_pages({page}, nullptr)) || + !page->annotations.navigation.start(continuation)) { + args->put_Cancel(TRUE); + return false; + } + page->annotations.suspend(); + return true; +} +#endif + +template +bool annotation_reserve_pages(Host& host, const std::vector>& pages, + std::string* error, bool hold = false) { + const bool accepted = annotation_reserve(host, pages, [&host] { +#ifdef _WIN32 + return MessageBoxW(static_cast(host.parent_window), + L"Leave this page? Unsent annotations will be kept but cannot be sent after replacement.", + L"Page annotations", MB_YESNO | MB_DEFBUTTON2 | MB_ICONWARNING) == IDYES; +#elif defined(__APPLE__) + NSAlert* alert = [[NSAlert alloc] init]; + alert.messageText = @"Leave this page?"; + alert.informativeText = @"Unsent annotations will be kept but cannot be sent after replacement."; + [alert addButtonWithTitle:@"Stay"]; + [alert addButtonWithTitle:@"Leave"]; + const bool leave = [alert runModal] == NSAlertSecondButtonReturn; + [alert release]; + return leave; +#else + return false; +#endif + }, error); + if (accepted && !hold) for (const auto& page : pages) page->annotations.navigation.arm(); + return accepted; +} + +template +void annotation_evaluate(const std::shared_ptr& host, const std::shared_ptr& page, + std::uint64_t sequence, const std::string& script, AnnotationCompletion done) { + const auto pending = page->annotations.requests.add([done](nlohmann::json response) { + done(response.value("ok", false), response.value("result", nlohmann::json())); + }); + if (!pending) return; + const auto finish = [pending](bool ok, nlohmann::json result) { + pending->finish({{"ok", ok}, {"result", std::move(result)}}); + }; +#ifdef _WIN32 + host->evaluate_annotation(page, sequence, script, finish, + [pending] { return !pending->completed(); }); +#elif defined(__APPLE__) + const auto incarnation = page->annotation_incarnation; + const std::weak_ptr weak = host; + const std::weak_ptr weak_page = page; + host->evaluate_value(page, script, + [weak, weak_page, sequence, incarnation, finish](bool ok, nlohmann::json result, std::string) { + const auto current_host = weak.lock(); + const auto current = weak_page.lock(); + const bool accepted = ok && current_host && current && !current->closing && + current_host->find_page(current->id) == current && + current->annotation_incarnation == incarnation && current->annotations.sequence() == sequence; + finish(accepted, accepted ? std::move(result) : nlohmann::json()); + }); +#endif +} + +template +void annotation_dispatch(const std::shared_ptr& host, const std::string& page_id, + const std::string& command_json, std::function completion) { + const auto page = host ? host->find_page(page_id) : nullptr; + const auto command = nlohmann::json::parse(command_json, nullptr, false); + // 发送成功后的 cleanup(remove)在页面已经关闭时也要能落地:记录归会话, + // 页签没了不影响删除。其余动作要求页面还活着。 + const bool cleanup = command.is_object() && command.value("action", nlohmann::json()) == "remove"; + if (!page || page->closing || (!cleanup && (!page->webview || + page->state.content_state != kAgentBrowserContentStateLive))) { + completion(nlohmann::json{{"ok", false}, {"error", "Annotation page is unavailable"}}.dump()); + return; + } + if (command.is_object() && command.value("action", nlohmann::json()) == "screenshot") { + const auto pending = page->annotations.requests.add( + [completion](nlohmann::json response) { completion(response.dump()); }); + if (!pending) { + completion(nlohmann::json{{"ok", false}, {"error", "Annotation capture is already running"}}.dump()); + return; + } + host->capture_screenshot(page, {{"format", "png"}}, pending, "true"); + return; + } + const std::weak_ptr weak = host; + const std::weak_ptr weak_page = page; + host->annotation_poller.start([weak] { + poll_annotations(weak, [](const auto& current_host, const auto& current, auto sequence, + const std::string& script, AnnotationCompletion done) { + annotation_evaluate(current_host, current, sequence, script, std::move(done)); + }); + }); + const auto evaluate = [weak, weak_page](const std::string& script, AnnotationCompletion done) { + const auto current_host = weak.lock(); + const auto current = weak_page.lock(); + if (!current_host || !current || current->closing || current_host->find_page(current->id) != current) { + done(false, nullptr); + return; + } + annotation_evaluate(current_host, current, current->annotations.sequence(), script, std::move(done)); + }; + if (annotation_host_submission(page->annotations, page_id, command, completion, + [weak, weak_page](const std::string& serialized) { + const auto current_host = weak.lock(); + const auto current = weak_page.lock(); + if (current_host && current && !current->closing && current_host->find_page(current->id) == current) + current_host->update_page(current, [serialized](AgentBrowserState& state) { state.page_annotations_json = serialized; }); + }, [evaluate, document_id = page->annotations.document_id()](const std::vector& numbers) { + const auto expression = page_annotation_runtime_expression( + page_annotation_remove_pins_payload(document_id, numbers)); + evaluate(expression, [](bool, nlohmann::json) {}); + })) return; + std::string expression; + std::string error; + if (!page->annotations.prepare(page_id, command, expression, error)) { + completion(nlohmann::json{{"ok", false}, {"error", error}}.dump()); + return; + } + const auto sequence = page->annotations.sequence(); + evaluate(expression, [weak, weak_page, sequence, completion](bool ok, nlohmann::json result) { + annotation_host_result(weak, weak_page, sequence, completion, ok, result); + }); +} + +#ifdef __APPLE__ +template +bool annotation_allow_action(Host& host, const std::shared_ptr& page, WKNavigationAction* action) { + if (action.targetFrame && !action.targetFrame.mainFrame) return true; + if (annotation_fragment_navigation(page->state.url, agent_browser_macos::utf8_string(action.request.URL.absoluteString))) { + if (page->annotations.navigation.reserved() && page->annotations.navigation.armed()) page->annotations.navigation.finish(); + return true; + } + if (page->annotations.navigation.navigating()) return action.navigationType == WKNavigationTypeOther; + if (!page->annotations.navigation.reserved() && !annotation_reserve_pages(host, std::vector{page}, nullptr)) return false; + return page->annotations.navigation.armed(); +} +#endif + +} diff --git a/src/apps/desktop/page_annotation_host_navigation.hpp b/src/apps/desktop/page_annotation_host_navigation.hpp new file mode 100644 index 000000000..995117f50 --- /dev/null +++ b/src/apps/desktop/page_annotation_host_navigation.hpp @@ -0,0 +1,101 @@ +#pragma once + +#include "page_annotation_host_submission.hpp" +#include "page_annotation_poller.hpp" + +namespace acecode::desktop { + +inline bool annotation_fragment_navigation(const std::string& current, const std::string& next) { + return current != next && current.substr(0, current.find('#')) == next.substr(0, next.find('#')); +} + +template +bool annotation_reserve(Host& host, const std::vector>& pages, + Confirm confirm, std::string* error) { + if (reserve_annotation_transition(pages, [&host](const auto& page) { + return !page->closing && host.find_page(page->id) == page; + }, confirm)) return true; + if (error) *error = "Navigation cancelled or annotation submission is in progress"; + return false; +} + +inline bool annotation_replaces_document(const std::string& method) { + return method == "Page.navigate" || method == "Page.reload" || + method == "Page.navigateToHistoryEntry" || method == "Page.setDocumentContent"; +} + +template +auto annotation_store_pages(Host& host, const Key& key) { + std::vector> affected; + for (const auto& state : host.states()) { + const auto page = host.find_page(state.page_id); + if (page && !page->closing && page->webview && page->store == key) affected.push_back(page); + } + return affected; +} + +template +auto annotation_transition_tickets(const std::vector>& pages) { + std::vector, std::uint64_t>> tickets; + for (const auto& page : pages) tickets.emplace_back(page, page->annotations.navigation.ticket()); + return tickets; +} + +template +void annotation_reload_reserved(Host& host, + const std::vector, std::uint64_t>>& tickets, + const Key& key, bool ok, Reload reload) { + for (const auto& item : tickets) { + const auto& page = item.first; + if (page->closing || host.find_page(page->id) != page || + page->annotations.navigation.ticket() != item.second) continue; + if (ok) page->annotations.navigation.arm(); + if (!ok || !page->webview || page->store != key || !reload(page)) page->annotations.navigation.finish(); + } +} + +template +void annotation_proxy_transition(Host& host, const std::shared_ptr& page, + const std::string& method, const std::shared_ptr& pending, Dispatch dispatch) { + if (annotation_replaces_document(method) && !host.reserve_annotation_pages({page}, nullptr)) { + finish_proxy_call(pending, {{"ok", false}, {"page_id", page->id}, {"error", "Navigation cancelled"}}); + return; + } + const auto ticket = page->annotations.navigation.ticket(); + const auto weak = host.weak_from_this(); + const std::weak_ptr weak_page = page; + dispatch([pending, weak, weak_page, ticket, method](nlohmann::json response) { + const auto current_host = weak.lock(); + const auto current = weak_page.lock(); + if (current_host && current && current_host->find_page(current->id) == current && + current->annotations.navigation.ticket() == ticket && annotation_replaces_document(method) && + (!response.value("ok", false) || method == "Page.setDocumentContent")) current->annotations.navigation.finish(); + finish_proxy_call(pending, std::move(response)); + }); +} + +template +void poll_annotations(const std::weak_ptr& weak, Evaluate evaluate) { + const auto host = weak.lock(); + if (!host) return; + for (const auto& state : host->states()) { + const auto page = host->find_page(state.page_id); + if (page) page->annotations.requests.expire(); + if (!page || host->find_page(page->id) != page || page->closing || !page->webview || + state.content_state != kAgentBrowserContentStateLive || !page->annotations.pollable()) continue; + const auto expression = std::string(kPageAnnotationRuntime) + "(" + nlohmann::json{ + {"action", "read"}, {"document_id", page->annotations.document_id()}}.dump() + ")"; + const auto sequence = page->annotations.sequence(); + const auto poll = page->annotations.begin_poll(); + const std::weak_ptr weak_page = page; + evaluate(host, page, sequence, expression, + [weak, weak_page, sequence, poll](bool ok, nlohmann::json result) { + const auto current = weak_page.lock(); + if (!current || !current->annotations.finish_poll(poll) || !ok || + current->annotations.sequence() != sequence) return; + annotation_lifecycle(weak, weak_page)(result); + }); + } +} + +} diff --git a/src/apps/desktop/page_annotation_host_submission.hpp b/src/apps/desktop/page_annotation_host_submission.hpp new file mode 100644 index 000000000..468f1366f --- /dev/null +++ b/src/apps/desktop/page_annotation_host_submission.hpp @@ -0,0 +1,92 @@ +#pragma once + +#include "agent_browser_proxy_request.hpp" +#include "page_annotation_session.hpp" + +namespace acecode::desktop { + +using AnnotationEvaluation = std::function)>; +using AnnotationUpdate = std::function; +using AnnotationRemoved = std::function&)>; +// 页面状态回报(轮询 / 交互结果)→ 记录失效状态;返回 false 表示回报本身不可信。 +using AnnotationLifecycle = std::function; + +template +AnnotationLifecycle annotation_lifecycle(std::weak_ptr weak, std::weak_ptr weak_page) { + return [weak, weak_page](const nlohmann::json& result) { + const auto host = weak.lock(); + const auto page = weak_page.lock(); + if (!host || !page || page->closing || host->find_page(page->id) != page) return false; + const auto revision = page->annotations.revision(); + bool valid = false; + if (page->annotations.recover_document_loss(result)) { + valid = true; + } else if (!page->annotations.navigation.blocked()) { + valid = page->annotations.observe_lifecycle(result); + } + const auto snapshot = page->annotations.snapshot().dump(); + if (revision != page->annotations.revision()) { + host->update_page(page, [snapshot](AgentBrowserState& state) { state.page_annotations_json = snapshot; }); + } + return valid; + }; +} + +template +void annotation_host_result(const std::weak_ptr& weak, + const std::weak_ptr& weak_page, std::uint64_t sequence, + const std::function& completion, bool ok, + const nlohmann::json& result, std::string error = {}) { + const auto self = weak.lock(); + const auto current = weak_page.lock(); + if (!self || !current || current->closing || + self->find_page(current->id) != current || !ok || + !current->annotations.complete(sequence, result, error)) { + if (current) current->annotations.fail(sequence); + completion(nlohmann::json{{"ok", false}, {"error", error.empty() + ? "Annotation document changed or runtime failed" : error}}.dump()); + return; + } + const auto snapshot = current->annotations.snapshot(); + const auto serialized = snapshot.dump(); + self->update_page(current, [serialized](AgentBrowserState& state) { + state.page_annotations_json = serialized; + }); + completion(nlohmann::json{{"ok", true}, {"page_id", current->id}, + {"annotations", snapshot}}.dump()); +} + +// 待发集合的两个写入动作:发送成功后删记录、保存后补图。发送本身走普通消息 +// 提交(Q35),原生侧不再有 capture / validate / acknowledge / release 租约。 +inline bool annotation_host_submission(PageAnnotationSession& session, + const std::string& page_id, const nlohmann::json& command, + const std::function& completion, AnnotationUpdate update, + AnnotationRemoved removed = {}) { + if (!command.is_object() || !command.contains("action") || + (command["action"] != "remove" && command["action"] != "attach_screenshot")) return false; + std::string error; + std::vector removed_numbers; + if (!session.submission(command, error, &removed_numbers)) { + completion(nlohmann::json{{"ok", false}, {"error", error}}.dump()); + return true; + } + if (removed && !removed_numbers.empty()) removed(removed_numbers); + const auto snapshot = session.snapshot(); + update(snapshot.dump()); + completion(nlohmann::json{{"ok", true}, {"page_id", page_id}, + {"annotations", snapshot}}.dump()); + return true; +} + +inline browser_capture::Validate annotation_capture_validation( + const std::string& expression, AnnotationEvaluation evaluate) { + if (expression.empty()) return {}; + return [expression, evaluate](std::function done) { + evaluate(expression, [done](bool ok, nlohmann::json value) { + done(ok && value.is_object() && value.contains("valid") && value["valid"] == true); + }); + }; +} + +} diff --git a/src/apps/desktop/page_annotation_navigation.hpp b/src/apps/desktop/page_annotation_navigation.hpp new file mode 100644 index 000000000..8e206f95c --- /dev/null +++ b/src/apps/desktop/page_annotation_navigation.hpp @@ -0,0 +1,76 @@ +#pragma once + +#include +#include +#include +#include + +namespace acecode::desktop { + +class AnnotationNavigationGuard { +public: + bool blocked() const { return reserved_ || navigating_; } + bool reserved() const { return reserved_; } + bool navigating() const { return navigating_; } + bool armed() const { return armed_; } + bool arm() { if (!reserved_) return false; armed_ = true; return true; } + std::uint64_t ticket() const { return ticket_; } + bool reserve() { + if (blocked()) return false; + reserved_ = true; + ++ticket_; + return true; + } + bool start(bool continuation = false) { + if (navigating_) return continuation; + if (!reserved_ || !armed_) return false; + reserved_ = false; + armed_ = false; + navigating_ = true; + return true; + } + void finish() { reserved_ = false; armed_ = false; navigating_ = false; ++ticket_; } +private: + bool reserved_ = false; + bool navigating_ = false; + bool armed_ = false; + std::uint64_t ticket_ = 0; +}; + +template +bool reserve_annotation_transition(const std::vector>& pages, + Current current, Confirm confirm) { + std::vector> reserved; + std::vector revisions; + std::vector sequences; + std::vector tickets; + const auto rollback = [&] { + for (std::size_t index = 0; index < reserved.size(); ++index) { + if (reserved[index]->annotations.navigation.ticket() == tickets[index]) + reserved[index]->annotations.navigation.finish(); + } + }; + bool work = false; + for (const auto& page : pages) { + if (!page || !current(page) || !page->annotations.navigation.reserve()) { + rollback(); + return false; + } + reserved.push_back(page); + revisions.push_back(page->annotations.revision()); + sequences.push_back(page->annotations.sequence()); + tickets.push_back(page->annotations.navigation.ticket()); + work = work || page->annotations.has_unsent_work(); + } + bool accepted = !work || confirm(); + for (std::size_t index = 0; index < reserved.size(); ++index) { + accepted = accepted && current(reserved[index]) && + revisions[index] == reserved[index]->annotations.revision() && + sequences[index] == reserved[index]->annotations.sequence() && + tickets[index] == reserved[index]->annotations.navigation.ticket(); + } + if (!accepted) rollback(); + return accepted; +} + +} diff --git a/src/apps/desktop/page_annotation_poller.hpp b/src/apps/desktop/page_annotation_poller.hpp new file mode 100644 index 000000000..98bece41b --- /dev/null +++ b/src/apps/desktop/page_annotation_poller.hpp @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include +#ifdef _WIN32 +#include +#include +#elif defined(__APPLE__) +#include +#endif + +namespace acecode::desktop { + +class AnnotationPoller { + struct State { std::mutex mutex; bool active = true; std::function tick; }; + std::shared_ptr state_; + static bool invoke(const std::shared_ptr& state) { + std::function tick; + { + std::lock_guard lock(state->mutex); + if (!state->active) return false; + tick = state->tick; + } + if (tick) tick(); + std::lock_guard lock(state->mutex); + return state->active; + } +#ifdef _WIN32 + UINT_PTR timer_ = 0; + inline static std::mutex timers_mutex_; + static auto& timers() { + static std::unordered_map> entries; + return entries; + } +#elif defined(__APPLE__) + static void schedule(const std::shared_ptr& state) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 250 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ + if (invoke(state)) schedule(state); + }); + } +#endif +public: + AnnotationPoller() = default; + AnnotationPoller(const AnnotationPoller&) = delete; + AnnotationPoller& operator=(const AnnotationPoller&) = delete; + ~AnnotationPoller() { stop(); } + void stop() { + std::function retired; + if (state_) { + std::lock_guard lock(state_->mutex); + state_->active = false; + retired = std::move(state_->tick); + } +#ifdef _WIN32 + if (timer_) { + KillTimer(nullptr, timer_); + std::lock_guard lock(timers_mutex_); + timers().erase(timer_); + timer_ = 0; + } +#endif + state_.reset(); + } + void start(std::function tick) { + if (state_) return; + state_ = std::make_shared(); + state_->tick = std::move(tick); +#ifdef _WIN32 + timer_ = SetTimer(nullptr, 0, 250, [](HWND, UINT, UINT_PTR timer, DWORD) { + std::shared_ptr state; + { + std::lock_guard lock(timers_mutex_); + const auto found = timers().find(timer); + if (found != timers().end()) state = found->second.lock(); + } + if (state) invoke(state); + }); + if (timer_) { + std::lock_guard lock(timers_mutex_); + timers()[timer_] = state_; + } else stop(); +#elif defined(__APPLE__) + schedule(state_); +#endif + } +}; + +} diff --git a/src/apps/desktop/page_annotation_requests.hpp b/src/apps/desktop/page_annotation_requests.hpp new file mode 100644 index 000000000..380d9c620 --- /dev/null +++ b/src/apps/desktop/page_annotation_requests.hpp @@ -0,0 +1,93 @@ +#pragma once + +#include "agent_browser_proxy_request.hpp" + +#include + +namespace acecode::desktop { + +class AnnotationRequests { +public: + using Clock = std::chrono::steady_clock; + AnnotationRequests() = default; + AnnotationRequests(const AnnotationRequests&) = delete; + AnnotationRequests& operator=(const AnnotationRequests&) = delete; + ~AnnotationRequests() { stop(); } + + std::shared_ptr add(std::function completion, + Clock::time_point now = Clock::now()) { + expire(now); + if (stopped_ || entries_.size() >= 32) { + completion(failure(stopped_ ? "Annotation page closed" : "Too many annotation requests")); + return {}; + } + const auto retirement = std::make_shared(); + auto pending = std::make_shared( + [retirement, completion = std::move(completion)](nlohmann::json response) { + retirement->retire(); + completion(std::move(response)); + }); + entries_.push_back({pending, now + std::chrono::seconds(15), retirement}); + return pending; + } + + browser_capture::RegisterCleanup cleanup(const std::shared_ptr& pending) const { + for (const auto& entry : entries_) { + if (entry.pending == pending) return [retirement = entry.retirement](std::function cleanup) { + retirement->install(std::move(cleanup)); + }; + } + return {}; + } + + void expire(Clock::time_point now = Clock::now()) { + std::vector> expired; + entries_.erase(std::remove_if(entries_.begin(), entries_.end(), [&](const auto& entry) { + if (entry.pending->completed()) return true; + if (entry.deadline > now) return false; + expired.push_back(entry.pending); + return true; + }), entries_.end()); + for (const auto& pending : expired) pending->finish(failure("Annotation request timed out")); + } + + void cancel(const std::string& reason) { + auto entries = std::move(entries_); + entries_.clear(); + for (const auto& entry : entries) entry.pending->finish(failure(reason)); + } + + void stop() { stopped_ = true; cancel("Annotation page closed"); } + void restart() { stopped_ = false; } + +private: + class Retirement { + public: + void install(std::function cleanup) { + if (!cleanup) return; + if (auto previous = std::move(cleanup_)) previous(); + if (retired_) cleanup(); + else cleanup_ = std::move(cleanup); + } + void retire() { + retired_ = true; + if (auto cleanup = std::move(cleanup_)) cleanup(); + } + private: + std::function cleanup_; + bool retired_ = false; + }; + struct Entry { + std::shared_ptr pending; + Clock::time_point deadline; + // Shared by the registry, pending completion and resource registration. + std::shared_ptr retirement; + }; + static nlohmann::json failure(const std::string& reason) { + return {{"ok", false}, {"error", reason}, {"recoverable", true}}; + } + std::vector entries_; + bool stopped_ = false; +}; + +} diff --git a/src/apps/desktop/page_annotation_runtime.hpp b/src/apps/desktop/page_annotation_runtime.hpp new file mode 100644 index 000000000..a1ac4f81a --- /dev/null +++ b/src/apps/desktop/page_annotation_runtime.hpp @@ -0,0 +1,518 @@ +#pragma once + +namespace acecode::desktop { + +inline constexpr const char kPageAnnotationRuntime[] = R"ACEANNOTATION( +((command, createTextPreview, createStyles) => { + const key = '__acecodePageAnnotationsV1'; + let runtime = globalThis[key]; + if (runtime && command.action === 'start' && runtime.document_id !== command.document_id) { + runtime.dispose(); + runtime = null; + } + if (!runtime && command.action === 'start') { + const documentId = command.document_id; + const rootDocument = document; + const rootElement = document.documentElement; + let active = false; + let selected = null; + let selectedId = ''; + let open = false; + let selectionMode = null; + let region = null; + let drag = null; + let hovered = null; + let modalSuspended = false; + const targets = []; + let sequence = 0; + const ids = new WeakMap(); + const pins = []; + const draftChains = new Map(); + const ancestors = target => { + const chain = []; + for (let node = target; node; node = node.parentNode || node.host) chain.push(node); + return chain; + }; + const observed = new WeakSet(); + const textPreview = createTextPreview(); + const styles = createStyles(rootDocument); + let original = false; + let markersHidden = false; + const host = document.createElement('div'); + host.style.cssText = 'all:initial;position:fixed;inset:0;pointer-events:none;z-index:2147483647'; + host.setAttribute('data-ace-annotation-overlay', ''); + const shadow = host.attachShadow({mode:'closed'}); + const outline = document.createElement('div'); + outline.style.cssText = 'position:fixed;border:2px solid Highlight;box-sizing:border-box;pointer-events:none;display:none'; + const hoverOutline = document.createElement('div'); + hoverOutline.style.cssText = 'position:fixed;border:1px solid Highlight;border-radius:2px;box-sizing:border-box;pointer-events:none;display:none'; + hoverOutline.setAttribute('data-ace-annotation-hover', ''); + const infoCard = document.createElement('div'); + infoCard.style.cssText = 'position:fixed;pointer-events:none;display:none;box-sizing:border-box;min-width:168px;max-width:260px;padding:8px 10px;border-radius:10px;background:#fff;color:#1f2328;font:12px/1.5 ui-sans-serif,system-ui,sans-serif;border:1px solid rgba(0,0,0,.08);box-shadow:0 8px 24px rgba(0,0,0,.18)'; + infoCard.setAttribute('data-ace-annotation-info', ''); + shadow.append(outline, hoverOutline, infoCard); + const regionOutline = document.createElement('div'); + regionOutline.style.cssText = 'position:fixed;border:2px dashed Highlight;box-sizing:border-box;pointer-events:none;display:none'; + shadow.append(regionOutline); + document.documentElement.append(host); + const connected = target => target?.isConnected && target.ownerDocument === rootDocument; + const rect = target => { + const bounds = target.getBoundingClientRect(); + return {x:bounds.x, y:bounds.y, width:bounds.width, height:bounds.height}; + }; + const pageBackground = () => { + for (const node of [document.body, document.documentElement]) { + if (!node) continue; + const color = getComputedStyle(node).backgroundColor; + if (color && color !== 'transparent' && color !== 'rgba(0, 0, 0, 0)') return color; + } + return '#ffffff'; + }; + const pagePoint = event => ({x:Math.max(0, event.clientX + scrollX), y:Math.max(0, event.clientY + scrollY)}); + const regionRect = (first, last) => ({x:Math.min(first.x, last.x), y:Math.min(first.y, last.y), + width:Math.abs(last.x - first.x), height:Math.abs(last.y - first.y)}); + const viewportRegion = bounds => ({...bounds, x:bounds.x - scrollX, y:bounds.y - scrollY}); + const place = (marker, bounds) => Object.assign(marker.style, + {left:`${bounds.x}px`, top:`${bounds.y}px`, width:`${bounds.width}px`, height:`${bounds.height}px`}); + const clearDraft = () => { + targets.length = 0; + draftChains.clear(); + selected = null; + selectedId = ''; + region = null; + selectionMode = null; + drag = null; + hovered = null; + open = false; + }; + const clearPins = () => { + for (const pin of pins) { + pin.marker.remove(); + pin.outline?.remove(); + } + pins.length = 0; + }; + const summary = target => ({id:ids.get(target), tag:target.localName.slice(0, 64), + text:(target.innerText || target.textContent || '').slice(0, 512), + locator:target.localName + (target.id ? '#' + target.id.slice(0, 128) : ''), bounds:rect(target), + text_preview:textPreview.describe(target, ids.get(target)), + style_preview:styles.describe(target, ids.get(target))}); + const hexColor = value => { + const match = /^rgba?\(([^)]+)\)$/i.exec(String(value || '')); + if (!match) return String(value || ''); + const parts = match[1].split(',').map(part => Number(part.trim())); + if (parts.length < 3 || parts.slice(0, 3).some(Number.isNaN)) return String(value || ''); + if (parts.length > 3 && parts[3] === 0) return 'transparent'; + return '#' + parts.slice(0, 3).map(part => + Math.max(0, Math.min(255, Math.round(part))).toString(16).padStart(2, '0')).join(''); + }; + const infoLine = (label, value, swatch) => { + const row = document.createElement('div'); + row.style.cssText = 'display:grid;grid-template-columns:36px minmax(0,1fr);align-items:center;gap:8px;min-height:18px'; + const name = document.createElement('span'); + name.textContent = label; + name.style.cssText = 'color:#8b949e;font-size:11px'; + const content = document.createElement('span'); + content.style.cssText = 'display:flex;align-items:center;gap:6px;min-width:0;overflow:hidden;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;color:#57606a'; + if (swatch) { + const dot = document.createElement('span'); + dot.style.cssText = `flex:0 0 auto;width:10px;height:10px;border-radius:3px;border:1px solid rgba(0,0,0,.12);background:${swatch}`; + content.append(dot); + } + const text = document.createElement('span'); + text.textContent = value; + text.style.cssText = 'min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap'; + content.append(text); + row.append(name, content); + return row; + }; + const renderInfo = target => { + const computedStyle = getComputedStyle(target); + const bounds = rect(target); + infoCard.replaceChildren(); + const head = document.createElement('div'); + head.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:5px'; + const tag = document.createElement('span'); + tag.textContent = target.localName.slice(0, 64); + tag.style.cssText = 'font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;font-weight:600;color:#1f2328'; + const size = document.createElement('span'); + size.textContent = `${Math.round(bounds.width)} x ${Math.round(bounds.height)}`; + size.style.cssText = 'font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;color:#8b949e'; + head.append(tag, size); + infoCard.append(head, + infoLine('颜色', hexColor(computedStyle.color), computedStyle.color), + infoLine('字体', `${computedStyle.fontSize} ${computedStyle.fontFamily}`, null)); + }; +)ACEANNOTATION" R"ACEANNOTATION( + const layout = () => { + const visible = !modalSuspended && active && connected(selected) && selectionMode !== 'region'; + outline.style.display = visible ? 'block' : 'none'; + if (visible) { + const bounds = rect(selected); + Object.assign(outline.style, {left:`${bounds.x}px`, top:`${bounds.y}px`, width:`${bounds.width}px`, height:`${bounds.height}px`}); + } + const hovering = !modalSuspended && active && connected(hovered) && !drag && selectionMode !== 'region' && + (!open || selectionMode === 'element'); + hoverOutline.style.display = hovering ? 'block' : 'none'; + infoCard.style.display = hovering ? 'block' : 'none'; + if (hovering) { + const bounds = rect(hovered); + Object.assign(hoverOutline.style, {left:`${bounds.x}px`, top:`${bounds.y}px`, width:`${bounds.width}px`, height:`${bounds.height}px`}); + const cardWidth = infoCard.offsetWidth; + const cardHeight = infoCard.offsetHeight; + infoCard.style.left = `${Math.max(8, Math.min(innerWidth - cardWidth - 8, bounds.x))}px`; + const below = bounds.y + bounds.height + 6; + infoCard.style.top = `${below + cardHeight <= innerHeight - 8 + ? below : Math.max(8, bounds.y - cardHeight - 6)}px`; + } + const displayedRegion = drag ? regionRect(drag.start, drag.end) : region; + regionOutline.style.display = !modalSuspended && active && displayedRegion ? 'block' : 'none'; + if (displayedRegion) place(regionOutline, viewportRegion(displayedRegion)); + const markersVisible = !markersHidden && !original; + for (const pin of pins) { + const visiblePin = markersVisible && !pin.invalid && pin.targets.every(connected); + pin.marker.style.display = visiblePin ? 'block' : 'none'; + if (pin.outline) pin.outline.style.display = visiblePin ? 'block' : 'none'; + if (pin.invalid || !pin.targets.every(connected)) continue; + const bounds = pin.region ? viewportRegion(pin.region) : rect(pin.targets[0]); + pin.marker.style.left = `${bounds.x}px`; + pin.marker.style.top = `${bounds.y}px`; + if (pin.outline) place(pin.outline, bounds); + } + }; + const lifecycle = () => ({document_id:documentId, + invalid_numbers:pins.filter(pin => pin.invalid).map(pin => pin.number)}); + const snapshot = () => { + layout(); + const target = connected(selected) ? summary(selected) : null; + return {...lifecycle(), active, popup:!!(target || region) && open, target, + targets:targets.map(summary), region, selection_mode:selectionMode, original, + markers_hidden:markersHidden, modal_suspended:modalSuspended, + differences:[...textPreview.differences(), ...styles.differences()], + page_background:pageBackground(), + viewport:{width:innerWidth, height:innerHeight, scroll_x:scrollX, scroll_y:scrollY}}; + }; + const select = event => { + if (!active || modalSuspended || !event.isTrusted || event.composedPath().includes(host)) return; + if (event.button !== 0) return; + event.preventDefault(); + event.stopImmediatePropagation(); + if (open && selectionMode !== 'element') { + textPreview.cancel(); + styles.cancel(); + clearDraft(); + layout(); + return; + } + const target = event.composedPath().find(node => node?.nodeType === 1); + if (!connected(target)) return; + if (!targets.includes(target) && targets.length >= 64) return; + if (!open) targets.length = 0; + if (!targets.includes(target)) { + targets.push(target); + draftChains.set(target, ancestors(target)); + observe(target); + } + selected = target; + if (!ids.has(target)) ids.set(target, `target-${++sequence}`); + selectedId = ids.get(target); + styles.select(target, selectedId); + selectionMode = null; + open = true; + layout(); + }; + const pointerDown = event => { + if (selectionMode !== 'region') { suppress(event); return; } + if (!active || modalSuspended || !event.isTrusted || event.button !== 0 || event.composedPath().includes(host)) return; + event.preventDefault(); + event.stopImmediatePropagation(); + drag = {start:pagePoint(event), end:pagePoint(event), pointerId:event.pointerId}; + host.setPointerCapture?.(event.pointerId); + layout(); + }; + const pointerMove = event => { + if (drag) { + if (!event.isTrusted || event.pointerId !== drag.pointerId) return; + event.preventDefault(); + event.stopImmediatePropagation(); + drag.end = pagePoint(event); + layout(); + return; + } + if (!active || modalSuspended || !event.isTrusted || drag || selectionMode === 'region' || + (open && selectionMode !== 'element')) return; + const path = event.composedPath?.() || []; + if (path.includes(host)) return; + const target = path.find(node => node?.nodeType === 1); + const next = target && connected(target) ? target : null; + if (next === hovered) return; + hovered = next; + if (hovered) renderInfo(hovered); + layout(); + }; + const pointerUp = event => { + if (!drag || !event.isTrusted || event.pointerId !== drag.pointerId) return; + event.preventDefault(); + event.stopImmediatePropagation(); + const next = regionRect(drag.start, pagePoint(event)); + drag = null; + if (next.width > 0 && next.height > 0) { + if (!open) { + targets.length = 0; + draftChains.clear(); + } + region = next; + selected = null; + selectedId = ''; + selectionMode = null; + open = true; + } + layout(); + }; + const pointerCancel = event => { + if (!drag || !event.isTrusted || event.pointerId !== drag.pointerId) return; + drag = null; + layout(); + }; + const suppress = event => { + if (active && event.isTrusted && !event.composedPath().includes(host)) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + }; + // The hover card follows the element under the pointer, so it has to die the + // moment the pointer is no longer over the page. Pointer moves inside the + // document already retarget the card, but leaving the webview (onto the app + // chrome, another window, or off-screen) fires no further pointermove and + // used to leave the last card pinned over the page. + const dropHover = () => { + if (!hovered) return; + hovered = null; + layout(); + }; + const pointerOut = event => { + if (event.relatedTarget) return; + dropHover(); + }; + const escape = event => { + if (!active || modalSuspended || !event.isTrusted || event.key !== 'Escape') return; + event.preventDefault(); + event.stopImmediatePropagation(); + if (selectionMode) { + selectionMode = null; + drag = null; + layout(); + return; + } + active = false; + textPreview.cancel(); + styles.cancel(); + clearDraft(); + layout(); + }; + document.addEventListener('pointerdown', pointerDown, true); + document.addEventListener('pointermove', pointerMove, true); + document.addEventListener('pointerup', pointerUp, true); + document.addEventListener('pointercancel', pointerCancel, true); + document.addEventListener('mousedown', suppress, true); + document.addEventListener('click', select, true); + document.addEventListener('keydown', escape, true); + document.addEventListener('pointerout', pointerOut, true); + globalThis.addEventListener('blur', dropHover); + globalThis.addEventListener('scroll', layout, true); + globalThis.addEventListener('resize', layout); + const removed = (target, chain, records) => !connected(target) || records.some(record => + Array.from(record.removedNodes || []).some(node => node === target || chain.includes(node) || node.contains?.(target))); +)ACEANNOTATION" R"ACEANNOTATION( + const inspect = (records = []) => { + const invalidIds = new Set(); + for (const pin of pins) { + if (!pin.invalid && pin.targets.some((target, index) => removed(target, pin.chains[index], records))) { + pin.invalid = true; + for (const target of pin.targets) invalidIds.add(ids.get(target)); + } + } + if (targets.some(target => removed(target, draftChains.get(target) || ancestors(target), records))) { + textPreview.cancel(); + styles.cancel(); + clearDraft(); + } + if (invalidIds.size) { + textPreview.invalidate?.(invalidIds); + styles.invalidate?.(invalidIds); + } + layout(); + }; + const mutations = typeof MutationObserver === 'function' ? new MutationObserver(inspect) : null; + const observe = target => { + for (const node of ancestors(target)) { + const root = node.getRootNode?.(); + if (root && !observed.has(root)) { + observed.add(root); + mutations?.observe(root, {subtree:true, childList:true}); + } + } + }; + mutations?.observe(rootDocument, {subtree:true, childList:true}); + const sizes = typeof ResizeObserver === 'function' ? new ResizeObserver(layout) : null; + sizes?.observe(document.documentElement); + runtime = Object.freeze({document_id:documentId, dispose() { + textPreview.dispose(); + styles.dispose(); + mutations?.disconnect(); + sizes?.disconnect(); + document.removeEventListener('pointerdown', pointerDown, true); + document.removeEventListener('pointermove', pointerMove, true); + document.removeEventListener('pointerup', pointerUp, true); + document.removeEventListener('pointercancel', pointerCancel, true); + document.removeEventListener('mousedown', suppress, true); + document.removeEventListener('click', select, true); + document.removeEventListener('keydown', escape, true); + document.removeEventListener('pointerout', pointerOut, true); + globalThis.removeEventListener('blur', dropHover); + globalThis.removeEventListener('scroll', layout, true); + globalThis.removeEventListener('resize', layout); + host.remove(); + }, run(next) { + if (document !== rootDocument || next.document_id !== documentId) return {error:'stale_document'}; + if (document.documentElement !== rootElement) { + runtime.dispose(); + return {error:'replaced_document'}; + } + inspect(mutations?.takeRecords?.() || []); + switch (next.action) { + case 'start': active = true; markersHidden = false; modalSuspended = false; hovered = null; break; + case 'read': break; + case 'set_modal_suspended': + modalSuspended = next.enabled === true; + if (modalSuspended) hovered = null; + break; + case 'exit': + textPreview.cancel(); + styles.cancel(); + active = false; + markersHidden = false; + modalSuspended = false; + clearDraft(); + break; + case 'cancel': textPreview.cancel(); styles.cancel(); clearDraft(); break; + case 'hide_markers': + markersHidden = next.enabled === true; + break; + case 'discard': + textPreview.discardAll(); + styles.discardAll(); + clearPins(); + clearDraft(); + original = false; + markersHidden = false; + modalSuspended = false; + textPreview.setOriginal(false); + styles.setOriginal(false); + break; + case 'remove_pins': { + const released = new Set(Array.isArray(next.numbers) ? next.numbers : []); + for (let index = pins.length - 1; index >= 0; index -= 1) { + if (!released.has(pins[index].number)) continue; + pins[index].marker.remove(); + pins[index].outline?.remove(); + pins.splice(index, 1); + } + break; + } + case 'original': original = next.enabled; textPreview.setOriginal(original); styles.setOriginal(original); break; + case 'preview_style': { + if (!active || !open || selectionMode || !connected(selected) || selectedId !== next.target_id) return {error:'stale_target'}; + try { styles.preview(selected, selectedId, next.styles, next.ratio_lock); } + catch (error) { return {error:String(error.message)}; } + break; + } + case 'preview_text': { + if (!active || !open || selectionMode || !connected(selected) || selectedId !== next.target_id) return {error:'stale_target'}; + const result = textPreview.preview(selected, selectedId, next.text); + if (result.error) return result; + break; + } + case 'add_target': + case 'add_region': + if (!active || selectionMode) return {error:'stale_target'}; + selectionMode = next.action === 'add_target' ? 'element' : 'region'; + break; + case 'select_target': { + const target = targets.find(item => ids.get(item) === next.target_id); + if (!active || !open || selectionMode || !connected(target)) return {error:'stale_target'}; + selected = target; + selectedId = ids.get(target); + styles.select(target, selectedId); + break; + } + case 'select_region': + if (!active || !open || selectionMode || !region) return {error:'stale_target'}; + selected = null; + selectedId = ''; + break; + case 'edit_record': { + // 从待发卡片点铅笔回到页面(#217):按保存时记下的 locator 找回元素, + // 重新进入批注态并把草稿切换成这一条。窗口内的重放(#216 的 replayable) + // 以后可以复用这条路径,所以只做「定位 + 选中」,不碰描述。 + const locator = typeof next.locator === 'string' ? next.locator : ''; + if (!locator || locator.length > 2048 || selectionMode) return {error:'stale_target'}; + let element = null; + try { element = document.querySelector(locator); } catch { element = null; } + if (!connected(element)) return {error:'stale_target'}; + active = true; + markersHidden = false; + modalSuspended = false; + targets.length = 0; + targets.push(element); + draftChains.set(element, ancestors(element)); + observe(element); + region = null; + selected = element; + if (!ids.has(element)) ids.set(element, `target-${++sequence}`); + selectedId = ids.get(element); + styles.select(element, selectedId); + open = true; + layout(); + break; + } + case 'save': { + if (!active || !open || selectionMode || !targets.every(connected) || + (!selected && !region) || (selected ? selectedId : null) !== next.target_id || + JSON.stringify(targets.map(target => ids.get(target))) !== JSON.stringify(next.target_ids) || + (region ? !next.region || ['x','y','width','height'].some(field => region[field] !== next.region[field]) + : next.region !== null)) return {error:'stale_target'}; + if (original) return {error:'original_view_active'}; + const result = textPreview.save(); + if (result.error) return result; + const differences = [...result.differences, ...styles.save()]; + const marker = document.createElement('span'); + marker.textContent = String(next.number); + marker.setAttribute('data-ace-annotation-pin', String(next.number)); + marker.style.cssText = 'position:fixed;pointer-events:none;border-radius:12px;padding:2px 6px;background:Highlight;color:HighlightText'; + shadow.append(marker); + let savedOutline = null; + if (region) { + savedOutline = document.createElement('div'); + savedOutline.setAttribute('data-ace-annotation-pin-outline', String(next.number)); + savedOutline.style.cssText = regionOutline.style.cssText; + savedOutline.style.display = 'block'; + shadow.append(savedOutline); + } + for (const target of targets) observe(target); + pins.push({number:next.number, targets:[...targets], chains:targets.map(ancestors), region, marker, outline:savedOutline, invalid:false}); + clearDraft(); + return {...snapshot(), differences}; + } + default: return {error:'unsupported_action'}; + } + return snapshot(); + }}); + Object.defineProperty(globalThis, key, {value:runtime, configurable:true}); + } + if (!runtime) return {error:'stale_document'}; + return runtime.run(command); +}) +)ACEANNOTATION"; + +} // namespace acecode::desktop diff --git a/src/apps/desktop/page_annotation_session.hpp b/src/apps/desktop/page_annotation_session.hpp new file mode 100644 index 000000000..9aae6ae25 --- /dev/null +++ b/src/apps/desktop/page_annotation_session.hpp @@ -0,0 +1,679 @@ +#pragma once + +#include "page_annotation_runtime.hpp" +#include "page_annotation_text_runtime.hpp" +#include "page_annotation_targets.hpp" +#include "page_annotation_style_runtime.hpp" +#include "page_annotation_submission.hpp" +#include "page_annotation_navigation.hpp" +#include "page_annotation_requests.hpp" +#include "session_annotation_store.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace acecode::desktop { + +inline std::string page_annotation_runtime_expression(const nlohmann::json& payload) { + return std::string(kPageAnnotationRuntime) + "(" + payload.dump() + "," + + kPageAnnotationTextRuntime + "," + kPageAnnotationStyleRuntime + ")"; +} + +inline nlohmann::json page_annotation_remove_pins_payload( + const std::string& document_id, const std::vector& numbers) { + return {{"action", "remove_pins"}, {"document_id", document_id}, {"numbers", numbers}}; +} + +class PageAnnotationSession { +public: + using Json = nlohmann::json; + + // 记录归属会话(Q33),页签只转发。同一会话的所有页签共享一个 store; + // 单页签场景(测试、未绑定会话的旧路径)允许自建一个。 + explicit PageAnnotationSession(std::shared_ptr store = + std::make_shared()) + : store_(std::move(store)) {} + + ~PageAnnotationSession() { requests.stop(); } + + const std::shared_ptr& store() const { return store_; } + + // 同一会话的页签共享一个 store(Q33)。宿主在建页时注入;不注入则自建一个, + // 单页签场景(测试、旧路径)行为与之前一致。 + void share_store(std::shared_ptr store) { + if (store) store_ = std::move(store); + } + + const std::string& document_id() const { return document_id_; } + AnnotationNavigationGuard navigation; + AnnotationRequests requests; + std::uint64_t revision() const { return revision_; } + bool has_unsent_work() const { + const auto& records = store_->records(page_id_); + return !targets_.empty() || !region_.is_null() || !selection_mode_.is_null() || busy_ || + std::any_of(records.begin(), records.end(), [](const auto& record) { + return record["status"] != "sent"; + }); + } + + bool observe_lifecycle(const Json& result) { + if (!result.is_object() || result.value("document_id", Json()) != document_id_) return false; + if (!result.contains("invalid_numbers")) return true; + const auto& numbers = result["invalid_numbers"]; + if (!numbers.is_array()) return false; + if (numbers.empty()) return true; + auto& records = store_->mutable_records(page_id_); + if (numbers.size() > records.size()) return false; + Json matched = Json::array(); + for (const auto& number : numbers) { + if (!number.is_number_unsigned() && !number.is_number_integer()) return false; + const auto found = std::find_if(records.begin(), records.end(), [&](const auto& record) { + return record["document_id"] == document_id_ && record["number"] == number; + }); + if (found == records.end() || std::find(matched.begin(), matched.end(), number) != matched.end()) return false; + matched.push_back(number); + } + bool changed = false; + for (auto& record : records) { + if (record["document_id"] == document_id_ && record["valid"] == true && + std::find(matched.begin(), matched.end(), record["number"]) != matched.end()) { + record["valid"] = false; + record["invalid_reason"] = "target_removed"; + changed = true; + } + } + if (changed) ++revision_; + return true; + } + + Json snapshot() const { + const auto& records = store_->records(page_id_); + const auto pending_count = std::count_if(records.begin(), records.end(), + [](const auto& record) { return record["status"] != "sent"; }); + return {{"document_id", document_id_}, {"active", active_}, + {"popup", popup_}, {"target", target_}, {"targets", targets_}, {"region", region_}, + {"selection_mode", selection_mode_}, {"viewport", viewport_}, {"records", records}, + {"page_shot", store_->page_shot(page_id_)}, + {"pending_count", pending_count}, {"original", original_}, {"differences", differences_}, + {"page_background", page_background_}, {"markers_hidden", markers_hidden_}, + {"modal_suspended", modal_suspended_}, {"draft_description", draft_description_}, + {"editing_record_id", editing_record_id_}, + {"revision", revision_}}; + } + + bool submission(const Json& command, std::string& error, + std::vector* removed_numbers = nullptr) { + if (!command.is_object() || command.dump().size() > 262144 || + !command.contains("action") || !command["action"].is_string() || + !command.contains("document_id") || !command["document_id"].is_string()) { + error = "Invalid annotation submission"; + return false; + } + // 发送成功后按 id 删记录,不校验文档代与有效性:已发出去的记录不该 + // 因为「发送这一刻文档刚好换了」留在待发集合里复活。 + const bool remove = command["action"] == "remove"; + // 保存后异步补图:把裁剪好的缩略图挂到记录上、整屏图挂到页签上。 + const bool attach = command["action"] == "attach_screenshot"; + if (!remove && !attach) { + error = "Invalid submission action"; + return false; + } + for (const auto& field : command.items()) { + if (field.key() != "action" && field.key() != "document_id" && + field.key() != "record_ids" && + !(attach && (field.key() == "record_id" || field.key() == "thumbnail" || + field.key() == "page_shot"))) { + error = "Unsupported submission field"; + return false; + } + } + if (attach) { + // 图是保存时截的(D2/D10),发送阶段不再捕获。空串表示该条无图 + // (目标不在视口内 / 捕获失败),待发卡片退化为标签 + 文本片段。 + constexpr std::size_t kThumbnailLimit = 512 * 1024; + constexpr std::size_t kPageShotLimit = 4 * 1024 * 1024; + const auto valid_image = [](const Json& value, std::size_t limit) { + if (!value.is_string()) return false; + const auto& text = value.get_ref(); + return text.empty() || (text.size() <= limit && text.rfind("data:image/", 0) == 0); + }; + if (command.contains("page_shot")) { + if (!valid_image(command["page_shot"], kPageShotLimit)) { + error = "Invalid annotation screenshot"; + return false; + } + store_->set_page_shot(page_id_, command["page_shot"].get()); + } + if (command.contains("record_id")) { + if (!command["record_id"].is_string() || + !command.contains("thumbnail") || + !valid_image(command["thumbnail"], kThumbnailLimit)) { + error = "Invalid annotation thumbnail"; + return false; + } + const auto id = command["record_id"].get(); + bool found = false; + for (auto& record : store_->mutable_records(page_id_)) { + if (record["id"] != id) continue; + record["thumbnail"] = command["thumbnail"]; + found = true; + break; + } + if (!found) { + error = "Unknown annotation"; + return false; + } + } + ++revision_; + return true; + } + if (navigation.blocked()) { + error = "Annotation navigation is pending"; + return false; + } + Json selected; + if (!annotation_submission_records(command, store_->records(page_id_), selected, error)) return false; + if (removed_numbers) { + removed_numbers->clear(); + for (const auto& gone : selected) removed_numbers->push_back(gone["number"].get()); + } + auto& records = store_->mutable_records(page_id_); + for (const auto& gone : selected) { + records.erase(std::remove_if(records.begin(), records.end(), + [&gone](const auto& record) { return record["id"] == gone["id"]; }), records.end()); + } + ++revision_; + return true; + } + + void replace_document() { + poll_pending_ = false; + ++poll_token_; + ++epoch_; + ++sequence_; + busy_ = false; + active_ = false; + popup_ = false; + original_ = false; + markers_hidden_ = false; + modal_suspended_ = false; + target_ = nullptr; + targets_ = Json::array(); + region_ = nullptr; + selection_mode_ = nullptr; + differences_ = Json::array(); + page_background_.clear(); + editing_record_id_.clear(); + edit_locator_.clear(); + draft_description_.clear(); + document_id_.clear(); + for (auto& record : store_->mutable_records(page_id_)) { + record["valid"] = false; + record["invalid_reason"] = "document_replaced"; + } + ++revision_; + requests.cancel("Annotation document replaced"); + requests.restart(); + } + + // The page runtime reports both a replaced root and a lost execution + // context as document-level errors. Native state must retire the old + // generation for either case; otherwise polling and exit keep addressing + // a runtime that no longer exists. + bool recover_document_loss(const Json& result) { + if (!result.is_object() || !result.contains("error") || !result["error"].is_string()) return false; + const auto& error = result["error"].get_ref(); + if (error != "replaced_document" && error != "stale_document") return false; + replace_document(); + return true; + } + + bool prepare(const std::string& page_id, const Json& command, + std::string& expression, std::string& error) { + if (navigation.blocked()) { + error = "Annotation navigation is pending"; + return false; + } + if (!command.is_object() || command.dump().size() > 32768 || + !command.contains("action") || !command["action"].is_string()) { + error = "Invalid annotation command"; + return false; + } + const auto action = command["action"].get(); + if (action != "start" && action != "read" && action != "exit" && + action != "cancel" && action != "save" && action != "add_target" && + action != "add_region" && action != "select_target" && action != "select_region" && + action != "preview_text" && action != "preview_style" && action != "original" && + action != "hide_markers" && action != "set_modal_suspended" && action != "discard" && + action != "edit_record") { + error = "Unsupported annotation action"; + return false; + } + for (const auto& item : command.items()) { + if (item.key() != "action" && item.key() != "document_id" && + !(action == "preview_style" && (item.key() == "styles" || item.key() == "ratio_lock" || item.key() == "target_id")) && + !(action == "preview_text" && (item.key() == "text" || item.key() == "target_id")) && + !(action == "original" && item.key() == "enabled") && + !(action == "hide_markers" && item.key() == "enabled") && + !(action == "set_modal_suspended" && item.key() == "enabled") && + !(action == "save" && (item.key() == "description" || item.key() == "target_id" || + item.key() == "target_ids" || item.key() == "region")) && + !(action == "select_target" && item.key() == "target_id") && + !(action == "edit_record" && item.key() == "record_id")) { + error = "Unsupported annotation field"; + return false; + } + } + if (busy_) { + error = "Annotation command already in progress"; + return false; + } + if (!page_id_.empty() && page_id != page_id_) { + error = "Stale annotation page"; + return false; + } + if (!command.contains("document_id") || !command["document_id"].is_string()) { + error = "Stale annotation document"; + return false; + } + if (action == "start") { + // Start is the only command allowed to establish a generation. A + // frontend snapshot may still echo the retired id while navigation + // completion is being published, so rebase instead of rejecting it. + if (!document_id_.empty() && command["document_id"] != "" && + command["document_id"] != document_id_) { + replace_document(); + } + if (document_id_.empty()) { + document_id_ = page_id + ":document:" + std::to_string(epoch_); + } + } else if (document_id_.empty() || command["document_id"] != document_id_) { + error = "Stale annotation document"; + return false; + } + if ((action == "add_target" || action == "add_region" || action == "select_target" || + action == "select_region") && (!active_ || !popup_ || !selection_mode_.is_null())) { + error = "Invalid annotation selection"; + return false; + } + if (action == "select_target" && (!command.contains("target_id") || + !command["target_id"].is_string() || + std::none_of(targets_.begin(), targets_.end(), [&](const Json& target) { + return target["id"] == command["target_id"]; + }))) { + error = "Unknown annotation target"; + return false; + } + if (action == "select_region" && region_.is_null()) { + error = "Missing annotation region"; + return false; + } + if (action == "edit_record") { + if (!command.contains("record_id") || !command["record_id"].is_string()) { + error = "Invalid annotation record"; + return false; + } + const auto record_id = command["record_id"].get(); + const auto& records = store_->records(page_id_); + const auto found = std::find_if(records.begin(), records.end(), + [&](const auto& record) { return record["id"] == record_id; }); + if (found == records.end()) { + error = "Unknown annotation"; + return false; + } + // 只有「当前文档里还有效」的记录能回到页面改(#217)。stale / orphan + // 走的是另一条路径(只剩文字可改,由弹窗处理)。 + if ((*found)["document_id"] != document_id_ || (*found)["valid"] != true) { + error = "Annotation target is invalid"; + return false; + } + const auto& targets = (*found)["targets"]; + if (!targets.is_array() || targets.empty() || !targets[0].contains("locator") || + !targets[0]["locator"].is_string() || + targets[0]["locator"].get_ref().empty()) { + error = "Annotation target is invalid"; + return false; + } + editing_record_id_ = record_id; + edit_locator_ = targets[0]["locator"].get(); + draft_description_ = (*found).value("description", std::string()); + } + if (action == "save" && (!active_ || !popup_ || original_ || !selection_mode_.is_null() || + (targets_.empty() && region_.is_null()) || + !command.contains("target_id") || command["target_id"] != (target_.is_null() ? Json(nullptr) : target_["id"]) || + !command.contains("target_ids") || command["target_ids"] != annotation_target_ids(targets_) || + !command.contains("region") || command["region"] != region_ || + !command.contains("description") || !command["description"].is_string() || + command["description"].get_ref().size() > 16384)) { + error = "Invalid annotation draft"; + return false; + } + if (action == "preview_text" && (!active_ || !popup_ || !selection_mode_.is_null() || !target_.is_object() || + !command.contains("target_id") || command["target_id"] != target_["id"] || + !command.contains("text") || !command["text"].is_string() || + command["text"].get_ref().size() > 16384)) { + error = "Invalid annotation text draft"; + return false; + } + if (action == "original" && (!command.contains("enabled") || !command["enabled"].is_boolean())) { + error = "Invalid original view request"; + return false; + } + if (action == "hide_markers" && (!command.contains("enabled") || !command["enabled"].is_boolean())) { + error = "Invalid marker visibility request"; + return false; + } + if (action == "set_modal_suspended" && + (!command.contains("enabled") || !command["enabled"].is_boolean())) { + error = "Invalid modal suspension request"; + return false; + } + if (action == "preview_style" && (!active_ || !popup_ || original_ || !selection_mode_.is_null() || !target_.is_object() || + !command.contains("target_id") || command["target_id"] != target_["id"] || + !command.contains("styles") || !valid_styles(command["styles"]) || + (command.contains("ratio_lock") && !command["ratio_lock"].is_boolean()))) { + error = "Invalid annotation style draft"; + return false; + } + pending_ = command; + page_id_ = page_id; + Json payload{{"action", action}, {"document_id", document_id_}}; + if (action == "save") { + payload["target_id"] = command["target_id"]; + payload["target_ids"] = command["target_ids"]; + payload["region"] = region_; + payload["number"] = store_->next_number(page_id_); + } + if (action == "preview_text") { + payload["target_id"] = command["target_id"]; + payload["text"] = command["text"]; + } + if (action == "original") payload["enabled"] = command["enabled"]; + if (action == "hide_markers") payload["enabled"] = command["enabled"]; + if (action == "set_modal_suspended") payload["enabled"] = command["enabled"]; + if (action == "select_target") payload["target_id"] = command["target_id"]; + if (action == "edit_record") { + payload["locator"] = edit_locator_; + } + if (action == "preview_style") { + payload["target_id"] = command["target_id"]; + payload["styles"] = command["styles"]; + if (command.contains("ratio_lock")) payload["ratio_lock"] = command["ratio_lock"]; + } + expression = page_annotation_runtime_expression(payload); + busy_ = true; + ++sequence_; + return true; + } + + std::uint64_t sequence() const { return sequence_; } + void suspend() { + ++sequence_; + busy_ = false; + poll_pending_ = false; + ++poll_token_; + requests.cancel("Annotation navigation started"); + } + bool pollable() const { + return !document_id_.empty() && !busy_ && !poll_pending_ && !navigation.blocked(); + } + std::uint64_t begin_poll() { + if (!pollable()) return 0; + poll_pending_ = true; + return ++poll_token_; + } + bool finish_poll(std::uint64_t token) { + if (!poll_pending_ || token != poll_token_) return false; + poll_pending_ = false; + return true; + } + + bool complete(std::uint64_t sequence, const Json& result, std::string& error) { + if (sequence != sequence_ || !busy_) { + error = "Stale annotation callback"; + return false; + } + busy_ = false; + if (recover_document_loss(result)) return true; + if (result.is_object() && result.contains("error") && result["error"].is_string()) { + const auto runtime_error = result["error"].get(); + if (runtime_error == "invalid_style_value") error = "Invalid style value"; + else if (runtime_error == "invalid_current_ratio") error = "Cannot lock zero or unresolved dimensions"; + else if (runtime_error == "original_view_active") error = "Leave original view before editing"; + else error = "Invalid or stale annotation result"; + return false; + } + if (!valid_result(result)) { + error = "Invalid or stale annotation result"; + return false; + } + const auto action = pending_["action"].get(); + if (!observe_lifecycle(result)) { + error = "Invalid annotation lifecycle report"; + return false; + } + if ((action == "save" || action == "cancel" || action == "exit" || action == "discard") && + (!result["target"].is_null() || result["popup"] != false || + !result["targets"].empty() || !result["region"].is_null() || !result["selection_mode"].is_null())) { + error = "Annotation action did not complete"; + return false; + } + const bool changed = action == "save" || action == "original" || action == "discard" || + action == "hide_markers" || action == "set_modal_suspended" || active_ != result["active"] || + popup_ != result["popup"] || target_ != result["target"] || viewport_ != result["viewport"] || + targets_ != result["targets"] || region_ != result["region"] || selection_mode_ != result["selection_mode"] || + differences_ != result.value("differences", Json::array()) || + page_background_ != result.value("page_background", std::string()) || + markers_hidden_ != result.value("markers_hidden", false) || + modal_suspended_ != result.value("modal_suspended", false); + if (((action == "preview_style" || action == "preview_text") && + (result["target"].is_null() || result["target"]["id"] != target_["id"])) || + (action == "original" && result.value("original", false) != pending_["enabled"])) { + error = "Annotation preview did not complete"; + return false; + } + if (action == "edit_record" && (result["popup"] != true || result["target"].is_null())) { + error = "Annotation target is invalid"; + return false; + } + if (action == "save") { + auto saved_targets = targets_; + for (auto& target : saved_targets) { + target.erase("style_preview"); + target.erase("text_preview"); + } + if (!editing_record_id_.empty()) { + // 铅笔路径:改的是同一条,编号与 id 不变(PRD §6.5)。 + for (auto& record : store_->mutable_records(page_id_)) { + if (record["id"] != editing_record_id_) continue; + record["description"] = pending_["description"]; + record["targets"] = saved_targets; + record["differences"] = result.value("differences", Json::array()); + record["region"] = region_; + record["document_id"] = document_id_; + record["valid"] = true; + break; + } + editing_record_id_.clear(); + draft_description_.clear(); + ++revision_; + } else { + store_->append(page_id_, { + {"document_id", document_id_}, + {"description", pending_["description"]}, {"targets", saved_targets}, + {"differences", result.value("differences", Json::array())}, {"region", region_}, + {"status", "pending"}, {"valid", true}, + }); + } + } else if (action == "discard") { + store_->discard(page_id_); + } + active_ = result["active"].get(); + popup_ = result["popup"].get(); + target_ = result["target"]; + targets_ = result["targets"]; + region_ = result["region"]; + selection_mode_ = result["selection_mode"]; + viewport_ = result["viewport"]; + original_ = result.value("original", false); + differences_ = targets_.empty() ? Json::array() : result.value("differences", Json::array()); + page_background_ = result.value("page_background", std::string()); + markers_hidden_ = result.value("markers_hidden", false); + modal_suspended_ = result.value("modal_suspended", false); + if (changed) ++revision_; + return true; + } + + void fail(std::uint64_t sequence) { + if (sequence == sequence_) busy_ = false; + } + +private: + static bool style_field(const std::string& field, bool difference = false) { + if (field.empty() || field.find('|') != std::string::npos) return false; + static const std::string fields = "|color|background-color|opacity|font-family|font-size|font-weight|" + "width|height|letter-spacing|word-spacing|gap|row-gap|column-gap|padding|margin|" + "padding-top|padding-right|padding-bottom|padding-left|margin-top|margin-right|margin-bottom|margin-left|" + "border-radius|border-color|border-width|border-top-left-radius|border-top-right-radius|" + "border-bottom-right-radius|border-bottom-left-radius|border-top-color|border-right-color|" + "border-bottom-color|border-left-color|border-top-width|border-right-width|border-bottom-width|border-left-width|"; + if (fields.find("|" + field + "|") != std::string::npos) return true; + return difference && (field == "border-top-style" || field == "border-right-style" || + field == "border-bottom-style" || field == "border-left-style"); + } + + static bool valid_styles(const Json& styles) { + if (!styles.is_object() || styles.size() > 48) return false; + for (const auto& item : styles.items()) { + if (!style_field(item.key()) || !item.value().is_string()) return false; + const auto& value = item.value().get_ref(); + if (value.size() > 256 || value.find_first_of(";{}@!<>\\\r\n") != std::string::npos || + value.find('\0') != std::string::npos) return false; + } + return true; + } + + static bool valid_style_preview(const Json& preview) { + if (!preview.is_object() || !preview.contains("ratio_locked") || !preview["ratio_locked"].is_boolean() || + !preview.contains("ratio") || !preview.contains("errors") || !preview["errors"].is_array() || + preview["errors"].size() > 48) return false; + if (!preview["ratio"].is_null()) { + if (!preview["ratio"].is_number()) return false; + const double ratio = preview["ratio"].get(); + if (!std::isfinite(ratio) || ratio <= 0) return false; + } + for (const auto& field : {"values", "styles"}) { + if (!preview.contains(field) || !preview[field].is_object() || preview[field].size() > 48) return false; + for (const auto& item : preview[field].items()) { + if (!style_field(item.key(), true) || !item.value().is_string() || + item.value().get_ref().size() > 2048) return false; + } + } + for (const auto& error : preview["errors"]) { + if (!error.is_string() || error.get_ref().size() > 128) return false; + } + return true; + } + + bool valid_result(const Json& result) const { + if (!result.is_object() || result.dump().size() > 4194304 || + !result.contains("document_id") || result["document_id"] != document_id_ || + !result.contains("active") || !result["active"].is_boolean() || + !result.contains("popup") || !result["popup"].is_boolean() || + !result.contains("target") || !result.contains("viewport") || !result["viewport"].is_object() || + !result.contains("targets") || !valid_annotation_targets(result["targets"]) || + !result.contains("region") || (!result["region"].is_null() && !valid_annotation_bounds(result["region"], true)) || + !result.contains("selection_mode") || !(result["selection_mode"].is_null() || + result["selection_mode"] == "element" || result["selection_mode"] == "region")) return false; + for (const auto& field : {"width", "height"}) { + const auto& viewport = result["viewport"]; + if (!viewport.contains(field) || !viewport[field].is_number()) return false; + const double value = viewport[field].get(); + if (!std::isfinite(value) || value <= 0 || value > 10000000) return false; + } + if (result.contains("original") && !result["original"].is_boolean()) return false; + if (result.contains("markers_hidden") && !result["markers_hidden"].is_boolean()) return false; + if (result.contains("modal_suspended") && !result["modal_suspended"].is_boolean()) return false; + if (result.contains("page_background") && + (!result["page_background"].is_string() || + result["page_background"].get_ref().size() > 128)) return false; + if (result.contains("differences")) { + if (!result["differences"].is_array() || result["differences"].size() > 3136) return false; + std::vector> seen; + for (const auto& difference : result["differences"]) { + const auto& allowed_targets = pending_["action"] == "save" ? targets_ : result["targets"]; + if (!difference.is_object() || difference.size() != 4 || + !difference.contains("property") || !difference["property"].is_string() || + std::none_of(allowed_targets.begin(), allowed_targets.end(), [&](const Json& item) { + return difference.value("target_id", Json()) == item["id"]; + }) || + (difference["property"] != "text" && !style_field(difference["property"].get(), true))) return false; + const auto identity = std::make_pair(difference["target_id"].get(), difference["property"].get()); + if (std::find(seen.begin(), seen.end(), identity) != seen.end()) return false; + seen.push_back(identity); + for (const auto& field : {"old_value", "new_value"}) { + if (!difference.contains(field) || !difference[field].is_string() || + difference[field].get_ref().size() > 16384) return false; + } + if (difference["old_value"] == difference["new_value"]) return false; + } + } + for (const auto& target : result["targets"]) { + if (target.contains("style_preview") && !valid_style_preview(target["style_preview"])) return false; + if (target.contains("text_preview")) { + const auto& text = target["text_preview"]; + if (!text.is_object() || !text.contains("value") || !text["value"].is_string() || + text["value"].get_ref().size() > 16384 || + !text.contains("editable") || !text["editable"].is_boolean() || + !text.contains("error") || !text["error"].is_string()) return false; + } + } + for (const auto& field : {"scroll_x", "scroll_y"}) { + const auto& viewport = result["viewport"]; + if (!viewport.contains(field) || !viewport[field].is_number()) return false; + const double value = viewport[field].get(); + if (!std::isfinite(value) || std::abs(value) > 10000000) return false; + } + const auto& target = result["target"]; + if (result["active"] == false && (!target.is_null() || result["popup"] != false || + !result["targets"].empty() || !result["region"].is_null() || !result["selection_mode"].is_null())) return false; + if (!result["selection_mode"].is_null() && result["popup"] != true) return false; + if (target.is_null()) return result["popup"] == false || !result["region"].is_null(); + return std::find(result["targets"].begin(), result["targets"].end(), target) != result["targets"].end(); + } + + std::shared_ptr store_; + std::string document_id_; + std::string page_id_; + std::uint64_t epoch_ = 1; + std::uint64_t sequence_ = 0; + std::uint64_t revision_ = 0; + bool busy_ = false; + bool active_ = false; + bool popup_ = false; + bool original_ = false; + bool markers_hidden_ = false; + bool modal_suspended_ = false; + Json target_ = nullptr; + Json targets_ = Json::array(); + Json region_ = nullptr; + Json selection_mode_ = nullptr; + bool poll_pending_ = false; + std::uint64_t poll_token_ = 0; + Json viewport_ = nullptr; + Json differences_ = Json::array(); + std::string page_background_; + // 铅笔路径(#217):正在改哪一条、该条保存时的 locator 与描述。 + std::string editing_record_id_; + std::string edit_locator_; + std::string draft_description_; + Json pending_; +}; + +} // namespace acecode::desktop diff --git a/src/apps/desktop/page_annotation_style_runtime.hpp b/src/apps/desktop/page_annotation_style_runtime.hpp new file mode 100644 index 000000000..98ae46a8f --- /dev/null +++ b/src/apps/desktop/page_annotation_style_runtime.hpp @@ -0,0 +1,234 @@ +#pragma once + +namespace acecode::desktop { + +inline constexpr const char kPageAnnotationStyleRuntime[] = R"ACESTYLES( +(rootDocument => { + const sides = ['top', 'right', 'bottom', 'left']; + const groups = { + 'border-radius':['border-top-left-radius','border-top-right-radius','border-bottom-right-radius','border-bottom-left-radius'], + 'border-color':sides.map(side => `border-${side}-color`), + 'border-width':sides.map(side => `border-${side}-width`), + padding:sides.map(side => `padding-${side}`), + margin:sides.map(side => `margin-${side}`), + gap:['row-gap','column-gap'], + }; + const fields = ['color','background-color','opacity','font-family','font-size','font-weight', + 'width','height','letter-spacing','word-spacing','row-gap','column-gap', + ...Object.keys(groups),...Object.values(groups).flat()]; + const properties = [...new Set(fields.flatMap(field => groups[field] || [field])), + ...sides.map(side => `border-${side}-style`)]; + const token = `data-ace-preview-${Array.from(crypto.getRandomValues(new Uint32Array(4)),value => value.toString(16)).join('')}`; + const targets = new Map(); + const sheets = new Map(); + const observedRoots = new Set(); + let original = false; + let nextToken = 0; + let rendered = new Set(); + const computed = target => { + const style = getComputedStyle(target); + return Object.fromEntries([...new Set([...fields,...properties])].map(field => [field,style.getPropertyValue(field)])); + }; + const connected = target => target.isConnected && target.ownerDocument === rootDocument; + const apply = () => { + const rules = new Map(); + const settling = new Map(); + const nextRendered = new Set(); + for (const state of targets.values()) { + if (!connected(state.target)) continue; + const root = state.target.getRootNode(); + if (!observedRoots.has(root)) { + observedRoots.add(root); + observer.observe(root,{childList:true,subtree:true,attributes:true,attributeFilter:[token]}); + } + const declarations = original ? {} : {...state.saved,...state.draft?.styles}; + const selector = Array(4).fill(`[${token}="${state.token}"]:not(#${token})`).join(''); + if (!Object.keys(declarations).length) { + if (rendered.has(state)) settling.set(root,(settling.get(root) || '') + `${selector}{transition:none !important;}`); + continue; + } + nextRendered.add(state); + if (state.target.getAttribute(token) !== state.token) state.target.setAttribute(token,state.token); + const rule = `${selector}{transition:none !important;animation:none !important;${Object.entries(declarations).map(([field,value]) => `${field}:${value} !important;`).join('')}}`; + rules.set(root,(rules.get(root) || '') + rule); + } + for (const root of [...rules.keys(),...settling.keys()]) { + if (!sheets.has(root)) { + const sheet = new CSSStyleSheet(); + sheets.set(root,sheet); + } + } + for (const [root,sheet] of sheets) { + if (!root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = [...root.adoptedStyleSheets,sheet]; + sheet.replaceSync((rules.get(root) || '') + (settling.get(root) || '')); + } + if (settling.size) { + for (const state of rendered) if (connected(state.target)) getComputedStyle(state.target).getPropertyValue('color'); + for (const root of settling.keys()) sheets.get(root).replaceSync(rules.get(root) || ''); + } + rendered = nextRendered; + }; + const observer = new MutationObserver(() => { + for (const root of observedRoots) { + for (const candidate of root.querySelectorAll(`[${token}]`)) { + if (![...targets.values()].some(state => state.target === candidate && candidate.getAttribute(token) === state.token)) { + candidate.removeAttribute(token); + } + } + } + apply(); + }); + const stateFor = (target,id) => { + let state = targets.get(id); + if (state && state.target !== target) throw new Error('stale_target'); + if (!state) { + state = {target,id,token:String(++nextToken),saved:{},draft:null}; + targets.set(id,state); + const root = target.getRootNode(); + if (!observedRoots.has(root)) { + observedRoots.add(root); + observer.observe(root,{childList:true,subtree:true,attributes:true,attributeFilter:[token]}); + } + } + return state; + }; + const changes = state => { + if (!state.draft) return []; + if (original) return state.draft.comparison || []; + const values = computed(state.target); + return [...state.draft.touched].filter(field => values[field] !== state.draft.baseline[field]) + .map(property => ({target_id:state.id,property,old_value:state.draft.baseline[property],new_value:values[property]})); + }; + const select = (target,id) => { + const state = stateFor(target,id); + if (!state.draft) { + const comparing = original; + if (comparing) { original = false; apply(); } + state.draft = {styles:{},baseline:computed(target),touched:new Set(),ratio:null,errors:[]}; + if (comparing) { original = true; apply(); } + } + return state; + }; + return { + select, + preview(target,id,styles,ratioLock) { + if (original) throw new Error('original_view_active'); + const state = select(target,id); + const draft = state.draft; + for (const [field,value] of Object.entries(styles)) { + if (!fields.includes(field) || typeof value !== 'string' || value.length > 256 || + /[;{}@!<>\\\u0000-\u001f]/.test(value) || /(?:url|var|env|attr|expression)\s*\(/i.test(value) || + (value && !CSS.supports(field,value))) throw new Error('invalid_style_value'); + } + const previous = {styles:{...draft.styles},touched:new Set(draft.touched),ratio:draft.ratio}; + if (ratioLock !== undefined) { + const values = computed(target); + const width = parseFloat(values.width); + const height = parseFloat(values.height); + if (ratioLock && (!(width > 0) || !(height > 0))) throw new Error('invalid_current_ratio'); + draft.ratio = ratioLock ? width / height : null; + } + for (const [field,value] of Object.entries(styles)) { + const expanded = groups[field] || [field]; + const declaration = rootDocument.createElement('span').style; + if (value) declaration.setProperty(field,value); + for (const property of expanded) { + draft.touched.add(property); + if (value) draft.styles[property] = declaration.getPropertyValue(property); + else delete draft.styles[property]; + } + if (field === 'border-width' && value) { + const values = computed(target); + for (const side of sides) { + const property = `border-${side}-style`; + if (values[property] === 'none') { + draft.styles[property] = 'solid'; + draft.touched.add(property); + } + } + } + if (field === 'border-width' && !value) { + for (const side of sides) delete draft.styles[`border-${side}-style`]; + } + } + apply(); + if (draft.ratio && (styles.width || styles.height)) { + const primary = styles.width ? 'width' : 'height'; + const linked = primary === 'width' ? 'height' : 'width'; + const value = parseFloat(computed(target)[primary]); + if (!Number.isFinite(value) || value < 0) { + Object.assign(draft,previous); + apply(); + throw new Error('invalid_current_ratio'); + } + draft.styles[linked] = `${primary === 'width' ? value / draft.ratio : value * draft.ratio}px`; + draft.touched.add(linked); + apply(); + } + draft.errors = []; + }, + describe(target,id) { + const state = stateFor(target,id); + const values = computed(target); + const baseline = state.draft?.baseline; + const previous = baseline + ? Object.fromEntries([...new Set([...fields,...properties])].map(field => [field,baseline[field] ?? values[field]])) + : values; + return {values,previous_values:previous,styles:{...state.draft?.styles}, + ratio_locked:!!state.draft?.ratio,ratio:state.draft?.ratio || null,errors:state.draft?.errors || []}; + }, + differences() { return [...targets.values()].flatMap(changes); }, + save() { + const differences = this.differences(); + for (const state of targets.values()) { + const changed = new Set(changes(state).map(change => change.property)); + for (const [field,value] of Object.entries(state.draft?.styles || {})) { + if (changed.has(field)) state.saved[field] = value; + } + state.draft = null; + } + apply(); + return differences; + }, + cancel() { for (const state of targets.values()) state.draft = null; apply(); }, + discardAll() { + for (const state of targets.values()) { + state.saved = {}; + state.draft = null; + } + apply(); + }, + invalidate(ids) { + for (const id of ids) { + const state = targets.get(id); + if (!state) continue; + state.saved = {}; + state.draft = null; + } + apply(); + }, + setOriginal(enabled) { + if (enabled && !original) { + for (const state of targets.values()) if (state.draft) state.draft.comparison = changes(state); + } + original = enabled; + apply(); + }, + dispose() { + original = true; + apply(); + observer.disconnect(); + for (const [root,sheet] of sheets) root.adoptedStyleSheets = root.adoptedStyleSheets.filter(item => item !== sheet); + for (const state of targets.values()) { + if (state.target.getAttribute(token) === state.token) state.target.removeAttribute(token); + } + targets.clear(); + sheets.clear(); + observedRoots.clear(); + rendered.clear(); + }, + }; +}) +)ACESTYLES"; + +} // namespace acecode::desktop diff --git a/src/apps/desktop/page_annotation_submission.hpp b/src/apps/desktop/page_annotation_submission.hpp new file mode 100644 index 000000000..ba8d09a16 --- /dev/null +++ b/src/apps/desktop/page_annotation_submission.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include +#include +#include + +namespace acecode::desktop { + +inline bool annotation_submission_records(const nlohmann::json& command, + const nlohmann::json& records, + nlohmann::json& selected, + std::string& error) { + selected = nlohmann::json::array(); + if (!command.is_object() || !command.contains("record_ids") || + !command["record_ids"].is_array() || command["record_ids"].empty() || + command["record_ids"].size() > 1024) { + error = "Invalid annotation membership"; + return false; + } + for (const auto& id : command["record_ids"]) { + if (!id.is_string()) { error = "Invalid annotation identity"; return false; } + const auto found = std::find_if(records.begin(), records.end(), + [&id](const auto& record) { return record["id"] == id; }); + if (found == records.end() || std::any_of(selected.begin(), selected.end(), + [&id](const auto& record) { return record["id"] == id; })) { + error = "Unknown or duplicate annotation"; + return false; + } + selected.push_back(*found); + } + return true; +} + +} // namespace acecode::desktop diff --git a/src/apps/desktop/page_annotation_targets.hpp b/src/apps/desktop/page_annotation_targets.hpp new file mode 100644 index 000000000..154049f6a --- /dev/null +++ b/src/apps/desktop/page_annotation_targets.hpp @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +#include +#include + +namespace acecode::desktop { + +inline bool valid_annotation_bounds(const nlohmann::json& bounds, bool region = false) { + if (!bounds.is_object() || bounds.size() != 4) return false; + for (const auto& field : {"x", "y", "width", "height"}) { + if (!bounds.contains(field) || !bounds[field].is_number()) return false; + const double value = bounds[field].get(); + const bool dimension = std::string(field) == "width" || std::string(field) == "height"; + if (!std::isfinite(value) || std::abs(value) > 10000000 || + (dimension && value < 0) || (region && (dimension ? value <= 0 : value < 0))) return false; + } + return true; +} + +inline bool valid_annotation_targets(const nlohmann::json& targets) { + if (!targets.is_array() || targets.size() > 64) return false; + std::set identities; + for (const auto& target : targets) { + if (!target.is_object()) return false; + for (const auto& field : {"id", "tag", "text", "locator"}) { + if (!target.contains(field) || !target[field].is_string() || + target[field].get_ref().size() > 2048) return false; + } + if (target["id"] == "" || target["tag"] == "" || + !identities.insert(target["id"].get()).second || + !target.contains("bounds") || !valid_annotation_bounds(target["bounds"])) return false; + } + return true; +} + +inline nlohmann::json annotation_target_ids(const nlohmann::json& targets) { + auto identities = nlohmann::json::array(); + for (const auto& target : targets) identities.push_back(target["id"]); + return identities; +} + +} // namespace acecode::desktop diff --git a/src/apps/desktop/page_annotation_text_runtime.hpp b/src/apps/desktop/page_annotation_text_runtime.hpp new file mode 100644 index 000000000..e0e73984c --- /dev/null +++ b/src/apps/desktop/page_annotation_text_runtime.hpp @@ -0,0 +1,196 @@ +#pragma once + +namespace acecode::desktop { + +inline constexpr const char kPageAnnotationTextRuntime[] = R"ACETEXT( +(() => { + const originals = new Map(); + const writes = new Map(); + const entries = new Map(); + const saved = []; + const drafts = new Map(); + let original = false; + const synchronize = () => { + for (const node of originals.keys()) { + if (writes.has(node)) { + if (node.data === writes.get(node)) continue; + for (const layer of [...saved, ...drafts.values()]) { + if (layer.changes.has(node)) layer.entry.stale = true; + } + for (const entry of entries.values()) if (entry.inserted === node) entry.inserted = null; + writes.delete(node); + } + originals.set(node, node.data); + } + }; + const collect = target => { + const nodes = []; + const visit = element => { + if (['script', 'style', 'noscript', 'template', 'input', 'textarea', 'select'].includes(element.localName)) return; + const style = getComputedStyle(element); + if (style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse') return; + for (const child of element.childNodes) { + if (child.nodeType === 3) nodes.push(child); + else if (child.nodeType === 1) visit(child); + } + }; + visit(target); + return nodes; + }; + const valid = entry => { + synchronize(); + const current = collect(entry.target); + const expected = entry.nodes.filter(node => node !== entry.inserted || node.parentNode); + return !entry.stale && entry.target.isConnected && current.length === expected.length && + current.every((node, index) => node === expected[index]) && entry.nodes.every((node, index) => + node === entry.inserted && !node.parentNode || node.parentNode === entry.parents[index] && entry.target.contains(node)); + }; + const render = () => { + synchronize(); + for (const entry of entries.values()) { + if (entry.inserted && !entry.inserted.parentNode && entry.target.isConnected && !original && + (saved.some(layer => layer.entry === entry) || drafts.has(entry.id))) entry.target.append(entry.inserted); + } + const values = new Map(originals); + if (!original) { + for (const layer of [...saved, ...drafts.values()]) { + if (!valid(layer.entry)) continue; + for (const [node, value] of layer.changes) values.set(node, value); + } + } + const retained = new Set([...saved, ...drafts.values()].filter(layer => valid(layer.entry)) + .flatMap(layer => [...layer.changes.keys()])); + for (const [node, value] of values) { + if (node.data !== value) { + node.data = value; + writes.set(node, value); + } + if (writes.has(node)) { + if (retained.has(node)) writes.set(node, value); + else writes.delete(node); + } + } + for (const entry of entries.values()) { + if (entry.inserted && (original || !saved.some(layer => layer.entry === entry) && !drafts.has(entry.id))) { + entry.inserted.remove(); + } else if (entry.inserted && !entry.inserted.parentNode && entry.target.isConnected) { + entry.target.append(entry.inserted); + } + } + }; + const ensure = (target, id) => { + if (entries.has(id)) return entries.get(id); + const nodes = collect(target); + const value = nodes.map(node => node.data).join(''); + const style = getComputedStyle(target); + const entry = {target, id, nodes, parents:nodes.map(node => node.parentNode), inserted:null, + editable:value.length <= 4096 && style.display !== 'none' && style.visibility !== 'hidden' && style.visibility !== 'collapse' && + !['script', 'style', 'noscript', 'template', 'input', 'textarea', 'select', 'img', 'br', 'hr', 'canvas', 'video', 'audio', 'iframe'].includes(target.localName)}; + for (const node of nodes) if (!originals.has(node)) originals.set(node, node.data); + entries.set(id, entry); + return entry; + }; + const effectiveNodes = (entry, includeDraft = true) => { + synchronize(); + const values = new Map(originals); + for (const layer of [...saved, ...(includeDraft ? drafts.values() : [])]) { + if (!valid(layer.entry)) continue; + for (const [node, value] of layer.changes) values.set(node, value); + } + return entry.nodes.map(node => values.get(node) ?? ''); + }; + const effective = (entry, includeDraft = true) => effectiveNodes(entry, includeDraft).join(''); + const releaseUnused = () => { + const retained = new Set(saved.map(layer => layer.entry)); + for (const [id, entry] of entries) if (!retained.has(entry)) entries.delete(id); + const nodes = new Set([...retained].flatMap(entry => entry.nodes)); + for (const node of originals.keys()) if (!nodes.has(node)) { originals.delete(node); writes.delete(node); } + }; + return Object.freeze({ + describe(target, id) { + const entry = ensure(target, id); + const current = valid(entry); + return {value:entry.editable ? effective(entry) : '', editable:entry.editable && current, + error:!current ? 'Text nodes changed; cancel and select the element again' : + entry.editable ? '' : 'Text exceeds the editable limit or is not visible content'}; + }, + preview(target, id, value) { + const entry = ensure(target, id); + if (!entry.editable || typeof value !== 'string' || value.length > 4096) return {error:'invalid_text'}; + if (!valid(entry)) return {error:'stale_text_nodes'}; + const baseline = effective(entry, false); + if (value === baseline) { + drafts.delete(id); + render(); + return {}; + } + if (!entry.nodes.length) { + entry.inserted = target.ownerDocument.createTextNode(''); + target.append(entry.inserted); + entry.nodes.push(entry.inserted); + entry.parents.push(target); + originals.set(entry.inserted, ''); + } else if (entry.inserted && !entry.inserted.parentNode) target.append(entry.inserted); + const previous = Array.from(baseline); + const characters = Array.from(value); + let start = 0; + while (start < previous.length && start < characters.length && previous[start] === characters[start]) ++start; + let suffix = 0; + while (suffix < previous.length - start && suffix < characters.length - start && + previous[previous.length - 1 - suffix] === characters[characters.length - 1 - suffix]) ++suffix; + const end = previous.length - suffix; + const replacement = characters.slice(start, characters.length - suffix).join(''); + let offset = 0; + let inserted = false; + const baselineNodes = effectiveNodes(entry, false); + const values = baselineNodes.map(part => { + const points = Array.from(part); + const stop = offset + points.length; + let next = points.slice(0, Math.max(0, start - offset)).join(''); + if (!inserted && start >= offset && start <= stop) { next += replacement; inserted = true; } + next += points.slice(Math.max(0, end - offset)).join(''); + offset = stop; + return next; + }); + const changes = new Map(entry.nodes.flatMap((node, index) => + values[index] === baselineNodes[index] ? [] : [[node, values[index]]])); + drafts.set(id, {entry, changes}); + render(); + return {}; + }, + differences() { + return [...drafts.values()].map(layer => ({target_id:layer.entry.id, property:'text', + old_value:effective(layer.entry, false), new_value:effective(layer.entry)})) + .filter(difference => difference.old_value !== difference.new_value); + }, + save() { + if ([...drafts.values()].some(layer => !valid(layer.entry))) return {error:'stale_text_nodes'}; + const differences = this.differences(); + saved.push(...drafts.values()); + drafts.clear(); + render(); + releaseUnused(); + return {differences}; + }, + cancel() { drafts.clear(); render(); releaseUnused(); }, + discardAll() { + saved.length = 0; + drafts.clear(); + render(); + releaseUnused(); + }, + invalidate(ids) { + for (let index = saved.length - 1; index >= 0; --index) { + if (ids.has(saved[index].entry.id)) saved.splice(index, 1); + } + for (const id of ids) drafts.delete(id); + render(); + releaseUnused(); + }, + setOriginal(enabled) { original = enabled; render(); }, + dispose() { saved.length = 0; drafts.clear(); original = true; render(); entries.clear(); originals.clear(); writes.clear(); }, + }); +}) +)ACETEXT"; + +} // namespace acecode::desktop diff --git a/src/apps/desktop/session_annotation_store.hpp b/src/apps/desktop/session_annotation_store.hpp new file mode 100644 index 000000000..a081e980f --- /dev/null +++ b/src/apps/desktop/session_annotation_store.hpp @@ -0,0 +1,150 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace acecode::desktop { + +// 会话级批注记录容器。 +// +// 记录归属会话,不归属页签:页签只是记录的渲染/编辑端点。关掉页签不能把用户 +// 写到一半的描述一起析构(Q33)。因此真正持有记录的应该是会话级的这个 store, +// 而 `PageAnnotationSession` 只做转发——它是「这个页签当前能对哪些记录下命令」 +// 的视图,不是权威。 +// +// 记录标识与文档无关(D9):`:annotation:`。旧标识把 document_id +// 拼进主键,而 document_id 内含自增 epoch,页面一刷新记录就指向不存在的文档代 +// (见 docs/specs/2026-11-22-html-page-annotations-t0-findings.md)。文档代降为 +// 记录的一个属性,只用来判 live / replayable。 +// +// 编号按 page_id 分组,并从当前仍存活的记录集合推导下一号:页签 A 的 1、2 +// 与页签 B 的 1、2 并存。发送/删除清空记录后,下一次保存重新从 1 开始;不能 +// 让已经离开待发集合的编号继续抬高新记录的序号。 +class SessionAnnotationStore { +public: + using Json = nlohmann::json; + + std::uint64_t revision() const { return revision_; } + + // 记录 id 与文档无关。`number` 在同一 page_id 的存活记录内唯一。 + static std::string record_id(const std::string& page_id, std::uint64_t number) { + return page_id + ":annotation:" + std::to_string(number); + } + + // 只读视图:未知页签返回空数组,不会在 store 里凭空建桶。 + const Json& records(const std::string& page_id) const { + static const Json empty = Json::array(); + const auto found = pages_.find(page_id); + return found == pages_.end() ? empty : found->second.records; + } + + // 可写视图。注意它会为该页签建桶。 + Json& mutable_records(const std::string& page_id) { return pages_[page_id].records; } + + std::uint64_t next_number(const std::string& page_id) const { + const auto found = pages_.find(page_id); + if (found == pages_.end()) return 1; + std::uint64_t highest = 0; + for (const auto& record : found->second.records) { + if (!record.is_object()) continue; + const auto number = record.find("number"); + if (number == record.end()) continue; + if (number->is_number_unsigned()) { + highest = std::max(highest, number->get()); + } else if (number->is_number_integer()) { + const auto value = number->get(); + if (value > 0) highest = std::max(highest, static_cast(value)); + } + } + return highest == std::numeric_limits::max() ? highest : highest + 1; + } + + // 追加一条记录并补齐 id / number / page_id。返回指向新记录的引用, + // 调用方可以继续往上写(例如异步补图回填 thumbnail)。 + Json& append(const std::string& page_id, Json record) { + auto& bucket = pages_[page_id]; + const auto number = next_number(page_id); + record["id"] = record_id(page_id, number); + record["number"] = number; + record["page_id"] = page_id; + bucket.records.push_back(std::move(record)); + ++revision_; + return bucket.records.back(); + } + + // 丢弃该页签的全部记录并把编号归 1。别页签的记录不受影响。 + void discard(const std::string& page_id) { + const auto found = pages_.find(page_id); + if (found == pages_.end()) return; + found->second.records = Json::array(); + ++revision_; + } + + bool erase(const std::string& page_id, const std::string& id) { + auto found = pages_.find(page_id); + if (found == pages_.end()) return false; + auto& records = found->second.records; + for (auto it = records.begin(); it != records.end(); ++it) { + if ((*it)["id"] != id) continue; + records.erase(it); + ++revision_; + return true; + } + return false; + } + + // 页签关闭:记录不销毁,标记来源页签已关闭。状态位本身由上层维护, + // 这里只保证记录还活着(P2 的 orphan 语义靠这个前提)。 + bool has_page(const std::string& page_id) const { return pages_.find(page_id) != pages_.end(); } + + // 该页最近一次的整屏图(已发消息卡片配图)。每页只留最新一张:不随记录 + // 增减而变化,所以删掉最后几条批注后配图仍是删除前的画面(PRD §11)。 + const std::string& page_shot(const std::string& page_id) const { + static const std::string empty; + const auto found = pages_.find(page_id); + return found == pages_.end() ? empty : found->second.page_shot; + } + + void set_page_shot(const std::string& page_id, std::string shot) { + auto& bucket = pages_[page_id]; + if (bucket.page_shot == shot) return; + bucket.page_shot = std::move(shot); + ++revision_; + } + + struct Page { + Json records = Json::array(); + std::string page_shot; + }; + + // 按页签遍历(用于跨页签广播与发送时聚合)。 + const std::map& pages() const { return pages_; } + +private: + std::map pages_; + std::uint64_t revision_ = 0; +}; + +// 宿主侧的会话级 store 索引:同一会话的所有页签共享一个容器,页签关掉后记录 +// 仍留在这里(Q33)。只在 UI 线程上访问,所以不加锁。 +class SessionAnnotationStoreRegistry { +public: + std::shared_ptr for_session( + const std::string& session_id) { + if (session_id.empty()) return std::make_shared(); + auto& slot = stores_[session_id]; + if (!slot) slot = std::make_shared(); + return slot; + } + +private: + std::map> stores_; +}; + +} // namespace acecode::desktop diff --git a/src/apps/web/routes/routes_sessions.cpp b/src/apps/web/routes/routes_sessions.cpp index 65e8c96f8..263056f1b 100644 --- a/src/apps/web/routes/routes_sessions.cpp +++ b/src/apps/web/routes/routes_sessions.cpp @@ -2235,7 +2235,7 @@ void WebServer::Impl::register_sessions() { } } - bool ok = deps.session_client->send_input(id, parsed.input); + const bool ok = deps.session_client->send_input(id, parsed.input); if (!ok) { crow::response r(404); r.body = R"({"error":"unknown session"})"; diff --git a/src/engine/agent/worker/agent_task_queue.hpp b/src/engine/agent/worker/agent_task_queue.hpp index fd86b865f..286527241 100644 --- a/src/engine/agent/worker/agent_task_queue.hpp +++ b/src/engine/agent/worker/agent_task_queue.hpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4e1bfbef7..1bbfecf98 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -76,6 +76,10 @@ file(GLOB_RECURSE ACECODE_TEST_SOURCES CONFIGURE_DEPENDS ) add_executable(acecode_unit_tests ${ACECODE_TEST_SOURCES}) +target_sources(acecode_unit_tests PRIVATE + ${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_capture_cdp.cpp + ${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_capture_layout.cpp + ${CMAKE_SOURCE_DIR}/src/apps/desktop/agent_browser_state_json.cpp) add_executable(acecode_runtime_log_fixture ${CMAKE_CURRENT_SOURCE_DIR}/utils/helpers/runtime_log_fixture.cpp @@ -226,6 +230,7 @@ if(WIN32 AND ACECODE_BUILD_DESKTOP) add_executable(agent_browser_host_smoke EXCLUDE_FROM_ALL ${ACECODE_AGENT_BROWSER_HOST_SMOKE_SOURCES} ) + target_include_directories(agent_browser_host_smoke PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(agent_browser_host_smoke PRIVATE acecode_include_roots) target_link_libraries(agent_browser_host_smoke PRIVATE acecode_desktop_support @@ -233,7 +238,7 @@ if(WIN32 AND ACECODE_BUILD_DESKTOP) webview::core cpr::cpr nlohmann_json::nlohmann_json - ole32 user32 ws2_32 + ole32 user32 ws2_32 windowscodecs uuid ) if(MSVC) set_target_properties(agent_browser_host_smoke PROPERTIES @@ -314,6 +319,7 @@ if(APPLE) MACOSX_BUNDLE EXCLUDE_FROM_ALL ${ACECODE_AGENT_BROWSER_HOST_MAC_SMOKE_SOURCES} ) + target_include_directories(agent_browser_host_mac_smoke PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(agent_browser_host_mac_smoke PRIVATE acecode_desktop_support acecode_base_core diff --git a/tests/agent/event_payload/message_payload_test.cpp b/tests/agent/event_payload/message_payload_test.cpp index bb2564ece..9b5588db3 100644 --- a/tests/agent/event_payload/message_payload_test.cpp +++ b/tests/agent/event_payload/message_payload_test.cpp @@ -11,6 +11,8 @@ #include "session/session_serializer.hpp" #include "utils/sha1.hpp" #include "llm/llm_provider.hpp" +#include "llm/message_predicates.hpp" +#include "session/request_context_record.hpp" #include @@ -136,3 +138,30 @@ TEST(MessagePayload, DirectJsonPreservesPersistedFieldsAndStableId) { EXPECT_EQ(acecode::serialize_message_json(message), golden); EXPECT_EQ(acecode::serialize_message(message), golden.dump()); } + +TEST(MessagePayload, ExecutionContextIdentitySurvivesWebPayloadRoundTrip) { + for (const auto* subtype : {acecode::kRequestContextSnapshot, acecode::kRequestContextUpdate}) { + ChatMessage context; + context.role = "user"; + context.is_meta = true; + context.subtype = subtype; + context.content = "\n\nShell sandbox: read-only\n\n"; + context.metadata = {{"request_context_version", 1}, + {"context_state", {{"execution", "Shell sandbox: read-only"}}}}; + const auto restored = acecode::deserialize_message_json(chat_message_to_payload_json(context)); + EXPECT_TRUE(acecode::is_request_context_record(restored)); + EXPECT_FALSE(acecode::is_real_user_message(restored)); + + ChatMessage user; + user.role = "user"; + user.content = context.content; + user.metadata = {{"client_message_id", "annotation-client-1"}}; + const auto accepted = acecode::deserialize_message_json(chat_message_to_payload_json(user)); + EXPECT_TRUE(acecode::is_real_user_message(accepted)); + EXPECT_EQ(accepted.content, context.content); + EXPECT_EQ(accepted.metadata["client_message_id"], "annotation-client-1"); + user.metadata = nlohmann::json::object(); + EXPECT_TRUE(acecode::is_real_user_message( + acecode::deserialize_message_json(chat_message_to_payload_json(user)))); + } +} diff --git a/tests/cpp_source_paths.json b/tests/cpp_source_paths.json index 68b081e37..fb11ee065 100644 --- a/tests/cpp_source_paths.json +++ b/tests/cpp_source_paths.json @@ -10,6 +10,7 @@ "desktop/agent_browser_runtime.hpp": "src/base/ipc/agent_browser_runtime.hpp", "desktop/context_picker.cpp": "src/base/platform/native_ui/context_picker.cpp", "desktop/main.cpp": "src/apps/desktop/main.cpp", + "desktop/agent_browser_state_json.cpp": "src/apps/desktop/agent_browser_state_json.cpp", "desktop/splash_screen.cpp": "src/apps/desktop/splash_screen.cpp", "desktop/startup_progress.hpp": "src/apps/desktop/startup_progress.hpp", "desktop/web_host.cpp": "src/apps/desktop/web_host.cpp", diff --git a/tests/desktop/agent_browser_capture_layout_test.cpp b/tests/desktop/agent_browser_capture_layout_test.cpp new file mode 100644 index 000000000..7ae925641 --- /dev/null +++ b/tests/desktop/agent_browser_capture_layout_test.cpp @@ -0,0 +1,338 @@ +#include "desktop/agent_browser_capture_layout.hpp" +#include "desktop/page_annotation_requests.hpp" + +#include + +#include +#include + +namespace acecode::desktop::browser_capture { +namespace { + +using nlohmann::json; + +struct LayoutProbe { + bool current = true; + std::string pin = ":root{scrollbar-gutter:stable!important}"; + std::string refresh; + std::string failure; + std::string stale; + std::string delay; + std::string malformed; + bool applied = true; + std::vector methods; + std::vector params; + CommandResult delayed; + int completions = 0; + json result; + std::string error; +}; + +void run(const std::shared_ptr& probe, RegisterCleanup cleanup = {}) { + const Command command = [probe](const std::string& method, const json& params, CommandResult done) { + probe->methods.push_back(method); + probe->params.push_back(params); + if (probe->delay == method) { probe->delayed = std::move(done); return; } + if (probe->stale == method) probe->current = false; + if (probe->malformed == method) { + done(nullptr, {}); + } else if (probe->failure == method || + (probe->failure == "clear" && method == "CSS.setStyleSheetText" && params["text"] == "")) { + done({}, "native_failure"); + } else if (method == "Page.getFrameTree") { + done({{"frameTree", {{"frame", {{"id", "frame"}}}}}}, {}); + } else if (method == "Page.createIsolatedWorld") { + done({{"executionContextId", 7}}, {}); + } else if (method == "Runtime.evaluate") { + const auto expression = params.value("expression", ""); + const json value = expression.find("getComputedStyle(document.documentElement)") == 0 + ? json(probe->applied) : json{{"pin", probe->pin}, {"refresh", probe->refresh}}; + done({{"result", {{"value", value}}}}, {}); + } else if (method == "CSS.createStyleSheet") { + done({{"styleSheetId", "owned-sheet"}}, {}); + } else if (method == "Page.captureScreenshot") { + done({{"data", "native PNG"}}, {}); + } else { + done(json::object(), {}); + } + }; + capture_preserving_layout(command, [probe] { return probe->current; }, + {{"format", "png"}, {"captureBeyondViewport", true}, + {"clip", {{"x", 0}, {"y", 0}, {"width", 845}, {"height", 2400}, {"scale", 1}}}}, + [probe](json result, std::string error) { + ++probe->completions; + probe->result = std::move(result); + probe->error = std::move(error); + }, std::move(cleanup)); +} + +void expect_cleared(const std::shared_ptr& probe) { + ASSERT_FALSE(probe->methods.empty()); + EXPECT_EQ(probe->methods.back(), "CSS.setStyleSheetText"); + EXPECT_EQ(probe->params.back(), (json{{"styleSheetId", "owned-sheet"}, {"text", ""}})); + EXPECT_EQ(probe->completions, 1); +} + +TEST(AgentBrowserCaptureLayout, OwnsDistinctInspectorSheetAndClearsBeforeCompletion) { + const auto probe = std::make_shared(); + run(probe); + EXPECT_EQ(probe->methods, (std::vector{"Page.getFrameTree", + "Page.createIsolatedWorld", "Runtime.evaluate", "DOM.enable", "CSS.enable", + "CSS.createStyleSheet", "CSS.setStyleSheetText", "Runtime.evaluate", "Page.captureScreenshot", + "CSS.setStyleSheetText"})); + EXPECT_EQ(probe->params[5], (json{{"frameId", "frame"}, {"force", true}})); + EXPECT_EQ(probe->params[6]["text"], probe->pin); + EXPECT_EQ(probe->params[8]["clip"]["width"], 845); + EXPECT_EQ(probe->params[8]["clip"]["scale"], 1); + EXPECT_EQ(probe->result, (json{{"data", "native PNG"}})); + EXPECT_TRUE(probe->error.empty()); + expect_cleared(probe); +} + +TEST(AgentBrowserCaptureLayout, NoClassicGutterDoesNotChangeStylesOrEnableDomains) { + const auto probe = std::make_shared(); + probe->pin.clear(); + run(probe); + EXPECT_EQ(probe->methods, (std::vector{"Page.getFrameTree", + "Page.createIsolatedWorld", "Runtime.evaluate", "Page.captureScreenshot"})); + EXPECT_TRUE(probe->error.empty()); + EXPECT_EQ(probe->completions, 1); +} + +TEST(AgentBrowserCaptureLayout, ExistingStableGutterRefreshesAfterCaptureWithoutReplacingGutter) { + const auto probe = std::make_shared(); + probe->pin.clear(); + probe->refresh = "scroll"; + run(probe); + EXPECT_EQ(probe->methods[9], "Page.captureScreenshot"); + EXPECT_EQ(probe->params[10]["text"], ":root{overflow-y:scroll!important}"); + EXPECT_EQ(probe->methods[11], "Runtime.evaluate"); + EXPECT_EQ(probe->params[11]["contextId"], 7); + EXPECT_TRUE(probe->error.empty()); + expect_cleared(probe); +} + +TEST(AgentBrowserCaptureLayout, CaptureAndPinErrorsPreserveOriginalFailureAndClearSheet) { + for (const auto* failure : {"Page.captureScreenshot", "CSS.setStyleSheetText"}) { + const auto probe = std::make_shared(); + probe->failure = failure; + run(probe); + EXPECT_EQ(probe->error, "native_failure"); + expect_cleared(probe); + } +} + +TEST(AgentBrowserCaptureLayout, CancellationDuringSheetCreationStillClearsOwnedSheet) { + const auto probe = std::make_shared(); + probe->stale = "CSS.createStyleSheet"; + run(probe); + EXPECT_EQ(probe->error, "capture_document_changed"); + EXPECT_EQ(probe->methods.size(), 7u); + expect_cleared(probe); +} + +TEST(AgentBrowserCaptureLayout, DeferredCaptureOwnsStateAndCleansAfterCancellation) { + const auto probe = std::make_shared(); + probe->delay = "Page.captureScreenshot"; + run(probe); + EXPECT_EQ(probe->completions, 0); + probe->current = false; + auto delayed = std::move(probe->delayed); + ASSERT_TRUE(delayed); + delayed({{"data", "late PNG"}}, {}); + EXPECT_EQ(probe->error, "capture_document_changed"); + expect_cleared(probe); +} + +TEST(AgentBrowserCaptureLayout, RegistryRetiresOwnedPinWithoutScreenshotCallbackBeforeRetry) { + for (const bool deadline : {false, true}) { + AnnotationRequests requests; + const auto now = AnnotationRequests::Clock::time_point{}; + std::map sheets; + std::vector screenshots; + int completions = 0; + int pins = 0; + const Command command = [&sheets, &screenshots, &pins](const std::string& method, + const json& params, CommandResult done) { + if (method == "Page.getFrameTree") { + done({{"frameTree", {{"frame", {{"id", "frame"}}}}}}, {}); + } else if (method == "Page.createIsolatedWorld") { + done({{"executionContextId", 7}}, {}); + } else if (method == "Runtime.evaluate") { + const bool verification = params.at("expression").get().find( + "getComputedStyle(document.documentElement)") == 0; + const bool pinned = std::any_of(sheets.begin(), sheets.end(), [](const auto& sheet) { + return !sheet.second.empty(); + }); + done({{"result", {{"value", verification ? json(pinned) : json{ + {"pin", pinned ? "" : ":root{scrollbar-gutter:stable!important}"}, + {"refresh", pinned ? "scroll" : ""}}}}}}, {}); + } else if (method == "CSS.createStyleSheet") { + const auto id = "owned-" + std::to_string(sheets.size()); + sheets[id] = ""; + done({{"styleSheetId", id}}, {}); + } else if (method == "CSS.setStyleSheetText") { + sheets.at(params.at("styleSheetId").get()) = params.at("text"); + if (params.at("text") == ":root{scrollbar-gutter:stable!important}") ++pins; + done(json::object(), {}); + } else if (method == "Page.captureScreenshot") { + screenshots.push_back(std::move(done)); + } else done(json::object(), {}); + }; + const auto begin = [&requests, now, &completions, &command] { + const auto pending = requests.add([&completions](json response) { + ++completions; + EXPECT_FALSE(response.value("ok", true)); + }, now); + capture_preserving_layout(command, [pending] { return !pending->completed(); }, + json::object(), [pending](json, std::string error) { + pending->finish({{"ok", error.empty()}}); + }, requests.cleanup(pending)); + return pending; + }; + const auto first = begin(); + ASSERT_EQ(screenshots.size(), 1u); + ASSERT_FALSE(sheets.at("owned-0").empty()); + if (deadline) requests.expire(now + std::chrono::seconds(16)); + else requests.cancel("Annotation navigation started"); + EXPECT_TRUE(first->completed()); + EXPECT_EQ(completions, 1); + EXPECT_TRUE(sheets.at("owned-0").empty()); + const auto retry = begin(); + ASSERT_EQ(screenshots.size(), 2u); + EXPECT_EQ(pins, 2); + EXPECT_FALSE(sheets.at("owned-1").empty()); + screenshots.front()({{"data", "late old image"}}, {}); + EXPECT_EQ(completions, 1); + EXPECT_FALSE(retry->completed()); + EXPECT_FALSE(sheets.at("owned-1").empty()); + requests.stop(); + EXPECT_EQ(completions, 2); + EXPECT_TRUE(sheets.at("owned-1").empty()); + screenshots.back()({{"data", "late retry image"}}, {}); + EXPECT_EQ(completions, 2); + } +} + +TEST(AgentBrowserCaptureLayout, RegistryCancellationRetiresLateCreatedSheetWithoutAdvancingOldCapture) { + AnnotationRequests requests; + int completions = 0; + const auto pending = requests.add([&completions](json) { ++completions; }); + const auto probe = std::make_shared(); + probe->delay = "CSS.createStyleSheet"; + run(probe, requests.cleanup(pending)); + auto late = std::move(probe->delayed); + ASSERT_TRUE(late); + requests.cancel("Replaced document"); + EXPECT_EQ(completions, 1); + EXPECT_EQ(probe->completions, 0); + late({{"styleSheetId", "retired-sheet"}}, {}); + EXPECT_EQ(probe->params.back(), (json{{"styleSheetId", "retired-sheet"}, {"text", ""}})); + EXPECT_EQ(probe->methods.back(), "CSS.setStyleSheetText"); + EXPECT_EQ(completions, 1); + EXPECT_EQ(probe->completions, 0); + EXPECT_EQ(std::count(probe->methods.begin(), probe->methods.end(), "CSS.setStyleSheetText"), 1); + EXPECT_EQ(std::count(probe->methods.begin(), probe->methods.end(), "Page.captureScreenshot"), 0); +} + +TEST(AgentBrowserCaptureLayout, RegistryDeadlineDuringRefreshClearsWithoutWaitingOrLateRootEvaluation) { + AnnotationRequests requests; + const auto now = AnnotationRequests::Clock::time_point{}; + int completions = 0; + const auto pending = requests.add([&completions](json) { ++completions; }, now); + const auto probe = std::make_shared(); + probe->pin.clear(); + probe->refresh = "scroll"; + probe->delay = "Page.captureScreenshot"; + run(probe, requests.cleanup(pending)); + auto screenshot = std::move(probe->delayed); + ASSERT_TRUE(screenshot); + probe->delay = "CSS.setStyleSheetText"; + screenshot({{"data", "native PNG"}}, {}); + auto refresh = std::move(probe->delayed); + ASSERT_TRUE(refresh); + EXPECT_NE(probe->params.back()["text"], ""); + requests.expire(now + std::chrono::seconds(16)); + EXPECT_EQ(completions, 1); + EXPECT_EQ(probe->params.back(), (json{{"styleSheetId", "owned-sheet"}, {"text", ""}})); + const auto commands = probe->methods.size(); + refresh(json::object(), {}); + screenshot({{"data", "duplicate PNG"}}, {}); + EXPECT_EQ(probe->methods.size(), commands); + EXPECT_EQ(probe->completions, 0); + EXPECT_EQ(completions, 1); +} + +TEST(AgentBrowserCaptureLayout, CleanupFailureNeverReportsCaptureSuccess) { + const auto probe = std::make_shared(); + probe->failure = "clear"; + run(probe); + EXPECT_EQ(probe->error, "native_failure"); + expect_cleared(probe); +} + +TEST(AgentBrowserCaptureLayout, EarlyNativeErrorNeverCapturesOrTouchesStyles) { + const auto probe = std::make_shared(); + probe->failure = "Page.createIsolatedWorld"; + run(probe); + EXPECT_EQ(probe->methods.size(), 2u); + EXPECT_EQ(probe->completions, 1); + EXPECT_EQ(probe->error, "native_failure"); +} + +TEST(AgentBrowserCaptureLayout, UnoverridableAuthorStyleFailsBeforeScreenshotAndClearsSheet) { + for (bool stable : {false, true}) { + const auto probe = std::make_shared(); + probe->applied = false; + if (stable) { probe->pin.clear(); probe->refresh = "scroll"; } + run(probe); + EXPECT_EQ(probe->error, "capture_layout_unsupported"); + for (const auto& method : probe->methods) EXPECT_NE(method, "Page.captureScreenshot"); + expect_cleared(probe); + } +} + +TEST(AgentBrowserCaptureLayout, MalformedPlanOrSheetNeverDispatchesScreenshot) { + for (const auto* method : {"Page.getFrameTree", "Page.createIsolatedWorld", + "Runtime.evaluate", "CSS.createStyleSheet"}) { + const auto probe = std::make_shared(); + probe->malformed = method; + run(probe); + EXPECT_EQ(probe->error, "capture_layout_failed"); + EXPECT_EQ(probe->completions, 1); + for (const auto& sent : probe->methods) EXPECT_NE(sent, "Page.captureScreenshot"); + } +} + +TEST(AgentBrowserCaptureLayout, StableGutterCancellationStillRefreshesAndClears) { + const auto probe = std::make_shared(); + probe->pin.clear(); + probe->refresh = "auto"; + probe->stale = "Page.captureScreenshot"; + run(probe); + EXPECT_EQ(probe->params[10]["text"], ":root{overflow-y:auto!important}"); + EXPECT_EQ(probe->methods[11], "Runtime.evaluate"); + EXPECT_EQ(probe->error, "capture_document_changed"); + expect_cleared(probe); +} + +TEST(AgentBrowserCaptureLayout, DeferredRestoreFailureStillClearsAndRetainsCaptureError) { + for (const auto* failure : {"Runtime.evaluate", "CSS.setStyleSheetText"}) { + for (bool capture_error : {false, true}) { + const auto probe = std::make_shared(); + probe->pin.clear(); + probe->refresh = "scroll"; + probe->delay = "Page.captureScreenshot"; + run(probe); + auto delayed = std::move(probe->delayed); + ASSERT_TRUE(delayed); + probe->failure = failure; + delayed({{"data", "PNG"}}, capture_error ? "screenshot_failure" : ""); + EXPECT_EQ(probe->error, capture_error ? "screenshot_failure" : "native_failure"); + expect_cleared(probe); + } + } +} + +} +} diff --git a/tests/desktop/agent_browser_capture_probe_test.cpp b/tests/desktop/agent_browser_capture_probe_test.cpp new file mode 100644 index 000000000..cc603a411 --- /dev/null +++ b/tests/desktop/agent_browser_capture_probe_test.cpp @@ -0,0 +1,66 @@ +#include "test_support/desktop/agent_browser_capture_probe_command.hpp" + +#include + +namespace acecode::desktop::capture_probe { +namespace { + +struct FakeClient { + nlohmann::json response; + std::string native_error; + std::string method; + nlohmann::json params; + + nlohmann::json command(const std::string& requested_method, + const nlohmann::json& requested_params, + std::chrono::milliseconds, std::nullptr_t, std::string& error) { + method = requested_method; + params = requested_params; + error = native_error; + return response; + } +}; + +TEST(AgentBrowserCaptureProbe, NullFullPageFailurePreservesNativeError) { + FakeClient client{nullptr, "capture_measure_failed"}; + std::string error; + nlohmann::json result; + EXPECT_NO_THROW(result = checked_command(client, "Page.captureScreenshot", + {{"fullPage", true}}, std::chrono::seconds(20), error)); + EXPECT_TRUE(result.is_null()); + EXPECT_EQ(error, "capture_measure_failed"); + EXPECT_EQ(client.method, "Page.captureScreenshot"); + EXPECT_EQ(client.params, nlohmann::json({{"fullPage", true}})); +} + +TEST(AgentBrowserCaptureProbe, MalformedCommandResultsFailWithoutThrowing) { + for (const auto& method : {"Runtime.evaluate", "Page.captureScreenshot"}) { + for (const auto& response : {nlohmann::json(), nlohmann::json::array(), + nlohmann::json("invalid")}) { + FakeClient client{response, {}}; + std::string error; + EXPECT_NO_THROW(checked_command(client, method, nlohmann::json::object(), + std::chrono::seconds(10), error)); + EXPECT_EQ(error, "native command returned a non-object result"); + } + } +} + +TEST(AgentBrowserCaptureProbe, ObjectCannotMaskNativeFailure) { + FakeClient client{nlohmann::json::object(), "native transport failed"}; + std::string error; + EXPECT_TRUE(checked_command(client, "Runtime.evaluate", nlohmann::json::object(), + std::chrono::seconds(10), error).is_null()); + EXPECT_EQ(error, "native transport failed"); +} + +TEST(AgentBrowserCaptureProbe, SuccessfulResultIsUnchanged) { + FakeClient client{{{"result", {{"value", {{"height", 2400}}}}}}, {}}; + std::string error; + EXPECT_EQ(checked_command(client, "Runtime.evaluate", nlohmann::json::object(), + std::chrono::seconds(10), error), client.response); + EXPECT_TRUE(error.empty()); +} + +} +} diff --git a/tests/desktop/agent_browser_capture_test.cpp b/tests/desktop/agent_browser_capture_test.cpp new file mode 100644 index 000000000..b1955d53f --- /dev/null +++ b/tests/desktop/agent_browser_capture_test.cpp @@ -0,0 +1,369 @@ +#include "desktop/agent_browser_capture.hpp" +#include "desktop/agent_browser_capture_cdp.hpp" +#include "desktop/page_annotation_session.hpp" + +#include +#include +#include +#include + +using namespace acecode::desktop::browser_capture; +using nlohmann::json; + +namespace { + +void append_word(std::string& bytes, std::uint32_t value) { + for (int shift = 24; shift >= 0; shift -= 8) bytes += static_cast(value >> shift); +} + +void append_chunk(std::string& bytes, const std::string& type, const std::string& data) { + append_word(bytes, static_cast(data.size())); + const auto payload = type + data; + bytes += payload; + std::uint32_t crc = 0xffffffffu; + for (unsigned char byte : payload) { + crc ^= byte; + for (int bit = 0; bit < 8; ++bit) crc = (crc >> 1) ^ ((crc & 1) ? 0xedb88320u : 0u); + } + append_word(bytes, crc ^ 0xffffffffu); +} + +std::string png(std::uint32_t width = 2, std::uint32_t height = 2000) { + std::string bytes("\x89PNG\r\n\x1a\n", 8); + std::string header; + append_word(header, width); + append_word(header, height); + header += std::string("\x08\x06\0\0\0", 5); + append_chunk(bytes, "IHDR", header); + std::string pixels(height * (1 + width * 4), '\0'); + for (std::uint32_t row = 0; row < height; ++row) { + for (std::uint32_t column = 0; column < width; ++column) { + const auto offset = row * (1 + width * 4) + 1 + column * 4; + pixels[offset + (row < height / 2 ? 0 : 1)] = '\xff'; + pixels[offset + 3] = '\xff'; + } + } + const auto length = static_cast(pixels.size()); + std::string compressed("\x78\x01\x01", 3); + compressed += static_cast(length); + compressed += static_cast(length >> 8); + compressed += static_cast(~length); + compressed += static_cast((~length) >> 8); + compressed += pixels; + std::uint32_t sum = 1, accum = 0; + for (unsigned char byte : pixels) { + sum = (sum + byte) % 65521; + accum = (accum + sum) % 65521; + } + append_word(compressed, (accum << 16) | sum); + append_chunk(bytes, "IDAT", compressed); + append_chunk(bytes, "IEND", {}); + return bytes; +} + +struct Backend { + Bounds bounds{0, 0, 2, 2000, "document-a"}; + bool current = true; + int captures = 0; + std::vector responses; + Measured measured; + Captured captured; + + void start(const std::string& expected = {}) { + std::make_shared("page-a", expected, + [this](Measured done) { measured = std::move(done); }, + [this](const Bounds& requested, Captured done) { + EXPECT_TRUE(same_document_bounds(requested, bounds)); + ++captures; + captured = std::move(done); + }, [this] { return current; }, + [this](json response) { responses.push_back(std::move(response)); })->start(); + } + + void measure() { auto done = std::move(measured); ASSERT_TRUE(done); done(bounds, {}); } + void capture() { auto done = std::move(captured); ASSERT_TRUE(done); done(png(), {}); } + void expect_error(const std::string& error) { + ASSERT_EQ(responses.size(), 1u); + EXPECT_FALSE(responses[0]["ok"].get()); + EXPECT_TRUE(responses[0]["recoverable"].get()); + EXPECT_EQ(responses[0]["page_id"], "page-a"); + EXPECT_EQ(responses[0]["error"], error); + EXPECT_FALSE(responses[0].contains("result")); + } +}; + +TEST(AgentBrowserCapture, ViewportDefaultAndExplicitFullPageAreDistinct) { + bool full = true; + EXPECT_TRUE(request_mode(json::object(), full).empty()); + EXPECT_FALSE(full); + for (const auto* key : {"fullPage", "captureBeyondViewport"}) { + EXPECT_TRUE(request_mode({{key, true}}, full).empty()); + EXPECT_TRUE(full); + EXPECT_TRUE(request_mode({{key, false}}, full).empty()); + EXPECT_FALSE(full); + } + EXPECT_TRUE(request_mode({{"format", "jpeg"}, {"quality", 80}}, full).empty()); +} + +TEST(AgentBrowserCapture, InvalidRequestsCannotSilentlyBecomeViewportCaptures) { + bool full = false; + for (const json& params : std::vector{nullptr, json::array(), + {{"fullPage", "true"}}, {{"captureBeyondViewport", 1}}, + {{"fullPage", true}, {"captureBeyondViewport", false}}, + {{"fullPage", true}, {"clip", json::object()}}, + {{"fullPage", true}, {"quality", 90}}, + {{"fullPage", true}, {"format", "jpeg"}}, {{"documentId", 5}}, + {{"documentId", ""}}, {{"documentId", std::string(257, 'x')}}}) { + EXPECT_EQ(request_mode(params, full), "capture_invalid_request") << params; + } +} + +TEST(AgentBrowserCapture, BoundsAreCheckedBeforeNativeAllocation) { + Bounds bounds{0, 0, 1024, 30000, "doc"}; + EXPECT_TRUE(validate_bounds(bounds).empty()); + bounds.height = 32769; + EXPECT_EQ(validate_bounds(bounds), "capture_resource_limit"); + bounds.height = 32768; + bounds.width = 1025; + EXPECT_EQ(validate_bounds(bounds), "capture_resource_limit"); + bounds.width = 0; + EXPECT_EQ(validate_bounds(bounds), "capture_invalid_bounds"); + bounds.width = std::numeric_limits::infinity(); + EXPECT_EQ(validate_bounds(bounds), "capture_invalid_bounds"); + bounds.width = std::numeric_limits::quiet_NaN(); + EXPECT_EQ(validate_bounds(bounds), "capture_invalid_bounds"); + bounds.width = 1; + bounds.device_scale = 0; + EXPECT_EQ(validate_bounds(bounds), "capture_invalid_bounds"); +} + +TEST(AgentBrowserCapture, RejectsViewportSubstitutionTruncationCorruptionAndResourceOverflow) { + const Bounds bounds{0, 0, 2, 2000, "doc"}; + EXPECT_TRUE(validate_png(png(), bounds).empty()); + EXPECT_EQ(validate_png(png(2, 600), bounds), "capture_incomplete_image"); + auto bytes = png(); + bytes.resize(bytes.size() - 1); + EXPECT_EQ(validate_png(bytes, bounds), "capture_invalid_png"); + bytes = png(); + bytes[45] ^= 1; + EXPECT_EQ(validate_png(bytes, bounds), "capture_invalid_png"); + EXPECT_EQ(validate_png(std::string(kMaxPngBytes + 1, 'x'), bounds), "capture_resource_limit"); +} + +TEST(AgentBrowserCapture, TallCaptureReturnsOneBoundImageOnlyAfterPostCaptureVerification) { + Backend backend; + backend.start("document-a"); + backend.measure(); + EXPECT_EQ(backend.captures, 1); + backend.capture(); + EXPECT_TRUE(backend.responses.empty()); + backend.measure(); + ASSERT_EQ(backend.responses.size(), 1u); + const auto& response = backend.responses[0]; + EXPECT_TRUE(response["ok"].get()); + EXPECT_EQ(response["result"]["documentId"], "document-a"); + EXPECT_EQ(response["result"]["height"], 2000); + EXPECT_EQ(response["result"]["fullPage"], true); + EXPECT_EQ(acecode::base64_decode(response["result"]["data"].get()), png()); +} + +TEST(AgentBrowserCapture, ExpectedDocumentMismatchDoesNotCapture) { + Backend backend; + backend.start("previous-document"); + backend.measure(); + EXPECT_EQ(backend.captures, 0); + backend.expect_error("capture_document_changed"); +} + +TEST(AgentBrowserCapture, NavigationCloseUnshareOrTimeoutInvalidatesEveryAsyncPhase) { + for (int phase = 0; phase < 4; ++phase) { + Backend backend; + if (phase == 0) backend.current = false; + backend.start(); + if (phase >= 2) backend.measure(); + if (phase >= 3) backend.capture(); + backend.current = false; + if (phase == 1 || phase == 3) backend.measure(); + if (phase == 2) backend.capture(); + backend.expect_error("capture_document_changed"); + } +} + +TEST(AgentBrowserCapture, DocumentLayoutAndScaleChangesRejectCapturedImage) { + for (int change = 0; change < 3; ++change) { + Backend backend; + backend.start(); backend.measure(); backend.capture(); + if (change == 0) backend.bounds.document = "reloaded"; + if (change == 1) backend.bounds.height += 1; + if (change == 2) backend.bounds.device_scale = 2; + backend.measure(); + backend.expect_error("capture_document_changed"); + } +} + +TEST(AgentBrowserCapture, NativeFailureCompletesOnceAndIndependentRetryCanSucceed) { + Backend backend; + backend.start(); backend.measure(); + auto delayed = std::move(backend.captured); + delayed({}, "capture_native_failed"); + delayed(png(), {}); + backend.expect_error("capture_native_failed"); + backend.responses.clear(); + backend.start(); backend.measure(); backend.capture(); backend.measure(); + ASSERT_EQ(backend.responses.size(), 1u); + EXPECT_EQ(backend.responses[0]["ok"], true); +} + +TEST(AgentBrowserCapture, MeasurementAndResourceFailuresNeverDispatchCapture) { + Backend backend; + backend.start(); + auto measured = std::move(backend.measured); + measured({}, "capture_measure_failed"); + backend.expect_error("capture_measure_failed"); + backend.responses.clear(); + backend.bounds.height = 40000; + backend.start(); backend.measure(); + backend.expect_error("capture_resource_limit"); + EXPECT_EQ(backend.captures, 0); +} + +TEST(AgentBrowserCapture, CdpPipelineRemeasuresBeforeReturningCompletePng) { + const auto methods = std::make_shared>(); + const auto responses = std::make_shared>(); + capture_cdp("page-a", json::object(), + [methods](const std::string& method, const json& params, CommandResult done) { + methods->push_back(method); + if (method == "Page.getFrameTree") { + done({{"frameTree", {{"frame", {{"id", "frame"}, {"loaderId", "document"}}}}}}, {}); + } else if (method == "Page.getLayoutMetrics") { + done({{"cssContentSize", {{"x", 0}, {"y", 0}, {"width", 2}, {"height", 2000}}}}, {}); + } else if (method == "Page.createIsolatedWorld") { + done({{"executionContextId", 7}}, {}); + } else if (method == "Runtime.evaluate") { + const json value = params.value("expression", "") == "window.devicePixelRatio" + ? json(1) : json{{"pin", ""}, {"refresh", ""}}; + done({{"result", {{"value", value}}}}, {}); + } else { + done({{"data", acecode::base64_encode(png())}}, {}); + } + }, [] { return true; }, + [responses](json response) { responses->push_back(std::move(response)); }); + EXPECT_EQ(*methods, (std::vector{"Page.getFrameTree", "Page.getLayoutMetrics", + "Page.createIsolatedWorld", "Runtime.evaluate", "Page.getFrameTree", + "Page.createIsolatedWorld", "Runtime.evaluate", "Page.captureScreenshot", + "Page.getFrameTree", "Page.getLayoutMetrics", "Page.createIsolatedWorld", "Runtime.evaluate"})); + ASSERT_EQ(responses->size(), 1u); + EXPECT_EQ((*responses)[0]["ok"], true); + EXPECT_EQ((*responses)[0]["result"]["data"], acecode::base64_encode(png())); + EXPECT_EQ((*responses)[0]["result"]["captureBeyondViewport"], true); +} + +TEST(AgentBrowserCapture, SessionRetirementClearsCdpPinBeforeRetryAndLateCallbacksCannotTouchNewLease) { + for (const bool replace : {false, true}) { + acecode::desktop::PageAnnotationSession session; + const auto now = acecode::desktop::AnnotationRequests::Clock::time_point{}; + std::map sheets; + std::vector screenshots; + std::vector responses; + int commands = 0; + int clears = 0; + const auto start_document = [&] { + std::string expression, error; + ASSERT_TRUE(session.prepare("page-a", {{"action", "start"}, {"document_id", ""}}, expression, error)); + ASSERT_TRUE(session.complete(session.sequence(), {{"document_id", session.document_id()}, + {"active", true}, {"popup", false}, {"original", false}, {"target", nullptr}, + {"targets", json::array()}, {"region", nullptr}, {"selection_mode", nullptr}, + {"differences", json::array()}, + {"viewport", {{"width", 800}, {"height", 600}, {"scroll_x", 0}, {"scroll_y", 0}}}}, error)); + }; + start_document(); + const Command command = [&](const std::string& method, const json& params, CommandResult done) { + ++commands; + if (method == "Page.getFrameTree") { + done({{"frameTree", {{"frame", {{"id", "frame"}, {"loaderId", session.document_id()}}}}}}, {}); + } else if (method == "Page.getLayoutMetrics") { + done({{"cssContentSize", {{"x", 0}, {"y", 0}, {"width", 2}, {"height", 2000}}}}, {}); + } else if (method == "Page.createIsolatedWorld") { + done({{"executionContextId", 7}}, {}); + } else if (method == "Runtime.evaluate") { + const auto expression = params.value("expression", ""); + const json value = expression == "window.devicePixelRatio" ? json(1) + : expression.find("getComputedStyle(document.documentElement)") == 0 ? json(true) + : json{{"pin", ":root{scrollbar-gutter:stable!important}"}, {"refresh", ""}}; + done({{"result", {{"value", value}}}}, {}); + } else if (method == "CSS.createStyleSheet") { + const auto id = session.document_id() + "-" + std::to_string(sheets.size()); + sheets[id] = ""; + done({{"styleSheetId", id}}, {}); + } else if (method == "CSS.setStyleSheetText") { + sheets.at(params.at("styleSheetId").get()) = params.at("text"); + if (params.at("text") == "") ++clears; + done(json::object(), {}); + } else if (method == "Page.captureScreenshot") { + screenshots.push_back(std::move(done)); + } else if (method == "DOM.enable" || method == "CSS.enable") { + done(json::object(), {}); + } else FAIL() << method; + }; + const auto begin = [&] { + const auto pending = session.requests.add([&](json response) { + responses.push_back(std::move(response)); + }, now); + const auto document = session.document_id(); + capture_cdp("page-a", json::object(), command, + [&session, document, pending] { + return session.document_id() == document && !pending->completed(); + }, [pending](json response) { pending->finish(std::move(response)); }, {}, + session.requests.cleanup(pending)); + return pending; + }; + const auto old = begin(); + ASSERT_EQ(screenshots.size(), 1u); + const auto old_sheet = sheets.begin()->first; + ASSERT_FALSE(sheets.at(old_sheet).empty()); + if (replace) session.replace_document(); + else session.requests.expire(now + std::chrono::seconds(16)); + ASSERT_EQ(responses.size(), 1u); + EXPECT_EQ(responses[0]["ok"], false); + EXPECT_TRUE(old->completed()); + EXPECT_TRUE(sheets.at(old_sheet).empty()); + EXPECT_EQ(clears, 1); + if (replace) start_document(); + const auto next = begin(); + ASSERT_EQ(screenshots.size(), 2u); + const auto before_late = commands; + screenshots.front()({{"data", acecode::base64_encode(png())}}, {}); + EXPECT_EQ(commands, before_late); + EXPECT_EQ(responses.size(), 1u); + EXPECT_FALSE(next->completed()); + EXPECT_EQ(std::count_if(sheets.begin(), sheets.end(), [](const auto& sheet) { + return !sheet.second.empty(); + }), 1); + screenshots.back()({{"data", acecode::base64_encode(png())}}, {}); + ASSERT_EQ(responses.size(), 2u); + EXPECT_EQ(responses.back()["ok"], true); + EXPECT_EQ(responses.back()["result"]["documentId"], session.document_id()); + EXPECT_TRUE(next->completed()); + EXPECT_EQ(clears, 2); + const auto finished = commands; + screenshots.front()({{"data", "duplicate"}}, {}); + screenshots.back()({{"data", "duplicate"}}, {}); + EXPECT_EQ(commands, finished); + EXPECT_EQ(responses.size(), 2u); + } +} + +TEST(AgentBrowserCapture, NativeViewportImageAndPostCaptureMeasurementFailureAreNotSuccess) { + Backend backend; + backend.start(); backend.measure(); + auto captured = std::move(backend.captured); + captured(png(2, 600), {}); + backend.expect_error("capture_incomplete_image"); + backend.responses.clear(); + backend.start(); backend.measure(); backend.capture(); + auto measured = std::move(backend.measured); + measured({}, "capture_measure_failed"); + backend.expect_error("capture_measure_failed"); +} + +} diff --git a/tests/desktop/agent_browser_native_boundaries_test.cpp b/tests/desktop/agent_browser_native_boundaries_test.cpp new file mode 100644 index 000000000..ad3cc93ab --- /dev/null +++ b/tests/desktop/agent_browser_native_boundaries_test.cpp @@ -0,0 +1,198 @@ +#include "desktop/agent_browser_capture_cdp.hpp" +#include "desktop/agent_browser_proxy_request.hpp" +#include "desktop/agent_browser_state_json.hpp" + +#include + +#include +#include +#include + +using namespace acecode::desktop; +using nlohmann::json; + +namespace { + +struct CdpProbe { + bool current = true; + std::string failure; + std::vector methods; + std::vector parameters; + std::vector responses; +}; + +browser_capture::Command command_for(const std::shared_ptr& probe) { + return [probe](const std::string& method, const json& params, + browser_capture::CommandResult done) { + probe->methods.push_back(method); + probe->parameters.push_back(params); + if (method == probe->failure) { + done({}, "capture_native_failed"); + } else if (method == "Page.getFrameTree") { + done({{"frameTree", {{"frame", {{"id", "frame"}, {"loaderId", "document"}}}}}}, {}); + } else if (method == "Page.getLayoutMetrics") { + done({{"cssContentSize", {{"x", 3}, {"y", 4}, {"width", 2}, {"height", 2000}}}}, {}); + } else if (method == "Page.createIsolatedWorld") { + done({{"executionContextId", 7}}, {}); + } else if (method == "Runtime.evaluate") { + const json value = params.value("expression", "") == "window.devicePixelRatio" + ? json(2) : json{{"pin", ""}, {"refresh", ""}}; + done({{"result", {{"value", value}}}}, {}); + } else { + done({{"data", "invalid PNG"}}, {}); + } + }; +} + +void start_probe(const std::shared_ptr& probe, browser_capture::Command command) { + browser_capture::capture_cdp("page", json::object(), std::move(command), + [probe] { return probe->current; }, + [probe](json response) { probe->responses.push_back(std::move(response)); }); +} + +json full_page_request() { + return {{"page_id", "page"}, {"method", "Page.captureScreenshot"}, + {"params", {{"fullPage", true}}}}; +} + +} + +TEST(AgentBrowserNativeBoundaries, CdpUsesMeasuredCssClipAndDeviceScale) { + const auto probe = std::make_shared(); + start_probe(probe, command_for(probe)); + EXPECT_EQ(probe->methods, (std::vector{"Page.getFrameTree", + "Page.getLayoutMetrics", "Page.createIsolatedWorld", "Runtime.evaluate", + "Page.getFrameTree", "Page.createIsolatedWorld", "Runtime.evaluate", + "Page.captureScreenshot"})); + ASSERT_EQ(probe->parameters.size(), 8u); + EXPECT_EQ(probe->parameters[2], (json{{"frameId", "frame"}, + {"worldName", "acecode.full-page-capture"}})); + EXPECT_EQ(probe->parameters[3], (json{{"expression", "window.devicePixelRatio"}, + {"contextId", 7}, {"returnByValue", true}})); + EXPECT_EQ(probe->parameters[7], (json{{"format", "png"}, {"fromSurface", true}, + {"captureBeyondViewport", true}, {"clip", {{"x", 3}, {"y", 4}, + {"width", 2}, {"height", 2000}, {"scale", 0.5}}}})); + ASSERT_EQ(probe->responses.size(), 1u); + EXPECT_EQ(probe->responses[0]["error"], "capture_invalid_png"); +} + +TEST(AgentBrowserNativeBoundaries, CdpMeasurementFailureNeverCaptures) { + const auto probe = std::make_shared(); + probe->failure = "Page.getLayoutMetrics"; + start_probe(probe, command_for(probe)); + EXPECT_EQ(probe->methods.size(), 2u); + ASSERT_EQ(probe->responses.size(), 1u); + EXPECT_EQ(probe->responses[0]["error"], "capture_native_failed"); +} + +TEST(AgentBrowserNativeBoundaries, AnnotationMeasurementRejectsInvalidOrReplacedTargets) { + for (bool valid : {false, true}) { + bool current = true; + int measurements = 0; + std::string error; + const auto measure = browser_capture::validated_measure( + [&measurements](browser_capture::Measured done) { + ++measurements; + done({}, {}); + }, [¤t] { return current; }, + [¤t, valid](std::function done) { + if (valid) current = false; + done(valid); + }); + measure([&error](browser_capture::Bounds, std::string failure) { error = failure; }); + EXPECT_EQ(measurements, 0); + EXPECT_EQ(error, "annotation_target_or_document_changed"); + } +} + +TEST(AgentBrowserNativeBoundaries, AsyncProxyCompletionIsExactlyOnceAndOutsideLock) { + int completions = 0; + PendingProxyCall* borrowed = nullptr; + PendingProxyCall pending([&completions, &borrowed](json response) { + ++completions; + EXPECT_TRUE(borrowed->completed()); + EXPECT_TRUE(response.value("ok", false)); + }); + borrowed = &pending; + pending.finish({{"ok", true}}); + pending.finish({{"ok", false}}); + EXPECT_EQ(completions, 1); +} + +TEST(AgentBrowserNativeBoundaries, CdpDelayedMeasurementRejectsReplacedPage) { + const auto probe = std::make_shared(); + const auto delayed = std::make_shared(); + start_probe(probe, [delayed](const std::string&, const json&, + browser_capture::CommandResult done) { + *delayed = std::move(done); + }); + EXPECT_TRUE(probe->responses.empty()); + probe->current = false; + auto done = std::move(*delayed); + ASSERT_TRUE(done); + done({{"frameTree", {{"frame", {{"id", "frame"}, {"loaderId", "document"}}}}}}, {}); + ASSERT_EQ(probe->responses.size(), 1u); + EXPECT_EQ(probe->responses[0]["error"], "capture_document_changed"); +} + +TEST(AgentBrowserNativeBoundaries, FullPageTimeoutOrStopCompletesAndRejectsLateSuccess) { + for (bool stopping : {false, true}) { + PendingProxyCall pending; + const std::atomic stopped{stopping}; + const auto expired = std::chrono::steady_clock::now(); + const auto response = pending.wait(full_page_request(), stopped, expired, "native timeout"); + EXPECT_TRUE(pending.completed()); + EXPECT_EQ(response, (json{{"ok", false}, {"page_id", "page"}, + {"error", stopping ? "capture_stopped" : "capture_timeout"}, {"recoverable", true}})); + pending.finish({{"ok", true}}); + EXPECT_EQ(pending.wait(full_page_request(), stopped, expired, "native timeout"), response); + } +} + +TEST(AgentBrowserNativeBoundaries, ViewportTimeoutPreservesNativeErrorAndLateCompletion) { + PendingProxyCall pending; + const std::atomic stopping{false}; + auto request = full_page_request(); + request["params"] = json::object(); + const auto expired = std::chrono::steady_clock::now(); + EXPECT_EQ(pending.wait(request, stopping, expired, "native timeout")["error"], "native timeout"); + EXPECT_FALSE(pending.completed()); + pending.finish({{"ok", true}}); + pending.finish({{"ok", false}}); + EXPECT_EQ(pending.wait(request, stopping, expired, "native timeout"), (json{{"ok", true}})); +} + +TEST(AgentBrowserNativeBoundaries, ProxyValidationPreservesAuthenticationAndPlatformErrors) { + EXPECT_EQ(browser_proxy_request_error(nullptr, "secret", "invalid method"), + "proxy request must be an object"); + EXPECT_EQ(browser_proxy_request_error(json::object(), "secret", "invalid method"), + "Agent Browser proxy authentication failed"); + json request{{"auth_token", "secret"}, {"method", ""}}; + EXPECT_EQ(browser_proxy_request_error(request, "secret", "invalid method"), "invalid method"); + request["operation"] = "create_page"; + EXPECT_TRUE(browser_proxy_request_error(request, "secret", "invalid method").empty()); + request["operation"] = "unknown"; + EXPECT_EQ(browser_proxy_request_error(request, "secret", "invalid method"), + "Agent Browser proxy operation is invalid"); +} + +TEST(AgentBrowserNativeBoundaries, SerializationPreservesOptionalPayloadSemantics) { + AgentBrowserState state; + state.page_id = "page"; + const auto empty = agent_browser_state_json(state); + EXPECT_EQ(empty.size(), 21u); + EXPECT_EQ(empty["page_id"], "page"); + EXPECT_TRUE(empty["owner"].is_null()); + EXPECT_FALSE(empty.contains("selected_element")); + EXPECT_FALSE(empty.contains("annotations")); + state.selected_element_json = "[1]"; + state.page_annotations_json = R"({"pending":2})"; + auto result = agent_browser_state_json(state); + EXPECT_EQ(result["selected_element"], json::array({1})); + EXPECT_EQ(result["annotations"], (json{{"pending", 2}})); + state.selected_element_json = "invalid"; + state.page_annotations_json = "[1]"; + result = agent_browser_state_json(state); + EXPECT_FALSE(result.contains("selected_element")); + EXPECT_FALSE(result.contains("annotations")); +} diff --git a/tests/desktop/helpers/agent_browser_host_mac_smoke.mm b/tests/desktop/helpers/agent_browser_host_mac_smoke.mm index 1b837b9bb..694211116 100644 --- a/tests/desktop/helpers/agent_browser_host_mac_smoke.mm +++ b/tests/desktop/helpers/agent_browser_host_mac_smoke.mm @@ -3,6 +3,7 @@ #import #import +#include "test_support/desktop/agent_browser_capture_probe.hpp" #include #include @@ -381,6 +382,9 @@ int main() { screenshot_ok = bytes.has_value() && acecode::agent_browser::agent_browser_png_dimensions( *bytes).has_value(); + if (screenshot_ok && worker_error.empty()) { + screenshot_ok = acecode::desktop::capture_probe::run(client, worker_error); + } } worker_done.store(true); }); diff --git a/tests/desktop/helpers/agent_browser_host_smoke.cpp b/tests/desktop/helpers/agent_browser_host_smoke.cpp index 79f98655d..a856f87d4 100644 --- a/tests/desktop/helpers/agent_browser_host_smoke.cpp +++ b/tests/desktop/helpers/agent_browser_host_smoke.cpp @@ -11,6 +11,7 @@ #endif #include #include +#include "test_support/desktop/agent_browser_capture_probe.hpp" #include #include @@ -521,6 +522,11 @@ int main() { ? "CDP screenshot was not a valid PNG" : agent_error)); } else { + if (!acecode::desktop::capture_probe::run(client, agent_error)) { + agent_exit_code.store(fail(agent_error)); + agent_done.store(true); + return; + } client.select_page( first_page, std::chrono::seconds(10), nullptr, agent_error); diff --git a/tests/desktop/helpers/html_annotation_fixture.html b/tests/desktop/helpers/html_annotation_fixture.html new file mode 100644 index 000000000..7913176a2 --- /dev/null +++ b/tests/desktop/helpers/html_annotation_fixture.html @@ -0,0 +1,60 @@ + + + + + + HTML annotation acceptance fixture + + + +
+

在静默之地,种下一颗星。

+
+

Nested elements

+

Before nested text after another node.

+ +
Style target
+
+
+

Target lifecycle

+

Original target

+

Original target

+ + Navigate +
+
+

Middle: orange

+

The green section belongs below this long orange section.

+
+
+

Bottom: green

+

FULL-PAGE-CAPTURE-END

+
+
+ + + diff --git a/tests/desktop/page_annotation_lifecycle_smoke.mjs b/tests/desktop/page_annotation_lifecycle_smoke.mjs new file mode 100644 index 000000000..4207f8c7c --- /dev/null +++ b/tests/desktop/page_annotation_lifecycle_smoke.mjs @@ -0,0 +1,132 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const binary = process.argv[2]; +assert.ok(binary, 'Usage: node tests/desktop/page_annotation_lifecycle_smoke.mjs '); +const factory = (file, delimiter) => fs.readFileSync(new URL(`../../src/apps/desktop/${file}`, import.meta.url), 'utf8') + .split(`R"${delimiter}(`).slice(1).map(part => part.split(`)${delimiter}"`)[0]).join(''); +const runtime = factory('page_annotation_runtime.hpp', 'ACEANNOTATION'); +const text = factory('page_annotation_text_runtime.hpp', 'ACETEXT'); +const styles = factory('page_annotation_style_runtime.hpp', 'ACESTYLES'); +const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ace-annotation-lifecycle-')); +try { + const fixture = path.join(directory, 'fixture.html'); + fs.writeFileSync(fixture, ` +
+
+
NOT RUN
`, 'utf8'); + const result = spawnSync(binary, ['--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check', + `--user-data-dir=${path.join(directory, 'profile')}`, '--dump-dom', pathToFileURL(fixture).href], + { encoding:'utf8', timeout:45000, windowsHide:true, maxBuffer:2 * 1024 * 1024 }); + assert.ifError(result.error); + assert.equal(result.status, 0, result.stderr); + const outcome = result.stdout.match(/
([\s\S]*?)<\/pre>/)?.[1];
+  if (!outcome?.startsWith('PASS:')) {
+    console.error(result.stdout.slice(-4000));
+    console.error(result.stderr.slice(-2000));
+  }
+  assert.ok(outcome?.startsWith('PASS:'), outcome || result.stdout || result.stderr);
+  console.log(outcome);
+} finally {
+  const relative = path.relative(fs.realpathSync(os.tmpdir()), fs.realpathSync(directory));
+  assert.ok(relative && !relative.startsWith('..') && !path.isAbsolute(relative) && path.basename(directory).startsWith('ace-annotation-lifecycle-'));
+  fs.rmSync(directory, { recursive:true, force:true, maxRetries:10, retryDelay:200 });
+}
diff --git a/tests/desktop/page_annotation_navigation_test.cpp b/tests/desktop/page_annotation_navigation_test.cpp
new file mode 100644
index 000000000..fb7e71fc3
--- /dev/null
+++ b/tests/desktop/page_annotation_navigation_test.cpp
@@ -0,0 +1,266 @@
+#include "desktop/agent_browser_host.hpp"
+#include "desktop/page_annotation_host_navigation.hpp"
+
+#include 
+
+namespace acecode::desktop {
+namespace {
+
+struct NavigationPage {
+    std::string id = "page";
+    bool closing = false;
+    PageAnnotationSession annotations;
+    bool webview = true;
+    int store = 1;
+    AgentBrowserState state;
+};
+
+struct NavigationHost : std::enable_shared_from_this {
+    using Page = NavigationPage;
+    std::vector> pages;
+    int updates = 0;
+    auto find_page(const std::string& id) {
+        const auto found = std::find_if(pages.begin(), pages.end(), [&](const auto& page) { return page->id == id; });
+        return found == pages.end() ? nullptr : *found;
+    }
+    auto states() {
+        std::vector result;
+        for (const auto& page : pages) result.push_back(page->state);
+        return result;
+    }
+    template 
+    void update_page(const std::shared_ptr& page, Update update) { ++updates; update(page->state); }
+};
+
+#ifdef _WIN32
+void pump_annotation_timers(DWORD duration, const std::function& finished = [] { return false; }) {
+    const auto deadline = GetTickCount64() + duration;
+    while (!finished() && GetTickCount64() < deadline) {
+        const auto remaining = static_cast(deadline - GetTickCount64());
+        MsgWaitForMultipleObjects(0, nullptr, FALSE, remaining, QS_TIMER);
+        MSG message{};
+        while (PeekMessageW(&message, nullptr, WM_TIMER, WM_TIMER, PM_REMOVE)) DispatchMessageW(&message);
+    }
+}
+
+TEST(PageAnnotationNavigation, PollTimerCanBeStoppedOrDestroyedInsideItsOwnCallback) {
+    int calls = 0;
+    {
+        AnnotationPoller stopped;
+        stopped.start([&] { ++calls; });
+        stopped.stop();
+        stopped.stop();
+        pump_annotation_timers(300);
+        EXPECT_EQ(calls, 0);
+    }
+    auto poller = std::make_unique();
+    poller->start([&] { ++calls; poller.reset(); });
+    poller->start([&] { calls += 100; });
+    pump_annotation_timers(2000, [&] { return calls > 0; });
+    EXPECT_EQ(calls, 1);
+    EXPECT_FALSE(poller);
+    pump_annotation_timers(300);
+    EXPECT_EQ(calls, 1);
+}
+#endif
+
+TEST(PageAnnotationNavigation, StoreCompletionOnlyReloadsFrozenCurrentReservedPages) {
+    auto host = std::make_shared();
+    for (const auto& id : {"first", "switched", "closed", "superseded", "replaced"}) {
+        const auto page = std::make_shared();
+        page->id = id;
+        page->state.page_id = id;
+        host->pages.push_back(page);
+    }
+    const auto pages = annotation_store_pages(*host, 1);
+    ASSERT_EQ(pages.size(), 5);
+    ASSERT_TRUE(reserve_annotation_transition(pages, [](const auto&) { return true; }, [] { return true; }));
+    const auto tickets = annotation_transition_tickets(pages);
+    pages[1]->store = 2;
+    pages[2]->closing = true;
+    pages[3]->annotations.navigation.finish();
+    ASSERT_TRUE(pages[3]->annotations.navigation.reserve());
+    host->pages.back() = std::make_shared();
+    host->pages.back()->id = "replaced";
+    std::vector reloaded;
+    annotation_reload_reserved(*host, tickets, 1, true, [&](const auto& page) {
+        reloaded.push_back(page->id);
+        EXPECT_TRUE(page->annotations.navigation.armed());
+        return false;
+    });
+    EXPECT_EQ(reloaded, std::vector{"first"});
+    EXPECT_FALSE(pages[0]->annotations.navigation.blocked());
+    EXPECT_FALSE(pages[1]->annotations.navigation.blocked());
+    EXPECT_TRUE(pages[3]->annotations.navigation.reserved());
+}
+
+TEST(PageAnnotationNavigation, PassivePollBoundsFlightsAndRejectsRetiredDocumentOrHost) {
+    auto host = std::make_shared();
+    const auto page = std::make_shared();
+    page->state.page_id = page->id;
+    page->state.content_state = kAgentBrowserContentStateLive;
+    host->pages.push_back(page);
+    std::string expression;
+    std::string error;
+    ASSERT_TRUE(page->annotations.prepare(page->id, {{"action", "start"}, {"document_id", ""}}, expression, error));
+    page->annotations.fail(page->annotations.sequence());
+    std::function done;
+    int evaluations = 0;
+    const auto evaluate = [&](const auto&, const auto&, auto, const auto&, auto callback) {
+        ++evaluations;
+        done = callback;
+    };
+    const std::weak_ptr weak = host;
+    const auto sequence = page->annotations.sequence();
+    poll_annotations(weak, evaluate);
+    poll_annotations(weak, evaluate);
+    EXPECT_EQ(evaluations, 1);
+    EXPECT_EQ(sequence, page->annotations.sequence());
+    page->annotations.replace_document();
+    const auto revision = page->annotations.revision();
+    done(true, {{"error", "replaced_document"}});
+    EXPECT_EQ(page->annotations.revision(), revision);
+    EXPECT_EQ(host->updates, 0);
+    ASSERT_TRUE(page->annotations.prepare(page->id, {{"action", "start"}, {"document_id", ""}}, expression, error));
+    page->annotations.fail(page->annotations.sequence());
+    poll_annotations(weak, evaluate);
+    EXPECT_EQ(evaluations, 2);
+    host.reset();
+    done(true, {{"error", "replaced_document"}});
+    EXPECT_EQ(page->annotations.revision(), revision);
+}
+
+TEST(PageAnnotationNavigation, PassivePollRetiresAStaleRuntimeDocument) {
+    auto host = std::make_shared();
+    const auto page = std::make_shared();
+    page->state.page_id = page->id;
+    page->state.content_state = kAgentBrowserContentStateLive;
+    host->pages.push_back(page);
+    std::string expression;
+    std::string error;
+    ASSERT_TRUE(page->annotations.prepare(page->id, {{"action", "start"}, {"document_id", ""}}, expression, error));
+    const std::string document = page->annotations.document_id();
+    page->annotations.fail(page->annotations.sequence());
+
+    std::function done;
+    poll_annotations(std::weak_ptr(host),
+        [&](const auto&, const auto&, auto, const auto&, auto callback) { done = callback; });
+    ASSERT_TRUE(done);
+    done(true, {{"error", "stale_document"}});
+
+    EXPECT_TRUE(page->annotations.document_id().empty());
+    EXPECT_FALSE(page->annotations.document_id() == document);
+    EXPECT_EQ(host->updates, 1);
+}
+
+TEST(PageAnnotationNavigation, UiTickExpiresRequestsEvenWhenDocumentCannotBePolled) {
+    const auto host = std::make_shared();
+    const auto page = std::make_shared();
+    page->state.page_id = page->id;
+    host->pages.push_back(page);
+    int completions = 0;
+    const auto held = page->annotations.requests.add([&](nlohmann::json result) {
+        ++completions;
+        EXPECT_EQ(result["ok"], false);
+        EXPECT_EQ(result["recoverable"], true);
+    }, AnnotationRequests::Clock::now() - std::chrono::seconds(16));
+    ASSERT_TRUE(page->annotations.navigation.reserve());
+    poll_annotations(std::weak_ptr(host), [](const auto&, const auto&, auto, const auto&, auto) {
+        ADD_FAILURE() << "Inactive document must not be evaluated";
+    });
+    EXPECT_EQ(completions, 1);
+    EXPECT_TRUE(held->completed());
+    held->finish({{"ok", true}});
+    EXPECT_EQ(completions, 1);
+}
+
+TEST(PageAnnotationNavigation, RollbackNeverClearsASupersedingTransition) {
+    const auto page = std::make_shared();
+    std::string expression;
+    std::string error;
+    ASSERT_TRUE(page->annotations.prepare(page->id, {{"action", "start"}, {"document_id", ""}}, expression, error));
+    EXPECT_FALSE(reserve_annotation_transition(std::vector{page}, [](const auto&) { return true; }, [&] {
+        page->annotations.navigation.finish();
+        EXPECT_TRUE(page->annotations.navigation.reserve());
+        return true;
+    }));
+    EXPECT_TRUE(page->annotations.navigation.reserved());
+}
+
+TEST(PageAnnotationNavigation, ReservationRequiresExplicitArmingAndBlocksWhileHeld) {
+    AnnotationNavigationGuard guard;
+    EXPECT_TRUE(guard.reserve());
+    EXPECT_FALSE(guard.start());
+    EXPECT_TRUE(guard.arm());
+    EXPECT_TRUE(guard.start());
+    EXPECT_FALSE(guard.start());
+    EXPECT_TRUE(guard.start(true));
+    EXPECT_FALSE(guard.reserve());
+    guard.finish();
+    EXPECT_TRUE(guard.reserve());
+    EXPECT_TRUE(guard.blocked());
+    guard.finish();
+    EXPECT_FALSE(guard.blocked());
+}
+
+TEST(PageAnnotationNavigation, AllEntryMethodsShareTheDestructiveTransitionFence) {
+    for (const auto& method : {"Page.navigate", "Page.reload", "Page.navigateToHistoryEntry", "Page.setDocumentContent"}) {
+        EXPECT_TRUE(annotation_replaces_document(method));
+    }
+    for (const auto& method : {"Runtime.evaluate", "Page.captureScreenshot", "Page.getNavigationHistory"}) {
+        EXPECT_FALSE(annotation_replaces_document(method));
+    }
+    EXPECT_TRUE(annotation_fragment_navigation("https://a.test/page#one", "https://a.test/page#two"));
+    EXPECT_FALSE(annotation_fragment_navigation("https://a.test/page", "https://a.test/other#two"));
+    EXPECT_FALSE(annotation_fragment_navigation("https://a.test/page", "https://a.test/page"));
+}
+
+TEST(PageAnnotationNavigation, DefaultStayAndReentrantChangesReleaseAllReservations) {
+    const auto page = std::make_shared();
+    std::string expression;
+    std::string error;
+    ASSERT_TRUE(page->annotations.prepare("page", {{"action", "start"}, {"document_id", ""}}, expression, error));
+    const std::vector> pages{page};
+    const auto current = [](const auto& candidate) { return !candidate->closing; };
+    int prompts = 0;
+    EXPECT_FALSE(reserve_annotation_transition(pages, current, [&] {
+        ++prompts;
+        EXPECT_FALSE(page->annotations.navigation.start());
+        return false;
+    }));
+    EXPECT_EQ(prompts, 1);
+    EXPECT_FALSE(page->annotations.navigation.blocked());
+    EXPECT_FALSE(reserve_annotation_transition(pages, current, [&] {
+        page->annotations.replace_document();
+        return true;
+    }));
+    EXPECT_FALSE(page->annotations.navigation.blocked());
+    ASSERT_TRUE(page->annotations.prepare("page", {{"action", "start"}, {"document_id", ""}}, expression, error));
+    EXPECT_FALSE(reserve_annotation_transition(pages, current, [&] {
+        page->closing = true;
+        return true;
+    }));
+    EXPECT_FALSE(page->annotations.navigation.blocked());
+}
+
+TEST(PageAnnotationNavigation, MultiplePagesAreReservedBeforeAnyConfirmationOrSideEffect) {
+    const auto first = std::make_shared();
+    const auto second = std::make_shared();
+    const auto current = [](const auto&) { return true; };
+    ASSERT_TRUE(second->annotations.navigation.reserve());
+    int prompts = 0;
+    EXPECT_FALSE(reserve_annotation_transition(std::vector{first, second}, current, [&] { ++prompts; return true; }));
+    EXPECT_EQ(prompts, 0);
+    EXPECT_FALSE(first->annotations.navigation.blocked());
+    second->annotations.navigation.finish();
+    EXPECT_TRUE(reserve_annotation_transition(std::vector{first, second}, current, [&] { ++prompts; return true; }));
+    EXPECT_EQ(prompts, 0);
+    const auto ticket = first->annotations.navigation.ticket();
+    first->annotations.navigation.finish();
+    ASSERT_TRUE(first->annotations.navigation.reserve());
+    EXPECT_NE(ticket, first->annotations.navigation.ticket());
+    EXPECT_TRUE(second->annotations.navigation.blocked());
+}
+
+}
+}
diff --git a/tests/desktop/page_annotation_session_test.cpp b/tests/desktop/page_annotation_session_test.cpp
new file mode 100644
index 000000000..4923c624f
--- /dev/null
+++ b/tests/desktop/page_annotation_session_test.cpp
@@ -0,0 +1,801 @@
+#include 
+#include 
+
+#include "desktop/page_annotation_session.hpp"
+#include "desktop/agent_browser_host.hpp"
+#include "desktop/page_annotation_host_submission.hpp"
+
+namespace acecode::desktop {
+namespace {
+
+using Json = nlohmann::json;
+
+class PageAnnotationSessionTest : public testing::Test {
+protected:
+    Json command(const std::string& action) const {
+        Json request{{"action", action}, {"document_id", session.snapshot()["document_id"]}};
+        if (action == "save") {
+            request["target_ids"] = annotation_target_ids(session.snapshot()["targets"]);
+            request["region"] = session.snapshot()["region"];
+        }
+        return request;
+    }
+
+    Json result(bool active = true, bool popup = false, Json target = nullptr) const {
+        return {{"document_id", session.snapshot()["document_id"]},
+                {"active", active}, {"popup", popup}, {"target", target},
+                {"original", false}, {"differences", Json::array()},
+                {"targets", target.is_null() ? Json::array() : Json::array({target})},
+                {"region", nullptr}, {"selection_mode", nullptr},
+                {"viewport", {{"width", 800}, {"height", 600}, {"scroll_x", 0}, {"scroll_y", 0}}}};
+    }
+
+    Json target() const {
+        return {{"id", "target-1"}, {"tag", "button"}, {"text", "Click"},
+                {"locator", "button#target"},
+                {"bounds", {{"x", 10}, {"y", 20}, {"width", 80}, {"height", 30}}}};
+    }
+
+    bool prepare(const Json& request) {
+        return session.prepare("page-1", request, expression, error);
+    }
+
+    void start() {
+        ASSERT_TRUE(prepare(command("start"))) << error;
+        ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+    }
+
+    void select() {
+        ASSERT_TRUE(prepare(command("read"))) << error;
+        ASSERT_TRUE(session.complete(session.sequence(), result(true, true, target()), error)) << error;
+    }
+
+    void save(const std::string& description) {
+        auto request = command("save");
+        request["description"] = description;
+        request["target_id"] = "target-1";
+        ASSERT_TRUE(prepare(request)) << error;
+        EXPECT_EQ(expression.find(description), std::string::npos);
+        ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+    }
+
+    PageAnnotationSession session;
+    std::string expression;
+    std::string error;
+};
+
+TEST_F(PageAnnotationSessionTest, PassivePollIsBoundedAndNeverAdvancesCommandSequence) {
+    EXPECT_EQ(session.begin_poll(), 0);
+    start();
+    const auto sequence = session.sequence();
+    const auto first = session.begin_poll();
+    EXPECT_NE(first, 0);
+    EXPECT_EQ(session.sequence(), sequence);
+    EXPECT_FALSE(session.pollable());
+    EXPECT_EQ(session.begin_poll(), 0);
+    EXPECT_FALSE(session.finish_poll(first + 1));
+    EXPECT_TRUE(session.finish_poll(first));
+    EXPECT_FALSE(session.finish_poll(first));
+    const auto suspended = session.begin_poll();
+    session.suspend();
+    EXPECT_FALSE(session.finish_poll(suspended));
+    const auto replaced = session.begin_poll();
+    session.replace_document();
+    start();
+    const auto current = session.begin_poll();
+    EXPECT_FALSE(session.finish_poll(replaced));
+    EXPECT_FALSE(session.pollable());
+    EXPECT_TRUE(session.finish_poll(current));
+    EXPECT_TRUE(session.navigation.reserve());
+    EXPECT_EQ(session.begin_poll(), 0);
+}
+
+TEST_F(PageAnnotationSessionTest, SnapshotRetainsPageBackgroundForOverlayCorners) {
+    ASSERT_TRUE(prepare(command("start"))) << error;
+    auto initial = result(true, false);
+    initial["page_background"] = "rgb(18, 53, 30)";
+    ASSERT_TRUE(session.complete(session.sequence(), initial, error)) << error;
+    EXPECT_EQ(session.snapshot()["page_background"], "rgb(18, 53, 30)");
+
+    session.replace_document();
+    EXPECT_EQ(session.snapshot()["page_background"], "");
+}
+
+TEST(AnnotationRequests, DeadlineBoundShutdownAndReentrantCompletion) {
+    const auto now = AnnotationRequests::Clock::time_point{};
+    int completions = 0;
+    std::shared_ptr late;
+    {
+        AnnotationRequests requests;
+        for (int index = 0; index < 32; ++index) {
+            ASSERT_TRUE(requests.add([&](Json result) {
+                ++completions;
+                EXPECT_EQ(result["ok"], false);
+            }, now));
+        }
+        EXPECT_FALSE(requests.add([&](Json) { ++completions; }, now));
+        EXPECT_EQ(completions, 1);
+        requests.expire(now + std::chrono::seconds(14));
+        EXPECT_EQ(completions, 1);
+        requests.expire(now + std::chrono::seconds(15));
+        EXPECT_EQ(completions, 33);
+        ASSERT_TRUE(requests.add([&](Json) {
+            ++completions;
+            late = requests.add([&](Json) { ++completions; }, now);
+        }, now));
+        requests.cancel("replacement");
+        ASSERT_TRUE(late);
+        EXPECT_FALSE(late->completed());
+    }
+    EXPECT_TRUE(late->completed());
+    EXPECT_EQ(completions, 35);
+    late->finish({{"ok", true}});
+    EXPECT_EQ(completions, 35);
+}
+
+TEST(AnnotationRequests, RetirementPrecedesResponseAndLateRegistrationCannotLeakResource) {
+    AnnotationRequests requests;
+    int retired = 0;
+    int completions = 0;
+    std::shared_ptr next;
+    const auto first = requests.add([&](Json) {
+        EXPECT_EQ(retired, 1);
+        ++completions;
+        next = requests.add([&](Json) { ++completions; });
+        requests.cleanup(next)([&] { ++retired; });
+    });
+    const auto register_cleanup = requests.cleanup(first);
+    auto resource = std::make_shared(0);
+    const std::weak_ptr weak_resource = resource;
+    register_cleanup([resource, &retired] { ++retired; });
+    resource.reset();
+    EXPECT_FALSE(weak_resource.expired());
+    requests.cancel("replaced");
+    EXPECT_TRUE(weak_resource.expired());
+    EXPECT_EQ(completions, 1);
+    ASSERT_TRUE(next);
+    EXPECT_FALSE(next->completed());
+    register_cleanup([&] { ++retired; });
+    EXPECT_EQ(retired, 2);
+    first->finish({{"ok", true}});
+    EXPECT_EQ(completions, 1);
+    EXPECT_FALSE(next->completed());
+    requests.stop();
+    EXPECT_EQ(retired, 3);
+    EXPECT_EQ(completions, 2);
+}
+
+TEST_F(PageAnnotationSessionTest, SaveCreatesImmutableDescriptionOnlyPendingRecordWithoutConversation) {
+    start();
+    select();
+    save("Make this easier to find");
+    const auto record = session.snapshot()["records"][0];
+    EXPECT_EQ(record["number"], 1);
+    EXPECT_EQ(record["page_id"], "page-1");
+    EXPECT_EQ(record["document_id"], session.snapshot()["document_id"]);
+    EXPECT_EQ(record["status"], "pending");
+    EXPECT_EQ(record["targets"], Json::array({target()}));
+    EXPECT_EQ(record["differences"], Json::array());
+    EXPECT_TRUE(record["region"].is_null());
+    EXPECT_EQ(session.snapshot()["pending_count"], 1);
+    auto returned = session.snapshot();
+    returned["records"][0]["description"] = "Changed outside owner";
+    EXPECT_EQ(session.snapshot()["records"][0], record);
+    select();
+    save("Second independent request");
+    EXPECT_EQ(session.snapshot()["records"][0], record);
+    EXPECT_EQ(session.snapshot()["records"][1]["number"], 2);
+    EXPECT_NE(session.snapshot()["records"][1]["id"], record["id"]);
+}
+
+TEST_F(PageAnnotationSessionTest, CancelAndExitPreserveSavedRecordsAndDoNotAllocateNumbers) {
+    start();
+    select();
+    save("Saved request");
+    const auto records = session.snapshot()["records"];
+    select();
+    ASSERT_TRUE(prepare(command("cancel")));
+    ASSERT_TRUE(session.complete(session.sequence(), result(), error));
+    EXPECT_EQ(session.snapshot()["records"], records);
+    ASSERT_TRUE(prepare(command("exit")));
+    ASSERT_TRUE(session.complete(session.sequence(), result(false), error));
+    EXPECT_EQ(session.snapshot()["records"], records);
+    EXPECT_EQ(session.snapshot()["active"], false);
+    start();
+    select();
+    save("After reopening");
+    EXPECT_EQ(session.snapshot()["records"][1]["number"], 2);
+}
+
+TEST_F(PageAnnotationSessionTest, HideMarkersAndDiscardAllKeepSessionStateExplicit) {
+    start();
+    select();
+    save("__annotation_description_sentinel__");
+    ASSERT_EQ(session.snapshot()["pending_count"], 1);
+
+    auto hidden = command("hide_markers");
+    hidden["enabled"] = true;
+    ASSERT_TRUE(prepare(hidden)) << error;
+    auto hidden_result = result();
+    hidden_result["markers_hidden"] = true;
+    ASSERT_TRUE(session.complete(session.sequence(), hidden_result, error)) << error;
+    EXPECT_EQ(session.snapshot()["markers_hidden"], true);
+    EXPECT_EQ(session.snapshot()["pending_count"], 1);
+
+    ASSERT_TRUE(prepare(command("discard"))) << error;
+    ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+    EXPECT_EQ(session.snapshot()["markers_hidden"], false);
+    EXPECT_TRUE(session.snapshot()["records"].empty());
+    EXPECT_EQ(session.snapshot()["pending_count"], 0);
+    EXPECT_FALSE(session.has_unsent_work());
+}
+
+TEST_F(PageAnnotationSessionTest, ModalSuspensionIsValidatedAndTracked) {
+    start();
+    select();
+
+    // set_modal_suspended requires a boolean `enabled` field.
+    auto missing = command("set_modal_suspended");
+    EXPECT_FALSE(prepare(missing));
+    auto invalid = command("set_modal_suspended");
+    invalid["enabled"] = "yes";
+    EXPECT_FALSE(prepare(invalid));
+
+    auto suspend = command("set_modal_suspended");
+    suspend["enabled"] = true;
+    ASSERT_TRUE(prepare(suspend)) << error;
+    EXPECT_NE(expression.find("set_modal_suspended"), std::string::npos);
+    EXPECT_NE(expression.find("\"enabled\":true"), std::string::npos);
+    auto suspended_result = result();
+    suspended_result["modal_suspended"] = true;
+    ASSERT_TRUE(session.complete(session.sequence(), suspended_result, error)) << error;
+    EXPECT_EQ(session.snapshot()["modal_suspended"], true);
+
+    auto bad_result_request = command("set_modal_suspended");
+    bad_result_request["enabled"] = false;
+    ASSERT_TRUE(prepare(bad_result_request)) << error;
+    auto non_boolean = result();
+    non_boolean["modal_suspended"] = "true";
+    EXPECT_FALSE(session.complete(session.sequence(), non_boolean, error));
+
+    auto resume = command("set_modal_suspended");
+    resume["enabled"] = false;
+    ASSERT_TRUE(prepare(resume)) << error;
+    auto resumed_result = result();
+    resumed_result["modal_suspended"] = false;
+    ASSERT_TRUE(session.complete(session.sequence(), resumed_result, error)) << error;
+    EXPECT_EQ(session.snapshot()["modal_suspended"], false);
+
+    session.replace_document();
+    EXPECT_EQ(session.snapshot()["modal_suspended"], false);
+}
+
+TEST_F(PageAnnotationSessionTest, TextCommandsBindTargetAndSaveOnlyAcknowledgedActualDifferences) {
+    start();
+    select();
+    auto request = command("preview_text");
+    request["target_id"] = "wrong";
+    request["text"] = "New label";
+    EXPECT_FALSE(prepare(request));
+    request["target_id"] = "target-1";
+    request["text"] = std::string(16385, 'x');
+    EXPECT_FALSE(prepare(request));
+    request["text"] = "New label";
+    ASSERT_TRUE(prepare(request)) << error;
+    EXPECT_NE(expression.find("__acecodePageAnnotationsV1"), std::string::npos);
+    EXPECT_NE(expression.find("New label"), std::string::npos);
+    auto selected = target();
+    selected["text_preview"] = {{"value", "New label"}, {"editable", true}, {"error", ""}};
+    ASSERT_TRUE(session.complete(session.sequence(), result(true, true, selected), error)) << error;
+    request = command("save");
+    request["target_id"] = "target-1";
+    request["description"] = "";
+    ASSERT_TRUE(prepare(request)) << error;
+    auto saved = result();
+    saved["differences"] = Json::array({{{"target_id", "target-1"}, {"property", "text"},
+                                         {"old_value", "Click"}, {"new_value", "New label"}}});
+    ASSERT_TRUE(session.complete(session.sequence(), saved, error)) << error;
+    EXPECT_EQ(session.snapshot()["records"][0]["differences"], saved["differences"]);
+    EXPECT_EQ(session.snapshot()["records"][0]["description"], "");
+    const auto records = session.snapshot()["records"];
+    request = command("original");
+    request["enabled"] = "true";
+    EXPECT_FALSE(prepare(request));
+    request["enabled"] = true;
+    ASSERT_TRUE(prepare(request));
+    auto original = result();
+    original["original"] = true;
+    ASSERT_TRUE(session.complete(session.sequence(), original, error));
+    EXPECT_EQ(session.snapshot()["original"], true);
+    EXPECT_EQ(session.snapshot()["records"], records);
+}
+
+TEST_F(PageAnnotationSessionTest, RejectsMalformedTextDifferencesWithoutCreatingRecord) {
+    start();
+    select();
+    auto request = command("save");
+    request["target_id"] = "target-1";
+    request["description"] = "";
+    const Json valid{{"target_id", "target-1"}, {"property", "text"},
+                     {"old_value", "Click"}, {"new_value", "Changed"}};
+    for (const auto& field : {"target_id", "property", "old_value", "new_value"}) {
+        ASSERT_TRUE(prepare(request));
+        auto saved = result();
+        auto malformed = valid;
+        malformed[field] = 42;
+        saved["differences"] = Json::array({malformed});
+        EXPECT_FALSE(session.complete(session.sequence(), saved, error));
+        EXPECT_EQ(session.snapshot()["pending_count"], 0);
+    }
+    ASSERT_TRUE(prepare(request));
+    auto saved = result();
+    auto unchanged = valid;
+    unchanged["new_value"] = unchanged["old_value"];
+    saved["differences"] = Json::array({unchanged});
+    EXPECT_FALSE(session.complete(session.sequence(), saved, error));
+    EXPECT_EQ(session.snapshot()["pending_count"], 0);
+}
+
+TEST_F(PageAnnotationSessionTest, RejectsArbitraryCapabilitiesAndRecordMutation) {
+    start();
+    for (const auto& action : {"send", "evaluate", "delete", "edit", "write_file", "capture"}) {
+        EXPECT_FALSE(prepare(command(action))) << action;
+    }
+    auto request = command("read");
+    request["script"] = "alert(1)";
+    EXPECT_FALSE(prepare(request));
+    request = command("read");
+    request["description"] = "Unexpected field";
+    EXPECT_FALSE(prepare(request));
+    request = command("cancel");
+    request["target_id"] = "Unexpected target";
+    EXPECT_FALSE(prepare(request));
+    request = command("save");
+    request["description"] = "Not selected";
+    request["target_id"] = "target-1";
+    EXPECT_FALSE(prepare(request));
+    select();
+    request["target_id"] = "another-target";
+    EXPECT_FALSE(prepare(request));
+    request["target_id"] = "target-1";
+    request["description"] = std::string(16385, 'x');
+    EXPECT_FALSE(prepare(request));
+}
+
+TEST_F(PageAnnotationSessionTest, DocumentReplacementRetainsInvalidRecordsAndRejectsLateCallbacks) {
+    start();
+    select();
+    save("Original document");
+    auto old_command = command("read");
+    const auto old_result = result(true, true, target());
+    ASSERT_TRUE(prepare(old_command));
+    const auto old_sequence = session.sequence();
+    session.replace_document();
+    EXPECT_FALSE(session.complete(old_sequence, old_result, error));
+    EXPECT_FALSE(prepare(old_command));
+    EXPECT_EQ(session.snapshot()["records"][0]["valid"], false);
+    EXPECT_EQ(session.snapshot()["active"], false);
+    start();
+    EXPECT_NE(session.snapshot()["document_id"], old_result["document_id"]);
+    select();
+    save("Replacement document");
+    EXPECT_EQ(session.snapshot()["records"][1]["number"], 2);
+}
+
+TEST_F(PageAnnotationSessionTest, StaleRuntimeDocumentResetsSessionAndAllowsStaleStartSnapshot) {
+    start();
+    select();
+    save("Retained after reload");
+    const std::string retired_document = session.document_id();
+    ASSERT_TRUE(prepare(command("read"))) << error;
+
+    const Json stale{{"error", "stale_document"}};
+    ASSERT_TRUE(stale.is_object());
+    ASSERT_TRUE(stale["error"].is_string());
+    EXPECT_TRUE(session.complete(session.sequence(), stale, error)) << error;
+    EXPECT_TRUE(session.document_id().empty());
+    EXPECT_EQ(session.snapshot()["active"], false);
+    EXPECT_EQ(session.snapshot()["records"][0]["valid"], false);
+    EXPECT_EQ(session.snapshot()["records"][0]["invalid_reason"], "document_replaced");
+
+    // The WebUI may still hold the pre-reload snapshot when the user starts
+    // again. Start must establish a fresh generation instead of rejecting it.
+    ASSERT_TRUE(prepare({{"action", "start"}, {"document_id", retired_document}})) << error;
+    EXPECT_NE(session.document_id(), retired_document);
+    ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+    EXPECT_EQ(session.snapshot()["active"], true);
+}
+
+TEST_F(PageAnnotationSessionTest, DocumentLossHelperRecognizesStaleRuntime) {
+    start();
+    const Json stale{{"error", "stale_document"}};
+    EXPECT_TRUE(session.recover_document_loss(stale));
+    EXPECT_TRUE(session.document_id().empty());
+}
+
+TEST_F(PageAnnotationSessionTest, FailedStartValidationDoesNotPoisonDocumentIdentity) {
+    start();
+    const std::string retired_document = session.document_id();
+    session.replace_document();
+
+    const auto sequence = session.sequence();
+    EXPECT_FALSE(prepare({{"action", "start"}}));
+    EXPECT_TRUE(session.document_id().empty());
+    EXPECT_EQ(session.sequence(), sequence);
+
+    ASSERT_TRUE(prepare({{"action", "start"}, {"document_id", retired_document}})) << error;
+    EXPECT_FALSE(session.document_id().empty());
+    EXPECT_NE(session.document_id(), retired_document);
+    ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+    EXPECT_EQ(session.snapshot()["active"], true);
+}
+
+TEST_F(PageAnnotationSessionTest, SerializesCommandsAndDoesNotLetOldFailureReleaseNewOperation) {
+    start();
+    ASSERT_TRUE(prepare(command("read")));
+    const auto old_sequence = session.sequence();
+    EXPECT_FALSE(prepare(command("exit")));
+    session.fail(old_sequence);
+    ASSERT_TRUE(prepare(command("read")));
+    session.fail(old_sequence);
+    EXPECT_FALSE(prepare(command("exit")));
+    EXPECT_FALSE(session.complete(old_sequence, result(), error));
+    EXPECT_TRUE(session.complete(session.sequence(), result(), error));
+}
+
+TEST_F(PageAnnotationSessionTest, MalformedOrUnacknowledgedSaveCannotCreateRecord) {
+    start();
+    select();
+    auto request = command("save");
+    request["description"] = "Never accepted";
+    request["target_id"] = "target-1";
+    ASSERT_TRUE(prepare(request));
+    EXPECT_FALSE(session.complete(session.sequence(), result(true, true, target()), error));
+    EXPECT_EQ(session.snapshot()["pending_count"], 0);
+    for (const auto& malformed : {Json(nullptr), Json::array(), Json{{"error", "stale_target"}}}) {
+        ASSERT_TRUE(prepare(command("read")));
+        EXPECT_FALSE(session.complete(session.sequence(), malformed, error));
+    }
+    auto malformed = result(true, true, target());
+    malformed["target"]["bounds"]["width"] = -1;
+    ASSERT_TRUE(prepare(command("read")));
+    EXPECT_FALSE(session.complete(session.sequence(), malformed, error));
+    malformed = result(false, true, target());
+    ASSERT_TRUE(prepare(command("read")));
+    EXPECT_FALSE(session.complete(session.sequence(), malformed, error));
+    malformed = result();
+    malformed["viewport"]["width"] = "800";
+    ASSERT_TRUE(prepare(command("read")));
+    EXPECT_FALSE(session.complete(session.sequence(), malformed, error));
+}
+
+TEST_F(PageAnnotationSessionTest, MultipleTargetsAndReplacementRegionSaveOneDescriptionAndNumber) {
+    start();
+    select();
+    auto second = target();
+    second["id"] = "target-2";
+    second["tag"] = "section";
+    second["differences"] = Json::array();
+    auto draft = result(true, true, second);
+    draft["targets"] = Json::array({target(), second});
+    ASSERT_TRUE(prepare(command("add_target"))) << error;
+    ASSERT_TRUE(session.complete(session.sequence(), draft, error)) << error;
+    auto select_first = command("select_target");
+    select_first["target_id"] = "target-1";
+    draft["target"] = target();
+    ASSERT_TRUE(prepare(select_first)) << error;
+    ASSERT_TRUE(session.complete(session.sequence(), draft, error)) << error;
+    ASSERT_TRUE(prepare(command("add_region"))) << error;
+    draft["region"] = {{"x", 10}, {"y", 520}, {"width", 100}, {"height", 80}};
+    draft["target"] = nullptr;
+    ASSERT_TRUE(session.complete(session.sequence(), draft, error)) << error;
+    ASSERT_TRUE(prepare(command("add_region"))) << error;
+    draft["region"] = {{"x", 30}, {"y", 900}, {"width", 120}, {"height", 40}};
+    ASSERT_TRUE(session.complete(session.sequence(), draft, error)) << error;
+    auto request = command("save");
+    request["target_id"] = nullptr;
+    request["description"] = "One shared description";
+    ASSERT_TRUE(prepare(request)) << error;
+    EXPECT_EQ(expression.find("One shared description"), std::string::npos);
+    ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+    const auto saved = session.snapshot()["records"];
+    ASSERT_EQ(saved.size(), 1);
+    EXPECT_EQ(saved[0]["number"], 1);
+    EXPECT_EQ(saved[0]["description"], "One shared description");
+    EXPECT_EQ(saved[0]["targets"], draft["targets"]);
+    EXPECT_EQ(saved[0]["region"], draft["region"]);
+    EXPECT_EQ(saved[0]["differences"], Json::array());
+    select();
+    ASSERT_TRUE(prepare(command("cancel")));
+    ASSERT_TRUE(session.complete(session.sequence(), result(), error));
+    EXPECT_EQ(session.snapshot()["records"], saved);
+    EXPECT_TRUE(session.snapshot()["targets"].empty());
+    EXPECT_TRUE(session.snapshot()["region"].is_null());
+}
+
+TEST_F(PageAnnotationSessionTest, RejectsMalformedTargetArraysRegionsAndForeignIdentity) {
+    start();
+    select();
+    for (const auto& targets : {Json(nullptr), Json::object(), Json::array({target(), target()}),
+                               Json::array({Json("target-1")}), Json(std::vector(65, target()))}) {
+        auto malformed = result(true, true, target());
+        malformed["targets"] = targets;
+        ASSERT_TRUE(prepare(command("read")));
+        EXPECT_FALSE(session.complete(session.sequence(), malformed, error));
+    }
+    for (const auto& region : {Json::array(), Json{{"x", -1}, {"y", 2}, {"width", 3}, {"height", 4}},
+         Json{{"x", 1}, {"y", 2}, {"width", 0}, {"height", 4}},
+         Json{{"x", 1}, {"y", 2}, {"width", 3}, {"height", "4"}},
+         Json{{"x", 1}, {"y", 2}, {"width", 3}, {"height", 4}, {"script", "send()"}},
+         Json{{"x", 1}, {"y", 10000001}, {"width", 3}, {"height", 4}}}) {
+        auto malformed = result(true, true, target());
+        malformed["region"] = region;
+        ASSERT_TRUE(prepare(command("read")));
+        EXPECT_FALSE(session.complete(session.sequence(), malformed, error));
+    }
+    auto request = command("select_target");
+    request["target_id"] = "target-2";
+    EXPECT_FALSE(prepare(request));
+    EXPECT_FALSE(prepare(command("select_region")));
+    EXPECT_FALSE(session.prepare("page-2", command("read"), expression, error));
+    request = command("save");
+    request["target_id"] = "target-1";
+    request["description"] = "Stale membership";
+    request["target_ids"] = Json::array({"target-1", "target-1"});
+    EXPECT_FALSE(prepare(request));
+    request["target_ids"] = Json::array({"target-1"});
+    request["region"] = {{"x", 0}, {"y", 0}, {"width", 1}, {"height", 1}};
+    EXPECT_FALSE(prepare(request));
+    EXPECT_TRUE(session.snapshot()["records"].empty());
+}
+
+TEST_F(PageAnnotationSessionTest, StyleCommandsAreRestrictedToTheActiveExactTargetAndDocument) {
+    start();
+    auto request = command("preview_style");
+    request["target_id"] = "target-1";
+    request["styles"] = {{"color", "blue"}};
+    EXPECT_FALSE(prepare(request));
+    select();
+    request["target_id"] = "another-target";
+    EXPECT_FALSE(prepare(request));
+    request["target_id"] = "target-1";
+    for (const auto& styles : {Json{{"position", "fixed"}}, Json{{"color", "red; width:999px"}},
+                              Json{{"color", 1}}, Json{{"width", std::string(257, 'x')}},
+                              Json{{"color|background-color", "red"}}, Json::array()}) {
+        request["styles"] = styles;
+        EXPECT_FALSE(prepare(request)) << styles;
+    }
+    request["styles"] = {{"width", "200px"}};
+    request["ratio_lock"] = "true";
+    EXPECT_FALSE(prepare(request));
+    request["ratio_lock"] = true;
+    ASSERT_TRUE(prepare(request)) << error;
+    EXPECT_NE(expression.find("\"ratio_lock\":true"), std::string::npos);
+    EXPECT_NE(expression.find("CSSStyleSheet"), std::string::npos);
+    auto stale = result(true, true, target());
+    stale["target"]["id"] = "another-target";
+    EXPECT_FALSE(session.complete(session.sequence(), stale, error));
+    ASSERT_TRUE(prepare(request));
+    ASSERT_TRUE(session.complete(session.sequence(), result(true, true, target()), error));
+}
+
+TEST_F(PageAnnotationSessionTest, SavesAcknowledgedActualStyleDifferencesAsImmutableRecords) {
+    start();
+    select();
+    const Json differences = Json::array({{{"target_id", "target-1"}, {"property", "color"},
+        {"old_value", "rgb(255, 0, 0)"}, {"new_value", "rgb(0, 0, 255)"}}});
+    auto request = command("preview_style");
+    request["target_id"] = "target-1";
+    request["styles"] = {{"color", "blue"}};
+    ASSERT_TRUE(prepare(request));
+    auto preview = result(true, true, target());
+    preview["differences"] = differences;
+    ASSERT_TRUE(session.complete(session.sequence(), preview, error));
+    EXPECT_EQ(session.snapshot()["differences"], differences);
+    request = command("save");
+    request["description"] = "";
+    request["target_id"] = "target-1";
+    ASSERT_TRUE(prepare(request));
+    auto saved = result();
+    saved["differences"] = differences;
+    ASSERT_TRUE(session.complete(session.sequence(), saved, error));
+    EXPECT_EQ(session.snapshot()["records"][0]["differences"], differences);
+    EXPECT_EQ(session.snapshot()["differences"], Json::array());
+    const auto record = session.snapshot()["records"][0];
+    select();
+    ASSERT_TRUE(prepare(command("cancel")));
+    ASSERT_TRUE(session.complete(session.sequence(), result(), error));
+    EXPECT_EQ(session.snapshot()["records"][0], record);
+}
+
+TEST_F(PageAnnotationSessionTest, RejectsNoOpUnknownAndForeignDifferencesWithoutAllocatingPins) {
+    start();
+    select();
+    auto request = command("save");
+    request["description"] = "";
+    request["target_id"] = "target-1";
+    const Json difference{{"target_id", "target-1"}, {"property", "width"},
+                          {"old_value", "100px"}, {"new_value", "200px"}};
+    for (const auto& alteration : {Json{{"target_id", "foreign"}}, Json{{"property", "script"}},
+                                   Json{{"new_value", "100px"}}, Json{{"old_value", 100}}}) {
+        auto malformed = result();
+        auto changed = difference;
+        changed.update(alteration);
+        malformed["differences"] = Json::array({changed});
+        ASSERT_TRUE(prepare(request));
+        EXPECT_FALSE(session.complete(session.sequence(), malformed, error));
+        EXPECT_EQ(session.snapshot()["pending_count"], 0);
+    }
+    save("First real record");
+    EXPECT_EQ(session.snapshot()["records"][0]["number"], 1);
+}
+
+TEST_F(PageAnnotationSessionTest, OriginalToggleIsIndependentOfModeAndRetainsRecordsAndPins) {
+    start();
+    select();
+    save("Saved");
+    const auto records = session.snapshot()["records"];
+    ASSERT_TRUE(prepare(command("exit")));
+    ASSERT_TRUE(session.complete(session.sequence(), result(false), error));
+    auto request = command("original");
+    EXPECT_FALSE(prepare(request));
+    request["enabled"] = true;
+    ASSERT_TRUE(prepare(request));
+    auto comparison = result(false);
+    comparison["original"] = true;
+    ASSERT_TRUE(session.complete(session.sequence(), comparison, error));
+    EXPECT_EQ(session.snapshot()["original"], true);
+    EXPECT_EQ(session.snapshot()["records"], records);
+    request["enabled"] = false;
+    ASSERT_TRUE(prepare(request));
+    EXPECT_FALSE(session.complete(session.sequence(), comparison, error));
+    ASSERT_TRUE(prepare(request));
+    ASSERT_TRUE(session.complete(session.sequence(), result(false), error));
+    EXPECT_EQ(session.snapshot()["original"], false);
+    EXPECT_EQ(session.snapshot()["records"], records);
+    session.replace_document();
+    EXPECT_EQ(session.snapshot()["original"], false);
+    EXPECT_EQ(session.snapshot()["differences"], Json::array());
+}
+
+TEST_F(PageAnnotationSessionTest, RemoveErasesExactlyTheNamedRecordsAndSurvivesDocumentReplacement) {
+    start();
+    select();
+    save("First");
+    const auto first = session.snapshot()["records"][0];
+    select();
+    save("Second");
+    auto request = command("remove");
+    request["record_ids"] = Json::array({first["id"]});
+    std::vector removed;
+    ASSERT_TRUE(session.submission(request, error, &removed)) << error;
+    EXPECT_EQ(removed, std::vector{1});
+    auto snapshot = session.snapshot();
+    EXPECT_EQ(snapshot["records"].size(), 1);
+    EXPECT_EQ(snapshot["records"][0]["description"], "Second");
+    // 发送那一刻文档换了也不影响删除:已发出去的记录不能留在待发集合里复活。
+    session.replace_document();
+    auto late = command("remove");
+    late["record_ids"] = Json::array({snapshot["records"][0]["id"]});
+    ASSERT_TRUE(session.submission(late, error, &removed)) << error;
+    EXPECT_EQ(removed, std::vector{2});
+    EXPECT_EQ(session.snapshot()["records"], Json::array());
+    EXPECT_EQ(session.snapshot()["pending_count"], 0);
+}
+
+TEST_F(PageAnnotationSessionTest, RemovePinsRuntimeCommandCarriesDocumentIdentity) {
+    const auto payload = page_annotation_remove_pins_payload("page:document:1", {1, 3});
+    EXPECT_EQ(payload["action"], "remove_pins");
+    EXPECT_EQ(payload["document_id"], "page:document:1");
+    EXPECT_EQ(payload["numbers"], Json::array({1, 3}));
+}
+
+TEST_F(PageAnnotationSessionTest, HostSubmissionReportsRemovedNumbersForPinCleanup) {
+    start();
+    select();
+    save("First");
+    select();
+    save("Second");
+    const auto records = session.snapshot()["records"];
+    Json ids = Json::array();
+    for (const auto& record : records) ids.push_back(record["id"]);
+    auto request = command("remove");
+    request["record_ids"] = ids;
+
+    std::vector removed_numbers;
+    std::string updated;
+    std::string completion;
+    ASSERT_TRUE(annotation_host_submission(
+        session, "page-1", request,
+        [&](std::string result) { completion = std::move(result); },
+        [&](std::string snapshot) { updated = std::move(snapshot); },
+        [&](const std::vector& numbers) { removed_numbers = numbers; }));
+    const auto response = Json::parse(completion);
+    ASSERT_EQ(response["ok"], true) << completion;
+    EXPECT_EQ(removed_numbers, std::vector({1, 2}));
+    ASSERT_FALSE(updated.empty());
+    EXPECT_TRUE(Json::parse(updated)["records"].empty());
+    EXPECT_TRUE(response["annotations"]["records"].empty());
+}
+
+TEST_F(PageAnnotationSessionTest, SubmissionRejectsUnknownMembershipAndRetiredLeaseActions) {
+    start();
+    select();
+    save("Retain me");
+    const auto before = session.snapshot();
+    auto request = command("remove");
+    const auto id = before["records"][0]["id"];
+    for (const auto& ids : {Json::array(), Json::array({"absent"}), Json::array({id, id}), Json::array({id, "absent"})}) {
+        request["record_ids"] = ids;
+        EXPECT_FALSE(session.submission(request, error));
+        EXPECT_EQ(session.snapshot(), before);
+    }
+    request["record_ids"] = Json::array({id});
+    request["text"] = "Untrusted model input";
+    EXPECT_FALSE(session.submission(request, error));
+    request.erase("text");
+    // 发送链路只剩 remove / attach_screenshot:批次的 capture / validate /
+    // acknowledge / release 已删除,不再被接受。
+    for (const auto* retired : {"capture", "validate", "acknowledge", "release"}) {
+        auto stale = request;
+        stale["action"] = retired;
+        EXPECT_FALSE(session.submission(stale, error)) << retired;
+    }
+    request["document_id"] = "other-document";
+    EXPECT_TRUE(session.submission(request, error)) << error;
+    EXPECT_EQ(session.snapshot()["records"], Json::array());
+}
+
+TEST_F(PageAnnotationSessionTest, LifecycleReportsAreAtomicDocumentBoundAndSticky) {
+    start(); select(); save("Retain");
+    const auto before = session.snapshot();
+    for (const auto& numbers : {Json::array({0}), Json::array({1, 1}), Json::array({"1"}), Json::array({1, 2})}) {
+        EXPECT_FALSE(session.observe_lifecycle({{"document_id", session.document_id()}, {"invalid_numbers", numbers}}));
+        EXPECT_EQ(session.snapshot(), before);
+    }
+    EXPECT_FALSE(session.observe_lifecycle({{"document_id", "wrong"}, {"invalid_numbers", Json::array({1})}}));
+    EXPECT_TRUE(session.observe_lifecycle({{"document_id", session.document_id()}, {"invalid_numbers", Json::array({1})}}));
+    EXPECT_EQ(session.snapshot()["records"][0]["valid"], false);
+    EXPECT_EQ(session.snapshot()["records"][0]["invalid_reason"], "target_removed");
+    EXPECT_TRUE(session.observe_lifecycle({{"document_id", session.document_id()}, {"invalid_numbers", Json::array()}}));
+    EXPECT_EQ(session.snapshot()["records"][0]["valid"], false);
+}
+
+TEST_F(PageAnnotationSessionTest, NavigationReservationBlocksRemovalWhileRecordsOutliveTheDocument) {
+    start(); select(); save("Retain");
+    auto request = command("remove");
+    request["record_ids"] = Json::array({session.snapshot()["records"][0]["id"]});
+    ASSERT_TRUE(session.navigation.reserve());
+    EXPECT_FALSE(prepare(command("start")));
+    EXPECT_FALSE(session.submission(request, error));
+    session.navigation.finish();
+    session.replace_document();
+    EXPECT_TRUE(session.submission(request, error)) << error;
+    EXPECT_EQ(session.snapshot()["records"], Json::array());
+    EXPECT_EQ(session.snapshot()["pending_count"], 0);
+}
+
+TEST_F(PageAnnotationSessionTest, NavigationSuspendsOldCallbacksWithoutDiscardingRecordsOnFailure) {
+    start(); select(); save("Retain");
+    ASSERT_TRUE(prepare(command("read")));
+    const auto old = session.sequence();
+    const auto response = result();
+    ASSERT_TRUE(session.navigation.reserve());
+    ASSERT_TRUE(session.navigation.arm());
+    ASSERT_TRUE(session.navigation.start());
+    session.suspend();
+    EXPECT_FALSE(session.complete(old, response, error));
+    EXPECT_FALSE(prepare(command("read")));
+    session.navigation.finish();
+    EXPECT_EQ(session.snapshot()["records"][0]["valid"], true);
+    ASSERT_TRUE(prepare(command("read")));
+    EXPECT_TRUE(session.complete(session.sequence(), result(), error));
+    ASSERT_TRUE(prepare(command("read")));
+    EXPECT_TRUE(session.complete(session.sequence(), {{"error", "replaced_document"}}, error));
+    EXPECT_EQ(session.snapshot()["records"][0]["valid"], false);
+    EXPECT_EQ(session.snapshot()["pending_count"], 1);
+    EXPECT_TRUE(session.document_id().empty());
+}
+
+} // namespace
+} // namespace acecode::desktop
diff --git a/tests/desktop/page_annotation_text_smoke.mjs b/tests/desktop/page_annotation_text_smoke.mjs
new file mode 100644
index 000000000..bb55cf420
--- /dev/null
+++ b/tests/desktop/page_annotation_text_smoke.mjs
@@ -0,0 +1,85 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const binary = process.argv[2];
+assert.ok(binary, 'Usage: node tests/desktop/page_annotation_text_smoke.mjs ');
+const source = fs.readFileSync(new URL('../../src/apps/desktop/page_annotation_text_runtime.hpp', import.meta.url), 'utf8');
+const factory = source.split('R"ACETEXT(')[1].split(')ACETEXT"')[0];
+const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ace-annotation-text-'));
+try {
+  const fixture = path.join(directory, 'fixture.html');
+  fs.writeFileSync(fixture, `
+
+
NOT RUN
+`, 'utf8'); + const result = spawnSync(binary, ['--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check', + `--user-data-dir=${path.join(directory, 'profile')}`, '--dump-dom', pathToFileURL(fixture).href], + {encoding:'utf8', timeout:45000, windowsHide:true, maxBuffer:2 * 1024 * 1024}); + assert.ifError(result.error); + assert.equal(result.status, 0, result.stderr); + const outcome = result.stdout.match(/
([\s\S]*?)<\/pre>/)?.[1];
+  assert.ok(outcome?.startsWith('PASS:'), outcome || result.stdout || result.stderr);
+  console.log(outcome);
+} finally {
+  const relative = path.relative(fs.realpathSync(os.tmpdir()), fs.realpathSync(directory));
+  assert.ok(relative && !relative.startsWith('..') && !path.isAbsolute(relative) && path.basename(directory).startsWith('ace-annotation-text-'));
+  fs.rmSync(directory, {recursive:true, force:true, maxRetries:10, retryDelay:200});
+}
diff --git a/tests/desktop/session_annotation_store_test.cpp b/tests/desktop/session_annotation_store_test.cpp
new file mode 100644
index 000000000..58133973b
--- /dev/null
+++ b/tests/desktop/session_annotation_store_test.cpp
@@ -0,0 +1,355 @@
+#include 
+
+#include 
+#include 
+
+#include "desktop/page_annotation_session.hpp"
+#include "desktop/session_annotation_store.hpp"
+
+namespace acecode::desktop {
+namespace {
+
+using Json = nlohmann::json;
+
+// 记录归属会话(Q33)的存储契约:标识与文档无关(D9)、编号按页签分组、
+// 丢弃只作用于本页签、页签析构不影响记录。
+class SessionAnnotationStoreTest : public testing::Test {
+protected:
+    struct Driver {
+        explicit Driver(std::shared_ptr shared, std::string page)
+            : store(std::move(shared)), page_id(std::move(page)), session(store) {}
+
+        Json command(const std::string& action) const {
+            Json request{{"action", action}, {"document_id", session.snapshot()["document_id"]}};
+            if (action == "save") {
+                request["target_ids"] = annotation_target_ids(session.snapshot()["targets"]);
+                request["region"] = session.snapshot()["region"];
+            }
+            return request;
+        }
+
+        Json result(bool active = true, bool popup = false, Json target = nullptr) const {
+            return {{"document_id", session.snapshot()["document_id"]},
+                    {"active", active}, {"popup", popup}, {"target", target},
+                    {"original", false}, {"differences", Json::array()},
+                    {"targets", target.is_null() ? Json::array() : Json::array({target})},
+                    {"region", nullptr}, {"selection_mode", nullptr},
+                    {"viewport", {{"width", 800}, {"height", 600}, {"scroll_x", 0}, {"scroll_y", 0}}}};
+        }
+
+        Json target() const {
+            return {{"id", "target-1"}, {"tag", "button"}, {"text", "Click"},
+                    {"locator", "button#target"},
+                    {"bounds", {{"x", 10}, {"y", 20}, {"width", 80}, {"height", 30}}}};
+        }
+
+        void start() {
+            ASSERT_TRUE(session.prepare(page_id, command("start"), expression, error)) << error;
+            ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+        }
+
+        void select() {
+            ASSERT_TRUE(session.prepare(page_id, command("read"), expression, error)) << error;
+            ASSERT_TRUE(session.complete(session.sequence(), result(true, true, target()), error)) << error;
+        }
+
+        void save(const std::string& description) {
+            auto request = command("save");
+            request["description"] = description;
+            request["target_id"] = "target-1";
+            ASSERT_TRUE(session.prepare(page_id, request, expression, error)) << error;
+            ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+        }
+
+        void discard() {
+            ASSERT_TRUE(session.prepare(page_id, command("discard"), expression, error)) << error;
+            ASSERT_TRUE(session.complete(session.sequence(), result(), error)) << error;
+        }
+
+        std::shared_ptr store;
+        std::string page_id;
+        PageAnnotationSession session;
+        std::string expression;
+        std::string error;
+    };
+};
+
+TEST_F(SessionAnnotationStoreTest, RecordIdentityDoesNotEmbedDocumentGeneration) {
+    auto store = std::make_shared();
+    Driver driver(store, "page-1");
+    driver.start();
+    driver.select();
+    driver.save("first");
+    const auto document = driver.session.snapshot()["document_id"];
+    driver.select();
+    driver.save("second");
+
+    const auto& records = store->records("page-1");
+    ASSERT_EQ(records.size(), 2u);
+    // 标识 = :annotation:,不含 document_id / epoch(D9)。
+    EXPECT_EQ(records[0]["id"], "page-1:annotation:1");
+    EXPECT_EQ(records[1]["id"], "page-1:annotation:2");
+    EXPECT_EQ(records[0]["page_id"], "page-1");
+    EXPECT_EQ(records[0]["document_id"], document);
+    EXPECT_EQ(records[0]["id"].get().find(":document:"), std::string::npos);
+
+    // 文档替换后仍能按同一编号继续,且旧记录不被删除——旧实现会把它们清空。
+    driver.session.replace_document();
+    driver.start();
+    driver.select();
+    driver.save("third");
+    const auto& after = store->records("page-1");
+    ASSERT_EQ(after.size(), 3u);
+    EXPECT_EQ(after[2]["id"], "page-1:annotation:3");
+    EXPECT_NE(after[2]["document_id"], document);
+    EXPECT_EQ(after[0]["id"], "page-1:annotation:1");
+}
+
+TEST_F(SessionAnnotationStoreTest, NumberingIsIndependentPerPage) {
+    auto store = std::make_shared();
+    Driver a(store, "page-a");
+    Driver b(store, "page-b");
+    a.start();
+    a.select();
+    a.save("a-first");
+    a.select();
+    a.save("a-second");
+    b.start();
+    b.select();
+    b.save("b-first");
+
+    EXPECT_EQ(store->records("page-a").size(), 2u);
+    EXPECT_EQ(store->records("page-b").size(), 1u);
+    EXPECT_EQ(store->next_number("page-a"), 3u);
+    EXPECT_EQ(store->next_number("page-b"), 2u);
+    // 每个页签的编号都从 1 开始,和旧实现(每页一个计数器)等价。
+    EXPECT_EQ(store->records("page-b")[0]["id"], "page-b:annotation:1");
+    EXPECT_EQ(store->records("page-b")[0]["number"], 1);
+    // 快照只暴露本页签的记录,页签之间互不可见。
+    EXPECT_EQ(a.session.snapshot()["records"].size(), 2u);
+    EXPECT_EQ(b.session.snapshot()["records"].size(), 1u);
+}
+
+TEST_F(SessionAnnotationStoreTest, DiscardClearsOnlyTheDiscardingPage) {
+    auto store = std::make_shared();
+    Driver a(store, "page-a");
+    Driver b(store, "page-b");
+    a.start();
+    a.select();
+    a.save("a-first");
+    b.start();
+    b.select();
+    b.save("b-first");
+
+    a.discard();
+    EXPECT_EQ(store->records("page-a").size(), 0u);
+    EXPECT_EQ(store->next_number("page-a"), 1u);
+    EXPECT_EQ(store->records("page-b").size(), 1u);
+    EXPECT_EQ(store->next_number("page-b"), 2u);
+
+    // 丢弃后编号确实从 1 重来,不会和旧记录撞 id。
+    a.select();
+    a.save("a-again");
+    ASSERT_EQ(store->records("page-a").size(), 1u);
+    EXPECT_EQ(store->records("page-a")[0]["id"], "page-a:annotation:1");
+}
+
+TEST_F(SessionAnnotationStoreTest, RecordsOutliveThePageThatWroteThem) {
+    auto store = std::make_shared();
+    {
+        Driver driver(store, "page-1");
+        driver.start();
+        driver.select();
+        driver.save("survives");
+    }
+    // 页签对象销毁(关页签)后记录仍在 store 里——这是 orphan 语义的前提。
+    ASSERT_EQ(store->records("page-1").size(), 1u);
+    EXPECT_EQ(store->records("page-1")[0]["description"], "survives");
+    EXPECT_EQ(store->records("page-1")[0]["status"], "pending");
+}
+
+TEST_F(SessionAnnotationStoreTest, EraseDropsOneRecordAndBumpsRevision) {
+    auto store = std::make_shared();
+    Driver driver(store, "page-1");
+    driver.start();
+    driver.select();
+    driver.save("keep");
+    driver.select();
+    driver.save("drop");
+
+    const auto before = store->revision();
+    EXPECT_FALSE(store->erase("page-1", "page-1:annotation:404"));
+    EXPECT_EQ(store->revision(), before);
+    EXPECT_TRUE(store->erase("page-1", "page-1:annotation:2"));
+    EXPECT_GT(store->revision(), before);
+    ASSERT_EQ(store->records("page-1").size(), 1u);
+    EXPECT_EQ(store->records("page-1")[0]["description"], "keep");
+    // 下一号从仍存活的记录重算;已发出/删除的最高号不再抬高新记录。
+    EXPECT_EQ(store->next_number("page-1"), 2u);
+    store->append("page-1", {{"document_id", driver.session.document_id()},
+                             {"description", "replacement"}, {"targets", Json::array()},
+                             {"differences", Json::array()}, {"region", nullptr},
+                             {"status", "pending"}, {"valid", true}});
+    EXPECT_EQ(store->records("page-1").back()["id"], "page-1:annotation:2");
+}
+
+TEST_F(SessionAnnotationStoreTest, SnapshotIsServedByTheStoreNotTheTab) {
+    auto store = std::make_shared();
+    Driver driver(store, "page-1");
+    driver.start();
+    ASSERT_TRUE(driver.session.snapshot()["records"].empty());
+
+    // 直接改存储(不经过页签的任何命令),快照必须跟着变——存储是权威(#210)。
+    store->append("page-1", {{"document_id", driver.session.document_id()},
+                             {"description", "poked"}, {"targets", Json::array()},
+                             {"differences", Json::array()}, {"region", nullptr},
+                             {"status", "pending"}, {"valid", true}});
+    const auto snapshot = driver.session.snapshot();
+    ASSERT_EQ(snapshot["records"].size(), 1u);
+    EXPECT_EQ(snapshot["records"][0]["description"], "poked");
+    EXPECT_EQ(snapshot["pending_count"], 1);
+}
+
+TEST_F(SessionAnnotationStoreTest, AttachScreenshotStoresThumbnailAndPageShot) {
+    auto store = std::make_shared();
+    Driver driver(store, "page-1");
+    driver.start();
+    driver.select();
+    driver.save("needs a picture");
+    const auto id = store->records("page-1")[0]["id"].get();
+
+    std::string error;
+    ASSERT_TRUE(driver.session.submission({
+        {"action", "attach_screenshot"}, {"document_id", ""}, {"record_id", id},
+        {"thumbnail", "data:image/png;base64,AAA"},
+        {"page_shot", "data:image/png;base64,BBB"},
+    }, error)) << error;
+    const auto snapshot = driver.session.snapshot();
+    EXPECT_EQ(snapshot["page_shot"], "data:image/png;base64,BBB");
+    EXPECT_EQ(store->records("page-1")[0]["thumbnail"], "data:image/png;base64,AAA");
+
+    // 只更新整屏图时不动记录上的缩略图(每页只留最新一张)。
+    ASSERT_TRUE(driver.session.submission({
+        {"action", "attach_screenshot"}, {"document_id", ""},
+        {"page_shot", "data:image/png;base64,CCC"},
+    }, error)) << error;
+    EXPECT_EQ(driver.session.snapshot()["page_shot"], "data:image/png;base64,CCC");
+    EXPECT_EQ(store->records("page-1")[0]["thumbnail"], "data:image/png;base64,AAA");
+
+    // 非 image data URL、超过体积上限、未知记录都要拒绝。
+    EXPECT_FALSE(driver.session.submission({
+        {"action", "attach_screenshot"}, {"document_id", ""}, {"record_id", id},
+        {"thumbnail", "https://evil.invalid/x.png"},
+    }, error));
+    EXPECT_FALSE(driver.session.submission({
+        {"action", "attach_screenshot"}, {"document_id", ""}, {"record_id", "page-1:annotation:404"},
+        {"thumbnail", "data:image/png;base64,AAA"},
+    }, error));
+}
+
+TEST_F(SessionAnnotationStoreTest, RemoveErasesRecordsWithoutDocumentCheck) {
+    auto store = std::make_shared();
+    Driver driver(store, "page-1");
+    driver.start();
+    driver.select();
+    driver.save("keep");
+    driver.select();
+    driver.save("sent");
+    const auto sent = store->records("page-1")[1]["id"].get();
+
+    std::string error;
+    // 文档代传空也能删:发送成功后清理不该被「这一刻文档刚好换了」挡住。
+    ASSERT_TRUE(driver.session.submission({
+        {"action", "remove"}, {"document_id", ""}, {"record_ids", Json::array({sent})},
+    }, error)) << error;
+    ASSERT_EQ(store->records("page-1").size(), 1u);
+    EXPECT_EQ(store->records("page-1")[0]["description"], "keep");
+
+    EXPECT_FALSE(driver.session.submission({
+        {"action", "remove"}, {"document_id", ""},
+        {"record_ids", Json::array({"page-1:annotation:404"})},
+    }, error));
+}
+
+TEST_F(SessionAnnotationStoreTest, RemovingAllSentRecordsRestartsNumberingAtOne) {
+    auto store = std::make_shared();
+    Driver driver(store, "page-1");
+    driver.start();
+    for (int index = 1; index <= 3; ++index) {
+        driver.select();
+        driver.save("sent-" + std::to_string(index));
+    }
+    ASSERT_EQ(driver.session.snapshot()["pending_count"], 3);
+    EXPECT_EQ(store->next_number("page-1"), 4u);
+
+    Json ids = Json::array();
+    for (const auto& record : store->records("page-1")) ids.push_back(record["id"]);
+    std::string error;
+    ASSERT_TRUE(driver.session.submission({
+        {"action", "remove"}, {"document_id", ""}, {"record_ids", ids},
+    }, error)) << error;
+    ASSERT_TRUE(store->records("page-1").empty());
+    EXPECT_EQ(store->next_number("page-1"), 1u);
+
+    driver.select();
+    driver.save("new round");
+    ASSERT_EQ(store->records("page-1").size(), 1u);
+    EXPECT_EQ(store->records("page-1")[0]["id"], "page-1:annotation:1");
+    EXPECT_EQ(store->records("page-1")[0]["number"], 1);
+}
+
+// 铅笔路径(#217):改的是同一条记录,不新增、编号不变。
+TEST_F(SessionAnnotationStoreTest, EditRecordUpdatesTheSameRecordInPlace) {
+    auto store = std::make_shared();
+    Driver driver(store, "page-1");
+    driver.start();
+    driver.select();
+    driver.save("first");
+
+    Json request{{"action", "edit_record"},
+                 {"document_id", driver.session.document_id()},
+                 {"record_id", "page-1:annotation:1"}};
+    ASSERT_TRUE(driver.session.prepare("page-1", request, driver.expression, driver.error))
+        << driver.error;
+    // 回页面后 popup 必须打开、目标必须被重新选中,否则这次编辑没有落点。
+    ASSERT_TRUE(driver.session.complete(driver.session.sequence(),
+        driver.result(true, true, driver.target()), driver.error)) << driver.error;
+    const auto popup = driver.session.snapshot();
+    EXPECT_EQ(popup["draft_description"], "first");
+    EXPECT_EQ(popup["editing_record_id"], "page-1:annotation:1");
+
+    auto save = driver.command("save");
+    save["description"] = "edited";
+    save["target_id"] = "target-1";
+    ASSERT_TRUE(driver.session.prepare("page-1", save, driver.expression, driver.error)) << driver.error;
+    ASSERT_TRUE(driver.session.complete(driver.session.sequence(),
+        driver.result(true, false), driver.error)) << driver.error;
+
+    const auto& records = store->records("page-1");
+    ASSERT_EQ(records.size(), 1u);
+    EXPECT_EQ(records[0]["id"], "page-1:annotation:1");
+    EXPECT_EQ(records[0]["number"], 1);
+    EXPECT_EQ(records[0]["description"], "edited");
+    EXPECT_EQ(driver.session.snapshot()["editing_record_id"], "");
+}
+
+// 目标已失效的记录不能回页面改:调用方要退化成「只改文字」。
+TEST_F(SessionAnnotationStoreTest, EditRecordRejectsStaleRecords) {
+    auto store = std::make_shared();
+    Driver driver(store, "page-1");
+    driver.start();
+    driver.select();
+    driver.save("first");
+    driver.session.replace_document();
+    // 刷新后重新进入批注模式:文档代是新的,旧记录属于上一代。
+    driver.start();
+
+    Json request{{"action", "edit_record"},
+                 {"document_id", driver.session.document_id()},
+                 {"record_id", "page-1:annotation:1"}};
+    EXPECT_FALSE(driver.session.prepare("page-1", request, driver.expression, driver.error));
+    EXPECT_EQ(driver.error, "Annotation target is invalid");
+}
+
+} // namespace
+} // namespace acecode::desktop
diff --git a/tests/test_support/desktop/agent_browser_capture_probe.hpp b/tests/test_support/desktop/agent_browser_capture_probe.hpp
new file mode 100644
index 000000000..b7e5a6294
--- /dev/null
+++ b/tests/test_support/desktop/agent_browser_capture_probe.hpp
@@ -0,0 +1,176 @@
+#pragma once
+
+#include "tool/agent_browser/cdp_client.hpp"
+#include "test_support/desktop/agent_browser_capture_probe_command.hpp"
+
+#ifdef _WIN32
+#include 
+#include 
+#include 
+#else
+#import 
+#endif
+
+#include 
+#include 
+
+namespace acecode::desktop::capture_probe {
+
+inline bool green_bottom_pixel(const std::vector& bytes) {
+#ifdef _WIN32
+    struct ComScope {
+        HRESULT result = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
+        ~ComScope() { if (SUCCEEDED(result)) CoUninitialize(); }
+    } com_scope;
+    if (FAILED(com_scope.result) && com_scope.result != RPC_E_CHANGED_MODE) return false;
+    Microsoft::WRL::ComPtr factory;
+    Microsoft::WRL::ComPtr stream;
+    Microsoft::WRL::ComPtr decoder;
+    Microsoft::WRL::ComPtr frame;
+    Microsoft::WRL::ComPtr converter;
+    if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER,
+            IID_PPV_ARGS(&factory))) || FAILED(factory->CreateStream(&stream)) ||
+        FAILED(stream->InitializeFromMemory(const_cast(bytes.data()),
+            static_cast(bytes.size()))) ||
+        FAILED(factory->CreateDecoderFromStream(stream.Get(), nullptr,
+            WICDecodeMetadataCacheOnLoad, &decoder)) ||
+        FAILED(decoder->GetFrame(0, &frame)) ||
+        FAILED(factory->CreateFormatConverter(&converter)) ||
+        FAILED(converter->Initialize(frame.Get(), GUID_WICPixelFormat32bppRGBA,
+            WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom))) return false;
+    UINT width = 0, height = 0;
+    if (FAILED(converter->GetSize(&width, &height)) || width < 2 || height < 20) return false;
+    WICRect rect{static_cast(width / 2), static_cast(height - 10), 1, 1};
+    std::array pixel{};
+    return SUCCEEDED(converter->CopyPixels(&rect, 4, 4, pixel.data())) &&
+        pixel[0] < 10 && pixel[1] > 245 && pixel[2] < 10 && pixel[3] > 245;
+#else
+    NSData* data = [NSData dataWithBytes:bytes.data() length:bytes.size()];
+    NSBitmapImageRep* image = [NSBitmapImageRep imageRepWithData:data];
+    if (!image || image.pixelsWide < 2 || image.pixelsHigh < 20) return false;
+    NSColor* color = [[image colorAtX:image.pixelsWide / 2 y:image.pixelsHigh - 10]
+        colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]];
+    return color && color.redComponent < 0.04 && color.greenComponent > 0.96 &&
+        color.blueComponent < 0.04 && color.alphaComponent > 0.96;
+#endif
+}
+
+inline bool run(agent_browser::AgentBrowserCdpClient& client, std::string& error) {
+    using namespace std::chrono_literals;
+    const auto require_object = [&error](const nlohmann::json& result,
+                                        const char* message) {
+        return capture_probe::require_object(result, error, message);
+    };
+    const auto evaluate = [&client, &error, &require_object](const std::string& expression) {
+        const auto result = checked_command(client, "Runtime.evaluate", {{"expression", expression},
+            {"awaitPromise", true}, {"returnByValue", true}}, 10s, error);
+        if (!require_object(result, "evaluate returned a non-object result")) return nlohmann::json();
+        const auto remote = result.find("result");
+        if (remote == result.end() || !require_object(*remote, "evaluate returned no remote object")) {
+            if (error.empty()) error = "evaluate returned no remote object";
+            return nlohmann::json();
+        }
+        if (!remote->contains("value")) {
+            error = "evaluate returned no value";
+            return nlohmann::json();
+        }
+        return (*remote)["value"];
+    };
+    const auto fixture = evaluate(R"JS((async () => {
+        document.documentElement.style.cssText = 'margin:0;padding:0;border:0;overflow:auto';
+        document.body.style.cssText = 'margin:0;padding:0;border:0;max-width:none';
+        const height = Math.max(2400, innerHeight * 3);
+        document.body.innerHTML = '
'; + scrollTo(0, 100); + await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + return {height, scroll:scrollY, viewport:innerHeight, width:innerWidth, + client:document.documentElement.clientWidth, + clientHeight:document.documentElement.clientHeight, sheets:document.styleSheets.length, + rootStyle:document.documentElement.getAttribute('style'), + bodyStyle:document.body.getAttribute('style')}; + })())JS"); + if (!require_object(fixture, "evaluate returned no fixture")) return false; + for (const auto* field : {"height", "scroll", "viewport", "width", "client", "clientHeight", "sheets"}) { + if (!fixture.contains(field) || !fixture[field].is_number_unsigned()) { + error = "evaluate returned invalid fixture dimensions"; + return false; + } + } + for (const auto* field : {"rootStyle", "bodyStyle"}) { + if (!fixture.contains(field) || !fixture[field].is_string()) { + error = "evaluate returned invalid fixture styles"; + return false; + } + } + const auto viewport = checked_command(client, "Page.captureScreenshot", {{"format", "png"}}, + 20s, error); + if (!require_object(viewport, "viewport capture returned a non-object result")) return false; + if (!viewport.contains("data") || !viewport["data"].is_string()) { + error = "viewport capture returned no PNG data"; + return false; + } + const auto viewport_bytes = agent_browser::decode_agent_browser_base64(viewport["data"].get()); + const auto viewport_size = viewport_bytes + ? agent_browser::agent_browser_png_dimensions(*viewport_bytes) : std::nullopt; + if (!error.empty() || !viewport_size) { error = "viewport capture failed"; return false; } + const auto full = checked_command(client, "Page.captureScreenshot", {{"fullPage", true}}, + 20s, error); + if (!require_object(full, "full-page capture returned a non-object result")) return false; + if (!full.contains("data") || !full["data"].is_string() || + !full.contains("fullPage") || !full["fullPage"].is_boolean() || + !full.contains("documentId") || !full["documentId"].is_string()) { + error = "full-page capture returned invalid metadata"; + return false; + } + const auto bytes = agent_browser::decode_agent_browser_base64(full["data"].get()); + const auto size = bytes ? agent_browser::agent_browser_png_dimensions(*bytes) : std::nullopt; + if (!error.empty() || !size || full.value("fullPage", false) != true || + size->second != fixture["height"].get() || + size->second <= fixture["viewport"].get() || !green_bottom_pixel(*bytes)) { + if (error.empty()) error = "full-page PNG did not contain the beyond-viewport green pixels"; + return false; + } + const auto after = evaluate(R"JS(({scroll:scrollY, viewport:innerHeight, width:innerWidth, + client:document.documentElement.clientWidth, + clientHeight:document.documentElement.clientHeight, sheets:document.styleSheets.length, + rootStyle:document.documentElement.getAttribute('style'), + bodyStyle:document.body.getAttribute('style')}))JS"); + if (!require_object(after, "evaluate returned no post-capture state")) return false; + for (const auto* field : {"scroll", "viewport", "width", "client", "clientHeight", + "sheets", "rootStyle", "bodyStyle"}) { + if (!after.contains(field) || after[field] != fixture[field]) { + error = "full-page capture changed layout, viewport, scroll or styles"; + return false; + } + } + client.command("Page.captureScreenshot", {{"fullPage", true}, {"documentId", "stale-document"}}, + 20s, nullptr, error); + if (error != "capture_document_changed") { + if (error.empty()) error = "stale document capture was not rejected"; + return false; + } + error.clear(); + evaluate("document.body.firstElementChild.style.height = '40000px'"); + if (!error.empty()) return false; + client.command("Page.captureScreenshot", {{"fullPage", true}}, 20s, nullptr, error); + if (error != "capture_resource_limit") { + if (error.empty()) error = "oversized capture was not rejected"; + return false; + } + error.clear(); + evaluate("document.body.firstElementChild.style.height = '" + + std::to_string(fixture["height"].get() - 100) + "px'"); + if (!error.empty()) return false; + const auto retry = checked_command(client, "Page.captureScreenshot", {{"fullPage", true}, + {"documentId", full.at("documentId")}}, 20s, error); + if (!require_object(retry, "retry capture returned a non-object result")) return false; + if (!retry.contains("fullPage") || !retry["fullPage"].is_boolean() || + !retry["fullPage"].get()) { + error = "retry capture did not return a full-page image"; + return false; + } + return true; +} + +} diff --git a/tests/test_support/desktop/agent_browser_capture_probe_command.hpp b/tests/test_support/desktop/agent_browser_capture_probe_command.hpp new file mode 100644 index 000000000..132888864 --- /dev/null +++ b/tests/test_support/desktop/agent_browser_capture_probe_command.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include + +#include +#include + +namespace acecode::desktop::capture_probe { + +inline bool require_object(const nlohmann::json& result, std::string& error, + const char* message) { + if (!error.empty()) return false; + if (result.is_object()) return true; + error = message; + return false; +} + +template +nlohmann::json checked_command(Client& client, const std::string& method, + const nlohmann::json& params, + std::chrono::milliseconds timeout, std::string& error) { + auto result = client.command(method, params, timeout, nullptr, error); + if (!require_object(result, error, "native command returned a non-object result")) return {}; + return result; +} + +} diff --git a/tests/web/web_server_smoke_test.cpp b/tests/web/web_server_smoke_test.cpp index bef70e9d0..e5513878b 100644 --- a/tests/web/web_server_smoke_test.cpp +++ b/tests/web/web_server_smoke_test.cpp @@ -52,6 +52,8 @@ #include "session/attachment_store.hpp" #include "session/pasted_text_attachment.hpp" #include "session/session_manager.hpp" +#include "session/session_serializer.hpp" +#include "session/request_context_record.hpp" #include "session/session_pin_store.hpp" #include "session_host/session_registry.hpp" #include "session_host/session_auto_title.hpp" @@ -7236,6 +7238,66 @@ TEST(WebServerHttp, TrajectoryRouteProjectsInactiveLegacySession) { // 场景:POST /api/sessions/:id/messages 只负责把输入交给 daemon 的 // AgentLoop 入队,不依赖当前 WebSocket 连接是否还绑定该会话。 +// 批注消息与普通消息走同一条路径:没有批次标识、没有回执、没有对账分支。 +TEST(WebServerHttp, PostMessageQueuesAnnotationTextWithClientMessageId) { + WebServerFixture fx; + auto create = cpr::Post(cpr::Url{fx.url("/api/sessions")}, + cpr::Header{{"Content-Type", "application/json"}}, cpr::Body{R"({})"}); + ASSERT_EQ(create.status_code, 201) << create.text; + const auto session_id = json::parse(create.text)["session_id"].get(); + auto entry = fx.registry->acquire(session_id); + ASSERT_NE(entry, nullptr); + acecode::ChatMessage context; + context.role = "user"; + context.uuid = "annotation-http-context"; + context.is_meta = true; + context.subtype = acecode::kRequestContextSnapshot; + context.content = R"( + +Shell sandbox: read-only + +)"; + context.metadata = {{"request_context_version", 1}, + {"context_state", {{"execution", "Shell sandbox: read-only"}}}}; + entry->loop->push_message(context); + entry->sm->on_message(context); + const auto url = fx.url("/api/sessions/" + session_id + "/messages"); + const json payload{{"text", "annotation changes"}, + {"client_message_id", "annotation-client-1"}}; + const auto queued = cpr::Post(cpr::Url{url}, + cpr::Header{{"Content-Type", "application/json"}}, cpr::Body{payload.dump()}); + ASSERT_EQ(queued.status_code, 202) << queued.text; + const auto receipt = json::parse(queued.text); + EXPECT_TRUE(receipt["queued"].get()); + EXPECT_FALSE(receipt.contains("annotation_batch_id")); + + int user_messages = 0; + bool context_seen = false; + const auto deadline = std::chrono::steady_clock::now() + 10s; + while (std::chrono::steady_clock::now() < deadline) { + const auto response = cpr::Get(cpr::Url{url}); + ASSERT_EQ(response.status_code, 200) << response.text; + user_messages = 0; + const auto body = json::parse(response.text); + for (const auto& message : body["messages"]) { + const auto record = acecode::deserialize_message_json(message); + if (record.uuid == context.uuid) { + EXPECT_TRUE(acecode::is_request_context_record(record)); + context_seen = true; + } + if (!acecode::is_real_user_message(record)) continue; + ++user_messages; + EXPECT_EQ(message.value("content", ""), "annotation changes"); + ASSERT_TRUE(record.metadata.is_object()); + EXPECT_EQ(record.metadata.value("client_message_id", ""), "annotation-client-1"); + } + if (user_messages != 0) break; + std::this_thread::sleep_for(20ms); + } + EXPECT_EQ(user_messages, 1); + EXPECT_TRUE(context_seen); +} + TEST(WebServerHttp, PostMessageQueuesInputInDaemonSession) { WebServerFixture fx; auto post = cpr::Post(cpr::Url{fx.url("/api/sessions")}, diff --git a/web/check-copy.mjs b/web/check-copy.mjs new file mode 100644 index 000000000..cfca77181 --- /dev/null +++ b/web/check-copy.mjs @@ -0,0 +1,20 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { collectStaticCopy } from './scripts/i18n-audit.mjs'; +import { sourceCatalogs } from './src/i18n/sourceCatalog.generated.js'; +import { OPAQUE_STATIC_COPY } from './src/i18n/sourceAllowlist.js'; +const cat = new Set(Object.values(sourceCatalogs['zh-CN'])); +const opaque = new Set(OPAQUE_STATIC_COPY); +const files = []; +(function walk(d) { + for (const e of fs.readdirSync(d, { withFileTypes: true })) { + const t = path.join(d, e.name); + if (e.isDirectory()) walk(t); + else if (/\.(js|jsx)$/.test(e.name)) files.push(t); + } +})('src'); +for (const f of files) { + for (const r of collectStaticCopy(fs.readFileSync(f, 'utf8'), f)) { + if (!cat.has(r.text) && !opaque.has(r.text)) console.log(`${f}:${r.line} ${JSON.stringify(r.text)}`); + } +} diff --git a/web/package.json b/web/package.json index 432677dab..903057395 100644 --- a/web/package.json +++ b/web/package.json @@ -7,6 +7,7 @@ "scripts": { "dev": "vite", "test": "node src/lib/runTests.js", + "test:annotations:browser": "node src/lib/pageAnnotationStyles.browser.test.js", "i18n:audit": "node scripts/i18n-audit.mjs", "i18n:catalog": "node scripts/generate-source-catalog.mjs", "sync:provider-logos": "node scripts/sync-provider-logos.mjs", diff --git a/web/scripts/i18n-en-overrides.mjs b/web/scripts/i18n-en-overrides.mjs index 78689790b..c17d30860 100644 --- a/web/scripts/i18n-en-overrides.mjs +++ b/web/scripts/i18n-en-overrides.mjs @@ -4,6 +4,125 @@ export const ENGLISH_SOURCE_OVERRIDES = Object.freeze({ '选区': 'Region', '已将选区添加到聊天': 'Region added to chat', '移除选区引用': 'Remove region reference', + '可见文本': 'Visible text', + '恢复预览': 'Restore preview', + '查看原图': 'View original', + '文字颜色': 'Text color', + '背景颜色': 'Background color', + '不透明度': 'Opacity', + '字体': 'Font family', + '字号': 'Font size', + '字重': 'Font weight', + '圆角': 'Corner radius', + '边框颜色': 'Border color', + '边框宽度': 'Border width', + '字间距': 'Letter spacing', + '词间距': 'Word spacing', + '间隙': 'Gap', + '内边距': 'Padding', + '上内边距': 'Top padding', + '右内边距': 'Right padding', + '下内边距': 'Bottom padding', + '左内边距': 'Left padding', + '外边距': 'Margin', + '上外边距': 'Top margin', + '右外边距': 'Right margin', + '下外边距': 'Bottom margin', + '左外边距': 'Left margin', + '上': 'Top', + '底部': 'Bottom', + '左': 'Left', + '右': 'Right', + '锁定宽高比例': 'Lock width-height ratio', + '调整': 'Adjust', + '添加评论...': 'Add a comment...', + '描述这些更改...': 'Describe these changes...', + '添加批注': 'Add annotation', + '正在批注': 'Annotating', + '正在批注 · {{p0}}': 'Annotating · {{p0}}', + '移动工具栏': 'Move toolbar', + '目标标签': 'Target tag', + '丢弃当前草稿': 'Discard current draft', + '丢弃批注': 'Discard annotations', + '丢弃所有待处理标注?': 'Discard all pending annotations?', + '页面上的所有编辑都将被移除': 'All edits on this page will be removed', + '放弃后所有标记和修改都被清空': 'Discarding removes every marker and edit', + '放弃': 'Discard', + '截取屏幕截图': 'Take screenshot', + '隐藏标记': 'Hide markers', + '按住查看原始页面': 'Hold to view original page', + '已复制截图': 'Screenshot copied', + '网页截图失败': 'Page screenshot failed', + '当前桌面版本不支持网页批注截图': 'This desktop version does not support page annotation screenshots', + '无法复制截图': 'Could not copy the screenshot', + '选择元素': 'Select element', + '区域 1': 'Region 1', + '{{p0}}色板': '{{p0}} swatch', + '{{p0}}选项': '{{p0}} options', + '恢复{{p0}}': 'Reset {{p0}}', + '收起{{p0}}': 'Collapse {{p0}}', + '展开{{p0}}': 'Expand {{p0}}', + '行间距': 'Row gap', + '列间距': 'Column gap', + 'Enter 添加 · Ctrl+Enter 发送': 'Enter to add · Ctrl+Enter to send', + '原始页面': 'Original page', + '原内联 !important 阻止预览:': 'Original inline !important blocks the preview:', + '高度': 'Height', + '宽度': 'Width', + '样式': 'Styles', + '发送批注': 'Send annotations', + '发送中': 'Sending', + '批注页面不可用': 'The annotated page is unavailable', + '请先选择对话': 'Select a conversation first', + '请切回发送批注的对话后重试': 'Switch back to the original conversation to retry', + '没有可发送的批注': 'No annotations to send', + '批注目标已失效': 'An annotation target is no longer valid', + '批注目标已失效,请重新选择元素后再发送': 'The annotated target is no longer valid. Reselect the element and send again.', + // 会话级待发批注(卡片 / 发送条 / 编辑弹窗 / 已发卡片) + '待发批注': 'Pending annotations', + '待发批注 {{p0}} 条': 'Pending annotations ({{p0}})', + '{{p0}} 条': '{{p0}} items', + '未命名页面': 'Untitled page', + '页面已关闭': 'Page closed', + '页面': 'Page', + '(未填写描述)': '(No description)', + '编辑第 {{p0}} 条批注': 'Edit annotation {{p0}}', + '删除第 {{p0}} 条批注': 'Delete annotation {{p0}}', + '删除这条': 'Delete this annotation', + '{{p0}} · 页面已关闭,只能修改文字': '{{p0}} · Page closed, only the description can be edited', + '{{p0}} · 目标已失效,只能修改文字': '{{p0}} · The target is no longer valid, only the description can be edited', + '这一页已经不再打开了,只能修改文字': 'This page is no longer open. Only the description can be edited.', + '无法回到该页面': 'Could not return to that page', + '目标:{{p0}}': 'Target: {{p0}}', + '查看{{p0}}截屏': 'View {{p0}} screenshot', + '还有 {{p0}} 条': '{{p0}} more', + '发送 {{p0}} 条批注': 'Send {{p0}} annotations', + '发送 {{p0}}': 'Send {{p0}}', + '丢弃当前页面的批注?': 'Discard annotations on this page?', + '这一页的所有编辑都将被移除': 'Every marker and edit on this page will be removed', + '其他页签的待发批注不受影响': 'Pending annotations on other tabs are unaffected', + '请先打开一个对话再发送批注': 'Open a conversation before sending annotations', + '发送未确认,批注已退回待发,可重试': 'Send unconfirmed. The annotations are back in the pending list; retry when ready.', + '没有收到发送确认,消息可能仍在发送中': 'No send confirmation arrived. The message may still be on its way.', + '批注未发出,仍在待发列表里,可重试': 'The annotations were not sent and stay in the pending list; retry when ready.', + '截图解码失败': 'Could not decode the screenshot', + '无法读取网页批注,正在重试': 'Could not read page annotations. Retrying.', + '网页内容已变化,请重新批注后再发送': 'The page content changed. Annotate again before sending.', + '截图正在进行中,请稍后再试': 'A capture is in progress. Try again shortly.', + '整页截图与批注文档不匹配': 'The full-page capture does not match the annotated document', + '截图上传未返回附件标识': 'The image upload did not return an attachment ID', + '尚未收到批注接收回执,请重试': 'Annotation acceptance is unconfirmed. Retry to check.', + '退出网页批注': 'Exit page annotations', + '退出批注模式': 'Exit annotation mode', + '网页批注': 'Page annotations', + '待发送': 'Pending', + '无法读取网页批注,请退出后重试': 'Could not read page annotations. Exit and try again.', + '网页批注操作失败': 'Page annotation operation failed', + '关闭批注': 'Close annotation', + '批注描述': 'Annotation description', + '描述修改要求': 'Describe the requested change', + '保存批注': 'Save annotation', + '当前桌面版本不支持网页批注': 'This desktop version does not support page annotations', '已存在的链接': 'Existing links', '打开可交互会话会消耗共享用户的token额度。': "Enabling interactive sessions consumes the sharing user's token allowance.", '持有链接即可访问,仅限可信局域网。提问消耗你的模型额度。': 'Anyone with the link can access this session. Use trusted local networks only. Questions use your model allowance.', @@ -70,6 +189,7 @@ export const ENGLISH_SOURCE_OVERRIDES = Object.freeze({ '展开摘要面板': 'Show summary panel', '调整摘要面板宽度': 'Resize summary panel', '拖动调整摘要面板宽度': 'Drag to resize the summary panel', + '拖动批注框': 'Drag annotation card', '复制文件路径': 'Copy file path', '查看输出': 'View output', '查看实时输出': 'View live output', @@ -1479,6 +1599,8 @@ export const ENGLISH_SOURCE_OVERRIDES = Object.freeze({ '{{p0}} 号批注位置,共 {{p1}} 条批注': 'Annotation marker {{p0}}, {{p1}} annotations', '批注 {{p0}},原文已变化': 'Annotation {{p0}}, source text changed', '批注 {{p0}}': 'Annotation {{p0}}', + '文本超出可编辑上限,或该内容不可见': 'Text exceeds the editable limit or is not visible content', + '文本节点已变化,请取消后重新选择元素': 'Text nodes changed; cancel and select the element again', '{{p0}} · 原文已变化': '{{p0}} · Source text changed', '添加能力或上下文': 'Add capability or context', // 蜂群模式分星型 / 网状(openspec add-mesh-swarm-mode) @@ -2635,6 +2757,21 @@ export const ENGLISH_SOURCE_OVERRIDES = Object.freeze({ '花瓣': 'Petals', '像素小人': 'Pixel characters', 'subagent sub-agent agent avatar portrait icon style petal flower geometric pixel 子代理 智能体 头像 图标 花瓣 几何图形 像素小人': 'subagent sub-agent agent avatar portrait icon style petal flower geometric pixel', + '批注目标': 'Annotation targets', + '{{p0}} 条注释': '{{p0}} comments', + '宽高': 'dimensions', + '垂直值': 'vertical values', + '水平值': 'horizontal values', + '锁定': 'Lock', + '解锁': 'Unlock', + '锁定{{p0}}{{p1}}': 'Lock {{p0}} {{p1}}', + '解锁{{p0}}{{p1}}': 'Unlock {{p0}} {{p1}}', + '解锁宽高比例': 'Unlock width and height ratio', + '发送批注': 'Send annotation', + '添加元素': 'Add element', + '添加区域': 'Add region', + '替换区域': 'Replace region', + '区域': 'Region', '排队': 'Queue', '输入框': 'Composer', '显示预测消息': 'Show predicted messages', diff --git a/web/src/components/AgentBrowserPanel.jsx b/web/src/components/AgentBrowserPanel.jsx index 1f69a1eb5..3f94ca38d 100644 --- a/web/src/components/AgentBrowserPanel.jsx +++ b/web/src/components/AgentBrowserPanel.jsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { clsx } from '../lib/format.js'; import { AGENT_BROWSER_STATE_EVENT, @@ -27,6 +27,7 @@ import { failedNativeSurfaceOcclusionSignature, nativeSurfaceOcclusionRectsFromClientRects, nativeSurfaceLayoutWithOcclusionFallback, + nativeSurfaceInteractionBlockedByDocument, nativeSurfaceOverlayGeometryByDocument, nativeSurfaceShouldShow, nativeSurfaceSupportsLocalOcclusion, @@ -35,6 +36,12 @@ import { } from '../lib/agentBrowserSurfaceCoordinator.js'; import { AgentBrowserMoreMenu } from './AgentBrowserMoreMenu.jsx'; import { AgentBrowserNewTab } from './AgentBrowserNewTab.jsx'; +import { PageAnnotationPopup, usePageAnnotations } from './PageAnnotations.jsx'; +import { PageAnnotationSendBar } from './PageAnnotationSendBar.jsx'; +import { annotationOutboxFor } from '../lib/annotationOutbox.js'; +import { capturePageAnnotationScreenshot } from '../lib/pageAnnotations.js'; +import { captureRectForRecord, cropAnnotationImages } from '../lib/annotationCapture.js'; +import { registerAnnotationEditor } from '../lib/annotationEdit.js'; import { NavigationArrowIcon, RefreshIcon, VsIcon } from './Icon.jsx'; import { toast } from './Toast.jsx'; @@ -59,6 +66,8 @@ const INITIAL_STATE = Object.freeze({ export function AgentBrowserPanel({ pageId, + api, + sessionId, agentActive = false, surfaceEnabled = true, onAddContext, @@ -75,6 +84,69 @@ export function AgentBrowserPanel({ const [address, setAddress] = useState(''); const nativePageVisible = agentBrowserShowsNativePage(state); const surface = agentBrowserSurfacePresentation(state); + const annotations = usePageAnnotations(pageId, state.page_id === pageId ? state.annotations : null); + const annotationPageBackground = useMemo(() => { + if (!annotations.snapshot?.active) return undefined; + const value = String(annotations.snapshot.page_background || '').trim(); + if (!value) return undefined; + const supports = globalThis.CSS?.supports; + if (typeof supports === 'function' && !supports.call(globalThis.CSS, 'color', value)) return undefined; + return value; + }, [annotations.snapshot?.active, annotations.snapshot?.page_background]); + // 记录归会话(Q33):页签只把快照上报到会话级待发箱,关掉时降级为 orphan 而不是删除。 + const annotationOutbox = useMemo(() => annotationOutboxFor(sessionId, api), [sessionId, api]); + useEffect(() => { + if (!annotationOutbox) return; + const closed = state.closed === true; + annotationOutbox.observe({ + pageId, + url: state.url, + title: state.title, + closed, + snapshot: closed ? null : annotations.snapshot, + }); + }, [annotationOutbox, pageId, state.url, state.title, state.closed, annotations.snapshot]); + // 保存后补图(#212):记录数一涨就说明刚存了一条,截一次视口、裁两张图回填。 + // 放在面板而不是保存命令里,是因为捕获是异步的,且失败不能阻塞保存。 + const captureStateRef = useRef({ pageId: '', count: 0 }); + useEffect(() => { + const snapshot = annotations.snapshot; + const records = Array.isArray(snapshot?.records) ? snapshot.records : []; + const previous = captureStateRef.current; + captureStateRef.current = { pageId, count: records.length }; + if (previous.pageId !== pageId || records.length <= previous.count) return undefined; + const record = records[records.length - 1]; + let cancelled = false; + void (async () => { + try { + const result = await capturePageAnnotationScreenshot(pageId); + if (cancelled || result?.ok !== true) return; + const rect = captureRectForRecord(record, snapshot.viewport); + const images = await cropAnnotationImages(result.data, rect, snapshot.viewport); + if (cancelled) return; + await annotations.command('attach_screenshot', { + record_id: record.id, + thumbnail: images.thumbnail, + page_shot: images.pageShot, + }); + } catch { + // 捕获失败只是该条无图,卡片退化为标签 + 文本片段。 + } + })(); + return () => { cancelled = true; }; + }, [pageId, annotations, annotations.snapshot]); + // 铅笔路径(#217):切到这一页,按 locator 重新选中那条记录。annotations + // 每次渲染都是新对象,用 ref 保证注册表只挂一次。 + const annotationsRef = useRef(annotations); + annotationsRef.current = annotations; + useEffect(() => { + if (!sessionId || !annotations.snapshot?.document_id) return undefined; + return registerAnnotationEditor(pageId, async (record) => { + const selected = await selectAgentBrowserPage(pageId); + if (selected?.ok === false) return selected; + return annotationsRef.current.command('edit_record', { record_id: record.id }); + }); + }, [pageId, sessionId, annotations.snapshot?.document_id]); useEffect(() => { let cancelled = false; @@ -138,6 +210,8 @@ export function AgentBrowserPanel({ scale, visible, ); + desiredLayout.interaction_blocked = !forceHidden && + nativeSurfaceInteractionBlockedByDocument(surfaceRect, document, window); desiredLayout.occlusion_rects = visible && supportsLocalOcclusion ? nativeSurfaceOcclusionRectsFromClientRects( surfaceRect, @@ -263,7 +337,10 @@ export function AgentBrowserPanel({ attributeFilter: [ 'aria-hidden', 'class', + 'data-ace-native-interaction', 'data-ace-native-overlay', + 'data-ace-native-overlay-bleed', + 'data-ace-native-overlay-square', 'hidden', 'style', ], @@ -450,13 +527,24 @@ export function AgentBrowserPanel({
+
-
+
+ {nativePageVisible && annotations.snapshot.popup && ( + { + annotationOutbox?.observe({ + pageId, + url: state.url, + title: state.title, + snapshot: next, + }); + }} + /> + )} + {surface.kind === 'empty' && (
+ {annotations.error && ( +
+ {annotations.error && {annotations.error}} +
+ )}
); } diff --git a/web/src/components/ChatView.jsx b/web/src/components/ChatView.jsx index 2fe538dc3..b5141909a 100644 --- a/web/src/components/ChatView.jsx +++ b/web/src/components/ChatView.jsx @@ -61,6 +61,15 @@ import { } from '../lib/composerAttachmentReservations.js'; import { InputBar } from './InputBar.jsx'; import { normalizeComposerPayload } from '../lib/composerSubmission.js'; +import { annotationOutboxFor } from '../lib/annotationOutbox.js'; +import { + annotationSendOutcome, localizedAnnotationSendError, prepareAnnotationSubmission, + registerAnnotationSubmitter, +} from '../lib/annotationSubmission.js'; +import { PageAnnotationPendingCard } from './PageAnnotationPendingCard.jsx'; +import { PageAnnotationEditDialog } from './PageAnnotationEditDialog.jsx'; +import { requestAnnotationEdit } from '../lib/annotationEdit.js'; +import { runPageAnnotationCommand } from '../lib/pageAnnotations.js'; import { uploadComposerAttachment } from '../lib/composerAttachmentUpload.js'; import InteractiveHomeLogo from './InteractiveHomeLogo.jsx'; import { SelectionActionPopover } from './SelectionActionPopover.jsx'; @@ -190,7 +199,8 @@ import { createPendingActionGuard } from '../lib/pendingActionGuard.js'; import { homeComposerDraft } from '../lib/homeComposerDrafts.js'; import { appendComposerText, composerContentAttachments, composerContentFromText, composerContentSignature, - composerContentText, normalizeComposerContent, reconcileComposerContentAttachments, + composerContentSubmissionText, composerContentText, normalizeComposerContent, + reconcileComposerContentAttachments, } from '../lib/composerContent.js'; import { inlineVisualSendText } from '../lib/inlineVisualFrame.js'; import { openExternalUrl } from '../lib/externalUrl.js'; @@ -660,6 +670,10 @@ const EXPERT_SWITCH_CANONICAL_POLL_ATTEMPTS = 6; const EXPERT_SWITCH_CANONICAL_POLL_INTERVAL_MS = 160; const FORK_ACTION_KEY = 'fork-session'; +const EMPTY_ANNOTATION_STATE = Object.freeze({ + revision: 0, records: Object.freeze([]), pages: Object.freeze([]), pendingCount: 0, +}); + export function ChatView({ titleTarget, actionsTarget, children, sessionRef, sessionId, homeLogoEffectEnabled = true, homeIntentSuggestions = [], onHomeIntentPrompt, homeComposerDrafts = {}, homeComposerAttentionRequest = 0, onHomeComposerDraftLoad, onHomeComposerDraftChange, onHomeComposerDraftAccepted, onHomeComposerDraftPatch, modelProfileRevision = 0, onSessionPromoted, onSessionExpertChanged, onHomeWorkspaceChange, onCommandWorkspaceChange, onConsoleCwdChange, onFindInConversation, onOpenModelSettings, health, autoFocusOnDesktopWindowFocus = false, onPermissionRequest, onQuestionRequest, permissionRequests = [], onPermissionDecision, questionRequest, onQuestionResolve, onPermissionModeChanged, onSubagentTasksChange, recentExpertIds = [], onRememberExpert, onInitialDraftConsumed, showSidePanel = false, responsiveSidebars = null, rightPanelPopupWidth, onRightPanelPopupResize, sidePanelWidth = 280, onSidePanelResize, previewPanelWidth = 640, previewPanelAutoFit = false, onPreviewPanelResize, onPreviewPanelVisibleChange, onRegisterPreviewLeaveGuard, sidePanelCollapsed = false, sidePanelListCollapsed = false, onToggleSidePanel, onRevealPreviewPanel, onToggleSidePanelList, onRevealSidePanelList, sidePanelMaximized = false, onToggleSidePanelMaximized, previewPresenting = false, onTogglePreviewPresentation, showAceCodeAvatar = false, showSessionTime = true, messageAutoCollapse = true, followUpPrompts = true, busySendMode = 'steer', summaryPanelWidth, onSummaryPanelResize, onEditWorkspace, summaryPanelOpen = false, onToggleSummaryPanel, nativeSurfacesVisible = true }) { const ref = useMemo(() => normalizeSessionRef(sessionRef, sessionId), [sessionRef, sessionId]); const sid = ref?.sessionId || ref?.id || ''; @@ -3670,19 +3684,37 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses // sendMode:'send'(Enter / 发送按钮)、'queue'(Ctrl+Enter,回复中排到回合结束)、 // 'fork'(Ctrl+Alt+Enter,在分叉出的新会话里发送)。 - const submit = useStableCallback((text, { sendMode = 'send' } = {}) => { - if (sessionRuntimeUnavailable) return; + const submit = useStableCallback((text, { sendMode = 'send', + extraAttachments = null, extraContexts = null, annotationSettle = null, + } = {}) => { + let annotationStatus = ''; + const settleAnnotations = (status) => { + if (annotationStatus || !annotationSettle) return; + annotationStatus = status; + annotationSettle(status); + }; + const fail = (error = '发送失败') => { + settleAnnotations('failed'); + return { ok: false, error }; + }; + if (sessionRuntimeUnavailable) return fail(); // 这个会话还在创建 / 建 worktree:遮罩出现之前也不接受第二次发送。 - if (sessionStartMask.isBlocking()) return; + if (sessionStartMask.isBlocking()) return fail(); const submittedContent = reconcileComposerContentAttachments(composerContentRef.current, composerAttachments); - const activeAttachments = submittedContent ? composerContentAttachments(submittedContent, composerAttachments, { sessionId: sid }) : composerAttachments; + const activeAttachments = [ + ...(submittedContent + ? composerContentAttachments(submittedContent, composerAttachments, { sessionId: sid }) + : composerAttachments), + ...(Array.isArray(extraAttachments) ? extraAttachments : []), + ]; if (activeAttachments.some((item) => item.error || (!item.id && !item.pending_upload && !item.uploading))) { - toast({ kind: 'err', text: tr('composerAttachment.stagedUnavailable') }); - return; + const message = tr('composerAttachment.stagedUnavailable'); + toast({ kind: 'err', text: message }); + return fail(message); } if (activeAttachments.some((item) => item.uploading)) { toast({ kind: 'err', text: '附件仍在上传,请稍后发送' }); - return; + return fail('附件仍在上传,请稍后发送'); } const pendingAttachmentLocalIds = activeAttachments .filter((item) => item?.pending_upload && item?.local_id) @@ -3693,8 +3725,9 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses ); const hasPendingAttachments = pendingAttachmentLocalIds.length > 0; if (pendingAttachmentFiles.length !== pendingAttachmentLocalIds.length) { - toast({ kind: 'err', text: tr('composerAttachment.stagedUnavailable') }); - return; + const message = tr('composerAttachment.stagedUnavailable'); + toast({ kind: 'err', text: message }); + return fail(message); } if (sid && hasPendingAttachments) { const pendingItems = activeAttachments.filter((item) => item?.pending_upload && item?.local_id); @@ -3703,17 +3736,19 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses // 暂存组已不在(例如从首页草稿带过来)时按保留的 File 直接上传。 if (!commitDeferredPastes()) uploadPasteReservations(pendingAttachmentFiles); toast({ kind: 'info', text: '粘贴的文本正在上传,完成后请再发送' }); - return; + return fail('粘贴的文本正在上传,完成后请再发送'); } toast({ kind: 'err', text: tr('composerAttachment.uploadRequired') }); - return; + return fail(tr('composerAttachment.uploadRequired')); } const payload = normalizeComposerPayload( text, activeAttachments, - composerContexts, + [...composerContexts, ...(Array.isArray(extraContexts) ? extraContexts : [])], swarmModeForSubmission(composerSwarmChoice, transcriptSwarmMode), - submittedContent, + // 批注正文已经由 prepareAnnotationSubmission 合并进 text。旧的空 + // composer_content 会让服务端用空编辑器正文覆盖它,导致 400。 + annotationSettle ? null : submittedContent, ); // 提交那一刻输入框里的原文。发送回执回来时拿它比对,用户在等待窗口里 // 写下的下一条就不会被这次发送的清理吞掉。 @@ -3722,13 +3757,13 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses const hasExtras = payloadHasExtras(payload) || hasPendingAttachments; const hasSwarmMode = typeof payload.swarm_mode === 'string'; if (!payload.text.trim() && !hasExtras) { - if (!retryUserMessageId || composerSubmitting || retrySubmissionRef.current) return; + if (!retryUserMessageId || composerSubmitting || retrySubmissionRef.current) return fail(); const latest = transcript.getState(); const latestRetryId = trailingUserMessageRetryId({ ...latest, sessionId: sid, loadState: transcriptLoadState, disabled: readOnlyExternalSession || sessionRuntimeUnavailable, }); - if (latestRetryId !== retryUserMessageId) return; + if (latestRetryId !== retryUserMessageId) return fail(); const request = { sessionId: sid }; retrySubmissionRef.current = request; setComposerSubmitting(true); @@ -3745,7 +3780,7 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses setComposerSubmitting(false); restoreChatInputFocusSoon(false); }); - return; + return { ok: false, error: '发送失败' }; } const route = inputRouteForPayload(payload); if (route.kind === 'paste_too_long') { @@ -3755,12 +3790,16 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses kind: 'err', text: `粘贴的文本太长,超出 /${route.command} 的上限(${route.limitBytes} 字节)。去掉命令可作为普通消息发送,或缩短内容`, }); - return; + return fail(); } const historyText = inputHistoryTextForPayload(payload); if (sendMode === 'fork' && route.kind === 'message') { + if (annotationSettle) return fail(); sendInForkedSession({ payload, historyText, submittedComposerText, submittedComposerContent }); - return; + return { ok: true }; + } + if (annotationSettle && route.kind !== 'message') { + return fail(); } if (route.kind === 'desktop_feedback') { if (!sid) { @@ -4008,7 +4047,7 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses }); return; } - if (composerSubmitting) return; + if (composerSubmitting) return fail(); // 用户再次主动发送 / 排队 = 解除「中断回合」带来的队列暂停:这条新消息先走, // 排队里的旧消息在它之后照常出队(与卡片栈上的「继续」同义)。 const liveTranscript = transcript.getState(); @@ -4021,6 +4060,7 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses // Ctrl+Enter = 排到回合结束。设置里「后续消息处理方式」选排队时两者对调(busySendAction)。 // 正在停止时只能排队。 const queuedId = enqueueInput(payload); + if (!queuedId) return fail(); const steerTurnId = String(liveTranscript.activeTurnId || activeTurnId || ''); const steer = busySendAction(sendMode, busySendMode) === 'steer'; if (queuedId && steer && liveTranscript.busy && !liveTranscript.abortPending && steerTurnId) { @@ -4030,7 +4070,8 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses clearCurrentSessionDraft(); clearComposerExtras(); restoreChatInputFocusSoon(false); - return; + settleAnnotations('sent'); + return { ok: true, status: 'queued' }; } const targetSid = sid; restoreComposerFocusAfterSubmitRef.current = true; @@ -4055,8 +4096,33 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses const sessionStartToken = sessionWorktreeIntent ? sessionStartMask.begin({ worktree: true, sessionId: targetSid }) : null; - sendInputOrBuiltin(targetSid, sessionSendPayload) - .then((queued) => { + const delivery = annotationSettle + ? annotationSendOutcome({ + api, + sessionId: targetSid, + clientMessageId: sessionSendPayload.client_message_id, + send: sendInputOrBuiltin(targetSid, sessionSendPayload), + }) + : sendInputOrBuiltin(targetSid, sessionSendPayload).then((value) => ({ status: 'accepted', value })); + return delivery + .then((outcome) => { + if (outcome.status === 'lost') { + // 自查没查到:批注退回待发,提示可重试;这条消息本身也不当已接受。 + settleAnnotations('failed'); + toast({ kind: 'err', text: '发送未确认,批注已退回待发,可重试' }); + if (sidRef.current === targetSid) { + applyEvent({ type: 'busy_changed', payload: { busy: false } }, { emitEffects: false }); + } + return { ok: false, status: 'lost', error: '发送未确认,批注已退回待发,可重试' }; + } + if (outcome.status === 'unknown') { + // 自查本身失败:不回滚,交给用户决定重试还是撤销。 + toast({ kind: 'info', text: '没有收到发送确认,消息可能仍在发送中' }); + settleAnnotations('unknown'); + return { ok: false, status: 'unknown', error: '没有收到发送确认,消息可能仍在发送中' }; + } + settleAnnotations('sent'); + const queued = outcome.value; if (!isBuiltin && sidRef.current === targetSid) { applyEvent(acceptedUserInputEvent(sessionSendPayload), { emitEffects: false }); } @@ -4079,12 +4145,15 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses } if (historyText.trim()) recordInputHistory(historyText); if (sidRef.current === targetSid && clearCurrentSessionDraft({ expectedText: submittedComposerText, expectedContent: submittedComposerContent })) clearComposerExtras(); + return { ok: true, status: outcome.status, value: outcome.value }; }) .catch((e) => { + settleAnnotations('failed'); toast({ kind: 'err', text: '发送失败:' + (e.message || '') }); if (sidRef.current === targetSid) { applyEvent({ type: 'busy_changed', payload: { busy: false } }, { emitEffects: false }); } + return { ok: false, error: '发送失败:' + (e.message || '') }; }) .finally(() => { if (sessionStartToken) sessionStartMask.end(sessionStartToken); @@ -4092,6 +4161,113 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses }); }); + // 批注容器:会话级待发集合。页签那边只上报快照,这里只读。 + const annotationBox = useMemo(() => annotationOutboxFor(sid, api), [sid, api]); + const annotationState = useSyncExternalStore( + useCallback((listener) => (annotationBox ? annotationBox.subscribe(listener) : () => {}), [annotationBox]), + useCallback(() => annotationBox?.getSnapshot() || EMPTY_ANNOTATION_STATE, [annotationBox]), + ); + + // 唯一的发送组装点(Q35):输入框正文 + 会话内全部待发批注,发成一条消息。 + // 输入框发送按钮、页内工具栏、浮窗 Ctrl+Enter 三条路径最后都落到这里。 + const submitWithAnnotations = useStableCallback(async (text, { sendMode = 'send' } = {}) => { + const targetSid = sidRef.current; + const value = typeof text === 'string' ? text : composerValueRef.current; + const records = annotationBox?.pendingRecords() || []; + if (!records.length) { + return (await submit(value, { sendMode })) || { ok: false, error: '发送失败' }; + } + if (!targetSid) return { ok: false, error: '请先打开一个对话再发送批注' }; + const submissionText = composerContentSubmissionText(composerContentRef.current) || value; + let prepared; + try { + prepared = await prepareAnnotationSubmission({ + sessionId: targetSid, + text: submissionText, + records, + outbox: annotationBox, + api, + }); + } catch (error) { + const message = localizedAnnotationSendError(error?.message || error); + toast({ kind: 'err', text: message }); + return { ok: false, error: message }; + } + let result; + try { + result = await submit(prepared.text, { + sendMode, + extraAttachments: prepared.shotAttachments, + extraContexts: prepared.contexts, + annotationSettle: (status) => { + if (status === 'sent') prepared.settle(true); + else if (status === 'failed') { + toast({ kind: 'err', text: '批注未发出,仍在待发列表里,可重试' }); + } + }, + }); + } catch (error) { + const message = localizedAnnotationSendError(error?.message || error); + toast({ kind: 'err', text: message }); + return { ok: false, error: message }; + } + if (result?.ok === false) return result; + if (result?.ok !== true) return { ok: false, error: '发送失败' }; + return { ok: true, annotations: records.length }; + }); + + useEffect(() => { + if (!sid) return undefined; + return registerAnnotationSubmitter(sid, submitWithAnnotations); + }, [sid, submitWithAnnotations]); + + const annotationGroups = useMemo(() => { + const groups = new Map(); + for (const page of annotationState.pages) { + if (!page.count) continue; + groups.set(page.id, { ...page, records: [] }); + } + for (const record of annotationState.records) { + groups.get(record.pageId)?.records.push(record); + } + return [...groups.values()]; + }, [annotationState]); + + // 删除待发批注:活页签走原生存储,已关闭页签只剩本地这份清单。 + const [editingAnnotation, setEditingAnnotation] = useState(null); + const editAnnotationRecord = useStableCallback(async (record) => { + const result = await requestAnnotationEdit(record.pageId, record, { + url: record.pageUrl, + pages: sessionBrowserPages, + tabs: previewTabs, + activate: (pageId) => showBrowserPage(pageId), + }); + if (result?.ok !== false) return; + if (result.reason === 'missing_page' + || result.error === 'Annotation target is invalid' + || result.error === 'Unknown annotation' + || result.error === 'Annotation page is unavailable') { + // 页签还开着但目标已没了:退化成只改文字(与页面已关闭同一形态)。 + setEditingAnnotation(result.reason === 'missing_page' || result.error === 'Annotation page is unavailable' + ? { ...record, state: 'orphan' } + : record); + return; + } + toast({ kind: 'err', text: result.error || '无法回到该页面' }); + }); + + const deleteAnnotationRecord = useStableCallback((record) => { + if (!record?.id) return; + const page = annotationState.pages.find((item) => item.id === record.pageId); + if (page?.closed || !record.pageId) { + annotationBox?.markSent([record.id]); + return; + } + void runPageAnnotationCommand(record.pageId, { + action: 'remove', document_id: '', record_ids: [record.id], + }).catch(() => {}); + }); + const drainQueuedInput = useStableCallback(() => { const targetSid = sidRef.current; if (!targetSid || busy || drainRef.current || sessionRuntimeUnavailable) return; @@ -6804,6 +6980,26 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses /> ) : ( <> + + {editingAnnotation ? ( + setEditingAnnotation(null)} + onSave={(record, description) => { + const saved = annotationBox?.updateDescription(record.id, description) === true; + if (!saved) toast({ kind: 'err', text: '保存失败' }); + return saved; + }} + onDelete={(record) => { + deleteAnnotationRecord(record); + setEditingAnnotation(null); + }} + /> + ) : null} 0} canRetryLastUserMessage={!!retryUserMessageId} queuePaused={!!queuePause} onResumeQueue={resumeQueue} @@ -6952,6 +7149,7 @@ export function ChatView({ titleTarget, actionsTarget, children, sessionRef, ses key={workbenchOwner} owner={workbenchOwner} api={api} + sessionId={sid} cwd={sidePanelCwd} workspaceCwd={sessionIsNoWorkspace ? '' : sidePanelCwd} tabs={previewTabs} diff --git a/web/src/components/InputBar.jsx b/web/src/components/InputBar.jsx index 786bcb55c..4489040a4 100644 --- a/web/src/components/InputBar.jsx +++ b/web/src/components/InputBar.jsx @@ -211,6 +211,7 @@ function ComposerBrowserContextCard({ item, onRemove }) { export const InputBar = forwardRef(function InputBar({ disabled, submitting = false, canRetryLastUserMessage = false, + hasPendingAnnotations = false, queuePaused = false, onResumeQueue, placeholder = '输入消息或 / 命令…', onSubmit, onAbort, busy, stopping = false, goal = null, mainComposer = false, followUpPrompt = null, @@ -632,7 +633,7 @@ export const InputBar = forwardRef(function InputBar({ // Recognition publishes editor refs before React necessarily renders the // new draft. Gate and send the same current snapshot, not the old button state. const currentDraft = serializeComposerGoal(valueRef.current, contentRef.current, goalModeRef.current); - const currentAction = getInputBarActionState({ value: currentDraft.text, disabled, busy, hasExtras, submitting, canRetryLastUserMessage, queuePaused, busySendMode }); + const currentAction = getInputBarActionState({ value: currentDraft.text, disabled, busy, hasExtras, hasPendingAnnotations, submitting, canRetryLastUserMessage, queuePaused, busySendMode }); if (!currentAction.canSubmit) return; // 队列暂停 + 空输入框:这一下是「继续」,不是发送 —— 空内容本来也没什么可发。 if (currentAction.mode === 'resume') { @@ -1448,7 +1449,7 @@ export const InputBar = forwardRef(function InputBar({ } }; - const actionState = getInputBarActionState({ value: draftValue, disabled, busy, hasExtras, submitting, canRetryLastUserMessage, queuePaused, busySendMode }); + const actionState = getInputBarActionState({ value: draftValue, disabled, busy, hasExtras, hasPendingAnnotations, submitting, canRetryLastUserMessage, queuePaused, busySendMode }); const macKeys = isMacShortcutHost(); const primaryKey = macKeys ? '⌘' : 'Ctrl'; // 回复中按设置对调:选了排队时 Enter 排到回合结束、Ctrl+Enter 插话。 @@ -1470,7 +1471,7 @@ export const InputBar = forwardRef(function InputBar({ }, }); const composerSpacingClass = isHero ? 'px-4 pt-3 pb-1 text-[14px]' : 'px-3 pt-2 pb-1 text-[13px]'; - const editing = !!(draftValue || hasExtras || goalMode || speech.active || composerComposing); + const editing = !!(draftValue || hasExtras || hasPendingAnnotations || goalMode || speech.active || composerComposing); const ghostPrompt = mainComposer && !disabled && !submitting && !busy && !stopping && !editing && !showDropdown && !activePathDropdown && !capabilityOpen && !expertSubmenuOpen ? followUpPrompt?.prompt || '' : ''; diff --git a/web/src/components/Message.jsx b/web/src/components/Message.jsx index 5b25ef65e..c6289ddbe 100644 --- a/web/src/components/Message.jsx +++ b/web/src/components/Message.jsx @@ -23,6 +23,7 @@ import { resolveLeadingSlashCommand } from '../lib/slashCommands.js'; import { useSlashCommands } from './SlashCommandsContext.jsx'; import { AttachmentStrip } from './AttachmentStrip.jsx'; import { ImageLightbox } from './ImageLightbox.jsx'; +import { PageAnnotationMessageCard } from './PageAnnotationMessageCard.jsx'; import { attachmentsFromContentParts, isImageAttachment } from '../lib/messageAttachments.js'; import { composerContentAttachments, @@ -38,6 +39,13 @@ import { AttachmentTextLoaderContext } from './AttachmentTextLoaderContext.jsx'; import { PastedTextCard } from './PastedTextCard.jsx'; import { PastedTextDialog } from './PastedTextDialog.jsx'; import { extractSessionReferences } from '../lib/sessionReference.js'; +import { + annotationShotsByName, + contentPartsWithoutAnnotationScreenshots, + pageAnnotationCardFromContexts, + pageAnnotationMessageCopyText, + parsePageAnnotationMessage, +} from '../lib/pageAnnotationMessage.js'; import { basenameForPath } from '../lib/selectionChatContext.js'; import { DESKTOP_CONTEXT_ACTION_EVENT, DESKTOP_CONTEXT_ACTIONS } from '../lib/desktopContextMenu.js'; @@ -323,6 +331,16 @@ function UserBubble({ const hasBubbleBody = composerContent ? composerContent.parts.some((part) => !isThumbnailPart(part)) : !!content; + const annotationCard = useMemo(() => parsePageAnnotationMessage( + composerContent ? composerContentText(composerContent) : content, + ) || pageAnnotationCardFromContexts(contentParts), [composerContent, content, contentParts]); + const annotationShots = useMemo(() => (annotationCard ? annotationShotsByName(contentParts) : null), + [annotationCard, contentParts]); + const annotationCopyText = annotationCard?.fromContext + ? (composerContent + ? extractSessionReferences(composerContentClipboardText(composerContent)).displayText + : content) + : annotationCard?.text; // f300:2400 多万字符的旧消息整段进 pre-wrap 气泡会卡死页面。气泡只渲染有界预览, // 截断时显示 … 与「查看全文」(只读对话框);复制仍取全文。 const messagePreview = useMemo(() => { @@ -340,6 +358,27 @@ function UserBubble({ ? extractSessionReferences(composerContentText(composerContent)).displayText : String(content ?? ''); }, [fullTextOpen, composerContent, content]); + const naturalBubble = hasBubbleBody ? ( +
+ {messagePreview.composerContent ? ( + + ) : } + {messagePreview.truncated ? ( + <> + {'…'} + + + ) : null} +
+ ) : null; return (
{fromSideChat && ( @@ -349,31 +388,22 @@ function UserBubble({ )} - {hasBubbleBody ? ( + {/* 用户正文与批注卡片同时存在:先显示说的话,再显示只读批注卡片。 */} + {annotationCard?.text ? (
- {messagePreview.composerContent ? ( - - ) : } - {messagePreview.truncated ? ( - <> - {'…'} - - - ) : null} + {annotationCard.text}
) : null} + {(!annotationCard || annotationCard.fromContext) ? naturalBubble : null} + {annotationCard ? ( + + ) : null} {fullTextOpen ? ( {relativeTime(ts)}} composerContent - ? extractSessionReferences(composerContentClipboardText(composerContent)).displayText - : content} + getCopyText={() => (annotationCard + ? pageAnnotationMessageCopyText(annotationCard, annotationCopyText) + : (composerContent + ? extractSessionReferences(composerContentClipboardText(composerContent)).displayText + : content))} onFork={onFork} forkPending={forkPending} forkLoading={forkLoading} diff --git a/web/src/components/Modal.jsx b/web/src/components/Modal.jsx index 4d1d3a20a..60924062f 100644 --- a/web/src/components/Modal.jsx +++ b/web/src/components/Modal.jsx @@ -30,8 +30,20 @@ export function Modal({ dismissOnEscape = true, layerClassName = 'z-[200]', labelledBy, + nativeOverlayMode = 'blocking', + nativeOverlayInteraction = 'blocking', }) { const zIndex = useOverlayLayer(); + // `blocking` keeps the existing full-surface semantics: the native view is + // hidden while the dialog is up. `overlap` lets a dialog sit above a native + // surface without hiding it; only the dialog card punches a hole in it. + // `interactive` (used with `overlap`) additionally keeps the native view + // painted but disables its input, so hover/selection inside the page cannot + // leak through a modal dialog. + const overlapsNativeSurface = nativeOverlayMode === 'overlap'; + const backdropNativeOverlay = overlapsNativeSurface ? undefined : 'blocking'; + const backdropInteraction = overlapsNativeSurface ? nativeOverlayInteraction : undefined; + const dialogNativeOverlay = overlapsNativeSurface ? 'overlap' : undefined; const dialogRef = useRef(null); const closeRef = useRef(onClose); const dismissOnEscapeRef = useRef(dismissOnEscape); @@ -88,13 +100,15 @@ export function Modal({ const modalLayer = (
dismissOnBackdrop && handleClose()} >
{ + const input = inputRef.current; + if (!input) return; + input.focus(); + const end = input.value.length; + input.setSelectionRange?.(end, end); + }, []); + if (!record) return null; + const locator = Array.isArray(record.targets) && record.targets[0]?.locator + ? String(record.targets[0].locator) + : record.element; + const pageLabel = record.pageTitle || record.pageUrl || '页面'; + const subtitle = record.state === 'orphan' + ? `${pageLabel} · 页面已关闭,只能修改文字` + : `${pageLabel} · 目标已失效,只能修改文字`; + const save = async () => { + setSaving(true); + try { + const saved = await onSave?.(record, description.trim()); + if (saved !== false) setEditing(false); + } catch { + setEditing(true); + } finally { + setSaving(false); + } + }; + return ( + +
+

+ {`编辑第 ${record.number} 条批注`} +

+

+ {subtitle} +

+ '; + document.querySelector('.ace-annotation-card').append(editor); + })()`); + const editorOverflow = await evaluate(`(() => { + const editor = document.querySelector('.ace-annotation-card.is-adjusting .ace-annotation-editor'); + const style = getComputedStyle(editor); + return { x: style.overflowX, y: style.overflowY }; + })()`); + assert.equal(editorOverflow.x, 'hidden', JSON.stringify(editorOverflow)); + assert.equal(editorOverflow.y, 'auto', JSON.stringify(editorOverflow)); + console.log('[pass] adjusting editor clips horizontal overflow without a left/right scrollbar'); + + // The target tag belongs on the drag-handle row, and the scrolling editor has + // to leave the visible-text box clear of the action bar divider. + await evaluate(`(() => { + const card = document.querySelector('.ace-annotation-card'); + const handle = document.createElement('div'); + handle.className = 'ace-annotation-design-handle'; + handle.innerHTML = '
div
'; + card.prepend(handle); + })()`); + const handleLayout = await evaluate(`(() => { + const handle = document.querySelector('.ace-annotation-design-handle'); + const tag = handle.querySelector('.ace-annotation-target-tag'); + const grip = handle.querySelector('.ace-annotation-design-grip'); + const editor = document.querySelector('.ace-annotation-card.is-adjusting .ace-annotation-editor'); + const textarea = editor.querySelector('.ace-annotation-text-input'); + const frame = handle.getBoundingClientRect(); + const tagBox = tag.getBoundingClientRect(); + const gripBox = grip.getBoundingClientRect(); + return { + rowCenters: [Math.round(tagBox.top + tagBox.height / 2), Math.round(gripBox.top + gripBox.height / 2)], + tagInset: Math.round(tagBox.left - frame.left), + gripInset: Math.round(frame.right - gripBox.right), + belowTextarea: Math.round(editor.getBoundingClientRect().bottom - textarea.getBoundingClientRect().bottom), + scrolls: editor.scrollHeight > editor.clientHeight, + }; + })()`); + assert.ok(Math.abs(handleLayout.rowCenters[0] - handleLayout.rowCenters[1]) <= 1, + `the target tag and drag grip must share one visual row: ${JSON.stringify(handleLayout)}`); + assert.equal(handleLayout.tagInset, 16, JSON.stringify(handleLayout)); + assert.equal(handleLayout.gripInset, 16, JSON.stringify(handleLayout)); + assert.equal(handleLayout.scrolls, false, 'fixture must fit the editor so the padding is measurable'); + assert.equal(handleLayout.belowTextarea, 2, + `the visible-text box keeps 2px to the action bar divider: ${JSON.stringify(handleLayout)}`); + console.log('[pass] target tag rides the drag-handle row; visible-text box keeps 2px above the action divider'); + + await evaluate(`document.getElementById('annotation-popup-layout').remove(); document.body.replaceChildren()`); + await request('Emulation.setDeviceMetricsOverride', { + width: 800, height: 600, deviceScaleFactor: 1, mobile: false, + }); + await evaluate(`document.body.innerHTML = '
Original child
'; globalThis.target = document.getElementById('target'); globalThis.originalInline = target.getAttribute('style'); globalThis.originalChild = target.firstElementChild; globalThis.previews = (${styles})(document); previews.select(target,'target-1');`); + const value = property => evaluate(`getComputedStyle(target).getPropertyValue(${JSON.stringify(property)})`); + const preview = fields => evaluate(`previews.preview(target,'target-1',${JSON.stringify(fields)}); previews.differences()`); + const cases = [ + ['color', '#00ff00', 'rgb(0, 255, 0)'], ['background-color', '#0000ff', 'rgb(0, 0, 255)'], + ['opacity', '0.5', '0.5'], ['font-family', 'monospace', 'monospace'], ['font-size', '24px', '24px'], + ['font-weight', '700', '700'], ['border-radius', '8px', '8px'], ['border-color', '#00ff00', 'rgb(0, 255, 0)'], + ['border-width', '3px', '3px'], ['width', '150px', '150px'], ['height', '70px', '70px'], + ['letter-spacing', '2px', '2px'], ['word-spacing', '4px', '4px'], ['gap', '6px', '6px'], + ['padding', '5px', '5px'], ['margin', '7px', '7px'], + ['padding-top', '1px', '1px'], ['padding-right', '2px', '2px'], ['padding-bottom', '3px', '3px'], ['padding-left', '4px', '4px'], + ['margin-top', '1px', '1px'], ['margin-right', '2px', '2px'], ['margin-bottom', '3px', '3px'], ['margin-left', '4px', '4px'], + ]; + for (const [property, requested, effective] of cases) { + const differences = await preview({ [property]: requested }); + assert.equal(await value(property), effective, property); + assert.ok(differences.length > 0, `${property} must produce a real difference`); + assert.ok(differences.every(change => change.target_id === 'target-1' && change.old_value !== change.new_value)); + assert.equal(await evaluate('target.getAttribute("style") === originalInline && target.firstElementChild === originalChild'), true); + await evaluate("previews.cancel(); previews.select(target,'target-1')"); + } + console.log('[pass] real Chromium CSS engine previews every style field without altering original inline styles or child identity'); + + assert.deepEqual(await preview({ color: '#ff0000', width: '100px', opacity: '1' }), []); + await preview({ padding: '1px 2px 3px 4px', margin: '5px 6px' }); + assert.equal(await value('padding-left'), '4px'); + assert.equal(await value('margin-right'), '6px'); + await evaluate("previews.cancel(); previews.select(target,'target-1')"); + for (const invalid of [{ color: 'red; width:999px' }, { 'background-color': 'url(https://example.invalid)' }, + { position: 'fixed' }, { 'font-family': 'var(--page-data)' }, { width: 'invalid-length' }]) { + assert.equal(await evaluate(`(() => { try { previews.preview(target,'target-1',${JSON.stringify(invalid)}); return false; } catch { return true; } })()`), true); + } + await preview({ color: '#0000ff' }); + const firstDifferences = await evaluate('previews.save()'); + assert.deepEqual(firstDifferences, [{ target_id: 'target-1', property: 'color', old_value: 'rgb(255, 0, 0)', new_value: 'rgb(0, 0, 255)' }]); + await evaluate("previews.select(target,'target-1')"); + const secondDifferences = await preview({ color: '#00ff00' }); + assert.equal(secondDifferences[0].old_value, 'rgb(0, 0, 255)'); + await evaluate('previews.setOriginal(true)'); + assert.equal(await value('color'), 'rgb(255, 0, 0)'); + assert.deepEqual(await evaluate('previews.differences()'), secondDifferences); + await evaluate('previews.setOriginal(false)'); + assert.equal(await value('color'), 'rgb(0, 255, 0)'); + await evaluate('previews.cancel()'); + assert.equal(await value('color'), 'rgb(0, 0, 255)'); + console.log('[pass] canonical no-ops, injection rejection, same-target layered cancel, and original/draft round trips'); + + await evaluate("previews.select(target,'target-1')"); + assert.equal(await evaluate("previews.describe(target,'target-1').ratio_locked"), false); + await preview({ width: '200px' }); + assert.equal(await value('height'), '40px'); + await evaluate("previews.preview(target,'target-1',{},true)"); + assert.equal(await evaluate("previews.describe(target,'target-1').ratio"), 5); + await preview({ height: '60px' }); + assert.equal(await value('width'), '300px'); + await preview({ width: '400px' }); + assert.equal(await value('height'), '80px'); + await evaluate("previews.preview(target,'target-1',{},false)"); + await preview({ width: '200px' }); + assert.equal(await value('height'), '80px'); + await evaluate('previews.cancel()'); + assert.equal(await value('width'), '100px'); + assert.equal(await value('height'), '40px'); + await evaluate("globalThis.inlineTarget = document.createElement('span'); inlineTarget.style.cssText='width:100px;height:40px'; inlineTarget.textContent='inline'; document.body.append(inlineTarget); previews.select(inlineTarget,'inline'); previews.preview(inlineTarget,'inline',{},true)"); + assert.equal(await evaluate("(() => { try { previews.preview(inlineTarget,'inline',{width:'auto'}); return false; } catch (error) { return error.message; } })()"), 'invalid_current_ratio'); + assert.equal(await evaluate("previews.describe(inlineTarget,'inline').values.width"), '100px'); + assert.deepEqual(await evaluate("previews.describe(inlineTarget,'inline').styles"), {}); + await evaluate('previews.cancel(); inlineTarget.remove()'); + console.log('[pass] ratio is default-off, captures current edited ratio, links either dimension, and unlocks/cancels'); + + await evaluate("target.style.setProperty('color','red','important'); previews.select(target,'target-1')"); + assert.deepEqual(await preview({ color: 'green' }), []); + assert.equal(await value('color'), 'rgb(255, 0, 0)'); + assert.equal(await evaluate("target.style.getPropertyPriority('color')"), 'important'); + assert.deepEqual(await evaluate("previews.describe(target,'target-1').errors"), []); + await evaluate('previews.cancel(); target.setAttribute("style",originalInline)'); + await evaluate("globalThis.clone = target.cloneNode(true); document.body.append(clone)"); + await evaluate('Promise.resolve()'); + assert.equal(await evaluate('getComputedStyle(clone).color'), 'rgb(255, 0, 0)'); + assert.equal(await value('color'), 'rgb(0, 0, 255)'); + await evaluate('target.remove(); Promise.resolve()'); + assert.equal(await evaluate('getComputedStyle(clone).color'), 'rgb(255, 0, 0)'); + await evaluate('document.body.append(target); Promise.resolve()'); + assert.equal(await value('color'), 'rgb(0, 0, 255)'); + await evaluate('previews.dispose(); clone.remove()'); + assert.equal(await value('color'), 'rgb(255, 0, 0)'); + assert.equal(await evaluate('document.adoptedStyleSheets.length'), 0); + console.log('[pass] inline-important stays red without a recorded difference or error; clones never inherit previews; disposal restores original stylesheet membership'); + + await evaluate("target.style.transition='color 10s'; globalThis.motionPreviews = (" + styles + ")(document); motionPreviews.select(target,'motion'); motionPreviews.preview(target,'motion',{color:'blue'});"); + assert.equal(await value('color'), 'rgb(0, 0, 255)'); + await evaluate('motionPreviews.setOriginal(true)'); + assert.equal(await value('color'), 'rgb(255, 0, 0)'); + assert.equal(await value('transition-duration'), '10s'); + await evaluate('motionPreviews.setOriginal(false)'); + assert.equal(await value('color'), 'rgb(0, 0, 255)'); + await evaluate('motionPreviews.cancel()'); + assert.equal(await value('color'), 'rgb(255, 0, 0)'); + assert.equal(await value('transition-duration'), '10s'); + await evaluate('motionPreviews.dispose(); target.setAttribute("style",originalInline)'); + console.log('[pass] original comparison and cancel settle instantly on transitioning pages and restore author transition declarations'); + + await evaluate("globalThis.shadowHost = document.createElement('section'); document.body.append(shadowHost); globalThis.shadowRoot = shadowHost.attachShadow({mode:'open'}); globalThis.shadowTarget = document.createElement('span'); shadowTarget.textContent='shadow'; shadowRoot.append(shadowTarget); globalThis.shadowPreviews = (" + styles + ")(document); shadowPreviews.select(shadowTarget,'shadow'); shadowPreviews.preview(shadowTarget,'shadow',{color:'blue'}); "); + assert.equal(await evaluate('getComputedStyle(shadowTarget).color'), 'rgb(0, 0, 255)'); + await evaluate('document.body.append(shadowTarget); Promise.resolve()'); + assert.equal(await evaluate('getComputedStyle(shadowTarget).color'), 'rgb(0, 0, 255)'); + await evaluate('shadowRoot.append(shadowTarget); Promise.resolve()'); + assert.equal(await evaluate('getComputedStyle(shadowTarget).color'), 'rgb(0, 0, 255)'); + await evaluate('shadowPreviews.dispose()'); + assert.equal(await evaluate('shadowRoot.adoptedStyleSheets.length'), 0); + assert.equal(await evaluate('document.adoptedStyleSheets.length'), 0); + console.log('[pass] stylesheet ownership and cleanup also work for shadow-root targets'); + + const run = async (action, fields = {}) => { + const current = action === 'save' ? await run('read') : null; + return evaluate(`(${runtime})(${JSON.stringify({ action, document_id: 'doc-browser', + ...(current ? {target_ids:current.targets.map(target => target.id), region:current.region} : {}), + ...fields })},${text},${styles})`); + }; + const click = async (x, y) => { + for (const type of ['mousePressed', 'mouseReleased']) await request('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1 }); + }; + await run('start'); + await click(20, 30); + assert.equal((await run('read')).popup, true); + const first = await run('preview_style', { target_id: 'target-1', styles: { color: 'blue' } }); + assert.equal(first.target.style_preview.ratio_locked, false); + assert.equal(first.differences.length, 1); + const saved = await run('save', { target_id: 'target-1', number: 1 }); + assert.equal(saved.differences[0].property, 'color'); + assert.equal(saved.target, null); + await run('exit'); + assert.equal(await value('color'), 'rgb(0, 0, 255)'); + await run('original', { enabled: true }); + assert.equal(await value('color'), 'rgb(255, 0, 0)'); + await run('original', { enabled: false }); + assert.equal(await value('color'), 'rgb(0, 0, 255)'); + await run('start'); + await click(20, 30); + await run('preview_style', { target_id: 'target-1', styles: { color: 'green' } }); + await run('cancel'); + assert.equal(await value('color'), 'rgb(0, 0, 255)'); + await run('start', { document_id: 'replacement-document' }); + assert.equal(await value('color'), 'rgb(255, 0, 0)'); + assert.equal(await evaluate('target.getAttribute("style") === originalInline && target.firstElementChild === originalChild'), true); + console.log('[pass] isolated runtime/trusted browser input integrates preview/save/differences, mode exit, original compare, cancel, and document rebinding'); + + // A menu or dialog floating over the page suspends the in-page outline and + // hover card so they cannot punch through the app's own overlay. + await run('start'); + assert.equal((await run('read')).modal_suspended, false, 'a fresh session starts unsuspended'); + const suspended = await run('set_modal_suspended', { enabled: true }); + assert.equal(suspended.modal_suspended, true, 'the runtime reports the suspended state back to native'); + assert.equal((await run('read')).modal_suspended, true, 'the suspended state survives a read'); + const resumed = await run('set_modal_suspended', { enabled: false }); + assert.equal(resumed.modal_suspended, false); + await run('exit'); + console.log('[pass] set_modal_suspended suspends and resumes the in-page chrome through the real runtime'); + await runAnnotationIntegration({ evaluate, request }); +} finally { + for (const waiter of pending.values()) clearTimeout(waiter.timeout); + pending.clear(); + if (socket?.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify({ id: ++sequence, method: 'Browser.close' })); + socket.close(); + } + if (child.exitCode === null) { + await Promise.race([exited, new Promise(resolve => setTimeout(resolve, 3000))]); + if (child.exitCode === null) child.kill(); + } + assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir())); + try { await fs.promises.rm(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } + catch (error) { + if (!['EPERM', 'EBUSY'].includes(error.code)) throw error; + console.warn(`Temporary browser profile remains locked: ${profile}`); + } +} diff --git a/web/src/lib/pageAnnotationText.test.js b/web/src/lib/pageAnnotationText.test.js new file mode 100644 index 000000000..77e14ad93 --- /dev/null +++ b/web/src/lib/pageAnnotationText.test.js @@ -0,0 +1,300 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import { DOMParser } from '@xmldom/xmldom'; + +const header = name => fs.readFileSync(new URL(`../../../src/apps/desktop/${name}.hpp`, import.meta.url), 'utf8'); +const textRuntime = header('page_annotation_text_runtime').split('R"ACETEXT(')[1].split(')ACETEXT"')[0]; +const runtime = header('page_annotation_runtime').split('R"ACEANNOTATION(').slice(1) + .map(part => part.split(')ACEANNOTATION"')[0]).join(''); + +function fixture(markup = '') { + const document = new DOMParser().parseFromString(`${markup}`, 'text/html'); + const listeners = new WeakMap(); + const contains = function contains(node) { + for (let current = node; current; current = current.parentNode) if (current === this) return true; + return false; + }; + const add = function add(type, callback) { + if (!listeners.has(this)) listeners.set(this, new Map()); + listeners.get(this).set(type, callback); + }; + const remove = function remove(type) { listeners.get(this)?.delete(type); }; + const decorate = node => { + node.remove = function removeNode() { this.parentNode?.removeChild(this); }; + if (node.nodeType === 3) Object.defineProperty(node, 'data', { + get() { return this.nodeValue; }, set(value) { this.nodeValue = value; this.length = value.length; }, + }); + if (node.nodeType !== 1) return node; + Object.defineProperty(node, 'isConnected', {get() { return document.documentElement.contains(this); }}); + node.style = {cssText:''}; + node.contains = contains; + node.append = function append(...nodes) { nodes.forEach(child => this.appendChild(child)); }; + node.attachShadow = function attachShadow() { return (this.shadow = document.createElement('shadow')); }; + node.getBoundingClientRect = () => ({x:10, y:20, width:100, height:40}); + node.addEventListener = add; + node.removeEventListener = remove; + Array.from(node.childNodes).forEach(decorate); + return node; + }; + decorate(document.documentElement); + const createElement = document.createElement.bind(document); + const createTextNode = document.createTextNode.bind(document); + document.createElement = tag => decorate(createElement(tag)); + document.createTextNode = value => decorate(createTextNode(value)); + document.addEventListener = add; + document.removeEventListener = remove; + const context = vm.createContext({ + document, innerWidth:800, innerHeight:600, scrollX:0, scrollY:0, + getComputedStyle: element => ({display:element.hasAttribute('hidden') ? 'none' : 'block', visibility:'visible'}), + addEventListener() {}, removeEventListener() {}, + }); + const target = document.getElementById('target'); + const text = vm.runInContext(`${textRuntime}()`, context); + const run = (action, fields = {}) => { + const current = action === 'save' ? run('read') : null; + return JSON.parse(JSON.stringify(vm.runInContext( + `${runtime}(${JSON.stringify({action, document_id:'doc', + ...(current ? {target_ids:current.targets.map(item => item.id), region:current.region} : {}), + ...fields})}, ${textRuntime}, () => ({describe:() => ({}), differences:() => [], + select() {}, save:() => [], cancel() {}, setOriginal() {}, dispose() {}}))`, context, + ))); + }; + const click = node => listeners.get(document).get('click')({ + isTrusted:true, button:0, composedPath:() => [node], preventDefault() {}, stopImmediatePropagation() {}, stopPropagation() {}, + }); + const select = () => { + click(target); + return run('read').target.id; + }; + return {document, target, text, run, select, listeners}; +} + +for (const action of ['save', 'cancel', 'exit']) { + const {target, run, select} = fixture(''); + run('start'); + const id = select(); + target.firstChild.data = 'Updated by page'; + assert.equal(run('read').target.text_preview.value, 'Updated by page'); + const result = run(action, action === 'save' ? {target_id:id, number:1} : {}); + assert.equal(target.textContent, 'Updated by page', `${action} must not restore merely observed text`); + assert.deepEqual(result.differences, []); +} + +{ + const {target, text} = fixture(''); + text.describe(target, 'one'); + target.firstChild.data = 'Updated by page'; + text.setOriginal(true); + text.setOriginal(false); + assert.equal(target.textContent, 'Updated by page'); + text.preview(target, 'one', 'Requested label'); + assert.equal(text.differences()[0].old_value, 'Updated by page'); + text.cancel(); + assert.equal(target.textContent, 'Updated by page'); + text.preview(target, 'one', 'Another preview'); + target.firstChild.data = 'Later page update'; + assert.equal(text.save().error, 'stale_text_nodes'); + text.cancel(); + text.dispose(); + assert.equal(target.textContent, 'Later page update', 'cleanup cannot overwrite a page write after the owned preview'); +} + +for (const saved of [false, true]) { + const {target, text} = fixture(''); + text.preview(target, 'parent', 'Hi world!'); + if (saved) text.save(); + target.childNodes[1].firstChild.data = 'Earth'; + text.setOriginal(true); + assert.equal(target.textContent, 'Hello Earth!'); + text.setOriginal(false); + assert.equal(target.textContent, 'Hi Earth!', 'a preview must not own unchanged descendant text'); + if (!saved) { + assert.equal(text.differences()[0].old_value, 'Hello Earth!'); + assert.equal(text.differences()[0].new_value, 'Hi Earth!'); + } + text.cancel(); + assert.equal(target.textContent, saved ? 'Hi Earth!' : 'Hello Earth!'); + text.dispose(); + assert.equal(target.textContent, 'Hello Earth!'); +} + +{ + const {target, text} = fixture(''); + text.preview(target, 'empty', 'Owned insertion'); + target.firstChild.data = 'Page adopted this text node'; + assert.equal(text.save().error, 'stale_text_nodes'); + text.cancel(); + text.dispose(); + assert.equal(target.textContent, 'Page adopted this text node'); +} + +for (const childFirst of [true, false]) { + const {target, text} = fixture(''); + const child = target.childNodes[1]; + const original = target.toString(); + text.describe(target, 'parent'); + text.describe(child, 'child'); + const parentEdit = () => text.preview(target, 'parent', 'Hi world!'); + const childEdit = () => text.preview(child, 'child', 'Earth'); + if (childFirst) { childEdit(); parentEdit(); } else { parentEdit(); childEdit(); } + const actual = target.textContent; + const actualChild = child.textContent; + const expected = [{target_id:'parent', property:'text', old_value:'Hello world!', new_value:actual}]; + if (actualChild !== 'world') expected.push({target_id:'child', property:'text', old_value:'world', new_value:actualChild}); + const ordered = value => JSON.parse(JSON.stringify(value)).sort((left, right) => left.target_id.localeCompare(right.target_id)); + assert.deepEqual(ordered(text.differences()), ordered(expected), 'overlapping diffs describe the final DOM, not overwritten requests'); + text.setOriginal(true); + assert.equal(target.toString(), original); + assert.deepEqual(ordered(text.differences()), ordered(expected)); + text.setOriginal(false); + assert.equal(target.textContent, actual); + assert.deepEqual(ordered(text.save().differences), ordered(expected)); + assert.equal(target.textContent, actual); + text.preview(child, 'child', 'Next'); + assert.equal(text.differences()[0].old_value, actualChild); + text.cancel(); + assert.equal(target.textContent, actual); + text.dispose(); + assert.equal(target.toString(), original); +} + +{ + const {target, text} = fixture(); + const nodes = [...Array.from(target.childNodes), target.childNodes[1].firstChild]; + const original = target.toString(); + const child = target.childNodes[1]; + let clicks = 0; + const listener = () => { ++clicks; }; + child.addEventListener('click', listener); + assert.equal(text.describe(target, 'one').value, 'Hello world!'); + text.preview(target, 'one', 'Hi world!'); + assert.equal(child.textContent, 'world'); + assert.equal(target.lastChild.textContent, 'secret'); + assert.equal(text.differences()[0].old_value, 'Hello world!'); + text.setOriginal(true); + assert.equal(target.toString(), original); + text.setOriginal(false); + assert.equal(target.firstChild.data, 'Hi '); + text.cancel(); + assert.equal(target.toString(), original); + assert.deepEqual([...Array.from(target.childNodes), child.firstChild], nodes); + listener(); + assert.equal(clicks, 1); + text.preview(target, 'one', 'Hello world!'); + assert.equal(text.differences().length, 0); + console.log('[pass] reversible text preserves exact nested nodes, hidden content, and unchanged child text'); +} + +{ + const {target, text} = fixture(); + text.preview(target, 'one', 'Saved world!'); + const first = JSON.stringify(text.save().differences); + text.preview(target, 'one', 'Draft world!'); + assert.equal(text.differences()[0].old_value, 'Saved world!'); + text.cancel(); + assert.equal(target.firstChild.data, 'Saved '); + text.preview(target, 'one', 'Saved world!'); + assert.equal(text.save().differences.length, 0); + assert.equal(JSON.parse(first)[0].new_value, 'Saved world!'); + text.setOriginal(true); + assert.equal(target.firstChild.data, 'Hello '); + text.setOriginal(false); + assert.equal(target.firstChild.data, 'Saved '); + text.dispose(); + assert.equal(target.firstChild.data, 'Hello '); + console.log('[pass] text saved/draft/original layers retain earlier saved previews and actual differences'); +} + +{ + const {target, text} = fixture(); + const original = target.toString(); + const child = target.childNodes[1]; + for (const value of ['', 'Prefix Hello world!', 'Hello world! suffix', 'Replacement', 'Hello world!', 'Hi \u{1f30d}!']) { + assert.equal(text.preview(target, 'one', value).error, undefined); + assert.equal(target.firstChild.data + child.textContent + target.childNodes[2].data, value); + assert.equal(target.childNodes[1], child); + text.setOriginal(true); + assert.equal(target.toString(), original); + text.setOriginal(false); + text.cancel(); + assert.equal(target.toString(), original); + } + text.preview(target, 'one', 'Saved world!'); + text.save(); + text.setOriginal(true); + text.preview(target, 'one', 'Hello world!'); + assert.equal(target.toString(), original); + assert.equal(text.differences()[0].old_value, 'Saved world!'); + text.save(); + text.setOriginal(false); + assert.equal(target.toString(), original); + console.log('[pass] insertion/deletion/Unicode and edits during comparison retain exact originals and saved baselines'); +} + +{ + const {target, text} = fixture(''); + const original = target.toString(); + const child = target.firstChild; + text.preview(target, 'empty', 'New text'); + assert.equal(target.lastChild.data, 'New text'); + text.setOriginal(true); + assert.equal(target.toString(), original); + text.setOriginal(false); + assert.equal(target.lastChild.data, 'New text'); + assert.equal(text.save().error, undefined); + text.preview(target, 'empty', ''); + assert.equal(target.textContent, ''); + text.cancel(); + assert.equal(target.textContent, 'New text'); + text.dispose(); + assert.equal(target.toString(), original); + assert.equal(target.firstChild, child); + console.log('[pass] empty targets use a reversible owned text node without disturbing children'); +} + +{ + const {target, text, document} = fixture(); + text.preview(target, 'one', 'Saved world!'); + target.childNodes[1].append(document.createTextNode('external')); + assert.equal(text.preview(target, 'one', 'Other').error, 'stale_text_nodes'); + assert.equal(text.save().error, 'stale_text_nodes'); + assert.equal(text.describe(target, 'one').editable, false); + text.cancel(); + assert.equal(text.describe(target, 'one').editable, true); + const large = fixture(`
${'x'.repeat(4097)}
`); + assert.equal(large.text.describe(large.target, 'large').editable, false); + assert.equal(large.text.preview(large.target, 'large', 'Small').error, 'invalid_text'); + console.log('[pass] changed node topology and over-limit text fail explicitly without truncation'); +} + +{ + const {target, run, select, listeners} = fixture(); + const child = target.childNodes[1]; + let clicked = 0; + child.addEventListener('click', () => { ++clicked; }); + const original = target.toString(); + run('start'); + const id = select(); + assert.equal(run('preview_text', {target_id:'wrong', text:'Bad'}).error, 'stale_target'); + assert.equal(run('preview_text', {target_id:id, text:'Saved world!'}).target.text_preview.value, 'Saved world!'); + const saved = run('save', {target_id:id, number:1}); + assert.deepEqual(saved.differences, [{target_id:id, property:'text', old_value:'Hello world!', new_value:'Saved world!'}]); + select(); + run('preview_text', {target_id:id, text:'Draft world!'}); + run('original', {enabled:true}); + assert.equal(target.toString(), original); + run('original', {enabled:false}); + run('cancel'); + assert.equal(target.firstChild.data, 'Saved '); + const pin = Array.from(target.ownerDocument.documentElement.lastChild.shadow.childNodes) + .find(node => node.getAttribute?.('data-ace-annotation-pin') === '1'); + assert.equal(pin.textContent, '1'); + select(); + run('preview_text', {target_id:id, text:'Unsaved world!'}); + run('exit'); + assert.equal(target.firstChild.data, 'Saved '); + listeners.get(child).get('click')(); + assert.equal(clicked, 1); + console.log('[pass] integrated runtime edits/saves/cancels text, retains pins/listeners and survives mode exit'); +} diff --git a/web/src/lib/pageAnnotationTextField.test.js b/web/src/lib/pageAnnotationTextField.test.js new file mode 100644 index 000000000..6ed32ec87 --- /dev/null +++ b/web/src/lib/pageAnnotationTextField.test.js @@ -0,0 +1,73 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import React from 'react'; +import { parseSync } from '@babel/core'; +import { transformWithEsbuild } from 'vite'; +import { createPageAnnotationController } from './pageAnnotations.js'; + +const source = fs.readFileSync(new URL('../components/PageAnnotationTextField.jsx', import.meta.url), 'utf8'); +const ast = parseSync(source, {configFile:false, babelrc:false, parserOpts:{plugins:['jsx']}}); +const body = ast.program.body.filter(node => node.type !== 'ImportDeclaration').map(node => node.declaration || node); +const transformed = await transformWithEsbuild(body.map(node => source.slice(node.start, node.end)).join('\n'), + 'PageAnnotationTextField.jsx', {loader:'jsx', jsxFactory:'React.createElement'}); +let value; +let dependencies; +const useState = initial => [value ??= initial, next => { value = next; }]; +const useEffect = (effect, next) => { + if (!dependencies || next.some((item, index) => item !== dependencies[index])) effect(); + dependencies = next; +}; +const {PageAnnotationTextField} = vm.runInNewContext(`${transformed.code}; ({PageAnnotationTextField});`, + {React, useEffect, useState}); +const textarea = field => field.props.children.find(child => child?.type === 'textarea'); + +{ + const requests = []; + let release; + let revision = 1; + const target = {id:'target-1', text_preview:{value:'Original', editable:true, error:''}}; + const controller = createPageAnnotationController({pageId:'page-1', invoke:async (pageId, command) => { + requests.push(command); + if (requests.length === 1) await new Promise(resolve => { release = resolve; }); + return {ok:true, page_id:pageId, annotations:{document_id:'doc', target, revision:++revision}}; + }}); + controller.observe({document_id:'doc', target, revision}); + const promises = []; + const props = {target, working:false, command:(...args) => { + const promise = controller.command(...args); + promises.push(promise); + return promise; + }}; + let field = PageAnnotationTextField(props); + assert.equal(textarea(field).props['aria-label'], '可见文本'); + textarea(field).props.onChange({target:{value:'First'}}); + field = PageAnnotationTextField(props); + textarea(field).props.onChange({target:{value:'Latest'}}); + field = PageAnnotationTextField({...props, target:{...target, text_preview:{...target.text_preview, value:'First'}}}); + assert.equal(textarea(field).props.value, 'Latest'); + const save = controller.command('save', {description:''}); + await Promise.resolve(); + assert.equal(requests.length, 1); + release(); + await Promise.all([...promises, save]); + assert.deepEqual(requests.map(command => command.action), ['preview_text', 'preview_text', 'save']); + assert.deepEqual(requests.slice(0, 2).map(command => command.text), ['First', 'Latest']); + assert.equal(requests[2].target_id, 'target-1'); + assert.ok(requests.every(command => command.document_id === 'doc')); + field = PageAnnotationTextField({...props, target:{...target, id:'target-2', text_preview:{value:'Second target', editable:true, error:''}}}); + field = PageAnnotationTextField({...props, target:{...target, id:'target-2', text_preview:{value:'Second target', editable:true, error:''}}}); + assert.equal(textarea(field).props.value, 'Second target'); + field = PageAnnotationTextField({...props, working:true}); + assert.equal(textarea(field).props.disabled, true); + field = PageAnnotationTextField({...props, target:{...target, text_preview:{value:'', editable:false, error:'Text is not editable'}}}); + assert.equal(textarea(field).props.disabled, true); + assert.equal(field.props.children[2].props.role, 'alert'); + assert.equal(field.props.children[2].props.children, 'Text is not editable'); + // Native prose hints must be localized through the i18n catalog, never shown raw. + field = PageAnnotationTextField({...props, target:{...target, text_preview:{value:'', editable:false, error:'Text exceeds the editable limit or is not visible content'}}}); + assert.equal(field.props.children[2].props.children, '文本超出可编辑上限,或该内容不可见'); + field = PageAnnotationTextField({...props, target:{...target, text_preview:{value:'', editable:false, error:'Text nodes changed; cancel and select the element again'}}}); + assert.equal(field.props.children[2].props.children, '文本节点已变化,请取消后重新选择元素'); + console.log('[pass] production text field keeps rapid local edits, binds target/document and queues save after previews'); +} diff --git a/web/src/lib/pageAnnotations.js b/web/src/lib/pageAnnotations.js new file mode 100644 index 000000000..65238bbc8 --- /dev/null +++ b/web/src/lib/pageAnnotations.js @@ -0,0 +1,90 @@ +import { parseAgentBrowserBridgeResult } from './agentBrowser.js'; + +export async function runPageAnnotationCommand(pageId, command, win = globalThis.window) { + if (typeof win?.aceDesktop_agentBrowserAnnotationCommand !== 'function') { + return { ok: false, error: '当前桌面版本不支持网页批注' }; + } + return parseAgentBrowserBridgeResult( + await win.aceDesktop_agentBrowserAnnotationCommand({ page_id: pageId, command }), + ); +} + +export async function capturePageAnnotationScreenshot(pageId, win = globalThis.window) { + if (typeof win?.aceDesktop_agentBrowserAnnotationScreenshot !== 'function') { + return { ok: false, error: '当前桌面版本不支持网页批注截图' }; + } + const result = parseAgentBrowserBridgeResult( + await win.aceDesktop_agentBrowserAnnotationScreenshot({ page_id: pageId }), + ); + const data = result?.result?.data; + if (result?.ok !== true || result?.page_id !== pageId || typeof data !== 'string' || !data) { + return { ok: false, error: result?.error || '网页截图失败' }; + } + return { ok: true, data, mimeType: 'image/png' }; +} + +export function createPageAnnotationController({ pageId, invoke = runPageAnnotationCommand, onChange }) { + let snapshot = { document_id: '', active: false, popup: false, pending_count: 0, revision: -1 }; + let tail = Promise.resolve(); + let disposed = false; + const observe = (next) => { + if (disposed || !next || !Number.isSafeInteger(next.revision) + || next.revision <= snapshot.revision) return; + snapshot = next; + onChange?.(snapshot); + }; + return { + observe, + getSnapshot: () => snapshot, + command(action, fields = {}) { + const command = { + action, document_id: snapshot.document_id, + ...(['preview_style', 'preview_text'].includes(action) ? { target_id: snapshot.target?.id } : {}), + ...(action === 'save' ? { + target_id: snapshot.target?.id ?? null, + target_ids: (snapshot.targets || []).map(target => target.id), + region: snapshot.region ? { ...snapshot.region } : null, + } : {}), + ...fields, + }; + const run = async () => { + if (disposed) return { ok: false, cancelled: true }; + try { + const result = await invoke(pageId, command); + if (result?.ok === true && result.page_id === pageId) observe(result.annotations); + return result; + } catch (error) { + return { ok: false, error: String(error?.message || error) }; + } + }; + const result = tail.then(run); + tail = result.then(() => undefined); + return result; + }, + dispose() { disposed = true; }, + }; +} + +export function pageAnnotationPopupPosition({ width, height, popupWidth, popupHeight, target, viewport }) { + const scaleX = viewport?.width > 0 ? width / viewport.width : 1; + const scaleY = viewport?.height > 0 ? height / viewport.height : 1; + const left = (target?.bounds?.x || 0) * scaleX; + const top = (target?.bounds?.y || 0) * scaleY; + const bottom = top + (target?.bounds?.height || 0) * scaleY; + const clamp = (value, available) => Math.max(8, Math.min(value, available - 8)); + return { + left: clamp(left, width - popupWidth), + top: clamp(bottom + 8 + popupHeight <= height ? bottom + 8 : top - popupHeight - 8, height - popupHeight), + }; +} + +export function pageAnnotationPopupDragPosition({ + startLeft, startTop, deltaX = 0, deltaY = 0, + width, height, popupWidth, popupHeight, +}) { + const clamp = (value, available) => Math.max(8, Math.min(value, available - 8)); + return { + left: clamp(startLeft + deltaX, width - popupWidth), + top: clamp(startTop + deltaY, height - popupHeight), + }; +} diff --git a/web/src/lib/pageAnnotations.test.js b/web/src/lib/pageAnnotations.test.js new file mode 100644 index 000000000..2e6e0c265 --- /dev/null +++ b/web/src/lib/pageAnnotations.test.js @@ -0,0 +1,576 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import React from 'react'; +import { transformWithEsbuild } from 'vite'; +import { + createPageAnnotationController, + pageAnnotationPopupDragPosition, + pageAnnotationPopupPosition, + runPageAnnotationCommand, +} from './pageAnnotations.js'; + +const source = fs.readFileSync(new URL('../../../src/apps/desktop/page_annotation_runtime.hpp', import.meta.url), 'utf8'); +const runtime = source.split('R"ACEANNOTATION(').slice(1) + .map(part => part.split(')ACEANNOTATION"')[0]).join(''); +const textSource = fs.readFileSync(new URL('../../../src/apps/desktop/page_annotation_text_runtime.hpp', import.meta.url), 'utf8'); +const textRuntime = textSource.split('R"ACETEXT(')[1].split(')ACETEXT"')[0]; +const styleSource = fs.readFileSync(new URL('../../../src/apps/desktop/page_annotation_style_runtime.hpp', import.meta.url), 'utf8'); +const styleRuntime = styleSource.split('R"ACESTYLES(')[1].split(')ACESTYLES"')[0]; + +function fixture() { + const documentListeners = new Map(); + const windowListeners = new Map(); + const observers = []; + class Observer { + constructor(callback) { this.callback = callback; this.active = true; this.records = []; observers.push(this); } + observe() {} + disconnect() { this.active = false; } + takeRecords() { return this.records.splice(0); } + } + let document; + const element = (tag) => ({ + nodeType: 1, localName: tag, ownerDocument: document, isConnected: true, + style: { cssText: '', getPropertyValue: () => '', getPropertyPriority: () => '' }, + attributes: new Map(), children: [], listeners: new Map(), id: '', textContent: '', + get childNodes() { return this.children; }, + offsetWidth: 80, offsetHeight: 24, + bounds: { x: 10, y: 20, width: 100, height: 40 }, + append(...children) { children.forEach(child => { child.parent = this; }); this.children.push(...children); }, + replaceChildren(...children) { this.children = children; children.forEach(child => { child.parent = this; }); }, + remove() { this.parent.children = this.parent.children.filter(child => child !== this); }, + attachShadow() { this.shadow = element('shadow'); return this.shadow; }, + setAttribute(name, value) { this.attributes.set(name, value); }, + getAttribute(name) { return this.attributes.get(name) ?? null; }, + removeAttribute(name) { this.attributes.delete(name); }, + getRootNode() { return document; }, + addEventListener(type, listener) { this.listeners.set(type, listener); }, + getBoundingClientRect() { return this.bounds; }, + }); + document = { + adoptedStyleSheets: [], querySelectorAll: () => [], + createElement: element, + addEventListener(type, listener) { documentListeners.set(type, listener); }, + removeEventListener(type) { documentListeners.delete(type); }, + }; + document.documentElement = element('html'); + const target = element('button'); + target.id = 'target'; + target.textContent = 'Original content'; + target.style.cssText = 'color: red'; + const child = element('strong'); + target.append(child); + const context = vm.createContext({ + document, innerWidth: 800, innerHeight: 600, scrollX: 0, scrollY: 0, + crypto: { getRandomValues: values => values.fill(1) }, + CSS: { supports: () => true }, + CSSStyleSheet: class { replaceSync() {} }, + getComputedStyle: () => ({ display: 'block', visibility: 'visible', + color: 'rgb(31, 35, 40)', fontSize: '14px', fontFamily: 'sans-serif', + getPropertyValue: field => ({ width: '100px', height: '40px' })[field] || '' }), + MutationObserver: Observer, ResizeObserver: Observer, + addEventListener(type, listener) { windowListeners.set(type, listener); }, + removeEventListener(type) { windowListeners.delete(type); }, + }); + const run = (action, fields = {}) => { + const current = action === 'save' ? run('read') : null; + return JSON.parse(JSON.stringify(vm.runInContext( + `${runtime}(${JSON.stringify({ action, document_id: 'doc-1', + ...(current ? { target_ids: current.targets.map(item => item.id), region: current.region } : {}), + ...fields })}, ${textRuntime}, ${styleRuntime})`, context, + ))); + }; + const event = (node, trusted = true, fields = {}) => ({ + isTrusted: trusted, button: 0, composedPath: () => [node], + preventDefault() { this.prevented = true; }, stopImmediatePropagation() {}, stopPropagation() {}, ...fields, + }); + const click = (trusted = true) => { + const input = event(target, trusted); + documentListeners.get('click')(input); + return input; + }; + const choose = node => documentListeners.get('click')(event(node)); + const pointer = (type, clientX, clientY, fields = {}) => documentListeners.get(type)( + event(target, true, { clientX, clientY, pointerId: 1, ...fields }), + ); + return { document, target, child, context, run, click, choose, pointer, element, event, documentListeners, windowListeners, observers }; +} + +{ + const page = fixture(); + assert.equal(page.run('read').error, 'stale_document'); + assert.equal(page.run('start').active, true); + assert.equal(page.click(false).prevented, undefined); + assert.equal(page.run('read').target, null); + assert.equal(page.click().prevented, true); + const selected = page.run('read'); + assert.equal(selected.target.id, 'target-1'); + assert.equal(selected.popup, true); + page.click(); + assert.equal(page.run('read').popup, false); + page.click(); + assert.equal(page.run('read').popup, true); + assert.equal(page.run('save', { target_id: 'wrong', number: 1 }).error, 'stale_target'); + const saved = page.run('save', { target_id: 'target-1', number: 1 }); + assert.equal(saved.target, null); + const shadow = page.document.documentElement.children[0].shadow; + const pin = shadow.children.find(child => child.attributes?.get('data-ace-annotation-pin') === '1'); + assert.equal(pin.textContent, '1'); + assert.deepEqual(page.run('read').invalid_numbers, []); + page.run('exit'); + assert.equal(shadow.children[0].style.display, 'none'); + assert.equal(shadow.children[1].style.display, 'none'); + assert.equal(pin.style.display, 'block'); + page.target.bounds = { x: 150, y: 250, width: 100, height: 40 }; + page.observers.forEach(observer => observer.callback()); + assert.equal(pin.style.left, '150px'); + assert.equal(pin.style.top, '250px'); + page.target.isConnected = false; + // 目标掉线的那一刻就要被记为失效(read 就地 inspect),之后即使重新连上 + // 也不会复活——失效是粘性的。 + assert.deepEqual(page.run('read').invalid_numbers, [1]); + page.target.isConnected = true; + assert.deepEqual(page.run('read').invalid_numbers, [1]); + assert.equal(pin.style.display, 'none'); + assert.equal(page.target.style.cssText, 'color: red'); + assert.equal(page.target.textContent, 'Original content'); + assert.equal(page.target.children[0], page.child); + page.run('start'); + page.click(); + page.run('cancel'); + assert.equal(page.run('read').popup, false); + assert.equal(shadow.children.length, 5); + page.click(); + assert.equal(page.run('read').target.id, 'target-1'); + page.documentListeners.get('keydown')(page.event(page.target, true, { key: 'Escape' })); + assert.equal(page.run('read').active, false); + assert.equal(pin.style.display, 'none'); + const pageWorld = vm.createContext({ document: page.document }); + assert.equal(vm.runInContext('typeof __acecodePageAnnotationsV1', pageWorld), 'undefined'); + assert.equal(page.run('read', { document_id: 'doc-2' }).error, 'stale_document'); + assert.equal(page.run('send').error, 'unsupported_action'); + assert.equal(page.run('start', { document_id: 'doc-2' }).active, true); + assert.equal(page.observers[0].active, false); + assert.equal(page.observers[1].active, false); + assert.equal(page.document.documentElement.children.length, 1); + assert.equal(page.document.documentElement.children[0].shadow.children.length, 4); + assert.equal(page.run('read').error, 'stale_document'); + console.log('[pass] annotation runtime selects, opens, cancels, saves immutable pins and exits without changing content'); +} + +{ + // A WebUI menu or dialog floating over the page suspends the outline and the + // hover style card so they cannot punch through the app's own overlay. + const page = fixture(); + page.run('start'); + assert.equal(page.run('read').modal_suspended, false); + const shadow = page.document.documentElement.children[0].shadow; + const [outline, hoverOutline, infoCard] = shadow.children; + page.pointer('pointermove', 20, 30); + assert.equal(hoverOutline.style.display, 'block', 'hovering paints the element outline'); + assert.equal(infoCard.style.display, 'block', 'hovering paints the style card'); + const suspended = page.run('set_modal_suspended', { enabled: true }); + assert.equal(suspended.modal_suspended, true); + assert.equal(outline.style.display, 'none', 'suspension hides the selection outline'); + assert.equal(hoverOutline.style.display, 'none', 'suspension hides the hover outline'); + assert.equal(infoCard.style.display, 'none', 'suspension hides the hover style card'); + const resumed = page.run('set_modal_suspended', { enabled: false }); + assert.equal(resumed.modal_suspended, false); + assert.equal(hoverOutline.style.display, 'none', 'resuming does not resurrect stale hover chrome'); + assert.equal(infoCard.style.display, 'none'); + page.pointer('pointermove', 20, 31); + assert.equal(hoverOutline.style.display, 'block', 'the next hover repaints the outline after resuming'); + page.click(); + assert.equal(outline.style.display, 'block', 'selecting paints the selection outline'); + page.run('set_modal_suspended', { enabled: true }); + assert.equal(outline.style.display, 'none', 'suspension also hides a selected element outline'); + page.run('set_modal_suspended', { enabled: false }); + console.log('[pass] modal suspension hides selection/hover chrome and only repaints on the next hover'); +} + +{ + // The hover card belongs to the element under the pointer. Leaving the page + // (onto the app chrome, another window, or off-screen) and losing window + // focus both stop pointermove events, so both have to drop the card instead + // of leaving the last element's bubble pinned over the content. + const page = fixture(); + page.run('start'); + const shadow = page.document.documentElement.children[0].shadow; + const [, hoverOutline, infoCard] = shadow.children; + const pointerOut = page.documentListeners.get('pointerout'); + const blur = page.windowListeners.get('blur'); + assert.equal(typeof pointerOut, 'function', 'the runtime listens for the pointer leaving the document'); + assert.equal(typeof blur, 'function', 'the runtime listens for window focus loss'); + page.pointer('pointermove', 20, 30); + assert.equal(infoCard.style.display, 'block'); + pointerOut(page.event(page.target, true, { relatedTarget: page.child })); + assert.equal(infoCard.style.display, 'block', 'moving between page elements keeps the card'); + pointerOut(page.event(page.target, true, { relatedTarget: null })); + assert.equal(hoverOutline.style.display, 'none', 'leaving the page hides the hover outline'); + assert.equal(infoCard.style.display, 'none', 'leaving the page hides the style card'); + page.pointer('pointermove', 20, 34); + assert.equal(infoCard.style.display, 'block', 'hovering again repaints the card'); + blur(); + assert.equal(hoverOutline.style.display, 'none', 'window blur hides the hover outline'); + assert.equal(infoCard.style.display, 'none', 'window blur hides the style card'); + console.log('[pass] hover chrome dies on pointer-leave and window blur instead of persisting over the page'); +} + +{ + const page = fixture(); + page.run('start'); + page.click(); + page.run('save', { target_id: 'target-1', number: 1 }); + const shadow = page.document.documentElement.children[0].shadow; + const pin = shadow.children.find(child => child.attributes?.get('data-ace-annotation-pin') === '1'); + assert.ok(pin); + + let snapshot = page.run('hide_markers', { enabled: true }); + assert.equal(snapshot.markers_hidden, true); + assert.equal(pin.style.display, 'none'); + snapshot = page.run('hide_markers', { enabled: false }); + assert.equal(snapshot.markers_hidden, false); + assert.equal(pin.style.display, 'block'); + + page.run('original', { enabled: true }); + assert.equal(pin.style.display, 'none'); + page.run('original', { enabled: false }); + assert.equal(pin.style.display, 'block'); + + snapshot = page.run('discard'); + assert.equal(snapshot.active, true); + assert.equal(snapshot.popup, false); + assert.equal(snapshot.targets.length, 0); + assert.equal(snapshot.markers_hidden, false); + assert.equal(shadow.children.includes(pin), false); + console.log('[pass] hide markers, hold-to-compare original view, and discard-all keep separate toolbar semantics'); +} + +{ + for (const ancestorRemoval of [false, true]) { + const page = fixture(); + const ancestor = page.element('section'); + page.target.parentNode = ancestor; + page.run('start'); page.click(); + page.run('add_target'); + const second = page.element('aside'); + page.choose(second); + page.run('add_region'); page.pointer('pointerdown', 1, 2); page.pointer('pointerup', 40, 50); + page.run('save', { target_id: null, number: 1 }); + page.run('exit'); + const removed = ancestorRemoval ? ancestor : page.target; + page.observers.forEach(observer => observer.records.push({ removedNodes: [removed] })); + assert.equal(page.target.isConnected, true); + assert.deepEqual(page.run('read').invalid_numbers, [1]); + const similar = page.element('button'); similar.id = page.target.id; + page.run('start'); page.choose(similar); + assert.equal(page.run('read').target.id, 'target-3'); + assert.deepEqual(page.run('read').invalid_numbers, [1]); + } + const draft = fixture(); + draft.run('start'); draft.click(); + draft.observers.forEach(observer => observer.records.push({ removedNodes: [draft.target] })); + assert.equal(draft.run('read').popup, false); + assert.deepEqual(draft.run('read').targets, []); + console.log('[pass] queued exact-node/ancestor removal is sticky across reinsertion, invalidates multi-target regions and never relocates similar nodes'); +} + +{ + const page = fixture(); + page.run('start'); page.click(); + const second = page.element('section'); + second.bounds = { x: 200, y: 300, width: 200, height: 100 }; + page.run('add_target'); + assert.equal(page.run('read').popup, true); + assert.equal(page.run('read').selection_mode, 'element'); + page.choose(second); + assert.equal(page.run('read').target.id, 'target-2'); + assert.equal(page.run('read').targets.length, 2); + page.run('add_target'); page.choose(page.target); + assert.equal(page.run('read').targets.length, 2); + assert.equal(page.run('read').selection_mode, null); + assert.equal(page.run('select_target', { target_id: 'target-2' }).target.tag, 'section'); + assert.equal(page.run('select_target', { target_id: 'absent' }).error, 'stale_target'); + page.run('add_region'); + page.context.scrollX = 40; page.context.scrollY = 500; + page.pointer('pointerdown', 80, 90); + page.pointer('pointermove', 20, 30); + page.pointer('pointerup', 20, 30); + const first = page.run('read'); + assert.deepEqual(first.region, { x: 60, y: 530, width: 60, height: 60 }); + assert.equal(first.target, null); + assert.equal(first.targets.length, 2); + const shadow = page.document.documentElement.children[0].shadow; + assert.equal(shadow.children[3].style.top, '30px'); + page.context.scrollY = 520; + page.windowListeners.get('scroll')(); + assert.equal(shadow.children[3].style.top, '10px'); + assert.deepEqual(page.run('read').region, first.region); + page.run('add_region'); + page.pointer('pointerdown', 10, 15); + page.context.scrollY = 550; + page.pointer('pointerup', 90, 80); + const replaced = page.run('read'); + assert.deepEqual(replaced.region, { x: 50, y: 535, width: 80, height: 95 }); + assert.equal(replaced.targets.length, 2); + assert.equal(replaced.target, null); + page.run('select_target', { target_id: 'target-1' }); + assert.equal(page.run('read').target.id, 'target-1'); + page.run('select_region'); + assert.equal(page.run('read').target, null); + assert.equal(page.run('save', { target_id: null, target_ids: ['target-2'], number: 1 }).error, 'stale_target'); + page.run('save', { target_id: null, number: 1, region: { + height: replaced.region.height, width: replaced.region.width, x: replaced.region.x, y: replaced.region.y, + } }); + assert.equal(shadow.children.filter(node => node.textContent === '1').length, 1); + assert.equal(page.run('read').targets.length, 0); + assert.equal(page.run('read').region, null); + page.run('exit'); + page.context.scrollY = 600; + page.windowListeners.get('scroll')(); + const savedPin = shadow.children.find(node => node.attributes?.get('data-ace-annotation-pin') === '1'); + const savedOutline = shadow.children.find(node => node.attributes?.get('data-ace-annotation-pin-outline') === '1'); + assert.equal(savedPin.style.top, '-65px'); + assert.equal(savedOutline.style.top, '-65px'); + page.run('start'); page.click(); + page.run('add_target'); page.choose(second); + page.run('add_region'); page.pointer('pointerdown', 10, 10); page.pointer('pointerup', 30, 30); + page.run('cancel'); + assert.deepEqual(page.run('read').targets, []); + assert.equal(page.run('read').region, null); + assert.equal(shadow.children.length, 6); + console.log('[pass] multiple exact targets deduplicate/switch, one page region replaces across scrolling, one pin saves and cancellation clears the whole draft'); +} + +{ + const page = fixture(); + page.run('start'); page.click(); + page.run('add_region'); + page.pointer('pointerdown', 10, 10, { isTrusted: false }); + page.pointer('pointerup', 100, 100); + assert.equal(page.run('read').region, null); + page.pointer('pointerdown', 10, 10); + page.pointer('pointerup', 20, 20, { pointerId: 2 }); + assert.equal(page.run('read').region, null); + page.pointer('pointercancel', 20, 20); + page.documentListeners.get('keydown')(page.event(page.target, true, { key: 'Escape' })); + assert.equal(page.run('read').popup, true); + assert.equal(page.run('read').selection_mode, null); + assert.equal(page.run('read').targets.length, 1); + page.run('add_region'); page.pointer('pointerdown', 10, 10); page.pointer('pointerup', 10, 10); + assert.equal(page.run('read').region, null); + page.run('cancel'); + console.log('[pass] synthetic/foreign/cancelled/zero-area drags cannot replace a region; Escape returns to the same draft'); +} + +{ + const page = fixture(); + page.run('start'); + page.click(); + page.target.isConnected = false; + assert.equal(page.run('save', { target_id: 'target-1', number: 1 }).error, 'stale_target'); + assert.equal(page.run('read').popup, false); + assert.equal(page.run('read').target, null); + console.log('[pass] detached exact target cannot be saved or relocated'); +} + +{ + const page = fixture(); + assert.equal(page.run('start').active, true); + // The toolbar must be able to start element picking before any popup exists. + assert.equal(page.run('add_target').selection_mode, 'element'); + page.choose(page.target); + const selected = page.run('read'); + assert.equal(selected.popup, true); + assert.equal(selected.target.id, 'target-1'); + + const regionPage = fixture(); + assert.equal(regionPage.run('start').active, true); + assert.equal(regionPage.run('add_region').selection_mode, 'region'); + regionPage.pointer('pointerdown', 10, 20); + regionPage.pointer('pointermove', 40, 60); + regionPage.pointer('pointerup', 40, 60); + const drawn = regionPage.run('read'); + assert.equal(drawn.popup, true); + assert.deepEqual(drawn.region, { x: 10, y: 20, width: 30, height: 40 }); + assert.deepEqual(drawn.targets, []); + regionPage.run('cancel'); + assert.equal(regionPage.run('read').popup, false); + console.log('[pass] toolbar starts element and region drafts before a popup exists'); +} + +{ + let release; + const requests = []; + const changes = []; + const queuedRegion = { x: 20, y: 700, width: 80, height: 30 }; + const actor = createPageAnnotationController({ + pageId: 'page-1', onChange: next => changes.push(next), + invoke: async (pageId, command) => { + requests.push({ pageId, command }); + if (command.action === 'read') await new Promise(resolve => { release = resolve; }); + return { ok: true, page_id: pageId, annotations: { document_id: 'doc-1', revision: 2, active: true } }; + }, + }); + actor.observe({ document_id: 'doc-1', revision: 1, active: true, target: { id: 'target-1' }, + targets: [{ id: 'target-1' }, { id: 'target-2' }], region: queuedRegion }); + const read = actor.command('read'); + const save = actor.command('save', { description: 'Requested change' }); + await Promise.resolve(); + assert.equal(requests.length, 1); + actor.observe({ document_id: 'doc-2', revision: 3, active: false }); + queuedRegion.x = 999; + release(); + await read; + await save; + assert.equal(requests[1].command.target_id, 'target-1'); + assert.equal(requests[1].command.document_id, 'doc-1'); + assert.deepEqual(requests[1].command.target_ids, ['target-1', 'target-2']); + assert.deepEqual(requests[1].command.region, { x: 20, y: 700, width: 80, height: 30 }); + assert.equal(actor.getSnapshot().document_id, 'doc-2'); + const count = changes.length; + actor.dispose(); + assert.equal((await actor.command('start')).cancelled, true); + actor.observe({ revision: 4 }); + assert.equal(changes.length, count); + console.log('[pass] trusted controller serializes commands, binds save identity and rejects late snapshots after replacement/disposal'); +} + +{ + const calls = []; + const result = await runPageAnnotationCommand('local-without-session', { action: 'start', document_id: '' }, { + aceDesktop_agentBrowserAnnotationCommand: async request => { calls.push(request); return '{"ok":true}'; }, + }); + assert.equal(result.ok, true); + assert.deepEqual(calls, [{ page_id: 'local-without-session', command: { action: 'start', document_id: '' } }]); + assert.equal((await runPageAnnotationCommand('page-1', {}, {})).ok, false); + const position = pageAnnotationPopupPosition({ + width: 400, height: 300, popupWidth: 200, popupHeight: 150, + target: { bounds: { x: 700, y: 500, height: 50 } }, viewport: { width: 800, height: 600 }, + }); + assert.deepEqual(position, { left: 192, top: 92 }); + assert.deepEqual(pageAnnotationPopupPosition({ width: 120, height: 80, popupWidth: 104, popupHeight: 64 }), { left: 8, top: 8 }); + assert.deepEqual(pageAnnotationPopupDragPosition({ + startLeft: 100, startTop: 50, deltaX: 300, deltaY: 250, + width: 600, height: 400, popupWidth: 200, popupHeight: 150, + }), { left: 392, top: 242 }); + assert.deepEqual(pageAnnotationPopupDragPosition({ + startLeft: 100, startTop: 50, deltaX: -300, deltaY: -250, + width: 600, height: 400, popupWidth: 200, popupHeight: 150, + }), { left: 8, top: 8 }); + console.log('[pass] annotation bridge is session-independent and popup placement accounts for viewport zoom and edges'); +} + +{ + const hooks = []; + let cursor = 0; + const calls = []; + const popupSource = fs.readFileSync(new URL('../components/PageAnnotations.jsx', import.meta.url), 'utf8'); + const compiled = await transformWithEsbuild( + popupSource.replace(/^import[\s\S]*?;\r?$/gm, '').replace(/^export /gm, ''), + 'PageAnnotations.jsx', { loader: 'jsx', jsxFactory: 'React.createElement' }, + ); + const popup = vm.runInNewContext(`${compiled.code}\nPageAnnotationPopup`, { + React, + PageAnnotationTextField: () => null, + clearTimeout, setTimeout, + useRef: value => ({ current: value ?? null }), useEffect: () => {}, useLayoutEffect: () => {}, + useState: initial => { + const index = cursor++; + if (!(index in hooks)) hooks[index] = initial; + return [hooks[index], next => { hooks[index] = next; }]; + }, + }); + const snapshot = { document_id: 'doc-1', popup: true, target: { id: 'target-1', tag: 'button' }, + targets: [{ id: 'target-1', tag: 'button', locator: 'button#first' }], region: null }; + const render = () => { + cursor = 0; + return popup({ snapshot, command: (...args) => calls.push(args), working: false, viewportRef: { current: null } }); + }; + const nodes = node => { + if (!node || typeof node !== 'object') return []; + if (typeof node.type === 'function') return nodes(node.type(node.props)); + return [node, ...React.Children.toArray(node.props?.children).flatMap(nodes)]; + }; + const textarea = tree => nodes(tree).find(node => node.type === 'textarea'); + textarea(render()).props.onChange({ target: { value: 'Shared request for every target' } }); + let tree = render(); + const adjust = nodes(tree).find(node => node.props?.['aria-label'] === '调整'); + assert.equal(adjust.props['aria-pressed'], undefined); + assert.equal(adjust.props['aria-expanded'], false); + const sendBar = fs.readFileSync(new URL('../components/PageAnnotationSendBar.jsx', import.meta.url), 'utf8'); + assert.match(sendBar, /run\('hide_markers'/); + assert.match(sendBar, /run\('discard'\)/); + assert.match(sendBar, /requestAnnotationSubmit\(sessionId\)[\s\S]{0,220}result\?\.ok === false/, + 'toolbar sends must inspect the shared submission result'); + assert.match(sendBar, /!active \|\| snapshot\.selection_mode \|\| snapshot\.popup/); + assert.match(sendBar, /这一页的所有编辑都将被移除/); + assert.match(sendBar, /其他页签的待发批注不受影响/); + assert.match(sendBar, /]*nativeOverlayMode="overlap"[^>]*nativeOverlayInteraction="disabled"/); + assert.match(sendBar, /suspendDialogChrome[\s\S]*setAnnotationChromeSuspended\('dialog', enabled/); + assert.match(sendBar, /closeDiscard[\s\S]*setConfirmDiscard\(false\)[\s\S]*suspendDialogChrome\(false\)/); + assert.match(sendBar, /setConfirmDiscard\(true\)[\s\S]*suspendDialogChrome\(true\)/); + assert.doesNotMatch(sendBar, />\s*放弃。\s*\s*放弃\s* \{[\s\S]{0,180}await selectAgentBrowserPage\(pageId\)/, + 'annotation editing must activate the native page before reopening the record'); + assert.match(panelSource, /!annotations\.snapshot\?\.document_id/, + 'the editor is published only after the remounted pane has its annotation document'); + assert.match(annotationsSource, /focusAnnotationDescription\(inputRef\.current\)/, + 'opening an element editor or an existing record must put the caret in the description'); + const annotationFocusSource = fs.readFileSync(new URL('./annotationFocus.js', import.meta.url), 'utf8'); + assert.match(annotationFocusSource, /aceDesktop_focusActiveWebview/, + 'the description focus must return native focus from the browser surface to the WebUI first'); + assert.match(annotationsSource, /querySelectorAll\('\[role="menu"\]'\)/); + assert.match(annotationsSource, /setAnnotationChromeSuspended\('menu', menuOpen\(\), apply\)/); + assert.match(annotationsSource, /action === 'set_modal_suspended'/, + 'chrome suppression must not mark the annotation session busy'); + snapshot.selection_mode = 'element'; + tree = render(); + assert.equal(tree.props.style.display, 'none'); + assert.equal(tree.props['data-ace-native-overlay'], undefined); + snapshot.targets.push({ id: 'target-2', tag: 'section', locator: 'section' }); + snapshot.target = snapshot.targets[1]; + snapshot.selection_mode = null; + tree = render(); + assert.equal(textarea(tree).props.value, 'Shared request for every target'); + assert.equal(tree.props['data-ace-native-overlay'], 'overlap'); + assert.equal(nodes(tree).filter(node => String(node.props?.className || '').includes('ace-annotation-chip')).length, 0); + snapshot.region = { x: 0, y: 500, width: 40, height: 30 }; + snapshot.target = null; + tree = render(); + assert.equal(nodes(tree).filter(node => node.type === 'textarea').length, 1); + assert.equal(nodes(tree).filter(node => node.type === 'input').length, 0); + await tree.props.onSubmit({ preventDefault() {} }); + assert.equal(calls.at(-1)[0], 'save'); + assert.equal(calls.at(-1)[1].description, 'Shared request for every target'); + const panel = fs.readFileSync(new URL('../components/AgentBrowserPanel.jsx', import.meta.url), 'utf8'); + assert.match(panel, /key=\{`\$\{pageId\}:\$\{annotations.snapshot.document_id\}`\}/); + console.log('[pass] trusted popup preserves shared description while hidden for selection and when switching element/region targets'); +} + +{ + const panel = fs.readFileSync(new URL('../components/AgentBrowserPanel.jsx', import.meta.url), 'utf8'); + const popup = fs.readFileSync(new URL('../components/PageAnnotations.jsx', import.meta.url), 'utf8'); + assert.match(panel, /createAgentBrowserElementContext\(selectedElement, event.detail\)/); + assert.match(panel, /toggleAgentBrowserElementSelection\(pageId\)/); + assert.match(popup, /data-ace-native-overlay=\{snapshot.selection_mode \? undefined : 'overlap'\}/); + assert.doesNotMatch(popup, /onAddContext|submitMessage|fetch\(|aceDesktop_.*(?:Write|Send)/); + const windows = fs.readFileSync(new URL('../../../src/apps/desktop/agent_browser_host.cpp', import.meta.url), 'utf8'); + assert.match(windows, /#include "agent_browser_native_commands_win\.hpp"/); + assert.match(windows, /agent_browser_windows::evaluate_annotation\(page->webview,/); + const commands = fs.readFileSync(new URL('../../../src/apps/desktop/agent_browser_native_commands_win.cpp', import.meta.url), 'utf8'); + assert.match(commands, /Page.createIsolatedWorld/); + assert.match(commands, /"contextId", world\["executionContextId"\]/); + assert.match(commands, /"grantUniveralAccess", false/); + assert.doesNotMatch(source, /chrome\.webview|webkit\.messageHandlers|postMessage|fetch\(/); + console.log('[pass] annotation popup uses local native occlusion and leaves source-selection/conversation path independent'); +} diff --git a/web/src/lib/questionPickerLayout.test.js b/web/src/lib/questionPickerLayout.test.js index 78a982aed..b808ea42f 100644 --- a/web/src/lib/questionPickerLayout.test.js +++ b/web/src/lib/questionPickerLayout.test.js @@ -31,7 +31,13 @@ const dockStart = chatView.indexOf('
\s*[\s\S]*? 0 ? version : 2; + normalized.pages = (Array.isArray(ctx.pages) ? ctx.pages : []) + .filter((page) => page && typeof page === 'object' && !Array.isArray(page)); + } return normalized; } diff --git a/web/src/lib/sessionStartMaskArchitecture.test.js b/web/src/lib/sessionStartMaskArchitecture.test.js index 78b34f945..eac3f86bc 100644 --- a/web/src/lib/sessionStartMaskArchitecture.test.js +++ b/web/src/lib/sessionStartMaskArchitecture.test.js @@ -75,7 +75,7 @@ run('等待期间发送与停止入口早退,不依赖遮罩是否已出现', () assert.match( chat, - /if \(sessionRuntimeUnavailable\) return;\s*\/\/[^\n]*\n\s*if \(sessionStartMask\.isBlocking\(\)\) return;/, + /if \(sessionRuntimeUnavailable\) return fail\(\);\s*\/\/[^\n]*\n\s*if \(sessionStartMask\.isBlocking\(\)\) return fail\(\);/, ); assert.match( between(chat, 'const stopCurrentWork = useStableCallback(', 'abort();'), @@ -126,7 +126,9 @@ run('建 worktree 的首条消息不走默认 30 秒超时,文案保留中英文 const api = source('lib/api.js'); assert.match(api, /export const WORKTREE_CREATE_TIMEOUT_MS = 5 \* 60 \* 1000;/); - assert.match(api, /body\.worktree\?\.create \? \{ timeoutMs: WORKTREE_CREATE_TIMEOUT_MS \} : \{\}/); + assert.match(api, /const requestOptions = body\.worktree\?\.create\s*\? \{ timeoutMs: WORKTREE_CREATE_TIMEOUT_MS \}\s*: \{\};/s); + assert.match(api, /const requestOptions =[\s\S]*?\/messages`,/); + assert.doesNotMatch(api, /annotation_reconcile_only/); for (const catalog of [source('i18n/catalogs/zh-CN.js'), source('i18n/catalogs/en-US.js')]) { assert.match(catalog, /sessionCreating:/); assert.match(catalog, /worktreeCreating:/); diff --git a/web/src/lib/sidebarSessionLoadingArchitecture.test.js b/web/src/lib/sidebarSessionLoadingArchitecture.test.js index e899434b6..e70e91a54 100644 --- a/web/src/lib/sidebarSessionLoadingArchitecture.test.js +++ b/web/src/lib/sidebarSessionLoadingArchitecture.test.js @@ -138,7 +138,7 @@ run('会话只有一个内容遮罩,直接挂在会话主列而非输入区', assert.equal(anchor?.value?.value, 'true', '遮罩必须以会话主列为直接父节点,不能落入输入区'); assert.match(chat.slice(parent.start, parent.openingElement.end), /ace-session-panel[^']*relative/); assert.match(chat, /readOnly: readOnlyExternalSession/); - assert.match(chat, /if \(sessionRuntimeUnavailable\) return;/); + assert.match(chat, /if \(sessionRuntimeUnavailable\) return fail\(\);/); assert.match(chat, /if \(!targetSid \|\| busy \|\| drainRef\.current \|\| sessionRuntimeUnavailable\) return;/); }); diff --git a/web/src/lib/slateComposerArchitecture.test.js b/web/src/lib/slateComposerArchitecture.test.js index 7e68cea88..d39ba7c73 100644 --- a/web/src/lib/slateComposerArchitecture.test.js +++ b/web/src/lib/slateComposerArchitecture.test.js @@ -281,7 +281,7 @@ run('rich context paste mutates Slate state while send gating reads the controll assert.match(composer, /INSERT_TEXT[\s\S]*applyPlainTextPaste\(detail\.text, detail\.selection\)/); assert.match(composer, /const applyPlainTextPaste = useCallback\([\s\S]*ensureLegalEditorDocument\(editor\)[\s\S]*Transforms\.select[\s\S]*insertPlainText\(editor, normalizedText\)/); assert.doesNotMatch(composer, /execCommand/); - assert.match(inputBar, /getInputBarActionState\(\{ value: draftValue, disabled, busy, hasExtras, submitting, canRetryLastUserMessage, queuePaused, busySendMode \}\)/); + assert.match(inputBar, /getInputBarActionState\(\{ value: draftValue, disabled, busy, hasExtras, hasPendingAnnotations, submitting, canRetryLastUserMessage, queuePaused, busySendMode \}\)/); assert.match(inputBar, / \{[\s\S]*setComposerValue\(next, normalized\)/); }); diff --git a/web/src/lib/themeSurfaces.test.js b/web/src/lib/themeSurfaces.test.js index 8ebfa395a..4c6507841 100644 --- a/web/src/lib/themeSurfaces.test.js +++ b/web/src/lib/themeSurfaces.test.js @@ -20,6 +20,7 @@ import { presentSystemNotice } from './systemNotice.js'; import { tr } from '../i18n/index.js'; import { clsx } from './format.js'; import { userMessageTextPreview } from './userMessagePreview.js'; +import * as pageAnnotationMessage from './pageAnnotationMessage.js'; async function run(name, fn) { await fn(); console.log(`[pass] ${name}`); } const read = (relative) => readFileSync(new URL(relative, import.meta.url), 'utf8'); @@ -237,6 +238,7 @@ await run('actual messages restrict custom wallpaper to user text and preserve a useTranslation: () => ({ t: tr }), useSlashCommands: () => ({ commands: [] }), resolveLeadingSlashCommand: () => null, renderMarkdownBlocks, useStreamingRenderThrottle, assistantChromeState, presentSystemNotice, clsx, VsIcon: () => null, userMessageTextPreview, + ...pageAnnotationMessage, PageAnnotationMessageCard: () => null, ActivityLine: activityLineComponent({ clsx, VsIcon: () => null }), AttachmentStrip: ({ align }) => React.createElement('span', { 'data-attachment-align': align }, 'Attachment'), }); diff --git a/web/src/lib/trailingUserMessageRetry.test.js b/web/src/lib/trailingUserMessageRetry.test.js index 07db77b3e..a9485cd3b 100644 --- a/web/src/lib/trailingUserMessageRetry.test.js +++ b/web/src/lib/trailingUserMessageRetry.test.js @@ -115,7 +115,7 @@ const inputBar = fs.readFileSync(new URL('../components/InputBar.jsx', import.me // Dictation consumes Enter until recognition completes; committed text then // reaches the same existing submission gate. assert.match(inputBar, /const submit = \(options\) => \{\s*if \(speech\.interceptSubmit\(\)\) return;/); -assert.match(inputBar, /const currentDraft = serializeComposerGoal\(valueRef\.current, contentRef\.current, goalModeRef\.current\);\s*const currentAction = getInputBarActionState\(\{ value: currentDraft\.text, disabled, busy, hasExtras, submitting, canRetryLastUserMessage, queuePaused, busySendMode \}\);\s*if \(!currentAction\.canSubmit\) return;/); +assert.match(inputBar, /const currentDraft = serializeComposerGoal\(valueRef\.current, contentRef\.current, goalModeRef\.current\);\s*const currentAction = getInputBarActionState\(\{ value: currentDraft\.text, disabled, busy, hasExtras, hasPendingAnnotations, submitting, canRetryLastUserMessage, queuePaused, busySendMode \}\);\s*if \(!currentAction\.canSubmit\) return;/); assert.match(inputBar, /onSubmit\?\.\(currentDraft\.text, \{ sendMode \}\)/); assert.match(inputBar, /onSubmit=\{submit\}/); assert.match(inputBar, / { const chat = source('components/ChatView.jsx'); const submit = section(chat, 'const submit = useStableCallback((text, { sendMode', 'const isBuiltin ='); - assert.match(submit, /if \(sendMode === 'fork' && route\.kind === 'message'\) \{\s*sendInForkedSession\(/); + assert.match(submit, /if \(sendMode === 'fork' && route\.kind === 'message'\) \{[\s\S]*?sendInForkedSession\(/); const busyBranch = section(chat, 'if ((liveTranscript.busy || liveTranscript.abortPending) && !isBuiltin) {', 'const targetSid = sid;'); assert.match(busyBranch, /const queuedId = enqueueInput\(payload\);/); // 设置 > 常规 > 输入框「后续消息处理方式」选排队时 Enter 与 Ctrl+Enter 对调,统一由 busySendAction 判定。 diff --git a/web/src/styles/globals.css b/web/src/styles/globals.css index 3256987dd..0b0e195c4 100644 --- a/web/src/styles/globals.css +++ b/web/src/styles/globals.css @@ -2188,7 +2188,7 @@ body { display: flex; align-items: center; gap: 4px; - min-height: 52px; + min-height: 44px; padding: 4px 4px 4px 12px; border-bottom: 1px solid var(--ace-settings-divider); } @@ -5570,6 +5570,1074 @@ a.ace-thread-link:focus-visible { align-items: center; gap: 2px; } +.ace-agent-browser-annotation-toggle { + width: 30px; + height: 30px; + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0; + border: 0; + border-radius: 999px; + background: transparent; + color: var(--ace-fg-2); + font: inherit; + font-size: 13px; + font-weight: 650; + cursor: pointer; +} +.ace-agent-browser-annotation-toggle:hover:not(:disabled) { + background: var(--ace-surface-alt); + color: var(--ace-fg); +} +.ace-agent-browser-annotation-toggle.is-active { + background: #d9ecff; + color: #185fae; +} +.ace-agent-browser-annotation-toggle:disabled { + opacity: 0.38; + cursor: default; +} +.ace-page-annotation-message { + width: min(280px, 100%); + border: 1px solid var(--ace-border); + border-radius: 16px; + background: var(--ace-surface); + box-shadow: var(--ace-shadow-lg); + color: var(--ace-fg); +} +.ace-page-annotation-message-shot { + display: block; + width: 100%; + height: 72px; + padding: 0; + border: 0; + overflow: hidden; + background: transparent; + cursor: zoom-in; +} +.ace-page-annotation-message-shot img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; + object-position: top; +} +.ace-page-annotation-message-body { + display: flex; + flex-direction: column; + gap: 4px; + padding: 10px 12px 12px; +} +.ace-page-annotation-message-title { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + font-size: 12px; + font-weight: 650; +} +.ace-page-annotation-message-title > span:last-child { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.ace-page-annotation-message-mark { + display: inline-flex; + flex: 0 0 auto; + color: var(--ace-fg-2); +} +.ace-page-annotation-message-text { + margin: 0; + font-size: 13px; + line-height: 1.45; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.ace-page-annotation-message-number { + margin-right: 6px; + color: var(--ace-fg-2); +} +.ace-page-annotation-message-summary { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; + height: 22px; + padding: 0 8px; + border: 1px solid var(--ace-border); + border-radius: 8px; + background: var(--ace-surface); + color: var(--ace-fg-2); + font-size: 11.5px; + line-height: 1; + white-space: nowrap; +} +/* 待发批注卡片(输入框上方)。超过 5 条时卡片内部滚动,不把输入框顶走。 */ +.ace-annotation-pending { + margin: 0 10px 6px; + border: 1px solid var(--ace-border); + border-radius: 12px; + background: var(--ace-surface); + color: var(--ace-fg); + overflow: hidden; +} +.ace-annotation-pending-head { + display: flex; + align-items: center; + gap: 8px; + padding: 7px 10px; + border-bottom: 1px solid var(--ace-border); + font-size: 12px; + font-weight: 650; +} +.ace-annotation-pending-count { + color: var(--ace-fg-2); + font-weight: 500; +} +.ace-annotation-pending-undo { + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--ace-fg-2); + font-weight: 500; +} +.ace-annotation-pending-undo button { + border: 0; + background: transparent; + color: var(--ace-accent, #185fae); + font: inherit; + cursor: pointer; + padding: 0; +} +.ace-annotation-pending-body { + max-height: 168px; + overflow-y: auto; +} +.ace-annotation-pending-group + .ace-annotation-pending-group { + border-top: 1px solid var(--ace-border); +} +.ace-annotation-pending-page { + display: flex; + align-items: center; + gap: 6px; + padding: 6px 10px 2px; + color: var(--ace-fg-2); + font-size: 11.5px; +} +.ace-annotation-pending-closed { + flex: 0 0 auto; + padding: 1px 6px; + border-radius: 6px; + background: var(--ace-surface-alt); + font-size: 10.5px; +} +.ace-annotation-pending-row { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 10px 6px; + font-size: 12.5px; +} +.ace-annotation-pending-thumb { + flex: 0 0 auto; + width: 24px; + height: 24px; + border-radius: 6px; + object-fit: cover; + object-position: top; + background: var(--ace-surface-alt); +} +.ace-annotation-pending-thumb.is-empty { + display: inline-flex; + align-items: center; + justify-content: center; + color: var(--ace-fg-mute, var(--ace-fg-2)); +} +.ace-annotation-pending-tag { + flex: 0 0 auto; + padding: 1px 6px; + border-radius: 6px; + background: var(--ace-surface-alt); + color: var(--ace-fg-2); + font-family: var(--ace-font-mono, ui-monospace, monospace); + font-size: 11px; +} +.ace-annotation-pending-text { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.ace-annotation-pending-action { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--ace-fg-2); + cursor: pointer; +} +.ace-annotation-pending-action:hover { + background: var(--ace-surface-alt); + color: var(--ace-fg); +} +.ace-page-annotation-message-footer { + position: relative; + display: flex; + align-items: center; + gap: 8px; + padding: 8px 10px; + min-width: 0; +} +.ace-page-annotation-message-footer .ace-page-annotation-message-title { + flex: 1 1 auto; + min-width: 0; +} +.ace-page-annotation-message-footer .ace-page-annotation-message-summary { + flex: 0 0 auto; + cursor: default; +} +.ace-page-annotation-message-detail { + position: absolute; + z-index: 30; + bottom: calc(100% - 4px); + left: 8px; + right: 8px; + display: flex; + flex-direction: column; + border: 1px solid var(--ace-border); + border-radius: 10px; + background: var(--ace-surface); + box-shadow: var(--ace-shadow-lg); + overflow: hidden; +} +.ace-page-annotation-message-detail-list { + overflow-y: auto; + padding: 4px 0; +} +.ace-page-annotation-message-detail-group + .ace-page-annotation-message-detail-group { + border-top: 1px solid var(--ace-border); + margin-top: 4px; + padding-top: 4px; +} +.ace-page-annotation-message-detail-page { + padding: 2px 10px 3px; + color: var(--ace-fg-2); + font-size: 11px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.ace-page-annotation-message-detail-row { + display: flex; + align-items: baseline; + gap: 6px; + padding: 2px 10px; + font-size: 12px; + line-height: 1.45; +} +.ace-page-annotation-message-tag { + flex: 0 0 auto; + padding: 0 5px; + border-radius: 5px; + background: var(--ace-surface-alt); + color: var(--ace-fg-2); + font-family: var(--ace-font-mono, ui-monospace, monospace); + font-size: 10.5px; +} +.ace-page-annotation-message-detail-text { + min-width: 0; + overflow-wrap: anywhere; +} +.ace-page-annotation-message-more { + border: 0; + border-top: 1px solid var(--ace-border); + padding: 5px 10px; + background: transparent; + color: var(--ace-accent, #185fae); + font: inherit; + font-size: 11.5px; + text-align: left; + cursor: pointer; +} +.ace-annotation-toolbar { + --ace-annotation-page-background: var(--ace-surface); + position: absolute; + z-index: 20; + left: 50%; + bottom: 16px; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 4px; + max-width: calc(100% - 24px); + height: 52px; + padding: 8px 10px 8px 12px; + border: 1px solid transparent; + border-radius: 14px; + background: #3a3a3a; + color: #f7f7f7; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 8px 22px rgba(0, 0, 0, 0.24); + isolation: isolate; +} +.ace-annotation-toolbar > button { + width: 34px; + height: 34px; + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + border: 0; + border-radius: 10px; + background: transparent; + color: inherit; + cursor: pointer; +} +.ace-annotation-toolbar > button:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.08); +} +.ace-annotation-toolbar > button[aria-pressed="true"] { + background: rgba(255, 255, 255, 0.14); +} +.ace-annotation-toolbar > button:disabled { + opacity: 0.35; + cursor: default; +} +.ace-annotation-toolbar > button.ace-annotation-send { + width: auto; + min-width: 64px; + height: 36px; + margin-left: 4px; + padding: 0 16px; + border-radius: 12px; + background: #3b93ff; + color: #fff; + font: inherit; + font-size: 15px; + font-weight: 650; + letter-spacing: 0.02em; +} +.ace-annotation-toolbar > button.ace-annotation-send:hover:not(:disabled) { + background: #2b84f3; +} +.ace-annotation-grip { + display: grid; + grid-template-columns: repeat(2, 3px); + gap: 3px 3px; + width: 16px; + height: 22px; + align-content: center; + justify-content: center; + margin: 0 4px 0 2px; + opacity: 0.92; + cursor: grab; + touch-action: none; +} +.ace-annotation-grip:active { + cursor: grabbing; +} +.ace-annotation-grip i { + width: 3px; + height: 3px; + border-radius: 50%; + background: currentColor; +} +.ace-annotation-count { + min-width: 104px; + margin: 0 10px 0 2px; + font-size: 15px; + font-weight: 650; + font-variant-numeric: tabular-nums; + text-align: center; + white-space: nowrap; + letter-spacing: 0.01em; +} +.ace-annotation-toolbar-error { + min-width: 0; + max-width: 220px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: #ffb4b4; + font-size: 12px; +} +.ace-annotation-toolbar-note { + color: rgba(255, 255, 255, 0.72); + font-size: 12px; + white-space: nowrap; +} +.ace-annotation-tooltip { + position: fixed; + z-index: 90; + display: inline-flex; + align-items: center; + gap: 8px; + max-width: 240px; + padding: 6px 9px; + transform: translateX(-50%); + border-radius: 7px; + background: #2f2f2f; + color: #fff; + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.22); + font-size: 12px; + line-height: 1.25; + white-space: nowrap; + pointer-events: none; +} +.ace-annotation-tooltip kbd { + padding: 1px 5px; + border: 1px solid rgba(255, 255, 255, 0.25); + border-radius: 4px; + color: rgba(255, 255, 255, 0.78); + font: inherit; + font-size: 11px; +} +.ace-annotation-card { + --ace-annotation-page-background: var(--ace-surface); + position: absolute; + z-index: 30; + display: flex; + flex-direction: column; + --ace-annotation-value-width: 136px; + width: 294px; + max-width: calc(100% - 16px); + max-height: calc(100% - 16px); + min-height: 44px; + box-sizing: border-box; + overflow: hidden; + padding: 0; + border: 1px solid rgba(var(--ace-fg-rgb, 31, 31, 31), 0.26); + border-radius: 16px; + background: var(--ace-surface); + color: var(--ace-fg); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04), 0 10px 24px rgba(0, 0, 0, 0.1); + font-size: 14px; +} +.ace-annotation-card:not(.is-adjusting) { + justify-content: center; +} +.ace-annotation-card.is-adjusting { + --ace-annotation-value-width: 176px; + width: var(--ace-annotation-adjust-width, min(380px, calc(100% - 16px))); + max-height: var(--ace-annotation-adjust-height, min(460px, calc(100% - 16px))); + padding: 0; +} +.ace-annotation-adjust, +.ace-annotation-cancel { + border: 0; + background: transparent; + color: var(--ace-fg-2); + cursor: pointer; +} +.ace-annotation-adjust { + position: static; + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border-radius: 8px; +} +.ace-annotation-card-header { + display: flex; + align-items: center; + gap: 6px; + min-height: 44px; + padding: 8px 46px 8px 6px; + box-sizing: border-box; +} +.ace-annotation-card.is-adjusting .ace-annotation-card-header { + padding: 8px 16px 8px 6px; +} +.ace-annotation-adjust[aria-expanded="true"], +.ace-annotation-adjust:hover, +.ace-annotation-adjust:focus-visible { + background: rgba(var(--ace-fg-rgb), 0.1); + color: var(--ace-fg); +} +.ace-annotation-adjust:active { + background: rgba(var(--ace-fg-rgb), 0.16); +} +.ace-annotation-adjust:focus-visible { + outline: 2px solid var(--ace-accent); + outline-offset: 1px; +} +.ace-annotation-cancel { + height: 28px; + padding: 0 12px; + border: 1px solid rgba(var(--ace-fg-rgb), 0.24); + border-radius: 8px; + background: transparent; + color: var(--ace-fg-2); + font: inherit; + font-size: 13px; + line-height: 1; + transition: background-color 120ms ease, border-color 120ms ease, color 120ms ease; +} +.ace-annotation-cancel:hover:not(:disabled) { + border-color: rgba(var(--ace-fg-rgb), 0.34); + background: rgba(var(--ace-fg-rgb), 0.1); + color: var(--ace-fg); +} +.ace-annotation-cancel:active:not(:disabled) { + background: rgba(var(--ace-fg-rgb), 0.13); +} +.ace-annotation-cancel:focus-visible { + outline: 2px solid var(--ace-accent, #3b82f6); + outline-offset: 1px; +} +.ace-annotation-actions { + position: absolute; + right: 8px; + bottom: 8px; + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; +} +.ace-annotation-card:not(.is-adjusting) .ace-annotation-actions { + top: 50%; + bottom: auto; + transform: translateY(-50%); +} +.ace-annotation-card.is-adjusting .ace-annotation-actions { + position: static; + left: auto; + right: auto; + bottom: auto; + flex: 0 0 auto; + padding: 10px 12px; + border-top: 1px solid var(--ace-border-soft); + background: var(--ace-surface); + justify-content: space-between; +} +.ace-annotation-editor { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; + padding: 8px 0 0; +} +.ace-annotation-card.is-adjusting .ace-annotation-editor { + flex: 0 1 auto; + min-height: 0; + max-height: 230px; + overflow-y: auto; + overflow-x: hidden; + overscroll-behavior: contain; + /* The scroll area ends on the action bar's divider. Keep the last field (the + visible-text box) 2px clear of that line instead of butting against it. */ + padding: 8px 0 2px; + scrollbar-gutter: stable; +} +.ace-annotation-editor fieldset { + display: flex; + flex-direction: column; + gap: 8px; + margin: 0; + border: 0; + padding: 0; +} +.ace-annotation-editor fieldset:disabled { + opacity: 0.6; +} +.ace-annotation-comment { + flex: 1 1 auto; + min-width: 0; + width: auto; + min-height: 28px; + height: 28px; + resize: none; + overflow: hidden; + border: 0; + outline: none; + background: transparent; + color: var(--ace-fg); + font: inherit; + line-height: 28px; +} +.ace-annotation-card.is-adjusting .ace-annotation-comment { + height: auto; + min-height: 28px; + max-height: 84px; + overflow: auto; + padding: 4px 0; + line-height: 20px; +} +.ace-annotation-submit { + flex: 0 0 auto; + width: 28px; + height: 28px; + display: inline-flex; + align-items: center; + justify-content: center; + border: 0; + border-radius: 999px; + background: var(--ace-fg); + color: var(--ace-surface); + cursor: pointer; +} +.ace-annotation-design-handle { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + flex: 0 0 auto; + min-height: 28px; + margin: 0; + padding: 0 16px; + background: transparent; + color: var(--ace-fg-2); + user-select: none; +} +.ace-annotation-design-grip { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: 0; + border-radius: 7px; + background: transparent; + color: var(--ace-fg-2); + opacity: 0.72; + cursor: grab; + touch-action: none; +} +.ace-annotation-design-grip:hover { + background: rgba(var(--ace-fg-rgb), 0.08); + color: var(--ace-fg); + opacity: 1; +} +.ace-annotation-design-grip:active { + cursor: grabbing; +} +.ace-annotation-design { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px 16px 0; +} +.ace-annotation-target-tag { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + color: var(--ace-fg-2); + font-size: 14px; + line-height: 20px; + text-overflow: ellipsis; + white-space: nowrap; +} +.ace-annotation-text-field { + display: flex; + flex-direction: column; + gap: 6px; + padding: 0 16px; + color: var(--ace-fg); + font-size: 14px; + line-height: 20px; +} +.ace-annotation-text-field > span { + color: var(--ace-fg-2); + font-size: 14px; + line-height: 20px; + margin: 0; + padding: 0; +} +.ace-annotation-text-input { + width: 100%; + box-sizing: border-box; + min-height: 58px; + resize: vertical; + border: 1px solid transparent; + border-radius: 8px; + background: rgba(var(--ace-fg-rgb), 0.05); + padding: 6px 8px; + color: var(--ace-fg); + font: inherit; + font-size: 14px; + line-height: 20px; + outline: none; +} +.ace-annotation-text-input:focus { + border-color: var(--ace-accent, #3b82f6); +} +.ace-annotation-text-input:disabled { + opacity: 0.55; +} +.ace-annotation-text-error { + color: var(--ace-danger, #dc2626); + font-size: 12px; +} +.ace-annotation-row, +.ace-annotation-color { + display: flex; + align-items: center; + min-width: 0; + gap: 8px; +} +.ace-annotation-row { + display: grid; + grid-template-columns: minmax(96px, 1fr) var(--ace-annotation-value-width); + align-items: center; + min-height: 28px; + column-gap: 12px; +} +.ace-annotation-row > span:first-child { + color: var(--ace-fg-2); + font-size: 14px; + line-height: 20px; +} +.ace-annotation-row > span:first-child { + display: block; + box-sizing: border-box; + justify-self: start; + min-width: 0; + margin: 0; + padding: 0; + border: 0; + text-align: start; +} +.ace-annotation-dimensions { + position: relative; + display: flex; + flex-direction: column; + gap: 6px; +} +.ace-annotation-pair { + position: relative; + display: flex; + flex-direction: column; + gap: 6px; +} +.ace-annotation-pair-lock { + position: absolute; + top: 50%; + right: calc(var(--ace-annotation-value-width) + 10px); + z-index: 2; + width: 26px; + height: 62px; + transform: translateY(-50%); + pointer-events: none; +} +.ace-annotation-pair-bracket { + position: absolute; + inset: 0; + color: rgba(var(--ace-fg-rgb), 0.28); +} +.ace-annotation-pair-lock-button { + position: absolute; + top: 50%; + right: -5px; + display: inline-flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + width: 16px; + height: 16px; + padding: 0; + transform: translateY(-50%); + border: 1px solid transparent; + border-radius: 999px; + background: var(--ace-surface); + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); + color: var(--ace-fg-2); + cursor: pointer; + pointer-events: auto; + transition: background-color 120ms ease, color 120ms ease; +} +.ace-annotation-pair-lock-button svg { + width: 12px; + height: 12px; +} +.ace-annotation-pair-lock-button:hover { + background: rgba(var(--ace-fg-rgb), 0.1); + color: var(--ace-fg); +} +.ace-annotation-pair-lock-button[aria-pressed="true"] { + color: var(--ace-fg); + background: rgba(var(--ace-fg-rgb), 0.08); +} +.ace-annotation-pair-lock-button:focus-visible { + outline: 2px solid var(--ace-accent, #3b82f6); + outline-offset: 2px; +} +.ace-annotation-expand { + display: inline-flex; + align-items: center; + justify-content: flex-start; + gap: 4px; + width: fit-content; + max-width: 100%; + min-height: 28px; + margin: 0; + padding: 0 2px; + padding-inline: 2px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--ace-fg-2); + font: inherit; + font-size: 14px; + line-height: 20px; + text-align: start; + cursor: pointer; +} +.ace-annotation-expand:hover { + background: rgba(var(--ace-fg-rgb), 0.06); +} +.ace-annotation-expand svg { + color: rgba(var(--ace-fg-rgb), 0.45); + transition: transform 120ms ease; +} +.ace-annotation-expand svg.is-open { + transform: rotate(90deg); +} +.ace-annotation-spacing-values { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(45px, 1fr)); + gap: 4px; + min-width: 0; +} +.ace-annotation-spacing > .ace-annotation-row { + grid-template-columns: minmax(96px, 1fr) minmax(0, 236px); +} +.ace-annotation-value-cell.is-compact { + padding-left: 0; +} +.ace-annotation-value-cell.is-compact .ace-annotation-reset { + width: 14px; + height: 18px; +} +.ace-annotation-value-cell.is-compact.has-reset { + padding-left: 14px; +} +.ace-annotation-value-pair { + display: grid; + grid-template-columns: repeat(2, minmax(45px, 1fr)); + gap: 4px; + min-width: 0; +} +.ace-annotation-value-pair .ace-annotation-value-cell.has-reset { + padding-left: 22px; +} +.ace-annotation-spacing-values .ace-annotation-value { + padding: 0 4px; + text-align: center; +} +.ace-annotation-value-cell { + position: relative; + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + width: 100%; + padding-left: 0; +} +.ace-annotation-value-cell.has-swatch, +.ace-annotation-value-cell.has-reset { + padding-left: 44px; +} +.ace-annotation-reset { + position: absolute; + left: 0; + top: 50%; + display: none; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + padding: 0; + transform: translateY(-50%); + border: 0; + border-radius: 999px; + background: transparent; + color: var(--ace-fg-2); + cursor: pointer; +} +.ace-annotation-value-cell.has-reset .ace-annotation-reset { + display: inline-flex; +} +.ace-annotation-value-cell > .ace-annotation-color-swatch { + position: absolute; + left: 22px; + top: 50%; + transform: translateY(-50%); +} +.ace-annotation-reset:hover { + background: rgba(var(--ace-fg-rgb), 0.09); + color: var(--ace-fg); +} +.ace-annotation-reset:focus-visible { + outline: 2px solid var(--ace-accent, #3b82f6); + outline-offset: 1px; +} +.ace-annotation-value-box { + display: flex; + align-items: center; + min-width: 0; + width: 100%; + height: 28px; + border: 1px solid transparent; + border-radius: 8px; + background: rgba(var(--ace-fg-rgb), 0.05); +} +.ace-annotation-value-box:focus-within { + border-color: var(--ace-accent, #3b82f6); +} +.ace-annotation-value-box > input { + flex: 1 1 auto; + min-width: 0; + height: 100%; + padding: 0 1px 0 8px; + border: 0; + background: transparent; + color: var(--ace-fg); + font-family: inherit; + font-size: 13px; + text-align: end; + outline: none; + appearance: textfield; + -moz-appearance: textfield; +} +.ace-annotation-value-box > input::-webkit-outer-spin-button, +.ace-annotation-value-box > input::-webkit-inner-spin-button { + margin: 0; + -webkit-appearance: none; +} +.ace-annotation-value-unit { + flex: 0 0 auto; + padding: 0 8px 0 1px; + color: var(--ace-fg-2); + font-family: inherit; + font-size: 13px; + line-height: 1; +} +.ace-annotation-value-box.is-compact > input { + padding: 0 0 0 6px; + font-size: 12.5px; +} +.ace-annotation-value-unit.is-compact { + padding: 0 5px 0 1px; + font-size: 12px; +} +.ace-annotation-select-trigger { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 26px; + margin-right: 1px; + padding: 0; + border: 0; + border-left: 1px solid var(--ace-border-soft); + border-radius: 0 8px 8px 0; + background: transparent; + color: var(--ace-fg-2); + cursor: pointer; +} +.ace-annotation-select-trigger:hover, +.ace-annotation-select-trigger[aria-expanded="true"] { + background: rgba(var(--ace-fg-rgb), 0.08); + color: var(--ace-fg); +} +.ace-annotation-select-menu { + position: fixed; + z-index: 80; + display: flex; + flex-direction: column; + max-height: 220px; + overflow-y: auto; + padding: 4px; + border: 1px solid var(--ace-border); + border-radius: 12px; + background: var(--ace-surface); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04), 0 8px 20px rgba(0, 0, 0, 0.12); +} +.ace-annotation-select-option { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + width: 100%; + min-height: 28px; + padding: 0 8px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--ace-fg); + font: inherit; + font-size: 13px; + text-align: start; + cursor: pointer; +} +.ace-annotation-select-option > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.ace-annotation-select-option:hover { + background: rgba(var(--ace-fg-rgb), 0.07); +} +.ace-annotation-select-option[aria-selected="true"] { + color: var(--ace-accent, #3b82f6); +} +.ace-annotation-value { + width: 100%; + min-width: 0; + height: 28px; + border: 1px solid transparent; + border-radius: 8px; + background: rgba(var(--ace-fg-rgb), 0.05); + color: var(--ace-fg); + font-family: inherit; + font-size: 13px; + text-align: end; + padding: 0 8px; + outline: none; +} +.ace-annotation-value:focus { + border-color: var(--ace-accent, #3b82f6); +} +.ace-annotation-color-swatch { + -webkit-appearance: none; + appearance: none; + width: 16px; + height: 16px; + flex: 0 0 auto; + padding: 0; + border: 1px solid rgba(var(--ace-fg-rgb), 0.16); + border-radius: 4px; + background: transparent; + overflow: hidden; + cursor: pointer; +} +.ace-annotation-color-swatch::-webkit-color-swatch-wrapper { + padding: 0; +} +.ace-annotation-color-swatch::-webkit-color-swatch { + border: 0; + border-radius: 3px; +} +.ace-annotation-submit:disabled, +.ace-annotation-cancel:disabled { + opacity: 0.45; + cursor: default; +} .ace-agent-browser-frame { --ace-browser-shared-angle: 135deg; flex: 1 1 auto;