Skip to content

Automate browser based workflows with AI

Move controlled popups into the opener's Skyvern Controlled group and show a frame on controlled tabs (SKY-17182, SKY-17183) (#8671)

Shuchang Zheng2f89e6bf8006
diff --git a/docs/changelog-emails/2026-05-may.md b/docs/changelog-emails/2026-05-may.md
index 5072f3409..ff7953299 100644
--- a/docs/changelog-emails/2026-05-may.md
+++ b/docs/changelog-emails/2026-05-may.md
@@ -1,4 +1,4 @@
-![Skyvern Changelog — May 2026](images/2026-05-00-header.png)
+![Skyvern Changelog — May 2026](./images/2026-05-00-header.png)
# Skyvern Changelog — April & May 2026
@@ -12,7 +12,7 @@
The workflow copilot got a lot more hands-on. **Hard-cancel** a run mid-flight instead of waiting it out, and **follow it live** as it **streams status narration** and surfaces **block-level events** (starts, completions, errors) while your workflow runs. When a test trips, it hands back the **work-in-progress workflow** so you can grab the draft and keep building. Self-healed retries are now visually separated from real failures, and a quick `/discover` in chat passes the whole build straight to the copilot.
-![Workflow Copilot v2 — live status narration with a streaming sub-event timeline, a self-healed retry shown apart from errors, and a hard-cancel button](images/2026-04-01-copilot-v2.png)
+![Workflow Copilot v2 — live status narration with a streaming sub-event timeline, a self-healed retry shown apart from errors, and a hard-cancel button](./images/2026-04-01-copilot-v2.png)
---
@@ -20,7 +20,7 @@ The workflow copilot got a lot more hands-on. **Hard-cancel** a run mid-flight i
Connecting Skyvern over MCP is now a clean **OAuth** flow. **Multi-org users** get an organization picker right in the authorize step. Skyvern runs as a native **OpenAI Apps SDK** app, ships **safety hints** for the ChatGPT connector, documents **Codex** remote OAuth end-to-end, and adds **OpenClaw** as a new target (`skyvern setup openclaw`). Under the hood: production OAuth callbacks, plus per-tool latency and error telemetry.
-![MCP OAuth — an authorize dialog with an organization picker for multi-org users, alongside supported clients: Claude, ChatGPT/Apps SDK, Codex, and OpenClaw](images/2026-04-02-mcp-oauth.png)
+![MCP OAuth — an authorize dialog with an organization picker for multi-org users, alongside supported clients: Claude, ChatGPT/Apps SDK, Codex, and OpenClaw](./images/2026-04-02-mcp-oauth.png)
---
@@ -28,7 +28,7 @@ Connecting Skyvern over MCP is now a clean **OAuth** flow. **Multi-org users** g
Your terminal is now a control panel. **`skyvern schedule`** creates, lists, toggles, and deletes workflow schedules without leaving the command line. **`skyvern config`** reads and writes org-level settings — timeouts, concurrency, default proxy — the same way. Both run over the MCP protocol, so Claude Code, Codex, and other MCP clients can use them through the same interface.
-![Terminal showing the new skyvern schedule and skyvern config CLI commands — listing schedules in a table, creating a cron schedule, and reading an org-level config value](images/2026-04-03-cli-schedule-config.png)
+![Terminal showing the new skyvern schedule and skyvern config CLI commands — listing schedules in a table, creating a cron schedule, and reading an org-level config value](./images/2026-04-03-cli-schedule-config.png)
---
@@ -36,7 +36,7 @@ Your terminal is now a control panel. **`skyvern schedule`** creates, lists, tog
Stop squinting at nested JSON. A new **Summarize with AI** button sits next to every block and workflow output — one click turns raw data into a plain-language summary of what your workflow extracted.
-![AI Summarize for workflow outputs — raw JSON on the left and a generated plain-language summary on the right, produced by a "Summarize with AI" button](images/2026-04-04-ai-summarize.png)
+![AI Summarize for workflow outputs — raw JSON on the left and a generated plain-language summary on the right, produced by a "Summarize with AI" button](./images/2026-04-04-ai-summarize.png)
---
@@ -44,7 +44,7 @@ Stop squinting at nested JSON. A new **Summarize with AI** button sits next to e
Set your error handling once — not on every block. Workflows now take an `error_code_mapping` field that **every block inherits automatically**. Define the defaults at the top, and override per-block only where you actually need to.
-![Workflow-level error code mapping — error codes mapped to messages once at the workflow level, with each block inheriting them and one block adding an override](images/2026-04-05-error-code-mapping.png)
+![Workflow-level error code mapping — error codes mapped to messages once at the workflow level, with each block inheriting them and one block adding an override](./images/2026-04-05-error-code-mapping.png)
---
@@ -52,7 +52,7 @@ Set your error handling once — not on every block. Workflows now take an `erro
Less busywork between test runs. The debugger now **pre-fills the Run dialog with the values from your last run**, so you're not re-typing the same inputs every time.
-![Debugger Run dialog pre-filled with parameter values from the last run, marked by a "Pre-filled from last run" badge](images/2026-04-06-debugger-run-dialog.png)
+![Debugger Run dialog pre-filled with parameter values from the last run, marked by a "Pre-filled from last run" badge](./images/2026-04-06-debugger-run-dialog.png)
---
@@ -62,7 +62,7 @@ Less busywork between test runs. The debugger now **pre-fills the Run dialog wit
The editor is now **drag-and-drop** — reorder your whole workflow, not just tweak blocks in place. Grab any block by its handle and **drop it where it belongs**: top level, inside a branch, deep in a loop. **Collapse** blocks and entire nested containers to focus, and your layout is **remembered per workflow** across sessions. It's fully **keyboard-driven** with screen-reader announcements, and every block's config **autosaves as you type**. (Recording mode still freezes drag, so a mid-record reorder can't shift block identities under the recorder.)
-![Draggable workflow editor — a workflow canvas with a grip handle on a block mid-drag, a drop indicator between blocks, several blocks collapsed to compact headers, and a global expand/collapse control](images/2026-05-01-draggable-editor.png)
+![Draggable workflow editor — a workflow canvas with a grip handle on a block mid-drag, a drop indicator between blocks, several blocks collapsed to compact headers, and a global expand/collapse control](./images/2026-05-01-draggable-editor.png)
---
@@ -70,7 +70,7 @@ The editor is now **drag-and-drop** — reorder your whole workflow, not just tw
We redesigned the run page around a compact **timeline sidebar** and a dedicated **detail panel** — scan every block at a glance, then open any one for its inputs, output, and diagnostics. A live **N-of-M completion counter** tracks progress and visibly flags blocks that never ran. The **app sidebar** got a refresh in the same pass, for cleaner navigation everywhere.
-![Redesigned workflow run page — a compact timeline sidebar listing blocks with a live "7/12 blocks" completion counter, next to a detail panel showing the selected block's inputs, output, and diagnostics](images/2026-05-02-run-page-redesign.png)
+![Redesigned workflow run page — a compact timeline sidebar listing blocks with a live "7/12 blocks" completion counter, next to a detail panel showing the selected block's inputs, output, and diagnostics](./images/2026-05-02-run-page-redesign.png)
---
@@ -78,7 +78,7 @@ We redesigned the run page around a compact **timeline sidebar** and a dedicated
Loop until you're done — not a fixed number of times. The new **While Loop block** repeats a sub-workflow **until your condition is met**: paginate until there's no Next button, retry until a status flips, drain a queue until it's empty.
-![While Loop block — a workflow containing a While Loop block with a condition expression, wrapping a sub-workflow that repeats until the condition turns false](images/2026-05-03-while-loop.png)
+![While Loop block — a workflow containing a While Loop block with a condition expression, wrapping a sub-workflow that repeats until the condition turns false](./images/2026-05-03-while-loop.png)
---
@@ -86,7 +86,7 @@ Loop until you're done — not a fixed number of times. The new **While Loop blo
Your automations, by the numbers. The new **`/analytics` page** breaks down **run volume, outcomes, and trends over time** in one view — no exports, no spreadsheets. (Gated per-org, so it lights up only where it's enabled.)
-![Analytics dashboard — an /analytics page with charts of workflow run volume and success rate over time, plus per-workflow performance breakdowns](images/2026-05-04-analytics-dashboard.png)
+![Analytics dashboard — an /analytics page with charts of workflow run volume and success rate over time, plus per-workflow performance breakdowns](./images/2026-05-04-analytics-dashboard.png)
---
@@ -94,7 +94,7 @@ Your automations, by the numbers. The new **`/analytics` page** breaks down **ru
The copilot is steadier when sessions get long or messy. A persistent **turn-narrative bubble** tracks what the agent is doing — and **survives page reloads**, so you never lose your place. Hit an unexpected error? It's **recoverable now**: instead of a frozen chat, you get a clear explanation and a **specific follow-up question** drawn from what it actually found missing. The **diff view** finally catches changes **nested inside conditionals and loops**, and we cleared a batch of edge cases — credential scope leaking after an edit, session context lost across turns, accepted proposals getting dropped.
-![Workflow Copilot — a chat thread showing a persistent turn-narrative bubble summarizing the agent's current action, a recovered error with a clear explanation, and a diff panel highlighting a change nested inside a loop block](images/2026-05-05-copilot.png)
+![Workflow Copilot — a chat thread showing a persistent turn-narrative bubble summarizing the agent's current action, a recovered error with a clear explanation, and a diff panel highlighting a change nested inside a loop block](./images/2026-05-05-copilot.png)
---
@@ -102,7 +102,7 @@ The copilot is steadier when sessions get long or messy. A persistent **turn-nar
Manage runs in bulk — cancel, retry, cap. The new **Retry API** re-runs a workflow **from the start or from any block** — no rebuilding inputs. **`POST /runs/cancel`** cancels **many runs in a single request** and tells you exactly which succeeded and which didn't. And two new guardrails — a **runtime limit** and a **per-workflow step cap** — stop runaway executions before they burn resources.
-![Run control APIs — an API panel showing POST /runs/cancel with a list of run IDs returning cancelled and failed arrays, a retry-from-block call, and workflow settings for a max runtime and a total step cap](images/2026-05-06-run-control.png)
+![Run control APIs — an API panel showing POST /runs/cancel with a list of run IDs returning cancelled and failed arrays, a retry-from-block call, and workflow settings for a max runtime and a total step cap](./images/2026-05-06-run-control.png)
---
@@ -110,7 +110,7 @@ Manage runs in bulk — cancel, retry, cap. The new **Retry API** re-runs a work
Route any run through **your own proxy** — just pass `{"proxy_location": {"url": "http://user:pass@host:port"}}` on any task, workflow, or browser-session request; no managed proxy infrastructure required. And **CDP connect headers** are now a first-class workflow setting — your provider's auth headers are masked, stored, and applied to the **CDP connection only**, never forwarded to target sites. (Plus: msedge is the new default browser for self-hosted templates, and the Docker Compose quickstart bootstraps your `.env` files on first run.)
-![Self-hosting upgrades — a workflow settings panel with a custom proxy URL field and a masked CDP Connect Headers field, beside a terminal running the Docker Compose quickstart that auto-creates .env files](images/2026-05-07-self-hosting.png)
+![Self-hosting upgrades — a workflow settings panel with a custom proxy URL field and a masked CDP Connect Headers field, beside a terminal running the Docker Compose quickstart that auto-creates .env files](./images/2026-05-07-self-hosting.png)
---
@@ -118,7 +118,7 @@ Route any run through **your own proxy** — just pass `{"proxy_location": {"url
Saved browser profiles — the logged-in sessions your workflows reuse — are easier to set up and manage. A **guided, step-by-step setup** walks you through creating one, a dedicated **management page** lets you **search, rename, and organize**, and saving now gives you **instant feedback** with an in-progress row the moment you hit save.
-![Browser profiles — a dedicated browser profiles management page with search and rename controls, next to a guided step-by-step "create a profile" flow and an in-progress placeholder row appearing on save](images/2026-05-08-browser-profiles.png)
+![Browser profiles — a dedicated browser profiles management page with search and rename controls, next to a guided step-by-step "create a profile" flow and an in-progress placeholder row appearing on save](./images/2026-05-08-browser-profiles.png)
---
diff --git a/docs/changelog-emails/2026-06-june.md b/docs/changelog-emails/2026-06-june.md
index bc960d3a0..1188e978a 100644
--- a/docs/changelog-emails/2026-06-june.md
+++ b/docs/changelog-emails/2026-06-june.md
@@ -1,4 +1,4 @@
-![Skyvern Changelog — June 2026](images/2026-06-00-header.png)
+![Skyvern Changelog — June 2026](./images/2026-06-00-header.png)
# Skyvern Changelog — June 2026
@@ -10,7 +10,7 @@
We renamed **Workflows to Agents** across the product, the public API, and the docs. The API now lives under **`/agents`** (e.g. `POST /v1/run/agents`) and accepts an **`agent_id`** alias for `workflow_id` — same `wpid_` value, echoed back in responses. It's fully backwards-compatible: your existing `workflow_id` inputs, `/workflows` endpoints, SDK methods, and bookmarked doc URLs all keep working.
-![Workflows are now Agents — the app renamed to Agents with the public API served under /agents and an agent_id alias for workflow_id, shown as backwards-compatible](images/2026-06-01-agents-rename.png)
+![Workflows are now Agents — the app renamed to Agents with the public API served under /agents and an agent_id alias for workflow_id, shown as backwards-compatible](./images/2026-06-01-agents-rename.png)
---
@@ -18,7 +18,7 @@ We renamed **Workflows to Agents** across the product, the public API, and the d
Meet the next-generation editor. **Workflow Studio** is an opt-in preview that reimagines how you build: a refreshed **build canvas**, an **integrated live browser view**, and a built-in **run viewer** — all in one place. Take control of the live browser, center the viewport, and watch a run unfold without leaving the editor. Flip it on from Feature Preview in Settings.
-![Workflow Studio preview — a redesigned editor with a build canvas on the left, an integrated live browser view in the center, and a run viewer panel, with a take-control button on the live browser](images/2026-06-02-workflow-studio.png)
+![Workflow Studio preview — a redesigned editor with a build canvas on the left, an integrated live browser view in the center, and a run viewer panel, with a take-control button on the live browser](./images/2026-06-02-workflow-studio.png)
---
@@ -26,7 +26,7 @@ Meet the next-generation editor. **Workflow Studio** is an opt-in preview that r
For when you want to drop to code. Code blocks now have a **dedicated code editor** with **syntax highlighting**, **Jinja parameter hints**, and a **run timeline** that records every action — including `page.evaluate(...)` calls. A **Build ↔ Code toggle** flips between visual and code editing, block labels and extraction output render correctly, and Copilot-generated code blocks support a **typed extraction schema** and fill logins with your stored credentials.
-![Code-first code block — a dedicated code editor with syntax highlighting and Jinja parameter hints, a Build/Code toggle in the header, and a run timeline listing each action taken](images/2026-06-03-code-first.png)
+![Code-first code block — a dedicated code editor with syntax highlighting and Jinja parameter hints, a Build/Code toggle in the header, and a run timeline listing each action taken](./images/2026-06-03-code-first.png)
---
@@ -34,7 +34,7 @@ For when you want to drop to code. Code blocks now have a **dedicated code edito
The Copilot got sharper about intent and context. It now **routes every request by mode** — **Ask** answers without touching your workflow, **Build** creates or edits it, **Code** generates executable code blocks. It **remembers the full chat history per workflow**, so prior context and decisions carry forward as you keep building. And its **repair loop is honest now**: when consecutive fixes make no verified progress, it stops after three tries and escalates cleanly — draft preserved — instead of spinning.
-![Workflow Copilot — a chat with an Ask / Build / Code mode selector, per-workflow chat history in a side rail, and a repair loop that halts after three attempts with an honest escalation message](images/2026-06-04-copilot.png)
+![Workflow Copilot — a chat with an Ask / Build / Code mode selector, per-workflow chat history in a side rail, and a repair loop that halts after three attempts with an honest escalation message](./images/2026-06-04-copilot.png)
---
@@ -42,7 +42,7 @@ The Copilot got sharper about intent and context. It now **routes every request
More choice for every run. New this month: **DeepSeek**, **Xiaomi MiMo** (and **MiMo-V2.5** via OpenRouter), **Gemini 3.5 Flash**, **GPT-5-mini** (your own OpenAI key or via OpenRouter), and **Claude Opus 4.8** (Anthropic + Bedrock). OpenRouter runs now track token counts and cost like every other provider. (Gemini 2.5 Pro/Flash are deprecated; CUA and the Claude Opus family are now enterprise-only.)
-![Model dropdown — an expanded model picker listing DeepSeek, Xiaomi MiMo, Gemini 3.5 Flash, GPT-5-mini, and Claude Opus 4.8, with an OpenRouter cost-tracking badge](images/2026-06-05-models.png)
+![Model dropdown — an expanded model picker listing DeepSeek, Xiaomi MiMo, Gemini 3.5 Flash, GPT-5-mini, and Claude Opus 4.8, with an OpenRouter cost-tracking badge](./images/2026-06-05-models.png)
---
@@ -50,7 +50,7 @@ More choice for every run. New this month: **DeepSeek**, **Xiaomi MiMo** (and **
Logins that just work. Pull credentials straight from **1Password** (with an item picker) or **Bitwarden**, look up one-time passcodes from **Gmail** via OAuth, and **fill OTP at runtime** from your stored TOTP secrets — even inside code blocks. Expired credential sessions **auto re-save**, and you can **clear a saved credential** without deleting and recreating it.
-![Credentials setup — a credential picker offering 1Password and Bitwarden vault items, a Gmail-backed OTP lookup option, and a runtime OTP fill using a stored TOTP secret](images/2026-06-06-credentials.png)
+![Credentials setup — a credential picker offering 1Password and Bitwarden vault items, a Gmail-backed OTP lookup option, and a runtime OTP fill using a stored TOTP secret](./images/2026-06-06-credentials.png)
---
@@ -58,7 +58,7 @@ Logins that just work. Pull credentials straight from **1Password** (with an ite
Automations that span tabs. The autonomous agent loop can now **open and work across multiple browser tabs** at once — following new-tab links and handling pop-ups — so flows that jump between tabs no longer dead-end.
-![Multi-tab browser control — an agent working across two browser tabs at once, following a link that opened a second tab and acting in both](images/2026-06-07-multi-tab.png)
+![Multi-tab browser control — an agent working across two browser tabs at once, following a link that opened a second tab and acting in both](./images/2026-06-07-multi-tab.png)
---
@@ -66,7 +66,7 @@ Automations that span tabs. The autonomous agent loop can now **open and work ac
Full GCP-native deployments. Self-hosted Skyvern now supports **Google Cloud Storage** for artifacts and **GCP Secret Manager** as a vault backend — so you can run the whole stack on Google Cloud with your own storage and secrets.
-![Self-hosting on GCP — a deployment config showing Google Cloud Storage selected for artifacts and GCP Secret Manager selected as the vault backend](images/2026-06-08-gcp-self-host.png)
+![Self-hosting on GCP — a deployment config showing Google Cloud Storage selected for artifacts and GCP Secret Manager selected as the vault backend](./images/2026-06-08-gcp-self-host.png)
---
diff --git a/docs/changelog-emails/2026-07-july.md b/docs/changelog-emails/2026-07-july.md
index c0c92f314..6294c1e81 100644
--- a/docs/changelog-emails/2026-07-july.md
+++ b/docs/changelog-emails/2026-07-july.md
@@ -1,4 +1,4 @@
-![Skyvern Changelog — July 2026](images/2026-07-00-header.png)
+![Skyvern Changelog — July 2026](./images/2026-07-00-header.png)
# Skyvern Changelog — July 2026
@@ -14,7 +14,7 @@ The next-generation editor is out of preview — **Workflow Studio is now availa
- **Runs**: a **Past Runs tab**, run **inputs and outputs broken down field by field**, code-block outputs shown inline, and searchable JSON
- **Polish**: block search, jump-to-start/end buttons, an unsaved-changes indicator that summarizes what changed, recent-activity history on the canvas, shareable block selection in the URL, and light mode
-![Workflow Studio for everyone — the redesigned Studio editor in light mode with resizable drag-to-reorder panes, a build canvas beside a run timeline, a Past Runs tab, a block search field with jump-to-start and jump-to-end buttons, a full-screen YAML editing toggle, and an unsaved-changes indicator in the header](images/2026-07-01-workflow-studio-ga.png)
+![Workflow Studio for everyone — the redesigned Studio editor in light mode with resizable drag-to-reorder panes, a build canvas beside a run timeline, a Past Runs tab, a block search field with jump-to-start and jump-to-end buttons, a full-screen YAML editing toggle, and an unsaved-changes indicator in the header](./images/2026-07-01-workflow-studio-ga.png)
---
@@ -22,7 +22,7 @@ The next-generation editor is out of preview — **Workflow Studio is now availa
When a step needs a human, you're in the loop. If a workflow step requires human review, you can now **approve or reject it directly from either run view** — no side channel required. The public run status API also reports a **`paused` state**, so your integrations get an accurate picture when a run pauses, including while it waits on review.
-![Human-in-the-loop approvals — a workflow run view paused on a step awaiting human review, with a review card showing Approve and Reject buttons and a status chip reading paused that matches the public run status API](images/2026-07-02-hitl-approvals.png)
+![Human-in-the-loop approvals — a workflow run view paused on a step awaiting human review, with a review card showing Approve and Reject buttons and a status chip reading paused that matches the public run status API](./images/2026-07-02-hitl-approvals.png)
---
@@ -30,7 +30,7 @@ When a step needs a human, you're in the loop. If a workflow step requires human
Show it once, get code. **Record actions in a live browser session** and Skyvern generates **reusable workflow code** from what you did — available now as an opt-in preview. Recording itself was redesigned around a **live draft panel** instead of a separate editor, with cleaner screenshots and more step types. **Live-draft enrichment is noticeably faster** too, so suggestions show up sooner while you record.
-![Code-first browser recording — a live browser session being recorded on the left with a red recording indicator, and a live draft panel on the right generating reusable workflow code step by step, each step paired with a clean screenshot](images/2026-07-03-browser-recording-code.png)
+![Code-first browser recording — a live browser session being recorded on the left with a red recording indicator, and a live draft panel on the right generating reusable workflow code step by step, each step paired with a clean screenshot](./images/2026-07-03-browser-recording-code.png)
---
@@ -40,7 +40,7 @@ Logins got a serious upgrade this month. The Credentials page adds a **Magic Lin
Workflows got smarter about using them, too. They can **rotate through a pool of credentials** across runs and automatically retry with a fallback credential when one fails. Runs that share a credential are serialized, so they no longer clobber each other's login sessions. The builder's credential picker is searchable with no 100-item cap. And to keep secrets out of sight, a per-workflow **mask-secrets setting** hides sensitive values in run outputs and logs, while the HTTP Request block can fetch response values as secrets and pass them between blocks.
-![Credentials and secrets — the Credentials page with a Magic Link tab selected, a passkey 2FA badge marked enterprise, an email-inbox 2FA identifier picker, a credential rotation pool with a fallback retry arrow, a searchable credential picker, and a workflow setting toggle labeled mask secret values](images/2026-07-04-credentials.png)
+![Credentials and secrets — the Credentials page with a Magic Link tab selected, a passkey 2FA badge marked enterprise, an email-inbox 2FA identifier picker, a credential rotation pool with a fallback retry arrow, a searchable credential picker, and a workflow setting toggle labeled mask secret values](./images/2026-07-04-credentials.png)
---
@@ -50,7 +50,7 @@ Files in, files out — anywhere. A new **Email Inbox block** (Gmail and Outlook
On the way out, the Download File block can deliver to **SFTP, Amazon S3, Azure, and Google Drive**, and SFTP joins the Cloud Storage upload targets. Google Drive uploads handle **files larger than 5 MB** with resumable transfers that pick up where they left off. The Cloud Storage block takes an optional prompt to upload only the files you want, and downloaded files get the correct extension detected from their content.
-![Document and file pipelines — a workflow canvas chaining an Email Inbox block for Gmail and Outlook, a Split PDF block fanning one document into several files, and a File Parser block unpacking a ZIP archive, flowing into a download destination picker listing SFTP, Amazon S3, Azure, and Google Drive](images/2026-07-05-file-pipelines.png)
+![Document and file pipelines — a workflow canvas chaining an Email Inbox block for Gmail and Outlook, a Split PDF block fanning one document into several files, and a File Parser block unpacking a ZIP archive, flowing into a download destination picker listing SFTP, Amazon S3, Azure, and Google Drive](./images/2026-07-05-file-pipelines.png)
---
@@ -58,7 +58,7 @@ On the way out, the Download File block can deliver to **SFTP, Amazon S3, Azure,
Organize runs your way — and get the story delivered. Runs can now be **tagged**, manually or via **auto-detected platform tags**, managed in bulk, and filtered by agent or run type in Run History. Analytics gained **grouping by run metadata** and a restructured console for a clearer read on usage and cost. And a new **weekly email digest** lands in your inbox with run volume, credit usage, a status breakdown, week-over-week trend indicators, and your lowest-success-rate workflows.
-![Run tags and weekly analytics digest — a run history list with colored tags and auto-detected platform tags, a bulk tagging toolbar over selected rows, an analytics dashboard grouped by run metadata, and a weekly email digest card showing run volume, credit usage, a status breakdown, and week-over-week trend arrows](images/2026-07-06-run-tags-digest.png)
+![Run tags and weekly analytics digest — a run history list with colored tags and auto-detected platform tags, a bulk tagging toolbar over selected rows, an analytics dashboard grouped by run metadata, and a weekly email digest card showing run volume, credit usage, a status breakdown, and week-over-week trend arrows](./images/2026-07-06-run-tags-digest.png)
---
@@ -66,7 +66,7 @@ Organize runs your way — and get the story delivered. Runs can now be **tagged
Bring your own brain — or pick a new one. Organizations can now set **default Smart and Fast custom LLMs** from account settings instead of configuring them on every workflow. Custom LLM setup accepts **provider-specific parameters**, and Google Gemini is natively supported as a provider. The model menu grew too: **Claude Opus 5**, **Grok 4.5**, Gemini 3.5 Flash Lite, Gemini 3.6 Flash, and DeepSeek V4 Flash are all selectable now.
-![Custom LLMs and new models — account settings with default Smart and Fast custom LLM selectors, a custom provider form showing Google Gemini with provider-specific parameters, and a model dropdown listing Claude Opus 5, Grok 4.5, Gemini 3.5 Flash Lite, Gemini 3.6 Flash, and DeepSeek V4 Flash](images/2026-07-07-custom-llms-models.png)
+![Custom LLMs and new models — account settings with default Smart and Fast custom LLM selectors, a custom provider form showing Google Gemini with provider-specific parameters, and a model dropdown listing Claude Opus 5, Grok 4.5, Gemini 3.5 Flash Lite, Gemini 3.6 Flash, and DeepSeek V4 Flash](./images/2026-07-07-custom-llms-models.png)
---
@@ -81,7 +81,7 @@ Under the hood, runs got harder to derail:
- Cloudflare Turnstile challenges are detected proactively for faster resolution, and simple arithmetic text CAPTCHAs hit during data lookups are solved automatically
- Code-block self-healing enforces a minimum retry floor before giving up
-![Self-healing made visible — a workflows list with reliability badges, a run page panel listing automatic recovery events on a timeline, a workflow settings toggle for self-healing, and a browser view paused in a virtual waiting room with a callout showing the run patiently waiting it out](images/2026-07-08-self-healing.png)
+![Self-healing made visible — a workflows list with reliability badges, a run page panel listing automatic recovery events on a timeline, a workflow settings toggle for self-healing, and a browser view paused in a virtual waiting room with a callout showing the run patiently waiting it out](./images/2026-07-08-self-healing.png)
---
diff --git a/docs/changelog-emails/2026-08-august.md b/docs/changelog-emails/2026-08-august.md
index a9375669a..b80b78102 100644
--- a/docs/changelog-emails/2026-08-august.md
+++ b/docs/changelog-emails/2026-08-august.md
@@ -1,4 +1,4 @@
-![Skyvern Changelog — August 2026](images/2026-08-00-header.png)
+![Skyvern Changelog — August 2026](./images/2026-08-00-header.png)
# Skyvern Changelog — August 2026
@@ -17,7 +17,7 @@ The updated Copilot chat is now the default everywhere, including the workflow e
Copilot supports the human-approval block and knows today's date. It retains gathered page facts across long sessions. The new stop button ends the current Copilot run.
-![Workflow Copilot updates — the Copilot chat panel beside a workflow canvas showing a flat activity log of what Copilot looked at, wrote, and ran, an expanded row with a narrator line, a code diff card with added and removed lines, and a Review changes card with Accept and Reject buttons](images/2026-08-01-copilot-updates.png)
+![Workflow Copilot updates — the Copilot chat panel beside a workflow canvas showing a flat activity log of what Copilot looked at, wrote, and ran, an expanded row with a narrator line, a code diff card with added and removed lines, and a Review changes card with Accept and Reject buttons](./images/2026-08-01-copilot-updates.png)
---
@@ -32,7 +32,7 @@ The opt-in **Skyvern 3.0** beta controls the browser through a persistent tool l
The engine supports run replay and typed action history.
-![Skyvern 3.0 engine beta — a block settings panel with the Engine dropdown open listing Skyvern 1.0 (Recommended), Skyvern 2.0 (Legacy), and Skyvern 3.0 (Beta) highlighted, beside a browser preview of a form with numbered set-of-marks boxes drawn over its fields, a CAPTCHA row, and a Submit button](images/2026-08-02-skyvern-3-engine.png)
+![Skyvern 3.0 engine beta — a block settings panel with the Engine dropdown open listing Skyvern 1.0 (Recommended), Skyvern 2.0 (Legacy), and Skyvern 3.0 (Beta) highlighted, beside a browser preview of a form with numbered set-of-marks boxes drawn over its fields, a CAPTCHA row, and a Submit button](./images/2026-08-02-skyvern-3-engine.png)
---
@@ -46,7 +46,7 @@ You can select MCP scopes at install time or on the hosted URL.
- The `lean` and `all` scopes include new tools. `skyvern_page` reads large pages with cursor pagination. `skyvern_extract_structured` returns schema-validated results. `skyvern_finish` declares a task's final outcome.
- Add Skyvern as a custom connector in **Claude.ai and Claude Desktop** through hosted MCP. Refresh tokens renew access without prompting you. Hosted MCP connects to the organization you picked at sign-in.
-![Control Chrome through MCP — a real Chrome window on a fictional Acme Corp dashboard with the Skyvern Agent extension popup showing a green Paired status, a Share this tab toggle switched on, and a list of shared tabs, connected to an MCP client terminal card reading BROWSER_TYPE=extension-connect](images/2026-08-03-control-chrome-mcp.png)
+![Control Chrome through MCP — a real Chrome window on a fictional Acme Corp dashboard with the Skyvern Agent extension popup showing a green Paired status, a Share this tab toggle switched on, and a list of shared tabs, connected to an MCP client terminal card reading BROWSER_TYPE=extension-connect](./images/2026-08-03-control-chrome-mcp.png)
---
@@ -61,7 +61,7 @@ The Login block now lists 1Password items in its credential dropdown.
Skyvern stores magic-link and OTP values exactly as received. Code blocks and cached scripts can complete an emailed sign-in with the new `magic_link` verb. Bitwarden updates reduce credential fetch time and failures. OTP logins use their full 15-minute polling budget.
-![Credentials and login updates — three panels side by side: the Login block's credential dropdown open listing a Skyvern credential and a 1Password group with two items, the Edit credential dialog with a Run sequentially checkbox ticked and a Passkey 2FA badge, and a workflow credential input with a Use Default Value toggle switched off and a provide-at-run-time hint](images/2026-08-04-credentials-login-updates.png)
+![Credentials and login updates — three panels side by side: the Login block's credential dropdown open listing a Skyvern credential and a 1Password group with two items, the Edit credential dialog with a Run sequentially checkbox ticked and a Passkey 2FA badge, and a workflow credential input with a Use Default Value toggle switched off and a provide-at-run-time hint](./images/2026-08-04-credentials-login-updates.png)
---
@@ -76,7 +76,7 @@ S3-compatible storage endpoints must use public HTTPS by default. Self-hosted de
Inside a loop, the File Parser can skip files it cannot parse. It follows Drive links behind confirm pages. A slow parse of a large document fails only its own block, not the whole run.
-![Files, email and storage — a workflow canvas with a Download File block whose destination is S3-compatible with an Endpoint URL field, a Send Email block with a Custom SMTP server section showing host and port, a File Parser block with an on-failure option set to skip to the next iteration, and an API request card showing POST /v1/upload_file with a retention_days form field](images/2026-08-05-files-email-storage-blocks.png)
+![Files, email and storage — a workflow canvas with a Download File block whose destination is S3-compatible with an Endpoint URL field, a Send Email block with a Custom SMTP server section showing host and port, a File Parser block with an on-failure option set to skip to the next iteration, and an API request card showing POST /v1/upload_file with a retention_days form field](./images/2026-08-05-files-email-storage-blocks.png)
---
@@ -90,7 +90,7 @@ Workflow runs can share one browser while retaining logged-in state and tabs.
Recordings from external providers are retained after teardown. A renewal never shortens a session.
-![Browser sessions and live view — a hosted browser session page with a live view of a fictional orders table and a Running badge, beside a Workflow Settings card with a Reuse browser session toggle switched on](images/2026-08-06-browser-sessions.png)
+![Browser sessions and live view — a hosted browser session page with a live view of a fictional orders table and a Running badge, beside a Workflow Settings card with a Reuse browser session toggle switched on](./images/2026-08-06-browser-sessions.png)
---
@@ -103,7 +103,7 @@ Run status and webhooks identify typed business errors from code blocks.
- Run detail displays **persisted code-block output** instead of a disabled Outputs panel.
- The sandboxed runner supports downloads, `page.url`, `Locator.or_`/`and_`, Python `class` statements, `page.frames`, and your configured timeouts. Advisory **security-scan warnings** appear when you save code in Copilot or lint through MCP.
-![Code block errors and outputs — two panels: the code block editor with a raise ErrorCode snippet and an Error Messages section below the code listing declared business error codes, and a run detail view of a failed code block with a red failure card, a View block screenshot button and page thumbnail, and an Outputs panel showing a JSON value](images/2026-08-07-code-block-errors-outputs.png)
+![Code block errors and outputs — two panels: the code block editor with a raise ErrorCode snippet and an Error Messages section below the code listing declared business error codes, and a run detail view of a failed code block with a red failure card, a View block screenshot button and page thumbnail, and an Outputs panel showing a JSON value](./images/2026-08-07-code-block-errors-outputs.png)
---
@@ -116,7 +116,7 @@ The run failure rate now excludes runs you cancelled.
- The selected **run status** applies to every chart, tile, table, and CSV export, including drill-downs. You can select several statuses at once.
- Run history search and status filters persist in the URL. `GET /runs` accepts the new `failure_category` filter for workflow runs.
-![Analytics and run history — an analytics dashboard with a grouped table by workflow tag showing runs and credits per tag, an Actions stat tile with count and failure rate, a Runs and Failures chart toggle, and a Run History list with a search field and Completed and Failed status filter chips reflected in the page URL](images/2026-08-08-analytics-run-history-filters.png)
+![Analytics and run history — an analytics dashboard with a grouped table by workflow tag showing runs and credits per tag, an Actions stat tile with count and failure rate, a Runs and Failures chart toggle, and a Run History list with a search field and Completed and Failed status filter chips reflected in the page URL](./images/2026-08-08-analytics-run-history-filters.png)
---
diff --git a/docs/developers/optimization/chrome-extension.mdx b/docs/developers/optimization/chrome-extension.mdx
index d741903a2..54913ac90 100644
--- a/docs/developers/optimization/chrome-extension.mdx
+++ b/docs/developers/optimization/chrome-extension.mdx
@@ -55,13 +55,11 @@ For manual setup:
4. Click **Load unpacked**.
5. Select the directory printed by the command.
-**Allow User Scripts is optional.** Leave it off for normal browser control. Use `skyvern_observe`,
-`skyvern_get_html`, `skyvern_find`, or `skyvern_get_value` to inspect pages, and use the click, type, select,
-and keypress tools to interact with them.
+**Direct JavaScript evaluation is unavailable in extension mode.** `skyvern_evaluate` and tools that call it return an error.
+Use `skyvern_observe`, `skyvern_get_html`, `skyvern_find`, or `skyvern_get_value` to inspect pages.
+Use `skyvern_click`, `skyvern_type`, `skyvern_select_option`, or `skyvern_press_key` to interact with pages.
-Only direct page evaluation (`skyvern_evaluate` and tools that call it) needs this setting. If you choose to use that
-feature, the setting is in **Skyvern Agent → Details** at `chrome://extensions`. An unavailable evaluation does not
-block the standard browser tools. A debugger disconnect is a separate connection problem.
+A debugger disconnect is a separate connection problem.
For a text input that should be filled without focus or key events, use the fixed extension form command:
@@ -71,7 +69,7 @@ For a text input that should be filled without focus or key events, use the fixe
Pass these arguments to `skyvern_type`. This explicit mode runs a bundled form-control handler in the selected
main-frame document. It accepts plain text, emits `input` and `change`, and preserves the current focus. It does
-not accept JavaScript expressions or require Allow User Scripts. The default `keyboard` mode keeps normal typing.
+not accept JavaScript expressions. The default `keyboard` mode keeps normal typing.
Value mode requires a unique CSS selector and `clear=true`; do not pass the coordinate-only `clear_first` option.
It supports visible, enabled, writable text, email,
@@ -197,17 +195,20 @@ Skyvern's scope includes:
- Existing tabs you explicitly add to **Skyvern Controlled**, by dragging or with the popup
- Tabs Skyvern creates and adds to **Skyvern Controlled**
-- Popups opened by a controlled tab and added to **Skyvern Controlled**
+- Popups opened by a controlled tab. Skyvern moves each popup into a tab in the opener's **Skyvern Controlled** group.
-The extension requests access to HTTP and HTTPS pages so `skyvern_evaluate` can run caller-supplied JavaScript through
-Chrome's User Scripts API. This direct path runs in the page's main context without depending on the page's content
-security policy. It verifies the exact tab-group identity before and after each command. The broker can keep
-`about:blank` as a controlled root tab while it waits for navigation, but direct evaluation refuses `about:blank` and
-every other non-HTTP(S) URL.
+While the agent is connected, controlled HTTP(S) pages show a glowing frame and the label "Skyvern is controlling this tab".
+The **Skyvern Controlled** group identifies controlled tabs. The toolbar badge **ON** shows that the bridge is connected.
+
+The extension requests access to HTTP and HTTPS pages for its bundled form-control script.
+It also needs this access for debugger control of tabs in **Skyvern Controlled**.
+The extension refuses its direct evaluation operation.
+Browser tools that use the debugger send Chrome DevTools Protocol commands to tabs in **Skyvern Controlled**.
+The broker can keep `about:blank` as a controlled root tab while it waits for navigation.
Debugger-based commands display Chrome's debugger infobar; Skyvern never hides it. Clicking **Cancel** in that infobar
-immediately revokes debugger access to the tab, and Skyvern does not automatically reattach. Main-context JavaScript
-commands do not attach the debugger or display its infobar. Skyvern never closes or restarts your Chrome browser.
+immediately revokes debugger access to the tab, and Skyvern does not automatically reattach.
+Skyvern never closes or restarts your Chrome browser.
The extension connects outbound to a bridge bound only to `127.0.0.1`. The default endpoint is
`ws://127.0.0.1:19777/extension/v1`. On macOS and Linux, a persistent daemon owns this listener and MCP processes reach
diff --git a/docs/index.mdx b/docs/index.mdx
index ae63cf122..2451edce8 100644
--- a/docs/index.mdx
+++ b/docs/index.mdx
@@ -5,6 +5,8 @@ slug: /
mode: custom
---
+{/* Keep the links on this page absolute. mint broken-links cannot resolve /docs/... paths, and raw <a> tags on this custom-mode page may render without the /docs base path. */}
+
<div className="sk-page">
{/* ===== HERO ===== */}
@@ -14,7 +16,7 @@ mode: custom
<div className="sk-hero-left">
<div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "12px" }}>
<p className="sk-mono sk-label" style={{ margin: "0" }}>DOCUMENTATION</p>
- <a href="/docs/changelog" className="sk-version-badge">v1.0.22 (latest)</a>
+ <a href="https://www.skyvern.com/docs/changelog" className="sk-version-badge">v1.0.22 (latest)</a>
</div>
<h1 className="sk-hero-title">
Automate any<br />browser workflow<br /><span className="sk-hero-accent">with AI.</span>
@@ -23,8 +25,8 @@ mode: custom
Describe what you want in plain English. Skyvern opens a real browser, reads the page visually, and completes the task.
</p>
<div className="sk-hero-actions">
- <a href="/docs/getting-started/quickstart" className="sk-btn-primary">Get started with the API →</a>
- <a href="/docs/cloud/getting-started/overview" className="sk-btn-secondary">Use the dashboard</a>
+ <a href="https://www.skyvern.com/docs/developers/getting-started/quickstart" className="sk-btn-primary">Get started with the API →</a>
+ <a href="https://www.skyvern.com/docs/cloud/getting-started/overview" className="sk-btn-secondary">Use the dashboard</a>
</div>
</div>
<div className="sk-hero-right">
@@ -60,10 +62,10 @@ mode: custom
<h3 className="sk-cell-title">Automate without code</h3>
<p className="sk-cell-desc">Use the dashboard to run tasks and build agents visually.</p>
<div className="sk-cell-links">
- <a href="/docs/cloud/getting-started/overview" className="sk-cell-link">Dashboard overview <span className="sk-arrow">↗</span></a>
- <a href="/docs/cloud/getting-started/run-your-first-task" className="sk-cell-link">Run your first task <span className="sk-arrow">↗</span></a>
- <a href="/docs/cloud/building-agents/build-an-agent" className="sk-cell-link">Build an agent <span className="sk-arrow">↗</span></a>
- <a href="/docs/integrations/zapier" className="sk-cell-link">Connect to Zapier <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/cloud/getting-started/overview" className="sk-cell-link">Dashboard overview <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/cloud/getting-started/run-your-first-task" className="sk-cell-link">Run your first task <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/cloud/building-agents/build-an-agent" className="sk-cell-link">Build an agent <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/integrations/zapier" className="sk-cell-link">Connect to Zapier <span className="sk-arrow">↗</span></a>
</div>
</div>
<div className="sk-bento-cell">
@@ -71,9 +73,9 @@ mode: custom
<h3 className="sk-cell-title">Build with the API</h3>
<p className="sk-cell-desc">Integrate browser automation into your product with Python, TypeScript, or REST.</p>
<div className="sk-cell-links">
- <a href="/docs/getting-started/quickstart" className="sk-cell-link">API quickstart <span className="sk-arrow">↗</span></a>
- <a href="/docs/sdk-reference/overview" className="sk-cell-link">SDK reference <span className="sk-arrow">↗</span></a>
- <a href="/docs/api-reference" className="sk-cell-link">API reference <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/developers/getting-started/quickstart" className="sk-cell-link">API quickstart <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/sdk-reference/overview" className="sk-cell-link">SDK reference <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/api-reference" className="sk-cell-link">API reference <span className="sk-arrow">↗</span></a>
</div>
</div>
<div className="sk-bento-cell">
@@ -81,10 +83,10 @@ mode: custom
<h3 className="sk-cell-title">Self-host</h3>
<p className="sk-cell-desc">Run Skyvern on your own infrastructure with your own LLM keys.</p>
<div className="sk-cell-links">
- <a href="/docs/self-hosted/overview" className="sk-cell-link">Deployment overview <span className="sk-arrow">↗</span></a>
- <a href="/docs/self-hosted/docker" className="sk-cell-link">Docker setup <span className="sk-arrow">↗</span></a>
- <a href="/docs/self-hosted/llm-configuration" className="sk-cell-link">LLM configuration <span className="sk-arrow">↗</span></a>
- <a href="/docs/self-hosted/kubernetes" className="sk-cell-link">Kubernetes <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/developers/self-hosted/overview" className="sk-cell-link">Deployment overview <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/developers/self-hosted/docker" className="sk-cell-link">Docker setup <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/developers/self-hosted/llm-configuration" className="sk-cell-link">LLM configuration <span className="sk-arrow">↗</span></a>
+ <a href="https://www.skyvern.com/docs/developers/self-hosted/kubernetes" className="sk-cell-link">Kubernetes <span className="sk-arrow">↗</span></a>
</div>
</div>
</div>
@@ -92,13 +94,13 @@ mode: custom
{/* ===== BENTO GRID: 2 COL: HOW IT WORKS + CONCEPTS ===== */}
<div className="sk-bento-row sk-bento-2col">
- <a href="/docs/getting-started/introduction" className="sk-bento-cell sk-bento-cell-link">
+ <a href="https://www.skyvern.com/docs/developers/getting-started/introduction" className="sk-bento-cell sk-bento-cell-link">
<p className="sk-mono sk-label">ARCHITECTURE</p>
<h3 className="sk-cell-title">How Skyvern works</h3>
<p className="sk-cell-desc">The agent loop, Planner-Agent-Validator architecture, and what happens under the hood when you run a task.</p>
<span className="sk-mono sk-arrow-lg">↗</span>
</a>
- <a href="/docs/getting-started/core-concepts" className="sk-bento-cell sk-bento-cell-link">
+ <a href="https://www.skyvern.com/docs/developers/getting-started/core-concepts" className="sk-bento-cell sk-bento-cell-link">
<p className="sk-mono sk-label">REFERENCE</p>
<h3 className="sk-cell-title">Core concepts</h3>
<p className="sk-cell-desc">Tasks, agents, blocks, runs, credentials, browser sessions, and engines.</p>
@@ -111,7 +113,7 @@ mode: custom
<p className="sk-mono sk-label" style={{ marginBottom: "24px", marginTop: "32px" }}>USE CASES</p>
<div className="sk-bento-row sk-bento-4col">
- <a href="/docs/cookbooks/bulk-invoice-downloader" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-teal">
+ <a href="https://www.skyvern.com/docs/cookbooks/bulk-invoice-downloader" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-teal">
<span className="sk-usecase-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="12" y1="18" x2="12" y2="12"/><polyline points="9 15 12 18 15 15"/></svg>
</span>
@@ -119,7 +121,7 @@ mode: custom
<p className="sk-cell-desc-sm">Log into vendor portals, find invoices, download PDFs.</p>
<span className="sk-mono sk-arrow-sm">↗</span>
</a>
- <a href="/docs/cookbooks/job-application-filler" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-orange">
+ <a href="https://www.skyvern.com/docs/cookbooks/job-application-filler" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-orange">
<span className="sk-usecase-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
</span>
@@ -127,7 +129,7 @@ mode: custom
<p className="sk-cell-desc-sm">Submit applications, registrations, and compliance forms.</p>
<span className="sk-mono sk-arrow-sm">↗</span>
</a>
- <a href="/docs/running-automations/extract-structured-data" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-teal">
+ <a href="https://www.skyvern.com/docs/developers/browser-automations/extract-structured-data" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-teal">
<span className="sk-usecase-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>
</span>
@@ -135,7 +137,7 @@ mode: custom
<p className="sk-cell-desc-sm">Pull structured data from any site without an API.</p>
<span className="sk-mono sk-arrow-sm">↗</span>
</a>
- <a href="/docs/cookbooks/healthcare-portal-data" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-orange">
+ <a href="https://www.skyvern.com/docs/cookbooks/healthcare-portal-data" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-orange">
<span className="sk-usecase-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
</span>
@@ -146,7 +148,7 @@ mode: custom
</div>
<div className="sk-bento-row sk-bento-4col">
- <a href="/docs/cloud/building-agents/build-an-agent" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-orange">
+ <a href="https://www.skyvern.com/docs/cloud/building-agents/build-an-agent" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-orange">
<span className="sk-usecase-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>
</span>
@@ -154,7 +156,7 @@ mode: custom
<p className="sk-cell-desc-sm">Search products, add to cart, and complete purchases on any store.</p>
<span className="sk-mono sk-arrow-sm">↗</span>
</a>
- <a href="/docs/running-automations/run-a-task" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-teal">
+ <a href="https://www.skyvern.com/docs/cloud/getting-started/run-from-code" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-teal">
<span className="sk-usecase-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 21h18"/><path d="M5 21V7l8-4v18"/><path d="M19 21V11l-6-4"/><path d="M9 9h1"/><path d="M9 13h1"/><path d="M9 17h1"/></svg>
</span>
@@ -162,7 +164,7 @@ mode: custom
<p className="sk-cell-desc-sm">Navigate complex government websites to register accounts or file forms.</p>
<span className="sk-mono sk-arrow-sm">↗</span>
</a>
- <a href="/docs/cloud/building-agents/configure-blocks" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-orange">
+ <a href="https://www.skyvern.com/docs/cloud/building-agents/configure-blocks" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-orange">
<span className="sk-usecase-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
</span>
@@ -170,7 +172,7 @@ mode: custom
<p className="sk-cell-desc-sm">Fill multi-step quote forms across providers in any language.</p>
<span className="sk-mono sk-arrow-sm">↗</span>
</a>
- <a href="/docs/cookbooks/job-application-filler" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-teal">
+ <a href="https://www.skyvern.com/docs/cookbooks/job-application-filler" className="sk-bento-cell sk-bento-cell-link sk-bento-cell-sm sk-usecase-teal">
<span className="sk-usecase-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
</span>
diff --git a/skills/skyvern/references/tool-map.md b/skills/skyvern/references/tool-map.md
index f2def6d65..ec92e5425 100644
--- a/skills/skyvern/references/tool-map.md
+++ b/skills/skyvern/references/tool-map.md
@@ -45,7 +45,7 @@
| `skyvern_scroll` | Scroll the page |
| `skyvern_press_key` | Press a keyboard key |
| `skyvern_wait` | Wait for a condition or duration |
-| `skyvern_evaluate` | Execute JavaScript in the page |
+| `skyvern_evaluate` | Execute JavaScript in the page (unavailable in extension mode) |
## Build reusable or multi-page automation
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
index 8702cfddf..993a2a30c 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
@@ -519,7 +519,7 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {
);
await waitFor(() =>
- expect(screen.getByText("Start a new chat")).toBeTruthy(),
+ expect(screen.getByText("What should this agent do?")).toBeTruthy(),
);
expect(screen.getByText("Upload an SOP")).toBeTruthy();
expect(screen.getByText("Record task")).toBeTruthy();
@@ -530,12 +530,6 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {
expect(actionLayout?.className).toContain(
"[@container_copilot-actions_(min-width:440px)]:grid-cols-2",
);
- expect(
- screen.getByText(
- "Complete the task in the browser. Skyvern captures the browser view and your clicks, typing, and navigation, then turns them into workflow steps.",
- ),
- ).toBeTruthy();
-
const file = new File(["procedure"], "procedure.pdf", {
type: "application/pdf",
});
@@ -613,7 +607,7 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {
</FeatureFlagContext.Provider>,
);
await waitFor(() =>
- expect(screen.getByText("Start a new chat")).toBeTruthy(),
+ expect(screen.getByText("What should this agent do?")).toBeTruthy(),
);
fireEvent.click(screen.getByRole("button", { name: "Upload an SOP" }));
act(() => {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 39ce6a62f..6c00b96fa 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -8930,30 +8930,25 @@ export function WorkflowCopilotChat({
messages.length === 0 &&
!isLoading &&
!recordingAuthoringActive ? (
- <div className="flex flex-col gap-5 rounded-lg border border-border bg-slate-elevation2 p-5 text-sm text-muted-foreground">
+ <div className="flex flex-col gap-6 px-1 pt-2 text-sm text-muted-foreground">
<div>
<p className="text-base font-semibold text-foreground">
- Start a new chat
+ What should this agent do?
</p>
- <p className="mt-2 leading-relaxed text-muted-foreground">
- Ask Copilot to draft or edit your agent. Provide a goal, the
- target site, and any credentials it should use.
+ <p className="mt-1.5 leading-relaxed">
+ Describe the goal and the site, and mention any login it
+ needs.
</p>
- <p className="mt-3 border-l-2 border-border bg-slate-elevation3 px-3 py-2 text-xs leading-relaxed text-muted-foreground">
- Example: “Build an agent to find the top post on Hacker News
- today.”
+ <p className="mt-2 text-xs text-muted-foreground/80">
+ Try “Find the top post on Hacker News today”
</p>
</div>
<div className="[container-name:copilot-actions] [container-type:inline-size]">
- <p className="font-semibold text-foreground">
- Or start from an existing process
+ <p className="text-xs text-muted-foreground/80">
+ Or start from
</p>
- <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
- Give Copilot the source material instead of describing it
- from scratch.
- </p>
- <div className="mt-3 grid grid-cols-1 gap-2 [@container_copilot-actions_(min-width:440px)]:grid-cols-2">
+ <div className="mt-2 grid grid-cols-1 gap-2 [@container_copilot-actions_(min-width:440px)]:grid-cols-2">
<TooltipProvider>
<ControlTooltip
content={
@@ -8986,7 +8981,7 @@ export function WorkflowCopilotChat({
: "Upload an SOP"}
</span>
<span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
- Turn an existing procedure into workflow steps.
+ A PDF of the procedure
</span>
</span>
</button>
@@ -8998,7 +8993,7 @@ export function WorkflowCopilotChat({
recordTaskDisabled
? (authoringUnavailableReason ??
"Record Task is available when the browser is ready")
- : "Demonstrate the task in the browser"
+ : "Skyvern records your clicks, typing, and navigation, then turns them into workflow steps"
}
blocked={recordTaskDisabled}
side="top"
@@ -9007,14 +9002,14 @@ export function WorkflowCopilotChat({
<button
type="button"
aria-label="Record task"
- className="flex w-full min-w-0 items-center gap-3 rounded-lg border border-red-500/45 bg-red-500/[0.06] p-3 text-left transition-colors hover:bg-red-500/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
+ className="flex w-full min-w-0 items-center gap-3 rounded-lg border border-border bg-slate-elevation3 p-3 text-left transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
disabled={recordTaskDisabled}
onClick={() => {
if (refuseMutationDuringYamlCommit()) return;
onRecordTask?.();
}}
>
- <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-red-500/40 bg-red-500/10">
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-slate-elevation2">
<span className="h-2.5 w-2.5 rounded-full bg-red-500" />
</span>
<span className="min-w-0">
@@ -9022,25 +9017,14 @@ export function WorkflowCopilotChat({
Record task
</span>
<span className="mt-0.5 block text-xs leading-snug text-muted-foreground">
- Demonstrate it in the browser and create workflow
- steps.
+ Do it once in the browser
</span>
</span>
</button>
</ControlTooltip>
</TooltipProvider>
</div>
- <p className="mt-3 text-xs leading-relaxed text-muted-foreground">
- Complete the task in the browser. Skyvern captures the
- browser view and your clicks, typing, and navigation, then
- turns them into workflow steps.
- </p>
</div>
-
- <p className="text-xs leading-relaxed text-muted-foreground">
- Already recorded this with another agent? Copy that
- workflow&apos;s prompt text and paste it here.
- </p>
</div>
) : null}
<ConvoAggregatePill
diff --git a/skyvern/browser_extension/extension/README.md b/skyvern/browser_extension/extension/README.md
index a6f749663..9529b57a8 100644
--- a/skyvern/browser_extension/extension/README.md
+++ b/skyvern/browser_extension/extension/README.md
@@ -39,13 +39,23 @@ extension becomes available.
7. Add controllable tabs to the **Skyvern Controlled** group.
-**Allow User Scripts is optional.** Leave it off for normal inspection and interaction with the browser tools.
-Only direct page evaluation (`skyvern_evaluate` and tools that call it) requires this setting. If you choose to use
-that feature, the setting is in **Skyvern Agent → Details** at `chrome://extensions`.
+Skyvern moves popups from controlled tabs into tabs in the opener's **Skyvern Controlled** group.
+The new tab becomes active only if the opener was active.
+If Chrome rejects the move, Skyvern keeps control of the separate popup.
-When evaluation is unavailable, use `skyvern_observe`, `skyvern_get_html`, `skyvern_find`, or `skyvern_get_value`,
-then the click, type, select, and keypress tools. Keep the user's permission choices; do not inject the expression
-through another API. A debugger disconnect is a separate connection problem.
+Every controlled HTTP(S) tab shows a glowing frame and the label "Skyvern is controlling this tab" while the agent is connected.
+To stop control of a tab, select **Remove from Skyvern Controlled** in the extension popup.
+You can also drag the tab out of the group.
+Tabs open before an extension update show the frame after their next reload or navigation.
+A fullscreen video or element covers the frame.
+
+Direct JavaScript evaluation is unavailable in extension mode. The `dom.evaluate` operation returns `OP_NOT_ALLOWED`:
+
+> Direct JavaScript evaluation is unavailable in extension mode. Use skyvern_observe, skyvern_get_html, skyvern_find, or skyvern_get_value to inspect the page. Use skyvern_click or skyvern_type to interact.
+
+This restriction also applies to `skyvern_evaluate` and tools that call it.
+Use the inspection and interaction tools. Do not reroute the expression through CDP or another injection API.
+Fixed value fills with `skyvern_type(input_method="value")` remain available. A debugger disconnect is a separate connection problem.
On POSIX, extension mode uses the persistent broker by default. The first broker start automatically validates or
initializes its journal and copies an existing legacy credential into the owner-only broker run directory, or creates
@@ -83,7 +93,7 @@ The extension connects outbound to `ws://127.0.0.1:19777/extension/v1` by defaul
In broker mode, `extension.secret` is daemon-owned and `skyvern browser extension-token` intentionally refuses to copy
it. Use the explicit pairing command instead. The popup token-paste flow remains available only with the legacy opt-out.
-Debugger-backed tools display Chrome's debugger infobar; direct `skyvern_evaluate` calls do not. Clicking **Cancel** in
+Debugger-backed tools display Chrome's debugger infobar. Clicking **Cancel** in
the infobar revokes debugger access. Removing a tab with the popup or dragging it out of **Skyvern Controlled** revokes
all extension access to that tab.
diff --git a/skyvern/browser_extension/extension/build_hash.json b/skyvern/browser_extension/extension/build_hash.json
index 52f103fcf..b98777f4a 100644
--- a/skyvern/browser_extension/extension/build_hash.json
+++ b/skyvern/browser_extension/extension/build_hash.json
@@ -1,3 +1,3 @@
{
- "sha256": "df25fdc72514f593b3699c34801c301b9cfeaa4706a6a64854be949f0b55b309"
+ "sha256": "bac2bf85b409f49fc3209c8656ed0f8078d0b02d9eea41858f48962f94fc80e0"
}
diff --git a/skyvern/browser_extension/extension/control_indicator.js b/skyvern/browser_extension/extension/control_indicator.js
new file mode 100644
index 000000000..029b00624
--- /dev/null
+++ b/skyvern/browser_extension/extension/control_indicator.js
@@ -0,0 +1,178 @@
+(() => {
+ let visible = false;
+ let epoch = null;
+ let revision = -1;
+ let host = null;
+ const suppressions = new Map();
+
+ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+ if (sender.id !== chrome.runtime.id) return false;
+ switch (message?.type) {
+ case "skyvern.indicator.state":
+ applyState(message);
+ return false;
+ case "skyvern.indicator.suppress":
+ if (typeof message.token !== "string" || !message.token) return false;
+ suppress(message.token);
+ render();
+ if (document.visibilityState === "hidden") {
+ sendResponse({ ok: true });
+ return false;
+ }
+ acknowledgeHidden(sendResponse);
+ return true;
+ case "skyvern.indicator.release":
+ release(message.token);
+ sendResponse({ ok: true });
+ return false;
+ default:
+ return false;
+ }
+ });
+
+ function applyState(state) {
+ if (
+ typeof state?.visible !== "boolean" ||
+ typeof state.epoch !== "string" ||
+ !Number.isSafeInteger(state.revision) ||
+ (state.epoch === epoch && state.revision <= revision)
+ )
+ return;
+ epoch = state.epoch;
+ revision = state.revision;
+ visible = state.visible;
+ render();
+ }
+
+ function suppress(token) {
+ if (typeof token !== "string" || !token || suppressions.has(token)) return;
+ suppressions.set(
+ token,
+ setTimeout(() => release(token), 60_000),
+ );
+ }
+
+ function release(token) {
+ clearTimeout(suppressions.get(token));
+ suppressions.delete(token);
+ render();
+ }
+
+ function acknowledgeHidden(sendResponse) {
+ let done = false;
+ let frame;
+ const finish = () => {
+ if (done) return;
+ done = true;
+ cancelAnimationFrame(frame);
+ document.removeEventListener("visibilitychange", onVisibility);
+ sendResponse({ ok: true });
+ };
+ const onVisibility = () => {
+ if (document.visibilityState === "hidden") finish();
+ };
+ document.addEventListener("visibilitychange", onVisibility);
+ frame = requestAnimationFrame(() => {
+ frame = requestAnimationFrame(finish);
+ });
+ }
+
+ function makeHost() {
+ const element = document.createElement("skyvern-control-indicator");
+ element.setAttribute("aria-hidden", "true");
+ for (const [name, value] of Object.entries({
+ all: "initial",
+ position: "fixed",
+ inset: "0",
+ "z-index": "2147483647",
+ "pointer-events": "none",
+ }))
+ element.style.setProperty(name, value, "important");
+ const shadow = element.attachShadow({ mode: "closed" });
+ const sheet = new CSSStyleSheet();
+ sheet.replaceSync(`
+:host{all:initial;position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:block;color-scheme:normal}
+*,*::before,*::after{box-sizing:border-box;pointer-events:none}
+.frame{position:fixed;inset:0;pointer-events:none;overflow:hidden;border-radius:10px}
+.edge,.glow,.rim{position:absolute;inset:0;overflow:hidden;border-radius:inherit}
+.edge{padding:2px;mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);mask-composite:exclude}
+.glow{opacity:.55;mask:linear-gradient(#fff,transparent) top/100% 20px,linear-gradient(0deg,#fff,transparent) bottom/100% 20px,linear-gradient(90deg,#fff,transparent) left/20px 100%,linear-gradient(270deg,#fff,transparent) right/20px 100%;mask-repeat:no-repeat;animation:breathe 4s ease-in-out infinite}
+.sweep{position:absolute;left:50%;top:50%;width:150vmax;height:150vmax;background:conic-gradient(from 25deg,#6D6CF6,#D9C8FF 28%,#022D46 55%,#6D6CF6 80%,#6D6CF6);transform:translate(-50%,-50%) rotate(0turn);animation:travel 8s linear infinite;will-change:transform}
+.pill{position:fixed;top:12px;left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:9px;height:32px;padding:0 13px 0 8px;border-radius:999px;white-space:nowrap;font:500 12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;letter-spacing:.05px;color:#fff;background:#16152ee0;backdrop-filter:blur(12px);box-shadow:0 4px 16px #16152e30,0 0 18px #6d6cf622}
+.rim{padding:1px;mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);mask-composite:exclude}
+.rim .sweep{width:300px;height:300px;background:conic-gradient(#6D6CF6,#D9C8FF 20%,#6D6CF6 40%,#022D46 70%,#6D6CF6);animation-duration:12s;opacity:.85}
+.mark{width:20px;height:20px;border-radius:50%;display:block;flex:none}
+.dot{position:relative;width:6px;height:6px;border-radius:50%;background:#9be6ca;box-shadow:0 0 6px #9be6ca55;flex:none;margin-left:3px}
+.dot::after{content:"";position:absolute;inset:-3px;border:1px solid #9be6ca;border-radius:50%;opacity:.35;animation:pulse 4s ease-in-out infinite}
+@media(max-width:599px){.pill{top:auto;bottom:12px}}
+@keyframes travel{to{transform:translate(-50%,-50%) rotate(1turn)}}
+@keyframes breathe{0%,100%{opacity:.55}50%{opacity:.9}}
+@keyframes pulse{0%,100%{transform:scale(.8);opacity:.15}50%{transform:scale(1.25);opacity:.45}}
+@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important;will-change:auto!important}.dot::after{opacity:0}}
+
+.label::after{content:"Skyvern is controlling this tab"}
+`);
+ shadow.adoptedStyleSheets = [sheet];
+ const add = (parent, tag, className) => {
+ const child = document.createElement(tag);
+ child.className = className;
+ parent.append(child);
+ return child;
+ };
+ const frame = add(shadow, "div", "frame");
+ add(add(frame, "div", "glow"), "div", "sweep");
+ add(add(frame, "div", "edge"), "div", "sweep");
+ const pill = add(shadow, "div", "pill");
+ add(add(pill, "span", "rim"), "span", "sweep");
+ const mark = add(pill, "img", "mark");
+ mark.src =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAhGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAEgAAAABAAAASAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAMKADAAQAAAABAAAAMAAAAAAoDQEPAAAACXBIWXMAAAsTAAALEwEAmpwYAAACymlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyIKICAgICAgICAgICAgeG1sbnM6ZXhpZj0iaHR0cDovL25zLmFkb2JlLmNvbS9leGlmLzEuMC8iPgogICAgICAgICA8dGlmZjpZUmVzb2x1dGlvbj43MjwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6UmVzb2x1dGlvblVuaXQ+MjwvdGlmZjpSZXNvbHV0aW9uVW5pdD4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+NzI8L3RpZmY6WFJlc29sdXRpb24+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjE8L2V4aWY6Q29sb3JTcGFjZT4KICAgICAgICAgPGV4aWY6UGl4ZWxZRGltZW5zaW9uPjI1NjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgrkVyGCAAANkElEQVRoBdVaCXCU5Rl+stnd3Pd9AoGES0KAIAmXQUAOJYJCQfAAES22nTr2mPEYtcfojLXO1Oloa6ejTp2KI4paCqhcIQkISThyJ+S+yJ3NtbvZze72eb8kEjQX0HbgY5Zs/n/3/97jeZ/3eT9w0sy5x4HbaTk5wYkvh92urNbcTrY7HA64urhAr9dB3su6vRxg1GNiouE0LOq3jQN2mx0hIUGYGTcZpl6jgtFtkwGFFkb/sR0bYejshoPODK3bIgOOvj6sXbcCKUsSceFSEaB1HrL/1q8Be58FC5MT8dwzu5CVk4fWplZoNFfjrv3OlVvsjbCMw2LFkmWL8MIvnoBep8Hh46dB+rnG0lvSAbvNpozcvPlePL37R3Bz1aGwtAZ5+SVw0l5r8rW/XePb//+XoagHBAfiKRq+Yc0yWJkFi6UfZ7Pz0csC1rAHDF//EwfEED0bjtViGb7XqO/tAgsaqnNzxZr1y7DnsQcRGRGC7t5eXraiv9+O3MLSEb//X3NAjJbisnHDsLAQ9JPqWlpMcGbK5d5IS0HF2g9XL0+kpCRj59b1SJgzAz0mCzq6etCvjO+HiYXc3m5g2x3ewgaeeNMOqLQTs4FBAYyYEdHhIZgyKRInM7IQEOCPPhrY29PzXeOxi4bhNXqL6KhwrF2RhG2pqzB7+lR0mcxo6OiEmbRppfE2ftbWb4ODvdfXzwew/zAQN+WAnWl31usxd+506HRahAf6I4SOpJ29gOXJC1Df3ILyylplvF02p1H+Qf5ISZqPzWvuwt2L5yHIwwMNRjPyKxvQ1tWtjO+z9BH3FvTyuoGZaGpqZxCMcPVwpw8OQooBGFxON6JGVeoZmaWL5mH3lvXQ6vToY9TSs3Nx4Jt0hIcGo83QiZbWdgUribq7qwv27tiEJ/n5uMgwlNZfwZcnv0XauUsoqqhFj9GkFKaN0JPPawgXnU4Hf0Y+iIFxUIFW1zSgoaERtkGWEh+uOwPy8EkRofjZw5uwM3UN6lvb8PHhkygqr4ahuxsRZJDK2npG0qqMVwXt7Iy3XnoGuwmVRmL58ZffxKdHTsGVRTsjdjKS7pwLPx8vqkw9g6Fj3TjDw90Vnoz4lcZWZJzJwaW8YvT09KpnDkX/uh2wm/vw4IZVuI8Ft3FFMq60tGHv796Cj5c7Pnr9eeicNTjAqL697yDOZF9S+ziI9zsXL1DG5xSV4aFf/h4aZuyFZ/cgfvZU6N1cYKSzfYSjldCwDmK+sroeH358EJcoHax9ZsX/wzvwkBPOTiFTXxn6ZayfYnxc3BS8+sxu2LnJvBkxLDIHjXZGQXkNymrqkbJwLqaR/jyJ68tMdzMdZL6xa8sGxESH494fP49ZM6bitRd+ygKOQGt3L660GRTjCGUKjEx0JCunEH/7+0eoYlYdJB4N95AhZqQ1IQgJbHZuux8v7d2Ozi4jqhua8ZdPDuFw+llk5ZXAQoeOnjjN1Ovw2588jARG1tPTQ22qYT+YHz8Tr7zzD0iDSr13BQ6nfYuq+mY4KGkE4/7+vnAnZJzITC0tHfj4k3+hh8X7/aZ1ww4w1IibFIEPvzyK1/76T6XHlSaRYmJ0QAYSQ/cdPoFd5HJn4jiUbCNZm0J6NJBePzuSBi8fb/zqlT+pvqAlzqVXSLOTWoiKjsIdc6azDhhTYcsROP+GHdBws5f//L5iB+FlhhZ6Fti8hFlYdGc8Gacb2edy4ePhhrbOLuRfrkFuSYXaLyV5PvYfOkanTUhMjMfc+Fnw9mZ2WC9WmwNNhNmliwXIycpFfm4BoidHIWpKNOqqamE0GkdtgkPOTAhCYrBwr+qo5OHkpYl4lCzkzCilpWcj7dRZbFqbgiriXuOkQSc1S0VJOcInRzITATh4NBM7H9+GKTFRMLLLmu3kccKytLQC2VkX0dzYwmfb1fMryyqJeS3ZSKsgOFoXvz4HBj/tTIzu3L0Zmzak4MAXJ3Dkm0zUs9CiOacmzIzFZTYtYZXM83l0xAlbUu/BwWMZCGJfqK5rQA05PDg0iBnwQikzdPTICZVVqQ1re4faxUkgSQyJjJjImlAGVBTIODv3bMO6NUvx7nufUzaYBhoKobB7aypyiy5j+rRo1Dc2I5vUt+ORTSitoAQuuIwowqKeUe4n/AooyiIiwmCgZFANUeBIhRkYHISmK40q6qMxzkgOXR1tRro7eE24fPnKJVhFefvJ50cRRLFWSk5vJHUKZhNmx+LM+QIkzZuJ1o4u7N21Bd1sOmmnc7By/UqsZe9YlJSImGkx8PL2Id4voq62gcWuhc5FTx6gDGF3DqITHqyt8WAz3NRxMyAHSL6BAUh9YC3O5xYjhDx/6IuvUV9dp4p5YfwMlLHp+LKT+pBl5PPfZGTjyLEzWLZiKU8SAlBdXoussznoEJiQYTTMWi8hIpEWqPj4eiM0LBit1E6h4cHIO5/PxnV17h1u8Pffj+8A057ITqonw3h4+6LodDbK8ktJm3rIvBoWEogKOhMdFUqHgIysAuz77CuER0WitPgyzmddQBeZyWoyqW7qNEiPQzARhw0GA+aHzIfJdB6xM4NZR67ol1mCDo63xoSQpFKGjFlsREZ2SPIEvs04d82pgIkS2EKI6VjgJpOVc2smbNy8rroWpq4uKlRfzJw6CeHEvRhkZ8SHQ0SaV6ehi+zUpwpax2box8amhpzxrOf9MTPgYOH68mHe7JaWvn5UknHaKN6ktatFKOQWl2H18iSUkIE6e81obh1gk9S1d+GBdcvhzY6s1TmrsbCssh7/PpqBdMrtAcU5ED+RJr3dRkXVFk5fnt7eaCJjTWSNmQECGh6enmC/gZldtfkK2780ssEllHeRcLKwR4guMjGKAXRYBo9JUWHwI7b1Ljq4MKo+Xh5YunAOXn/+abz48yeUXhoa3gV6XcyChZDst9p47HPt3Du030g/xxRzgs8AHufFzJzGWcSGmooq1JRVqS4qDxMc2wifBp7VJC9MQBfF2KTIEORcLFSOVdQ2oYNdWpSBH6PqyR6hobUJs6ZhKtkr/exFZbQbxZ/e1XWgiCMi0E1Z3tHWyuePHV+xYRwHHPDy9UFkbIzi8E5SZGVJmcKwGnMZOWGUjg4DWqgqJerxNM7Pzxf5pNkKvnJyi3AsMxvnLhapQX86mx5hr+rChQ6lU+t7+vrBzCK3MZOBISGsiQ5mpFMFSIwca43tAL+p45ARFTsNhlYD8nJyoeEmkeys7ixuIwtYClbOamToLqR86GGDWzB3NpZwSLEy9E2kTivh19bWgTQa29zeheQFc3hQpcVsyvNsNroa9oTe3h7SqR+ZzgftrS0wso8MMdUNOyBflEi7unmg8FwWHmVhPvfkdjyweim2b1iNzevugkynhZerFEyk05ZRy2RSmDW3tCOWouyOGbHoZ020kSpFYRazE/fynGfF4gR4urspZjrCwpY6CAgiFTOj7c3Nqj/ctAMK44x4S30DXnxqh1K4f3x/P9478BVn31McNjT49Z6HEEdYnBI80zANsyHCr5GSIq+whONlA0LZYeWEoo3ZsNOJ0rJqJM2fg8msFxcy1Gdfp5MoCFcfP1KyBZ1tHIQURseK/cC9MSEkHxHeXpw4F8EcrN/ef5j1MA1uHp6MZAmysi7hOKO9e+sGxNKJE5QOwt/iuPC7sJQcTDVQ44j29ySjiUS2mc08hvHHSp5c9Ntt+PTQSaVgpc9IFs093Soz45vPpI77IaY/KiyMCrMQU1jMDg4xrm5uiJkeR2zpUUgR9/RLb5Ii4+lIKkQ3DV/ijGSlnRDqIrs4Sw/htaZmRllIgH9UsEnZMmuYWQvCWhNd4zvAzbo4r5oYtbamNsLEirqaGrgzmmERkXCikizIK8Ib7+7Dnu3384RhnpIY3zdA5LUcvUgDE4t9KaldObk1sbjb2QOECCQDaoDnZye6xneARVVSSc0fGY7KsnJytBGePv5oqKtXkQwMCYWWCvLAoeP46lQWfvvsE5hEjreLlhlhKRnBLCzhdOaiccaJjBxCpldlxmrm2dAEsT/06HEdENlQVlENF3bUqTwyLC8uRp/ZgsDQcB6F9MHI7Li5e6jTg9ff+YBHLe146zfPIo7SWWZi6bZilLzUe1Lv+tXLsHHVEuSSsd7bf0gpT3VPsnOda9wilufJ5jV1V7By+RIOIgZUV1WzKbnC3ctLYdgskWMxmligmewVSfPuwJMPpULLHtLa3kn49QnsEUwmemTrfXiDcsLQ3YOnXvgDSjiZadgTbnRN+GhRIuRNg5MSE0iH7Sjn0O3Q6OHC6POfnSkJqEoJGxOLUE9q3Mo+8eimtdRAHPQ5fUnBRoeH8hmeOJ55Hq++/QGKisvHPToZq6ClUibsgERIFSB/ytlnIIWaFF87a0JDLMsxulCn/HOoZMRCaPn4eVP3xGIG5bQHZUMj4XWBnbeIekoOvMaLvJbWj4ZxccxKD67LAX5HrSFHtDRaYZvYlWO/qydoA3LbajGTVjmckyIVN0rIWFPSHybSZV35Nd0oKZBq6eU2NwS+oTPKIUfEGHFExNiApeKn/J8G/k2avZk1iv18sNxhj7mZh4/8XYXMkW9d99WRzXei8fKSpZVp6FZd/cyq4ucfGMjrdMDOl3bj3ck/uH2rXBgM8qjmyMn1fwCpJWsaG/VU1QAAAABJRU5ErkJggg==";
+ mark.alt = "";
+ add(pill, "span", "label");
+ add(pill, "span", "dot");
+ return element;
+ }
+
+ function render() {
+ const root = document.documentElement;
+ if (!root) return;
+ if (!host) {
+ if (!visible) return;
+ host = makeHost();
+ }
+ host.style.setProperty(
+ "display",
+ visible && suppressions.size === 0 ? "block" : "none",
+ "important",
+ );
+ if (host.parentNode !== root) {
+ for (const other of document.querySelectorAll(
+ "skyvern-control-indicator",
+ )) {
+ if (other !== host) other.remove();
+ }
+ root.append(host);
+ }
+ }
+
+ function query() {
+ try {
+ void chrome.runtime
+ .sendMessage({ type: "skyvern.indicator.query" })
+ .then((state) => {
+ for (const token of state?.captureTokens ?? []) suppress(token);
+ applyState(state);
+ render();
+ })
+ .catch(() => undefined);
+ } catch {}
+ }
+
+ query();
+ new MutationObserver(() => {
+ if (!host || host.parentNode !== document.documentElement) render();
+ }).observe(document, { childList: true, subtree: true });
+ window.addEventListener("pageshow", (event) => {
+ if (event.persisted) query();
+ });
+})();
diff --git a/skyvern/browser_extension/extension/debugger_router.js b/skyvern/browser_extension/extension/debugger_router.js
index 5dea4f5ab..297a4ce4f 100644
--- a/skyvern/browser_extension/extension/debugger_router.js
+++ b/skyvern/browser_extension/extension/debugger_router.js
@@ -35,6 +35,8 @@ export class DebuggerRouter {
tabScope,
sendEvent,
onAttachedChange,
+ isIndicatorVisible = () => false,
+ sendIndicatorMessage = async () => undefined,
attachTimeoutMs = ATTACH_TIMEOUT_MS,
commandTimeoutMs = COMMAND_TIMEOUT_MS,
recoveryTimeoutMs = RECOVERY_TIMEOUT_MS,
@@ -43,6 +45,9 @@ export class DebuggerRouter {
this.tabScope = tabScope;
this.sendEvent = sendEvent;
this.onAttachedChange = onAttachedChange;
+ this.isIndicatorVisible = isIndicatorVisible;
+ this.sendIndicatorMessage = sendIndicatorMessage;
+ this.captureReleases = new Map();
this.attachedTabs = new Set();
this.attachStates = new Map();
this.childTargets = new Map();
@@ -56,6 +61,7 @@ export class DebuggerRouter {
void this.handleDebuggerEvent(source, method, params);
});
chrome.debugger.onDetach.addListener((source, reason) => {
+ this.releaseCaptures(source.tabId);
void this.handleDebuggerDetach(source, reason);
});
}
@@ -344,12 +350,18 @@ export class DebuggerRouter {
);
let result;
try {
+ const release =
+ values.method === "Page.captureScreenshot" &&
+ this.isIndicatorVisible(tabId)
+ ? await this.suppressIndicator(tabId)
+ : undefined;
result = await this.sendCommandWithTimeout(
target,
values.method,
values.params ?? {},
commandTimeoutMs,
lease,
+ release,
);
} catch (error) {
if (urlChangeGranted) {
@@ -416,19 +428,70 @@ export class DebuggerRouter {
});
}
+ getCaptureTokens(tabId) {
+ return [...(this.captureReleases.get(tabId)?.keys() ?? [])];
+ }
+
+ async suppressIndicator(tabId) {
+ const token = crypto.randomUUID();
+ const releases = this.captureReleases.get(tabId) ?? new Map();
+ this.captureReleases.set(tabId, releases);
+ const release = () => {
+ if (!releases.delete(token)) return;
+ if (releases.size === 0) this.captureReleases.delete(tabId);
+ void this.messageIndicator(tabId, {
+ type: "skyvern.indicator.release",
+ token,
+ });
+ };
+ releases.set(token, release);
+ try {
+ await this.withTimeout(
+ () =>
+ this.messageIndicator(tabId, {
+ type: "skyvern.indicator.suppress",
+ token,
+ }),
+ 250,
+ );
+ } catch {}
+ return release;
+ }
+
+ async messageIndicator(tabId, message) {
+ try {
+ return await this.sendIndicatorMessage(tabId, message);
+ } catch {}
+ }
+
+ releaseCaptures(tabId) {
+ for (const release of this.captureReleases.get(tabId)?.values() ?? [])
+ release();
+ }
+
async sendCommandWithTimeout(
target,
method,
params,
timeoutMs,
lease = null,
+ onSettled,
) {
let timedOut = false;
const command = this.withTimeout(
() => {
- lease?.assertCurrent();
- if (lease) lease.dispatched = true;
- return chrome.debugger.sendCommand(target, method, params);
+ try {
+ lease?.assertCurrent();
+ if (lease) lease.dispatched = true;
+ const pending = chrome.debugger.sendCommand(target, method, params);
+ // The timeout/lease race can end before Chrome has sampled the pixels.
+ return onSettled
+ ? Promise.resolve(pending).finally(onSettled)
+ : pending;
+ } catch (error) {
+ onSettled?.();
+ throw error;
+ }
},
timeoutMs,
() => {
@@ -577,6 +640,7 @@ export class DebuggerRouter {
if (token !== null && this.attachStates.get(tabId)?.token !== token) {
return;
}
+ this.releaseCaptures(tabId);
this.notifyDetached(tabId, reason);
this.attachStates.delete(tabId);
this.forgetChildTargets(tabId);
diff --git a/skyvern/browser_extension/extension/dom_router.js b/skyvern/browser_extension/extension/dom_router.js
index 22a9e528a..ba1135af3 100644
--- a/skyvern/browser_extension/extension/dom_router.js
+++ b/skyvern/browser_extension/extension/dom_router.js
@@ -5,74 +5,23 @@ import {
requireTabId,
} from "./protocol.js";
-const MAX_EXPRESSION_LENGTH = 1_000_000;
-
function assertWebTab(tab) {
const url = typeof tab?.url === "string" ? tab.url.trim().toLowerCase() : "";
if (!url.startsWith("http://") && !url.startsWith("https://")) {
throw new ProtocolError(
ERROR_CODES.RESTRICTED_URL,
- "DOM evaluation is available only on HTTP or HTTPS tabs.",
+ "This operation is available only on HTTP or HTTPS tabs.",
);
}
}
-function pageEvaluationError(injectionResult) {
- if (
- typeof injectionResult?.error !== "string" ||
- injectionResult.error.length === 0
- ) {
- return null;
- }
- return new ProtocolError(
- ERROR_CODES.CDP_ERROR,
- `The page expression failed: ${injectionResult.error.slice(0, 500)}`,
+export async function evaluateDom() {
+ throw new ProtocolError(
+ ERROR_CODES.OP_NOT_ALLOWED,
+ "Direct JavaScript evaluation is unavailable in extension mode. Use skyvern_observe, skyvern_get_html, skyvern_find, or skyvern_get_value to inspect the page. Use skyvern_click or skyvern_type to interact.",
);
}
-export async function evaluateDom(tabScope, args) {
- const values = requireArgs(args);
- if (
- Object.keys(values).some((key) => !["tabId", "expression"].includes(key)) ||
- typeof values.expression !== "string" ||
- values.expression.length === 0 ||
- values.expression.length > MAX_EXPRESSION_LENGTH
- ) {
- throw new ProtocolError(
- ERROR_CODES.OP_NOT_ALLOWED,
- "A DOM evaluation requires a valid expression.",
- );
- }
- const tabId = requireTabId(values.tabId);
- return tabScope.runTabOperation(tabId, async (lease) => {
- assertWebTab(await tabScope.assertControllableLocked(tabId, lease));
- let injectionResults;
- try {
- injectionResults = await chrome.userScripts.execute({
- target: { tabId },
- world: "MAIN",
- injectImmediately: true,
- js: [{ code: values.expression }],
- });
- } catch {
- lease.assertCurrent();
- assertWebTab(await tabScope.assertControllableLocked(tabId, lease));
- throw new ProtocolError(
- ERROR_CODES.CDP_ERROR,
- "Chrome could not run this page expression. Direct evaluation requires the optional Allow User Scripts setting. Use browser controls if evaluation is unavailable; keep the user's current permissions.",
- );
- }
- lease.assertCurrent();
- assertWebTab(await tabScope.assertControllableLocked(tabId, lease));
- const injectionResult = injectionResults?.[0];
- const evaluationError = pageEvaluationError(injectionResult);
- if (evaluationError !== null) {
- throw evaluationError;
- }
- return { result: injectionResult?.result ?? null };
- });
-}
-
const FORM_FILL_ERRORS = Object.freeze({
document_changed:
"The selected document changed or the fill expired. Inspect the page before retrying.",
diff --git a/skyvern/browser_extension/extension/indicator_state.js b/skyvern/browser_extension/extension/indicator_state.js
new file mode 100644
index 000000000..fde3324f4
--- /dev/null
+++ b/skyvern/browser_extension/extension/indicator_state.js
@@ -0,0 +1,60 @@
+export class IndicatorState {
+ constructor({ sendMessage, getCaptureTokens = () => [] }) {
+ this.sendMessage = sendMessage;
+ this.getCaptureTokens = getCaptureTokens;
+ this.scopedTabs = new Set();
+ this.connected = false;
+ this.epoch = crypto.randomUUID();
+ this.revision = 0;
+ }
+
+ isVisible(tabId) {
+ return this.connected && this.scopedTabs.has(tabId);
+ }
+
+ state(tabId) {
+ return {
+ visible: this.isVisible(tabId),
+ epoch: this.epoch,
+ revision: this.revision,
+ };
+ }
+
+ query(sender) {
+ if (!Number.isInteger(sender.tab?.id) || sender.frameId !== 0) {
+ return null;
+ }
+ return {
+ ...this.state(sender.tab.id),
+ captureTokens: this.getCaptureTokens(sender.tab.id),
+ };
+ }
+
+ onScopeChange(tabId, scoped) {
+ if (scoped) {
+ this.scopedTabs.add(tabId);
+ } else {
+ this.scopedTabs.delete(tabId);
+ }
+ this.revision += 1;
+ this.push(tabId);
+ }
+
+ setConnected(connected) {
+ if (this.connected === connected) return;
+ this.connected = connected;
+ this.revision += 1;
+ for (const tabId of this.scopedTabs) this.push(tabId);
+ }
+
+ push(tabId) {
+ try {
+ void Promise.resolve(
+ this.sendMessage(tabId, {
+ type: "skyvern.indicator.state",
+ ...this.state(tabId),
+ }),
+ ).catch(() => undefined);
+ } catch {}
+ }
+}
diff --git a/skyvern/browser_extension/extension/manifest.json b/skyvern/browser_extension/extension/manifest.json
index 2767d6ef1..3c2ec4f9a 100644
--- a/skyvern/browser_extension/extension/manifest.json
+++ b/skyvern/browser_extension/extension/manifest.json
@@ -1,13 +1,12 @@
{
"manifest_version": 3,
"name": "Skyvern Agent",
- "version": "0.2.11",
+ "version": "0.2.13",
"description": "Connects explicitly shared Chrome tabs to a local Skyvern browser session.",
"minimum_chrome_version": "138",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwePOj+WEmgtKAfyF3PkP6UHuWMvHhJgt0K+53fM9I/WNgu2N4YwCqYjD0h5fr4wCZfwiElUfgwxjDBHwX/Re/Y4G7WlSEG4lDTFNSRGQczHYQnerh8NHR3Gtpq59WKtRxzbbl/e1sVxab6ZyvKjiPZlbmjL44455SldRDPBNJ/5XiSflRkgV1hJ/OOdsVT4ghzjRTJsFhFTK8X0LeMupnYbjgcLb6he0ox+dX/eeDlRt3Sq5uu9+QfJg93/yOo55c0NAa7AW+1+r37GfAtezbqk3fNSraNFfhH+GQhnA6d/KPKTC7Ut2SH1Y8NYHh1yDkyYVr2bq4T6Twr/H0YgL/wIDAQAB",
"permissions": [
"debugger",
- "userScripts",
"tabs",
"tabGroups",
"storage",
@@ -15,6 +14,13 @@
],
"host_permissions": ["http://*/*", "https://*/*"],
"content_scripts": [
+ {
+ "matches": ["http://*/*", "https://*/*"],
+ "js": ["control_indicator.js"],
+ "run_at": "document_start",
+ "all_frames": false,
+ "world": "ISOLATED"
+ },
{
"matches": ["http://*/*", "https://*/*"],
"js": ["form_controls.js"],
diff --git a/skyvern/browser_extension/extension/service_worker.js b/skyvern/browser_extension/extension/service_worker.js
index 993520e5d..922fc3c50 100644
--- a/skyvern/browser_extension/extension/service_worker.js
+++ b/skyvern/browser_extension/extension/service_worker.js
@@ -14,6 +14,7 @@ import {
ProtocolError,
requireArgs,
} from "./protocol.js";
+import { IndicatorState } from "./indicator_state.js";
import { TabScope } from "./tab_scope.js";
const PENDING_PAIRING_STORAGE_KEY = "pendingPairingOffer";
@@ -29,6 +30,13 @@ let lastResetEpoch = null;
let lastResetGeneration = -1;
let lastResetOk = null;
+const sendIndicatorMessage = (tabId, message) =>
+ chrome.tabs.sendMessage(tabId, message, { frameId: 0 });
+const indicator = new IndicatorState({
+ sendMessage: sendIndicatorMessage,
+ getCaptureTokens: (tabId) => debuggerRouter.getCaptureTokens(tabId),
+});
+
const bridge = new BridgeConnection({
onRequest: (op, args) => dispatchRequest(op, args),
onAuthenticated: async () => {
@@ -37,14 +45,20 @@ const bridge = new BridgeConnection({
},
onReset: (epoch, generation) => enqueueReset(epoch, generation),
onEvent: (event, params) => handleBrokerEvent(event, params),
- onStateChange: () => updateActionState(),
+ onStateChange: (state) => {
+ indicator.setConnected(state.connected);
+ void updateActionState();
+ },
});
const tabScope = new TabScope({
+ onScopeChange: (tabId, scoped) => indicator.onScopeChange(tabId, scoped),
sendEvent: (event, params) => bridge.sendEvent(event, params),
});
debuggerRouter = new DebuggerRouter({
+ isIndicatorVisible: (tabId) => indicator.isVisible(tabId),
+ sendIndicatorMessage,
tabScope,
sendEvent: (event, params) => bridge.sendEvent(event, params),
onAttachedChange: () => updateActionState(),
@@ -432,6 +446,10 @@ initialized.catch((error) =>
);
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+ if (message?.type === "skyvern.indicator.query") {
+ sendResponse(indicator.query(sender));
+ return false;
+ }
void initialized
.catch(() => undefined)
.then(() =>
diff --git a/skyvern/browser_extension/extension/tab_scope.js b/skyvern/browser_extension/extension/tab_scope.js
index 8215473db..3fbda32aa 100644
--- a/skyvern/browser_extension/extension/tab_scope.js
+++ b/skyvern/browser_extension/extension/tab_scope.js
@@ -61,8 +61,13 @@ function isScopeRevocation(error) {
}
export class TabScope {
- constructor({ sendEvent, operationTimeoutMs = TAB_OPERATION_TIMEOUT_MS }) {
+ constructor({
+ sendEvent,
+ onScopeChange,
+ operationTimeoutMs = TAB_OPERATION_TIMEOUT_MS,
+ }) {
this.sendEvent = sendEvent;
+ this.onScopeChange = onScopeChange;
this.scopedTabIds = new Set();
this.quarantinedTabIds = new Set();
this.scopedGroupIds = new Map();
@@ -73,6 +78,7 @@ export class TabScope {
this.creationMarkerWrite = Promise.resolve();
this.creationCleanups = new Map();
this.expectedGroupTransitions = new Map();
+ this.pendingAdoptions = new Map();
this.tabOperations = new Map();
this.debuggerRouter = null;
this.tabOperationLeases = new Map();
@@ -94,7 +100,19 @@ export class TabScope {
void this.ready.then(() => this.sweepPopupGroups());
}
});
- chrome.tabs.onAttached.addListener((tabId) => {
+ chrome.tabs.onAttached.addListener((tabId, attachInfo) => {
+ const adoption = this.pendingAdoptions.get(tabId);
+ if (adoption) {
+ if (
+ !adoption.matched &&
+ attachInfo.newWindowId === adoption.toWindowId
+ ) {
+ adoption.matched = true;
+ if (adoption.admissionDone) this.pendingAdoptions.delete(tabId);
+ return;
+ }
+ adoption.tainted = true;
+ }
if (this.scopedTabIds.has(tabId)) {
this.cancelTabOperations(
tabId,
@@ -138,6 +156,12 @@ export class TabScope {
});
}
+ notifyScopeChange(tabId, scoped) {
+ try {
+ this.onScopeChange?.(tabId, scoped);
+ } catch {}
+ }
+
setDebuggerRouter(debuggerRouter) {
this.debuggerRouter = debuggerRouter;
}
@@ -215,6 +239,7 @@ export class TabScope {
await this.sweepPopupGroups();
this.resolveReady();
await this.reconcileStoredTabs();
+ for (const tabId of this.scopedTabIds) this.notifyScopeChange(tabId, true);
}
async prepareForReset() {
@@ -248,7 +273,10 @@ export class TabScope {
async reset() {
const scopedGroups = [...this.scopedGroupIds];
+ const scopedTabIds = [...this.scopedTabIds];
this.scopedTabIds.clear();
+ for (const tabId of scopedTabIds) this.notifyScopeChange(tabId, false);
+ this.pendingAdoptions.clear();
this.scopedGroupIds.clear();
this.expectedGroupTransitions.clear();
this.tabOperations.clear();
@@ -439,6 +467,7 @@ export class TabScope {
}
const scopedTab = await this.addToScopeLocked(tab, lease);
lease.assertCurrent();
+ this.notifyScopeChange(scopedTab.id, true);
this.sendEvent(EVENTS.SCOPE_TAB_ADDED, {
...this.publicTab(scopedTab, false),
origin: "shared",
@@ -550,6 +579,7 @@ export class TabScope {
this.quarantinedTabIds.delete(tab.id);
creation.committed = true;
try {
+ this.notifyScopeChange(tab.id, true);
this.sendEvent(EVENTS.SCOPE_TAB_ADDED, {
...this.publicTab(currentTab, false),
origin: "created",
@@ -922,11 +952,75 @@ export class TabScope {
}
}
+ async adoptPopup(tab, generation) {
+ if (
+ this.quarantinedTabIds.has(tab.id) ||
+ this.activeCreation?.tabId === tab.id ||
+ !this.scopedTabIds.has(tab.openerTabId)
+ )
+ return null;
+ const groupId = this.scopedGroupIds.get(tab.openerTabId);
+ if (!Number.isInteger(groupId) || groupId <= 0) return null;
+ let opener;
+ try {
+ const child = await this.getTab(tab.id);
+ if ((await this.getWindowType(child.windowId)) !== "popup") return null;
+ opener = await this.getTab(tab.openerTabId);
+ if (
+ opener.groupId !== groupId ||
+ isTabRestricted(opener) ||
+ !(await this.getControlledGroup(groupId)) ||
+ (await this.getWindowType(opener.windowId)) !== "normal" ||
+ !this.scopedTabIds.has(tab.openerTabId) ||
+ this.scopedGroupIds.get(tab.openerTabId) !== groupId ||
+ this.quarantinedTabIds.has(tab.id) ||
+ this.activeCreation?.tabId === tab.id ||
+ generation !== this.operationGeneration
+ )
+ return null;
+ } catch {
+ return null;
+ }
+ const adoption = {
+ openerTabId: tab.openerTabId,
+ toWindowId: opener.windowId,
+ groupId,
+ openerActive: opener.active === true,
+ generation,
+ matched: false,
+ tainted: false,
+ admissionDone: false,
+ };
+ this.pendingAdoptions.set(tab.id, adoption);
+ try {
+ await chrome.tabs.move(tab.id, { windowId: opener.windowId, index: -1 });
+ return adoption;
+ } catch {
+ this.pendingAdoptions.delete(tab.id);
+ return null;
+ }
+ }
+
+ assertAdoptionCurrent(adoption) {
+ if (
+ adoption &&
+ (adoption.tainted || adoption.generation !== this.operationGeneration)
+ ) {
+ throw new ProtocolError(
+ ERROR_CODES.TAB_NOT_SCOPED,
+ "The popup moved during adoption.",
+ );
+ }
+ }
+
async handleTabCreated(tab) {
await this.ready;
if (!Number.isInteger(tab.id) || !Number.isInteger(tab.openerTabId)) {
return;
}
+ const generation = this.operationGeneration;
+ const adoption = await this.adoptPopup(tab, generation);
+ if (generation !== this.operationGeneration) return;
const admitCreatedTab = async () => {
if (
this.quarantinedTabIds.has(tab.id) ||
@@ -951,20 +1045,32 @@ export class TabScope {
this.assertCreationAdmission(tab.id);
try {
this.createdTabIds.add(tab.id);
+ this.assertAdoptionCurrent(adoption);
await this.persistScope(lease);
const scopedTab = await this.addToScopeLocked(tab, lease);
openerLease.assertCurrent();
await this.assertControllableLocked(tab.openerTabId, openerLease);
lease.assertCurrent();
+ this.assertAdoptionCurrent(adoption);
+ this.notifyScopeChange(scopedTab.id, true);
this.sendEvent(EVENTS.TABS_CREATED, {
tabId: scopedTab.id,
openerTabId: tab.openerTabId,
url: tabUrl(scopedTab),
});
+ if (adoption?.openerActive) {
+ try {
+ await chrome.tabs.update(tab.id, { active: true });
+ } catch {}
+ }
} catch (error) {
if (error.creationIdentification) {
- this.createdTabIds.delete(tab.id);
- await this.persistScope();
+ // An adopted popup cannot be the explicit creation's normal tab.
+ // Keep ownership so reset can close it while admission waits.
+ if (!adoption) {
+ this.createdTabIds.delete(tab.id);
+ await this.persistScope();
+ }
throw error;
}
if (this.scopedTabIds.has(tab.id)) {
@@ -989,11 +1095,24 @@ export class TabScope {
});
});
};
- return this.runCreationAdmission(tab.id, admitCreatedTab, true);
+ try {
+ return await this.runCreationAdmission(tab.id, admitCreatedTab, true);
+ } finally {
+ if (adoption) {
+ adoption.admissionDone = true;
+ if (
+ adoption.matched &&
+ this.pendingAdoptions.get(tab.id) === adoption
+ ) {
+ this.pendingAdoptions.delete(tab.id);
+ }
+ }
+ }
}
async handleTabRemoved(tabId) {
await this.ready;
+ this.pendingAdoptions.delete(tabId);
await this.runTabOperation(
tabId,
async (lease) => {
@@ -1151,6 +1270,7 @@ export class TabScope {
lease,
);
lease.assertCurrent();
+ this.notifyScopeChange(scopedTab.id, true);
this.sendEvent(EVENTS.SCOPE_TAB_ADDED, {
...this.publicTab(scopedTab, false),
origin: "shared",
@@ -1215,11 +1335,12 @@ export class TabScope {
return await this.assertControllableLocked(tab.id, lease);
} catch (error) {
const scopedGroupId = this.scopedGroupIds.get(tab.id);
+ this.scopedTabIds.delete(tab.id);
+ this.notifyScopeChange(tab.id, false);
+ this.scopedGroupIds.delete(tab.id);
if (Number.isInteger(scopedGroupId) && scopedGroupId >= 0) {
await this.ungroupTabLocked(tab.id, scopedGroupId);
}
- this.scopedTabIds.delete(tab.id);
- this.scopedGroupIds.delete(tab.id);
await this.persistScope(lease);
throw error;
}
@@ -1253,6 +1374,7 @@ export class TabScope {
if (!this.scopedTabIds.delete(tabId)) {
return;
}
+ this.notifyScopeChange(tabId, false);
// Hand the tab back to the operator. A later reset must not close it.
this.createdTabIds.delete(tabId);
this.expectedGroupTransitions.delete(tabId);
@@ -1288,6 +1410,17 @@ export class TabScope {
}
const windowType = await this.getWindowType(tab.windowId);
lease?.assertCurrent();
+ const adoption = this.pendingAdoptions.get(tabId);
+ this.assertAdoptionCurrent(adoption);
+ if (
+ adoption &&
+ (windowType !== "normal" || tab.windowId !== adoption.toWindowId)
+ ) {
+ throw new ProtocolError(
+ ERROR_CODES.TAB_NOT_SCOPED,
+ "The popup left its adoption window.",
+ );
+ }
if (windowType !== "normal") {
if (tab.groupId !== TAB_GROUP_ID_NONE) {
const controlledGroup = await this.getControlledGroup(tab.groupId);
@@ -1310,11 +1443,23 @@ export class TabScope {
}
let groupId;
try {
- const groups = await chrome.tabGroups.query({ windowId: tab.windowId });
+ let existingGroup;
+ if (adoption) {
+ existingGroup = await this.getControlledGroup(adoption.groupId);
+ if (!existingGroup || existingGroup.windowId !== adoption.toWindowId) {
+ throw new ProtocolError(
+ ERROR_CODES.TAB_NOT_SCOPED,
+ "The opener's group is no longer controlled.",
+ );
+ }
+ } else {
+ const groups = await chrome.tabGroups.query({ windowId: tab.windowId });
+ existingGroup = groups.find(
+ (group) => group.title === SKYVERN_GROUP_TITLE,
+ );
+ }
lease?.assertCurrent();
- const existingGroup = groups.find(
- (group) => group.title === SKYVERN_GROUP_TITLE,
- );
+ this.assertAdoptionCurrent(adoption);
const expectedGroupId = existingGroup?.id ?? ANY_GROUP_ID;
const transition = this.expectGroupTransition(tabId, expectedGroupId);
let grouped = false;
diff --git a/skyvern/browser_extension/runtime.py b/skyvern/browser_extension/runtime.py
index 764ef55fb..a67c439e1 100644
--- a/skyvern/browser_extension/runtime.py
+++ b/skyvern/browser_extension/runtime.py
@@ -340,23 +340,6 @@ class BrowserExtensionRuntime:
def describe_reported_build_hash(status: dict[str, Any]) -> str:
return status.get("extensionReportedBuildHash") or "no hash reported (pre-dates this check)"
- async def evaluate(self, expression: str) -> Any:
- await self._relay.ensure_root_lease()
- tabs = await self._relay.list_scoped_tabs()
- candidates = [tab for tab in tabs if type(tab.get("tabId")) is int]
- active = [tab for tab in candidates if tab.get("active") is True]
- if len(active) == 1:
- tab = active[0]
- elif len(candidates) == 1:
- tab = candidates[0]
- else:
- raise BrowserExtensionError("Select one Skyvern Controlled tab before evaluating JavaScript")
- result = await self._relay.request(
- "dom.evaluate",
- {"tabId": tab["tabId"], "expression": expression},
- )
- return result.get("result")
-
async def fill_input(self, page: Any, selector: str, text: str, *, timeout: float = 5.0) -> dict[str, Any]:
"""Send fixed input data to the selected page; never evaluate caller source."""
deadline = int(time.time() * 1000 + min(timeout, 30.0) * 1000)
diff --git a/skyvern/cli/commands/browser.py b/skyvern/cli/commands/browser.py
index 0dcda3df7..7c8f3fd2d 100644
--- a/skyvern/cli/commands/browser.py
+++ b/skyvern/cli/commands/browser.py
@@ -658,8 +658,9 @@ browser_app.command("extension-broker-daemon", hidden=True)(extension_broker_dae
def extension_install() -> None:
extension_dir = BrowserExtensionRuntime.extension_dir().resolve()
console.print(str(extension_dir), markup=False, soft_wrap=True)
- console.print("Allow User Scripts is optional; leave it off for normal browser control.")
- console.print("Only direct page evaluation needs that setting.")
+ console.print(
+ "Direct JavaScript evaluation is unavailable in extension mode. Use the inspection and interaction tools."
+ )
if broker_mode_enabled():
if _open_chrome_extensions():
diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.py
index 86b56959b..970e0bc1a 100644
--- a/skyvern/cli/mcp_tools/browser.py
+++ b/skyvern/cli/mcp_tools/browser.py
@@ -2684,9 +2684,11 @@ async def skyvern_evaluate(
For multi-line await, use an explicit return. Full responses are returned by default; use
``verbosity="summary"`` for an opt-in compact response. The mandatory response-size cap still applies.
On the page/CDP route an expression that never settles within the browser action deadline returns a
- TIMEOUT result; the extension route reports ACTION_FAILED with a tab-selection hint.
- In extension mode, this optional tool requires Allow User Scripts. Prefer inspection and
- interaction tools for ordinary browser tasks; keep the user's permissions if evaluation is unavailable.
+ TIMEOUT result. Direct JavaScript evaluation is unavailable in extension mode.
+ The extension returns OP_NOT_ALLOWED, which this tool reports as ACTION_FAILED.
+ Use skyvern_observe, skyvern_get_html, skyvern_find, or skyvern_get_value to inspect the page.
+ Use skyvern_click or skyvern_type to interact. Do not enable User Scripts or reroute the
+ expression through CDP or another injection API.
Security: executes in page context — use only with trusted expressions.
"""
# Block JS that sets password field values
@@ -2715,31 +2717,19 @@ async def skyvern_evaluate(
and cdp_url is None
and (session_id is None or session_id == current_context.session_id)
)
- if direct_extension_evaluation and extension_runtime is not None and current_context is not None:
- browser_context = current_context
- with Timer() as timer:
- try:
- result = await extension_runtime.evaluate(js)
- timer.mark("extension")
- except Exception as exc:
- return make_result(
- "skyvern_evaluate",
- ok=False,
- browser_context=browser_context,
- timing_ms=timer.timing_ms,
- error=make_error(
- ErrorCode.ACTION_FAILED,
- str(exc),
- "Use the inspection and interaction tools on an HTTP(S) tab in Skyvern Controlled. "
- "Direct evaluation is optional; keep the user's current permissions and do not bypass them.",
- exc=exc,
- ),
- )
+ if direct_extension_evaluation:
return make_result(
"skyvern_evaluate",
- browser_context=browser_context,
- data={"result": result, "sdk_equivalent": f"await page.evaluate({expression[:80]!r})"},
- timing_ms=timer.timing_ms,
+ ok=False,
+ browser_context=current_context,
+ error=make_error(
+ ErrorCode.ACTION_FAILED,
+ "OP_NOT_ALLOWED: Direct JavaScript evaluation is unavailable in extension mode. "
+ "Use skyvern_observe, skyvern_get_html, skyvern_find, or skyvern_get_value to inspect the page. "
+ "Use skyvern_click or skyvern_type to interact.",
+ "Use the normal browser controls. Do not enable User Scripts or reroute the expression "
+ "through CDP or another injection API.",
+ ),
)
try:
@@ -3030,6 +3020,9 @@ async def skyvern_evaluate_and_screenshot(
) -> dict[str, Any]:
"""Run JavaScript to read the page AND capture a screenshot in ONE call.
+ Direct JavaScript evaluation is unavailable in extension mode. This tool returns the evaluation
+ failure and can still return screenshot evidence. Use inspection and interaction tools instead.
+
A single "do it and prove it" primitive: your JS returns the scraped values and the tool returns
them together with a screenshot of the page as visual proof, so every fact you read is backed by
an image without a second tool call. The screenshot is saved to a file path by default (pass
diff --git a/skyvern/cli/mcp_tools/instructions.py b/skyvern/cli/mcp_tools/instructions.py
index 5528261bb..e7c2050b4 100644
--- a/skyvern/cli/mcp_tools/instructions.py
+++ b/skyvern/cli/mcp_tools/instructions.py
@@ -13,19 +13,15 @@ static JSON/XML fetches, or generic web search.
## Chrome Extension Permissions
-Normal browser control does not require Chrome's **Allow User Scripts** setting. Prefer \
-skyvern_observe, skyvern_get_html, skyvern_find, and skyvern_get_value for inspection; use \
-skyvern_click, skyvern_type, skyvern_select_option, and skyvern_press_key for interaction.
-Do not use skyvern_evaluate or evaluation composites for ordinary inspection or form filling.
-In extension mode, direct page evaluation is an optional feature that requires Allow User Scripts.
-If it is unavailable, keep the current permissions and use the browser controls. Do not route the \
-expression through CDP, another injection API, or a script shim to bypass the setting.
-Do not ask users to enable User Scripts for ordinary browser tasks or repeat a request they declined.
-A debugger disconnect is a separate connection problem; enabling User Scripts is not its remedy.
+Direct JavaScript evaluation and evaluation composites are unavailable in extension mode.
+Use skyvern_observe, skyvern_get_html, skyvern_find, or skyvern_get_value to inspect the page.
+Use skyvern_click, skyvern_type, skyvern_select_option, or skyvern_press_key to interact.
+Do not enable User Scripts or reroute the expression through CDP, another injection API, or a script shim.
+A debugger disconnect is a separate connection problem.
For a non-password text input in the selected main frame, skyvern_type with a unique CSS selector \
and input_method="value" uses a fixed bundled extension command without focusing the input. It accepts \
only plain text, requires clear=true, and cannot combine with intent, coordinates, delay, or Enter. \
-It does not require User Scripts. Keep keyboard mode for controls that need real key events.
+Keep keyboard mode for controls that need real key events.
## Task Classification — classify before choosing a tool
diff --git a/skyvern/cli/mcp_tools/prompts.py b/skyvern/cli/mcp_tools/prompts.py
index 6ecd7187e..386abee53 100644
--- a/skyvern/cli/mcp_tools/prompts.py
+++ b/skyvern/cli/mcp_tools/prompts.py
@@ -666,6 +666,26 @@ skyvern_navigate(url="http://localhost:<port>/<route>")
Health gate:
+In extension mode, use this health gate. Do not call `skyvern_evaluate`. Before each `skyvern_navigate` to a route under test, call `skyvern_get_errors(clear=True)`, `skyvern_console_messages(clear=True)`, `skyvern_handle_dialog(clear=True)`, and `skyvern_network_requests(clear=True)`; discard what they return.
+
+```text
+skyvern_tab_list()
+skyvern_get_errors()
+skyvern_console_messages(level="error")
+skyvern_get_html(selector="body")
+skyvern_find(by="role", value="alert")
+skyvern_find(by="role", value="dialog")
+skyvern_handle_dialog()
+```
+
+PASS requires the active tab URL to match the expected route, with no unexpected login redirect.
+The body must contain the expected page content, not only scripts or an empty app container.
+Require no unexpected error text, visible alerts, visible dialogs, JavaScript errors, console errors, or JavaScript dialog events.
+`skyvern_handle_dialog` reads dialog history; JavaScript dialogs are auto-dismissed by default.
+If a call fails or evidence is incomplete, record FAIL and stop this test. Do not treat missing evidence as PASS.
+
+Outside extension mode, use this health gate:
+
```text
skyvern_evaluate(expression="(() => {
const errors = [];
@@ -682,7 +702,15 @@ skyvern_evaluate(expression="(() => {
})()")
```
-Prefer deterministic DOM assertions:
+In extension mode, use `skyvern_find`, `skyvern_get_html`, `skyvern_get_value`, or `skyvern_tab_list` for assertions.
+
+```text
+skyvern_find(by="role", value="button")
+skyvern_get_html(selector="h1")
+skyvern_tab_list()
+```
+
+Outside extension mode, prefer deterministic DOM assertions:
```text
skyvern_evaluate(expression="!!document.querySelector('button')")
@@ -698,7 +726,9 @@ skyvern_validate(prompt="The page shows the success toast and the form is no lon
skyvern_screenshot()
```
-Also check for failed network requests once per page:
+In extension mode, call `skyvern_network_requests()` and inspect captured requests for failures or HTTP status codes of 400 or greater.
+If capture is unavailable or incomplete, report the network check as unverified.
+Outside extension mode, check for failed network requests once per page:
```text
skyvern_evaluate(expression="(() => {
@@ -890,13 +920,16 @@ other reviewers.
| What you need | Tool | Speed |
|---------------|------|-------|
-| Check element exists, text, count, URL | `skyvern_evaluate` | ~10ms |
+| Check element exists, text, count, URL outside extension mode | `skyvern_evaluate` | ~10ms |
| Click, type, fill forms, multi-step interaction | `skyvern_act` | 5-30s |
| Visual check | `skyvern_validate` | 15-50s |
| Screenshot | `skyvern_screenshot` | ~1s |
| Wait for async content | `skyvern_wait` | varies |
-Default to `skyvern_evaluate` for frontend/browser assertions. For backend API validation, prefer simple
+Outside extension mode only:
+Default to `skyvern_evaluate` for frontend/browser assertions.
+In extension mode, use `skyvern_find`, `skyvern_get_html`, `skyvern_get_value`, or `skyvern_tab_list` for assertions.
+For backend API validation, prefer simple
HTTP requests and deterministic response checks over browser-based inference.
---
@@ -1037,7 +1070,8 @@ If the backend contract is broken, frontend results are not trustworthy.
## Step 3A: Frontend/Browser QA
- Use browser automation against the provided URL
-- Prefer deterministic assertions with `skyvern_evaluate`
+- Outside extension mode, prefer deterministic assertions with `skyvern_evaluate`
+- In extension mode, use `skyvern_find`, `skyvern_get_html`, `skyvern_get_value`, or `skyvern_tab_list` for assertions
- Use `skyvern_act` only when a real interaction is required
- Capture a screenshot when visual evidence matters
diff --git a/skyvern/cli/skills/qa/SKILL.md b/skyvern/cli/skills/qa/SKILL.md
index e12016873..f04533476 100644
--- a/skyvern/cli/skills/qa/SKILL.md
+++ b/skyvern/cli/skills/qa/SKILL.md
@@ -187,6 +187,26 @@ skyvern_navigate(url="http://localhost:<port>/<route>")
Health gate after navigation:
+In extension mode, use this health gate. Do not call `skyvern_evaluate`. Before each `skyvern_navigate` to a route under test, call `skyvern_get_errors(clear=True)`, `skyvern_console_messages(clear=True)`, `skyvern_handle_dialog(clear=True)`, and `skyvern_network_requests(clear=True)`; discard what they return.
+
+```text
+skyvern_tab_list()
+skyvern_get_errors()
+skyvern_console_messages(level="error")
+skyvern_get_html(selector="body")
+skyvern_find(by="role", value="alert")
+skyvern_find(by="role", value="dialog")
+skyvern_handle_dialog()
+```
+
+PASS requires the active tab URL to match the expected route, with no unexpected login redirect.
+The body must contain the expected page content, not only scripts or an empty app container.
+Require no unexpected error text, visible alerts, visible dialogs, JavaScript errors, console errors, or JavaScript dialog events.
+`skyvern_handle_dialog` reads dialog history; JavaScript dialogs are auto-dismissed by default.
+If a call fails or evidence is incomplete, record FAIL and stop this test. Do not treat missing evidence as PASS.
+
+Outside extension mode, use this health gate:
+
```text
skyvern_evaluate(expression="(() => {
const errors = [];
@@ -203,7 +223,15 @@ skyvern_evaluate(expression="(() => {
})()")
```
-Prefer deterministic DOM assertions:
+In extension mode, use `skyvern_find`, `skyvern_get_html`, `skyvern_get_value`, or `skyvern_tab_list` for assertions.
+
+```text
+skyvern_find(by="role", value="button")
+skyvern_get_html(selector="h1")
+skyvern_tab_list()
+```
+
+Outside extension mode, prefer deterministic DOM assertions:
```text
skyvern_evaluate(expression="!!document.querySelector('button')")
@@ -220,7 +248,9 @@ skyvern_validate(prompt="The page shows the success toast and the form is no lon
skyvern_screenshot()
```
-Also check for failed network requests once per page:
+In extension mode, call `skyvern_network_requests()` and inspect captured requests for failures or HTTP status codes of 400 or greater.
+If capture is unavailable or incomplete, report the network check as unverified.
+Outside extension mode, check for failed network requests once per page:
```text
skyvern_evaluate(expression="(() => {
diff --git a/skyvern/cli/skills/skyvern/references/tool-map.md b/skyvern/cli/skills/skyvern/references/tool-map.md
index f2def6d65..ec92e5425 100644
--- a/skyvern/cli/skills/skyvern/references/tool-map.md
+++ b/skyvern/cli/skills/skyvern/references/tool-map.md
@@ -45,7 +45,7 @@
| `skyvern_scroll` | Scroll the page |
| `skyvern_press_key` | Press a keyboard key |
| `skyvern_wait` | Wait for a condition or duration |
-| `skyvern_evaluate` | Execute JavaScript in the page |
+| `skyvern_evaluate` | Execute JavaScript in the page (unavailable in extension mode) |
## Build reusable or multi-page automation
diff --git a/skyvern/cli/skills/smoke-test/SKILL.md b/skyvern/cli/skills/smoke-test/SKILL.md
index c0e727c4c..d1f8bcaba 100644
--- a/skyvern/cli/skills/smoke-test/SKILL.md
+++ b/skyvern/cli/skills/smoke-test/SKILL.md
@@ -236,6 +236,26 @@ Never omit it and rely on the current page - this prevents test-to-test state bl
After navigation, run the health gate to catch broken pages early:
+In extension mode, use this health gate. Do not call `skyvern_evaluate`. Before each `skyvern_navigate` to a route under test, call `skyvern_get_errors(clear=True)`, `skyvern_console_messages(clear=True)`, `skyvern_handle_dialog(clear=True)`, and `skyvern_network_requests(clear=True)`; discard what they return.
+
+```text
+skyvern_tab_list()
+skyvern_get_errors()
+skyvern_console_messages(level="error")
+skyvern_get_html(selector="body")
+skyvern_find(by="role", value="alert")
+skyvern_find(by="role", value="dialog")
+skyvern_handle_dialog()
+```
+
+PASS requires the active tab URL to match the expected route, with no unexpected login redirect.
+The body must contain the expected page content, not only scripts or an empty app container.
+Require no unexpected error text, visible alerts, visible dialogs, JavaScript errors, console errors, or JavaScript dialog events.
+`skyvern_handle_dialog` reads dialog history; JavaScript dialogs are auto-dismissed by default.
+If a call fails or evidence is incomplete, record FAIL and stop this test. Do not treat missing evidence as PASS.
+
+Outside extension mode, use this health gate:
+
```text
skyvern_evaluate(expression="(() => {
const errors = [];
diff --git a/skyvern/cli/skills/testing/SKILL.md b/skyvern/cli/skills/testing/SKILL.md
index 9c47c9105..0b87fb0b3 100644
--- a/skyvern/cli/skills/testing/SKILL.md
+++ b/skyvern/cli/skills/testing/SKILL.md
@@ -27,6 +27,17 @@ skyvern_evaluate(expression="fetch('/api/v1/workflows?page=1&page_size=1', {cred
A 2xx means fully healthy; 401/403 means the backend is running but requires authentication.
Only `status: 0` or a network error means the backend is actually down.
+In extension mode, `skyvern_evaluate` is unavailable, so use these commands after you create the browser session:
+
+```
+skyvern_navigate(url="{{base_url}}/api/v1/workflows?page=1&page_size=1")
+skyvern_network_requests(url_pattern="/api/v1/workflows", resource_type="document")
+```
+
+**Pass**: Read the document response's `status`; any HTTP status confirms the backend is reachable.
+A 2xx means fully healthy; 401 or 403 means the backend is running but requires authentication.
+No captured response means the backend is down.
+
```
skyvern_navigate(url="{{base_url}}/discover")
skyvern_validate(prompt="The page does NOT show any error messages, error toasts, 'Something went wrong', a persistent loading spinner, a blank white screen, or a connection refused message")
diff --git a/skyvern/config.py b/skyvern/config.py
index e2856be21..dc211692e 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -558,9 +558,6 @@ class Settings(BaseSettings):
# actuation without the probe realm gives working actions whose readbacks answer about the main
# document instead of the element's own -- a verdict reported without being measured.
TASK_V3_FRAME_PERCEPTION: bool = False
- # Force-on term only: the arm is randomized per run by the flag of the same name and read through
- # run_arm_enabled() in skyvern/forge/taskv3/run_arms.py (SKY-16501).
- TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED: bool = False
# Swap in the fill-rule text an AgentFunction supplies (task_v3_required_field_answers_text); with no
# text supplied the run gets the control prompt. Force-on term only: runs are randomized per run by the
# flag of the same name, read through run_arm_enabled().
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 512f5b6d4..bf6c56c95 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -198,7 +198,6 @@ from skyvern.forge.taskv3.run_arms import (
EXTRACTION_REPORTS_FLAG,
GOAL_CHECK_ENFORCE_FLAG,
GOAL_CHECK_FLAG,
- OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG,
REQUIRED_FIELD_ANSWERS_FLAG,
TYPE_COORDINATE_CLICK_FLAG,
resolve_run_arm,
@@ -2270,13 +2269,6 @@ class ForgeAgent:
distinct_id=task.workflow_run_id or task.task_id,
organization_id=task.organization_id,
)
- await resolve_run_arm(
- context,
- OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG,
- distinct_id=task.workflow_run_id or task.task_id,
- organization_id=task.organization_id,
- forced=settings.TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED,
- )
await resolve_run_arm(
context,
TYPE_COORDINATE_CLICK_FLAG,
@@ -2491,6 +2483,9 @@ class ForgeAgent:
# verdict composed late must check the page's name against the registry as it stands then.
return _taskv3_label_secret_values(task)
+ def _login_identifier_tokens() -> Collection[str]:
+ return app.WORKFLOW_CONTEXT_MANAGER.login_identifier_secret_ids_for_run(task.workflow_run_id)
+
async def _should_cancel() -> bool:
refreshed = await app.DATABASE.tasks.get_task(
task_id=task.task_id, organization_id=organization.organization_id
@@ -3163,6 +3158,7 @@ class ForgeAgent:
initial_navigation_url=initial_navigation_url,
caller_known_urls=verdict_known_urls,
label_secret_values=_label_secret_values,
+ login_identifier_tokens=_login_identifier_tokens,
)
finally:
if context and credential_parameter_key is not None:
diff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.py
index 6cfe2f92e..9f81d444d 100644
--- a/skyvern/forge/sdk/workflow/context_manager.py
+++ b/skyvern/forge/sdk/workflow/context_manager.py
@@ -338,6 +338,8 @@ class WorkflowRunContext:
self.browser_session_id: str | None = None
self.include_secrets_in_templates: bool = False
self.credential_totp_identifiers: dict[str, str] = {}
+ # Secret ids minted for the username slot of a login credential; never derived from a field name.
+ self.login_identifier_secret_ids: set[str] = set()
self.resolved_credential_parameter_ids: dict[str, str] = {}
# tested_url per credential parameter key: where each credential's secrets may be released.
self.credential_tested_urls: dict[str, str] = {}
@@ -1045,6 +1047,8 @@ class WorkflowRunContext:
secret_id = f"{random_secret_id}_{field_key}"
self.secrets[secret_id] = field_value
self.values[parameter.key][field_key] = secret_id
+ if isinstance(credential, PasswordCredential) and key == "username" and credential.password:
+ self.login_identifier_secret_ids.add(secret_id)
if isinstance(credential, PasswordCredential) and credential.totp:
random_secret_id = self.generate_random_secret_id()
@@ -1477,6 +1481,8 @@ class WorkflowRunContext:
self.secrets[username_secret_id] = secret_credentials[BitwardenConstants.USERNAME]
password_secret_id = f"{random_secret_id}_password"
self.secrets[password_secret_id] = secret_credentials[BitwardenConstants.PASSWORD]
+ if secret_credentials[BitwardenConstants.PASSWORD]:
+ self.login_identifier_secret_ids.add(username_secret_id)
self.values[parameter.key] = {
"context": "These values are placeholders. When you type this in, the real value gets inserted (For security reasons)",
"username": username_secret_id,
@@ -1535,6 +1541,7 @@ class WorkflowRunContext:
# login secret
username_secret_id = f"{random_secret_id}_username"
self.secrets[username_secret_id] = secret_username
+ self.login_identifier_secret_ids.add(username_secret_id)
# password secret
password_secret_id = f"{random_secret_id}_password"
self.secrets[password_secret_id] = secret_password
@@ -2229,6 +2236,11 @@ class WorkflowContextManager:
return set()
return collect_redactable_secret_values({}, otp_values=list(current_context.runtime_secret_values))
+ def login_identifier_secret_ids_for_run(self, workflow_run_id: str | None) -> frozenset[str]:
+ if workflow_run_id is None or workflow_run_id not in self.workflow_run_contexts:
+ return frozenset()
+ return frozenset(self.workflow_run_contexts[workflow_run_id].login_identifier_secret_ids)
+
def secret_values_for_drop_check(self, workflow_run_id: str | None) -> set[str]:
"""Every configured secret value, with no numeric floor and no masking opt-in, for a check that only
DROPS page text on a match and never redacts with the set: a short PIN or CVV must still match."""
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index a3e9c4acd..b9128932c 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -293,6 +293,7 @@ async def run_task_v3_agent_loop(
initial_navigation_url: str | None = None,
caller_known_urls: frozenset[str] = frozenset(),
label_secret_values: Callable[[], Collection[str]] | None = None,
+ login_identifier_tokens: Callable[[], Collection[str]] | None = None,
page_probe: Callable[[], Awaitable[str | None]] | None = None,
reload_page: Callable[[], Awaitable[None]] | None = None,
restore_page_url: Callable[[Any, str], Awaitable[None]] | None = None,
@@ -571,6 +572,7 @@ async def run_task_v3_agent_loop(
initial_navigation_url=initial_navigation_url,
caller_known_urls=caller_known_urls,
label_secret_values=label_secret_values,
+ login_identifier_tokens=login_identifier_tokens,
page_probe=None if page_free else page_probe,
page_fingerprint=None if page_free else page_fingerprint,
reload_page=None if page_free else reload_page,
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 75df88d0e..86830ba99 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -1298,6 +1298,10 @@ CREDENTIAL_ENTRY_TOOLS = (FILL_TOOLS | frozenset({CODE_TOOL_NAME})) - frozenset(
# threshold. It is chosen against today's submit precision — _may_submit counts any click, so a
# click that submits nothing still spends budget — and must be re-derived if that precision improves.
CREDENTIAL_SUBMIT_BUDGET = 2
+# A login identifier spends no lockout allowance, but identifier-first flows can send a code or hit lookup
+# throttles on every submit, so it gets a higher budget rather than none — 5 is an unmeasured judgment
+# with no replay behind it, unlike CREDENTIAL_SUBMIT_BUDGET.
+LOGIN_IDENTIFIER_SUBMIT_BUDGET = 5
def _credential_placeholders(args: dict[str, Any]) -> set[str]:
@@ -2839,6 +2843,9 @@ async def run_agent_tool_loop(
# Resolves the run's drop-check secret values when a verdict is about to name a page-supplied
# element. Read at verdict time, not loop start: the registry grows as a run resolves credentials.
label_secret_values: Callable[[], Collection[str]] | None = None,
+ # Placeholder tokens minted for a login credential's username slot, held to
+ # LOGIN_IDENTIFIER_SUBMIT_BUDGET instead of CREDENTIAL_SUBMIT_BUDGET. Read per refusal.
+ login_identifier_tokens: Callable[[], Collection[str]] | None = None,
page_probe: Callable[[], Awaitable[str | None]] | None = None,
reload_page: Callable[[], Awaitable[None]] | None = None,
max_refresh_cycles: int = 3,
@@ -3540,6 +3547,17 @@ async def run_agent_tool_loop(
if tool_name in CREDENTIAL_ENTRY_TOOLS
else set()
)
+ if spent_credentials and login_identifier_tokens is not None:
+ try:
+ identifiers = set(login_identifier_tokens())
+ except Exception:
+ LOG.warning("taskv3 loop could not resolve the run's login identifier tokens", tool=tool_name)
+ identifiers = set()
+ spent_credentials = {
+ token
+ for token in spent_credentials
+ if token not in identifiers or st.credential_submits.get(token, 0) >= LOGIN_IDENTIFIER_SUBMIT_BUDGET
+ }
if spent_credentials:
LOG.info(CREDENTIAL_RESUBMIT_REFUSED_EVENT, tool=tool_name, turn=st.turns)
if activity is not None:
diff --git a/skyvern/forge/taskv3/run_arms.py b/skyvern/forge/taskv3/run_arms.py
index fc1b6f045..206e7984d 100644
--- a/skyvern/forge/taskv3/run_arms.py
+++ b/skyvern/forge/taskv3/run_arms.py
@@ -16,7 +16,6 @@ from skyvern.forge.sdk.experimentation.providers import NoOpExperimentationProvi
LOG = structlog.get_logger()
-OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG = "TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED"
TYPE_COORDINATE_CLICK_FLAG = "TASK_V3_TYPE_COORDINATE_CLICK"
DATE_SEGMENT_AIM_FLAG = "TASK_V3_DATE_SEGMENT_AIM"
REQUIRED_FIELD_ANSWERS_FLAG = "TASK_V3_REQUIRED_FIELD_ANSWERS"
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index f80d67f6e..315c9584f 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -80,7 +80,6 @@ from skyvern.forge.taskv3.loop import (
from skyvern.forge.taskv3.preflight import PREFLIGHT_TOOL_NAMES, preflight_tool_action
from skyvern.forge.taskv3.run_arms import (
DATE_SEGMENT_AIM_FLAG,
- OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG,
TYPE_COORDINATE_CLICK_FLAG,
run_arm_enabled,
)
@@ -5698,6 +5697,11 @@ _FIND_MENU_JS = (
+ _MENU_ROW_ROLES_JS
+ r""";
const vis = (r) => r.width > 0 && r.height > 0;
+ // 80 is the shared "row-sized text, not a paragraph" ceiling. A row the page declares an option or
+ // menu item may run to ROW_TEXT_MAX, so a long option caption is listed whole.
+ const UNDECLARED_ROW_TEXT_MAX = 80;
+ const ROW_TEXT_MAX = 200;
+ const DECLARED_ROW_SEL = OPT_SEL + ',[role="menuitem"]';
// `cascade`: the caller just clicked a row that DETACHED (a category replacing the list with its
// children). The trigger is gone, so trigger-anchored geometry/ARIA is waived — new rows in a
// FLOATING container carry the claim instead (enforced below).
@@ -5733,7 +5737,14 @@ _FIND_MENU_JS = (
const r = el.getBoundingClientRect();
if (!vis(r) || r.height > 90) continue;
const txt = (el.innerText || '').trim();
- if (!txt || txt.length > 80) continue;
+ if (!txt || txt.length > ROW_TEXT_MAX) continue;
+ // A long row is an option only when the page declares one on it, in it or around it: an inherited
+ // pointer cursor otherwise makes every paragraph of a clickable popover read as a menu row.
+ if (txt.length > UNDECLARED_ROW_TEXT_MAX) {
+ let declaresOption = false;
+ try { declaresOption = el.matches(DECLARED_ROW_SEL) || !!el.querySelector(DECLARED_ROW_SEL) || !!composedClosest(el, DECLARED_ROW_SEL); } catch (e) { declaresOption = false; }
+ if (!declaresOption) continue;
+ }
// Options are individually actionable rows. Requiring it per-row keeps a dialog's title/body
// text from being listed as "options" (and a horizontal Confirm/Cancel button pair then fails
// the stacked-rows check below). The role set is observe's, minus the container and
@@ -5876,7 +5887,7 @@ _FIND_MENU_JS = (
for (const c of best.g) {
n++;
c.el.setAttribute('data-tv3-menu', String(n));
- if (options.length < 15) options.push({ n, text: c.txt.slice(0, 60) });
+ if (options.length < 15) options.push({ n, text: c.txt.slice(0, ROW_TEXT_MAX) });
}
// Undeclared virtualisation: a list that renders only a window declares nothing (no aria-setsize),
// but its scroll container carries the FULL extent (react-window sizes a spacer to the whole list).
@@ -5913,7 +5924,26 @@ _FIND_MENU_JS = (
}
}
} catch (e) { partial = false; }
- return { count: n, options, partial };
+ // A listbox or menu declares its options even when a row renders nothing this finder can read. Only
+ // rendered, outermost options count (a filter hides the rest), unless the options state the set size.
+ let declared = 0;
+ try {
+ const LIST_ROLES = '[role="listbox"],[role="menu"]';
+ const lb = composedClosest(best.g[0].el, LIST_ROLES);
+ if (lb && best.g.every((c) => composedClosest(c.el, LIST_ROLES) === lb)) {
+ const itemSel = lb.getAttribute('role') === 'menu'
+ ? '[role="menuitem"],[role="menuitemradio"],[role="menuitemcheckbox"]'
+ : '[role="option"]';
+ for (const o of lb.querySelectorAll(itemSel)) {
+ const size = parseInt(o.getAttribute('aria-setsize') || '', 10);
+ if (size > 0) { declared = size; break; }
+ const outer = o.parentElement && o.parentElement.closest(itemSel);
+ if (outer && lb.contains(outer)) continue;
+ if (vis(o.getBoundingClientRect())) declared++;
+ }
+ }
+ } catch (e) { declared = 0; }
+ return declared > n ? { count: n, options, partial, declared } : { count: n, options, partial };
}"""
)
@@ -6354,7 +6384,6 @@ async () => {
// Field text is retained at this width and masked, then capped for display, in Python. Substituted
// per call from the payload refs: any minted URL that starts inside a display window fits whole.
const _RETAIN_WIDTH = __OBSERVE_RETAIN_WIDTH__;
- const _DROP_OFFVIEWPORT_UNNAMED = __OBSERVE_DROP_OFFVIEWPORT_UNNAMED__;
const _GROUP_TEXT_TOTAL_CAP = """
+ str(OBSERVE_GROUP_TEXT_TOTAL_CAP)
+ r""";
@@ -6367,6 +6396,7 @@ async () => {
// that also holds text fields has an innerText naming every question in it.
const _NONCHOICE_SEL = 'input:not([type=hidden]):not([type=checkbox]):not([type=radio]),textarea,select,[role=combobox],[role=listbox],[role=spinbutton],[contenteditable]:not([contenteditable="false" i])';
const _CHOICE_SEL = 'input[type=checkbox],input[type=radio],[role=checkbox],[role=radio],[role=switch]';
+ const _CAPTIONED_CHOICE_SEL = 'input[type=checkbox],input[type=radio],[role=checkbox],[role=radio]';
// Read through the prototypes: the walk below crosses the control's <form>, whose named controls
// shadow its own properties (<input name="matches"> makes form.matches that input).
const _getter = (proto, name) => {
@@ -6421,54 +6451,429 @@ async () => {
if (!_qs.call(el, _CHOICE_SEL)) return false;
try { return _visibleText(el, 0).length < 2; } catch (e) { return true; }
};
- // Question text for a control whose own name is weak. Choice controls take the text of the
- // nearest group ancestor that has any (legend + options), if it is purely options. Text fields
- // take the nearest text block that PRECEDES the control inside that ancestor, stopping at a
- // previous control: a container holding several questions has an innerText naming all of them,
+ // Question text for a control whose own name is weak. Choice controls take their group's question
+ // (_choiceGroupText). Text fields take the nearest text block that
+ // PRECEDES the control inside that ancestor, stopping at a previous control: a container holding several questions has an innerText naming all of them,
// and a group text that names the wrong question is the mis-association this field exists to
// end. The ancestor's own text is used only when it wraps this one control. Bounded to 6 levels
// and 8 siblings. Any throw yields no group text, never a dropped element.
const _groupText = (el, isChoice) => {
+ if (isChoice) return _choiceGroupText(el);
try {
let node = el;
for (let depth = 0; depth < 6; depth++) {
const parent = _parentOf.call(node);
if (!parent) break;
- if (!isChoice) {
- let scanned = 0;
- for (let s = _prevOf.call(node); s && scanned < 8; s = _prevOf.call(s), scanned++) {
- const kind = _nodeTypeOf.call(s);
- if (kind === 3) {
- const t = _normText(_contentOf.call(s));
- if (t.length >= 2) return t;
- continue;
- }
- if (kind !== 1) continue;
- if (_matches.call(s, _CTRL_SEL) || _qs.call(s, _CTRL_SEL)) break;
- if (_unseen(s)) continue;
- let t = '';
- try { t = _normText(_innerTextOf.call(s)); } catch (e) { continue; }
- // One character is decoration (a required marker), never a question.
- if (t.length < 2) continue;
- // Text right after a checkbox or radio -- bare, or in a wrapper with no text of its own --
- // is that control's caption, not this one's question. A previous question block that
- // happens to hold options is not a wrapper, and the text after it is the next question.
- let before = _prevOf.call(s);
- while (before && _nodeTypeOf.call(before) !== 1 && !_normText(_contentOf.call(before))) before = _prevOf.call(before);
- if (before && _nodeTypeOf.call(before) === 1 && _captionHost(before)) break;
- return t;
+ let scanned = 0;
+ for (let s = _prevOf.call(node); s && scanned < 8; s = _prevOf.call(s), scanned++) {
+ const kind = _nodeTypeOf.call(s);
+ if (kind === 3) {
+ const t = _normText(_contentOf.call(s));
+ if (t.length >= 2) return t;
+ continue;
}
+ if (kind !== 1) continue;
+ if (_matches.call(s, _CTRL_SEL) || _qs.call(s, _CTRL_SEL)) break;
+ if (_unseen(s)) continue;
+ let t = '';
+ try { t = _normText(_innerTextOf.call(s)); } catch (e) { continue; }
+ // One character is decoration (a required marker), never a question.
+ if (t.length < 2) continue;
+ // Text right after a checkbox or radio -- bare, or in a wrapper with no text of its own --
+ // is that control's caption, not this one's question. A previous question block that
+ // happens to hold options is not a wrapper, and the text after it is the next question.
+ let before = _prevOf.call(s);
+ while (before && _nodeTypeOf.call(before) !== 1 && !_normText(_contentOf.call(before))) before = _prevOf.call(before);
+ if (before && _nodeTypeOf.call(before) === 1 && _captionHost(before)) break;
+ return t;
}
node = parent;
if (!_matches.call(node, _GROUP_SEL)) continue;
const t = _normText(_innerTextOf.call(node));
if (!t) continue;
- if (isChoice) return _qsa.call(node, _NONCHOICE_SEL).length === 0 ? t : '';
return _qsa.call(node, _CTRL_SEL).length === 1 ? t : '';
}
} catch (e) { /* fail open: the record keeps today's shape */ }
return '';
};
+ // A choice group's question: the legacy text for this member when it names more than the options,
+ // else what the page declares for the group, resolved once per group.
+ const _choiceGroupText = (el) => {
+ const legacy = _legacyChoiceText(el);
+ if (legacy) return legacy;
+ let g;
+ try { g = _choiceGroup(el); } catch (e) { return ''; }
+ let declared = g.entry ? g.entry.text : undefined;
+ if (declared === undefined) {
+ try { declared = _choiceQuestion(el, g); } catch (e) { declared = ''; }
+ if (g.entry) g.entry.text = declared;
+ }
+ return declared || '';
+ };
+ // The pre-declared-name rung, unchanged: the first group ancestor with any text, if it holds no
+ // non-choice control. Text that is only the options' captions names no question.
+ const _legacyChoiceText = (el) => {
+ try {
+ let node = el;
+ for (let depth = 0; depth < 6; depth++) {
+ const parent = _parentOf.call(node);
+ if (!parent) break;
+ node = parent;
+ if (!_matches.call(node, _GROUP_SEL)) continue;
+ const t = _innerTextMemo(node);
+ if (!t) continue;
+ if (_qsa.call(node, _NONCHOICE_SEL).length) return '';
+ return _captionsOnly(node, t) ? '' : t;
+ }
+ } catch (e) { /* fail open: no group text */ }
+ return '';
+ };
+ // A choice group's question is its members' own group text unless that is only captions, then a declared
+ // name that holds exactly this group, else the no-question marker.
+ // Radios sharing a name are one group whatever the markup around them, so they are keyed by name
+ // within their options container (else form or root); other choices by that container alone. Every
+ // member of a group then reads the same question, computed once.
+ const _choiceGroups = new Map();
+ const _choiceGroupOf = new Map();
+ // A radio and a checkbox are never options of one question.
+ const _RADIO_SEL = 'input[type=radio],[role=radio]';
+ const _CHECK_SEL = 'input[type=checkbox],[role=checkbox],[role=switch]';
+ // Group finding crosses shadow boundaries: an option component may hold its native input in its own
+ // shadow root, and a plain parentElement walk would make every option a group of one.
+ const _composedParent = (n) => {
+ const p = _parentOf.call(n);
+ if (p) return p;
+ const root = Node.prototype.getRootNode.call(n);
+ return root && root.nodeType === 11 ? root.host : null;
+ };
+ const _openShadowOf = (n) => { try { return _shadowRootOf.call(n); } catch (e) { return null; } };
+ // Memoised per box for the call: every member of a group asks the same questions of the same boxes.
+ const _memo = (fn) => {
+ const seen = new Map();
+ return (box, arg) => {
+ let byArg = seen.get(box);
+ if (!byArg) { byArg = new Map(); seen.set(box, byArg); }
+ if (!byArg.has(arg)) byArg.set(arg, fn(box, arg));
+ return byArg.get(arg);
+ };
+ };
+ // Controls of one kind under box, one shadow level deep, counted only as far as 2. A native input the
+ // page hides beside an ARIA proxy of the same kind is that proxy's form value, not a second option.
+ const _proxiedNative = (c, kin) => {
+ if (_tagNameOf.call(c) === 'INPUT' && (c.getAttribute('aria-hidden') === 'true' || _unseen(c))) {
+ const p = _parentOf.call(c);
+ if (p && Array.from(_qsa.call(p, kin)).some((o) => _tagNameOf.call(o) !== 'INPUT')) return true;
+ }
+ return false;
+ };
+ // Calls visit on box and on each open shadow root one level under it, until visit returns true or
+ // cap descendants have been walked. A page whose root walk found no shadow root has none to visit.
+ const _eachScope = (box, visit, cap) => {
+ if (visit(box) || (allRoots.length < 2 && !undiscoveredRoots)) return;
+ const walker = document.createTreeWalker(box, 1);
+ for (let d = walker.nextNode(), seen = 0; d && seen < cap; d = walker.nextNode(), seen++) {
+ const sr = _openShadowOf(d);
+ if (sr && visit(sr)) return;
+ }
+ };
+ const _qsaIn = (scope, sel) => (_nodeTypeOf.call(scope) === 11 ? scope.querySelectorAll(sel) : _qsa.call(scope, sel));
+ const _kinCount = _memo((box, kin) => {
+ let n = 0;
+ _eachScope(box, (scope) => {
+ for (const c of _qsaIn(scope, kin)) {
+ if (!_proxiedNative(c, kin)) n++;
+ if (n > 1) return true;
+ }
+ return false;
+ }, 400);
+ return n;
+ });
+ const _hasChoice = (n) => {
+ if (_matches.call(n, _CHOICE_SEL) || _qs.call(n, _CHOICE_SEL)) return true;
+ const sr = _openShadowOf(n);
+ return !!sr && !!sr.querySelector(_CHOICE_SEL);
+ };
+ const _nodeText = (c) => (_nodeTypeOf.call(c) === 3 ? _normText(_contentOf.call(c)) : _visibleText(c, 1));
+ const _radioNameCount = _memo((box) => {
+ const names = new Set();
+ for (const r of _qsa.call(box, 'input[type=radio]')) { if (r.name) names.add(r.name); }
+ return names.size;
+ });
+ // Several questions share box when it holds a non-choice control, radios of more than one name, or
+ // text after its first option that is no option's caption.
+ const _holdsSeveralGroups = _memo((box) => {
+ for (const c of _qsa.call(box, _CTRL_SEL)) { if (!_matches.call(c, _CHOICE_SEL)) return true; }
+ if (_radioNameCount(box) > 1) return true;
+ let seenOption = false;
+ for (let c = _firstChildOf.call(box); c; c = _nextOf.call(c)) {
+ const kind = _nodeTypeOf.call(c);
+ if (kind !== 1 && kind !== 3) continue;
+ if (kind === 1 && _hasChoice(c)) { seenOption = true; continue; }
+ if (seenOption && !_afterChoice(c) && _nodeText(c).length >= 2) return true;
+ }
+ return false;
+ });
+ // A radiogroup within 4 composed levels is the group whatever it holds. Otherwise the options
+ // container is the lowest such ancestor holding another control of this kind.
+ const _choiceGroup = (el) => {
+ const known = _choiceGroupOf.get(el);
+ if (known) return known;
+ const radio = _matches.call(el, _RADIO_SEL);
+ const kin = radio ? _RADIO_SEL : _CHECK_SEL;
+ let box = null;
+ let declaredBox = false;
+ let node = el;
+ for (let depth = 0; radio && depth < 4 && node; depth++) {
+ node = _composedParent(node);
+ // A radiogroup whose native radios carry several names holds several groups; the names decide.
+ if (node && _matches.call(node, '[role=radiogroup]') && _radioNameCount(node) < 2) { box = node; declaredBox = true; }
+ if (box) break;
+ }
+ node = el;
+ for (let depth = 0; !box && depth < 4; depth++) {
+ node = _composedParent(node);
+ if (!node) break;
+ if (_kinCount(node, kin) > 1) box = node;
+ }
+ const multi = !!box && !declaredBox && _holdsSeveralGroups(box);
+ let scope = box;
+ let name = '';
+ if (!declaredBox && _tagNameOf.call(el) === 'INPUT' && el.type === 'radio' && el.name) {
+ // A box holding several groups is not this name's container: the name spans it (a matrix column).
+ scope = (!multi && box) || el.form || Node.prototype.getRootNode.call(el);
+ name = el.name;
+ }
+ let entry = null;
+ if (scope) {
+ let byName = _choiceGroups.get(scope);
+ if (!byName) { byName = new Map(); _choiceGroups.set(scope, byName); }
+ entry = byName.get(name);
+ if (!entry) { entry = {}; byName.set(name, entry); }
+ }
+ const g = { box, declaredBox, multi, radio, entry, scope, name };
+ _choiceGroupOf.set(el, g);
+ return g;
+ };
+ const _GROUP_ROLE_SEL = '[role=radiogroup],[role=group],fieldset';
+ // Removes each option's caption from text once, in one forward pass: captions read in the order
+ // their options sit. One found only earlier (an aria-label, a caption laid out first) takes its first
+ // remaining occurrence instead.
+ const _stripCaptions = (text, node) => {
+ let out = '';
+ let cursor = 0;
+ const choices = _qsa.call(node, _CHOICE_SEL);
+ for (const c of choices) {
+ const cap = _ownCaption(c, choices[0]);
+ if (!cap) continue;
+ const at = text.indexOf(cap, cursor);
+ if (at >= 0) {
+ out += text.slice(cursor, at) + ' ';
+ cursor = at + cap.length;
+ continue;
+ }
+ text = (out + text.slice(cursor)).replace(cap, ' ');
+ out = '';
+ cursor = 0;
+ }
+ return out + text.slice(cursor);
+ };
+ const _captionsOnly = _memo((node, t) => _normText(_stripCaptions(t, node)).length < 2);
+ const _innerTextMemo = _memo((node) => _normText(_innerTextOf.call(node)));
+ // el.labels walks the whole document on each call, so a caption read for a whole group looks its
+ // labels up in one index per root instead: the labels whose control is el, which is what el.labels holds.
+ const _labelIndex = _memo((root) => {
+ const byControl = new Map();
+ for (const l of root.querySelectorAll('label')) {
+ const c = l.control;
+ if (!c) continue;
+ if (!byControl.has(c)) byControl.set(c, []);
+ byControl.get(c).push(l);
+ }
+ return byControl;
+ });
+ const _labelTextOf = _memo((l) => _labelText(l));
+ const _labelHoldsSeveral = _memo((l) => _qsa.call(l, _CHOICE_SEL).length > 1);
+ // Inside a label wrapping its control, the text after the control is its caption and any text
+ // before it is the question.
+ const _textAfter = (l, el) => {
+ try {
+ const r = document.createRange();
+ r.setStartAfter(el);
+ r.setEnd(l, l.childNodes.length);
+ return _normText(r.toString());
+ } catch (e) { return ''; }
+ };
+ // A question precedes its options, so a label laid out before the group's first member (a question
+ // `label for=` that member) is not an option's caption; nor is a label wrapping several options.
+ const _ownCaption = _memo((el, first) => {
+ let t = _normText(el.getAttribute('aria-label'));
+ if (!t && el.labels) {
+ for (const l of _labelIndex(Node.prototype.getRootNode.call(el)).get(el) || []) {
+ const pos = Node.prototype.compareDocumentPosition.call(l, first);
+ if (pos & 4 && !(pos & 16)) continue;
+ if (_labelHoldsSeveral(l)) continue;
+ t = _normText(_labelTextOf(l));
+ if (t && Node.prototype.contains.call(l, el)) t = _textAfter(l, el) || t;
+ if (t) break;
+ }
+ }
+ if (!t) { try { t = _normText(_innerTextOf.call(el)); } catch (e) { t = ''; } }
+ if (!t) t = _shadowText(el);
+ return t;
+ });
+ // How many elements carry each id in a root, counted once per root.
+ const _idCounts = _memo((root) => {
+ const counts = new Map();
+ for (const n of root.querySelectorAll('[id]')) counts.set(n.id, (counts.get(n.id) || 0) + 1);
+ return counts;
+ });
+ // An id carried by several elements is undeclared: getElementById returns the first, which in a
+ // templated form is another group's question.
+ const _groupElName = (grp) => {
+ let t = _normText(grp.getAttribute('aria-label'));
+ const ids = _normText(grp.getAttribute('aria-labelledby'));
+ const root = Node.prototype.getRootNode.call(grp);
+ if (!t && ids && root && root.getElementById && root.querySelectorAll) {
+ const counts = _idCounts(root);
+ t = _normText(ids.split(' ').slice(0, 20).map((id) => {
+ const n = counts.get(id) === 1 ? root.getElementById(id) : null;
+ return n ? _labelText(n) : '';
+ }).join(' ').slice(0, 2000));
+ }
+ if (!t && _tagNameOf.call(grp) === 'FIELDSET') {
+ const legend = _qs.call(grp, ':scope > legend');
+ if (legend) t = _normText(_innerTextOf.call(legend));
+ }
+ return t;
+ };
+ const _composedContains = (outer, n) => {
+ for (let d = 0; n && d < 64; d++, n = _composedParent(n)) { if (n === outer) return true; }
+ return false;
+ };
+ // Native radios per root and name, indexed once: a group keyed by name finds its members here.
+ const _radiosByName = _memo((root) => {
+ const byName = new Map();
+ for (const r of root.querySelectorAll('input[type=radio]')) {
+ if (!r.name) continue;
+ if (!byName.has(r.name)) byName.set(r.name, []);
+ byName.get(r.name).push(r);
+ }
+ return byName;
+ });
+ // The controls under a named element, open shadow roots included, read once per element.
+ const _controlsOf = _memo((grp) => {
+ let nonChoice = false;
+ const choices = [];
+ _eachScope(grp, (scope) => {
+ if (!nonChoice && _qsaIn(scope, _NONCHOICE_SEL).length) nonChoice = true;
+ for (const c of _qsaIn(scope, _CHOICE_SEL)) choices.push(c);
+ return false;
+ }, Infinity);
+ return { nonChoice, choices };
+ });
+ const _proxied = _memo((c, kin) => _proxiedNative(c, kin));
+ // A native radio group is every radio of its name in the same form and tree, wherever its boxes are.
+ const _inGroup = (c, el, g, kin) => {
+ if (c === el) return true;
+ if (!g.entry || !_matches.call(c, kin)) return false;
+ if (g.name) return _tagNameOf.call(c) === 'INPUT' && c.name === g.name && c.form === el.form;
+ try { return _choiceGroup(c).entry === g.entry; } catch (e) { return false; }
+ };
+ // A named element names this group only if it holds the whole group and no choice control of any kind
+ // outside it. Otherwise it names a section, an option or a sibling group, and none of those is the question.
+ const _holdsOnlyThisGroup = (grp, el, g, kin) => {
+ for (const c of _controlsOf(grp).choices) {
+ if (!_inGroup(c, el, g, kin) && !_proxied(c, kin)) return false;
+ }
+ if (!g.entry) return true;
+ if (g.name) {
+ const root = Node.prototype.getRootNode.call(el);
+ for (const r of _radiosByName(root).get(g.name) || []) {
+ if (r.form === el.form && !_composedContains(grp, r)) return false;
+ }
+ return true;
+ }
+ return !g.box || _composedContains(grp, g.box);
+ };
+ const _groupFits = new Map();
+ const _namesOnlyThisGroup = (grp, el, g) => {
+ let byGroup = _groupFits.get(grp);
+ if (!byGroup) { byGroup = new Map(); _groupFits.set(grp, byGroup); }
+ const key = g.entry || el;
+ if (byGroup.has(key)) return byGroup.get(key);
+ const kin = g.radio ? _RADIO_SEL : _CHECK_SEL;
+ const fits = (_matches.call(grp, '[role=radiogroup]') || !_controlsOf(grp).nonChoice) && _holdsOnlyThisGroup(grp, el, g, kin);
+ byGroup.set(key, fits);
+ return fits;
+ };
+ // The name the page declares for the group: the first named fieldset, role=group or radiogroup above
+ // it that passes both gates, walking past unnamed wrappers and per-option named ones (a field library
+ // wraps each option in its own role=group). A section above the group fails the same gates.
+ const _declaredGroupName = (el, g) => {
+ let grp = g && g.declaredBox ? g.box : Element.prototype.closest.call(el, _GROUP_ROLE_SEL);
+ // Radios with no native name and no radiogroup box are keyed by their box, which can hold several
+ // questions laid out as siblings; only a radiogroup declares which of them it owns.
+ const ownerOnly = !!g && g.radio && !g.name && !g.declaredBox;
+ for (let hops = 0; grp && hops < 4; hops++) {
+ const t = _groupElName(grp);
+ const owns = !ownerOnly || _matches.call(grp, '[role=radiogroup]');
+ if (t && owns && _namesOnlyThisGroup(grp, el, g) && !_captionsOnly(grp, t)) return t;
+ const up = _parentOf.call(grp);
+ grp = up ? Element.prototype.closest.call(up, _GROUP_ROLE_SEL) : null;
+ }
+ return '';
+ };
+ // Text or an element right after a choice control is that control's caption, not a question,
+ // unless the control already shows a caption of its own.
+ const _afterChoice = (s) => {
+ let before = _prevOf.call(s);
+ while (before && _nodeTypeOf.call(before) !== 1 && !_normText(_contentOf.call(before))) before = _prevOf.call(before);
+ if (!before || _nodeTypeOf.call(before) !== 1 || !_captionHost(before)) return false;
+ try { return !(_matches.call(before, _CHOICE_SEL) && _visibleText(before, 0).length >= 2); } catch (e) { return true; }
+ };
+ // What a component draws in its own open shadow root, slotted content and choice controls excluded:
+ // a choice component's caption.
+ const _shadowText = (host) => {
+ const sr = _openShadowOf(host);
+ if (!sr) return '';
+ let t = '';
+ for (let c = _firstChildOf.call(sr); c; c = _nextOf.call(c)) {
+ const kind = _nodeTypeOf.call(c);
+ if (kind === 3) t += ' ' + _contentOf.call(c);
+ else if (kind === 1 && !_hasChoice(c)) { try { t += ' ' + _visibleText(c, 1); } catch (e) { /* no text */ } }
+ }
+ return _normText(t);
+ };
+ // A row's header cell names its radios only when they are one native group sharing one name (a row of
+ // several names is already several groups): in a transposed matrix the header is an answer.
+ const _rowHeaderQuestion = (box) => {
+ for (const r of _qsa.call(box, _RADIO_SEL)) {
+ if (_tagNameOf.call(r) !== 'INPUT' || !r.name) return '';
+ }
+ return _normText(Array.from(_qsa.call(box, ':scope > th, :scope > [role=rowheader]')).map((c) => _visibleText(c, 1)).join(' '));
+ };
+ // Only text the page declares as the box's question: a table row's header cell, or what a group
+ // component slots into a slot named for its label. A wrong question is worse than none, so nothing
+ // else is read. The label slot is the component's own label API; help, error and default slots are not.
+ const _boxQuestion = (box, g) => {
+ if (_matches.call(box, 'tr,[role=row]')) return g.radio ? _rowHeaderQuestion(box) : '';
+ let out = '';
+ for (let c = _firstChildOf.call(box); c; c = _nextOf.call(c)) {
+ if (_nodeTypeOf.call(c) !== 1) continue;
+ const slot = _assignedSlotOf.call(c);
+ if (!slot || !/label/i.test(slot.getAttribute('name') || '')) continue;
+ if (_matches.call(c, '[role=alert],[aria-live],[hidden]')) continue;
+ out += ' ' + _nodeText(c);
+ }
+ return _normText(out);
+ };
+ const _choiceQuestion = (el, g) => {
+ const declared = _declaredGroupName(el, g);
+ if (declared || !g.box || g.multi) return declared;
+ const t = _boxQuestion(g.box, g);
+ if (!t || _matches.call(g.box, 'tr,[role=row]')) return t;
+ return _namesOnlyThisGroup(g.box, el, g) && !_captionsOnly(g.box, t) ? t : '';
+ };
const _isAutocomplete = """
+ _IS_AUTOCOMPLETE_JS
+ r""";
@@ -7384,6 +7789,7 @@ async () => {
let truncatedInComponents = 0;
let lastGroup = '';
let groupTotal = 0;
+ let radioGroupsMissing = 0;
const _a11yRemoved = """
+ _A11Y_REMOVED_JS
+ r""";
@@ -7536,13 +7942,19 @@ async () => {
// every field of a template, not a name, so it does not count as one below.
let strongLabel = (el.getAttribute('aria-label') || '').trim();
if (!strongLabel && el.labels) {
- for (const l of el.labels) { strongLabel = _labelText(l); if (strongLabel) break; }
+ for (const l of el.labels) { strongLabel = _labelTextOf(l); if (strongLabel) break; }
}
if (!strongLabel) strongLabel = byId('aria-labelledby');
const boundName = strongLabel;
let slottedName = false;
if (!strongLabel) strongLabel = (el.innerText || '').trim();
if (!strongLabel && host) { strongLabel = slottedText(el, host); slottedName = !!strongLabel; }
+ const pageName = strongLabel;
+ // A radio or checkbox component may draw its caption in its own shadow root, where innerText does
+ // not reach. A switch's drawn text is its state ('Off'), and a title outranks a drawn caption.
+ if (!strongLabel && _matches.call(el, _CAPTIONED_CHOICE_SEL) && !(el.getAttribute('title') || '').trim()) {
+ try { strongLabel = _shadowText(el).slice(0, _RETAIN_WIDTH); } catch (e) { strongLabel = ''; }
+ }
// A skinned native is exempt: the zero-rect carve-out above already established that the page
// draws a visible proxy for it and that the tools drive it directly, which is the opposite
// finding to this one.
@@ -7560,10 +7972,7 @@ async () => {
}
// An unnamed control no scroll can bring on screen is one the model can neither identify nor
// click: an action on it waits out the whole timeout. Named controls stay, off screen or not, and
- // so does a file input, which takes files without being visible. Counted in every arm, so the
- // exposed SET can be compared across arms; only the drop is gated. The per-call count cannot: a
- // drop does not consume the element budget, so a truncating call in treatment examines further
- // down the page than the same call in control.
+ // so does a file input, which takes files without being visible.
if (ownGated && !pointerRoot && !hidden && unnamed && !_reportsState(el)
&& !(el.tagName === 'INPUT' && String(el.type || '').toLowerCase() === 'file')
&& gr.width !== 0 && gr.height !== 0 && _outsideViewport(gr) && !_scrollReachable(gateEl, gr)) {
@@ -7573,11 +7982,9 @@ async () => {
offViewportUnnamedHostExempt++;
} else {
offViewportUnreachableUnnamed++;
- if (_DROP_OFFVIEWPORT_UNNAMED) {
- hiddenDropped++;
- hiddenDroppedOffViewport++;
- continue;
- }
+ hiddenDropped++;
+ hiddenDroppedOffViewport++;
+ continue;
}
}
if (pointerRoot && pointerListed >= _POINTER_ROOT_CAP) { pointerCapped++; continue; }
@@ -7685,15 +8092,45 @@ async () => {
// required") shared by every field, which would name nothing and dedupe to nothing.
// The record carries the text at the masking width; the budget, the dedupe and the
// name-vs-description comparison all stay at the 200-char display width.
- const gtFull = (_groupText(el, isChoice) || byId('aria-describedby')).slice(0, _RETAIN_WIDTH);
+ const ownGroup = _groupText(el, isChoice);
+ const gtFull = (ownGroup || byId('aria-describedby')).slice(0, _RETAIN_WIDTH);
const gt = gtFull.slice(0, 200);
- // A slotted caption is compared at the 140 width it used to be stored at.
- const nameLength = slottedName ? Math.min(strongLabel.length, 140) : strongLabel.length;
- if (gt && gt.length > nameLength && gt !== lastGroup && groupTotal + gt.length <= _GROUP_TEXT_TOTAL_CAP) {
+ // A slotted caption is compared at the 140 width it used to be stored at. A drawn shadow caption
+ // is not compared at all: it must not hide a group text the page declared.
+ const nameLength = slottedName ? Math.min(pageName.length, 140) : pageName.length;
+ let g = null;
+ if (isChoice) { try { g = _choiceGroup(el); } catch (e) { g = null; } }
+ // A question resolved for the whole group rides on its first listed member only, however short:
+ // on a later member it reads as the start of a new group.
+ const shared = !!(g && g.entry && g.entry.text) && gtFull === g.entry.text.slice(0, _RETAIN_WIDTH);
+ if (shared) {
+ if (!g.entry.shown && groupTotal + gt.length <= _GROUP_TEXT_TOTAL_CAP) {
+ rec.group = gtFull;
+ lastGroup = gt;
+ groupTotal += gt.length;
+ }
+ g.entry.shown = true;
+ } else if (gt && gt.length > nameLength && gt !== lastGroup && groupTotal + gt.length <= _GROUP_TEXT_TOTAL_CAP) {
rec.group = gtFull;
lastGroup = gt;
groupTotal += gt.length;
}
+ // Every member carries its group's number, so the digest can say once per group that no
+ // question was found; checkboxes are left out, being mostly self-describing consents.
+ if (el.type === 'radio' || role === 'radio') {
+ // A fresh object per element on purpose: a control with no group entry is its own group.
+ const entry = (g && g.entry) || {};
+ // Found means the page gave a question, printed or not: the page budget or the same-text dedupe
+ // may hold it back. A description is a hint or an error, never the group's question.
+ if (ownGroup) entry.found = true;
+ else if (!entry.found) {
+ if (!entry.missing) entry.missing = ++radioGroupsMissing;
+ rec.group_missing = entry.missing;
+ }
+ // A member printing its group's question after an earlier member took a number carries that
+ // number too, so the render can drop the earlier marker.
+ if (ownGroup && rec.group && entry.missing) rec.group_missing = entry.missing;
+ }
}
const toggle = _toggleState(el);
if ('pressed' in toggle) rec.pressed = toggle.pressed;
@@ -8277,13 +8714,6 @@ def _observe_js_returning(expression: str, retain_width: int) -> str:
key = f'"__tv3el_{secrets.token_hex(8)}"'
return (
_OBSERVE_JS_TEMPLATE.replace("__OBSERVE_RETAIN_WIDTH__", str(int(retain_width)), 1)
- .replace(
- "__OBSERVE_DROP_OFFVIEWPORT_UNNAMED__",
- "true"
- if run_arm_enabled(OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG, settings.TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED)
- else "false",
- 1,
- )
.replace("__OBSERVE_RETURN__", expression, 1)
.replace("__OBSERVE_EL_KEY__", key)
)
@@ -8322,6 +8752,9 @@ def _menu_open_note(found: dict[str, Any], selector: str, *, clicked_row: bool =
# this note has just renumbered every data-tv3-menu, so the selector clicked to get here is one
# of the ones it is about to declare stale.
closer = "the row you just clicked" if clicked_row else selector
+ declared = found.get("declared")
+ if isinstance(declared, int) and not isinstance(declared, bool) and declared > count:
+ overflow += f" (the list declares {declared} options; {count} are listed)"
return (
f"This click opened a menu of {count} options: {'; '.join(parts)}{overflow}. To select one, click "
f'its [data-tv3-menu="N"] selector NOW — clicking {closer} again or elsewhere closes the menu '
@@ -10170,7 +10603,19 @@ def build_browser_tools(
)
bodies: list[str] = []
- for e in elements:
+
+ def _realm_of(idx: int) -> Any:
+ return owners[idx] if idx < len(owners) else None
+
+ # Keyed by realm: each frame numbers its own groups from 1. A group any member prints a question
+ # for never takes the marker, whichever member comes first.
+ missing_groups_shown: set[tuple[Any, int]] = {
+ (_realm_of(i), el["group_missing"])
+ for i, el in enumerate(elements)
+ if el.get("group") and el.get("group_missing")
+ }
+
+ for _render_idx, e in enumerate(elements):
extra = ""
if e.get("value"):
extra += f" value={_field(e['value'], OBSERVE_DISPLAY_WIDTHS['value'])}"
@@ -10232,8 +10677,12 @@ def build_browser_tools(
extra += " [hidden-native: styled proxy; select_option acts on it directly]"
else:
extra += " [hidden-native: styled proxy; click acts on it directly]"
+ missing_key = (_realm_of(_render_idx), e.get("group_missing"))
if e.get("group"):
extra += f" group={_field(e['group'], OBSERVE_DISPLAY_WIDTHS['group'])}"
+ elif e.get("group_missing") and missing_key not in missing_groups_shown:
+ missing_groups_shown.add(missing_key)
+ extra += " group=(no question found)"
if e.get("a11yRemoved"):
# What the page declared, not a prediction: aria-hidden with a negative tabindex does
# not stop a click landing or a field filling (measured), and a control the page
diff --git a/tests/unit/browser_extension/test_control_indicator.py b/tests/unit/browser_extension/test_control_indicator.py
new file mode 100644
index 000000000..a97a4dac6
--- /dev/null
+++ b/tests/unit/browser_extension/test_control_indicator.py
@@ -0,0 +1,397 @@
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+EXTENSION = Path(__file__).parents[3] / "skyvern/browser_extension/extension"
+
+
+def run_node(script: str) -> None:
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is required for indicator contract coverage")
+ script = script.replace("EXTENSION_URI", json.dumps(EXTENSION.as_uri() + "/"))
+ result = subprocess.run(
+ [node, "--input-type=module", "--eval", script],
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=10,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def test_indicator_visibility_requires_scope_and_connection_and_binds_query_to_sender() -> None:
+ """Disconnects and revocations must hide the indicator; queries cannot read another tab."""
+ run_node("""
+import assert from 'node:assert/strict';
+const { IndicatorState } = await import(EXTENSION_URI + 'indicator_state.js');
+const deliveries = [];
+const indicator = new IndicatorState({ sendMessage: (id, state) => deliveries.push({ id, ...state }) });
+const query = id => indicator.query({ tab: { id }, frameId: 0 });
+indicator.onScopeChange(7, true);
+assert.equal(query(7).visible, false);
+indicator.setConnected(true);
+assert.equal(deliveries.at(-1).visible, true);
+const connected = query(7);
+assert.equal(connected.visible, true);
+assert.equal(query(8).visible, false);
+assert.equal(indicator.query({ tabId: 7, frameId: 0 }), null);
+assert.equal(indicator.query({ tab: { id: 7 }, frameId: 1 }), null);
+indicator.onScopeChange(7, false);
+assert.equal(query(7).visible, false);
+assert.equal(deliveries.at(-1).visible, false);
+indicator.onScopeChange(7, true);
+indicator.setConnected(false);
+assert.equal(query(7).visible, false);
+assert.equal(deliveries.at(-1).visible, false);
+assert.ok(query(7).revision > connected.revision);
+indicator.setConnected(true);
+assert.equal(query(7).visible, true);
+""")
+
+
+ROUTER_SETUP = """
+import assert from 'node:assert/strict';
+const { DebuggerRouter } = await import(EXTENSION_URI + 'debugger_router.js');
+const events = [];
+let detachListener;
+let chromeCommand = async () => ({ data: 'pixels' });
+let message = async () => ({ ok: true });
+let shown = true;
+const lease = { assertCurrent() {}, invalidated: new Promise(() => {}) };
+globalThis.chrome = { debugger: {
+ onEvent: { addListener() {} },
+ onDetach: { addListener(fn) { detachListener = fn; } },
+ sendCommand(target, method, params) {
+ events.push({ type: 'capture', method });
+ return chromeCommand(target, method, params);
+ },
+} };
+const router = new DebuggerRouter({
+ tabScope: {
+ async runTabOperation(tabId, operation, generation, allow, classify) {
+ classify?.(lease);
+ return operation(lease);
+ },
+ async assertControllableLocked() {},
+ async handleDebuggerDetachLocked() {},
+ },
+ sendEvent() {}, onAttachedChange() {},
+ isIndicatorVisible: () => shown,
+ sendIndicatorMessage(tabId, payload) {
+ events.push({ tabId, ...payload });
+ return message(payload);
+ },
+ commandTimeoutMs: 20,
+});
+router.attachedTabs.add(7);
+router.attachStates.set(7, { status: 'attached' });
+const send = (method = 'Page.captureScreenshot', extra = {}) => router.send({ tabId: 7, method, ...extra });
+const tick = () => new Promise(resolve => setTimeout(resolve, 0));
+"""
+
+
+def test_capture_suppression_order_and_best_effort_timeout() -> None:
+ """Capture must wait for hide acknowledgment, but a missing script must not block it."""
+ run_node(
+ ROUTER_SETUP
+ + """
+let acknowledge;
+message = () => new Promise(resolve => { acknowledge = resolve; });
+const first = send();
+await tick();
+assert.equal(events.length, 1);
+assert.equal(events[0].type, 'skyvern.indicator.suppress');
+acknowledge({ ok: true });
+assert.deepEqual(await first, { result: { data: 'pixels' } });
+assert.deepEqual(events.map(x => x.type), ['skyvern.indicator.suppress', 'capture', 'skyvern.indicator.release']);
+assert.equal(events[0].token, events[2].token);
+message = async () => ({ ok: true });
+events.length = 0;
+await send('Page.startScreencast');
+assert.deepEqual(events.map(x => x.type), ['capture']);
+events.length = 0;
+shown = false;
+await send();
+assert.deepEqual(events.map(x => x.type), ['capture']);
+shown = true;
+events.length = 0;
+message = () => new Promise(() => {});
+await send();
+assert.deepEqual(events.map(x => x.type), ['skyvern.indicator.suppress', 'capture', 'skyvern.indicator.release']);
+for (const fail of [() => { throw new Error('no script'); }, async () => { throw new Error('no tab'); }]) {
+ message = fail;
+ assert.deepEqual(await send(), { result: { data: 'pixels' } });
+}
+console.log('PASS capture waits for suppression acknowledgment and tolerates an unavailable content script');
+"""
+ )
+
+
[email protected]("terminal", ["resolve", "reject", "detach", "lease", "dispatch_failure"])
+def test_capture_release_tracks_underlying_command_settlement(terminal: str) -> None:
+ """Timeout/cancellation must keep pending pixels hidden; settlement or detach must release them."""
+ run_node(
+ ROUTER_SETUP
+ + """
+const { ProtocolError, ERROR_CODES } = await import(EXTENSION_URI + 'protocol.js');
+const terminal = TERMINAL;
+const cancellation = new ProtocolError(ERROR_CODES.COMMAND_TIMEOUT, 'lease invalidated');
+if (terminal === 'lease') router.commandTimeoutMs = 1000;
+let resolveCommand, rejectCommand, cancelLease;
+lease.invalidated = new Promise((_, reject) => { cancelLease = reject; });
+chromeCommand = () => {
+ if (terminal === 'dispatch_failure') throw new Error('Chrome refused the command');
+ return new Promise((resolve, reject) => { resolveCommand = resolve; rejectCommand = reject; });
+};
+// Child-session timeouts leave Chrome running; lease cancellation must do the same.
+const pending = send('Page.captureScreenshot', { sessionId: 'child' }).catch(error => error);
+if (terminal === 'lease') {
+ await tick();
+ cancelLease(cancellation);
+}
+const outcome = await pending;
+if (terminal === 'lease') assert.equal(outcome, cancellation);
+else assert.equal(outcome.code, terminal === 'dispatch_failure' ? 'CDP_ERROR' : 'COMMAND_TIMEOUT');
+if (terminal !== 'dispatch_failure') {
+ assert.deepEqual(events.map(x => x.type), ['skyvern.indicator.suppress', 'capture']);
+ if (terminal === 'detach') {
+ router.tabScope.runTabOperation = () => new Promise(() => {});
+ detachListener({ tabId: 7 }, 'canceled_by_user');
+ await tick();
+ assert.equal(events.at(-1).type, 'skyvern.indicator.release');
+ resolveCommand({});
+ } else if (terminal === 'reject') {
+ rejectCommand(new Error('capture failed'));
+ } else {
+ resolveCommand({ data: 'late pixels' });
+ }
+}
+await tick();
+assert.deepEqual(events.map(x => x.type), ['skyvern.indicator.suppress', 'capture', 'skyvern.indicator.release']);
+assert.equal(events[0].token, events[2].token);
+assert.equal(router.captureReleases.size, 0);
+console.log('PASS suppression survives wrapper cancellation and ends on settlement or detach');
+""".replace("TERMINAL", json.dumps(terminal))
+ )
+
+
+CONTENT_SETUP = """
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+const source = fs.readFileSync(new URL('control_indicator.js', EXTENSION_URI), 'utf8');
+let listener, observer, resolveQuery;
+const timers = new Map();
+const frames = new Map();
+const windowEvents = new Map();
+const documentEvents = new Map();
+let nextId = 0;
+class Element {
+ constructor(tag) {
+ this.tagName = tag;
+ this.childNodes = [];
+ this.parentNode = null;
+ this.attributes = {};
+ this.styles = {};
+ this.style = { setProperty: (name, value, priority) => { this.styles[name] = { value, priority }; } };
+ }
+ setAttribute(name, value) { this.attributes[name] = value; }
+ append(child) {
+ child.remove();
+ this.childNodes.push(child);
+ child.parentNode = this;
+ }
+ remove() {
+ if (this.parentNode) {
+ this.parentNode.childNodes = this.parentNode.childNodes.filter(node => node !== this);
+ this.parentNode = null;
+ }
+ }
+ cloneNode(deep = false) {
+ const clone = new Element(this.tagName);
+ clone.attributes = { ...this.attributes };
+ clone.styles = structuredClone(this.styles);
+ if (deep) for (const child of this.childNodes) clone.append(child.cloneNode(true));
+ return clone;
+ }
+ attachShadow(options) {
+ assert.equal(options.mode, 'closed');
+ return new Element('#shadow-root');
+ }
+}
+const document = {
+ documentElement: null,
+ visibilityState: 'visible',
+ createElement: tag => new Element(tag),
+ querySelectorAll(tag) {
+ const matches = [];
+ const visit = node => {
+ if (!node) return;
+ if (node.tagName === tag) matches.push(node);
+ node.childNodes.forEach(visit);
+ };
+ visit(this.documentElement);
+ return matches;
+ },
+ addEventListener: (name, fn) => documentEvents.set(name, fn),
+ removeEventListener: (name, fn) => { if (documentEvents.get(name) === fn) documentEvents.delete(name); },
+};
+const context = {
+ document,
+ window: { addEventListener: (name, fn) => windowEvents.set(name, fn) },
+ CSSStyleSheet: class { replaceSync(css) { this.css = css; } },
+ MutationObserver: class {
+ constructor(fn) { observer = fn; }
+ observe(target, options) { assert.equal(target, document); assert.equal(options.subtree, true); }
+ },
+ setTimeout(fn, delay) { const id = ++nextId; timers.set(id, { fn, delay }); return id; },
+ clearTimeout(id) { timers.delete(id); },
+ requestAnimationFrame(fn) { const id = ++nextId; frames.set(id, fn); return id; },
+ cancelAnimationFrame(id) { frames.delete(id); },
+ chrome: { runtime: {
+ id: 'extension',
+ onMessage: { addListener(fn) { listener = fn; } },
+ sendMessage(message) {
+ assert.equal(typeof listener, 'function', 'listener must precede query');
+ assert.equal(message.type, 'skyvern.indicator.query');
+ return new Promise(resolve => { resolveQuery = resolve; });
+ },
+ } },
+};
+vm.runInNewContext(source, context);
+const state = (visible, revision, epoch = 'worker-a') => ({ type: 'skyvern.indicator.state', visible, revision, epoch });
+const trusted = { id: 'extension' };
+const emit = (message, respond = () => {}) => listener(message, trusted, respond);
+const nextFrame = () => {
+ const callbacks = [...frames.values()]; frames.clear();
+ for (const callback of callbacks) callback();
+};
+const tick = () => new Promise(resolve => setTimeout(resolve, 0));
+"""
+
+
+def test_content_script_state_ordering_and_overlapping_suppression() -> None:
+ """Stale state and overlapping captures must not expose the indicator in agent images."""
+ run_node(
+ CONTENT_SETUP
+ + """
+document.documentElement = new Element('html');
+listener(state(true, 1), { id: 'foreign' }, () => {});
+assert.equal(document.documentElement.childNodes.length, 0);
+emit(state(true, 2));
+const host = document.documentElement.childNodes[0];
+const display = () => host.styles.display.value;
+assert.equal(display(), 'block');
+resolveQuery(state(false, 1));
+await tick();
+assert.equal(display(), 'block', 'stale query must not overwrite a pushed state');
+emit(state(false, 3));
+emit(state(true, 3));
+assert.equal(display(), 'none');
+emit(state(true, 0, 'worker-b'));
+assert.equal(display(), 'block', 'new worker epoch must supersede old revisions');
+let acknowledged = false;
+emit({ type: 'skyvern.indicator.suppress', token: 'one' }, () => { acknowledged = true; });
+assert.equal(display(), 'none');
+nextFrame();
+assert.equal(acknowledged, false, 'acknowledgment must wait for paint');
+nextFrame();
+assert.equal(acknowledged, true);
+emit({ type: 'skyvern.indicator.suppress', token: 'two' });
+emit(state(true, 1, 'worker-b'));
+for (let i = 0; i < 2; i++) emit({ type: 'skyvern.indicator.release', token: 'one' });
+assert.equal(display(), 'none', 'release must leave other tokens hidden');
+emit({ type: 'skyvern.indicator.release', token: 'two' });
+assert.equal(display(), 'block');
+windowEvents.get('pageshow')({ persisted: true });
+resolveQuery(state(false, 2, 'worker-b'));
+await tick();
+assert.equal(display(), 'none', 'bfcache restore must refresh scope');
+"""
+ )
+
+
+def test_content_script_query_restores_pending_capture_after_navigation() -> None:
+ run_node(
+ CONTENT_SETUP
+ + """
+const { DebuggerRouter } = await import(EXTENSION_URI + 'debugger_router.js');
+const { IndicatorState } = await import(EXTENSION_URI + 'indicator_state.js');
+let finishCapture;
+globalThis.chrome = { debugger: {
+ onEvent: { addListener() {} }, onDetach: { addListener() {} },
+ sendCommand() { return new Promise(resolve => { finishCapture = resolve; }); },
+} };
+const lease = { assertCurrent() {}, invalidated: new Promise(() => {}) };
+const router = new DebuggerRouter({
+ tabScope: {
+ async runTabOperation(tabId, operation, generation, allow, classify) {
+ classify?.(lease);
+ return operation(lease);
+ },
+ async assertControllableLocked() {},
+ },
+ sendEvent() {}, onAttachedChange() {}, isIndicatorVisible: () => true,
+ async sendIndicatorMessage(tabId, message) {
+ // Suppression went to the previous document; release reaches the new one.
+ if (message.type === 'skyvern.indicator.release') emit(message);
+ return { ok: true };
+ },
+});
+router.attachedTabs.add(7);
+router.attachStates.set(7, { status: 'attached' });
+const indicator = new IndicatorState({
+ sendMessage() {}, getCaptureTokens: tabId => router.getCaptureTokens(tabId),
+});
+indicator.onScopeChange(7, true);
+indicator.setConnected(true);
+const capture = router.send({ tabId: 7, method: 'Page.captureScreenshot' });
+await tick();
+assert.equal(typeof finishCapture, 'function');
+assert.equal(router.getCaptureTokens(7).length, 1);
+assert.deepEqual(router.getCaptureTokens(8), []);
+document.documentElement = new Element('html');
+resolveQuery(indicator.query({ tab: { id: 7 }, frameId: 0 }));
+await tick();
+const host = document.documentElement.childNodes[0];
+assert.equal(host.styles.display.value, 'none', 'new document must inherit outstanding capture tokens');
+assert.equal(timers.size, 1);
+assert.equal([...timers.values()][0].delay, 60_000);
+finishCapture({ data: 'pixels' });
+await capture;
+assert.equal(host.styles.display.value, 'block', 'release must clear the inherited capture token');
+assert.equal(timers.size, 0);
+assert.deepEqual(router.getCaptureTokens(7), []);
+console.log('PASS new-document query inherits capture suppression until release');
+"""
+ )
+
+
+def test_content_script_remount_removes_cloned_hosts() -> None:
+ run_node(
+ CONTENT_SETUP
+ + """
+document.documentElement = new Element('html');
+resolveQuery(state(true, 1));
+await tick();
+const host = document.documentElement.childNodes[0];
+const oldRoot = document.documentElement;
+document.documentElement = oldRoot.cloneNode(true);
+const clonedHost = document.documentElement.childNodes[0];
+assert.notEqual(clonedHost, host);
+observer();
+assert.deepEqual(document.querySelectorAll('skyvern-control-indicator'), [host]);
+assert.equal(clonedHost.parentNode, null);
+assert.equal(host.parentNode, document.documentElement);
+assert.equal(oldRoot.childNodes.length, 0);
+observer();
+assert.equal(document.querySelectorAll('skyvern-control-indicator').length, 1);
+console.log('PASS cloned document root retains exactly one indicator host');
+"""
+ )
diff --git a/tests/unit/browser_extension/test_extension_bridge_hardening.py b/tests/unit/browser_extension/test_extension_bridge_hardening.py
index a7299df81..658a8e1a1 100644
--- a/tests/unit/browser_extension/test_extension_bridge_hardening.py
+++ b/tests/unit/browser_extension/test_extension_bridge_hardening.py
@@ -470,142 +470,46 @@ def test_dom_evaluate_contract() -> None:
dom_uri = (extension_dir / "dom_router.js").as_uri()
protocol_uri = (extension_dir / "protocol.js").as_uri()
script = f"""
-const scriptCalls = [];
-globalThis.chrome = {{
- userScripts: {{
- async execute({{ target, world, injectImmediately, js }}) {{
- scriptCalls.push({{ target, world, injectImmediately, js }});
- try {{
- return [{{ result: await globalThis.eval(js[0].code) }}];
- }} catch (error) {{
- return [{{ error: String(error?.message ?? error) }}];
- }}
- }},
- }},
-}};
-
+import assert from "node:assert/strict";
const {{ evaluateDom }} = await import({json.dumps(dom_uri)});
-const {{ ERROR_CODES, ProtocolError }} = await import({json.dumps(protocol_uri)});
-
-let leaseChecks = 0;
-let controllableChecks = 0;
-let controllableUrl = "https://example.test/";
-const lease = {{ assertCurrent() {{ leaseChecks += 1; }} }};
-const tabScope = {{
- async runTabOperation(tabId, operation) {{
- if (tabId !== 7) throw new Error(`unexpected tab ID: ${{tabId}}`);
- return operation(lease);
+const {{ ProtocolError, ERROR_CODES }} = await import({json.dumps(protocol_uri)});
+let chromeAccesses = 0;
+let argumentAccesses = 0;
+globalThis.callerSourceRan = false;
+Object.defineProperty(globalThis, "chrome", {{
+ get() {{
+ chromeAccesses += 1;
+ throw new Error("DOM evaluation must not access Chrome");
}},
- async assertControllableLocked(tabId, currentLease) {{
- if (tabId !== 7 || currentLease !== lease) throw new Error("scope check lost the tab lease");
- controllableChecks += 1;
- return {{ id: tabId, groupId: 700, url: controllableUrl }};
+}});
+const unreadable = new Proxy({{}}, {{
+ get() {{
+ argumentAccesses += 1;
+ throw new Error("DOM evaluation must not read its arguments");
+ }},
+ ownKeys() {{
+ argumentAccesses += 1;
+ throw new Error("DOM evaluation must not enumerate its arguments");
}},
-}};
-
-const evaluated = await evaluateDom(tabScope, {{
- tabId: 7,
- expression: "({{ answer: 6 * 7 }})",
}});
-if (
- evaluated.result?.answer !== 42 ||
- scriptCalls.length !== 1 ||
- scriptCalls[0].target?.tabId !== 7 ||
- scriptCalls[0].world !== "MAIN" ||
- scriptCalls[0].injectImmediately !== true ||
- scriptCalls[0].js?.[0]?.code !== "({{ answer: 6 * 7 }})" ||
- controllableChecks !== 2 ||
- leaseChecks !== 1
-) {{
- throw new Error(`DOM evaluation contract failed: ${{JSON.stringify({{
- evaluated,
- scriptCalls,
- controllableChecks,
- leaseChecks,
- }})}}`);
-}}
-
-for (const [expression, expected] of [["false", false], ["0", 0], ["null", null]]) {{
- const response = await evaluateDom(tabScope, {{ tabId: 7, expression }});
- if (!Object.is(response.result, expected)) {{
- throw new Error(`DOM evaluation changed a falsy result: ${{expression}}`);
- }}
-}}
-const thrownEvaluationError = await evaluateDom(tabScope, {{
- tabId: 7,
- expression: "(() => {{ throw new Error('page failure'); }})()",
-}}).then(() => null, (error) => error);
-if (
- thrownEvaluationError?.code !== ERROR_CODES.CDP_ERROR ||
- !thrownEvaluationError.message.includes("page failure")
-) {{
- throw new Error(`thrown page evaluation was not structured: ${{thrownEvaluationError?.message}}`);
-}}
-
-const invalidError = await evaluateDom(tabScope, {{
- tabId: 7,
- expression: "1 + 1",
- extra: true,
-}}).then(() => null, (error) => error);
-if (invalidError?.code !== ERROR_CODES.OP_NOT_ALLOWED) {{
- throw new Error(`invalid DOM arguments did not fail closed: ${{invalidError?.code}}`);
-}}
-
-const callsBeforeBlank = scriptCalls.length;
-controllableUrl = "about:blank";
-const blankError = await evaluateDom(tabScope, {{
- tabId: 7,
- expression: "1 + 1",
-}}).then(() => null, (error) => error);
-if (
- blankError?.code !== ERROR_CODES.RESTRICTED_URL ||
- scriptCalls.length !== callsBeforeBlank
-) {{
- throw new Error(`about:blank reached MAIN evaluation: ${{blankError?.code}}`);
-}}
-controllableUrl = "https://example.test/";
-
-chrome.userScripts.execute = async () => {{ throw new Error("injection blocked"); }};
-const injectionError = await evaluateDom(tabScope, {{
- tabId: 7,
- expression: "1 + 1",
-}}).then(() => null, (error) => error);
-if (injectionError?.code !== ERROR_CODES.CDP_ERROR) {{
- throw new Error(`failed injection was not structured: ${{injectionError?.code}}`);
-}}
-
-let revalidationChecks = 0;
-let failedInjectionCalls = 0;
-chrome.userScripts.execute = async () => {{
- failedInjectionCalls += 1;
- throw new Error("navigation interrupted injection");
-}};
-tabScope.assertControllableLocked = async (tabId, currentLease) => {{
- if (tabId !== 7 || currentLease !== lease) throw new Error("scope check lost the tab lease");
- revalidationChecks += 1;
- if (revalidationChecks === 2) {{
- throw new ProtocolError(
- ERROR_CODES.RESTRICTED_URL,
- "Chrome does not allow controlling this URL.",
- );
- }}
- return {{ id: tabId, groupId: 700, url: "https://example.test/" }};
-}};
-const revokedError = await evaluateDom(tabScope, {{
- tabId: 7,
- expression: "1 + 1",
-}}).then(() => null, (error) => error);
-if (
- revokedError?.code !== ERROR_CODES.RESTRICTED_URL ||
- revalidationChecks !== 2 ||
- failedInjectionCalls !== 1
-) {{
- throw new Error(`failed injection hid scope revocation: ${{JSON.stringify({{
- code: revokedError?.code,
- revalidationChecks,
- failedInjectionCalls,
- }})}}`);
+for (const args of [
+ {{ tabId: 7, expression: "globalThis.callerSourceRan = true" }},
+ unreadable,
+ undefined,
+]) {{
+ await assert.rejects(evaluateDom(unreadable, args), (error) => {{
+ assert(error instanceof ProtocolError);
+ assert.equal(error.code, ERROR_CODES.OP_NOT_ALLOWED);
+ assert.equal(error.message,
+ "Direct JavaScript evaluation is unavailable in extension mode. " +
+ "Use skyvern_observe, skyvern_get_html, skyvern_find, or skyvern_get_value to inspect the page. " +
+ "Use skyvern_click or skyvern_type to interact.");
+ return true;
+ }});
}}
+assert.equal(chromeAccesses, 0);
+assert.equal(argumentAccesses, 0);
+assert.equal(globalThis.callerSourceRan, false);
"""
result = subprocess.run(
@@ -2089,6 +1993,13 @@ await waitUntil(() => !router.attachedTabs.has(21) && !router.attachStates.has(2
"case",
[
"child_popup",
+ "adopt_late_attach",
+ "adopt_unmatched_attach",
+ "adopt_move_rejected",
+ "adopt_group_failure",
+ "adopt_identification_retry",
+ "adopt_identification_retry_reset",
+ "adopt_renamed_opener_group",
"child_panel",
"child_app",
"child_devtools",
@@ -2127,6 +2038,9 @@ const events = [];
const removed = [];
const updates = [];
const commands = [];
+const moves = [];
+const activations = [];
+let moveHook = null;
const listener = {{ addListener() {{}} }};
globalThis.chrome = {{
tabs: {{
@@ -2134,6 +2048,23 @@ globalThis.chrome = {{
onUpdated: {{ addListener(fn) {{ updates.push(fn); }} }},
async get(id) {{ if (!tabs.has(id)) throw new Error("missing tab"); return {{ ...tabs.get(id) }}; }},
async query() {{ return [...tabs.values()]; }},
+ async move(id, options) {{
+ moves.push({{ id, ...options }});
+ if (caseName === "adopt_move_rejected") throw new Error("move rejected");
+ Object.assign(tabs.get(id), {{ windowId: options.windowId, groupId: -1, active: false }});
+ delete tabs.get(id).openerTabId;
+ if (moveHook) await moveHook();
+ if (caseName !== "adopt_late_attach") {{
+ state.attached.forEach((fn) => fn(id, {{ newWindowId: options.windowId }}));
+ }}
+ return {{ ...tabs.get(id) }};
+ }},
+ async update(id, options) {{
+ activations.push({{ id, ...options }});
+ assert(events.some((entry) => entry.event === "tabs.created" && entry.params.tabId === id));
+ Object.assign(tabs.get(id), options);
+ return {{ ...tabs.get(id) }};
+ }},
async remove(id) {{ removed.push(id); tabs.delete(id); }},
async create({{ url }}) {{
const tab = {{ id: 3, windowId: 2, groupId: -1, url, status: "complete" }};
@@ -2144,7 +2075,7 @@ globalThis.chrome = {{
}},
tabGroups: {{
async query() {{ return []; }},
- async get(id) {{ return {{ id, title: "Skyvern Controlled" }}; }},
+ async get(id) {{ return {{ id, windowId: 1, title: "Skyvern Controlled" }}; }},
async update() {{}},
}},
storage: {{ session: {{
@@ -2259,14 +2190,119 @@ if (caseName.startsWith("startup_attached")) {{
await scope.handleTabCreated({{ ...tab, windowId: 1 }});
assert(scope.isScoped(2));
assert((await scope.list()).tabs.some((item) => item.tabId === 2));
- assert.equal(tab.windowId, 2);
- assert.equal(tab.groupId, type === "normal" ? 700 : -1);
- assert.equal(state.groupCalls.length, type === "normal" ? 1 : 0);
+ assert.equal(tab.windowId, type === "popup" ? 1 : 2);
+ assert.equal(tab.groupId, ["normal", "popup"].includes(type) ? 700 : -1);
+ assert.equal(state.groupCalls.length, ["normal", "popup"].includes(type) ? 1 : 0);
+ if (type === "popup") {{
+ assert.deepEqual(moves, [{{ id: 2, windowId: 1, index: -1 }}]);
+ assert.equal(state.groupCalls[0].groupId, 700);
+ assert.equal(scope.pendingAdoptions.size, 0);
+ assert.deepEqual(events.find((entry) => entry.event === "tabs.created").params,
+ {{ tabId: 2, openerTabId: 1, url: tab.url }});
+ }}
if (type === "normal") assert.equal(state.groupCalls[0].createProperties.windowId, 2);
const router = new DebuggerRouter({{ tabScope: scope, sendEvent() {{}}, onAttachedChange() {{}} }});
await router.attach({{ tabId: 2 }});
await router.send({{ tabId: 2, method: "Runtime.evaluate", params: {{ expression: "1" }} }});
assert(commands.some((command) => command.target.tabId === 2 && command.method === "Runtime.evaluate"));
+ }} else if (caseName.startsWith("adopt_")) {{
+ tabs.set(1, {{ id: 1, windowId: 1, groupId: 701,
+ active: caseName === "adopt_late_attach",
+ url: "https://opener.example.test" }});
+ scope.scopedTabIds.add(1);
+ scope.scopedGroupIds.set(1, 701);
+ tab.openerTabId = 1;
+ chrome.tabGroups.query = async () => [
+ {{ id: 700, windowId: 1, title: "Skyvern Controlled" }},
+ {{ id: 701, windowId: 1, title: "Skyvern Controlled" }},
+ ];
+ if (caseName === "adopt_unmatched_attach") {{
+ moveHook = async () => {{
+ state.attached.forEach((fn) => fn(2, {{ newWindowId: 3 }}));
+ }};
+ }}
+ if (caseName === "adopt_group_failure") {{
+ chrome.tabs.group = async () => {{ throw new Error("group failed"); }};
+ }}
+ if (caseName === "adopt_renamed_opener_group") {{
+ state.groupTitles.set(701, "Personal tabs");
+ }}
+ let identify;
+ let retryCount = 0;
+ const identificationRetry = caseName.startsWith("adopt_identification_retry");
+ if (identificationRetry) {{
+ const persist = scope.persistScope.bind(scope);
+ scope.persistScope = async (...args) => {{
+ await persist(...args);
+ if (scope.createdTabIds.has(2) && retryCount++ === 0) {{
+ assert.equal(tab.windowId, 1);
+ scope.activeCreation = {{ tabId: null,
+ identified: new Promise((resolve) => {{ identify = resolve; }}) }};
+ }}
+ }};
+ }}
+ const admission = scope.handleTabCreated({{ ...tab }});
+ if (identificationRetry) {{
+ await waitUntil(() => identify && scope.activeOperationCount === 0);
+ assert(scope.createdTabIds.has(2));
+ assert(stored.createdTabIds.includes(2));
+ if (caseName === "adopt_identification_retry_reset") {{
+ await scope.prepareForReset();
+ await scope.reset();
+ scope.finishReset();
+ assert.deepEqual(removed, [2]);
+ assert(!tabs.has(2), "reset must close the adopted child during the retry wait");
+ assert(!scope.createdTabIds.has(2));
+ assert(!stored.createdTabIds.includes(2));
+ }}
+ scope.activeCreation = null;
+ identify();
+ }}
+ if (caseName === "adopt_identification_retry_reset") {{
+ await admission;
+ assert.equal(scope.pendingAdoptions.size, 0);
+ assert(!scope.isScoped(2));
+ assert(!events.some((entry) => entry.event === "tabs.created"));
+ }} else if (caseName === "adopt_renamed_opener_group") {{
+ await admission;
+ assert.deepEqual(moves, []);
+ assert.equal(tab.windowId, 2);
+ assert.equal(tab.groupId, -1);
+ assert(!scope.isScoped(2));
+ assert.equal(scope.pendingAdoptions.size, 0);
+ }} else if (["adopt_unmatched_attach", "adopt_group_failure"].includes(caseName)) {{
+ await assert.rejects(admission);
+ assert.deepEqual(removed, [2]);
+ assert(!scope.isScoped(2));
+ assert(!events.some((entry) => entry.event === "tabs.created"));
+ await scope.handleTabRemoved(2);
+ assert.equal(scope.pendingAdoptions.size, 0);
+ }} else {{
+ await admission;
+ assert(scope.isScoped(2));
+ assert(scope.createdTabIds.has(2));
+ assert.equal(events.find((entry) => entry.event === "tabs.created").params.openerTabId, 1);
+ if (caseName === "adopt_move_rejected") {{
+ assert.equal(tab.windowId, 2);
+ assert.equal(tab.groupId, -1);
+ assert.equal(scope.pendingAdoptions.size, 0);
+ }} else {{
+ assert.equal(tab.windowId, 1);
+ assert.equal(tab.groupId, 701);
+ assert.equal(scope.scopedGroupIds.get(2), 701);
+ if (caseName === "adopt_late_attach") {{
+ assert.equal(scope.pendingAdoptions.get(2).admissionDone, true);
+ state.attached.forEach((fn) => fn(2, {{ newWindowId: 1 }}));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert(scope.isScoped(2));
+ assert.equal(scope.pendingAdoptions.size, 0);
+ assert(!events.some((entry) => entry.event === "scope.tabRemoved"));
+ }}
+ const active = caseName === "adopt_late_attach";
+ assert.deepEqual(activations, active ? [{{ id: 2, active: true }}] : []);
+ assert.equal(tab.active, active);
+ }}
+ }}
}} else if (caseName === "create_popup") {{
await assert.rejects(scope.create({{ url: "https://created.example.test" }}));
assert.deepEqual(removed, [3]);
@@ -2370,3 +2406,103 @@ if (caseName.startsWith("startup_attached")) {{
[node, "--input-type=module", "--eval", script], capture_output=True, text=True, check=False, timeout=10
)
assert result.returncode == 0, result.stderr
+
+
+def test_scope_observer_commit_and_synchronous_removal_contract() -> None:
+ """Scope observers must see committed membership before events or asynchronous removal cleanup."""
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is required for the extension scope test")
+ extension_dir = Path(__file__).parents[3] / "skyvern" / "browser_extension" / "extension"
+ script = f"""
+import assert from "node:assert/strict";
+const tabs = new Map([
+ [1, {{ id: 1, windowId: 1, groupId: 700, url: "https://one.example.test" }}],
+ [2, {{ id: 2, windowId: 1, groupId: -1, url: "https://two.example.test" }}],
+]);
+const stored = {{ scopedTabIds: [1], scopedTabGroupIds: {{ 1: 700 }} }};
+const changes = [];
+const updates = [];
+const listener = {{ addListener() {{}} }};
+globalThis.chrome = {{
+ tabs: {{
+ onCreated: listener, onRemoved: listener,
+ onUpdated: {{ addListener(fn) {{ updates.push(fn); }} }},
+ async get(id) {{ if (!tabs.has(id)) throw new Error("missing"); return {{ ...tabs.get(id) }}; }},
+ async remove(id) {{ tabs.delete(id); }},
+ async create({{ url }}) {{
+ const tab = {{ id: 3, windowId: 1, groupId: -1, url, status: "complete" }};
+ tabs.set(3, tab);
+ updates.forEach((fn) => fn(3, {{ status: "complete" }}));
+ return {{ ...tab }};
+ }},
+ }},
+ tabGroups: {{
+ async query() {{ return []; }},
+ async get(id) {{ return {{ id, title: "Skyvern Controlled" }}; }},
+ async update() {{}},
+ }},
+ storage: {{ session: {{
+ async get(defaults) {{ return {{ ...defaults, ...stored }}; }},
+ async set(values) {{ Object.assign(stored, structuredClone(values)); }},
+ async remove(keys) {{ for (const key of keys) delete stored[key]; }},
+ }} }},
+}};
+{_WINDOW_GROUP_FAKES}
+installWindowGroupFakes(chrome, tabs, updates);
+const {{ TabScope }} = await import({json.dumps((extension_dir / "tab_scope.js").as_uri())});
+const scope = new TabScope({{
+ onScopeChange(id, scoped) {{
+ changes.push([id, scoped]);
+ assert.equal(scope.isScoped(id), scoped);
+ throw new Error("observer failure is ignored");
+ }},
+ sendEvent(event, params) {{
+ if (["scope.tabAdded", "tabs.created"].includes(event)) {{
+ assert.deepEqual(changes.at(-1), [params.tabId, true]);
+ }}
+ }},
+}});
+await scope.initialize();
+assert.deepEqual(changes, [[1, true]]);
+await scope.shareTab(2);
+assert.deepEqual(changes.at(-1), [2, true]);
+let releaseDetach;
+scope.setDebuggerRouter({{
+ detachIfAttachedLocked(id) {{
+ assert.deepEqual(changes.at(-1), [id, false]);
+ return new Promise((resolve) => {{ releaseDetach = resolve; }});
+ }},
+}});
+const removing = scope.removeFromScopeLocked(2, "unshared", true);
+assert.deepEqual(changes.at(-1), [2, false]);
+assert(!scope.isScoped(2));
+releaseDetach();
+await removing;
+scope.setDebuggerRouter(null);
+await scope.create({{ url: "https://three.example.test" }});
+assert.deepEqual(changes.at(-1), [3, true]);
+tabs.set(4, {{ id: 4, windowId: 1, groupId: 700, url: "https://four.example.test" }});
+await scope.handleTabUpdated(4, {{ groupId: 700 }});
+assert.deepEqual(changes.at(-1), [4, true]);
+tabs.set(5, {{ id: 5, windowId: 1, groupId: -1, openerTabId: 1, url: "https://five.example.test" }});
+await scope.handleTabCreated({{ ...tabs.get(5) }});
+assert.deepEqual(changes.at(-1), [5, true]);
+const group = chrome.tabs.group;
+chrome.tabs.group = async () => {{ throw new Error("grouping failed"); }};
+await assert.rejects(scope.shareTab(2));
+assert.deepEqual(changes.at(-1), [2, false]);
+chrome.tabs.group = group;
+const ids = [...scope.scopedTabIds];
+const beforeReset = changes.length;
+await scope.prepareForReset();
+const resetting = scope.reset();
+assert.deepEqual(changes.slice(beforeReset), ids.map((id) => [id, false]));
+assert.equal(scope.scopedTabIds.size, 0);
+await resetting;
+scope.finishReset();
+"""
+ result = subprocess.run(
+ [node, "--input-type=module", "--eval", script], capture_output=True, text=True, check=False, timeout=10
+ )
+ assert result.returncode == 0, result.stderr
diff --git a/tests/unit/browser_extension/test_mcp_glue.py b/tests/unit/browser_extension/test_mcp_glue.py
index 5883ff9ae..d65491992 100644
--- a/tests/unit/browser_extension/test_mcp_glue.py
+++ b/tests/unit/browser_extension/test_mcp_glue.py
@@ -949,7 +949,8 @@ def test_browser_extension_install_copies_token_opens_chrome_and_prints_steps(
assert "1. Enable Developer mode." in result.stdout
assert "2. Click Load unpacked." in result.stdout
assert f"3. Select {extension_dir}." in result.stdout
- assert "Allow User Scripts is optional" in result.stdout
+ assert "Direct JavaScript evaluation is unavailable in extension mode." in result.stdout
+ assert "Use the inspection and interaction tools." in " ".join(result.stdout.split())
assert "enable Allow User Scripts" not in result.stdout
assert "4. Open the Skyvern Agent popup." in result.stdout
assert "5. Paste the pairing token and click Connect." in result.stdout
@@ -991,7 +992,8 @@ def test_default_extension_install_describes_auto_enable_without_loading_legacy_
assert result.exit_code == 0
assert "its first broker start enables broker state automatically" in result.stdout
assert "skyvern browser extension-pair" in result.stdout
- assert "Allow User Scripts is optional" in result.stdout
+ assert "Direct JavaScript evaluation is unavailable in extension mode." in result.stdout
+ assert "Use the inspection and interaction tools." in " ".join(result.stdout.split())
assert "enable Allow User Scripts" not in result.stdout
assert "extension-broker-enable" not in result.stdout
token_loader.assert_not_called()
@@ -1011,7 +1013,8 @@ def test_browser_extension_install_attempts_one_click_pairing_when_bridge_is_lis
result = CliRunner().invoke(browser_app, ["extension-install"])
assert result.exit_code == 0
- assert "Allow User Scripts is optional" in result.stdout
+ assert "Direct JavaScript evaluation is unavailable in extension mode." in result.stdout
+ assert "Use the inspection and interaction tools." in " ".join(result.stdout.split())
assert "enable Allow User Scripts" not in result.stdout
assert "4. Approve pairing in the Skyvern Agent confirmation tab (one click)." in result.stdout
assert '5. Add tabs to the "Skyvern Controlled" group.' in result.stdout
diff --git a/tests/unit/browser_extension/test_protocol.py b/tests/unit/browser_extension/test_protocol.py
index bc44c2f94..a6d0b6f65 100644
--- a/tests/unit/browser_extension/test_protocol.py
+++ b/tests/unit/browser_extension/test_protocol.py
@@ -131,7 +131,15 @@ def test_manifest_key_derives_extension_id() -> None:
derived_extension_id = "".join(chr(ord("a") + int(nibble, 16)) for nibble in digest_prefix)
assert derived_extension_id == EXTENSION_ID
- assert "userScripts" in manifest["permissions"]
+ assert "userScripts" not in manifest["permissions"]
+ assert "web_accessible_resources" not in manifest
+ assert {
+ "matches": ["http://*/*", "https://*/*"],
+ "js": ["control_indicator.js"],
+ "run_at": "document_start",
+ "all_frames": False,
+ "world": "ISOLATED",
+ } in manifest["content_scripts"]
assert "activeTab" not in manifest["permissions"]
assert "scripting" not in manifest["permissions"]
assert manifest["minimum_chrome_version"] == "138"
@@ -146,8 +154,11 @@ def test_package_extension_builds_store_upload_zip(tmp_path: Path) -> None:
packaged_manifest = json.loads(archive.read("manifest.json"))
assert "key" not in packaged_manifest
+ assert "userScripts" not in packaged_manifest["permissions"]
assert "service_worker.js" in names
assert "dom_router.js" in names
+ assert "control_indicator.js" in names
+ assert "indicator_state.js" in names
assert "README.md" not in names
assert "build_hash.json" in names
diff --git a/tests/unit/browser_extension/test_runtime.py b/tests/unit/browser_extension/test_runtime.py
index a34913c76..f76b977b5 100644
--- a/tests/unit/browser_extension/test_runtime.py
+++ b/tests/unit/browser_extension/test_runtime.py
@@ -152,28 +152,6 @@ async def test_singleton_is_idempotent_and_late_binds_adapter_callbacks(monkeypa
assert adapters[0].disconnect_count == 1
-async def test_evaluate_routes_to_active_controlled_tab() -> None:
- relay = MagicMock()
- relay.ensure_root_lease = AsyncMock(return_value={"tabId": 17})
- relay.list_scoped_tabs = AsyncMock(
- return_value=[
- {"tabId": 17, "active": False},
- {"tabId": 18, "active": True},
- ]
- )
- relay.request = AsyncMock(return_value={"result": {"answer": 42}})
- runtime = BrowserExtensionRuntime(relay, MagicMock())
-
- assert await runtime.evaluate("({ answer: 6 * 7 })") == {"answer": 42}
- relay.ensure_root_lease.assert_awaited_once_with()
- relay.list_scoped_tabs.assert_awaited_once_with()
- relay.request.assert_awaited_once_with(
- "dom.evaluate",
- {"tabId": 18, "expression": "({ answer: 6 * 7 })"},
- )
-
-
@pytest.mark.asyncio
async def test_page_debugger_attached_caches_target_binding_and_detaches_alias() -> None:
relay = MagicMock()
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index 51191cd5f..07d45c1e1 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -81,7 +81,6 @@ from skyvern.forge.taskv3.run_arms import (
CUSTOMER_PRECEDENCE_FLAG,
DATE_SEGMENT_AIM_FLAG,
EXTRACTION_REPORTS_FLAG,
- OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG,
REQUIRED_FIELD_ANSWERS_FLAG,
TYPE_COORDINATE_CLICK_FLAG,
run_arm_enabled,
@@ -178,9 +177,6 @@ async def _run_execute_task_v3(
loop_mock.context = context
loop_mock.active_credential_parameter_key_during_loop = context.active_credential_parameter_key
loop_mock.frame_perception_enabled_during_loop = frame_perception_enabled()
- loop_mock.observe_offviewport_drop_during_loop = run_arm_enabled(
- OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG, forced=False
- )
loop_mock.type_coordinate_click_enabled_during_loop = run_arm_enabled(TYPE_COORDINATE_CLICK_FLAG, forced=False)
loop_mock.date_segment_aim_enabled_during_loop = run_arm_enabled(DATE_SEGMENT_AIM_FLAG, forced=False)
loop_mock.required_field_answers_during_loop = run_arm_enabled(REQUIRED_FIELD_ANSWERS_FLAG, forced=False)
@@ -300,34 +296,6 @@ async def _run_execute_task_v3(
return out_step, out_task, loop_mock, post_step_mock
-async def test_execute_task_v3_pins_the_observe_offviewport_arm_before_the_loop(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(settings, "TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED", False)
- reader = AsyncMock(
- side_effect=lambda flag, *_a, **_k: "treatment" if flag == OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG else None
- )
- monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "get_value_cached", reader)
-
- outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])
- _step, task, loop_mock, _post = await _run_execute_task_v3(
- monkeypatch,
- outcome,
- workflow_run_id="wr_offviewport_reach",
- data_extraction_goal=None,
- extracted_information_schema=None,
- )
-
- # Read inside the loop: the context is the same object after the run, so a pin written late would
- # still be visible here -- and every observe call builds its script from the arm as it stands then.
- assert loop_mock.observe_offviewport_drop_during_loop is True
- assert loop_mock.context.run_arms[OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG] == (task.workflow_run_id, "treatment")
- assert [c.args[1] for c in reader.await_args_list if c.args[0] == OBSERVE_DROP_OFFVIEWPORT_UNNAMED_FLAG] == [
- task.workflow_run_id
- ]
-
-
@pytest.mark.asyncio
async def test_execute_task_v3_resolves_frame_perception_before_the_loop(monkeypatch: pytest.MonkeyPatch) -> None:
"""`_execute_task_v3` must actually call `resolve_frame_perception` with the run's real
diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.py
index 36721e77b..a47c28bb1 100644
--- a/tests/unit/test_mcp_browser_tools.py
+++ b/tests/unit/test_mcp_browser_tools.py
@@ -1201,7 +1201,7 @@ async def test_click_native_option_sdk_equivalent_quotes_observed_strings(
@pytest.mark.asyncio
-async def test_evaluate_uses_direct_extension_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_evaluate_refuses_direct_extension_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
get_page = AsyncMock(side_effect=AssertionError("extension evaluation must bypass Playwright"))
evaluate = AsyncMock(return_value={"answer": 42})
runtime = SimpleNamespace(evaluate=evaluate)
@@ -1219,9 +1219,18 @@ async def test_evaluate_uses_direct_extension_runtime(monkeypatch: pytest.Monkey
result = await mcp_browser.skyvern_evaluate(expression="({ answer: 6 * 7 })")
- assert result["ok"] is True
- assert result["data"]["result"] == {"answer": 42}
- evaluate.assert_awaited_once_with("({ answer: 6 * 7 })")
+ assert result["ok"] is False
+ assert result["error"]["code"] == mcp_browser.ErrorCode.ACTION_FAILED
+ assert result["error"]["message"] == (
+ "OP_NOT_ALLOWED: Direct JavaScript evaluation is unavailable in extension mode. "
+ "Use skyvern_observe, skyvern_get_html, skyvern_find, or skyvern_get_value to inspect the page. "
+ "Use skyvern_click or skyvern_type to interact."
+ )
+ assert result["error"]["hint"] == (
+ "Use the normal browser controls. Do not enable User Scripts or reroute the expression "
+ "through CDP or another injection API."
+ )
+ evaluate.assert_not_called()
get_page.assert_not_awaited()
diff --git a/tests/unit/test_mcp_legacy_manifest.py b/tests/unit/test_mcp_legacy_manifest.py
index 8492270b8..6dece7d66 100644
--- a/tests/unit/test_mcp_legacy_manifest.py
+++ b/tests/unit/test_mcp_legacy_manifest.py
@@ -10,7 +10,8 @@ from skyvern.cli.mcp_tools import mcp
from skyvern.cli.mcp_tools.instructions import DEFAULT_INSTRUCTIONS
from skyvern.cli.mcp_tools.scopes import MCPScope, apply_scope
-DEFAULT_INSTRUCTIONS_SHA256 = "e887c974662ff34dcf1c28a0428acd03fb1bec0bb3baa35b4ccec9d85f3f886a"
+# Re-frozen for SKY-17181: the extension-mode evaluation guidance changed.
+DEFAULT_INSTRUCTIONS_SHA256 = "f2b0ac0fea44be39e5be84ec28617ad6fc9b6323003d1114c08d4dd7e9598d7f"
# Digests snapshot each legacy tool's wire manifest: name, schema, description, annotations, _meta.
# New tool names are ignored; any change to a legacy tool fails.
@@ -52,10 +53,10 @@ LEGACY_TOOL_MANIFEST_DIGESTS = {
"skyvern_credential_get": "b91bc6df14644a3a9b47e61ba05623652d208dbee58d75b595863112261c26b6",
"skyvern_credential_list": "25377204b867b5ad92e7a18b49a081dc84a109002841263c5c2132857b6e5dac",
"skyvern_drag": "58b53906edc106537f2c799da2bf5e1b8991ec9ce6a3ac5df01827aaf91b3564",
- # Re-frozen for SKY-15733: the description now says an expression that never settles returns TIMEOUT on
- # the page/CDP route and ACTION_FAILED on the extension route. Description text only; the schema is unchanged.
- "skyvern_evaluate": "581eb480a8b6979babd574eef3f1f1f82cdfbe3b5c55f089fedfcf66ab1ed61a",
- "skyvern_evaluate_and_screenshot": "2e886e466be8ed71e003f3f0c06d4ac7cb627a7eb4b2d8698a4cc0694d258de6",
+ # Re-frozen for SKY-17181: both descriptions now say that direct JavaScript evaluation is unavailable
+ # in extension mode. Description text only; the schemas are unchanged.
+ "skyvern_evaluate": "871062d2b6a6c00df9213787dc3ba642f1b4641ecd7311c8b10f08533778b5d7",
+ "skyvern_evaluate_and_screenshot": "5047c99d93ea43b8810047cae4dfb368bdbad79e7fcfbed1af5f748ec0f41aef",
"skyvern_execute": "2cb175e508b11a4e40564d2057a0725566fc1ba72080ac789512e350b8b0d532",
"skyvern_extract": "1a6323ec190bb05a00ff1739fc8e379fc6325e4ed16b4058d532743976c3f5dc",
"skyvern_extract_and_screenshot": "005995f97c6a8078bd1f589d78415c51e7a1189752da35ea2f56c7da902bee01",
diff --git a/tests/unit/test_non_secret_credential_fields.py b/tests/unit/test_non_secret_credential_fields.py
index 04b4d1768..89f2e9bd7 100644
--- a/tests/unit/test_non_secret_credential_fields.py
+++ b/tests/unit/test_non_secret_credential_fields.py
@@ -193,3 +193,33 @@ async def test_password_less_credential_resolves_real_password_to_empty(
assert entries["login_real_password"] == ""
assert entries["login_real_username"] == "[email protected]"
assert entries["login"]["password"] == ""
+
+
+async def test_password_less_credential_username_is_not_recorded_as_identifier(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A password-less login makes the username its only authenticator, so it must not be exempted
+ from the re-submit budget the way a real login's username is."""
+ credential = PasswordCredential(username="[email protected]", password="")
+
+ context, values = await _register(monkeypatch, credential=credential, parameter_key="login")
+
+ assert context.login_identifier_secret_ids == set()
+ assert context.secrets[values["username"]] == "[email protected]"
+
+
+async def test_only_a_logins_username_slot_is_recorded_as_an_identifier(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A customer-named metadata field, a card, or a response path called `username` also mints a token
+ # ending in `_username`; none of them is a login identifier, so the re-submit budget must still bind them.
+ credential = PasswordCredential(username="[email protected]", password="pw-value-1", metadata={"username": "pw-2"})
+
+ context, values = await _register(monkeypatch, credential=credential, parameter_key="login")
+ context.register_secret_value("pw-value-3", suffix="username")
+
+ assert context.login_identifier_secret_ids == {values["username"]}
+ assert context.secrets[values["username"]] == "[email protected]"
+
+ card_context, _ = await _register(monkeypatch)
+ assert card_context.login_identifier_secret_ids == set()
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index b85839941..374b796ce 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -10888,6 +10888,12 @@ async def test_refused_fill_call_stops_the_rest_of_its_batch(fill_tool: str) ->
_PASSWORD = "placeholder_TlK9_password"
_USERNAME = "placeholder_TlK9_username"
+# The exemption keys on tokens the run minted for a login's username slot, never on how a token reads:
+# a vault field, response path or parameter the customer named `username` also mints a `_username` token.
+
+
+def _issued_identifiers() -> frozenset[str]:
+ return frozenset({_USERNAME})
@pytest.mark.asyncio
@@ -11021,6 +11027,166 @@ async def test_ordinary_text_is_resubmitted_freely() -> None:
assert outcome.status == "completed", outcome.reason
+async def test_a_login_identifier_is_not_refused_within_its_own_budget() -> None:
+ # A navigation click and a click that reached nothing spend the username's budget; page-side
+ # autofill then overwrites the field. Re-entering an identifier spends no lockout allowance.
+ calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [_billable_tool("type", calls), _billable_tool("click", calls), make_finish_tool()]
+ script = [
+ [("type", {"selector": "ref=1", "text": _USERNAME})],
+ [("click", {"selector": "ref=2"})],
+ [("click", {"selector": "ref=3"})],
+ [("type", {"selector": "ref=4", "text": _USERNAME})],
+ [("click", {"selector": "ref=5"})],
+ [("type", {"selector": "ref=6", "text": _USERNAME})],
+ [("click", {"selector": "ref=7"})],
+ [("finish", {"status": "completed", "reason": "signed in"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, login_identifier_tokens=_issued_identifiers)
+
+ assert [args.get("text") for name, args in calls if name == "type"] == [_USERNAME, _USERNAME, _USERNAME]
+ assert [e for e in logs if e["event"] == loop_module.CREDENTIAL_RESUBMIT_REFUSED_EVENT] == []
+ assert outcome.status == "completed", outcome.reason
+
+
+async def test_a_login_identifier_past_its_own_budget_is_refused() -> None:
+ budget = loop_module.LOGIN_IDENTIFIER_SUBMIT_BUDGET
+ calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [_billable_tool("type", calls), _billable_tool("click", calls), make_finish_tool()]
+ script: list[list[tuple[str, dict[str, Any]]]] = []
+ for attempt in range(budget):
+ script.append([("type", {"selector": f"ref={attempt}", "text": _USERNAME})])
+ script.append([("click", {"selector": "ref=submit"})])
+ script.append([("type", {"selector": "ref=last", "text": _USERNAME})])
+ script.append([("finish", {"status": "failed", "reason": "the site kept asking for the identifier"})])
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, login_identifier_tokens=_issued_identifiers, max_turns=40)
+
+ assert [args.get("text") for name, args in calls if name == "type"] == [_USERNAME] * budget
+ assert [e["tool"] for e in logs if e["event"] == loop_module.CREDENTIAL_RESUBMIT_REFUSED_EVENT] == ["type"]
+ assert outcome.status == "failed", outcome.reason
+
+
+async def test_exempting_the_identifier_leaves_its_password_bound() -> None:
+ calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [_billable_tool("type", calls), _billable_tool("click", calls), make_finish_tool()]
+ script = [
+ [("type", {"selector": "ref=1", "text": _USERNAME})],
+ [("click", {"selector": "ref=2"})],
+ [("type", {"selector": "ref=3", "text": _PASSWORD})],
+ [("click", {"selector": "ref=4"})],
+ [("type", {"selector": "ref=5", "text": _PASSWORD})],
+ [("click", {"selector": "ref=6"})],
+ [("type", {"selector": "ref=7", "text": _PASSWORD})],
+ [("click", {"selector": "ref=8"})],
+ [("finish", {"status": "failed", "reason": "the site rejected the credential"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, login_identifier_tokens=_issued_identifiers)
+
+ assert [args.get("text") for name, args in calls if name == "type"] == [_USERNAME, _PASSWORD, _PASSWORD]
+ assert [e["tool"] for e in logs if e["event"] == loop_module.CREDENTIAL_RESUBMIT_REFUSED_EVENT] == ["type"]
+ assert outcome.status == "failed", outcome.reason
+
+
+async def test_a_retyped_login_lets_the_identifier_through_but_not_the_password_or_its_submit() -> None:
+ calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [_billable_tool("type", calls), _billable_tool("click", calls), make_finish_tool()]
+ login = [
+ ("type", {"selector": "ref=1", "text": _USERNAME}),
+ ("type", {"selector": "ref=2", "text": _PASSWORD}),
+ ("click", {"selector": "ref=3"}),
+ ]
+ script = [
+ login,
+ login,
+ login,
+ [("finish", {"status": "failed", "reason": "the site rejected the credential"})],
+ ]
+ with capture_logs() as logs:
+ outcome, caller = await _run(script, tools, login_identifier_tokens=_issued_identifiers)
+
+ assert [(name, args.get("text")) for name, args in calls] == [
+ ("type", _USERNAME),
+ ("type", _PASSWORD),
+ ("click", None),
+ ("type", _USERNAME),
+ ("type", _PASSWORD),
+ ("click", None),
+ ("type", _USERNAME),
+ ]
+ assert [e["tool"] for e in logs if e["event"] == loop_module.CREDENTIAL_RESUBMIT_REFUSED_EVENT] == ["type"]
+ last_batch = [m["content"] for m in caller.message_history if m.get("role") == "tool"][6:9]
+ assert [c.split(":")[0] for c in last_batch[1:]] == ["refused", "skipped"]
+ assert not last_batch[0].startswith(("refused", "skipped"))
+ assert outcome.status == "failed", outcome.reason
+
+
+ "token",
+ [
+ "placeholder_TlK9_card_number",
+ "placeholder_TlK9",
+ "placeholder_TlK9_login_handle",
+ "placeholder_TlK9_passwordplaceholder_Xq2w_username",
+ "placeholder_Q7mz_username",
+ ],
+ ids=[
+ "card",
+ "plain-secret",
+ "unrecognised-suffix",
+ "password-merged-into-identifier",
+ "username-shaped-but-not-issued",
+ ],
+)
+async def test_every_secret_other_than_a_login_identifier_stays_bound(token: str) -> None:
+ calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [_billable_tool("type", calls), _billable_tool("click", calls), make_finish_tool()]
+ script = [
+ [("type", {"selector": "ref=1", "text": token})],
+ [("click", {"selector": "ref=2"})],
+ [("type", {"selector": "ref=3", "text": token})],
+ [("click", {"selector": "ref=4"})],
+ [("type", {"selector": "ref=5", "text": token})],
+ [("finish", {"status": "failed", "reason": "the site rejected the value"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, login_identifier_tokens=_issued_identifiers)
+
+ assert [args.get("text") for name, args in calls if name == "type"] == [token, token]
+ assert [e["tool"] for e in logs if e["event"] == loop_module.CREDENTIAL_RESUBMIT_REFUSED_EVENT] == ["type"]
+ assert outcome.status == "failed", outcome.reason
+
+
+async def test_a_login_identifier_is_bound_when_the_run_cannot_name_its_identifiers() -> None:
+ def unresolvable() -> frozenset[str]:
+ raise RuntimeError("workflow context gone")
+
+ calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [_billable_tool("type", calls), _billable_tool("click", calls), make_finish_tool()]
+ script = [
+ [("type", {"selector": "ref=1", "text": _USERNAME})],
+ [("click", {"selector": "ref=2"})],
+ [("type", {"selector": "ref=3", "text": _USERNAME})],
+ [("click", {"selector": "ref=4"})],
+ [("type", {"selector": "ref=5", "text": _USERNAME})],
+ [("finish", {"status": "failed", "reason": "the site rejected the value"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, login_identifier_tokens=unresolvable)
+
+ assert [args.get("text") for name, args in calls if name == "type"] == [_USERNAME, _USERNAME]
+ assert [e["tool"] for e in logs if e["event"] == loop_module.CREDENTIAL_RESUBMIT_REFUSED_EVENT] == ["type"]
+ assert outcome.status == "failed", outcome.reason
+
+
# --- SKY-16271: what a guard verdict says to the customer ----------------------
# `LoopOutcome.reason` is persisted verbatim as `task.failure_reason`, a field on the customer webhook
# and the run view (`test_execute_task_v3_leaves_failure_reason_byte_identical_when_redaction_is_off`
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 0897ad13c..db0ed5c74 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -37,7 +37,7 @@ import skyvern.forge.taskv3.tools as taskv3_tools
from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.core import skyvern_context
-from skyvern.forge.sdk.core.skyvern_context import RunArm, SkyvernContext
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.services import credentials as credentials_module
from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager, WorkflowRunContext
from skyvern.forge.sdk.workflow.models.credential_release import (
@@ -3661,6 +3661,1693 @@ async def test_observe_group_text_has_a_page_total_cap() -> None:
assert groups[-1] is None
+def _radio_records(data: dict[str, Any]) -> list[dict[str, Any]]:
+ return [e for e in data["elements"] if e.get("type") == "radio" or e.get("role") == "radio"]
+
+
+def _assert_each_question_reaches_only_its_own_radios(
+ data: dict[str, Any],
+ content: str,
+ groups: dict[str, set[str]],
+ key: Callable[[dict[str, Any]], str],
+) -> None:
+ # Field-agnostic on purpose: the question may arrive in any field of the radio's record, but it
+ # must arrive on that group's radios, on no other group's radios, and in a radio line the model reads.
+ radios = _radio_records(data)
+ for question, members in groups.items():
+ own = [e for e in radios if key(e) in members]
+ assert len(own) == len(members), f"fixture radios for {question!r} are not all listed: {radios}"
+ assert any(question in json.dumps(e) for e in own), f"{question!r} is on none of its radios: {own}"
+ foreign = [e for e in radios if key(e) not in members and question in json.dumps(e)]
+ assert not foreign, f"{question!r} is on another group's radios: {foreign}"
+ radio_lines = [line for line in content.splitlines() if "/radio" in line]
+ assert any(question in line for line in radio_lines), f"{question!r} is on no radio line:\n{content}"
+
+
+def _yes_no_radios(name: str) -> str:
+ return (
+ f'<label><input type="radio" name="{name}" value="{name}-yes">Yes</label>'
+ f'<label><input type="radio" name="{name}" value="{name}-no">No</label>'
+ )
+
+
+def _assert_marked_not_guessed(data: dict[str, Any], content: str, markers: int, never: list[str]) -> None:
+ # A question the page does not declare is never guessed from nearby text: the radio lines carry
+ # the fail-loud marker, once per group, and none of the nearby text. `placement` is left out: its
+ # section heading is a disambiguation qualifier, printed only when two lines collide.
+ radios = _radio_records(data)
+ assert radios, data
+ for e in radios:
+ assert not e.get("group"), e
+ for text in never:
+ assert text not in json.dumps({k: v for k, v in e.items() if k != "placement"}), (text, e)
+ assert content.count("group=(no question found)") == markers, content
+
+
+@_skip_no_browser
[email protected]("caption_first", [False, True], ids=["caption-after-control", "caption-before-control"])
+async def test_observe_radio_question_in_a_fieldset_legend_reaches_its_radios(caption_first: bool) -> None:
+ def radios(name: str) -> str:
+ if not caption_first:
+ return _yes_no_radios(name)
+ return "".join(
+ f'<label>{v} <input type="radio" name="{name}" value="{name}-{v.lower()}"></label>' for v in ("Yes", "No")
+ )
+
+ html = (
+ "<!doctype html><html><body><form>"
+ f"<fieldset><legend>Are you at least 18 years old?</legend>{radios('qa')}</fieldset>"
+ f"<fieldset><legend>Do you hold a valid driving licence?</legend>{radios('qb')}</fieldset>"
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_each_question_reaches_only_its_own_radios(
+ data,
+ r.content,
+ {
+ "Are you at least 18 years old?": {"qa-yes", "qa-no"},
+ "Do you hold a valid driving licence?": {"qb-yes", "qb-no"},
+ },
+ key=lambda e: str(e.get("value")),
+ )
+
+
+@_skip_no_browser
[email protected]("with_text_input", [False, True], ids=["radios-only", "block-with-text-input"])
+async def test_observe_radios_after_an_undeclared_question_block_are_marked_not_guessed(with_text_input: bool) -> None:
+ # No fieldset, no class, no ARIA: the block before each radio wrapper may be the question, a hint or
+ # another section's text, and nothing on the page says which. Each group is marked instead.
+ detail = '<input type="text" name="qb-detail" placeholder="Please explain">' if with_text_input else ""
+ html = (
+ "<!doctype html><html><body><form><div>"
+ f"<label>Are you legally authorized to work in this country?</label><div>{_yes_no_radios('qa')}</div>"
+ f"<p>Will you now or in the future require sponsorship?</p><div>{_yes_no_radios('qb')}{detail}</div>"
+ f"<label>Have you worked for this company before?</label><div>{_yes_no_radios('qc')}</div>"
+ "</div></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(
+ data,
+ r.content,
+ 3,
+ [
+ "Are you legally authorized to work in this country?",
+ "Will you now or in the future require sponsorship?",
+ "Have you worked for this company before?",
+ ],
+ )
+
+
+@_skip_no_browser
+async def test_observe_radio_question_in_a_table_row_header_reaches_its_radios() -> None:
+ questions = {
+ "qa": "Are you willing to relocate?",
+ "qb": "Are you willing to travel?",
+ "qc": "Are you able to work weekends?",
+ }
+ rows = "".join(
+ f'<tr><th>{q}</th><td><label><input type="radio" name="{k}" value="{k}-yes">Yes</label></td>'
+ f'<td><label><input type="radio" name="{k}" value="{k}-no">No</label></td></tr>'
+ for k, q in questions.items()
+ )
+ html = f"<!doctype html><html><body><form><table>{rows}</table></form></body></html>"
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_each_question_reaches_only_its_own_radios(
+ data, r.content, {q: {f"{k}-yes", f"{k}-no"} for k, q in questions.items()}, key=lambda e: str(e.get("value"))
+ )
+
+
+# Mirrors a design-system form: the whole form sits in an app host's shadow root, each group is an
+# unmarked custom element whose question is a light-DOM child slotted into `label-content`, and each
+# radio draws its caption in its own shadow root.
+_SHADOW_RADIO_GROUPS_HTML = """<!doctype html><html><body>
+<x-app id="app"></x-app>
+<script>
+customElements.define('x-radio', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML =
+ '<span style="display:inline-block;width:12px;height:12px;border:1px solid #333;border-radius:50%"></span>'
+ + '<span class="cap"></span>';
+ }
+ connectedCallback() {
+ this.shadowRoot.querySelector('.cap').textContent = this.getAttribute('label');
+ this.style.display = 'inline-block';
+ this.style.cursor = 'pointer';
+ this.tabIndex = 0;
+ if (!this.hasAttribute('aria-checked')) this.setAttribute('aria-checked', 'false');
+ this.addEventListener('click', () => {
+ for (const s of this.parentElement.querySelectorAll('x-radio'))
+ s.setAttribute('aria-checked', s === this ? 'true' : 'false');
+ });
+ }
+ get value() { return this.getAttribute('value'); }
+});
+customElements.define('x-radio-group', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML =
+ '<div><slot name="label-content"></slot></div><div><slot></slot></div>';
+ }
+ connectedCallback() { this.style.display = 'block'; }
+});
+customElements.define('x-app', class extends HTMLElement {
+ constructor() {
+ super();
+ const groups = [['qa', 'Are you legally authorized to work in this country?'],
+ ['qb', 'Will you now or in the future require sponsorship?'],
+ ['qc', 'Have you worked for this company before?']];
+ this.attachShadow({mode: 'open'}).innerHTML = '<form>' + groups.map(([k, q]) =>
+ '<x-radio-group><span slot="label-content">' + q + '</span>'
+ + '<x-radio id="' + k + '-yes" role="radio" label="Yes" value="1"></x-radio>'
+ + '<x-radio id="' + k + '-no" role="radio" label="No" value="0"></x-radio>'
+ + '</x-radio-group>').join('') + '</form>';
+ }
+});
+</script></body></html>"""
+
+
+@_skip_no_browser
+async def test_observe_radio_question_slotted_into_a_shadow_radio_group_reaches_its_radios() -> None:
+ async with _content_page(_SHADOW_RADIO_GROUPS_HTML) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_each_question_reaches_only_its_own_radios(
+ data,
+ r.content,
+ {
+ "Are you legally authorized to work in this country?": {"#qa-yes", "#qa-no"},
+ "Will you now or in the future require sponsorship?": {"#qb-yes", "#qb-no"},
+ "Have you worked for this company before?": {"#qc-yes", "#qc-no"},
+ },
+ key=lambda e: str(e.get("selector")),
+ )
+
+
+@_skip_no_browser
+async def test_observe_shadow_radio_is_named_by_its_caption_not_its_value() -> None:
+ # The caption lives in the radio's own shadow root; the value ('1'/'0') is not a name the model
+ # can match against 'Yes'/'No'.
+ async with _content_page(_SHADOW_RADIO_GROUPS_HTML) as page:
+ data = await _observe_data(page)
+ labels = {e["selector"]: e.get("label") for e in _radio_records(data)}
+ assert labels["#qa-yes"] == "Yes", labels
+ assert labels["#qa-no"] == "No", labels
+
+
+@_skip_no_browser
+async def test_observe_radiogroup_aria_labelledby_question_reaches_its_radios() -> None:
+ def group(k: str, question: str) -> str:
+ return (
+ f'<p id="{k}-q">{question}</p>'
+ f'<div role="radiogroup" aria-labelledby="{k}-q">'
+ f'<div id="{k}-yes" role="radio" aria-checked="false" tabindex="0">Yes</div>'
+ f'<div id="{k}-no" role="radio" aria-checked="false" tabindex="-1">No</div></div>'
+ )
+
+ html = (
+ "<!doctype html><html><body><form>"
+ + group("qa", "Are you legally authorized to work in this country?")
+ + group("qb", "Will you now or in the future require sponsorship?")
+ + "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_each_question_reaches_only_its_own_radios(
+ data,
+ r.content,
+ {
+ "Are you legally authorized to work in this country?": {"#qa-yes", "#qa-no"},
+ "Will you now or in the future require sponsorship?": {"#qb-yes", "#qb-no"},
+ },
+ key=lambda e: str(e.get("selector")),
+ )
+
+
+@_skip_no_browser
+async def test_observe_marks_radios_whose_question_cannot_be_found() -> None:
+ html = (
+ "<!doctype html><html><body><form>"
+ f"<div>{_yes_no_radios('qa')}</div><div>{_yes_no_radios('qb')}</div>"
+ f"<fieldset><legend>Do you hold a valid driving licence?</legend>{_yes_no_radios('qc')}</fieldset>"
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ by_value = {str(e.get("value")): e for e in _radio_records(data)}
+ for value in ("qa-yes", "qa-no", "qb-yes", "qb-no"):
+ assert by_value[value].get("group_missing"), f"{value} is not marked as having no question: {by_value[value]}"
+ # A radio whose question WAS found is not marked, so the marker cannot be a constant.
+ assert not by_value["qc-yes"].get("group_missing"), by_value["qc-yes"]
+
+
+@_skip_no_browser
+async def test_observe_renders_the_no_question_marker_once_per_radio_group() -> None:
+ html = (
+ "<!doctype html><html><body><form>"
+ f"<div>{_yes_no_radios('qa')}</div><div>{_yes_no_radios('qb')}</div>"
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ radio_lines = [line for line in r.content.splitlines() if "/radio" in line]
+ assert len(radio_lines) == 4, r.content
+ assert r.content.count("group=(no question found)") == 2, r.content
+ assert "(no question found)" in radio_lines[0] and "(no question found)" in radio_lines[2], r.content
+
+
+@_skip_no_browser
+async def test_observe_a_short_group_question_rides_on_its_first_option_only() -> None:
+ # Each group's question is shorter than its option captions. It must still reach the group, and on
+ # its first option: printed on a later option it reads as the start of another group.
+ def group(k: str, question: str) -> str:
+ return (
+ f'<div role="radiogroup" aria-label="{question}">'
+ f'<div id="{k}-1" role="radio" aria-checked="false" tabindex="0">Light roast beans</div>'
+ f'<div id="{k}-2" role="radio" aria-checked="false" tabindex="-1">Medium roast beans</div>'
+ f'<div id="{k}-3" role="radio" aria-checked="false" tabindex="-1">Dark roast beans</div></div>'
+ )
+
+ html = "<!doctype html><html><body><form>" + group("qa", "Small") + group("qb", "Large") + "</form></body></html>"
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ groups = {e["selector"]: e.get("group") for e in _radio_records(data)}
+ assert groups == {
+ "#qa-1": "Small",
+ "#qa-2": None,
+ "#qa-3": None,
+ "#qb-1": "Large",
+ "#qb-2": None,
+ "#qb-3": None,
+ }, groups
+ radio_lines = [line for line in r.content.splitlines() if "/radio" in line]
+ assert [("group='Small'" in line, "group='Large'" in line) for line in radio_lines] == [
+ (True, False),
+ (False, False),
+ (False, False),
+ (False, True),
+ (False, False),
+ (False, False),
+ ], r.content
+
+
+@_skip_no_browser
[email protected]("layout", ["section-wrappers", "flat-sections", "checkbox-pairs"])
+async def test_observe_lone_checkboxes_never_take_another_sections_text(layout: str) -> None:
+ # Documentation-style sections, each a heading, a paragraph and a demo of its own checkbox(es):
+ # nothing groups the sections, so no checkbox may borrow a neighbouring section's text, or the
+ # page title above them all.
+ sections = [
+ ("Mixed state demo", "A checkbox can show a mixed state."),
+ ("Turned off demo", "Add the attribute to turn a checkbox off."),
+ ("Toggle style demo", "Render the checkbox as a toggle."),
+ ]
+ boxes_per_demo = 2 if layout == "checkbox-pairs" else 1
+ blocks = []
+ for i, (title, para) in enumerate(sections):
+ demo = (
+ "<div>"
+ + "".join(
+ f"<div class='check'><input type='checkbox' id='c{i}{k}'><label for='c{i}{k}'>Option {i}{k}</label></div>"
+ for k in range(boxes_per_demo)
+ )
+ + "</div>"
+ )
+ body = f"<h3>{title}</h3><p>{para}</p><div class='demo'>{demo}</div>"
+ blocks.append(body if layout == "flat-sections" else f"<section>{body}</section>")
+ html = f"<!doctype html><html><body><main><h2>Form controls</h2>{''.join(blocks)}</main></body></html>"
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ checkboxes = [e for e in data["elements"] if e.get("type") == "checkbox"]
+ assert len(checkboxes) == 3 * boxes_per_demo, checkboxes
+ for e in checkboxes:
+ own = int(str(e["selector"])[2])
+ for j, (title, para) in enumerate(sections):
+ if j != own:
+ assert title not in json.dumps(e) and para not in json.dumps(e), e
+ # A preceding paragraph is never a checkbox's question, and a container holding every
+ # section names none of them.
+ assert not e.get("group"), e
+
+
+_SHADOW_LABELLED_GROUPS_HTML = """<!doctype html><html><body>
+<script>
+customElements.define('x-choice-group', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML = '<fieldset><legend></legend><slot></slot></fieldset>';
+ }
+ connectedCallback() {
+ this.shadowRoot.querySelector('legend').textContent = this.getAttribute('label');
+ this.style.display = 'block';
+ }
+});
+</script>
+<p>Set the value attribute to choose the initially selected option.</p>
+<x-choice-group label="Coffee roast">
+ <div role="radio" id="qa-1" aria-checked="false" tabindex="0">Light</div>
+ <div role="radio" id="qa-2" aria-checked="false" tabindex="-1">Dark</div>
+</x-choice-group>
+<p>Add the disabled attribute to turn off the whole group.</p>
+<x-choice-group label="Shipping speed">
+ <div role="radio" id="qb-1" aria-checked="false" tabindex="0">Standard</div>
+ <div role="radio" id="qb-2" aria-checked="false" tabindex="-1">Express</div>
+</x-choice-group>
+</body></html>"""
+
+
+@_skip_no_browser
+async def test_observe_radio_group_label_drawn_in_the_group_components_shadow_root_is_marked_not_guessed() -> None:
+ # What a group component draws in its own shadow root may be its label, a hint or an error, so it is
+ # never read as the question, and neither is the paragraph above the group.
+ async with _content_page(_SHADOW_LABELLED_GROUPS_HTML) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 2, ["Set the value attribute", "Add the disabled"])
+
+
+# Each option component holds its native radio in its own shadow root.
+_SHADOW_NATIVE_OPTION_HTML = """<!doctype html><html><body>
+<script>
+customElements.define('x-opt', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML = '<label><input type="radio" name="roast"><slot></slot></label>';
+ }
+});
+</script>
+<form>__QUESTION__<div><x-opt>Light</x-opt><x-opt>Medium</x-opt><x-opt>Dark</x-opt></div></form>
+</body></html>"""
+
+
+@_skip_no_browser
[email protected]("paragraph", ["", "Which roast do you want?"], ids=["bare", "paragraph-before"])
+async def test_observe_radios_in_each_options_own_shadow_root_are_one_group(paragraph: str) -> None:
+ html = _SHADOW_NATIVE_OPTION_HTML.replace("__QUESTION__", f"<p>{paragraph}</p>" if paragraph else "")
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ radios = _radio_records(data)
+ assert [e.get("label") for e in radios] == ["Light", "Medium", "Dark"], radios
+ assert len({e.get("group_missing") for e in radios}) == 1 and radios[0].get("group_missing"), radios
+ _assert_marked_not_guessed(data, r.content, 1, [paragraph] if paragraph else [])
+
+
+@_skip_no_browser
[email protected]("with_label", [True, False], ids=["label-before", "nav-links-only"])
[email protected]("declared", [True, False], ids=["radiogroup", "plain-container"])
+async def test_observe_proxy_radios_are_one_group_and_never_take_nearby_text(with_label: bool, declared: bool) -> None:
+ # Each option is a role=radio button beside a hidden native radio carrying its form value.
+ def option(value: str, caption: str) -> str:
+ return (
+ f'<div><button type="button" role="radio" aria-checked="false" id="d-{value}">{caption}</button>'
+ f'<input type="radio" aria-hidden="true" tabindex="-1" value="{value}" '
+ 'style="position:absolute;pointer-events:none;opacity:0;margin:0;width:16px;height:16px"></div>'
+ )
+
+ html = (
+ "<!doctype html><html><body>"
+ '<nav><a href="#one">First kit</a> <a href="#two">Second kit</a></nav>'
+ + ("<label>Choose a density</label>" if with_label else "")
+ + ('<div role="radiogroup">' if declared else "<div>")
+ + option("default", "Default")
+ + option("comfortable", "Comfortable")
+ + option("compact", "Compact")
+ # A declared radiogroup is one group whatever else it holds, a hint after its options included.
+ + ("<p>You can change this later.</p>" if declared else "")
+ + "</div></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ radios = _radio_records(data)
+ assert {"#d-default", "#d-comfortable", "#d-compact"} <= {e.get("selector") for e in radios}, radios
+ # An undeclared label before the group is not guessed at either; the group is marked once.
+ _assert_marked_not_guessed(
+ data, r.content, 1, ["First kit", "Second kit", "Choose a density", "You can change this later."]
+ )
+
+
+@_skip_no_browser
+async def test_observe_radiogroup_labelled_by_text_after_it_reaches_its_radios() -> None:
+ # The labelling text follows each group, so the text before group B is group A's question.
+ def group(k: str, question: str) -> str:
+ return (
+ f'<div role="radiogroup" aria-labelledby="{k}-q">'
+ f'<div id="{k}-yes" role="radio" aria-checked="false" tabindex="0">Yes</div>'
+ f'<div id="{k}-no" role="radio" aria-checked="false" tabindex="-1">No</div></div>'
+ f'<p id="{k}-q">{question}</p>'
+ )
+
+ html = (
+ "<!doctype html><html><body><form>"
+ + group("qa", "Are you legally authorized to work in this country?")
+ + group("qb", "Will you now or in the future require sponsorship?")
+ + "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_each_question_reaches_only_its_own_radios(
+ data,
+ r.content,
+ {
+ "Are you legally authorized to work in this country?": {"#qa-yes", "#qa-no"},
+ "Will you now or in the future require sponsorship?": {"#qb-yes", "#qb-no"},
+ },
+ key=lambda e: str(e.get("selector")),
+ )
+
+
+@_skip_no_browser
[email protected]("wrapper", ["bare", "in-a-field-wrapper", "under-a-visible-label"])
+async def test_observe_radiogroup_holding_a_text_field_keeps_its_declared_name(wrapper: str) -> None:
+ name = (
+ 'aria-labelledby="pcm-label"' if wrapper == "under-a-visible-label" else 'aria-label="Preferred contact method"'
+ )
+ group = (
+ f'<div role="radiogroup" {name}>'
+ '<div role="radio" id="p-email" aria-checked="false" tabindex="0">Email</div>'
+ '<div role="radio" id="p-phone" aria-checked="false" tabindex="-1">Phone</div>'
+ '<div role="radio" id="p-other" aria-checked="false" tabindex="-1">Other</div>'
+ '<input type="text" name="other_detail" aria-label="Other method"></div>'
+ )
+ if wrapper == "in-a-field-wrapper":
+ group = f'<div class="form-field">{group}</div>'
+ elif wrapper == "under-a-visible-label":
+ group = f'<div class="form-field"><span id="pcm-label">Preferred contact method</span>{group}</div>'
+ html = f"<!doctype html><html><body><form>{group}</form></body></html>"
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ by_sel = {e["selector"]: e for e in _radio_records(data)}
+ assert "Preferred contact method" in (by_sel["#p-email"].get("group") or ""), by_sel
+ assert not any(e.get("group_missing") for e in by_sel.values()), by_sel
+
+
+@_skip_no_browser
+async def test_observe_flat_named_radio_groups_are_each_marked_once() -> None:
+ # No per-question wrapper: both groups and both questions are siblings in one container. The radio
+ # names still tell the groups apart, so each is marked once and neither takes the other's question.
+ html = (
+ "<!doctype html><html><body><form><div>"
+ f"<p>Are you willing to relocate?</p>{_yes_no_radios('qa')}"
+ f"<p>Are you willing to travel?</p>{_yes_no_radios('qb')}"
+ "</div></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 2, ["Are you willing to relocate?", "Are you willing to travel?"])
+ by_value = {str(e.get("value")): e.get("group_missing") for e in _radio_records(data)}
+ assert by_value["qa-yes"] == by_value["qa-no"] != by_value["qb-yes"] == by_value["qb-no"], by_value
+
+
+@_skip_no_browser
+async def test_observe_a_container_of_several_unnamed_radio_groups_is_marked_once_not_per_option() -> None:
+ # Nothing names or declares the two groups apart, so the container is marked once: a marker on every
+ # option would read as a new group starting at each one.
+ html = (
+ "<!doctype html><html><body><div>"
+ "<p>First question here?</p>"
+ '<div role="radio" id="a-1" aria-checked="false" tabindex="0">Yes</div>'
+ '<div role="radio" id="a-2" aria-checked="false" tabindex="-1">No</div>'
+ "<p>Second question here?</p>"
+ '<div role="radio" id="b-1" aria-checked="false" tabindex="0">Yes</div>'
+ '<div role="radio" id="b-2" aria-checked="false" tabindex="-1">No</div>'
+ "</div></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 1, ["First question here?", "Second question here?"])
+
+
+@_skip_no_browser
+async def test_observe_a_caption_after_a_radio_is_never_the_next_groups_question() -> None:
+ # Bare captions: 'No' is the second radio's caption, and it sits right before the next group.
+ html = (
+ "<!doctype html><html><body><form>"
+ '<input type="radio" name="a" value="a1">Yes <input type="radio" name="a" value="a2">No'
+ '<div><input type="radio" name="b" value="b1">Sure <input type="radio" name="b" value="b2">Nope</div>'
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ by_value = {str(e.get("value")): e for e in _radio_records(data)}
+ assert not by_value["b1"].get("group") and not by_value["b2"].get("group"), by_value
+ assert by_value["b1"].get("group_missing"), by_value
+
+
+def _yes_no_labelled(name: str, yes: str = "Yes", no: str = "No") -> str:
+ return (
+ f'<label><input type="radio" name="{name}" value="{name}-yes">{yes}</label>'
+ f'<label><input type="radio" name="{name}" value="{name}-no">{no}</label>'
+ )
+
+
+@_skip_no_browser
+ ("body", "never", "markers"),
+ [
+ pytest.param(
+ "<div><h1>Senior Engineer</h1><div>We are looking for an engineer who loves distributed systems.</div></div>"
+ f"<form><div>{_yes_no_labelled('a', 'I am a veteran', 'I am not a veteran')}</div>"
+ "<label>Email<input type=text name=email></label></form>",
+ ["Senior Engineer", "distributed systems"],
+ 1,
+ id="description-before-form",
+ ),
+ pytest.param(
+ "<form><div><label>Are you authorized to work here?</label><small>Select one option</small>"
+ f"<div>{_yes_no_radios('a')}</div></div></form>",
+ ["Select one option"],
+ 1,
+ id="hint-between",
+ ),
+ pytest.param(
+ "<form><div><label>Are you authorized to work here?</label>"
+ f"<div style='color:red'>This field is required</div><div>{_yes_no_radios('a')}</div></div>"
+ f"<div><label>Do you need sponsorship?</label><div style='color:red'>This field is required</div>"
+ f"<div>{_yes_no_radios('b')}</div></div></form>",
+ ["This field is required"],
+ 2,
+ id="error-between",
+ ),
+ pytest.param(
+ "<form><label>Name <input type=text name=n></label><section><h3>Voluntary Self-Identification</h3>"
+ f"<div>{_yes_no_labelled('vet', 'I identify as a veteran', 'I do not identify as a veteran')}</div>"
+ "</section></form>",
+ ["Voluntary Self-Identification"],
+ 1,
+ id="section-title",
+ ),
+ pytest.param(
+ f"<form><div><h4>Pick a delivery option</h4>{_yes_no_radios('a')}</div></form>",
+ ["Pick a delivery option"],
+ 1,
+ id="heading-inside-options-box",
+ ),
+ pytest.param(
+ "<form><p>Please answer all the questions below honestly.</p>"
+ f"<div><div>{_yes_no_radios('a')}</div><label>Are you willing to relocate?</label></div></form>",
+ ["Please answer all the questions"],
+ 1,
+ id="instruction-before",
+ ),
+ pytest.param(
+ "<form>"
+ + "".join(
+ f"<div class='q'><div class='application-label'>{q}</div><div class='application-field'><ul>"
+ f"<li><label><input type=radio name={k} value={k}-yes>Yes</label></li>"
+ f"<li><label><input type=radio name={k} value={k}-no>No</label></li></ul>"
+ "<div style='color:red'>This field is required.</div></div></div>"
+ for k, q in (("a", "Are you authorized to work here?"), ("b", "Do you need sponsorship?"))
+ )
+ + "</form>",
+ ["This field is required."],
+ 2,
+ id="error-after-options-in-the-field-wrapper",
+ ),
+ ],
+)
+async def test_observe_text_near_a_radio_group_is_never_taken_as_its_question(
+ body: str, never: list[str], markers: int
+) -> None:
+ async with _content_page(f"<!doctype html><html><body>{body}</body></html>") as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, markers, never)
+
+
+# A group component that slots its question in and draws a validation message in its own shadow root.
+_SHADOW_ERROR_GROUP_HTML = """<!doctype html><html><body>
+<script>
+customElements.define('x-field-group', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML =
+ '<div><slot name="label"></slot></div><slot></slot><div>Please select an option</div>';
+ }
+ connectedCallback() { this.style.display = 'block'; }
+});
+</script>
+<form>
+<x-field-group><span slot="label">Are you authorized to work here?</span>
+ <div role="radio" id="qa-1" aria-checked="false" tabindex="0">Yes</div>
+ <div role="radio" id="qa-2" aria-checked="false" tabindex="-1">No</div></x-field-group>
+<x-field-group><span slot="label">Do you need sponsorship?</span>
+ <div role="radio" id="qb-1" aria-checked="false" tabindex="0">Yes</div>
+ <div role="radio" id="qb-2" aria-checked="false" tabindex="-1">No</div></x-field-group>
+</form></body></html>"""
+
+
+@_skip_no_browser
+async def test_observe_a_group_components_drawn_error_never_replaces_its_slotted_question() -> None:
+ async with _content_page(_SHADOW_ERROR_GROUP_HTML) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_each_question_reaches_only_its_own_radios(
+ data,
+ r.content,
+ {"Are you authorized to work here?": {"#qa-1", "#qa-2"}, "Do you need sponsorship?": {"#qb-1", "#qb-2"}},
+ key=lambda e: str(e.get("selector")),
+ )
+ for e in _radio_records(data):
+ assert "Please select an option" not in json.dumps(e), e
+
+
+# Choice components that draw their caption, or their state, in their own shadow root.
+_DRAWN_CAPTION_COMPONENTS_JS = """<script>
+for (const [tag, role] of [['x-cap-radio', 'radio'], ['x-cap-switch', 'switch']]) {
+ customElements.define(tag, class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML =
+ '<span style="display:inline-block;width:12px;height:12px;border:1px solid #333"></span><span class="cap"></span>';
+ }
+ connectedCallback() {
+ this.shadowRoot.querySelector('.cap').textContent = this.getAttribute('caption');
+ this.setAttribute('role', role);
+ this.setAttribute('aria-checked', 'false');
+ this.tabIndex = 0;
+ this.style.display = 'block';
+ }
+ });
+}
+</script>"""
+
+
+@_skip_no_browser
+async def test_observe_a_fieldset_legend_survives_option_captions_longer_than_it() -> None:
+ # The legend is shorter than each drawn caption; a drawn caption must not hide the declared question.
+ html = (
+ f"<!doctype html><html><body>{_DRAWN_CAPTION_COMPONENTS_JS}<form>"
+ '<fieldset><legend>Relocate?</legend><x-cap-radio id="r-yes" caption="Yes, I am willing to relocate"></x-cap-radio>'
+ '<x-cap-radio id="r-no" caption="No, I am not willing to relocate"></x-cap-radio></fieldset>'
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ by_sel = {e["selector"]: e for e in _radio_records(data)}
+ assert by_sel["#r-yes"].get("label") == "Yes, I am willing to relocate", by_sel
+ assert "Relocate?" in (by_sel["#r-yes"].get("group") or ""), by_sel
+ assert not any(e.get("group_missing") for e in by_sel.values()), by_sel
+
+
+@_skip_no_browser
+async def test_observe_a_lone_radios_legend_survives_a_longer_drawn_caption() -> None:
+ # A lone radio (no sibling of its own kind) never gets a cached choice-group entry, so its group
+ # text is compared against the page-declared name, not the shadow-drawn caption that fills it later.
+ html = (
+ f"<!doctype html><html><body>{_DRAWN_CAPTION_COMPONENTS_JS}<form>"
+ "<fieldset><legend>Relocate?</legend>"
+ '<x-cap-radio id="r-yes" caption="Yes, I am willing to relocate"></x-cap-radio></fieldset>'
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ by_sel = {e["selector"]: e for e in _radio_records(data)}
+ assert by_sel["#r-yes"].get("label") == "Yes, I am willing to relocate", by_sel
+ assert "Relocate?" in (by_sel["#r-yes"].get("group") or ""), by_sel
+ assert not any(e.get("group_missing") for e in by_sel.values()), by_sel
+
+
+@_skip_no_browser
+async def test_observe_a_titled_choice_component_is_named_by_its_title_not_its_drawn_text() -> None:
+ # A switch draws its state ('Off'), which is never its name; a title outranks any drawn caption.
+ html = (
+ f"<!doctype html><html><body>{_DRAWN_CAPTION_COMPONENTS_JS}<form>"
+ '<x-cap-switch id="s-dark" caption="Off" title="Enable dark mode"></x-cap-switch>'
+ '<x-cap-switch id="s-bare" caption="Off"></x-cap-switch>'
+ '<x-cap-radio id="r-titled" caption="Yes" title="Subscribe to updates"></x-cap-radio>'
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ labels = {e["selector"]: e.get("label") for e in data["elements"]}
+ assert labels["#s-dark"] == "Enable dark mode", labels
+ assert labels["#s-bare"] != "Off", labels
+ assert labels["#r-titled"] == "Subscribe to updates", labels
+
+
+@_skip_no_browser
+async def test_observe_radio_list_items_holding_only_captions_do_not_silence_the_marker() -> None:
+ # Each <li> holds one option, so its text is that option's caption, never the group's question.
+ html = (
+ "<!doctype html><html><body><form>"
+ "<p>Are you willing to relocate?</p><ul>"
+ '<li><label><input type="radio" name="a" value="a1">Yes</label></li>'
+ '<li><label><input type="radio" name="a" value="a2">No</label></li></ul>'
+ "<p>Are you willing to travel?</p><ul>"
+ '<li><label><input type="radio" name="b" value="b1">Yes</label></li>'
+ '<li><label><input type="radio" name="b" value="b2">No</label></li></ul>'
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 2, ["Are you willing to relocate?", "Are you willing to travel?"])
+
+
+@_skip_no_browser
+async def test_observe_a_fieldset_legend_naming_a_section_is_never_a_radio_question() -> None:
+ # The fieldset also holds a text field, so its legend names the section, not the radio group.
+ html = (
+ "<!doctype html><html><body><form><fieldset><legend>Personal details</legend>"
+ '<label>Full name <input type="text" name="full_name"></label>'
+ f"{_yes_no_radios('qa')}</fieldset></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 1, ["Personal details"])
+
+
+# A group component with a label slot for its question and a default slot for its options.
+_SLOTTING_GROUP_JS = """<script>
+customElements.define('x-slot-group', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML = '<div><slot name="label"></slot></div><slot></slot>';
+ }
+ connectedCallback() { this.style.display = 'block'; }
+});
+</script>"""
+
+
+@_skip_no_browser
+async def test_observe_a_group_component_slotting_two_questions_gives_neither_to_all_its_options() -> None:
+ # Each option shows its own caption, so the second question after the first group's last option is
+ # not that option's caption: the component holds two questions and is marked, not named.
+ html = (
+ f"<!doctype html><html><body>{_SLOTTING_GROUP_JS}<form><x-slot-group>"
+ '<span slot="label">Do you drive?</span>'
+ '<div role="radio" id="a-1" aria-checked="false" tabindex="0">Yes</div>'
+ '<div role="radio" id="a-2" aria-checked="false" tabindex="-1">No</div>'
+ '<span slot="label">Do you smoke?</span>'
+ '<div role="radio" id="b-1" aria-checked="false" tabindex="0">Yes</div>'
+ '<div role="radio" id="b-2" aria-checked="false" tabindex="-1">No</div>'
+ "</x-slot-group></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 1, ["Do you drive?", "Do you smoke?"])
+
+
+@_skip_no_browser
+async def test_observe_a_slotted_question_excludes_the_captions_that_follow_its_options() -> None:
+ # The options draw no caption of their own; the text after each is that option's caption.
+ radio = (
+ '<div role="radio" aria-label="{0}" aria-checked="false" tabindex="0" '
+ 'style="display:inline-block;width:12px;height:12px;border:1px solid #333"></div><span>{0}</span>'
+ )
+ html = (
+ f"<!doctype html><html><body>{_SLOTTING_GROUP_JS}<form><x-slot-group>"
+ '<span slot="label">Are you willing to relocate?</span>'
+ + radio.format("Yes")
+ + radio.format("No")
+ + "</x-slot-group>"
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ radios = _radio_records(data)
+ assert [e.get("group") for e in radios] == ["Are you willing to relocate?", None], radios
+ assert not any(e.get("group_missing") for e in radios), radios
+
+
+# A group component that draws a question from its `label` attribute and has label, help-text and
+# error slots; an option component with its caption in light DOM; and a plain layout component.
+_SLOT_API_COMPONENTS_JS = """<script>
+customElements.define('x-rg', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML = '<div><div class="lbl"></div><slot name="label"></slot>'
+ + '<div><slot></slot></div><div><slot name="help-text"></slot></div><div><slot name="error"></slot></div></div>';
+ }
+ connectedCallback() {
+ this.style.display = 'block';
+ this.shadowRoot.querySelector('.lbl').textContent = this.getAttribute('label') || '';
+ }
+});
+customElements.define('x-r', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML =
+ '<span style="display:inline-block;width:10px;height:10px;border:1px solid"></span><slot></slot>';
+ }
+ connectedCallback() {
+ this.setAttribute('role', 'radio');
+ this.setAttribute('tabindex', '0');
+ this.setAttribute('aria-checked', 'false');
+ this.style.display = 'block';
+ }
+});
+customElements.define('x-stack', class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({mode: 'open'}).innerHTML = '<div style="display:flex;flex-direction:column"><slot></slot></div>';
+ }
+});
+</script>"""
+
+
+def _swatch(label: str) -> str:
+ return (
+ f'<div role="radio" aria-checked="false" tabindex="0" aria-label="{label}" '
+ 'style="display:inline-block;width:24px;height:24px;border:1px solid"></div>'
+ )
+
+
+@_skip_no_browser
+ ("body", "never", "markers"),
+ [
+ pytest.param(
+ "<x-rg label='Are you legally authorized to work here?'><div slot='help-text'>Choose the option that "
+ "applies to you</div><x-r>Yes</x-r><x-r>No</x-r></x-rg>"
+ "<x-rg label='Will you require visa sponsorship?'><div slot='help-text'>Choose the option that applies "
+ "to you</div><x-r>Yes</x-r><x-r>No</x-r></x-rg>",
+ ["Choose the option that applies to you"],
+ 2,
+ id="help-text-slot",
+ ),
+ pytest.param(
+ "<x-rg label='Are you legally authorized to work here?'><div slot='error'>This field is required.</div>"
+ "<x-r>Yes</x-r><x-r>No</x-r></x-rg>"
+ "<x-rg label='Will you require visa sponsorship?'><div slot='error'>This field is required.</div>"
+ "<x-r>Yes</x-r><x-r>No</x-r></x-rg>",
+ ["This field is required."],
+ 2,
+ id="error-slot",
+ ),
+ pytest.param(
+ "<x-stack><h4>Color</h4>"
+ + _swatch("Red")
+ + _swatch("Blue")
+ + "<h4>Size</h4>"
+ + _swatch("Small")
+ + _swatch("Medium")
+ + "</x-stack>",
+ ["Color", "Size"],
+ 1,
+ id="default-slot-headings",
+ ),
+ pytest.param(
+ "<label>Which plan do you want?</label><x-stack><div role='alert'>Please select an option to continue."
+ "</div>" + _yes_no_labelled("plan", "Basic", "Pro") + "</x-stack>",
+ ["Please select an option", "Which plan do you want?"],
+ 1,
+ id="default-slot-alert",
+ ),
+ pytest.param(
+ "<x-rg><div slot='label' role='alert'>This field is required.</div><x-r>Yes</x-r><x-r>No</x-r></x-rg>",
+ ["This field is required."],
+ 1,
+ id="alert-in-label-slot",
+ ),
+ pytest.param(
+ "<x-rg><span slot='label'>Yes / No</span><x-r>Yes</x-r><x-r>No</x-r></x-rg>",
+ ["Yes / No"],
+ 1,
+ id="captions-only-label-slot",
+ ),
+ pytest.param(
+ "<x-rg><span slot='label'>Contact preferences</span><x-r>Yes</x-r><x-r>No</x-r>"
+ "<label><input type=checkbox name=c>Email me</label></x-rg>",
+ ["Contact preferences"],
+ 1,
+ id="label-slot-over-another-choice",
+ ),
+ ],
+)
+async def test_observe_only_a_label_slot_names_a_group_components_radios(
+ body: str, never: list[str], markers: int
+) -> None:
+ html = f"<!doctype html><html><body>{_SLOT_API_COMPONENTS_JS}<form>{body}</form></body></html>"
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, markers, never)
+
+
+@_skip_no_browser
+async def test_observe_a_label_slot_names_its_radios_past_an_error_slotted_first() -> None:
+ html = (
+ f"<!doctype html><html><body>{_SLOT_API_COMPONENTS_JS}<form>"
+ '<x-rg><div slot="error">This field is required.</div>'
+ '<span slot="label">Are you legally authorized?</span><x-r>Yes</x-r><x-r>No</x-r></x-rg>'
+ "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ radios = _radio_records(data)
+ assert radios[0].get("group") == "Are you legally authorized?", radios
+ assert not any("This field is required." in json.dumps(e) for e in radios), radios
+
+
+def _aria_radio(caption: str) -> str:
+ return f'<div role="radio" aria-checked="false" tabindex="0">{caption}</div>'
+
+
+@_skip_no_browser
+ ("body", "section"),
+ [
+ pytest.param(
+ "<div role='group' aria-label='Driving history'><div><div><div>"
+ "<div><p>Do you have a license?</p><div><div>"
+ + _aria_radio("Yes")
+ + "</div><div>"
+ + _aria_radio("No")
+ + "</div></div></div>"
+ "<div><p>Any accidents in 5 years?</p><div><div>"
+ + _aria_radio("Yes")
+ + "</div><div>"
+ + _aria_radio("No")
+ + "</div></div></div></div></div></div></div>",
+ "Driving history",
+ id="role-group-over-two-aria-groups",
+ ),
+ pytest.param(
+ "<fieldset><legend>Relocation and travel</legend><div><div><div>"
+ f"<div><p>Relocate?</p><div>{_yes_no_radios('qa')}</div></div>"
+ f"<div><p>Travel?</p><div>{_yes_no_radios('qb')}</div></div>"
+ "</div></div></div></fieldset>",
+ "Relocation and travel",
+ id="fieldset-over-two-named-groups",
+ ),
+ pytest.param(
+ "<div role='radiogroup' aria-label='Survey'><div><p>Q1 Do you drive?</p>"
+ + _yes_no_radios("a")
+ + "</div><div><p>Q2 Do you smoke?</p>"
+ + _yes_no_radios("b")
+ + "</div></div>",
+ "Survey",
+ id="radiogroup-over-two-named-groups",
+ ),
+ ],
+)
+async def test_observe_a_section_name_over_several_groups_is_never_their_question(body: str, section: str) -> None:
+ async with _content_page(f"<!doctype html><html><body><form>{body}</form></body></html>") as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 2, [section])
+
+
+@_skip_no_browser
+async def test_observe_a_section_name_over_several_checkbox_groups_is_never_their_question() -> None:
+ def box(name: str, caption: str) -> str:
+ return f'<div><label><input type="checkbox" name="{name}">{caption}</label></div>'
+
+ html = (
+ "<!doctype html><html><body><form><fieldset><legend>Preferences</legend><div><div><div>"
+ f"<div><p>Which newsletters?</p><div>{box('n1', 'Weekly digest')}{box('n2', 'Product news')}</div></div>"
+ f"<div><p>Which channels?</p><div>{box('c1', 'Email')}{box('c2', 'SMS')}</div></div>"
+ "</div></div></div></fieldset></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ checkboxes = [e for e in data["elements"] if e.get("type") == "checkbox"]
+ assert len(checkboxes) == 4, checkboxes
+ assert not any("Preferences" in (e.get("group") or "") for e in checkboxes), checkboxes
+
+
+@_skip_no_browser
[email protected]("kind", ["radio", "checkbox"])
+async def test_observe_a_section_holding_several_questions_gives_none_of_them_to_one_group(kind: str) -> None:
+ # Each option sits in its own list item, so the first container past them holds both questions.
+ questions = {"a": "Are you over 18?", "b": "Do you have a driving licence?"}
+
+ def row(k: str) -> str:
+ items = "".join(
+ f'<li><label><input type="{kind}" name="{k}" value="{k}-{v}">{v}</label></li>' for v in ("Yes", "No")
+ )
+ return f'<div class="row"><p>{questions[k]}</p><ul>{items}</ul></div>'
+
+ html = f"<!doctype html><html><body><form><fieldset>{row('a')}{row('b')}</fieldset></form></body></html>"
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ boxes = [e for e in data["elements"] if e.get("type") == kind]
+ assert len(boxes) == 4, boxes
+ for e in boxes:
+ foreign = questions["b" if str(e.get("value")).startswith("a-") else "a"]
+ assert foreign not in json.dumps(e), e
+ if kind == "radio":
+ _assert_marked_not_guessed(data, r.content, 2, list(questions.values()))
+
+
+@_skip_no_browser
+async def test_observe_a_frames_radio_group_keeps_its_marker_beside_the_pages_own(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Each realm numbers its groups from 1, so the page's first group and the frame's share a number.
+ monkeypatch.setattr(settings, "TASK_V3_FRAME_PERCEPTION", True)
+ frame = "<form><div><p>Do you smoke?</p><div>{}</div></div></form>".format(_yes_no_radios("f").replace('"', "'"))
+ html = (
+ f"<!doctype html><html><body><form><div><p>Do you drive?</p><div>{_yes_no_radios('m')}</div></div></form>"
+ f'<iframe srcdoc="{frame}" width="400" height="200"></iframe></body></html>'
+ )
+ async with _live_page(html) as page:
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ radio_lines = [line for line in r.content.splitlines() if "/radio" in line]
+ assert len(radio_lines) == 4, r.content
+ assert [("(no question found)" in line) for line in radio_lines] == [True, False, True, False], r.content
+
+
+@_skip_no_browser
+async def test_observe_a_radio_groups_description_never_puts_its_marker_mid_group() -> None:
+ # The description is a validation error printed on the first option: a marker on the second
+ # would read as the start of another group.
+ radios = "".join(
+ f'<label><input type="radio" name="a" value="{v}" aria-describedby="err">{v}</label>' for v in ("Yes", "No")
+ )
+ html = (
+ f"<!doctype html><html><body><form><div><span>Are you over 18?</span>{radios}"
+ "<div id='err' style='color:red'>This field is required</div></div>"
+ "<label>Email <input type=text name=e></label></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ radio_lines = [line for line in r.content.splitlines() if "/radio" in line]
+ assert len(radio_lines) == 2, r.content
+ assert "(no question found)" not in radio_lines[1], r.content
+
+
+@_skip_no_browser
+async def test_observe_a_short_hint_never_silences_an_undeclared_radio_groups_marker() -> None:
+ # A group with no question anywhere keeps its marker even when a member has a description: a hint
+ # is not a question.
+ html = (
+ "<!doctype html><html><body><form><ul>"
+ '<li class="application-question"><div class="application-field"><ul>'
+ '<li><label><input type="radio" name="q1" value="q1-yes" aria-describedby="hint">'
+ "<span>I consent to receive communications</span></label></li>"
+ '<li><label><input type="radio" name="q1" value="q1-no">'
+ "<span>I do not consent to receive communications</span></label></li>"
+ '</ul></div><p id="hint">See policy</p></li>'
+ "</ul></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ assert not any(e.get("group") for e in _radio_records(data)), _radio_records(data)
+ assert r.content.count("group=(no question found)") == 1, r.content
+
+
+_TWO_CHECKBOXES = (
+ "<label><input type=checkbox name=c1>Email me</label><label><input type=checkbox name=c2>Text me</label>"
+)
+
+
+@_skip_no_browser
+async def test_observe_a_checkbox_group_never_takes_a_radio_groups_question() -> None:
+ html = (
+ "<!doctype html><html><body><form><div class='form-group'><p>Are you over 18?</p>"
+ f"{_yes_no_radios('a')}<div class='opts'>{_TWO_CHECKBOXES}</div></div>"
+ "<div class='form-group'><label for=e>Email</label><input id=e></div></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ checkbox_lines = [line for line in r.content.splitlines() if "/checkbox" in line]
+ assert len(checkbox_lines) == 2, r.content
+ for line in checkbox_lines:
+ assert "Are you over 18?" not in line, r.content
+
+
+def _choice_form(body: str) -> str:
+ return (
+ f"<!doctype html><html><body><form>{body}"
+ "<div class='form-group'><label for=e>Email</label><input id=e></div></form></body></html>"
+ )
+
+
+def _li_radios(name: str) -> str:
+ return (
+ "<ul>"
+ + "".join(
+ f"<li><label><input type=radio name={name} value={name}-{v.lower()}>{v}</label></li>" for v in ("Yes", "No")
+ )
+ + "</ul>"
+ )
+
+
+def _day_checkboxes() -> str:
+ return (
+ "<label><input type=checkbox name=d1 value=mon>Monday</label>"
+ "<label><input type=checkbox name=d2 value=tue>Tuesday</label>"
+ )
+
+
+def _plan_cards(name: str, shown: bool = False) -> str:
+ def card(plan: str) -> str:
+ named = (
+ f"aria-labelledby={name}-{plan}><span id={name}-{plan}>{plan} plan</span>"
+ if shown
+ else f"aria-label='{plan} plan'>"
+ )
+ return (
+ f"<div role=group {named}<label><input type=radio name={name} value={name}-{plan.lower()}>"
+ f"Select {plan}</label></div>"
+ )
+
+ return "".join(card(plan) for plan in ("Pro", "Basic"))
+
+
+@_skip_no_browser
+ ("body", "expected", "wrong"),
+ [
+ pytest.param(
+ "<fieldset><legend>Work authorization</legend><p>Are you legally authorized to work here?</p>"
+ f"{_yes_no_radios('a')}</fieldset>",
+ {"a-yes": "Are you legally authorized to work here?"},
+ (),
+ id="topic-legend-over-question",
+ ),
+ pytest.param(
+ "<fieldset><legend>Privacy</legend><div class='form-group'><p>Do you consent to us storing your data?</p>"
+ f"{_yes_no_radios('a')}</div><div class='form-group'>"
+ "<label><input type=checkbox name=z value=alerts>Send me job alerts</label></div></fieldset>",
+ {"a-yes": "Do you consent to us storing your data?"},
+ ("Privacy",),
+ id="section-legend",
+ ),
+ pytest.param(
+ "<section role=group aria-labelledby=st><h2 id=st>Step 3 of 8</h2><div class='question'>"
+ f"<p>Do you have a driving license?</p>{_yes_no_radios('a')}</div><button type=button>Next</button></section>",
+ {"a-yes": "Do you have a driving license?"},
+ ("Step 3 of 8",),
+ id="step-heading",
+ ),
+ pytest.param(
+ "<h2 id=h>Additional questions</h2><div class='form-group'><p>Will you require sponsorship?</p>"
+ f"<div role=radiogroup aria-labelledby=h>{_yes_no_radios('a')}</div></div>",
+ {"a-yes": "Will you require sponsorship?"},
+ ("Additional questions",),
+ id="section-heading",
+ ),
+ pytest.param(
+ f"<fieldset><legend>Yes / No</legend><div class='form-group'><p>Do you smoke?</p>{_yes_no_radios('a')}</div></fieldset>",
+ {"a-yes": "Do you smoke?"},
+ ("Yes / No",),
+ id="captions-legend",
+ ),
+ pytest.param(
+ "<div class='form-group'><p>Are you over 18?</p>"
+ f"<div role=radiogroup aria-label='Yes or No'>{_yes_no_radios('a')}</div></div>",
+ {"a-yes": "Are you over 18?"},
+ ("Yes or No",),
+ id="captions-aria-label",
+ ),
+ pytest.param(
+ "<fieldset><legend>Preferences</legend><div class='form-group'><p>Which days can you work?</p>"
+ f"{_day_checkboxes()}</div><div class='form-group'><p>Are you over 18?</p>{_yes_no_radios('a')}</div></fieldset>",
+ {"mon": "Which days can you work?", "a-yes": "Are you over 18?"},
+ ("Preferences",),
+ id="radio-and-checkbox-groups-in-a-section",
+ ),
+ pytest.param(
+ "<fieldset><legend>Terms</legend><p>By checking this box you confirm the information is accurate.</p>"
+ "<label><input type=checkbox name=t value=agree>I agree</label></fieldset>",
+ {"agree": "By checking this box you confirm the information is accurate."},
+ (),
+ id="consent-statement",
+ ),
+ pytest.param(
+ f"<div class='form-group'><p>Choose a plan</p>{_plan_cards('p', shown=True)}</div>",
+ {"p-pro": "Pro plan", "p-basic": "Basic plan"},
+ (),
+ id="per-option-cards",
+ ),
+ ],
+)
+async def test_observe_a_choice_groups_own_text_outranks_an_outer_declared_name(
+ body: str, expected: dict[str, str], wrong: tuple[str, ...]
+) -> None:
+ async with _content_page(_choice_form(body)) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ choices = {str(e.get("value")): e for e in data["elements"] if e.get("type") in ("radio", "checkbox")}
+ for value, question in expected.items():
+ assert question in (choices[value].get("group") or ""), choices
+ for e in choices.values():
+ for text in wrong:
+ assert text not in (e.get("group") or ""), choices
+ assert "(no question found)" not in r.content, r.content
+
+
+@_skip_no_browser
+ ("body", "never"),
+ [
+ pytest.param(
+ f"<div role=group aria-label='Preferences'><div>{_yes_no_radios('a')}</div><div>{_day_checkboxes()}</div></div>",
+ ["Preferences"],
+ id="section-holding-a-checkbox-group",
+ ),
+ pytest.param(f"<div class='opts'>{_plan_cards('p')}</div>", ["plan"], id="per-option-wrapper-in-a-box"),
+ pytest.param(
+ f"<div class='opts'>{_plan_cards('p')}<input aria-label='Notes'></div>",
+ ["plan"],
+ id="per-option-wrapper-by-name",
+ ),
+ pytest.param(
+ "<div class='form-group'><p>Are you over 18?</p>"
+ "<div role=group aria-label=Yes><label><input type=radio name=a value=a-yes>Yes</label></div>"
+ "<div role=group aria-label=No><label><input type=radio name=a value=a-no>No</label></div></div>",
+ [],
+ id="per-option-answer-labels",
+ ),
+ pytest.param(
+ "<div class='opts'><div role=group aria-label=Yes><input type=radio value=a-yes></div>"
+ "<div role=group aria-label=No><input type=radio value=a-no></div></div>",
+ ["Yes"],
+ id="unnamed-per-option-wrapper",
+ ),
+ pytest.param(
+ f"<div><div role=radiogroup aria-label='Yes / No'>{_yes_no_radios('a')}</div></div>",
+ ["Yes / No"],
+ id="captions-only-name",
+ ),
+ pytest.param(
+ f"<fieldset><legend>Preferences</legend><div class='form-group'><p>Can we contact you?</p>{_li_radios('c')}"
+ "</div><x-toggle id=t></x-toggle></fieldset><script>document.getElementById('t').attachShadow({mode:'open'})"
+ ".innerHTML='<label><input type=checkbox value=alerts>Email me job alerts</label>';</script>",
+ ["Preferences"],
+ id="shadow-checkbox-in-the-section",
+ ),
+ pytest.param(
+ f"<fieldset><legend>Contact details</legend><div class='form-group'><p>Can we call you?</p>{_li_radios('c')}"
+ "</div><x-input id=t></x-input></fieldset><script>document.getElementById('t').attachShadow({mode:'open'})"
+ ".innerHTML='<label>Phone number <input type=text></label>';</script>",
+ ["Contact details"],
+ id="shadow-text-field-in-the-section",
+ ),
+ ],
+)
+async def test_observe_a_declared_name_that_is_not_this_whole_groups_gets_the_marker(
+ body: str, never: list[str]
+) -> None:
+ async with _content_page(_choice_form(body)) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 1, never)
+ for e in data["elements"]:
+ if e.get("type") == "checkbox":
+ assert not any(text in (e.get("group") or "") for text in never), e
+
+
+def _per_option_named_radios(name: str) -> str:
+ return "".join(
+ f"<div role=group aria-label={v}><label><input type=radio name={name} value={name}-{v.lower()}>{v}</label></div>"
+ for v in ("Yes", "No")
+ )
+
+
+@_skip_no_browser
+ ("body", "question"),
+ [
+ pytest.param(
+ f"<fieldset><legend>Are you over 18?</legend>{_per_option_named_radios('a')}</fieldset>",
+ "Are you over 18?",
+ id="legend-above-per-option-names",
+ ),
+ pytest.param(
+ f"<fieldset><legend>Preferences</legend><div>{_per_option_named_radios('a')}</div>"
+ f"<div>{_per_option_named_radios('b')}</div></fieldset>",
+ None,
+ id="section-above-per-option-names",
+ ),
+ ],
+)
+async def test_observe_a_per_option_name_defers_to_the_named_group_above_it(body: str, question: str | None) -> None:
+ async with _content_page(_choice_form(body)) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ if question is None:
+ _assert_marked_not_guessed(data, r.content, 2, ["Preferences"])
+ return
+ radios = {str(e.get("value")): e for e in _radio_records(data)}
+ assert question in (radios["a-yes"].get("group") or ""), radios
+ assert "(no question found)" not in r.content, r.content
+
+
+def _aria_yes_no(k: str) -> str:
+ return (
+ f'<div id="{k}-yes" role="radio" aria-checked="false" tabindex="0">Yes</div>'
+ f'<div id="{k}-no" role="radio" aria-checked="false" tabindex="-1">No</div>'
+ )
+
+
+@_skip_no_browser
+ ("body", "question", "markers"),
+ [
+ pytest.param(
+ '<div class="q"><p id="q-label">Are you over 18?</p><div role="radiogroup" aria-labelledby="q-label">'
+ f'{_aria_yes_no("qa")}</div></div><div class="q"><p id="q-label">Have you ever been convicted of a felony?</p>'
+ f'<div role="radiogroup" aria-labelledby="q-label">{_aria_yes_no("qb")}</div></div>',
+ "Are you over 18?",
+ 2,
+ id="templated-question-reusing-its-id",
+ ),
+ pytest.param(
+ f"<fieldset><legend>Eligibility</legend><div class='form-group'>{_aria_yes_no('qa')}{_aria_yes_no('qb')}"
+ "</div></fieldset>",
+ "Eligibility",
+ 1,
+ id="section-legend-over-flat-aria-radios",
+ ),
+ ],
+)
+async def test_observe_a_declared_name_that_may_be_another_questions_gets_the_marker(
+ body: str, question: str, markers: int
+) -> None:
+ async with _content_page(_choice_form(body)) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, markers, [question])
+
+
+@_skip_no_browser
+async def test_observe_a_legend_never_names_a_radio_group_it_holds_only_part_of() -> None:
+ body = (
+ f"<fieldset><legend>Contact preference</legend><div class=opts>{_li_radios('x')}</div></fieldset>"
+ "<p>Other</p><label><input type=radio name=x value=x-none>Prefer not to say</label>"
+ )
+ async with _content_page(_choice_form(body)) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ assert "Contact preference" not in json.dumps(_radio_records(data)), _radio_records(data)
+ assert "group=(no question found)" in r.content, r.content
+
+
+@_skip_no_browser
+ ("body", "question"),
+ [
+ pytest.param(
+ "<div class='form-group'><label for=r1>How would you rate your interview experience?</label><div>"
+ + "".join(f"<input type=radio id=r{i} name=r value={i}><label for=r{i}>{i}</label>" for i in range(1, 6))
+ + "</div></div>",
+ "How would you rate your interview experience? 12345",
+ id="rating",
+ ),
+ pytest.param(
+ "<div class='form-group'><label for=n0>How likely are you to recommend us?</label><div>"
+ + "".join(f"<input type=radio id=n{i} name=n value={i}><label for=n{i}>{i}</label>" for i in range(11))
+ + "</div></div>",
+ "How likely are you to recommend us? 012345678910",
+ id="nps",
+ ),
+ pytest.param(
+ "<div class='form-group'><label>Preferred contact method <input type=radio name=c value=email> Email "
+ "<input type=radio name=c value=phone> Phone</label></div>",
+ "Preferred contact method Email Phone",
+ id="label-wrapping-question-and-options",
+ ),
+ pytest.param(
+ "<div class='form-group'><label>Do you agree? <input type=radio name=d value=yes> Yes</label>"
+ "<label><input type=radio name=d value=no> No</label></div>",
+ "Do you agree? Yes No",
+ id="label-wrapping-question-and-first-option",
+ ),
+ pytest.param(
+ "<div class='form-group'><label>I <input type=radio name=t value=agree> agree or "
+ "<input type=radio name=t value=disagree> disagree with the terms</label></div>",
+ "I agree or disagree with the terms",
+ id="sentence-label-wrapping-both-options",
+ ),
+ ],
+)
+async def test_observe_a_question_label_for_the_first_option_is_not_its_caption(body: str, question: str) -> None:
+ # A question labelling the first option precedes every option, so the scale keeps its question line.
+ async with _content_page(_choice_form(body)) as page:
+ data = await _observe_data(page)
+ groups = [e.get("group") for e in _radio_records(data) if e.get("group")]
+ assert groups == [question], _radio_records(data)
+
+
+@_skip_no_browser
+async def test_observe_a_later_members_question_drops_an_earlier_members_marker() -> None:
+ body = (
+ "<ul><li><label><input type=radio name=s value=standard>Standard</label></li>"
+ "<li><label><input type=radio name=s value=express>Express</label><span>Extra fee applies</span></li></ul>"
+ )
+ async with _content_page(_choice_form(body)) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ radios = {str(e.get("value")): e for e in _radio_records(data)}
+ assert "Extra fee applies" in (radios["express"].get("group") or ""), radios
+ assert "(no question found)" not in r.content, r.content
+
+
+@_skip_no_browser
+async def test_observe_a_fieldset_legend_names_its_radiogroup_through_unnamed_option_wrappers() -> None:
+ # A form library's layout: fieldset > legend, an unnamed radiogroup, and a role=group per option
+ # with its own layout wrappers, so the legend sits deeper than any fixed ancestor walk reaches.
+ def option(k: str, v: str, caption: str) -> str:
+ return (
+ f'<div role="group"><div><div><div><label><input type="radio" name="{k}" value="{k}-{v}">{caption}'
+ "</label></div></div></div></div>"
+ )
+
+ def group(k: str, legend: str, a: str, b: str) -> str:
+ return (
+ f'<fieldset><legend>{legend}</legend><div role="radiogroup">'
+ f"{option(k, 'a', a)}{option(k, 'b', b)}</div></fieldset>"
+ )
+
+ html = (
+ "<!doctype html><html><body><form>"
+ + group("plan", "Subscription Plan", "Basic", "Pro")
+ + group("notify", "Notification Preferences", "Email", "SMS")
+ + "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_each_question_reaches_only_its_own_radios(
+ data,
+ r.content,
+ {"Subscription Plan": {"plan-a", "plan-b"}, "Notification Preferences": {"notify-a", "notify-b"}},
+ key=lambda e: str(e.get("value")),
+ )
+ assert not any(e.get("group_missing") for e in _radio_records(data)), _radio_records(data)
+
+
+@_skip_no_browser
+async def test_observe_a_legend_names_proxy_radios_whose_option_wrappers_hold_only_captions() -> None:
+ # fieldset > legend > unnamed radiogroup > one role=group wrapper per option, each holding a
+ # role=radio button and the hidden native radio carrying its form value.
+ def option(k: str, v: str, caption: str) -> str:
+ return (
+ f'<div role="group"><button type="button" role="radio" aria-checked="false" id="{k}-{v}">{caption}'
+ f'</button><input type="radio" name="{k}" value="{v}" aria-hidden="true" tabindex="-1" '
+ 'style="position:absolute;pointer-events:none;opacity:0;margin:0;width:16px;height:16px"></div>'
+ )
+
+ def group(k: str, legend: str, a: str, b: str) -> str:
+ return (
+ f'<fieldset><legend>{legend}</legend><div role="radiogroup">'
+ f"{option(k, 'a', a)}{option(k, 'b', b)}</div></fieldset>"
+ )
+
+ html = (
+ "<!doctype html><html><body><form>"
+ + group("plan", "Subscription Plan", "Basic", "Pro")
+ + group("notify", "Notification Preferences", "Email", "SMS")
+ + "</form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ radios = _radio_records(data)
+ groups = {e["selector"]: e.get("group") or "" for e in radios}
+ assert "Subscription Plan" in groups["#plan-a"] and "Notification Preferences" in groups["#notify-a"], groups
+ for sel, text in groups.items():
+ if sel.startswith("#plan"):
+ assert "Notification Preferences" not in text, groups
+ if sel.startswith("#notify"):
+ assert "Subscription Plan" not in text, groups
+ assert text not in ("Basic", "Pro", "Email", "SMS"), groups
+ assert "(no question found)" not in r.content, r.content
+
+
+@_skip_no_browser
+async def test_observe_an_options_only_field_container_gets_the_marker_not_its_captions() -> None:
+ # li.question > div.label + div.field > ul > li > label > input: the field container's text is only its
+ # options' captions, which name no question. A group either shows its own question or gets one marker.
+ def question(label: str, items: str) -> str:
+ return (
+ f'<li class="application-question"><div class="application-label">{label}</div>'
+ f'<div class="application-field"><ul>{items}</ul></div></li>'
+ )
+
+ def radio(name: str, value: str, caption: str) -> str:
+ return f'<li><label><input type="radio" name="{name}" value="{value}"><span>{caption}</span></label></li>'
+
+ languages = [f"Language {i} (L{i:02d})" for i in range(40)]
+ html = (
+ "<!doctype html><html><body><form><ul>"
+ + question(
+ "Are you legally authorized to work here?", radio("q1", "q1-yes", "Yes") + radio("q1", "q1-no", "No")
+ )
+ + question("Will you require sponsorship?", radio("q2", "q2-yes", "Yes") + radio("q2", "q2-no", "No"))
+ + question(
+ "May we record the interview?",
+ radio("q3", "q3-yes", "Yes, I consent") + radio("q3", "q3-no", "No, I do not consent"),
+ )
+ + question(
+ "Language skills",
+ "".join(
+ f'<li><label><input type="checkbox" name="lang{i}"><span>{t}</span></label></li>'
+ for i, t in enumerate(languages)
+ ),
+ )
+ + "</ul></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ questions = {
+ "q1": "Are you legally authorized to work here?",
+ "q2": "Will you require sponsorship?",
+ "q3": "May we record the interview?",
+ }
+ shown = set()
+ for e in _radio_records(data):
+ own = questions[str(e.get("value")).split("-")[0]]
+ assert e.get("group") in (None, own), e
+ if e.get("group"):
+ shown.add(own)
+ assert r.content.count("group=(no question found)") == len(questions) - len(shown), r.content
+ checkboxes = [e for e in data["elements"] if e.get("type") == "checkbox"]
+ assert len(checkboxes) == 40, checkboxes
+ assert all(e.get("group") in (None, "Language skills") for e in checkboxes), checkboxes
+
+
+@_skip_no_browser
[email protected]("native", [False, True], ids=["aria-radios", "native-radios-named-by-column"])
+async def test_observe_a_transposed_matrix_header_cell_is_never_the_question(native: bool) -> None:
+ # Each row's header is an answer; the questions are the column headers.
+ def cell(o: str, q: str) -> str:
+ return f'<input type="radio" name="{q}" value="{q}-{o}" aria-label="{o}">' if native else _aria_radio(o)
+
+ rows = "".join(
+ f"<tr><th>{o}</th><td>{cell(o, 'q1')}</td><td>{cell(o, 'q2')}</td></tr>" for o in ("Agree", "Disagree")
+ )
+ html = (
+ "<!doctype html><html><body><table><tr><th></th><th>Q1 Price</th><th>Q2 Quality</th></tr>"
+ f"{rows}</table></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ _assert_marked_not_guessed(data, r.content, 2, [])
+
+
+@_skip_no_browser
[email protected]("layout", ["over-the-page-budget", "same-legend-twice"])
+async def test_observe_a_declared_question_held_back_from_printing_is_not_marked_missing(layout: str) -> None:
+ # A legend the page budget or the same-text dedupe keeps off the line is still a question found.
+ if layout == "over-the-page-budget":
+ legend = "Please tell us about your experience with the following statement which is long enough " * 2
+ body = "".join(
+ f"<fieldset><legend>{k}. {legend}</legend>{_yes_no_radios(f'q{k}')}</fieldset>" for k in range(30)
+ )
+ else:
+ body = "".join(
+ f"<fieldset><legend>Relationship to you</legend>{_yes_no_radios(f'rel{k}')}</fieldset>" for k in range(2)
+ )
+ async with _content_page(f"<!doctype html><html><body><form>{body}</form></body></html>") as page:
+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})
+ assert "(no question found)" not in r.content, r.content
+
+
+@_skip_no_browser
+async def test_observe_a_radiogroup_laid_out_in_rows_is_one_group() -> None:
+ # Options sit in rows of two; the radiogroup, not each row, is the group.
+ def row(a: str, b: str) -> str:
+ return (
+ f'<div><div role="radio" id="{a}" aria-checked="false" tabindex="0">{a}</div>'
+ f'<div role="radio" id="{b}" aria-checked="false" tabindex="-1">{b}</div></div>'
+ )
+
+ html = (
+ '<!doctype html><html><body><form><div role="radiogroup" aria-label="Preferred shift">'
+ + row("Morning", "Afternoon")
+ + row("Evening", "Overnight")
+ + "</div></form></body></html>"
+ )
+ async with _content_page(html) as page:
+ data = await _observe_data(page)
+ radios = _radio_records(data)
+ assert [e.get("group") for e in radios] == ["Preferred shift", None, None, None], radios
+ assert not any(e.get("group_missing") for e in radios), radios
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_observe_uncounts_a_marker_whose_element_threw_before_it_was_listed() -> None:
@@ -7454,6 +9141,240 @@ async def test_dom_a_radiogroup_category_reports_its_children_and_the_leaf_commi
assert await page.evaluate("() => window.__commits") == 1
+_LONG_MENU_OPTIONS = (
+ "Unrestricted right to work in this location, no sponsorship required now or in future",
+ "Visa currently required to work in this location",
+ "Visa will be required in the future to work here",
+)
+# Two answers that read alike until past character 60.
+_SHARED_PREFIX_MENU_OPTIONS = (
+ "I am authorized to work in this location for any employer and do not need sponsorship",
+ "I am authorized to work in this location for any employer but will need sponsorship later",
+ "No",
+)
+
+# `__ROWS__` is replaced by a JS function building one row for (text, onPick).
+_LONG_OPTION_MENU_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <button id="trigger" style="position:absolute;top:40px;left:40px;width:420px;height:28px">Select...</button>
+ <script>
+ window.__picked = null;
+ const OPTIONS = __OPTIONS__;
+ const makeRow = __ROWS__;
+ document.getElementById('trigger').addEventListener('click', () => {
+ const ex = document.getElementById('list');
+ if (ex) { ex.remove(); return; }
+ const list = document.createElement('div');
+ list.id = 'list';
+ list.setAttribute('role', 'listbox');
+ list.setAttribute('style', 'position:absolute;top:74px;left:40px;width:760px;background:#fff;'
+ + 'border:1px solid #ccc;white-space:nowrap;font:13px sans-serif');
+ for (const txt of OPTIONS) {
+ list.appendChild(makeRow(txt, () => {
+ window.__picked = txt;
+ document.getElementById('trigger').textContent = txt;
+ list.remove();
+ }));
+ }
+ document.body.appendChild(list);
+ });
+ </script>
+</body></html>
+"""
+
+_PLAIN_OPTION_ROW_JS = """(txt, onPick) => {
+ const row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('style', 'height:26px;padding:2px 6px;cursor:pointer');
+ row.textContent = txt;
+ row.addEventListener('click', onPick);
+ return row;
+}"""
+
+# A custom option element with no role, its caption in a child, and an empty role=option child
+# that renders no box.
+_CUSTOM_OPTION_ROW_JS = """(txt, onPick) => {
+ const row = document.createElement('x-option');
+ row.setAttribute('style', 'display:block;height:26px;padding:2px 6px;cursor:pointer');
+ const cap = document.createElement('span');
+ cap.textContent = txt;
+ const aria = document.createElement('div');
+ aria.setAttribute('role', 'option');
+ row.appendChild(cap);
+ row.appendChild(aria);
+ row.addEventListener('click', onPick);
+ return row;
+}"""
+
+
+@_skip_no_browser
+ ("row_js", "options"),
+ [
+ pytest.param(_PLAIN_OPTION_ROW_JS, _LONG_MENU_OPTIONS, id="role-option-rows"),
+ pytest.param(_CUSTOM_OPTION_ROW_JS, _LONG_MENU_OPTIONS, id="custom-option-element"),
+ pytest.param(_PLAIN_OPTION_ROW_JS, _SHARED_PREFIX_MENU_OPTIONS, id="answers-alike-until-past-60-chars"),
+ ],
+)
+async def test_dom_a_menu_lists_an_option_whose_caption_is_long_and_it_commits(
+ row_js: str, options: tuple[str, ...]
+) -> None:
+ # A row over the enumerator's text-length ceiling was dropped and the rest renumbered, so
+ # [data-tv3-menu="1"] pointed at the second option and the model committed the wrong answer.
+ html = _LONG_OPTION_MENU_FIXTURE_HTML.replace("__OPTIONS__", json.dumps(list(options))).replace("__ROWS__", row_js)
+ async with _content_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ click = _tool(tools, "click")
+ opened = await click.handler({"selector": "#trigger"})
+ assert opened.status == "ok", opened.content
+ assert "opened a menu of 3 options" in opened.content, opened.content
+ for text in options:
+ assert repr(text) in opened.content, f"{text!r} missing from the menu note:\n{opened.content}"
+ picked = await click.handler({"selector": '[data-tv3-menu="1"]'})
+ assert picked.status == "ok", picked.content
+ assert await page.evaluate("() => window.__picked") == options[0]
+
+
+# Rows whose text starts with '~' are rendered hidden, as a filtering widget hides what it filtered out.
+_DECLARED_COUNT_ROW_JS = """(txt, onPick) => {
+ const row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('style', 'height:26px;padding:2px 6px;cursor:pointer');
+ if (txt.startsWith('~')) row.style.display = 'none';
+ if (txt.startsWith('^')) {
+ const inner = document.createElement('span');
+ inner.setAttribute('role', 'option');
+ inner.textContent = txt.slice(1);
+ row.appendChild(inner);
+ } else {
+ row.textContent = txt.replace(/^[~#]/, '');
+ }
+ if (txt.startsWith('#')) row.setAttribute('aria-setsize', '50');
+ row.addEventListener('click', onPick);
+ return row;
+}"""
+
+
+@_skip_no_browser
+ ("options", "clause"),
+ [
+ pytest.param(
+ ["", "Alpha option", "Beta option"], "the list declares 3 options; 2 are listed", id="unreadable-row"
+ ),
+ pytest.param(
+ ["Alpha option", "Beta option", *[f"~Hidden {i}" for i in range(40)]], None, id="filtered-out-rows"
+ ),
+ pytest.param(["^Alpha option", "^Beta option", "^Gamma option"], None, id="nested-option-roles"),
+ pytest.param(
+ ["#Alpha option", "#Beta option"], "the list declares 50 options; 2 are listed", id="aria-setsize"
+ ),
+ ],
+)
+async def test_dom_a_menu_note_counts_only_the_options_the_listbox_declares_and_renders(
+ options: list[str], clause: str | None
+) -> None:
+ html = _LONG_OPTION_MENU_FIXTURE_HTML.replace("__OPTIONS__", json.dumps(options)).replace(
+ "__ROWS__", _DECLARED_COUNT_ROW_JS
+ )
+ async with _content_page(html) as page:
+ opened = await _tool(build_browser_tools(_fixed_page_provider(page)), "click").handler({"selector": "#trigger"})
+ assert "opened a menu of" in opened.content, opened.content
+ if clause:
+ assert clause in opened.content, opened.content
+ else:
+ assert "the list declares" not in opened.content, opened.content
+
+
+_MENU_ITEM_ROW_JS = """(txt, onPick) => {
+ const row = document.createElement('div');
+ row.setAttribute('role', 'menuitem');
+ row.setAttribute('style', 'display:block;height:26px;padding:2px 6px;cursor:pointer');
+ row.textContent = txt;
+ row.addEventListener('click', onPick);
+ return row;
+}"""
+
+
+@_skip_no_browser
+async def test_dom_a_menu_of_menuitems_lists_a_long_item_and_it_commits() -> None:
+ html = (
+ _LONG_OPTION_MENU_FIXTURE_HTML.replace("__OPTIONS__", json.dumps(list(_LONG_MENU_OPTIONS)))
+ .replace("__ROWS__", _MENU_ITEM_ROW_JS)
+ .replace("list.setAttribute('role', 'listbox');", "list.setAttribute('role', 'menu');")
+ )
+ async with _content_page(html) as page:
+ click = _tool(build_browser_tools(_fixed_page_provider(page)), "click")
+ opened = await click.handler({"selector": "#trigger"})
+ assert "opened a menu of 3 options" in opened.content, opened.content
+ picked = await click.handler({"selector": '[data-tv3-menu="1"]'})
+ assert picked.status == "ok", picked.content
+ assert await page.evaluate("() => window.__picked") == _LONG_MENU_OPTIONS[0]
+
+
+@_skip_no_browser
+async def test_dom_a_menu_note_counts_the_items_a_menu_declares() -> None:
+ html = (
+ _LONG_OPTION_MENU_FIXTURE_HTML.replace("__OPTIONS__", json.dumps(["", "Alpha option", "Beta option"]))
+ .replace("__ROWS__", _MENU_ITEM_ROW_JS)
+ .replace("list.setAttribute('role', 'listbox');", "list.setAttribute('role', 'menu');")
+ )
+ async with _content_page(html) as page:
+ opened = await _tool(build_browser_tools(_fixed_page_provider(page)), "click").handler({"selector": "#trigger"})
+ assert "the list declares 3 options; 2 are listed" in opened.content, opened.content
+
+
+# Typing reveals one real suggestion row beside a long tip paragraph that repeats the typed words.
+_SUGGESTION_WITH_TIP_HTML = """<!doctype html><html><body style="margin:0">
+<input id="role" type="text" aria-label="Job title"
+ style="position:absolute;top:20px;left:20px;width:600px;height:28px">
+<div id="list" style="position:absolute;top:52px;left:20px;width:600px;background:#fff;font:13px sans-serif"></div>
+<script>
+const f = document.getElementById('role'), list = document.getElementById('list');
+f.addEventListener('input', () => setTimeout(() => {
+ if (!f.value) { list.innerHTML = ''; return; }
+ list.innerHTML = '<div class="row" style="cursor:pointer;padding:3px">Software Engineer</div>'
+ + '<div class="hint" style="padding:3px;color:#666">Tip: titles such as Senior Software Engineer are grouped '
+ + 'under their base title; pick the closest base title and add seniority in the next step.</div>';
+ list.querySelector('.row').addEventListener('click', () => { f.value = 'Software Engineer'; window.__picked = 'row'; });
+ list.querySelector('.hint').addEventListener('click', () => { window.__picked = 'hint'; });
+}, 50));
+</script></body></html>"""
+
+
+@_skip_no_browser
+async def test_dom_type_picks_the_suggestion_row_not_a_long_tip_paragraph() -> None:
+ async with _content_page(_SUGGESTION_WITH_TIP_HTML) as page:
+ await _tool(build_browser_tools(_fixed_page_provider(page)), "type").handler(
+ {"selector": "#role", "text": "Senior Software Engineer"}
+ )
+ assert await page.evaluate("() => window.__picked || null") == "row"
+
+
+@_skip_no_browser
+async def test_dom_paragraphs_in_a_clickable_popover_are_not_a_menu() -> None:
+ # The popover's pointer cursor is inherited by its paragraphs; long rows need a declared option role.
+ para = "We updated our privacy policy to explain how application data is retained and how long we keep it."
+ html = (
+ '<!doctype html><html><body><button id="trigger" style="position:absolute;top:20px;left:20px">News</button>'
+ "<script>document.getElementById('trigger').addEventListener('click', () => {"
+ "const pop = document.createElement('div');"
+ "pop.setAttribute('style', 'position:absolute;top:60px;left:20px;width:700px;background:#fff;cursor:pointer');"
+ f"pop.innerHTML = '<p style=margin:4px>{para} First.</p><p style=margin:4px>{para} Second.</p>';"
+ "document.body.appendChild(pop);});</script></body></html>"
+ )
+ async with _content_page(html) as page:
+ opened = await _tool(build_browser_tools(_fixed_page_provider(page)), "click").handler({"selector": "#trigger"})
+ assert opened.status == "ok", opened.content
+ assert "opened a menu" not in opened.content, opened.content
+
+
_REVEAL_HIDDEN_MENU_FIXTURE_HTML = """
<!doctype html><html><body style="margin:0">
<div id="trigger" tabindex="0"
@@ -27573,7 +29494,12 @@ async def test_observe_stays_silent_about_hidden_chrome_when_it_can_still_see_th
assert r.data is not None and r.data["summary"]["hidden_dropped"] == 1
-_HIDDEN_DROP_BUCKETS = ("hidden_dropped_off_canvas", "hidden_dropped_visibility", "hidden_dropped_zero_rect")
+_HIDDEN_DROP_BUCKETS = (
+ "hidden_dropped_off_canvas",
+ "hidden_dropped_visibility",
+ "hidden_dropped_zero_rect",
+ "hidden_dropped_off_viewport",
+)
def _hidden_drop_split(summary: dict[str, Any]) -> dict[str, int]:
@@ -27637,6 +29563,7 @@ async def test_observe_splits_a_mixed_blind_page_by_gate_and_the_pooled_count_is
"hidden_dropped_off_canvas": 1,
"hidden_dropped_visibility": 2,
"hidden_dropped_zero_rect": 3,
+ "hidden_dropped_off_viewport": 0,
}, summary
assert summary["hidden_dropped"] == 6, summary
assert "note: the page has 6 control(s) that are present but not visible" in r.content, r.content
@@ -27673,9 +29600,11 @@ async def test_a_frames_hidden_drops_are_summed_into_the_page_split(monkeypatch:
"hidden_dropped_off_canvas": 1,
"hidden_dropped_visibility": 1,
"hidden_dropped_zero_rect": 3,
+ "hidden_dropped_off_viewport": 2,
}, summary
- assert summary["hidden_dropped"] == 5, summary
- # Counted in every arm and in every realm: this one is armed off, and each frame holds one.
+ assert summary["hidden_dropped"] == 7, summary
+ # Each realm holds one droppable unnamed off-viewport control; the frame's second one sits under a
+ # custom-element host and is exempt.
assert summary["off_viewport_unreachable_unnamed"] == 2, summary
assert summary["off_viewport_unnamed_host_exempt"] == 1, summary
@@ -30876,29 +32805,19 @@ _OFFVIEWPORT_UNNAMED_HTML = (
)
-async def _observe_offviewport_fixture(monkeypatch: pytest.MonkeyPatch, arm: RunArm) -> Any:
- # Driven by the run's pinned arm, not the env force, so the observe tool is shown to read the arm.
- monkeypatch.setattr(settings, "TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED", False)
- context = skyvern_context.SkyvernContext(
- run_arms={"TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED": ("wr_offviewport", arm)}
- )
- skyvern_context.set(context)
- try:
- async with _content_page(_OFFVIEWPORT_UNNAMED_HTML) as page:
- tools = build_browser_tools(_fixed_page_provider(page))
- r = await _tool(tools, "observe").handler({})
- finally:
- skyvern_context.reset()
+async def _observe_offviewport_fixture() -> Any:
+ # No SkyvernContext, no flag provider and no setting: the drop must happen with nothing turning it on.
+ async with _content_page(_OFFVIEWPORT_UNNAMED_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
assert r.status == "ok" and r.data is not None, r.content
return r
@_skip_no_browser
@pytest.mark.asyncio
-async def test_observe_drops_an_unnamed_control_no_scroll_can_bring_into_the_viewport(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- r = await _observe_offviewport_fixture(monkeypatch, arm="treatment")
+async def test_observe_drops_an_unnamed_control_no_scroll_can_bring_into_the_viewport() -> None:
+ r = await _observe_offviewport_fixture()
assert "button/submit ''" not in r.content, r.content
assert "button/reset ''" not in r.content, r.content
@@ -30916,62 +32835,36 @@ async def test_observe_drops_an_unnamed_control_no_scroll_can_bring_into_the_vie
assert r.data["summary"]["hidden_dropped"] == 3, r.data["summary"]
-async def _observe_records(page: Any, arm: RunArm) -> dict[str, Any]:
- from skyvern.forge.taskv3.tools import observe_js # noqa: PLC0415
-
- context = skyvern_context.SkyvernContext(
- run_arms={"TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED": ("wr_offviewport", arm)}
- )
- skyvern_context.set(context)
- try:
- return json.loads(await page.evaluate(observe_js()))
- finally:
- skyvern_context.reset()
-
-
@_skip_no_browser
@pytest.mark.asyncio
-async def test_the_drop_never_removes_a_control_whose_record_reports_state(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # The property, over whatever the page holds: a control the arm removes must not be one whose
+async def test_the_drop_never_removes_a_control_whose_record_reports_state() -> None:
+ # The property, over whatever the page holds: a control the drop removes must not be one whose
# record carries state. Asserting the class rather than the three forms a field list happens to
# enumerate -- that list is what drifted before (SKY-16501).
- monkeypatch.setattr(settings, "TASK_V3_OBSERVE_DROP_OFFVIEWPORT_UNNAMED", False)
+ from skyvern.forge.taskv3.tools import observe_js # noqa: PLC0415
+
async with _content_page(_OFFVIEWPORT_UNNAMED_HTML) as page:
- listed_off = await _observe_records(page, "control")
- listed_on = await _observe_records(page, "treatment")
+ listed = json.loads(await page.evaluate(observe_js()))
+ # A viewport this large puts every box inside it, so the second reading is the page with nothing
+ # dropped: the baseline the dropped set is taken against.
+ await page.evaluate(
+ "() => { for (const k of ['innerWidth', 'innerHeight'])"
+ " Object.defineProperty(window, k, { get: () => 1e7, configurable: true }); }"
+ )
+ baseline = json.loads(await page.evaluate(observe_js()))
def _identity(e: dict[str, Any]) -> str:
return str(e.get("selector") or f"i={e.get('i')}")
+ assert baseline["hiddenDroppedOffViewport"] == 0, baseline
state_keys = ("value", "checked", "selected", "selectedOptions")
- stateful = {_identity(e) for e in listed_off["elements"] if any(k in e for k in state_keys)}
- kept = {_identity(e) for e in listed_on["elements"]}
- dropped = {_identity(e) for e in listed_off["elements"]} - kept
+ stateful = {_identity(e) for e in baseline["elements"] if any(k in e for k in state_keys)}
+ dropped = {_identity(e) for e in baseline["elements"]} - {_identity(e) for e in listed["elements"]}
- assert dropped, listed_off["elements"]
+ assert len(dropped) == listed["hiddenDroppedOffViewport"] == 3, (dropped, listed["hiddenDroppedOffViewport"])
assert stateful & dropped == set(), sorted(stateful & dropped)
-@_skip_no_browser
[email protected]("arm", ["control", "unrandomized"])
-async def test_observe_lists_unnamed_offviewport_controls_outside_treatment(
- monkeypatch: pytest.MonkeyPatch, arm: RunArm
-) -> None:
- r = await _observe_offviewport_fixture(monkeypatch, arm=arm)
-
- assert "button/submit ''" in r.content, r.content
- assert "button/reset ''" in r.content, r.content
- assert "div/option ''" in r.content, r.content
- assert "(16 interactive elements)" in r.content, r.content
- assert r.data["summary"]["hidden_dropped_off_viewport"] == 0, r.data["summary"]
- # Exposure is measured in every arm, so treatment and control can be compared on the same set.
- assert r.data["summary"]["off_viewport_unreachable_unnamed"] == 3, r.data["summary"]
- assert r.data["summary"]["off_viewport_unnamed_host_exempt"] == 2, r.data["summary"]
-
-
# SKY-16917. The shapes below are what a canvas-backed rich-text editor presents: a surface <div> that
# holds no text, a hidden contenteditable that stops taking keys partway, and one whose text never
# appears in its own DOM. type(clear=false) reported "typed into" for all three, and the run finished