Skip to content

Automate browser based workflows with AI

fix(SKY-11910): surface custom dropdown options in MCP observe + non-leaking action errors (#7165)

Marc Kelechavae7a57dd653c6
diff --git a/skyvern/cli/core/browser_ops.py b/skyvern/cli/core/browser_ops.py
index 1585f8fd1..2276bd521 100644
--- a/skyvern/cli/core/browser_ops.py
+++ b/skyvern/cli/core/browser_ops.py
@@ -568,6 +568,268 @@ _PASSWORD_NAME_RE = re.compile(
# Structural fields always kept in serialized output; display fields filtered if empty.
_ELEMENT_KEEP_ALWAYS = frozenset({"ref", "role"})
+_OBSERVE_INTERACTABLES_JS = r"""
+(scopeSelector) => {
+ const root = scopeSelector ? document.querySelector(scopeSelector) : document.body;
+ if (!root) return [];
+
+ const esc = (value) => (window.CSS && CSS.escape ? CSS.escape(value) : String(value).replace(/[^a-zA-Z0-9_-]/g, "\\$&"));
+ const classes = (element) => (element.className || "").toString();
+ const lowerClasses = (element) => classes(element).toLowerCase();
+ const isPassword = (element) => element.tagName.toLowerCase() === "input" && (element.getAttribute("type") || "").toLowerCase() === "password";
+ const text = (element) => {
+ const aria = element.getAttribute("aria-label");
+ if (aria?.trim()) return aria.trim();
+ const labelledBy = element.getAttribute("aria-labelledby");
+ if (labelledBy) {
+ const labelledText = labelledBy
+ .split(/\s+/)
+ .map((id) => document.getElementById(id)?.innerText || document.getElementById(id)?.textContent || "")
+ .join(" ")
+ .replace(/\s+/g, " ")
+ .trim();
+ if (labelledText) return labelledText;
+ }
+ if (element.id) {
+ const labelText = (document.querySelector(`label[for="${esc(element.id)}"]`)?.innerText || "")
+ .replace(/\s+/g, " ")
+ .trim();
+ if (labelText) return labelText;
+ }
+ if (element.labels && element.labels.length) {
+ const labelsText = Array.from(element.labels)
+ .map((node) => node.innerText || node.textContent || "")
+ .join(" ")
+ .replace(/\s+/g, " ")
+ .trim();
+ if (labelsText) return labelsText;
+ }
+ return (element.innerText || element.textContent || element.getAttribute("placeholder") || (isPassword(element) ? "" : element.value) || "")
+ .replace(/\s+/g, " ")
+ .trim();
+ };
+ const cssPath = (element) => {
+ if (element.id) return `#${esc(element.id)}`;
+ const parts = [];
+ for (let current = element; current && current.nodeType === Node.ELEMENT_NODE && current !== document.documentElement; current = current.parentElement) {
+ let part = current.tagName.toLowerCase();
+ if (current.id) {
+ parts.unshift(`#${esc(current.id)}`);
+ break;
+ }
+ const siblings = current.parentElement
+ ? Array.from(current.parentElement.children).filter((child) => child.tagName === current.tagName)
+ : [];
+ if (siblings.length > 1) part += `:nth-of-type(${siblings.indexOf(current) + 1})`;
+ parts.unshift(part);
+ }
+ return parts.join(" > ");
+ };
+ const visible = (element) => {
+ if (element.tagName.toLowerCase() === "option") return element.parentElement ? visible(element.parentElement) : false;
+ const style = window.getComputedStyle(element);
+ const rect = element.getBoundingClientRect();
+ return !element.hidden && element.getAttribute("aria-hidden") !== "true" && style?.display !== "none" && style?.visibility !== "hidden" && style?.visibility !== "collapse" && rect.width > 0 && rect.height > 0;
+ };
+ const explicitRole = (element) => (element.getAttribute("role") || "").toLowerCase();
+ const nativeRole = (element) => {
+ const tag = element.tagName.toLowerCase();
+ const type = (element.getAttribute("type") || "").toLowerCase();
+ if (["button", "select", "option", "textarea"].includes(tag)) {
+ return { button: "button", select: "combobox", option: "option", textarea: "textbox" }[tag];
+ }
+ if (tag === "a" && element.href) return "link";
+ if (tag !== "input") return "";
+ return { checkbox: "checkbox", radio: "radio", range: "slider", search: "searchbox" }[type] || "textbox";
+ };
+ const widgetRoles = new Set(["button", "checkbox", "combobox", "link", "listbox", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "searchbox", "slider", "spinbutton", "switch", "tab", "textbox", "treeitem"]);
+ const pointer = (element) => window.getComputedStyle(element)?.cursor === "pointer";
+ const staticClick = (element) => element.hasAttribute("onclick") || typeof element.onclick === "function" || element.hasAttribute("jsaction");
+ const frameworkClick = (element) => {
+ if (element.getAttributeNames().some((attr) => ["ng-click", "data-ng-click", "x-ng-click", "(click)"].includes(attr.toLowerCase()))) return true;
+ try {
+ return Boolean(window.jQuery?._data?.(element, "events")?.click);
+ } catch (_) {
+ return false;
+ }
+ };
+ const knownClass = (element) => {
+ const className = classes(element);
+ return className.includes("dropdown-item") || className.includes("ui-menu-item") || className.includes("pac-item") || className.includes("rddlItem") || className === "option";
+ };
+ const ancestorMatching = (element, predicate) => {
+ for (let current = element.parentElement, depth = 0; current && depth < 5; current = current.parentElement, depth += 1) {
+ if (predicate(current)) return current;
+ }
+ return null;
+ };
+ const optionContainer = (element) => ancestorMatching(element, (candidate) => {
+ const role = explicitRole(candidate);
+ const cls = lowerClasses(candidate);
+ return role === "listbox" || role === "menu" || ["list", "menu", "option", "dropdown", "select"].some((token) => cls.includes(token));
+ });
+ const interactiveAncestor = (element) => ancestorMatching(element, (candidate) => {
+ const role = explicitRole(candidate);
+ const cls = lowerClasses(candidate);
+ return pointer(candidate) || staticClick(candidate) || frameworkClick(candidate) || candidate.getAttribute("tabindex") === "0" || candidate.getAttribute("aria-expanded") === "true" || cls.includes("open") || role === "combobox" || role === "listbox";
+ });
+ const optionLike = (element) => Boolean(text(element) && optionContainer(element) && interactiveAncestor(element));
+ const roleFor = (element) => explicitRole(element) || nativeRole(element) || (optionLike(element) ? "option" : "button");
+ const candidate = (element) => {
+ if (!visible(element) || (window.getComputedStyle(element)?.pointerEvents === "none" && !element.disabled)) return false;
+ const tag = element.tagName.toLowerCase();
+ return Boolean(nativeRole(element) || widgetRoles.has(explicitRole(element)) || staticClick(element) || frameworkClick(element) || knownClass(element) || pointer(element) || (tag === "div" && element.getAttribute("tabindex") === "0") || optionLike(element));
+ };
+
+ return Array.from(root.querySelectorAll("*"))
+ .filter(candidate)
+ .map((element) => {
+ const tag = element.tagName.toLowerCase();
+ const item = { role: roleFor(element), name: text(element), tag, selector: cssPath(element) };
+ if (isPassword(element)) {
+ item.value = "";
+ item.is_password = true;
+ } else if (["input", "textarea", "select", "option"].includes(tag)) {
+ item.value = element.value || element.getAttribute("value") || "";
+ }
+ if (tag === "select") item.options = Array.from(element.options).map((option) => text(option));
+ return item;
+ })
+ .filter((item) => item.name || item.role);
+}
+"""
+
+
+_NATIVE_OPTION_TARGET_JS = r"""
+(element) => {
+ if (!element || element.tagName?.toLowerCase() !== "option") return null;
+ const select = element.closest("select");
+ if (!select) return null;
+
+ const esc = (value) => (window.CSS && CSS.escape ? CSS.escape(value) : String(value).replace(/[^a-zA-Z0-9_-]/g, "\\$&"));
+ const cssPath = (target) => {
+ if (target.id) return `#${esc(target.id)}`;
+ const parts = [];
+ for (let current = target; current && current.nodeType === Node.ELEMENT_NODE && current !== document.documentElement; current = current.parentElement) {
+ let part = current.tagName.toLowerCase();
+ if (current.id) {
+ parts.unshift(`#${esc(current.id)}`);
+ break;
+ }
+ const siblings = current.parentElement
+ ? Array.from(current.parentElement.children).filter((child) => child.tagName === current.tagName)
+ : [];
+ if (siblings.length > 1) part += `:nth-of-type(${siblings.indexOf(current) + 1})`;
+ parts.unshift(part);
+ }
+ return parts.join(" > ");
+ };
+
+ return {
+ select_selector: cssPath(select),
+ index: Array.prototype.indexOf.call(select.options, element),
+ value: element.value ?? element.getAttribute("value") ?? "",
+ label: (element.label || element.textContent || "").replace(/\s+/g, " ").trim(),
+ };
+}
+"""
+
+
+_NATIVE_OPTION_PROBE_TIMEOUT_MS = 1000
+
+
+@dataclass
+class NativeOptionSelection:
+ select_selector: str
+ value: str | None = None
+ label: str | None = None
+ index: int | None = None
+ selected_by: Literal["index", "value", "label"] = "index"
+
+
+async def select_native_option_if_targeted(
+ page: Any,
+ selector: str,
+ *,
+ timeout: int = 30000,
+) -> NativeOptionSelection | None:
+ """If ``selector`` targets a native <option>, select it via its parent <select>.
+
+ Native options inside a collapsed select are not actionable click targets in
+ Playwright. This keeps selector/ref driven click flows deterministic by
+ translating that specific target shape into a select_option call.
+ """
+ raw_page = getattr(page, "page", page)
+ locator_factory = getattr(raw_page, "locator", None)
+ if locator_factory is None:
+ return None
+
+ locator = locator_factory(selector)
+ first_locator = getattr(locator, "first", locator)
+ # Bounded classification probe: only decides whether the target is a native <option>.
+ # If the element is not readily present, defer to the caller's click (preserving
+ # direct-mode fast-fail and resilient-mode waiting) instead of blocking the full
+ # action timeout here.
+ probe_timeout = min(timeout, _NATIVE_OPTION_PROBE_TIMEOUT_MS)
+ try:
+ option_info = await first_locator.evaluate(_NATIVE_OPTION_TARGET_JS, timeout=probe_timeout)
+ except Exception:
+ return None
+ if not isinstance(option_info, dict):
+ return None
+
+ select_selector = option_info.get("select_selector")
+ if not isinstance(select_selector, str) or not select_selector:
+ return None
+
+ select_locator = locator_factory(select_selector)
+ value = option_info.get("value")
+ label = option_info.get("label")
+ index = option_info.get("index")
+ last_error: Exception | None = None
+
+ # The ref identified ONE specific <option>. Prefer its index so duplicate or empty option
+ # values cannot resolve to the wrong option; fall back to value, then label.
+ if isinstance(index, int) and index >= 0:
+ try:
+ await select_locator.select_option(index=index, timeout=timeout)
+ return NativeOptionSelection(
+ select_selector=select_selector,
+ value=str(value) if value is not None else None,
+ label=str(label) if label else None,
+ index=index,
+ selected_by="index",
+ )
+ except Exception as exc:
+ last_error = exc
+
+ if value is not None:
+ try:
+ await select_locator.select_option(value=str(value), timeout=timeout)
+ return NativeOptionSelection(
+ select_selector=select_selector,
+ value=str(value),
+ label=str(label) if label else None,
+ index=index if isinstance(index, int) else None,
+ selected_by="value",
+ )
+ except Exception as exc:
+ last_error = exc
+
+ if label:
+ await select_locator.select_option(label=str(label), timeout=timeout)
+ return NativeOptionSelection(
+ select_selector=select_selector,
+ value=str(value) if value is not None else None,
+ label=str(label),
+ index=index if isinstance(index, int) else None,
+ selected_by="label",
+ )
+
+ if last_error is not None:
+ raise last_error
+ raise ValueError(f"Native option target {selector!r} has no selectable index, value, or label")
+
@dataclass
class ObservedElement:
@@ -575,6 +837,7 @@ class ObservedElement:
role: str
name: str
tag: str
+ selector: str | None = None
value: str | None = None
options: list[str] | None = None
match_index: int = 0
@@ -618,6 +881,103 @@ def _extract_options(node: dict[str, Any]) -> list[str] | None:
return opts if opts else None
+async def _get_dom_observe_elements(page: Any, selector: str | None = None) -> list[dict[str, Any]]:
+ evaluate = getattr(page, "evaluate", None)
+ if evaluate is None:
+ return []
+ try:
+ result = await evaluate(_OBSERVE_INTERACTABLES_JS, selector)
+ except Exception:
+ return []
+ if not isinstance(result, list):
+ return []
+ return [element for element in result if isinstance(element, dict)]
+
+
+def _merge_dom_observe_elements(
+ a11y_elements: list[dict[str, Any]],
+ dom_elements: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ merged = list(a11y_elements)
+ selector_seen = {element.get("selector") for element in merged if element.get("selector")}
+
+ # Only upgrade an a11y element with a DOM selector when the (role, name, tag) key is
+ # unambiguous on both sides. A duplicate label would otherwise risk attaching the
+ # selector to the wrong element — a confidently wrong deterministic action. Ambiguous
+ # DOM elements still fall through to the append path with their own distinct selector.
+ def _key(role: str, name: str, tag: str) -> tuple[str, str, str]:
+ return role, name, tag
+
+ a11y_key_counts: dict[tuple[str, str, str], int] = {}
+ for element in merged:
+ if not element.get("selector"):
+ role = element.get("role", "")
+ key = _key(role, element.get("name", ""), _ROLE_TO_TAG.get(role, ""))
+ a11y_key_counts[key] = a11y_key_counts.get(key, 0) + 1
+ dom_key_counts: dict[tuple[str, str, str], int] = {}
+ for dom_element in dom_elements:
+ key = _key(dom_element.get("role", ""), dom_element.get("name", ""), dom_element.get("tag", ""))
+ dom_key_counts[key] = dom_key_counts.get(key, 0) + 1
+
+ for dom_element in dom_elements:
+ dom_selector = dom_element.get("selector")
+ if dom_selector and dom_selector in selector_seen:
+ continue
+ dom_key = _key(dom_element.get("role", ""), dom_element.get("name", ""), dom_element.get("tag", ""))
+ unambiguous = a11y_key_counts.get(dom_key, 0) == 1 and dom_key_counts.get(dom_key, 0) == 1
+ matched_existing = False
+ if unambiguous:
+ for existing in merged:
+ if (
+ not existing.get("selector")
+ and existing.get("role", "") == dom_element.get("role", "")
+ and existing.get("name", "") == dom_element.get("name", "")
+ and _ROLE_TO_TAG.get(existing.get("role", ""), "") == dom_element.get("tag", "")
+ ):
+ existing["selector"] = dom_selector
+ if dom_element.get("value") is not None and existing.get("value") is None:
+ existing["value"] = dom_element.get("value")
+ if dom_element.get("is_password"):
+ existing["is_password"] = True
+ if dom_element.get("options") and not existing.get("children"):
+ existing["options"] = dom_element.get("options")
+ matched_existing = True
+ if dom_selector:
+ selector_seen.add(dom_selector)
+ break
+ if not matched_existing:
+ merged.append(dom_element)
+ if dom_selector:
+ selector_seen.add(dom_selector)
+
+ # Any accessible name the DOM identifies as a password field redacts EVERY element
+ # sharing that (role, name, tag) key — a duplicate accessible name must not let an
+ # unflagged a11y value slip through.
+ password_keys = {
+ _key(dom_element.get("role", ""), dom_element.get("name", ""), dom_element.get("tag", ""))
+ for dom_element in dom_elements
+ if dom_element.get("is_password")
+ }
+ if password_keys:
+ # Keys present among the ORIGINAL a11y elements (NOT the appended DOM elements — an
+ # appended DOM password would otherwise "match" itself and defeat the fail-closed check).
+ a11y_password_keys = {
+ _key(e.get("role", ""), e.get("name", ""), _ROLE_TO_TAG.get(e.get("role", ""), "")) for e in a11y_elements
+ }
+ for element in merged:
+ role = element.get("role", "")
+ if _key(role, element.get("name", ""), _ROLE_TO_TAG.get(role, "")) in password_keys:
+ element["is_password"] = True
+ if password_keys - a11y_password_keys:
+ # Fail closed: a DOM password field could not be mapped to any original a11y element
+ # (unlabeled or divergent accessible name). Redact every a11y textbox value so a
+ # password can never leak through an unmatched pairing.
+ for element in merged:
+ if element.get("role") == "textbox" and element.get("value"):
+ element["is_password"] = True
+ return merged
+
+
async def do_observe(
page: Any,
selector: str | None = None,
@@ -625,52 +985,69 @@ async def do_observe(
max_elements: int = 50,
) -> ObserveResult:
"""Capture interactive elements with stable refs for batch operations."""
- if selector:
+ accessibility = getattr(page, "accessibility", None)
+ if selector and accessibility is not None:
element_handle = await page.locator(selector).first.element_handle()
- snapshot = await page.accessibility.snapshot(root=element_handle)
+ snapshot = await accessibility.snapshot(root=element_handle)
+ elif accessibility is not None:
+ snapshot = await accessibility.snapshot()
else:
- snapshot = await page.accessibility.snapshot()
+ snapshot = None
all_elements = _flatten_a11y_tree(snapshot)
+ dom_elements = await _get_dom_observe_elements(page, selector)
if interactive_only:
all_elements = [e for e in all_elements if e.get("role") in INTERACTIVE_ROLES]
+ all_elements = _merge_dom_observe_elements(all_elements, dom_elements)
+
total = len(all_elements)
- # Compute group sizes against the FULL filtered list (pre-cap) so that
- # kept elements colliding with off-cap siblings still get disambiguated.
+ # Compute group sizes against the FULL filtered list (pre-cap) so that kept elements
+ # colliding with off-cap siblings still get disambiguated. Also assign a STABLE match
+ # ordinal in original (pre-cap, pre-reorder) order so the `nth=N` fallback ref keeps
+ # pointing at the right element even when the cap reorders elements below.
full_group_size: dict[tuple[str, str], int] = {}
+ stable_counts: dict[tuple[str, str], int] = {}
for elem in all_elements:
- full_group_size[(elem.get("role", ""), elem.get("name", ""))] = (
- full_group_size.get((elem.get("role", ""), elem.get("name", "")), 0) + 1
- )
-
- capped = all_elements[:max_elements]
+ gkey = (elem.get("role", ""), elem.get("name", ""))
+ full_group_size[gkey] = full_group_size.get(gkey, 0) + 1
+ elem["_match_index"] = stable_counts.get(gkey, 0)
+ stable_counts[gkey] = elem["_match_index"] + 1
+
+ if total > max_elements:
+ # Keep the custom options this scan surfaces from being crowded out of the cap:
+ # option-role elements first, then other selector-bearing elements, then the rest.
+ options = [e for e in all_elements if e.get("role") == "option"]
+ other_selector = [e for e in all_elements if e.get("role") != "option" and e.get("selector")]
+ rest = [e for e in all_elements if e.get("role") != "option" and not e.get("selector")]
+ capped = (options + other_selector + rest)[:max_elements]
+ else:
+ capped = all_elements
observed: list[ObservedElement] = []
- group_counts: dict[tuple[str, str], int] = {}
for i, elem in enumerate(capped):
role = elem.get("role", "")
name = elem.get("name", "")
value = elem.get("value")
- # DESIGN-2: Redact password field values
- if value and _is_password_field(role, name):
+ # DESIGN-2: Redact password field values — by DOM input type (is_password) or name.
+ if elem.get("is_password") or (value and _is_password_field(role, name)):
value = "***"
key = (role, name)
- match_index = group_counts.get(key, 0)
- group_counts[key] = match_index + 1
+ match_index = elem.get("_match_index", 0)
observed.append(
ObservedElement(
ref=f"e{i}",
role=role,
name=name,
- tag=_ROLE_TO_TAG.get(role, ""),
+ tag=elem.get("tag") or _ROLE_TO_TAG.get(role, ""),
+ selector=elem.get("selector"),
value=value,
- options=_extract_options(elem),
+ options=elem.get("options") or _extract_options(elem),
match_index=match_index,
needs_disambiguation=full_group_size[key] > 1,
)
@@ -694,6 +1071,7 @@ def serialize_elements(elements: list[ObservedElement]) -> list[dict[str, Any]]:
"role": e.role,
"name": e.name,
"tag": e.tag,
+ "selector": e.selector,
"value": e.value,
"options": e.options,
}
@@ -705,6 +1083,8 @@ def serialize_elements(elements: list[ObservedElement]) -> list[dict[str, Any]]:
def ref_to_selector(elem: dict[str, Any]) -> str:
"""Convert an observed element's a11y data to a Playwright role selector."""
+ if selector := elem.get("selector"):
+ return selector
role = elem.get("role", "")
name = elem.get("name", "")
if name:
diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.py
index 67c5405fb..756f35928 100644
--- a/skyvern/cli/mcp_tools/browser.py
+++ b/skyvern/cli/mcp_tools/browser.py
@@ -27,6 +27,7 @@ from skyvern.cli.core.browser_ops import (
do_screenshot,
parse_extract_schema,
ref_to_selector,
+ select_native_option_if_targeted,
serialize_elements,
)
from skyvern.cli.core.guards import (
@@ -57,6 +58,8 @@ LOG = structlog.get_logger(__name__)
# Matches `await` as a keyword, not inside single-line comments or strings.
_AWAIT_RE = re.compile(r"\bawait\b")
_SINGLE_LINE_COMMENT_RE = re.compile(r"//[^\n]*")
+_ERROR_MESSAGE_MAX_CHARS = 500
+_ERROR_BODY_MESSAGE_KEYS = ("detail", "error", "message")
def _blank_to_none(value: str | None) -> str | None:
@@ -65,6 +68,56 @@ def _blank_to_none(value: str | None) -> str | None:
return value if value is None or value.strip() else None
+def _truncate_error_message(message: str) -> str:
+ message = message.strip()
+ if len(message) <= _ERROR_MESSAGE_MAX_CHARS:
+ return message
+ return f"{message[:_ERROR_MESSAGE_MAX_CHARS]}..."
+
+
+def _message_from_error_body(body: Any) -> str | None:
+ if isinstance(body, dict):
+ for key in _ERROR_BODY_MESSAGE_KEYS:
+ value = body.get(key)
+ if isinstance(value, str) and value.strip():
+ return _truncate_error_message(value)
+ if isinstance(value, dict):
+ nested = _message_from_error_body(value)
+ if nested:
+ return nested
+ # Only whitelisted dict keys are surfaced. A raw string body (or any unrecognized shape)
+ # from an SDK ApiError can carry secrets/tokens, so it is never surfaced verbatim.
+ return None
+
+
+def _exception_details(exc: Exception) -> dict[str, Any]:
+ details: dict[str, Any] = {"exception_type": type(exc).__name__}
+ status_code = getattr(exc, "status_code", None)
+ if status_code is not None:
+ details["status_code"] = status_code
+ return details
+
+
+def _exception_message(exc: Exception) -> str:
+ status_code = getattr(exc, "status_code", None)
+ # 5xx bodies carry the backend's wrapped internal exception text (see
+ # get_user_facing_exception_message's "Unexpected error: {exception}" fallback in
+ # skyvern/exceptions.py) — never surface them. 4xx bodies are the API's intended
+ # client-facing feedback (typed BadRequest/NotFound/UnprocessableEntity errors).
+ surface_body = not (isinstance(status_code, int) and status_code >= 500)
+ body_message = _message_from_error_body(getattr(exc, "body", None)) if surface_body else None
+ if body_message:
+ return f"HTTP {status_code}: {body_message}" if status_code is not None else body_message
+ # API-error-shaped exceptions (SDK ApiError) have a leaky __str__ that renders headers
+ # and the raw body; never fall back to str(exc) for them — surface only status + type.
+ if status_code is not None or hasattr(exc, "body"):
+ return f"HTTP {status_code}: {type(exc).__name__}" if status_code is not None else type(exc).__name__
+ message = str(exc).strip()
+ if message:
+ return _truncate_error_message(message)
+ return type(exc).__name__
+
+
def _must_reject_localhost_url(ctx: Any, url: str | None) -> bool:
return bool(url and is_localhost_url(url) and getattr(ctx, "can_access_localhost", None) is False)
@@ -224,6 +277,9 @@ async def skyvern_click(
return make_result("skyvern_click", ok=False, error=no_browser_error())
deterministic = selector is not None and selector_mode == "direct"
+ used_ai_path = False
+ native_option_selection = None
+ resolved: str | None = None
with Timer() as timer:
try:
kwargs: dict[str, Any] = {"timeout": timeout}
@@ -232,11 +288,17 @@ async def skyvern_click(
if click_count is not None:
kwargs["click_count"] = click_count
- if deterministic:
+ if selector is not None and (deterministic or ai_mode is None or ai_mode == "fallback"):
+ native_option_selection = await select_native_option_if_targeted(page, selector, timeout=timeout)
+
+ if native_option_selection is not None:
+ resolved = native_option_selection.select_selector
+ elif deterministic:
# selector_mode="direct": pin the selector, no overlay-dismiss or AI re-target, so a
# missed target fails fast and the agent re-derives it instead of AI scout-scrolling.
resolved = await page.click(selector=selector, mode="direct", **kwargs)
elif ai_mode is not None:
+ used_ai_path = True
resolved = await page.click(selector=selector, prompt=intent, ai=ai_mode, **kwargs) # type: ignore[arg-type]
else:
assert selector is not None
@@ -255,7 +317,7 @@ async def skyvern_click(
),
)
except Exception as e:
- code = ErrorCode.AI_FALLBACK_FAILED if (ai_mode and not deterministic) else ErrorCode.ACTION_FAILED
+ code = ErrorCode.AI_FALLBACK_FAILED if used_ai_path else ErrorCode.ACTION_FAILED
return make_result(
"skyvern_click",
ok=False,
@@ -263,19 +325,47 @@ async def skyvern_click(
timing_ms=timer.timing_ms,
error=make_error(
code,
- str(e),
+ _exception_message(e),
"The element may be hidden, disabled, or intercepted by another element",
+ details=_exception_details(e),
),
)
data: dict[str, Any] = {"selector": selector, "intent": intent, "ai_mode": ai_mode}
+ if native_option_selection is not None:
+ data["selected_option"] = {
+ "select_selector": native_option_selection.select_selector,
+ "selected_by": native_option_selection.selected_by,
+ }
+ if native_option_selection.index is not None:
+ data["selected_option"]["index"] = native_option_selection.index
+ if native_option_selection.value is not None:
+ data["selected_option"]["value"] = native_option_selection.value
+ if native_option_selection.label is not None:
+ data["selected_option"]["label"] = native_option_selection.label
if resolved and resolved != selector:
data["resolved_selector"] = resolved
# Build sdk_equivalent: prefer hybrid selector+prompt for production scripts.
# resolved_selector already contains the "xpath=" prefix (e.g. "xpath=//button[@id='x']"),
# so pass it directly as the selector positional arg.
resolved_sel = resolved if resolved and resolved != selector else selector
- if resolved_sel and intent:
+ if native_option_selection is not None:
+ if native_option_selection.selected_by == "label":
+ data["sdk_equivalent"] = (
+ f'await page.select_option("{native_option_selection.select_selector}", '
+ f'label="{native_option_selection.label}")'
+ )
+ elif native_option_selection.selected_by == "index":
+ data["sdk_equivalent"] = (
+ f'await page.select_option("{native_option_selection.select_selector}", '
+ f"index={native_option_selection.index})"
+ )
+ else:
+ data["sdk_equivalent"] = (
+ f'await page.select_option("{native_option_selection.select_selector}", '
+ f'value="{native_option_selection.value}")'
+ )
+ elif resolved_sel and intent:
data["sdk_equivalent"] = f'await page.click("{resolved_sel}", prompt="{intent}")'
elif ai_mode:
data["sdk_equivalent"] = f'await page.click(prompt="{intent}")'
@@ -542,7 +632,7 @@ async def skyvern_file_upload(
ok=False,
browser_context=ctx,
timing_ms=timer.timing_ms,
- error=make_error(code, str(e), "File upload failed"),
+ error=make_error(code, _exception_message(e), "File upload failed", details=_exception_details(e)),
)
return make_result(
@@ -622,8 +712,9 @@ async def skyvern_hover(
timing_ms=timer.timing_ms,
error=make_error(
code,
- str(e),
+ _exception_message(e),
"The element may be hidden or not interactable",
+ details=_exception_details(e),
),
)
@@ -775,8 +866,9 @@ async def skyvern_type(
timing_ms=timer.timing_ms,
error=make_error(
code,
- str(e),
+ _exception_message(e),
"The element may not be editable or may be hidden",
+ details=_exception_details(e),
),
)
@@ -903,7 +995,12 @@ async def skyvern_scroll(
ok=False,
browser_context=ctx,
timing_ms=timer.timing_ms,
- error=make_error(code, str(e), "Could not find element to scroll into view"),
+ error=make_error(
+ code,
+ _exception_message(e),
+ "Could not find element to scroll into view",
+ details=_exception_details(e),
+ ),
)
return make_result(
@@ -1018,7 +1115,12 @@ async def skyvern_select_option(
ok=False,
browser_context=ctx,
timing_ms=timer.timing_ms,
- error=make_error(code, str(e), "Check selector and available options"),
+ error=make_error(
+ code,
+ _exception_message(e),
+ "Check selector and available options",
+ details=_exception_details(e),
+ ),
)
# NOTE: The SDK select_option() returns the selected value, not a resolved
@@ -1320,7 +1422,12 @@ async def skyvern_extract(
ok=False,
browser_context=ctx,
timing_ms=timer.timing_ms,
- error=make_error(ErrorCode.SDK_ERROR, str(e), "Check that the page has loaded and the prompt is clear"),
+ error=make_error(
+ ErrorCode.SDK_ERROR,
+ _exception_message(e),
+ "Check that the page has loaded and the prompt is clear",
+ details=_exception_details(e),
+ ),
)
return make_result(
@@ -1357,7 +1464,12 @@ async def skyvern_validate(
ok=False,
browser_context=ctx,
timing_ms=timer.timing_ms,
- error=make_error(ErrorCode.SDK_ERROR, str(e), "Check that the page has loaded and the prompt is clear"),
+ error=make_error(
+ ErrorCode.SDK_ERROR,
+ _exception_message(e),
+ "Check that the page has loaded and the prompt is clear",
+ details=_exception_details(e),
+ ),
)
return make_result(
@@ -1409,7 +1521,12 @@ async def skyvern_act(
ok=False,
browser_context=ctx,
timing_ms=timer.timing_ms,
- error=make_error(ErrorCode.SDK_ERROR, str(e), "Simplify the prompt or break the task into steps"),
+ error=make_error(
+ ErrorCode.SDK_ERROR,
+ _exception_message(e),
+ "Simplify the prompt or break the task into steps",
+ details=_exception_details(e),
+ ),
)
return make_result(
@@ -1519,8 +1636,9 @@ async def skyvern_run_task(
timing_ms=timer.timing_ms,
error=make_error(
ErrorCode.SDK_ERROR,
- str(e) or type(e).__name__,
+ _exception_message(e),
"Check the prompt, URL, and timeout settings",
+ details=_exception_details(e),
),
)
@@ -1682,8 +1800,9 @@ async def skyvern_login(
timing_ms=timer.timing_ms,
error=make_error(
ErrorCode.SDK_ERROR,
- str(e) or type(e).__name__,
+ _exception_message(e),
"Check credential_type and required fields for your credential provider",
+ details=_exception_details(e),
),
)
diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.py
index 0d74bd10c..9193243ea 100644
--- a/tests/unit/test_mcp_browser_tools.py
+++ b/tests/unit/test_mcp_browser_tools.py
@@ -4,12 +4,13 @@ from __future__ import annotations
import asyncio
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
from skyvern.cli.core.result import BrowserContext
from skyvern.cli.mcp_tools import browser as mcp_browser
+from skyvern.client.errors import InternalServerError, UnprocessableEntityError
@pytest.mark.asyncio
@@ -192,6 +193,35 @@ async def test_skyvern_click_selector_plus_intent_falls_back_by_default(monkeypa
assert click.await_args.kwargs.get("mode") != "direct"
+async def test_skyvern_click_selector_plus_intent_runs_native_option_precheck(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ page, select_option = _native_option_page(monkeypatch)
+
+ result = await mcp_browser.skyvern_click(selector="#region > option:nth-of-type(4)", intent="pick the region")
+
+ assert result["ok"] is True
+ page.click.assert_not_awaited()
+ select_option.assert_awaited_once_with(value="east", timeout=30000)
+ assert result["data"]["selected_option"]["select_selector"] == "#region"
+
+
+async def test_skyvern_click_selector_plus_intent_probe_miss_falls_back(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ click = _click_page(monkeypatch)
+ probe = AsyncMock(return_value=None)
+ monkeypatch.setattr(mcp_browser, "select_native_option_if_targeted", probe)
+
+ result = await mcp_browser.skyvern_click(selector="#possibly-stale", intent="the blue submit button")
+
+ assert result["ok"] is True
+ probe.assert_awaited_once()
+ assert click.await_args.kwargs.get("ai") == "fallback"
+
+
@pytest.mark.asyncio
async def test_skyvern_click_selector_mode_direct_ignores_intent(monkeypatch: pytest.MonkeyPatch) -> None:
click = _click_page(monkeypatch)
@@ -222,6 +252,33 @@ def _action_page(monkeypatch: pytest.MonkeyPatch, **methods: AsyncMock) -> None:
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, context)))
+def _native_option_page(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ option_selector: str = "#region > option:nth-of-type(4)",
+ option_info: dict[str, str] | None = None,
+ select_side_effect: object | None = None,
+) -> tuple[SimpleNamespace, AsyncMock]:
+ option_info = option_info or {
+ "select_selector": "#region",
+ "value": "east",
+ "label": "East",
+ }
+ option_locator = SimpleNamespace(evaluate=AsyncMock(return_value=option_info))
+ option_locator.first = option_locator
+ select_option = AsyncMock(side_effect=select_side_effect)
+ select_locator = SimpleNamespace(select_option=select_option)
+ raw_page = SimpleNamespace(
+ locator=MagicMock(
+ side_effect=lambda selector: option_locator if selector == option_selector else select_locator
+ )
+ )
+ page = SimpleNamespace(page=raw_page, click=AsyncMock(return_value="#unexpected-click"))
+ context = BrowserContext(mode="cloud_session", session_id="pbs_test")
+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, context)))
+ return page, select_option
+
+
@pytest.mark.asyncio
async def test_skyvern_type_selector_is_resilient_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
fill = AsyncMock(return_value="Noor")
@@ -269,6 +326,175 @@ async def test_skyvern_type_intent_only_uses_proactive_ai(monkeypatch: pytest.Mo
assert fill.await_args.kwargs.get("mode") != "direct"
+async def test_skyvern_click_native_option_selector_uses_parent_select(monkeypatch: pytest.MonkeyPatch) -> None:
+ page, select_option = _native_option_page(monkeypatch)
+
+ result = await mcp_browser.skyvern_click(selector="#region > option:nth-of-type(4)")
+
+ assert result["ok"] is True
+ page.click.assert_not_awaited()
+ select_option.assert_awaited_once_with(value="east", timeout=30000)
+ assert result["data"]["resolved_selector"] == "#region"
+ assert result["data"]["selected_option"] == {
+ "select_selector": "#region",
+ "selected_by": "value",
+ "value": "east",
+ "label": "East",
+ }
+ assert result["data"]["sdk_equivalent"] == 'await page.select_option("#region", value="east")'
+
+
+async def test_skyvern_click_native_option_selector_can_fall_back_to_label(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ page, select_option = _native_option_page(monkeypatch, select_side_effect=[Exception("bad value"), None])
+
+ result = await mcp_browser.skyvern_click(selector="#region > option:nth-of-type(4)", timeout=5000)
+
+ assert result["ok"] is True
+ page.click.assert_not_awaited()
+ assert select_option.await_args_list[0].kwargs == {"value": "east", "timeout": 5000}
+ assert select_option.await_args_list[1].kwargs == {"label": "East", "timeout": 5000}
+ assert result["data"]["selected_option"]["selected_by"] == "label"
+ assert result["data"]["sdk_equivalent"] == 'await page.select_option("#region", label="East")'
+
+
+async def test_skyvern_click_native_option_selector_selects_by_index(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The ref identifies ONE specific <option>; a duplicate/empty value must not resolve to the
+ # wrong option. Selection must use the probe's index, not the value.
+ page, select_option = _native_option_page(
+ monkeypatch,
+ option_info={"select_selector": "#region", "index": 3, "value": "", "label": "East"},
+ )
+
+ result = await mcp_browser.skyvern_click(selector="#region > option:nth-of-type(4)")
+
+ assert result["ok"] is True
+ page.click.assert_not_awaited()
+ select_option.assert_awaited_once_with(index=3, timeout=30000)
+ assert result["data"]["selected_option"]["selected_by"] == "index"
+ assert result["data"]["selected_option"]["index"] == 3
+ assert result["data"]["sdk_equivalent"] == 'await page.select_option("#region", index=3)'
+
+
+async def test_skyvern_type_ai_error_surfaces_http_status_and_body(monkeypatch: pytest.MonkeyPatch) -> None:
+ # 4xx bodies are the API's intended client-facing feedback — surfaced for self-correction.
+ fill = AsyncMock(
+ side_effect=UnprocessableEntityError(
+ body={"detail": "Element locator did not match any element"},
+ headers={"authorization": "redacted"},
+ )
+ )
+ _action_page(monkeypatch, fill=fill)
+
+ result = await mcp_browser.skyvern_type(intent="the first name field", text="Noor")
+
+ assert result["ok"] is False
+ assert result["error"]["code"] == mcp_browser.ErrorCode.AI_FALLBACK_FAILED
+ assert result["error"]["message"] == "HTTP 422: Element locator did not match any element"
+ assert "headers" not in result["error"]["message"].lower()
+ assert "authorization" not in result["error"]["message"].lower()
+ assert result["error"]["details"] == {
+ "exception_type": "UnprocessableEntityError",
+ "status_code": 422,
+ }
+
+
+async def test_skyvern_type_ai_error_5xx_body_text_is_suppressed(monkeypatch: pytest.MonkeyPatch) -> None:
+ # 5xx bodies carry the backend's wrapped internal exception text
+ # ("Unexpected error: {exception}"); only status + exception type may surface.
+ fill = AsyncMock(side_effect=InternalServerError(body={"error": "Unexpected error: KeyError('internal-host')"}))
+ _action_page(monkeypatch, fill=fill)
+
+ result = await mcp_browser.skyvern_type(intent="the first name field", text="Noor")
+
+ assert result["ok"] is False
+ assert result["error"]["message"] == "HTTP 500: InternalServerError"
+ assert "internal-host" not in result["error"]["message"]
+ assert "Unexpected error" not in result["error"]["message"]
+
+
+async def test_skyvern_type_ai_error_empty_body_does_not_leak_headers(monkeypatch: pytest.MonkeyPatch) -> None:
+ # An ApiError whose body carries no recognized message key must not fall back to str(exc),
+ # which renders headers + raw body via the SDK ApiError.__str__. Surface only status + type.
+ fill = AsyncMock(
+ side_effect=InternalServerError(
+ body=None,
+ headers={"authorization": "Bearer sk-SECRET", "set-cookie": "sess=abc"},
+ )
+ )
+ _action_page(monkeypatch, fill=fill)
+
+ result = await mcp_browser.skyvern_type(intent="the first name field", text="Noor")
+
+ assert result["ok"] is False
+ message = result["error"]["message"]
+ assert message == "HTTP 500: InternalServerError"
+ for leaked in ("authorization", "bearer", "sk-secret", "set-cookie", "sess=abc", "headers"):
+ assert leaked not in message.lower()
+
+
+async def test_skyvern_type_ai_error_string_body_does_not_leak_token(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A raw string body (not a recognized dict shape) can carry tokens/secrets; it must never
+ # be surfaced verbatim — only status + exception type.
+ fill = AsyncMock(side_effect=InternalServerError(body="upstream said: token=sk-LEAKED-1234 is invalid"))
+ _action_page(monkeypatch, fill=fill)
+
+ result = await mcp_browser.skyvern_type(intent="the first name field", text="Noor")
+
+ assert result["ok"] is False
+ message = result["error"]["message"]
+ assert message == "HTTP 500: InternalServerError"
+ assert "sk-LEAKED-1234" not in message
+ assert "token=" not in message
+
+
+async def test_skyvern_act_sdk_error_does_not_leak_headers(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The SDK/agent handlers (act/extract/validate/run_task/login) must also route ApiError
+ # through _exception_message, not str(e) — otherwise ApiError.__str__ leaks headers/body.
+ _action_page(monkeypatch)
+ monkeypatch.setattr(
+ mcp_browser,
+ "do_act",
+ AsyncMock(side_effect=InternalServerError(body=None, headers={"authorization": "Bearer sk-SECRET"})),
+ )
+
+ result = await mcp_browser.skyvern_act(prompt="close the banner")
+
+ assert result["ok"] is False
+ message = result["error"]["message"]
+ assert message == "HTTP 500: InternalServerError"
+ for leaked in ("authorization", "bearer", "sk-secret", "headers"):
+ assert leaked not in message.lower()
+
+
+async def test_skyvern_type_ai_error_uses_exception_type_for_empty_message(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class SilentFailure(Exception):
+ def __str__(self) -> str:
+ return ""
+
+ fill = AsyncMock(side_effect=SilentFailure())
+ _action_page(monkeypatch, fill=fill)
+
+ result = await mcp_browser.skyvern_type(intent="the first name field", text="Noor")
+
+ assert result["ok"] is False
+ assert result["error"]["code"] == mcp_browser.ErrorCode.AI_FALLBACK_FAILED
+ assert result["error"]["message"] == "SilentFailure"
+ assert result["error"]["details"] == {"exception_type": "SilentFailure"}
+
+
@pytest.mark.asyncio
async def test_skyvern_select_option_selector_is_resilient_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
select = AsyncMock(return_value="us")
diff --git a/tests/unit/test_mcp_observe_execute.py b/tests/unit/test_mcp_observe_execute.py
index c1d045936..c84068bcf 100644
--- a/tests/unit/test_mcp_observe_execute.py
+++ b/tests/unit/test_mcp_observe_execute.py
@@ -250,6 +250,230 @@ class TestDoObserve:
result = await do_observe(page)
assert result.elements[0].options == ["US", "UK", "CA"]
+ @pytest.mark.asyncio
+ async def test_dom_interactables_are_merged_with_selectors(self) -> None:
+ page = _make_page(_make_a11y_tree(children=[{"role": "textbox", "name": "City", "value": ""}]))
+ page.evaluate = AsyncMock(
+ return_value=[
+ {
+ "role": "option",
+ "name": "Lakewood",
+ "tag": "div",
+ "selector": "#city-list > div:nth-of-type(1)",
+ }
+ ]
+ )
+
+ result = await do_observe(page)
+ serialized = serialize_elements(result.elements)
+
+ city_option = next(element for element in serialized if element["name"] == "Lakewood")
+ assert city_option["selector"] == "#city-list > div:nth-of-type(1)"
+ assert ref_to_selector(city_option) == "#city-list > div:nth-of-type(1)"
+
+ @pytest.mark.asyncio
+ async def test_dom_interactables_work_without_accessibility_snapshot(self) -> None:
+ page = SimpleNamespace(
+ url="https://example.com/form",
+ title=AsyncMock(return_value="Form"),
+ evaluate=AsyncMock(
+ return_value=[
+ {
+ "role": "option",
+ "name": "Music",
+ "tag": "div",
+ "selector": "#category-options > div:nth-of-type(2)",
+ }
+ ]
+ ),
+ )
+
+ result = await do_observe(page)
+ serialized = serialize_elements(result.elements)
+
+ assert len(serialized) == 1
+ assert serialized[0]["name"] == "Music"
+ assert serialized[0]["selector"] == "#category-options > div:nth-of-type(2)"
+
+ @pytest.mark.asyncio
+ async def test_dom_selector_is_attached_to_matching_a11y_option(self) -> None:
+ tree = _make_a11y_tree(
+ children=[
+ {
+ "role": "combobox",
+ "name": "Region",
+ "children": [
+ {"role": "option", "name": "North"},
+ {"role": "option", "name": "East"},
+ ],
+ },
+ ]
+ )
+ page = _make_page(tree)
+ page.evaluate = AsyncMock(
+ return_value=[
+ {
+ "role": "option",
+ "name": "East",
+ "tag": "option",
+ "selector": "#region > option:nth-of-type(2)",
+ "value": "east",
+ }
+ ]
+ )
+
+ result = await do_observe(page)
+ serialized = serialize_elements(result.elements)
+
+ east_option = next(element for element in serialized if element["name"] == "East")
+ assert east_option["selector"] == "#region > option:nth-of-type(2)"
+ assert east_option["value"] == "east"
+ assert ref_to_selector(east_option) == "#region > option:nth-of-type(2)"
+
+ @pytest.mark.asyncio
+ async def test_dom_password_field_value_redacted_by_type_not_name(self) -> None:
+ # A password input whose accessible name is NOT password-like must still be redacted
+ # when the DOM scan flags it (is_password); its raw value must never surface.
+ page = _make_page(_make_a11y_tree(children=[]))
+ page.evaluate = AsyncMock(
+ return_value=[
+ {
+ "role": "textbox",
+ "name": "Current",
+ "tag": "input",
+ "value": "",
+ "is_password": True,
+ "selector": "#pw",
+ }
+ ]
+ )
+ result = await do_observe(page)
+ serialized = serialize_elements(result.elements)
+ pw = next(element for element in serialized if element["name"] == "Current")
+ assert pw["value"] == "***"
+
+ @pytest.mark.asyncio
+ async def test_duplicate_label_options_do_not_get_wrong_selector(self) -> None:
+ # Two a11y options share a label and two DOM options share it too. The merge must NOT
+ # attach a DOM selector to an a11y option (ambiguous) — that would risk a confidently
+ # wrong deterministic action.
+ tree = _make_a11y_tree(
+ children=[
+ {
+ "role": "combobox",
+ "name": "Region",
+ "children": [
+ {"role": "option", "name": "North"},
+ {"role": "option", "name": "North"},
+ ],
+ },
+ ]
+ )
+ page = _make_page(tree)
+ page.evaluate = AsyncMock(
+ return_value=[
+ {
+ "role": "option",
+ "name": "North",
+ "tag": "option",
+ "selector": "#r > option:nth-of-type(1)",
+ "value": "n1",
+ },
+ {
+ "role": "option",
+ "name": "North",
+ "tag": "option",
+ "selector": "#r > option:nth-of-type(2)",
+ "value": "n2",
+ },
+ ]
+ )
+ result = await do_observe(page)
+ serialized = serialize_elements(result.elements)
+ a11y_norths = [e for e in serialized if e["name"] == "North" and not e.get("selector")]
+ assert len(a11y_norths) == 2
+
+ @pytest.mark.asyncio
+ async def test_duplicate_name_password_redacts_all_a11y_values(self) -> None:
+ # A password field whose accessible name is shared with another textbox must have its
+ # a11y value redacted even when the DOM match is ambiguous (duplicate name).
+ tree = _make_a11y_tree(
+ children=[
+ {"role": "textbox", "name": "Current", "value": "s3cr3t"},
+ {"role": "textbox", "name": "Current", "value": ""},
+ ]
+ )
+ page = _make_page(tree)
+ page.evaluate = AsyncMock(
+ return_value=[
+ {
+ "role": "textbox",
+ "name": "Current",
+ "tag": "input",
+ "value": "",
+ "is_password": True,
+ "selector": "#pw",
+ },
+ ]
+ )
+ result = await do_observe(page, max_elements=100)
+ serialized = serialize_elements(result.elements)
+ currents = [element for element in serialized if element["name"] == "Current"]
+ assert currents, serialized
+ for element in currents:
+ assert element["value"] in ("***", "", None), element
+ assert all("s3cr3t" not in str(element.get("value") or "") for element in serialized)
+
+ @pytest.mark.asyncio
+ async def test_match_index_stable_when_cap_reorders(self) -> None:
+ # A selector-bearing duplicate reordered ahead of the cap must NOT shift the nth ordinal
+ # of a selectorless duplicate sharing its (role, name). The a11y duplicate must keep its
+ # original ordinal (0), so its `nth=N` fallback ref points at the right element.
+ tree = _make_a11y_tree(
+ children=[
+ {"role": "combobox", "name": "Dup", "value": ""},
+ {"role": "combobox", "name": "Dup", "value": ""},
+ ]
+ )
+ page = _make_page(tree)
+ page.evaluate = AsyncMock(
+ return_value=[
+ {"role": "combobox", "name": "Dup", "tag": "select", "selector": "#dup3"},
+ ]
+ )
+ result = await do_observe(page, max_elements=2)
+ selectorless_dups = [e for e in result.elements if e.name == "Dup" and not e.selector]
+ assert selectorless_dups, result.elements
+ assert selectorless_dups[0].match_index == 0
+
+ @pytest.mark.asyncio
+ async def test_divergent_name_dom_password_fails_closed(self) -> None:
+ # If a DOM password field's accessible name diverges from the a11y name (so it cannot be
+ # mapped), fail closed: redact every a11y textbox value rather than leak the a11y value.
+ tree = _make_a11y_tree(
+ children=[
+ {"role": "textbox", "name": "Account", "value": "s3cr3t"},
+ ]
+ )
+ page = _make_page(tree)
+ page.evaluate = AsyncMock(
+ return_value=[
+ {
+ "role": "textbox",
+ "name": "DifferentName",
+ "tag": "input",
+ "value": "",
+ "is_password": True,
+ "selector": "#pw",
+ },
+ ]
+ )
+ result = await do_observe(page, max_elements=100)
+ serialized = serialize_elements(result.elements)
+ account = next(element for element in serialized if element["name"] == "Account")
+ assert account["value"] == "***"
+ assert all("s3cr3t" not in str(element.get("value") or "") for element in serialized)
+
@pytest.mark.asyncio
async def test_role_to_tag_mapping(self) -> None:
page = _make_page()
@@ -615,6 +839,60 @@ class TestSkyvernExecuteMCP:
click_call = mcp_browser.skyvern_click.call_args
assert 'role=button[name="Sign In"]' in str(click_call)
+ @pytest.mark.asyncio
+ async def test_execute_observe_then_click_native_option_ref_selects_parent(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ option_selector = "#region > option:nth-of-type(4)"
+ option_locator = SimpleNamespace(
+ evaluate=AsyncMock(
+ return_value={
+ "select_selector": "#region",
+ "value": "east",
+ "label": "East",
+ }
+ )
+ )
+ option_locator.first = option_locator
+ select_option = AsyncMock()
+ select_locator = SimpleNamespace(select_option=select_option)
+ page = SimpleNamespace(
+ url="https://example.com/form",
+ title=AsyncMock(return_value="Form"),
+ accessibility=None,
+ evaluate=AsyncMock(
+ return_value=[
+ {
+ "role": "option",
+ "name": "East",
+ "tag": "option",
+ "selector": option_selector,
+ "value": "east",
+ }
+ ]
+ ),
+ locator=MagicMock(
+ side_effect=lambda selector: option_locator if selector == option_selector else select_locator
+ ),
+ click=AsyncMock(return_value="#unexpected-click"),
+ )
+ ctx = BrowserContext(mode="local")
+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
+
+ result = await mcp_browser.skyvern_execute(
+ steps=[
+ {"tool": "observe", "params": {}},
+ {"tool": "click", "params": {"ref": "e0"}},
+ ]
+ )
+
+ assert result["ok"] is True
+ assert result["data"]["steps_completed"] == 2
+ page.click.assert_not_awaited()
+ select_option.assert_awaited_once_with(value="east", timeout=30000)
+ assert result["data"]["results"][1]["data"]["resolved_selector"] == "#region"
+
@pytest.mark.asyncio
async def test_execute_unknown_ref_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
page = _make_page()