Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Count a visible Cloudflare challenge frame as a present captcha in the solve ladder (SKY-16235) (#8595)
Andrew Neilson81042d747918
diff --git a/skyvern/webeye/display_recorder.py b/skyvern/webeye/display_recorder.pyindex 9b2868e03..44f63748d 100644--- a/skyvern/webeye/display_recorder.py+++ b/skyvern/webeye/display_recorder.py@@ -29,6 +29,7 @@ from skyvern.config import settingsfrom skyvern.webeye import attach_onlyfrom skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifactfrom skyvern.webeye.display_capture_bridge import build_bridge_command+from skyvern.webeye.video_utils import remux_mp4_faststarttry:import fcntl@@ -429,6 +430,10 @@ class DisplayRecorder:self._reserved = False# Latched once the arm signal is successfully delivered to the bridge (parent-side exactly-once).self._armed = False+ # Latched only after a terminal faststart remux COMPLETES. Tracked separately from ``_stop_result``+ # so a cancellation during the remux (which propagates) leaves this False and a later cleanup retry+ # re-attempts the remux, without ever re-escalating the already-stopped recorder.+ self._faststart_done = Falsedef arm_capture(self) -> bool:"""Signal the bridge to begin its timeline at the current ready page (SIGUSR1). Parent-side@@ -471,28 +476,73 @@ class DisplayRecorder:async def stop(self, release_lock: bool = True) -> bool:async with self._stop_lock:- if self._stop_result is not None:- return self._stop_result- graceful = self.process.returncode == 0- pending_cancel = False- try:- graceful = await self._escalate_shutdown(graceful)- except asyncio.CancelledError:- pending_cancel = True- finally:- # Reap the child and (unless reserved) release the lock even under repeated cancellation, so a- # cancelled stop never leaks the bridge/ffmpeg or blocks the next run.- if self.process.returncode is None:- _kill_process_group(self.process)- if await _reap_surviving_cancellation(self.process):- pending_cancel = True- graceful = False- if release_lock:- self._release_lock()- self._stop_result = graceful- if pending_cancel:- raise asyncio.CancelledError()- return graceful+ # Exactly-once recorder stop: the escalate + reap + latch runs only on the first call, so a+ # later cleanup retry never re-signals or re-reaps the already-stopped bridge.+ if self._stop_result is None:+ graceful = self.process.returncode == 0+ pending_cancel = False+ try:+ graceful = await self._escalate_shutdown(graceful)+ except asyncio.CancelledError:+ pending_cancel = True+ finally:+ # Reap the child even under repeated cancellation, so a cancelled stop never leaks the+ # bridge/ffmpeg or blocks the next run.+ if self.process.returncode is None:+ _kill_process_group(self.process)+ if await _reap_surviving_cancellation(self.process):+ pending_cancel = True+ graceful = False+ self._stop_result = graceful+ if pending_cancel:+ if release_lock:+ self._release_lock()+ raise asyncio.CancelledError()+ # Release the lock (unless reserved) on this and every retry; _release_lock is idempotent, so a+ # retry after a cancelled faststart still frees it exactly once.+ if release_lock:+ self._release_lock()+ # Terminal faststart, retriable across cancellation: only a graceful stop has a complete MP4 to+ # remux (a forced/failed stop keeps the fragmented crash-salvage file). _faststart_done is latched+ # only AFTER the remux returns, so a cancellation here propagates and a later retry re-attempts it;+ # ordinary remux failures are fail-open inside the helper and are not retried.+ if self._stop_result and not self._faststart_done:+ await self._faststart_finalized_recording()+ self._faststart_done = True+ return self._stop_result++ async def _faststart_finalized_recording(self) -> None:+ """Rewrite the finalized recording to a seekable faststart layout in place.++ The bridge writes a fragmented MP4 so an abrupt kill still leaves a decodable file; once a+ graceful stop finalizes it, a native ``<video>`` still can't seek it (``empty_moov``, no+ ``sidx``). Best-effort: any failure keeps the original recording so it is never lost and+ recording cleanup never turns into task failure.+ """+ path = self.video_artifact.video_path+ if not path:+ return+ try:+ remuxed = await remux_mp4_faststart(path)+ except Exception: # noqa: BLE001 - playback optimization must never fail recording cleanup+ LOG.warning(+ "Display recording faststart remux errored; keeping raw file", owner_id=self.owner_id, exc_info=True+ )+ return+ if remuxed is None:+ return+ # ``remux_mp4_faststart`` wrote the temp beside ``path`` (same mount), so this is an atomic+ # rename: it either fully swaps in the faststart file or leaves the original byte-identical.+ try:+ os.replace(remuxed, path)+ except OSError:+ LOG.warning(+ "Failed to swap in faststart display recording; keeping raw file",+ owner_id=self.owner_id,+ exc_info=True,+ )+ with suppress(OSError):+ os.unlink(remuxed)async def _escalate_shutdown(self, graceful: bool) -> bool:if self.process.returncode is not None:diff --git a/skyvern/webeye/utils/captcha_solver.py b/skyvern/webeye/utils/captcha_solver.pyindex 1d904a8c4..86bea58f7 100644--- a/skyvern/webeye/utils/captcha_solver.py+++ b/skyvern/webeye/utils/captcha_solver.py@@ -4,7 +4,9 @@ A bounded, engine-agnostic ladder that detects a visible captcha challenge and dsolver arms (DOM checkbox, reCAPTCHA anchor in-frame click, the solver extension, and the reCAPTCHAtoken route). Detection keys off DOM/iframe markers, so it sees the challenge even when the widgetrenders in a cross-origin iframe (the ``<iframe>`` element is a main-frame node a targeted locator can-find); a caller that opts in with ``probe_child_frames`` also has visible child frames' documents probed.+find), and a visible ``challenges.cloudflare.com`` frame counts too, since a Turnstile mounted under a closed+shadow root is invisible to CSS locators; a caller that opts in with ``probe_child_frames`` also has visible+child frames' documents probed.Solving routes through the ``AGENT_FUNCTION`` seam (``auto_solve_captchas`` / ``solve_recaptcha_token``),so this module stays OSS-clean: the OSS bases return False and the cloud overrides do the real solve.@@ -21,6 +23,7 @@ import structlogfrom playwright.async_api import Error as PlaywrightErrorfrom playwright.async_api import Frame, Page+from skyvern.config import settingsfrom skyvern.forge import appif TYPE_CHECKING:@@ -69,6 +72,7 @@ _RECAPTCHA_MARKER_SELECTOR = ", ".join(_RECAPTCHA_RESPONSE_SELECTOR = 'textarea[name="g-recaptcha-response"], textarea[id^="g-recaptcha-response"]'_RECAPTCHA_ANCHOR_HOSTS = ("www.google.com", "www.recaptcha.net")_RECAPTCHA_ANCHOR_PATHS = ("/recaptcha/api2/anchor", "/recaptcha/enterprise/anchor")+_CLOUDFLARE_CHALLENGE_HOST = "challenges.cloudflare.com"_RECAPTCHA_ANCHOR_ARM_TIMEOUT_SECONDS = 5# The extension arm polls a solver over the network; the scout caller has no enclosing bound._EXTENSION_ARM_TIMEOUT_SECONDS = 12@@ -123,9 +127,29 @@ def _intersects_viewport(box: Any, viewport: Any) -> bool:)-async def _frame_has_visible_match(frame: Any, selector: str, viewport: Any) -> bool:+async def _frame_has_visible_match(+ frame: Any, selector: str | None, viewport: Any, *, challenge_frames: bool = False+) -> bool:+ challenge_candidate = challenge_frames and (+ _matches_cloudflare_challenge_host(frame.url) or frame.url in ("", "about:blank")+ )+ if selector is None and not challenge_candidate:+ return Falseasync with asyncio.timeout(1.0):- if not await (await frame.frame_element()).is_visible():+ element = await frame.frame_element()+ if not await element.is_visible():+ return False+ # A frame that has not committed its cross-origin navigation still reports the challenge host in the+ # iframe element's `src`, so an uncommitted frame is judged on the attribute instead of `frame.url`.+ if challenge_candidate and (+ _matches_cloudflare_challenge_host(frame.url)+ or _matches_cloudflare_challenge_host(await element.get_attribute("src"))+ ):+ # Turnstile's invisible mode mounts a 1x1 frame that `is_visible()` still accepts; there is nothing+ # to solve in it, so only an on-screen frame with room for an interactive widget counts.+ box = await element.bounding_box()+ return box is not None and box["width"] > 1 and box["height"] > 1 and _intersects_viewport(box, viewport)+ if selector is None:return False# Every match, not a prefix: stale hidden widgets can precede the live one; the timeout bounds the walk.matches = frame.locator(selector)@@ -136,9 +160,13 @@ async def _frame_has_visible_match(frame: Any, selector: str, viewport: Any) ->return False-async def _visible_child_frame_match(page: Page | RecordingPage, selector: str) -> bool:+async def _visible_child_frame_match(+ page: Page | RecordingPage, selector: str | None, *, challenge_frames: bool = False+) -> bool:"""True when a visible child frame holds a visible `selector` match; each frame's probe is bounded, and a- frame that fails it (detached, wedged, no element) is skipped so one broken frame cannot blind the rest."""+ frame that fails it (detached, wedged, no element) is skipped so one broken frame cannot blind the rest.+ With ``challenge_frames``, a visible challenge-host frame counts on its own, by its committed URL or, before+ that navigation commits, by its iframe ``src``."""# A frame probe must never be able to break the ladder: an unreadable page reads as "no nested challenge",# logged apart from a clean scan so a systematically blind page type stays countable.try:@@ -150,10 +178,15 @@ async def _visible_child_frame_match(page: Page | RecordingPage, selector: str)viewport = page.viewport_sizeexcept Exception:viewport = None+ # A display-fitted `no_viewport` context reports None; without a size every off-screen frame would pass.+ if not viewport:+ viewport = {"width": settings.BROWSER_WIDTH, "height": settings.BROWSER_HEIGHT}# Frames are probed concurrently under one deadline, so the frame that matters is found regardless of# where it sits in frame order; a sequential walk let earlier wedged frames spend the budget first.probes = [- asyncio.ensure_future(_frame_has_visible_match(f, selector, viewport)) for f in frames if f is not main_frame+ asyncio.ensure_future(_frame_has_visible_match(f, selector, viewport, challenge_frames=challenge_frames))+ for f in frames+ if f is not main_frame]try:for probe in asyncio.as_completed(probes, timeout=_CHILD_FRAME_SCAN_BUDGET_SECONDS):@@ -171,6 +204,16 @@ async def _visible_child_frame_match(page: Page | RecordingPage, selector: str)return False+def _matches_cloudflare_challenge_host(frame_url: str | None) -> bool:+ if not frame_url:+ return False+ try:+ hostname = (urlparse(frame_url).hostname or "").lower()+ except ValueError:+ return False+ return hostname == _CLOUDFLARE_CHALLENGE_HOST or hostname.endswith("." + _CLOUDFLARE_CHALLENGE_HOST)++def _is_trusted_recaptcha_anchor_url(frame_url: str | None) -> bool:if not frame_url:return False@@ -207,8 +250,9 @@ async def solve_challenge_ladder(Thin public entry: it enters the ``AGENT_FUNCTION`` captcha-solver lifecycle scope exactly oncearound the ladder, so a deployment can bind a page-scoped solver lifecycle for the whole solve- (its self-heal/teardown owned by that scope). ``probe_child_frames`` opts a caller into also- detecting a challenge inside visible child frames; the default keeps the main-document-only check.+ (its self-heal/teardown owned by that scope). ``probe_child_frames`` opts a caller into also probing+ visible child frames' documents for markers; the default checks the main document plus a visible+ ``challenges.cloudflare.com`` frame."""async with app.AGENT_FUNCTION.captcha_solver_lifecycle_scope(page):return await _solve_challenge_ladder_impl(@@ -245,9 +289,10 @@ async def _solve_challenge_ladder_impl(if (checkbox_count == 0and marker_count == 0- and not (- probe_child_frames- and await _visible_child_frame_match(page, f"{_CAPTCHA_CHECKBOX_SELECTOR}, {_CAPTCHA_MARKER_SELECTOR}")+ and not await _visible_child_frame_match(+ page,+ f"{_CAPTCHA_CHECKBOX_SELECTOR}, {_CAPTCHA_MARKER_SELECTOR}" if probe_child_frames else None,+ challenge_frames=True,)):return Falsediff --git a/skyvern/webeye/video_utils.py b/skyvern/webeye/video_utils.pyindex 717c9336b..6aed72c21 100644--- a/skyvern/webeye/video_utils.py+++ b/skyvern/webeye/video_utils.py@@ -52,8 +52,11 @@ async def _run_ffmpeg_to_temp(timeout_seconds: float,operation: str,input_args: list[str] | None = None,+ output_dir: str | None = None,) -> str | None:- with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as dst_tmp:+ # ``output_dir`` places the temp output on a chosen filesystem so a caller can later swap it in+ # with an atomic ``os.replace`` (same mount); ``None`` keeps the default system temp location.+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False, dir=output_dir) as dst_tmp:dst_path = dst_tmp.namekeep_output = False@@ -169,6 +172,30 @@ async def _remux_webm(src_path: str) -> str | None:)+async def remux_mp4_faststart(src_path: str) -> str | None:+ """Stream-copy an MP4 into a non-fragmented, faststart (front-``moov``) layout.++ Fragmented MP4s (``empty_moov`` + ``moof`` fragments, no ``sidx``) carry a+ zero-duration init ``moov`` and no seek index, so a native ``<video>`` must+ download and demux the whole file to read a duration or seek; a ``-c copy``+ remux rewrites one front ``moov`` with real sample tables and duration. The+ temp output is created beside the source so the caller can swap it in with an+ atomic ``os.replace`` on the same mount. Returns a temp path, or ``None`` if+ ffmpeg is missing or the remux fails.+ """+ if shutil.which(FFMPEG_BINARY) is None:+ LOG.warning("ffmpeg binary not found on PATH, skipping mp4 faststart remux", src=src_path)+ return None+ return await _run_ffmpeg_to_temp(+ src_path,+ suffix=".mp4",+ output_args=["-c", "copy", "-movflags", "+faststart"],+ timeout_seconds=FFMPEG_REMUX_TIMEOUT_SECONDS,+ operation="ffmpeg mp4 faststart remux",+ output_dir=os.path.dirname(src_path) or None,+ )++async def _prepare_recording_upload(src_path: str) -> PreparedRecordingUpload | None:if shutil.which(FFMPEG_BINARY) is None:LOG.warning("ffmpeg binary not found on PATH, returning raw recording", src=src_path)diff --git a/tests/unit/test_code_block_captcha.py b/tests/unit/test_code_block_captcha.pyindex bab940e63..455b591a5 100644--- a/tests/unit/test_code_block_captcha.py+++ b/tests/unit/test_code_block_captcha.py@@ -2,10 +2,16 @@ from __future__ import annotationsimport asyncioimport time+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from pathlib import Pathfrom unittest.mock import AsyncMock+from urllib.parse import urlparseimport pytestfrom playwright.async_api import Error as PlaywrightError+from playwright.async_api import Page, Route, async_playwright+from playwright.sync_api import sync_playwrightfrom skyvern.forge import appfrom skyvern.forge.agent_functions import AgentFunction@@ -18,6 +24,11 @@ from skyvern.webeye.utils import captcha_solver as captcha_solver_modulefrom skyvern.webeye.utils.captcha_solver import CaptchaChallengeUnsolvedError, solve_challenge_ladderfrom tests.unit.conftest import ScopeRecordingAgentFunction+CHALLENGE_URL = (+ "https://challenges.cloudflare.com/cdn-cgi/challenge-platform/turnstile/if/ov2/av0/fake?sitekey=0xTESTKEY"+)+CHALLENGE_SUBDOMAIN_URL = "https://edge.challenges.cloudflare.com/cdn-cgi/challenge-platform/fake"+class FakeLocator:def __init__(@@ -78,12 +89,22 @@ class FakeLocator:class FakeFrameElement:- def __init__(self, *, visible: bool) -> None:+ def __init__(self, *, visible: bool, src: str | None = None, box: dict[str, float] | None = None) -> None:self._visible = visible+ self._src = src+ self._box = box if box is not None else {"x": 0.0, "y": 100.0, "width": 300.0, "height": 65.0}+ self.get_attribute_calls: list[str] = []async def is_visible(self) -> bool:return self._visible+ async def bounding_box(self) -> dict[str, float]:+ return self._box++ async def get_attribute(self, name: str) -> str | None:+ self.get_attribute_calls.append(name)+ return self._src if name == "src" else None+class FakeFrame:def __init__(@@ -96,6 +117,8 @@ class FakeFrame:nested_marker: FakeLocator | None = None,is_hcaptcha_marker: bool = False,visible: bool = True,+ src: str | None = None,+ box: dict[str, float] | None = None,) -> None:self.url = urlself.anchor = anchor or FakeLocator(count=0)@@ -103,7 +126,7 @@ class FakeFrame:self.detached = detachedself.nested_marker = nested_marker or FakeLocator(count=0)self.is_hcaptcha_marker = is_hcaptcha_marker- self._element = FakeFrameElement(visible=visible)+ self.element = FakeFrameElement(visible=visible, src=src, box=box)def locator(self, selector: str) -> FakeLocator:if selector == "#recaptcha-anchor":@@ -118,7 +141,7 @@ class FakeFrame:return self.detachedasync def frame_element(self) -> FakeFrameElement:- return self._element+ return self.elementclass FakePage:@@ -187,6 +210,7 @@ async def test_real_sandbox_solve_captcha_is_fast_noop_without_challenge(monkeypawait fn()+ assert await solve_challenge_ladder(FakePage()) is Falseagent_function.auto_solve_captchas.assert_not_awaited()agent_function.solve_recaptcha_token.assert_not_awaited()@@ -1065,8 +1089,8 @@ async def test_a_challenge_frame_behind_wedged_frames_is_still_found(monkeypatch@pytest.mark.asyncioasync def test_child_frames_are_not_probed_unless_the_caller_opts_in(monkeypatch: pytest.MonkeyPatch) -> None:- # The code-block builtin keeps the main-document-only presence check; only an opted-in caller- # (the Task V3 solve_captcha tool) reaches a challenge nested in a child frame.+ # The default path only reads child frames' URLs; probing their documents for markers stays opt-in+ # (the Task V3 solve_captcha tool), so a marker nested in a non-challenge-host frame reads absent.agent_function = type("AgentFunctionStub",(AgentFunction,),@@ -1268,3 +1292,296 @@ async def test_ladder_anchor_completion_gate_runs_inside_scope(assert await solve_challenge_ladder(page) is Trueassert agent_function.events == expected_events+++def _has_playwright_browser() -> bool:+ try:+ with sync_playwright() as playwright:+ return Path(playwright.chromium.executable_path).exists()+ except Exception:+ return False+++_skip_no_browser = pytest.mark.skipif(+ not _has_playwright_browser(),+ reason="Requires Playwright browsers installed (run: playwright install chromium)",+)++_AUTO_RENDER_TURNSTILE_HTML = f"""<!DOCTYPE html>+<html><body>+ <form><input id="email" type="email" /><button type="submit">Submit</button></form>+ <div class="cf-turnstile" data-sitekey="0xTESTKEY">+ <iframe src="{CHALLENGE_URL}" style="width:300px;height:65px"></iframe>+ </div>+</body></html>+"""++_CLOSED_SHADOW_TURNSTILE_HTML = f"""<!DOCTYPE html>+<html><body>+ <form><input id="email" type="email" /><button type="submit">Submit</button></form>+ <div id="widget-host"></div>+ <script>+ const root = document.getElementById("widget-host").attachShadow({{mode: "closed"}});+ const f = document.createElement("iframe");+ f.src = "{CHALLENGE_URL}";+ f.style.width = "300px";+ f.style.height = "65px";+ root.appendChild(f);+ </script>+</body></html>+"""+++async def _fulfill_challenge(route: Route) -> None:+ await route.fulfill(status=200, content_type="text/html", body="<html><body>Verify you are human</body></html>")+++@asynccontextmanager+async def _challenge_browser_page(html: str) -> AsyncIterator[Page]:+ async with async_playwright() as playwright:+ browser = await playwright.chromium.launch(headless=True)+ try:+ context = await browser.new_context()+ await context.route("https://challenges.cloudflare.com/**", _fulfill_challenge)+ page = await context.new_page()+ await page.set_content(html, wait_until="load")+ assert any(urlparse(frame.url).hostname == "challenges.cloudflare.com" for frame in page.frames), (+ "challenge frame did not commit"+ )+ yield page+ finally:+ await browser.close()+++def _stub_solver_agent() -> AgentFunction:+ return type(+ "AgentFunctionStub",+ (AgentFunction,),+ {+ "auto_solve_captchas": AsyncMock(return_value=True),+ "solve_recaptcha_token": AsyncMock(return_value=False),+ },+ )()+++@_skip_no_browser+async def test_browser_auto_render_turnstile_is_present(monkeypatch: pytest.MonkeyPatch) -> None:+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)++ async with _challenge_browser_page(_AUTO_RENDER_TURNSTILE_HTML) as page:+ assert await solve_challenge_ladder(page) is True++ agent_function.auto_solve_captchas.assert_awaited_once()+++@_skip_no_browser+async def test_browser_closed_shadow_root_turnstile_is_present(monkeypatch: pytest.MonkeyPatch) -> None:+ # A Turnstile mounted under a closed shadow root is unreachable by CSS locators; only page.frames sees it.+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)++ async with _challenge_browser_page(_CLOSED_SHADOW_TURNSTILE_HTML) as page:+ assert await page.locator(captcha_solver_module._CAPTCHA_MARKER_SELECTOR).count() == 0+ assert await page.locator(captcha_solver_module._CAPTCHA_CHECKBOX_SELECTOR).count() == 0++ assert await solve_challenge_ladder(page) is True++ agent_function.auto_solve_captchas.assert_awaited_once()++[email protected]("probe_child_frames", [False, True])[email protected]("frame_url", [CHALLENGE_URL, CHALLENGE_SUBDOMAIN_URL])+async def test_visible_cloudflare_challenge_frame_reaches_extension_arm(+ monkeypatch: pytest.MonkeyPatch, probe_child_frames: bool, frame_url: str+) -> None:+ """A Turnstile widget can mount where no CSS locator reaches it, so a visible frame on the challenge+ host is itself the presence signal, for both callers."""+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ page = FakePage(frames=[FakeFrame(url=frame_url, visible=True)])++ assert await solve_challenge_ladder(page, probe_child_frames=probe_child_frames) is True++ agent_function.auto_solve_captchas.assert_awaited_once_with(page)+++async def test_builtin_reaches_extension_arm_for_a_visible_cloudflare_challenge_frame(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ page = FakePage(frames=[FakeFrame(url=CHALLENGE_URL, visible=True)])++ assert await block_module._code_block_solve_captcha_builtin(page) is True++ agent_function.auto_solve_captchas.assert_awaited_once_with(page)+++ ("frame_url", "visible", "box"),+ [+ ("https://evil.example.com/?next=challenges.cloudflare.com", True, None),+ ("https://challenges.cloudflare.com.evil.example/", True, None),+ (CHALLENGE_URL, False, None),+ (CHALLENGE_URL, True, {"x": 0.0, "y": 0.0, "width": 1.0, "height": 1.0}),+ (CHALLENGE_URL, True, {"x": -9999.0, "y": 0.0, "width": 300.0, "height": 65.0}),+ ],+)+async def test_decoy_and_hidden_cloudflare_frames_stay_absent(+ monkeypatch: pytest.MonkeyPatch, frame_url: str, visible: bool, box: dict[str, float] | None+) -> None:+ """The host must be matched on the parsed hostname, and Turnstile's hidden helper frames, its+ invisible-mode 1x1 frame, and a frame parked off-screen sit on the real host, so those must keep+ reading absent."""+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ page = FakePage(frames=[FakeFrame(url=frame_url, visible=visible, box=box)])++ assert await solve_challenge_ladder(page) is False++ agent_function.auto_solve_captchas.assert_not_awaited()++[email protected](("frame_x", "present"), [(100.0, True), (5000.0, False)])+async def test_challenge_frame_is_judged_on_screen_when_the_page_reports_no_viewport(+ monkeypatch: pytest.MonkeyPatch, frame_x: float, present: bool+) -> None:+ """A display-fitted browser context reports no viewport size, so the configured browser size stands in."""+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ page = FakePage(+ frames=[+ FakeFrame(url=CHALLENGE_URL, visible=True, box={"x": frame_x, "y": 0.0, "width": 300.0, "height": 65.0})+ ]+ )+ page.viewport_size = None++ assert await solve_challenge_ladder(page) is present+++async def test_an_uncommitted_challenge_frame_matches_on_its_iframe_src(monkeypatch: pytest.MonkeyPatch) -> None:+ """A cross-origin challenge frame reports an empty URL until its navigation commits, while the iframe+ element's src already names the challenge host."""+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ page = FakePage(frames=[FakeFrame(url="", src=CHALLENGE_URL, visible=True)])++ assert await solve_challenge_ladder(page) is True++ agent_function.auto_solve_captchas.assert_awaited_once_with(page)+++ "src",+ [+ "https://evil.example.com/?next=challenges.cloudflare.com",+ "https://challenges.cloudflare.com.evil.example/",+ ],+)+async def test_an_uncommitted_frame_with_a_decoy_src_stays_absent(monkeypatch: pytest.MonkeyPatch, src: str) -> None:+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ page = FakePage(frames=[FakeFrame(url="about:blank", src=src, visible=True)])++ assert await solve_challenge_ladder(page) is False++ agent_function.auto_solve_captchas.assert_not_awaited()+++async def test_an_uncommitted_frame_with_a_foreign_src_is_still_selector_scanned(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The src probe must not short-circuit an uncommitted frame out of the marker scan it would otherwise+ get."""+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ frame = FakeFrame(+ url="about:blank", src="https://cdn.example/widget", nested_marker=FakeLocator(count=1), visible=True+ )+ page = FakePage(frames=[frame])++ assert await solve_challenge_ladder(page, probe_child_frames=True) is True+++async def test_a_committed_non_challenge_frame_is_never_probed_for_its_src(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Reading the src attribute is a round trip per frame; only frames with no committed URL may pay it."""+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ frame = FakeFrame(url="https://app.example/embed", nested_marker=FakeLocator(count=1), visible=True)+ page = FakePage(frames=[frame])++ assert await solve_challenge_ladder(page, probe_child_frames=True) is True+ assert frame.element.get_attribute_calls == []+++class _DetachedChallengeFrame(_DetachedFrame):+ url = CHALLENGE_URL+++async def test_a_raising_challenge_frame_does_not_hide_a_visible_one(monkeypatch: pytest.MonkeyPatch) -> None:+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ page = FakePage(frames=[_DetachedChallengeFrame(), FakeFrame(url=CHALLENGE_URL, visible=True)]) # type: ignore[list-item]++ assert await solve_challenge_ladder(page) is True+++class _WedgedChallengeFrame(_WedgedFrame):+ url = CHALLENGE_URL+++async def test_wedged_challenge_frames_are_bounded_on_the_default_path(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(app, "AGENT_FUNCTION", AgentFunction())+ monkeypatch.setattr(captcha_solver_module, "_CHILD_FRAME_SCAN_BUDGET_SECONDS", 0.3)+ page = FakePage(frames=[_WedgedChallengeFrame() for _ in range(5)])++ started = time.monotonic()+ assert await solve_challenge_ladder(page) is False+ assert time.monotonic() - started < 1.0+++async def test_the_opted_in_absent_path_runs_one_frame_scan(monkeypatch: pytest.MonkeyPatch) -> None:+ # Two composed scans (challenge-host frames, then markers) would each spend the whole budget.+ monkeypatch.setattr(app, "AGENT_FUNCTION", AgentFunction())+ monkeypatch.setattr(captcha_solver_module, "_CHILD_FRAME_SCAN_BUDGET_SECONDS", 0.3)+ page = FakePage(frames=[_WedgedChallengeFrame()])++ started = time.monotonic()+ assert await solve_challenge_ladder(page, probe_child_frames=True) is False+ assert time.monotonic() - started < 0.5+++async def test_visible_challenge_frame_keeps_the_turnstile_extension_budget(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A Turnstile page must not inherit the hCaptcha image-challenge bound: it would hold a failing+ extension arm open for a minute and a half."""+ agent_function = _stub_solver_agent()+ monkeypatch.setattr(app, "AGENT_FUNCTION", agent_function)+ resolve_calls: list[float] = []+ monkeypatch.setattr(+ agent_function,+ "resolve_captcha_solver_extension_timeout",+ lambda _page, default_timeout: resolve_calls.append(default_timeout) or default_timeout,+ )+ page = FakePage(frames=[FakeFrame(url=CHALLENGE_URL, visible=True)])++ assert await solve_challenge_ladder(page, probe_child_frames=True) is True+ assert resolve_calls == [captcha_solver_module._EXTENSION_ARM_TIMEOUT_SECONDS]diff --git a/tests/unit/test_display_recorder.py b/tests/unit/test_display_recorder.pyindex 8f01aa0e0..293e26b35 100644--- a/tests/unit/test_display_recorder.py+++ b/tests/unit/test_display_recorder.py@@ -405,6 +405,197 @@ async def test_stop_is_idempotent() -> None:assert len(proc.signals) == n_signals+def _recorder_with_path(proc: _FakeProc, video_path) -> dr.DisplayRecorder:+ from skyvern.webeye.browser_artifacts import VideoArtifact++ return dr.DisplayRecorder(+ display=":99",+ owner_id="wr_x",+ process=proc,+ lock_fd=-1,+ video_artifact=VideoArtifact(video_path=str(video_path)),+ )+++async def test_stop_graceful_remuxes_finalized_recording_in_place(tmp_path, monkeypatch) -> None:+ video_path = tmp_path / "rec.mp4"+ video_path.write_bytes(b"FRAGMENTED-ORIGINAL")++ calls: list[str] = []++ async def _fake_remux(src: str) -> str:+ calls.append(src)+ out = tmp_path / "faststart.mp4"+ out.write_bytes(b"FASTSTART-REMUXED")+ return str(out)++ monkeypatch.setattr(dr, "remux_mp4_faststart", _fake_remux, raising=False)++ rec = _recorder_with_path(_FakeProc(exits_on="SIGINT"), video_path)+ assert await rec.stop() is True+ # Remuxed exactly once, on the finalized recording, applied in place before upload.+ assert calls == [str(video_path)]+ assert video_path.read_bytes() == b"FASTSTART-REMUXED"+++async def test_stop_nongraceful_does_not_remux(tmp_path, monkeypatch) -> None:+ video_path = tmp_path / "rec.mp4"+ video_path.write_bytes(b"FRAGMENTED-PARTIAL")++ calls: list[str] = []++ async def _fake_remux(src: str) -> str:+ calls.append(src)+ return src++ monkeypatch.setattr(dr, "remux_mp4_faststart", _fake_remux, raising=False)++ # Nonzero finalize (failed/forced) is crash-salvage: the fragmented partial must be preserved.+ rec = _recorder_with_path(_FakeProc(exits_on="SIGINT", exit_code=1), video_path)+ assert await rec.stop() is False+ assert calls == []+ assert video_path.read_bytes() == b"FRAGMENTED-PARTIAL"+++async def test_stop_graceful_remux_failure_keeps_original(tmp_path, monkeypatch) -> None:+ video_path = tmp_path / "rec.mp4"+ video_path.write_bytes(b"FRAGMENTED-ORIGINAL")++ async def _fake_remux_none(src: str) -> None:+ return None++ monkeypatch.setattr(dr, "remux_mp4_faststart", _fake_remux_none, raising=False)++ rec = _recorder_with_path(_FakeProc(exits_on="SIGINT"), video_path)+ # Fail-open: a remux that yields nothing must not fail cleanup or lose the recording.+ assert await rec.stop() is True+ assert video_path.read_bytes() == b"FRAGMENTED-ORIGINAL"+++async def test_stop_graceful_keeps_original_when_swap_fails(tmp_path, monkeypatch) -> None:+ video_path = tmp_path / "rec.mp4"+ video_path.write_bytes(b"FRAGMENTED-ORIGINAL")+ tmp_out = tmp_path / "faststart.mp4"++ async def _fake_remux(src: str) -> str:+ tmp_out.write_bytes(b"FASTSTART-REMUXED")+ return str(tmp_out)++ def _swap_boom(src: str, dst: str) -> None:+ raise OSError("atomic swap failed")++ monkeypatch.setattr(dr, "remux_mp4_faststart", _fake_remux, raising=False)+ monkeypatch.setattr(dr.os, "replace", _swap_boom)++ rec = _recorder_with_path(_FakeProc(exits_on="SIGINT"), video_path)+ # Swap failure must not fail cleanup; the original recording stays byte-identical and the temp is cleaned.+ assert await rec.stop() is True+ assert video_path.read_bytes() == b"FRAGMENTED-ORIGINAL"+ assert not tmp_out.exists()+++async def test_stop_retries_faststart_after_cancellation(tmp_path, monkeypatch) -> None:+ video_path = tmp_path / "rec.mp4"+ video_path.write_bytes(b"FRAGMENTED-ORIGINAL")+ tmp_out = tmp_path / "faststart.mp4"+ calls = {"n": 0}++ async def _remux(src: str) -> str:+ calls["n"] += 1+ if calls["n"] == 1:+ raise asyncio.CancelledError() # cancelled mid-finalize+ tmp_out.write_bytes(b"FASTSTART-REMUXED")+ return str(tmp_out)++ monkeypatch.setattr(dr, "remux_mp4_faststart", _remux, raising=False)++ proc = _FakeProc(exits_on="SIGINT")+ rec = _recorder_with_path(proc, video_path)+ # First finalize: the recorder stops gracefully but the faststart remux is cancelled and propagates.+ with pytest.raises(asyncio.CancelledError):+ await rec.finalize_keeping_reservation()+ assert rec.is_stopped # recorder stop latched exactly once+ assert video_path.read_bytes() == b"FRAGMENTED-ORIGINAL" # not remuxed yet++ # Cleanup retry attempts the remux again (without re-escalating the already-stopped recorder).+ assert await rec.stop() is True+ assert calls["n"] == 2+ assert video_path.read_bytes() == b"FASTSTART-REMUXED"+ assert proc.signals.count(signal.SIGINT) == 1 # exactly-once stop: no second escalation+++async def test_no_remux_before_terminal_stop(tmp_path, monkeypatch) -> None:+ calls: list[str] = []++ async def _fake_remux(src: str) -> str:+ calls.append(src)+ return src++ monkeypatch.setattr(dr, "remux_mp4_faststart", _fake_remux, raising=False)++ rec = _recorder_with_path(_FakeProc(exits_on="SIGINT"), tmp_path / "rec.mp4")+ assert rec.arm_capture() is True+ # While recording (armed, not yet stopped) the fragmented MP4 is never remuxed.+ assert calls == []+++async def test_stop_graceful_real_ffmpeg_defragments_finalized_recording(tmp_path) -> None:+ import shutil as _shutil+ import struct+ import subprocess++ if _shutil.which("ffmpeg") is None:+ pytest.skip("ffmpeg not installed")++ video_path = tmp_path / "rec.mp4"+ subprocess.check_call(+ [+ "ffmpeg",+ "-y",+ "-hide_banner",+ "-loglevel",+ "error",+ "-f",+ "lavfi",+ "-i",+ "color=black:size=160x90:rate=15:duration=1",+ "-c:v",+ "libx264",+ "-pix_fmt",+ "yuv420p",+ "-movflags",+ "+frag_keyframe+empty_moov+default_base_moof",+ "-f",+ "mp4",+ str(video_path),+ ]+ )+ assert b"moof" in video_path.read_bytes() # precondition: fragmented while recording++ rec = _recorder_with_path(_FakeProc(exits_on="SIGINT"), video_path)+ assert await rec.stop() is True++ out = video_path.read_bytes()+ # Finalized terminal recording is de-fragmented and carries a real (non-zero) duration,+ # so a native <video> can read the length and seek without a full-file scan.+ assert b"moof" not in out+ i = out.find(b"mvhd")+ assert i >= 0+ body = out[i + 4 :]+ if body[0] == 1:+ duration = struct.unpack(">Q", body[4 + 8 + 8 + 4 : 4 + 8 + 8 + 4 + 8])[0]+ else:+ duration = struct.unpack(">I", body[4 + 4 + 4 + 4 : 4 + 4 + 4 + 4 + 4])[0]+ assert duration > 0++@pytest.mark.asyncioasync def test_stop_owner_sweep_finishes_then_reraises_cancellation(monkeypatch) -> None:# Finish-then-re-raise (mirrors stop()/_reap/_reclaim): a per-owner release that COMPLETES then raisesdiff --git a/tests/unit/test_video_utils.py b/tests/unit/test_video_utils.pyindex 7a3e13ff3..c79c8a080 100644--- a/tests/unit/test_video_utils.py+++ b/tests/unit/test_video_utils.py@@ -16,9 +16,22 @@ from skyvern.webeye.video_utils import (plan_run_segment,prepare_recording_for_upload,probe_media_duration_seconds,+ remux_mp4_faststart,)+def _mvhd_duration(data: bytes) -> int | None:+ """Read the movie duration from the first ``mvhd`` box (0 for an empty_moov init)."""+ i = data.find(b"mvhd")+ if i < 0:+ return None+ body = data[i + 4 :]+ version = body[0]+ if version == 1:+ return struct.unpack(">Q", body[4 + 8 + 8 + 4 : 4 + 8 + 8 + 4 + 8])[0]+ return struct.unpack(">I", body[4 + 4 + 4 + 4 : 4 + 4 + 4 + 4 + 4])[0]++def _write_unfinalized_webm(path: str) -> bytes:"""Write a WebM whose Segment has the "unknown size" VINT and no Duration/Cues.@@ -320,6 +333,88 @@ async def test_finalize_webm_end_to_end_sets_duration(tmp_path) -> None:assert b"\x44\x89" in output[:4096]+async def test_remux_mp4_faststart_defragments_and_sets_duration(tmp_path) -> None:+ import shutil+ import subprocess++ if shutil.which("ffmpeg") is None:+ pytest.skip("ffmpeg not installed")++ frag = str(tmp_path / "frag.mp4")+ subprocess.check_call(+ [+ "ffmpeg",+ "-y",+ "-hide_banner",+ "-loglevel",+ "error",+ "-f",+ "lavfi",+ "-i",+ "color=black:size=160x90:rate=15:duration=1",+ "-c:v",+ "libx264",+ "-pix_fmt",+ "yuv420p",+ "-movflags",+ "+frag_keyframe+empty_moov+default_base_moof",+ "-f",+ "mp4",+ frag,+ ]+ )+ frag_bytes = open(frag, "rb").read()+ # Precondition: input is a fragmented MP4 whose init moov carries no duration.+ assert b"moof" in frag_bytes+ assert _mvhd_duration(frag_bytes) == 0++ out_path = await remux_mp4_faststart(frag)+ assert out_path is not None+ # Output is created beside the source (same mount) so the caller can swap it in atomically.+ assert os.path.dirname(out_path) == os.path.dirname(frag)+ try:+ out_bytes = open(out_path, "rb").read()+ finally:+ os.unlink(out_path)++ # Postcondition: de-fragmented (no movie-fragment boxes) with a real duration,+ # so a native <video> can read the length and seek without a full-file scan.+ assert b"moof" not in out_bytes+ assert (_mvhd_duration(out_bytes) or 0) > 0+ # Faststart layout specifically: the moov must sit ahead of the mdat, not just be de-fragmented+ # (de-fragmentation alone already drops moof and sets duration even without +faststart).+ moov_off = out_bytes.find(b"moov")+ mdat_off = out_bytes.find(b"mdat")+ assert moov_off != -1 and mdat_off != -1 and moov_off < mdat_off+++async def test_remux_mp4_faststart_writes_output_beside_source(tmp_path, monkeypatch) -> None:+ # Deterministic (no ffmpeg): the helper must place its temp output on the source's own+ # directory/mount so the caller's swap is an atomic same-filesystem os.replace.+ src = tmp_path / "sub" / "rec.mp4"+ src.parent.mkdir(parents=True)+ src.write_bytes(b"x")++ captured: dict[str, object] = {}++ async def _fake_run(src_path, *, suffix, output_args, timeout_seconds, operation, input_args=None, output_dir=None):+ captured["output_dir"] = output_dir+ captured["output_args"] = output_args+ out = tmp_path / "sub" / "out.mp4"+ out.write_bytes(b"y")+ return str(out)++ monkeypatch.setattr(video_utils.shutil, "which", lambda _binary: "/usr/bin/ffmpeg")+ monkeypatch.setattr(video_utils, "_run_ffmpeg_to_temp", _fake_run)++ out = await remux_mp4_faststart(str(src))+ assert out is not None+ assert captured["output_dir"] == str(src.parent)+ assert captured["output_args"] == ["-c", "copy", "-movflags", "+faststart"]++def test_plan_run_segment_clamps_leading_run_in_long_session() -> None:# The production incident: a 29-min run is the first slice of a ~3h session recording.video_start = datetime(2026, 6, 4, 15, 59, 0, tzinfo=UTC)