Skip to content

Automate browser based workflows with AI

Fix remote browser session recording target reuse (#6919)

LawyZheng6bcba9c4893f
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 150e45a5b..a5282e93f 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -4731,10 +4731,23 @@ class ForgeAgent:
)
LOG.debug("Uploading video artifacts", number_of_video_artifacts=len(video_artifacts))
for video_artifact in video_artifacts:
- await app.ARTIFACT_MANAGER.update_artifact_data(
- artifact_id=video_artifact.video_artifact_id,
- organization_id=task.organization_id,
- data=video_artifact.video_data,
+ if video_artifact.video_artifact_id:
+ await app.ARTIFACT_MANAGER.update_artifact_data(
+ artifact_id=video_artifact.video_artifact_id,
+ organization_id=task.organization_id,
+ data=video_artifact.video_data,
+ )
+ continue
+ # No pre-registered artifact row: a recording attached at browser teardown
+ # (remote-CDP path) needs a RECORDING artifact created from the on-disk file.
+ # Upload by path so the bytes stream straight from disk to storage.
+ video_path = video_artifact.video_path
+ if not video_path or not os.path.exists(video_path):
+ continue
+ video_artifact.video_artifact_id = await app.ARTIFACT_MANAGER.create_artifact(
+ step=last_step,
+ artifact_type=ArtifactType.RECORDING,
+ path=video_path,
)
_ctx = skyvern_context.current()
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 1f737522b..94012f490 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -6362,14 +6362,46 @@ class WorkflowService:
LOG.debug("Persisting video data", number_of_video_artifacts=len(video_artifacts))
# Flush here: code-block recordings key on the block/run id, which clean_up_workflow's task-id drain skips.
upload_keys: set[str] = set()
+ last_step: Step | None = None
+ last_step_resolved = False
for video_artifact in video_artifacts:
- upload_key = await app.ARTIFACT_MANAGER.update_artifact_data(
- artifact_id=video_artifact.video_artifact_id,
- organization_id=workflow_run.organization_id,
- data=video_artifact.video_data,
+ if video_artifact.video_artifact_id:
+ upload_key = await app.ARTIFACT_MANAGER.update_artifact_data(
+ artifact_id=video_artifact.video_artifact_id,
+ organization_id=workflow_run.organization_id,
+ data=video_artifact.video_data,
+ )
+ if upload_key:
+ upload_keys.add(upload_key)
+ continue
+
+ # No pre-registered artifact row: a recording attached at browser teardown
+ # (remote-CDP path) needs a RECORDING artifact created from the on-disk file.
+ # Upload by path so the bytes stream straight from disk to storage.
+ video_path = video_artifact.video_path
+ if not video_path or not os.path.exists(video_path):
+ continue
+ if not last_step_resolved:
+ last_step_resolved = True
+ tasks = await app.DATABASE.tasks.get_tasks_by_workflow_run_id(workflow_run.workflow_run_id)
+ if tasks:
+ last_step = await app.DATABASE.tasks.get_latest_step(
+ task_id=tasks[-1].task_id, organization_id=workflow_run.organization_id
+ )
+ if last_step is None:
+ LOG.warning(
+ "Cannot persist path-based recording: no latest step for workflow run",
+ workflow_run_id=workflow_run.workflow_run_id,
+ video_path=video_path,
+ )
+ continue
+ artifact_id = await app.ARTIFACT_MANAGER.create_artifact(
+ step=last_step,
+ artifact_type=ArtifactType.RECORDING,
+ path=video_path,
)
- if upload_key:
- upload_keys.add(upload_key)
+ video_artifact.video_artifact_id = artifact_id
+ upload_keys.add(last_step.task_id)
if upload_keys:
await app.ARTIFACT_MANAGER.wait_for_upload_aiotasks(list(upload_keys))
diff --git a/skyvern/webeye/browser_artifacts.py b/skyvern/webeye/browser_artifacts.py
index 05bfd95e8..25c32dcab 100644
--- a/skyvern/webeye/browser_artifacts.py
+++ b/skyvern/webeye/browser_artifacts.py
@@ -26,6 +26,8 @@ class BrowserArtifacts(BaseModel):
# publisher. Local Playwright contexts leave it False. Type must stay
# ``bool`` — the manager guards with ``is True`` identity, not truthiness.
needs_cdp_frame_publisher: bool = False
+ # Optional opaque identifier for a remote browser session.
+ remote_browser_session_id: str | None = None
_browser_console_log_lock: asyncio.Lock = PrivateAttr(default_factory=asyncio.Lock)
async def append_browser_console_log(self, msg: str) -> int:
diff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.py
index b3ef3cee3..d0c0ebe48 100644
--- a/skyvern/webeye/real_browser_manager.py
+++ b/skyvern/webeye/real_browser_manager.py
@@ -484,7 +484,12 @@ class RealBrowserManager(BrowserManager):
for i, video_artifact in enumerate(browser_state.browser_artifacts.video_artifacts):
path = video_artifact.video_path
if path and os.path.exists(path=path):
- if finalize:
+ # Only the local Playwright-launched recording path produces WebM
+ # that needs the remux fix-up. Other producers (e.g. fully formed
+ # MP4 downloaded from a remote source) are already container-valid
+ # and would be corrupted by ``finalize_webm`` — read those raw.
+ is_webm = path.lower().endswith(".webm")
+ if finalize and is_webm:
# Remux via ffmpeg so the WebM container has a valid Duration + Cues,
# even when browser_context.close() was killed mid-finalization.
browser_state.browser_artifacts.video_artifacts[i].video_data = await finalize_webm(path)
diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.py
index 96b145644..174c8a686 100644
--- a/skyvern/webeye/real_browser_state.py
+++ b/skyvern/webeye/real_browser_state.py
@@ -152,7 +152,15 @@ class RealBrowserState(BrowserState):
if await self.get_working_page() is None:
page: Page | None = None
use_existing_page = False
- if browser_address and len(self.browser_context.pages) > 0:
+ # Some remote browser sessions bind their capture/streaming to the
+ # CDP target that existed at session creation. Opening a new tab
+ # and then running _close_all_other_pages detaches that binding
+ # from the page the agent actually navigates. Reuse the existing
+ # page so the remote session stays aligned with the active target.
+ has_remote_browser_session = bool(
+ self.browser_artifacts and self.browser_artifacts.remote_browser_session_id
+ )
+ if (browser_address or has_remote_browser_session) and len(self.browser_context.pages) > 0:
pages = await self.list_valid_pages()
if pages:
page = pages[-1]
diff --git a/tests/unit/test_browser_artifacts_remote_browser_session_id.py b/tests/unit/test_browser_artifacts_remote_browser_session_id.py
new file mode 100644
index 000000000..fb7df3b69
--- /dev/null
+++ b/tests/unit/test_browser_artifacts_remote_browser_session_id.py
@@ -0,0 +1,21 @@
+"""``BrowserArtifacts.remote_browser_session_id`` is an opaque identifier for
+a remote browser session. The OSS package carries only the id; downstream
+creators populate it. This test pins the default (``None``) and the contract
+that consumers can read/write it through normal pydantic semantics — nothing
+more.
+"""
+
+from __future__ import annotations
+
+from skyvern.webeye.browser_artifacts import BrowserArtifacts
+
+
+def test_remote_browser_session_id_defaults_to_none() -> None:
+ artifacts = BrowserArtifacts()
+ assert artifacts.remote_browser_session_id is None
+
+
+def test_remote_browser_session_id_round_trips() -> None:
+ artifacts = BrowserArtifacts()
+ artifacts.remote_browser_session_id = "opaque-session-handle"
+ assert artifacts.remote_browser_session_id == "opaque-session-handle"
diff --git a/tests/unit/test_cleanup_browser_video_path_fallback.py b/tests/unit/test_cleanup_browser_video_path_fallback.py
new file mode 100644
index 000000000..18af64d74
--- /dev/null
+++ b/tests/unit/test_cleanup_browser_video_path_fallback.py
@@ -0,0 +1,163 @@
+"""Path-fallback behavior for ``Agent.cleanup_browser_and_create_artifacts``.
+
+The standalone-task cleanup mirrors the workflow path: a recording attached during browser teardown
+arrives as ``VideoArtifact(video_path=..., video_artifact_id=None)``; ``update_artifact_data`` no-ops
+on a falsy id, so the MP4 must be promoted to a step-scoped RECORDING artifact via
+``create_artifact(path=...)`` before the task's task-id drain runs.
+
+OSS-synced: synthetic ids and example.* placeholders only.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from skyvern.forge.agent import ForgeAgent
+from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifact
+
+
+def _make_task(task_id: str = "tsk_1", organization_id: str = "o_1") -> MagicMock:
+ task = MagicMock()
+ task.task_id = task_id
+ task.organization_id = organization_id
+ task.webhook_callback_url = None
+ return task
+
+
+def _make_step(step_id: str = "stp_1", task_id: str = "tsk_1") -> MagicMock:
+ step = MagicMock()
+ step.step_id = step_id
+ step.task_id = task_id
+ return step
+
+
+def _browser_state() -> MagicMock:
+ state = MagicMock()
+ state.browser_artifacts = BrowserArtifacts()
+ state.browser_context = None
+ return state
+
+
+async def test_cleanup_creates_recording_from_path_when_id_is_none(tmp_path: Path) -> None:
+ mp4 = tmp_path / "session.mp4"
+ mp4.write_bytes(b"mp4-bytes")
+ video_artifacts = [VideoArtifact(video_path=str(mp4))]
+ assert video_artifacts[0].video_artifact_id is None
+
+ agent = ForgeAgent()
+ task = _make_task()
+ last_step = _make_step()
+ browser_state = _browser_state()
+
+ with patch("skyvern.forge.agent.app") as mock_app:
+ mock_app.BROWSER_MANAGER.cleanup_for_task = AsyncMock(return_value=browser_state)
+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)
+ mock_app.BROWSER_MANAGER.get_har_data = AsyncMock(return_value=b"")
+ mock_app.BROWSER_MANAGER.get_browser_console_log = AsyncMock(return_value=b"")
+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()
+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock(return_value="a_recording_path")
+
+ await agent.cleanup_browser_and_create_artifacts(
+ close_browser_on_completion=True,
+ last_step=last_step,
+ task=task,
+ )
+
+ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_not_awaited()
+ # Bytes streamed by path; do not load the whole video into memory.
+ create_call_args = [
+ c
+ for c in mock_app.ARTIFACT_MANAGER.create_artifact.await_args_list
+ if c.kwargs.get("artifact_type") == ArtifactType.RECORDING
+ ]
+ assert len(create_call_args) == 1
+ kwargs = create_call_args[0].kwargs
+ assert kwargs["step"] is last_step
+ assert kwargs["path"] == str(mp4)
+ assert kwargs.get("data") is None
+ # The new id is stored back so downstream lookups find the row.
+ assert video_artifacts[0].video_artifact_id == "a_recording_path"
+
+
+async def test_cleanup_path_fallback_skips_when_path_missing(tmp_path: Path) -> None:
+ absent = tmp_path / "missing.mp4"
+ video_artifacts = [VideoArtifact(video_path=str(absent))]
+
+ agent = ForgeAgent()
+ task = _make_task()
+ last_step = _make_step()
+ browser_state = _browser_state()
+
+ with patch("skyvern.forge.agent.app") as mock_app:
+ mock_app.BROWSER_MANAGER.cleanup_for_task = AsyncMock(return_value=browser_state)
+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)
+ mock_app.BROWSER_MANAGER.get_har_data = AsyncMock(return_value=b"")
+ mock_app.BROWSER_MANAGER.get_browser_console_log = AsyncMock(return_value=b"")
+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()
+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()
+
+ await agent.cleanup_browser_and_create_artifacts(
+ close_browser_on_completion=True,
+ last_step=last_step,
+ task=task,
+ )
+
+ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_not_awaited()
+ recording_calls = [
+ c
+ for c in mock_app.ARTIFACT_MANAGER.create_artifact.await_args_list
+ if c.kwargs.get("artifact_type") == ArtifactType.RECORDING
+ ]
+ assert recording_calls == []
+ assert video_artifacts[0].video_artifact_id is None
+
+
+async def test_cleanup_preserves_update_path_for_pre_registered_artifact(tmp_path: Path) -> None:
+ # A standard Playwright recording arrives pre-registered (``initialize_execution_state``); the
+ # existing data-update path stays in charge and the new path-upload helper stays idle.
+ video_artifacts = [
+ VideoArtifact(
+ video_path=str(tmp_path / "playwright.webm"),
+ video_artifact_id="a_existing",
+ video_data=b"video",
+ )
+ ]
+
+ agent = ForgeAgent()
+ task = _make_task()
+ last_step = _make_step()
+ browser_state = _browser_state()
+
+ with patch("skyvern.forge.agent.app") as mock_app:
+ mock_app.BROWSER_MANAGER.cleanup_for_task = AsyncMock(return_value=browser_state)
+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)
+ mock_app.BROWSER_MANAGER.get_har_data = AsyncMock(return_value=b"")
+ mock_app.BROWSER_MANAGER.get_browser_console_log = AsyncMock(return_value=b"")
+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()
+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()
+
+ await agent.cleanup_browser_and_create_artifacts(
+ close_browser_on_completion=True,
+ last_step=last_step,
+ task=task,
+ )
+
+ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(
+ artifact_id="a_existing",
+ organization_id="o_1",
+ data=b"video",
+ )
+ recording_calls = [
+ c
+ for c in mock_app.ARTIFACT_MANAGER.create_artifact.await_args_list
+ if c.kwargs.get("artifact_type") == ArtifactType.RECORDING
+ ]
+ assert recording_calls == []
+ assert video_artifacts[0].video_artifact_id == "a_existing"
diff --git a/tests/unit/test_code_block_recording_artifact.py b/tests/unit/test_code_block_recording_artifact.py
index f148ecb78..ade8437a6 100644
--- a/tests/unit/test_code_block_recording_artifact.py
+++ b/tests/unit/test_code_block_recording_artifact.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import asyncio
from datetime import datetime, timezone
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -399,3 +400,150 @@ class TestPersistVideoDataFlushesUploads:
await WorkflowService().persist_video_data(_browser_state([]), workflow, workflow_run)
wait_for_uploads.assert_not_awaited()
+
+
+class TestPersistVideoDataPathFallback:
+ """A recording attached during browser teardown lands as ``VideoArtifact(video_path=...)`` with no
+ ``video_artifact_id`` — the existing ``update_artifact_data`` call no-ops on a falsy id, so the MP4
+ must be promoted to a durable step-scoped RECORDING artifact via ``create_artifact(path=...)``."""
+
+ @pytest.mark.asyncio
+ async def test_creates_recording_from_path_when_id_is_none(self, tmp_path: Path) -> None:
+ mp4 = tmp_path / "session.mp4"
+ mp4.write_bytes(b"mp4-bytes")
+ video_artifacts = [VideoArtifact(video_path=str(mp4))]
+ assert video_artifacts[0].video_artifact_id is None
+
+ last_task = SimpleNamespace(task_id="tsk_1", organization_id="o_1")
+ last_step = SimpleNamespace(task_id="tsk_1", step_id="stp_1", organization_id="o_1")
+ get_video = AsyncMock(return_value=video_artifacts)
+ get_tasks = AsyncMock(return_value=[last_task])
+ get_latest_step = AsyncMock(return_value=last_step)
+ update_data = AsyncMock()
+ create_artifact = AsyncMock(return_value="a_recording_path")
+ wait_for_uploads = AsyncMock()
+ workflow = SimpleNamespace(workflow_id="w_1")
+ workflow_run = SimpleNamespace(workflow_run_id="wr_1", organization_id="o_1")
+
+ with (
+ patch(f"{_SERVICE_PATH}.BROWSER_MANAGER.get_video_artifacts", get_video),
+ patch(f"{_SERVICE_PATH}.DATABASE.tasks.get_tasks_by_workflow_run_id", get_tasks),
+ patch(f"{_SERVICE_PATH}.DATABASE.tasks.get_latest_step", get_latest_step),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.update_artifact_data", update_data),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.create_artifact", create_artifact),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.wait_for_upload_aiotasks", wait_for_uploads),
+ ):
+ await WorkflowService().persist_video_data(_browser_state(video_artifacts), workflow, workflow_run)
+
+ # The id-less artifact was promoted via path-upload, not data-upload.
+ update_data.assert_not_awaited()
+ create_artifact.assert_awaited_once()
+ kwargs = create_artifact.call_args.kwargs
+ assert kwargs["step"] is last_step
+ assert kwargs["artifact_type"] == ArtifactType.RECORDING
+ assert kwargs["path"] == str(mp4)
+ assert "data" not in kwargs or kwargs.get("data") is None
+ # The new id is stored back so downstream lookups find the row.
+ assert video_artifacts[0].video_artifact_id == "a_recording_path"
+ # The step-scoped upload aiotask must be drained by persist_video_data.
+ wait_for_uploads.assert_awaited_once_with(["tsk_1"])
+
+ @pytest.mark.asyncio
+ async def test_skips_when_video_path_missing_on_disk(self, tmp_path: Path) -> None:
+ # A path that no longer exists (e.g. cleanup raced the download teardown) must not crash
+ # and must not trigger a step lookup or an artifact insert.
+ absent = tmp_path / "missing.mp4"
+ video_artifacts = [VideoArtifact(video_path=str(absent))]
+
+ get_video = AsyncMock(return_value=video_artifacts)
+ get_tasks = AsyncMock()
+ get_latest_step = AsyncMock()
+ update_data = AsyncMock()
+ create_artifact = AsyncMock()
+ wait_for_uploads = AsyncMock()
+ workflow = SimpleNamespace(workflow_id="w_1")
+ workflow_run = SimpleNamespace(workflow_run_id="wr_1", organization_id="o_1")
+
+ with (
+ patch(f"{_SERVICE_PATH}.BROWSER_MANAGER.get_video_artifacts", get_video),
+ patch(f"{_SERVICE_PATH}.DATABASE.tasks.get_tasks_by_workflow_run_id", get_tasks),
+ patch(f"{_SERVICE_PATH}.DATABASE.tasks.get_latest_step", get_latest_step),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.update_artifact_data", update_data),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.create_artifact", create_artifact),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.wait_for_upload_aiotasks", wait_for_uploads),
+ ):
+ await WorkflowService().persist_video_data(_browser_state(video_artifacts), workflow, workflow_run)
+
+ get_tasks.assert_not_awaited()
+ get_latest_step.assert_not_awaited()
+ create_artifact.assert_not_awaited()
+ update_data.assert_not_awaited()
+ wait_for_uploads.assert_not_awaited()
+ assert video_artifacts[0].video_artifact_id is None
+
+ @pytest.mark.asyncio
+ async def test_path_fallback_noops_when_workflow_run_has_no_tasks(self, tmp_path: Path) -> None:
+ # A workflow with no tasks gives the helper nothing to attach a step-scoped artifact to;
+ # log and skip rather than creating an orphan or crashing.
+ mp4 = tmp_path / "session.mp4"
+ mp4.write_bytes(b"mp4-bytes")
+ video_artifacts = [VideoArtifact(video_path=str(mp4))]
+
+ get_video = AsyncMock(return_value=video_artifacts)
+ get_tasks = AsyncMock(return_value=[])
+ get_latest_step = AsyncMock()
+ update_data = AsyncMock(return_value=None)
+ create_artifact = AsyncMock()
+ wait_for_uploads = AsyncMock()
+ workflow = SimpleNamespace(workflow_id="w_1")
+ workflow_run = SimpleNamespace(workflow_run_id="wr_1", organization_id="o_1")
+
+ with (
+ patch(f"{_SERVICE_PATH}.BROWSER_MANAGER.get_video_artifacts", get_video),
+ patch(f"{_SERVICE_PATH}.DATABASE.tasks.get_tasks_by_workflow_run_id", get_tasks),
+ patch(f"{_SERVICE_PATH}.DATABASE.tasks.get_latest_step", get_latest_step),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.update_artifact_data", update_data),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.create_artifact", create_artifact),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.wait_for_upload_aiotasks", wait_for_uploads),
+ ):
+ await WorkflowService().persist_video_data(_browser_state(video_artifacts), workflow, workflow_run)
+
+ get_latest_step.assert_not_awaited()
+ create_artifact.assert_not_awaited()
+ wait_for_uploads.assert_not_awaited()
+ assert video_artifacts[0].video_artifact_id is None
+
+ @pytest.mark.asyncio
+ async def test_preserves_update_path_for_pre_registered_artifact(self, tmp_path: Path) -> None:
+ # A code-block recording arrives pre-registered (``_ensure_run_recording_artifact``); the
+ # existing data-update path stays in charge and the new path-upload helper stays idle.
+ video_artifacts = [
+ VideoArtifact(
+ video_path=str(tmp_path / "code-block.webm"),
+ video_artifact_id="a_existing",
+ video_data=b"video",
+ )
+ ]
+
+ get_video = AsyncMock(return_value=video_artifacts)
+ get_tasks = AsyncMock()
+ update_data = AsyncMock(return_value="wrb_1")
+ create_artifact = AsyncMock()
+ wait_for_uploads = AsyncMock()
+ workflow = SimpleNamespace(workflow_id="w_1")
+ workflow_run = SimpleNamespace(workflow_run_id="wr_1", organization_id="o_1")
+
+ with (
+ patch(f"{_SERVICE_PATH}.BROWSER_MANAGER.get_video_artifacts", get_video),
+ patch(f"{_SERVICE_PATH}.DATABASE.tasks.get_tasks_by_workflow_run_id", get_tasks),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.update_artifact_data", update_data),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.create_artifact", create_artifact),
+ patch(f"{_SERVICE_PATH}.ARTIFACT_MANAGER.wait_for_upload_aiotasks", wait_for_uploads),
+ ):
+ await WorkflowService().persist_video_data(_browser_state(video_artifacts), workflow, workflow_run)
+
+ get_tasks.assert_not_awaited()
+ create_artifact.assert_not_awaited()
+ update_data.assert_awaited_once()
+ wait_for_uploads.assert_awaited_once_with(["wrb_1"])
+ assert video_artifacts[0].video_artifact_id == "a_existing"
diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.py
index 998d9ca68..8dd012958 100644
--- a/tests/unit/test_real_browser_manager.py
+++ b/tests/unit/test_real_browser_manager.py
@@ -387,6 +387,22 @@ async def test_get_video_artifacts_finalize_false_skips_ffmpeg(tmp_path) -> None
assert artifacts[0].video_data == b"partial-webm-bytes"
+async def test_get_video_artifacts_non_webm_skips_ffmpeg(tmp_path) -> None:
+ """Non-WebM container files (e.g. fully-formed MP4 from a remote source)
+ are container-valid already; remuxing them through ``finalize_webm`` would
+ corrupt the file. The extension-based short-circuit reads them raw."""
+ src = tmp_path / "recording.mp4"
+ src.write_bytes(b"mp4-bytes")
+ browser_state = _make_browser_state_with_video(str(src))
+
+ with patch("skyvern.webeye.real_browser_manager.finalize_webm", new=AsyncMock()) as m:
+ artifacts = await RealBrowserManager().get_video_artifacts(browser_state=browser_state)
+
+ m.assert_not_awaited()
+ assert artifacts[0].video_data == b"mp4-bytes"
+
+
def _make_page_mock(video_path: str | None) -> MagicMock:
page = MagicMock()
if video_path is None:
diff --git a/tests/unit/test_real_browser_state_existing_page_reuse.py b/tests/unit/test_real_browser_state_existing_page_reuse.py
new file mode 100644
index 000000000..8741c147c
--- /dev/null
+++ b/tests/unit/test_real_browser_state_existing_page_reuse.py
@@ -0,0 +1,71 @@
+"""Some remote browser sessions bind capture/streaming to the CDP target that
+existed at session creation. ``check_and_fix_state`` must reuse that existing
+page on the first task instead of opening a new tab and closing the original,
+so the remote session stays aligned with the page the agent navigates.
+"""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from skyvern.webeye.browser_artifacts import BrowserArtifacts
+from skyvern.webeye.real_browser_state import RealBrowserState
+
+
+def _build_state(*, session_id: str | None, existing_pages: list[MagicMock]) -> RealBrowserState:
+ state = RealBrowserState(
+ pw=AsyncMock(),
+ browser_artifacts=BrowserArtifacts(remote_browser_session_id=session_id),
+ )
+ context = MagicMock()
+ context.pages = existing_pages
+ context.new_page = AsyncMock()
+ state.browser_context = context
+ state._close_all_other_pages = AsyncMock()
+ state.list_valid_pages = AsyncMock(return_value=list(existing_pages))
+ state.navigate_to_url = AsyncMock()
+ return state
+
+
+async def test_check_and_fix_state_reuses_existing_page_for_remote_browser_session() -> None:
+ existing_page = MagicMock()
+ existing_page.url = "about:blank"
+ state = _build_state(session_id="remote-session-abc", existing_pages=[existing_page])
+
+ await state.check_and_fix_state(url="https://example.com/")
+
+ assert state.browser_context.new_page.await_count == 0, "remote browser session must not open a new tab"
+ state._close_all_other_pages.assert_not_awaited()
+ state.navigate_to_url.assert_awaited_once()
+ args, kwargs = state.navigate_to_url.call_args
+ assert kwargs.get("page") is existing_page or (args and args[0] is existing_page)
+ assert await state.get_working_page() is existing_page
+
+
+async def test_check_and_fix_state_creates_new_page_when_context_has_no_pages() -> None:
+ state = _build_state(session_id=None, existing_pages=[])
+
+ new_page = MagicMock()
+ new_page.url = "about:blank"
+ state.browser_context.new_page = AsyncMock(return_value=new_page)
+
+ await state.check_and_fix_state(url="https://example.com/")
+
+ state.browser_context.new_page.assert_awaited_once()
+ state._close_all_other_pages.assert_awaited_once()
+ state.navigate_to_url.assert_awaited_once()
+
+
+async def test_check_and_fix_state_reuses_existing_page_with_browser_address() -> None:
+ existing_page = MagicMock()
+ existing_page.url = "about:blank"
+ state = _build_state(session_id=None, existing_pages=[existing_page])
+
+ await state.check_and_fix_state(url="https://example.com/", browser_address="http://remote:9222")
+
+ assert state.browser_context.new_page.await_count == 0
+ state._close_all_other_pages.assert_not_awaited()
+ state.navigate_to_url.assert_awaited_once()