Skip to content

Automate browser based workflows with AI

Classify scrape timeouts by the run's selected browser engine (RUS-5) (#7691)

LawyZhengf40153aecca5
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.py
index dac3cf702..ed49c35b6 100644
--- a/skyvern/exceptions.py
+++ b/skyvern/exceptions.py
@@ -56,6 +56,10 @@ class SkyvernException(Exception):
return type(self).__name__
+class SkyvernPageAnalysisTimeout(SkyvernException):
+ pass
+
+
class SkyvernExtraNotInstalled(ImportError):
def __init__(self, feature: str, extra: str = "server"):
self.feature = feature
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index ff3723c6d..6c5930d9b 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -71,6 +71,7 @@ from skyvern.exceptions import (
PhoneNumberInputMismatch,
SecretInputMismatch,
SkyvernException,
+ SkyvernPageAnalysisTimeout,
)
from skyvern.experimentation.wait_utils import get_or_create_wait_config, get_wait_time
from skyvern.forge import app
@@ -4394,6 +4395,17 @@ async def handle_input_text_action(
if action.stop_batch_after_dropdown_select:
select_result.action_result.skip_remaining_actions = True
return [select_result.action_result]
+ except SkyvernPageAnalysisTimeout as inc_error:
+ # A page-analysis timeout after both incremental attempts previously arrived here as a
+ # Playwright TimeoutError (a PlaywrightError) and was re-raised; the neutral
+ # SkyvernPageAnalysisTimeout is not a PlaywrightError, so re-raise explicitly instead of
+ # letting the broad handler below swallow it and falsely return ActionSuccess.
+ LOG.warning(
+ "Page-analysis timeout during incremental element processing",
+ error_type=type(inc_error).__name__,
+ error_message=str(inc_error),
+ )
+ raise inc_error
except PlaywrightError as inc_error:
# Handle Playwright-specific errors during incremental element processing
# (e.g., TOTP form auto-submit, or search-dropdown selection triggering navigation)
@@ -4506,7 +4518,7 @@ async def _wait_for_upload_processing(page: Page) -> None:
dom_stable_ms=300,
dom_stability_timeout_ms=2000,
)
- except (TimeoutError, asyncio.TimeoutError):
+ except (TimeoutError, asyncio.TimeoutError, SkyvernPageAnalysisTimeout):
LOG.info("Upload processing page-ready wait timed out, continuing")
except PlaywrightError:
LOG.warning("Upload processing page-ready wait interrupted by Playwright error, continuing", exc_info=True)
diff --git a/skyvern/webeye/browser_state.py b/skyvern/webeye/browser_state.py
index ce547a83e..5613fff90 100644
--- a/skyvern/webeye/browser_state.py
+++ b/skyvern/webeye/browser_state.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Awaitable, Callable, Literal, Protocol
+from typing import TYPE_CHECKING, Awaitable, Callable, Literal, Protocol
from playwright.async_api import BrowserContext, Page, Playwright
@@ -11,12 +11,18 @@ from skyvern.webeye.browser_artifacts import BrowserArtifacts
from skyvern.webeye.browser_factory import BrowserCleanupFunc
from skyvern.webeye.scraper.scraped_page import CleanupElementTreeFunc, ScrapedPage, ScrapeExcludeFunc
+if TYPE_CHECKING:
+ from skyvern.webeye.browser_engine import BrowserEngineSelection
+
class BrowserState(Protocol):
browser_context: BrowserContext | None
browser_artifacts: BrowserArtifacts
browser_cleanup: BrowserCleanupFunc
pw: Playwright
+ # The per-run pinned engine (or None for states built outside the per-run engine seam), so
+ # recovery code can classify driver-native errors against THIS run's selected engine.
+ engine_selection: BrowserEngineSelection | None
def add_on_close(self, callback: Callable[[], Awaitable[None]]) -> None: ...
diff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.py
index f10aeaacb..eae756f37 100644
--- a/skyvern/webeye/scraper/scraper.py
+++ b/skyvern/webeye/scraper/scraper.py
@@ -15,6 +15,7 @@ from skyvern.exceptions import (
NoElementFound,
ScrapingFailed,
ScrapingFailedBlankPage,
+ SkyvernPageAnalysisTimeout,
UnknownElementTreeFormat,
)
from skyvern.experimentation.wait_utils import empty_page_retry_wait
@@ -74,6 +75,21 @@ async def build_scraping_failed_reason(
return f"{base} URL: {safe_requested}."
+def _scrape_timed_out(browser_state: BrowserState, error: BaseException) -> bool:
+ """Whether ``error`` is a page-analysis timeout from THIS run's selected browser engine.
+
+ Uses the per-run engine selection's timeout family so a run pinned to a non-Playwright engine
+ still routes its native timeouts to PAGE_LOAD_TIMEOUT; falls back to the stock Playwright
+ timeout identity for states built outside the per-run engine seam (``engine_selection`` is None).
+ """
+ if isinstance(error, SkyvernPageAnalysisTimeout):
+ return True
+ selection = browser_state.engine_selection
+ if selection is not None:
+ return selection.is_engine_timeout_error(error)
+ return isinstance(error, TimeoutError)
+
+
RESERVED_ATTRIBUTES = {
"accept", # for input file
"alt",
@@ -254,7 +270,9 @@ async def scrape_website(
raise e
else:
raise ScrapingFailed(
- reason=await build_scraping_failed_reason(browser_state, url, timed_out=isinstance(e, TimeoutError))
+ reason=await build_scraping_failed_reason(
+ browser_state, url, timed_out=_scrape_timed_out(browser_state, e)
+ )
) from e
LOG.info("Scraping failed, will retry", max_retries=max_retries, num_retry=num_retry, url=url, wait_seconds=0.5)
await asyncio.sleep(0.5)
@@ -738,7 +756,7 @@ class IncrementalScrapePage(ElementTreeBuilder):
incremental_elements, incremental_tree = await self.skyvern_frame.get_incremental_element_tree(
wait_until_finished=True
)
- except TimeoutError:
+ except (TimeoutError, SkyvernPageAnalysisTimeout):
LOG.warning(
"Timeout to get incremental elements with wait_until_finished, going to get incremental elements without waiting",
)
diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.py
index efa0eca36..9a6c7757a 100644
--- a/skyvern/webeye/utils/page.py
+++ b/skyvern/webeye/utils/page.py
@@ -19,7 +19,7 @@ from playwright._impl._errors import TimeoutError
from playwright.async_api import ElementHandle, Frame, Locator, Page
from skyvern.constants import PAGE_CONTENT_TIMEOUT, SKYVERN_DIR
-from skyvern.exceptions import FailedToTakeScreenshot
+from skyvern.exceptions import FailedToTakeScreenshot, SkyvernPageAnalysisTimeout
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.trace import apply_context_attrs, traced
@@ -550,11 +550,11 @@ class SkyvernFrame:
timeout_ms=timeout_ms,
initial_error=error_msg,
)
- except asyncio.TimeoutError:
+ except asyncio.TimeoutError as error:
# Re-raised and handled by the caller (scrape retries / failure classification),
# so this is not the failure boundary; log without a traceback at warning.
LOG.warning("Skyvern timed out trying to analyze the page", expression=expression)
- raise TimeoutError("Skyvern timed out trying to analyze the page")
+ raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page") from error
@staticmethod
async def _evaluate_with_navigation_recovery(
@@ -583,7 +583,7 @@ class SkyvernFrame:
"Skyvern timed out trying to analyze the page after navigation recovery",
expression=expression,
)
- raise TimeoutError("Skyvern timed out trying to analyze the page")
+ raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
LOG.warning(
"JS execution context lost (likely due to page navigation), re-injecting domUtils.js and retrying",
@@ -600,18 +600,18 @@ class SkyvernFrame:
"Skyvern timed out trying to analyze the page after navigation recovery",
expression=expression,
)
- raise TimeoutError("Skyvern timed out trying to analyze the page")
+ raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
try:
async with asyncio.timeout(inject_budget):
# Same dispatch helper so a prefixed Page re-injects
# JS_FUNCTION_DEFS via Runtime.evaluate (preserving the marker).
await _dispatch_evaluate(frame, JS_FUNCTION_DEFS, None)
- except asyncio.TimeoutError:
+ except asyncio.TimeoutError as error:
LOG.exception(
"Skyvern timed out trying to analyze the page during domUtils.js re-injection",
expression=expression,
)
- raise TimeoutError("Skyvern timed out trying to analyze the page")
+ raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page") from error
except (PlaywrightError, RuntimeError) as inject_err:
last_error_msg = str(inject_err)
if attempt == _NAVIGATION_RECOVERY_MAX_ATTEMPTS or not _is_navigation_context_lost(last_error_msg):
@@ -628,13 +628,13 @@ class SkyvernFrame:
"Skyvern timed out trying to analyze the page after navigation recovery",
expression=expression,
)
- raise TimeoutError("Skyvern timed out trying to analyze the page")
+ raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
try:
async with asyncio.timeout(retry_budget):
return await evaluate_expression()
- except asyncio.TimeoutError:
+ except asyncio.TimeoutError as error:
LOG.exception("Skyvern timed out on retry after JS context re-injection", expression=expression)
- raise TimeoutError("Skyvern timed out trying to analyze the page")
+ raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page") from error
except (PlaywrightError, RuntimeError) as retry_err:
last_error_msg = str(retry_err)
if attempt == _NAVIGATION_RECOVERY_MAX_ATTEMPTS or not _is_navigation_context_lost(last_error_msg):
@@ -1148,7 +1148,7 @@ class SkyvernFrame:
await self.frame.wait_for_load_state("load", timeout=timeout_ms)
await self.wait_for_animation_end(timeout_ms=timeout_ms)
_span.set_attribute("animation_result", "finished")
- except (TimeoutError, asyncio.TimeoutError):
+ except (TimeoutError, asyncio.TimeoutError, SkyvernPageAnalysisTimeout):
_span.set_attribute("animation_result", "timeout")
LOG.debug("Timed out waiting for animation end, but ignore it", exc_info=True)
return
@@ -1198,7 +1198,7 @@ class SkyvernFrame:
_li_span.set_attribute("timeout_ms", loading_indicator_timeout_ms)
try:
await self._wait_for_loading_indicators_gone(timeout_ms=loading_indicator_timeout_ms)
- except (TimeoutError, asyncio.TimeoutError):
+ except (TimeoutError, asyncio.TimeoutError, SkyvernPageAnalysisTimeout):
loading_indicator_result = "timeout"
LOG.info("Loading indicator timeout - some indicators may still be present, proceeding", sampling=True)
except Exception:
@@ -1231,7 +1231,7 @@ class SkyvernFrame:
_ds_span.set_attribute("stable_ms", dom_stable_ms)
try:
await self._wait_for_dom_stable(stable_ms=dom_stable_ms, timeout_ms=dom_stability_timeout_ms)
- except (TimeoutError, asyncio.TimeoutError):
+ except (TimeoutError, asyncio.TimeoutError, SkyvernPageAnalysisTimeout):
dom_stability_result = "timeout"
LOG.warning("DOM stability timeout - DOM may still be changing, proceeding")
except Exception:
diff --git a/tests/unit/test_animation_wait_attrs.py b/tests/unit/test_animation_wait_attrs.py
index 6fd48e76f..8109f81ca 100644
--- a/tests/unit/test_animation_wait_attrs.py
+++ b/tests/unit/test_animation_wait_attrs.py
@@ -3,7 +3,12 @@
import ast
import inspect
import os
+from unittest.mock import AsyncMock
+import pytest
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+
+from skyvern.exceptions import SkyvernPageAnalysisTimeout
from skyvern.webeye.utils.page import SkyvernFrame
@@ -13,6 +18,27 @@ def test_safe_wait_caller_defaults_to_unknown() -> None:
assert sig.parameters["caller"].default == "unknown"
+async def test_safe_wait_for_animation_end_classifies_skyvern_analysis_timeout(
+ span_exporter: InMemorySpanExporter,
+) -> None:
+ frame = AsyncMock()
+ frame.wait_for_load_state = AsyncMock()
+ skyvern_frame = SkyvernFrame(frame=frame)
+ skyvern_frame.wait_for_animation_end = AsyncMock(
+ side_effect=SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
+ )
+
+ await skyvern_frame.safe_wait_for_animation_end(caller="test")
+
+ span = next(
+ (span for span in span_exporter.get_finished_spans() if span.name == "skyvern.browser.wait_for_animation"),
+ None,
+ )
+ assert span is not None
+ assert (span.attributes or {}).get("animation_result") == "timeout"
+
+
def test_all_production_call_sites_pass_caller() -> None:
"""Every safe_wait_for_animation_end call in production code must include caller=.
diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.py
index 23ccc9d64..8afd26a5a 100644
--- a/tests/unit/test_download_file_action_handler.py
+++ b/tests/unit/test_download_file_action_handler.py
@@ -2320,8 +2320,7 @@ async def test_handle_action_download_in_flight_request_does_not_extend_custom_t
)
elapsed = time.monotonic() - started_at
- # Keep wall-clock bounds loose to tolerate scheduling jitter on shared CI runners.
- assert elapsed < 0.5
+ assert elapsed < 0.1
assert results[-1].download_triggered is False
assert action.download_triggered is False
span_attrs = _download_wait_span_attrs(span_exporter)
diff --git a/tests/unit/test_input_text_incremental_timeout_reraise.py b/tests/unit/test_input_text_incremental_timeout_reraise.py
new file mode 100644
index 000000000..bfe20a940
--- /dev/null
+++ b/tests/unit/test_input_text_incremental_timeout_reraise.py
@@ -0,0 +1,104 @@
+"""Ancestor-path regression for the neutral ``SkyvernPageAnalysisTimeout`` (RUS-5 / SKY-12007).
+
+``IncrementalScrapePage.get_incremental_element_tree`` retries the analysis once without waiting;
+if that second attempt also times out it raises ``SkyvernPageAnalysisTimeout`` up into
+``handle_input_text_action``'s incremental-processing block. Previously this surfaced as a Playwright
+``TimeoutError`` (a ``PlaywrightError``), which the handler's Playwright-specific ``except`` re-raised,
+so the input action failed rather than silently succeeding. The neutral timeout is not a
+``PlaywrightError``, so without explicit handling it would fall into the broad ``except Exception`` that
+swallows incremental-processing errors and the action would falsely return ``ActionSuccess``.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from skyvern.exceptions import SkyvernPageAnalysisTimeout
+from skyvern.forge.sdk.models import StepStatus
+from skyvern.webeye.actions.actions import InputOrSelectContext, InputTextAction
+from skyvern.webeye.actions.handler import handle_input_text_action
+from skyvern.webeye.actions.responses import ActionSuccess
+from skyvern.webeye.scraper.scraper import IncrementalScrapePage
+from tests.unit.conftest import make_input_element_mock
+from tests.unit.helpers import make_organization, make_step, make_task
+
+_NOW = datetime.now(UTC)
+_ORG = make_organization(_NOW)
+_TASK = make_task(_NOW, _ORG, navigation_payload={}, navigation_goal="Fill the field")
+_STEP = make_step(_NOW, _TASK, step_id="stp-1", status=StepStatus.created, order=0, output=None)
+
+
+async def test_incremental_element_tree_propagates_when_both_attempts_time_out() -> None:
+ """Both the wait-until-finished attempt and the no-wait retry raising ``SkyvernPageAnalysisTimeout``
+ must leave the timeout propagating out of ``get_incremental_element_tree`` (the ancestor that feeds
+ the input handler), not be swallowed by the one-shot retry."""
+ skyvern_frame = MagicMock()
+ skyvern_frame.get_frame.return_value = MagicMock()
+ skyvern_frame.get_incremental_element_tree = AsyncMock(
+ side_effect=SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
+ )
+
+ incremental = IncrementalScrapePage(skyvern_frame=skyvern_frame)
+
+ with pytest.raises(SkyvernPageAnalysisTimeout):
+ await incremental.get_incremental_element_tree(AsyncMock())
+
+ assert skyvern_frame.get_incremental_element_tree.await_count == 2
+
+
+async def _run_input_with_incremental_error(error: BaseException) -> list:
+ skyvern_el = make_input_element_mock(element_id="AADC")
+ dom_instance = MagicMock()
+ dom_instance.get_skyvern_element_by_id = AsyncMock(return_value=skyvern_el)
+
+ inc = MagicMock()
+ inc.start_listen_dom_increment = AsyncMock()
+ inc.stop_listen_dom_increment = AsyncMock()
+ inc.get_incremental_element_tree = AsyncMock(side_effect=error)
+
+ skyvern_frame = MagicMock()
+ skyvern_frame.safe_wait_for_animation_end = AsyncMock()
+
+ scraped_page = MagicMock()
+ scraped_page.id_to_element_dict = {"AADC": {"tagName": "input"}}
+
+ context = InputOrSelectContext(field="Account", is_search_bar=True, is_location_input=False)
+ action = InputTextAction(element_id="AADC", text="123456", reasoning="type the account number")
+
+ with (
+ patch("skyvern.webeye.actions.handler.DomUtil", return_value=dom_instance),
+ patch("skyvern.webeye.actions.handler.SkyvernFrame.create_instance", new=AsyncMock(return_value=skyvern_frame)),
+ patch("skyvern.webeye.actions.handler.IncrementalScrapePage", return_value=inc),
+ patch("skyvern.webeye.actions.handler.get_input_value", new=AsyncMock(return_value="")),
+ patch(
+ "skyvern.webeye.actions.handler.get_actual_value_of_parameter_if_secret_with_task",
+ return_value="123456",
+ ),
+ patch("skyvern.webeye.actions.handler._get_input_or_select_context", new=AsyncMock(return_value=context)),
+ ):
+ return await handle_input_text_action(
+ action=action, page=MagicMock(), scraped_page=scraped_page, task=_TASK, step=_STEP
+ )
+
+
+async def test_input_action_reraises_semantic_analysis_timeout() -> None:
+ """A ``SkyvernPageAnalysisTimeout`` out of incremental processing must propagate (former
+ Playwright-timeout behavior), never be swallowed into an ``ActionSuccess``."""
+ with pytest.raises(SkyvernPageAnalysisTimeout):
+ await _run_input_with_incremental_error(
+ SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
+ )
+
+
+async def test_input_action_still_swallows_unrelated_incremental_error() -> None:
+ """A genuinely unexpected non-timeout error in incremental processing keeps the pre-existing
+ tolerant behavior (logged and swallowed, action returns success) — the fix is scoped to the
+ semantic timeout only."""
+ results = await _run_input_with_incremental_error(RuntimeError("unexpected DOM state"))
+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)
diff --git a/tests/unit/test_navigation_recovery.py b/tests/unit/test_navigation_recovery.py
index 95ffc9e57..ec5062fff 100644
--- a/tests/unit/test_navigation_recovery.py
+++ b/tests/unit/test_navigation_recovery.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+import asyncio
from unittest.mock import ANY, AsyncMock
import pytest
from playwright._impl._errors import Error as PlaywrightError
+from skyvern.exceptions import SkyvernPageAnalysisTimeout
from skyvern.webeye.utils.page import (
SkyvernFrame,
_is_navigation_context_lost,
@@ -75,6 +77,32 @@ def _reference_error() -> PlaywrightError:
class TestEvaluateWithNavigationRecovery:
+ @pytest.mark.asyncio
+ async def test_evaluate_timeout_raises_skyvern_page_analysis_timeout(self) -> None:
+ frame = AsyncMock()
+ source_error = asyncio.TimeoutError()
+ frame.evaluate = AsyncMock(side_effect=source_error)
+
+ with pytest.raises(
+ SkyvernPageAnalysisTimeout, match="Skyvern timed out trying to analyze the page"
+ ) as exc_info:
+ await SkyvernFrame.evaluate(frame=frame, expression="() => 42", timeout_ms=30000)
+
+ assert exc_info.value.__cause__ is source_error
+
+ @pytest.mark.asyncio
+ async def test_navigation_recovery_deadline_raises_skyvern_page_analysis_timeout(self) -> None:
+ frame = AsyncMock()
+
+ with pytest.raises(SkyvernPageAnalysisTimeout, match="Skyvern timed out trying to analyze the page"):
+ await SkyvernFrame._evaluate_with_navigation_recovery(
+ frame=frame,
+ expression="() => 42",
+ evaluate_expression=AsyncMock(),
+ timeout_ms=0,
+ initial_error="execution context destroyed",
+ )
+
@pytest.mark.asyncio
async def test_recovers_after_one_context_destroyed(self) -> None:
"""First eval fails, re-inject + retry succeeds."""
diff --git a/tests/unit/test_page_ready_networkidle_tolerance.py b/tests/unit/test_page_ready_networkidle_tolerance.py
index 0b36ec44f..ecd016e56 100644
--- a/tests/unit/test_page_ready_networkidle_tolerance.py
+++ b/tests/unit/test_page_ready_networkidle_tolerance.py
@@ -2,7 +2,9 @@ import asyncio
from unittest.mock import AsyncMock
import pytest
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from skyvern.exceptions import SkyvernPageAnalysisTimeout
from skyvern.webeye.utils.page import SkyvernFrame
@@ -25,6 +27,44 @@ def _isolated_frame(side_effect: BaseException) -> SkyvernFrame:
return skyvern_frame
+def _span_attrs(span_exporter: InMemorySpanExporter, name: str) -> dict:
+ span = next((span for span in span_exporter.get_finished_spans() if span.name == name), None)
+ assert span is not None
+ return dict(span.attributes or {})
+
+
+async def test_wait_for_page_ready_classifies_loading_indicator_skyvern_analysis_timeout(
+ span_exporter: InMemorySpanExporter,
+) -> None:
+ skyvern_frame = _isolated_frame(Exception())
+ skyvern_frame.frame.wait_for_load_state = AsyncMock()
+ skyvern_frame._wait_for_loading_indicators_gone = AsyncMock(
+ side_effect=SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
+ )
+
+ await skyvern_frame.wait_for_page_ready()
+
+ attrs = _span_attrs(span_exporter, "skyvern.browser.page_ready.loading_indicators")
+ assert attrs.get("result") == "timeout"
+
+
+async def test_wait_for_page_ready_classifies_dom_stability_skyvern_analysis_timeout(
+ span_exporter: InMemorySpanExporter,
+) -> None:
+ skyvern_frame = _isolated_frame(Exception())
+ skyvern_frame.frame.wait_for_load_state = AsyncMock()
+ skyvern_frame._wait_for_dom_stable = AsyncMock(
+ side_effect=SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
+ )
+
+ await skyvern_frame.wait_for_page_ready()
+
+ attrs = _span_attrs(span_exporter, "skyvern.browser.page_ready.dom_stability")
+ assert attrs.get("result") == "timeout"
+
+
@pytest.mark.asyncio
async def test_wait_for_page_ready_swallows_foreign_networkidle_error() -> None:
skyvern_frame = _isolated_frame(_ForeignTimeoutError("Timeout 3000.0ms exceeded."))
diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.py
index 5ee342b11..3ad157bb8 100644
--- a/tests/unit/test_real_browser_manager.py
+++ b/tests/unit/test_real_browser_manager.py
@@ -10,7 +10,9 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from skyvern.webeye import real_browser_manager
from skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifact
+from skyvern.webeye.browser_engine import BrowserEngineMetadata, BrowserEngineSelection
from skyvern.webeye.browser_factory import set_popup_video_listener
from skyvern.webeye.real_browser_manager import RealBrowserManager
from skyvern.webeye.real_browser_state import RealBrowserState
@@ -1019,3 +1021,43 @@ async def test_pbs_recovery_falls_through_to_get_or_create_page_when_fresh_state
assert create_call.kwargs.get("url") == "https://example.com"
# We never re-attempted navigate_to_url on the fresh state (no page to use).
fresh.navigate_to_url.assert_not_awaited()
+
+
+class _EngineUnderTestError(Exception):
+ pass
+
+
+class _EngineUnderTestTimeout(_EngineUnderTestError):
+ pass
+
+
+async def test_create_browser_state_stamps_resolved_engine_selection() -> None:
+ """The exact BrowserEngineSelection resolved at the manager's ownership boundary
+ (get_or_resolve_engine_selection) must be the identical object pinned on the constructed
+ RealBrowserState, so a run's recovery/classification code binds to THIS run's engine identity
+ rather than a rebuilt or dropped selection."""
+ manager = RealBrowserManager()
+ fake_pw = MagicMock()
+ selection = BrowserEngineSelection(
+ name="engine-under-test",
+ start_driver=AsyncMock(return_value=fake_pw),
+ error_type=_EngineUnderTestError,
+ timeout_error_type=_EngineUnderTestTimeout,
+ metadata=BrowserEngineMetadata(name="engine-under-test", version="0.0.0"),
+ selection_reason="test",
+ )
+
+ with (
+ patch.object(manager, "get_or_resolve_engine_selection", AsyncMock(return_value=selection)),
+ patch.object(
+ real_browser_manager.BrowserContextFactory,
+ "create_browser_context",
+ AsyncMock(return_value=(MagicMock(), BrowserArtifacts(), None)),
+ ),
+ ):
+ state = await manager._create_browser_state(workflow_run_id="wr_engine_stamp")
+
+ assert state.engine_selection is selection
+ assert state.pw is fake_pw
+ selection.start_driver.assert_awaited_once()
diff --git a/tests/unit/test_scraper_engine_timeout_classification.py b/tests/unit/test_scraper_engine_timeout_classification.py
new file mode 100644
index 000000000..84da5c67f
--- /dev/null
+++ b/tests/unit/test_scraper_engine_timeout_classification.py
@@ -0,0 +1,141 @@
+"""``scrape_website`` timeout classification must follow the per-run selected browser engine's
+timeout family, not a hard-coded stock-Playwright ``isinstance`` — so a run pinned to a different
+engine still routes its native page-analysis timeouts to PAGE_LOAD_TIMEOUT, while a foreign
+exception (including another engine's timeout) is not misclassified as a timeout.
+
+These stay driver-agnostic: they pin fake engine selections and mock ``scrape_web_unsafe`` so they
+hold on an image shipping only stock Playwright.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, call, patch
+
+import pytest
+from playwright.async_api import Error as PlaywrightError
+from playwright.async_api import TimeoutError as PlaywrightTimeoutError
+
+from skyvern.exceptions import ScrapingFailed, SkyvernPageAnalysisTimeout
+from skyvern.webeye.browser_engine import BrowserEngineMetadata, BrowserEngineSelection
+from skyvern.webeye.scraper import scraper
+
+_TIMEOUT_REASON_MARKER = "page-analysis timeout"
+
+
+class _EngineAError(Exception):
+ pass
+
+
+class _EngineATimeout(_EngineAError):
+ pass
+
+
+async def _never_start(): # pragma: no cover - never awaited in these tests
+ raise AssertionError("start_driver must not be called")
+
+
+def _selection(name: str, error_type: type[BaseException], timeout_type: type[BaseException]) -> BrowserEngineSelection:
+ return BrowserEngineSelection(
+ name=name,
+ start_driver=_never_start,
+ error_type=error_type,
+ timeout_error_type=timeout_type,
+ metadata=BrowserEngineMetadata(name=name, version="0.0.0"),
+ selection_reason="test",
+ )
+
+
+def _browser_state(selection: BrowserEngineSelection | None) -> SimpleNamespace:
+ return SimpleNamespace(engine_selection=selection, get_working_page=AsyncMock(return_value=None))
+
+
+async def _run_scrape_and_capture(browser_state: SimpleNamespace, error: BaseException) -> ScrapingFailed:
+ with patch.object(scraper, "scrape_web_unsafe", AsyncMock(side_effect=error)):
+ with pytest.raises(ScrapingFailed) as exc_info:
+ await scraper.scrape_website(
+ browser_state, # type: ignore[arg-type]
+ "https://example.com/path?token=secret",
+ cleanup_element_tree=AsyncMock(),
+ max_retries=0,
+ )
+ return exc_info.value
+
+
+async def test_selected_engine_native_timeout_is_classified_as_timeout() -> None:
+ selection = _selection("engine-a", _EngineAError, _EngineATimeout)
+ failure = await _run_scrape_and_capture(_browser_state(selection), _EngineATimeout("deadline exceeded"))
+ assert _TIMEOUT_REASON_MARKER in (failure.reason or "")
+ assert isinstance(failure.__cause__, _EngineATimeout)
+
+
+async def test_skyvern_page_analysis_timeout_is_engine_neutral() -> None:
+ selection = _selection("engine-a", _EngineAError, _EngineATimeout)
+ failure = await _run_scrape_and_capture(
+ _browser_state(selection), SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
+ )
+ assert _TIMEOUT_REASON_MARKER in (failure.reason or "")
+ assert isinstance(failure.__cause__, SkyvernPageAnalysisTimeout)
+
+
+async def test_incremental_element_tree_retries_without_wait_after_skyvern_page_analysis_timeout() -> None:
+ frame = SimpleNamespace(url="https://example.com")
+ get_incremental_element_tree = AsyncMock(
+ side_effect=[
+ SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page"),
+ ([], []),
+ ]
+ )
+ skyvern_frame = SimpleNamespace(
+ get_frame=lambda: frame,
+ get_incremental_element_tree=get_incremental_element_tree,
+ )
+ cleanup_element_tree = AsyncMock(return_value=[])
+
+ incremental_page = scraper.IncrementalScrapePage(skyvern_frame=skyvern_frame) # type: ignore[arg-type]
+ result = await incremental_page.get_incremental_element_tree(cleanup_element_tree)
+
+ assert result == []
+ assert get_incremental_element_tree.await_args_list == [
+ call(wait_until_finished=True),
+ call(wait_until_finished=False),
+ ]
+ cleanup_element_tree.assert_awaited_once_with(frame, frame.url, [])
+
+
+async def test_foreign_engine_timeout_is_not_classified_as_timeout() -> None:
+ selection = _selection("engine-a", _EngineAError, _EngineATimeout)
+ failure = await _run_scrape_and_capture(_browser_state(selection), PlaywrightTimeoutError("pw timeout"))
+ assert _TIMEOUT_REASON_MARKER not in (failure.reason or "")
+ assert isinstance(failure.__cause__, PlaywrightTimeoutError)
+
+
+async def test_unrelated_exception_is_not_classified_as_timeout_and_is_not_swallowed() -> None:
+ selection = _selection("engine-a", _EngineAError, _EngineATimeout)
+ failure = await _run_scrape_and_capture(_browser_state(selection), ValueError("boom"))
+ assert _TIMEOUT_REASON_MARKER not in (failure.reason or "")
+ assert isinstance(failure.__cause__, ValueError)
+
+
+async def test_playwright_selection_preserves_stock_timeout_classification() -> None:
+ selection = _selection("playwright", PlaywrightError, PlaywrightTimeoutError)
+ failure = await _run_scrape_and_capture(_browser_state(selection), PlaywrightTimeoutError("pw timeout"))
+ assert _TIMEOUT_REASON_MARKER in (failure.reason or "")
+
+
+async def test_no_selection_falls_back_to_stock_playwright_timeout_identity() -> None:
+ failure = await _run_scrape_and_capture(_browser_state(None), PlaywrightTimeoutError("pw timeout"))
+ assert _TIMEOUT_REASON_MARKER in (failure.reason or "")
+
+
+async def test_no_selection_non_timeout_is_not_classified_as_timeout() -> None:
+ failure = await _run_scrape_and_capture(_browser_state(None), PlaywrightError("navigated away"))
+ assert _TIMEOUT_REASON_MARKER not in (failure.reason or "")
diff --git a/tests/unit/test_upload_file_wait.py b/tests/unit/test_upload_file_wait.py
index 26c33c6d8..292ac4c4a 100644
--- a/tests/unit/test_upload_file_wait.py
+++ b/tests/unit/test_upload_file_wait.py
@@ -12,6 +12,7 @@ import pytest
from playwright._impl._errors import Error as PlaywrightError
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
+from skyvern.exceptions import SkyvernPageAnalysisTimeout
from skyvern.webeye.actions import handler as handler_module
from skyvern.webeye.actions.handler import _wait_for_upload_processing
@@ -58,6 +59,16 @@ async def test_swallows_asyncio_timeout() -> None:
await _wait_for_upload_processing(AsyncMock())
+async def test_swallows_page_analysis_timeout_during_frame_creation() -> None:
+ with patch(
+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",
+ new_callable=AsyncMock,
+ side_effect=SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page"),
+ ):
+ await _wait_for_upload_processing(AsyncMock())
+
+
@pytest.mark.asyncio
async def test_swallows_playwright_error() -> None:
mock_frame = AsyncMock()