From 51e173f9942735b2bd936aadd66b1a455cc5464f Mon Sep 17 00:00:00 2001 From: Emre Sokullu Date: Sun, 25 Oct 2026 05:49:32 +0300 Subject: [PATCH 01/70] Vision mode: screenshot-and-coordinate Act runs with diff updates Act runs whose model takes images now see the tab as screenshots and act with coordinates instead of the accessibility tree (Settings > Advanced > Vision mode, on by default; the tree path stays for text-only models and when the setting is off). - Shared modules (byte-identical in both builds): vision-mode, vision-budget (per-provider sizes that no server rescales, 28/32 px grids, WebP/JPEG, token estimates), vision-diff (cell diff, regions, patch/keyframe/none planning), vision-session (image ids f/p/z, image->CSS maps, staleness), vision-tools (tool surface, prompt, labels, click_at translation), vision-encoder (canvas resample/encode), vision-runtime (keyframes, observation after batches, native tools, pruning). - click_at is rewritten into a canonical coordinate click before the batch pipeline, so every gate and hard guard still applies; Chrome dispatches trusted CDP pointer events at the exact point, Firefox a synthetic sequence from the content script. - Captures account for CDP clip coordinates being document coordinates and for output = clip x scale x DPR (retina, browser zoom); the real capture is resampled to the planned size so mapping stays exact. - Only the current frame, its patches and zooms stay in the request. - Legacy auto-screenshots: clip now starts at the scroll offset (was blank on scrolled pages) and divides the DPR out (was 2x on retina). - Settings UI, locales (23), config export, trace runtime config, docs. - Tests: unit, agent run loop (both builds), Chromium DPR 1/2/3 pipeline, installed MV3 e2e at DPR 1/2 and browser zoom. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WKLAisk5u8VVdGkG8ZwtUf --- AGENT.md | 2 + README.md | 4 + docs/accessibility-tree-and-refs.md | 2 + docs/agent-tools.md | 8 + docs/vision-mode.md | 123 +++++ package.json | 3 +- src/chrome/src/agent/agent.js | 363 ++++++++++++++- src/chrome/src/agent/mutation-tools.js | 2 +- src/chrome/src/agent/permission-gate.js | 12 + src/chrome/src/agent/tools.js | 22 +- src/chrome/src/agent/vision-budget.js | 205 +++++++++ src/chrome/src/agent/vision-diff.js | 298 ++++++++++++ src/chrome/src/agent/vision-encoder.js | 173 +++++++ src/chrome/src/agent/vision-mode.js | 55 +++ src/chrome/src/agent/vision-runtime.js | 561 +++++++++++++++++++++++ src/chrome/src/agent/vision-session.js | 309 +++++++++++++ src/chrome/src/agent/vision-tools.js | 346 ++++++++++++++ src/chrome/src/background.js | 25 + src/chrome/src/config-transfer.js | 6 + src/chrome/src/content/content.js | 172 +++++++ src/chrome/src/trace/runtime-config.js | 2 + src/chrome/src/ui/locales/ar.js | 9 + src/chrome/src/ui/locales/bn.js | 9 + src/chrome/src/ui/locales/de.js | 9 + src/chrome/src/ui/locales/en.js | 9 + src/chrome/src/ui/locales/es.js | 9 + src/chrome/src/ui/locales/fa.js | 9 + src/chrome/src/ui/locales/fr.js | 9 + src/chrome/src/ui/locales/he.js | 9 + src/chrome/src/ui/locales/hi.js | 9 + src/chrome/src/ui/locales/id.js | 9 + src/chrome/src/ui/locales/ja.js | 9 + src/chrome/src/ui/locales/ko.js | 9 + src/chrome/src/ui/locales/ms.js | 9 + src/chrome/src/ui/locales/nl.js | 9 + src/chrome/src/ui/locales/pl.js | 9 + src/chrome/src/ui/locales/pt.js | 9 + src/chrome/src/ui/locales/ru.js | 9 + src/chrome/src/ui/locales/th.js | 9 + src/chrome/src/ui/locales/tl.js | 9 + src/chrome/src/ui/locales/tr.js | 9 + src/chrome/src/ui/locales/uk.js | 9 + src/chrome/src/ui/locales/vi.js | 9 + src/chrome/src/ui/locales/zh.js | 9 + src/chrome/src/ui/settings.html | 21 + src/chrome/src/ui/settings.js | 16 +- src/firefox/src/agent/agent.js | 219 ++++++++- src/firefox/src/agent/mutation-tools.js | 2 +- src/firefox/src/agent/permission-gate.js | 12 + src/firefox/src/agent/tools.js | 22 +- src/firefox/src/agent/vision-budget.js | 205 +++++++++ src/firefox/src/agent/vision-diff.js | 298 ++++++++++++ src/firefox/src/agent/vision-encoder.js | 173 +++++++ src/firefox/src/agent/vision-mode.js | 55 +++ src/firefox/src/agent/vision-runtime.js | 561 +++++++++++++++++++++++ src/firefox/src/agent/vision-session.js | 309 +++++++++++++ src/firefox/src/agent/vision-tools.js | 346 ++++++++++++++ src/firefox/src/background.js | 24 + src/firefox/src/config-transfer.js | 6 + src/firefox/src/content/content.js | 172 +++++++ src/firefox/src/trace/runtime-config.js | 2 + src/firefox/src/ui/locales/ar.js | 9 + src/firefox/src/ui/locales/bn.js | 9 + src/firefox/src/ui/locales/de.js | 9 + src/firefox/src/ui/locales/en.js | 9 + src/firefox/src/ui/locales/es.js | 9 + src/firefox/src/ui/locales/fa.js | 9 + src/firefox/src/ui/locales/fr.js | 9 + src/firefox/src/ui/locales/he.js | 9 + src/firefox/src/ui/locales/hi.js | 9 + src/firefox/src/ui/locales/id.js | 9 + src/firefox/src/ui/locales/ja.js | 9 + src/firefox/src/ui/locales/ko.js | 9 + src/firefox/src/ui/locales/ms.js | 9 + src/firefox/src/ui/locales/nl.js | 9 + src/firefox/src/ui/locales/pl.js | 9 + src/firefox/src/ui/locales/pt.js | 9 + src/firefox/src/ui/locales/ru.js | 9 + src/firefox/src/ui/locales/th.js | 9 + src/firefox/src/ui/locales/tl.js | 9 + src/firefox/src/ui/locales/tr.js | 9 + src/firefox/src/ui/locales/uk.js | 9 + src/firefox/src/ui/locales/vi.js | 9 + src/firefox/src/ui/locales/zh.js | 9 + src/firefox/src/ui/settings.html | 21 + src/firefox/src/ui/settings.js | 16 +- test/quality/vision-mode-mv3.mjs | 198 ++++++++ test/vision-mode-agent.mjs | 302 ++++++++++++ test/vision-mode.mjs | 425 +++++++++++++++++ test/vision-pipeline-browser.mjs | 217 +++++++++ 90 files changed, 6708 insertions(+), 21 deletions(-) create mode 100644 docs/vision-mode.md create mode 100644 src/chrome/src/agent/vision-budget.js create mode 100644 src/chrome/src/agent/vision-diff.js create mode 100644 src/chrome/src/agent/vision-encoder.js create mode 100644 src/chrome/src/agent/vision-mode.js create mode 100644 src/chrome/src/agent/vision-runtime.js create mode 100644 src/chrome/src/agent/vision-session.js create mode 100644 src/chrome/src/agent/vision-tools.js create mode 100644 src/firefox/src/agent/vision-budget.js create mode 100644 src/firefox/src/agent/vision-diff.js create mode 100644 src/firefox/src/agent/vision-encoder.js create mode 100644 src/firefox/src/agent/vision-mode.js create mode 100644 src/firefox/src/agent/vision-runtime.js create mode 100644 src/firefox/src/agent/vision-session.js create mode 100644 src/firefox/src/agent/vision-tools.js create mode 100644 test/quality/vision-mode-mv3.mjs create mode 100644 test/vision-mode-agent.mjs create mode 100644 test/vision-mode.mjs create mode 100644 test/vision-pipeline-browser.mjs diff --git a/AGENT.md b/AGENT.md index f2d010ade4..a47f1759bf 100644 --- a/AGENT.md +++ b/AGENT.md @@ -67,6 +67,8 @@ vanilla JS/CSS unless there is a very strong reason to add a framework. - `docs/adding-a-tool.md`: required checklist for new or changed agent tools. - `docs/accessibility-tree-and-refs.md`: AX refs, page reads, and interaction targeting. +- `docs/vision-mode.md`: screenshot-and-coordinate Act runs (the default for + image-capable models), capture/DPR rules, diffs and the vision tool surface. - `docs/site-adapters.md`: adapter shape, prompt style, and testing guidance. - `docs/providers-and-models.md`: provider configuration and model capability assumptions. diff --git a/README.md b/README.md index 14fe80e306..915fbd64b9 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,10 @@ required; turning the existing switch off also purges queued diagnostics. elements, via the accessibility tree rather than brittle selectors - **Acts on it** — click, type, scroll, navigate, upload, download, and verify forms, with per-site permission prompts before consequential actions +- **Vision mode** — with a model that takes images, Act runs see the page as + screenshots and click, type and scroll at coordinates; only the changed part + of the screen is sent after each action, and retina displays and browser + zoom are handled ([details](docs/vision-mode.md)) - **Plan before Act** — Act and Dev can generate a structured plan, show it for approval, and pin the approved plan to the scratchpad before any tool runs - **Multi-step agent** — autonomous tool-use loop, configurable up to 195 steps diff --git a/docs/accessibility-tree-and-refs.md b/docs/accessibility-tree-and-refs.md index 82874fead5..b95b26fbab 100644 --- a/docs/accessibility-tree-and-refs.md +++ b/docs/accessibility-tree-and-refs.md @@ -2,6 +2,8 @@ The accessibility-tree (AX) subsystem is the primary page-interaction path for the agent. It replaces the older index-based `get_interactive_elements` for almost all flows. +An Act run in [vision mode](vision-mode.md) (the default when the model takes images) does not use this subsystem for its model: it sees screenshots and acts with coordinates. Everything below applies to Ask, Dev, text-only models and Act with vision mode off. + --- ## Architecture diff --git a/docs/agent-tools.md b/docs/agent-tools.md index d362331cfd..01ca717a7a 100644 --- a/docs/agent-tools.md +++ b/docs/agent-tools.md @@ -26,6 +26,14 @@ Tier defaults and resolution rules are documented in lean Act run gets its tier's tools and prompt, and WebBrain skips its quality checks; see [lean mode](lean-mode.md). +**Vision mode** (Settings → Advanced → Vision mode, on by default) replaces the +tree, ref and selector tools of an Act run whose model takes images with +coordinate tools (`click_at`, `scroll_at`, `hover_at`, `drag_at`, `zoom`, +`take_screenshot`, `wait`) and a vision prompt; the run sees the page as a +full frame and then patches of what changed. The matrix below is the +accessibility-tree surface. See [vision mode](vision-mode.md) for the exact +replacement list. + ## Accessibility read budgets For complete HTML-table JSON, `extract_data({type:"tables", caption:"Exact caption", diff --git a/docs/vision-mode.md b/docs/vision-mode.md new file mode 100644 index 0000000000..a02130be74 --- /dev/null +++ b/docs/vision-mode.md @@ -0,0 +1,123 @@ +# Vision mode + +In vision mode an Act run sees the tab only as screenshots and acts with the mouse and keyboard at coordinates. There is no accessibility tree, no `ref_id` and no CSS selector in the model's view. The run starts from a full frame of the viewport; after every action WebBrain sends only what changed on screen (a patch), a new full frame when most of the screen changed, or a one-line "no visible change". + +The accessibility-tree path stays available (Settings → Advanced → **Vision mode** → Off) and is used automatically when the model cannot take images. + +## The setting + +Settings → Advanced: + +- **Vision mode** (storage key `visionMode`): **On** (default) or **Off**. On applies to Act runs whose model receives screenshots directly (`provider.supportsVision`). A separate describe-only vision model cannot aim clicks, so a text-only model keeps the accessibility tree. Ask and Dev are unchanged. +- **Vision screenshot size** (`visionQuality`): **Economy**, **Balanced** (default) or **Sharp**. It caps the model-facing image (Economy: long edge 1024 px / 0.6 MP; Balanced: 1440 px / 1.05 MP; Sharp: the provider's own limit). The model can always `zoom` for detail. + +A run decides once, when it starts (`_beginVisionRun` snapshots both settings), like lean mode. The resolved state is recorded in the trace's runtime config as `vision_mode_setting` and `vision_mode`. The `Agent` class default is `off`, so embedders and unit tests opt in explicitly; `background.js` applies the stored setting, whose default is `on`. + +## Tools + +A vision run gets its tier's Act tools with the DOM-targeting ones replaced (`VISION_REMOVED_TOOLS` in `vision-tools.js`): + +| Removed | Added | +|---|---| +| `get_accessibility_tree`, `click_ax`, `type_ax`, `set_field`, `set_checked`, `hover`, `drag_drop`, `inspect_viewport`, `get_interactive_elements`, `click`, `scroll`, `browser_batch`, `wait_for_element`, `find_text`, `verify_form`, `iframe_*`, `get_frames`, `get_shadow_dom`, `shadow_dom_query`, `promote_iframe`, `carousel_navigate`, `upload_file`, `download_resource_from_page`, `gmail_count_results` | `click_at`, `scroll_at`, `hover_at`, `drag_at`, `zoom`, `take_screenshot`, `wait` | + +`type_text` stays with a vision schema (`text`, `clear`; it types into the focused field). Everything that does not name a DOM target is kept: `press_keys`, `navigate`, `go_back`/`go_forward`, `read_page`, `read_pdf`, `extract_data`, `fetch_url`, downloads, scheduling, `scratchpad_write`, `progress_*`, `clarify`, `done`, skills and the CAPTCHA tools. `read_page` is the cheap way to get exact long text; screenshots are the primary view. + +| Tool | What it does | +|---|---| +| `click_at({x, y, image?, button?, clicks?})` | A real mouse click at the point. `clicks:2` double-clicks, `clicks:3` selects a line, `button:"right"` opens a context menu. | +| `scroll_at({direction, amount?, x?, y?})` | Mouse-wheel scrolling of whatever is under the point (page, pane, list, map), in steps of ~100 CSS px. | +| `hover_at({x, y})` | Moves the pointer without clicking (hover menus, tooltips). | +| `drag_at({start_x, start_y, end_x, end_y})` | Press, move and release (sliders, reordering, selecting). | +| `zoom({x, y, width, height})` | Returns the rectangle as a sharper image `z` (up to 2 image px per CSS px). | +| `take_screenshot()` | A fresh full frame. | +| `wait({seconds})` | Waits 0.2–10 s; the screen update follows. | + +The vision prompt (`buildVisionActPrompt`, used through `getVisionActPrompt` in `tools.js`) replaces the tier's tree-centred Act prompt and reuses the shared sensitive-data and plan-to-execution sections verbatim. + +## Images and coordinates + +Every image is labeled with an id: `f` for a full frame, `p` for a patch, `z` for a zoom. The model gives a point in the pixels of the image it read it from and names that image with `image` when it is a patch or zoom; with no `image` the point is read from the current screen (latest frame plus its patches). `VisionSession` (`vision-session.js`) keeps each image's map to the frame and the frame's map to CSS pixels, so the model never rescales anything. + +Gemini and Qwen3-VL point in relative 0..1000 coordinates; for them the tools and prompt say so and the session converts (`coordinates: 'normalized'`). Every other model uses image pixels. + +A point is refused before any dispatch when: + +- its image belongs to an earlier frame (`stale_image`), or the area around it changed in a later patch (`stale_area`); +- it lies outside the image; +- it is the second or later coordinate action of one model turn and the live screen changed near it after the earlier action (`_visionStabilityBlock`, checked right before dispatch, after every gate). + +### Capture, retina and zoom + +`vision-budget.js` picks the image size per provider family (`detectVisionProfile`), as the largest size the provider accepts **unchanged**: every vision API shrinks larger images before the model sees them, and the model then answers in the shrunk image's pixels. + +| Profile | Limits | Format | +|---|---|---| +| Anthropic | long edge ≤ 1568, ≤ 1.15 MP | WebP | +| OpenAI | ≤ 2048, short edge ≤ 768 | WebP | +| Gemini | ≤ 1536, ≤ 1.2 MP; 0..1000 points | WebP | +| Qwen2/2.5-VL, UI-TARS | ≤ 1.0 MP, multiples of 28 (so `smart_resize` is the identity) | JPEG | +| Qwen3-VL / Qwen3.5+ | ≤ 1.05 MP, multiples of 32; 0..1000 points | JPEG | +| Local (llama.cpp, Ollama, LM Studio, WebGPU) | ≤ 1280, ≤ 1.0 MP, multiples of 28 | JPEG (llama.cpp cannot decode WebP) | + +An image never has more pixels than the CSS viewport: a retina capture is downscaled locally, and `zoom` is the path to fine detail. WebP is ~30% smaller than JPEG for UI screenshots, so uploads are faster; providers bill images by pixels, so the token cost is the same. + +Chrome captures with CDP `Page.captureScreenshot`. Two properties of that call drive the implementation (verified in `test/vision-pipeline-browser.mjs`): + +- **Clip coordinates are document coordinates.** A clip at `0,0` on a scrolled page captures the unrendered top of the document, a blank frame. The clip starts at the visual viewport's page offset (`Page.getLayoutMetrics`). +- **The output is clip × scale × device pixel ratio.** The requested scale divides the DPR out (browser zoom is part of the DPR), and whatever size actually comes back is resampled to the plan (`rasterizeFrame`), so emulated DPRs and compositor quirks cannot change the coordinate map. + +Firefox captures with `tabs.captureTab`, whose `scale` is image pixels per CSS pixel (no DPR factor) and whose `rect` is page-relative. + +### Diffs + +After a batch WebBrain waits until two consecutive captures match (bounded, ~1 s), then compares the new frame with what the model has seen (`vision-diff.js`): 16 px cells, a per-pixel threshold that ignores encoder noise and caret blinks, nearby changes merged, at most 4 padded regions. `planFrameUpdate` sends: + +- **nothing but a one-line note** when nothing changed: "no visible change" is also the clearest signal that a click missed; +- **patches** for local changes (typing, a menu, a toast); +- **a new frame** when more than 45% changed, the patch chain is 6 long, patches would cost ≥ 70% of a frame, or the URL, viewport size or DPR changed. + +The "seen" buffer copies only patched regions, so changes below the threshold accumulate until they are sent instead of drifting forever. + +Only the current frame, its patches and zooms stay in the model request (`pruneVisionImages`); older images become a short placeholder. Screen updates are app-owned user turns (`webbrainAppOwned`), never mistaken for a new request. + +## Input dispatch and safety + +`click_at` is rewritten into an ordinary coordinate `click` (`translateVisionClick`) before the batch pipeline runs, so the permission gate, the submit probe and every hard guard (recipient, deletion, money, credentials, publishing) inspect it like any other click. Only the final dispatch differs: + +- **Chrome**: trusted CDP pointer events at exactly the point (`_visionDispatchClick`), with the coordinate path's dispatch-time protections kept: a native `` popup is never visible in a screenshot: such a field is focused and `type_text` picks the option. +- HTML5 drag and drop driven only by `dataTransfer` may not react to synthetic or CDP pointer drags. +- Firefox input is synthetic (`isTrusted: false`); pages that require trusted events need Chrome. diff --git a/package.json b/package.json index 925086b245..97d126ab58 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "test:webmcp": "node test/webmcp-e2e.mjs", "test:vision": "node test/vision/run.mjs", "test:vision:validate": "node --test test/vision/lib/score.test.mjs && node test/vision/validate.mjs", + "test:vision-mode": "node --test test/vision-mode.mjs test/vision-mode-agent.mjs test/vision-pipeline-browser.mjs && node test/quality/vision-mode-mv3.mjs && node test/quality/vision-mode-mv3.mjs --dpr=2 && node test/quality/vision-mode-mv3.mjs --dpr=2 --zoom=1.5", "test:llm-tiny:validate": "node --test test/llm-tiny/cases.test.mjs test/llm-tiny/lib/adapters.test.mjs && node --check test/llm-tiny/run.mjs && node test/llm-tiny/run.mjs --help", "test:anonymous": "node test/anonymous/run.mjs", "test:ci": "node ci/test.mjs && node ci/cloud-capture.test.mjs", @@ -106,7 +107,7 @@ "test:shard:browser-a": "node --test test/captcha-draft-content.mjs test/captcha-challenge-surfaces.mjs && node test/bot-memory-dom.mjs && node test/bot-memory-click-dom.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/sidepanel-permission-gate-ui.mjs test/model-picker-status-ui.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-chat-selection.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/native-button-preparation.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/activity-brain-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/lifecycle-run-ui.mjs test/lifecycle-menu-prompts-held.mjs test/delivery-cdp-input.mjs test/delivery-click-ax-response-loss.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-native-button-route.mjs test/delivery-dispatch-boundary.mjs test/delivery-stop-compound.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/submit-probe-readings.mjs test/declined-submission-identity.mjs test/improver-content-account-chrome.mjs test/improver-content-recipient.mjs test/improver-content-truncated-replacement.mjs test/improver-forms-probe.mjs test/improver-misc-trace-browser.mjs test/page-feedback-held-time.mjs test/page-monitor-held-observation.mjs", "test:shard:browser-b1": "node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs test/message-control-readings.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/integration-mv3.mjs --batch && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/ask-person-activity-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs", "test:shard:browser-b2": "node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs --selector-recovery && node test/quality/upload-release-binding-mv3.mjs --sequential-assets && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/shared-action-guards-mv3.mjs && node test/quality/video-upload-attachment-mv3.mjs && node --test test/iframe-probe-match-index.mjs", - "test:shard:browser-c": "node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/mastodon-delete-after-correction-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs", + "test:shard:browser-c": "node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/mastodon-delete-after-correction-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs && npm run test:vision-mode", "test:shard:tail": "node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security && node --test test/placeholder-submit-probe.mjs", "test:composer-context": "node --test test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs", "test:bot-memory": "node --test test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs && node test/bot-memory-dom.mjs && node test/quality/cloud-bot-memory-mv3.mjs", diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js index 0a7ae26c60..6d27650095 100644 --- a/src/chrome/src/agent/agent.js +++ b/src/chrome/src/agent/agent.js @@ -19,7 +19,10 @@ import { AUTO_MODE, AUTO_MODE_ASK_NOTE, autoModeGenerativeMediaNote, REQUEST_ACT import { SEMANTIC_BATCH_LIMITS, SEMANTIC_DECISION_VERSION, acceptSemanticAnswer, acceptSemanticBatchAnswers, boundedSemanticData, controlEffectCommits, semanticDataComplete, semanticBatchChunks, semanticBatchDecisionMessages, semanticDecisionMessages, semanticQuestion, semanticSystemOneBatchQuestions, semanticSystemOneQuestion, WORKFLOW_STATES } from './semantic-decisions.js'; import { SOCIAL_PLATFORMS, socialPublicationApiPlatform, normalizePublicationContract, resolvePublicationText, publicationProgress, exactPublicationText, publicationMediaMatches, publicationContractMessages, publicationAuditMessages, parsePublicationJson, publicationAuditValidation } from './social-publish-contract.js'; import { mastodonPublicationIntentMessages, normalizeMastodonPublicationIntent, captureNativeMastodonPublication, mastodonPublicationBinding, mastodonPublicationReceipt, mastodonPublicationNavigation } from './mastodon-publication.js'; -import { AGENT_TOOLS, AGENT_TOOL_NAMES, RESERVED_AGENT_TOOL_NAMES, RETIRED_AGENT_TOOL_NAMES, getToolsForMode, SYSTEM_PROMPT_BATCHING, SYSTEM_PROMPT_ASK, SYSTEM_PROMPT_ACT, SYSTEM_PROMPT_ACT_COMPACT, SYSTEM_PROMPT_ACT_MID, SYSTEM_PROMPT_LEAN_NOTE, SYSTEM_PROMPT_GENERATIVE_MEDIA, SYSTEM_PROMPT_DEV_APPENDIX, SYSTEM_PROMPT_WEBMCP_ASK, SYSTEM_PROMPT_WEBMCP_ACT } from './tools.js'; +import { AGENT_TOOLS, AGENT_TOOL_NAMES, RESERVED_AGENT_TOOL_NAMES, RETIRED_AGENT_TOOL_NAMES, getToolsForMode, SYSTEM_PROMPT_BATCHING, SYSTEM_PROMPT_ASK, SYSTEM_PROMPT_ACT, SYSTEM_PROMPT_ACT_COMPACT, SYSTEM_PROMPT_ACT_MID, SYSTEM_PROMPT_LEAN_NOTE, SYSTEM_PROMPT_GENERATIVE_MEDIA, SYSTEM_PROMPT_DEV_APPENDIX, SYSTEM_PROMPT_WEBMCP_ASK, SYSTEM_PROMPT_WEBMCP_ACT, getVisionActPrompt } from './tools.js'; +import { installVisionRuntime } from './vision-runtime.js'; +import { VISION_NATIVE_TOOLS } from './vision-tools.js'; +import { normalizeVisionModeSetting } from './vision-mode.js'; import { rejectedCompletionRecovery } from './completion-recovery.js'; import { FailureRecoveryRegistry, modelFailureRecovery } from './failure-recovery.js'; import { validateToolArguments } from './tool-arguments.js'; @@ -605,6 +608,9 @@ const SOCIAL_POST_SITES = new Set(['twitter', 'bluesky']); const COMPLETION_DOCUMENT_OBSERVATION_TOOLS = new Set([ 'chat_observe', 'auto_screenshot', + // Vision mode observations (vision-tools.js). + 'take_screenshot', + 'zoom', 'get_accessibility_tree', 'read_page', 'read_page_source', @@ -1036,6 +1042,13 @@ export class Agent extends LoopDetector { // resolves it once at its start (_beginLeanRun) and keeps the answer in // _leanRuns, so its prompt note and guards agree. See lean-mode.js. this.leanMode = 'auto'; + // Vision mode (vision-mode.js): 'on' | 'off'. The class default keeps + // the accessibility-tree path for embedders and the unit suite; + // background.js applies the stored setting, whose default is 'on'. + this.visionMode = 'off'; + this.visionQuality = 'balanced'; + this._visionSessions = new Map(); + this._visionRunSnapshots = new Map(); this._leanRuns = new Map(); // Advisory lists a run's calls carry, by owning tab, so a guard that is // handed only the list still knows which run it belongs to. @@ -8271,6 +8284,9 @@ export class Agent extends LoopDetector { screenshot_redaction: this.screenshotRedaction === true, strict_secret_mode: this.strictSecretMode === true, lean_mode_setting: normalizeLeanModeSetting(this.leanMode), + vision_mode_setting: normalizeVisionModeSetting(this.visionMode, 'off'), + // Whether this tab's run resolved to vision mode. + ...(tabId != null && this._visionRunSnapshots?.has(tabId) ? { vision_mode: this._visionRunState(tabId).active === true } : {}), // Whether this tab's run resolved to lean mode (traces show which ran). ...(tabId != null && this._leanRuns?.has(tabId) ? { lean_mode: this._leanRunActive(tabId) } : {}), plan_before_act_mode: this._normalizePlanBeforeActMode(this.planBeforeActMode), @@ -9594,6 +9610,8 @@ export class Agent extends LoopDetector { } async _maybeJevFastTurn(tabId, task, messages, mode, allowed, provider, costState, runOptions = {}, recovery = null) { + // The fast path proposes tree-ref actions; a vision run has none. + if (this._visionRunState(tabId, mode).active) return null; if (this._steeringRuns.get(tabId)?.acceptedIds.size || this._pageFeedbackRuns?.get(tabId)?.revision) return null; const context = this.systemOneContext(tabId); if (!['act', 'dev'].includes(mode) || this._checkAbort(tabId)) return null; @@ -12613,6 +12631,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d return enrichedUserMessage(contextLine + userMessage); } + // Vision mode takes its own first frame right before the model's first + // decision (vision-runtime.js); a legacy capture here would only cost + // tokens and a second image. + if (this._visionRunState(tabId).active) { + return enrichedUserMessage(contextLine + userMessage); + } + // Determine vision capability: either a dedicated vision model is // configured (routes screenshots there, text to main), or the main // provider itself supports images. Without either, plain text context. @@ -15581,6 +15606,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d toolCalls = expandBrowserBatchCalls(toolCalls, { enabled: this.browserBatchEnabled !== false, tier: this._resolvePromptTier(provider), allowedToolNames, toolSchemas: batchSchemas, }); + // Vision mode: click_at becomes an ordinary coordinate click here, before + // any gate or guard runs (vision-runtime.js). + toolCalls = this._visionTranslateToolCalls(tabId, toolCalls); const originalUpdate = onUpdate; const cancellationState = { active: null }; // Begin wrapper rows at their execution position, including rejected batches. @@ -16048,7 +16076,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d const jevPending = this._jevPendingCalls?.get(tc.id); const fnName = tc.function?.name || ''; - if (!allowedToolNames.has(fnName)) { + // A translated click_at runs as `click`, which vision runs do not advertise. + if (!allowedToolNames.has(fnName) && tc._vision?.internalName !== fnName) { if (fnName) { // A named but unadvertised tool is a rejection before dispatch, so // it goes through loop accounting; otherwise a model can repeat a @@ -16071,6 +16100,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; } continue; } + if (tc._vision?.error) { + const recovery = await recordPreparationFailure(toolIndex, tc._vision.tool || fnName, this._parseToolCallArgs(tc).args || {}, tc._vision.error); + if (recovery) return recovery; + continue; + } // Where this call's time goes before dispatch (_predispatchTimer), from // its first preparation step on: a consequential call whose arguments // or coordinates fail, or that a check stops, still records it. @@ -17404,6 +17438,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d { completionBatchStartState, _browserBatch: tc._browserBatch, + _vision: tc._vision || null, traceStep: step, jevBinding: jevPending?.call.binding, detectedSubmitAction, @@ -18475,6 +18510,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d // model sees the warning and the new viewport in the same turn. this._injectNavNotices(messages, navNotices, onUpdate, tabId); + // Vision mode shows the model a patch, a new frame or "no visible + // change" after every batch instead of the legacy auto-screenshot. + if (this._visionRunState(tabId).active) { + await this._visionObserveAfterBatch(tabId, messages, onUpdate, { toolCalls }); + this._persist(tabId); + return { action: 'continue' }; + } + // Auto-screenshot once per batch, debounced 500ms. Capture if either // the main provider supports images, or a dedicated vision model is // configured to describe them. @@ -19270,6 +19313,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d return shot; } + /** + * Clip for a CDP capture of the visible viewport. Clip coordinates are + * document coordinates (a clip at 0,0 on a scrolled page captures the + * unrendered top of the document: a blank frame), and the output is + * clip x scale x devicePixelRatio (scale 1 on a retina screen is twice the + * CSS size), so the scale divides the DPR out. + */ + _viewportCaptureClip(probe, cssW, cssH, scale = 1) { + const dpr = Math.max(0.25, Number(probe?.dpr) || 1); + return { + x: Math.max(0, Number(probe?.scrollX) || 0), + y: Math.max(0, Number(probe?.scrollY) || 0), + width: cssW, + height: cssH, + scale: scale / dpr, + }; + } + async _captureAutoScreenshot(tabId, { coordAligned = false } = {}) { try { await cdpClient.attach(tabId); @@ -19294,7 +19355,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d cdpClient.sendCommand(tabId, 'Page.captureScreenshot', { format: 'jpeg', quality: 60, - clip: { x: 0, y: 0, width: cssW, height: cssH, scale: 1 }, + clip: this._viewportCaptureClip(probe, cssW, cssH, 1), }) ); if (!shot?.data) return null; @@ -19339,7 +19400,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d format: 'jpeg', quality: Math.round(budget.initialJpegQuality * 100), fromSurface: true, - clip: { x: 0, y: 0, width: cssW, height: cssH, scale }, + clip: this._viewportCaptureClip(probe, cssW, cssH, scale), }) ); if (!shot?.data) return null; @@ -19775,7 +19836,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d cdpClient.sendCommand(tabId, 'Page.captureScreenshot', { format: 'png', fromSurface: true, - clip: { x: 0, y: 0, width: cssW, height: cssH, scale: 1 }, + clip: this._viewportCaptureClip(probe, cssW, cssH, 1), }) ); if (!shot?.data) return null; @@ -20520,6 +20581,228 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d }; } + // ───────────── Vision mode platform layer (Chrome) ───────────── + // vision-runtime.js owns the logic; these methods are the CDP specifics. + // Every Input.* command passes cdpClient's page-agent fence, so the page + // monitor attributes these events to the agent, not to a person. + + /** CSS viewport, scroll offset, DPR and URL of the tab. */ + async _visionPlatformProbe(tabId) { + await cdpClient.attach(tabId); + const [metrics, page] = await Promise.all([ + cdpClient.sendCommand(tabId, 'Page.getLayoutMetrics').catch(() => null), + cdpClient.evaluate(tabId, '({ w: innerWidth, h: innerHeight, sx: scrollX, sy: scrollY, dpr: devicePixelRatio, url: location.href })') + .catch(() => null), + ]); + const value = page?.result?.value || {}; + const visual = metrics?.cssVisualViewport || null; + let url = String(value.url || ''); + if (!url) { + try { url = (await chrome.tabs.get(tabId))?.url || ''; } catch { url = ''; } + } + // The visual viewport excludes classic scrollbars, so points never land + // on one, and its page offset is where CDP clips start (clip coordinates + // are document coordinates: a clip at 0,0 on a scrolled page is blank). + return { + cssWidth: Number(visual?.clientWidth) || Number(value.w) || 0, + cssHeight: Number(visual?.clientHeight) || Number(value.h) || 0, + scrollX: Number.isFinite(Number(visual?.pageX)) ? Number(visual.pageX) : (Number(value.sx) || 0), + scrollY: Number.isFinite(Number(visual?.pageY)) ? Number(visual.pageY) : (Number(value.sy) || 0), + devicePixelRatio: Number(value.dpr) || 1, + url, + }; + } + + /** + * Capture the viewport (or `cssRegion` of it) close to outWidth x + * outHeight. The compositor renders clip x scale x device pixel ratio, so + * the requested scale divides the DPR out; whatever size actually comes + * back is resampled to the plan by the runtime. + */ + async _visionPlatformCapture(tabId, { probe, cssRegion = null, outWidth, outHeight }) { + await cdpClient.attach(tabId); + await cdpClient.sendCommand(tabId, 'Page.enable').catch(() => {}); + await this._preparePageForCapture(tabId); + const region = cssRegion || { x: 0, y: 0, width: probe.cssWidth, height: probe.cssHeight }; + const dpr = Math.max(0.25, Number(probe?.devicePixelRatio) || 1); + const scale = Math.max(0.05, Math.min(4, Number(outWidth) / (Math.max(1, region.width) * dpr))); + const shot = await this._withIndicatorsHidden(tabId, () => cdpClient.sendCommand(tabId, 'Page.captureScreenshot', { + format: 'jpeg', + quality: 90, + fromSurface: true, + clip: { + x: (Number(probe?.scrollX) || 0) + region.x, + y: (Number(probe?.scrollY) || 0) + region.y, + width: Math.max(1, region.width), + height: Math.max(1, region.height), + scale, + }, + })); + return shot?.data ? `data:image/jpeg;base64,${shot.data}` : null; + } + + async _visionPlatformWheel(tabId, { x, y, deltaX = 0, deltaY = 0 }) { + await cdpClient.attach(tabId); + await cdpClient.sendCommand(tabId, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none', buttons: 0 }); + // Wheel notches of ~100 CSS px, like a mouse; smooth-scroll handlers and + // scroll-snapping lists behave as they do for a person. + const notches = Math.max(1, Math.min(30, Math.round(Math.max(Math.abs(deltaX), Math.abs(deltaY)) / 100))); + for (let i = 0; i < notches; i++) { + await cdpClient.sendCommand(tabId, 'Input.dispatchMouseEvent', { + type: 'mouseWheel', x, y, deltaX: deltaX / notches, deltaY: deltaY / notches, button: 'none', buttons: 0, + }); + await new Promise(resolve => setTimeout(resolve, 16)); + } + return { success: true, dispatched: true, method: 'cdp-wheel' }; + } + + async _visionPlatformHover(tabId, { x, y }) { + await cdpClient.attach(tabId); + // Approach from one pixel away so enter/over handlers fire even when the + // pointer already rests at the point. + await cdpClient.sendCommand(tabId, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x: Math.max(0, x - 1), y: Math.max(0, y - 1), button: 'none', buttons: 0 }); + await cdpClient.sendCommand(tabId, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none', buttons: 0 }); + const hit = await this._visionHitTest(tabId, x, y); + return { success: true, dispatched: true, method: 'cdp-hover', ...(hit?.target ? { target: hit.target } : {}) }; + } + + async _visionPlatformDrag(tabId, { from, to, steps = 12 }) { + await cdpClient.attach(tabId); + await cdpClient.sendCommand(tabId, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x: from.x, y: from.y, button: 'none', buttons: 0 }); + let pressed = false; + try { + await sendTrustedCdpInput(options => cdpClient.sendCommand(tabId, 'Input.dispatchMouseEvent', { + type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1, + }, '', options), { onSent: () => { pressed = true; } }); + for (let i = 1; i <= steps; i++) { + const t = i / steps; + await cdpClient.sendCommand(tabId, 'Input.dispatchMouseEvent', { + type: 'mouseMoved', x: from.x + (to.x - from.x) * t, y: from.y + (to.y - from.y) * t, button: 'left', buttons: 1, + }); + await new Promise(resolve => setTimeout(resolve, 16)); + } + } finally { + if (pressed) { + await cdpClient.sendCommand(tabId, 'Input.dispatchMouseEvent', { + type: 'mouseReleased', x: to.x, y: to.y, button: 'left', buttons: 0, clickCount: 1, + }).catch(() => {}); + } + } + return { success: true, dispatched: pressed, method: 'cdp-drag' }; + } + + /** Tag and role under a CSS point (no accessible name: it can identify the signed-in user). */ + async _visionHitTest(tabId, x, y) { + try { + const response = await cdpClient.evaluate(tabId, `(() => { + let el = document.elementFromPoint(${Number(x)}, ${Number(y)}); + for (let depth = 0; el?.shadowRoot && depth < 8; depth++) { + const inner = el.shadowRoot.elementFromPoint(${Number(x)}, ${Number(y)}); + if (!inner || inner === el) break; + el = inner; + } + if (!el) return null; + const select = el.closest ? el.closest('select') : null; + if (select) { + select.focus(); + return { isSelect: true, current: select.options[select.selectedIndex]?.text?.trim() || '', + options: Array.from(select.options).slice(0, 60).map(option => option.text.trim()), target: { tag: 'select' } }; + } + const role = el.getAttribute && el.getAttribute('role'); + return { isSelect: false, target: { tag: String(el.tagName || '').toLowerCase(), ...(role ? { role: role.slice(0, 32) } : {}) } }; + })()`); + return response?.result?.value || null; + } catch { + return null; + } + } + + /** + * Dispatch a vision click: trusted pointer events at exactly the CSS point + * (button and click count as asked), keeping the coordinate path's + * dispatch-time protections: native opens an OS popup no screenshot can show; it is + // focused instead so type_text picks the option. + const hit = await this._visionHitTest(tabId, x, y); + throwIfAborted(); + if (hit?.isSelect && button === 'left') { + return { + success: false, dispatched: false, noDispatch: true, nativeSelect: true, tag: 'SELECT', text: hit.current, + options: hit.options, + error: `That point is a native dropdown (current: "${hit.current}"). It is focused now: choose an option with type_text({text: "