Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
[codex] Compress browser session recordings (#6419)
Suchintan7a6f1c0685a4
diff --git a/skyvern/config.py b/skyvern/config.pyindex 9615ad40f..d0275a3b3 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -91,6 +91,10 @@ class Settings(BaseSettings):CHROME_EXECUTABLE_PATH: str | None = NoneMAX_SCRAPING_RETRIES: int = 0VIDEO_PATH: str | None = "./video"+ VIDEO_COMPRESSION_ENABLED: bool = True+ VIDEO_COMPRESSION_CRF: int = 28+ VIDEO_COMPRESSION_PRESET: str = "veryfast"+ VIDEO_COMPRESSION_TIMEOUT_SECONDS: float = 300.0HAR_PATH: str | None = "./har"LOG_PATH: str = "./log"TEMP_PATH: str = "./temp"diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.pyindex 876ef61f9..b3dce571c 100644--- a/skyvern/forge/sdk/artifact/storage/s3.py+++ b/skyvern/forge/sdk/artifact/storage/s3.py@@ -35,6 +35,7 @@ from skyvern.forge.sdk.schemas.ai_suggestions import AISuggestionfrom skyvern.forge.sdk.schemas.files import FileInfofrom skyvern.forge.sdk.schemas.task_v2 import TaskV2, Thoughtfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock+from skyvern.webeye.video_utils import prepare_recording_for_uploadLOG = structlog.get_logger()@@ -50,6 +51,12 @@ def _safe_get_file_size(path: str) -> int | None:return None+def _replace_file_extension(path: str, extension: str) -> str:+ normalized_extension = extension.lstrip(".")+ stem, _ = os.path.splitext(path)+ return f"{stem}.{normalized_extension}" if normalized_extension else path++class S3Storage(BaseStorage):_PATH_VERSION = "v1"# Cap concurrent head_object fan-out in the legacy listing fallback.@@ -869,6 +876,31 @@ class S3Storage(BaseStorage):"""Sync a file from local browser session to S3."""uri = self._build_browser_session_uri(organization_id, browser_session_id, artifact_type, remote_path, date)sc = await self._get_storage_class_for_org(organization_id, self.bucket)++ if artifact_type == "videos":+ # Compress finalized Playwright recordings before upload. The raw+ # local file remains the source of truth if ffmpeg fails; the S3+ # object and artifact metadata reflect the prepared upload file.+ async with prepare_recording_for_upload(local_file_path) as prepared_upload:+ upload_file_path = prepared_upload.path+ upload_remote_path = _replace_file_extension(remote_path, prepared_upload.file_extension)+ uri = self._build_browser_session_uri(+ organization_id, browser_session_id, artifact_type, upload_remote_path, date+ )+ await self.async_client.upload_file_from_path(uri, upload_file_path, storage_class=sc)+ # Register the uploaded recording for signed artifact serving.+ checksum = calculate_sha256_for_file(upload_file_path)+ file_size = _safe_get_file_size(upload_file_path)+ await app.ARTIFACT_MANAGER.create_browser_session_recording_artifact(+ organization_id=organization_id,+ browser_session_id=browser_session_id,+ uri=uri,+ filename=os.path.basename(upload_remote_path),+ checksum=checksum,+ file_size=file_size,+ )+ return uri+await self.async_client.upload_file_from_path(uri, local_file_path, storage_class=sc)if artifact_type == "downloads":@@ -887,45 +919,16 @@ class S3Storage(BaseStorage):# overwrite) and ``create_browser_session_download_artifact``# (idempotent on ``(session, uri)``) are safe to retry.is_partial = remote_path.endswith(BROWSER_DOWNLOADING_SUFFIX)- checksum = None if is_partial else calculate_sha256_for_file(local_file_path)- file_size = None if is_partial else _safe_get_file_size(local_file_path)+ download_checksum = None if is_partial else calculate_sha256_for_file(local_file_path)+ download_file_size = None if is_partial else _safe_get_file_size(local_file_path)await app.ARTIFACT_MANAGER.create_browser_session_download_artifact(organization_id=organization_id,browser_session_id=browser_session_id,uri=uri,filename=os.path.basename(remote_path),- checksum=checksum,- file_size=file_size,- )- elif artifact_type == "videos":- # Register a RECORDING artifact row so- # ``GET /v1/browser_sessions/{id}`` serves the recording via a- # short signed ``/v1/artifacts/{id}/content`` URL instead of a- # raw S3 presigned URL. Recordings are uploaded once at session- # close (Playwright finalizes the file when the browser context- # closes — there's no partial / mid-write state to track).- #- # Artifact-row creation is best-effort here. The only caller- # (``DefaultPersistentSessionsManager.close_session``) wraps the- # whole final-sync in ``except Exception: LOG.exception(...)``- # without retry, so propagating doesn't recover from a missed- # write the way the watcher's retry does for downloads. The- # safety net is the gated legacy listing fallback in- # ``get_shared_recordings_in_browser_session``: when the session- # has no RECORDING rows we fall through to the S3 LIST path, so- # a row-less recording still surfaces via the legacy presigned- # URL until a subsequent close writes the row.- checksum = calculate_sha256_for_file(local_file_path)- file_size = _safe_get_file_size(local_file_path)- await app.ARTIFACT_MANAGER.create_browser_session_recording_artifact(- organization_id=organization_id,- browser_session_id=browser_session_id,- uri=uri,- filename=os.path.basename(remote_path),- checksum=checksum,- file_size=file_size,+ checksum=download_checksum,+ file_size=download_file_size,)-return uriasync def delete_browser_session_file(diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 74a831d8a..143a5797a 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -2057,6 +2057,10 @@ _ARTIFACT_CONTENT_TYPES: dict[ArtifactType, str] = {ArtifactType.DOWNLOAD: "application/octet-stream",}_ARTIFACT_CONTENT_TYPE_DEFAULT = "application/json"+_VIDEO_CONTENT_TYPES_BY_EXTENSION = {+ ".mp4": "video/mp4",+ ".webm": "video/webm",+}def _sanitize_header_filename(name: str) -> str:@@ -2133,9 +2137,16 @@ def _artifact_response_config(artifact: Artifact) -> tuple[str, str]:so browsers never render user-supplied content inline (SKY-8862). All othertypes keep the historical ``inline`` behaviour."""- media_type = _ARTIFACT_CONTENT_TYPES.get(artifact.artifact_type, _ARTIFACT_CONTENT_TYPE_DEFAULT)+ raw_name = _artifact_filename_from_uri(artifact.uri)+ if artifact.artifact_type == ArtifactType.RECORDING:+ _, dot, extension = raw_name.lower().rpartition(".")+ media_type = _VIDEO_CONTENT_TYPES_BY_EXTENSION.get(+ f"{dot}{extension}" if dot else "",+ _ARTIFACT_CONTENT_TYPES.get(artifact.artifact_type, _ARTIFACT_CONTENT_TYPE_DEFAULT),+ )+ else:+ media_type = _ARTIFACT_CONTENT_TYPES.get(artifact.artifact_type, _ARTIFACT_CONTENT_TYPE_DEFAULT)if artifact.artifact_type == ArtifactType.DOWNLOAD:- raw_name = _artifact_filename_from_uri(artifact.uri)return media_type, _build_attachment_disposition(raw_name)return media_type, "inline"diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.pyindex 1bcbf974c..42cde0ce6 100644--- a/skyvern/webeye/browser_factory.py+++ b/skyvern/webeye/browser_factory.py@@ -360,6 +360,10 @@ class BrowserContextFactory:],"record_har_path": har_dir,"record_video_dir": video_dir,+ "record_video_size": {+ "width": settings.BROWSER_WIDTH,+ "height": settings.BROWSER_HEIGHT,+ },"viewport": {"width": settings.BROWSER_WIDTH,"height": settings.BROWSER_HEIGHT,@@ -925,6 +929,7 @@ async def _connect_to_cdp_browser()browser_context = await browser.new_context(record_video_dir=browser_args["record_video_dir"],+ record_video_size=browser_args["record_video_size"],viewport=browser_args["viewport"],extra_http_headers=browser_args["extra_http_headers"],)diff --git a/skyvern/webeye/default_persistent_sessions_manager.py b/skyvern/webeye/default_persistent_sessions_manager.pyindex 33b71075a..e09c3722f 100644--- a/skyvern/webeye/default_persistent_sessions_manager.py+++ b/skyvern/webeye/default_persistent_sessions_manager.py@@ -482,6 +482,22 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):organization_id=organization_id,)+ try:+ await browser_session.browser_state.close()+ except TargetClosedError:+ LOG.info(+ "Browser context already closed",+ organization_id=organization_id,+ session_id=browser_session_id,+ )+ except Exception:+ LOG.warning(+ "Error while closing browser session",+ organization_id=organization_id,+ session_id=browser_session_id,+ exc_info=True,+ )+if browser_artifacts and browser_artifacts.video_artifacts:for video_artifact in browser_artifacts.video_artifacts:if video_artifact.video_path:@@ -508,22 +524,6 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):self._browser_sessions.pop(browser_session_id, None)if browser_session.cdp_port is not None:_release_cdp_port(browser_session.cdp_port)-- try:- await browser_session.browser_state.close()- except TargetClosedError:- LOG.info(- "Browser context already closed",- organization_id=organization_id,- session_id=browser_session_id,- )- except Exception:- LOG.warning(- "Error while closing browser session",- organization_id=organization_id,- session_id=browser_session_id,- exc_info=True,- )else:LOG.info("Browser session not found in memory, marking as deleted in database",diff --git a/skyvern/webeye/video_utils.py b/skyvern/webeye/video_utils.pyindex ac6be6ec8..ed6a89106 100644--- a/skyvern/webeye/video_utils.py+++ b/skyvern/webeye/video_utils.py@@ -4,83 +4,232 @@ import asyncioimport osimport shutilimport tempfile+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from dataclasses import dataclassimport structlog+from skyvern.config import settings+LOG = structlog.get_logger()FFMPEG_BINARY = "ffmpeg"FFMPEG_REMUX_TIMEOUT_SECONDS = 30-async def finalize_webm(src_path: str) -> bytes:- """Return the bytes of a WebM recording with a valid end timestamp.+@dataclass(frozen=True)+class PreparedRecordingUpload:+ path: str+ file_extension: str- Browser recordings can end up with an unfinalized Matroska container when- ``browser_context.close()`` is killed mid-shutdown (close timeout, OOM,- pod eviction). The file is left with an "unknown size" Segment, no- ``Duration`` element, and no ``Cues`` index — so players show no end- timestamp and can't seek. Remuxing via ffmpeg stream-copy rewrites the- container with a backfilled Segment size, a Duration element, and Cues- at the front for HTTP streaming. VP8 clusters are copied unmodified.- Falls back to the raw bytes if ffmpeg is unavailable, times out, or- errors so recording upload is never regressed relative to today.- """- if not os.path.exists(src_path):- raise FileNotFoundError(src_path)+def _read_file(src_path: str) -> bytes:+ with open(src_path, "rb") as f:+ return f.read()+++async def _kill_and_wait_for_process(proc: asyncio.subprocess.Process) -> None:+ if proc.returncode is None:+ try:+ proc.kill()+ except ProcessLookupError:+ pass+ await proc.wait()- if shutil.which(FFMPEG_BINARY) is None:- LOG.warning("ffmpeg binary not found on PATH, returning raw webm bytes", src=src_path)- with open(src_path, "rb") as f:- return f.read()- with tempfile.NamedTemporaryFile(suffix=".webm", delete=False) as dst_tmp:+async def _run_ffmpeg_to_temp(+ src_path: str,+ *,+ suffix: str,+ output_args: list[str],+ timeout_seconds: float,+ operation: str,+) -> str | None:+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as dst_tmp:dst_path = dst_tmp.name+ keep_output = Falsetry:- proc = await asyncio.create_subprocess_exec(- FFMPEG_BINARY,- "-hide_banner",- "-loglevel",- "error",- "-y",- "-i",- src_path,- "-c",- "copy",- "-cues_to_front",- "1",- "-reserve_index_space",- "200k",- dst_path,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )try:- _, stderr = await asyncio.wait_for(proc.communicate(), timeout=FFMPEG_REMUX_TIMEOUT_SECONDS)+ proc = await asyncio.create_subprocess_exec(+ FFMPEG_BINARY,+ "-hide_banner",+ "-loglevel",+ "error",+ "-y",+ "-i",+ src_path,+ *output_args,+ dst_path,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ except Exception:+ LOG.warning("ffmpeg subprocess failed to start", operation=operation, src=src_path, exc_info=True)+ return None++ try:+ _, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout_seconds)+ except asyncio.CancelledError:+ await _kill_and_wait_for_process(proc)+ LOG.warning("ffmpeg subprocess cancelled", operation=operation, src=src_path)+ raiseexcept asyncio.TimeoutError:- proc.kill()- await proc.wait()- LOG.warning("ffmpeg remux timed out, returning raw webm bytes", src=src_path)- with open(src_path, "rb") as f:- return f.read()+ await _kill_and_wait_for_process(proc)+ LOG.warning(+ "ffmpeg subprocess timed out", operation=operation, src=src_path, timeout_seconds=timeout_seconds+ )+ return Noneif proc.returncode != 0 or not os.path.exists(dst_path) or os.path.getsize(dst_path) == 0:LOG.warning(- "ffmpeg remux failed, returning raw webm bytes",+ "ffmpeg subprocess failed",+ operation=operation,src=src_path,returncode=proc.returncode,stderr=stderr.decode(errors="replace")[:500] if stderr else "",)- with open(src_path, "rb") as f:- return f.read()+ return None- with open(dst_path, "rb") as f:- return f.read()+ keep_output = True+ return dst_pathfinally:- if os.path.exists(dst_path):+ if not keep_output and os.path.exists(dst_path):try:os.unlink(dst_path)except OSError:LOG.debug("failed to cleanup ffmpeg temp output", path=dst_path, exc_info=True)+++async def _compress_recording_to_mp4(src_path: str) -> str | None:+ output_args = [+ "-map",+ "0:v:0",+ "-an",+ "-c:v",+ "libx264",+ "-preset",+ settings.VIDEO_COMPRESSION_PRESET,+ "-crf",+ str(settings.VIDEO_COMPRESSION_CRF),+ "-pix_fmt",+ "yuv420p",+ "-movflags",+ "+faststart",+ ]+ dst_path = await _run_ffmpeg_to_temp(+ src_path,+ suffix=".mp4",+ output_args=output_args,+ timeout_seconds=settings.VIDEO_COMPRESSION_TIMEOUT_SECONDS,+ operation="ffmpeg recording mp4 compression",+ )+ if dst_path is None:+ return None++ try:+ src_size = os.path.getsize(src_path)+ dst_size = os.path.getsize(dst_path)+ LOG.info(+ "Compressed recording to mp4",+ src=src_path,+ original_size_bytes=src_size,+ compressed_size_bytes=dst_size,+ compression_ratio=round(dst_size / src_size, 4) if src_size > 0 else None,+ )+ except OSError:+ LOG.debug("failed to calculate recording compression ratio", src=src_path, dst=dst_path, exc_info=True)+ return dst_path+++async def _remux_webm(src_path: str) -> str | None:+ output_args = [+ "-c",+ "copy",+ "-cues_to_front",+ "1",+ "-reserve_index_space",+ "200k",+ ]+ return await _run_ffmpeg_to_temp(+ src_path,+ suffix=".webm",+ output_args=output_args,+ timeout_seconds=FFMPEG_REMUX_TIMEOUT_SECONDS,+ operation="ffmpeg webm remux",+ )+++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)+ return None++ if settings.VIDEO_COMPRESSION_ENABLED:+ compressed_path = await _compress_recording_to_mp4(src_path)+ if compressed_path is not None:+ return PreparedRecordingUpload(path=compressed_path, file_extension="mp4")++ LOG.warning("ffmpeg mp4 compression failed, falling back to stream-copy webm remux", src=src_path)++ remuxed_path = await _remux_webm(src_path)+ if remuxed_path is None:+ LOG.warning("ffmpeg webm remux failed, returning raw webm", src=src_path)+ return None+ return PreparedRecordingUpload(path=remuxed_path, file_extension="webm")+++@asynccontextmanager+async def prepare_recording_for_upload(src_path: str) -> AsyncIterator[PreparedRecordingUpload]:+ """Yield the best available recording path for upload."""+ if not os.path.exists(src_path):+ raise FileNotFoundError(src_path)++ prepared = await _prepare_recording_upload(src_path)+ source_extension = os.path.splitext(src_path)[1].lstrip(".").lower() or "webm"+ upload = prepared or PreparedRecordingUpload(path=src_path, file_extension=source_extension)+ try:+ yield upload+ finally:+ if prepared and os.path.exists(prepared.path):+ try:+ os.unlink(prepared.path)+ except OSError:+ LOG.debug("failed to cleanup prepared recording temp output", path=prepared.path, exc_info=True)+++@asynccontextmanager+async def prepare_webm_for_upload(src_path: str) -> AsyncIterator[str]:+ """Yield a finalized WebM path for compatibility with existing callers."""+ if not os.path.exists(src_path):+ raise FileNotFoundError(src_path)++ remuxed_path = None+ if shutil.which(FFMPEG_BINARY) is not None:+ remuxed_path = await _remux_webm(src_path)+ try:+ yield remuxed_path or src_path+ finally:+ if remuxed_path and os.path.exists(remuxed_path):+ try:+ os.unlink(remuxed_path)+ except OSError:+ LOG.debug("failed to cleanup prepared webm temp output", path=remuxed_path, exc_info=True)+++async def finalize_webm(src_path: str) -> bytes:+ """Return finalized, upload-ready WebM recording bytes.++ Browser recordings can end up with an unfinalized Matroska container when+ ``browser_context.close()`` is killed mid-shutdown (close timeout, OOM,+ pod eviction). The file is left with an "unknown size" Segment, no+ ``Duration`` element, and no ``Cues`` index — so players show no end+ timestamp and can't seek.++ This path intentionally stays WebM because some artifact rows are allocated+ before the final bytes are available. Browser-session S3 uploads use+ ``prepare_recording_for_upload`` and can switch to MP4 dynamically.+ """+ async with prepare_webm_for_upload(src_path) as upload_path:+ return await asyncio.to_thread(_read_file, upload_path)diff --git a/tests/unit/test_browser_session_recording_artifacts.py b/tests/unit/test_browser_session_recording_artifacts.pyindex 844591ee2..712d37f49 100644--- a/tests/unit/test_browser_session_recording_artifacts.py+++ b/tests/unit/test_browser_session_recording_artifacts.py@@ -12,6 +12,7 @@ Mirrors the SKY-8861 download artifact pipeline infrom __future__ import annotations+from contextlib import asynccontextmanagerfrom unittest.mock import AsyncMock, MagicMock, patchfrom urllib.parse import urlparse@@ -20,6 +21,7 @@ import pytestfrom skyvern.forge.sdk.artifact.manager import ArtifactManagerfrom skyvern.forge.sdk.artifact.models import Artifact, ArtifactTypefrom skyvern.forge.sdk.artifact.storage.s3 import S3Storage+from skyvern.webeye.video_utils import PreparedRecordingUpload_DUMMY_KEYRING_JSON = '{"current_kid": "k1", "keys": {"k1": {"secret": "0000000000000000000000000000000000000000000000000000000000000000"}}}'@@ -150,12 +152,20 @@ async def test_sync_browser_session_file_registers_recording_artifact(tmp_path):storage.async_client.upload_file_from_path = AsyncMock()recording_file = tmp_path / "recording.webm"recording_file.write_bytes(b"fake-video")+ compressed_file = tmp_path / "recording.compressed.mp4"+ compressed_file.write_bytes(b"compressed-video")mock_create = AsyncMock(return_value="a_new")mock_artifact_manager = MagicMock()mock_artifact_manager.create_browser_session_recording_artifact = mock_create+ @asynccontextmanager+ async def fake_prepare_recording_for_upload(path: str):+ assert path == str(recording_file)+ yield PreparedRecordingUpload(path=str(compressed_file), file_extension="mp4")+with (+ patch("skyvern.forge.sdk.artifact.storage.s3.prepare_recording_for_upload", fake_prepare_recording_for_upload),patch.object(storage, "_get_storage_class_for_org", new=AsyncMock(return_value=MagicMock())),patch("skyvern.forge.sdk.artifact.storage.s3.calculate_sha256_for_file", return_value="sha-r"),patch("skyvern.forge.sdk.artifact.storage.s3.app") as app_module,@@ -170,18 +180,22 @@ async def test_sync_browser_session_file_registers_recording_artifact(tmp_path):date="2026-04-26",)+ storage.async_client.upload_file_from_path.assert_awaited_once()+ assert storage.async_client.upload_file_from_path.call_args.args[0].endswith("/recording.mp4")+ assert storage.async_client.upload_file_from_path.call_args.args[1] == str(compressed_file)mock_create.assert_awaited_once()_, kwargs = mock_create.call_argsassert kwargs["organization_id"] == "o_1"assert kwargs["browser_session_id"] == "pbs_1"- assert kwargs["filename"] == "recording.webm"+ assert kwargs["filename"] == "recording.mp4"assert kwargs["checksum"] == "sha-r"- assert kwargs["file_size"] == recording_file.stat().st_size+ assert kwargs["file_size"] == compressed_file.stat().st_sizeassert kwargs["uri"].startswith("s3://") and "/browser_sessions/pbs_1/videos/" in kwargs["uri"]+ assert kwargs["uri"].endswith("/recording.mp4")@pytest.mark.asyncio-async def test_sync_browser_session_file_recording_failure_propagates():+async def test_sync_browser_session_file_recording_failure_propagates(tmp_path):"""Contract: ``sync_browser_session_file(artifact_type="videos")``raises when the artifact-row insert fails. The exception propagates tothe caller; ``DefaultPersistentSessionsManager.close_session`` is@@ -195,12 +209,20 @@ async def test_sync_browser_session_file_recording_failure_propagates():storage = S3Storage()storage.async_client = MagicMock()storage.async_client.upload_file_from_path = AsyncMock()+ recording_file = tmp_path / "recording.webm"+ recording_file.write_bytes(b"fake-video")mock_create = AsyncMock(side_effect=RuntimeError("DB unreachable"))mock_artifact_manager = MagicMock()mock_artifact_manager.create_browser_session_recording_artifact = mock_create+ @asynccontextmanager+ async def fake_prepare_recording_for_upload(path: str):+ assert path == str(recording_file)+ yield PreparedRecordingUpload(path=str(recording_file), file_extension="webm")+with (+ patch("skyvern.forge.sdk.artifact.storage.s3.prepare_recording_for_upload", fake_prepare_recording_for_upload),patch.object(storage, "_get_storage_class_for_org", new=AsyncMock(return_value=MagicMock())),patch("skyvern.forge.sdk.artifact.storage.s3.calculate_sha256_for_file", return_value="sha-r"),patch("skyvern.forge.sdk.artifact.storage.s3.app") as app_module,@@ -211,7 +233,7 @@ async def test_sync_browser_session_file_recording_failure_propagates():organization_id="o_1",browser_session_id="pbs_1",artifact_type="videos",- local_file_path="/tmp/recording.webm",+ local_file_path=str(recording_file),remote_path="recording.webm",)diff --git a/tests/unit/test_proxy_url_custom.py b/tests/unit/test_proxy_url_custom.pyindex de5711472..9cf18b950 100644--- a/tests/unit/test_proxy_url_custom.py+++ b/tests/unit/test_proxy_url_custom.py@@ -33,6 +33,12 @@ def test_build_browser_args_invalid_custom_proxy_url_ignored() -> None:assert "proxy" not in args+def test_build_browser_args_sets_record_video_size_to_viewport() -> None:+ args = BrowserContextFactory.build_browser_args()++ assert args["record_video_size"] == args["viewport"]++def test_deserialize_proxy_location_custom_url_returns_dict() -> None:result = deserialize_proxy_location('{"url": "http://user:[email protected]:8080"}')assert result == {"url": "http://user:[email protected]:8080"}diff --git a/tests/unit/test_video_utils.py b/tests/unit/test_video_utils.pyindex de9fe45d3..6eb8bf92d 100644--- a/tests/unit/test_video_utils.py+++ b/tests/unit/test_video_utils.py@@ -1,13 +1,15 @@from __future__ import annotationsimport asyncio+import osimport structfrom unittest.mock import AsyncMock, patchimport pytest+from skyvern.config import settingsfrom skyvern.webeye import video_utils-from skyvern.webeye.video_utils import finalize_webm+from skyvern.webeye.video_utils import finalize_webm, prepare_recording_for_uploaddef _write_unfinalized_webm(path: str) -> bytes:@@ -71,7 +73,7 @@ async def test_finalize_webm_without_ffmpeg_returns_raw(tmp_path) -> None:@pytest.mark.asyncio-async def test_finalize_webm_invokes_ffmpeg_with_cues_at_front(tmp_path) -> None:+async def test_prepare_recording_for_upload_invokes_ffmpeg_with_h264_mp4_compression(tmp_path) -> None:src = str(tmp_path / "src.webm")_write_unfinalized_webm(src)@@ -91,19 +93,89 @@ async def test_finalize_webm_invokes_ffmpeg_with_cues_at_front(tmp_path) -> Nonewith patch.object(video_utils.shutil, "which", return_value="/usr/bin/ffmpeg"):with patch.object(video_utils.asyncio, "create_subprocess_exec", side_effect=fake_exec):- result = await finalize_webm(src)+ async with prepare_recording_for_upload(src) as prepared:+ with open(prepared.path, "rb") as f:+ result = f.read()+ extension = prepared.file_extensionassert result == b"REMUXED_CONTENT"- assert "-c" in captured_args and "copy" in captured_args- assert "-cues_to_front" in captured_args- # cues_to_front must be followed by "1"- assert captured_args[captured_args.index("-cues_to_front") + 1] == "1"- assert "-reserve_index_space" in captured_args+ assert extension == "mp4"+ assert "-c:v" in captured_args+ assert captured_args[captured_args.index("-c:v") + 1] == "libx264"+ assert "-preset" in captured_args+ assert captured_args[captured_args.index("-preset") + 1] == settings.VIDEO_COMPRESSION_PRESET+ assert "-crf" in captured_args+ assert captured_args[captured_args.index("-crf") + 1] == str(settings.VIDEO_COMPRESSION_CRF)+ assert "-pix_fmt" in captured_args+ assert captured_args[captured_args.index("-pix_fmt") + 1] == "yuv420p"+ assert "-an" in captured_args+ assert "-movflags" in captured_args+ assert captured_args[captured_args.index("-movflags") + 1] == "+faststart"assert captured_args[0] == video_utils.FFMPEG_BINARYassert captured_args[-2] != src # output path is the temp file, not input+ assert captured_args[-1].endswith(".mp4")assert src in captured_args+async def test_prepare_recording_for_upload_can_disable_compression_and_stream_copy_remux(tmp_path) -> None:+ src = str(tmp_path / "src.webm")+ _write_unfinalized_webm(src)++ captured_args: list[str] = []++ async def fake_exec(*args, **kwargs):+ captured_args.extend(args)+ output_path = args[-1]+ with open(output_path, "wb") as f:+ f.write(b"REMUXED_CONTENT")+ proc = AsyncMock()+ proc.returncode = 0+ proc.communicate = AsyncMock(return_value=(b"", b""))+ proc.wait = AsyncMock(return_value=0)+ return proc++ with patch.object(settings, "VIDEO_COMPRESSION_ENABLED", False):+ with patch.object(video_utils.shutil, "which", return_value="/usr/bin/ffmpeg"):+ with patch.object(video_utils.asyncio, "create_subprocess_exec", side_effect=fake_exec):+ async with prepare_recording_for_upload(src) as prepared:+ with open(prepared.path, "rb") as f:+ result = f.read()+ extension = prepared.file_extension++ assert result == b"REMUXED_CONTENT"+ assert extension == "webm"+ assert "-c" in captured_args and "copy" in captured_args+ assert "-c:v" not in captured_args+++async def test_prepare_recording_for_upload_yields_temp_path_and_cleans_up(tmp_path) -> None:+ src = str(tmp_path / "src.webm")+ _write_unfinalized_webm(src)++ async def fake_exec(*args, **kwargs):+ output_path = args[-1]+ with open(output_path, "wb") as f:+ f.write(b"COMPRESSED_CONTENT")+ proc = AsyncMock()+ proc.returncode = 0+ proc.communicate = AsyncMock(return_value=(b"", b""))+ proc.wait = AsyncMock(return_value=0)+ return proc++ with patch.object(video_utils.shutil, "which", return_value="/usr/bin/ffmpeg"):+ with patch.object(video_utils.asyncio, "create_subprocess_exec", side_effect=fake_exec):+ async with prepare_recording_for_upload(src) as prepared:+ temp_path = prepared.path+ assert prepared.path != src+ assert prepared.file_extension == "mp4"+ with open(prepared.path, "rb") as f:+ assert f.read() == b"COMPRESSED_CONTENT"++ assert not os.path.exists(temp_path)++@pytest.mark.asyncioasync def test_finalize_webm_falls_back_on_ffmpeg_error(tmp_path) -> None:src = str(tmp_path / "src.webm")@@ -123,6 +195,54 @@ async def test_finalize_webm_falls_back_on_ffmpeg_error(tmp_path) -> None:assert result == expected+async def test_finalize_webm_kills_ffmpeg_on_cancellation(tmp_path) -> None:+ src = str(tmp_path / "src.webm")+ _write_unfinalized_webm(src)++ killed = False+ waited = False+ output_paths: list[str] = []++ class FakeProcess:+ returncode = None++ async def communicate(self):+ return b"", b""++ def kill(self):+ nonlocal killed+ killed = True+ self.returncode = -9++ async def wait(self):+ nonlocal waited+ waited = True+ return self.returncode++ async def fake_exec(*args, **kwargs):+ output_path = args[-1]+ output_paths.append(output_path)+ with open(output_path, "wb") as f:+ f.write(b"PARTIAL_OUTPUT")+ return FakeProcess()++ async def immediate_cancel(coro, timeout):+ coro.close()+ raise asyncio.CancelledError()++ with patch.object(video_utils.shutil, "which", return_value="/usr/bin/ffmpeg"):+ with patch.object(video_utils.asyncio, "create_subprocess_exec", side_effect=fake_exec):+ with patch.object(video_utils.asyncio, "wait_for", side_effect=immediate_cancel):+ with pytest.raises(asyncio.CancelledError):+ await finalize_webm(src)++ assert killed+ assert waited+ assert output_paths+ assert not any(os.path.exists(output_path) for output_path in output_paths)++@pytest.mark.asyncioasync def test_finalize_webm_falls_back_on_timeout(tmp_path) -> None:src = str(tmp_path / "src.webm")@@ -176,5 +296,5 @@ async def test_finalize_webm_end_to_end_sets_duration(tmp_path) -> None:)output = await finalize_webm(src)- # Duration element tag is 0x4489 — must be present after remux.+ # Duration element tag is 0x4489 — must be present after finalization.assert b"\x44\x89" in output[:4096]