Skip to content

Automate browser based workflows with AI

Log how each bare task's engine was chosen, once per run (#8246)

pedrohsdb6dff8ac63f79
diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.py
index f51f6561a..295a5a3d5 100644
--- a/skyvern/forge/sdk/copilot/composition_evidence.py
+++ b/skyvern/forge/sdk/copilot/composition_evidence.py
@@ -63,6 +63,11 @@ _MAX_SELECT_OPTIONS = 30
_MAX_CHALLENGE_CONTROLS = 8
_MAX_MODAL_OVERLAYS = 5
_MAX_MODAL_DISMISS_CONTROLS = 6
+_MAX_CARRIED_VALUE_CHARS = 240
+# The browser caps every field it emits in-page at this width, which is what makes
+# _structured_identity's whole report safe there. Nothing caps the parsed caller, so it matches.
+_MAX_PARSED_LABEL_CONTEXT_CHARS = 2048
+_MAX_LABEL_CONTEXT_HOPS = 4
_MAX_PAGE_OBSTRUCTIONS = 5
_MAX_VISIBLE_CONTROLS = 6
_MAX_CLICKABLE_CONTROLS = 12
@@ -1523,6 +1528,139 @@ def _control_label(node: Any) -> str:
return ""
+_NAMING_TAGS = ("label", "h1", "h2", "h3", "h4")
+_CONTROL_TAGS = ("input", "select", "textarea", "button")
+_CONTROL_ROLES = frozenset({"textbox", "combobox"})
+_NAMED_BY_OWN_TEXT_ROLES = frozenset({"button", "link", "menuitem", "tab", "option", "checkbox", "radio"})
+_INPUT_TYPE_ROLES = {
+ "button": "button",
+ "submit": "button",
+ "reset": "button",
+ "checkbox": "checkbox",
+ "radio": "radio",
+ "text": "textbox",
+ "search": "textbox",
+ "email": "textbox",
+ "tel": "textbox",
+ "url": "textbox",
+ "password": "textbox",
+ "": "textbox",
+}
+
+
+def _implicit_role(node: Any) -> str:
+ """Mirror of ``implicitRole``. The browser reports an element's implicit role in ``identity``, so a
+ twin that reads only the explicit attribute names the same element differently."""
+ tag = getattr(node, "name", None) or ""
+ if tag == "a":
+ return "link" if node.has_attr("href") else ""
+ if tag == "button":
+ return "button"
+ if tag == "select":
+ return "combobox"
+ if tag == "textarea":
+ return "textbox"
+ if tag == "input":
+ return _INPUT_TYPE_ROLES.get(_attr_value(node, "type").lower(), "")
+ return "heading" if re.fullmatch(r"h[1-6]", tag) else ""
+
+
+def _value_like(text: str) -> bool:
+ """Mirror of ``valueLike``: a datum rather than a name."""
+ return any(character.isdigit() for character in text) and not re.search(r"[A-Za-z]{3}", text)
+
+
+def _naming_text_of(node: Any) -> str:
+ return _attr_value(node, "aria-label") or _node_text(node)
+
+
+def _is_naming_node(node: Any) -> bool:
+ return getattr(node, "name", None) in _NAMING_TAGS or bool(_attr_value(node, "aria-label"))
+
+
+def _is_or_holds_control(node: Any) -> bool:
+ if getattr(node, "name", None) in _CONTROL_TAGS or _attr_value(node, "role") in _CONTROL_ROLES:
+ return True
+ return node.find(_CONTROL_TAGS) is not None
+
+
+def _named_by_own_text(node: Any) -> bool:
+ """``NAMED_BY_OWN_TEXT_ROLES`` over the tags this path reports. The browser resolves an implicit
+ role for any element; only a control whose own text reads as a datum needs the distinction."""
+ return (_attr_value(node, "role") or _implicit_role(node)) in _NAMED_BY_OWN_TEXT_ROLES
+
+
+def _label_context_for(node: Any) -> str:
+ """Mirror of ``labelContextFor``. The parsed twin previously fed ``identity.label_context`` from
+ ``_control_label`` — the mirror of ``controlLabel``, which feeds ``text`` — so the two producers
+ named the same element differently and the field carried nothing ``text`` did not."""
+ own = _attr_value(node, "aria-label")
+ if own:
+ return own
+ node_id = _attr_value(node, "id")
+ if node_id:
+ root = node
+ while getattr(root, "parent", None) is not None:
+ root = root.parent
+ for candidate in root.find_all("label"):
+ if _attr_value(candidate, "for") == node_id:
+ return _naming_text_of(candidate)
+ wrapping = node.find_parent("label")
+ if wrapping is not None:
+ own_text = _node_text(node)
+ wrapping_text = _node_text(wrapping)
+ # A control with no text of its own subtracts nothing, which is the whole point for a
+ # checkbox: the label wrapping it is the only thing naming it.
+ text = "".join(wrapping_text.split(own_text)).strip() if own_text else wrapping_text.strip()
+ if text:
+ return text
+ if _reads_as_one_leaf(node):
+ own_text = _node_text(node)
+ if own_text and (_named_by_own_text(node) or not _value_like(own_text)):
+ return own_text
+ inner = next((child for child in node.find_all(True) if _is_naming_node(child)), None)
+ if inner is not None:
+ return _naming_text_of(inner)
+ children = node.find_all(True, recursive=False)
+ if children and not children[0].find(True) and len(children) > 1:
+ leading = _node_text(children[0])
+ if leading and not _value_like(leading):
+ return leading
+ return _label_context_from_ancestors(node)
+
+
+def _label_context_from_ancestors(node: Any) -> str:
+ """A label sitting beside a field names the field it precedes, so document order decides which one
+ is ours and a control standing between the two means the label belongs to that one instead."""
+ current = node.parent
+ for _ in range(_MAX_LABEL_CONTEXT_HOPS):
+ if current is None or getattr(current, "name", None) is None:
+ break
+ children = current.find_all(True, recursive=False)
+ mine = next((index for index, child in enumerate(children) if child is node or node in child.descendants), -1)
+ if mine >= 0:
+ naming = [
+ index
+ for index, child in enumerate(children)
+ if index != mine and node not in child.descendants and _is_naming_node(child)
+ ]
+ adjacent = [
+ index
+ for index in naming
+ if not any(
+ _is_or_holds_control(children[between]) for between in range(min(index, mine) + 1, max(index, mine))
+ )
+ ]
+ if adjacent:
+ preceding = [index for index in adjacent if index < mine]
+ # Nothing precedes us and several could apply: no honest pick, so say nothing.
+ if not preceding and len(adjacent) > 1:
+ return ""
+ return _naming_text_of(children[preceding[-1] if preceding else adjacent[0]])
+ current = current.parent
+ return ""
+
+
_MAX_SELECTOR_CHARS = 160
# The rung that produced a candidate, so the model can tell a name-anchored offer from a positional
# one. An untyped candidate is not passed on: nothing downstream can rank or grade it.
@@ -1550,42 +1688,73 @@ def _bounded_selector(selector: str) -> str:
return selector if len(selector) <= _MAX_SELECTOR_CHARS else ""
-def _selector_for(node: Any) -> str:
- """Mirror of ``selectorFor`` in composition_browser_expressions. The selector is a contract: the
- model clicks it and authors it into generated blocks, so every candidate is verified to match
- this exact node and nothing else before it is handed out."""
+def _selector_candidates_for(node: Any, *, include_aria_label: bool = False) -> list[dict[str, str]]:
+ """Mirror of ``selectorCandidatesFor``'s attribute rungs, in the same order. The positional path
+ and the aria-label rung are offered only to callers that ask: the first costs an ancestor walk,
+ and the second would change which selector ``_selector_for`` settles on."""
tag_name = getattr(node, "name", None) or "*"
- candidates: list[str] = []
+ candidates: list[dict[str, str]] = []
node_id = _attr_value(node, "id")
if node_id:
candidates.append(
- f"#{node_id}" if _simple_css_identifier(node_id) else f'{tag_name}[id="{_css_attr(node_id)}"]'
+ {
+ "selector": f"#{node_id}"
+ if _simple_css_identifier(node_id)
+ else f'{tag_name}[id="{_css_attr(node_id)}"]',
+ "source": "id",
+ }
)
node_name = _attr_value(node, "name")
node_value = _attr_value(node, "value")
if node_name and node_value:
- candidates.append(f'{tag_name}[name="{_css_attr(node_name)}"][value="{_css_attr(node_value)}"]')
+ candidates.append(
+ {
+ "selector": f'{tag_name}[name="{_css_attr(node_name)}"][value="{_css_attr(node_value)}"]',
+ "source": "name_value",
+ }
+ )
classes = _classes_for(node)
class_selector = _class_selector(classes)
if class_selector and node_value:
- candidates.append(f'{tag_name}{class_selector}[value="{_css_attr(node_value)}"]')
+ candidates.append(
+ {"selector": f'{tag_name}{class_selector}[value="{_css_attr(node_value)}"]', "source": "class_value"}
+ )
if node_name:
- candidates.append(f'{tag_name}[name="{_css_attr(node_name)}"]')
+ candidates.append({"selector": f'{tag_name}[name="{_css_attr(node_name)}"]', "source": "name"})
+ aria_label = _attr_value(node, "aria-label") if include_aria_label else ""
+ if aria_label:
+ candidates.append({"selector": f'{tag_name}[aria-label="{_css_attr(aria_label)}"]', "source": "aria_label"})
href = _attr_value(node, "href")
if tag_name == "a" and href:
- candidates.append(f'a[href="{_css_attr(href)}"]')
+ candidates.append({"selector": f'a[href="{_css_attr(href)}"]', "source": "href"})
if class_selector:
- candidates.append(f"{tag_name}{class_selector}")
+ candidates.append({"selector": f"{tag_name}{class_selector}", "source": "class"})
node_type = _attr_value(node, "type")
if class_selector and node_type:
- candidates.append(f'{tag_name}{class_selector}[type="{_css_attr(node_type)}"]')
+ candidates.append(
+ {"selector": f'{tag_name}{class_selector}[type="{_css_attr(node_type)}"]', "source": "class_type"}
+ )
+ return candidates
+
+
+def _carried_selector_candidates(node: Any) -> list[dict[str, str]]:
+ candidates = _selector_candidates_for(node, include_aria_label=True)
+ candidates.append({"selector": _structural_path(node), "source": "structural"})
+ return _structured_selector_candidates(candidates)
+
+
+def _selector_for(node: Any) -> str:
+ """Mirror of ``selectorFor`` in composition_browser_expressions. The selector is a contract: the
+ model clicks it and authors it into generated blocks, so every candidate is verified to match
+ this exact node and nothing else before it is handed out."""
+ candidates = [entry["selector"] for entry in _selector_candidates_for(node)]
for candidate in candidates:
if _resolves_uniquely(node, candidate):
return candidate
path = _structural_path(node)
if _resolves_uniquely(node, path):
return path
- return candidates[0] if candidates else str(tag_name)
+ return candidates[0] if candidates else str(getattr(node, "name", None) or "*")
def _clickable_controls_channel(controls: list[dict[str, Any]] | None) -> dict[str, Any]:
@@ -2456,17 +2625,28 @@ def _modal_dismiss_controls(node: Any) -> list[dict[str, Any]]:
aria_label = _schema_text(_attr_value(control, "aria-label"), 120)
title = _schema_text(_attr_value(control, "title"), 120)
seen_selectors.add(selector)
+ entry = {
+ "tag": str(getattr(control, "name", "") or "").lower()[:40],
+ "text": text,
+ "aria_label": aria_label,
+ "title": title,
+ "selector": selector,
+ "type": _attr_value(control, "type")[:40],
+ }
controls.append(
- {
- "tag": str(getattr(control, "name", "") or "").lower()[:40],
- "text": text,
- "aria_label": aria_label,
- "title": title,
- "selector": selector,
- "type": _attr_value(control, "type")[:40],
- }
+ _attach_node_evidence(
+ {key: value for key, value in entry.items() if value != ""},
+ {
+ "selector_candidates": _carried_selector_candidates(control),
+ "identity": {
+ "tag": entry["tag"],
+ "role": _attr_value(control, "role") or _implicit_role(control),
+ "label_context": _schema_text(_label_context_for(control), _MAX_PARSED_LABEL_CONTEXT_CHARS),
+ },
+ },
+ )
)
- return [{key: value for key, value in entry.items() if value} for entry in controls]
+ return controls
def _modal_overlay_entry(node: Any) -> dict[str, Any]:
@@ -2523,10 +2703,16 @@ def _page_obstructions_from_modal_overlays(modal_overlays: list[dict[str, Any]])
continue
text = _bounded_string(control.get("text") or control.get("aria_label") or control.get("title"), 120)
selector = _bounded_string(control.get("selector"), 160)
- if text or selector:
- visible_controls.append(
- {key: value for key, value in {"text": text, "selector": selector}.items() if value}
- )
+ if not (text or selector):
+ continue
+ # The capture is the only place these facts exist; a control that reaches the model with
+ # one selector and no fallbacks cannot be clicked again once that selector goes stale.
+ carried = dict(control)
+ if text:
+ carried["text"] = text
+ if selector:
+ carried["selector"] = selector
+ visible_controls.append(carried)
entry = {
"kind": "modal_overlay",
"source": DOM_EVIDENCE_SOURCE,
@@ -3190,6 +3376,22 @@ def _structured_challenge_controls(value: Any) -> list[dict[str, Any]]:
return controls
+def _is_carried_control_key(key: Any) -> bool:
+ return isinstance(key, str) and 0 < len(key) <= 40 and key.replace("_", "").isalnum()
+
+
+def _carry_value(value: Any) -> str | bool | int | float:
+ if isinstance(value, (bool, int, float)):
+ return value
+ if isinstance(value, str):
+ return _bounded_string(value, _MAX_CARRIED_VALUE_CHARS)
+ # null and an empty collection are the producer's ordinary "not applicable", so they leave as the
+ # empty string the caller already drops; every other unmodelled shape arrives bounded, not dropped.
+ if value is None or (isinstance(value, (list, dict, tuple, set)) and not value):
+ return ""
+ return _bounded_string(str(value), _MAX_CARRIED_VALUE_CHARS)
+
+
def _structured_modal_dismiss_controls(value: Any) -> list[dict[str, Any]]:
controls: list[dict[str, Any]] = []
if not isinstance(value, list):
@@ -3197,15 +3399,23 @@ def _structured_modal_dismiss_controls(value: Any) -> list[dict[str, Any]]:
for control in value[:_MAX_MODAL_DISMISS_CONTROLS]:
if not isinstance(control, dict):
continue
- entry = {
- "tag": (_structured_str(control.get("tag")) or "").lower()[:40],
- "text": _schema_text(_structured_str(control.get("text")), 120),
- "aria_label": _schema_text(_structured_str(control.get("aria_label")), 120),
- "title": _schema_text(_structured_str(control.get("title")), 120),
- "selector": _bounded_selector(_structured_str(control.get("selector"))),
- "type": _structured_str(control.get("type"))[:40],
- }
- controls.append(_attach_node_evidence({k: v for k, v in entry.items() if v}, control))
+ # selector_candidates and identity are excluded from the carry so _attach_node_evidence stays
+ # their only writer; a raw copy would smuggle in the shapes that normalization rejects.
+ carried_keys = [
+ key for key in control if key not in ("selector_candidates", "identity") and _is_carried_control_key(key)
+ ]
+ entry: dict[str, Any] = {key: _carry_value(control[key]) for key in carried_keys}
+ entry.update(
+ {
+ "tag": (_structured_str(control.get("tag")) or "").lower()[:40],
+ "text": _schema_text(_structured_str(control.get("text")), 120),
+ "aria_label": _schema_text(_structured_str(control.get("aria_label")), 120),
+ "title": _schema_text(_structured_str(control.get("title")), 120),
+ "selector": _bounded_selector(_structured_str(control.get("selector"))),
+ "type": _structured_str(control.get("type"))[:40],
+ }
+ )
+ controls.append(_attach_node_evidence({k: v for k, v in entry.items() if v != ""}, control))
return controls
diff --git a/skyvern/forge/sdk/routes/sdk.py b/skyvern/forge/sdk/routes/sdk.py
index ef5b054f4..21b32ef2b 100644
--- a/skyvern/forge/sdk/routes/sdk.py
+++ b/skyvern/forge/sdk/routes/sdk.py
@@ -5,7 +5,13 @@ from fastapi import Depends, HTTPException, status
from skyvern.core.script_generations.real_skyvern_page_ai import RealSkyvernPageAi
from skyvern.core.script_generations.script_skyvern_page import ScriptSkyvernPage
-from skyvern.exceptions import ScrapingFailed, ScreenshotTargetClosed, SkyvernActionFailed, SkyvernHTTPException
+from skyvern.exceptions import (
+ MissingBrowserStatePage,
+ ScrapingFailed,
+ ScreenshotTargetClosed,
+ SkyvernActionFailed,
+ SkyvernHTTPException,
+)
from skyvern.forge import app
from skyvern.forge.sdk.api.files import validate_download_url
from skyvern.forge.sdk.core import skyvern_context
@@ -305,6 +311,23 @@ async def run_sdk_action(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="The browser page, context or browser was closed before the action could complete.",
)
+ except MissingBrowserStatePage as e:
+ await app.DATABASE.tasks.update_task(
+ task_id=task.task_id,
+ organization_id=organization_id,
+ status=TaskStatus.failed,
+ failure_reason=str(e),
+ )
+ LOG.warning(
+ "SDK action failed because the browser had no page left to act on",
+ action_type=action.type,
+ browser_session_id=browser_session_id,
+ error=str(e),
+ )
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
+ detail="The browser had no page left to act on before the action could complete.",
+ )
except SkyvernHTTPException as e:
await app.DATABASE.tasks.update_task(
task_id=task.task_id,
diff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.py
index 8aa666df9..28b39a143 100644
--- a/skyvern/webeye/scraper/scraper.py
+++ b/skyvern/webeye/scraper/scraper.py
@@ -13,6 +13,7 @@ from skyvern.config import settings
from skyvern.constants import DEFAULT_MAX_TOKENS, SKYVERN_ID_ATTR
from skyvern.exceptions import (
FailedToTakeScreenshot,
+ MissingBrowserStatePage,
NoElementFound,
ScrapingFailed,
ScrapingFailedBlankPage,
@@ -334,6 +335,14 @@ async def scrape_website(
except ScrapingFailedBlankPage:
raise
except Exception as e:
+ if isinstance(e, MissingBrowserStatePage) and e.diagnostic is not None:
+ # A disconnect was observed and never recovered, so the browser context is gone for
+ # good: check_and_fix_state only rebuilds a None context, and a lost page cannot be
+ # reopened on a disconnected one. Neither a retry here nor a later rung of the caller's
+ # scrape ladder can change that, and calling it ScrapingFailed blames the site for a
+ # browser-lifecycle failure. A missing page with no observed disconnect may still be a
+ # transient reopen failure, so that case keeps its retries.
+ raise
# NOTE: MAX_SCRAPING_RETRIES is set to 0 in both staging and production
if num_retry > max_retries:
if isinstance(e, ScreenshotTargetClosed):
diff --git a/tests/unit/data/click_overlay_named_dismiss.structured.json b/tests/unit/data/click_overlay_named_dismiss.structured.json
new file mode 100644
index 000000000..1124ee5ae
--- /dev/null
+++ b/tests/unit/data/click_overlay_named_dismiss.structured.json
@@ -0,0 +1,239 @@
+{
+ "anti_bot_indicators": [],
+ "body_has_markup": true,
+ "challenge_controls": [],
+ "clickable_controls": [
+ {
+ "disabled": false,
+ "identity": {
+ "label_context": "Continue to statements",
+ "role": "button",
+ "tag": "button"
+ },
+ "selector": "#btn-open-statements",
+ "selector_candidates": [
+ {
+ "selector": "#btn-open-statements",
+ "source": "id"
+ },
+ {
+ "selector": "body:nth-of-type(1) > main:nth-of-type(1) > button:nth-of-type(1)",
+ "source": "structural"
+ }
+ ],
+ "tag": "button",
+ "text": "Continue to statements",
+ "visible": true
+ }
+ ],
+ "forms": [
+ {
+ "action": "",
+ "fields": [
+ {
+ "checked": false,
+ "class": [],
+ "disabled": false,
+ "filled": true,
+ "id": "accept-terms",
+ "identity": {
+ "label_context": "I agree.",
+ "role": "checkbox",
+ "tag": "input"
+ },
+ "label": "I agree.",
+ "name": "accept_terms",
+ "options": [],
+ "placeholder": "",
+ "readonly": false,
+ "required": false,
+ "selector": "#accept-terms",
+ "selector_candidates": [
+ {
+ "selector": "#accept-terms",
+ "source": "id"
+ },
+ {
+ "selector": "input[name=\"accept_terms\"]",
+ "source": "name"
+ },
+ {
+ "selector": "#terms-modal > label:nth-of-type(1) > input:nth-of-type(1)",
+ "source": "structural"
+ }
+ ],
+ "type": "checkbox",
+ "value": "",
+ "visible": true
+ }
+ ],
+ "id": "terms-modal",
+ "method": "",
+ "name": "",
+ "submit_controls": [
+ {
+ "class": [],
+ "disabled": false,
+ "id": "btn-continue",
+ "identity": {
+ "label_context": "Continue",
+ "role": "button",
+ "tag": "button"
+ },
+ "name": "",
+ "selector": "#btn-continue",
+ "selector_candidates": [
+ {
+ "selector": "#btn-continue",
+ "source": "id"
+ },
+ {
+ "selector": "#terms-modal > button:nth-of-type(1)",
+ "source": "structural"
+ }
+ ],
+ "text": "Continue",
+ "type": "submit",
+ "value": "",
+ "visible": true
+ }
+ ]
+ }
+ ],
+ "key_value_relations": [],
+ "key_value_relations_truncated": false,
+ "modal_overlays": [
+ {
+ "aria_modal": false,
+ "class": [
+ "overlay"
+ ],
+ "dismiss_controls": [
+ {
+ "aria_label": "",
+ "identity": {
+ "label_context": "I agree.",
+ "role": "checkbox",
+ "tag": "input"
+ },
+ "selector": "#accept-terms",
+ "selector_candidates": [
+ {
+ "selector": "#accept-terms",
+ "source": "id"
+ },
+ {
+ "selector": "input[name=\"accept_terms\"]",
+ "source": "name"
+ },
+ {
+ "selector": "#terms-modal > label:nth-of-type(1) > input:nth-of-type(1)",
+ "source": "structural"
+ }
+ ],
+ "tag": "input",
+ "text": "",
+ "title": "",
+ "type": "checkbox"
+ },
+ {
+ "aria_label": "",
+ "identity": {
+ "label_context": "Continue",
+ "role": "button",
+ "tag": "button"
+ },
+ "selector": "#btn-continue",
+ "selector_candidates": [
+ {
+ "selector": "#btn-continue",
+ "source": "id"
+ },
+ {
+ "selector": "#terms-modal > button:nth-of-type(1)",
+ "source": "structural"
+ }
+ ],
+ "tag": "button",
+ "text": "Continue",
+ "title": "",
+ "type": "submit"
+ }
+ ],
+ "id": "terms-overlay",
+ "role": "",
+ "selector": "#terms-overlay",
+ "text": "Terms and Privacy I agree. Continue"
+ },
+ {
+ "aria_modal": true,
+ "class": [
+ "modal"
+ ],
+ "dismiss_controls": [
+ {
+ "aria_label": "",
+ "identity": {
+ "label_context": "I agree.",
+ "role": "checkbox",
+ "tag": "input"
+ },
+ "selector": "#accept-terms",
+ "selector_candidates": [
+ {
+ "selector": "#accept-terms",
+ "source": "id"
+ },
+ {
+ "selector": "input[name=\"accept_terms\"]",
+ "source": "name"
+ },
+ {
+ "selector": "#terms-modal > label:nth-of-type(1) > input:nth-of-type(1)",
+ "source": "structural"
+ }
+ ],
+ "tag": "input",
+ "text": "",
+ "title": "",
+ "type": "checkbox"
+ },
+ {
+ "aria_label": "",
+ "identity": {
+ "label_context": "Continue",
+ "role": "button",
+ "tag": "button"
+ },
+ "selector": "#btn-continue",
+ "selector_candidates": [
+ {
+ "selector": "#btn-continue",
+ "source": "id"
+ },
+ {
+ "selector": "#terms-modal > button:nth-of-type(1)",
+ "source": "structural"
+ }
+ ],
+ "tag": "button",
+ "text": "Continue",
+ "title": "",
+ "type": "submit"
+ }
+ ],
+ "id": "terms-modal",
+ "role": "dialog",
+ "selector": "#terms-modal",
+ "text": "Terms and Privacy I agree. Continue"
+ }
+ ],
+ "navigation_targets": [],
+ "navigation_targets_truncated": false,
+ "page_title": "",
+ "result_containers": [],
+ "result_containers_truncated": false,
+ "reveal_relations_truncated": false,
+ "visible_text_excerpt": "Continue to statements\nTerms and Privacy\nI agree. Continue",
+ "visual_obstruction_candidates": []
+}
diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.py
index ca8d41036..ca4116dc7 100644
--- a/tests/unit/test_copilot_composition_evidence.py
+++ b/tests/unit/test_copilot_composition_evidence.py
@@ -12,6 +12,7 @@ from unittest.mock import patch
import pytest
import yaml
+from bs4 import BeautifulSoup
from skyvern.config import settings
from skyvern.forge.sdk.copilot import tools as tools_module
@@ -34,12 +35,20 @@ from skyvern.forge.sdk.copilot.composition_browser_expressions import (
)
from skyvern.forge.sdk.copilot.composition_evidence import (
_BARE_MAGNITUDE_RE,
+ _MAX_CARRIED_VALUE_CHARS,
_MAX_CLICKABLE_CONTROLS,
+ _MAX_MODAL_DISMISS_CONTROLS,
_MAX_NAVIGATION_TARGETS,
+ _MAX_PARSED_LABEL_CONTEXT_CHARS,
_MAX_SELECTOR_CHARS,
+ _MAX_VISIBLE_CONTROLS,
_SELECTOR_CANDIDATE_SOURCES,
_UNKNOWN_SELECTOR_SOURCE,
+ _carried_selector_candidates,
+ _page_obstructions_from_modal_overlays,
+ _selector_for,
_structural_path,
+ _structured_modal_dismiss_controls,
composition_page_evidence_error,
has_actionable_steer_content,
has_bounded_page_schema,
@@ -5174,3 +5183,365 @@ def test_html_fallback_capture_carries_no_visibility_flags() -> None:
form = parsed["forms"][0]
assert [control for control in form["fields"] + form["submit_controls"] if "visible" in control] == []
+
+
+_DISMISS_FIXTURE_HTML = Path(__file__).parent / "data/click_overlay_named_dismiss.html"
+_DISMISS_FIXTURE_STRUCTURED = Path(__file__).parent / "data/click_overlay_named_dismiss.structured.json"
+_DISMISS_FIXTURE_URL = "https://example.test/statements"
+
+
+def _dismiss_control_keys(evidence: dict[str, Any]) -> set[frozenset[str]]:
+ return {frozenset(control) for overlay in evidence["modal_overlays"] for control in overlay["dismiss_controls"]}
+
+
+def _visible_control_keys(evidence: dict[str, Any]) -> set[frozenset[str]]:
+ return {
+ frozenset(control)
+ for obstruction in evidence["page_obstructions"]
+ for control in obstruction["visible_controls"]
+ }
+
+
+def test_obstruction_conversion_keeps_every_field_the_capture_produced() -> None:
+ control = {
+ "tag": "button",
+ "text": "Close",
+ "selector": "#close",
+ "type": "button",
+ "selector_candidates": [{"selector": "#close", "source": "id"}],
+ "identity": {"tag": "button", "role": "button", "label_context": "Close"},
+ "disabled": False,
+ "shadow_host_depth": 2,
+ }
+
+ obstructions = _page_obstructions_from_modal_overlays(
+ [{"selector": "#modal", "text": "Consent", "dismiss_controls": [control]}]
+ )
+
+ assert set(obstructions[0]["visible_controls"][0]) >= set(control)
+
+
+def test_obstruction_conversion_bounds_control_count_without_dropping_fields() -> None:
+ controls = [
+ {"tag": "button", "text": f"Option {index}", "selector": f"#option-{index}", "type": "button"}
+ for index in range(_MAX_VISIBLE_CONTROLS + 3)
+ ]
+
+ obstructions = _page_obstructions_from_modal_overlays([{"selector": "#modal", "dismiss_controls": controls}])
+
+ visible_controls = obstructions[0]["visible_controls"]
+ assert len(visible_controls) == _MAX_VISIBLE_CONTROLS
+ assert all(set(carried) == set(controls[0]) for carried in visible_controls)
+
+
+def test_obstruction_conversion_bounds_oversized_text_by_size_only() -> None:
+ control = {
+ "tag": "button",
+ "text": "Close " * 200,
+ "selector": "#close",
+ "type": "button",
+ "identity": {"tag": "button", "role": "button", "label_context": "Close"},
+ }
+
+ obstructions = _page_obstructions_from_modal_overlays([{"selector": "#modal", "dismiss_controls": [control]}])
+
+ carried = obstructions[0]["visible_controls"][0]
+ assert set(carried) == set(control)
+ assert len(carried["text"]) <= 120
+
+
+def test_structured_dismiss_controls_carry_producer_fields_they_do_not_name() -> None:
+ control = {
+ "tag": "BUTTON",
+ "text": "Accept",
+ "aria_label": "",
+ "title": "",
+ "selector": "#accept",
+ "type": "button",
+ "selector_candidates": [{"selector": "#accept", "source": "id"}],
+ "identity": {"tag": "button", "role": "button", "label_context": "Accept cookies"},
+ "pointer_events_none": True,
+ "occluded_by": "x" * (_MAX_CARRIED_VALUE_CHARS + 60),
+ "bounding_box": {"x": 10, "y": 20},
+ }
+
+ entry = _structured_modal_dismiss_controls([control])[0]
+
+ assert entry["pointer_events_none"] is True
+ assert len(entry["occluded_by"]) == _MAX_CARRIED_VALUE_CHARS
+ # A shape the carry does not model is bounded, not dropped: the field this test is named for.
+ assert "10" in entry["bounding_box"] and "20" in entry["bounding_box"]
+ assert entry["selector_candidates"] == [{"selector": "#accept", "source": "id"}]
+ assert entry["identity"]["label_context"] == "Accept cookies"
+
+
+def test_structured_dismiss_controls_reject_unbounded_evidence_the_producer_sent() -> None:
+ control = {
+ "tag": "button",
+ "text": "Accept",
+ "selector": "#accept",
+ "selector_candidates": [{"selector": "#" + "a" * (_MAX_SELECTOR_CHARS + 1), "source": "id"}],
+ "identity": {"role": "button", "label_context": "Accept cookies"},
+ }
+
+ entry = _structured_modal_dismiss_controls([control])[0]
+
+ assert "selector_candidates" not in entry
+ assert "identity" not in entry
+
+
+def test_identity_label_context_is_reported_whole_so_a_cut_prefix_cannot_read_as_a_rename() -> None:
+ label = "x" * 5000
+ control = {
+ "tag": "button",
+ "text": "Accept",
+ "selector": "#accept",
+ "identity": {"tag": "button", "role": "button", "label_context": label},
+ }
+
+ entry = _structured_modal_dismiss_controls([control])[0]
+
+ assert entry["identity"]["label_context"] == label
+
+
+def test_parsed_dismiss_controls_bound_a_label_context_no_upstream_cap_protects() -> None:
+ # The parsed path has no packet cap to fail closed above it, and _control_label falls through to
+ # the control's whole subtree text, so this caller bounds what _structured_identity reports whole.
+ label = "word " * 2000
+ html = f'<div role="dialog"><button id="accept">{label}</button></div>'
+
+ parsed = parse_composition_html(html, inspected_url=_DISMISS_FIXTURE_URL, current_url=_DISMISS_FIXTURE_URL)
+
+ control = parsed["modal_overlays"][0]["dismiss_controls"][0]
+ assert len(control["identity"]["label_context"]) == _MAX_PARSED_LABEL_CONTEXT_CHARS
+
+
+def test_a_producer_field_emitted_as_null_or_empty_is_absent_rather_than_rendered_as_text() -> None:
+ control = {
+ "tag": "button",
+ "text": "Accept",
+ "selector": "#accept",
+ "occluded_by": None,
+ "covering_selectors": [],
+ "bounding_box": {},
+ }
+
+ entry = _structured_modal_dismiss_controls([control])[0]
+
+ assert "occluded_by" not in entry
+ assert "covering_selectors" not in entry
+ assert "bounding_box" not in entry
+
+
+def test_a_control_named_only_by_its_wrapping_label_is_not_reported_anonymous() -> None:
+ # A checkbox has no text of its own, so the label wrapping it is the only thing naming it. The
+ # browser producer reports that label; the parsed twin reported nothing until it mirrored the ladder.
+ html = '<div role="dialog"><label><input type="checkbox" id="accept-terms" /><span>I agree.</span></label></div>'
+
+ parsed = parse_composition_html(html, inspected_url=_DISMISS_FIXTURE_URL, current_url=_DISMISS_FIXTURE_URL)
+
+ control = parsed["modal_overlays"][0]["dismiss_controls"][0]
+ assert control["identity"]["label_context"] == "I agree."
+ assert control.get("text", "") != control["identity"]["label_context"]
+
+
+def test_no_selector_candidate_the_producer_sent_is_dropped_for_being_one_too_many() -> None:
+ sent = [{"selector": f"#accept-{index}", "source": "id"} for index in range(40)]
+ sent.append({"selector": "html > body > button", "source": "structural"})
+ control = {"tag": "button", "text": "Accept", "selector": "#accept", "selector_candidates": sent}
+
+ entry = _structured_modal_dismiss_controls([control])[0]
+
+ assert [candidate["selector"] for candidate in entry["selector_candidates"]] == [
+ candidate["selector"] for candidate in sent
+ ]
+
+
+def test_structured_dismiss_controls_screen_an_injected_key_without_dropping_carried_ones() -> None:
+ injected_key = "onclick=alert(1)"
+ control: dict[str, Any] = {
+ "tag": "button",
+ "text": "Accept",
+ "selector": "#accept",
+ injected_key: "x",
+ }
+ control.update({f"extra_{index}": index for index in range(40)})
+
+ entry = _structured_modal_dismiss_controls([control])[0]
+
+ assert injected_key not in entry
+ assert entry["text"] == "Accept"
+ assert all(entry[f"extra_{index}"] == index for index in range(1, 40))
+
+
+def test_both_dismiss_control_producers_agree_on_the_fields_they_report() -> None:
+ parsed_html = parse_composition_html(
+ _DISMISS_FIXTURE_HTML.read_text(),
+ inspected_url=_DISMISS_FIXTURE_URL,
+ current_url=_DISMISS_FIXTURE_URL,
+ )
+ parsed_structured = parse_composition_structured(
+ json.loads(_DISMISS_FIXTURE_STRUCTURED.read_text()),
+ inspected_url=_DISMISS_FIXTURE_URL,
+ current_url=_DISMISS_FIXTURE_URL,
+ )
+ assert parsed_structured is not None
+
+ assert _dismiss_control_keys(parsed_html) == _dismiss_control_keys(parsed_structured)
+ assert _visible_control_keys(parsed_html) == _visible_control_keys(parsed_structured)
+
+ # Key sets alone pass while the two producers name the same element differently, which is what
+ # happened when the parsed twin fed label_context from the function that feeds `text`.
+ def identities(evidence: dict[str, Any]) -> dict[str, dict[str, str]]:
+ found: dict[str, dict[str, str]] = {}
+ for overlay in evidence["modal_overlays"]:
+ for control in overlay["dismiss_controls"]:
+ found.setdefault(control["selector"], control["identity"])
+ return found
+
+ from_html, from_structured = identities(parsed_html), identities(parsed_structured)
+ shared = set(from_html) & set(from_structured)
+ assert shared
+ for selector in shared:
+ assert from_html[selector] == from_structured[selector], selector
+
+
+def test_obstruction_conversion_hands_over_every_control_and_candidate_untouched() -> None:
+ controls = [
+ {
+ "text": "Accept all",
+ "selector": "#accept",
+ "selector_candidates": [
+ {"selector": "div > button:nth-of-type(1)", "source": "structural"},
+ {"selector": 'button[name="accept"]', "source": "name"},
+ {"selector": 'button[name="accept "]', "source": "name"},
+ {"selector": "#accept", "source": "id"},
+ ],
+ },
+ {
+ "text": "Necessary only",
+ "selector": "#necessary",
+ "selector_candidates": [
+ {"selector": 'button[aria-label="Necessary only"]', "source": "aria_label"},
+ {"selector": "#necessary", "source": "id"},
+ ],
+ },
+ {
+ "text": "Manage preferences",
+ "selector": "#manage",
+ "selector_candidates": [{"selector": "#manage", "source": "id"}],
+ },
+ ]
+
+ obstructions = _page_obstructions_from_modal_overlays([{"selector": "#modal", "dismiss_controls": controls}])
+ visible_controls = obstructions[0]["visible_controls"]
+
+ assert [control["text"] for control in visible_controls] == [control["text"] for control in controls]
+ assert [control["selector_candidates"] for control in visible_controls] == [
+ control["selector_candidates"] for control in controls
+ ]
+
+
+def test_page_obstruction_evidence_carries_candidates_and_identity() -> None:
+ payload = json.loads(_DISMISS_FIXTURE_STRUCTURED.read_text())
+ produced = payload["modal_overlays"][0]["dismiss_controls"][0]
+
+ parsed = parse_composition_structured(
+ payload,
+ inspected_url=_DISMISS_FIXTURE_URL,
+ current_url=_DISMISS_FIXTURE_URL,
+ )
+ assert parsed is not None
+
+ assert {key for key, value in produced.items() if isinstance(value, (list, dict))} == {
+ "selector_candidates",
+ "identity",
+ }
+ normalized = parsed["modal_overlays"][0]["dismiss_controls"][0]
+ assert normalized["selector_candidates"] == produced["selector_candidates"]
+ assert normalized["identity"]["tag"] == produced["identity"]["tag"]
+
+ control = parsed["page_obstructions"][0]["visible_controls"][0]
+ assert control["selector_candidates"] == produced["selector_candidates"]
+ assert control["identity"]["tag"] == produced["identity"]["tag"]
+
+
+def test_parsed_dismiss_controls_bound_the_number_of_controls_they_report() -> None:
+ buttons = "".join(
+ f'<button id="close-{index}">Close {index}</button>' for index in range(_MAX_MODAL_DISMISS_CONTROLS + 4)
+ )
+ html = f'<div role="dialog">{buttons}</div>'
+
+ parsed = parse_composition_html(html, inspected_url=_DISMISS_FIXTURE_URL, current_url=_DISMISS_FIXTURE_URL)
+
+ controls = parsed["modal_overlays"][0]["dismiss_controls"]
+ assert len(controls) == _MAX_MODAL_DISMISS_CONTROLS
+ assert all(control["selector_candidates"] for control in controls)
+
+
+def test_chosen_selector_ignores_the_aria_label_rung_the_candidates_keep() -> None:
+ soup = BeautifulSoup('<div role="dialog"><button aria-label="Close consent notice">x</button></div>', "html.parser")
+ control = soup.find("button")
+
+ chosen = _selector_for(control)
+ sources = [candidate["source"] for candidate in _carried_selector_candidates(control)]
+
+ assert "aria-label" not in chosen
+ assert chosen == _structural_path(control)
+ assert "aria_label" in sources
+
+
+def test_parsed_dismiss_controls_never_emit_an_unbounded_candidate() -> None:
+ html = f'<div role="dialog"><button id="{"i" * (_MAX_SELECTOR_CHARS + 40)}">Close</button></div>'
+
+ parsed = parse_composition_html(html, inspected_url=_DISMISS_FIXTURE_URL, current_url=_DISMISS_FIXTURE_URL)
+ control = parsed["modal_overlays"][0]["dismiss_controls"][0]
+
+ assert control["selector_candidates"]
+ assert all(len(candidate["selector"]) <= _MAX_SELECTOR_CHARS for candidate in control["selector_candidates"])
+
+
+def test_obstruction_conversion_keeps_a_producer_reported_false() -> None:
+ payload = {
+ "modal_overlays": [
+ {
+ "selector": "#modal",
+ "text": "Consent",
+ "dismiss_controls": [
+ {
+ "tag": "button",
+ "text": "Accept",
+ "selector": "#accept",
+ "pointer_events_none": False,
+ "stacking_index": 0,
+ }
+ ],
+ }
+ ]
+ }
+
+ parsed = parse_composition_structured(payload, inspected_url=_DISMISS_FIXTURE_URL, current_url=_DISMISS_FIXTURE_URL)
+ assert parsed is not None
+
+ control = parsed["page_obstructions"][0]["visible_controls"][0]
+ assert control["pointer_events_none"] is False
+ assert control["stacking_index"] == 0
+
+
+def test_parsed_dismiss_controls_offer_selector_sources_in_the_browser_rung_order() -> None:
+ html = (
+ '<div role="dialog"><button id="btn-close" name="close" class="cta" type="button" '
+ 'aria-label="Close consent">x</button></div>'
+ )
+
+ parsed = parse_composition_html(html, inspected_url=_DISMISS_FIXTURE_URL, current_url=_DISMISS_FIXTURE_URL)
+ control = parsed["modal_overlays"][0]["dismiss_controls"][0]
+
+ assert [candidate["source"] for candidate in control["selector_candidates"]] == [
+ "id",
+ "name",
+ "aria_label",
+ "class",
+ "class_type",
+ "structural",
+ ]
diff --git a/tests/unit/test_run_sdk_action_failures.py b/tests/unit/test_run_sdk_action_failures.py
index bd40cbd97..3c9a79a54 100644
--- a/tests/unit/test_run_sdk_action_failures.py
+++ b/tests/unit/test_run_sdk_action_failures.py
@@ -7,7 +7,12 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import HTTPException
-from skyvern.exceptions import ScrapingFailed, ScreenshotTargetClosed, SkyvernActionFailed
+from skyvern.exceptions import (
+ MissingBrowserStatePage,
+ ScrapingFailed,
+ ScreenshotTargetClosed,
+ SkyvernActionFailed,
+)
from skyvern.forge.sdk.db.enums import TaskType
from skyvern.forge.sdk.routes.sdk import _sdk_action_context_refcounts, run_sdk_action
from tests.unit.conftest import LEGACY_DOWNLOAD_ESCAPE_CASES
@@ -239,6 +244,29 @@ async def test_handler_returns_422_when_browser_target_closed(
mock_app.DATABASE.tasks.update_task.assert_awaited()
+async def test_handler_returns_422_when_browser_state_page_is_missing(
+ mock_request: Any, mock_organization: Any, mock_app: Any
+) -> None:
+ """A closed browser context is the same caller-visible condition as a closed target, so it
+ must not fall through to the generic handler and surface as a 500."""
+ with (
+ patch("skyvern.forge.sdk.routes.sdk.app", mock_app),
+ patch("skyvern.forge.sdk.routes.sdk.skyvern_context") as mock_ctx,
+ patch(
+ "skyvern.core.script_generations.script_skyvern_page.ScriptSkyvernPage.create_scraped_page",
+ new_callable=AsyncMock,
+ side_effect=MissingBrowserStatePage(task_id="tsk_gone"),
+ ),
+ ):
+ mock_ctx.ensure_context.return_value = MagicMock(request_id="req_test", tz_info=None, prompt=None)
+ with pytest.raises(HTTPException) as exc_info:
+ await run_sdk_action(mock_request, organization=mock_organization)
+
+ assert exc_info.value.status_code == 422
+ mock_app.DATABASE.tasks.update_task.assert_awaited()
+
+
@pytest.mark.asyncio
async def test_handler_propagates_unknown_exception(mock_request: Any, mock_organization: Any, mock_app: Any) -> None:
with (
diff --git a/tests/unit/test_screenshot_target_closed_callers.py b/tests/unit/test_screenshot_target_closed_callers.py
index a58d0f021..4f650abe2 100644
--- a/tests/unit/test_screenshot_target_closed_callers.py
+++ b/tests/unit/test_screenshot_target_closed_callers.py
@@ -9,6 +9,11 @@ alongside ``ScrapingFailed`` / ``MissingBrowserStatePage``, and ``execute_step``
cleanly at warning. Task teardown, the action handler, complete-action verification and the SDK
route (``test_run_sdk_action_failures.py``) were the frames left over from that first pass. These
tests pin every frame, with controls so unrelated failures still ERROR.
+
+``MissingBrowserStatePage`` is the same class of condition -- the browser context is gone, so no
+page exists to scrape -- and it needs the same pass-through. ``scrape_website`` laundered it into
+``ScrapingFailed``, which the step's scrape ladder treats as retryable, so a closed context spent
+every rung of ``SCRAPE_TYPE_ORDER`` re-discovering that the browser was still gone before failing.
"""
from __future__ import annotations
@@ -27,7 +32,13 @@ import skyvern.forge.agent as agent_mod
import skyvern.services.task_v2_service as task_v2_mod
import skyvern.webeye.actions.handler as handler_mod
import skyvern.webeye.scraper.scraper as scraper_mod
-from skyvern.exceptions import FailedToTakeScreenshot, ScreenshotTargetClosed
+from skyvern.exceptions import (
+ BrowserStateDiagnostic,
+ FailedToTakeScreenshot,
+ MissingBrowserStatePage,
+ ScrapingFailed,
+ ScreenshotTargetClosed,
+)
from skyvern.forge.agent import ForgeAgent
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
@@ -205,6 +216,140 @@ class TestScrapeRetryLoopTargetClosed:
assert any("All scrape attempts failed" in str(call.args[0]) for call in log.error.call_args_list)
+def _browser_gone() -> MissingBrowserStatePage:
+ """A missing page whose browser state already observed an unrecovered disconnect."""
+ now = datetime.now(UTC)
+ return MissingBrowserStatePage(
+ task_id="tsk_gone",
+ diagnostic=BrowserStateDiagnostic(
+ reason="browser_context_close_event",
+ disconnect_observed_at=now,
+ event="browser_context_close",
+ observation_source="browser_event",
+ ),
+ detected_at=now,
+ )
+
+
+class TestMissingBrowserStatePagePassThrough:
+ """A closed browser context is terminal: ``check_and_fix_state`` only rebuilds when
+ ``browser_context`` is ``None`` (a closed context is not), and ``_reopen_lost_working_page``
+ bails on a disconnected context. Every further scrape attempt is guaranteed to fail the same
+ way, so the scraper must surface the condition instead of relabelling it a scrape failure.
+ """
+
+ @pytest.mark.asyncio
+ async def test_scrape_website_reraises_missing_page_unchanged(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ error = _browser_gone()
+ monkeypatch.setattr(scraper_mod, "scrape_web_unsafe", AsyncMock(side_effect=error))
+ monkeypatch.setattr(scraper_mod, "build_scraping_failed_reason", AsyncMock(return_value="reason"))
+
+ with pytest.raises(MissingBrowserStatePage) as exc_info:
+ await scraper_mod.scrape_website(
+ browser_state=MagicMock(),
+ url="https://example.test/apply",
+ cleanup_element_tree=AsyncMock(),
+ max_retries=0,
+ )
+
+ assert exc_info.value is error
+
+ @pytest.mark.asyncio
+ async def test_scrape_website_retries_are_not_spent_on_a_gone_browser(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """``max_retries`` is 0 in production, but a caller passing a budget must not spend it either."""
+ scrape = AsyncMock(side_effect=_browser_gone())
+ monkeypatch.setattr(scraper_mod, "scrape_web_unsafe", scrape)
+ monkeypatch.setattr(scraper_mod, "build_scraping_failed_reason", AsyncMock(return_value="reason"))
+
+ with pytest.raises(MissingBrowserStatePage):
+ await scraper_mod.scrape_website(
+ browser_state=MagicMock(),
+ url="https://example.test/apply",
+ cleanup_element_tree=AsyncMock(),
+ max_retries=3,
+ )
+
+ assert scrape.await_count == 1
+
+ @pytest.mark.asyncio
+ async def test_missing_page_without_an_observed_disconnect_keeps_its_retries(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Control: no disconnect was observed, so the page may yet reopen -- the browser is not
+ provably gone and the caller's ladder still deserves its attempts."""
+ scrape = AsyncMock(side_effect=MissingBrowserStatePage(task_id="tsk_maybe"))
+ monkeypatch.setattr(scraper_mod, "scrape_web_unsafe", scrape)
+ monkeypatch.setattr(scraper_mod, "build_scraping_failed_reason", AsyncMock(return_value="reason"))
+
+ with pytest.raises(ScrapingFailed):
+ await scraper_mod.scrape_website(
+ browser_state=MagicMock(),
+ url="https://example.test/apply",
+ cleanup_element_tree=AsyncMock(),
+ max_retries=0,
+ )
+
+ def _ladder_rig(self, monkeypatch: pytest.MonkeyPatch, scrape_error: Exception) -> tuple[ForgeAgent, list, dict]:
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task = make_task(now, organization)
+ step = make_step(now, task, step_id="step-gone", status=StepStatus.running, order=0, output=None)
+ browser_state, _, _ = make_browser_state()
+
+ monkeypatch.setattr(scraper_mod, "scrape_web_unsafe", AsyncMock(side_effect=scrape_error))
+ monkeypatch.setattr(scraper_mod, "build_scraping_failed_reason", AsyncMock(return_value="reason"))
+ monkeypatch.setattr(
+ agent_mod.app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", AsyncMock(return_value=False)
+ )
+ skyvern_context.set(SkyvernContext(task_id=task.task_id, organization_id=task.organization_id))
+
+ # Drive the real scraper so the ladder sees the exception type scrape_website actually raises.
+ attempts: list[object] = []
+
+ async def scrape_with_type(*args: Any, **kwargs: Any) -> Any:
+ attempts.append(kwargs.get("scrape_type"))
+ return await scraper_mod.scrape_website(
+ browser_state=browser_state,
+ url=task.url,
+ cleanup_element_tree=AsyncMock(),
+ max_retries=0,
+ )
+
+ agent = ForgeAgent()
+ monkeypatch.setattr(agent, "_scrape_with_type", scrape_with_type)
+
+ return (
+ agent,
+ attempts,
+ {"task": task, "step": step, "browser_state": browser_state, "engine": RunEngine.skyvern_v1},
+ )
+
+ @pytest.mark.asyncio
+ async def test_ladder_stops_at_the_first_rung_when_the_browser_is_gone(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ agent, attempts, kwargs = self._ladder_rig(monkeypatch, _browser_gone())
+
+ with pytest.raises(MissingBrowserStatePage):
+ await agent.build_and_record_step_prompt(**kwargs)
+
+ assert len(attempts) == 1, f"a closed browser context still cost {len(attempts)} scrape attempts"
+
+ @pytest.mark.asyncio
+ async def test_ladder_still_spends_every_rung_on_a_real_scrape_failure(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Control: a site-caused failure is still worth retrying with the next strategy."""
+ agent, attempts, kwargs = self._ladder_rig(monkeypatch, RuntimeError("boom"))
+
+ with pytest.raises(ScrapingFailed):
+ await agent.build_and_record_step_prompt(**kwargs)
+
+ assert len(attempts) == len(agent_mod.SCRAPE_TYPE_ORDER)
+
+
class TestAgentStepPassThrough:
"""``agent_step`` must treat a closed target as an expected terminal failure, the way it already
treats ``ScrapingFailed`` / ``MissingBrowserStatePage`` — otherwise its generic handler re-files