Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-11500): drop the throwaway default-tab recording (#7123)
Celal Zamanoğluf4bdd49b0a23
diff --git a/skyvern/webeye/browser_artifacts.py b/skyvern/webeye/browser_artifacts.pyindex 25c32dcab..896be506f 100644--- a/skyvern/webeye/browser_artifacts.py+++ b/skyvern/webeye/browser_artifacts.py@@ -5,6 +5,7 @@ import osimport aiofilesimport structlog+from playwright.async_api import Pagefrom pydantic import BaseModel, PrivateAttrLOG = structlog.get_logger()@@ -29,6 +30,15 @@ class BrowserArtifacts(BaseModel):# 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)+ # Tombstoned synchronously before any await, so set_popup_video_listener can't+ # re-register a page's video after RealBrowserState decides to discard it.+ _discarded_pages: set[Page] = PrivateAttr(default_factory=set)++ def discard_page_video(self, page: Page) -> None:+ self._discarded_pages.add(page)++ def is_page_video_discarded(self, page: Page) -> bool:+ return page in self._discarded_pagesasync def append_browser_console_log(self, msg: str) -> int:if self.browser_console_log_path is None:diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.pyindex 1c3c31bdb..def99102b 100644--- a/skyvern/webeye/browser_factory.py+++ b/skyvern/webeye/browser_factory.py@@ -170,6 +170,10 @@ def set_popup_video_listener(browser_context: BrowserContext, browser_artifacts:raw_path = await video.path()if raw_path is None:return+ # The await above may have raced a discard (RealBrowserState closing this page+ # before it ever became the working page) — honor it even though it landed after.+ if browser_artifacts.is_page_video_discarded(page):+ returnvideo_path = str(raw_path)# After the await, another handler may have already registered this pathif video_path in tracked_paths:diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.pyindex 3a599fb8b..fac3c3684 100644--- a/skyvern/webeye/real_browser_state.py+++ b/skyvern/webeye/real_browser_state.py@@ -102,13 +102,19 @@ class RealBrowserState(BrowserState):LOG.error("BrowserState has no page", urls=[p.url for p in pages])raise MissingBrowserStatePage()- async def _close_all_other_pages(self) -> None:+ async def _close_all_other_pages(self, discard_orphaned_videos: bool = False) -> None:cur_page = await self.get_working_page()if not self.browser_context or not cur_page:returnpages = self.browser_context.pagesfor page in pages:if page != cur_page:+ if discard_orphaned_videos:+ # Tombstone before any await: set_popup_video_listener's registration for+ # this same page may still be in flight, and must observe the tombstone+ # whenever it resolves rather than re-appending after we remove it below.+ self.browser_artifacts.discard_page_video(page)+ await self._discard_video_artifact(page)try:async with asyncio.timeout(2):await page.close()@@ -117,6 +123,29 @@ class RealBrowserState(BrowserState):except Exception:LOG.exception("Error while closing the page", url=page.url)+ async def _discard_video_artifact(self, page: Page) -> None:+ # This page never became the working page — its video must not be registered.+ video = page.video+ if not video:+ return+ try:+ async with asyncio.timeout(settings.POPUP_VIDEO_PATH_TIMEOUT_SECONDS):+ path = str(await video.path())+ except Exception:+ # Best-effort: leave the artifact registered rather than raising — the+ # near-empty video is uploaded as-is instead of silently disappearing.+ try:+ page_origin = urlparse(page.url).hostname or "unknown"+ except Exception:+ page_origin = "unknown"+ LOG.warning("Could not get video path to discard orphaned artifact", page_origin=page_origin, exc_info=True)+ return+ video_artifacts = self.browser_artifacts.video_artifacts+ filtered = [va for va in video_artifacts if va.video_path != path]+ if len(filtered) != len(video_artifacts):+ LOG.debug("Discarded orphaned video artifact", video_path=path)+ self.browser_artifacts.video_artifacts = filtered+async def check_and_fix_state(self,url: str | None = None,@@ -177,7 +206,7 @@ class RealBrowserState(BrowserState):await self.set_working_page(page, 0)if not use_existing_page:- await self._close_all_other_pages()+ await self._close_all_other_pages(discard_orphaned_videos=True)if url and not _same_page_ignoring_fragment(page.url, url):await self.navigate_to_url(page=page, url=url)diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.pyindex 8ee2cccdc..77d5d4c2b 100644--- a/tests/unit/test_real_browser_manager.py+++ b/tests/unit/test_real_browser_manager.py@@ -479,6 +479,28 @@ async def test_popup_video_listener_multiple_popups() -> None:]+async def test_popup_video_listener_skips_page_discarded_before_it_registers() -> None:+ """RealBrowserState.discard_page_video() may tombstone a page while+ set_popup_video_listener's fire-and-forget _on_page for that same page is still awaiting+ video.path() — the late registration must not re-append after the discard."""++ artifacts = BrowserArtifacts(video_artifacts=[VideoArtifact(video_path="/tmp/videos/main.webm")])+ browser_context = MagicMock()+ set_popup_video_listener(browser_context=browser_context, browser_artifacts=artifacts)++ handler = browser_context.on.call_args[0][1]+ orphan = _make_page_mock("/tmp/videos/orphan.webm")++ # Simulate the discard landing first (RealBrowserState._close_all_other_pages tombstones+ # synchronously, before it ever awaits anything), then the listener's registration resolving.+ artifacts.discard_page_video(orphan)+ await handler(orphan)++ paths = [va.video_path for va in artifacts.video_artifacts]+ assert paths == ["/tmp/videos/main.webm"]++@pytest.mark.asyncioasync def test_set_working_page_does_not_touch_video_artifacts() -> None:"""set_working_page only sets the working page; video tracking is handled by the listener."""diff --git a/tests/unit/test_real_browser_state_discards_orphaned_tab_video.py b/tests/unit/test_real_browser_state_discards_orphaned_tab_video.pynew file mode 100644index 000000000..b5b6850d9--- /dev/null+++ b/tests/unit/test_real_browser_state_discards_orphaned_tab_video.py@@ -0,0 +1,168 @@+"""launch_persistent_context() auto-opens a default tab before Skyvern picks a working+page. check_and_fix_state() then opens a fresh page and discards that default tab via+_close_all_other_pages(), but the tab's near-empty video was still registered and later+uploaded as a spurious second RECORDING artifact. The video must be dropped at the same+moment the orphaned page is discarded.+"""++from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifact+from skyvern.webeye.real_browser_state import RealBrowserState+++def _make_page(video_path: str | None) -> MagicMock:+ page = MagicMock()+ page.close = AsyncMock()+ if video_path is None:+ page.video = None+ else:+ page.video = MagicMock()+ page.video.path = AsyncMock(return_value=video_path)+ return page+++def _build_state(+ *, pages: list[MagicMock], working_page: MagicMock | None, video_artifacts: list[VideoArtifact]+) -> RealBrowserState:+ state = RealBrowserState(pw=AsyncMock(), browser_artifacts=BrowserArtifacts(video_artifacts=video_artifacts))+ context = MagicMock()+ context.pages = pages+ state.browser_context = context+ state.get_working_page = AsyncMock(return_value=working_page)+ return state+++async def test_check_and_fix_state_discards_default_tab_video_when_opening_new_page() -> None:+ """End-to-end at the real call site: opening a fresh page drops the default tab's video."""+ default_tab = _make_page("/tmp/default-tab.webm")+ default_tab.url = "about:blank"+ new_page = _make_page("/tmp/new-page.webm")+ new_page.url = "about:blank"++ state = RealBrowserState(+ pw=AsyncMock(),+ browser_artifacts=BrowserArtifacts(video_artifacts=[VideoArtifact(video_path="/tmp/default-tab.webm")]),+ )+ context = MagicMock()+ context.pages = [default_tab]+ context.new_page = AsyncMock(return_value=new_page)+ state.browser_context = context+ state.navigate_to_url = AsyncMock()++ working_page_holder: dict[str, MagicMock | None] = {"page": None}++ async def _get_working_page() -> MagicMock | None:+ return working_page_holder["page"]++ async def _set_working_page(page: MagicMock | None, index: int = 0) -> None:+ working_page_holder["page"] = page++ state.get_working_page = _get_working_page+ state.set_working_page = _set_working_page++ await state.check_and_fix_state()++ context.new_page.assert_awaited_once()+ default_tab.close.assert_awaited_once()+ # The "page" event listener (browser_factory.set_popup_video_listener) registers new_page's+ # own video separately; this test only covers the default tab's entry being dropped here.+ assert state.browser_artifacts.video_artifacts == []+++async def test_close_all_other_pages_discards_orphaned_page_video() -> None:+ """Direct unit coverage of the orphaned-page video pruning logic."""+ throwaway_page = _make_page("/tmp/throwaway.webm")+ real_page = _make_page("/tmp/real.webm")+ state = _build_state(+ pages=[throwaway_page, real_page],+ working_page=real_page,+ video_artifacts=[+ VideoArtifact(video_path="/tmp/throwaway.webm"),+ VideoArtifact(video_path="/tmp/real.webm"),+ ],+ )++ await state._close_all_other_pages(discard_orphaned_videos=True)++ throwaway_page.close.assert_awaited_once()+ real_page.close.assert_not_awaited()+ assert [va.video_path for va in state.browser_artifacts.video_artifacts] == ["/tmp/real.webm"]+ assert state.browser_artifacts.is_page_video_discarded(throwaway_page) is True+++async def test_check_and_fix_state_reuse_branch_preserves_existing_page_video() -> None:+ """browser_address/remote-session runs reuse the existing page as the working page instead+ of opening a new one, so _close_all_other_pages (and the discard inside it) never runs —+ that page's video, its ONLY recording, must survive untouched."""+ existing_page = _make_page("/tmp/existing.webm")+ existing_page.url = "about:blank"++ state = RealBrowserState(+ pw=AsyncMock(),+ browser_artifacts=BrowserArtifacts(video_artifacts=[VideoArtifact(video_path="/tmp/existing.webm")]),+ )+ context = MagicMock()+ context.pages = [existing_page]+ context.new_page = AsyncMock()+ state.browser_context = context+ state.navigate_to_url = AsyncMock()+ state.list_valid_pages = AsyncMock(return_value=[existing_page])++ working_page_holder: dict[str, MagicMock | None] = {"page": None}++ async def _get_working_page() -> MagicMock | None:+ return working_page_holder["page"]++ async def _set_working_page(page: MagicMock | None, index: int = 0) -> None:+ working_page_holder["page"] = page++ state.get_working_page = _get_working_page+ state.set_working_page = _set_working_page++ await state.check_and_fix_state(browser_address="http://remote:9222")++ context.new_page.assert_not_awaited()+ existing_page.close.assert_not_awaited()+ assert [va.video_path for va in state.browser_artifacts.video_artifacts] == ["/tmp/existing.webm"]+ assert state.browser_artifacts.is_page_video_discarded(existing_page) is False+++async def test_close_all_other_pages_keeps_videos_by_default() -> None:+ """The teardown call site (close_current_open_page) does not opt in: a page closed there+ may be a real popup the agent used, not a throwaway, so its video must survive."""+ other_page = _make_page("/tmp/popup.webm")+ real_page = _make_page("/tmp/real.webm")+ state = _build_state(+ pages=[other_page, real_page],+ working_page=real_page,+ video_artifacts=[+ VideoArtifact(video_path="/tmp/popup.webm"),+ VideoArtifact(video_path="/tmp/real.webm"),+ ],+ )++ await state._close_all_other_pages()++ other_page.close.assert_awaited_once()+ assert {va.video_path for va in state.browser_artifacts.video_artifacts} == {+ "/tmp/popup.webm",+ "/tmp/real.webm",+ }+++async def test_discard_video_artifact_noop_when_page_has_no_video() -> None:+ """Recording disabled (page.video is None) must be a harmless no-op."""+ state = _build_state(pages=[], working_page=None, video_artifacts=[VideoArtifact(video_path="/tmp/real.webm")])+ page = _make_page(None)++ await state._discard_video_artifact(page)++ assert [va.video_path for va in state.browser_artifacts.video_artifacts] == ["/tmp/real.webm"]