From 9e1b4022dd4e9de42432a34819b9942e719af5fc Mon Sep 17 00:00:00 2001 From: Trae User Date: Wed, 18 Nov 2026 23:13:16 +0800 Subject: [PATCH 01/34] docs: Plan desktop HTML page annotations --- .../add-html-page-annotations/.openspec.yaml | 2 + .../add-html-page-annotations/design.md | 33 ++++++++++ .../add-html-page-annotations/proposal.md | 27 ++++++++ .../specs/html-page-annotations/spec.md | 65 +++++++++++++++++++ .../add-html-page-annotations/tasks.md | 46 +++++++++++++ 5 files changed, 173 insertions(+) create mode 100644 openspec/changes/add-html-page-annotations/.openspec.yaml create mode 100644 openspec/changes/add-html-page-annotations/design.md create mode 100644 openspec/changes/add-html-page-annotations/proposal.md create mode 100644 openspec/changes/add-html-page-annotations/specs/html-page-annotations/spec.md create mode 100644 openspec/changes/add-html-page-annotations/tasks.md 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 00000000..41484f31 --- /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 00000000..6f1de5bb --- /dev/null +++ b/openspec/changes/add-html-page-annotations/design.md @@ -0,0 +1,33 @@ +# 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 while retaining markers. 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. +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. 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 00000000..356e5422 --- /dev/null +++ b/openspec/changes/add-html-page-annotations/proposal.md @@ -0,0 +1,27 @@ +# 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 00000000..c59d778d --- /dev/null +++ b/openspec/changes/add-html-page-annotations/specs/html-page-annotations/spec.md @@ -0,0 +1,65 @@ +# 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, element outline/control button and host-controlled popup above the browser. 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: Reversible actual-change previews +The system SHALL preview visible text, text color, background, opacity, font, font size/weight, radius, border color/width, width/height, 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 while pins remain visible +- **AND** toggling back restores saved previews 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 + +### 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 00000000..94d954e3 --- /dev/null +++ b/openspec/changes/add-html-page-annotations/tasks.md @@ -0,0 +1,46 @@ +# Tasks + +## 1. Element annotation closed loop (#194) + +- [ ] 1.1 Add document-bound annotation runtime and restricted native/trusted commands; verify stale-document and untrusted-command rejection. +- [ ] 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. +- [ ] 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. +- [ ] 2.2 Add default-off current-ratio lock and draft-only cancellation over saved layers; verify repeated edits of the same target. +- [ ] 2.3 Add original-view comparison retaining pins and restoring previews; verify round trips and mode exit. + +## 3. Visible text previews (#196) + +- [ ] 3.1 Implement reversible text-node previews preserving child-node identity; verify nested elements, text changes and exact restoration. +- [ ] 3.2 Integrate saved/draft/original text layers and actual differences; verify cancellation retains earlier saved text. + +## 4. Multiple targets and region (#197) + +- [ ] 4.1 Support adding multiple elements to one draft with shared description/pin; verify target switching and save. +- [ ] 4.2 Support one page-coordinate region replaced by subsequent drags without property editing; verify scroll coordinates and replacement. + +## 5. Full-page native screenshot (#198) + +- [ ] 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. + +## 6. Reliable batch send (#199) + +- [ ] 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. +- [ ] 6.2 Submit through existing conversation boundary with queue semantics, receipts and receiver-side batch deduplication; verify busy mode, switching sessions and uncertain retry. +- [ ] 6.3 Retain pending data on preparation/submission failure and acknowledge only accepted records; verify pin retention, counts and increasing numbers. + +## 7. Navigation and invalidation (#200) + +- [ ] 7.1 Guard active navigation/refresh with default-stay confirmation and no auto-send; verify all host entry paths. +- [ ] 7.2 Retain invalid unsent records on document replacement or target removal and block affected batches without relocation; verify stale callbacks and absent conversation. + +## 8. Integration and acceptance (#201) + +- [ ] 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. +- [ ] 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. From edd093aede1a44def404c524f6f96bd757c890ad Mon Sep 17 00:00:00 2001 From: Trae User Date: Wed, 18 Nov 2026 23:19:29 +0800 Subject: [PATCH 02/34] docs: Track HTML annotation platform acceptance --- .../html-page-annotations-acceptance.md | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 docs/desktop-shell/html-page-annotations-acceptance.md 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 00000000..b4b683af --- /dev/null +++ b/docs/desktop-shell/html-page-annotations-acceptance.md @@ -0,0 +1,48 @@ +# 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`. + +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 for initial planning artifacts, 2026-11-18 | +| Annotation interaction through conversation submission | Pending implementation | +| All property previews, text-node identity and saved/draft layering | Pending implementation | +| Batch freeze, queue, receipt, receiver deduplication and failures | Pending implementation | +| Navigation, removed target, document ownership and untrusted commands | Pending implementation | +| Source-selection annotation regressions | Pending | +| Full frontend test suite and production build | Pending | +| Windows native build and focused tests | Pending | +| macOS native build and focused tests | Not executed; macOS environment required | +| Standards and specification code review | Pending | + +## 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. + +| 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 | +| Explicit batch send yields one message and exactly one full-page image with 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 frozen batch; additions during send remain pending | Not executed | Not executed | +| Accepted batch clears only its pending count, retains pins/previews, and subsequent numbers increase | Not executed | Not executed | +| Capture/upload failure sends nothing; uncertain receipt retries same identity 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. From 8f6ec6d6135fe5bee3466e0b2e9022f69ab4aebf Mon Sep 17 00:00:00 2001 From: Trae User Date: Wed, 18 Nov 2026 23:21:00 +0800 Subject: [PATCH 03/34] test: Add long-page HTML annotation acceptance fixture --- .../html-page-annotations-acceptance.md | 8 ++- .../helpers/html_annotation_fixture.html | 60 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 tests/desktop/helpers/html_annotation_fixture.html diff --git a/docs/desktop-shell/html-page-annotations-acceptance.md b/docs/desktop-shell/html-page-annotations-acceptance.md index b4b683af..6ef9d2ee 100644 --- a/docs/desktop-shell/html-page-annotations-acceptance.md +++ b/docs/desktop-shell/html-page-annotations-acceptance.md @@ -14,7 +14,7 @@ This is the execution checklist, not a claim that the feature is complete. Keep | Batch freeze, queue, receipt, receiver deduplication and failures | Pending implementation | | Navigation, removed target, document ownership and untrusted commands | Pending implementation | | Source-selection annotation regressions | Pending | -| Full frontend test suite and production build | Pending | +| Full frontend test suite and production build | Baseline passed at edd093ae on Windows, 2026-11-18; integrated implementation rerun pending | | Windows native build and focused tests | Pending | | macOS native build and focused tests | Not executed; macOS environment required | | Standards and specification code review | Pending | @@ -23,6 +23,8 @@ This is the execution checklist, not a claim that the feature is complete. Keep 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 | @@ -46,3 +48,7 @@ Run the following independently on Windows and macOS against the integrated buil ## 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-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. diff --git a/tests/desktop/helpers/html_annotation_fixture.html b/tests/desktop/helpers/html_annotation_fixture.html new file mode 100644 index 00000000..7913176a --- /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

+
+
+ + + From 5de67d6d069aad4cd6eb73cbe9ea4c29e47b5e51 Mon Sep 17 00:00:00 2001 From: Trae User Date: Wed, 18 Nov 2026 23:40:18 +0800 Subject: [PATCH 04/34] Implement explicit document-bound full-page capture (#198) --- docs/agent-browser.md | 39 ++- .../add-html-page-annotations/design.md | 18 ++ .../add-html-page-annotations/tasks.md | 19 ++ src/apps/desktop/agent_browser_capture.hpp | 205 +++++++++++++++ src/apps/desktop/agent_browser_host.cpp | 174 +++++++++++++ src/apps/desktop/agent_browser_host_mac.mm | 130 +++++++++- tests/CMakeLists.txt | 2 +- tests/desktop/agent_browser_capture_test.cpp | 240 ++++++++++++++++++ .../helpers/agent_browser_capture_probe.hpp | 113 +++++++++ .../helpers/agent_browser_host_mac_smoke.mm | 4 + .../helpers/agent_browser_host_smoke.cpp | 6 + 11 files changed, 946 insertions(+), 4 deletions(-) create mode 100644 src/apps/desktop/agent_browser_capture.hpp create mode 100644 tests/desktop/agent_browser_capture_test.cpp create mode 100644 tests/desktop/helpers/agent_browser_capture_probe.hpp diff --git a/docs/agent-browser.md b/docs/agent-browser.md index 810f0b62..4c629028 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 仍不能绕过网页权限、系统安全提示或不可见页面约束。 diff --git a/openspec/changes/add-html-page-annotations/design.md b/openspec/changes/add-html-page-annotations/design.md index 6f1de5bb..db0cc868 100644 --- a/openspec/changes/add-html-page-annotations/design.md +++ b/openspec/changes/add-html-page-annotations/design.md @@ -15,6 +15,24 @@ See proposal.md for motivation and GitHub spec #193 for the complete approved co 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 while retaining markers. 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. diff --git a/openspec/changes/add-html-page-annotations/tasks.md b/openspec/changes/add-html-page-annotations/tasks.md index 94d954e3..5b48e1a2 100644 --- a/openspec/changes/add-html-page-annotations/tasks.md +++ b/openspec/changes/add-html-page-annotations/tasks.md @@ -27,6 +27,25 @@ - [ ] 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 +remain unverified; 5.1/5.2 stay unchecked rather than claiming platform acceptance. +`openspec validate add-html-page-annotations --strict` and `git diff --check` pass. + ## 6. Reliable batch send (#199) - [ ] 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. diff --git a/src/apps/desktop/agent_browser_capture.hpp b/src/apps/desktop/agent_browser_capture.hpp new file mode 100644 index 00000000..1d9ca78c --- /dev/null +++ b/src/apps/desktop/agent_browser_capture.hpp @@ -0,0 +1,205 @@ +#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; + +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_host.cpp b/src/apps/desktop/agent_browser_host.cpp index 9d508f2e..86736106 100644 --- a/src/apps/desktop/agent_browser_host.cpp +++ b/src/apps/desktop/agent_browser_host.cpp @@ -1,6 +1,7 @@ #include "agent_browser_host.hpp" #include "agent_browser_cookie_jars.hpp" +#include "agent_browser_capture.hpp" #include "agent_browser_navigation_state.hpp" #include "ipc/agent_browser_runtime.hpp" #include "ipc/agent_browser_store_state.hpp" @@ -18,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -2180,6 +2182,155 @@ struct AgentBrowserHost::Impl return true; } + void capture_command( + const std::shared_ptr& page, const std::string& method, + const nlohmann::json& params, + std::function 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 = page->webview->CallDevToolsProtocolMethod( + wide_method.c_str(), wide_params.c_str(), callback.Get()); + if (FAILED(started)) completion({}, "capture_dispatch_failed"); + } + + void capture_screenshot( + const std::shared_ptr& page, const nlohmann::json& params, + const std::shared_ptr& pending) { + 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 current = [weak, page, webview, navigation_id, controller_generation, pending] { + const auto self = weak.lock(); + { + std::lock_guard lock(pending->mutex); + 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 && + self->page_shared_with_agent(page); + }; + const browser_capture::Measure measure = [weak, page, current](browser_capture::Measured done) { + const auto self = weak.lock(); + if (!self || !current()) { done({}, "capture_document_changed"); return; } + self->capture_command(page, "Page.getFrameTree", nlohmann::json::object(), + [weak, page, current, done](nlohmann::json tree, std::string error) { + const auto owner = weak.lock(); + if (!owner || !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", ""); + owner->capture_command(page, "Page.getLayoutMetrics", nlohmann::json::object(), + [weak, page, current, frame, document, done](nlohmann::json metrics, std::string metrics_error) { + if (!metrics_error.empty()) { done({}, metrics_error); return; } + const auto self = weak.lock(); + if (!self || !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 browser_capture::Bounds bounds{size["x"].get(), + size["y"].get(), size["width"].get(), + size["height"].get(), document}; + self->capture_command(page, "Page.createIsolatedWorld", + {{"frameId", frame["id"]}, {"worldName", "acecode.full-page-capture"}}, + [weak, page, current, bounds, done](nlohmann::json world, std::string world_error) { + if (!world_error.empty()) { done({}, world_error); return; } + const auto owner = weak.lock(); + if (!owner || !current()) { done({}, "capture_document_changed"); return; } + if (!world.contains("executionContextId") || + !world["executionContextId"].is_number_integer()) { + done({}, "capture_measure_failed"); return; + } + owner->capture_command(page, "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 browser_capture::Capture capture = [weak, page, current]( + const browser_capture::Bounds& bounds, browser_capture::Captured done) { + const auto self = weak.lock(); + if (!self || !current()) { done({}, "capture_document_changed"); return; } + self->capture_command(page, "Page.captureScreenshot", + {{"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() > + ((browser_capture::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"); + }); + }; + std::make_shared( + page->id, params.value("documentId", ""), measure, capture, current, + [pending](nlohmann::json response) { finish_proxy_call(pending, std::move(response)); }) + ->start(); + } + void call_cdp_on_ui( const std::string& requested_page, const AgentBrowserPageOwner& owner, @@ -2214,6 +2365,19 @@ struct AgentBrowserHost::Impl if (environment) begin_create_controller(page); return; } + 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; + } + } 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()); @@ -2425,6 +2589,16 @@ struct AgentBrowserHost::Impl pending->ready.wait_for(lock, std::chrono::milliseconds(50)); } if (pending->completed) return pending->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) { + pending->completed = true; + pending->response = {{"ok", false}, {"page_id", request.value("page_id", "")}, + {"error", proxy_stopping.load() ? "capture_stopped" : "capture_timeout"}, + {"recoverable", true}}; + return pending->response; + } return {{"ok", false}, {"page_id", request.value("page_id", "")}, {"error", proxy_stopping.load() diff --git a/src/apps/desktop/agent_browser_host_mac.mm b/src/apps/desktop/agent_browser_host_mac.mm index 298dcb8c..9eac9552 100644 --- a/src/apps/desktop/agent_browser_host_mac.mm +++ b/src/apps/desktop/agent_browser_host_mac.mm @@ -3,6 +3,7 @@ #ifdef __APPLE__ #include "agent_browser_cookie_jars.hpp" +#include "agent_browser_capture.hpp" #include "agent_browser_macos_helpers.hpp" #include "agent_browser_navigation_state.hpp" #include "ipc/agent_browser_runtime.hpp" @@ -2302,7 +2303,124 @@ CGEventType cg_mouse_event_type(const std::string& type, const std::shared_ptr& page, const json& params, const std::shared_ptr& pending) { - (void)params; + bool full_page = false; + const auto request_error = browser_capture::request_mode(params, full_page); + if (!request_error.empty()) { + finish_proxy_call(pending, {{"ok", false}, {"page_id", page->id}, + {"error", request_error}, {"recoverable", true}}); + return; + } + if (full_page) { + 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 current = [weak, page, view, navigation_id, pending] { + const auto self = weak.lock(); + { + std::lock_guard lock(pending->mutex); + 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 && + self->page_shared_with_agent(page); + }; + const browser_capture::Measure measure = [weak, page, current]( + browser_capture::Measured done) { + const auto self = weak.lock(); + if (!self || !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"; + self->evaluate_value(page, 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 browser_capture::Capture capture = [view, current]( + const browser_capture::Bounds& bounds, browser_capture::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 > browser_capture::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 > browser_capture::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", ""), measure, capture, current, + [pending](json response) { finish_proxy_call(pending, std::move(response)); }) + ->start(); + return; + } // 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. @@ -2694,6 +2812,16 @@ CGEventType cg_mouse_event_type(const std::string& type, pending->ready.wait_for(lock, std::chrono::milliseconds(50)); } if (pending->completed) return pending->response; + bool full_page = false; + if (request.value("method", "") == "Page.captureScreenshot" && + browser_capture::request_mode(request.value("params", json::object()), full_page).empty() && + full_page) { + pending->completed = true; + pending->response = {{"ok", false}, {"page_id", request.value("page_id", "")}, + {"error", proxy_stopping.load() ? "capture_stopped" : "capture_timeout"}, + {"recoverable", true}}; + return pending->response; + } return {{"ok", false}, {"page_id", request.value("page_id", "")}, {"error", proxy_stopping.load() diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5211fa0b..0fb5f1d2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -220,7 +220,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 diff --git a/tests/desktop/agent_browser_capture_test.cpp b/tests/desktop/agent_browser_capture_test.cpp new file mode 100644 index 00000000..5cae7855 --- /dev/null +++ b/tests/desktop/agent_browser_capture_test.cpp @@ -0,0 +1,240 @@ +#include "desktop/agent_browser_capture.hpp" + +#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, 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/helpers/agent_browser_capture_probe.hpp b/tests/desktop/helpers/agent_browser_capture_probe.hpp new file mode 100644 index 00000000..035fd077 --- /dev/null +++ b/tests/desktop/helpers/agent_browser_capture_probe.hpp @@ -0,0 +1,113 @@ +#pragma once + +#include "tool/agent_browser/cdp_client.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 evaluate = [&client, &error](const std::string& expression) { + return client.command("Runtime.evaluate", {{"expression", expression}, + {"awaitPromise", true}, {"returnByValue", true}}, 10s, nullptr, error) + .value("result", nlohmann::json::object()).value("value", nlohmann::json()); + }; + 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'; + 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}; + })())JS"); + if (!error.empty() || !fixture.is_object()) return false; + const auto viewport = client.command("Page.captureScreenshot", {{"format", "png"}}, + 20s, nullptr, error); + const auto viewport_bytes = agent_browser::decode_agent_browser_base64(viewport.value("data", "")); + 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 = client.command("Page.captureScreenshot", {{"fullPage", true}}, + 20s, nullptr, error); + const auto bytes = agent_browser::decode_agent_browser_base64(full.value("data", "")); + 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("({scroll:scrollY, viewport:innerHeight, width:innerWidth})"); + if (!error.empty() || after["scroll"] != fixture["scroll"] || + after["viewport"] != fixture["viewport"] || after["width"] != fixture["width"]) { + error = "full-page capture changed viewport or scroll"; return false; + } + client.command("Page.captureScreenshot", {{"fullPage", true}, {"documentId", "stale-document"}}, + 20s, nullptr, error); + if (error != "capture_document_changed") { 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") { error = "oversized capture was not rejected"; return false; } + error.clear(); + evaluate("document.body.firstElementChild.style.height = " + + std::to_string(fixture["height"].get() - 100)); + if (!error.empty()) return false; + const auto retry = client.command("Page.captureScreenshot", {{"fullPage", true}, + {"documentId", full.at("documentId")}}, 20s, nullptr, error); + return error.empty() && retry.value("fullPage", false); +} + +} diff --git a/tests/desktop/helpers/agent_browser_host_mac_smoke.mm b/tests/desktop/helpers/agent_browser_host_mac_smoke.mm index 1b837b9b..0910fa1f 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 "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 79f98655..fa0fbc43 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 "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); From f0be44edfbfbdfe9dc836d36b2994d15e09c4fa8 Mon Sep 17 00:00:00 2001 From: Trae User Date: Wed, 18 Nov 2026 23:42:29 +0800 Subject: [PATCH 05/34] feat: Add trusted single-element page annotations (#194) --- cmake/acecode_source_paths.cmake | 1 + docs/agent-browser.md | 56 ++++++ .../add-html-page-annotations/design.md | 29 +++ .../add-html-page-annotations/tasks.md | 6 +- src/apps/desktop/agent_browser_host.cpp | 140 ++++++++++++- src/apps/desktop/agent_browser_host.hpp | 4 + src/apps/desktop/agent_browser_host_mac.mm | 57 +++++- src/apps/desktop/main.cpp | 6 + src/apps/desktop/page_annotation_bridge.cpp | 30 +++ src/apps/desktop/page_annotation_bridge.hpp | 13 ++ src/apps/desktop/page_annotation_runtime.hpp | 149 ++++++++++++++ src/apps/desktop/page_annotation_session.hpp | 178 +++++++++++++++++ .../desktop/page_annotation_session_test.cpp | 184 ++++++++++++++++++ web/scripts/i18n-en-overrides.mjs | 10 + web/src/components/AgentBrowserPanel.jsx | 29 ++- web/src/components/PageAnnotations.jsx | 137 +++++++++++++ web/src/i18n/sourceCatalog.generated.js | 20 ++ web/src/lib/pageAnnotations.js | 60 ++++++ web/src/lib/pageAnnotations.test.js | 183 +++++++++++++++++ web/src/lib/runTests.js | 1 + 20 files changed, 1286 insertions(+), 7 deletions(-) create mode 100644 src/apps/desktop/page_annotation_bridge.cpp create mode 100644 src/apps/desktop/page_annotation_bridge.hpp create mode 100644 src/apps/desktop/page_annotation_runtime.hpp create mode 100644 src/apps/desktop/page_annotation_session.hpp create mode 100644 tests/desktop/page_annotation_session_test.cpp create mode 100644 web/src/components/PageAnnotations.jsx create mode 100644 web/src/lib/pageAnnotations.js create mode 100644 web/src/lib/pageAnnotations.test.js diff --git a/cmake/acecode_source_paths.cmake b/cmake/acecode_source_paths.cmake index 3bc6498e..07a854d6 100644 --- a/cmake/acecode_source_paths.cmake +++ b/cmake/acecode_source_paths.cmake @@ -6,6 +6,7 @@ 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/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") diff --git a/docs/agent-browser.md b/docs/agent-browser.md index 4c629028..fd833d5c 100644 --- a/docs/agent-browser.md +++ b/docs/agent-browser.md @@ -382,6 +382,62 @@ 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 路径上露出可信表单,不是聊天栏替代。选择状态通过宿主发起的 + read 读取,不接受网页主动发来的特权请求。 + +后续样式、文本、多目标/区域功能分别扩展上述运行时、原生草稿模型及可信浮窗,不要改走 +`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 或单文件编译代替。 + ## 常见故障 - “Open ACECode Desktop”:工具运行在 daemon,但没有兼容的 Windows Desktop 或 diff --git a/openspec/changes/add-html-page-annotations/design.md b/openspec/changes/add-html-page-annotations/design.md index db0cc868..4ee52d39 100644 --- a/openspec/changes/add-html-page-annotations/design.md +++ b/openspec/changes/add-html-page-annotations/design.md @@ -49,3 +49,32 @@ See proposal.md for motivation and GitHub spec #193 for the complete approved co ## 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. + +## #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. diff --git a/openspec/changes/add-html-page-annotations/tasks.md b/openspec/changes/add-html-page-annotations/tasks.md index 5b48e1a2..adc2d6b8 100644 --- a/openspec/changes/add-html-page-annotations/tasks.md +++ b/openspec/changes/add-html-page-annotations/tasks.md @@ -2,9 +2,9 @@ ## 1. Element annotation closed loop (#194) -- [ ] 1.1 Add document-bound annotation runtime and restricted native/trusted commands; verify stale-document and untrusted-command rejection. -- [ ] 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. -- [ ] 1.3 Preserve saved pins on mode exit and immutable saved records; verify behavior and existing source-selection regression tests. +- [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) diff --git a/src/apps/desktop/agent_browser_host.cpp b/src/apps/desktop/agent_browser_host.cpp index 86736106..80831a58 100644 --- a/src/apps/desktop/agent_browser_host.cpp +++ b/src/apps/desktop/agent_browser_host.cpp @@ -1,4 +1,5 @@ #include "agent_browser_host.hpp" +#include "page_annotation_session.hpp" #include "agent_browser_cookie_jars.hpp" #include "agent_browser_capture.hpp" @@ -86,6 +87,7 @@ struct AgentBrowserHost::Impl struct Page { std::string id; + PageAnnotationSession annotations; AgentBrowserState state; AgentBrowserBounds requested_bounds; bool creation_started = false; @@ -1484,6 +1486,13 @@ struct AgentBrowserHost::Impl 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); } @@ -1562,8 +1571,10 @@ struct AgentBrowserHost::Impl current, "[browser] " + technical); if (failure_kind.empty()) return S_OK; + current->annotations.replace_document(); 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; @@ -1690,6 +1701,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; @@ -1740,6 +1752,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{}; @@ -1749,7 +1762,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; @@ -2166,6 +2180,84 @@ struct AgentBrowserHost::Impl return true; } + using AnnotationResult = std::function; + + void annotation_cdp(const std::shared_ptr& page, + std::uint64_t sequence, const wchar_t* method, + const nlohmann::json& params, AnnotationResult completion) { + const auto weak = weak_from_this(); + const std::weak_ptr weak_page = page; + const auto incarnation = page->controller_generation; + const auto serialized = acecode::utf8_to_wide(params.dump()); + auto callback = Microsoft::WRL::Callback< + ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>( + [weak, weak_page, incarnation, sequence, completion](HRESULT status, LPCWSTR raw) -> HRESULT { + const auto self = weak.lock(); + const auto current = weak_page.lock(); + if (!self || !current || current->closing || + self->find_page(current->id) != current || + current->controller_generation != incarnation || + current->annotations.sequence() != sequence) { + 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 = page->webview->CallDevToolsProtocolMethod( + method, serialized.c_str(), callback.Get()); + if (FAILED(status)) completion(false, nullptr); + } + + void evaluate_annotation(const std::shared_ptr& page, + std::uint64_t sequence, std::string expression, + AnnotationResult completion) { + const auto weak = weak_from_this(); + const std::weak_ptr weak_page = page; + annotation_cdp(page, sequence, L"Page.getFrameTree", nlohmann::json::object(), + [weak, weak_page, sequence, expression, completion](bool ok, nlohmann::json result) { + const auto self = weak.lock(); + const auto current = weak_page.lock(); + if (!ok || !self || !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}, + }; + self->annotation_cdp(current, sequence, L"Page.createIsolatedWorld", params, + [weak, weak_page, sequence, expression, completion](bool created, nlohmann::json world) { + const auto owner = weak.lock(); + const auto target = weak_page.lock(); + if (!created || !owner || !target || + !world.contains("executionContextId") || + !world["executionContextId"].is_number_integer()) { + completion(false, nullptr); + return; + } + owner->annotation_cdp(target, sequence, 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())); + }); + }); + }); + } + bool open_developer_tools_on_ui(const std::string& page_id, std::string* error) { auto page = find_page(page_id); @@ -2903,6 +2995,52 @@ 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 + const auto page = impl_ ? impl_->find_page(page_id) : nullptr; + if (!page || page->closing || !page->webview || + page->state.content_state != kAgentBrowserContentStateLive) { + completion(nlohmann::json{{"ok", false}, {"error", "Annotation page is unavailable"}}.dump()); + return; + } + const auto command = nlohmann::json::parse(command_json, nullptr, false); + 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(); + const std::weak_ptr weak = impl_; + const std::weak_ptr weak_page = page; + impl_->evaluate_annotation(page, sequence, expression, + [weak, weak_page, sequence, completion](bool ok, nlohmann::json result) { + const auto self = weak.lock(); + const auto current = weak_page.lock(); + std::string error; + 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()); + }); +#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 8d3aa049..0012b038 100644 --- a/src/apps/desktop/agent_browser_host.hpp +++ b/src/apps/desktop/agent_browser_host.hpp @@ -67,6 +67,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 +137,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_mac.mm b/src/apps/desktop/agent_browser_host_mac.mm index 9eac9552..3f0ad548 100644 --- a/src/apps/desktop/agent_browser_host_mac.mm +++ b/src/apps/desktop/agent_browser_host_mac.mm @@ -1,4 +1,5 @@ #include "agent_browser_host.hpp" +#include "page_annotation_session.hpp" #ifdef __APPLE__ @@ -443,6 +444,8 @@ - (void)webView:(WKWebView*)webView struct Page { std::string id; + PageAnnotationSession annotations; + std::uint64_t annotation_incarnation = 0; AgentBrowserState state; AgentBrowserBounds requested_bounds; ACECodeAgentBrowserSurfaceView* surface = nil; @@ -1012,6 +1015,7 @@ void clear_history(const std::shared_ptr& page) { void teardown_page(const std::shared_ptr& page) { if (!page) return; + ++page->annotation_incarnation; clear_dialog(page, true); clear_history(page); if (page->webview) { @@ -1264,6 +1268,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; @@ -1305,12 +1310,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; @@ -1574,6 +1581,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}, @@ -1910,12 +1921,14 @@ 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(); 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; @@ -3183,6 +3196,46 @@ 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) { + const auto page = impl_ ? impl_->find_page(page_id) : nullptr; + if (!page || page->closing || !page->webview || + page->state.content_state != kAgentBrowserContentStateLive) { + completion(json{{"ok", false}, {"error", "Annotation page is unavailable"}}.dump()); + return; + } + const auto command = json::parse(command_json, nullptr, false); + std::string expression; + std::string error; + if (!page->annotations.prepare(page_id, command, expression, error)) { + completion(json{{"ok", false}, {"error", error}}.dump()); + return; + } + const auto sequence = page->annotations.sequence(); + const std::weak_ptr weak = impl_; + const std::weak_ptr weak_page = page; + const auto incarnation = page->annotation_incarnation; + impl_->evaluate_value(page, expression, + [weak, weak_page, sequence, incarnation, completion](bool ok, 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 || current->annotation_incarnation != incarnation || !ok || + !current->annotations.complete(sequence, result, error)) { + if (current) current->annotations.fail(sequence); + completion(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(json{{"ok", true}, {"page_id", current->id}, {"annotations", snapshot}}.dump()); + }); +} + 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/main.cpp b/src/apps/desktop/main.cpp index 67e5cb81..66acb89b 100644 --- a/src/apps/desktop/main.cpp +++ b/src/apps/desktop/main.cpp @@ -16,6 +16,7 @@ #include "daemon_pool.hpp" #include "agent_browser_host.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" @@ -141,6 +142,10 @@ nlohmann::json agent_browser_state_json( 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; } @@ -1082,6 +1087,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); std::atomic restart_requested{false}; const bool reveal_in_foreground = note_desktop_version_launch(ACECODE_VERSION) || relaunched; diff --git a/src/apps/desktop/page_annotation_bridge.cpp b/src/apps/desktop/page_annotation_bridge.cpp new file mode 100644 index 00000000..dc662caa --- /dev/null +++ b/src/apps/desktop/page_annotation_bridge.cpp @@ -0,0 +1,30 @@ +#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 bool delivered = browser.with([&](AgentBrowserHost& current) { + current.annotation_command(args[0]["page_id"].get(), + args[0]["command"].dump(), 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 00000000..85d76fd9 --- /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_runtime.hpp b/src/apps/desktop/page_annotation_runtime.hpp new file mode 100644 index 00000000..1a8b78dd --- /dev/null +++ b/src/apps/desktop/page_annotation_runtime.hpp @@ -0,0 +1,149 @@ +#pragma once + +namespace acecode::desktop { + +inline constexpr const char kPageAnnotationRuntime[] = R"ACEANNOTATION( +(command => { + 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; + let active = false; + let selected = null; + let selectedId = ''; + let open = false; + let sequence = 0; + const ids = new WeakMap(); + const pins = []; + const host = document.createElement('div'); + host.style.cssText = 'all:initial;position:fixed;inset:0;pointer-events:none;z-index:2147483647'; + 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 control = document.createElement('button'); + control.type = 'button'; + control.textContent = 'Annotate'; + control.setAttribute('aria-label', 'Annotate selected element'); + control.style.cssText = 'position:fixed;pointer-events:auto;background:ButtonFace;color:ButtonText;border:1px solid ButtonBorder;border-radius:4px;padding:4px 8px;display:none'; + shadow.append(outline, control); + 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 layout = () => { + const visible = active && connected(selected); + outline.style.display = visible ? 'block' : 'none'; + control.style.display = visible && !open ? '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`}); + control.style.left = `${Math.max(0, Math.min(innerWidth - control.offsetWidth, bounds.x))}px`; + control.style.top = `${Math.max(0, Math.min(innerHeight - control.offsetHeight, bounds.y + bounds.height))}px`; + } + for (const pin of pins) { + pin.marker.style.display = connected(pin.target) ? 'block' : 'none'; + if (!connected(pin.target)) continue; + const bounds = rect(pin.target); + pin.marker.style.left = `${bounds.x}px`; + pin.marker.style.top = `${bounds.y}px`; + } + }; + const snapshot = () => { + layout(); + const target = connected(selected) ? { + id:selectedId, + tag:selected.localName.slice(0, 64), + text:(selected.innerText || selected.textContent || '').slice(0, 512), + locator:selected.localName + (selected.id ? '#' + selected.id.slice(0, 128) : ''), + bounds:rect(selected), + } : null; + return {document_id:documentId, active, popup:!!target && open, target, + viewport:{width:innerWidth, height:innerHeight}}; + }; + const select = event => { + if (!active || !event.isTrusted || event.composedPath().includes(host)) return; + if (event.button !== 0) return; + event.preventDefault(); + event.stopImmediatePropagation(); + if (open) return; + const target = event.composedPath().find(node => node?.nodeType === 1); + if (!connected(target)) return; + selected = target; + if (!ids.has(target)) ids.set(target, `target-${++sequence}`); + selectedId = ids.get(target); + open = false; + layout(); + }; + const suppress = event => { + if (active && event.isTrusted && !event.composedPath().includes(host)) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + }; + const escape = event => { + if (!active || !event.isTrusted || event.key !== 'Escape') return; + event.preventDefault(); + event.stopImmediatePropagation(); + active = false; + selected = null; + open = false; + layout(); + }; + control.addEventListener('click', event => { + if (!active || !event.isTrusted || !connected(selected)) return; + event.preventDefault(); + event.stopPropagation(); + open = true; + layout(); + }); + document.addEventListener('pointerdown', suppress, true); + document.addEventListener('mousedown', suppress, true); + document.addEventListener('click', select, true); + document.addEventListener('keydown', escape, true); + globalThis.addEventListener('scroll', layout, true); + globalThis.addEventListener('resize', layout); + runtime = Object.freeze({document_id:documentId, dispose() { + document.removeEventListener('pointerdown', suppress, true); + document.removeEventListener('mousedown', suppress, true); + document.removeEventListener('click', select, true); + document.removeEventListener('keydown', escape, true); + globalThis.removeEventListener('scroll', layout, true); + globalThis.removeEventListener('resize', layout); + host.remove(); + }, run(next) { + if (document !== rootDocument || next.document_id !== documentId) return {error:'stale_document'}; + switch (next.action) { + case 'start': active = true; break; + case 'read': break; + case 'exit': active = false; selected = null; open = false; break; + case 'cancel': selected = null; open = false; break; + case 'save': { + if (!active || !open || !connected(selected) || selectedId !== next.target_id) return {error:'stale_target'}; + const marker = document.createElement('span'); + marker.textContent = String(next.number); + marker.style.cssText = 'position:fixed;pointer-events:none;border-radius:12px;padding:2px 6px;background:Highlight;color:HighlightText'; + shadow.append(marker); + pins.push({target:selected, marker}); + selected = null; + open = false; + break; + } + 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 00000000..24edc0d6 --- /dev/null +++ b/src/apps/desktop/page_annotation_session.hpp @@ -0,0 +1,178 @@ +#pragma once + +#include "page_annotation_runtime.hpp" + +#include +#include +#include +#include + +namespace acecode::desktop { + +class PageAnnotationSession { +public: + using Json = nlohmann::json; + + Json snapshot() const { + return {{"document_id", document_id_}, {"active", active_}, + {"popup", popup_}, {"target", target_}, {"viewport", viewport_}, {"records", records_}, + {"pending_count", records_.size()}, {"revision", revision_}}; + } + + void replace_document() { + ++epoch_; + ++sequence_; + busy_ = false; + active_ = false; + popup_ = false; + target_ = nullptr; + document_id_.clear(); + for (auto& record : records_) record["valid"] = false; + ++revision_; + } + + bool prepare(const std::string& page_id, const Json& command, + std::string& expression, std::string& error) { + 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") { + error = "Unsupported annotation action"; + return false; + } + for (const auto& item : command.items()) { + if (item.key() != "action" && item.key() != "document_id" && + !(action == "save" && (item.key() == "description" || item.key() == "target_id"))) { + error = "Unsupported annotation field"; + return false; + } + } + if (busy_) { + error = "Annotation command already in progress"; + return false; + } + if (document_id_.empty() && action == "start") { + document_id_ = page_id + ":document:" + std::to_string(epoch_); + } + if (!command.contains("document_id") || !command["document_id"].is_string() || + (action != "start" && command["document_id"] != document_id_) || + (action == "start" && command["document_id"] != "" && + command["document_id"] != document_id_) || document_id_.empty()) { + error = "Stale annotation document"; + return false; + } + if (action == "save" && (!active_ || !popup_ || !target_.is_object() || + !command.contains("target_id") || command["target_id"] != target_["id"] || + !command.contains("description") || !command["description"].is_string() || + command["description"].get_ref().size() > 16384)) { + error = "Invalid annotation draft"; + return false; + } + pending_ = command; + page_id_ = page_id; + Json payload{{"action", action}, {"document_id", document_id_}}; + if (action == "save") { + payload["target_id"] = target_["id"]; + payload["number"] = next_number_; + } + expression = std::string(kPageAnnotationRuntime) + "(" + payload.dump() + ")"; + busy_ = true; + ++sequence_; + return true; + } + + std::uint64_t sequence() const { return sequence_; } + + 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 (!valid_result(result)) { + error = "Invalid or stale annotation result"; + return false; + } + const auto action = pending_["action"].get(); + if ((action == "save" || action == "cancel" || action == "exit") && + (!result["target"].is_null() || result["popup"] != false)) { + error = "Annotation action did not complete"; + return false; + } + const bool changed = action == "save" || active_ != result["active"] || + popup_ != result["popup"] || target_ != result["target"] || viewport_ != result["viewport"]; + if (action == "save") { + records_.push_back({ + {"id", document_id_ + ":annotation:" + std::to_string(next_number_)}, + {"number", next_number_++}, {"document_id", document_id_}, + {"page_id", page_id_}, + {"description", pending_["description"]}, {"targets", Json::array({target_})}, + {"differences", Json::array()}, {"region", nullptr}, + {"status", "pending"}, {"valid", true}, + }); + } + active_ = result["active"].get(); + popup_ = result["popup"].get(); + target_ = result["target"]; + viewport_ = result["viewport"]; + if (changed) ++revision_; + return true; + } + + void fail(std::uint64_t sequence) { + if (sequence == sequence_) busy_ = false; + } + +private: + bool valid_result(const Json& result) const { + if (!result.is_object() || result.dump().size() > 8192 || + !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()) 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; + } + const auto& target = result["target"]; + if (result["active"] == false && (!target.is_null() || result["popup"] != false)) return false; + if (target.is_null()) return result["popup"] == false; + 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"] == "" || + !target.contains("bounds") || !target["bounds"].is_object()) return false; + for (const auto& field : {"x", "y", "width", "height"}) { + const auto& bounds = target["bounds"]; + if (!bounds.contains(field) || !bounds[field].is_number()) return false; + const double value = bounds[field].get(); + if (!std::isfinite(value) || std::abs(value) > 10000000 || + ((std::string(field) == "width" || std::string(field) == "height") && value < 0)) return false; + } + return true; + } + + std::string document_id_; + std::string page_id_; + std::uint64_t epoch_ = 1; + std::uint64_t sequence_ = 0; + std::uint64_t revision_ = 0; + std::uint64_t next_number_ = 1; + bool busy_ = false; + bool active_ = false; + bool popup_ = false; + Json target_ = nullptr; + Json viewport_ = nullptr; + Json records_ = Json::array(); + Json pending_; +}; + +} // namespace acecode::desktop diff --git a/tests/desktop/page_annotation_session_test.cpp b/tests/desktop/page_annotation_session_test.cpp new file mode 100644 index 00000000..1f80b413 --- /dev/null +++ b/tests/desktop/page_annotation_session_test.cpp @@ -0,0 +1,184 @@ +#include + +#include "desktop/page_annotation_session.hpp" + +namespace acecode::desktop { +namespace { + +using Json = nlohmann::json; + +class PageAnnotationSessionTest : public testing::Test { +protected: + Json command(const std::string& action) const { + return {{"action", action}, {"document_id", session.snapshot()["document_id"]}}; + } + + 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}, + {"viewport", {{"width", 800}, {"height", 600}}}}; + } + + 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, 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, 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, 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)); +} + +} // namespace +} // namespace acecode::desktop diff --git a/web/scripts/i18n-en-overrides.mjs b/web/scripts/i18n-en-overrides.mjs index 8a2f47e0..21358be7 100644 --- a/web/scripts/i18n-en-overrides.mjs +++ b/web/scripts/i18n-en-overrides.mjs @@ -1,6 +1,16 @@ // Human-reviewed product terminology and phrases where generic machine // translation is ambiguous without ACECode context. export const ENGLISH_SOURCE_OVERRIDES = Object.freeze({ + '退出网页批注': 'Exit page annotations', + '网页批注': '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.', diff --git a/web/src/components/AgentBrowserPanel.jsx b/web/src/components/AgentBrowserPanel.jsx index 1f69a1eb..f7455a68 100644 --- a/web/src/components/AgentBrowserPanel.jsx +++ b/web/src/components/AgentBrowserPanel.jsx @@ -35,6 +35,7 @@ import { } from '../lib/agentBrowserSurfaceCoordinator.js'; import { AgentBrowserMoreMenu } from './AgentBrowserMoreMenu.jsx'; import { AgentBrowserNewTab } from './AgentBrowserNewTab.jsx'; +import { PageAnnotationPopup, usePageAnnotations } from './PageAnnotations.jsx'; import { NavigationArrowIcon, RefreshIcon, VsIcon } from './Icon.jsx'; import { toast } from './Toast.jsx'; @@ -75,6 +76,7 @@ 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); useEffect(() => { let cancelled = false; @@ -450,13 +452,23 @@ export function AgentBrowserPanel({
+ +
+ '; + 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()`); @@ -135,8 +326,9 @@ try { await evaluate("target.style.setProperty('color','red','important'); previews.select(target,'target-1')"); assert.deepEqual(await preview({ color: 'green' }), []); - assert.deepEqual(await evaluate("previews.describe(target,'target-1').errors"), ['inline_important:color']); + 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()'); @@ -149,7 +341,7 @@ try { 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 conflicts are explicit; clones never inherit previews; disposal restores original stylesheet membership'); + 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)'); @@ -186,7 +378,6 @@ try { }; await run('start'); await click(20, 30); - await click(30, 70); 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); @@ -202,7 +393,6 @@ try { assert.equal(await value('color'), 'rgb(0, 0, 255)'); await run('start'); await click(20, 30); - await click(30, 70); await run('preview_style', { target_id: 'target-1', styles: { color: 'green' } }); await run('cancel'); assert.equal(await value('color'), 'rgb(0, 0, 255)'); @@ -210,6 +400,18 @@ try { 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); diff --git a/web/src/lib/pageAnnotationText.test.js b/web/src/lib/pageAnnotationText.test.js index f62efca2..77e14ad9 100644 --- a/web/src/lib/pageAnnotationText.test.js +++ b/web/src/lib/pageAnnotationText.test.js @@ -5,7 +5,8 @@ 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(')[1].split(')ACEANNOTATION"')[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'); @@ -59,13 +60,11 @@ function fixture(markup = '