diff --git a/.github/workflows/lmstudio-plugin.yml b/.github/workflows/lmstudio-plugin.yml new file mode 100644 index 0000000000..70c22d9f31 --- /dev/null +++ b/.github/workflows/lmstudio-plugin.yml @@ -0,0 +1,42 @@ +name: LM Studio Plugin + +on: + pull_request: + paths: + - ".github/workflows/lmstudio-plugin.yml" + - "lmstudio-plugin/**" + push: + branches: + - main + paths: + - ".github/workflows/lmstudio-plugin.yml" + - "lmstudio-plugin/**" + +permissions: + contents: read + +concurrency: + group: lmstudio-plugin-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + defaults: + run: + working-directory: lmstudio-plugin + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + cache-dependency-path: lmstudio-plugin/package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Build and test + run: npm test 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/CHANGELOG.md b/CHANGELOG.md index 96d9c30830..957be5873d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,33 @@ This changelog was generated from the repository Git history and release tags. V ## [Unreleased] +### Added +- Settings → General → **Agent activity effect** chooses how a tab looks while WebBrain works on it: **Neural circuit**, the new default, where circuit traces grow in from the edges and signals run along them toward each element WebBrain acts on; **Aurora**, a soft purple band that drifts around the frame; **Scan**, corner brackets with a slow scanning beam; **Gears**, meshing cog trains turning in the corners; or **Classic glow**, the pulsing border used until now. Every style lets clicks, typing and scrolling through to the page, is hidden while WebBrain takes a screenshot, and holds still when your system asks to reduce motion. A new choice applies to a running task at once and is included in settings export and import. Chrome and Firefox. + +### Changed +- The agent cursor no longer disappears three seconds after an action. It now keeps one, smaller size: it glides from target to target, presses once with a ripple when WebBrain clicks, and between actions stays where it last acted, slowly fading in and out until the task ends. The ring around the target still fades after a moment. Chrome and Firefox. + +## [44.0.0] - 2026-10-27 + +### Added +- Vision mode: Act runs whose model takes images now see the page as screenshots and act with the mouse and keyboard at coordinates, in Chrome and Firefox. It is the default for image-capable models; Settings → Advanced → **Vision mode** offers **Auto** and **Off**, and a saved On or true reads as Auto. A run starts from a full frame; after each action WebBrain sends only what changed on screen, a new frame when most of the screen changed, or the note "no visible change". The new tools are `click_at`, `scroll_at`, `hover_at`, `drag_at`, `zoom`, `take_screenshot` and `wait`, and `type_text` types into the focused field. Ask, Dev, text-only models, whole-conversation reads, the WhatsApp Web and Telegram contact checks, and site workflows that need the element inventory keep the accessibility tree. See `docs/vision-mode.md`. +- Vision screenshots are sized for the provider that receives them. The **Vision screenshot size** setting offers Economy, Balanced and Sharp; each provider gets the largest image it accepts without shrinking it, and the per-provider grid keeps patches exact. Retina displays and browser zoom are divided out of the capture so a point the model reads maps back to the same CSS pixel. Models that point in 0..1000 coordinates, such as Gemini, Qwen3-VL, GLM-4.xV and InternVL, are handled as such, and the image format is WebP except where the provider or local server needs JPEG. +- Vision mode in Firefox reproduces what a person's pointer does: a click places the caret or selects a word, a double or triple click selects as it does in the browser, a wheel goes to the nearest scroller that can move, a drag moves native sliders and runs HTML5 drag and drop, a CSS-only hover menu opens, pointer capture is kept, and same-origin frames receive the point in their own coordinates. With **Firefox trusted automation** on and the companion reporting point input, a left click and a hover go out as trusted input instead. Chrome sends trusted CDP pointer events at the point. A click that would open a native file chooser is refused in both builds. + +### Changed +- A vision run keeps only the current screen, its patches and its zooms in the model's request; older images become short placeholders. A local change that is too small to send accumulates until it is sent rather than being lost. Navigation, a viewport resize or a change of device pixel ratio starts a new full frame, and points read from an earlier screen or from an area that has since changed are refused before any input goes out. +- Vision steps are quicker. The settle wait ends on micro changes such as a caret or clock instead of waiting its full time, page feedback no longer reads the accessibility tree, an unchanged screen is not sent again before a decision, and a zoom taken after an action of its batch stays usable. The installed Chrome fixture's four steps went from about 15 seconds to about 7.5 seconds. +- A vision decision survives automatic page churn while the pixels around its point still match what the model saw, and a person's input, a navigation or another document still cancels it. Typing and key presses right after a click are checked by whether the clicked point took focus, so a page reacting to that focus no longer blocks them. + ### Fixed +- Every hard guard works on coordinate clicks. A click or drag can no longer delete, commit a corrected change or press a disabled control without the same binding, confirmation and re-check at dispatch that a ref or selector click gets. The submit probe reads points inside open shadow roots and treats plain content as a non-submit target; a repeated click on a control, a drag that would click a control or cross a frame it cannot inspect, and a wheel over a focused number field are refused. Deletions, whole-thread reads and protected messaging pages keep the tree path where their checks need it. +- Loop detection now judges a vision action by whether the screen changed, so repeating a click after a visible change is progress and repeating it on an unchanged screen still stops the run. A drag opens completion verification, `take_screenshot` verifies nothing until the screen after its batch is actually captured, and a pending CAPTCHA gate gets WebBrain's own root tree read before the next action. A refused point stops the rest of its batch, and vision tool, capture and encoding failures become tool results or notes instead of ending the run. +- Chrome screenshots under browser zoom and on retina displays now cover the whole viewport and keep points in the right place. The legacy auto-screenshot clip now starts at the scroll offset, so scrolled pages are no longer captured blank, and it divides out the device pixel ratio instead of capturing at twice the intended scale. - Firefox: **download_social_media** saves media instead of stopping with "An unexpected error occurred", and after WebBrain is updated or reloaded, actions in tabs that were already open no longer fail because WebBrain could not load its page scripts into them again. Firefox looks up a script the background page injects from the background page's own folder, not from the extension's root, so every such injection named a file that does not exist. They now name the file from the root. +### Tests +- Vision mode has unit and run-loop coverage in both builds for sizing, diffs, sessions, tool surfaces, prompts, stale points, page churn, viewport resizes, guard behaviour and tree fallback. Chromium tests cover the real capture and dispatch path at device pixel ratios 1, 2 and 3 and at browser zoom, including a scrolled page and a `target=_blank` link. Installed-extension fixtures cover a form submitted at a vision point, a named and a vague deletion, and a canvas counter that needs ten clicks. Firefox input is tested in a real headless Firefox, including CSS hover, native range inputs, pointer capture, scaled frames and trusted input through the companion. + ## [42.4.0] - 2026-10-24 ### Added 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 ccbd633520..4c7e003cbe 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/adding-a-tool.md b/docs/adding-a-tool.md index 0a8d15c619..0afb8c4c6b 100644 --- a/docs/adding-a-tool.md +++ b/docs/adding-a-tool.md @@ -418,10 +418,10 @@ if (name === 'chrome_only_tool') { Every new tool should be classified for security: 1. **Can it read or exfiltrate data from the page?** → Add credential-field sensitivity checks if it reads input values. -2. **Can it perform destructive mutations?** → Classify it under the normal permission gate. The persistent **Always allow API mutations** setting (on by default) or the conversation's `/allow-api` override waives prompts only for write-method network egress, not other mutating capabilities. +2. **Can it perform destructive mutations?** → Classify it under the normal permission gate. The conversation's `/allow-api` override waives prompts only for write-method network egress, not other mutating capabilities. The persistent **Always allow API mutations** setting (on by default) authorizes that egress but, on a new install, leaves each host's prompt in place. 3. **Can it be prompt-injected?** → If the tool accepts user-provided strings that end up in tool-call arguments, document the injection surface in the tool description. 4. **Which mode/tier should expose it?** → Ask-only semantic read goes in `ASK_ONLY_TOOLS`; common action tools should join the smallest normal tier that can reliably use them; developer-only source/style/debug tools go in Dev-only; Full fallbacks that Mid should get only during debugging go in Dev-extended. -5. **Can it shortcut repeated UI actions to network calls?** → Keep the UI-first policy intact. The background API observer may surface exact XHR/fetch URL+method hints during click loops, plus an opaque `replayRequestId` when same-origin body/header replay material is available. Write-method `fetch_url` / `research_url` calls are authorized by the persistent **Always allow API mutations** setting (on by default) or the conversation's `/allow-api` override. An unreadable persistent setting grants no authorization, and hidden form tokens must stay behind the replay id rather than being exposed to the model. GET requests and non-network capabilities still use the normal permission gate. +5. **Can it shortcut repeated UI actions to network calls?** → Keep the UI-first policy intact. The background API observer may surface exact XHR/fetch URL+method hints during click loops, plus an opaque `replayRequestId` when same-origin body/header replay material is available. Write-method `fetch_url` / `research_url` calls are authorized by the persistent **Always allow API mutations** setting (on by default; per-host prompt on new installs) or the conversation's `/allow-api` override. An unreadable persistent setting grants no authorization, and hidden form tokens must stay behind the replay id rather than being exposed to the model. GET requests and non-network capabilities still use the normal permission gate. See `docs/security-model.md` for the full threat model. diff --git a/docs/agent-tools.md b/docs/agent-tools.md index d362331cfd..305569a27e 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, Auto 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/architecture.md b/docs/architecture.md index 8f4a3b1622..e549b2dec7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,7 +57,7 @@ This doc covers the shared architecture and calls out where the builds diverge. │ │ │ accessibility-tree.js — AX tree builder + ref_ids │ │ content.js — DOM reader, clicker, typer │ -│ agent-visual-indicator.js — pulsing border + Stop │ +│ agent-visual-indicator.js — edge effect + Stop │ └─────────────────────────────────────────────────────┘ ``` @@ -324,7 +324,8 @@ background.js handleMessage('chat_start') ``` _enrichUserMessageWithCurrentPage(tabId, messages, userMessage) - 1. Collect URL + title via chrome.tabs.get(tabId) + 1. Collect URL + title via chrome.tabs.get(tabId); quote them in the + [Current page context] note inside an box 2. If persistent API permission or this tab's /allow-api is active → inject [API ALLOWED] preamble 3. If site adapters enabled → getActiveAdapter(url) → inject adapter notes 4. If provider supports vision (or dedicated vision model configured): @@ -1498,7 +1499,8 @@ request bodies and a small allowlist of replay-safe headers behind an opaque `replayRequestId`; hidden form tokens are reused internally by `fetch_url` only for the same tab and origin, not printed into model context. Write methods are authorized by the persistent **Always allow API mutations** setting (on by -default) or the conversation's `/allow-api` override. An unreadable persistent +default; on a new install each host still gets the network permission prompt) +or the conversation's `/allow-api` override. An unreadable persistent setting grants no authorization. GET requests and non-network capabilities still use the normal permission gate. @@ -1600,7 +1602,7 @@ Key points: - Ask is read-only; Act and Dev are action modes. Dev adds source/style/page-debugging tools and is blocked for Compact-tier providers. - Plan before Act can require human approval before any action-mode tool call - An unanswered `clarify` question follows Settings → Budgets → "When a question times out": finish the task (default) or play it safe. Questions about deletion, money, credentials, the recipient, or an unrequested publication always time out to the safe answer (see `docs/security-model.md`). -- The persistent **Always allow API mutations** setting (on by default) or the conversation's `/allow-api` override waives permission prompts for write-method `fetch_url` / `research_url` calls +- The conversation's `/allow-api` override waives permission prompts for write-method `fetch_url` / `research_url` calls. The persistent **Always allow API mutations** setting (on by default) allows those calls; it also waives their prompts only on installs from before new installs started asking per host (`apiMutationSitePrompt`) - Tool results capped at 8 KB to limit prompt-injection surface - `strictSecretMode` instructs the model not to quote credentials in summaries, redacts known credential values (including short numeric PIN/CVV values) out of everything a cloud run publishes, and fails closed to scalar redaction if its bounded secret registry fills - Trace data is local-only (IndexedDB), never transmitted diff --git a/docs/cloud-bridge-browser-approval.md b/docs/cloud-bridge-browser-approval.md index 4724372809..6b27cd8464 100644 --- a/docs/cloud-bridge-browser-approval.md +++ b/docs/cloud-bridge-browser-approval.md @@ -2,10 +2,12 @@ A backend can require explicit approval of a WebBrain installation before it is allowed to run `cloud_*` commands. The feature is opt-in: **without a Cloud Bridge token the bridge behaves exactly as before** (local MCP server, no approval step). +With a token, the backend and the browser first authenticate each other with a challenge-response over the token. The token itself never crosses the socket, so a program that takes the loopback port before the real backend learns nothing it can reuse and cannot get the browser to run commands. + ## Architecture ``` -background (cloud-runs.js) --cloud-bridge-start {url, token, browserId, installationId, extensionVersion}--> offscreen (cloud-bridge.js) <== WebSocket ==> backend +background (cloud-runs.js) --cloud-bridge-start {url, token, browserId, installationId, extensionVersion, legacyBearerAuth}--> offscreen (cloud-bridge.js) <== WebSocket ==> backend ``` ```mermaid @@ -24,7 +26,7 @@ flowchart LR BG --> AG --> TAB end subgraph Backend["Backend (today: local ws:// only)"] - SRV["WebSocket server
checks token
approves / rejects"] + SRV["WebSocket server
proves the token, checks the browser's proof
approves / rejects"] end OFF <== "WebSocket opened by the extension" ==> SRV ``` @@ -34,7 +36,7 @@ The French guide ([cloud-bridge-test-guide.fr.md](cloud-bridge-test-guide.fr.md) **Chrome vs Firefox.** Chrome (MV3) hosts the socket in an offscreen document (`src/chrome/src/offscreen/cloud-bridge.js`). Firefox (MV2) has no offscreen documents, so `src/firefox/src/cloud-bridge.js` is a module that runs in the persistent background page and hands commands directly to `handleMessage`. The protocol, storage keys, approval rules and Settings tab are identical; `src/firefox/src/cloud-runs.js` mirrors the Chrome controller and receives the bridge as an injected dependency. - `cloud-runs.js` reads the persistent identity from `chrome.storage.local` and passes it to the offscreen page with the existing `cloud-bridge-start` message (the offscreen page has no storage access). -- `offscreen/cloud-bridge.js` sends the enriched `hello` and tracks the approval state **per socket**. +- `offscreen/cloud-bridge.js` sends the enriched `hello`, runs the challenge-response and tracks the authentication and approval state **per socket**. - Command routing (`cloud_run`, `cloud_status`, `cloud_respond`, `cloud_abort`, workflows, scheduled jobs) and payloads are unchanged. ## Local configuration @@ -48,28 +50,27 @@ Keys in `chrome.storage.local` (the existing mechanism; the URL and enable toggl | `webbrainCloudBridgeToken` | Cloud Bridge credential. Distinct from provider API keys. Setting it turns approval on. | | `webbrainCloudBridgeBrowserId` | Backend-visible name; defaults to the installation id | | `webbrainCloudBridgeInstallationId` | Generated once (`crypto.randomUUID()`) | +| `webbrainCloudBridgeLegacyBearerAuth` | Deprecated. Only the boolean `true` turns it on; see [Legacy bearer hello](#legacy-bearer-hello-deprecated). Not shown in Settings. | -All of these are editable in **Settings → Bridge**: enable toggle, backend URL, token, browser name (`browserId`), the read-only installation ID, and a **Save & test connection** button. The test saves the form, (re)starts the bridge and reports one of: backend unreachable, connected (no approval needed), waiting for approval, approved, or rejected (with the reason). +All of these except the legacy flag are editable in **Settings → Bridge**: enable toggle, backend URL, token, browser name (`browserId`), the read-only installation ID, and a **Save & test connection** button. The test saves the form, (re)starts the bridge and reports one of: backend unreachable, connected (no approval needed), waiting for approval, approved, or rejected (with the reason). To try it end to end: run `node examples/cloud-bridge-approval-server.mjs --token dev-token`, enter `dev-token` in the tab, press **Save & test connection** (status: waiting for approval), then type `approve` in the server terminal (status: approved) or `reject`. The older Display → MCP block controls the same enable/URL keys; it is not refreshed live when the new tab changes them (reload Settings). -Changing the token or browserId reconnects the socket. +Changing the token, browserId or legacy flag reconnects the socket. ## Messages -Extension → backend, on every socket open: +### 1. Extension → backend: `hello` (every socket open) ```json { "type": "hello", "client": "webbrain-extension", "protocolVersion": 2, - "capabilities": ["saved_workflows_v1", "run_modes_v1", "scheduled_jobs_v1", "run_provider_v1", "private_results_v1", "bot_memory_v1"], - "auth": { "type": "bearer", "token": "dev-token" }, - "browserId": "my-laptop", - "installationId": "0b0c6a3e-…", + "capabilities": ["saved_workflows_v1", "run_modes_v1", "scheduled_jobs_v1", "run_provider_v1", "private_results_v1", "bot_memory_v1", "run_handoff_v1"], + "auth": { "type": "challenge", "method": "hmac-sha256-v1", "nonce": "<64 lowercase hex chars>" }, "browser": { "name": "Chrome", "version": "126.0.0.0" }, "extensionVersion": "40.2.1", "platform": "Linux x86_64", @@ -77,9 +78,33 @@ Extension → backend, on every socket open: } ``` -`auth`, `browserId` and `installationId` are only sent when a token is configured. The token is never included in `status`. +`auth` is only sent when a token is configured. `nonce` is 32 fresh random bytes per socket. The hello carries neither the token nor `browserId` / `installationId` (they are also removed from its `status`); those come in step 3, after the backend has proved itself. Without a token the hello is unchanged from earlier versions (no `auth`; `status` keeps both IDs). -Backend → extension: +### 2. Backend → extension: `auth_challenge` + +```json +{ "type": "auth_challenge", "method": "hmac-sha256-v1", "nonce": "<64 lowercase hex chars>", "proof": "<64 lowercase hex chars>" } +``` + +`nonce` is the backend's own 32 random bytes. `proof` is + +``` +hex(HMAC-SHA256(key = UTF-8(token), message = UTF-8(JSON.stringify(["webbrain-bridge-auth-v1", "controller", helloNonce, backendNonce])))) +``` + +`JSON.stringify` of a string array has no whitespace, for example `["webbrain-bridge-auth-v1","controller","ab…","cd…"]`. The extension answers only the first `auth_challenge` of a socket. If the method, either nonce or the proof is wrong it sends nothing back, closes the socket, reports `Bridge controller failed authentication` and reconnects with the usual backoff (the real backend may get its port back). It is not a rejection. + +### 3. Extension → backend: `auth_response` + +```json +{ "type": "auth_response", "method": "hmac-sha256-v1", "proof": "<64 lowercase hex chars>", "browserId": "my-laptop", "installationId": "0b0c6a3e-…" } +``` + +`proof` is the same HMAC over `["webbrain-bridge-auth-v1", "extension", helloNonce, backendNonce, browserId, installationId]`. The backend recomputes it with its token (compare in constant time) and rejects the browser if it does not match. The role label stops either side from replaying the other's proof, and the nonces stop a recorded proof from working on another socket. + +Test vector: token `secret-token`, hello nonce `00` × 32, backend nonce `11` × 32, `browserId` `browser-1`, `installationId` `install-1` give the backend proof `04734662625940a90c0e3aeed5a653b6fb2e24779baa71b6dccab394601937d4` and the extension proof `5670c5e30c40e94ed27cd0e99148310d44a3efe54d668b2f9fd21efe9a8e913e`. + +### 4. Backend → extension: approval ```json { "type": "connection_pending", "browserId": "my-laptop" } @@ -87,6 +112,8 @@ Backend → extension: { "type": "connection_rejected", "browserId": "my-laptop", "reason": "Rejected by user" } ``` +- With a token, `connection_pending` and `connection_approved` are ignored until the backend's `auth_challenge` has been verified. Send them after a valid `auth_response`. +- `connection_rejected` is honoured at any point, since it only takes rights away. - `browserId` is optional; if present and different from the local one, the message is ignored. - `connection_rejected` closes the socket and **stops auto-reconnect** until the settings change or the bridge is restarted. @@ -111,7 +138,28 @@ contract, credential handling, and image-upgrade checks. ## Reconnection -Approval belongs to one WebSocket. Every new socket (reconnect, URL/identity change) starts `pending`, resends `hello`, and must be approved again. +Authentication and approval belong to one WebSocket. Every new socket (reconnect, URL/identity change) starts `pending`, resends `hello` with a new nonce, and must pass the challenge and be approved again. With a token, the reconnect backoff is only reset once the backend has proved itself, so a program that keeps failing the challenge is retried at most every 30 seconds. + +## Legacy bearer hello (deprecated) + +Before the challenge-response, a token-configured hello carried `"auth": { "type": "bearer", "token": "…" }` plus `browserId` and `installationId`, and the extension accepted `connection_approved` from whoever answered. A backend that has not implemented steps 2 and 3 yet sees a hello without a token and should refuse it. + +To keep such a backend working during the transition, set the flag by hand in the extension's console (service worker console on Chrome, background page console on Firefox): + +```js +chrome.storage.local.set({ webbrainCloudBridgeLegacyBearerAuth: true }) // Firefox: browser.storage.local +``` + +With the flag the extension sends the old bearer hello and accepts unauthenticated approval messages, exactly as before. It hands the token to whatever listens on the configured port, so use it only until the backend implements the challenge, then remove it with `chrome.storage.local.remove('webbrainCloudBridgeLegacyBearerAuth')`. The flag will be removed in a later release. + +## Implementing a backend + +1. On `hello` with `auth.type === "challenge"` and `auth.method === "hmac-sha256-v1"`, check that `auth.nonce` is 64 lowercase hex characters, generate 32 random bytes of your own, and send `auth_challenge` with your proof. Answer each socket's hello once. +2. On `auth_response`, recompute the extension's proof from both nonces and the `browserId` / `installationId` in the message, compare in constant time, and reply `connection_rejected` (and close) on a mismatch. +3. Only then treat the socket as the browser: send `connection_pending` / `connection_approved`, and route `cloud_*` commands to it. +4. Optionally, during a transition, also accept the deprecated bearer hello (constant-time compare of `auth.token`) for extension builds that predate the challenge. + +The example server below is a complete reference. ## Local test server @@ -120,9 +168,10 @@ Approval belongs to one WebSocket. Every new socket (reconnect, URL/identity cha ```bash node examples/cloud-bridge-approval-server.mjs --token dev-token # manual approval node examples/cloud-bridge-approval-server.mjs --token dev-token --auto-approve +node examples/cloud-bridge-approval-server.mjs --token dev-token --legacy-bearer # also accept the deprecated bearer hello ``` -It replies `connection_pending` after a valid `hello` (or `connection_rejected` for a bad token). On stdin, type `approve`, `reject`, or `send {"id":"1","action":"cloud_status","payload":{"runId":"run_x"}}`. +It runs the challenge-response and replies `connection_pending` after a valid `auth_response` (or `connection_rejected` for a bad proof or an unexpected hello). If its token differs from the browser's, the browser drops it first (`Bridge controller failed authentication`). On stdin, type `approve`, `reject`, or `send {"id":"1","action":"cloud_status","payload":{"runId":"run_x"}}`. Automated tests (unit with a fake WebSocket + one end-to-end run against that server): @@ -133,7 +182,8 @@ npm run test:cloud-bridge-approval ## Limits & security - The bridge URL is still restricted to `ws://` on localhost/127.0.0.1/::1. A remote backend needs a local relay, or a deliberate relaxation (needs TLS and a decision upstream). -- The token travels in the `hello` over that local socket; it is stored in plain `chrome.storage.local` like other settings. -- The backend is responsible for validating the token and for the user-facing approval UI; the extension only enforces "no approval, no commands". +- The token never travels over the socket (unless the deprecated legacy flag is set); it is stored in plain `chrome.storage.local` like other settings. Use a long random token: any program that can connect to the real backend can collect its proofs and try to guess a weak token offline. +- The backend is responsible for verifying the browser's proof and for the user-facing approval UI; the extension enforces "no proof from the backend, no identity and no approval" and "no approval, no commands". +- **Without a token there is no authentication.** Any program that listens on the configured port first, such as another user's process on a shared machine, can send `cloud_*` commands to the browser and read their results. This mode exists for the local MCP server, the LM Studio plugin and WebBrain Cloud, which do not use a token today; it is only active after the user (or the Cloud image) turns the bridge on. - The extension still only accepts the `cloud_*` run actions; no cookies, tabs, history, provider keys or configuration are exposed. - Approval is not persisted and not revocable from the extension side other than by disabling the bridge or rotating the token. diff --git a/docs/cloud-bridge-test-guide.fr.md b/docs/cloud-bridge-test-guide.fr.md index e9d2b2829c..2f31537a0a 100644 --- a/docs/cloud-bridge-test-guide.fr.md +++ b/docs/cloud-bridge-test-guide.fr.md @@ -22,7 +22,7 @@ flowchart LR BG --> AG --> TAB end subgraph Backend["Backend (aujourd'hui : ws:// en local uniquement)"] - SRV["Serveur WebSocket
vérifie le token
approuve / refuse"] + SRV["Serveur WebSocket
prouve le token, vérifie la preuve du navigateur
approuve / refuse"] end OFF <== "WebSocket initié par l'extension" ==> SRV ``` @@ -35,11 +35,17 @@ sequenceDiagram participant B as Backend participant U as Utilisateur E->>B: connexion WebSocket - E->>B: hello {auth.token, browserId, installationId, navigateur, version, plateforme, capabilities} - alt token invalide + E->>B: hello {auth.nonce, navigateur, version, plateforme, capabilities} + B-->>E: auth_challenge {nonce serveur, preuve HMAC(token)} + alt preuve du serveur invalide + Note over E: rien n'est envoyé, socket fermée, nouvel essai avec délai croissant + else preuve du serveur valide + E->>B: auth_response {preuve HMAC(token), browserId, installationId} + end + alt preuve du navigateur invalide B-->>E: connection_rejected Note over E: socket fermée, pas de reconnexion auto - else token valide + else preuve du navigateur valide B-->>E: connection_pending B->>E: cloud_run (avant approbation) E-->>B: ok:false, connection_not_approved (403) @@ -54,7 +60,7 @@ sequenceDiagram B->>E: cloud_status {runId} E-->>B: status completed + résultat end - Note over E,B: coupure réseau → nouvelle socket → nouveau hello → repart en pending + Note over E,B: coupure réseau → nouvelle socket → nouveau hello et nouveau challenge → repart en pending ``` ## 1. Prérequis @@ -102,7 +108,7 @@ node examples/cloud-bridge-approval-server.mjs --token dev-token Vous devez voir : `Listening on ws://127.0.0.1:17374/extension`. -Options : `--port 17374` (défaut), `--auto-approve` (approuve automatiquement, pratique pour tester les commandes). +Options : `--port 17374` (défaut), `--auto-approve` (approuve automatiquement, pratique pour tester les commandes), `--legacy-bearer` (accepte aussi l'ancien `hello` qui contenait le token, voir le scénario G). Ce terminal sert à la fois de **backend** (il affiche tout ce que l'extension envoie, préfixé par `<-`) et de **console d'approbation**. @@ -118,16 +124,18 @@ Ce terminal sert à la fois de **backend** (il affiche tout ce que l'extension e Le statut passe à : *Connected — waiting for the backend to approve this browser.* -Dans le terminal du serveur, vous voyez le `hello` reçu, par exemple : +Dans le terminal du serveur, vous voyez le `hello` reçu, puis la réponse au challenge, par exemple : ```json {"type":"hello","client":"webbrain-extension","protocolVersion":2, "capabilities":["saved_workflows_v1","run_modes_v1","scheduled_jobs_v1"], - "auth":{"type":"bearer","token":"dev-token"}, - "browserId":"mon-chrome","installationId":"…", + "auth":{"type":"challenge","method":"hmac-sha256-v1","nonce":"…"}, "browser":{"name":"Chrome","version":"…"},"extensionVersion":"38.0.13","platform":"Linux", …} +{"type":"auth_response","method":"hmac-sha256-v1","proof":"…","browserId":"mon-chrome","installationId":"…"} ``` +Le token n'apparaît jamais : le serveur prouve d'abord qu'il le connaît (`auth_challenge`), puis l'extension envoie sa propre preuve avec `browserId` et `installationId`. + ## 5. Scénarios à tester ### A. Commande avant approbation (doit être refusée) @@ -167,17 +175,21 @@ Dans le terminal : `reject`. Le statut devient *Rejected by the backend: …*, l ### D. Reconnexion 1. Arrêter le serveur (Ctrl+C) puis le relancer : l'extension se reconnecte automatiquement (délai croissant, jusqu'à 30 s). -2. Elle renvoie un `hello`, et la connexion est de nouveau **en attente** : toute commande est refusée tant que vous n'avez pas retapé `approve`. +2. Elle renvoie un `hello` avec un nouveau nonce, refait le challenge, et la connexion est de nouveau **en attente** : toute commande est refusée tant que vous n'avez pas retapé `approve`. Note connue : juste après une reconnexion, le texte de statut de la page Settings peut rester sur « approved » alors que la connexion est repassée en attente ; les commandes sont bien refusées. Cliquer sur **Save & test connection** pour resynchroniser l'affichage. ### E. Mauvais token -Mettre un autre token dans Settings puis **Save & test connection** : le serveur répond `connection_rejected` (« Invalid token »). +Mettre un autre token dans Settings puis **Save & test connection** : la preuve du serveur ne correspond plus, l'extension ferme la socket sans rien envoyer d'autre et affiche *Connection error: Bridge controller failed authentication*. Elle réessaie ensuite avec un délai croissant (jusqu'à 30 s), sans jamais passer en *approved*. ### F. Mode historique (sans token) -Vider le champ token et sauvegarder : plus aucune approbation n'est exigée, le comportement est celui d'avant la feature (serveur MCP local inchangé). Le serveur de test ne l'acceptera pas (il exige un token) ; ce mode se teste avec le serveur MCP du dépôt (`mcp-server/`). +Vider le champ token et sauvegarder : plus aucune approbation n'est exigée, le comportement est celui d'avant la feature (serveur MCP local inchangé). Le serveur de test ne l'acceptera pas (il exige un token) ; ce mode se teste avec le serveur MCP du dépôt (`mcp-server/`). Attention : sans token, n'importe quel programme qui écoute le premier sur le port configuré peut piloter le navigateur. + +### G. Ancien `hello` avec token (déprécié) + +Pour un backend qui n'implémente pas encore le challenge : lancer le serveur avec `--legacy-bearer`, puis dans la console du service worker `chrome.storage.local.set({webbrainCloudBridgeLegacyBearerAuth: true})`. Le `hello` contient alors de nouveau `"auth":{"type":"bearer","token":"dev-token"}`. Sans ce drapeau, l'extension n'envoie jamais le token. Le retirer ensuite : `chrome.storage.local.remove('webbrainCloudBridgeLegacyBearerAuth')`. ## 6. Inspecter / déboguer @@ -199,19 +211,21 @@ Problèmes fréquents : | *Backend unreachable* | Le serveur n'est pas lancé, mauvais port, ou URL autre que `ws://127.0.0.1/localhost` | | Rien ne change après modification du code | Extension non rechargée (↻ sur `chrome://extensions`) | | Reste « Rejected » | Normal : pas de reconnexion auto après un refus, cliquer sur **Save & test connection** | +| *Connection error: Bridge controller failed authentication* | Le token du serveur diffère de celui de Settings, ou un autre programme occupe le port | +| *Rejected by the backend: Invalid token* avec un ancien backend | Le backend attend encore le token dans le `hello` : l'adapter au challenge, ou scénario G | | Port 17374 déjà utilisé | Un serveur MCP tourne déjà : l'arrêter ou utiliser `--port` (et changer l'URL dans Settings) | ## 7. Tests automatisés ```bash -npm run test:cloud-bridge-approval # 18 tests (Chrome + Firefox) : hello, pending, approved, rejected, commande avant/après, reconnexion, minuteur annulé après refus, mode sans token, identité unique, e2e vs serveur d'exemple +npm run test:cloud-bridge-approval # Chrome + Firefox : hello, challenge, faux serveur sur le port, mauvais token, pending, approved, rejected, commande avant/après, reconnexion, minuteur annulé après refus, mode sans token, drapeau historique, identité unique, e2e vs serveur d'exemple node test/run.js # suite complète existante (≈ 2400 tests) ``` ## 8. Bonnes pratiques de sécurité pour vos essais - Utilisez un token de test (`dev-token`), jamais une vraie clé API de provider : le token du Cloud Bridge est distinct. -- Le token est stocké en clair dans `chrome.storage.local` et envoyé dans le `hello` (en local uniquement). +- Le token est stocké en clair dans `chrome.storage.local` mais n'est jamais envoyé sur la socket (sauf avec le drapeau historique du scénario G). - Le serveur d'exemple est un outil de test local, pas un backend de production. ## 9. Test réel : lancer une vraie tâche (`cloud_run`) @@ -232,6 +246,6 @@ status run_xxxxx # état d'un run (l'id est dans la réponse de cloud Votre backend doit : 1. **Écouter en WebSocket** sur une URL `ws://127.0.0.1` / `localhost` / `::1` (l'extension se connecte *vers* lui). Un backend distant n'est pas accepté tel quel : utilisez un relais local ou voyez la décision « URL localhost uniquement » dans la doc technique. -2. À la réception du `hello`, vérifier `auth.token`, puis répondre `{"type":"connection_pending"}` puis, après validation côté utilisateur, `{"type":"connection_approved"}` (ou `connection_rejected`). +2. À la réception du `hello`, répondre `auth_challenge` avec son propre nonce et sa preuve HMAC, puis vérifier la preuve de l'`auth_response` (calcul exact dans la doc technique, section « Messages »). Ensuite seulement répondre `{"type":"connection_pending"}` puis, après validation côté utilisateur, `{"type":"connection_approved"}` (ou `connection_rejected`). L'extension ignore toute approbation reçue avant que le serveur ait prouvé le token. 3. Envoyer ensuite les commandes `{"id","action","payload"}` et lire les réponses `{"id","ok","result"|"error"}`. diff --git a/docs/cookie-banners.md b/docs/cookie-banners.md index ac9dc5ebb2..fbe753bd2e 100644 --- a/docs/cookie-banners.md +++ b/docs/cookie-banners.md @@ -39,6 +39,12 @@ Settings → Advanced → **Cookie banners** (storage key `cookieBanners`): - On `init`, the host replies with the compact rules for that frame, WebBrain's own rules for that URL, and a fixed config: opt out only, the heuristic in reject-only mode, hide-only rules on, banner pre-hiding for at most 2 s. +- The wrapper creates the ` +`; + +const server = createServer((req, res) => { + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.end(req.url.startsWith('/cross') ? '' : page(server.address().port)); +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const url = `http://127.0.0.1:${server.address().port}/`; +const firefox = spawn(process.env.FIREFOX_BINARY || (process.platform === 'darwin' ? '/Applications/Firefox.app/Contents/MacOS/firefox' : 'firefox'), + ['--headless', '--remote-allow-system-access', '--no-remote', '--profile', profile, '--remote-debugging-port', '0'], { stdio: ['ignore', 'pipe', 'pipe'] }); +let session; +try { + const port = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('Firefox did not start BiDi')), 30000); + let output = ''; + const onData = data => { + output += data; + const match = output.match(/WebDriver BiDi listening on ws:\/\/127\.0\.0\.1:(\d+)/); + if (match) { clearTimeout(timer); resolve(Number(match[1])); } + }; + firefox.stderr.on('data', onData); + firefox.stdout.on('data', onData); + firefox.on('error', reject); + }); + session = new BidiSession(); + await session.connect(port); + await session.send('webExtension.install', { extensionData: { type: 'path', path: fileURLToPath(new URL('../src/firefox/', import.meta.url)) } }); + // The window's first tab: some Firefox builds (Playwright's) cannot open + // a tab over BiDi. + const initial = await session.send('browsingContext.getTree', {}); + const context = initial.contexts.find(item => !String(item.url || '').startsWith('moz-extension://'))?.context; + assert.ok(context, 'Firefox has a tab to use'); + try { await session.send('browsingContext.setViewport', { context, viewport: { width: 1000, height: 700 } }); } catch { /* keep the window's size */ } + await session.send('browsingContext.navigate', { context, url, wait: 'complete' }); + const evaluate = async expression => { + const response = await session.send('script.evaluate', { target: { context }, expression, awaitPromise: true }); + if (response.type === 'exception') throw new Error(response.exceptionDetails.text); + return response.result.value; + }; + const evaluateJson = async expression => JSON.parse(await evaluate(`JSON.stringify(${expression})`)); + // The extension's install page drives the content script, as the + // background page does. + let extensionContext = null; + for (let i = 0; i < 60 && !extensionContext; i++) { + const tree = await session.send('browsingContext.getTree', {}); + extensionContext = tree.contexts.find(item => item.url?.startsWith('moz-extension://'))?.context || null; + if (!extensionContext) await delay(250); + } + assert.ok(extensionContext, 'the installed extension opens a page'); + const extensionEval = async expression => { + const response = await session.send('script.evaluate', { target: { context: extensionContext }, expression, awaitPromise: true }); + if (response.type === 'exception') throw new Error(response.exceptionDetails.text); + return response.result.value; + }; + const tabId = await extensionEval(`browser.tabs.query({}).then(tabs => tabs.find(tab => tab.url === ${JSON.stringify(url)}).id)`); + const vision = async params => JSON.parse(await extensionEval(`browser.tabs.sendMessage(${tabId}, { target: 'content', action: 'vision_input', params: ${JSON.stringify(params)} }, { frameId: 0 }).then(value => JSON.stringify(value ?? null))`)); + const take = async () => evaluateJson('window.log.splice(0)'); + const viewport = await evaluateJson('({ width: innerWidth, height: innerHeight })'); + assert.ok(viewport.width >= 920 && viewport.height >= 620, `the fixture needs a 920x620 viewport, got ${JSON.stringify(viewport)}`); + + // The content script answers once it has loaded (document_idle). + let ready = null; + for (let i = 0; i < 40 && !ready?.success; i++) { + try { ready = await vision({ type: 'hover', x: 900, y: 600 }); } catch { ready = null; } + if (!ready?.success) await delay(250); + } + check('the content script answers vision_input', ready?.success, JSON.stringify(ready)); + check('this Firefox throws for setPointerCapture(1) without the emulation', + (await evaluate(`(() => { try { document.body.setPointerCapture(1); return 'no error'; } catch (error) { return error.name; } })()`)) === 'NotFoundError'); + + // 1. CSS :hover reaches a CSS-only menu; the selector listed beside it keeps its cascade. + let result = await vision({ type: 'hover', x: 120, y: 40 }); + const hovered = await evaluateJson(`({ submenu: getComputedStyle(document.querySelector('#menu .submenu')).display, + save: getComputedStyle(document.getElementById('save')).display, + rewritten: [...document.styleSheets[0].cssRules].some(rule => (rule.selectorText || '').includes('data-webbrain-hover')) })`); + check('hover_at opens a CSS :hover menu', result?.success && hovered.submenu === 'block', JSON.stringify({ result, hovered })); + check('a selector listed beside :hover keeps its own cascade', hovered.save === 'none', JSON.stringify(hovered)); + check('the :hover selector is rewritten in place', hovered.rewritten, JSON.stringify(hovered)); + // A person's own (trusted) pointer movement ends it and restores the page's selectors. + await session.send('input.performActions', { context, actions: [{ type: 'pointer', id: 'person', parameters: { pointerType: 'mouse' }, actions: [{ type: 'pointerMove', x: 600, y: 660, origin: 'viewport' }] }] }); + let restored = null; + for (let i = 0; i < 20; i++) { + restored = await evaluateJson(`({ marked: document.querySelectorAll('[data-webbrain-hover]').length, + submenu: getComputedStyle(document.querySelector('#menu .submenu')).display, + rewritten: [...document.styleSheets[0].cssRules].some(rule => (rule.selectorText || '').includes('data-webbrain-hover')) })`); + if (!restored.marked && !restored.rewritten) break; + await delay(100); + } + check('a person moving the mouse ends the emulation and restores the selectors', + !restored.marked && !restored.rewritten && restored.submenu === 'none', JSON.stringify(restored)); + + // 2. Pointer capture: a thumb whose handlers are on itself gets every move and the release. + await take(); + result = await vision({ type: 'drag', x: 40, y: 210, toX: 540, toY: 210, steps: 5 }); + const dragLog = await take(); + const moves = dragLog.filter(entry => entry[0] === 'move'); + check('drag_at succeeds on a capturing thumb', result?.success, JSON.stringify(result)); + check('the capturing thumb gets the press', dragLog[0]?.[0] === 'down', JSON.stringify(dragLog)); + check('gotpointercapture before the moves, lostpointercapture after the release', + dragLog.findIndex(entry => entry[0] === 'got') === 1 + && dragLog.findIndex(entry => entry[0] === 'lost') > dragLog.findIndex(entry => entry[0] === 'up'), JSON.stringify(dragLog)); + check('every move reaches the thumb, far past its box, with capture held', + moves.length === 5 && moves.at(-1)[1] === 540 && moves.every(entry => entry[2] === true), JSON.stringify(dragLog)); + check('the release reaches the thumb at the end point', + JSON.stringify(dragLog.find(entry => entry[0] === 'up')) === JSON.stringify(['up', 540]), JSON.stringify(dragLog)); + check("the page's own setPointerCapture is back after the sequence", await evaluate('Element.prototype.setPointerCapture === window.nativeCapture')); + + // 3. A control that drops the implicit capture first completes its press. + result = await vision({ type: 'click', x: 760, y: 40 }); + check('a react-aria style press completes', result?.success && (await take()).some(entry => entry[0] === 'pressed'), JSON.stringify(result)); + + // 4. A click on a range track moves the thumb. + result = await vision({ type: 'click', x: 170, y: 290 }); + const rangeLog = await take(); + check('click_at on a range track sets its value', result?.rangeValue === '50' + && JSON.stringify(rangeLog) === JSON.stringify([['input', '50'], ['change', '50']]), JSON.stringify({ result, rangeLog })); + + // 5. Text: a double click selects the word under the pointer, a drag the text it crosses. + const bravo = await evaluateJson("wordPoint('bravo')"); + result = await vision({ type: 'click', x: bravo.x, y: bravo.y, clickCount: 2 }); + const word = await evaluate('String(getSelection())'); + check('a double click selects the word under the pointer', result?.success && word === 'bravo', JSON.stringify({ result, word })); + const from = await evaluateJson("wordPoint('alpha', 'start')"); + const to = await evaluateJson("wordPoint('charlie', 'end')"); + result = await vision({ type: 'drag', x: from.x, y: from.y, toX: to.x, toY: to.y, steps: 6 }); + const dragged = await evaluate('String(getSelection())'); + check('a drag across text selects it', result?.success && /^alpha bravo charli/.test(dragged), JSON.stringify({ result, dragged })); + await evaluate('getSelection().removeAllRanges()'); + + // 6. A wheel scrolls the box under the pointer. + result = await vision({ type: 'wheel', x: 120, y: 430, deltaY: 200 }); + const scrolled = await evaluate("document.getElementById('scroller').scrollTop"); + check('a wheel scrolls the box under the pointer', result?.success && result.moved === true && Math.abs(scrolled - 200) <= 1, JSON.stringify({ result, scrolled })); + + // 7. A scaled same-origin frame takes the click where it is drawn. + result = await vision({ type: 'click', x: 400 + (3 + 250) * 0.5, y: 300 + (3 + 120) * 0.5 }); + const frameLog = await evaluateJson("document.getElementById('scaled').contentWindow.log.splice(0)"); + check('a click in a scale(0.5) frame lands on the drawn button', + result?.success && JSON.stringify(frameLog) === JSON.stringify([['click', 250, 120]]), JSON.stringify({ result, frameLog })); + + // 8. Another origin's frame is refused instead of clicked at its element. + result = await vision({ type: 'click', x: 800, y: 150 }); + check('a click on a cross-origin frame is refused', + result?.visionInputRefused === 'opaque_frame' && result?.noDispatch === true, JSON.stringify(result)); + + // 9. Trusted input: the content script marks the element at the point and + // the companion session moves (and for a click presses) the real pointer there. + // Playwright's Firefox build answers browsingContext.locateNodes with no + // node at all. There the marked node is found by script instead, exactly + // one in the frames at the binding's URL as BidiSession.locate requires; + // every other step is the production session's. + const locator = await session.send('browsingContext.locateNodes', { context, locator: { type: 'css', value: 'html' } }); + if (!locator.nodes?.length) { + locatedByScript = true; + session.locate = async (token, targetUrl, root = null) => { + if (!/^[a-f0-9-]{36}$/.test(token) || !/^https?:\/\//.test(targetUrl)) throw new Error('Invalid tab binding'); + const tree = await session.send('browsingContext.getTree', root ? { root } : {}); + const contexts = []; + const visit = nodes => { for (const node of nodes || []) { contexts.push(node); visit(node.children); } }; + visit(tree.contexts); + const matches = []; + for (const frame of contexts) { + if (frame.url !== targetUrl) continue; + const found = await session.send('script.evaluate', { target: { context: frame.context }, awaitPromise: false, + expression: `(() => { const nodes = document.querySelectorAll('[data-webbrain-bidi="${token}"]'); return nodes.length === 1 ? nodes[0] : nodes.length; })()` }); + if (found.result?.sharedId) matches.push({ context: frame.context, node: { sharedId: found.result.sharedId } }); + else if (found.result?.value > 1) matches.push(null, null); + } + if (matches.length !== 1) throw new Error('Tab or element binding is stale or ambiguous; re-read the page'); + return matches[0]; + }; + } + const bindToken = crypto.randomUUID(); + await evaluate(`document.documentElement.setAttribute('data-webbrain-bidi', ${JSON.stringify(bindToken)})`); + const runId = crypto.randomUUID(); + await session.openRun(runId, bindToken, url); + const trustedLog = async () => evaluateJson('window.trusted.splice(0)'); + const perform = (action, payload) => session.perform(runId, action, payload) + .catch(error => ({ success: false, error: error.message, ...error.dispatchState })); + await trustedLog(); + const markedToken = () => evaluate(`document.querySelector('[data-webbrain-bidi]')?.getAttribute('data-webbrain-bidi') || null`); + let prepared = await vision({ type: 'click', x: 760.4, y: 269.6, _bidiPrepare: crypto.randomUUID() }); + const clickToken = await evaluate(`document.getElementById('trust').getAttribute('data-webbrain-bidi')`); + check('the content script marks the element at a trusted click point', prepared?.bidiPrepared === true && prepared?.noDispatch === true + && JSON.stringify(prepared.point) === JSON.stringify({ x: 760, y: 270 }) && typeof clickToken === 'string' && /^fpg_/.test(prepared._filePickerGuardId || ''), JSON.stringify({ prepared, clickToken })); + check('preparing sends nothing to the page', (await trustedLog()).length === 0); + result = await perform('click_at', { token: clickToken, url: prepared.url, point: prepared.point }); + const clicked = await trustedLog(); + check('click_at is one trusted press and click at the point', result?.success === true + && JSON.stringify(clicked) === JSON.stringify([['pointerdown', true, 760, 270, 'trust'], ['click', true, 760, 270, 'trust']]), JSON.stringify({ result, clicked })); + // The companion checks the marked element is still the one at the point. + prepared = await vision({ type: 'click', x: 760, y: 270, _bidiPrepare: crypto.randomUUID() }); + const staleToken = await markedToken(); + const refusal = await perform('click_at', { token: staleToken, url: prepared.url, point: { x: 120, y: 40 } }); + check('a point that no longer hits the marked element sends nothing', refusal?.success === false && refusal.noDispatch === true + && (await trustedLog()).length === 0, JSON.stringify(refusal)); + // A trusted hover is the browser's own :hover, with no emulation. + prepared = await vision({ type: 'hover', x: 120, y: 40, _bidiPrepare: crypto.randomUUID() }); + const hoverToken = await markedToken(); + result = await perform('hover_at', { token: hoverToken, url: prepared.url, point: prepared.point }); + const realHover = await evaluateJson(`({ submenu: getComputedStyle(document.querySelector('#menu .submenu')).display, + emulated: document.querySelectorAll('[data-webbrain-hover]').length, matches: document.getElementById('menu').matches(':hover') })`); + check('hover_at opens a CSS :hover menu through the real :hover', result?.success === true && realHover.submenu === 'block' + && realHover.emulated === 0 && realHover.matches === true, JSON.stringify({ result, realHover })); + await session.closeRun(runId); +} catch (error) { + check('harness', false, error?.stack || error); +} finally { + try { await session?.send('browser.close', {}); } catch { /* already gone */ } + await session?.close?.().catch(() => {}); + await new Promise(resolve => { if (firefox.exitCode != null) resolve(); else { firefox.once('exit', resolve); setTimeout(resolve, 3000); } }); + if (firefox.exitCode == null) { + if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(firefox.pid), '/T', '/F']); + else firefox.kill('SIGKILL'); + await delay(500); + } + server.close(); + const ownedProfile = await assertOwnedProfile(); + await rm(ownedProfile, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); +} + +const failed = results.filter(item => !item.ok); +if (failed.length) { + console.error(JSON.stringify(failed, null, 1)); + console.error(`FAIL: ${failed.length} of ${results.length} Firefox vision input checks`); + process.exitCode = 1; +} else { + console.log(`PASS: ${results.length} Firefox vision input checks (CSS :hover and its restore, pointer capture, react-aria press, range track click, word and drag text selection, wheel, scaled frame click, cross-origin frame refusal; trusted click_at and hover_at through the companion session${locatedByScript ? ', its marked node found by script' : ''})`); +} diff --git a/test/input-receiving-frame.mjs b/test/input-receiving-frame.mjs new file mode 100644 index 0000000000..3b47603aae --- /dev/null +++ b/test/input-receiving-frame.mjs @@ -0,0 +1,212 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { test } from 'node:test'; +import { chromium } from 'playwright'; +import { cdpClient } from '../src/chrome/src/cdp/cdp-client.js'; + +// A coordinate click, type_text without a selector and press_keys reach the +// document under the point or holding focus. The permission gate charges that +// document's host, so the production CDP resolver must find an embedded +// cross-origin (process-isolated) frame the way Chrome delivers the input, and +// not be talked out of it by the top page. Only chrome.debugger is bridged to +// Playwright's CDP sessions; no website is contacted. +const TAB = 31; +const MERCHANT = 'https://merchant.invalid/checkout'; +const WALLET = 'https://wallet.invalid/pay'; +const SANDBOXED = 'https://wallet.invalid/sandboxed'; +const OBJECT = 'https://wallet.invalid/object'; +const top = ` + + + +`; +const walletHtml = ''; + +test('Chrome: the input receiving frame is the embedded frame under the point or holding focus', { timeout: 60000 }, async t => { + const saved = { chrome: globalThis.chrome, attach: cdpClient.attach }; + const browser = await chromium.launch({ headless: true, args: ['--site-per-process'] }); + const children = new Map(); // fake sessionId -> Playwright CDP session of an OOPIF + const frameByTarget = new Map(); + let session; + let attaches = 0; + const send = async (target, method, params) => { + if (!target.sessionId && method === 'Target.attachToTarget') { + const frame = frameByTarget.get(params.targetId); + if (!frame) throw new Error(`No target ${params.targetId}`); + const sessionId = `child-${++attaches}`; + children.set(sessionId, await frame.page().context().newCDPSession(frame)); + return { sessionId }; + } + if (!target.sessionId && method === 'Target.detachFromTarget') { + await children.get(params.sessionId)?.detach(); + children.delete(params.sessionId); + return {}; + } + return (target.sessionId ? children.get(target.sessionId) : session).send(method, params); + }; + globalThis.chrome = { + runtime: {}, + debugger: { sendCommand: (target, method, params, callback) => { + send(target, method, params).then(callback, error => { + chrome.runtime.lastError = { message: error.message }; callback(); delete chrome.runtime.lastError; + }); + } }, + }; + cdpClient.attach = async () => cdpClient.sessions.set(TAB, {}); + try { + const context = await browser.newContext({ viewport: { width: 900, height: 700 } }); + await context.route('**/*', route => { + const url = route.request().url(); + if (url === MERCHANT) return route.fulfill({ contentType: 'text/html', body: top }); + if (url === WALLET || url === SANDBOXED || url === OBJECT) return route.fulfill({ contentType: 'text/html', body: walletHtml }); + return route.abort(); + }); + const page = await context.newPage(); + await page.goto(MERCHANT); + session = await context.newCDPSession(page); + // Playwright gives no content frame for an ; find it by address. + const frameOf = async selector => (await (await page.locator(selector).elementHandle()).contentFrame()) + || page.frames().find(frame => frame.url() === OBJECT); + for (const id of ['wallet', 'sandboxed', 'object']) { + const frame = await frameOf(`#${id}`); + await frame.waitForSelector('#card'); + const { result } = await session.send('Runtime.evaluate', { expression: `document.getElementById(${JSON.stringify(id)})` }); + const { node } = await session.send('DOM.describeNode', { objectId: result.objectId }); + frameByTarget.set(node.frameId, frame); + } + const wallet = await (await page.locator('#wallet').elementHandle()).contentFrame(); + const same = await (await page.locator('#same').elementHandle()).contentFrame(); + await same.waitForSelector('#inner'); + // Scroll the top page so viewport points differ from document points. + await page.evaluate(() => scrollTo(0, 30)); + const centre = async (frameSelector, fieldSelector) => { + const box = await page.locator(frameSelector).evaluate(node => { + const rect = node.getBoundingClientRect(); return { left: rect.left + 3, top: rect.top + 3 }; + }); + const frame = await frameOf(frameSelector); + const field = await frame.locator(fieldSelector).evaluate(node => { + const rect = node.getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; + }); + return { x: box.left + field.x, y: box.top + field.y }; + }; + + await t.test('a point on the top document stays with the top document', async () => { + const point = await page.locator('#topField').evaluate(node => { + const rect = node.getBoundingClientRect(); return { x: rect.left + 5, y: rect.top + 5 }; + }); + assert.deepEqual(await cdpClient.resolveInputFrame(TAB, point), { topDocument: true }); + }); + + await t.test('a point over a process-isolated cross-origin frame resolves to that frame', async () => { + const frame = await cdpClient.resolveInputFrame(TAB, await centre('#wallet', '#card')); + assert.equal(frame.topDocument, false); + assert.equal(new URL(frame.url).hostname, 'wallet.invalid'); + assert.equal(children.size, 0, 'temporary child sessions are detached'); + }); + + await t.test('an hosting another site is a frame like an `; + await context.route('**/*', route => { + const url = route.request().url(); + if (url === MERCHANT) return route.fulfill({ contentType: 'text/html', body: html }); + if (url === WALLET) return route.fulfill({ contentType: 'text/html', body: walletHtml }); + return route.abort(); + }); + const tab = await context.newPage(); + await tab.goto(MERCHANT); + await tab.evaluate(() => { + window.fixtureHandlers = []; + const runtime = { onMessage: { addListener(fn) { window.fixtureHandlers.push(fn); } }, getURL: p => p, sendMessage: async () => ({}) }; + window.chrome = { runtime }; window.browser = { runtime }; + }); + for (const file of ['file-upload-policy.js', 'rich-text-toolbar-heuristic.js', 'accessibility-tree.js', 'content.js']) { + await tab.addScriptTag({ content: await readFile(new URL(`../src/firefox/src/content/${file}`, import.meta.url), 'utf8') }); + } + const wallet = await (await tab.locator('#wallet').elementHandle()).contentFrame(); + await wallet.waitForSelector('#card'); + const call = (action, params) => tab.evaluate(message => new Promise(resolve => { + for (const handler of window.fixtureHandlers) handler(message, {}, resolve); + }), { target: 'content', action, params: { ...params, _bidiPrepare: randomUUID() } }); + const centre = selector => tab.locator(selector).evaluate(node => { + const rect = node.getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; + }); + + const overFrame = await call('click', await centre('#wallet')); + assert.equal(overFrame.embeddedFrameTarget, true, JSON.stringify(overFrame)); + assert.equal(overFrame.noDispatch, true); + assert.equal(overFrame.bidiPrepared, undefined); + assert.equal(await tab.evaluate(() => document.querySelector('[data-webbrain-bidi]')), null, 'the frame was marked for trusted input'); + const onPage = await call('click', await centre('#pay')); + assert.equal(onPage.bidiPrepared, true, JSON.stringify(onPage)); + + await wallet.locator('#card').focus(); + const enter = await call('press_keys', { key: 'Enter' }); + assert.equal(enter.embeddedFrameTarget, true, JSON.stringify(enter)); + assert.equal(enter.bidiPrepared, undefined); + // Tab and Escape stay ungated, as on Chrome. + const escape = await call('press_keys', { key: 'Escape' }); + assert.equal(escape.bidiPrepared, true, JSON.stringify(escape)); + } finally { + await browser.close(); + } +}); diff --git a/test/monitor-intervention-contract.mjs b/test/monitor-intervention-contract.mjs index ba16f2c3b2..eb4be11e78 100644 --- a/test/monitor-intervention-contract.mjs +++ b/test/monitor-intervention-contract.mjs @@ -305,6 +305,75 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) { } finally { await browser.close(); } }); + test(`${build}: a vision point's trusted click and hover through the companion belong to the agent`, { timeout: 60000 }, async t => { + const browser = await engine.launch({ headless: true }); + // As the run prepares a vision point (page-feedback.js) and the companion + // validates and marks before trusted input (firefox-companion/session.mjs), + // with the element content.js _visionBidiPrepare marks: the one + // document.elementFromPoint gives for the point. + const trusted = async (page, { x, y, kind = 'click', mark = null }) => { + const prepared = await message(page, 'page_monitor_prepare', { operationId: 'vision', tool: 'click', allowPassiveRebase: true, visionPoint: true, x, y }); + assert.equal(prepared.ready, true); + const fence = await message(page, 'page_monitor_dispatch', { operationId: 'vision', kind: 'click', frameId: 0, navigationCandidate: kind === 'click', fenceOnly: true }); + assert.equal(fence.ready, true, JSON.stringify(fence)); + const validation = await message(page, 'page_monitor_validate', { ...fence.guard, kind: 'click', rebindFocus: false }); + assert.equal(validation.ready, true, JSON.stringify(validation)); + const marker = createNativeActionMarker({ ...fence.guard, revision: validation.revision }, 'click', 1); + await page.evaluate(({ x, y, marker, mark }) => { + const el = mark ? eval(mark) : document.elementFromPoint(x, y); + el.setAttribute('data-webbrain-native-action', marker); + }, { x, y, marker, mark }); + if (kind === 'click') await page.mouse.click(x, y); + else await page.mouse.move(x, y, { steps: 2 }); + await message(page, 'page_monitor_finish', { operationId: 'vision' }); + await settle(page); + return sources(page); + }; + const shadowHost = page => page.evaluate(() => { + const host = document.createElement('div'); + host.id = 'shadow-host'; + host.style.cssText = 'position:absolute;left:600px;top:300px;width:200px;height:60px'; + document.body.append(host); + const root = host.attachShadow({ mode: 'open' }); + root.innerHTML = ''; + window.innerClicks = 0; + root.getElementById('inner').addEventListener('click', () => { window.innerClicks++; }); + }).then(() => settle(page)).then(() => page.evaluate(() => { feedback = []; delivered = []; })); + try { + await t.test('a trusted click on the marked element is no user input', async () => { + const { context, page } = await fixture(browser, build); + try { + const box = await page.locator('#toggle').boundingBox(); + const events = await trusted(page, { x: Math.round(box.x + box.width / 2), y: Math.round(box.y + box.height / 2) }); + assert.equal(await page.evaluate(() => document.getElementById('hidden-switch').checked), true, 'the click landed'); + assert.equal(events.some(event => event.endsWith('/user')), false, `the trusted click is the agent's: ${events}`); + } finally { await context.close(); } + }); + await t.test('a trusted hover on the marked element is no user input', async () => { + const { context, page } = await fixture(browser, build); + try { + const box = await page.locator('#send').boundingBox(); + const events = await trusted(page, { x: Math.round(box.x + box.width / 2), y: Math.round(box.y + box.height / 2), kind: 'hover' }); + assert.equal(events.some(event => event.endsWith('/user')), false, `the trusted hover is the agent's: ${events}`); + } finally { await context.close(); } + }); + // Why content.js leaves a point inside an open shadow root synthetic: the + // monitor binds the host there, and neither a mark on the host nor one on + // the element inside covers the trusted events, which come from inside. + for (const [name, mark] of [['the host', null], ['the element inside', "document.getElementById('shadow-host').shadowRoot.getElementById('inner')"]]) { + await t.test(`inside an open shadow root a mark on ${name} does not cover a trusted click`, async () => { + const { context, page } = await fixture(browser, build); + try { + await shadowHost(page); + const events = await trusted(page, { x: 700, y: 330, mark }); + assert.equal(await page.evaluate(() => window.innerClicks), 1); + assert.ok(events.some(event => event.endsWith('/user')), `the click is not shown as the agent's: ${events}`); + } finally { await context.close(); } + }); + } + } finally { await browser.close(); } + }); + test(`${build}: finishing an operation delivers its own pending reactions first`, { timeout: 60000 }, async t => { const browser = await engine.launch({ headless: true }); try { diff --git a/test/monitor-vision-wheel.mjs b/test/monitor-vision-wheel.mjs new file mode 100644 index 0000000000..4ea5041435 --- /dev/null +++ b/test/monitor-vision-wheel.mjs @@ -0,0 +1,109 @@ +// Vision mode's mouse wheel (scroll_at) through the real page monitor. Its +// own wheel events stay the agent's even when the browser delivers them after +// the next notch was already fenced, and page churn does not void the +// operation while a person's input still does. Chromium runs both builds' +// monitor (the file is shared verbatim). +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { test } from 'node:test'; +import { chromium } from 'playwright'; + +const RUN = 'vision-wheel'; +const html = ` +
0
`; + +async function fixture(browser, build) { + const context = await browser.newContext({ viewport: { width: 1000, height: 700 } }); + await context.route('https://wheel.test/**', route => route.fulfill({ contentType: 'text/html', body: html })); + await context.addInitScript(RUN => { + window.feedback = []; window.messageListeners = []; + const runtime = { + onMessage: { addListener: fn => messageListeners.push(fn), removeListener() {} }, + async sendMessage(message) { + if (message.action === 'get_page_monitor_state') return { active: true, runToken: RUN, documentToken: message.documentToken }; + if (message.action === 'page_feedback') { feedback.push(message.feedback); return { accepted: true }; } + return {}; + }, + }; + window.chrome = { runtime }; window.browser = window.chrome; + window.deliver = (action, params = {}) => new Promise(resolve => { + for (const listener of messageListeners) { + let answered = false; + const asynchronous = listener({ target: 'content', action, params: { runToken: RUN, ...params } }, {}, value => { answered = true; resolve(value); }); + if (answered || asynchronous === true) return; + } + resolve(undefined); + }); + }, RUN); + await context.addInitScript({ content: fs.readFileSync(new URL(`../src/${build}/src/content/page-monitor.js`, import.meta.url), 'utf8') }); + const page = await context.newPage(); + await page.goto('https://wheel.test/start'); + await page.waitForFunction(() => window.__wbPageMonitor?.active); + await page.waitForTimeout(300); + return { context, page }; +} + +const message = (page, action, params = {}) => page.evaluate(({ action, params }) => deliver(action, params), { action, params }); +// What page-feedback.js sends for scroll_at, and what cdpClient's fence sends +// before each mouseWheel command. +const prepare = page => message(page, 'page_monitor_prepare', { operationId: 'wheel', tool: 'scroll_at', allowPassiveRebase: true, visionWheel: true }); +const wheelFence = page => message(page, 'page_monitor_dispatch', { + operationId: 'wheel', kind: 'scroll', nativeWheel: true, nativeInput: true, eventTypes: ['wheel'], x: 400, y: 300, +}); +const userEvents = page => page.evaluate(() => feedback.filter(event => event.source === 'user').map(event => event.kind)); + +for (const build of ['chrome', 'firefox']) { + test(`${build}: a vision wheel keeps its own events and survives page churn, not a person`, { timeout: 120000 }, async t => { + const browser = await chromium.launch({ headless: true }); + try { + await t.test('two notches fenced before their wheel events arrive are both the agent\'s', async () => { + const { context, page } = await fixture(browser, build); + try { + await page.mouse.move(400, 300); + assert.equal((await prepare(page)).ready, true); + assert.equal((await wheelFence(page)).ready, true); + assert.equal((await wheelFence(page)).ready, true); + await page.mouse.wheel(0, 100); + await page.mouse.wheel(0, 100); + await page.waitForFunction(() => window.scrollY >= 200); + await page.waitForTimeout(400); + assert.deepEqual(await userEvents(page), [], 'no wheel or scroll is reported as a person\'s'); + // A third wheel the agent never fenced is a person's. + await page.mouse.wheel(0, 100); + await page.waitForTimeout(400); + assert.ok((await userEvents(page)).includes('activity'), JSON.stringify(await userEvents(page))); + } finally { await context.close(); } + }); + + await t.test('page churn after preparation does not void the wheel', async () => { + const { context, page } = await fixture(browser, build); + try { + await page.mouse.move(400, 300); + assert.equal((await prepare(page)).ready, true); + await page.evaluate(() => { + let ticks = 0; + window.churn = setInterval(() => { document.getElementById('ticker').textContent = String(++ticks); }, 20); + }); + await page.waitForTimeout(300); + const fenced = await wheelFence(page); + await page.evaluate(() => clearInterval(window.churn)); + assert.equal(fenced.ready, true, JSON.stringify(fenced)); + } finally { await context.close(); } + }); + + await t.test('a person\'s click after preparation voids it', async () => { + const { context, page } = await fixture(browser, build); + try { + assert.equal((await prepare(page)).ready, true); + await page.click('#human'); + await page.waitForTimeout(300); + await page.mouse.move(400, 300); + const fenced = await wheelFence(page); + assert.equal(fenced.ready, false, JSON.stringify(fenced)); + assert.equal(fenced.preparationVeto?.predicate, 'intervention_changed', JSON.stringify(fenced)); + } finally { await context.close(); } + }); + } finally { await browser.close(); } + }); +} diff --git a/test/page-monitor-ui.mjs b/test/page-monitor-ui.mjs index ce6c02dd5d..185d94634d 100644 --- a/test/page-monitor-ui.mjs +++ b/test/page-monitor-ui.mjs @@ -2255,6 +2255,70 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) { } finally { await browser.close(); } }); + test(`${build}: agent cursor, target ring and every activity effect stay out of page feedback`, async () => { + const { browser, page } = await fixture(engine, build); + try { + // The settings select writes `agentIndicatorStyle`; the indicator applies it live. + await page.evaluate(() => { + window.storageListeners = []; + chrome.storage = { + local: { get: async defaults => ({ ...defaults, agentIndicatorStyle: 'scan' }) }, + onChanged: { addListener: fn => storageListeners.push(fn) }, + }; + }); + await page.addScriptTag({ content: read(build, 'content/agent-visual-indicator.js') }); + await page.evaluate(() => { + feedback = []; + messageListeners.forEach(listener => listener({ type: 'WB_SHOW_AGENT_INDICATORS' }, {}, () => {})); + }); + await page.waitForTimeout(300); + // Glide, press and ripple, then the resting breath (opacity only, via Web Animations). + await page.evaluate(() => window.__webbrainAgentIndicator.showTarget(document.getElementById('agent'), 'click_ax')); + await page.waitForTimeout(500); + await page.evaluate(() => window.__webbrainAgentIndicator.showTarget(document.getElementById('field'), 'type_text')); + await page.waitForTimeout(2200); + const resting = await page.evaluate(() => { + const cursor = document.getElementById('webbrain-agent-target-cursor'); + const effect = document.getElementById('webbrain-agent-effect'); + return { + cursorPointerEvents: getComputedStyle(cursor).pointerEvents, + cursorShown: getComputedStyle(cursor).opacity === '1', + breathing: cursor.firstElementChild.getAnimations().some(animation => animation.effect.getComputedTiming().iterations === Infinity), + effectPointerEvents: getComputedStyle(effect).pointerEvents, + effectDisplay: getComputedStyle(effect).display, + }; + }); + assert.deepEqual(resting, { + cursorPointerEvents: 'none', cursorShown: true, breathing: true, effectPointerEvents: 'none', effectDisplay: 'block', + }); + for (const style of ['aurora', 'gears', 'classic', 'circuit']) { + await page.evaluate(style => storageListeners.forEach(fn => fn({ agentIndicatorStyle: { newValue: style } }, 'local')), style); + await page.evaluate(() => window.__webbrainAgentIndicator.showTarget(document.getElementById('select'), 'click_coordinates')); + await page.waitForTimeout(650); + } + assert.equal(await page.evaluate(() => document.querySelectorAll('#webbrain-agent-effect').length), 1, 'the previous effect is removed after a switch'); + assert.equal((await page.evaluate(() => feedback)).length, 0, JSON.stringify(await page.evaluate(() => feedback))); + // Screenshot capture hides every part, and nothing intercepts real input. + await page.evaluate(() => messageListeners.forEach(listener => listener({ type: 'WB_HIDE_FOR_TOOL_USE' }, {}, () => {}))); + assert.deepEqual(await page.evaluate(() => ['webbrain-agent-effect', 'webbrain-agent-target-cursor', 'webbrain-agent-stop-container'] + .map(id => getComputedStyle(document.getElementById(id)).display)), ['none', 'none', 'none']); + await page.evaluate(() => messageListeners.forEach(listener => listener({ type: 'WB_SHOW_AFTER_TOOL_USE' }, {}, () => {}))); + await page.locator('#human').click(); + assert.ok((await page.evaluate(() => feedback)).some(event => event.kind === 'click' && event.source === 'user')); + // Reduced motion: the canvas keeps one still frame, and the glow and the ring stop pulsing. + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.waitForTimeout(100); + const frame = () => page.evaluate(() => document.getElementById('webbrain-agent-effect').toDataURL()); + const still = await frame(); + await page.waitForTimeout(400); + assert.equal(await frame(), still, 'the circuit holds still under reduced motion'); + await page.evaluate(() => storageListeners.forEach(fn => fn({ agentIndicatorStyle: { newValue: 'classic' } }, 'local'))); + await page.evaluate(() => window.__webbrainAgentIndicator.showTarget(document.getElementById('select'), 'click_coordinates')); + assert.deepEqual(await page.evaluate(() => ['webbrain-agent-glow-border', 'webbrain-agent-target-outline'] + .map(id => getComputedStyle(document.getElementById(id)).animationName)), ['none', 'none']); + } finally { await browser.close(); } + }); + test(`${build}: companion native markers renew per key without hiding a later human edit`, async () => { const { browser, page } = await fixture(engine, build); try { diff --git a/test/page-resource-download-browser.mjs b/test/page-resource-download-browser.mjs new file mode 100644 index 0000000000..b79c813ca7 --- /dev/null +++ b/test/page-resource-download-browser.mjs @@ -0,0 +1,61 @@ +// download_resource_from_page reads the element's resource in the page +// (network-tools.js readPageResourceForDownload), in real Chromium for both +// builds' copies: a blob is read up to a size limit and its reader cancelled +// past it, and a streaming playlist is refused rather than saved as media. +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { test } from 'node:test'; +import { chromium } from 'playwright'; + +const api = { runtime: { getURL: value => value, onMessage: { addListener() {} } }, storage: { local: { get: async () => ({}) }, onChanged: { addListener() {} } }, downloads: { onChanged: { addListener() {} } } }; +globalThis.chrome ??= api; +globalThis.browser ??= api; + +const server = http.createServer((request, response) => { + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + response.end('Resources'); +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const origin = `http://127.0.0.1:${server.address().port}`; +test.after(() => new Promise(resolve => server.close(resolve))); + +for (const build of ['chrome', 'firefox']) { + test(`${build}: a page resource is read within its limit, and a streaming playlist is not saved as media`, async () => { + const { readPageResourceForDownload } = await import(`../src/${build}/src/network/network-tools.js`); + const browser = await chromium.launch({ channel: 'chromium' }); + try { + const page = await (await browser.newContext()).newPage(); + await page.goto(`${origin}/page`); + await page.evaluate(() => { + const add = (id, url, tag = 'video') => { const el = document.createElement(tag); el.id = id; el.src = url; document.body.append(el); }; + add('small', URL.createObjectURL(new Blob([new Uint8Array(2048)], { type: 'video/mp4' }))); + add('large', URL.createObjectURL(new Blob([new Uint8Array(300 * 1024)], { type: 'video/mp4' }))); + add('hls-blob', URL.createObjectURL(new Blob(['#EXTM3U\n'], { type: 'application/vnd.apple.mpegurl' }))); + add('hls', '/stream/master.m3u8?token=1'); + add('dash', '/stream/manifest.mpd'); + add('file', '/media/clip.mp4'); + }); + const read = (selector, maxBytes) => page.evaluate(({ source, selector, maxBytes }) => { + // eslint-disable-next-line no-new-func + const fn = new Function(`return (${source})`)(); + return fn(selector, maxBytes); + }, { source: readPageResourceForDownload.toString(), selector, maxBytes }); + const small = await read('#small', 100 * 1024); + assert.equal(small.ok, true, JSON.stringify(small).slice(0, 200)); + assert.equal(small.size, 2048); + assert.match(small.url, /^data:video\/mp4;base64,/); + const large = await read('#large', 100 * 1024); + assert.deepEqual({ ok: large.ok, tooLarge: large.tooLarge }, { ok: false, tooLarge: true }); + for (const selector of ['#hls-blob', '#hls', '#dash']) { + const playlist = await read(selector, 100 * 1024); + assert.equal(playlist.ok, false, selector); + assert.equal(playlist.streamingPlaylist, true, selector); + assert.match(playlist.error, /streaming playlist/); + } + const file = await read('#file', 100 * 1024); + assert.deepEqual({ ok: file.ok, isBlob: file.isBlob, crossOrigin: file.crossOrigin }, { ok: true, isBlob: false, crossOrigin: false }); + } finally { + await browser.close(); + } + }); +} diff --git a/test/quality/anchored-action-mv3.mjs b/test/quality/anchored-action-mv3.mjs index 2266d168a3..8bbdeedc4d 100644 --- a/test/quality/anchored-action-mv3.mjs +++ b/test/quality/anchored-action-mv3.mjs @@ -89,7 +89,7 @@ try { const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planReviewMode: 'never', - maxAgentSteps: 8, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, + visionMode: 'off', maxAgentSteps: 8, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/bluesky-composer-mv3.mjs b/test/quality/bluesky-composer-mv3.mjs index 3a92d6e4ac..ea74ebe7d1 100644 --- a/test/quality/bluesky-composer-mv3.mjs +++ b/test/quality/bluesky-composer-mv3.mjs @@ -241,7 +241,7 @@ try { if(event.action==='agent_update'&&blueskyRuns[event.requestId])blueskyRuns[event.requestId].push({type:event.type,data:event.data}); }); return chrome.storage.local.set({helpImproveWebBrain:false,tracingEnabled:false,autoScreenshot:false,screenshotFallback:false, - planBeforeActMode:'off',planBeforeAct:false,planReviewMode:'never',maxAgentSteps:10,systemOneEnabled:false,agentAllowLocalNetwork:true, + planBeforeActMode:'off',planBeforeAct:false,planReviewMode:'never',visionMode:'off',maxAgentSteps:10,systemOneEnabled:false,agentAllowLocalNetwork:true, askBeforeConsequentialActions:false,openaiAskStreamingEnabled:false}); }); assert.equal((await message('update_provider',{providerId:'openrouter',config:{apiKey:'owned-fixture-fake-key', diff --git a/test/quality/bulk-resume-mv3.mjs b/test/quality/bulk-resume-mv3.mjs index faea946a1d..e68cc1db30 100644 --- a/test/quality/bulk-resume-mv3.mjs +++ b/test/quality/bulk-resume-mv3.mjs @@ -228,7 +228,7 @@ try { window.bulkEvents = []; chrome.runtime.onMessage.addListener(event => { if (event.action === 'agent_update') bulkEvents.push({ requestId: event.requestId, type: event.type, data: event.data }); }); await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', - screenshotFallback: false, autoScreenshot: false, maxAgentSteps: 150, systemOneEnabled: false, tracingEnabled: false, + screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: 150, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }); }); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `${origin}/v1`, model: 'minimax/minimax-m3', contextWindow: 1000000, enabled: true, supportsAskStreaming: false } })).ok, true); diff --git a/test/quality/cloud-bot-memory-mv3.mjs b/test/quality/cloud-bot-memory-mv3.mjs index c1be944bad..0bd9dc50ac 100644 --- a/test/quality/cloud-bot-memory-mv3.mjs +++ b/test/quality/cloud-bot-memory-mv3.mjs @@ -209,7 +209,7 @@ try { const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', - maxAgentSteps: 8, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, + visionMode: 'off', maxAgentSteps: 8, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-memory-fixture-key', baseUrl: origin + '/v1', model: 'minimax/minimax-m3', enabled: true, contextWindow: 1000000, supportsAskStreaming: false } })).ok, true); diff --git a/test/quality/correction-cross-site-mv3.mjs b/test/quality/correction-cross-site-mv3.mjs index df2d2df84c..ef0c575ddc 100644 --- a/test/quality/correction-cross-site-mv3.mjs +++ b/test/quality/correction-cross-site-mv3.mjs @@ -427,7 +427,7 @@ async function runVariant(variant, script) { const message = (action, data = {}) => settings.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await settings.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, userMemoryEnabled: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', - maxAgentSteps: 30, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, + visionMode: 'off', maxAgentSteps: 30, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `${base}/v1`, model: 'minimax/minimax-m3', enabled: true, contextWindow: 1000000, diff --git a/test/quality/download-upload-mv3.mjs b/test/quality/download-upload-mv3.mjs index 463a5a3a6f..a9d912814a 100644 --- a/test/quality/download-upload-mv3.mjs +++ b/test/quality/download-upload-mv3.mjs @@ -77,7 +77,7 @@ try { const worker=context.serviceWorkers()[0]||await context.waitForEvent('serviceworker'),id=new URL(worker.url()).host; const harness=await context.newPage();await harness.goto(`chrome-extension://${id}/src/ui/settings.html`); const message=(action,data={})=>harness.evaluate(({action,data})=>chrome.runtime.sendMessage({target:'background',action,...data}),{action,data}); - await harness.evaluate(async()=>{window.events=[];chrome.runtime.onMessage.addListener(e=>{if(e.action==='agent_update')events.push({type:e.type,data:e.data});});await chrome.storage.local.set({helpImproveWebBrain:false,planBeforeActMode:'off',planReviewMode:'never',screenshotFallback:false,autoScreenshot:false,maxAgentSteps:15,systemOneEnabled:false,tracingEnabled:false,agentAllowLocalNetwork:true,askBeforeConsequentialActions:false,openaiAskStreamingEnabled:false});}); + await harness.evaluate(async()=>{window.events=[];chrome.runtime.onMessage.addListener(e=>{if(e.action==='agent_update')events.push({type:e.type,data:e.data});});await chrome.storage.local.set({helpImproveWebBrain:false,planBeforeActMode:'off',planReviewMode:'never',screenshotFallback:false,autoScreenshot:false,visionMode:'off',maxAgentSteps:15,systemOneEnabled:false,tracingEnabled:false,agentAllowLocalNetwork:true,askBeforeConsequentialActions:false,openaiAskStreamingEnabled:false});}); assert.equal((await message('update_provider',{providerId:'openrouter',config:{apiKey:'owned-fixture-fake-key',baseUrl:`${base}/v1`,model:'minimax/minimax-m3',contextWindow:1000000,enabled:true,supportsAskStreaming:false}})).ok,true); assert.equal((await message('set_active_provider',{providerId:'openrouter'})).ok,true); const page=await context.newPage();await page.goto(`${base}/attachment`); diff --git a/test/quality/downloaded-file-saved-bytes-mv3.mjs b/test/quality/downloaded-file-saved-bytes-mv3.mjs index 2893755c73..dfeec3fa4d 100644 --- a/test/quality/downloaded-file-saved-bytes-mv3.mjs +++ b/test/quality/downloaded-file-saved-bytes-mv3.mjs @@ -96,7 +96,7 @@ try { await worker.evaluate(()=>{const originalFetch=globalThis.fetch;globalThis.blockedFetches=0;globalThis.fetch=(input,init)=>{const u=new URL(typeof input==='string'?input:input.url);if(!['127.0.0.1','localhost'].includes(u.hostname)&&!['chrome-extension:','data:'].includes(u.protocol)){blockedFetches++;throw Error('Owned fixture only');}return originalFetch(input,init);};}); const harness=await context.newPage();await harness.goto(`chrome-extension://${id}/src/ui/settings.html`); const message=(action,data={})=>harness.evaluate(({action,data})=>chrome.runtime.sendMessage({target:'background',action,...data}),{action,data}); - await harness.evaluate(async()=>{window.events=[];chrome.runtime.onMessage.addListener(e=>{if(e.action==='agent_update')events.push({type:e.type,data:e.data});});await chrome.storage.local.set({helpImproveWebBrain:false,planBeforeActMode:'off',planReviewMode:'never',screenshotFallback:false,autoScreenshot:false,maxAgentSteps:15,systemOneEnabled:false,tracingEnabled:false,agentAllowLocalNetwork:true,askBeforeConsequentialActions:false,openaiAskStreamingEnabled:false});}); + await harness.evaluate(async()=>{window.events=[];chrome.runtime.onMessage.addListener(e=>{if(e.action==='agent_update')events.push({type:e.type,data:e.data});});await chrome.storage.local.set({helpImproveWebBrain:false,planBeforeActMode:'off',planReviewMode:'never',screenshotFallback:false,autoScreenshot:false,visionMode:'off',maxAgentSteps:15,systemOneEnabled:false,tracingEnabled:false,agentAllowLocalNetwork:true,askBeforeConsequentialActions:false,openaiAskStreamingEnabled:false});}); assert.equal((await message('update_provider',{providerId:'openrouter',config:{apiKey:'owned-fixture-fake-key',baseUrl:`${base}/v1`,model:'minimax/minimax-m3',contextWindow:1000000,enabled:true,supportsAskStreaming:false}})).ok,true); assert.equal((await message('set_active_provider',{providerId:'openrouter'})).ok,true); const page=await context.newPage();await page.goto(`${base}/attachment`); diff --git a/test/quality/dropdown-menu-mv3.mjs b/test/quality/dropdown-menu-mv3.mjs index 06288561be..eb7e83bba6 100644 --- a/test/quality/dropdown-menu-mv3.mjs +++ b/test/quality/dropdown-menu-mv3.mjs @@ -160,7 +160,7 @@ try { const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/file-upload-accept-mv3.mjs b/test/quality/file-upload-accept-mv3.mjs index f3de803853..1d3f4ac713 100644 --- a/test/quality/file-upload-accept-mv3.mjs +++ b/test/quality/file-upload-accept-mv3.mjs @@ -86,7 +86,7 @@ try { await worker.evaluate(()=>{const originalFetch=globalThis.fetch;globalThis.blockedFetches=0;globalThis.fetch=(input,init)=>{const u=new URL(typeof input==='string'?input:input.url);if(!['127.0.0.1','localhost'].includes(u.hostname)&&!['chrome-extension:','data:'].includes(u.protocol)){blockedFetches++;throw Error('Owned fixture only');}return originalFetch(input,init);};}); const harness=await context.newPage();await harness.goto(`chrome-extension://${id}/src/ui/settings.html`); const message=(action,data={})=>harness.evaluate(({action,data})=>chrome.runtime.sendMessage({target:'background',action,...data}),{action,data}); - await harness.evaluate(async()=>{window.events=[];chrome.runtime.onMessage.addListener(e=>{if(e.action==='agent_update')events.push({type:e.type,data:e.data});});await chrome.storage.local.set({helpImproveWebBrain:false,planBeforeActMode:'off',planReviewMode:'never',screenshotFallback:false,autoScreenshot:false,maxAgentSteps:15,systemOneEnabled:false,tracingEnabled:false,agentAllowLocalNetwork:true,askBeforeConsequentialActions:false,openaiAskStreamingEnabled:false});}); + await harness.evaluate(async()=>{window.events=[];chrome.runtime.onMessage.addListener(e=>{if(e.action==='agent_update')events.push({type:e.type,data:e.data});});await chrome.storage.local.set({helpImproveWebBrain:false,planBeforeActMode:'off',planReviewMode:'never',screenshotFallback:false,autoScreenshot:false,visionMode:'off',maxAgentSteps:15,systemOneEnabled:false,tracingEnabled:false,agentAllowLocalNetwork:true,askBeforeConsequentialActions:false,openaiAskStreamingEnabled:false});}); assert.equal((await message('update_provider',{providerId:'openrouter',config:{apiKey:'owned-fixture-fake-key',baseUrl:`${base}/v1`,model:'minimax/minimax-m3',contextWindow:1000000,enabled:true,supportsAskStreaming:false}})).ok,true); assert.equal((await message('set_active_provider',{providerId:'openrouter'})).ok,true); const page=await context.newPage();await page.goto(`${base}/attachment`); diff --git a/test/quality/inline-social-composer-mv3.mjs b/test/quality/inline-social-composer-mv3.mjs index 21f921660f..a8d7aa7640 100644 --- a/test/quality/inline-social-composer-mv3.mjs +++ b/test/quality/inline-social-composer-mv3.mjs @@ -389,7 +389,7 @@ try { }); return chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 10, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 10, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }); }); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', diff --git a/test/quality/integration-mv3.mjs b/test/quality/integration-mv3.mjs index 786429bda6..02b608c154 100644 --- a/test/quality/integration-mv3.mjs +++ b/test/quality/integration-mv3.mjs @@ -97,7 +97,7 @@ try { await harness.evaluate(async () => { window.events = []; chrome.runtime.onMessage.addListener(event => { if (event.action === 'agent_update') events.push({ type: event.type, data: event.data }); }); - await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, maxAgentSteps: 12, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }); + await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: 12, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }); }); if (browserBatchDisabled) await harness.evaluate(async () => { await chrome.storage.local.set({ browserBatchEnabled: false }); diff --git a/test/quality/literal-calculate-midrun-mv3.mjs b/test/quality/literal-calculate-midrun-mv3.mjs index b3bbe3d74f..98075e1b1b 100644 --- a/test/quality/literal-calculate-midrun-mv3.mjs +++ b/test/quality/literal-calculate-midrun-mv3.mjs @@ -192,7 +192,7 @@ try { chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await settings.evaluate(async () => chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, - maxAgentSteps: 10, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, + visionMode: 'off', maxAgentSteps: 10, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false, contextWindowMode: 'full', // gpt-5.4-mini on a router is a strong model, so Auto lean mode would skip the // calculation reading and the tool projection this case checks. diff --git a/test/quality/literal-frame-mv3.mjs b/test/quality/literal-frame-mv3.mjs index 977078f4ee..89ca7a5773 100644 --- a/test/quality/literal-frame-mv3.mjs +++ b/test/quality/literal-frame-mv3.mjs @@ -311,7 +311,7 @@ try { if (event.action === 'agent_update' && ownedRuns[event.requestId]) ownedRuns[event.requestId].events.push({ type: event.type, data: event.data }); }); await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', - screenshotFallback: false, autoScreenshot: false, maxAgentSteps: 22, systemOneEnabled: false, tracingEnabled: false, + screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: 22, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }); }); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, diff --git a/test/quality/mastodon-delete-after-correction-mv3.mjs b/test/quality/mastodon-delete-after-correction-mv3.mjs index 2cc6c4df7e..2f91fd7276 100644 --- a/test/quality/mastodon-delete-after-correction-mv3.mjs +++ b/test/quality/mastodon-delete-after-correction-mv3.mjs @@ -260,7 +260,7 @@ try { const message = (action, data = {}) => settings.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await settings.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, userMemoryEnabled: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', - maxAgentSteps: 40, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, + visionMode: 'off', maxAgentSteps: 40, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `${base}/v1`, model: 'minimax/minimax-m3', enabled: true, contextWindow: 1000000, supportsAskStreaming: false, supportsVision: false } })).ok, true); diff --git a/test/quality/mastodon-delete-confirmation-mv3.mjs b/test/quality/mastodon-delete-confirmation-mv3.mjs index 8ef43b060d..e35d38f063 100644 --- a/test/quality/mastodon-delete-confirmation-mv3.mjs +++ b/test/quality/mastodon-delete-confirmation-mv3.mjs @@ -224,7 +224,7 @@ agent._recordCompletionSubmitAttempt = function (...args) { const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/mastodon-deletion-mv3.mjs b/test/quality/mastodon-deletion-mv3.mjs index d7a41951b5..2927f39d48 100644 --- a/test/quality/mastodon-deletion-mv3.mjs +++ b/test/quality/mastodon-deletion-mv3.mjs @@ -154,7 +154,7 @@ agent._recordCompletionSubmitAttempt = function (...args) { const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/mastodon-deletion-navigation-mv3.mjs b/test/quality/mastodon-deletion-navigation-mv3.mjs index 9454c5431b..cadd6eea1a 100644 --- a/test/quality/mastodon-deletion-navigation-mv3.mjs +++ b/test/quality/mastodon-deletion-navigation-mv3.mjs @@ -179,7 +179,7 @@ try { const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/mastodon-publication-mv3.mjs b/test/quality/mastodon-publication-mv3.mjs index 29a2401575..d57e2bf5e1 100644 --- a/test/quality/mastodon-publication-mv3.mjs +++ b/test/quality/mastodon-publication-mv3.mjs @@ -116,7 +116,7 @@ try { const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 10, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 10, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/mastodon-reply-route-mv3.mjs b/test/quality/mastodon-reply-route-mv3.mjs index ba6dfb570b..8b7bf326f3 100644 --- a/test/quality/mastodon-reply-route-mv3.mjs +++ b/test/quality/mastodon-reply-route-mv3.mjs @@ -189,7 +189,7 @@ try { const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/native-chat-mv3.mjs b/test/quality/native-chat-mv3.mjs index acae00089a..967361ee4c 100644 --- a/test/quality/native-chat-mv3.mjs +++ b/test/quality/native-chat-mv3.mjs @@ -280,7 +280,7 @@ try { nativeRuns[event.requestId].events.push({ type: event.type, data: event.data }); }); await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, maxAgentSteps: 40, + planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: 40, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }); }); diff --git a/test/quality/native-chat-presubmit-mv3.mjs b/test/quality/native-chat-presubmit-mv3.mjs index 4bd99e71eb..1526ab3934 100644 --- a/test/quality/native-chat-presubmit-mv3.mjs +++ b/test/quality/native-chat-presubmit-mv3.mjs @@ -402,7 +402,7 @@ try { nativeRuns[event.requestId].events.push({ type: event.type, data: event.data }); }); await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, maxAgentSteps: 40, + planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: 40, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }); }); diff --git a/test/quality/native-chat-soak.mjs b/test/quality/native-chat-soak.mjs index b994ef5ce8..9bb9d65711 100644 --- a/test/quality/native-chat-soak.mjs +++ b/test/quality/native-chat-soak.mjs @@ -180,7 +180,7 @@ try { } }); await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', - screenshotFallback: false, autoScreenshot: false, maxAgentSteps: 30, systemOneEnabled: false, tracingEnabled: false, + screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: 30, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false, scheduledTasksEnabled: true, scheduledRequireConsequentialConfirmation: false }); }); diff --git a/test/quality/open-chat-recipients-mv3.mjs b/test/quality/open-chat-recipients-mv3.mjs index a9a4702a80..90e55003cd 100644 --- a/test/quality/open-chat-recipients-mv3.mjs +++ b/test/quality/open-chat-recipients-mv3.mjs @@ -172,7 +172,7 @@ async function runVariant(variant, request, alsoNamed, steps, cardAnswers, expec const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 20, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 20, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `${base}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/recipient-clarify-mv3.mjs b/test/quality/recipient-clarify-mv3.mjs index 535f8837a8..04e1c017e7 100644 --- a/test/quality/recipient-clarify-mv3.mjs +++ b/test/quality/recipient-clarify-mv3.mjs @@ -183,7 +183,7 @@ async function runVariant(variant, steps, answer, source, cardAnswer, expectedSe const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `${base}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/resolved-address-mv3.mjs b/test/quality/resolved-address-mv3.mjs new file mode 100644 index 0000000000..d87b70b81d --- /dev/null +++ b/test/quality/resolved-address-mv3.mjs @@ -0,0 +1,126 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { chromium } from 'playwright'; + +// Chrome has no DNS API for extensions, so fetch_url, read_page_source and +// research_url rely on webRequest reporting details.ip for the extension's +// own service-worker fetch and its hidden tab. This runs the real Chrome +// network tools in a disposable browser whose resolver maps a public-looking +// name onto this loopback server, the DNS answer the URL text cannot reveal. +const root = path.resolve(process.env.WEBBRAIN_TEST_ROOT || '.'); +const out = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-resolved-address-')); +const extension = path.join(out, 'extension'); +const profile = path.join(out, 'profile'); +const copied = new Set(); +async function copy(relative) { + if (copied.has(relative)) return; + copied.add(relative); + const bytes = await fs.readFile(path.join(root, 'src/chrome', relative)); + const dest = path.join(extension, relative); + await fs.mkdir(path.dirname(dest), { recursive: true }); + await fs.writeFile(dest, bytes); + for (const m of bytes.toString().matchAll(/^import\s+(?:[\s\S]*?)\sfrom\s+['"]([^'"]+)['"];?/gm)) { + await copy(path.posix.normalize(path.posix.join(path.posix.dirname(relative), m[1]))); + } +} +await copy('src/network/network-tools.js'); +await fs.writeFile(path.join(extension, 'manifest.json'), JSON.stringify({ + manifest_version: 3, name: 'Resolved address fixture', version: '1.0', + permissions: ['storage', 'tabs', 'scripting', 'webRequest'], host_permissions: [''], + background: { service_worker: 'src/background.js', type: 'module' }, +})); +await fs.writeFile(path.join(extension, 'src/background.js'), + "import * as network from './network/network-tools.js'; globalThis.network = network;"); + +const secret = 'LOOPBACK-ADMIN-SECRET'; +const hits = []; +let port; +const server = http.createServer((req, res) => { + hits.push(req.url); + if (req.url === '/redirect') { + res.writeHead(302, { Location: `http://public.rebind.test:${port}/admin` }); + return res.end(); + } + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(`Admin
${secret}
`); +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +port = server.address().port; + +let browser; +let chrome; +const rows = []; +try { + chrome = spawn(chromium.executablePath(), [ + '--headless=new', '--no-sandbox', '--no-first-run', '--no-default-browser-check', + '--disable-background-networking', '--no-proxy-server', `--user-data-dir=${profile}`, + '--remote-debugging-port=0', `--disable-extensions-except=${extension}`, `--load-extension=${extension}`, + '--host-resolver-rules=MAP public.rebind.test 127.0.0.1, MAP * ~NOTFOUND, EXCLUDE localhost, EXCLUDE 127.0.0.1', + 'about:blank', + ], { windowsHide: true, stdio: 'ignore' }); + let endpoint; + for (let n = 0; n < 100 && !endpoint; n++) { + try { + const [p, u] = (await fs.readFile(path.join(profile, 'DevToolsActivePort'), 'utf8')).trim().split(/\r?\n/); + endpoint = `ws://127.0.0.1:${p}${u}`; + } catch { await new Promise(r => setTimeout(r, 100)); } + } + assert.ok(endpoint, 'disposable browser endpoint'); + browser = await chromium.connectOverCDP(endpoint); + const context = browser.contexts()[0]; + const worker = context.serviceWorkers().find(w => w.url().endsWith('/src/background.js')) + || await context.waitForEvent('serviceworker', { predicate: w => w.url().endsWith('/src/background.js') }); + for (let n = 0; n < 100 && !(await worker.evaluate(() => Boolean(globalThis.network))); n++) { + await new Promise(r => setTimeout(r, 100)); + } + + const admin = `http://public.rebind.test:${port}/admin`; + const run = (tool, url) => worker.evaluate(({ tool, url }) => ( + tool === 'fetch_url' ? network.fetchUrl(url) + : tool === 'read_page_source' ? network.readPageSource(url) + : network.researchUrl(url, { timeout: 10000 }) + ), { tool, url }); + const openTabs = () => worker.evaluate(() => chrome.tabs.query({}).then(tabs => tabs.length)); + const tabsBefore = await openTabs(); + + for (const [tool, url] of [ + ['fetch_url', admin], + ['read_page_source', admin], + ['research_url', admin], + ['research_url', `http://public.rebind.test:${port}/redirect`], + ]) { + const before = hits.length; + const result = await run(tool, url); + rows.push({ tool, url, allowLocalNetwork: false, success: result.success, error: result.error, requests: hits.slice(before) }); + assert.equal(result.success, false, `${tool} ${url}: a name resolving to loopback must be blocked`); + assert.match(result.error, /^public\.rebind\.test resolved to a blocked address\. Blocked loopback IPv4: 127\.0\.0\.1/); + assert.doesNotMatch(JSON.stringify(result), new RegExp(secret), `${tool}: loopback content must not be returned`); + } + assert.equal(await openTabs(), tabsBefore, 'research_url must close its hidden tab'); + + // The user's local-network opt-in relaxes the resolved address as it does + // a loopback literal. + await worker.evaluate(() => chrome.storage.local.set({ agentAllowLocalNetwork: true })); + for (let n = 0; n < 50 && !(await worker.evaluate(() => network.getAllowLocalNetwork())); n++) { + await new Promise(r => setTimeout(r, 50)); + } + for (const tool of ['fetch_url', 'read_page_source', 'research_url']) { + const result = await run(tool, admin); + rows.push({ tool, url: admin, allowLocalNetwork: true, success: result.success, error: result.error }); + assert.equal(result.success, true, `${tool}: local-network access should permit loopback (${result.error || ''})`); + assert.match(JSON.stringify(result), new RegExp(secret), `${tool}: permitted content should be returned`); + } + console.log(JSON.stringify({ passed: true, chrome: browser.version(), rows }, null, 2)); +} catch (error) { + console.log(JSON.stringify({ passed: false, error: String(error.stack || error), rows }, null, 2)); + process.exitCode = 1; +} finally { + await browser?.close().catch(() => {}); + if (chrome && !chrome.killed) chrome.kill(); + await new Promise(resolve => server.close(resolve)); + await fs.rm(out, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }).catch(() => {}); +} diff --git a/test/quality/shared-action-guards-mv3.mjs b/test/quality/shared-action-guards-mv3.mjs index e5464b1f44..06231e8e57 100644 --- a/test/quality/shared-action-guards-mv3.mjs +++ b/test/quality/shared-action-guards-mv3.mjs @@ -485,7 +485,7 @@ try { panel = await context.newPage(); await panel.goto(`chrome-extension://${new URL(worker.url()).host}/src/ui/sidepanel.html`); const message = (action, data = {}) => settings.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await settings.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, userMemoryEnabled: false, tracingEnabled: false, - autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', maxAgentSteps: 24, + autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 24, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-key', baseUrl: `${localOrigin}/v1`, model: 'minimax/minimax-m3', enabled: true, contextWindow: 1000000, supportsAskStreaming: false, supportsVision: false } })).ok, true); diff --git a/test/quality/steering-worker-restart-mv3.mjs b/test/quality/steering-worker-restart-mv3.mjs index faaa9640da..01ba64d7d1 100644 --- a/test/quality/steering-worker-restart-mv3.mjs +++ b/test/quality/steering-worker-restart-mv3.mjs @@ -113,7 +113,7 @@ try { const send = (page, action, data = {}) => page.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await settings.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', - planBeforeAct: false, planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, maxAgentSteps: 10, + planBeforeAct: false, planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: 10, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false, contextWindowMode: 'full' })); assert.equal((await send(settings, 'update_provider', { providerId: 'openrouter', config: { diff --git a/test/quality/telegram-cold-preparation-mv3.mjs b/test/quality/telegram-cold-preparation-mv3.mjs index 2b1e61bca6..8a3e1e87bb 100644 --- a/test/quality/telegram-cold-preparation-mv3.mjs +++ b/test/quality/telegram-cold-preparation-mv3.mjs @@ -173,7 +173,7 @@ try { chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await settings.evaluate(async () => chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, - maxAgentSteps: 10, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, + visionMode: 'off', maxAgentSteps: 10, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false, contextWindowMode: 'full' })); assert.equal((await messageFrom(settings, 'update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-loopback-fake-key', baseUrl: `${origin}/v1`, model: 'openai/gpt-5.4-mini', diff --git a/test/quality/unbound-deletion-mv3.mjs b/test/quality/unbound-deletion-mv3.mjs index 6d3db028f3..cd3acf4bf0 100644 --- a/test/quality/unbound-deletion-mv3.mjs +++ b/test/quality/unbound-deletion-mv3.mjs @@ -175,7 +175,7 @@ async function runVariant(variant, confirmation, { task, evidence, target, kept, const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true, diff --git a/test/quality/upload-release-binding-mv3.mjs b/test/quality/upload-release-binding-mv3.mjs index 65915d28f0..6136e301d4 100644 --- a/test/quality/upload-release-binding-mv3.mjs +++ b/test/quality/upload-release-binding-mv3.mjs @@ -130,7 +130,7 @@ try { const harness = await context.newPage(); await harness.goto(`chrome-extension://${new URL(worker.url()).host}/src/ui/settings.html`); const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planReviewMode: 'never', - screenshotFallback: false, autoScreenshot: false, maxAgentSteps: 18, systemOneEnabled: false, tracingEnabled: false, + screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: 18, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-key', baseUrl: `${base}/v1`, model: 'minimax/minimax-m3', enabled: true, contextWindow: 1000000, supportsAskStreaming: false } })).ok, true); diff --git a/test/quality/video-upload-attachment-mv3.mjs b/test/quality/video-upload-attachment-mv3.mjs index 0afdd9c26f..e746b83ced 100644 --- a/test/quality/video-upload-attachment-mv3.mjs +++ b/test/quality/video-upload-attachment-mv3.mjs @@ -90,7 +90,7 @@ try { chrome.runtime.onMessage.addListener(e => { if (e.action === 'agent_update') events.push({ type: e.type, data: e.data }); }); await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planReviewMode: 'never', screenshotFallback: false, autoScreenshot: false, - maxAgentSteps: 15, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, + visionMode: 'off', maxAgentSteps: 15, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false, }); }); diff --git a/test/quality/vision-mode-delete-mv3.mjs b/test/quality/vision-mode-delete-mv3.mjs new file mode 100644 index 0000000000..2dd4be5960 --- /dev/null +++ b/test/quality/vision-mode-delete-mv3.mjs @@ -0,0 +1,212 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { chromium } from 'playwright'; +import { defaultDecide, fixtureFixedChoiceReply } from '../semantic-decision-stub.mjs'; + +// A deletion in vision mode, end to end in the installed MV3 extension. In a +// vision run every click is a click_at point, and WebBrain's deletion guard +// used to refuse any coordinate click ("Activate the specific control with a +// ref or selector click") although a vision run offers no ref, selector or +// tree tool: a user's "delete this note" could never be carried out. The +// background, Agent, submit probe, guards, CDP capture and trusted input are +// real; a loopback provider plays the model, reads the frame labels and +// clicks the note's Delete button and then the site's own confirmation. +// node test/quality/vision-mode-delete-mv3.mjs the request names the note +// node test/quality/vision-mode-delete-mv3.mjs --vague "delete it": WebBrain's card asks once +const vague = process.argv.includes('--vague'); +const out = path.resolve(process.env.WEBBRAIN_QUALITY_ARTIFACTS || 'ci/artifacts/vision-mode-delete-mv3'); +await fs.mkdir(out, { recursive: true }); + +const NOTES = [ + { id: 'n1', text: 'Buy oat milk' }, + { id: 'n2', text: 'Call the dentist on Monday' }, + { id: 'n3', text: 'Pick up dry cleaning' }, +]; +// Absolute positions keep the fixture's CSS geometry known to the "model". +const row = index => ({ x: 60, y: 100 + index * 70, w: 520, h: 56 }); +const LAYOUT = { + deleteButton: index => ({ x: 60 + 420, y: 100 + index * 70 + 10, w: 90, h: 36 }), + dialog: { x: 380, y: 260, w: 420, h: 200 }, + confirm: { x: 380 + 290, y: 260 + 140, w: 110, h: 40 }, + cancel: { x: 380 + 170, y: 260 + 140, w: 100, h: 40 }, +}; +const target = 0; +const request = vague ? 'delete it' : `Delete my note "${NOTES[target].text}".`; +const body = `My notes + +

My notes

    ${NOTES.map((note, index) => { + const box = row(index); + return `
  • ${note.text}

  • `; +}).join('')}
+`; + +const intent = { request_kind: 'execute', scope_relation: 'new', requires_state_change: true, + requires_submission: true, messaging: null, deliverables: ['The note is deleted.'], + allows_planner_shaped_result: false, allows_app_state_tool_evidence: false, + completion_requirements: { download: false }, read_scope: 'visible_page', + summary: 'Delete the note.', steps: [{ id: '1', action: 'Delete the note and confirm.' }], + memory: { use_progress_ledger: false, progress_action: null }, scheduling: null, risks: [] }; + +const providerCalls = []; +const deletes = []; +const offered = []; +let keyframe = null; +let actionCalls = 0; +const centre = (rect, image) => ({ + x: Math.round((rect.x + rect.w / 2) / image.ratio), + y: Math.round((rect.y + rect.h / 2) / image.ratio), +}); +const textOf = content => typeof content === 'string' ? content : Array.isArray(content) + ? content.filter(part => part?.type === 'text').map(part => part.text || '').join('\n') : ''; + +const server = http.createServer(async (incoming, response) => { + const deleted = /^\/api\/notes\/(n\d)$/.exec(incoming.url || '')?.[1]; + if (deleted && incoming.method === 'DELETE') { + deletes.push(deleted); + response.writeHead(200, { 'Content-Type': 'application/json' }); response.end('{"ok":true}'); return; + } + if (incoming.url === '/v1/chat/completions') { + let text = ''; for await (const chunk of incoming) text += chunk; + const input = JSON.parse(text); providerCalls.push(input); + const isAction = Array.isArray(input.tools) && input.tools.length > 0; + const system = textOf(input.messages?.[0]?.content); + // The deletion question is answered as a model would read the request. + const fixedChoice = fixtureFixedChoiceReply(input.messages, { + deletion_request: ({ request: asked, page }) => defaultDecide('deletion_request', { request: asked, page }), + }); + let completion; + if (fixedChoice) completion = { role: 'assistant', content: fixedChoice }; + else if (system.startsWith('Evaluate only the observable requirements of the genuine user task')) { + completion = { role: 'assistant', content: JSON.stringify({ outcome: 'succeeded', reason: 'The note is no longer listed.' }) }; + } else if (!isAction) completion = { role: 'assistant', content: JSON.stringify(intent) }; + else { + offered.push(input.tools.map(tool => tool.function?.name || tool.name)); + for (const message of input.messages) { + if (!Array.isArray(message.content)) continue; + const label = message.content.filter(block => block.type === 'text').map(block => block.text).join('\n'); + const declared = /SCREENSHOT f\d+[\s\S]*?(\d+)x(\d+) image; 1 image px = ([\d.]+) CSS px/.exec(label); + if (declared) keyframe = { width: Number(declared[1]), height: Number(declared[2]), ratio: Number(declared[3]) }; + } + const step = actionCalls++; + const results = new Map(input.messages.filter(message => message.role === 'tool').map(message => [message.tool_call_id, String(message.content)])); + const clicks = input.messages.filter(message => message.role === 'assistant').flatMap(message => message.tool_calls || []) + .filter(item => item.function.name === 'click_at').map(item => /"success":true/.test(results.get(item.id) || '')); + const done = clicks.filter(Boolean).length; + let call; + if (!keyframe) call = { name: 'take_screenshot', args: {} }; + // A refused click is not retried blindly: the run ends and the test reads why. + else if (clicks.length > done) call = { name: 'done', args: { outcome: 'blocked', summary: 'A click was refused.' } }; + else if (done === 0) call = { name: 'click_at', args: centre(LAYOUT.deleteButton(target), keyframe) }; + else if (done === 1) call = { name: 'click_at', args: centre(LAYOUT.confirm, keyframe) }; + else call = { name: 'done', args: { outcome: 'success', summary: 'The note was deleted.' } }; + completion = { role: 'assistant', content: '', tool_calls: [{ id: `vision-delete-${step}`, type: 'function', + function: { name: call.name, arguments: JSON.stringify(call.args) } }] }; + } + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ id: `completion-${providerCalls.length}`, choices: [{ message: completion, + finish_reason: completion.tool_calls ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 100, completion_tokens: 20 } })); + return; + } + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + response.end(body); +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const url = `http://127.0.0.1:${server.address().port}/notes`; +const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-vision-delete-mv3-')); +let context; +try { + // A copy of the extension that lets the test answer WebBrain's own card. + const extension = path.join(profile, 'extension'); await fs.cp(path.resolve('src/chrome'), extension, { recursive: true }); + await fs.appendFile(path.join(extension, 'src/background.js'), '\nglobalThis.visionDeleteFixtureAgent = agent;\n'); + context = await chromium.launchPersistentContext(path.join(profile, 'user'), { + headless: true, channel: 'chromium', viewport: null, + args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`, '--window-size=1280,900'], + }); + const worker = context.serviceWorkers()[0] || await context.waitForEvent('serviceworker', { timeout: 30000 }); + const id = new URL(worker.url()).host; + const harness = await context.newPage(); await harness.goto(`chrome-extension://${id}/src/ui/settings.html`); + const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); + // visionMode is deliberately left unset: vision mode is the default. + await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, + planReviewMode: 'never', screenshotFallback: false, autoScreenshot: 'navigation', maxAgentSteps: 10, systemOneEnabled: false, + tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); + assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', + baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'anthropic/claude-sonnet-4.5', contextWindow: 200000, + enabled: true, supportsAskStreaming: false, supportsVision: true } })).ok, true); + assert.equal((await message('set_active_provider', { providerId: 'openrouter' })).ok, true); + const page = await context.newPage(); await page.goto(url); + const tabId = await harness.evaluate(async url => (await chrome.tabs.query({})).find(tab => tab.url === url)?.id, url); + // WebBrain's deletion card is answered "Delete"; any other question would be unexpected. + const cards = [], unexpected = []; + let answering = true; + const answerer = (async () => { + const answered = new Set(); + while (answering) { + const pending = await worker.evaluate(tabId => [...(globalThis.visionDeleteFixtureAgent?._pendingClarifications?.get(tabId)?.keys() || [])], tabId).catch(() => []); + for (const clarifyId of pending) { + if (answered.has(clarifyId)) continue; + answered.add(clarifyId); + if (!clarifyId.startsWith('deletion_')) { unexpected.push(clarifyId); continue; } + cards.push(clarifyId); + assert.equal((await message('clarify_response', { tabId, clarifyId, answer: 'once', source: 'option' })).ok, true); + } + await new Promise(resolve => setTimeout(resolve, 100)); + } + })(); + const result = await message('chat', { tabId, text: request, mode: 'act', requestId: 'vision-delete-mv3', locale: 'en' }); + answering = false; await answerer; + const remaining = await page.evaluate(() => [...document.querySelectorAll('.note')].map(item => item.dataset.id)); + const blocked = result.updates.filter(event => event.type === 'tool_result' && event.data?.result?.actionGuard) + .map(event => ({ tool: event.data.name, reason: event.data.result.actionGuard.reason, error: String(event.data.result.error || '').slice(0, 300) })); + const prompts = result.updates.filter(event => event.type === 'clarify' && event.data?.promptKind === 'mutationConfirmation') + .map(event => event.data.mutationConfirmation); + await fs.writeFile(path.join(out, `evidence${vague ? '-vague' : ''}.json`), JSON.stringify({ request, result, deletes, remaining, blocked, + cards, prompts, unexpected, offered }, (_key, item) => typeof item === 'string' && item.startsWith('data:image/') ? '[screenshot omitted]' : item, 2)); + + assert.deepEqual(unexpected, [], 'no other question was asked'); + assert.deepEqual(blocked, [], `no step of the deletion was refused: ${JSON.stringify(blocked)}`); + assert.ok(offered.length, 'the model was asked to act'); + for (const tools of offered) { + assert.ok(tools.includes('click_at'), `a vision tool surface: ${tools}`); + for (const name of ['click', 'click_ax', 'get_accessibility_tree']) assert.ok(!tools.includes(name), `${name} not offered`); + } + // A vague request is put to the user once, about this note; the answer also + // covers the site's own confirmation. A request naming the note asks nothing. + assert.equal(cards.length, vague ? 1 : 0, JSON.stringify(prompts)); + if (vague) assert.match(String(prompts[0]?.item || ''), /Buy oat milk/, JSON.stringify(prompts)); + assert.deepEqual(deletes, [NOTES[target].id], 'exactly the note whose Delete opened the confirmation was deleted, once'); + assert.deepEqual(remaining, ['n2', 'n3']); + const done = result.updates.findLast(event => event.type === 'tool_result' && event.data?.name === 'done')?.data?.result; + assert.equal(done?.done, true, JSON.stringify(done)); + assert.equal(done?.outcome, 'success', JSON.stringify(done)); + console.log(JSON.stringify({ passed: true, installedMV3: true, vague, deletes, cards: cards.length, actionCalls })); +} finally { + await context?.close(); await new Promise(resolve => server.close(resolve)); + const resolved = path.resolve(profile); + if (!resolved.startsWith(path.resolve(os.tmpdir()) + path.sep + 'webbrain-vision-delete-mv3-')) throw new Error('Unexpected temporary profile path.'); + await fs.rm(resolved, { recursive: true, force: true }); +} diff --git a/test/quality/vision-mode-mv3.mjs b/test/quality/vision-mode-mv3.mjs new file mode 100644 index 0000000000..4e39c6a976 --- /dev/null +++ b/test/quality/vision-mode-mv3.mjs @@ -0,0 +1,343 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { chromium } from 'playwright'; +import { fixtureFixedChoiceReply } from '../semantic-decision-stub.mjs'; + +// Vision mode end to end in the installed MV3 extension: background, Agent, +// CDP capture and trusted input are real; a loopback provider plays the +// model. It reads each screenshot label, computes image coordinates for the +// fixture's controls and acts with click_at / type_text, so the whole chain +// (DPR-aware capture, model-size image, image → CSS mapping, exact-point +// dispatch, patches) has to be right for the form to be filled and sent. +// node test/quality/vision-mode-mv3.mjs DPR 1 +// node test/quality/vision-mode-mv3.mjs --dpr=2 retina +// node test/quality/vision-mode-mv3.mjs --zoom=1.25 browser zoom 125% +// node test/quality/vision-mode-mv3.mjs --scroll=100 page scrolled 100 CSS px +// Two colored markers (one fixed, one in the document) must appear in the +// first frame exactly where the frame label's scale puts their CSS boxes. +const dpr = Number((process.argv.find(arg => arg.startsWith('--dpr=')) || '--dpr=1').slice(6)) || 1; +const zoom = Number((process.argv.find(arg => arg.startsWith('--zoom=')) || '--zoom=1').slice(7)) || 1; +const scroll = Number((process.argv.find(arg => arg.startsWith('--scroll=')) || '--scroll=0').slice(9)) || 0; +const out = path.resolve(process.env.WEBBRAIN_QUALITY_ARTIFACTS || 'ci/artifacts/vision-mode-mv3'); +await fs.mkdir(out, { recursive: true }); + +// Absolute positions keep the fixture's CSS geometry known to the "model". +const LAYOUT = { + name: { x: 60, y: 140, w: 320, h: 36 }, + submit: { x: 60, y: 220, w: 180, h: 44 }, + // Viewport-fixed and document-positioned markers for the pixel check. + fixedMarker: { x: 700, y: 60, w: 80, h: 40 }, + pageMarker: { x: 600, y: 230, w: 60, h: 50 }, + // A viewport-fixed target=_blank link: the tab it opens is rerouted into + // this tab, as for any click. + link: { x: 60, y: 400, w: 220, h: 32 }, +}; +const body = `Vision MV3 fixture + +
+Open details +

Vision form

+`; + +function imageSize(dataUrl) { + const match = /^data:image\/(webp|jpeg|png);base64,(.+)$/.exec(String(dataUrl || '')); + if (!match) return null; + const bytes = Buffer.from(match[2], 'base64'); + if (match[1] === 'png') return { type: 'png', width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) }; + if (match[1] === 'webp') { + const chunk = bytes.toString('ascii', 12, 16); + if (chunk === 'VP8X') return { type: 'webp', width: 1 + bytes.readUIntLE(24, 3), height: 1 + bytes.readUIntLE(27, 3) }; + if (chunk === 'VP8 ') return { type: 'webp', width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff }; + if (chunk === 'VP8L') { + const bits = bytes.readUInt32LE(21); + return { type: 'webp', width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }; + } + return null; + } + let i = 2; + while (i < bytes.length) { + const marker = bytes[i + 1]; + const length = bytes.readUInt16BE(i + 2); + if (marker >= 0xc0 && marker <= 0xc3) return { type: 'jpeg', height: bytes.readUInt16BE(i + 5), width: bytes.readUInt16BE(i + 7) }; + i += 2 + length; + } + return null; +} + +const providerCalls = []; +const submissions = []; +const frames = []; +let cssViewport = null; +let actionCalls = 0; +let keyframe = null; +// The fixture page, for the scripted model to read the scroll position the +// wheel left before it clicks the link. +let livePage = null; +let scrollBeforeLink = null; +let valueBeforeLink = null; +// The "model" converts the fixture's CSS geometry with the ratio the frame +// label declares, as a model reading the label would. +const centre = (rect, image, { fixed = false } = {}) => ({ + x: Math.round((rect.x + rect.w / 2) / image.ratio), + y: Math.round((rect.y - (fixed ? 0 : scroll) + rect.h / 2) / image.ratio), +}); + +const server = http.createServer(async (request, response) => { + if (request.url === '/submit') { + let text = ''; for await (const chunk of request) text += chunk; + submissions.push(JSON.parse(text)); response.writeHead(200, { 'Content-Type': 'application/json' }); response.end('{"ok":true}'); return; + } + if (request.url === '/v1/chat/completions') { + let text = ''; for await (const chunk of request) text += chunk; + const input = JSON.parse(text); providerCalls.push(input); + const isAction = Array.isArray(input.tools) && input.tools.length > 0; + const fixedChoice = fixtureFixedChoiceReply(input.messages); + let completion; + if (fixedChoice) completion = { role: 'assistant', content: fixedChoice }; + else if (!isAction) completion = { role: 'assistant', content: JSON.stringify({ outcome: 'uncertain', reason: 'Scripted fixture.' }) }; + else { + // Every image the extension sent in this request, with its label. + for (const message of input.messages) { + if (!Array.isArray(message.content)) continue; + const label = message.content.filter(block => block.type === 'text').map(block => block.text).join('\n'); + for (const block of message.content) { + if (block.type !== 'image_url') continue; + const url = block.image_url?.url || block.image_url; + const size = imageSize(url); + const key = /SCREENSHOT (f\d+)/.exec(label)?.[1]; + if (key && !frames.some(frame => frame.id === key)) { + const declared = /(\d+)x(\d+) image; 1 image px = ([\d.]+) CSS px/.exec(label); + frames.push({ id: key, size, declared: declared ? { width: Number(declared[1]), height: Number(declared[2]), ratio: Number(declared[3]) } : null, call: providerCalls.length, ...(frames.length ? {} : { dataUrl: url }) }); + } + } + } + keyframe = frames.at(-1)?.declared || null; + const step = actionCalls++; + // Decide from the history, not a step count: WebBrain may set a + // response aside when the page changed while the model was thinking. + const results = new Map(input.messages.filter(message => message.role === 'tool').map(message => [message.tool_call_id, String(message.content)])); + const pairs = input.messages.filter(message => message.role === 'assistant').flatMap(message => message.tool_calls || []) + .map(item => ({ name: item.function.name, ok: /"success":true/.test(results.get(item.id) || '') })); + const typedAt = pairs.findLastIndex(pair => pair.name === 'type_text' && pair.ok); + const submitted = typedAt >= 0 && pairs.slice(typedAt + 1).some(pair => pair.name === 'click_at' && pair.ok); + const scrolled = pairs.some(pair => pair.name === 'scroll_at' && pair.ok); + const clicked = pairs.filter(pair => pair.name === 'click_at' && pair.ok).length; + let call; + if (!keyframe) call = { name: 'take_screenshot', args: {} }; + else if (typedAt < 0) { + const last = pairs.at(-1); + call = last?.name === 'click_at' && last.ok + ? { name: 'type_text', args: { text: 'Vision QA' } } + : [{ name: 'click_at', args: centre(LAYOUT.name, keyframe) }, { name: 'type_text', args: { text: 'Vision QA' } }]; + } else if (!submitted) call = { name: 'click_at', args: centre(LAYOUT.submit, keyframe) }; + // A wheel at the middle of the screen while the ticker keeps changing. + else if (!scrolled) call = { name: 'scroll_at', args: { direction: 'down', amount: 3, x: Math.round(keyframe.width / 2), y: Math.round(keyframe.height / 2) } }; + else if (clicked < 3) { + scrollBeforeLink ??= await livePage?.evaluate(() => window.scrollY).catch(() => null); + valueBeforeLink ??= await livePage?.evaluate(() => document.getElementById('name').value).catch(() => null); + call = { name: 'click_at', args: centre(LAYOUT.link, keyframe, { fixed: true }) }; + } + else call = { name: 'done', args: { summary: 'The name was sent.', outcome: 'success' } }; + completion = { role: 'assistant', content: '', tool_calls: [call].flat().map((item, index) => ({ id: `vision-${step}-${index}`, type: 'function', function: { name: item.name, arguments: JSON.stringify(item.args) } })) }; + } + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ id: `completion-${providerCalls.length}`, choices: [{ message: completion, finish_reason: isAction ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 100, completion_tokens: 20 } })); + return; + } + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + response.end(request.url === '/details' ? 'Details

Details page

' : body); +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const url = `http://127.0.0.1:${server.address().port}/form`; +const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-vision-mv3-')); +let context; +try { + const extension = path.resolve('src/chrome'); + // No viewport emulation: --force-device-scale-factor is how a retina + // screen looks to Chrome (page DPR and compositor scale agree). + context = await chromium.launchPersistentContext(profile, { + headless: true, channel: 'chromium', viewport: null, + args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`, `--force-device-scale-factor=${dpr}`, '--window-size=1280,900'], + }); + const worker = context.serviceWorkers()[0] || await context.waitForEvent('serviceworker', { timeout: 30000 }); + const id = new URL(worker.url()).host; + const harness = await context.newPage(); await harness.goto(`chrome-extension://${id}/src/ui/settings.html`); + const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); + await harness.evaluate(async () => { + window.events = []; + chrome.runtime.onMessage.addListener(event => { if (event.action === 'agent_update') events.push({ type: event.type, data: event.data }); }); + // visionMode is deliberately left unset: vision mode is the default. + await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', screenshotFallback: false, autoScreenshot: 'navigation', maxAgentSteps: 12, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false, leanMode: 'on' }); + }); + assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'anthropic/claude-sonnet-4.5', contextWindow: 200000, enabled: true, supportsAskStreaming: false, supportsVision: true } })).ok, true); + assert.equal((await message('set_active_provider', { providerId: 'openrouter' })).ok, true); + const page = await context.newPage(); await page.goto(url); + livePage = page; + const tabId = await harness.evaluate(async url => (await chrome.tabs.query({})).find(tab => tab.url === url)?.id, url); + if (zoom !== 1) { + await harness.evaluate(async ({ tabId, zoom }) => chrome.tabs.setZoom(tabId, zoom), { tabId, zoom }); + await page.waitForFunction(expected => Math.abs(window.devicePixelRatio - expected) < 0.05, dpr * zoom); + } + if (scroll) { + await page.evaluate(y => window.scrollTo(0, y), scroll); + await page.waitForFunction(y => Math.abs(window.scrollY - y) < 1, scroll); + } + // What the scripted model knows about the screen: its CSS size. + cssViewport = await page.evaluate(() => ({ width: document.documentElement.clientWidth, height: document.documentElement.clientHeight, dpr: devicePixelRatio, scrollY: window.scrollY })); + const started = performance.now(); + const result = await message('chat', { tabId, text: 'Type Vision QA into the Name field and press Send name.', mode: 'act', requestId: 'vision-mv3', locale: 'en' }); + const elapsedMs = Math.round(performance.now() - started); + const events = await harness.evaluate(() => events); + // The form page is gone once the link was followed: its field as it was + // right before that click. + const value = valueBeforeLink; + const finalUrl = page.url(); + const webPages = context.pages().filter(item => /^http/.test(item.url())).map(item => item.url()); + await fs.writeFile(path.join(out, `evidence-dpr${dpr}-zoom${zoom}-scroll${scroll}.json`), JSON.stringify({ result, value, submissions, frames, cssViewport, elapsedMs, events, providerCalls }, + (_key, item) => typeof item === 'string' && item.startsWith('data:image/') ? `[image ${JSON.stringify(imageSize(item))}]` : item, 2)); + + const actionRequests = providerCalls.filter(call => Array.isArray(call.tools) && call.tools.length); + const tools = actionRequests[0]?.tools.map(tool => tool.function.name) || []; + for (const name of ['click_at', 'type_text', 'scroll_at', 'zoom', 'take_screenshot']) assert.ok(tools.includes(name), `${name} offered: ${tools}`); + for (const name of ['get_accessibility_tree', 'click_ax', 'set_field', 'click']) assert.ok(!tools.includes(name), `${name} not offered`); + assert.ok(frames.length >= 1, 'the model received a full frame'); + const first = frames[0]; + assert.equal(first.id, 'f1'); + assert.ok(first.declared, 'the frame label declares its size'); + assert.deepEqual({ width: first.size.width, height: first.size.height }, { width: first.declared.width, height: first.declared.height }, + 'the image the model receives has exactly the declared size'); + assert.equal(first.size.type, 'webp', 'Anthropic-family models get WebP'); + // Never device pixels: at most one image px per CSS px. + assert.ok(first.size.width <= cssViewport.width, `image ${first.size.width}px for a ${cssViewport.width}px CSS viewport at DPR ${cssViewport.dpr}`); + // The pixels show the page where the label's scale says: each marker's box + // in the image, times the declared CSS px per image px, is its CSS box in + // the viewport (browser zoom and scrolling included). + const boxes = await page.evaluate(async dataUrl => { + const bitmap = await createImageBitmap(await (await fetch(dataUrl)).blob()); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext('2d'); + context.drawImage(bitmap, 0, 0); + const { data, width, height } = context.getImageData(0, 0, bitmap.width, bitmap.height); + const find = test => { + let x0 = Infinity, y0 = Infinity, x1 = -1, y1 = -1; + for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) { + const i = (y * width + x) * 4; + if (test(data[i], data[i + 1], data[i + 2])) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); } + } + return x1 < 0 ? null : { x0, y0, x1: x1 + 1, y1: y1 + 1 }; + }; + return { + fixed: find((r, g, b) => r > 200 && g < 90 && b > 200), + page: find((r, g, b) => r < 90 && g > 200 && b > 200), + }; + }, first.dataUrl); + const ratio = first.declared.ratio; + for (const [key, rect, offsetY] of [['fixed', LAYOUT.fixedMarker, 0], ['page', LAYOUT.pageMarker, cssViewport.scrollY]]) { + const box = boxes[key]; + assert.ok(box, `${key} marker visible in f1`); + const css = { x0: box.x0 * ratio, y0: box.y0 * ratio, x1: box.x1 * ratio, y1: box.y1 * ratio }; + // Clipped to the viewport (at 150% zoom it is only 853 CSS px wide). + const expected = { + x0: Math.max(0, rect.x), y0: Math.max(0, rect.y - offsetY), + x1: Math.min(cssViewport.width, rect.x + rect.w), y1: Math.min(cssViewport.height, rect.y - offsetY + rect.h), + }; + for (const side of ['x0', 'y0', 'x1', 'y1']) { + assert.ok(Math.abs(css[side] - expected[side]) <= 3, `${key} marker ${side}: image says CSS ${css[side].toFixed(1)}, page has ${expected[side]} (${JSON.stringify({ box, ratio, cssViewport })})`); + } + } + assert.equal(value, 'Vision QA', `the click focused the field and typing reached it: ${JSON.stringify(result).slice(0, 600)}`); + assert.equal(submissions.length, 1, JSON.stringify(events.filter(event => event.type === 'tool_result').map(event => event.data), null, 1).slice(0, 3000)); + assert.deepEqual(submissions[0], { name: 'Vision QA' }); + // The model-facing click results (tool messages) name the exact-point path. + const toolResults = actionRequests.at(-1).messages.filter(message => message.role === 'tool').map(message => String(message.content)); + const clickResults = toolResults.filter(text => /"method":"cdp-vision-pointer"/.test(text)); + assert.ok(clickResults.length >= 2, toolResults.join('\n').slice(0, 2000)); + // click_at + type_text in one response: the typing went into the field the + // click focused although the page reacted to that focus (the hint) and kept + // changing (the ticker). + const typeResults = actionRequests.flatMap(request => request.messages) + .filter(message => message.role === 'tool' && /vision-\d+-1$/.test(message.tool_call_id || '')); + const firstType = typeResults[0] ? String(typeResults[0].content) : ''; + assert.match(firstType, /"success":true/, `type_text after click_at in the same response: ${firstType.slice(0, 400)}`); + // No accessibility-tree text reaches a vision run's model. + for (const request of actionRequests) { + const text = JSON.stringify(request.messages.map(message => (Array.isArray(message.content) + ? message.content.filter(block => block.type === 'text') : message.content))); + assert.doesNotMatch(text, /pageContent|\[BROWSER STATE: current page observed/, 'tree text in a vision request'); + } + // scroll_at under the same churn: dispatched on the first try, and the page + // moved by about the three wheel notches asked for. + const history = actionRequests.at(-1).messages; + const scrollIds = history.filter(message => message.role === 'assistant').flatMap(message => message.tool_calls || []) + .filter(item => item.function.name === 'scroll_at').map(item => item.id); + const firstScroll = String(history.find(message => message.role === 'tool' && message.tool_call_id === scrollIds[0])?.content || ''); + assert.match(firstScroll, /"success":true/, `scroll_at during page churn: ${firstScroll.slice(0, 400)}`); + assert.ok(scrollBeforeLink - cssViewport.scrollY >= 150, `the wheel scrolled the page (${cssViewport.scrollY} -> ${scrollBeforeLink})`); + // The link's new tab became this tab's page: one web page, now /details. + assert.match(finalUrl, /\/details$/, `the tab the link opened was rerouted into the run's tab (${finalUrl})`); + assert.deepEqual(webPages, [finalUrl], `no extra tab is left open: ${JSON.stringify(webPages)}`); + const linkResult = String(history.find(message => message.role === 'tool' && /"redirectedFromNewTab":true/.test(String(message.content)))?.content || ''); + assert.ok(linkResult, 'the click result says the new tab was rerouted'); + // Churn did not make WebBrain throw decisions away: click+type, send, + // scroll, link, done. + assert.ok(actionRequests.length <= 6, `${actionRequests.length} model calls`); + // Until the link navigates: one screen update per step, and no browser- + // state message. The ticker and the caret never changed the screen by more + // than a micro change between an update and the next decision. + const beforeLink = actionRequests.slice(0, 4); + const updatesIn = request => request.messages.filter(message => Array.isArray(message.content) + && message.content.some(block => block.type === 'text' && /UNTRUSTED SCREEN UPDATE|UNTRUSTED SCREENSHOT f\d+|no visible change/.test(block.text))).length; + for (let index = 1; index < beforeLink.length; index++) { + assert.equal(updatesIn(beforeLink[index]) - updatesIn(beforeLink[index - 1]), 1, `one screen update before decision ${index + 1}`); + } + for (const request of beforeLink) { + assert.doesNotMatch(JSON.stringify(request.messages), /\[BROWSER STATE UPDATE/, 'page churn alone sends no browser-state message'); + } + // The pre-dispatch probe saw the real button although the page replaced + // elementFromPoint in its own world. + assert.ok(clickResults.some(text => /"target":\{"tag":"button"\}/.test(text)), clickResults.join('\n')); + // After the first frame the model got patches or "no visible change", not + // a new full frame per action. + const laterImages = actionRequests.slice(1).flatMap(call => call.messages.filter(message => Array.isArray(message.content)) + .map(message => message.content.filter(block => block.type === 'text').map(block => block.text).join('\n'))); + assert.ok(laterImages.some(text => /UNTRUSTED SCREEN UPDATE|no visible change/.test(text)), 'incremental updates followed the first frame'); + // Pruning: every image in the last request belongs to the current frame + // (the last full frame and the patches after it); older ones are placeholders. + const lastRequest = actionRequests.at(-1); + const labelOf = message => (Array.isArray(message.content) ? message.content.filter(block => block.type === 'text').map(block => block.text).join('\n') : ''); + const lastFrameAt = lastRequest.messages.findLastIndex(message => /UNTRUSTED SCREENSHOT f\d+/.test(labelOf(message)) + && message.content.some(block => block.type === 'image_url')); + assert.ok(lastFrameAt >= 0, 'the current frame is in the request'); + const olderImages = lastRequest.messages.slice(0, lastFrameAt) + .flatMap(message => (Array.isArray(message.content) ? message.content : [])).filter(block => block.type === 'image_url').length; + assert.equal(olderImages, 0, 'images before the current frame were pruned'); + console.log(JSON.stringify({ passed: true, dpr, zoom, scroll, cssViewport, firstFrame: { ...first, dataUrl: undefined }, markers: boxes, frames: frames.length, actionRequests: actionRequests.length, submitted: submissions.length, elapsedMs })); +} finally { + await context?.close(); await new Promise(resolve => server.close(resolve)); + const resolved = path.resolve(profile); + if (!resolved.startsWith(path.resolve(os.tmpdir()) + path.sep + 'webbrain-vision-mv3-')) throw new Error('Unexpected temporary profile path.'); + await fs.rm(resolved, { recursive: true, force: true }); +} diff --git a/test/quality/vision-mode-repeat-mv3.mjs b/test/quality/vision-mode-repeat-mv3.mjs new file mode 100644 index 0000000000..1fb3c45403 --- /dev/null +++ b/test/quality/vision-mode-repeat-mv3.mjs @@ -0,0 +1,120 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { chromium } from 'playwright'; +import { fixtureFixedChoiceReply } from '../semantic-decision-stub.mjs'; + +// The same point clicked again and again in vision mode, end to end in the +// installed MV3 extension. Loop detection used to count every click_at at one +// point and stop the run at the eighth ("the page never responded") although +// each click visibly changed the screen, and a DOM text snapshot called a +// click on a canvas a failure. Here the model presses a "+" button ten times +// (the counter it changes is drawn on a canvas, so the DOM text never moves), +// then a dead button below it: the ten presses all go out, and the dead +// button is stopped once its clicks keep leaving the screen unchanged. +const out = path.resolve(process.env.WEBBRAIN_QUALITY_ARTIFACTS || 'ci/artifacts/vision-mode-repeat-mv3'); +await fs.mkdir(out, { recursive: true }); +const LAYOUT = { + plus: { x: 60, y: 120, w: 80, h: 48 }, + dead: { x: 60, y: 260, w: 160, h: 40 }, +}; +const PRESSES = 10; +const body = `Counter + +

Counter

+ +`; + +const providerCalls = []; +let presses = 0; +let keyframe = null; +let actionCalls = 0; +const centre = (rect, image) => ({ x: Math.round((rect.x + rect.w / 2) / image.ratio), y: Math.round((rect.y + rect.h / 2) / image.ratio) }); +const server = http.createServer(async (incoming, response) => { + if (incoming.url === '/press') { presses++; response.writeHead(204); response.end(); return; } + if (incoming.url === '/v1/chat/completions') { + let text = ''; for await (const chunk of incoming) text += chunk; + const input = JSON.parse(text); providerCalls.push(input); + const isAction = Array.isArray(input.tools) && input.tools.length > 0; + const fixedChoice = fixtureFixedChoiceReply(input.messages); + let completion; + if (fixedChoice) completion = { role: 'assistant', content: fixedChoice }; + else if (!isAction) completion = { role: 'assistant', content: JSON.stringify({ outcome: 'uncertain', reason: 'Scripted fixture.' }) }; + else { + for (const message of input.messages) { + if (!Array.isArray(message.content)) continue; + const label = message.content.filter(block => block.type === 'text').map(block => block.text).join('\n'); + const declared = /SCREENSHOT f\d+[\s\S]*?(\d+)x(\d+) image; 1 image px = ([\d.]+) CSS px/.exec(label); + if (declared) keyframe = { width: Number(declared[1]), height: Number(declared[2]), ratio: Number(declared[3]) }; + } + const step = actionCalls++; + const results = new Map(input.messages.filter(message => message.role === 'tool').map(message => [message.tool_call_id, String(message.content)])); + const clicks = input.messages.filter(message => message.role === 'assistant').flatMap(message => message.tool_calls || []) + .filter(item => item.function.name === 'click_at').map(item => ({ ok: /"success":true/.test(results.get(item.id) || ''), result: results.get(item.id) || '' })); + const pressed = clicks.filter(click => click.ok).length; + let call; + if (!keyframe) call = { name: 'take_screenshot', args: {} }; + else if (pressed < PRESSES) call = { name: 'click_at', args: centre(LAYOUT.plus, keyframe) }; + // Then the dead button, until WebBrain stops the run. + else call = { name: 'click_at', args: centre(LAYOUT.dead, keyframe) }; + completion = { role: 'assistant', content: '', tool_calls: [{ id: `vision-repeat-${step}`, type: 'function', function: { name: call.name, arguments: JSON.stringify(call.args) } }] }; + } + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ id: `completion-${providerCalls.length}`, choices: [{ message: completion, finish_reason: completion.tool_calls ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 100, completion_tokens: 20 } })); + return; + } + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + response.end(body); +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const url = `http://127.0.0.1:${server.address().port}/counter`; +const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-vision-repeat-mv3-')); +let context; +try { + const extension = path.resolve('src/chrome'); + context = await chromium.launchPersistentContext(profile, { + headless: true, channel: 'chromium', viewport: null, + args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`, '--window-size=1280,900'], + }); + const worker = context.serviceWorkers()[0] || await context.waitForEvent('serviceworker', { timeout: 30000 }); + const id = new URL(worker.url()).host; + const harness = await context.newPage(); await harness.goto(`chrome-extension://${id}/src/ui/settings.html`); + const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); + await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, + planReviewMode: 'never', screenshotFallback: false, autoScreenshot: 'navigation', maxAgentSteps: 30, systemOneEnabled: false, + tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false })); + assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', + baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'anthropic/claude-sonnet-4.5', contextWindow: 200000, + enabled: true, supportsAskStreaming: false, supportsVision: true } })).ok, true); + assert.equal((await message('set_active_provider', { providerId: 'openrouter' })).ok, true); + const page = await context.newPage(); await page.goto(url); + const tabId = await harness.evaluate(async url => (await chrome.tabs.query({})).find(tab => tab.url === url)?.id, url); + const result = await message('chat', { tabId, text: `Press the + button ${PRESSES} times.`, mode: 'act', requestId: 'vision-repeat-mv3', locale: 'en' }); + const blocked = result.updates.filter(event => event.type === 'tool_result' && event.data?.result?.success === false) + .map(event => ({ tool: event.data.name, error: String(event.data.result.error || '').slice(0, 200) })); + await fs.writeFile(path.join(out, 'evidence.json'), JSON.stringify({ result, presses, blocked, actionCalls }, + (_key, item) => typeof item === 'string' && item.startsWith('data:image/') ? '[screenshot omitted]' : item, 2)); + // The model moves on to the dead button only after ten successful presses. + assert.equal(presses, PRESSES, `every press went out: ${presses}; ${JSON.stringify(blocked).slice(0, 800)}`); + const finalText = String(result.response || result.text || result.finalResponse || JSON.stringify(result.updates.filter(event => event.type === 'text').at(-1)?.data || '')); + // The dead button is stopped by the loop guard, with the model's own point. + assert.match(finalText, /in the screenshot several times and the screen did not change/, finalText.slice(0, 600)); + const deadClicks = actionCalls - PRESSES - 1; + assert.ok(deadClicks <= 9, `the dead button was stopped after ${deadClicks} clicks`); + console.log(JSON.stringify({ passed: true, installedMV3: true, presses, deadClicks, actionCalls })); +} finally { + await context?.close(); await new Promise(resolve => server.close(resolve)); + const resolved = path.resolve(profile); + if (!resolved.startsWith(path.resolve(os.tmpdir()) + path.sep + 'webbrain-vision-repeat-mv3-')) throw new Error('Unexpected temporary profile path.'); + await fs.rm(resolved, { recursive: true, force: true }); +} diff --git a/test/quality/vision-mode-upload-mv3.mjs b/test/quality/vision-mode-upload-mv3.mjs new file mode 100644 index 0000000000..6bc0660404 --- /dev/null +++ b/test/quality/vision-mode-upload-mv3.mjs @@ -0,0 +1,163 @@ +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { chromium } from 'playwright'; +import { fixtureFixedChoiceReply } from '../semantic-decision-stub.mjs'; + +// A file upload in a vision run, end to end in the installed MV3 extension: +// background, Agent, CDP capture, trusted input and the file-chooser guard are +// real; a loopback provider plays the model. Its click_at lands on a native +// file input, the guard stops the chooser, the next step gets the element +// tools and attaches the user's video with upload_file, and the step after +// that is back on screenshots, on a fresh full frame. +// node test/quality/vision-mode-upload-mv3.mjs +const out = path.resolve(process.env.WEBBRAIN_QUALITY_ARTIFACTS || 'ci/artifacts/vision-mode-upload-mv3'); +await fs.mkdir(out, { recursive: true }); + +const mp4 = Buffer.concat([Buffer.from([0, 0, 0, 24]), Buffer.from('ftypmp42'), Buffer.alloc(4), Buffer.from('mp42isom')]); +const sha = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); +const LAYOUT = { upload: { x: 60, y: 140, w: 360, h: 48 } }; +const body = `Vision upload fixture + +

Video upload

+`; + +const providerCalls = []; +let actionCalls = 0; +const labelOf = message => (Array.isArray(message.content) ? message.content.filter(block => block.type === 'text').map(block => block.text).join('\n') : ''); +const centre = (rect, frame) => ({ x: Math.round((rect.x + rect.w / 2) / frame.ratio), y: Math.round((rect.y + rect.h / 2) / frame.ratio) }); + +const server = http.createServer(async (request, response) => { + if (request.url === '/v1/chat/completions') { + let text = ''; for await (const chunk of request) text += chunk; + const input = JSON.parse(text); providerCalls.push(input); + const isAction = Array.isArray(input.tools) && input.tools.length > 0; + const judge = String(input.messages?.[0]?.content || '').startsWith('Evaluate only the observable requirements of the genuine user task'); + const fixedChoice = fixtureFixedChoiceReply(input.messages); + let completion; + if (fixedChoice) completion = { role: 'assistant', content: fixedChoice }; + else if (judge) completion = { role: 'assistant', content: JSON.stringify({ outcome: 'uncertain', reason: 'Scripted fixture.' }) }; + else if (!isAction) { + completion = { role: 'assistant', content: JSON.stringify({ + request_kind: 'execute', scope_relation: 'new', deliverables: ['Attach the uploaded video to the page input'], + requires_state_change: true, requires_submission: false, messaging: null, + completion_requirements: { download: false }, allows_planner_shaped_result: false, allows_app_state_tool_evidence: false, + read_scope: 'visible_page', summary: 'Attach the uploaded video clip to the QA video input.', + steps: [{ id: '1', action: 'Attach the video to the QA video input.' }], + memory: { use_progress_ledger: false, progress_action: null }, scheduling: null, risks: [], + }) }; + } else { + const offered = input.tools.map(tool => tool.function.name); + // The current full frame, as a model reading its label would size it. + const frameMessage = input.messages.findLast(message => /UNTRUSTED SCREENSHOT f\d+/.test(labelOf(message)) && message.content.some(block => block.type === 'image_url')); + const declared = frameMessage && /(\d+)x(\d+) image; 1 image px = ([\d.]+) CSS px/.exec(labelOf(frameMessage)); + const frame = declared ? { width: Number(declared[1]), height: Number(declared[2]), ratio: Number(declared[3]) } : null; + const results = new Map(input.messages.filter(message => message.role === 'tool').map(message => [message.tool_call_id, String(message.content)])); + const pairs = input.messages.filter(message => message.role === 'assistant').flatMap(message => message.tool_calls || []) + .map(item => ({ name: item.function.name, text: results.get(item.id) || '' })); + const blocked = pairs.find(pair => pair.name === 'click_at' && /"filePickerBlocked":true/.test(pair.text)); + const uploaded = pairs.some(pair => pair.name === 'upload_file' && /"success":true/.test(pair.text)); + const attachmentId = JSON.stringify(input.messages).match(/attachment_[A-Za-z0-9]+_\d+(?= \(clip\.mp4\))/)?.[0]; + let call; + if (offered.includes('upload_file') && blocked && !uploaded) { + call = { name: 'upload_file', args: { selector: /"selector":"((?:[^"\\]|\\.)+)"/.exec(blocked.text)?.[1]?.replace(/\\"/g, '"') || '#upload', attachmentId } }; + } else if (offered.includes('click_at') && !blocked && frame) call = { name: 'click_at', args: centre(LAYOUT.upload, frame) }; + else if (offered.includes('take_screenshot') && !frame) call = { name: 'take_screenshot', args: {} }; + else call = { name: 'done', args: { summary: 'The clip was attached to the QA video input.', outcome: 'success' } }; + const step = actionCalls++; + completion = { role: 'assistant', content: '', tool_calls: [{ id: `vision-upload-${step}`, type: 'function', function: { name: call.name, arguments: JSON.stringify(call.args) } }] }; + } + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ id: `completion-${providerCalls.length}`, choices: [{ message: completion, finish_reason: isAction ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 100, completion_tokens: 20 } })); + return; + } + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + response.end(body); +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const base = `http://127.0.0.1:${server.address().port}`; +const url = `${base}/upload`; +const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-vision-upload-mv3-')); +let context; +try { + const extension = path.resolve('src/chrome'); + context = await chromium.launchPersistentContext(profile, { + headless: true, channel: 'chromium', viewport: null, + args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`, '--window-size=1280,900'], + }); + const worker = context.serviceWorkers()[0] || await context.waitForEvent('serviceworker', { timeout: 30000 }); + const id = new URL(worker.url()).host; + const harness = await context.newPage(); await harness.goto(`chrome-extension://${id}/src/ui/settings.html`); + const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data }); + await harness.evaluate(async () => { + window.events = []; + chrome.runtime.onMessage.addListener(event => { if (event.action === 'agent_update') events.push({ type: event.type, data: event.data }); }); + // visionMode is deliberately left unset: vision mode is the default. + await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', screenshotFallback: false, autoScreenshot: 'navigation', maxAgentSteps: 12, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false, leanMode: 'on' }); + }); + assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', baseUrl: `${base}/v1`, model: 'anthropic/claude-sonnet-4.5', contextWindow: 200000, enabled: true, supportsAskStreaming: false, supportsVision: true } })).ok, true); + assert.equal((await message('set_active_provider', { providerId: 'openrouter' })).ok, true); + const page = await context.newPage(); await page.goto(url); + const tabId = await harness.evaluate(async url => (await chrome.tabs.query({})).find(tab => tab.url === url)?.id, url); + assert.ok(Number.isInteger(tabId), 'the fixture tab is known'); + const result = await message('chat', { + tabId, text: 'Attach the clip I uploaded to the QA video input.', mode: 'act', requestId: 'vision-upload-mv3', locale: 'en', + attachments: [{ kind: 'video', name: 'clip.mp4', dataUrl: `data:video/mp4;base64,${mp4.toString('base64')}`, mimeType: 'video/mp4', size: mp4.length }], + }); + const events = await harness.evaluate(() => events); + const nativeAttachments = await page.evaluate(() => window.nativeAttachments); + await fs.writeFile(path.join(out, 'evidence.json'), JSON.stringify({ result, events, nativeAttachments, providerCalls }, + (_key, item) => typeof item === 'string' && item.startsWith('data:image/') ? `[image ${item.length} chars]` : item, 2)); + + const actionRequests = providerCalls.filter(call => Array.isArray(call.tools) && call.tools.length); + const offered = actionRequests.map(call => call.tools.map(tool => tool.function.name)); + const toolTexts = request => request.messages.filter(item => item.role === 'tool').map(item => String(item.content)); + const summary = JSON.stringify({ offered: offered.map(names => (names.includes('click_at') ? 'vision' : names.includes('upload_file') ? 'tree' : names.join(','))), tools: (result.updates || []).filter(event => event.type === 'tool_result').map(event => ({ name: event.data?.name, result: JSON.stringify(event.data?.result).slice(0, 300) })) }, null, 1); + assert.ok(offered[0]?.includes('click_at') && !offered[0].includes('upload_file'), `the run starts on screenshots: ${summary}`); + const handoffAt = offered.findIndex(names => names.includes('upload_file')); + assert.ok(handoffAt > 0, `a later step offers upload_file: ${summary}`); + assert.ok(!offered[handoffAt].includes('click_at'), 'the handoff step is on the element tools'); + // The real CDP click reached the file input and the guard stopped its chooser. + const blocked = toolTexts(actionRequests[handoffAt]).find(text => /"filePickerBlocked":true/.test(text)) || ''; + assert.match(blocked, /"uploadHandoff":true/, blocked); + assert.match(blocked, /"dispatched":true/, blocked); + assert.match(blocked, /"selector":"[^"]+"/, `the guard named the input: ${blocked}`); + const uploads = (result.updates || []).filter(event => event.type === 'tool_result' && event.data?.name === 'upload_file'); + assert.equal(uploads.length, 1, summary); + assert.equal(uploads[0].data.result.success, true, JSON.stringify(uploads[0].data.result)); + assert.deepEqual(nativeAttachments, [{ name: 'clip.mp4', size: mp4.length, mime: 'video/mp4', sha256: sha(mp4) }], 'the page input received the exact bytes once'); + // The step after the upload is back on screenshots, on a fresh full frame. + const backAt = offered.findIndex((names, index) => index > handoffAt && names.includes('click_at')); + assert.ok(backAt > handoffAt, `vision resumed after the upload: ${summary}`); + assert.ok(!offered[backAt].includes('upload_file')); + const back = actionRequests[backAt]; + const frameAt = back.messages.findLastIndex(item => /UNTRUSTED SCREENSHOT f\d+/.test(labelOf(item)) && item.content.some(block => block.type === 'image_url')); + assert.ok(frameAt >= 0, 'the resumed step has a full frame'); + const frameLabel = labelOf(back.messages[frameAt]); + assert.match(frameLabel, /\(vision resumed\)/, frameLabel); + assert.notEqual(/SCREENSHOT (f\d+)/.exec(frameLabel)[1], 'f1'); + assert.ok(back.messages.slice(frameAt + 1).every(item => !/UNTRUSTED SCREEN/.test(labelOf(item))), 'the fresh frame is the latest screen'); + const olderImages = back.messages.slice(0, frameAt).flatMap(item => (Array.isArray(item.content) ? item.content : [])).filter(block => block.type === 'image_url').length; + assert.equal(olderImages, 0, 'screenshots from before the handoff left the request'); + assert.equal(events.findLast(event => event.type === 'run_complete')?.data?.status, 'completed', summary); + assert.equal(JSON.stringify(providerCalls).includes(mp4.toString('base64')), false, 'the video bytes never reach the model'); + console.log(JSON.stringify({ passed: true, offered: offered.map(names => (names.includes('click_at') ? 'vision' : 'tree')), frame: /SCREENSHOT (f\d+)/.exec(frameLabel)[1], attachment: nativeAttachments[0] })); +} finally { + await context?.close(); await new Promise(resolve => server.close(resolve)); + const resolved = path.resolve(profile); + if (!resolved.startsWith(path.resolve(os.tmpdir()) + path.sep + 'webbrain-vision-upload-mv3-')) throw new Error('Unexpected temporary profile path.'); + await fs.rm(resolved, { recursive: true, force: true }); +} diff --git a/test/quality/whatsapp-contact-mv3.mjs b/test/quality/whatsapp-contact-mv3.mjs index 9410ae07d1..d81bf9fb5f 100644 --- a/test/quality/whatsapp-contact-mv3.mjs +++ b/test/quality/whatsapp-contact-mv3.mjs @@ -643,7 +643,7 @@ for (const [object, name, doneOnly] of [[agent, '_executeToolImpl', true], [agen await harness.evaluate(async scenario => { window.qaRun = { finished: false, events: [] }; chrome.runtime.onMessage.addListener(event => { if (event.action === 'agent_update' && event.requestId === 'owned-wa-contact') qaRun.events.push({ type: event.type, data: event.data }); }); await chrome.storage.local.set({ helpImproveWebBrain: false, planBeforeActMode: 'off', planBeforeAct: false, planReviewMode: 'never', - screenshotFallback: false, autoScreenshot: false, maxAgentSteps: scenario === 'postwrite_debt' ? 32 : scenario === 'bootstrap_native' ? 28 : 20, systemOneEnabled: false, tracingEnabled: false, + screenshotFallback: false, autoScreenshot: false, visionMode: 'off', maxAgentSteps: scenario === 'postwrite_debt' ? 32 : scenario === 'bootstrap_native' ? 28 : 20, systemOneEnabled: false, tracingEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false, ...(scenario === 'postwrite_debt' ? { onboardingComplete: true, pinCoachmarkPending: false } : {}) }); }, scenario); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', diff --git a/test/quality/x-compose-dialog-mv3.mjs b/test/quality/x-compose-dialog-mv3.mjs index e627174c29..ec2f0fc891 100644 --- a/test/quality/x-compose-dialog-mv3.mjs +++ b/test/quality/x-compose-dialog-mv3.mjs @@ -364,7 +364,7 @@ try { }); return chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false, autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false, - planReviewMode: 'never', maxAgentSteps: 12, systemOneEnabled: false, agentAllowLocalNetwork: true, + planReviewMode: 'never', visionMode: 'off', maxAgentSteps: 12, systemOneEnabled: false, agentAllowLocalNetwork: true, askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }); }); assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key', diff --git a/test/run.js b/test/run.js index bcf6dc51fe..84827fc61b 100644 --- a/test/run.js +++ b/test/run.js @@ -401,10 +401,10 @@ const { transcribeAudio } = await import( // network-tools.js references chrome.* inside a try/catch at module load, so // it imports cleanly under Node — the storage init silently no-ops and // validateFetchUrl / registrableDomain are pure functions. -const { validateFetchUrl, registrableDomain, filenameFromContentDisposition: filenameFromContentDispositionCh, fetchUrl: fetchUrlCh, researchUrl: researchUrlCh, downloadFiles: downloadFilesCh, downloadResourceFromPage: downloadResourceFromPageCh, executeHttpSkillTool: executeHttpSkillToolCh } = await import( +const { validateFetchUrl, validateResolvedAddress: validateResolvedAddressCh, registrableDomain, filenameFromContentDisposition: filenameFromContentDispositionCh, fetchUrl: fetchUrlCh, readPageSource: readPageSourceCh, researchUrl: researchUrlCh, downloadFiles: downloadFilesCh, downloadResourceFromPage: downloadResourceFromPageCh, executeHttpSkillTool: executeHttpSkillToolCh } = await import( 'file://' + path.join(ROOT, 'src/chrome/src/network/network-tools.js').replace(/\\/g, '/') ); -const { validateFetchUrl: validateFetchUrlFx, registrableDomain: registrableDomainFx, filenameFromContentDisposition: filenameFromContentDispositionFx, fetchUrl: fetchUrlFx, readPageSource: readPageSourceFx, researchUrl: researchUrlFx, downloadFiles: downloadFilesFx, downloadResourceFromPage: downloadResourceFromPageFx, executeHttpSkillTool: executeHttpSkillToolFx } = await import( +const { validateFetchUrl: validateFetchUrlFx, validateResolvedAddress: validateResolvedAddressFx, registrableDomain: registrableDomainFx, filenameFromContentDisposition: filenameFromContentDispositionFx, fetchUrl: fetchUrlFx, readPageSource: readPageSourceFx, researchUrl: researchUrlFx, downloadFiles: downloadFilesFx, downloadResourceFromPage: downloadResourceFromPageFx, executeHttpSkillTool: executeHttpSkillToolFx } = await import( 'file://' + path.join(ROOT, 'src/firefox/src/network/network-tools.js').replace(/\\/g, '/') ); const { firefoxRestrictedDomainForUrl, firefoxRestrictedDomainFailure, firefoxHostPermissionFailure } = await import( @@ -22762,6 +22762,264 @@ test('research_url rejects blocked redirect targets before returning hidden-tab } }); +test('resolved addresses use the same tiers as URL literals in both ports', () => { + const cases = [ + ['127.0.0.1', false, false], ['127.0.0.1', true, true], + ['10.0.0.5', false, false], ['10.0.0.5', true, true], + ['172.16.0.1', false, false], ['192.168.1.1', false, false], ['192.168.1.1', true, true], + ['169.254.169.254', true, false], ['100.64.0.1', true, false], + ['0.0.0.0', true, false], ['224.0.0.1', true, false], + ['::1', false, false], ['::1', true, true], ['[::1]', false, false], + ['fd00::1', false, false], ['fd00::1', true, true], ['fe80::1', true, false], + ['::ffff:127.0.0.1', false, false], ['::ffff:7f00:1', false, false], + ['::ffff:169.254.169.254', true, false], ['::ffff:8.8.8.8', false, true], + ['93.184.216.34', false, true], ['2606:4700::6810:84e5', false, true], + ['', true, false], ['example.com', true, false], + ]; + for (const [label, validate] of [['chrome', validateResolvedAddressCh], ['firefox', validateResolvedAddressFx]]) { + for (const [address, allowLocal, ok] of cases) { + assert.equal(validate(address, { allowLocalNetwork: allowLocal }).ok, ok, + `${label}: ${address || '(empty)'} (allowLocal=${allowLocal}) should ${ok ? 'pass' : 'be blocked'}`); + } + } +}); + +// webRequest stand-in for the resolved-address checks. Events respect the +// tabId/types filter the production listener registers with. +function makeAddressWebRequest() { + const listeners = {}; + const api = {}; + for (const name of ['onBeforeRedirect', 'onResponseStarted', 'onErrorOccurred']) { + listeners[name] = new Map(); + api[name] = { + addListener: (fn, filter) => listeners[name].set(fn, filter || {}), + removeListener: fn => listeners[name].delete(fn), + }; + } + return { + api, + emit(name, details) { + for (const [fn, filter] of [...listeners[name]]) { + if (filter.tabId != null && filter.tabId !== details.tabId) continue; + if (filter.types && !filter.types.includes(details.type)) continue; + fn(details); + } + }, + count: () => Object.values(listeners).reduce((sum, map) => sum + map.size, 0), + }; +} + +test('fetch_url and read_page_source discard responses from a blocked resolved address', async () => { + const previousFetch = globalThis.fetch; + const previousChrome = globalThis.chrome; + const previousBrowser = globalThis.browser; + const secret = 'INTERNAL-ADMIN-SECRET'; + try { + for (const [label, apiName, fetchUrl, readPageSource] of [ + ['chrome', 'chrome', fetchUrlCh, readPageSourceCh], + ['firefox', 'browser', fetchUrlFx, readPageSourceFx], + ]) { + for (const tool of ['fetch_url', 'read_page_source']) { + for (const [ip, proxyInfo, blocked] of [ + ['127.0.0.1', null, true], + ['::ffff:a9fe:a9fe', null, true], + ['10.1.2.3', null, true], + ['93.184.216.34', null, false], + // Firefox reports the proxy's address for proxied requests; only its + // DNS check before sending applies there. + ...(apiName === 'browser' ? [['127.0.0.1', { type: 'http', host: '127.0.0.1', port: 8080 }, false]] : []), + ]) { + const webRequest = makeAddressWebRequest(); + globalThis[apiName] = { webRequest: webRequest.api }; + const url = 'https://rebind.example/admin#section'; + let fetchCalls = 0; + globalThis.fetch = async (rawUrl) => { + fetchCalls++; + // The webRequest event can arrive after fetch() resolves. + setTimeout(() => webRequest.emit('onResponseStarted', { + url: 'https://rebind.example/admin', tabId: -1, type: 'xmlhttprequest', ip, proxyInfo, + }), 5); + return { + status: 200, + url: String(rawUrl).replace(/#.*$/, ''), + headers: new Headers({ 'content-type': 'text/html' }), + text: async () => `admin${secret}`, + }; + }; + const result = tool === 'fetch_url' ? await fetchUrl(url) : await readPageSource(url); + const name = `${label}/${tool}/${ip}${proxyInfo ? '/proxied' : ''}`; + assert.equal(fetchCalls, 1, `${name}: request should be sent once`); + assert.equal(webRequest.count(), 0, `${name}: webRequest listeners must be removed`); + if (blocked) { + assert.equal(result.success, false, `${name}: blocked address must fail`); + assert.match(result.error || '', /^rebind\.example resolved to a blocked address\. Blocked /, `${name}: unexpected error`); + assert.doesNotMatch(JSON.stringify(result), new RegExp(secret), `${name}: body must be discarded`); + } else { + assert.equal(result.success, true, `${name}: public address must pass (${result.error || ''})`); + assert.match(JSON.stringify(result), new RegExp(secret), `${name}: body should be returned`); + } + } + } + } + } finally { + globalThis.fetch = previousFetch; + if (previousChrome === undefined) delete globalThis.chrome; + else globalThis.chrome = previousChrome; + if (previousBrowser === undefined) delete globalThis.browser; + else globalThis.browser = previousBrowser; + } +}); + +test('Firefox network readers refuse hostnames that resolve to blocked addresses before sending', async () => { + const previousFetch = globalThis.fetch; + const previousBrowser = globalThis.browser; + try { + for (const [addresses, blocked] of [ + [['93.184.216.34', '10.0.0.7'], true], + [['2606:4700::6810:84e5', 'fd12::1'], true], + [['169.254.169.254'], true], + [['93.184.216.34', '2606:4700::6810:84e5'], false], + [new Error('NS_ERROR_UNKNOWN_HOST'), false], + ]) { + let fetchCalls = 0; + let tabsCreated = 0; + const resolved = []; + globalThis.fetch = async (rawUrl) => { + fetchCalls++; + return { + status: 200, + url: String(rawUrl), + headers: new Headers({ 'content-type': 'text/html' }), + text: async () => 'okpublic body', + }; + }; + globalThis.browser = { + dns: { + async resolve(host) { + resolved.push(host); + if (addresses instanceof Error) throw addresses; + return { addresses, isTRR: false }; + }, + }, + tabs: { + async create() { tabsCreated++; throw new Error('stop after the pre-check'); }, + async remove() {}, + }, + }; + const name = addresses instanceof Error ? 'lookup failure' : addresses.join(','); + const results = [ + await fetchUrlFx('https://rebind.example/data'), + await readPageSourceFx('https://rebind.example/data'), + await researchUrlFx('https://rebind.example/data'), + ]; + assert.deepEqual(resolved, ['rebind.example', 'rebind.example', 'rebind.example'], `${name}: each tool should resolve the hostname`); + if (blocked) { + for (const result of results) { + assert.equal(result.success, false, `${name}: must be refused`); + assert.match(result.error || '', /rebind\.example resolved to a blocked address\. Blocked /, `${name}: unexpected error`); + } + assert.equal(fetchCalls, 0, `${name}: nothing may be sent`); + assert.equal(tabsCreated, 0, `${name}: no hidden tab may be opened`); + } else { + assert.equal(results[0].success, true, `${name}: fetch_url should proceed (${results[0].error || ''})`); + assert.equal(results[1].success, true, `${name}: read_page_source should proceed (${results[1].error || ''})`); + assert.equal(fetchCalls, 2, `${name}: both fetches should be sent`); + assert.equal(tabsCreated, 1, `${name}: research_url should open its hidden tab`); + } + } + + // IP literals are classified by the URL check and are never looked up. + const resolved = []; + globalThis.browser = { dns: { async resolve(host) { resolved.push(host); return { addresses: [] }; } } }; + globalThis.fetch = async (rawUrl) => ({ + status: 200, url: String(rawUrl), headers: new Headers({ 'content-type': 'text/plain' }), text: async () => 'ok', + }); + await fetchUrlFx('https://93.184.216.34/'); + await fetchUrlFx('https://[2606:4700::6810:84e5]/'); + assert.deepEqual(resolved, []); + } finally { + globalThis.fetch = previousFetch; + if (previousBrowser === undefined) delete globalThis.browser; + else globalThis.browser = previousBrowser; + } +}); + +test('research_url discards a hidden tab whose top-level response came from a blocked address', async () => { + const previousChrome = globalThis.chrome; + const previousBrowser = globalThis.browser; + const previousSetTimeout = globalThis.setTimeout; + const nativeSetTimeout = previousSetTimeout; + // Skip the intentional 800 ms SPA hydration pause, as the redirect test does. + globalThis.setTimeout = (fn, ms, ...args) => nativeSetTimeout(fn, ms === 800 ? 0 : ms, ...args); + const publicUrl = 'https://public.example/start'; + try { + for (const [label, researchUrl, apiName] of [ + ['chrome', researchUrlCh, 'chrome'], + ['firefox', researchUrlFx, 'browser'], + ]) { + for (const scenario of ['response', 'redirect-hop', 'during-extraction', 'other-tab', 'public']) { + const webRequest = makeAddressWebRequest(); + let executeCalls = 0; + let removeCalls = 0; + const mainFrame = (name, tabId, ip, url = publicUrl) => + webRequest.emit(name, { url, tabId, type: 'main_frame', ip, proxyInfo: null }); + const tabs = { + async create() { + // Navigation events start before tabs.create() resolves. + if (scenario === 'redirect-hop') mainFrame('onBeforeRedirect', 77, '192.168.0.10', 'https://hop.example/'); + if (scenario === 'other-tab') mainFrame('onResponseStarted', 12, '127.0.0.1'); + mainFrame('onResponseStarted', 77, scenario === 'response' ? '127.0.0.1' : '93.184.216.34'); + return { id: 77, url: publicUrl }; + }, + async get() { return { id: 77, url: publicUrl }; }, + async remove() { removeCalls++; }, + onUpdated: { + addListener(fn) { nativeSetTimeout(() => fn(77, { status: 'complete' }), 0); }, + removeListener() {}, + }, + }; + const pageResult = { title: 'page', url: publicUrl, text: 'hidden tab text', originalLength: 15, links: [] }; + const extract = () => { + executeCalls++; + if (scenario === 'during-extraction') mainFrame('onResponseStarted', 77, '169.254.169.254', 'https://public.example/next'); + }; + if (apiName === 'chrome') { + globalThis.chrome = { + tabs, + webRequest: webRequest.api, + scripting: { async executeScript() { extract(); return [{ result: pageResult }]; } }, + }; + } else { + globalThis.browser = { + webRequest: webRequest.api, + tabs: { ...tabs, async executeScript() { extract(); return [pageResult]; } }, + }; + } + + const result = await researchUrl(publicUrl, { timeout: 1000 }); + const name = `${label}/${scenario}`; + assert.equal(removeCalls, 1, `${name}: hidden tab should always be closed`); + assert.equal(webRequest.count(), 0, `${name}: webRequest listeners must be removed`); + if (scenario === 'public' || scenario === 'other-tab') { + assert.equal(result.success, true, `${name}: public address must pass (${result.error || ''})`); + assert.equal(result.text, 'hidden tab text'); + continue; + } + assert.equal(result.success, false, `${name}: blocked address must fail`); + assert.match(result.error || '', /resolved to a blocked address\. Blocked /, `${name}: unexpected error`); + assert.equal(result.text, undefined, `${name}: page text must not be returned`); + assert.equal(executeCalls, scenario === 'during-extraction' ? 1 : 0, `${name}: extraction timing mismatch`); + } + } + } finally { + globalThis.setTimeout = previousSetTimeout; + if (previousChrome === undefined) delete globalThis.chrome; + else globalThis.chrome = previousChrome; + if (previousBrowser === undefined) delete globalThis.browser; + else globalThis.browser = previousBrowser; + } +}); + test('firefox port validator agrees with chrome on a sample of cases', () => { // Sanity check that the two ports stay in sync. Pick one case from each // category — full coverage runs against the chrome copy above. @@ -42876,6 +43134,13 @@ test('sidepanel exposes schedule slash commands in both builds', () => { assert.equal(pick('See https://en.wikipedia.org/wiki/Function_(mathematics) daily.'), 'https://en.wikipedia.org/wiki/Function_(mathematics)', `${label}: a bracket that closes one inside the address stays`); assert.equal(pick('(see https://en.wikipedia.org/wiki/Function_(mathematics)).'), 'https://en.wikipedia.org/wiki/Function_(mathematics)', `${label}: prose punctuation after a balanced address is dropped`); assert.equal(pick('Check [https://example.com/a].'), 'https://example.com/a'); + assert.equal(pick('Check “https://webbrain.one” daily.'), 'https://webbrain.one', `${label}: a closing curly quote never reaches the host`); + for (const [open, close] of [['“', '”'], ['‘', '’'], ['«', '»'], ['»', '«'], ['„', '“'], ['「', '」'], ['『', '』'], ['(', ')']]) { + assert.equal(pick(`毎日${open}https://example.com/a${close}を確認。`), 'https://example.com/a', `${label}: ${open}…${close} stays outside the address`); + } + assert.equal(pick('Check https://example.com/a。次に報告'), 'https://example.com/a', `${label}: CJK punctuation ends the address`); + assert.equal(pick('Check https://example.com/a…'), 'https://example.com/a'); + assert.equal(pick('Check “https://en.wikipedia.org/wiki/Function_(mathematics)”.'), 'https://en.wikipedia.org/wiki/Function_(mathematics)', `${label}: balanced brackets survive inside quotes`); } assert.match(panel, /targetType\.value = 'url'/, `${label}: schedule form should default http(s) pages to URL targets`); assert.match(panel, /content\.appendChild\(form\)/, `${label}: schedule form should append after initial target defaults are applied`); @@ -57763,8 +58028,8 @@ test('sidepanel long replies use reading-first turn navigation', () => { ); assert.equal( (clarifySource.match(/scrollToBottom\(\{ force: true \}\);/g) || []).length, - 8, - `${label}: workflow healing, submit, recipient, deletion, video-length, unverified-step, permission, and clarify prompts should override reading-first scroll suppression`, + 9, + `${label}: workflow healing, submit, recipient, deletion, video-length, download-read, unverified-step, permission, and clarify prompts should override reading-first scroll suppression`, ); assert.match( panel, @@ -82763,6 +83028,72 @@ for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) { } } +for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) { + for (const { name, stored, storageError, sitePrompt } of [ + { name: 'an install without the marker keeps the earlier waiver', stored: {}, sitePrompt: false }, + { name: 'the new-install marker keeps the site prompt', stored: { apiMutationSitePrompt: true }, sitePrompt: true }, + { name: 'a malformed marker keeps the site prompt', stored: { apiMutationSitePrompt: 'false' }, sitePrompt: true }, + { name: 'a storage read failure keeps the site prompt', storageError: true, sitePrompt: true }, + ]) { + test(`${label} API mutation site prompt startup: ${name}`, async () => { + const source = fs.readFileSync(path.join(ROOT, `src/${label}/src/background.js`), 'utf8'); + const start = source.indexOf('const ALWAYS_ALLOW_API_MUTATIONS_KEY ='); + const end = source.indexOf('agent.setConversationScopeChangeListener(', start); + const agent = new AgentClass({}); + const api = { + storage: { + local: { + get: async (defaults) => { + if (storageError) throw new Error('Storage unavailable'); + return { ...defaults, ...stored }; + }, + }, + }, + }; + const ready = vm.runInNewContext( + `${source.slice(start, end)}\nalwaysAllowApiMutationsReady;`, + { agent, [label === 'chrome' ? 'chrome' : 'browser']: api }, + ); + const tabId = 4897; + assert.equal(agent.isApiMutationPromptWaived(tabId), false, 'nothing is waived before storage hydration'); + await ready; + assert.equal(agent.apiMutationSitePrompt, sitePrompt); + assert.equal(agent.isApiMutationPromptWaived(tabId), !storageError && !sitePrompt); + }); + } +} + +test('a new install keeps the per-site prompt for default-on API mutations; updates are not migrated', async () => { + for (const [label, apiName, AgentClass] of [['chrome', 'chrome', AgentCh], ['firefox', 'browser', AgentFx]]) { + const bg = fs.readFileSync(path.join(ROOT, `src/${label}/src/background.js`), 'utf8'); + const start = bg.indexOf('// Always allow API mutations is on by default, so leaving it on'); + const marker = ` ${apiName}.storage.local.set({ apiMutationSitePrompt: true }).catch(() => {});\n});\n`; + const end = bg.indexOf(marker, start); + assert.ok(start > -1 && end > start, `${label}: install marker block not found`); + for (const reason of ['install', 'update', `${apiName}_update`]) { + const stored = reason === 'install' ? {} : { alwaysAllowApiMutations: true }; + const before = structuredClone(stored); + let onInstalled = null; + const api = { + runtime: { onInstalled: { addListener: (listener) => { onInstalled = listener; } } }, + storage: { local: { set: async (values) => { Object.assign(stored, values); } } }, + }; + vm.runInNewContext(bg.slice(start, end + marker.length), { [apiName]: api }); + onInstalled({ reason }); + await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(stored, reason === 'install' ? { apiMutationSitePrompt: true } : before, `${label}: ${reason}`); + } + const onChanged = bg.match(/if \(changes\.apiMutationSitePrompt\) \{[\s\S]*?\n \}/)?.[0]; + assert.ok(onChanged, `${label}: live marker changes are not applied`); + for (const [newValue, expected] of [[true, true], [undefined, false], [false, false]]) { + const agent = new AgentClass({}); + agent.setApiMutationSitePrompt(!expected); + vm.runInNewContext(onChanged, { agent, changes: { apiMutationSitePrompt: { newValue } } }); + assert.equal(agent.apiMutationSitePrompt, expected, `${label}: live change to ${newValue}`); + } + } +}); + test('persistent API mutation permission is global and independent of /allow-api lifecycle', () => { for (const AgentClass of [AgentCh, AgentFx]) { const agent = new AgentClass({}); @@ -83813,6 +84144,112 @@ test('iframe submit without urlFilter fails before confirmation or dispatch', as } }); +// A coordinate click, type_text without a selector and press_keys go to the +// document under the point or with focus. On Chrome (CDP) that can be an +// embedded wallet frame, so a grant for the merchant page must not cover it. +function receivingFrameGateAgent(AgentClass, tabId, { frameUrls = [], choice = 'deny' } = {}) { + const agent = new AgentClass({ getVisionProvider: async () => null }); + const state = { executed: [], prompts: [], resolved: [] }; + agent._ensureGateSetting = async () => false; + agent._skipPermissionGate = false; + agent._currentUrl = async () => 'https://merchant.example/checkout'; + agent._recordProgressObservation = async () => null; + agent._autoRecordProgressAction = () => null; + agent._progressWarningForAction = () => ''; + agent._persist = () => { }; + agent._detectLikelySubmitAction = async () => null; + agent._iframeRectsForCoordinate = async () => []; + agent.permissions.hydrate = async () => { }; + // The merchant page itself is already allowed for every capability. + agent.permissions.check = host => host === 'merchant.example' + ? { allowed: true, needsPrompt: false } + : { allowed: false, needsPrompt: true }; + agent.permissions.record = async () => { }; + agent._promptPermission = async (_tabId, capability, host) => { + state.prompts.push({ capability, host }); + return choice; + }; + agent._inputReceivingFrameUrl = async (_tabId, name) => { + state.resolved.push(name); + return frameUrls.length > 1 ? frameUrls.shift() : frameUrls[0]; + }; + agent.executeTool = async (_tabId, name) => { + state.executed.push(name); + return { success: true }; + }; + return { agent, state }; +} + +const RECEIVING_FRAME_CALLS = [ + ['click', { x: 120, y: 80, coordinate_space: 'css' }, 'click'], + ['type_text', { text: '4242 4242 4242 4242' }, 'type'], + ['press_keys', { key: 'Enter' }, 'click'], +]; + +test('Chrome point and focus input is charged to the embedded frame it reaches', async () => { + for (const [name, args, capability] of RECEIVING_FRAME_CALLS) { + const { agent, state } = receivingFrameGateAgent(AgentCh, 5121, { frameUrls: ['https://wallet.example/pay'] }); + const messages = []; + await agent._executeToolBatch(5121, [{ id: `frame_${name}`, function: { name, arguments: JSON.stringify(args) } }], + messages, () => { }, { supportsVision: false }, '', new Set([name]), 1); + assert.deepEqual(state.resolved, [name], `${name}: the receiving frame was not resolved before the gate`); + assert.deepEqual(state.prompts, [{ capability, host: 'wallet.example' }], `${name}: the merchant grant covered the wallet frame`); + assert.deepEqual(state.executed, [], `${name}: input reached the wallet frame without its permission`); + assert.match(JSON.parse(messages[0].content).error, /denied permission to .* wallet\.example/, name); + } +}); + +test('Chrome point and focus input stays on the page grant while it reaches the top document', async () => { + for (const [name, args] of RECEIVING_FRAME_CALLS) { + const { agent, state } = receivingFrameGateAgent(AgentCh, 5122, { frameUrls: ['https://merchant.example/checkout'] }); + await agent._executeToolBatch(5122, [{ id: `top_${name}`, function: { name, arguments: JSON.stringify(args) } }], + [], () => { }, { supportsVision: false }, '', new Set([name]), 1); + assert.deepEqual(state.prompts, [], `${name}: a top-document input asked again`); + assert.deepEqual(state.executed, [name], `${name}: a top-document input did not run`); + } +}); + +test('Chrome point and focus input fails closed when its receiving document is unknown', async () => { + for (const [name, args] of RECEIVING_FRAME_CALLS) { + const { agent, state } = receivingFrameGateAgent(AgentCh, 5123, { frameUrls: [''] }); + const messages = []; + await agent._executeToolBatch(5123, [{ id: `unknown_${name}`, function: { name, arguments: JSON.stringify(args) } }], + messages, () => { }, { supportsVision: false }, '', new Set([name]), 1); + assert.deepEqual(state.prompts, [], `${name}: an unidentified frame must not borrow a prompt or the page grant`); + assert.deepEqual(state.executed, [], `${name}: input ran without an identified receiving document`); + const result = JSON.parse(messages[0].content); + assert.equal(result.denied, true, name); + assert.match(result.error, /could not identify the site of the document/, name); + } +}); + +test('Chrome point and focus input is not sent when its document changed while the card was open', async () => { + for (const [name, args] of RECEIVING_FRAME_CALLS) { + const { agent, state } = receivingFrameGateAgent(AgentCh, 5124, { + frameUrls: ['https://wallet.example/pay', 'https://attacker.example/'], + choice: 'once', + }); + const messages = []; + await agent._executeToolBatch(5124, [{ id: `moved_${name}`, function: { name, arguments: JSON.stringify(args) } }], + messages, () => { }, { supportsVision: false }, '', new Set([name]), 1); + assert.equal(state.prompts.length, 1, name); + assert.deepEqual(state.resolved, [name, name], `${name}: the receiver was not checked again after the card`); + assert.deepEqual(state.executed, [], `${name}: input followed the page into a document the user was not asked about`); + assert.match(JSON.parse(messages[0].content).error, /changed to one on attacker\.example/, name); + } +}); + +test('Firefox point and focus input is charged to the top document it stays in', async () => { + for (const [name, args] of RECEIVING_FRAME_CALLS) { + const { agent, state } = receivingFrameGateAgent(AgentFx, 5125); + await agent._executeToolBatch(5125, [{ id: `fx_${name}`, function: { name, arguments: JSON.stringify(args) } }], + [], () => { }, { supportsVision: false }, '', new Set([name]), 1); + assert.deepEqual(state.resolved, [], `${name}: Firefox has no CDP receiving-frame resolver`); + assert.deepEqual(state.prompts, [], name); + assert.deepEqual(state.executed, [name], name); + } +}); + test('form validation classifier surfaces native and custom submission errors', () => { const url = 'https://addons.mozilla.org/en-US/developers/addon/webbrain/versions/submit/'; const invalidField = { @@ -86751,6 +87188,62 @@ test('agent allows mutating fetch_url after conversation or persistent API appro } }); +test('default-on API mutation setting leaves the network prompt for each host on new installs', async () => { + for (const AgentClass of [AgentCh, AgentFx]) { + for (const { name, grant, sitePrompt, choice = 'once', prompted, ran } of [ + { name: 'new install: the user allows the host', grant: 'persistent', sitePrompt: true, prompted: true, ran: true }, + { name: 'new install: the user denies the host', grant: 'persistent', sitePrompt: true, choice: 'deny', prompted: true, ran: false }, + { name: 'new install with /allow-api', grant: 'conversation', sitePrompt: true, prompted: false, ran: true }, + { name: 'new install with a cloud run grant', grant: 'temporary', sitePrompt: true, prompted: false, ran: true }, + { name: 'install from before the marker', grant: 'persistent', sitePrompt: false, prompted: false, ran: true }, + ]) { + const agent = new AgentClass({ getVisionProvider: async () => null }); + const tabId = 4908; + let executed = false; + agent.executeTool = async () => { + executed = true; + return { success: true }; + }; + agent._currentUrl = async () => 'https://shop.example/account'; + agent._skipPermissionGate = false; + agent._ensureGateSetting = async () => false; + const prompts = []; + agent._promptPermission = async (_tabId, capability, host) => { + prompts.push({ capability, host }); + return choice; + }; + agent.setApiMutationSitePrompt(sitePrompt); + if (grant === 'persistent') agent.setAlwaysAllowApiMutations(true); + if (grant === 'conversation') agent.setApiMutationsAllowed(tabId, true); + if (grant === 'temporary') agent.setTemporaryApiMutationsAllowed(tabId, true); + const messages = []; + + await agent._executeToolBatch( + tabId, + [{ + id: 'api_write', + function: { + name: 'fetch_url', + arguments: JSON.stringify({ url: 'https://collector.example/api/events', method: 'POST', body: '{"a":1}' }), + }, + }], + messages, + () => { }, + { supportsVision: false }, + '', + new Set(['fetch_url']), + 1, + ); + + const label = `${AgentClass.name}: ${name}`; + assert.deepEqual(prompts, prompted ? [{ capability: Capability.NETWORK, host: 'collector.example' }] : [], `${label}: prompts`); + assert.equal(executed, ran, `${label}: dispatch`); + assert.equal(messages.length, 1, `${label}: one tool result`); + assert.doesNotMatch(messages[0].content, /requiresApiAllow/, `${label}: the write was authorized`); + } + } +}); + test('cloud Ask dispatch blocks API mutations even with an existing conversation grant', async () => { const agent = new AgentCh({ getVisionProvider: async () => null }); const tabId = 4906; @@ -113501,6 +113994,33 @@ test('hostForCapability: navigate/network use target URL, others use current pag assert.equal(hostForCapability(Capability.NAVIGATE, { steps: 2 }, 'https://cur.com', 'go_forward'), 'cur.com'); }); +test('point and focus input is charged to its receiving document, failing closed without one', () => { + for (const [label, Cap, reqHosts] of [['firefox', Capability, requiredHosts], ['chrome', CapabilityCh, requiredHostsCh]]) { + const page = 'https://merchant.example/checkout'; + const wallet = { _inputFrameUrl: 'https://wallet.example/pay' }; + for (const [name, args, capability] of [ + ['click', { x: 10, y: 20, ...wallet }, Cap.CLICK], + ['type_text', { text: '4242', ...wallet }, Cap.TYPE], + ['press_keys', { key: 'Enter', ...wallet }, Cap.CLICK], + ]) { + assert.deepEqual(reqHosts(capability, args, page, name), ['wallet.example'], `${label}: ${name}`); + // No receiving document: never fall back to the page's grant. + const { _inputFrameUrl, ...unresolved } = args; + assert.deepEqual(reqHosts(capability, unresolved, page, name), [], `${label}: ${name} without a receiver`); + assert.deepEqual(reqHosts(capability, { ...args, _inputFrameUrl: '' }, page, name), [], `${label}: ${name} with an opaque receiver`); + } + // An element WebBrain resolved itself keeps the page host. + for (const [name, args, capability] of [ + ['click', { selector: '#pay', ...wallet }, Cap.CLICK], + ['click', { ref_id: 'ref_4', ...wallet }, Cap.CLICK], + ['type_text', { selector: '#card', text: '4242', ...wallet }, Cap.TYPE], + ['type_ax', { ref_id: 'ref_5', text: '4242', ...wallet }, Cap.TYPE], + ]) { + assert.deepEqual(reqHosts(capability, args, page, name), ['merchant.example'], `${label}: ${name} ${JSON.stringify(args)}`); + } + } +}); + test('generate_image permission and result trust are bound to the configured provider in both builds', () => { for (const [label, Cap, hostFor, reqHosts, untrustedTools] of [ ['firefox', Capability, hostForCapability, requiredHosts, UNTRUSTED_CONTENT_TOOLS], @@ -119957,6 +120477,38 @@ test('Chrome click_ax timeout after mouse press unwinds without completing the c } }); +test('agent activity effect is a General setting, portable, and read live by the page indicator', () => { + for (const [label, prefix, configTransfer, runtimeApi] of [ + ['chrome', 'src/chrome', ConfigTransferCh, 'chrome'], + ['firefox', 'src/firefox', ConfigTransferFx, 'browser'], + ]) { + const settingsHtml = fs.readFileSync(path.join(ROOT, prefix, 'src/ui/settings.html'), 'utf8'); + const settingsJs = fs.readFileSync(path.join(ROOT, prefix, 'src/ui/settings.js'), 'utf8'); + const indicator = fs.readFileSync(path.join(ROOT, prefix, 'src/content/agent-visual-indicator.js'), 'utf8'); + + const select = settingsPanelHtml(settingsHtml, 'display').match(/\s*