Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-12341): stop masking OTP-extraction backend failures as client 400s (#7348)
Aaron Perez2a9d56753628
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex f5e816166..59450b529 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -288,7 +288,16 @@ class MissingWorkflowRunBrowserState(SkyvernException):super().__init__(f"Browser state for workflow run {workflow_run_id} and task {task_id} is missing.")-class CaptchaNotSolvedInTime(SkyvernException):+class CaptchaSolveError(SkyvernException):+ """Base for captcha-solve failures.++ Shared marker so the action handler can catch captcha-solve failures with a+ dedicated typed arm (logged as a handled failure) instead of the generic+ "Unhandled exception" arm. Cloud captcha-solve exceptions subclass this too.+ """+++class CaptchaNotSolvedInTime(CaptchaSolveError):def __init__(self, task_id: str, final_state: str) -> None:super().__init__(f"Captcha not solved in time for task {task_id}. Final state: {final_state}")diff --git a/skyvern/forge/sdk/copilot/model_resolver.py b/skyvern/forge/sdk/copilot/model_resolver.pyindex cfa67f362..097073ec2 100644--- a/skyvern/forge/sdk/copilot/model_resolver.py+++ b/skyvern/forge/sdk/copilot/model_resolver.py@@ -16,6 +16,7 @@ Known limitations:from __future__ import annotations+import refrom typing import Anyimport structlog@@ -40,6 +41,16 @@ from skyvern.schemas.llm import LLMConfig, LLMRouterConfigLOG = structlog.get_logger()+# Shape of a Skyvern registry alias (e.g. AZURE_OPENAI_GPT5_6_SOL, VERTEX_GEMINI_2.5_PRO, or a+# single-token key like OLLAMA, or a hyphenated one like OPENAI_GPT-4O-2024-08-06): all-caps+# alphanumeric segments, optionally joined by "-"/"_"/".", no provider prefix. Real litellm+# model strings (gpt-4o, azure/gpt-4.1) never match — they are lowercase and/or provider-+# prefixed. Used to fail fast when the copilot is pointed at an alias whose config isn't+# registered here, rather than letting get_config synthesize a provider-less model that 400s+# inside the Agents SDK with "LLM Provider NOT provided". Scoped to this copilot path so the+# self-hosted LLM_KEY synth fallback in get_config stays intact. SKY-12322.+_REGISTRY_STYLE_ALIAS = re.compile(r"[A-Z0-9]+(?:[-_.][A-Z0-9]+)*")+# Keys in litellm_params that are routed elsewhere (top-level kwargs to# LitellmModel or the dedicated ModelSettings.extra_headers slot), so they# don't count as "unrouted" when we log dropped keys.@@ -170,8 +181,26 @@ def resolve_model_config(and not LLMConfigRegistry.is_registered(llm_key)):llm_key = settings.OPENAI_COMPATIBLE_MODEL_KEY+config = LLMConfigRegistry.get_config(llm_key)+ # get_config synthesizes a config whose model_name IS the llm_key when the key isn't+ # registered. For a registry-style alias (its ENABLE_* flag/credentials unset here) that+ # synthesized model has no provider prefix and 400s inside the Agents SDK with "LLM Provider+ # NOT provided", so fail fast. A registered config or a raw self-hosted model string has+ # model_name != the alias (or isn't registry-style), so the self-hosted synth path and all+ # normal resolutions are untouched. SKY-12322.+ if (+ not LLMConfigRegistry.is_registered(llm_key)+ and isinstance(config, LLMConfig)+ and config.model_name == llm_key+ and _REGISTRY_STYLE_ALIAS.fullmatch(llm_key)+ ):+ raise InvalidLLMConfigError(+ f"copilot llm_key '{llm_key}' looks like a Skyvern LLM registry alias but is not "+ f"registered in this environment; its ENABLE_* flag or provider credentials are likely unset."+ )+if isinstance(config, LLMRouterConfig):config = _degrade_router_to_direct(llm_key, config)diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex 16bf09447..13f64f8e9 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -466,8 +466,13 @@ async def send_totp_code(parse_exception_type_name = type(e).__name__if parse_exception_type_name:+ # parse_otp_login raised, meaning the OTP-extraction dependency (LLM backend)+ # failed rather than the caller supplying unparseable input. Surface a retryable+ # 502 so relays retry once the backend recovers, instead of a 400 that reads as+ # "bad input" and masks a backend outage.LOG.error("Failed to parse otp login",+ organization_id=curr_org.organization_id,totp_identifier=redacted_totp_identifier,task_id=data.task_id,workflow_id=data.workflow_id,@@ -475,11 +480,15 @@ async def send_totp_code(content_length=len(data.content),exception_type=parse_exception_type_name,)- raise HTTPException(status_code=400, detail="Failed to parse otp login")+ raise HTTPException(+ status_code=502,+ detail="OTP extraction is temporarily unavailable. Please retry in a few minutes.",+ )if not otp_value:LOG.error("Failed to parse otp login",+ organization_id=curr_org.organization_id,totp_identifier=redacted_totp_identifier,task_id=data.task_id,workflow_id=data.workflow_id,diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex dfecabc1f..a9fc0396e 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -32,6 +32,7 @@ from skyvern.constants import (from skyvern.core.script_generations.fuzzy_matcher import match_option_exact_or_stemfrom skyvern.errors.errors import TOTPExpiredError, UserDefinedError, filter_to_user_defined_codesfrom skyvern.exceptions import (+ CaptchaSolveError,CardNumberInputMismatch,EmptySelect,ErrEmptyTweakValue,@@ -2345,6 +2346,14 @@ class ActionHandler:except ImaginarySecretValue as e:LOG.exception("Imaginary secret value", action=action, exc_info=True)actions_result.append(ActionFailure(e))+ except CaptchaSolveError as e:+ LOG.warning(+ "Captcha solve failed",+ action=action,+ exception_type=type(e).__name__,+ exception_message=str(e),+ )+ actions_result.append(ActionFailure(e))except Exception as e:LOG.exception("Unhandled exception in action handler", action=action)actions_result.append(ActionFailure(e))diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.pyindex 6b5deb797..e32f8f274 100644--- a/skyvern/webeye/cdp_download_interceptor.py+++ b/skyvern/webeye/cdp_download_interceptor.py@@ -129,6 +129,23 @@ _FILENAME_PATH_SEPARATOR_RE = re.compile(r"[\\/]+")_FILENAME_CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f\x7f]")_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")+# Substrings that identify a CDP interception which was already resolved/cancelled, or whose+# target/frame detached, before our async handler could respond — a benign race between+# Fetch.requestPaused firing and us sending continue/fulfill (common for telemetry requests+# cancelled by navigation). Retrying is futile; these must not surface as error-level failures.+# Matched case-insensitively against the raised error message.+_STALE_INTERCEPTION_ERROR_SUBSTRINGS = (+ "invalid interceptionid",+ "target closed",+ "session closed",+ "has been closed",+)+++def _is_stale_interception_error(error: BaseException) -> bool:+ message = str(error).lower()+ return any(substr in message for substr in _STALE_INTERCEPTION_ERROR_SUBSTRINGS)+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)."""@@ -755,6 +772,18 @@ class CDPDownloadInterceptor:else:await self._continue_response(cdp_session, request_id)except Exception as e:+ if _is_stale_interception_error(e):+ # The interception was resolved/cancelled or its target detached before we+ # responded (SKY-11964). Retrying continue/fulfill would fail identically, so+ # drop it quietly — real download flows aren't stalled by a request that no+ # longer exists.+ LOG.debug(+ "CDP interception went stale before response (benign race)",+ request_id=request_id,+ url=url,+ error=str(e),+ )+ returnLOG.error("Error handling CDP request",request_id=request_id,@@ -875,8 +904,17 @@ class CDPDownloadInterceptor:try:await self._fulfill_with_body(cdp_session, request_id, response_status, raw_response_headers, data)except Exception as e:- LOG.warning("fulfillRequest failed after download", filename=filename, url=url, error=str(e))- # Can't continue response after body extraction, just log the error+ # The file is already saved to disk at this point; only the browser-side replay failed.+ # A stale interception here (target navigated/closed) is a benign race, not an error.+ if _is_stale_interception_error(e):+ LOG.debug(+ "fulfillRequest hit stale interception after download (benign race)",+ filename=filename,+ url=url,+ error=str(e),+ )+ else:+ LOG.warning("fulfillRequest failed after download", filename=filename, url=url, error=str(e))async def _fulfill_with_body(self,diff --git a/tests/unit/test_cdp_download_interceptor.py b/tests/unit/test_cdp_download_interceptor.pyindex 37892c6f9..7fbdf7e89 100644--- a/tests/unit/test_cdp_download_interceptor.py+++ b/tests/unit/test_cdp_download_interceptor.py@@ -5,7 +5,12 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptor, extract_filename, is_download_response+from skyvern.webeye.cdp_download_interceptor import (+ CDPDownloadInterceptor,+ _is_stale_interception_error,+ extract_filename,+ is_download_response,+)class TestIsDownloadResponse:@@ -707,6 +712,90 @@ class TestCDPDownloadInterceptorProxyAuth:assert second_call.args[1]["authChallengeResponse"]["response"] == "CancelAuth"+class TestStaleInterceptionRace:+ """Fetch.continueRequest/continueResponse can fail with 'Invalid InterceptionId' when the+ interception is resolved/cancelled or its target detaches before our async handler responds.+ That is a benign race (SKY-11964), not an error-level failure, and retrying it is futile."""++ _MOD = "skyvern.webeye.cdp_download_interceptor"++ def _make_interceptor(self) -> CDPDownloadInterceptor:+ return CDPDownloadInterceptor(output_dir="/tmp/test_downloads")++ def _make_cdp_session(self) -> MagicMock:+ session = MagicMock()+ session.send = AsyncMock()+ return session++ @staticmethod+ def _response_event() -> dict:+ return {+ "requestId": "req-1",+ "request": {"url": "https://example.com/analytics/collect"},+ "resourceType": "XHR",+ "responseStatusCode": 200,+ "responseHeaders": [{"name": "content-type", "value": "text/plain"}],+ }++ @pytest.mark.parametrize(+ ("message", "expected"),+ [+ pytest.param("Protocol error (Fetch.continueResponse): Invalid InterceptionId", True, id="invalid_id"),+ pytest.param("Protocol error (Fetch.continueRequest): Invalid InterceptionId", True, id="invalid_id_req"),+ pytest.param("Target page, context or browser has been closed", True, id="target_closed"),+ pytest.param("Session closed. Most likely the page has been closed.", True, id="session_closed"),+ pytest.param("Protocol error (Fetch.continueResponse): Some other CDP failure", False, id="other_cdp"),+ pytest.param("Connection reset by peer", False, id="generic"),+ ],+ )+ def test_is_stale_interception_error(self, message: str, expected: bool) -> None:+ assert _is_stale_interception_error(Exception(message)) is expected++ @pytest.mark.asyncio+ async def test_stale_continue_response_not_retried_or_error_logged(self) -> None:+ interceptor = self._make_interceptor()+ cdp_session = self._make_cdp_session()+ cdp_session.send.side_effect = Exception("Protocol error (Fetch.continueResponse): Invalid InterceptionId")++ with patch(f"{self._MOD}.LOG") as mock_log:+ await interceptor._handle_request_paused(self._response_event(), cdp_session)++ # Only the original continueResponse — no futile recovery retry against a dead interception.+ assert cdp_session.send.call_count == 1+ mock_log.error.assert_not_called()++ @pytest.mark.asyncio+ async def test_non_stale_response_error_still_retries_and_logs(self) -> None:+ interceptor = self._make_interceptor()+ cdp_session = self._make_cdp_session()+ cdp_session.send.side_effect = Exception("Protocol error (Fetch.continueResponse): boom")++ with patch(f"{self._MOD}.LOG") as mock_log:+ await interceptor._handle_request_paused(self._response_event(), cdp_session)++ # Original continueResponse + one recovery attempt; real failures still surface as errors.+ assert cdp_session.send.call_count == 2+ mock_log.error.assert_called_once()++ @pytest.mark.asyncio+ async def test_stale_request_stage_error_not_logged_as_error(self) -> None:+ interceptor = self._make_interceptor()+ cdp_session = self._make_cdp_session()+ cdp_session.send.side_effect = Exception("Protocol error (Fetch.continueRequest): Invalid InterceptionId")+ event = {+ "requestId": "req-2",+ "request": {"url": "https://example.com/page"},+ "resourceType": "Document",+ # No responseStatusCode — Request-stage event+ }++ with patch(f"{self._MOD}.LOG") as mock_log:+ await interceptor._handle_request_paused(event, cdp_session)++ assert cdp_session.send.call_count == 1+ mock_log.error.assert_not_called()++class TestBlobDownloadCapture:"""Browser-initiated blob: URL downloads (e.g. a page that builds the file client-side andtriggers a blob download) must be read back via SkyvernFrame and saved, not dropped."""diff --git a/tests/unit/test_copilot_model_resolver.py b/tests/unit/test_copilot_model_resolver.pyindex c63256f5b..b46c82244 100644--- a/tests/unit/test_copilot_model_resolver.py+++ b/tests/unit/test_copilot_model_resolver.py@@ -408,3 +408,30 @@ class TestModelResolver:assert model_name == "openai/gpt-4o"assert run_config.model_provider._base_url == "https://api.githubcopilot.com"assert run_config.model_provider._api_key == "gho_test"+++ "alias", ["ACME_UNREGISTERED_PROVIDER_MODEL", "ZZUNREGISTEREDPROVIDER", "ZZ-UNREGISTERED-HYPHEN-KEY"]+)+def test_resolve_model_config_raises_for_unregistered_registry_alias(alias: str) -> None:+ # Copilot pointed at a registry-style alias whose config isn't registered here must fail+ # fast, not synthesize a provider-less model that 400s inside the Agents SDK. SKY-12322.+ from skyvern.forge.sdk.api.llm.config_registry import LLMConfigRegistry+ from skyvern.forge.sdk.api.llm.exceptions import InvalidLLMConfigError++ assert not LLMConfigRegistry.is_registered(alias)+ handler = MagicMock()+ handler.llm_key = alias+ with pytest.raises(InvalidLLMConfigError):+ resolve_model_config(handler)++[email protected]("model_name", ["gpt-4o", "azure/gpt-4.1"])+def test_resolve_model_config_synthesizes_self_hosted_model(model_name: str) -> None:+ # A raw self-hosted model string is not registry-style, so the guard leaves it alone and+ # get_config's synth fallback resolves it — the self-hosted LLM_KEY path stays intact.+ handler = MagicMock()+ handler.llm_key = model_name+ resolved_model_name, _run_config, resolved_llm_key, _ = resolve_model_config(handler)+ assert resolved_model_name == model_name+ assert resolved_llm_key == model_namediff --git a/tests/unit/test_copilot_token_accounting.py b/tests/unit/test_copilot_token_accounting.pyindex 2cbf86f2b..8a3a51913 100644--- a/tests/unit/test_copilot_token_accounting.py+++ b/tests/unit/test_copilot_token_accounting.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom unittest.mock import MagicMock+import pytestfrom agents.run_context import RunContextWrapperfrom agents.usage import InputTokensDetails, OutputTokensDetails, Usage@@ -217,7 +218,11 @@ class TestAccumulateUsage:assert not hasattr(foreign_ctx, "total_tokens_used")-def test_resolve_model_config_sets_include_usage_true() -> None:+def test_resolve_model_config_sets_include_usage_true(monkeypatch: pytest.MonkeyPatch) -> None:+ # settings.LLM_KEY defaults to an OpenAI registry alias that isn't registered when+ # ENABLE_OPENAI is off (bare unit env); point it at a resolvable litellm model so the+ # None-llm_key fallback path resolves without tripping the SKY-12322 alias guard.+ monkeypatch.setattr("skyvern.forge.sdk.copilot.model_resolver.settings.LLM_KEY", "gpt-4o")handler = MagicMock()handler.llm_key = Nonediff --git a/tests/unit/test_credentials_totp_route_logging.py b/tests/unit/test_credentials_totp_route_logging.pyindex d2d565ace..982b4c4b5 100644--- a/tests/unit/test_credentials_totp_route_logging.py+++ b/tests/unit/test_credentials_totp_route_logging.py@@ -75,6 +75,7 @@ async def test_send_totp_code_parse_failure_log_redacts_identifier_and_content(error_log = next((r for r in logs if r.get("event") == "Failed to parse otp login"), None)assert error_log is not None+ assert error_log["organization_id"] == "o_test"assert error_log["totp_identifier"] == "[REDACTED_OTP_IDENTIFIER]"assert error_log["content_length"] == len(raw_content)assert "content" not in error_log@@ -102,8 +103,10 @@ async def test_send_totp_code_parser_exception_log_redacts_raw_exception_contextcurr_org=SimpleNamespace(organization_id="o_test"),)- assert exc_info.value.status_code == 400- assert exc_info.value.detail == "Failed to parse otp login"+ # A raised parser is a backend/dependency failure, not bad caller input, so the+ # endpoint returns a retryable 502 with a static detail that never echoes the payload.+ assert exc_info.value.status_code == 502+ assert exc_info.value.detail == "OTP extraction is temporarily unavailable. Please retry in a few minutes."assert exc_info.value.__cause__ is Noneassert exc_info.value.__context__ is Noneassert raw_identifier not in str(exc_info.value)@@ -113,6 +116,7 @@ async def test_send_totp_code_parser_exception_log_redacts_raw_exception_contexterror_log = next((r for r in logs if r.get("event") == "Failed to parse otp login"), None)assert error_log is not None+ assert error_log["organization_id"] == "o_test"assert error_log["totp_identifier"] == "[REDACTED_OTP_IDENTIFIER]"assert error_log["content_length"] == len(raw_content)assert error_log["exception_type"] == "RuntimeError"diff --git a/tests/unit/test_exception_messages.py b/tests/unit/test_exception_messages.pyindex f1133b7b1..b07a870ed 100644--- a/tests/unit/test_exception_messages.py+++ b/tests/unit/test_exception_messages.py@@ -3,6 +3,8 @@ from http import HTTPStatusimport pytestfrom skyvern.exceptions import (+ CaptchaNotSolvedInTime,+ CaptchaSolveError,CdpConnectionConfigurationError,SkyvernException,SkyvernExtraNotInstalled,@@ -36,6 +38,15 @@ def test_unknown_error_while_creating_browser_context_strips_call_log() -> None:assert "[email protected]" in message+def test_captcha_not_solved_in_time_is_captcha_solve_error() -> None:+ # The action handler catches CaptchaSolveError before its generic arm; this+ # subclass relationship is what routes captcha-solve failures to the handled+ # log path instead of "Unhandled exception in action handler".+ error = CaptchaNotSolvedInTime("task_123", "unsolved")+ assert isinstance(error, CaptchaSolveError)+ assert isinstance(error, SkyvernException)++def test_unknown_error_preserves_cdp_configuration_guidance() -> None:inner_exception = CdpConnectionConfigurationError("Skyvern reached the configured CDP address, but /json/version returned HTTP 404. "