Skip to content

Automate browser based workflows with AI

Never pair a failed code block's page URL with another page's title (SKY-17711) (#8802)

Andrew Neilsone964995c0b24
diff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.py
index fe9b1dca9..1ff60c56f 100644
--- a/skyvern/forge/sdk/copilot/tools/_shared.py
+++ b/skyvern/forge/sdk/copilot/tools/_shared.py
@@ -533,9 +533,10 @@ async def _fallback_page_info(
# page.url is a synchronous property, so it is already in hand when the title stalls, and most
# callers here destructure the title away and want only the url.
url = ""
+ page: Page | None = None
async def _read() -> str:
- nonlocal url
+ nonlocal url, page
browser_state = await resolve_browser_state_for_context(ctx, session_id=session_id)
if not browser_state:
return ""
@@ -548,13 +549,16 @@ async def _fallback_page_info(
# page.title() waits on the renderer, so a wedged or busy page hangs here forever rather than
# raising — and every caller reaches this path, since a tool result's browser_context carries
# no url. Without the bound, one unreachable page deadlocks the whole turn.
+ title = ""
try:
title = await asyncio.wait_for(_read(), timeout=_DISCOVERY_PER_CALL_TIMEOUT_SECONDS)
except TimeoutError:
LOG.info("copilot page title read timed out", session_id=session_id, page_url=url)
- return url, ""
except Exception:
- return url, ""
+ pass
+ # A document committed during title() would pair one document's url with another's title.
+ if page is not None and page.url != url:
+ return page.url, ""
return url, title
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index f58dddf79..7419018ad 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -8608,10 +8608,14 @@ async def wrapper({default_args}):
return "".join(char for char in redacted if unicodedata.category(char)[0] != "C").strip()[:1000] or None
state: dict[str, str] = {}
+ first_url: str | None = None
+ later_url: str | None = None
+ page_title: str | None = None
try:
async with asyncio.timeout(0.5):
try:
- final_url = mask_fact(page.url)
+ first_url = page.url
+ final_url = mask_fact(first_url)
if final_url:
state["final_url"] = final_url
except asyncio.CancelledError:
@@ -8620,12 +8624,15 @@ async def wrapper({default_args}):
pass
try:
page_title = mask_fact(await page.title())
- if page_title:
- state["page_title"] = page_title
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001 - failure evidence is best effort.
pass
+ finally:
+ with contextlib.suppress(Exception):
+ later_url = page.url
+ if later_url != first_url and (later_final_url := mask_fact(later_url)):
+ state["final_url"] = later_final_url
try:
receiver_url = mask_fact(receiver.url) if receiver is not None else None
if receiver_url:
@@ -8647,6 +8654,9 @@ async def wrapper({default_args}):
raise
except TimeoutError:
pass
+ # A document committed after the first url read would pair one document's URL with another's title.
+ if page_title and first_url is not None and later_url == first_url:
+ state["page_title"] = page_title
return state
async def _persist_captured_failure_final_url(
diff --git a/tests/unit/test_copilot_credential_pause.py b/tests/unit/test_copilot_credential_pause.py
index 5d2b76a0b..90fa7a343 100644
--- a/tests/unit/test_copilot_credential_pause.py
+++ b/tests/unit/test_copilot_credential_pause.py
@@ -3022,9 +3022,13 @@ class _RegistrationVault:
logging.getLogger("skyvern.test.vault").exception("vault create failed")
raise HTTPException(status_code=502, detail=f"Custom credential service returned HTTP 500 for {data.name}")
self.stored += 1
- tasks.add_task(self.hooks_run.append, self.credential.credential_id)
+ tasks.add_task(self._run_hook, self.credential.credential_id)
return self.credential
+ # Starlette sends a sync task to a worker thread, so a sync append lands whenever that thread runs.
+ async def _run_hook(self, credential_id: str) -> None:
+ self.hooks_run.append(credential_id)
+
async def create_credential(
self, organization_id: str, data: CreateCredentialRequest, created_by: str | None
) -> Credential:
diff --git a/tests/unit/test_copilot_watchdog.py b/tests/unit/test_copilot_watchdog.py
index acc918e92..9045b62ae 100644
--- a/tests/unit/test_copilot_watchdog.py
+++ b/tests/unit/test_copilot_watchdog.py
@@ -30,6 +30,7 @@ from skyvern.forge.sdk.copilot.tools import (
_fallback_page_info,
_read_progress_sources,
_run_blocks_and_collect_debug,
+ _shared,
_watchdog_error_message,
run_execution,
)
@@ -174,23 +175,27 @@ class _ErrorCtx:
origin_run_redaction_registry = None
-async def test_fallback_page_info_uses_persistent_session_state_without_sdk_reconnect(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from skyvern.forge import app as forge_app
-
- page = SimpleNamespace(url="https://example.test/current", title=AsyncMock(return_value="Current page"))
+def _install_fallback_page(
+ monkeypatch: pytest.MonkeyPatch, page: SimpleNamespace
+) -> tuple[SimpleNamespace, SimpleNamespace]:
browser_state = SimpleNamespace(get_or_create_page=AsyncMock(return_value=page))
session_manager = SimpleNamespace(get_browser_state=AsyncMock(return_value=browser_state))
monkeypatch.setattr(forge_app, "PERSISTENT_SESSIONS_MANAGER", session_manager)
-
ctx = SimpleNamespace(
organization_id="o_test",
browser_session_id="pbs_copilot",
turn_origin=TurnOrigin.interactive,
attached_browser_drivers={},
)
+ return session_manager, ctx
+
+
+async def test_fallback_page_info_uses_persistent_session_state_without_sdk_reconnect(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ page = SimpleNamespace(url="https://example.test/current", title=AsyncMock(return_value="Current page"))
+ session_manager, ctx = _install_fallback_page(monkeypatch, page)
current_url, page_title = await _fallback_page_info(ctx)
@@ -209,32 +214,40 @@ async def test_fallback_page_info_bounds_a_title_that_never_resolves_and_keeps_t
"""A wedged renderer hangs `title()` rather than raising it. The bound has to return, and it
has to keep the url — `page.url` is synchronous, so it is already in hand when the title
stalls, and most callers of this helper want only the url."""
- from skyvern.forge import app as forge_app
- from skyvern.forge.sdk.copilot.tools import _shared
async def _never_resolves() -> str:
await asyncio.Event().wait()
return "unreachable"
page = SimpleNamespace(url="https://example.test/wedged", title=_never_resolves)
- browser_state = SimpleNamespace(get_or_create_page=AsyncMock(return_value=page))
- session_manager = SimpleNamespace(get_browser_state=AsyncMock(return_value=browser_state))
- monkeypatch.setattr(forge_app, "PERSISTENT_SESSIONS_MANAGER", session_manager)
+ _, ctx = _install_fallback_page(monkeypatch, page)
monkeypatch.setattr(_shared, "_DISCOVERY_PER_CALL_TIMEOUT_SECONDS", 0.05)
- ctx = SimpleNamespace(
- organization_id="o_test",
- browser_session_id="pbs_copilot",
- turn_origin=TurnOrigin.interactive,
- attached_browser_drivers={},
- )
-
current_url, page_title = await asyncio.wait_for(_fallback_page_info(ctx), timeout=5)
assert current_url == "https://example.test/wedged"
assert page_title == ""
[email protected]("title_raises", [False, True])
+async def test_fallback_page_info_never_pairs_a_title_with_another_documents_url(
+ monkeypatch: pytest.MonkeyPatch, title_raises: bool
+) -> None:
+ page = SimpleNamespace(url="https://portal.fixture.test/login")
+
+ async def _title_across_navigation() -> str:
+ page.url = "https://portal.fixture.test/dashboard"
+ if title_raises:
+ raise RuntimeError("Execution context was destroyed, most likely because of a navigation")
+ return "Ops Portal"
+
+ page.title = _title_across_navigation
+ _, ctx = _install_fallback_page(monkeypatch, page)
+
+ assert await _fallback_page_info(ctx) == ("https://portal.fixture.test/dashboard", "")
+
+
@pytest.mark.asyncio
async def test_ceiling_error_message_advises_splitting() -> None:
"""The error must tell the LLM to split the workflow, not retry — a longer run won't fit either."""
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index 64e6dd658..1806dbdd2 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -3046,13 +3046,19 @@ async def test_failure_locator_tracks_exact_exception_without_reparsing_selector
assert recording.failure_locator(caught.value) is None
+def _passthrough_codeblock_redaction(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ block_module.app,
+ "AGENT_FUNCTION",
+ SimpleNamespace(redact_codeblock_parameter_values=lambda value, _parameters, **_budget: value),
+ )
+
+
@pytest.mark.asyncio
async def test_inline_timeout_snapshot_masks_before_bounding_and_uses_exact_locator(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The inline diagnostic reads the recorded locator, never a selector parsed from the error."""
- from skyvern.forge.sdk.workflow.models import block as block_module
-
secret = "credential-secret"
exception = PlaywrightTimeoutError("locator timed out")
@@ -3072,11 +3078,7 @@ async def test_inline_timeout_snapshot_masks_before_bounding_and_uses_exact_loca
recording = RecordingPage(SnapshotPage())
locator = TimedOutLocator()
monkeypatch.setattr(RecordingPage, "failure_locator", lambda _self, exc: locator if exc is exception else None)
- monkeypatch.setattr(
- block_module.app,
- "AGENT_FUNCTION",
- SimpleNamespace(redact_codeblock_parameter_values=lambda value, _parameters, **_budget: value),
- )
+ _passthrough_codeblock_redaction(monkeypatch)
context = SimpleNamespace(mask_secrets_in_data=lambda value: value.replace(secret, "*****"))
block = _make_code_block("pass")
@@ -3100,6 +3102,98 @@ async def test_inline_timeout_snapshot_masks_before_bounding_and_uses_exact_loca
) == {"final_url": "https://fixture.test/checkout?token=*****", "page_title": state["page_title"]}
+ ("navigates_during", "expected_state"),
+ [
+ ("title", {"final_url": "https://portal.fixture.test/dashboard"}),
+ ("title_raises", {"final_url": "https://portal.fixture.test/dashboard"}),
+ (
+ "covering_element",
+ {
+ "final_url": "https://portal.fixture.test/login",
+ "page_title": "Ops Portal",
+ "covering_element": "div.banner",
+ },
+ ),
+ ],
+)
+async def test_inline_failure_snapshot_never_pairs_a_title_with_another_documents_url(
+ monkeypatch: pytest.MonkeyPatch, navigates_during: str, expected_state: dict[str, str]
+) -> None:
+ class NavigatingPage(FakePage):
+ def __init__(self) -> None:
+ super().__init__()
+ self.url = "https://portal.fixture.test/login"
+
+ async def title(self) -> str:
+ if navigates_during != "covering_element":
+ self.url = "https://portal.fixture.test/dashboard"
+ if navigates_during == "title_raises":
+ raise RuntimeError("Execution context was destroyed, most likely because of a navigation")
+ return "Ops Portal"
+
+ page = NavigatingPage()
+
+ class NavigatingLocator:
+ async def evaluate(self, _script: str) -> str:
+ page.url = "https://portal.fixture.test/dashboard"
+ return "div.banner"
+
+ _passthrough_codeblock_redaction(monkeypatch)
+ state = await _make_code_block("pass")._capture_inline_failure_page_state(
+ page=RecordingPage(page),
+ failure_locator=NavigatingLocator() if navigates_during == "covering_element" else None,
+ workflow_run_context=SimpleNamespace(mask_secrets_in_data=lambda value: value),
+ redaction_parameters={},
+ )
+
+ assert state == expected_state
+
+
+ ("failing_url_reads", "expected_state"),
+ [
+ ({2}, {"final_url": "https://portal.fixture.test/login"}),
+ ({1}, {"final_url": "https://portal.fixture.test/dashboard"}),
+ ({1, 2}, {}),
+ ],
+)
+async def test_inline_failure_snapshot_drops_the_title_when_the_first_url_read_or_the_url_reread_fails(
+ monkeypatch: pytest.MonkeyPatch, failing_url_reads: set[int], expected_state: dict[str, str]
+) -> None:
+ class UrlReadFailsPage(FakePage):
+ def __init__(self) -> None:
+ super().__init__()
+ self.url_reads = 0
+ self.urls = ["https://portal.fixture.test/login", "https://portal.fixture.test/dashboard"]
+
+ @property
+ def url(self) -> str:
+ self.url_reads += 1
+ if self.url_reads in failing_url_reads:
+ raise RuntimeError("Execution context was destroyed, most likely because of a navigation")
+ return self.urls[self.url_reads - 1]
+
+ @url.setter
+ def url(self, _value: str) -> None:
+ pass
+
+ async def title(self) -> str:
+ return "Ops Portal"
+
+ _passthrough_codeblock_redaction(monkeypatch)
+ state = await _make_code_block("pass")._capture_inline_failure_page_state(
+ page=RecordingPage(UrlReadFailsPage()),
+ failure_locator=None,
+ workflow_run_context=SimpleNamespace(mask_secrets_in_data=lambda value: value),
+ redaction_parameters={},
+ )
+
+ assert state == expected_state
+
+
@pytest.mark.asyncio
async def test_later_page_operation_invalidates_an_inflight_failure_locator():
from playwright.async_api import TimeoutError as PlaywrightTimeoutError