Skip to content

Automate browser based workflows with AI

Recover and classify stale frame/element targets in typing and frame resolution (SKY-12618, SKY-12558) (#7637)

Aaron Perez6836b2583d9f
diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.py
index b711f7664..8a97e2944 100644
--- a/skyvern/webeye/utils/dom.py
+++ b/skyvern/webeye/utils/dom.py
@@ -56,6 +56,14 @@ def is_incompatible_text_input_error(exc: BaseException) -> bool:
return "is not an" in str(exc).lower()
+def is_element_detached_error(exc: BaseException) -> bool:
+ # "Element is not attached to the DOM" (ElementHandle ops on a replaced node) and
+ # "Frame was detached" (ops routed through a frame that navigated or was removed)
+ # both mean the resolved target no longer exists in the live page.
+ message = str(exc).lower()
+ return "not attached to the dom" in message or "frame was detached" in message
+
+
def is_post_dispatch_click_timeout(exc: BaseException) -> bool:
"""A Playwright `TimeoutError` whose message references the post-click
auto-wait for scheduled navigations means the click was physically
@@ -95,7 +103,23 @@ async def resolve_locator(scrape_page: ScrapedPage, page: Page, frame: str, css:
if frame_handler is None:
raise NoneFrameError(frame_id=child_frame)
- content_frame = await frame_handler.content_frame()
+ try:
+ content_frame = await frame_handler.content_frame()
+ except PlaywrightError as exc:
+ if not is_element_detached_error(exc):
+ raise
+ # The iframe node detached between query_selector and content_frame (page
+ # mutation). Re-query once for a fresh handle; if it is gone or detaches
+ # again, classify as a missing element instead of leaking the raw error.
+ frame_handler = await current_frame.query_selector(f"[{SKYVERN_ID_ATTR}='{child_frame}']")
+ if frame_handler is None:
+ raise MissingElement(element_id=child_frame) from exc
+ try:
+ content_frame = await frame_handler.content_frame()
+ except PlaywrightError as retry_exc:
+ if not is_element_detached_error(retry_exc):
+ raise
+ raise MissingElement(element_id=child_frame) from retry_exc
if content_frame is None:
raise NoneFrameError(frame_id=child_frame)
current_frame = content_frame
@@ -942,15 +966,61 @@ class SkyvernElement:
async def focus(self, timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS) -> None:
await self.get_locator().focus(timeout=timeout)
+ async def refresh_locator_if_stale(self) -> None:
+ """Re-resolve via the tag-name xpath (same fallback as get_skyvern_element_by_id)
+ when the scraped css selector no longer matches — a page mutation replaced the node
+ and the stamped unique-id attribute went with it. Best-effort: swaps the locator
+ only on an unambiguous xpath match; a detach can be transient (mid re-render), so
+ anything else falls through to Playwright's own auto-wait instead of failing fast."""
+ if await self._safe_match_count(self.get_locator()) > 0:
+ return
+ xpath: str | None = self.get_element_dict().get("xpath")
+ if not xpath:
+ return
+ fresh_locator = self.get_frame().locator(f"xpath={xpath}")
+ if await self._safe_match_count(fresh_locator) == 1:
+ LOG.info(
+ "Re-resolved stale element locator by xpath",
+ element_id=self.get_id(),
+ xpath=xpath,
+ )
+ self.locator = fresh_locator
+
+ async def _safe_match_count(self, locator: Locator) -> int:
+ # count() itself raises when the locator's frame detached; that means 0 matches
+ # here, not a new error to surface.
+ try:
+ return await locator.count()
+ except PlaywrightError as exc:
+ if is_element_detached_error(exc):
+ return 0
+ raise
+
+ async def _classify_typing_timeout(self, exc: TimeoutError) -> None:
+ """Raise MissingElement when the typing target vanished mid-action; otherwise
+ return so the caller re-raises the original timeout (a readiness problem)."""
+ if await self._safe_match_count(self.get_locator()) == 0:
+ raise MissingElement(element_id=self.get_id()) from exc
+
async def input_sequentially(self, text: str, default_timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS) -> None:
- await handler_utils.input_sequentially(self.get_locator(), text, timeout=default_timeout)
+ await self.refresh_locator_if_stale()
+ try:
+ await handler_utils.input_sequentially(self.get_locator(), text, timeout=default_timeout)
+ except TimeoutError as exc:
+ await self._classify_typing_timeout(exc)
+ raise
async def press_key(self, key: str, timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS) -> None:
await self.get_locator().press(key=key, timeout=timeout)
async def press_fill(self, text: str, timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS) -> None:
+ await self.refresh_locator_if_stale()
locator = self.get_locator()
- await EventStrategyFactory.type_text(locator.page, locator, text)
+ try:
+ await EventStrategyFactory.type_text(locator.page, locator, text)
+ except TimeoutError as exc:
+ await self._classify_typing_timeout(exc)
+ raise
async def input(self, text: str, timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS) -> None:
if self.get_tag_name().lower() not in COMMON_INPUT_TAGS:
diff --git a/tests/unit/test_stale_context_guards.py b/tests/unit/test_stale_context_guards.py
new file mode 100644
index 000000000..b00e9fc22
--- /dev/null
+++ b/tests/unit/test_stale_context_guards.py
@@ -0,0 +1,168 @@
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from playwright.async_api import Error as PlaywrightError
+from playwright.async_api import TimeoutError as PlaywrightTimeoutError
+
+from skyvern.exceptions import MissingElement
+from skyvern.webeye.utils.dom import SkyvernElement, is_element_detached_error, resolve_locator
+
+_DETACHED_ERROR = "ElementHandle.content_frame: Element is not attached to the DOM"
+_FRAME_DETACHED_ERROR = "Locator.count: Frame was detached"
+_TYPE_TIMEOUT_ERROR = "Locator.type: Timeout 10000ms exceeded."
+
+
+def test_predicate_matches_detached_errors() -> None:
+ assert is_element_detached_error(PlaywrightError(_DETACHED_ERROR)) is True
+ assert is_element_detached_error(PlaywrightError(_FRAME_DETACHED_ERROR)) is True
+ assert is_element_detached_error(PlaywrightTimeoutError(_TYPE_TIMEOUT_ERROR)) is False
+
+
+def _scrape_page_with_frame() -> MagicMock:
+ scraped_page = MagicMock()
+ scraped_page.id_to_element_dict = {"frame-1": {"id": "frame-1", "frame": "main.frame"}}
+ return scraped_page
+
+
+def _frame_handler(content_frame_result: object) -> MagicMock:
+ handler = MagicMock()
+ if isinstance(content_frame_result, BaseException):
+ handler.content_frame = AsyncMock(side_effect=content_frame_result)
+ else:
+ handler.content_frame = AsyncMock(return_value=content_frame_result)
+ return handler
+
+
+async def test_resolve_locator_requeries_detached_iframe_handle() -> None:
+ content = MagicMock()
+ page = MagicMock()
+ page.query_selector = AsyncMock(
+ side_effect=[_frame_handler(PlaywrightError(_DETACHED_ERROR)), _frame_handler(content)]
+ )
+ _, frame = await resolve_locator(_scrape_page_with_frame(), page, "frame-1", "[unique_id='el-1']")
+ assert frame is content
+ assert page.query_selector.await_count == 2
+
+
+async def test_resolve_locator_classifies_iframe_gone_after_detach() -> None:
+ page = MagicMock()
+ page.query_selector = AsyncMock(side_effect=[_frame_handler(PlaywrightError(_DETACHED_ERROR)), None])
+ with pytest.raises(MissingElement):
+ await resolve_locator(_scrape_page_with_frame(), page, "frame-1", "[unique_id='el-1']")
+
+
+async def test_resolve_locator_classifies_repeated_detach() -> None:
+ page = MagicMock()
+ page.query_selector = AsyncMock(
+ side_effect=[
+ _frame_handler(PlaywrightError(_DETACHED_ERROR)),
+ _frame_handler(PlaywrightError(_DETACHED_ERROR)),
+ ]
+ )
+ with pytest.raises(MissingElement):
+ await resolve_locator(_scrape_page_with_frame(), page, "frame-1", "[unique_id='el-1']")
+
+
+async def test_resolve_locator_reraises_unrelated_errors() -> None:
+ page = MagicMock()
+ page.query_selector = AsyncMock(side_effect=[_frame_handler(PlaywrightError("Protocol error"))])
+ with pytest.raises(PlaywrightError):
+ await resolve_locator(_scrape_page_with_frame(), page, "frame-1", "[unique_id='el-1']")
+
+
+def _make_element(locator: MagicMock, frame: MagicMock | None = None, xpath: str | None = None) -> SkyvernElement:
+ static_element: dict = {"id": "el-1", "tagName": "input"}
+ if xpath:
+ static_element["xpath"] = xpath
+ return SkyvernElement(locator, frame or MagicMock(), static_element)
+
+
+def _locator_with_counts(*counts: object) -> MagicMock:
+ locator = MagicMock()
+ locator.count = AsyncMock(side_effect=list(counts))
+ return locator
+
+
+async def test_input_sequentially_reresolves_stale_locator_by_xpath(monkeypatch: pytest.MonkeyPatch) -> None:
+ fresh_locator = _locator_with_counts(1)
+ frame = MagicMock()
+ frame.locator.return_value = fresh_locator
+ element = _make_element(_locator_with_counts(0), frame=frame, xpath="//form/input")
+
+ typed_with = AsyncMock()
+ monkeypatch.setattr("skyvern.webeye.actions.handler_utils.input_sequentially", typed_with)
+ await element.input_sequentially("hello")
+
+ frame.locator.assert_called_once_with("xpath=//form/input")
+ assert element.get_locator() is fresh_locator
+ assert typed_with.await_args.args[0] is fresh_locator
+
+
+async def test_input_sequentially_keeps_locator_on_ambiguous_xpath(monkeypatch: pytest.MonkeyPatch) -> None:
+ stale_locator = _locator_with_counts(0)
+ frame = MagicMock()
+ frame.locator.return_value = _locator_with_counts(2)
+ element = _make_element(stale_locator, frame=frame, xpath="//form/input")
+
+ typed_with = AsyncMock()
+ monkeypatch.setattr("skyvern.webeye.actions.handler_utils.input_sequentially", typed_with)
+ await element.input_sequentially("hello")
+
+ assert element.get_locator() is stale_locator
+
+
+async def test_input_sequentially_treats_detached_frame_count_as_stale(monkeypatch: pytest.MonkeyPatch) -> None:
+ fresh_locator = _locator_with_counts(1)
+ frame = MagicMock()
+ frame.locator.return_value = fresh_locator
+ element = _make_element(
+ _locator_with_counts(PlaywrightError(_FRAME_DETACHED_ERROR)), frame=frame, xpath="//form/input"
+ )
+
+ monkeypatch.setattr("skyvern.webeye.actions.handler_utils.input_sequentially", AsyncMock())
+ await element.input_sequentially("hello")
+
+ assert element.get_locator() is fresh_locator
+
+
+async def test_input_sequentially_classifies_timeout_when_element_gone(monkeypatch: pytest.MonkeyPatch) -> None:
+ element = _make_element(_locator_with_counts(1, 0))
+ monkeypatch.setattr(
+ "skyvern.webeye.actions.handler_utils.input_sequentially",
+ AsyncMock(side_effect=PlaywrightTimeoutError(_TYPE_TIMEOUT_ERROR)),
+ )
+ with pytest.raises(MissingElement):
+ await element.input_sequentially("hello")
+
+
+async def test_input_sequentially_reraises_timeout_when_element_present(monkeypatch: pytest.MonkeyPatch) -> None:
+ element = _make_element(_locator_with_counts(1, 1))
+ monkeypatch.setattr(
+ "skyvern.webeye.actions.handler_utils.input_sequentially",
+ AsyncMock(side_effect=PlaywrightTimeoutError(_TYPE_TIMEOUT_ERROR)),
+ )
+ with pytest.raises(PlaywrightTimeoutError):
+ await element.input_sequentially("hello")
+
+
+async def test_press_fill_classifies_timeout_when_element_gone(monkeypatch: pytest.MonkeyPatch) -> None:
+ element = _make_element(_locator_with_counts(1, 0))
+
+ async def _raise(*args: object, **kwargs: object) -> None:
+ raise PlaywrightTimeoutError(_TYPE_TIMEOUT_ERROR)
+
+ monkeypatch.setattr("skyvern.webeye.utils.dom.EventStrategyFactory.type_text", _raise)
+ with pytest.raises(MissingElement):
+ await element.press_fill("hello")