Skip to content

Automate browser based workflows with AI

Stop the copilot being cut off mid-repair after 35 model calls (SKY-13734) (#8166)

Andrew Neilson3c0d5da84171
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index b625aca00..8f6a81ece 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -10568,6 +10568,20 @@
"title": "Parameters",
"default": []
},
+ "error_code_mapping": {
+ "anyOf": [
+ {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error Code Mapping"
+ },
"prompt": {
"anyOf": [
{
@@ -10781,6 +10795,20 @@
],
"title": "Parameter Keys"
},
+ "error_code_mapping": {
+ "anyOf": [
+ {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error Code Mapping"
+ },
"prompt": {
"anyOf": [
{
diff --git a/skyvern/cli/commands/browser.py b/skyvern/cli/commands/browser.py
index 866aec4e5..9b4131769 100644
--- a/skyvern/cli/commands/browser.py
+++ b/skyvern/cli/commands/browser.py
@@ -829,7 +829,7 @@ def navigate(
cli_state.frame_name = None
cli_state.frame_index = None
save_state(cli_state)
- return {"url": result.url, "title": result.title}
+ return {"url": result.url, "title": result.title, "load_state": result.load_state}
try:
data = asyncio.run(_run())
diff --git a/skyvern/cli/core/browser_ops.py b/skyvern/cli/core/browser_ops.py
index 72be6460c..a988de9ae 100644
--- a/skyvern/cli/core/browser_ops.py
+++ b/skyvern/cli/core/browser_ops.py
@@ -17,13 +17,14 @@ from pathlib import Path
from typing import Any, Callable, Literal
import structlog
+from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from skyvern.exceptions import BlockedHost, SkyvernHTTPException
from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.utils.url_validators import validate_fetch_url
from skyvern.webeye.utils.page import JS_FUNCTION_DEFS, SkyvernFrame
-from .guards import CREDENTIAL_HINT, GuardError
+from .guards import CREDENTIAL_HINT, GuardError, validate_wait_until
LOG = structlog.get_logger(__name__)
@@ -68,10 +69,18 @@ LOCALHOST_RECOVERY_HINT = (
)
+# Lifecycle states in ascending strength. A document that has committed is really there even
+# when a later state never arrives, so navigation degrades down this ladder rather than
+# reporting a failure for a page that is already loaded and usable.
+_LOAD_STATE_LADDER = ("commit", "domcontentloaded", "load", "networkidle")
+_WEAKER_LOAD_STATE_TIMEOUT_MS = 1000
+
+
@dataclass
class NavigateResult:
url: str
title: str
+ load_state: str = "load"
@dataclass
@@ -104,6 +113,25 @@ def parse_extract_schema(schema: str | dict[str, Any] | None) -> dict[str, Any]
raise GuardError(f"Invalid JSON schema: {e}", "Provide schema as a valid JSON string")
+async def _reached_load_state(page: Any, requested: str, budget_ms: int) -> str:
+ """Return the strongest lifecycle state the committed document actually reached.
+
+ Anything below ``requested`` is probed briefly: those states have already fired in
+ every healthy navigation, so the short budget only bounds a document that stalled.
+ """
+ weaker_states = _LOAD_STATE_LADDER[1 : _LOAD_STATE_LADDER.index(requested) + 1]
+ for index, state in enumerate(reversed(weaker_states)):
+ try:
+ await page.wait_for_load_state(
+ state,
+ timeout=budget_ms if index == 0 else _WEAKER_LOAD_STATE_TIMEOUT_MS,
+ )
+ except PlaywrightTimeoutError:
+ continue
+ return state
+ return "commit"
+
+
async def do_navigate(
page: Any,
url: str,
@@ -113,6 +141,7 @@ async def do_navigate(
can_access_localhost: bool = False,
is_localhost_destination: bool = False,
) -> NavigateResult:
+ validate_wait_until(wait_until)
try:
validated_url = await asyncio.to_thread(validate_fetch_url, url)
except BlockedHost as e:
@@ -122,8 +151,19 @@ async def do_navigate(
validated_url = url
except SkyvernHTTPException as e:
raise GuardError(str(e), "Use a valid public HTTP(S) URL") from e
- await page.goto(validated_url, timeout=timeout, wait_until=wait_until)
- return NavigateResult(url=page.url, title=await page.title())
+
+ # Commit first so a navigation that never reaches the document still fails, then wait for
+ # the requested lifecycle state separately: a page whose `load` never fires is navigated,
+ # not failed, and reporting the weaker state beats a false failure on a usable page.
+ started = time.monotonic()
+ await page.goto(validated_url, timeout=timeout, wait_until="commit")
+ requested = wait_until or "load"
+ load_state = "commit"
+ if requested != "commit":
+ # Floor the leftover budget: Playwright reads timeout=0 as "wait forever".
+ remaining_ms = max(timeout - int((time.monotonic() - started) * 1000), _WEAKER_LOAD_STATE_TIMEOUT_MS)
+ load_state = await _reached_load_state(page, requested, remaining_ms)
+ return NavigateResult(url=page.url, title=await page.title(), load_state=load_state)
async def do_screenshot(
diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.py
index 121eee3ac..c7a39a1e0 100644
--- a/skyvern/cli/mcp_tools/browser.py
+++ b/skyvern/cli/mcp_tools/browser.py
@@ -554,10 +554,25 @@ async def skyvern_navigate(
# second bump can invalidate its snapshot of the old document.
clear_session_ref_map(session_id=ctx.session_id, cdp_url=ctx.cdp_url)
+ requested_load_state = wait_until or "load"
+ warnings = (
+ []
+ if result.load_state == requested_load_state
+ else [
+ f"Navigation succeeded but the page never reached '{requested_load_state}'; "
+ f"it settled at '{result.load_state}'. The page is loaded — retrying the navigation will not help."
+ ]
+ )
return action_result(
"skyvern_navigate",
browser_context=ctx,
- data={"url": result.url, "title": result.title, "sdk_equivalent": f"await page.goto({url!r})"},
+ data={
+ "url": result.url,
+ "title": result.title,
+ "load_state": result.load_state,
+ "sdk_equivalent": f"await page.goto({url!r})",
+ },
+ warnings=warnings,
timing_ms=timer.timing_ms,
)
@@ -2500,6 +2515,7 @@ async def _run_paired_capture(
data: dict[str, Any] = {}
artifacts: list[dict[str, Any]] = []
sdk_equivalents: list[str] = []
+ warnings: list[str] = []
error: dict[str, Any] | None = None
skip_to_screenshot = False
@@ -2507,6 +2523,9 @@ async def _run_paired_capture(
if skip_to_screenshot and operation != "screenshot":
continue
operation_result = await operation_functions[operation](**params, session_id=session_id, cdp_url=cdp_url)
+ operation_warnings = operation_result.get("warnings")
+ if isinstance(operation_warnings, list):
+ warnings.extend(item for item in operation_warnings if isinstance(item, str))
operation_data = operation_result.get("data")
if isinstance(operation_data, dict) and isinstance(operation_data.get("sdk_equivalent"), str):
sdk_equivalents.append(operation_data["sdk_equivalent"])
@@ -2542,6 +2561,7 @@ async def _run_paired_capture(
ok=error is None,
browser_context=ctx,
data=data,
+ warnings=warnings,
error=error,
timing_ms={"total": int((time.perf_counter() - started_at) * 1000)},
)
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 2e78c8dba..8626e5706 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -78,6 +78,7 @@ from skyvern.forge.sdk.copilot.completion_criteria_store import (
)
from skyvern.forge.sdk.copilot.completion_verification import only_structural_requested_output_abstentions
from skyvern.forge.sdk.copilot.config import (
+ DEFAULT_MAX_TURNS,
SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD,
BlockAuthoringPolicy,
CopilotConfig,
@@ -113,6 +114,7 @@ from skyvern.forge.sdk.copilot.credential_literal_rebind import (
from skyvern.forge.sdk.copilot.credential_pause import credential_pause_reason, preflight_credential_pause
from skyvern.forge.sdk.copilot.data_write_defaults import default_data_write_continue_on_failure
from skyvern.forge.sdk.copilot.enforcement import (
+ _elapsed_run_seconds,
artifact_health_blocked,
dump_derivation_inputs,
log_scouted_spine_unresolved_at_turn_halt,
@@ -1918,6 +1920,15 @@ def _attempted_summary(narrative_summary: object, narrative_payload: object) ->
return None
+def _terminal_cause_for_context(ctx: CopilotContext) -> TerminalCause | None:
+ # The deadline owns capacity, so it wins if both capacity latches are set.
+ if ctx.copilot_total_timeout_exceeded is True:
+ return "deadline_expired"
+ if ctx.copilot_max_turns_exceeded is True:
+ return "max_turns_exceeded"
+ return None
+
+
def _assemble_terminal_envelope_safe(
*,
response_type: str,
@@ -2080,7 +2091,7 @@ def _make_agent_result(
workflow_mutated=bool(kwargs.get("workflow_was_persisted")) or kwargs.get("updated_workflow") is not None,
turn_outcome_response_kind=turn_outcome_response_kind,
final_message=str(kwargs.get("user_response") or ""),
- terminal_cause="deadline_expired" if ctx.copilot_total_timeout_exceeded is True else None,
+ terminal_cause=_terminal_cause_for_context(ctx),
)
kwargs["terminal_envelope"] = terminal_envelope
result = AgentResult(global_llm_context=final_context, turn_outcome=turn_outcome, **kwargs)
@@ -3336,6 +3347,19 @@ def _build_max_turns_exit_result(ctx: CopilotContext, global_llm_context: str |
)
+def _handle_max_turns_exceeded(ctx: CopilotContext, global_llm_context: str | None) -> AgentResult:
+ ctx.copilot_max_turns_exceeded = True
+ start_monotonic = ctx.copilot_run_start_monotonic
+ LOG.warning(
+ "copilot_max_turns_exceeded",
+ limit=ctx.copilot_config.max_turns if ctx.copilot_config is not None else DEFAULT_MAX_TURNS,
+ iteration=ctx.enforcement_pass_count,
+ elapsed_seconds=round(_elapsed_run_seconds(ctx, start_monotonic), 3) if start_monotonic is not None else 0.0,
+ model_call_count=ctx.model_calls_this_turn,
+ )
+ return _build_max_turns_exit_result(ctx, global_llm_context)
+
+
def _build_unexpected_error_exit_result(
ctx: CopilotContext,
global_llm_context: str | None,
@@ -5391,7 +5415,7 @@ async def _run_copilot_turn_impl(
)
return _build_turn_halt_exit_result(ctx, global_llm_context, exc.halt)
except MaxTurnsExceeded:
- return _build_max_turns_exit_result(ctx, global_llm_context)
+ return _handle_max_turns_exceeded(ctx, global_llm_context)
except CopilotTotalTimeoutError:
return _build_timeout_exit_result(ctx, global_llm_context)
except CopilotUnrecoverableToolError as exc:
diff --git a/skyvern/forge/sdk/copilot/config.py b/skyvern/forge/sdk/copilot/config.py
index 78f5150f1..63e65d532 100644
--- a/skyvern/forge/sdk/copilot/config.py
+++ b/skyvern/forge/sdk/copilot/config.py
@@ -34,7 +34,7 @@ def download_scout_act_required_for_policy(block_authoring_policy: BlockAuthorin
DEFAULT_PROMPT_TEMPLATE = "workflow-copilot-agent.j2"
-DEFAULT_MAX_TURNS = 35
+DEFAULT_MAX_TURNS = 200
DEFAULT_TOKEN_BUDGET = 90_000
SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD = 3
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 3f13e6dab..3f1b910a5 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -772,6 +772,9 @@ class CopilotContext(AgentContext):
format_nudge_count: int = 0
no_workflow_nudge_count: int = 0
copilot_total_timeout_exceeded: bool = False
+ copilot_max_turns_exceeded: bool = False
+ model_calls_this_turn: int = 0
+ enforcement_pass_count: int = 0
user_message: str = ""
block_goal_main_goal: str = ""
allow_untested_workflow_draft: bool = False
diff --git a/skyvern/forge/sdk/copilot/hooks.py b/skyvern/forge/sdk/copilot/hooks.py
index 723e99303..d74d64045 100644
--- a/skyvern/forge/sdk/copilot/hooks.py
+++ b/skyvern/forge/sdk/copilot/hooks.py
@@ -7,9 +7,10 @@ from collections.abc import Mapping
from typing import TYPE_CHECKING, Any
import structlog
-from agents.agent import Agent
+from agents.agent import Agent, AgentBase
+from agents.items import TResponseInputItem
from agents.lifecycle import RunHooksBase
-from agents.run_context import RunContextWrapper
+from agents.run_context import AgentHookContext, RunContextWrapper
from agents.tool import Tool
from skyvern.forge.sdk.copilot.enforcement import (
@@ -75,6 +76,32 @@ class CopilotRunHooks(RunHooksBase):
def __init__(self, ctx: CopilotContext) -> None:
self._ctx = ctx
+ async def on_llm_start(
+ self,
+ context: RunContextWrapper,
+ agent: Agent,
+ system_prompt: str | None,
+ input_items: list[TResponseInputItem],
+ ) -> None:
+ try:
+ self._ctx.model_calls_this_turn += 1
+ except Exception:
+ LOG.warning(
+ "CopilotRunHooks.on_llm_start counting failed",
+ **_copilot_log_fields(self._ctx),
+ exc_info=True,
+ )
+
+ async def on_agent_start(self, context: AgentHookContext, agent: AgentBase) -> None:
+ try:
+ self._ctx.enforcement_pass_count += 1
+ except Exception:
+ LOG.warning(
+ "CopilotRunHooks.on_agent_start counting failed",
+ **_copilot_log_fields(self._ctx),
+ exc_info=True,
+ )
+
async def on_tool_end(
self,
context: RunContextWrapper,
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 1e383b29d..f0b071e9e 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -311,6 +311,9 @@ class AgentContext:
post_update_nudge_count: int = 0
format_nudge_count: int = 0
copilot_total_timeout_exceeded: bool = False
+ copilot_max_turns_exceeded: bool = False
+ model_calls_this_turn: int = 0
+ enforcement_pass_count: int = 0
failed_test_nudge_count: int = 0
explore_without_workflow_nudge_count: int = 0
last_test_ok: bool | None = None
diff --git a/skyvern/forge/sdk/copilot/terminal_envelope.py b/skyvern/forge/sdk/copilot/terminal_envelope.py
index 16bfeb8c1..6ebf7ecba 100644
--- a/skyvern/forge/sdk/copilot/terminal_envelope.py
+++ b/skyvern/forge/sdk/copilot/terminal_envelope.py
@@ -12,7 +12,7 @@ LOG = structlog.get_logger(__name__)
TerminalNextState = Literal["completed", "proposal_pending", "awaiting_user_input", "stopped"]
TerminalResponseKind = Literal["question", "update", "answer", "stopped"]
-TerminalCause = Literal["deadline_expired"]
+TerminalCause = Literal["deadline_expired", "max_turns_exceeded"]
_FINAL_RUN_VERDICTS = frozenset({"demonstrated", "not_demonstrated", "not_evaluated"})
_REVIEW_PROPOSAL_DISPOSITIONS = frozenset({"review_untested", "review_tested"})
_SHADOW_REASON_TRAILING_PUNCTUATION = ".,;:!?"
diff --git a/skyvern/forge/sdk/core/http_request_authorization.py b/skyvern/forge/sdk/core/http_request_authorization.py
index 8fa5cc5f6..89621bbb0 100644
--- a/skyvern/forge/sdk/core/http_request_authorization.py
+++ b/skyvern/forge/sdk/core/http_request_authorization.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
-from typing import TypeAlias, TypeVar
+from typing import Any, TypeAlias, TypeVar
T = TypeVar("T")
@@ -64,3 +64,12 @@ async def deny_unenrolled_redirect_hop(
the network.
"""
raise RuntimeError("Redirect hop authorization is not enrolled for this browser session")
+
+
+def is_unenrolled_redirect_hop_authorizer(authorizer: RedirectHopAuthorizer[Any]) -> bool:
+ """Whether this authorizer is the unenrolled sentinel, which denies every hop it is given.
+
+ Call sites use this to report an unenrolled seam as its own operational state instead of
+ surfacing the sentinel's denial as an indistinguishable transport failure.
+ """
+ return authorizer is deny_unenrolled_redirect_hop
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index a82bf5b7f..fe7be9ca2 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -59,6 +59,7 @@ from skyvern.constants import (
PDF_OCR_PAGE_CONCURRENCY,
SAVE_DOWNLOADED_FILES_TIMEOUT,
)
+from skyvern.errors.errors import UserDefinedError
from skyvern.exceptions import (
AzureConfigurationError,
BranchEvaluationContextTooLargeError,
@@ -454,6 +455,17 @@ def build_block_failure_output(failure_reason: str, error_codes: Sequence[str])
}
+def build_user_defined_error_output(error_code: str, reasoning: str) -> dict[str, Any]:
+ """<label>_output payload for a declared ErrorCode raise (SKY-13668): a UserDefinedError
+ entry with confidence 1.0, matching UserDefinedError's own serialized shape."""
+ error = UserDefinedError(error_code=error_code, reasoning=reasoning, confidence_float=1.0)
+ return {
+ "status": BlockStatus.failed.value,
+ "failure_reason": reasoning,
+ "errors": [error.model_dump(mode="json")],
+ }
+
+
class Block(BaseModel, abc.ABC):
"""Base class for workflow nodes (see branching spec [[s-4bnl]] for metadata semantics)."""
@@ -3774,6 +3786,18 @@ class CodeBlockCaptchaError(Exception):
"""Sanitized CAPTCHA-primitive error with no site, selector, vendor, or token details."""
+class ErrorCode(Exception):
+ """Caller-declared business error a code block can raise for a condition named in its
+ error_code_mapping manifest (SKY-13668). ``code`` must be a manifest key to be surfaced
+ as a USER_DEFINED_ERROR; otherwise it fails closed like any other unclassified exception.
+ """
+
+ def __init__(self, code: str, reasoning: str) -> None:
+ self.error_code = code
+ self.reasoning = reasoning
+ super().__init__(f"{code}: {reasoning}")
+
+
CODE_BLOCK_TAB_OPEN_FAILURE_REASON = "Code block could not open a tab in the browser session; the session's browser may be held by another Playwright client"
@@ -4197,6 +4221,7 @@ class CodeBlock(Block):
code: str
parameters: list[PARAMETER_TYPE] = []
+ error_code_mapping: dict[str, str] | None = None
prompt: str | None = None
steps: list[CodeBlockStep] | None = None
@@ -4250,6 +4275,7 @@ class CodeBlock(Block):
"json": SimpleNamespace(dumps=json.dumps, loads=json.loads),
"html": SimpleNamespace(escape=html.escape),
"Exception": Exception,
+ "ErrorCode": ErrorCode,
"otp": _code_block_otp_builtin,
"solve_captcha": _code_block_solve_captcha_builtin,
}
@@ -5228,6 +5254,8 @@ async def wrapper({default_args}):
organization_id: str | None,
browser_state: BrowserState | None,
page: Page | None,
+ output_parameter_value: dict[str, Any] | list | str | None = None,
+ error_codes: list[str] | None = None,
) -> BlockResult:
"""Fail a code block after recording the page it died on.
@@ -5245,10 +5273,11 @@ async def wrapper({default_args}):
return await self.build_block_result(
success=False,
failure_reason=failure_reason,
- output_parameter_value=None,
+ output_parameter_value=output_parameter_value,
status=status,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
+ error_codes=error_codes,
)
async def _resolve_failure_with_heal(
@@ -5960,6 +5989,27 @@ async def wrapper({default_args}):
browser_state=browser_state,
page=page,
)
+ if isinstance(e, ErrorCode) and self.error_code_mapping and e.error_code in self.error_code_mapping:
+ # A declared business error: skip self-heal entirely (it's an intentional
+ # outcome, not an unexpected failure to recover from) and shape the output as a
+ # USER_DEFINED_ERROR. An undeclared code, or ErrorCode with no manifest at all,
+ # falls through unchanged into the ordinary exception path below.
+ await recorder.persist(recorder.recorded_actions())
+ await recorder.finalize(success=False)
+ reasoning = workflow_run_context.mask_secrets_in_data(e.reasoning)
+ failure_output = build_user_defined_error_output(e.error_code, reasoning)
+ return await self._failed_result_with_evidence(
+ failure_reason=reasoning,
+ status=BlockStatus.failed,
+ workflow_run_context=workflow_run_context,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ browser_state=browser_state,
+ page=page,
+ output_parameter_value=failure_output,
+ error_codes=[e.error_code],
+ )
exc = CustomizedCodeException(e)
failing_line = user_code_line_from_exception(e)
# User code can raise an exception carrying a resolved secret (e.g.
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index 8e48f209e..da685a32b 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -606,6 +606,7 @@ def block_yaml_to_block(
**base_kwargs,
code=block_yaml.code,
parameters=_resolve_block_parameters(block_yaml, parameters),
+ error_code_mapping=block_yaml.error_code_mapping,
prompt=block_yaml.prompt,
steps=code_block_steps,
)
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index f032e0b8c..90227f275 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -896,6 +896,7 @@ class CodeBlockYAML(BlockYAML):
code: str
parameter_keys: list[str] | None = None
+ error_code_mapping: dict[str, str] | None = None
prompt: str | None = Field(
default=None,
description="Plain-language goal of this code block, shown as the block's Goal in the editor",
diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.py
index 8b6e74b97..561726fb1 100644
--- a/skyvern/webeye/cdp_download_interceptor.py
+++ b/skyvern/webeye/cdp_download_interceptor.py
@@ -41,6 +41,7 @@ from playwright.async_api import Browser, BrowserContext, CDPSession, Page
from skyvern.constants import BROWSER_DOWNLOADING_SUFFIX, BROWSER_INTERCEPTOR_DISABLE_TIMEOUT
from skyvern.forge.sdk.api import files as file_api
+from skyvern.forge.sdk.core.http_request_authorization import is_unenrolled_redirect_hop_authorizer
from skyvern.webeye.utils.page import SkyvernFrame
if TYPE_CHECKING:
@@ -237,6 +238,22 @@ def _is_stale_interception_error(error: BaseException) -> bool:
return any(substr in message for substr in _STALE_INTERCEPTION_ERROR_SUBSTRINGS)
+def _exception_origin(error: BaseException) -> str:
+ """Name the frame that raised ``error`` as ``module:function:line``.
+
+ Exception messages and tracebacks on the download path can carry the credential-bearing
+ download URL, so this reports only where a failure came from and never what it said.
+ """
+ traceback = error.__traceback__
+ if traceback is None:
+ return "unknown"
+ while traceback.tb_next is not None:
+ traceback = traceback.tb_next
+ code = traceback.tb_frame.f_code
+ module = traceback.tb_frame.f_globals.get("__name__")
+ return f"{module if isinstance(module, str) else code.co_filename}:{code.co_name}:{traceback.tb_lineno}"
+
+
def _parse_headers(raw_headers: list[dict[str, str]]) -> dict[str, str]:
"""Convert CDP header list [{name, value}] to a lowercase-keyed dict (last value wins)."""
result: dict[str, str] = {}
@@ -1122,6 +1139,9 @@ class CDPDownloadInterceptor:
if self._browser_context is None:
LOG.error("Browser download context is unenrolled")
return
+ if is_unenrolled_redirect_hop_authorizer(self._redirect_hop_authorizer):
+ LOG.error("Redirect hop authorization is unenrolled for this browser session, dropping direct download")
+ return
t0 = time.monotonic()
try:
@@ -1136,7 +1156,13 @@ class CDPDownloadInterceptor:
authorize_request_hop=self._redirect_hop_authorizer,
)
except Exception as exc:
- LOG.error("Guarded direct download failed", error_type=type(exc).__name__)
+ # The download URL is credential-bearing and can reappear inside an exception message
+ # (aiohttp embeds it), so the raise site stands in for the message and traceback.
+ LOG.error(
+ "Guarded direct download failed",
+ error_type=type(exc).__name__,
+ error_origin=_exception_origin(exc),
+ )
return
data = response.body
diff --git a/tests/unit/test_cdp_download_interceptor.py b/tests/unit/test_cdp_download_interceptor.py
index 41c42544e..86a1fce84 100644
--- a/tests/unit/test_cdp_download_interceptor.py
+++ b/tests/unit/test_cdp_download_interceptor.py
@@ -17,6 +17,7 @@ import pytest
from structlog.testing import capture_logs
import skyvern.webeye.cdp_download_interceptor as mod
+from skyvern.forge.sdk.core.http_request_authorization import deny_unenrolled_redirect_hop
from skyvern.webeye.cdp_download_interceptor import (
CDPDownloadInterceptor,
_is_stale_interception_error,
@@ -2552,6 +2553,50 @@ class TestDirectHttpDownloadAuthAndHtmlGuard:
for log in logs
)
+ @pytest.mark.asyncio
+ async def test_guarded_download_failure_logs_the_raising_module(self, tmp_path: Path) -> None:
+ interceptor = _make_interceptor(output_dir=str(tmp_path))
+ interceptor._browser_context = self._context()
+
+ async def guarded_fetch(*_args: Any, **_kwargs: Any) -> None:
+ raise RuntimeError("exception-secret")
+
+ with (
+ patch.object(mod.file_api, "fetch_file_bytes", guarded_fetch, create=True),
+ capture_logs() as logs,
+ ):
+ await interceptor._download_url_directly("https://site.example/report.pdf?sig=url-secret", "report.pdf")
+
+ failures = [log for log in logs if log.get("event") == "Guarded direct download failed"]
+ assert len(failures) == 1
+ assert failures[0]["error_type"] == "RuntimeError"
+ assert failures[0]["error_origin"].startswith(f"{__name__}:guarded_fetch:")
+ serialized_logs = repr(logs)
+ assert "url-secret" not in serialized_logs
+ assert "exception-secret" not in serialized_logs
+
+ @pytest.mark.asyncio
+ async def test_unenrolled_hop_authorizer_is_reported_as_unenrolled(self, tmp_path: Path) -> None:
+ interceptor = _make_interceptor(
+ output_dir=str(tmp_path),
+ redirect_hop_authorizer=deny_unenrolled_redirect_hop,
+ )
+ interceptor._browser_context = self._context()
+ guarded_fetch = AsyncMock(side_effect=AssertionError("unenrolled authorization must not reach the fetch seam"))
+
+ with (
+ patch.object(mod.file_api, "fetch_file_bytes", guarded_fetch, create=True),
+ capture_logs() as logs,
+ ):
+ await interceptor._download_url_directly("https://site.example/report.pdf?sig=url-secret", "report.pdf")
+
+ guarded_fetch.assert_not_awaited()
+ assert list(tmp_path.iterdir()) == []
+ assert [log["event"] for log in logs] == [
+ "Redirect hop authorization is unenrolled for this browser session, dropping direct download"
+ ]
+ assert "url-secret" not in repr(logs)
+
@pytest.mark.asyncio
async def test_cookie_header_omits_control_characters(self, tmp_path: Path) -> None:
interceptor = _make_interceptor(output_dir=str(tmp_path))
diff --git a/tests/unit/test_cli_shared_core.py b/tests/unit/test_cli_shared_core.py
index 0f599903a..f5ec5d2a2 100644
--- a/tests/unit/test_cli_shared_core.py
+++ b/tests/unit/test_cli_shared_core.py
@@ -6,6 +6,7 @@ from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock
import pytest
+from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from skyvern.cli.core import browser_ops
from skyvern.cli.core.browser_ops import do_act, do_extract, do_navigate, do_screenshot, parse_extract_schema
@@ -102,30 +103,107 @@ def test_resolve_ai_mode(selector: str | None, intent: str | None, expected: tup
# ---------------------------------------------------------------------------
-async def test_do_navigate_success(monkeypatch: pytest.MonkeyPatch) -> None:
+def _navigable_page(url: str = "https://example.com/final", title: str = "Example") -> MagicMock:
page = MagicMock()
page.goto = AsyncMock()
- page.url = "https://example.com/final"
- page.title = AsyncMock(return_value="Example")
+ page.wait_for_load_state = AsyncMock()
+ page.url = url
+ page.title = AsyncMock(return_value=title)
+ return page
+
+
+async def test_do_navigate_success(monkeypatch: pytest.MonkeyPatch) -> None:
+ page = _navigable_page()
monkeypatch.setattr(browser_ops, "validate_fetch_url", lambda url: url)
result = await do_navigate(page, "https://example.com")
assert result.url == "https://example.com/final"
assert result.title == "Example"
+ assert result.load_state == "load"
@pytest.mark.asyncio
-async def test_do_navigate_passes_wait_until_through(monkeypatch: pytest.MonkeyPatch) -> None:
- page = MagicMock()
- page.goto = AsyncMock()
- page.url = "https://example.com/final"
- page.title = AsyncMock(return_value="Example")
+async def test_do_navigate_commits_before_waiting_for_the_requested_state(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ page = _navigable_page()
+ monkeypatch.setattr(browser_ops, "validate_fetch_url", lambda url: url)
+
+ await do_navigate(page, "https://example.com", wait_until="networkidle")
+
+ page.goto.assert_awaited_once_with("https://example.com", timeout=30000, wait_until="commit")
+ assert page.wait_for_load_state.await_args.args[0] == "networkidle"
+
+
+async def test_do_navigate_skips_the_lifecycle_wait_when_commit_is_requested(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ page = _navigable_page()
+ monkeypatch.setattr(browser_ops, "validate_fetch_url", lambda url: url)
+
+ result = await do_navigate(page, "https://example.com", wait_until="commit")
+
+ assert result.load_state == "commit"
+ page.wait_for_load_state.assert_not_awaited()
+
+
+async def test_do_navigate_rejects_invalid_wait_until() -> None:
+ page = _navigable_page()
+
+ with pytest.raises(GuardError):
+ await do_navigate(page, "https://example.com", wait_until="badvalue")
+
+ page.goto.assert_not_awaited()
+
+
+async def test_do_navigate_reports_the_weaker_state_when_load_never_fires(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def only_domcontentloaded_fires(state: str, timeout: int) -> None:
+ if state != "domcontentloaded":
+ raise PlaywrightTimeoutError(f"{state} never fired")
+
+ page = _navigable_page()
+ page.wait_for_load_state = AsyncMock(side_effect=only_domcontentloaded_fires)
+ monkeypatch.setattr(browser_ops, "validate_fetch_url", lambda url: url)
+
+ result = await do_navigate(page, "https://example.com")
+
+ assert result.load_state == "domcontentloaded"
+ assert result.url == "https://example.com/final"
+ assert result.title == "Example"
+
+
+async def test_do_navigate_reports_commit_when_no_lifecycle_state_arrives(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ page = _navigable_page()
+ page.wait_for_load_state = AsyncMock(side_effect=PlaywrightTimeoutError("nothing fired"))
monkeypatch.setattr(browser_ops, "validate_fetch_url", lambda url: url)
- result = await do_navigate(page, "https://example.com", wait_until="badvalue")
+ result = await do_navigate(page, "https://example.com")
+
+ assert result.load_state == "commit"
assert result.url == "https://example.com/final"
- page.goto.assert_awaited_once_with("https://example.com", timeout=30000, wait_until="badvalue")
+
+
+async def test_do_navigate_still_fails_when_the_document_never_commits(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ page = _navigable_page()
+ page.goto = AsyncMock(side_effect=PlaywrightTimeoutError("never committed"))
+ monkeypatch.setattr(browser_ops, "validate_fetch_url", lambda url: url)
+
+ with pytest.raises(PlaywrightTimeoutError):
+ await do_navigate(page, "https://example.com")
+
+ page.wait_for_load_state.assert_not_awaited()
@pytest.mark.asyncio
@@ -151,10 +229,7 @@ async def test_do_navigate_rejects_unsafe_url(url: str) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("url", ["http://localhost:3000/", "http://127.0.0.1:8000/"])
async def test_do_navigate_allows_local_url_when_context_permits(url: str) -> None:
- page = MagicMock()
- page.goto = AsyncMock()
- page.url = url
- page.title = AsyncMock(return_value="Local")
+ page = _navigable_page(url=url, title="Local")
result = await do_navigate(
page,
@@ -164,7 +239,7 @@ async def test_do_navigate_allows_local_url_when_context_permits(url: str) -> No
)
assert result.url == url
- page.goto.assert_awaited_once_with(url, timeout=30000, wait_until=None)
+ page.goto.assert_awaited_once_with(url, timeout=30000, wait_until="commit")
@pytest.mark.asyncio
diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.py
index e506d62c5..f935fd5e6 100644
--- a/tests/unit/test_copilot_hooks.py
+++ b/tests/unit/test_copilot_hooks.py
@@ -17,6 +17,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.code_block_synthesis import dynamic_row_evidence_fingerprint, synthesize_code_block
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.hooks import CopilotRunHooks
+from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.copilot.tools import (
_capture_scout_ambiguity,
_click_post_hook,
@@ -28,6 +29,7 @@ from skyvern.forge.sdk.copilot.tools.scouting import (
_prenav_dynamic_row_for_selector,
)
from skyvern.forge.sdk.copilot.turn_halt import CopilotTurnHalt, turn_halt_from_blocker_signal
+from tests.unit.copilot_test_helpers import make_copilot_ctx
@dataclass
@@ -1972,3 +1974,35 @@ def test_browser_overlays_are_gated_by_phase_and_session_classification() -> Non
# is asking the model to do — leaving one out re-asks for work it already did.
observers = browser_overlays - {"navigate_browser"}
assert observers <= _OBSERVATION_TOOLS, observers - _OBSERVATION_TOOLS
+
+
+async def test_lifecycle_hooks_count_model_calls_and_enforcement_passes() -> None:
+ ctx = make_copilot_ctx()
+ hooks = CopilotRunHooks(ctx)
+
+ await hooks.on_agent_start(MagicMock(), MagicMock())
+ await hooks.on_llm_start(MagicMock(), MagicMock(), None, [])
+ await hooks.on_llm_start(MagicMock(), MagicMock(), None, [])
+
+ assert ctx.enforcement_pass_count == 1
+ assert ctx.model_calls_this_turn == 2
+
+
+async def test_lifecycle_hooks_count_on_a_bare_agent_context() -> None:
+ ctx = AgentContext(
+ organization_id="org-1",
+ workflow_id="wf-1",
+ workflow_permanent_id="wfp-1",
+ workflow_yaml="",
+ browser_session_id=None,
+ stream=MagicMock(is_disconnected=AsyncMock(return_value=False)),
+ )
+ hooks = CopilotRunHooks(ctx)
+
+ await hooks.on_agent_start(MagicMock(), MagicMock())
+ await hooks.on_llm_start(MagicMock(), MagicMock(), None, [])
+
+ assert ctx.enforcement_pass_count == 1
+ assert ctx.model_calls_this_turn == 1
diff --git a/tests/unit/test_copilot_page_evidence_policy.py b/tests/unit/test_copilot_page_evidence_policy.py
index 92b0de7a5..b0d381bd2 100644
--- a/tests/unit/test_copilot_page_evidence_policy.py
+++ b/tests/unit/test_copilot_page_evidence_policy.py
@@ -67,7 +67,7 @@ def test_structured_page_inspection_is_not_rationed() -> None:
def test_default_loop_budget_allows_inspect_build_run_answer_trajectory() -> None:
- assert DEFAULT_MAX_TURNS >= 35
+ assert DEFAULT_MAX_TURNS == 200
def test_block_observation_ref_rejects_negative_steps() -> None:
diff --git a/tests/unit/test_copilot_terminal_envelope.py b/tests/unit/test_copilot_terminal_envelope.py
index d0f1d5745..20eb92853 100644
--- a/tests/unit/test_copilot_terminal_envelope.py
+++ b/tests/unit/test_copilot_terminal_envelope.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import time
from typing import Any
import pytest
@@ -10,6 +11,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import (
CopilotToolBlockerSignal,
clear_terminal_evidence_on_workflow_edit,
)
+from skyvern.forge.sdk.copilot.config import CopilotConfig
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
from skyvern.forge.sdk.copilot.terminal_envelope import (
TerminalOutcomeEnvelope,
@@ -617,3 +619,59 @@ def test_envelope_has_no_cause_when_deadline_did_not_expire() -> None:
assert result.terminal_envelope is not None
assert result.terminal_envelope["terminal_cause"] is None
+
+
+def test_max_turns_exit_types_the_cause_and_logs_the_backstop_fields() -> None:
+ ctx = make_copilot_ctx()
+ ctx.copilot_config = CopilotConfig()
+ ctx.copilot_run_start_monotonic = time.monotonic() - 12.0
+ ctx.enforcement_pass_count = 3
+ ctx.model_calls_this_turn = 12
+
+ with structlog.testing.capture_logs() as logs:
+ result = agent_module._handle_max_turns_exceeded(ctx, global_llm_context=None)
+
+ assert ctx.copilot_max_turns_exceeded is True
+ assert result.terminal_envelope is not None
+ assert result.terminal_envelope["terminal_cause"] == "max_turns_exceeded"
+
+ backstop_logs = [entry for entry in logs if entry.get("event") == "copilot_max_turns_exceeded"]
+ assert len(backstop_logs) == 1
+ assert backstop_logs[0]["limit"] == 200
+ assert backstop_logs[0]["iteration"] == 3
+ assert backstop_logs[0]["model_call_count"] == 12
+ assert backstop_logs[0]["elapsed_seconds"] == pytest.approx(12.0, abs=1.0)
+
+
+def test_max_turns_exit_without_deadline_is_not_an_untyped_stop() -> None:
+ ctx = make_copilot_ctx()
+ ctx.copilot_total_timeout_exceeded = False
+ ctx.copilot_max_turns_exceeded = True
+
+ result = agent_module._build_max_turns_exit_result(ctx, global_llm_context=None)
+
+ assert result.terminal_envelope is not None
+ assert result.terminal_envelope["terminal_cause"] is not None
+ assert result.terminal_envelope["terminal_cause"] == "max_turns_exceeded"
+
+
+def test_deadline_wins_when_both_capacity_latches_are_set() -> None:
+ ctx = make_copilot_ctx()
+ ctx.copilot_total_timeout_exceeded = True
+ ctx.copilot_max_turns_exceeded = True
+
+ result = agent_module._build_max_turns_exit_result(ctx, global_llm_context=None)
+
+ assert result.terminal_envelope is not None
+ assert result.terminal_envelope["terminal_cause"] == "deadline_expired"
+
+
+def test_max_turns_exit_has_no_cause_when_neither_latch_is_set() -> None:
+ ctx = make_copilot_ctx()
+ ctx.copilot_total_timeout_exceeded = False
+ ctx.copilot_max_turns_exceeded = False
+
+ result = agent_module._build_max_turns_exit_result(ctx, global_llm_context=None)
+
+ assert result.terminal_envelope is not None
+ assert result.terminal_envelope["terminal_cause"] is None
diff --git a/tests/unit/test_iframe_support.py b/tests/unit/test_iframe_support.py
index 7842afc6d..571d2df9c 100644
--- a/tests/unit/test_iframe_support.py
+++ b/tests/unit/test_iframe_support.py
@@ -67,6 +67,7 @@ class TestMCPFrameTools:
fake_page = MagicMock()
fake_page.goto = AsyncMock()
+ fake_page.wait_for_load_state = AsyncMock()
fake_page.url = "https://example.com/new"
fake_page.title = AsyncMock(return_value="New Page")
fake_ctx = MagicMock()
diff --git a/tests/unit/test_mcp_argument_validation.py b/tests/unit/test_mcp_argument_validation.py
index eb07c206a..7589a28f6 100644
--- a/tests/unit/test_mcp_argument_validation.py
+++ b/tests/unit/test_mcp_argument_validation.py
@@ -7,11 +7,11 @@ names that don't match the tool's contract.
from __future__ import annotations
-from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
+from skyvern.cli.core.browser_ops import NavigateResult
from skyvern.cli.core.result import BrowserContext
from skyvern.cli.mcp_tools import browser as mcp_browser
from skyvern.cli.mcp_tools import mcp
@@ -41,7 +41,7 @@ def _mock_navigation(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:
page = make_skyvern_page(make_mock_page())
context = BrowserContext(mode="cloud_session", session_id="pbs_test")
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, context)))
- navigate = AsyncMock(return_value=SimpleNamespace(url="https://example.com", title="Example"))
+ navigate = AsyncMock(return_value=NavigateResult(url="https://example.com", title="Example"))
monkeypatch.setattr(mcp_browser, "do_navigate", navigate)
return navigate
diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.py
index 38a57ee29..624ba03e2 100644
--- a/tests/unit/test_mcp_browser_tools.py
+++ b/tests/unit/test_mcp_browser_tools.py
@@ -16,6 +16,7 @@ from skyvern.cli.core.browser_ops import (
CustomSelectMatchError,
CustomSelectOpenError,
CustomSelectPasswordError,
+ NavigateResult,
do_select_option,
)
from skyvern.cli.core.result import Artifact, BrowserContext, set_concise_responses
@@ -965,7 +966,7 @@ def _sdk_equivalent_page(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
mcp_browser,
"do_navigate",
- AsyncMock(return_value=SimpleNamespace(url="https://example.test", title="Example")),
+ AsyncMock(return_value=NavigateResult(url="https://example.test", title="Example")),
)
monkeypatch.setattr(mcp_browser, "do_extract", AsyncMock(return_value=SimpleNamespace(extracted={})))
monkeypatch.setattr(mcp_browser, "do_act", AsyncMock(return_value=SimpleNamespace(prompt="done", completed=True)))
@@ -2803,6 +2804,69 @@ async def test_navigating_paired_tools_clear_the_ref_map_around_navigation(
assert clear.call_count == 2
+async def test_navigate_reports_ok_with_a_warning_when_the_page_settles_below_the_requested_state(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A page that never fires `load` is navigated, not failed — say so instead of ACTION_FAILED."""
+ _sdk_equivalent_page(monkeypatch)
+ monkeypatch.setattr(
+ mcp_browser,
+ "do_navigate",
+ AsyncMock(return_value=NavigateResult(url="https://example.test", title="Example", load_state="commit")),
+ )
+
+ result = await mcp_browser.skyvern_navigate(url="https://example.test")
+
+ assert result["ok"] is True, result
+ assert result["data"]["load_state"] == "commit"
+ assert result["data"]["url"] == "https://example.test"
+ assert any("never reached 'load'" in warning for warning in result["warnings"]), result
+
+
+async def test_navigate_does_not_warn_when_the_requested_state_is_reached(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _sdk_equivalent_page(monkeypatch)
+ monkeypatch.setattr(
+ mcp_browser,
+ "do_navigate",
+ AsyncMock(
+ return_value=NavigateResult(url="https://example.test", title="Example", load_state="domcontentloaded")
+ ),
+ )
+
+ result = await mcp_browser.skyvern_navigate(url="https://example.test", wait_until="domcontentloaded")
+
+ assert result["ok"] is True, result
+ assert result["warnings"] == []
+
+
+async def test_navigating_paired_tools_surface_the_degraded_load_state(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _sdk_equivalent_page(monkeypatch)
+ monkeypatch.setattr(
+ mcp_browser,
+ "do_navigate",
+ AsyncMock(return_value=NavigateResult(url="https://example.test", title="Example", load_state="commit")),
+ )
+ monkeypatch.setattr(mcp_browser, "do_screenshot", AsyncMock(return_value=SimpleNamespace(data=b"png")))
+ monkeypatch.setattr(
+ mcp_browser,
+ "save_artifact",
+ Mock(return_value=Artifact(kind="screenshot", path="/tmp/shot.png", mime="image/png", bytes=3)),
+ )
+
+ result = await mcp_browser.skyvern_navigate_and_screenshot(url="https://example.test")
+
+ assert result["ok"] is True, result
+ assert result["data"]["load_state"] == "commit"
+ assert any("never reached 'load'" in warning for warning in result["warnings"]), result
+
+
@pytest.mark.asyncio
async def test_navigating_paired_tools_clear_the_ref_map_even_when_navigation_fails(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_mcp_observe_execute.py b/tests/unit/test_mcp_observe_execute.py
index 3c18f1cb8..980b46618 100644
--- a/tests/unit/test_mcp_observe_execute.py
+++ b/tests/unit/test_mcp_observe_execute.py
@@ -15,6 +15,7 @@ from skyvern.cli.core.browser_ops import (
_DOMUTILS_INTERACTABILITY_READY_JS,
_OBSERVE_INTERACTABLES_JS,
ExecuteStep,
+ NavigateResult,
ObserveResult,
_flatten_a11y_tree,
do_execute,
@@ -1576,7 +1577,7 @@ class TestSkyvernExecuteMCP:
async def fake_navigate(*args: Any, **kwargs: Any) -> Any:
in_flight_generation.append(session_manager.session_ref_generation(session_id=ctx.session_id))
- return SimpleNamespace(url="https://example.com/next", title="Next")
+ return NavigateResult(url="https://example.com/next", title="Next")
monkeypatch.setattr(mcp_browser, "do_navigate", fake_navigate)
diff --git a/tests/unit/test_mcp_response_size_cap.py b/tests/unit/test_mcp_response_size_cap.py
index 6e92a5b5e..1e30d8881 100644
--- a/tests/unit/test_mcp_response_size_cap.py
+++ b/tests/unit/test_mcp_response_size_cap.py
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, Mock
import pytest
+from skyvern.cli.core.browser_ops import NavigateResult
from skyvern.cli.core.result import Artifact, BrowserContext
from skyvern.cli.mcp_tools import browser as mcp_browser
from skyvern.cli.mcp_tools import mcp
@@ -244,7 +245,7 @@ async def test_every_registered_extract_tool_caps_an_oversize_extraction(
monkeypatch.setattr(
mcp_browser,
"do_navigate",
- AsyncMock(return_value=SimpleNamespace(url="https://example.test", title="Example")),
+ AsyncMock(return_value=NavigateResult(url="https://example.test", title="Example")),
)
monkeypatch.setattr(mcp_browser, "do_screenshot", AsyncMock(return_value=SimpleNamespace(data=b"png")))
monkeypatch.setattr(
@@ -275,7 +276,7 @@ def _stub_browser(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
mcp_browser,
"do_navigate",
- AsyncMock(return_value=SimpleNamespace(url="https://example.test", title="Example")),
+ AsyncMock(return_value=NavigateResult(url="https://example.test", title="Example")),
)
monkeypatch.setattr(mcp_browser, "do_screenshot", AsyncMock(return_value=SimpleNamespace(data=b"png")))
monkeypatch.setattr(
diff --git a/tests/unit/workflow/test_code_block_error_manifest.py b/tests/unit/workflow/test_code_block_error_manifest.py
new file mode 100644
index 000000000..f106ca1a5
--- /dev/null
+++ b/tests/unit/workflow/test_code_block_error_manifest.py
@@ -0,0 +1,213 @@
+"""Tests for CodeBlock's error_code_mapping manifest + ErrorCode primitive (SKY-13668, stream 1).
+
+Covers the inline (non-secure-runner) execution path only: a declared `raise ErrorCode(code,
+reasoning)` is surfaced as a USER_DEFINED_ERROR and skips self-healing; an undeclared code (or a
+raise with no manifest at all) fails closed exactly like an ordinary exception.
+"""
+
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock
+
+import pytest
+
+from skyvern.forge.sdk.workflow.models.block import CodeBlock
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
+from skyvern.schemas.workflows import BlockStatus
+from skyvern.webeye.browser_artifacts import BrowserArtifacts
+
+
+class FakeBrowserState:
+ def __init__(self) -> None:
+ self.browser_artifacts = BrowserArtifacts()
+
+ async def get_working_page(self) -> object:
+ return object()
+
+
+class FakeWorkflowRunContext:
+ values: dict[str, object] = {}
+ secrets: dict[str, object] = {}
+ include_secrets_in_templates = False
+ organization_id = None
+ workflow_title = "Test Workflow"
+ workflow_id = "w_test"
+ workflow_permanent_id = "wpid_test"
+ workflow_run_id = "wrid_test"
+ browser_session_id = None
+ workflow_run_outputs: list[object] = []
+
+ def get_block_metadata(self, label: str | None) -> dict[str, object]:
+ return {}
+
+ def build_workflow_run_summary(self) -> str:
+ return ""
+
+ def mask_secrets_in_data(self, data: object, mask: str = "*****") -> object:
+ return data
+
+
+def _output_parameter(key: str) -> OutputParameter:
+ now = datetime.now(timezone.utc)
+ return OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key=key,
+ description="test output",
+ output_parameter_id=f"op_{key}",
+ workflow_id="w_test",
+ created_at=now,
+ modified_at=now,
+ )
+
+
+async def _run_code_block(monkeypatch: pytest.MonkeyPatch, block: CodeBlock, self_heal_mock: AsyncMock | None = None):
+ async def validate_code_block(*args: object, **kwargs: object) -> None:
+ return None
+
+ async def get_browser_state(*args: object, **kwargs: object) -> FakeBrowserState:
+ return FakeBrowserState()
+
+ async def record_output(*args: object, **kwargs: object) -> None:
+ return None
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.block.app.AGENT_FUNCTION.validate_code_block",
+ validate_code_block,
+ )
+ monkeypatch.setattr(CodeBlock, "get_or_create_browser_state", get_browser_state)
+ monkeypatch.setattr(CodeBlock, "get_workflow_run_context", lambda *args: FakeWorkflowRunContext())
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", record_output)
+ if self_heal_mock is not None:
+ monkeypatch.setattr(CodeBlock, "_resolve_failure_with_heal", self_heal_mock)
+
+ return await block.execute(workflow_run_id="wrid_test", workflow_run_block_id="")
+
+
+async def test_no_manifest_success_is_unchanged(monkeypatch: pytest.MonkeyPatch) -> None:
+ """AC1: a block with no error_code_mapping behaves exactly as before on success."""
+ block = CodeBlock(label="ok_block", code="value = 'ok'", output_parameter=_output_parameter("ok_output"))
+ result = await _run_code_block(monkeypatch, block)
+
+ assert result.success is True
+ assert result.status == BlockStatus.completed
+ assert result.output_parameter_value == {"value": "ok"}
+ assert result.error_codes == []
+
+
+async def test_declared_error_code_surfaces_as_user_defined_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ """AC2: a declared ErrorCode raise writes a USER_DEFINED_ERROR with the code/reasoning/confidence 1.0."""
+ block = CodeBlock(
+ label="login_block",
+ code="raise ErrorCode('LOGIN_FAILED', 'could not find the login button')",
+ output_parameter=_output_parameter("login_output"),
+ error_code_mapping={"LOGIN_FAILED": "the login form could not be located"},
+ )
+ result = await _run_code_block(monkeypatch, block)
+
+ assert result.success is False
+ assert result.status == BlockStatus.failed
+ assert result.error_codes == ["LOGIN_FAILED"]
+ assert result.output_parameter_value["errors"] == [
+ {
+ "error_code": "LOGIN_FAILED",
+ "reasoning": "could not find the login button",
+ "confidence_float": 1.0,
+ "error_type": "USER_DEFINED_ERROR",
+ }
+ ]
+
+
+async def test_undeclared_error_code_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """AC4: raising a code absent from the manifest is NOT surfaced as a caller-defined error."""
+ block = CodeBlock(
+ label="undeclared_block",
+ code="raise ErrorCode('NOT_IN_MANIFEST', 'should not be trusted')",
+ output_parameter=_output_parameter("undeclared_output"),
+ error_code_mapping={"LOGIN_FAILED": "the login form could not be located"},
+ )
+ result = await _run_code_block(monkeypatch, block)
+
+ assert result.success is False
+ assert result.status == BlockStatus.failed
+ assert result.error_codes == []
+ assert result.output_parameter_value is None
+ assert "NOT_IN_MANIFEST" not in (result.failure_reason or "") or "should not be trusted" in (
+ result.failure_reason or ""
+ )
+
+
+async def test_error_code_raise_with_no_manifest_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """AC4 variant: raising ErrorCode with no manifest configured at all is an ordinary failure."""
+ block = CodeBlock(
+ label="no_manifest_block",
+ code="raise ErrorCode('X', 'y')",
+ output_parameter=_output_parameter("no_manifest_output"),
+ )
+ result = await _run_code_block(monkeypatch, block)
+
+ assert result.success is False
+ assert result.status == BlockStatus.failed
+ assert result.error_codes == []
+ assert result.output_parameter_value is None
+
+
+async def test_declared_error_code_skips_self_heal(monkeypatch: pytest.MonkeyPatch) -> None:
+ """AC5: a declared typed raise must not be routed through self-heal."""
+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)
+ heal_mock = AsyncMock(side_effect=AssertionError("self-heal should not be attempted for a declared ErrorCode"))
+ block = CodeBlock(
+ label="healable_login_block",
+ code="raise ErrorCode('LOGIN_FAILED', 'could not find the login button')",
+ output_parameter=_output_parameter("heal_output"),
+ error_code_mapping={"LOGIN_FAILED": "the login form could not be located"},
+ )
+ result = await _run_code_block(monkeypatch, block, self_heal_mock=heal_mock)
+
+ assert result.success is False
+ heal_mock.assert_not_called()
+
+
+async def test_ordinary_exception_still_eligible_for_self_heal(monkeypatch: pytest.MonkeyPatch) -> None:
+ """AC5 counterpart: an ordinary exception (or an undeclared ErrorCode) still reaches self-heal resolution."""
+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)
+ heal_mock = AsyncMock(return_value=None)
+ block = CodeBlock(
+ label="ordinary_failure_block",
+ code="raise Exception('boom')",
+ output_parameter=_output_parameter("ordinary_output"),
+ )
+ await _run_code_block(monkeypatch, block, self_heal_mock=heal_mock)
+
+ heal_mock.assert_called_once()
+
+
+async def test_multiple_manifest_entries_resolve_independently(monkeypatch: pytest.MonkeyPatch) -> None:
+ """AC3: a manifest with multiple entries lets different branches raise different declared codes."""
+ manifest = {
+ "LOGIN_FAILED": "the login form could not be located",
+ "CAPTCHA_BLOCKED": "a captcha challenge blocked progress",
+ }
+ login_block = CodeBlock(
+ label="branch_a",
+ code="raise ErrorCode('LOGIN_FAILED', 'no login form')",
+ output_parameter=_output_parameter("branch_a_output"),
+ error_code_mapping=manifest,
+ )
+ captcha_block = CodeBlock(
+ label="branch_b",
+ code="raise ErrorCode('CAPTCHA_BLOCKED', 'captcha shown')",
+ output_parameter=_output_parameter("branch_b_output"),
+ error_code_mapping=manifest,
+ )
+
+ login_result = await _run_code_block(monkeypatch, login_block)
+ captcha_result = await _run_code_block(monkeypatch, captcha_block)
+
+ assert login_result.error_codes == ["LOGIN_FAILED"]
+ assert captcha_result.error_codes == ["CAPTCHA_BLOCKED"]
diff --git a/tests/unit/workflow/test_code_block_schema.py b/tests/unit/workflow/test_code_block_schema.py
index 04b814722..f037c2b1b 100644
--- a/tests/unit/workflow/test_code_block_schema.py
+++ b/tests/unit/workflow/test_code_block_schema.py
@@ -39,6 +39,18 @@ def test_code_block_yaml_defaults_keep_legacy_shape() -> None:
block_yaml = CodeBlockYAML(label="code_1", code="x = 1")
assert block_yaml.prompt is None
assert block_yaml.steps is None
+ assert block_yaml.error_code_mapping is None
+
+
+def test_code_block_yaml_and_converter_preserve_error_code_mapping() -> None:
+ mapping = {"login_failed": "could not find the login button", "CAPTCHA-1": "captcha detected"}
+ block_yaml = CodeBlockYAML(label="code_1", code="x = 1", error_code_mapping=mapping)
+
+ block = block_yaml_to_block(block_yaml, {"code_1_output": _output_parameter()})
+
+ assert block_yaml.error_code_mapping == mapping
+ assert isinstance(block, CodeBlock)
+ assert block.error_code_mapping == mapping
def test_converter_coerces_step_action_type_to_enum() -> None:
@@ -194,6 +206,7 @@ def test_code_block_model_roundtrip() -> None:
dumped = block.model_dump()
assert dumped["prompt"] == "g"
assert dumped["steps"][0]["action_type"] == "click"
+ assert dumped["error_code_mapping"] is None
def _make_workflow_run_context(values: dict | None = None) -> WorkflowRunContext: