Skip to content

Automate browser based workflows with AI

Task V3: list hidden native form controls behind styled proxies and act on them without the actionability timeout (#8258)

pedrohsdbbc6c1beb28c1
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index dce3cfb3a..eb3ac4a4f 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -238,6 +238,160 @@ _SELECTOR_EXISTS_JS = (
}"""
)
+# The single discriminator observe and both act paths share: the element that visibly stands in for a
+# control the page renders at zero size. Nothing rendered means a collapsed section, a closed modal or
+# an inactive step. Kept as one fragment because three page.evaluate payloads cannot be kept in sync by
+# hand, and the whole point is that perception and action agree on what counts as a styled proxy.
+_VISIBLE_PROXY_JS = r"""(el) => {
+ let named = el.labels && el.labels[0];
+ if (!named) {
+ const lbId = el.getAttribute('aria-labelledby');
+ // An IDREF resolves inside the element's OWN tree, so a control in a shadow root must be looked
+ // up there -- document.getElementById cannot see it. Read through the prototype like every other
+ // root check here; an element whose root cannot hold ids simply has no name.
+ let root = null;
+ try { root = Node.prototype.getRootNode.call(el); } catch (e) { root = null; }
+ named = lbId && root && root.getElementById ? root.getElementById(String(lbId).trim().split(/\s+/)[0]) : null;
+ }
+ const r = named ? named.getBoundingClientRect() : null;
+ return r && r.width > 0 && r.height > 0 ? named : null;
+}"""
+
+# The executor's selector engine pierces open shadow roots, and observe now derives selectors from
+# every one of them, so a probe resolving a selector against the document alone silently declines to
+# act on a control it has just listed. Roots are visited in walk order, the order that engine matches
+# in, and gathered once per payload so a probe never walks the page twice.
+_ROOT_QUERY_JS = (
+ r"""(() => {
+ const _roots = """
+ + _SHADOW_ROOTS_JS
+ + r""";
+ const roots = _roots(document);
+ return {
+ find: (sel) => {
+ for (const root of roots) {
+ let f = null;
+ // A throw is the ROOT's, not the selector's -- it was already parsed by an earlier root.
+ try { f = root.querySelector(sel); } catch (e) { continue; }
+ if (f) return f;
+ }
+ return null;
+ },
+ all: (sel) => {
+ const out = [];
+ for (const root of roots) {
+ try { for (const e of root.querySelectorAll(sel)) out.push(e); } catch (e) { /* this root only */ }
+ }
+ return out;
+ },
+ };
+})()"""
+)
+
+
+# Design-system forms render a <select> at zero size behind a styled listbox proxy. Playwright's
+# actionability wait never resolves against it, so select_option probes visibility first and only
+# forces past actionability when the element exists but is genuinely hidden this way.
+_SELECT_VISIBILITY_JS = (
+ r"""(sel) => {
+ const _visibleProxy = """
+ + _VISIBLE_PROXY_JS
+ + r""";
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ try {
+ const el = _q.find(sel);
+ if (!el) return { exists: false, visible: false };
+ const r = el.getBoundingClientRect();
+ const cs = getComputedStyle(el);
+ // Forcing a value onto a select nothing stands in for carries a value the user never saw into
+ // whatever the run submits next.
+ return {
+ exists: true,
+ visible: r.width > 0 && r.height > 0 && cs.visibility !== 'hidden',
+ disabled: !!el.disabled,
+ proxied: !!_visibleProxy(el),
+ };
+ } catch (e) { return { exists: false, visible: false }; }
+}"""
+)
+
+# Read back after a forced select_option so a styled proxy that silently didn't sync from its
+# native control is caught rather than reported as a successful selection.
+_SELECT_READBACK_JS = (
+ r"""(sel) => {
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ try {
+ const el = _q.find(sel);
+ if (!el) return null;
+ const idx = el.selectedIndex;
+ const opt = idx >= 0 ? el.options[idx] : null;
+ // Playwright matches label= against option.label (whitespace-collapsed), not raw text.
+ return { value: el.value, selectedIndex: idx, selectedLabel: opt ? opt.label : null };
+ } catch (e) { return null; }
+}"""
+)
+
+# A skinned checkbox/radio is a zero-size or invisible native input whose visible <label> is the
+# real click target; the label is tagged (stale tags cleared first) so click can act on it.
+_SKINNED_CHECKBOX_PROBE_JS = (
+ r"""(sel) => {
+ const _visibleProxy = """
+ + _VISIBLE_PROXY_JS
+ + r""";
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ try {
+ // Cleared across roots, not just the document: a tag left inside a component would still be
+ // matched by the executor's piercing engine and clicked as though it were this call's proxy.
+ _q.all('[data-tv3-proxy]').forEach((e) => e.removeAttribute('data-tv3-proxy'));
+ const el = _q.find(sel);
+ if (!el) return { exists: false, skinned: false, labelTagged: false };
+ const type = String(el.type || '').toLowerCase();
+ if (el.tagName === 'INPUT' && type === 'file') return { exists: true, skinned: false, labelTagged: false, file: true };
+ const r = el.getBoundingClientRect();
+ const cs = getComputedStyle(el);
+ const invisible = r.width === 0 || r.height === 0 || cs.visibility === 'hidden' || parseFloat(cs.opacity || '1') < 0.05;
+ if (el.tagName === 'SELECT') {
+ return { exists: true, skinned: false, labelTagged: false, select: true, invisible, proxied: !!_visibleProxy(el) };
+ }
+ if (el.tagName !== 'INPUT' || (type !== 'checkbox' && type !== 'radio')) {
+ return { exists: true, skinned: false, labelTagged: false };
+ }
+ if (!invisible) return { exists: true, skinned: false, labelTagged: false };
+ const radio = type === 'radio';
+ const proxy = _visibleProxy(el);
+ if (!proxy) return { exists: true, skinned: false, labelTagged: false, radio, unproxied: true };
+ const disabled = !!el.disabled;
+ // A label that also wraps another control (a button, link, or a second input) is not a safe
+ // proxy: a real click on it can activate that control instead.
+ const label = el.labels && el.labels[0];
+ const wrapsOther = (l) => Array.from(l.querySelectorAll('button,a[href],input,select,textarea')).some((c) => c !== el);
+ // Only a real <label> activates its control on click; an aria-labelledby target is a name, not a proxy.
+ if (label && label === proxy && !wrapsOther(label)) {
+ label.setAttribute('data-tv3-proxy', '1');
+ return { exists: true, skinned: true, labelTagged: true, radio, disabled };
+ }
+ return { exists: true, skinned: true, labelTagged: false, radio, disabled };
+ } catch (e) { return { exists: false, skinned: false, labelTagged: false }; }
+}"""
+)
+
+# Read twice (before and after the forced click): a proxy that does not sync from its native input
+# must fail loud, not read as a successful toggle.
+_CHECKBOX_CHECKED_JS = (
+ r"""(sel) => {
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ try { const el = _q.find(sel); return el ? !!el.checked : null; } catch (e) { return null; }
+}"""
+)
+
# Pre-click state for the dropdown-commit path: whether a click-opened menu (rows tagged
# data-tv3-menu by _FIND_MENU_JS) is currently open, whether the click target IS one of its rows, and
# that row's state fingerprint — aria checked/selected/pressed, class, child count, text — so an option
@@ -416,6 +570,9 @@ _OBSERVE_JS = (
const _isAutocomplete = """
+ _IS_AUTOCOMPLETE_JS
+ r""";
+ const _visibleProxy = """
+ + _VISIBLE_PROXY_JS
+ + r""";
// [role=textbox] is deliberately absent: on a div without contenteditable it names a control that
// cannot be filled, and the ones that can are already matched by [contenteditable=true].
const _WIDGET_ROLES = ['button', 'checkbox', 'radio', 'combobox', 'option', 'menuitem',
@@ -708,6 +865,11 @@ _OBSERVE_JS = (
let unnamedUnsafe = 0;
let i = 0;
let dropped = 0;
+ // Two counters, deliberately: hiddenKept bounds the retention work and is spent the moment a
+ // control passes the styled-proxy gate, while hiddenListed is what the digest note claims. They
+ // diverge whenever a retained control is dropped later for having no selector that names it.
+ let hiddenKept = 0;
+ let hiddenListed = 0;
let truncated = 0;
let truncatedInComponents = 0;
let lastGroup = '';
@@ -720,7 +882,22 @@ _OBSERVE_JS = (
// loop is inside page.evaluate: one throw costs the whole element list, not one element.
try {
const r = el.getBoundingClientRect();
- if (r.width === 0 || r.height === 0) continue;
+ let hidden = false;
+ if (r.width === 0 || r.height === 0) {
+ // Design systems skin a native SELECT/checkbox/radio/file input at zero size behind a styled
+ // proxy widget. Keep only that narrow shape, and only with a visible label pointing at it —
+ // a genuinely hidden button/link/text-input is still dropped, same as before.
+ const tag = el.tagName;
+ const type = String(el.type || '').toLowerCase();
+ const skinnable = tag === 'SELECT' || (tag === 'INPUT' && (type === 'checkbox' || type === 'radio' || type === 'file'));
+ if (skinnable && _visibleProxy(el)) {
+ if (hiddenKept >= 40) { dropped++; continue; }
+ hidden = true;
+ hiddenKept++;
+ } else {
+ continue;
+ }
+ }
let selector = naturalSelector(el);
if (!selector) {
// We do not write inside a shadow root. Setting a marker there is a mutation of the
@@ -745,6 +922,15 @@ _OBSERVE_JS = (
}
let label = (el.getAttribute('aria-label') || el.getAttribute('placeholder') || '').trim();
if (!label && el.labels && el.labels[0]) label = (el.labels[0].innerText || '').trim();
+ if (!label) {
+ const lbId = el.getAttribute('aria-labelledby');
+ // Tree-scoped for the same reason as _VISIBLE_PROXY_JS: the shadow walk feeds this loop
+ // elements whose label id lives in their own root, not in the document.
+ let lbRoot = null;
+ try { lbRoot = Node.prototype.getRootNode.call(el); } catch (e) { lbRoot = null; }
+ const lb = lbId && lbRoot && lbRoot.getElementById ? lbRoot.getElementById(String(lbId).trim().split(/\s+/)[0]) : null;
+ if (lb) label = (lb.innerText || '').trim();
+ }
if (!label) label = (el.innerText || (el.type === 'password' ? '' : el.value) || '').trim();
const role = el.getAttribute('role');
// el.type is only trustworthy where the UA normalises it to a known keyword. On INPUT, BUTTON
@@ -753,6 +939,7 @@ _OBSERVE_JS = (
// line -- and a MIME type is noise to the model anyway.
const _typed = el.tagName === 'INPUT' || el.tagName === 'BUTTON' || el.tagName === 'SELECT';
const rec = { i, tag: el.tagName.toLowerCase(), type: (_typed && el.type) || null, selector, label: label.slice(0, 140) };
+ if (hidden) rec.hidden = true;
// A widget role is what the element IS -- a <div role="switch"> renders as a bare div otherwise,
// and the model cannot tell it from decoration. The role travels with its state below, or it is
// not worth surfacing: an on switch and an off one that read identically invite toggling the
@@ -805,6 +992,7 @@ _OBSERVE_JS = (
const pressed = el.getAttribute('aria-pressed');
if (pressed === 'true' || pressed === 'false') rec.pressed = pressed === 'true';
if (mintedValue !== null) mintedOn.push({ rec: rec, el: el, m: mintedValue });
+ if (hidden) hiddenListed++;
out.push(rec);
if (++i > 250) {
// Count what the budget actually cost, not what is left in the array: a zero-size match would
@@ -953,7 +1141,7 @@ _OBSERVE_JS = (
}
} catch (e) { iframeInfo.total = 0; iframeInfo.entries.length = 0; }
- return JSON.stringify({ url: location.href, title: document.title, text: texts, textTruncated: textFull, textDropped: textDropped, iframes: iframeInfo, dropped: dropped, truncated: truncated, truncatedInComponents: truncatedInComponents, unnamedAnonymous: unnamedAnonymous, unnamedDuplicated: unnamedDuplicated, unnamedUnverifiable: unnamedUnverifiable, unnamedUnsafe: unnamedUnsafe, unreadableRoot: sawUnreadableRoot, rootCount: allRoots.length - 1, elements: out });
+ return JSON.stringify({ url: location.href, title: document.title, text: texts, textTruncated: textFull, textDropped: textDropped, iframes: iframeInfo, dropped: dropped, truncated: truncated, truncatedInComponents: truncatedInComponents, unnamedAnonymous: unnamedAnonymous, unnamedDuplicated: unnamedDuplicated, unnamedUnverifiable: unnamedUnverifiable, unnamedUnsafe: unnamedUnsafe, unreadableRoot: sawUnreadableRoot, rootCount: allRoots.length - 1, hiddenListed: hiddenListed, elements: out });
}
"""
)
@@ -1063,6 +1251,11 @@ def build_browser_tools(
# is a different, invalid URL.
url_note = f" (url truncated from {len(sanitized_url)} chars)" if len(sanitized_url) > 300 else ""
lines = [f"url={shown_url}{url_note} title={data.get('title')!r} ({len(elements)} interactive elements)"]
+ hidden_kept = data.get("hiddenListed") or 0
+ if hidden_kept:
+ lines.append(
+ f"note: {hidden_kept} native control(s) hidden behind styled proxies are listed with [hidden-native]"
+ )
for t in data.get("text") or []:
lines.append(f"text: {t!r}")
text_dropped = data.get("textDropped") or 0
@@ -1161,6 +1354,13 @@ def build_browser_tools(
extra += " *invalid" if e["invalid"] is True else f" *invalid={e['invalid']!r}"
if e.get("autocomplete"):
extra += " [autocomplete→use select_combobox]"
+ if e.get("hidden"):
+ if e.get("type") == "file":
+ extra += " [hidden-native: styled proxy; file_upload works on it directly]"
+ elif e.get("tag") == "select":
+ extra += " [hidden-native: styled proxy; select_option acts on it directly]"
+ else:
+ extra += " [hidden-native: styled proxy; click acts on it directly]"
if e.get("group"):
extra += f" group={e['group']!r}"
# INVARIANT for this line and every line above it: no page-controlled byte reaches the
@@ -1198,13 +1398,30 @@ def build_browser_tools(
html = ""
else:
html = await page.content()
- # The click/type reaction gate stamps data-tv3-pre on every visible element; it is internal
- # bookkeeping, and left in place it costs a third of the truncation budget below in noise.
- html = html.replace(' data-tv3-pre="1"', "")
+ # The click/type reaction gate stamps data-tv3-pre on every visible element and the skinned-click
+ # probe stamps data-tv3-proxy on one label; both are internal bookkeeping, and left in place the
+ # first costs a third of the truncation budget below in noise.
+ html = html.replace(' data-tv3-pre="1"', "").replace(' data-tv3-proxy="1"', "")
if len(html) > 20000:
return ToolResult.ok(html[:20000] + "…[truncated at 20000 chars]")
return ToolResult.ok(html)
+ def _unreachable_error(selector: str) -> ToolResult:
+ return ToolResult.error(
+ f"{selector} is not rendered and nothing visible stands in for it — its section is collapsed, "
+ "closed or inactive, so a person could not reach this control either. Act on whatever reveals "
+ "it (the section header, the step, the modal trigger), then re-observe."
+ )
+
+ async def _clear_proxy_tags(page: Any) -> None:
+ try:
+ await page.evaluate(
+ "() => { const _q = " + _ROOT_QUERY_JS + "; "
+ "_q.all('[data-tv3-proxy]').forEach((e) => e.removeAttribute('data-tv3-proxy')); }"
+ )
+ except Exception:
+ pass
+
async def _click_reaction(
page: Any, selector: str, pre: dict[str, Any], url_before: str
) -> tuple[str | None, str | None]:
@@ -1337,21 +1554,97 @@ def build_browser_tools(
pass
url_before = await _url(page)
try:
- await page.click(selector, timeout=15000)
- except Exception as e:
- gone = False
+ skin_probe = await page.evaluate(_SKINNED_CHECKBOX_PROBE_JS, selector)
+ except Exception:
+ skin_probe = None
+ if isinstance(skin_probe, dict) and skin_probe.get("file"):
+ return ToolResult.error(
+ f"{selector} is a file input — clicking it opens a native picker the run cannot drive; "
+ "use file_upload with this selector instead"
+ )
+ if isinstance(skin_probe, dict) and skin_probe.get("select") and skin_probe.get("invisible"):
+ # Playwright's actionability wait never resolves against it, so a click here is 15s of pure
+ # loss followed by a raise; select_option forces past that on the same selector — but only
+ # for one something visible stands in for, so an unreachable select is sent to reveal first
+ # rather than to a tool that would refuse it a turn later.
+ if not skin_probe.get("proxied"):
+ return _unreachable_error(selector)
+ return ToolResult.error(
+ f"{selector} is a hidden native <select> — a click cannot open it; use select_option "
+ "with this selector instead"
+ )
+ if isinstance(skin_probe, dict) and skin_probe.get("unproxied"):
+ return _unreachable_error(selector)
+ skinned = bool(isinstance(skin_probe, dict) and skin_probe.get("skinned"))
+ label_tagged = bool(isinstance(skin_probe, dict) and skin_probe.get("labelTagged"))
+ checked_before: bool | None = None
+ if skinned:
+ if skin_probe.get("disabled"):
+ # Playwright refuses a label bound to a disabled control the same way it refuses the
+ # control, so the click path would spend its full timeout and then blame a re-render.
+ await _clear_proxy_tags(page)
+ return ToolResult.error(f"{selector} is disabled — it cannot be toggled until the page enables it")
try:
- gone = not await page.evaluate(_SELECTOR_EXISTS_JS, selector)
+ checked_before = await page.evaluate(_CHECKBOX_CHECKED_JS, selector)
except Exception:
+ checked_before = None
+ if checked_before is True and skin_probe.get("radio"):
+ # The probe tagged the label on its way here; left behind it shows up in get_html.
+ await _clear_proxy_tags(page)
+ return ToolResult.ok(f"{selector} is already selected — no change needed")
+
+ if skinned and label_tagged:
+ try:
+ await page.click('[data-tv3-proxy="1"]', timeout=15000)
+ except Exception as e:
+ return ToolResult.error(
+ f"click on {selector} via its label failed ({type(e).__name__}) — the page may have "
+ "re-rendered; re-observe and act on fresh selectors"
+ )
+ finally:
+ await _clear_proxy_tags(page)
+ base = f"clicked {selector} via its label — now at {await _url(page)}"
+ elif skinned:
+ await page.evaluate(
+ "(sel) => { const _q = " + _ROOT_QUERY_JS + "; const el = _q.find(sel); if (el) el.click(); }",
+ selector,
+ )
+ base = f"clicked {selector} (hidden native control, toggled directly) — now at {await _url(page)}"
+ else:
+ try:
+ await page.click(selector, timeout=15000)
+ except Exception as e:
gone = False
- if gone:
+ try:
+ gone = not await page.evaluate(_SELECTOR_EXISTS_JS, selector)
+ except Exception:
+ gone = False
+ if gone:
+ return ToolResult.error(
+ f"click on {selector} failed: the element no longer exists on the page — it was "
+ "likely removed by a re-render (e.g. a menu closed and destroyed its options). "
+ f"Re-observe and act on fresh selectors. (original error: {type(e).__name__})"
+ )
+ raise
+ base = f"clicked {selector} — now at {await _url(page)}"
+
+ if skinned:
+ try:
+ checked_after = await page.evaluate(_CHECKBOX_CHECKED_JS, selector)
+ except Exception:
+ checked_after = None
+ if checked_after is None:
+ return ToolResult.ok(
+ f"{base} — the control left the page after the click, so its state could not be "
+ "verified; re-observe before relying on it"
+ )
+ if checked_after == checked_before:
return ToolResult.error(
- f"click on {selector} failed: the element no longer exists on the page — it was "
- "likely removed by a re-render (e.g. a menu closed and destroyed its options). "
- f"Re-observe and act on fresh selectors. (original error: {type(e).__name__})"
+ f"click on {selector} did NOT commit: the control still reads checked={checked_after!r} — "
+ "the styled proxy may not sync from its hidden control; re-observe and act on the visible "
+ "proxy instead"
)
- raise
- base = f"clicked {selector} — now at {await _url(page)}"
+
if pre is None:
return ToolResult.ok(base)
try:
@@ -1550,11 +1843,45 @@ def build_browser_tools(
if error is not None:
return error
selector = args["selector"]
- if args.get("label") is not None:
- await page.select_option(selector, label=args["label"], timeout=15000)
+ label = args.get("label")
+ value = args.get("value")
+ try:
+ probe = await page.evaluate(_SELECT_VISIBILITY_JS, selector)
+ except Exception:
+ probe = None
+ # force bypasses actionability for a select a design system hides behind a styled proxy;
+ # Playwright still sets the value and dispatches native input/change on the real element.
+ if isinstance(probe, dict) and probe.get("exists") and probe.get("disabled"):
+ return ToolResult.error(f"{selector} is disabled — it cannot be set until the page enables it")
+ force = bool(isinstance(probe, dict) and probe.get("exists") and not probe.get("visible"))
+ if force and not probe.get("proxied"):
+ return _unreachable_error(selector)
+ if label is not None:
+ await page.select_option(selector, label=label, timeout=15000, force=force)
else:
- await page.select_option(selector, value=args.get("value"), timeout=15000)
- return ToolResult.ok(f"selected on {selector}")
+ await page.select_option(selector, value=value, timeout=15000, force=force)
+ if not force:
+ return ToolResult.ok(f"selected on {selector}")
+ try:
+ readback = await page.evaluate(_SELECT_READBACK_JS, selector)
+ except Exception:
+ readback = None
+ committed = False
+ value_read: Any = None
+ if isinstance(readback, dict):
+ value_read = readback.get("value")
+ committed = readback.get("selectedLabel") == label if label is not None else value_read == value
+ if readback is None:
+ return ToolResult.ok(
+ f"selected on {selector} — the control left the page afterwards, so the selection could not "
+ "be verified; re-observe before relying on it"
+ )
+ if not committed:
+ return ToolResult.error(
+ f"select on {selector} did NOT commit: native select still reads {value_read!r} — the styled "
+ "widget may not sync from its hidden control; re-observe and act on the visible proxy instead"
+ )
+ return ToolResult.ok(f"selected on {selector} (hidden native select, set directly)")
async def press_key(args: dict[str, Any]) -> ToolResult:
page, error = await _resolve_page()
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 6288e1fc9..7e6fc9ab9 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -11,6 +11,7 @@ import contextlib
import html
import json
import re
+import time
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any, Awaitable, Callable
@@ -117,7 +118,12 @@ class _FakePage:
self.calls.append(("type", {"selector": selector, "text": text}))
async def select_option(
- self, selector: str, value: Any = None, label: Any = None, timeout: int | None = None
+ self,
+ selector: str,
+ value: Any = None,
+ label: Any = None,
+ timeout: int | None = None,
+ force: bool = False,
) -> None:
self.calls.append(("select_option", {"selector": selector, "value": value, "label": label}))
@@ -2511,6 +2517,64 @@ async def test_dom_get_html_strips_reaction_bookkeeping_attrs() -> None:
assert "data-tv3-pre" not in html.content
+# --- Hidden native controls skinned by a styled proxy (SKY-14662): design-system forms hide the
+# real <select>/checkbox behind a custom widget. observe must still list them so the model can act
+# on the real control directly, instead of guessing at the invisible proxy internals. ---
+
+_HIDDEN_NATIVE_HTML = """
+<!doctype html><html><body>
+ <label for="country">Country</label>
+ <select id="country" style="display:none">
+ <option value="">Pick</option>
+ <option value="us">United States</option>
+ <option value="ca">Canada</option>
+ </select>
+ <div role="listbox" id="country-proxy" style="width:200px;height:30px">Pick</div>
+ <select id="ghost" style="display:none"><option>x</option></select>
+ <label for="agree" style="display:inline-block;width:200px;height:24px">I agree</label>
+ <input id="agree" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">
+ <input id="nolabel" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">
+ <input id="visible-text" type="text" style="width:0;height:0;border:0;padding:0">
+ <script>
+ document.getElementById('country').addEventListener('change', e => {
+ window.__changed = e.target.value;
+ document.getElementById('country-proxy').textContent = e.target.selectedOptions[0].text;
+ });
+ document.getElementById('agree').addEventListener('change', e => {
+ window.__agreeChanged = e.target.checked;
+ });
+ </script>
+</body></html>
+"""
+
+# Same shapes, but the page's own change listener reverts the value/checked state synchronously —
+# the styled proxy never actually adopted the change, so the forced action must fail loud rather
+# than report success on a widget that silently didn't sync.
+_HIDDEN_SELECT_REVERTS_HTML = """
+<!doctype html><html><body>
+ <label for="country">Country</label>
+ <select id="country" style="display:none">
+ <option value="">Pick</option>
+ <option value="us">United States</option>
+ <option value="ca">Canada</option>
+ </select>
+ <script>
+ document.getElementById('country').addEventListener('change', e => { e.target.value = ''; });
+ </script>
+</body></html>
+"""
+
+_HIDDEN_CHECKBOX_REVERTS_HTML = """
+<!doctype html><html><body>
+ <label for="agree" style="display:inline-block;width:200px;height:24px">I agree</label>
+ <input id="agree" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">
+ <script>
+ document.getElementById('agree').addEventListener('change', e => { e.target.checked = false; });
+ </script>
+</body></html>
+"""
+
+
_SHADOW_FIXTURE_HTML = """
<h1 id="posting-title">Software Engineer</h1>
<p id="blurb">This role sits on the platform team, and the posting body runs long enough that the
@@ -2585,6 +2649,20 @@ async def _shadow_page() -> AsyncIterator[Any]:
yield page
+@_skip_no_browser
+async def test_observe_lists_hidden_native_select_with_visible_label() -> None:
+ async with _content_page(_HIDDEN_NATIVE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ assert r.status == "ok"
+ assert "#country" in r.content
+ assert "United States" in r.content
+ assert "hidden-native" in r.content
+ assert "#ghost" not in r.content
+ assert "#visible-text" not in r.content
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_observe_enumerates_controls_inside_open_shadow_roots() -> None:
@@ -2607,6 +2685,18 @@ async def test_observe_enumerates_controls_inside_open_shadow_roots() -> None:
assert "Apply With Partner" in r.content
+@_skip_no_browser
+async def test_observe_lists_skinned_checkbox_with_visible_label() -> None:
+ async with _content_page(_HIDDEN_NATIVE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ assert r.status == "ok"
+ assert "#agree" in r.content
+ assert "hidden-native" in r.content
+ assert "#nolabel" not in r.content
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_observe_reports_a_reused_component_id_as_reused_not_as_anonymous() -> None:
@@ -2640,6 +2730,20 @@ async def test_observe_reports_a_reused_component_id_as_reused_not_as_anonymous(
assert "have no id, name or data-testid of their own" not in r.content, r.content
+@_skip_no_browser
+async def test_select_option_on_hidden_native_select_sets_value_and_fires_change() -> None:
+ async with _content_page(_HIDDEN_NATIVE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ start = time.monotonic()
+ r = await _tool(tools, "select_option").handler({"selector": "#country", "label": "United States"})
+ elapsed = time.monotonic() - start
+ assert r.status == "ok"
+ assert elapsed < 10
+ assert await page.evaluate("window.__changed") == "us"
+ assert await page.eval_on_selector("#country-proxy", "el => el.textContent") == "United States"
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_a_component_that_mirrors_its_id_inward_is_named_by_its_tag() -> None:
@@ -2667,6 +2771,16 @@ async def test_a_component_that_mirrors_its_id_inward_is_named_by_its_tag() -> N
assert await page.evaluate("() => window.hits") == ["inner:INPUT"]
+@_skip_no_browser
+async def test_select_option_on_hidden_native_select_fails_loud_when_change_does_not_commit() -> None:
+ async with _content_page(_HIDDEN_SELECT_REVERTS_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#country", "label": "United States"})
+ assert r.status == "error"
+ assert "did NOT commit" in r.content
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_typing_into_a_component_control_does_not_claim_a_check_we_could_not_run() -> None:
@@ -2695,6 +2809,21 @@ async def test_typing_into_a_component_control_does_not_claim_a_check_we_could_n
)
+@_skip_no_browser
+async def test_click_on_skinned_checkbox_routes_via_label() -> None:
+ async with _content_page(_HIDDEN_NATIVE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ start = time.monotonic()
+ r = await _tool(tools, "click").handler({"selector": "#agree"})
+ elapsed = time.monotonic() - start
+ assert r.status == "ok"
+ assert elapsed < 10
+ assert await page.eval_on_selector("#agree", "el => el.checked") is True
+ assert await page.evaluate("window.__agreeChanged") is True
+ assert await page.eval_on_selector_all("[data-tv3-proxy]", "els => els.length") == 0
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_the_iframe_line_is_emitted_even_when_the_scan_found_nothing() -> None:
@@ -2750,6 +2879,20 @@ async def test_a_root_cannot_disguise_itself_as_our_own_malformed_selector() ->
assert first.content == again.content, f"{err} churned:\n{first.content}\n---\n{again.content}"
+@_skip_no_browser
+async def test_click_refuses_a_skinned_checkbox_with_no_proxy_at_all() -> None:
+ # observe refuses to list this one (no visibly-rendered proxy), so click must not act on it either.
+ async with _content_page(_HIDDEN_NATIVE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ start = time.monotonic()
+ r = await _tool(tools, "click").handler({"selector": "#nolabel"})
+ elapsed = time.monotonic() - start
+ assert r.status == "error"
+ assert elapsed < 10
+ assert await page.eval_on_selector("#nolabel", "el => el.checked") is False
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_a_pre_seeded_marker_holding_a_line_separator_cannot_forge_a_line() -> None:
@@ -2774,6 +2917,42 @@ async def test_a_pre_seeded_marker_holding_a_line_separator_cannot_forge_a_line(
assert "FORGED" not in r.content, r.content
+@_skip_no_browser
+async def test_click_on_skinned_checkbox_fails_loud_when_toggle_does_not_commit() -> None:
+ async with _content_page(_HIDDEN_CHECKBOX_REVERTS_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "click").handler({"selector": "#agree"})
+ assert r.status == "error"
+ assert "did NOT commit" in r.content
+
+
+_HIDDEN_NATIVE_EDGES_HTML = """
+<!doctype html><html><body>
+ <label for="state">State</label>
+ <select id="state" style="display:none">
+ <option value="">Pick</option>
+ <option value="ny">
+ New York
+ </option>
+ </select>
+ <label for="locked">Locked</label>
+ <select id="locked" style="display:none" disabled><option value="">Pick</option><option value="a">A</option></select>
+ <label for="cv" style="display:inline-block;width:120px;height:24px">Resume</label>
+ <input id="cv" type="file" style="position:absolute;width:0;height:0;opacity:0">
+ <div id="many"></div>
+ <script>
+ const many = document.getElementById('many');
+ for (let n = 0; n < 45; n++) {
+ many.insertAdjacentHTML('beforeend',
+ `<label for="h${n}" style="display:inline-block;width:60px;height:20px">H${n}</label>` +
+ `<select id="h${n}" style="display:none"><option value="">Pick</option><option value="x">X</option></select>`);
+ }
+ </script>
+</body></html>
+"""
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_an_unverifiable_commit_is_not_reported_as_an_empty_field() -> None:
@@ -2815,6 +2994,18 @@ async def test_a_playwright_syntax_selector_is_not_called_a_component_control()
assert "cannot resolve that selector" in r.content, f"{selector}: {r.content}"
+@_skip_no_browser
+async def test_forced_select_readback_accepts_whitespace_padded_option_label() -> None:
+ # Playwright matches label= against the whitespace-collapsed option.label; the commit read-back
+ # must not reject a selection that Playwright itself accepted.
+ async with _content_page(_HIDDEN_NATIVE_EDGES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#state", "label": "New York"})
+ assert r.status == "ok"
+ assert await page.eval_on_selector("#state", "el => el.value") == "ny"
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_a_widget_that_unmounts_its_own_input_is_not_called_a_component() -> None:
@@ -2837,6 +3028,16 @@ async def test_a_widget_that_unmounts_its_own_input_is_not_called_a_component()
assert r.status == "error" and "NOT filled" in r.content, r
+@_skip_no_browser
+async def test_forced_select_refuses_disabled_select() -> None:
+ async with _content_page(_HIDDEN_NATIVE_EDGES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#locked", "label": "A"})
+ assert r.status == "error" and "disabled" in r.content
+ assert await page.eval_on_selector("#locked", "el => el.value") == ""
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_an_unreadable_root_is_disclosed_on_the_very_first_observe() -> None:
@@ -2861,6 +3062,31 @@ async def test_an_unreadable_root_is_disclosed_on_the_very_first_observe() -> No
assert first.content == again.content, f"static page churned:\n{first.content}\n---\n{again.content}"
+@_skip_no_browser
+async def test_observe_bounds_hidden_natives_and_points_file_inputs_at_file_upload() -> None:
+ async with _content_page(_HIDDEN_NATIVE_EDGES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ assert r.status == "ok"
+ listed = [line for line in r.content.splitlines() if line.startswith("[") and "hidden-native" in line]
+ assert len(listed) == 40
+ assert "note: 40 native control(s)" in r.content
+ assert "could not be described" in r.content # the overflow is disclosed, not silently dropped
+ cv_line = next(line for line in listed if "[#cv]" in line)
+ assert "file_upload" in cv_line and "click" not in cv_line
+
+
+_LABEL_WRAPS_BUTTON_HTML = """
+<!doctype html><html><body>
+ <label style="display:inline-block;width:240px;height:40px">
+ <input id="opt" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">
+ <button id="danger" type="button" style="width:240px;height:40px" onclick="window.__fired = true">Submit</button>
+ </label>
+</body></html>
+"""
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_a_host_whose_shadow_root_read_throws_is_disclosed() -> None:
@@ -3300,6 +3526,17 @@ async def test_stale_id_probe_does_not_report_shadow_hosted_selector_as_gone() -
assert await page.evaluate(_SELECTOR_EXISTS_JS, "#deep-ctrl") is True
+@_skip_no_browser
+async def test_skinned_click_never_routes_through_a_label_that_wraps_another_control() -> None:
+ async with _content_page(_LABEL_WRAPS_BUTTON_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "click").handler({"selector": "#opt"})
+ assert r.status == "ok"
+ assert await page.eval_on_selector("#opt", "el => el.checked") is True
+ assert await page.evaluate("window.__fired") is None
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_observe_does_not_manufacture_blind_spots_from_decorative_components() -> None:
@@ -3525,6 +3762,25 @@ async def test_observe_survives_named_getter_clobbering_while_piercing() -> None
assert r.content.count("[#") >= 3, "a raising accessor must not empty the element list"
+@_skip_no_browser
+async def test_click_on_file_input_redirects_to_file_upload_without_waiting() -> None:
+ async with _content_page(_HIDDEN_NATIVE_EDGES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ start = time.monotonic()
+ r = await _tool(tools, "click").handler({"selector": "#cv"})
+ assert time.monotonic() - start < 10
+ assert r.status == "error" and "file_upload" in r.content
+
+
+_ARIA_LABELLEDBY_HTML = """
+<!doctype html><html><body>
+ <span id="consent-text" style="display:inline-block;width:200px;height:24px">I consent</span>
+ <input id="consent" type="checkbox" aria-labelledby="consent-text" style="position:absolute;width:0;height:0;opacity:0">
+</body></html>
+"""
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_observe_element_choice_survives_a_page_that_overrides_matches() -> None:
@@ -3568,6 +3824,42 @@ async def test_observe_discloses_elements_dropped_by_the_budget() -> None:
assert "inside components" in note, note
+@_skip_no_browser
+async def test_aria_labelledby_names_and_routes_a_skinned_checkbox() -> None:
+ async with _content_page(_ARIA_LABELLEDBY_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ line = next(ln for ln in r.content.splitlines() if "[#consent]" in ln)
+ assert "I consent" in line and "hidden-native" in line
+ r = await _tool(tools, "click").handler({"selector": "#consent"})
+ assert r.status == "ok" and "toggled directly" in r.content # a span is a name, not a click proxy
+ assert await page.eval_on_selector("#consent", "el => el.checked") is True
+
+
+# A section the page has collapsed hides the control AND the proxy the user would have clicked, so
+# there is nothing on screen standing in for it — the discriminator observe already applies. The
+# selector survives the collapse, so the model can still hold it from an earlier observation.
+_COLLAPSED_PANEL_HTML = """
+<!doctype html><html><body>
+ <div id="panel">
+ <label for="terms" style="display:inline-block;width:200px;height:24px">Accept terms</label>
+ <input id="terms" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">
+ <label for="tier" style="display:inline-block;width:200px;height:24px">Tier</label>
+ <select id="tier" style="position:absolute;width:0;height:0;opacity:0">
+ <option value="">Pick</option>
+ <option value="pro">Pro</option>
+ </select>
+ </div>
+ <script>
+ document.getElementById('terms').addEventListener('change', e => { window.__termsChanged = e.target.checked; });
+ document.getElementById('tier').addEventListener('change', e => { window.__tierChanged = e.target.value; });
+ window.__collapse = () => { document.getElementById('panel').style.display = 'none'; };
+ </script>
+</body></html>
+"""
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_minted_marker_does_not_collide_with_one_planted_in_a_shadow_root() -> None:
@@ -3613,6 +3905,24 @@ async def test_budget_note_counts_only_what_it_actually_cost_and_offers_no_false
assert note.startswith("note: 9 more element(s)"), note
+@_skip_no_browser
+async def test_click_refuses_a_skinned_checkbox_once_its_proxy_stops_rendering() -> None:
+ async with _content_page(_COLLAPSED_PANEL_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r_open = await _tool(tools, "observe").handler({})
+ assert "#terms" in r_open.content # listed while the panel is open
+ await page.evaluate("window.__collapse()")
+ r_closed = await _tool(tools, "observe").handler({})
+ assert "#terms" not in r_closed.content # observe refuses it once collapsed
+ start = time.monotonic()
+ r = await _tool(tools, "click").handler({"selector": "#terms"})
+ assert time.monotonic() - start < 10
+ assert r.status == "error"
+ assert await page.eval_on_selector("#terms", "el => el.checked") is False
+ assert await page.evaluate("window.__termsChanged") is None
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_selector_exists_probe_is_not_fooled_by_a_named_getter_shadow_root() -> None:
@@ -3781,6 +4091,20 @@ async def test_observe_logs_omission_only_when_something_was_actually_omitted()
assert f"{entry['omitted_anonymous']} have no id, name or data-testid of their own" in note
+@_skip_no_browser
+async def test_select_option_refuses_a_hidden_select_once_its_proxy_stops_rendering() -> None:
+ async with _content_page(_COLLAPSED_PANEL_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await page.evaluate("window.__collapse()")
+ start = time.monotonic()
+ r = await _tool(tools, "select_option").handler({"selector": "#tier", "label": "Pro"})
+ assert time.monotonic() - start < 10
+ assert r.status == "error"
+ assert await page.eval_on_selector("#tier", "el => el.value") == ""
+ assert await page.evaluate("window.__tierChanged") is None
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_a_page_cannot_forge_an_element_line_into_the_observe_payload() -> None:
@@ -3834,6 +4158,28 @@ async def test_switch_state_is_reported_only_when_the_page_states_it() -> None:
assert "checked=True" in listed["#on"], listed["#on"]
+@_skip_no_browser
+async def test_hidden_select_digest_names_select_option_alone_and_click_refuses_it() -> None:
+ async with _content_page(_HIDDEN_NATIVE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ line = next(ln for ln in r.content.splitlines() if "[#country]" in ln)
+ assert "select_option" in line and "click" not in line
+ start = time.monotonic()
+ rc = await _tool(tools, "click").handler({"selector": "#country"})
+ assert time.monotonic() - start < 10
+ assert rc.status == "error" and "select_option" in rc.content
+
+
+_DISABLED_SKINNED_HTML = """
+<!doctype html><html><body>
+ <label for="agree" style="display:inline-block;width:200px;height:24px">I agree</label>
+ <input id="agree" type="checkbox" disabled style="position:absolute;width:0;height:0;opacity:0">
+</body></html>
+"""
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_observe_line_count_matches_its_header_across_hostile_attribute_values() -> None:
@@ -3932,6 +4278,26 @@ async def test_a_planted_marker_cannot_steer_a_click_to_a_decoy() -> None:
assert await page.evaluate("() => window.hits") == ["Real Button"]
+@_skip_no_browser
+async def test_click_refuses_a_disabled_skinned_checkbox_without_waiting() -> None:
+ async with _content_page(_DISABLED_SKINNED_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ start = time.monotonic()
+ r = await _tool(tools, "click").handler({"selector": "#agree"})
+ assert time.monotonic() - start < 10
+ assert r.status == "error" and "disabled" in r.content
+ assert await page.eval_on_selector("#agree", "el => el.checked") is False
+
+
+_SKINNED_RADIO_HTML = """
+<!doctype html><html><body>
+ <label for="pick" style="display:inline-block;width:200px;height:24px">Standard shipping</label>
+ <input id="pick" type="radio" name="ship" checked style="position:absolute;width:0;height:0;opacity:0">
+</body></html>
+"""
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_digest_carries_a_live_region_rendered_inside_a_component() -> None:
@@ -3979,6 +4345,18 @@ async def test_shadow_control_with_an_id_is_observable_and_clickable_end_to_end(
assert await page.evaluate("() => window.hits") == ["inner-btn"]
+@_skip_no_browser
+async def test_no_change_click_leaves_no_proxy_tag_on_the_page() -> None:
+ async with _content_page(_SKINNED_RADIO_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "click").handler({"selector": "#pick"})
+ assert r.status == "ok" and "already selected" in r.content
+ assert await page.eval_on_selector_all("[data-tv3-proxy]", "els => els.length") == 0
+ html = await _tool(tools, "get_html").handler({})
+ assert "data-tv3-proxy" not in html.content
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_one_unreadable_root_does_not_cost_every_selector_on_the_page() -> None:
@@ -4012,6 +4390,21 @@ async def test_one_unreadable_root_does_not_cost_every_selector_on_the_page() ->
) in first.content
+@_skip_no_browser
+async def test_click_on_an_unreachable_hidden_select_says_reveal_it_not_use_select_option() -> None:
+ # select_option would refuse this one too, so pointing the model at it costs a turn to learn nothing.
+ async with _content_page(_COLLAPSED_PANEL_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await page.evaluate("window.__collapse()")
+ start = time.monotonic()
+ r = await _tool(tools, "click").handler({"selector": "#tier"})
+ assert time.monotonic() - start < 10
+ assert r.status == "error"
+ assert "select_option" not in r.content
+ assert "reveal" in r.content
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_a_truncated_header_url_says_so() -> None:
@@ -4031,3 +4424,110 @@ async def test_a_truncated_header_url_says_so() -> None:
tools = build_browser_tools(_fixed_page_provider(page))
r = await _tool(tools, "observe").handler({})
assert "url truncated" not in r.content.splitlines()[0]
+
+
+# The seam between the styled-proxy retention above and the open-shadow-root walk: neither mechanism
+# was ever exercised against the other. A zero-size native inside a component reaches the retention
+# block only because the walk enumerates it, and it keeps its name only if the label lookup is scoped
+# to the component's own tree. Both labelling routes are covered because they resolve differently:
+# .labels is tree-scoped by the platform, aria-labelledby is an IDREF we resolve ourselves.
+_HIDDEN_NATIVE_IN_SHADOW_HTML = """
+<!doctype html><html><body>
+ <ds-country id="country-host"></ds-country>
+ <ds-terms id="terms-host"></ds-terms>
+ <script>
+ var c = document.getElementById('country-host').attachShadow({mode: 'open'});
+ c.innerHTML =
+ '<label for="sr-country">Shipping Country</label>' +
+ '<select id="sr-country" style="display:none">' +
+ '<option value="">Pick</option><option value="us">United States</option>' +
+ '<option value="ca">Canada</option></select>' +
+ '<div role="listbox" id="sr-country-proxy" style="width:200px;height:30px">Pick</div>';
+ c.getElementById('sr-country').addEventListener('change', function (e) {
+ window.__srChanged = e.target.value;
+ c.getElementById('sr-country-proxy').textContent = e.target.selectedOptions[0].text;
+ });
+ var t = document.getElementById('terms-host').attachShadow({mode: 'open'});
+ t.innerHTML =
+ '<span id="sr-terms-label" style="display:inline-block;width:200px;height:24px">Accept Terms</span>' +
+ '<input id="sr-terms" type="checkbox" aria-labelledby="sr-terms-label" ' +
+ 'style="position:absolute;width:0;height:0;opacity:0">';
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_observe_lists_hidden_natives_inside_open_shadow_roots_by_either_label_route() -> None:
+ async with _content_page(_HIDDEN_NATIVE_IN_SHADOW_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ assert r.status == "ok"
+ tagged = [ln for ln in r.content.splitlines() if "[hidden-native" in ln and not ln.startswith("note:")]
+ assert len(tagged) == 2, r.content
+ # <label for> inside the same root: the platform scopes .labels for us.
+ assert any("sr-country" in ln and "Shipping Country" in ln for ln in tagged), tagged
+ # aria-labelledby is an IDREF we resolve ourselves. Resolved against the document it finds
+ # nothing, so the control reads as unlabelled and is dropped at zero size -- listed nowhere
+ # and counted as no omission.
+ assert any("sr-terms" in ln and "Accept Terms" in ln for ln in tagged), tagged
+ assert "note: 2 native control(s) hidden behind styled proxies" in r.content
+
+
+@_skip_no_browser
+async def test_select_option_drives_a_hidden_native_select_inside_an_open_shadow_root() -> None:
+ async with _content_page(_HIDDEN_NATIVE_IN_SHADOW_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ start = time.monotonic()
+ r = await _tool(tools, "select_option").handler({"selector": "#sr-country", "label": "Canada"})
+ elapsed = time.monotonic() - start
+ assert r.status == "ok"
+ assert elapsed < 10
+ assert await page.evaluate("window.__srChanged") == "ca"
+ assert (
+ await page.evaluate(
+ "() => document.getElementById('country-host').shadowRoot"
+ ".getElementById('sr-country-proxy').textContent"
+ )
+ == "Canada"
+ )
+
+
+# Two dropzones of the same component reuse one id, so neither is nameable and both are dropped
+# AFTER the styled-proxy gate already counted them. The note must count what it listed, not what it
+# retained, or it reports controls the model cannot find any line for.
+_SHARED_ID_DROPZONES_HTML = """
+<!doctype html><html><body>
+ <ds-drop id="dz-single"></ds-drop>
+ <ds-drop id="dz-a"></ds-drop>
+ <ds-drop id="dz-b"></ds-drop>
+ <script>
+ function mk(hostId, inputId, labelText) {
+ var r = document.getElementById(hostId).attachShadow({mode: 'open'});
+ r.innerHTML =
+ '<label for="' + inputId + '" style="display:inline-block;width:240px;height:40px">' +
+ labelText + '</label>' +
+ '<input type="file" id="' + inputId + '" style="position:absolute;width:0;height:0;opacity:0">';
+ }
+ mk('dz-single', 'resume-unique', 'Upload resume (only one)');
+ mk('dz-a', 'resume', 'Upload resume');
+ mk('dz-b', 'resume', 'Upload cover letter');
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_hidden_native_note_counts_only_the_controls_it_actually_listed() -> None:
+ async with _content_page(_SHARED_ID_DROPZONES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ assert r.status == "ok"
+ tagged = [ln for ln in r.content.splitlines() if "[hidden-native" in ln and not ln.startswith("note:")]
+ assert len(tagged) == 1 and "resume-unique" in tagged[0], r.content
+ assert "note: 1 native control(s) hidden behind styled proxies" in r.content, r.content
+ # the two that share an id are dropped, and said to be dropped, rather than counted as listed
+ assert "reused by another instance of the same component" in r.content