Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Recover adopted-session statement downloads from live and transient PDF blobs (SKY-12621) (#8007)
LawyZhenge7266fb8b0d0
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex 5fcccc69d..ba402ef18 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -189,8 +189,11 @@ from skyvern.webeye.utils.dom import (from skyvern.webeye.utils.page import (SkyvernFrame,_all_page_frames,+ _blob_url_origin,apply_secret_visual_mask_to_active_element,+ probe_blob_action_freshness,take_element_screenshot,+ teardown_blob_url_retention,)LOG = structlog.get_logger()@@ -925,6 +928,27 @@ class _EagerAdoptedBlobCapture:)+async def _close_eager_capture_then_teardown_retention(+ eager_blob_capture: _EagerAdoptedBlobCapture,+ page: Page,+ *,+ browser_session_id: str | None,+ workflow_run_id: str | None,+) -> None:+ # aclose() can re-raise CancelledError when the enclosing action is cancelled; the retention+ # wrapper patches page-realm URL.createObjectURL/revokeObjectURL and must be torn down anyway, or+ # a cancelled adopted session leaks the patched globals. The original cancellation still+ # propagates after the finally, and a teardown failure stays fail-open/debug-only.+ try:+ await eager_blob_capture.aclose()+ finally:+ if browser_session_id:+ try:+ await teardown_blob_url_retention(page, workflow_run_id=workflow_run_id)+ except Exception:+ LOG.debug("Failed to tear down blob URL retention", workflow_run_id=workflow_run_id)++async def _save_adopted_session_download(download: Download,page: Page,@@ -978,6 +1002,29 @@ async def _save_adopted_session_download(if download.url.startswith("blob:"):blob_bytes = await _read_adopted_session_blob_bytes(download, page, workflow_run_id=workflow_run_id)if blob_bytes is None:+ # The download event's own blob is unreadable (owner torn down / remote-CDP), but the+ # statement is often still displayed in a live same-origin blob: PDF iframe whose bytes+ # are recoverable. Bounded by the same budget as blocked-inline-PDF recovery.+ recovered_bytes: bytes | None = None+ try:+ async with asyncio.timeout(_BLOCKED_INLINE_PDF_RECOVERY_TIMEOUT_SECONDS):+ recovered_bytes = await _recover_adopted_session_blob_pdf_iframe(page, download, workflow_run_id)+ except asyncio.TimeoutError:+ LOG.warning(+ "Adopted-session blob PDF iframe recovery exceeded its budget; treating as no recovery",+ workflow_run_id=workflow_run_id,+ recovery_budget_seconds=_BLOCKED_INLINE_PDF_RECOVERY_TIMEOUT_SECONDS,+ )+ if recovered_bytes is not None:+ download_target.write_bytes(recovered_bytes)+ LOG.info(+ "Recovered adopted-session statement from a live blob: PDF iframe",+ download_dir=str(download_dir),+ workflow_run_id=workflow_run_id,+ recovered_bytes=len(recovered_bytes),+ download_target=str(download_target),+ )+ return download_targetLOG.warning("Adopted-session blob download could not be read from any open page",download_dir=str(download_dir),@@ -1132,6 +1179,142 @@ def _looks_like_pdf(data: bytes) -> bool:return header[:5] == b"%PDF-"+_BLOB_IFRAME_SRC_TITLE_JS = (+ "() => Array.from(document.querySelectorAll('iframe')).map((f) => [f.src || '', f.title || ''])"+)+++def _strip_url_fragment(url: str) -> str:+ return url.split("#", 1)[0]+++async def _blob_iframe_src_titles(page: Page) -> dict[str, str]:+ """Map each blob: <iframe> src (fragment-stripped) to its title attribute, across every frame."""+ mapping: dict[str, str] = {}+ main_frame = page.main_frame+ for frame in _all_page_frames(page):+ target: Page | Frame = page if frame is main_frame else frame+ try:+ pairs = await SkyvernFrame.evaluate(frame=target, expression=_BLOB_IFRAME_SRC_TITLE_JS)+ except Exception:+ continue+ if not isinstance(pairs, list):+ continue+ for pair in pairs:+ if not isinstance(pair, (list, tuple)) or len(pair) != 2:+ continue+ src, title = pair+ if isinstance(src, str) and src.startswith("blob:"):+ mapping.setdefault(_strip_url_fragment(src), title if isinstance(title, str) else "")+ return mapping+++async def _read_blob_pdf_bytes(page: Page, blob_url: str, workflow_run_id: str | None) -> bytes | None:+ """Read a blob: URL and return its bytes only when they are a non-empty PDF, else None."""+ data = await SkyvernFrame.read_blob_url_bytes(+ page=page,+ blob_url=blob_url,+ workflow_run_id=workflow_run_id,+ max_size_bytes=MAX_FILE_SIZE_BYTES,+ probe=True,+ )+ if data and _looks_like_pdf(data):+ return data+ return None+++async def _recover_adopted_session_blob_pdf_iframe(+ page: Page, download: Download, workflow_run_id: str | None+) -> bytes | None:+ """Best-effort recovery of a statement PDF from a live same-origin blob: <iframe> when the download's own bytes are lost.++ An adopted/persistent session can fire a client-side blob download whose bytes are unrecoverable+ (empty ``save_as`` and an unfetchable download URL) while the statement is still displayed in a+ same-origin ``blob:`` PDF iframe — a different, still-live object readable from the document that+ minted it. Candidates come from the iframe ``src`` attribute, not ``frame.url``: Chromium's built-in+ PDF viewer reports the framed document's URL as ``about:blank`` while the element keeps its blob src.++ Matching the download's suggested filename against exactly one iframe title basename is a+ conservative correlation, not proof that the iframe holds the requested document — a stale iframe+ left from an earlier same-named document could still match. It is chosen because it is far safer+ than trusting whatever single PDF happens to be on screen. No suggested filename, no match, or+ several equally-titled matches all fail closed (return None) — an ambiguous or unmatched viewer is+ never saved. The matched candidate is scoped to the download's blob origin, capped at+ ``MAX_FILE_SIZE_BYTES``, and must carry PDF magic. Because this is a best-effort backstop, any+ page/frame access error during candidate discovery or reading also fails closed.+ """+ download_origin = _blob_url_origin(download.url)+ if download_origin is None:+ return None++ suggested = os.path.basename(download.suggested_filename or "").strip().lower()+ if not suggested:+ # Non-sensitive: reason + booleans/counts only, never filename/title/blob URL/domain.+ LOG.info(+ "Adopted-session blob PDF iframe recovery skipped",+ workflow_run_id=workflow_run_id,+ reason="missing_suggested_filename",+ )+ return None++ try:+ src_titles = await _blob_iframe_src_titles(page)+ same_origin_candidates = [src for src in src_titles if _blob_url_origin(src) == download_origin]+ named = [+ src for src in same_origin_candidates if os.path.basename(src_titles[src]).strip().lower() == suggested+ ]++ if len(named) == 1:+ # Freshness gate: the candidate blob must be a live key in this action window's retention+ # Map, proving it was minted through the pre-click wrapper. A lingering iframe reusing a+ # common filename would otherwise pass the title/PDF gates and save the wrong document.+ freshness = await probe_blob_action_freshness(page, named[0], workflow_run_id=workflow_run_id)+ if not freshness.retained:+ LOG.info(+ "Adopted-session blob PDF iframe recovery skipped",+ workflow_run_id=workflow_run_id,+ reason="not_action_fresh" if freshness.state_observed else "retention_state_unobservable",+ )+ return None+ # The single filename match must itself be a real PDF; otherwise fail closed rather than+ # fall back to any other on-screen blob iframe.+ return await _read_blob_pdf_bytes(page, named[0], workflow_run_id)++ if len(named) > 1:+ LOG.warning(+ "Adopted-session blob PDF iframe recovery skipped",+ workflow_run_id=workflow_run_id,+ reason="duplicate_filename_match",+ candidate_count=len(same_origin_candidates),+ match_count=len(named),+ )+ elif not same_origin_candidates:+ LOG.info(+ "Adopted-session blob PDF iframe recovery skipped",+ workflow_run_id=workflow_run_id,+ reason="no_same_origin_blob_iframe",+ candidate_count=0,+ )+ else:+ LOG.info(+ "Adopted-session blob PDF iframe recovery skipped",+ workflow_run_id=workflow_run_id,+ reason="no_filename_title_match",+ candidate_count=len(same_origin_candidates),+ )+ return None+ except Exception as exc:+ # Best-effort backstop: a page/frame torn down mid-discovery (e.g. remote session closing)+ # must fail closed, not raise. CancelledError (BaseException) still propagates.+ LOG.warning(+ "Adopted-session blob PDF iframe recovery skipped",+ workflow_run_id=workflow_run_id,+ reason="recovery_error",+ error_type=type(exc).__name__,+ )+ return None++async def _collect_inline_iframe_src_candidates(page: Page) -> list[str]:"""Every http(s) <iframe> src on the page, deduped, order-preserving.@@ -3473,7 +3656,12 @@ class ActionHandler:# Fallback for exceptional exits that never reached the post-action stamp.if action.finished_at is None:action.finished_at = naive_utc_now()- await eager_blob_capture.aclose()+ await _close_eager_capture_then_teardown_retention(+ eager_blob_capture,+ page,+ browser_session_id=task.browser_session_id,+ workflow_run_id=task.workflow_run_id,+ )for observed_popup, popup_callback in download_popup_callbacks:try:_remove_download_listener(observed_popup, popup_callback)diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.pyindex 582087093..64bc5d523 100644--- a/skyvern/webeye/utils/page.py+++ b/skyvern/webeye/utils/page.py@@ -9,7 +9,7 @@ import urllib.parsefrom collections.abc import Awaitable, Callablefrom enum import StrEnumfrom io import BytesIO-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, NamedTupleimport structlogfrom opentelemetry import trace as otel_trace@@ -741,6 +741,279 @@ def _all_page_frames(page: Page) -> list[Frame]:return frames+MAX_RETAINED_BLOB_COUNT = 8+MAX_RETAINED_BLOB_TOTAL_BYTES = 100 * 1024 * 1024++_BLOB_RETENTION_STATE_KEY = "__skyvernBlobRetention"+# Stable ownership brand + schema version. A same-name page global is only ever mutated, restored, or+# trusted as fresh when it carries this brand/version AND the full member schema below; anything else+# (a page's own global, a corrupt/partial state, or one whose wrappers are no longer the active URL+# methods) is left untouched and never read as owned.+_BLOB_RETENTION_BRAND = "skyvern.blobRetention"+_BLOB_RETENTION_VERSION = 1++# Injected into every retention JS block. `isOwned` validates the complete schema needed for safe+# exact-native restoration (origCreate/origRevoke), retained-map clearing/revocation (retained/deferred),+# wrapper identity (wrapCreate/wrapRevoke), and closure neutralization (active). Restores compare each+# URL method to its exact Skyvern wrapper independently, so a page hook is never clobbered.+_BLOB_RETENTION_OWNERSHIP_JS = f"""+ const KEY = '{_BLOB_RETENTION_STATE_KEY}';+ const BRAND = '{_BLOB_RETENTION_BRAND}';+ const VERSION = {_BLOB_RETENTION_VERSION};+ const isOwned = (s) => !!s && s.brand === BRAND && s.version === VERSION+ && typeof s.origCreate === 'function' && typeof s.origRevoke === 'function'+ && (s.retained instanceof Map) && (s.deferred instanceof Set)+ && typeof s.wrapCreate === 'function' && typeof s.wrapRevoke === 'function'+ && typeof s.active === 'boolean';+"""++# Wrap URL.createObjectURL/revokeObjectURL in the page realm so a PDF-shaped object URL minted during+# the action window survives a synchronous revoke long enough for the in-page read to recover its bytes.+# Both wrappers return their native values; only PDF-typed (or untyped) blobs are retained, bounded by+# count and total size; every other blob revokes natively so unrelated downloads are unaffected.+_BLOB_RETENTION_INSTALL_JS = (+ "(config) => {"+ + _BLOB_RETENTION_OWNERSHIP_JS+ + """+ if (Object.prototype.hasOwnProperty.call(window, KEY)) {+ const existing = window[KEY];+ // Any existing own property that is not a valid owned state is foreign (a page's own global,+ // including a null/undefined placeholder): never overwrite, delete, or modify it, and never touch+ // the URL methods. Fail open (no retention).+ if (!isOwned(existing)) return false;+ // Valid owned stale state (a prior window that never tore down), possibly with the page having+ // rewrapped one or both URL methods. Neutralize the closures first, settle the deferred revokes,+ // restore ONLY each method that still directly equals our wrapper (preserve any page hook), clear+ // the maps, and drop the state — regardless of any wrapper mismatch — so no prior key stays fresh.+ existing.active = false;+ try {+ if (URL.createObjectURL === existing.wrapCreate) URL.createObjectURL = existing.origCreate;+ if (URL.revokeObjectURL === existing.wrapRevoke) URL.revokeObjectURL = existing.origRevoke;+ for (const url of existing.deferred) { try { Reflect.apply(existing.origRevoke, URL, [url]); } catch (e) {} }+ existing.retained.clear();+ existing.deferred.clear();+ } catch (e) { return false; }+ try { delete window[KEY]; } catch (e) {}+ // If the owned state could not be dropped, do not overwrite it or patch the URL methods.+ if (Object.prototype.hasOwnProperty.call(window, KEY)) return false;+ }+ // Capture whatever the current methods are now — a restored native, or a page hook we preserved. Keep+ // the exact function objects (not .bind(URL) wrappers) so teardown restores them by identity; call+ // them with an explicit URL receiver via Reflect.apply at the call sites instead.+ const origCreate = URL.createObjectURL;+ const origRevoke = URL.revokeObjectURL;+ const state = {+ brand: BRAND,+ version: VERSION,+ active: true,+ origCreate: origCreate,+ origRevoke: origRevoke,+ retained: new Map(),+ deferred: new Set(),+ totalBytes: 0,+ maxCount: config.maxCount,+ maxTotalBytes: config.maxTotalBytes,+ };+ // The wrappers retain/defer only while state.active. Once teardown or a stale rearm flips it off,+ // a closure orphaned inside a third-party wrapper chain degrades to a pure native pass-through.+ const wrapCreate = function (obj) {+ const url = Reflect.apply(origCreate, URL, arguments);+ try {+ if (state.active && typeof Blob !== 'undefined' && obj instanceof Blob) {+ const type = (obj.type || '').toLowerCase();+ const size = obj.size || 0;+ const pdfish = type === 'application/pdf' || type === '';+ if (pdfish && state.retained.size < state.maxCount && (state.totalBytes + size) <= state.maxTotalBytes) {+ state.retained.set(url, obj);+ state.totalBytes += size;+ }+ }+ } catch (e) {}+ return url;+ };+ const wrapRevoke = function (url) {+ if (state.active && state.retained.has(url)) {+ state.deferred.add(url);+ return undefined;+ }+ return Reflect.apply(origRevoke, URL, arguments);+ };+ state.wrapCreate = wrapCreate;+ state.wrapRevoke = wrapRevoke;+ // Publish and verify ownership BEFORE patching either URL method. A non-writable same-name property+ // makes this assignment a silent no-op; if the state did not take, change nothing else and fail open.+ try { window[KEY] = state; } catch (e) { return false; }+ if (window[KEY] !== state) return false;+ URL.createObjectURL = wrapCreate;+ URL.revokeObjectURL = wrapRevoke;+ // Partial patch (e.g. a frozen URL method): roll back only the method that actually took, neutralize+ // and drop the just-published state, and fail open with the methods at their pre-install identities.+ if (URL.createObjectURL !== wrapCreate || URL.revokeObjectURL !== wrapRevoke) {+ state.active = false;+ if (URL.createObjectURL === wrapCreate) URL.createObjectURL = origCreate;+ if (URL.revokeObjectURL === wrapRevoke) URL.revokeObjectURL = origRevoke;+ try { delete window[KEY]; } catch (e) { window[KEY] = undefined; }+ return false;+ }+ return true;+}+"""+)++_BLOB_RETENTION_TEARDOWN_JS = (+ "() => {"+ + _BLOB_RETENTION_OWNERSHIP_JS+ + """+ const state = window[KEY];+ if (state === undefined || state === null) return false;+ // Foreign / corrupt same-name global: never touch a property we do not own.+ if (!isOwned(state)) return false;+ // Neutralize first: any wrapper closure still captured in a third-party chain must stop retaining+ // and deferring the moment we tear down, even though we cannot pull it out of that chain.+ state.active = false;+ try {+ // Restore each URL method independently: if one still directly equals our wrapper, restore that+ // saved exact method; if the other was replaced later by the page, preserve that later method so+ // we never clobber it.+ if (URL.createObjectURL === state.wrapCreate) URL.createObjectURL = state.origCreate;+ if (URL.revokeObjectURL === state.wrapRevoke) URL.revokeObjectURL = state.origRevoke;+ for (const url of state.deferred) { try { Reflect.apply(state.origRevoke, URL, [url]); } catch (e) {} }+ state.retained.clear();+ state.deferred.clear();+ } finally {+ try { delete window[KEY]; } catch (e) { window[KEY] = undefined; }+ }+ return true;+}+"""+)+++async def _evaluate_in_all_frames(page: Page, expression: str, arg: Any, *, workflow_run_id: str | None) -> None:+ main_frame = page.main_frame+ for frame in _all_page_frames(page):+ try:+ if frame is main_frame:+ await evaluate_in_main_world(page, expression, arg)+ else:+ await frame.evaluate(expression, arg)+ except Exception:+ # Best effort: a torn-down or navigating frame just misses this window. No URL/customer+ # data is logged, and a failure here must never break the action.+ LOG.debug("blob URL retention could not reach a frame", workflow_run_id=workflow_run_id)+++async def install_blob_url_retention(+ page: Page,+ *,+ max_retained_count: int = MAX_RETAINED_BLOB_COUNT,+ max_total_bytes: int = MAX_RETAINED_BLOB_TOTAL_BYTES,+ workflow_run_id: str | None = None,+) -> None:+ """Retain PDF-shaped object URLs minted during the action window against a synchronous revoke.++ Installed into the page's realms before the download-triggering click; paired with+ ``teardown_blob_url_retention`` which performs the deferred revokes and restores the originals.+ """+ config = {"maxCount": max_retained_count, "maxTotalBytes": max_total_bytes}+ await _evaluate_in_all_frames(page, _BLOB_RETENTION_INSTALL_JS, config, workflow_run_id=workflow_run_id)+++async def teardown_blob_url_retention(page: Page, *, workflow_run_id: str | None = None) -> None:+ await _evaluate_in_all_frames(page, _BLOB_RETENTION_TEARDOWN_JS, None, workflow_run_id=workflow_run_id)+++# Read-only probe of the retention state installed by _BLOB_RETENTION_INSTALL_JS. Returns only+# booleans: whether this realm exposes a Skyvern-owned retention state, and whether the passed URL is a+# live key in its retained Map. A foreign / corrupt same-name global fails closed (never trusted). The+# URL crosses into page JS but never comes back out and is never logged.+_BLOB_RETENTION_PROBE_JS = (+ "(url) => {"+ + _BLOB_RETENTION_OWNERSHIP_JS+ + """+ const state = window[KEY];+ // Require a valid owned AND active state: a stale cleanup can flip active off while retained keys+ // linger, and those must never be trusted as action-fresh.+ if (!isOwned(state) || state.active !== true) {+ return { observed: false, retained: false };+ }+ return { observed: true, retained: state.retained.has(url) };+}+"""+)+++class BlobActionFreshness(NamedTuple):+ state_observed: bool+ retained: bool+++def _blob_freshness_probe_frames(page: Page, blob_origin: str) -> list[Frame]:+ """Frames to probe for a blob's retention state: those at the blob origin (the creator realm is+ same-origin as the blob) plus indeterminate-origin frames (``about:blank``/``srcdoc``) that may+ inherit the creator origin. Main frame first, deduped."""+ seen: set[int] = set()+ frames: list[Frame] = []+ for frame in [page.main_frame, *page.frames]:+ frame_id = id(frame)+ if frame_id in seen:+ continue+ seen.add(frame_id)+ try:+ origin = _frame_origin(frame.url)+ except Exception:+ # An unreadable frame url is indeterminate; include it and let the probe best-effort.+ frames.append(frame)+ continue+ if origin == blob_origin or origin is None:+ frames.append(frame)+ return frames+++async def probe_blob_action_freshness(+ page: Page,+ blob_url: str,+ *,+ workflow_run_id: str | None = None,+) -> BlobActionFreshness:+ """Whether ``blob_url`` (fragment-stripped) is a live key in a ``__skyvernBlobRetention.retained``+ Map in any realm relevant to its origin — proof it was minted through the pre-click retention+ wrapper during this action window.++ The blob creator realm is not necessarily the frame displaying it (main/parent may mint the blob+ and assign it to an iframe ``src``), so this probes the blob-origin frames plus indeterminate-origin+ frames. Main frame routes through ``evaluate_in_main_world``; sub-frames through ``frame.evaluate``.+ Only booleans cross the boundary; the URL is passed in but never logged or returned. Best-effort per+ realm: a probe failure in one frame never raises and the verdict rests on the other realms. Returns+ ``(state_observed, retained)`` — both False when no realm exposes retention state, so the caller+ fails closed.+ """+ blob_origin = _blob_url_origin(blob_url)+ if blob_origin is None:+ return BlobActionFreshness(state_observed=False, retained=False)++ frames = _blob_freshness_probe_frames(page, blob_origin)+ main_frame = page.main_frame+ state_observed = False+ retained = False+ for frame in frames:+ try:+ if frame is main_frame:+ result = await evaluate_in_main_world(page, _BLOB_RETENTION_PROBE_JS, blob_url)+ else:+ result = await frame.evaluate(_BLOB_RETENTION_PROBE_JS, blob_url)+ except Exception:+ LOG.debug("blob action-freshness probe could not reach a frame", workflow_run_id=workflow_run_id)+ continue+ if not isinstance(result, dict):+ continue+ if result.get("observed"):+ state_observed = True+ if result.get("retained"):+ retained = True+ return BlobActionFreshness(state_observed=state_observed, retained=retained)++def pop_destination_facts(nodes: object) -> dict[str, dict]:"""Strip SKY-12875 destination facts out of scraper payloads, in place, at the JS->Pythonboundary. Every downstream consumer — element hashes and cached-action matching, persisteddiff --git a/tests/unit/test_adopted_session_blob_iframe_recovery_e2e.py b/tests/unit/test_adopted_session_blob_iframe_recovery_e2e.pynew file mode 100644index 000000000..e116d623e--- /dev/null+++ b/tests/unit/test_adopted_session_blob_iframe_recovery_e2e.py@@ -0,0 +1,809 @@+"""E2E regression for adopted-session blob-download recovery via the live PDF iframe.++Reproduces the production failure mode where a persistent/adopted (CDP-connected) browser session+fires a Playwright ``download`` event for a client-side ``blob:`` statement, but the download's own+bytes cannot be captured (``save_as`` yields an empty file and the download URL cannot be fetched from+any page/frame). The statement itself is still on screen in a live same-origin ``blob:`` PDF iframe.++Merged code returns no file for this case; the recovery reads the live iframe's blob and lands a valid+PDF. Driven over ``connect_over_cdp`` against a real headless Chromium so the read path is exercised for+real; only the ``Download`` object is a stand-in, because a remote-CDP session's empty ``save_as`` /+unfetchable download URL cannot be reproduced by a single local browser.++Skipped in CI when Playwright browsers are not installed.+"""++from __future__ import annotations++import asyncio+import socket+import threading+import urllib.parse+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest+import pytest_asyncio+from playwright.async_api import async_playwright++from skyvern.webeye.actions.handler import _save_adopted_session_download+from skyvern.webeye.utils.page import (+ SkyvernFrame,+ install_blob_url_retention,+ probe_blob_action_freshness,+ teardown_blob_url_retention,+)+++def _has_playwright_browser() -> bool:+ try:+ from playwright.sync_api import sync_playwright # noqa: PLC0415++ with sync_playwright() as p:+ return Path(p.chromium.executable_path).exists()+ except Exception:+ return False+++pytestmark = pytest.mark.skipif(+ not _has_playwright_browser(),+ reason="Requires Playwright browsers installed (run: playwright install chromium)",+)+++def _pdf_for(name: str) -> bytes:+ """A minimal valid PDF embedding the doc name, so distinct statements have distinct bytes."""+ stream = f"BT /F1 18 Tf 20 100 Td ({name}) Tj ET".encode()+ return (+ b"%PDF-1.4\n"+ b"1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n"+ b"2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n"+ b"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 4 0 R>>endobj\n"+ b"4 0 obj<</Length " + str(len(stream)).encode() + b">>stream\n" + stream + b"\nendstream endobj\n"+ b"xref\n0 5\n0000000000 65535 f \ntrailer<</Root 1 0 R/Size 5>>\nstartxref\n0\n%%EOF\n"+ )+++# Renders one same-origin blob: PDF iframe per doc name (title == doc name), like the production DOM.+# ``__renderStatements`` is exposed so a test can mint the blobs AFTER installing retention (so their+# URLs land in the action window's retained Map); ``?docs=`` still auto-renders at load for the+# fail-closed cases that never reach the freshness gate. Returns the minted (fragment-less) blob URLs.+_PAGE = """<!doctype html><html><body style="margin:0"><div id="v"></div>+<script>+window.__renderStatements = async (docs) => {+ const urls = [];+ for (const name of docs.split(',')) {+ const resp = await fetch('/statement.pdf?name=' + encodeURIComponent(name));+ const buf = await resp.arrayBuffer();+ const url = URL.createObjectURL(new Blob([buf], {type: 'application/pdf'}));+ urls.push(url);+ const f = document.createElement('iframe');+ f.width = '100%'; f.height = '300'; f.title = name; f.src = url + '#view=FitH';+ document.getElementById('v').appendChild(f);+ }+ return urls;+};+(async () => {+ const q = new URLSearchParams(location.search).get('docs');+ if (q) await window.__renderStatements(q);+ window.__ready = true;+})();+</script></body></html>"""+++class _Handler(BaseHTTPRequestHandler):+ def log_message(self, *a: Any) -> None: # keep test output clean+ pass++ def do_GET(self) -> None:+ parsed = urllib.parse.urlparse(self.path)+ if parsed.path == "/statement.pdf":+ name = urllib.parse.parse_qs(parsed.query).get("name", ["doc"])[0]+ body, ctype = _pdf_for(name), "application/pdf"+ else:+ body, ctype = _PAGE.encode(), "text/html; charset=utf-8"+ self.send_response(200)+ self.send_header("Content-Type", ctype)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+++@pytest_asyncio.fixture+async def cdp_adopted():+ """Serve the statement page, launch Chromium with remote debugging, and adopt it over CDP."""+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ port = server.server_address[1]+ threading.Thread(target=server.serve_forever, daemon=True).start()++ with socket.socket() as _s:+ _s.bind(("127.0.0.1", 0))+ cdp_port = _s.getsockname()[1]++ async with async_playwright() as p:+ launcher = await p.chromium.launch(+ headless=True,+ args=[f"--remote-debugging-port={cdp_port}", "--no-proxy-server", "--proxy-bypass-list=*"],+ proxy={"server": "direct://"},+ )+ adopted = await p.chromium.connect_over_cdp(f"http://127.0.0.1:{cdp_port}")+ context = adopted.contexts[0] if adopted.contexts else await adopted.new_context(accept_downloads=True)++ async def open_page(docs: str | None = None):+ page = await context.new_page()+ suffix = f"/?docs={docs}" if docs else "/"+ await page.goto(f"http://127.0.0.1:{port}{suffix}", wait_until="domcontentloaded")+ for _ in range(50):+ if await page.evaluate("() => window.__ready === true"):+ break+ await asyncio.sleep(0.1)+ return page, port++ try:+ yield open_page+ finally:+ await adopted.close()+ await launcher.close()+ server.shutdown()+++def _unreadable_blob_download(page: Any, port: int, suggested_filename: str) -> MagicMock:+ """A Download whose own bytes are unrecoverable: empty save_as and an unfetchable blob URL.++ Same origin as the live statement iframe(s), a distinct (nonexistent) blob id — mirroring the+ production observation that the download event's blob differs from the live viewer blob.+ """+ download = MagicMock()+ download.url = f"blob:http://127.0.0.1:{port}/00000000-0000-4000-8000-000000000000"+ download.suggested_filename = suggested_filename+ download.page = page+ download.failure = AsyncMock(return_value=None)+ download.save_as = AsyncMock() # no-op: leaves an empty target, as adopted blob save_as does+ return download+++async def test_recovers_named_statement_from_live_blob_iframe(cdp_adopted, tmp_path) -> None:+ # The download's suggested filename matches the on-screen iframe's title. The blob is minted+ # through the action-window retention wrapper, so it is action-fresh and recovered.+ page, port = await cdp_adopted()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ await page.evaluate("(d) => window.__renderStatements(d)", "AnnualStatement.pdf")+ download = _unreadable_blob_download(page, port, suggested_filename="AnnualStatement.pdf")+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ assert saved is not None, "named statement was not recovered from the live PDF iframe"+ data = Path(saved).read_bytes()+ assert data.startswith(b"%PDF-") and b"(AnnualStatement.pdf)" in data+++async def test_filename_match_selects_correct_iframe_not_first(cdp_adopted, tmp_path) -> None:+ # Two blob PDF iframes; the DECOY is first in DOM order. Selection must follow the filename match.+ page, port = await cdp_adopted()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ await page.evaluate("(d) => window.__renderStatements(d)", "DecoyDoc.pdf,AnnualStatement2026.pdf")+ download = _unreadable_blob_download(page, port, suggested_filename="AnnualStatement2026.pdf")+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ assert saved is not None+ data = Path(saved).read_bytes()+ assert b"(AnnualStatement2026.pdf)" in data, "recovered the wrong (decoy) iframe"+ assert b"(DecoyDoc.pdf)" not in data+++async def test_single_iframe_name_mismatch_fails_closed(cdp_adopted, tmp_path) -> None:+ # Exactly one blob PDF iframe on screen, but the suggested filename does not match its title:+ # never assume the visible viewer is the requested statement.+ page, port = await cdp_adopted("AnnualStatement.pdf")+ download = _unreadable_blob_download(page, port, suggested_filename="something-else.pdf")++ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")++ assert saved is None, "a single name-mismatched blob PDF iframe must fail closed"+ assert list(Path(tmp_path).iterdir()) == []+++async def test_ambiguous_multiple_pdf_iframes_fail_closed(cdp_adopted, tmp_path) -> None:+ # Two PDF blob iframes and a suggested filename that matches neither: never guess.+ page, port = await cdp_adopted("DocOne.pdf,DocTwo.pdf")+ download = _unreadable_blob_download(page, port, suggested_filename="something-else.pdf")++ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")++ assert saved is None, "ambiguous multiple blob PDF iframes must fail closed"+ assert list(Path(tmp_path).iterdir()) == []+++async def test_duplicate_title_match_fails_closed(cdp_adopted, tmp_path) -> None:+ # Two iframes carry the SAME title that matches the suggested filename: ambiguous, fail closed.+ page, port = await cdp_adopted("Statement.pdf,Statement.pdf")+ download = _unreadable_blob_download(page, port, suggested_filename="Statement.pdf")++ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")++ assert saved is None, "duplicate matching titles must fail closed"+ assert list(Path(tmp_path).iterdir()) == []+++# ---------------------------------------------------------------------------+# Action-freshness gate: a named blob PDF iframe is recovered only when its blob was minted through+# the pre-click retention wrapper during this action window (a live key in __skyvernBlobRetention.+# retained). A same-named iframe whose blob was minted outside the window is rejected — a wrong+# document is worse than a visible miss.+# ---------------------------------------------------------------------------+++async def test_stale_iframe_not_minted_through_retention_fails_closed(cdp_adopted, tmp_path) -> None:+ # The statement blob was minted at page load, before retention install: its URL is not a key in+ # the action window's retained Map, so recovery fails closed even though the title matches.+ page, port = await cdp_adopted("AnnualStatement.pdf")+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ download = _unreadable_blob_download(page, port, suggested_filename="AnnualStatement.pdf")+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ assert saved is None, "a stale iframe blob not minted through the action window must fail closed"+ assert list(Path(tmp_path).iterdir()) == []+++async def test_inactive_owned_state_probes_as_not_fresh(cdp_adopted, tmp_path) -> None:+ # Stale cleanup can flip an owned state's active flag off (e.g. it neutralizes the closures and then+ # returns on an exception) while retained keys remain in the Map. The freshness probe must require a+ # valid owned AND active state, so those inactive retained keys are never trusted as action-fresh.+ page, _ = await cdp_adopted()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ urls = await page.evaluate("(d) => window.__renderStatements(d)", "AnnualStatement.pdf")+ blob_url = urls[0]+ # While active, the retained blob is action-fresh (guards the setup is valid).+ active = await probe_blob_action_freshness(page, blob_url, workflow_run_id="wr-test")+ assert active.state_observed is True and active.retained is True+ # Neutralize the closures but leave the retained keys, as an interrupted stale cleanup would.+ await page.evaluate("() => { window.__skyvernBlobRetention.active = false; }")+ inactive = await probe_blob_action_freshness(page, blob_url, workflow_run_id="wr-test")+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ assert inactive.state_observed is False, "an inactive owned state must not be observed as fresh"+ assert inactive.retained is False+++async def test_creator_realm_blob_recovered_when_display_frame_differs(cdp_adopted, tmp_path) -> None:+ # The main realm mints the blob and assigns it to the iframe src; Chromium's PDF viewer renders it+ # in a separate frame with no retention state. Recovery must succeed by probing the creator (main)+ # realm, not only the display frame.+ page, port = await cdp_adopted()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ await page.evaluate("(d) => window.__renderStatements(d)", "AnnualStatement.pdf")+ download = _unreadable_blob_download(page, port, suggested_filename="AnnualStatement.pdf")+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ assert saved is not None, "creator-realm retention state was not found"+ assert b"(AnnualStatement.pdf)" in Path(saved).read_bytes()+++async def test_retained_iframe_blob_synchronously_revoked_still_recovered(cdp_adopted, tmp_path) -> None:+ # The site revokes the object URL synchronously after minting it; the retention wrapper defers the+ # revoke, so the URL stays a live key in the retained Map and recovery still succeeds this window.+ page, port = await cdp_adopted()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ urls = await page.evaluate("(d) => window.__renderStatements(d)", "AnnualStatement.pdf")+ await page.evaluate("(u) => URL.revokeObjectURL(u)", urls[0])+ download = _unreadable_blob_download(page, port, suggested_filename="AnnualStatement.pdf")+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ assert saved is not None, "a retained-then-revoked blob must remain recoverable while the window is live"+ assert b"(AnnualStatement.pdf)" in Path(saved).read_bytes()+++async def test_sequential_window_stale_iframe_fails_closed(cdp_adopted, tmp_path) -> None:+ # A prior action window minted and displayed the statement, then tore retention down. In a new+ # window (fresh, empty retained Map) the leftover iframe's blob is not action-fresh: fail closed.+ page, port = await cdp_adopted()+ await install_blob_url_retention(page, workflow_run_id="wr-1")+ await page.evaluate("(d) => window.__renderStatements(d)", "Statement.pdf")+ await teardown_blob_url_retention(page, workflow_run_id="wr-1")++ await install_blob_url_retention(page, workflow_run_id="wr-2")+ try:+ download = _unreadable_blob_download(page, port, suggested_filename="Statement.pdf")+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-2")+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-2")++ assert saved is None, "a same-named iframe from a prior action window must not be accepted"+ assert list(Path(tmp_path).iterdir()) == []+++# ---------------------------------------------------------------------------+# Canonical transient-blob shape: two untitled iframes, no persistent blob PDF+# iframe, and a "View Document" control that mints a PDF Blob transiently, fires+# a download, then revokes the object URL synchronously — so by the time any+# reader runs the blob: URL is already dead. Pre-action blob retention keeps the+# URL alive for the action window so the existing in-page read recovers the bytes.+# ---------------------------------------------------------------------------++_CANON_PAGE = """<!doctype html><html><body style="margin:0">+<iframe title="" src="/frame_a.html" width="100%" height="60"></iframe>+<iframe title="" src="/frame_b.html" width="100%" height="60"></iframe>+<button id="view">View Document</button>+<script>+window.__mintStatement = async (name, type) => {+ const resp = await fetch('/statement.pdf?name=' + encodeURIComponent(name));+ const buf = await resp.arrayBuffer();+ const blob = new Blob([buf], {type: type || 'application/pdf'});+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove();+ URL.revokeObjectURL(url); // synchronous teardown, as the production site does+ return url;+};+window.__ready = true;+</script></body></html>"""+++class _CanonHandler(BaseHTTPRequestHandler):+ def log_message(self, *a: Any) -> None:+ pass++ def do_GET(self) -> None:+ parsed = urllib.parse.urlparse(self.path)+ if parsed.path == "/statement.pdf":+ name = urllib.parse.parse_qs(parsed.query).get("name", ["doc"])[0]+ body, ctype = _pdf_for(name), "application/pdf"+ elif parsed.path in ("/frame_a.html", "/frame_b.html"):+ body, ctype = b"<!doctype html><html><body>untitled</body></html>", "text/html; charset=utf-8"+ else:+ body, ctype = _CANON_PAGE.encode(), "text/html; charset=utf-8"+ self.send_response(200)+ self.send_header("Content-Type", ctype)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+++@pytest_asyncio.fixture+async def cdp_canonical():+ """Serve the canonical statement page and adopt a real Chromium over CDP."""+ server = ThreadingHTTPServer(("127.0.0.1", 0), _CanonHandler)+ port = server.server_address[1]+ threading.Thread(target=server.serve_forever, daemon=True).start()++ with socket.socket() as _s:+ _s.bind(("127.0.0.1", 0))+ cdp_port = _s.getsockname()[1]++ async with async_playwright() as p:+ launcher = await p.chromium.launch(+ headless=True,+ args=[f"--remote-debugging-port={cdp_port}", "--no-proxy-server", "--proxy-bypass-list=*"],+ proxy={"server": "direct://"},+ )+ adopted = await p.chromium.connect_over_cdp(f"http://127.0.0.1:{cdp_port}")+ context = adopted.contexts[0] if adopted.contexts else await adopted.new_context(accept_downloads=True)++ async def open_page():+ page = await context.new_page()+ await page.goto(f"http://127.0.0.1:{port}/", wait_until="domcontentloaded")+ for _ in range(50):+ if await page.evaluate("() => window.__ready === true"):+ break+ await asyncio.sleep(0.1)+ return page, port++ try:+ yield open_page+ finally:+ await adopted.close()+ await launcher.close()+ server.shutdown()+++def _savefails_blob_download(page: Any, blob_url: str, suggested_filename: str) -> MagicMock:+ """A Download carrying the real minted blob URL, whose eager save_as yields an empty file.++ The empty save_as models the exact production observation for a remote-CDP adopted session+ ("Adopted-session eager save_as produced an empty file"); everything else — the blob URL and+ the in-page read that recovers it — runs for real.+ """+ download = MagicMock()+ download.url = blob_url+ download.suggested_filename = suggested_filename+ download.page = page+ download.failure = AsyncMock(return_value=None)+ download.save_as = AsyncMock() # no-op: leaves an empty target, as adopted blob save_as does+ return download+++async def test_canonical_transient_revoked_blob_is_recovered_while_retained(cdp_canonical, tmp_path) -> None:+ page, _ = await cdp_canonical()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ blob_url = await page.evaluate("(n) => window.__mintStatement(n)", "AnnualStatement.pdf")+ assert isinstance(blob_url, str) and blob_url.startswith("blob:")+ download = _savefails_blob_download(page, blob_url, suggested_filename="AnnualStatement.pdf")+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr-test")+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ assert saved is not None, "canonical transient blob was not recovered while retained"+ data = Path(saved).read_bytes()+ assert data.startswith(b"%PDF-") and b"(AnnualStatement.pdf)" in data+++async def test_pdf_blob_stays_readable_while_retained_then_dies_on_teardown(cdp_canonical, tmp_path) -> None:+ page, _ = await cdp_canonical()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ blob_url = await page.evaluate("(n) => window.__mintStatement(n)", "Statement.pdf")++ retained = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url=blob_url, probe=True)+ assert retained is not None and retained.startswith(b"%PDF-"), "retained PDF blob should be readable"++ await teardown_blob_url_retention(page, workflow_run_id="wr-test")+ after = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url=blob_url, probe=True)+ assert after is None, "teardown must perform the deferred revoke so the URL is no longer readable"+++async def test_native_revoke_restored_after_teardown(cdp_canonical, tmp_path) -> None:+ page, _ = await cdp_canonical()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ # With the wrappers restored, a fresh mint+revoke must behave natively: the URL dies immediately.+ blob_url = await page.evaluate("(n) => window.__mintStatement(n)", "Statement.pdf")+ after = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url=blob_url, probe=True)+ assert after is None, "after teardown the native synchronous revoke must take effect again"+++async def test_native_method_objects_restored_by_identity_after_teardown(cdp_canonical, tmp_path) -> None:+ # Teardown must restore the exact native function objects, not a bound wrapper: identity, name and+ # toString must be indistinguishable from the pre-install originals for the persistent session.+ page, _ = await cdp_canonical()+ await page.evaluate(+ "() => { window.__origCreate = URL.createObjectURL; window.__origRevoke = URL.revokeObjectURL; }"+ )+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ identity = await page.evaluate(+ """() => ({+ createSame: URL.createObjectURL === window.__origCreate,+ revokeSame: URL.revokeObjectURL === window.__origRevoke,+ })"""+ )+ assert identity["createSame"], "createObjectURL must be restored to the exact native function object"+ assert identity["revokeSame"], "revokeObjectURL must be restored to the exact native function object"+++async def test_non_pdf_blob_is_not_retained(cdp_canonical, tmp_path) -> None:+ page, _ = await cdp_canonical()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ # A non-PDF blob (image) is an unrelated download: it must revoke natively, not be retained.+ blob_url = await page.evaluate("(n) => window.__mintStatement(n, 'image/png')", "logo.png")+ after = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url=blob_url, probe=True)+ assert after is None, "an unrelated non-PDF blob must not be retained"+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")+++async def test_retention_preserves_native_return_values(cdp_canonical, tmp_path) -> None:+ page, _ = await cdp_canonical()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ try:+ shapes = await page.evaluate(+ """() => {+ const b = new Blob([new Uint8Array([37,80,68,70])], {type: 'application/pdf'});+ const url = URL.createObjectURL(b);+ const revokeReturn = URL.revokeObjectURL(url);+ return { urlOk: typeof url === 'string' && url.startsWith('blob:'),+ revokeUndefined: revokeReturn === undefined };+ }"""+ )+ assert shapes["urlOk"], "createObjectURL must still return a real blob: URL string"+ assert shapes["revokeUndefined"], "revokeObjectURL must still return undefined"+ finally:+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")+++async def test_teardown_is_idempotent(cdp_canonical, tmp_path) -> None:+ page, _ = await cdp_canonical()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")+ # A second teardown with no retention installed must be a harmless no-op.+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")+++# ---------------------------------------------------------------------------+# State ownership: install/probe/teardown only act on a validly branded, complete Skyvern-owned state.+# A foreign page global sharing the name is never mutated and never trusted; a valid stale owned state+# (a prior window that never tore down) is settled and cleared on rearm so no key leaks across windows.+# ---------------------------------------------------------------------------+++async def test_foreign_same_name_global_is_untouched_and_not_trusted(cdp_canonical) -> None:+ # A page owns a truthy window.__skyvernBlobRetention with a lying retained.has. Install/teardown must+ # not replace it or clobber the URL methods, and the freshness probe must fail closed on it.+ page, port = await cdp_canonical()+ await page.evaluate(+ """() => {+ window.__foreignSentinel = { retained: { has: () => true }, note: 'page-owned' };+ window.__skyvernBlobRetention = window.__foreignSentinel;+ window.__origCreate = URL.createObjectURL;+ window.__origRevoke = URL.revokeObjectURL;+ }"""+ )++ await install_blob_url_retention(page, workflow_run_id="wr-test")+ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ state = await page.evaluate(+ """() => ({+ sameProp: window.__skyvernBlobRetention === window.__foreignSentinel,+ stillPresent: !!window.__skyvernBlobRetention && window.__skyvernBlobRetention.note === 'page-owned',+ createUntouched: URL.createObjectURL === window.__origCreate,+ revokeUntouched: URL.revokeObjectURL === window.__origRevoke,+ })"""+ )+ assert state["sameProp"], "install/teardown must not replace a foreign same-name global"+ assert state["stillPresent"], "the foreign property must not be deleted or mutated"+ assert state["createUntouched"] and state["revokeUntouched"], "URL methods must not be clobbered"++ fresh = await probe_blob_action_freshness(page, f"blob:http://127.0.0.1:{port}/x", workflow_run_id="wr-test")+ assert fresh.state_observed is False and fresh.retained is False, "a foreign global must not read as owned/fresh"+++async def test_rearm_over_stale_owned_state_clears_prior_window(cdp_canonical) -> None:+ # A prior window installed retention and minted a statement, then never tore down (crash/cancel).+ # Re-installing must settle+restore+clear the stale state and rearm with an empty retained Map, so+ # the prior window's blob key is not action-fresh and the exact natives survive by identity.+ page, _ = await cdp_canonical()+ await page.evaluate(+ "() => { window.__origCreate = URL.createObjectURL; window.__origRevoke = URL.revokeObjectURL; }"+ )++ await install_blob_url_retention(page, workflow_run_id="wr-1")+ stale_url = await page.evaluate("(n) => window.__mintStatement(n)", "Statement.pdf")+ assert isinstance(stale_url, str) and stale_url.startswith("blob:")+ fresh_before = await probe_blob_action_freshness(page, stale_url, workflow_run_id="wr-1")+ assert fresh_before.state_observed and fresh_before.retained, "the minted blob should be fresh within its window"++ # Rearm WITHOUT tearing down the prior window.+ await install_blob_url_retention(page, workflow_run_id="wr-2")+ fresh_after = await probe_blob_action_freshness(page, stale_url, workflow_run_id="wr-2")+ assert fresh_after.state_observed, "rearm must leave a fresh Skyvern-owned state observable"+ assert not fresh_after.retained, "the prior window's blob key must not survive rearm as action-fresh"++ await teardown_blob_url_retention(page, workflow_run_id="wr-2")+ identity = await page.evaluate(+ """() => ({+ createSame: URL.createObjectURL === window.__origCreate,+ revokeSame: URL.revokeObjectURL === window.__origRevoke,+ })"""+ )+ assert identity["createSame"] and identity["revokeSame"], "rearm+teardown must restore the exact native methods"+++async def test_wrapper_mismatch_teardown_neutralizes_orphaned_wrappers(cdp_canonical) -> None:+ # A third party re-wraps the URL methods around Skyvern's wrappers after install. Teardown cannot+ # restore the natives (that would clobber the third party), so it must instead neutralize the+ # captured Skyvern wrappers: after the owned global is dropped, a PDF minted+revoked through the+ # third-party chain must pass through natively (revoked, unreadable), not be retained/deferred into+ # an orphaned bounded map with no future teardown handle.+ page, _ = await cdp_canonical()+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ await page.evaluate(+ """() => {+ const skCreate = URL.createObjectURL;+ const skRevoke = URL.revokeObjectURL;+ URL.createObjectURL = function () { return skCreate.apply(URL, arguments); };+ URL.revokeObjectURL = function () { return skRevoke.apply(URL, arguments); };+ window.__tpCreate = URL.createObjectURL;+ window.__tpRevoke = URL.revokeObjectURL;+ }"""+ )++ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ state = await page.evaluate(+ """() => ({+ tpCreateKept: URL.createObjectURL === window.__tpCreate,+ tpRevokeKept: URL.revokeObjectURL === window.__tpRevoke,+ skyvernDropped: window.__skyvernBlobRetention === undefined,+ })"""+ )+ assert state["tpCreateKept"] and state["tpRevokeKept"], "teardown must not clobber third-party URL methods"+ assert state["skyvernDropped"], "the owned Skyvern global must be dropped"++ # Mint + synchronous revoke a PDF through the third-party chain (which still calls the captured+ # Skyvern wrappers). With the wrappers neutralized, the revoke is a native pass-through: unreadable.+ orphan_url = await page.evaluate("(n) => window.__mintStatement(n)", "Orphan.pdf")+ assert isinstance(orphan_url, str) and orphan_url.startswith("blob:")+ after = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url=orphan_url, probe=True)+ assert after is None, "a PDF created+revoked through the orphaned chain must pass through natively, not defer"+++# ---------------------------------------------------------------------------+# Ownership edge cases: a valid owned stale state must be settled and dropped on rearm even when the page+# has rewrapped one or both URL methods; teardown restores each method independently; and install never+# patches the URL methods unless it can actually publish (own) its state.+# ---------------------------------------------------------------------------+++async def _wrap_url_methods(page, which: str) -> None:+ # Wrap the named URL method(s) in a page-owned function that calls the current (Skyvern) method.+ await page.evaluate(+ """(which) => {+ if (which === 'create' || which === 'both') {+ const c = URL.createObjectURL;+ URL.createObjectURL = function () { return c.apply(URL, arguments); };+ window.__pageCreate = URL.createObjectURL;+ }+ if (which === 'revoke' || which === 'both') {+ const r = URL.revokeObjectURL;+ URL.revokeObjectURL = function () { return r.apply(URL, arguments); };+ window.__pageRevoke = URL.revokeObjectURL;+ }+ }""",+ which,+ )+++async def test_stale_owned_with_rewrapped_hooks_is_reset_on_rearm(cdp_canonical) -> None:+ # A prior window installed retention and minted a statement, then the page wrapped BOTH URL methods+ # around Skyvern's wrappers (so a combined wrapper-active check is false). Rearm must still neutralize,+ # settle and drop the stale state — the prior key must not stay fresh — while preserving the page hooks,+ # and the final teardown must restore those pre-rearm (page-hook) methods.+ page, _ = await cdp_canonical()+ await install_blob_url_retention(page, workflow_run_id="wr-1")+ stale_url = await page.evaluate("(n) => window.__mintStatement(n)", "Stale.pdf")+ before = await probe_blob_action_freshness(page, stale_url, workflow_run_id="wr-1")+ assert before.state_observed and before.retained+ await _wrap_url_methods(page, "both")++ await install_blob_url_retention(page, workflow_run_id="wr-2")+ after = await probe_blob_action_freshness(page, stale_url, workflow_run_id="wr-2")+ assert after.state_observed, "rearm must leave a fresh owned state observable"+ assert not after.retained, "the prior window's key must not survive a rewrapped-hook rearm as fresh"++ await teardown_blob_url_retention(page, workflow_run_id="wr-2")+ final = await page.evaluate(+ """() => ({+ createIsPageHook: URL.createObjectURL === window.__pageCreate,+ revokeIsPageHook: URL.revokeObjectURL === window.__pageRevoke,+ dropped: window.__skyvernBlobRetention === undefined,+ })"""+ )+ assert final["createIsPageHook"] and final["revokeIsPageHook"], "teardown must restore the pre-rearm page hooks"+ assert final["dropped"], "the owned state must be dropped after teardown"++[email protected]("replaced", ["create", "revoke"])+async def test_one_sided_url_replacement_teardown_restores_independently(cdp_canonical, replaced: str) -> None:+ # Exactly one URL method is replaced by the page after install; the other is still Skyvern's wrapper.+ # Teardown must restore the still-Skyvern method to its native and preserve the page-replaced one.+ page, _ = await cdp_canonical()+ await page.evaluate(+ "() => { window.__origCreate = URL.createObjectURL; window.__origRevoke = URL.revokeObjectURL; }"+ )+ await install_blob_url_retention(page, workflow_run_id="wr-test")+ await _wrap_url_methods(page, replaced)++ await teardown_blob_url_retention(page, workflow_run_id="wr-test")++ r = await page.evaluate(+ """() => ({+ createNative: URL.createObjectURL === window.__origCreate,+ revokeNative: URL.revokeObjectURL === window.__origRevoke,+ createIsPage: URL.createObjectURL === window.__pageCreate,+ revokeIsPage: URL.revokeObjectURL === window.__pageRevoke,+ dropped: window.__skyvernBlobRetention === undefined,+ })"""+ )+ assert r["dropped"]+ if replaced == "create":+ assert r["createIsPage"], "the page-replaced createObjectURL must be preserved"+ assert r["revokeNative"], "the still-Skyvern revokeObjectURL must be restored to native"+ else:+ assert r["revokeIsPage"], "the page-replaced revokeObjectURL must be preserved"+ assert r["createNative"], "the still-Skyvern createObjectURL must be restored to native"++[email protected]("value", ["null", "undefined"])+async def test_non_writable_same_name_property_blocks_install_without_side_effects(cdp_canonical, value: str) -> None:+ # A page defines a non-writable, non-configurable same-name property (null/undefined). Install must+ # not patch either URL method and must not modify/delete the foreign property.+ page, _ = await cdp_canonical()+ await page.evaluate(+ """(v) => {+ window.__origCreate = URL.createObjectURL;+ window.__origRevoke = URL.revokeObjectURL;+ Object.defineProperty(window, '__skyvernBlobRetention', {+ value: v === 'null' ? null : undefined, writable: false, configurable: false, enumerable: true,+ });+ }""",+ value,+ )++ await install_blob_url_retention(page, workflow_run_id="wr-test")++ r = await page.evaluate(+ """() => ({+ createUntouched: URL.createObjectURL === window.__origCreate,+ revokeUntouched: URL.revokeObjectURL === window.__origRevoke,+ hasProp: Object.prototype.hasOwnProperty.call(window, '__skyvernBlobRetention'),+ isNull: window.__skyvernBlobRetention === null,+ isUndefined: window.__skyvernBlobRetention === undefined,+ })"""+ )+ assert r["createUntouched"] and r["revokeUntouched"], "install must not patch URL methods when it cannot own state"+ assert r["hasProp"], "the foreign non-writable property must remain"+ assert r["isNull"] if value == "null" else r["isUndefined"], "the foreign property value must be unchanged"+++async def test_partial_url_patch_failure_rolls_back_and_fails_open(cdp_canonical) -> None:+ # revokeObjectURL is frozen non-writable, so install can patch createObjectURL but not revokeObjectURL.+ # Install must detect the partial patch, roll back createObjectURL, drop the just-owned state, and fail+ # open with both methods at their pre-install identities.+ page, _ = await cdp_canonical()+ await page.evaluate(+ """() => {+ window.__origCreate = URL.createObjectURL;+ window.__origRevoke = URL.revokeObjectURL;+ Object.defineProperty(URL, 'revokeObjectURL', {+ value: URL.revokeObjectURL, writable: false, configurable: true,+ });+ }"""+ )++ await install_blob_url_retention(page, workflow_run_id="wr-test")++ r = await page.evaluate(+ """() => ({+ createRolledBack: URL.createObjectURL === window.__origCreate,+ revokeUnchanged: URL.revokeObjectURL === window.__origRevoke,+ dropped: window.__skyvernBlobRetention === undefined,+ })"""+ )+ assert r["createRolledBack"], "createObjectURL must roll back to native after a partial patch"+ assert r["revokeUnchanged"], "the frozen revokeObjectURL must be unchanged"+ assert r["dropped"], "the just-published state must be dropped on rollback"diff --git a/tests/unit/test_adopted_session_download_save.py b/tests/unit/test_adopted_session_download_save.pyindex 59fc3d537..e8214fd4d 100644--- a/tests/unit/test_adopted_session_download_save.py+++ b/tests/unit/test_adopted_session_download_save.py@@ -249,11 +249,18 @@ async def test_blob_url_in_page_fetch_returns_not_ok(tmp_path) -> None:failing_frame = _frame(BLOB_ORIGIN_FRAME_URL, evaluate_return={"ok": False, "status": 0})page = _blob_capable_page(failing_frame)- saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr")+ # The live-blob-iframe recovery seam runs after the download-url read fails and would issue its+ # own DOM probe; stub it out so this test isolates the download-url in-page fetch behavior.+ with patch(+ "skyvern.webeye.actions.handler._recover_adopted_session_blob_pdf_iframe",+ new=AsyncMock(return_value=None),+ ) as recover:+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr")assert saved is Nonepage.context.request.get.assert_not_awaited()failing_frame.evaluate.assert_awaited_once()+ recover.assert_awaited_once_with(page, download, "wr")assert list(tmp_path.iterdir()) == []@@ -264,11 +271,18 @@ async def test_blob_url_evaluate_raises_returns_none(tmp_path) -> None:raising_frame = _frame(BLOB_ORIGIN_FRAME_URL, evaluate_return=Exception("frame detached"))page = _blob_capable_page(raising_frame)- saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr")+ # The live-blob-iframe recovery seam runs after the download-url read fails and would issue its+ # own DOM probe; stub it out so this test isolates the download-url in-page fetch behavior.+ with patch(+ "skyvern.webeye.actions.handler._recover_adopted_session_blob_pdf_iframe",+ new=AsyncMock(return_value=None),+ ) as recover:+ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr")assert saved is Nonepage.context.request.get.assert_not_awaited()raising_frame.evaluate.assert_awaited_once()+ recover.assert_awaited_once_with(page, download, "wr")assert list(tmp_path.iterdir()) == []@@ -668,6 +682,63 @@ async def test_eager_capture_aclose_reraises_outer_cancellation() -> None:assert reraised, "aclose must propagate an outer cancellation, not swallow it"+async def test_retention_teardown_runs_even_when_aclose_is_cancelled() -> None:+ """If closing the eager capture raises CancelledError, the page-realm retention wrapper must still+ be torn down for an adopted session, and the original cancellation must propagate afterwards."""+ from skyvern.webeye.actions.handler import _close_eager_capture_then_teardown_retention++ capture = MagicMock()+ capture.aclose = AsyncMock(side_effect=asyncio.CancelledError())+ page = MagicMock()++ with patch("skyvern.webeye.actions.handler.teardown_blob_url_retention", AsyncMock()) as teardown:+ with pytest.raises(asyncio.CancelledError):+ await _close_eager_capture_then_teardown_retention(+ capture, page, browser_session_id="pbs-1", workflow_run_id="wr"+ )++ teardown.assert_awaited_once()+++async def test_retention_teardown_failure_does_not_replace_cancellation() -> None:+ """A teardown failure stays fail-open/debug-only and must not swallow or replace the original+ cancellation raised by aclose."""+ from skyvern.webeye.actions.handler import _close_eager_capture_then_teardown_retention++ capture = MagicMock()+ capture.aclose = AsyncMock(side_effect=asyncio.CancelledError())+ page = MagicMock()++ with patch(+ "skyvern.webeye.actions.handler.teardown_blob_url_retention",+ AsyncMock(side_effect=RuntimeError("teardown boom")),+ ) as teardown:+ with pytest.raises(asyncio.CancelledError):+ await _close_eager_capture_then_teardown_retention(+ capture, page, browser_session_id="pbs-1", workflow_run_id="wr"+ )++ teardown.assert_awaited_once()+++async def test_retention_teardown_skipped_without_browser_session() -> None:+ """Non-adopted sessions never installed the retention wrapper, so teardown must not run."""+ from skyvern.webeye.actions.handler import _close_eager_capture_then_teardown_retention++ capture = MagicMock()+ capture.aclose = AsyncMock()+ page = MagicMock()++ with patch("skyvern.webeye.actions.handler.teardown_blob_url_retention", AsyncMock()) as teardown:+ await _close_eager_capture_then_teardown_retention(capture, page, browser_session_id=None, workflow_run_id="wr")++ capture.aclose.assert_awaited_once()+ teardown.assert_not_awaited()++@pytest.mark.asyncioasync def test_read_adopted_session_blob_bytes_prefers_owner_then_fans_out() -> None:"""The extracted reader returns the first page that owns the blob, owner (download.page) first."""diff --git a/tests/unit/test_browser_effect_sink_enumeration.py b/tests/unit/test_browser_effect_sink_enumeration.pyindex b7d4b1f79..9c045d3c4 100644--- a/tests/unit/test_browser_effect_sink_enumeration.py+++ b/tests/unit/test_browser_effect_sink_enumeration.py@@ -25,7 +25,7 @@ _DISCOVERED_BROWSER_API_CALLS = {"clear": 4,"close": 5,"dblclick": 2,- "evaluate": 9,+ "evaluate": 10,"fill": 2,"focus": 2,"go_back": 1,@@ -73,6 +73,7 @@ _DISCOVERED_BROWSER_API_CALLS = {_EVALUATE_CALLERS = {"skyvern/webeye/actions/handler.py": Counter({+ "_blob_iframe_src_titles": 1,"_collect_inline_iframe_src_candidates": 1,"_evaluate_element_scoped": 1,"_normal_select_readback_contradicts": 1,@@ -198,21 +199,21 @@ def test_discovered_browser_api_lower_bound_is_stable() -> None:}assert observed == _DISCOVERED_BROWSER_API_CALLS- assert sum(sum(methods.values()) for methods in observed.values()) == 141+ assert sum(sum(methods.values()) for methods in observed.values()) == 142handler_candidates = _candidate_signatures("skyvern/webeye/actions/handler.py", _CANDIDATE_METHODS)classified_non_browser = Counter({signature: count for signature, count in handler_candidates.items() if signature in _NON_BROWSER_CANDIDATES})assert classified_non_browser == _NON_BROWSER_CANDIDATESassert sum(_NON_BROWSER_CANDIDATES.values()) == 5- assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 136+ assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 137def test_every_raw_evaluate_call_is_classified() -> None:observed = {path: callers for path in _owned_source_paths() if (callers := _callers_for_method(path, "evaluate"))}assert observed == _EVALUATE_CALLERS- assert sum(sum(callers.values()) for callers in observed.values()) == 16+ assert sum(sum(callers.values()) for callers in observed.values()) == 17def test_every_cdp_dispatch_is_classified_by_exact_command() -> None:diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.pyindex 0450a356c..b3c20c389 100644--- a/tests/unit/test_download_file_action_handler.py+++ b/tests/unit/test_download_file_action_handler.py@@ -25,6 +25,7 @@ from skyvern.webeye.actions.handler import (_EagerAdoptedBlobCapture,_looks_like_pdf,_persist_captured_download,+ _recover_adopted_session_blob_pdf_iframe,_recover_blocked_inline_pdf_download,_remove_download_listener,handle_download_file_action,@@ -32,6 +33,7 @@ from skyvern.webeye.actions.handler import (from skyvern.webeye.actions.responses import ActionFailure, ActionSuccessfrom skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptorfrom skyvern.webeye.scraper.scraped_page import ScrapedPage+from skyvern.webeye.utils.page import BlobActionFreshnessfrom tests.unit.helpers import make_organization, make_step, make_task# Five seconds is only a test-side runaway guard. The behavior under test is@@ -4076,12 +4078,16 @@ async def test_handle_action_adopted_session_helper_failure_does_not_short_circu"""now = datetime.now(UTC)organization = make_organization(now)+ # Small, non-flaky budget: enough for a baseline poll plus at least one post-helper poll, while+ # keeping the test fast. The stated contract (keep polling after the helper returns None) is what+ # this test isolates, so the real _save_adopted_session_download is replaced with an instant None+ # below rather than being driven to failure by the outer timeout.task = make_task(now,organization,workflow_run_id="wr-1",browser_session_id="bs-1",- download_timeout=0.01,+ download_timeout=0.3,)step = make_step(now, task, step_id="step-1", status=StepStatus.created, order=0, output=None)@@ -4092,7 +4098,6 @@ async def test_handle_action_adopted_session_helper_failure_does_not_short_circupage.expose_binding = AsyncMock()download_callbacks: dict[str, Callable[[object], None]] = {}page.on.side_effect = lambda event, callback: download_callbacks.__setitem__(event, callback)- page.context.request.get = AsyncMock(side_effect=Exception("connection gone"))browser_state = MagicMock()browser_state.list_valid_pages = AsyncMock(return_value=[page])@@ -4117,7 +4122,11 @@ async def test_handle_action_adopted_session_helper_failure_does_not_short_circudownload = MagicMock()download.suggested_filename = "report.pdf"download.url = "https://example.com/presigned/report.pdf"- download.save_as = AsyncMock(side_effect=Exception("Target page, context or browser has been closed"))++ # Isolate the stated contract: the adopted-session save helper returns None (could not save), and+ # the poll loop must keep polling the browser-session folder afterwards. Replacing the real helper+ # keeps this fast and deterministic instead of driving it to failure via the outer timeout.+ save_helper = AsyncMock(return_value=None)async def mock_inner_handle_action(*args: object, **kwargs: object) -> list[ActionSuccess]:download_callbacks["download"](download)@@ -4137,6 +4146,7 @@ async def test_handle_action_adopted_session_helper_failure_does_not_short_circuwith (patch.object(ActionHandler, "_handle_action", side_effect=mock_inner_handle_action),patch("skyvern.webeye.actions.handler.get_download_dir", return_value=primary_dir),+ patch("skyvern.webeye.actions.handler._save_adopted_session_download", save_helper),patch("skyvern.webeye.actions.handler.skyvern_context.current",return_value=MagicMock(run_id="bs-1", download_suffix=None),@@ -4157,8 +4167,9 @@ async def test_handle_action_adopted_session_helper_failure_does_not_short_circuassert results[-1].download_triggered is Falseassert action.download_triggered is False- download.save_as.assert_awaited_once()- # the loop kept polling the browser-session folder after the helper failure,+ # The adopted-session save helper was attempted and returned None (could not save).+ save_helper.assert_awaited()+ # the loop kept polling the browser-session folder after the helper returned None,# rather than breaking out on the first failed attempt.assert mock_app.STORAGE.list_downloaded_files_in_browser_session.await_count >= 2span_attrs = _download_wait_span_attrs(span_exporter)@@ -5327,3 +5338,527 @@ async def test_handle_action_managed_session_disables_eager_and_popup_wiring() -assert captured_kwargs.get("enabled") is Falseassert "popup" not in page_listenersassert not any(c.args and c.args[0] == "popup" for c in page.on.call_args_list)+++def _blob_download(url: str, suggested_filename: str) -> MagicMock:+ download = MagicMock()+ download.url = url+ download.suggested_filename = suggested_filename+ return download+++def _patch_fresh_probe(*, state_observed: bool = True, retained: bool = True):+ """Patch the retention-freshness gate to a fixed verdict so selection-logic tests can reach the+ read path without standing up a real retention Map."""+ return patch(+ "skyvern.webeye.actions.handler.probe_blob_action_freshness",+ new=AsyncMock(return_value=BlobActionFreshness(state_observed=state_observed, retained=retained)),+ )+++class TestRecoverAdoptedSessionBlobPdfIframe:+ """Fast guardrail coverage for the live blob: PDF iframe recovery selection logic."""++ @pytest.mark.asyncio+ async def test_non_blob_download_url_returns_none_without_reading(self) -> None:+ page = MagicMock()+ with (+ patch("skyvern.webeye.actions.handler._blob_iframe_src_titles", new=AsyncMock()) as titles,+ patch("skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes", new=AsyncMock()) as read,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("https://x.example/file.pdf", "file.pdf"), "wr"+ )+ assert result is None+ titles.assert_not_awaited()+ read.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_named_match_pdf_iframe_is_recovered(self) -> None:+ page = MagicMock()+ src = "blob:https://portal.example/live-uuid"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={src: "Statement.pdf"}),+ ),+ _patch_fresh_probe(),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(return_value=b"%PDF-1.4 real"),+ ),+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "statement.pdf"), "wr"+ )+ assert result == b"%PDF-1.4 real"++ @pytest.mark.asyncio+ async def test_empty_suggested_filename_fails_closed_without_reading(self) -> None:+ page = MagicMock()+ with (+ patch("skyvern.webeye.actions.handler._blob_iframe_src_titles", new=AsyncMock()) as titles,+ patch("skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes", new=AsyncMock()) as read,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", ""), "wr"+ )+ assert result is None+ titles.assert_not_awaited()+ read.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_single_iframe_name_mismatch_fails_closed(self) -> None:+ page = MagicMock()+ src = "blob:https://portal.example/live-uuid"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={src: "Statement.pdf"}),+ ),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(return_value=b"%PDF-1.4 real"),+ ) as read,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "different-name.pdf"), "wr"+ )+ assert result is None+ read.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_duplicate_matching_titles_fail_closed(self) -> None:+ page = MagicMock()+ srcs = {+ "blob:https://portal.example/a-uuid": "Statement.pdf",+ "blob:https://portal.example/b-uuid": "Statement.pdf",+ }+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value=srcs),+ ),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(return_value=b"%PDF-1.4 x"),+ ) as read,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )+ assert result is None+ read.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_non_pdf_blob_iframe_is_not_recovered(self) -> None:+ page = MagicMock()+ src = "blob:https://portal.example/live-uuid"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={src: "Statement.pdf"}),+ ),+ _patch_fresh_probe(),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(return_value=b"<html>login</html>"),+ ),+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "statement.pdf"), "wr"+ )+ assert result is None++ @pytest.mark.asyncio+ async def test_other_origin_blob_iframe_is_ignored(self) -> None:+ page = MagicMock()+ other = "blob:https://ads.example/other-uuid"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={other: "Ad.pdf"}),+ ),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(return_value=b"%PDF-1.4 ad"),+ ) as read,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "statement.pdf"), "wr"+ )+ assert result is None+ read.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_filename_match_selects_named_iframe_not_first(self) -> None:+ page = MagicMock()+ decoy = "blob:https://portal.example/decoy-uuid"+ wanted = "blob:https://portal.example/wanted-uuid"++ async def _read(*, page, blob_url, workflow_run_id, max_size_bytes, probe): # noqa: ANN001+ return b"%PDF-1.4 " + blob_url.encode()++ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={decoy: "DecoyDoc.pdf", wanted: "AnnualStatement2026.pdf"}),+ ),+ _patch_fresh_probe(),+ patch("skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes", new=_read),+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page,+ _blob_download("blob:https://portal.example/dl-uuid", "AnnualStatement2026.pdf"),+ "wr",+ )+ assert result == b"%PDF-1.4 " + wanted.encode()++ @pytest.mark.asyncio+ async def test_ambiguous_pdfs_without_filename_match_fail_closed(self) -> None:+ page = MagicMock()+ srcs = {+ "blob:https://portal.example/a-uuid": "DocA.pdf",+ "blob:https://portal.example/b-uuid": "DocB.pdf",+ }+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value=srcs),+ ),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(return_value=b"%PDF-1.4 x"),+ ),+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "unrelated.pdf"), "wr"+ )+ assert result is None++ @pytest.mark.asyncio+ async def test_filename_match_that_is_not_pdf_fails_closed(self) -> None:+ page = MagicMock()+ srcs = {+ "blob:https://portal.example/named-uuid": "Statement.pdf",+ "blob:https://portal.example/other-uuid": "Other.pdf",+ }++ async def _read(*, page, blob_url, workflow_run_id, max_size_bytes, probe): # noqa: ANN001+ return b"<html>not a pdf</html>" if "named-uuid" in blob_url else b"%PDF-1.4 other"++ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value=srcs),+ ),+ _patch_fresh_probe(),+ patch("skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes", new=_read),+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )+ assert result is None++ @pytest.mark.asyncio+ async def test_no_filename_match_logs_reason_and_candidate_count(self) -> None:+ page = MagicMock()+ srcs = {+ "blob:https://portal.example/a-uuid": "DocA.pdf",+ "blob:https://portal.example/b-uuid": "DocB.pdf",+ }+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value=srcs),+ ),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(return_value=b"%PDF-1.4 x"),+ ),+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "unrelated.pdf"), "wr"+ )+ assert result is None+ reason_calls = [c for c in log.info.call_args_list if c.kwargs.get("reason") == "no_filename_title_match"]+ assert len(reason_calls) == 1+ assert reason_calls[0].kwargs["candidate_count"] == 2++ @pytest.mark.asyncio+ async def test_missing_suggested_filename_logs_reason(self) -> None:+ page = MagicMock()+ with (+ patch("skyvern.webeye.actions.handler._blob_iframe_src_titles", new=AsyncMock()) as titles,+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", ""), "wr"+ )+ assert result is None+ titles.assert_not_awaited()+ assert any(c.kwargs.get("reason") == "missing_suggested_filename" for c in log.info.call_args_list)++ @pytest.mark.asyncio+ async def test_no_same_origin_candidate_logs_reason(self) -> None:+ page = MagicMock()+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={"blob:https://ads.example/x": "Ad.pdf"}),+ ),+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "statement.pdf"), "wr"+ )+ assert result is None+ no_origin = [c for c in log.info.call_args_list if c.kwargs.get("reason") == "no_same_origin_blob_iframe"]+ assert len(no_origin) == 1+ assert no_origin[0].kwargs["candidate_count"] == 0++ @pytest.mark.asyncio+ async def test_duplicate_match_logs_reason_and_counts(self) -> None:+ page = MagicMock()+ srcs = {+ "blob:https://portal.example/a-uuid": "Statement.pdf",+ "blob:https://portal.example/b-uuid": "Statement.pdf",+ }+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value=srcs),+ ),+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )+ assert result is None+ dup = [c for c in log.warning.call_args_list if c.kwargs.get("reason") == "duplicate_filename_match"]+ assert len(dup) == 1+ assert dup[0].kwargs["match_count"] == 2+ assert dup[0].kwargs["candidate_count"] == 2++ @pytest.mark.asyncio+ async def test_page_access_error_during_discovery_fails_closed(self) -> None:+ # Simulate the page/frame being torn down (e.g. remote session closing) mid-discovery.+ page = MagicMock()+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(side_effect=RuntimeError("Target page, context or browser has been closed")),+ ),+ patch("skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes", new=AsyncMock()) as read,+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )+ assert result is None+ read.assert_not_awaited()+ errors = [c for c in log.warning.call_args_list if c.kwargs.get("reason") == "recovery_error"]+ assert len(errors) == 1+ assert errors[0].kwargs["error_type"] == "RuntimeError"++ @pytest.mark.asyncio+ async def test_read_error_during_recovery_fails_closed(self) -> None:+ # A matched candidate whose read raises must fail closed, not propagate.+ page = MagicMock()+ src = "blob:https://portal.example/live-uuid"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={src: "Statement.pdf"}),+ ),+ _patch_fresh_probe(),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(side_effect=RuntimeError("frame detached")),+ ),+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )+ assert result is None+ assert any(c.kwargs.get("reason") == "recovery_error" for c in log.warning.call_args_list)++ @pytest.mark.asyncio+ async def test_recovery_does_not_swallow_cancellation(self) -> None:+ # CancelledError (BaseException) must propagate so the enclosing timeout/cancel scope observes it.+ page = MagicMock()+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(side_effect=asyncio.CancelledError()),+ ),+ patch("skyvern.webeye.actions.handler.LOG"),+ ):+ with pytest.raises(asyncio.CancelledError):+ await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )++ @pytest.mark.asyncio+ async def test_stale_named_iframe_not_action_fresh_fails_closed(self) -> None:+ # Title matches but the candidate blob is absent from the live retention Map: a lingering+ # same-named iframe from an earlier action must never be saved.+ page = MagicMock()+ src = "blob:https://portal.example/stale-uuid"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={src: "Statement.pdf"}),+ ),+ patch(+ "skyvern.webeye.actions.handler.probe_blob_action_freshness",+ new=AsyncMock(return_value=BlobActionFreshness(state_observed=True, retained=False)),+ ),+ patch("skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes", new=AsyncMock()) as read,+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )+ assert result is None+ read.assert_not_awaited()+ assert any(c.kwargs.get("reason") == "not_action_fresh" for c in log.info.call_args_list)++ @pytest.mark.asyncio+ async def test_retention_state_unobservable_fails_closed(self) -> None:+ # No probe realm exposes retention state at all: fail closed, distinctly from not_action_fresh.+ page = MagicMock()+ src = "blob:https://portal.example/live-uuid"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={src: "Statement.pdf"}),+ ),+ patch(+ "skyvern.webeye.actions.handler.probe_blob_action_freshness",+ new=AsyncMock(return_value=BlobActionFreshness(state_observed=False, retained=False)),+ ),+ patch("skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes", new=AsyncMock()) as read,+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )+ assert result is None+ read.assert_not_awaited()+ assert any(c.kwargs.get("reason") == "retention_state_unobservable" for c in log.info.call_args_list)++ @pytest.mark.asyncio+ async def test_action_fresh_named_iframe_is_recovered(self) -> None:+ # The candidate blob is a live key in the retention Map: proceed to the PDF read and save.+ page = MagicMock()+ src = "blob:https://portal.example/live-uuid"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={src: "Statement.pdf"}),+ ),+ _patch_fresh_probe(),+ patch(+ "skyvern.webeye.actions.handler.SkyvernFrame.read_blob_url_bytes",+ new=AsyncMock(return_value=b"%PDF-1.4 fresh"),+ ),+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", "Statement.pdf"), "wr"+ )+ assert result == b"%PDF-1.4 fresh"++ @pytest.mark.asyncio+ async def test_freshness_gate_skip_logs_no_sensitive_values(self) -> None:+ # The gate's skip log must carry only a reason + workflow id: never the blob URL, title,+ # suggested filename, or origin/domain.+ page = MagicMock()+ src = "blob:https://portal.example/secret-uuid"+ suggested = "AnnualStatement.pdf"+ with (+ patch(+ "skyvern.webeye.actions.handler._blob_iframe_src_titles",+ new=AsyncMock(return_value={src: suggested}),+ ),+ patch(+ "skyvern.webeye.actions.handler.probe_blob_action_freshness",+ new=AsyncMock(return_value=BlobActionFreshness(state_observed=True, retained=False)),+ ),+ patch("skyvern.webeye.actions.handler.LOG") as log,+ ):+ result = await _recover_adopted_session_blob_pdf_iframe(+ page, _blob_download("blob:https://portal.example/dl-uuid", suggested), "wr"+ )+ assert result is None+ for log_call in log.mock_calls:+ rendered = repr(log_call)+ assert src not in rendered+ assert suggested not in rendered+ assert "portal.example" not in rendered+++async def _run_download_action_for_wiring(*, browser_session_id: str | None) -> tuple:+ now = datetime.now(UTC)+ organization = make_organization(now)+ task, step, page, browser_state, scraped_page, action = _make_download_click_context(+ now=now,+ organization=organization,+ page_url="https://example.com/download",+ )+ task = task.model_copy(update={"download_timeout": 0.01, "browser_session_id": browser_session_id})++ with tempfile.TemporaryDirectory() as temp_dir:+ mock_app = MagicMock()+ mock_app.BROWSER_MANAGER.get_for_task.return_value = browser_state+ mock_app.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)+ storage = MagicMock()+ storage.list_downloading_files_in_browser_session = AsyncMock(return_value=[])+ storage.list_downloaded_files_in_browser_session = AsyncMock(return_value=[])+ mock_app.STORAGE = storage++ install = AsyncMock()+ teardown = AsyncMock()+ with (+ patch.object(ActionHandler, "_handle_action", side_effect=AsyncMock(return_value=[ActionSuccess()])),+ patch("skyvern.webeye.actions.handler.get_download_dir", return_value=temp_dir),+ patch("skyvern.webeye.actions.handler.list_files_in_directory", return_value=[]),+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=None),+ patch("skyvern.webeye.utils.page.install_blob_url_retention", install),+ patch("skyvern.webeye.actions.handler.teardown_blob_url_retention", teardown),+ patch("skyvern.webeye.actions.handler.app", mock_app),+ ):+ await ActionHandler.handle_action(+ scraped_page=scraped_page,+ task=task,+ step=step,+ page=page,+ action=action,+ )+ return install, teardown, page+++async def test_adopted_session_download_no_longer_installs_retention_but_still_tears_down() -> None:+ # Activation moved to the targeted cloud click setup; the generic handler keeps only the teardown.+ install, teardown, page = await _run_download_action_for_wiring(browser_session_id="pbs-1")++ install.assert_not_awaited()+ teardown.assert_awaited_once()+ assert teardown.await_args.args[0] is page+++async def test_managed_session_download_does_not_touch_blob_retention() -> None:+ install, teardown, _ = await _run_download_action_for_wiring(browser_session_id=None)++ install.assert_not_awaited()+ teardown.assert_not_awaited()+++def test_handler_module_no_longer_imports_blob_retention_install() -> None:+ import skyvern.webeye.actions.handler as handler_module++ assert not hasattr(handler_module, "install_blob_url_retention")diff --git a/tests/unit/test_read_blob_url_bytes.py b/tests/unit/test_read_blob_url_bytes.pyindex 9fabf1a4b..0b66e99cb 100644--- a/tests/unit/test_read_blob_url_bytes.py+++ b/tests/unit/test_read_blob_url_bytes.py@@ -3,7 +3,12 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from skyvern.webeye.utils.page import _SAME_ORIGIN_FETCH_JS, SkyvernFrame+from skyvern.webeye.utils.page import (+ _SAME_ORIGIN_FETCH_JS,+ BlobActionFreshness,+ SkyvernFrame,+ probe_blob_action_freshness,+)_MOD = "skyvern.webeye.utils.page"@@ -312,3 +317,180 @@ async def test_read_http_url_bytes_rejects_oversized() -> None:result = await SkyvernFrame.read_http_url_bytes(page=page, url="https://host.example/x.pdf", max_size_bytes=10)assert result is None+++# ---------------------------------------------------------------------------+# probe_blob_action_freshness: the retention-freshness gate. A named blob: iframe+# candidate is action-fresh only when its fragment-stripped URL is a live key in a+# __skyvernBlobRetention.retained Map in some realm relevant to the blob origin+# (or an indeterminate-origin frame that may inherit the creator origin). Only+# booleans cross the boundary; the URL is passed in but never logged or returned.+# ---------------------------------------------------------------------------++_BLOB = "blob:https://files.example.org/live-uuid"+_BLOB_ORIGIN_URL = "https://files.example.org/app"+_OTHER_ORIGIN_URL = "https://app.example.com/dashboard"+++async def test_probe_freshness_retained_in_main_realm() -> None:+ page = MagicMock()+ main_frame = MagicMock()+ main_frame.url = _BLOB_ORIGIN_URL+ page.main_frame = main_frame+ page.frames = [main_frame]+ eval_mock = AsyncMock(return_value={"observed": True, "retained": True})++ with patch(f"{_MOD}.evaluate_in_main_world", new=eval_mock):+ result = await probe_blob_action_freshness(page, _BLOB, workflow_run_id="wr")++ assert result == BlobActionFreshness(state_observed=True, retained=True)+ # Main frame routes through the main-world seam, never a raw main_frame.evaluate.+ main_frame.evaluate.assert_not_called()+ _p, _js, arg = eval_mock.await_args.args+ assert arg == _BLOB+++async def test_probe_freshness_state_present_but_candidate_absent() -> None:+ page = MagicMock()+ main_frame = MagicMock()+ main_frame.url = _BLOB_ORIGIN_URL+ page.main_frame = main_frame+ page.frames = [main_frame]+ eval_mock = AsyncMock(return_value={"observed": True, "retained": False})++ with patch(f"{_MOD}.evaluate_in_main_world", new=eval_mock):+ result = await probe_blob_action_freshness(page, _BLOB)++ assert result == BlobActionFreshness(state_observed=True, retained=False)+++async def test_probe_freshness_no_state_observable_anywhere() -> None:+ page = MagicMock()+ main_frame = MagicMock()+ main_frame.url = _BLOB_ORIGIN_URL+ page.main_frame = main_frame+ page.frames = [main_frame]+ eval_mock = AsyncMock(return_value={"observed": False, "retained": False})++ with patch(f"{_MOD}.evaluate_in_main_world", new=eval_mock):+ result = await probe_blob_action_freshness(page, _BLOB)++ assert result == BlobActionFreshness(state_observed=False, retained=False)+++async def test_probe_freshness_creator_realm_not_display_frame() -> None:+ """Main/parent mints the blob and assigns it to an iframe src; the display frame's realm has no+ retention state. The gate must succeed by probing the creator (main) realm, and still best-effort+ probe the indeterminate display frame."""+ page = MagicMock()+ main_frame = MagicMock()+ main_frame.url = _BLOB_ORIGIN_URL+ display_frame = MagicMock()+ display_frame.url = "about:blank"+ display_frame.evaluate = AsyncMock(return_value={"observed": False, "retained": False})+ page.main_frame = main_frame+ page.frames = [main_frame, display_frame]+ main_eval = AsyncMock(return_value={"observed": True, "retained": True})++ with patch(f"{_MOD}.evaluate_in_main_world", new=main_eval):+ result = await probe_blob_action_freshness(page, _BLOB)++ assert result == BlobActionFreshness(state_observed=True, retained=True)+ display_frame.evaluate.assert_awaited_once()+++async def test_probe_freshness_probe_failure_in_one_frame_is_best_effort() -> None:+ """A probe raising in one realm never escapes; the verdict rests on the other realms."""+ page = MagicMock()+ main_frame = MagicMock()+ main_frame.url = _BLOB_ORIGIN_URL+ sub_frame = MagicMock()+ sub_frame.url = "https://files.example.org/preview"+ sub_frame.evaluate = AsyncMock(return_value={"observed": True, "retained": True})+ page.main_frame = main_frame+ page.frames = [main_frame, sub_frame]+ main_eval = AsyncMock(side_effect=RuntimeError("main realm detached"))++ with patch(f"{_MOD}.evaluate_in_main_world", new=main_eval):+ result = await probe_blob_action_freshness(page, _BLOB)++ assert result == BlobActionFreshness(state_observed=True, retained=True)+ sub_frame.evaluate.assert_awaited_once()+++async def test_probe_freshness_sub_frame_routes_through_frame_evaluate() -> None:+ """A main frame at a different (determinate) origin is not probed; a same-origin sub-frame is,+ via frame.evaluate with the candidate URL as the argument."""+ page = MagicMock()+ main_frame = MagicMock()+ main_frame.url = _OTHER_ORIGIN_URL+ sub_frame = MagicMock()+ sub_frame.url = "https://files.example.org/preview"+ sub_frame.evaluate = AsyncMock(return_value={"observed": True, "retained": True})+ page.main_frame = main_frame+ page.frames = [main_frame, sub_frame]+ main_eval = AsyncMock(return_value={"observed": True, "retained": True})++ with patch(f"{_MOD}.evaluate_in_main_world", new=main_eval):+ result = await probe_blob_action_freshness(page, _BLOB)++ assert result == BlobActionFreshness(state_observed=True, retained=True)+ main_eval.assert_not_awaited()+ _js, arg = sub_frame.evaluate.await_args.args+ assert arg == _BLOB+++async def test_probe_freshness_non_blob_url_returns_unobservable_without_probing() -> None:+ page = MagicMock()+ page.main_frame = MagicMock()+ page.frames = [page.main_frame]++ with patch(f"{_MOD}.evaluate_in_main_world", new=AsyncMock()) as eval_mock:+ result = await probe_blob_action_freshness(page, "https://files.example.org/not-a-blob")++ assert result == BlobActionFreshness(state_observed=False, retained=False)+ eval_mock.assert_not_awaited()+++async def test_probe_freshness_never_logs_candidate_url() -> None:+ page = MagicMock()+ main_frame = MagicMock()+ main_frame.url = _BLOB_ORIGIN_URL+ page.main_frame = main_frame+ page.frames = [main_frame]+ log_mock = MagicMock()+ eval_mock = AsyncMock(side_effect=RuntimeError("boom"))++ with (+ patch(f"{_MOD}.evaluate_in_main_world", new=eval_mock),+ patch(f"{_MOD}.LOG", log_mock),+ ):+ result = await probe_blob_action_freshness(page, _BLOB, workflow_run_id="wr")++ assert result == BlobActionFreshness(state_observed=False, retained=False)+ log_mock.debug.assert_called()+ for call in log_mock.mock_calls:+ assert _BLOB not in repr(call)+++def test_retention_js_blocks_share_ownership_brand_and_version() -> None:+ # Drift guard: install/teardown/probe must validate the same Skyvern ownership brand + version so a+ # foreign or stale same-name global is never treated as owned.+ from skyvern.webeye.utils import page as page_mod++ for js in (+ page_mod._BLOB_RETENTION_INSTALL_JS,+ page_mod._BLOB_RETENTION_TEARDOWN_JS,+ page_mod._BLOB_RETENTION_PROBE_JS,+ ):+ assert page_mod._BLOB_RETENTION_BRAND in js+ assert f"VERSION = {page_mod._BLOB_RETENTION_VERSION}" in js+ assert "isOwned" in js