Skip to content

Automate browser based workflows with AI

Task V3 observe: name a Yes/No button pair's question on both buttons and echo it on click (SKY-18212) (#9037)

Shuchang Zheng9e71516d7e60
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 77c991579..8fd99fa58 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -128,7 +128,6 @@ from skyvern.exceptions import (
get_user_facing_exception_message,
)
from skyvern.forge import app
-from skyvern.forge.failure_classifier import OUTPUT_ONLY_ANTI_BOT_REASON_CODES, classify_from_failure_reason
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api import email
from skyvern.forge.sdk.api.aws import AsyncAWSClient
@@ -2063,26 +2062,6 @@ def _run_lost_its_browser(workflow_run_id: str) -> bool:
return get_browser_connection_loss(app.BROWSER_MANAGER.get_for_workflow_run(workflow_run_id)) is not None
-def _is_retry_blocking_anti_bot_entry(category: dict) -> bool:
- return (
- category.get("category") == "ANTI_BOT_DETECTION"
- and category.get("reason_code") not in OUTPUT_ONLY_ANTI_BOT_REASON_CODES
- )
-
-
-def _should_skip_retry_on_anti_bot_detection(task: Task) -> bool:
- categories = task.failure_category
- if categories:
- return any(_is_retry_blocking_anti_bot_entry(c) for c in categories)
-
- if task.failure_reason:
- result = classify_from_failure_reason(task.failure_reason)
- if result and any(_is_retry_blocking_anti_bot_entry(c) for c in result):
- return True
-
- return False
-
-
def _engine_is_unset(engine: RunEngine | None) -> bool:
return engine is None
@@ -2950,19 +2929,6 @@ class BaseTaskBlock(Block):
else:
current_retry += 1
will_retry = current_retry <= self.max_retries
- if will_retry and _should_skip_retry_on_anti_bot_detection(updated_task):
- LOG.warning(
- "Skipping retry - task failed due to anti-bot detection",
- task_id=updated_task.task_id,
- workflow_run_id=workflow_run_id,
- workflow_id=workflow.workflow_id,
- organization_id=workflow_run.organization_id,
- current_retry=current_retry,
- max_retries=self.max_retries,
- failure_reason=updated_task.failure_reason,
- failure_category=updated_task.failure_category,
- )
- will_retry = False
downloaded_files = None
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index c54f2b886..14c1a2037 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -31,7 +31,13 @@ from urllib.parse import urlsplit
import structlog
from skyvern.errors.errors import resolve_error_code_mapping_key
-from skyvern.exceptions import CompletionGateTerminationError, SkyvernContextWindowExceededError, StepTerminationError
+from skyvern.exceptions import (
+ CompletionGateTerminationError,
+ MissingBrowserState,
+ MissingBrowserStatePage,
+ SkyvernContextWindowExceededError,
+ StepTerminationError,
+)
from skyvern.forge.sdk.api.llm.exceptions import LLMContentFilteredError
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
@@ -531,6 +537,17 @@ def _raised_error_class(exc: BaseException) -> ToolErrorClass:
return "handler_raised"
+def _is_browser_gone(exc: BaseException) -> bool:
+ """Whether a raise that escaped a tool handler says the browser itself is gone.
+
+ The same closed pair the block layer tests for a terminal browser loss
+ (`skyvern/forge/sdk/workflow/models/block.py`), so the loop and the block agree on what "the
+ browser is gone" means rather than carrying two spellings of it. Decided by TYPE, never by the
+ message: a page accessor's message can carry the URLs it found.
+ """
+ return isinstance(exc, (MissingBrowserState, MissingBrowserStatePage))
+
+
def mark_is_filler(mark: Any) -> bool:
# look() numbers marks from 1, so 0 addresses nothing: it is an upstream filling the optional slot,
# not the model addressing by mark. `to_openai_tool` sets the `strict` key that provokes that, so
@@ -1029,6 +1046,15 @@ NAV_DEAD_END_GUARD = "navigation_dead_end"
# A page-level handler kept asking for the page to be reloaded past the per-run cap: the page cannot
# be stabilized, and acting on it would mean acting on a page declared stale.
PAGE_REFRESH_EXHAUSTED_GUARD = "page_refresh_exhausted"
+# The browser or its page is gone: the page accessor behind every tool already tried to reopen a lost
+# tab and could not, so every later call raises the same error and the model spends turns on a browser
+# that cannot come back (SKY-18903). The only guard whose verdict is `failed` rather than `terminated`:
+# the run reached no verdict about the task, the engine lost the browser under it.
+BROWSER_LOST_GUARD = "browser_lost"
+BROWSER_LOST_EVENT = "taskv3 loop browser lost"
+BROWSER_LOST_REASON = "The run lost its connection to the browser and could not continue."
+# What the model is told about the calls queued behind the one that found the browser gone.
+BROWSER_LOST_SKIP_REASON = "the run lost its connection to the browser"
# A URL long enough to be a payload rather than a place is DROPPED from a verdict, never cut: the
# customer-facing reason is redacted by whole-value match, so a truncated URL would no longer match a
@@ -2181,7 +2207,7 @@ def _budget_exhausted_observation(cap: str, recency: ActivityRecency | None) ->
return f"{json_line}\nThe run's budget cap has tripped; this is the final turn before the run ends."
-def _guard_verdict(guard: str, reason: str) -> LoopOutcome:
+def _guard_verdict(guard: str, reason: str, *, status: Literal["failed", "terminated"] = "terminated") -> LoopOutcome:
"""The one way a loop guard ends a run: the customer-facing sentence in `reason`, the machine class
in `guard`.
@@ -2190,8 +2216,12 @@ def _guard_verdict(guard: str, reason: str) -> LoopOutcome:
that tripped, the tool that reported it and the selector it compared all belong on the guard's own
log line instead (SKY-16271). `_budget_exhausted_reason` below holds the same standard for the
budget exits.
+
+ `terminated` is the default because a guard normally reports a verdict the run reached about the
+ task (see FINISH_STATUS_TAXONOMY). A guard that reports the engine losing the browser under the
+ run reached no such verdict and passes `failed`.
"""
- return LoopOutcome("terminated", reason, guard=guard)
+ return LoopOutcome(status, reason, guard=guard)
def _verdict_url(url: Any, caller_known_urls: Collection[str]) -> str | None:
@@ -5260,6 +5290,7 @@ async def run_agent_tool_loop(
tool_started_at = time.monotonic()
st.event_seq += 1
dispatch_seq = st.event_seq
+ browser_gone = False
if spec is None:
result = ToolResult.error(f"unknown_tool: {tool_name}")
elif refuse_navigation and tool_name in URL_CHANGING_TOOLS:
@@ -5286,6 +5317,7 @@ async def run_agent_tool_loop(
exc_info=True,
**_navigate_record_fields(tool_name, args, None),
)
+ browser_gone = _is_browser_gone(exc)
raised_class = _raised_error_class(exc)
result = ToolResult.error(f"tool_error: {type(exc).__name__}: {exc}", error_class=raised_class)
tool_duration_seconds = time.monotonic() - tool_started_at
@@ -5841,6 +5873,16 @@ async def run_agent_tool_loop(
)
break
+ if browser_gone:
+ # The page accessor behind every tool already tried to reopen a lost tab and could not,
+ # so nothing the model does next can reach a page: handing this back as a tool error buys
+ # only identical raises on later turns (SKY-18903). Checked ahead of the poisoning read
+ # below, which would spend a probe on the dead page to learn what this already says.
+ LOG.info(BROWSER_LOST_EVENT, tool=tool_name, turn=st.turns, guard=BROWSER_LOST_GUARD)
+ st.outcome = _guard_verdict(BROWSER_LOST_GUARD, BROWSER_LOST_REASON, status="failed")
+ _append_skipped_tool_results(st.messages, tool_calls[idx + 1 :], BROWSER_LOST_SKIP_REASON)
+ break
+
if result.status == "error":
call_moved_page = (
tool_name == "navigate"
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index 2800b8994..5a7afbb46 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -9193,6 +9193,62 @@ async (__tv3TextArgs) => {
} catch (e) { /* fail open: the record keeps today's shape */ }
return '';
};
+ // Pressable buttons that set a form value -- a wrapper holding only pressable buttons and the checkbox, radio
+ // or hidden input they write (a Yes/No pair) -- answer one question, the way a radio group does. Without that
+ // input they are page controls (a save, view or font toggle) that their own labels name.
+ const _isToggleChoice = (el) => {
+ try {
+ const own = el.getAttribute('aria-pressed');
+ if (own !== 'true' && own !== 'false') return false;
+ const parent = _parentOf.call(el);
+ if (!parent) return false;
+ const buttons = _qsa.call(parent, 'button,[role=button]');
+ if (buttons.length < 2) return false;
+ for (const b of buttons) {
+ const p = b.getAttribute('aria-pressed');
+ if (p !== 'true' && p !== 'false') return false;
+ }
+ const inputs = _qsa.call(parent, 'input,select,textarea');
+ if (!inputs.length) return false;
+ for (const i of inputs) {
+ const t = (i.getAttribute('type') || '').toLowerCase();
+ if (t !== 'checkbox' && t !== 'radio' && t !== 'hidden') return false;
+ }
+ return true;
+ } catch (e) { return false; }
+ };
+ // A toggle pair's question is the label or legend before it in its entry, past any description or hint between
+ // them: two questions sharing one hint ("answer for this role's location") would otherwise read the same. Only a
+ // label beside that text outranks it; climbing past the first level with text or a control would reach a section
+ // legend, so the nearest text decides there.
+ const _toggleQuestion = (el) => {
+ try {
+ let node = _parentOf.call(el);
+ for (let depth = 0; node && depth < 3; depth++) {
+ let scanned = 0;
+ let stop = false;
+ for (let s = _prevOf.call(node); s && scanned < 8; s = _prevOf.call(s), scanned++) {
+ const kind = _nodeTypeOf.call(s);
+ if (kind === 3) { if (_normText(_contentOf.call(s)).length >= 2) stop = true; continue; }
+ if (kind !== 1) continue;
+ if (_matches.call(s, _CTRL_SEL) || _qs.call(s, _CTRL_SEL)) { stop = true; break; }
+ if (_unseen(s)) continue;
+ const t = _visibleText(s, 0);
+ if (t.length < 2) continue;
+ // A label is often wrapped in a title box of its own; a sibling holding no control can only caption.
+ const lab = _matches.call(s, 'label,legend') ? s : _qs.call(s, 'label,legend');
+ if (lab && !_unseen(lab)) {
+ const lt = lab === s ? t : _visibleText(lab, 0);
+ if (lt.length >= 2) return lt;
+ }
+ stop = true;
+ }
+ if (stop) break;
+ node = _parentOf.call(node);
+ }
+ } catch (e) { /* fall back to the nearest text */ }
+ return _groupText(el, false);
+ };
// A choice group's question: the legacy text for this member when it names more than the options,
// else what the page declares for the group, resolved once per group.
const _choiceGroupText = (el) => {
@@ -10631,6 +10687,7 @@ async (__tv3TextArgs) => {
return false;
};
let lastGroup = '';
+ let lastGroupToggle = false;
let groupTotal = 0;
let radioGroupsMissing = 0;
const _a11yRemoved = """
@@ -10934,6 +10991,8 @@ async (__tv3TextArgs) => {
Object.assign(rec, _stateFields(el));
if (el.getAttribute('aria-required') === 'true' || el.required) rec.required = true;
const isChoice = el.type === 'checkbox' || el.type === 'radio' || role === 'checkbox' || role === 'radio';
+ const isToggle = !isChoice && _isToggleChoice(el);
+ if (isToggle) rec.toggle_choice = true;
// Read .validity, never checkValidity(): that dispatches an 'invalid' event and perception must
// not mutate the page. Checkbox/radio .value is the static attribute ("on"), so they are excluded.
const ai = el.getAttribute('aria-invalid');
@@ -10951,7 +11010,7 @@ async (__tv3TextArgs) => {
// answer without fetching raw HTML. Deduped against the previous element to keep grouped
// options compact; capped per page so a long form cannot turn this into a second DOM dump.
// A pointer root is named by its own content; a short caption ('?') would borrow a stranger's text.
- if (!pointerRoot && (isChoice || strongLabel.length < 3)) {
+ if (!pointerRoot && (isChoice || isToggle || strongLabel.length < 3)) {
// The description is the last rung: it is routinely a per-field hint ("This field is
// required") shared by every field, which would name nothing and dedupe to nothing.
// The record carries the text at the masking width; the budget, the dedupe and the
@@ -10960,9 +11019,9 @@ async (__tv3TextArgs) => {
// that only acts it names the wrong target, as a date heading read as the name of the arrow beside it.
const takesValue = isChoice || _isFieldControl(el) || rec.autocomplete === true
|| el.hasAttribute('aria-checked') || el.hasAttribute('aria-pressed');
- const ownGroup = takesValue ? _groupText(el, isChoice) : '';
+ const ownGroup = !takesValue ? '' : isToggle ? _toggleQuestion(el) : _groupText(el, isChoice);
// Every member keeps its group's question, though the digest prints it on the first member only.
- if (isChoice && ownGroup) rec.question = ownGroup.slice(0, _RETAIN_WIDTH);
+ if ((isChoice || isToggle) && ownGroup) rec.question = ownGroup.slice(0, _RETAIN_WIDTH);
const gtFull = (ownGroup || byId('aria-describedby')).slice(0, _RETAIN_WIDTH);
const gt = gtFull.slice(0, 200);
// A slotted caption is compared at the 140 width it used to be stored at. A drawn shadow caption
@@ -10977,13 +11036,19 @@ async (__tv3TextArgs) => {
if (!g.entry.shown && groupTotal + gt.length <= _GROUP_TEXT_TOTAL_CAP) {
rec.group = gtFull;
lastGroup = gt;
+ lastGroupToggle = false;
groupTotal += gt.length;
}
g.entry.shown = true;
} else if (gt && gt.length > nameLength && gt !== lastGroup && groupTotal + gt.length <= _GROUP_TEXT_TOTAL_CAP) {
rec.group = gtFull;
lastGroup = gt;
+ lastGroupToggle = isToggle;
groupTotal += gt.length;
+ } else if (isToggle && lastGroupToggle && gt && gt === lastGroup) {
+ // Every button of a pair prints its question: one printed only on its neighbour reads as answering the
+ // question beside it. The repeat is not charged, as the budget bounds distinct question text.
+ rec.group = gtFull;
}
// Every member carries its group's number, so the digest can say once per group that no
// question was found; checkboxes are left out, being mostly self-describing consents.
@@ -13834,7 +13899,8 @@ def build_browser_tools(
# A radio or checkbox's question and caption as observe read them, for a click's answer.
"question": _mask_refs(str(e.get("question") or "")),
"option": _mask_refs(str(e.get("label") or "")),
- "choice": next((c for c in (e.get("role"), e.get("type")) if c in ("radio", "checkbox")), ""),
+ "choice": next((c for c in (e.get("role"), e.get("type")) if c in ("radio", "checkbox")), "")
+ or ("toggle" if e.get("toggle_choice") else ""),
}
# Compact rendering keeps the persistent-conversation prefix small (cost is ~linear in it).
raw_url = _mask_refs(str(data.get("url") or ""))
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 0fa676446..398e03c3e 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -29,7 +29,12 @@ import pytest
from structlog.testing import capture_logs
import skyvern.webeye.cdp_download_interceptor as cdp_module
-from skyvern.exceptions import CompletionGateTerminationError, SkyvernContextWindowExceededError, StepTerminationError
+from skyvern.exceptions import (
+ CompletionGateTerminationError,
+ MissingBrowserStatePage,
+ SkyvernContextWindowExceededError,
+ StepTerminationError,
+)
from skyvern.forge.sdk.api.llm.exceptions import LLMContentFilteredError, LLMProviderErrorRetryableTask
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
@@ -49,6 +54,9 @@ from skyvern.forge.taskv3.loop import (
ACTION_LOOP_NUDGE_AFTER,
ACTION_LOOP_TERMINATE_AFTER,
ACTION_OUTCOME_DATA_KEY,
+ BROWSER_LOST_EVENT,
+ BROWSER_LOST_GUARD,
+ BROWSER_LOST_REASON,
CLICK_DISPATCHED_DATA_KEY,
CODE_TOOL_NAME,
COMPLETION_GATE_REFUSAL,
@@ -12184,6 +12192,47 @@ async def test_a_handler_that_raises_still_reports_the_time_it_spent_resolving_t
assert "resolve_seconds" not in by_tool["finish"]
+async def test_a_lost_browser_ends_the_run_where_any_other_raise_comes_back_as_a_tool_error() -> None:
+ # SKY-18903: the page accessor behind every tool raises MissingBrowserStatePage only after its own
+ # reopen attempt failed, so handing that back as a tool error bought 7-9 identical errors and four
+ # more model turns per task on a browser that cannot come back. The arms are in ONE script because
+ # the whole claim is the discriminator: a generic raise must still be a retryable tool error (turn 1
+ # is answered and the run reaches turn 2), and only the browser-gone class ends the run.
+ observe_calls: list[tuple[str, dict[str, Any]]] = []
+ type_calls: list[tuple[str, dict[str, Any]]] = []
+
+ async def browser_is_gone(args: dict[str, Any]) -> ToolResult:
+ raise MissingBrowserStatePage(task_id="tsk_lost")
+
+ tools = [
+ _recording_tool("type", type_calls, raises=True, billable=True),
+ ToolSpec(name="click", description="c", parameters={}, handler=browser_is_gone, billable=True),
+ _recording_tool("observe", observe_calls),
+ make_finish_tool(),
+ ]
+ script = [
+ [("type", {"selector": "#a", "text": "x"})],
+ [("click", {"selector": "#b"}), ("observe", {})],
+ [("finish", {"status": "completed", "reason": "never reached"})],
+ ]
+ with capture_logs() as logs:
+ outcome, caller = await _run(script, tools)
+
+ assert (outcome.status, outcome.guard) == ("failed", BROWSER_LOST_GUARD)
+ # Verbatim: this leaves the system as the task's customer-visible failure_reason.
+ assert outcome.reason == BROWSER_LOST_REASON
+ # Two turns, not three: the model was never asked to act on the dead browser again.
+ assert caller.calls == 2
+ # The sibling queued behind it never ran, and its tool_call id is still answered.
+ assert observe_calls == []
+ assert [content.startswith("skipped:") for content in _tool_contents(outcome, "observe")] == [True]
+ # The control arm: the generic raise was answered as an error the model could read and retry past.
+ assert any("tool_error: RuntimeError" in content for content in _tool_contents(outcome, "type"))
+ (lost,) = (entry for entry in logs if entry["event"] == BROWSER_LOST_EVENT)
+ assert (lost["guard"], lost["tool"]) == (BROWSER_LOST_GUARD, "click")
+
+
def test_every_driver_timeout_type_installed_here_classifies_as_a_driver_timeout() -> None:
# Written against the driver-type TABLE rather than a hard-coded package, because the hazard is
# precisely that CI and production do not install the same driver: the browser image repoints
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 625af3425..ce2fc5f03 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -5801,6 +5801,55 @@ async def test_click_on_a_choice_option_names_the_question_observe_bound_it_to()
assert by_selector.content.endswith("\npicked this option for an unknown question"), by_selector.content
+@_skip_no_browser
+async def test_yes_no_toggle_buttons_name_their_question_and_echo_it_but_page_toggles_do_not() -> None:
+ # Adjacent Yes/No pairs of pressable buttons: with the question on the "No" alone, the model paired the
+ # unlabeled "Yes" with the question beside it and pressed the wrong button.
+ questions = (
+ "Are you legally authorized to work in this country?",
+ "Will you now or in the future require visa sponsorship?",
+ )
+ pair = (
+ "<div class='yesno'><button type='button' aria-pressed='false'>Yes</button>"
+ "<button type='button' aria-pressed='false'>No</button><input type='checkbox' hidden></div>"
+ )
+ # Both questions share one hint between their label and their buttons; the hint names neither question.
+ hint = "<div class='hint'><p>Answer for the country where this role is located.</p></div>"
+ # The second label sits in a title box of its own, a common layout.
+ labels = (f"<label>{questions[0]}</label>", f"<div class='title'><label>{questions[1]}</label></div>")
+ entries = "".join(f"<div class='entry'>{label}{hint}{pair}</div>" for label in labels)
+ # A pair whose question is plain text, in a section whose legend titles the section and asks nothing.
+ unlabeled = "Are you at least 18 years old?"
+ section = (
+ f"<fieldset><legend>Work eligibility</legend><div class='entry'><div>{unlabeled}</div>{pair}</div></fieldset>"
+ )
+ # Pressable buttons that set no form value are page controls; the card title beside them is not a question.
+ card = (
+ "<div class='card'><h3>Blue road bike</h3><div class='actions'>"
+ "<button type='button' aria-pressed='false'>Save this bike</button>"
+ "<button type='button' aria-pressed='false'>Track price on this bike</button></div></div>"
+ )
+ async with _live_page(f"<!doctype html><html><body><form>{entries}{section}</form>{card}</body></html>") as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ buttons = re.findall(r"^ref=(\d+) button\S* '(Yes|No)'.*?(?: group='([^']*)')?$", r.content, re.M)
+ assert [(label, group) for _, label, group in buttons] == [
+ (label, q) for q in (*questions, unlabeled) for label in ("Yes", "No")
+ ], r.content
+ page_toggles = [line for line in r.content.splitlines() if line.startswith("ref=") and "this bike'" in line]
+ assert len(page_toggles) == 2 and not any(" group=" in line for line in page_toggles), r.content
+ sponsorship_yes = next(ref for ref, label, group in buttons if label == "Yes" and group == questions[1])
+ clicked = await _tool(tools, "click").handler({"selector": f"ref={sponsorship_yes}"})
+ save = re.search(r"^ref=(\d+) button\S* 'Save this bike'", r.content, re.M)
+ assert save, r.content
+ saved = await _tool(tools, "click").handler({"selector": f"ref={save.group(1)}"})
+ assert clicked.status == "ok" and clicked.content.endswith(f"\nclicked 'Yes' for question {questions[1]!r}"), (
+ clicked.content
+ )
+ assert saved.status == "ok" and "question" not in saved.content, saved.content
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_click_echo_stays_silent_when_the_pick_could_not_be_confirmed() -> None:
diff --git a/tests/unit/workflow/test_block_anti_bot_retry.py b/tests/unit/workflow/test_block_anti_bot_retry.py
new file mode 100644
index 000000000..2f28b7f89
--- /dev/null
+++ b/tests/unit/workflow/test_block_anti_bot_retry.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.schemas.tasks import TaskStatus
+from skyvern.forge.sdk.workflow.models import block as block_module
+from skyvern.forge.sdk.workflow.models.block import Block, TaskBlock
+from tests.unit._task_block_fakes import mock_block_execute_deps, output_parameter
+from tests.unit.helpers import make_organization, make_task
+
+
+ "failure_category",
+ [None, [{"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9, "reasoning": "captcha"}]],
+ ids=["classified_from_reason", "recorded_category"],
+)
+async def test_a_task_block_failing_on_captcha_text_retries_as_configured(failure_category: list | None) -> None:
+ block = TaskBlock(
+ label="nav",
+ url="https://example.com",
+ navigation_goal="go",
+ output_parameter=output_parameter(),
+ max_retries=1,
+ )
+ now = datetime.now(timezone.utc)
+ organization = make_organization(now)
+ first = make_task(
+ now,
+ organization,
+ task_id="tsk_first",
+ status=TaskStatus.failed,
+ failure_reason="Page blocked by captcha challenge",
+ failure_category=failure_category,
+ )
+ second = make_task(now, organization, task_id="tsk_second", status=TaskStatus.completed)
+
+ with (
+ skyvern_context.scoped(SkyvernContext()),
+ mock_block_execute_deps(working_page_url="https://example.com") as deps,
+ patch.object(Block, "record_output_parameter_value", new_callable=AsyncMock),
+ ):
+ deps.browser_manager.get_for_workflow_run = MagicMock(return_value=None)
+ deps.tasks_db.get_last_task_for_workflow_run = AsyncMock(side_effect=[None, first])
+ deps.tasks_db.get_task = AsyncMock(side_effect=[first, second])
+ deps.agent.create_task_and_step_from_block = AsyncMock(
+ side_effect=[(first, SimpleNamespace(step_id="stp_first")), (second, SimpleNamespace(step_id="stp_second"))]
+ )
+ block_module.app.STORAGE = MagicMock(
+ get_current_attempt_downloaded_files=AsyncMock(return_value=[]),
+ get_downloaded_file_signature_aliases=MagicMock(return_value=()),
+ )
+ block_module.app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts = AsyncMock(return_value=[])
+ block_module.app.WORKFLOW_SERVICE.get_recent_workflow_screenshot_artifacts = AsyncMock(return_value=[])
+
+ result = await block.execute(
+ workflow_run_id="wr_task_block_test", workflow_run_block_id="wrb_test", organization_id="o_test"
+ )
+
+ assert result.success is True
diff --git a/tests/unit/workflow/test_block_anti_bot_retry_skip.py b/tests/unit/workflow/test_block_anti_bot_retry_skip.py
deleted file mode 100644
index 6e1410645..000000000
--- a/tests/unit/workflow/test_block_anti_bot_retry_skip.py
+++ /dev/null
@@ -1,189 +0,0 @@
-from __future__ import annotations
-
-from datetime import datetime, timezone
-
-import pytest
-
-from skyvern.exceptions import (
- BrowserSessionDegraded,
- MissingBrowserStatePage,
- ScreenshotTargetClosed,
- get_user_facing_exception_message,
-)
-from skyvern.forge.failure_classifier import bounded_failure_categories, classify_from_failure_reason
-from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
-from skyvern.forge.sdk.workflow.models.block import _should_skip_retry_on_anti_bot_detection
-
-
-def _make_failed_task(
- *,
- failure_reason: str | None = None,
- failure_category: list[dict] | None = None,
-) -> Task:
- now = datetime.now(timezone.utc)
- return Task(
- task_id="tsk_test",
- organization_id="o_test",
- url="https://example.com/login",
- created_at=now,
- modified_at=now,
- status=TaskStatus.failed,
- failure_reason=failure_reason,
- failure_category=failure_category,
- )
-
-
-class TestPersistedCategory:
- def test_primary_anti_bot_category_skips_retry(self) -> None:
- task = _make_failed_task(
- failure_category=[
- {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9, "reasoning": "captcha"},
- ],
- )
- assert _should_skip_retry_on_anti_bot_detection(task) is True
-
- def test_anti_bot_secondary_position_still_skips_retry(self) -> None:
- task = _make_failed_task(
- failure_category=[
- {"category": "MAX_STEPS_EXCEEDED", "confidence_float": 0.9, "reasoning": "max"},
- {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.7, "reasoning": "captcha"},
- ],
- )
- assert _should_skip_retry_on_anti_bot_detection(task) is True
-
- def test_auth_failure_does_not_skip_retry(self) -> None:
- task = _make_failed_task(
- failure_category=[
- {"category": "AUTH_FAILURE", "confidence_float": 0.9, "reasoning": "bad password"},
- ],
- )
- assert _should_skip_retry_on_anti_bot_detection(task) is False
-
- @pytest.mark.parametrize("model_category", ["SITE_BLOCKED_ME", " anti_bot_detection "])
- def test_unrecognized_model_category_does_not_suppress_captcha_retries(self, model_category: str) -> None:
- categories = bounded_failure_categories([{"category": model_category}])
- task = _make_failed_task(
- failure_category=categories,
- failure_reason="The page showed a captcha challenge",
- )
-
- assert categories[0]["category"] == "UNKNOWN"
- assert _should_skip_retry_on_anti_bot_detection(task) is False
-
- def test_persisted_primary_wins_over_reason_keywords(self) -> None:
- """A persisted non-anti-bot primary must NOT be overridden by reason text.
-
- Example: persisted AUTH_FAILURE whose reason happens to mention a captcha;
- retry should still proceed because the persisted classification is the
- authoritative signal.
- """
- task = _make_failed_task(
- failure_category=[
- {"category": "AUTH_FAILURE", "confidence_float": 0.9, "reasoning": "bad password"},
- ],
- failure_reason="Login failed; the page also showed a captcha challenge after submit",
- )
- assert _should_skip_retry_on_anti_bot_detection(task) is False
-
-
-class TestFallbackFromReason:
- def test_keyword_reason_skips_retry_when_no_category(self) -> None:
- task = _make_failed_task(failure_reason="Page blocked by captcha challenge")
- assert _should_skip_retry_on_anti_bot_detection(task) is True
-
- def test_managed_challenge_service_reason_skips_retry(self) -> None:
- task = _make_failed_task(failure_reason="Bot detection service blocked access")
- assert _should_skip_retry_on_anti_bot_detection(task) is True
-
- def test_max_steps_with_captcha_in_reason_skips_retry(self) -> None:
- """Exact ticket scenario for tasks without a persisted category list.
-
- The agent stores max_steps failures as 'Reached the maximum steps (...)'.
- That phrase ranks higher in the classifier than the captcha keyword,
- so [0] is MAX_STEPS_EXCEEDED and [1] is ANTI_BOT_DETECTION. The fallback
- must still recognize the anti-bot signal in any position.
- """
- task = _make_failed_task(
- failure_reason=(
- "Reached the maximum steps (10). Possible failure reasons: "
- "the page presented a captcha challenge after the login form submit"
- ),
- )
- assert _should_skip_retry_on_anti_bot_detection(task) is True
-
- def test_benign_reason_does_not_skip_retry(self) -> None:
- task = _make_failed_task(failure_reason="Could not find the submit button on the page")
- assert _should_skip_retry_on_anti_bot_detection(task) is False
-
- def test_no_reason_and_no_category_does_not_skip_retry(self) -> None:
- task = _make_failed_task()
- assert _should_skip_retry_on_anti_bot_detection(task) is False
-
- def test_access_denied_with_auth_context_does_not_skip(self) -> None:
- """Auth-context 'access denied' classifies as AUTH_FAILURE, not bot detection."""
- task = _make_failed_task(
- failure_reason="Access denied after login - user does not have permission",
- )
- assert _should_skip_retry_on_anti_bot_detection(task) is False
-
-
-# Each decision was recorded from the classifier before site rate-limit and 403 wording was labeled anti-bot and
-# before integration throttles were labeled website errors. Those labels are bookkeeping: a failure that kept its
-# retries then must keep them now, and one that skipped them must still skip them.
- ("reason", "skips_retry"),
- [
- pytest.param(
- "Failed to send the form because a captcha appeared", True, id="captcha-reason-worded-like-integration"
- ),
- pytest.param("HTTP request failed: 429 Too Many Requests", False, id="http-request-throttle"),
- pytest.param(
- "The site returned Cloudflare Error 1015 (HTTP 429: temporarily rate limited/banned).",
- True,
- id="cloudflare-keyword-with-429",
- ),
- pytest.param("Page indicates 403 error or rate limit; cannot proceed.", False, id="hedged-403-or-rate-limit"),
- pytest.param("The site says this page was requested too many times.", False, id="requested-too-many-times"),
- pytest.param("The site returned a 403 Forbidden page.", False, id="forbidden-page"),
- pytest.param("Google Sheets rate limit on write: quota exceeded", False, id="sheets-quota"),
- pytest.param("Page blocked by captcha challenge", True, id="captcha"),
- pytest.param("Access denied: rate limit exceeded", True, id="access-denied-with-rate-limit"),
- ],
-)
-def test_site_throttle_labeling_does_not_change_the_retry_decision(reason: str, skips_retry: bool) -> None:
- from_reason = _make_failed_task(failure_reason=reason)
- from_persisted = _make_failed_task(failure_category=classify_from_failure_reason(reason, fallback_to_unknown=True))
-
- assert _should_skip_retry_on_anti_bot_detection(from_reason) is skips_retry
- assert _should_skip_retry_on_anti_bot_detection(from_persisted) is skips_retry
-
-
-_BROWSER_LOSSES = [
- pytest.param(MissingBrowserStatePage(), id="page-missing"),
- pytest.param(ScreenshotTargetClosed("Target page, context or browser has been closed"), id="target-closed"),
- pytest.param(BrowserSessionDegraded(3, "screenshot"), id="browser-degraded"),
-]
-
-
[email protected]("browser_loss", _BROWSER_LOSSES)
- "reason_suffix",
- [
- pytest.param("", id="exception-message-only"),
- pytest.param(" A captcha challenge was still on the page.", id="reason-also-names-a-captcha"),
- ],
-)
-def test_the_unsolved_captcha_relabel_leaves_the_retry_decision_unchanged(
- browser_loss: Exception, reason_suffix: str
-) -> None:
- """Categorization is output-only: relabeling a browser loss as anti-bot must not stop a block retry."""
- reason = get_user_facing_exception_message(browser_loss) + reason_suffix
- before = classify_from_failure_reason(reason, exception=browser_loss, fallback_to_unknown=True)
- after = classify_from_failure_reason(
- reason, exception=browser_loss, fallback_to_unknown=True, unsolved_captcha_exception="CaptchaNotSolvedInTime"
- )
-
- assert after is not None and after[0]["category"] == "ANTI_BOT_DETECTION"
- assert _should_skip_retry_on_anti_bot_detection(
- _make_failed_task(failure_reason=reason, failure_category=after)
- ) is _should_skip_retry_on_anti_bot_detection(_make_failed_task(failure_reason=reason, failure_category=before))