Skip to content

Automate browser based workflows with AI

fix: preserve provider-owned remote download handling (#8115)

LawyZheng1948de79cb36
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index eda197c8f..2dc9394b9 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -211,6 +211,7 @@ from skyvern.utils.token_counter import count_tokens
from skyvern.utils.url_validators import prepend_scheme_and_validate_url
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, ActionStatus
+from skyvern.webeye.browser_artifacts import DownloadBinding
from skyvern.webeye.browser_factory import rebind_download_dir
from skyvern.webeye.browser_state import BrowserState
from skyvern.webeye.real_browser_state import RealBrowserState
@@ -603,17 +604,26 @@ class Block(BaseModel, abc.ABC):
skyvern_context.current(), fallback_run_id=workflow_run_id
)
try:
- adopted_context = browser_state.browser_context
- adopted_browser = adopted_context.browser if adopted_context else None
- rebind_page = None if adopted_browser is not None else await browser_state.get_working_page()
- if adopted_browser is not None or rebind_page is not None:
- await rebind_download_dir(adopted_browser, run_id=rebind_run_id, page=rebind_page)
+ if browser_state.browser_artifacts.download_binding == DownloadBinding.SESSION_DIR:
+ # Provider-owned remote binding: preserve the provider-selected destination
+ # instead of re-pointing downloads to a run-scoped dir.
LOG.info(
- "Rebound download dir on adopted persistent session",
+ "Skipping download-dir rebind on adopted session: preserving provider-selected destination",
browser_session_id=browser_session_id,
workflow_run_id=workflow_run_id,
- run_id=rebind_run_id,
)
+ else:
+ adopted_context = browser_state.browser_context
+ adopted_browser = adopted_context.browser if adopted_context else None
+ rebind_page = None if adopted_browser is not None else await browser_state.get_working_page()
+ if adopted_browser is not None or rebind_page is not None:
+ await rebind_download_dir(adopted_browser, run_id=rebind_run_id, page=rebind_page)
+ LOG.info(
+ "Rebound download dir on adopted persistent session",
+ browser_session_id=browser_session_id,
+ workflow_run_id=workflow_run_id,
+ run_id=rebind_run_id,
+ )
except Exception:
LOG.warning(
"Failed to rebind download dir on adopted persistent session",
@@ -710,15 +720,24 @@ class Block(BaseModel, abc.ABC):
skyvern_context.current(), fallback_run_id=workflow_run_id
)
try:
- owning_browser = browser_state.browser_context.browser if browser_state.browser_context else None
- rebind_page = None if owning_browser is not None else await browser_state.get_working_page()
- if owning_browser is not None or rebind_page is not None:
- await rebind_download_dir(owning_browser, run_id=rebind_run_id, page=rebind_page)
+ if browser_state.browser_artifacts.download_binding == DownloadBinding.SESSION_DIR:
+ # Defense-in-depth: a mismatched caller (e.g. a cached adopted state fetched without a
+ # browser_session_id) must never rebind a provider-owned remote binding off its
+ # provider-selected destination.
LOG.info(
- "Rebound download dir on workflow-run browser",
+ "Skipping workflow-run download-dir rebind: preserving provider-selected destination",
workflow_run_id=workflow_run_id,
- run_id=rebind_run_id,
)
+ else:
+ owning_browser = browser_state.browser_context.browser if browser_state.browser_context else None
+ rebind_page = None if owning_browser is not None else await browser_state.get_working_page()
+ if owning_browser is not None or rebind_page is not None:
+ await rebind_download_dir(owning_browser, run_id=rebind_run_id, page=rebind_page)
+ LOG.info(
+ "Rebound download dir on workflow-run browser",
+ workflow_run_id=workflow_run_id,
+ run_id=rebind_run_id,
+ )
except Exception:
LOG.warning(
"Failed to rebind download dir on workflow-run browser",
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index d337fb19d..4bc7a48f2 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -153,6 +153,7 @@ from skyvern.webeye.actions.actions import (
WebAction,
)
from skyvern.webeye.actions.responses import ActionAbort, ActionFailure, ActionResult, ActionSuccess
+from skyvern.webeye.browser_artifacts import DownloadBinding
from skyvern.webeye.browser_engine import UNSET_SELECTION, BrowserEngineSelection, resolve_engine_selection_for_task
from skyvern.webeye.browser_factory import initialize_download_dir, resolve_artifact_path
from skyvern.webeye.browser_state import BrowserState
@@ -959,13 +960,22 @@ async def _save_adopted_session_download(
download_dir: Path,
workflow_run_id: str | None = None,
eager_blob_bytes: bytes | None = None,
+ download_binding: DownloadBinding = DownloadBinding.RUN_DIR,
) -> Path | None:
"""Land an adopted-session download's bytes into download_dir, returning the file path or None.
- Eager save_as is the only protection against the worker pod tearing the shared browser down before a
- deferred save_as runs.
+ A provider-owned remote non-blob event is signal-only and returns None; blob and default behavior
+ are unchanged.
"""
download_target = _download_target_path(download_dir, download.suggested_filename)
+ if download_binding == DownloadBinding.SESSION_DIR and not download.url.startswith("blob:"):
+ # Signal-only for a provider-owned remote binding: the run connection holds no bytes to save_as
+ # and a URL replay would run through the wrong identity, so defer to the provider destination.
+ LOG.info(
+ "Provider-owned remote download: suppressing local save/replay, deferring to provider destination",
+ workflow_run_id=workflow_run_id,
+ )
+ return None
# Non-empty bytes captured at download-event time (blob owner still alive) win outright: skip
# save_as, which returns empty for blobs anyway. A zero-byte eager capture is indistinguishable
# from an unreadable one and would be a false success, so fall through to save_as + fan-out
@@ -3503,6 +3513,11 @@ class ActionHandler:
and captured_download is not None
and not download_event_fallback_attempted
):
+ resolved_download_binding = (
+ browser_state.browser_artifacts.download_binding
+ if browser_state is not None
+ else DownloadBinding.RUN_DIR
+ )
download_event_fallback_attempted = True
saved_path = await _save_adopted_session_download(
captured_download,
@@ -3515,6 +3530,7 @@ class ActionHandler:
_remaining_download_wait_seconds(),
)
),
+ download_binding=resolved_download_binding,
)
if saved_path is not None:
download_event_fallback_used = True
@@ -3526,12 +3542,24 @@ class ActionHandler:
workflow_run_id=task.workflow_run_id,
)
break
- download_event_fallback_failed = True
- LOG.warning(
- "Adopted-session download could not be saved or re-fetched; falling through to browser-session folder poll",
- download_dir=download_dir,
- workflow_run_id=task.workflow_run_id,
- )
+ if (
+ resolved_download_binding == DownloadBinding.SESSION_DIR
+ and not captured_download.url.startswith("blob:")
+ ):
+ # Expected signal-only deferral for a provider-owned remote binding: no
+ # save_as/replay was attempted, so this is not a failure. Keep polling.
+ LOG.info(
+ "Provider-owned remote download deferred to provider-destination observation",
+ download_dir=download_dir,
+ workflow_run_id=task.workflow_run_id,
+ )
+ else:
+ download_event_fallback_failed = True
+ LOG.warning(
+ "Adopted-session download could not be saved or re-fetched; falling through to browser-session folder poll",
+ download_dir=download_dir,
+ workflow_run_id=task.workflow_run_id,
+ )
# Keep polling: the shared browser may still land the file in the session folder.
if await _drain_and_move_staged_xhr(
xhr_fallback_moved_paths, _remaining_download_wait_seconds()
diff --git a/skyvern/webeye/browser_artifacts.py b/skyvern/webeye/browser_artifacts.py
index db67ff363..44f10cde2 100644
--- a/skyvern/webeye/browser_artifacts.py
+++ b/skyvern/webeye/browser_artifacts.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import os
+from enum import Enum
import aiofiles
import structlog
@@ -11,6 +12,19 @@ from pydantic import BaseModel, PrivateAttr
LOG = structlog.get_logger()
+class DownloadBinding(str, Enum):
+ """Where this browser's downloads are bound.
+
+ RUN_DIR (default): the run-scoped directory; downloads are rebound there and read locally. This is
+ the local/default behavior for local runs and any non-provider-owned session.
+ SESSION_DIR: a provider-owned remote download destination. The run-dir rebind must be skipped and a
+ URL replay is forbidden, so the provider-selected destination is preserved.
+ """
+
+ RUN_DIR = "run_dir"
+ SESSION_DIR = "session_dir"
+
+
class VideoArtifact(BaseModel):
video_path: str | None = None
video_artifact_id: str | None = None
@@ -30,6 +44,10 @@ class BrowserArtifacts(BaseModel):
needs_cdp_frame_publisher: bool = False
# Optional opaque identifier for a remote browser session.
remote_browser_session_id: str | None = None
+ # Download destination binding for this browser. SESSION_DIR (a provider-owned remote destination)
+ # means the run-dir rebind must be skipped and URL replay forbidden; RUN_DIR (default) preserves
+ # local/default delivery. See DownloadBinding.
+ download_binding: DownloadBinding = DownloadBinding.RUN_DIR
# The saved browser profile the creator actually applied to this browser's user-data-dir.
# None when none was requested or the chosen creator could not load one (remote/vendor browsers,
# storage miss, corruption fallback) — consumers must treat None as "profile not applied".
diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.py
index 39bada4fb..d4dd8d5d6 100644
--- a/skyvern/webeye/browser_factory.py
+++ b/skyvern/webeye/browser_factory.py
@@ -47,7 +47,7 @@ from skyvern.forge import app
from skyvern.forge.sdk.api.files import get_download_dir, make_temp_directory, resolve_run_download_id
from skyvern.forge.sdk.core.skyvern_context import current, ensure_context
from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput, get_tzinfo_from_proxy
-from skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifact
+from skyvern.webeye.browser_artifacts import BrowserArtifacts, DownloadBinding, VideoArtifact
from skyvern.webeye.cdp_connection import (
build_cdp_connect_headers,
)
@@ -543,6 +543,16 @@ async def _apply_download_behaviour(browser: Browser) -> None:
await rebind_download_dir(browser, resolve_run_download_id(context))
+def _resolve_download_binding(kwargs: dict[str, Any]) -> DownloadBinding:
+ """Read the optional caller-threaded download binding from loosely-typed creator kwargs.
+
+ ``**kwargs`` values carry no static type, so narrow to DownloadBinding and fall back to the RUN_DIR
+ default for any absent or unexpected value — keeping the generic browser_address path type-safe.
+ """
+ binding = kwargs.get("download_binding")
+ return binding if isinstance(binding, DownloadBinding) else DownloadBinding.RUN_DIR
+
+
class BrowserContextCreator(Protocol):
def __call__(
self, playwright: Playwright, proxy_location: ProxyLocationInput = None, **kwargs: dict[str, Any]
@@ -838,6 +848,7 @@ async def _create_headless_chromium(
cdp_connect_headers=cdp_connect_headers,
apply_download_behaviour=True,
validate_browser_address=True,
+ download_binding=_resolve_download_binding(kwargs),
)
# Check for browser_profile_id and load from storage if available
@@ -933,6 +944,7 @@ async def _create_headful_chromium(
cdp_connect_headers=cdp_connect_headers,
apply_download_behaviour=True,
validate_browser_address=True,
+ download_binding=_resolve_download_binding(kwargs),
)
# Check for browser_profile_id and load from storage if available
@@ -1056,6 +1068,7 @@ async def _create_cdp_connection_browser(
cdp_connect_headers=cdp_connect_headers,
apply_download_behaviour=True,
validate_browser_address=True,
+ download_binding=_resolve_download_binding(kwargs),
)
browser_type = settings.BROWSER_TYPE
@@ -1121,6 +1134,7 @@ async def _connect_to_cdp_browser(
cdp_connect_headers: dict[str, str] | None = None,
apply_download_behaviour: bool = False,
validate_browser_address: bool = True,
+ download_binding: DownloadBinding = DownloadBinding.RUN_DIR,
) -> tuple[BrowserContext, BrowserArtifacts, BrowserCleanupFunc]:
parsed_headers = parse_extra_headers(extra_http_headers)
@@ -1134,6 +1148,9 @@ async def _connect_to_cdp_browser(
# Single chokepoint for OSS remote-CDP creation; stamp the marker so
# RealBrowserManager attaches the CDP frame publisher.
browser_artifacts.needs_cdp_frame_publisher = True
+ # Carry the caller's binding onto the fresh artifacts so a reconnect that rebuilds through this
+ # generic path preserves the provider-selected destination by construction, not by a later relabel.
+ browser_artifacts.download_binding = download_binding
LOG.info("Connecting browser CDP connection", remote_browser_url=redact_cdp_url(remote_browser_url))
cdp_headers = merge_cdp_connect_headers(
@@ -1149,7 +1166,14 @@ async def _connect_to_cdp_browser(
validate_browser_address=validate_browser_address,
)
- if apply_download_behaviour:
+ if apply_download_behaviour and download_binding == DownloadBinding.SESSION_DIR:
+ # Provider-owned remote binding: preserve the provider-selected destination. Re-sending a
+ # run-scoped download path here would overwrite it, so leave the binding untouched.
+ LOG.info(
+ "Skipping run-dir download rebind on CDP connect: preserving provider-selected destination",
+ remote_browser_url=redact_cdp_url(remote_browser_url),
+ )
+ elif apply_download_behaviour:
try:
await _apply_download_behaviour(browser)
except Exception:
diff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.py
index 359b11ca6..f93884877 100644
--- a/skyvern/webeye/real_browser_manager.py
+++ b/skyvern/webeye/real_browser_manager.py
@@ -28,7 +28,7 @@ from skyvern.forge.sdk.routes.streaming.registries import (
from skyvern.forge.sdk.schemas.tasks import Task
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun
from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput
-from skyvern.webeye.browser_artifacts import VideoArtifact
+from skyvern.webeye.browser_artifacts import DownloadBinding, VideoArtifact
from skyvern.webeye.browser_engine import (
BrowserEngineContext,
BrowserEngineSelection,
@@ -131,6 +131,15 @@ async def _rebind_pbs_download_dir(
download_run_id: str,
browser_session_id: str,
) -> None:
+ if browser_state.browser_artifacts.download_binding == DownloadBinding.SESSION_DIR:
+ # Provider-owned remote binding: preserve the provider-selected destination. Re-pointing to a
+ # run-scoped dir would overwrite it, so skip the rebind.
+ LOG.info(
+ "Skipping download-dir rebind: preserving provider-selected destination",
+ browser_session_id=browser_session_id,
+ download_run_id=download_run_id,
+ )
+ return
browser_context = browser_state.browser_context
if browser_context is None:
return
diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.py
index 4b3cd1d4d..070ddae0d 100644
--- a/skyvern/webeye/real_browser_state.py
+++ b/skyvern/webeye/real_browser_state.py
@@ -28,7 +28,7 @@ from skyvern.forge import app
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.trace import traced
from skyvern.schemas.runs import ProxyLocationInput
-from skyvern.webeye.browser_artifacts import BrowserArtifacts
+from skyvern.webeye.browser_artifacts import BrowserArtifacts, DownloadBinding
from skyvern.webeye.browser_engine import BrowserEngineSelection
from skyvern.webeye.browser_factory import BrowserCleanupFunc, BrowserContextFactory, resolve_artifact_path
from skyvern.webeye.browser_state import BrowserState
@@ -199,10 +199,18 @@ class RealBrowserState(BrowserState):
cdp_connect_headers: dict[str, str] | None = None,
browser_address: str | None = None,
browser_profile_id: str | None = None,
+ download_binding: DownloadBinding | None = None,
) -> None:
if self.browser_context is None:
LOG.info("creating browser context")
context = skyvern_context.current()
+ # When recreation omits a binding, preserve the prior artifacts' binding instead of
+ # downgrading to RUN_DIR.
+ effective_download_binding = download_binding
+ if effective_download_binding is None:
+ effective_download_binding = (
+ self.browser_artifacts.download_binding if self.browser_artifacts else DownloadBinding.RUN_DIR
+ )
(
browser_context,
browser_artifacts,
@@ -222,6 +230,7 @@ class RealBrowserState(BrowserState):
browser_address_is_server_assigned=bool(context and context.browser_address_is_server_assigned),
browser_profile_id=browser_profile_id,
engine_selection=self.engine_selection,
+ download_binding=effective_download_binding,
)
self.browser_context = browser_context
self.browser_artifacts = browser_artifacts
@@ -502,6 +511,12 @@ class RealBrowserState(BrowserState):
# The old driver pipe is gone, so check_and_fix_state must not reuse self.pw; start a
# fresh Playwright driver and reconnect to the same (still-alive) remote browser.
stale_pw = self.pw
+ # check_and_fix_state rebuilds through the factory; forward this session's download binding so the
+ # creator seam preserves the provider-selected destination on reconnect. The binding is carried
+ # forward, never overridden after the fact, so a genuine provider change is not mislabeled.
+ prior_download_binding = (
+ self.browser_artifacts.download_binding if self.browser_artifacts else DownloadBinding.RUN_DIR
+ )
self.browser_context = None
await self.set_working_page(None)
# Reconnect on the SAME engine this state was pinned to at creation; never silently switch
@@ -520,6 +535,7 @@ class RealBrowserState(BrowserState):
cdp_connect_headers=cdp_connect_headers,
browser_address=browser_address,
browser_profile_id=browser_profile_id,
+ download_binding=prior_download_binding,
)
except Exception:
# The caller abandons this state on failure, so stop the just-started driver too or it leaks.
diff --git a/tests/unit/test_adopted_session_download_save.py b/tests/unit/test_adopted_session_download_save.py
index e8214fd4d..6780da745 100644
--- a/tests/unit/test_adopted_session_download_save.py
+++ b/tests/unit/test_adopted_session_download_save.py
@@ -22,6 +22,7 @@ from skyvern.webeye.actions.handler import (
_read_adopted_session_blob_bytes,
_save_adopted_session_download,
)
+from skyvern.webeye.browser_artifacts import DownloadBinding
PDF_BODY = b"%PDF-1.4\n" + b"x" * 830
@@ -78,6 +79,45 @@ async def test_happy_path_eager_save_writes_bytes(tmp_path) -> None:
page.context.request.get.assert_not_awaited()
+async def test_session_dir_non_blob_suppresses_worker_replay(tmp_path) -> None:
+ # A provider-owned remote binding delivers the file through the provider destination, so the run
+ # connection has no bytes and a URL replay would run through the wrong identity. The helper must NOT
+ # save_as or replay; it returns None (signal only) so the loop keeps polling.
+ download = _download()
+ page = _page_with_refetch()
+
+ saved = await _save_adopted_session_download(
+ download, page, tmp_path, workflow_run_id="wr", download_binding=DownloadBinding.SESSION_DIR
+ )
+
+ assert saved is None
+ page.context.request.get.assert_not_awaited()
+ download.save_as.assert_not_awaited()
+ assert list(tmp_path.iterdir()) == []
+
+
+async def test_session_dir_blob_still_recovers_in_page(tmp_path) -> None:
+ # A blob download on a SESSION_DIR session is identity-safe via the in-page read (the bytes live in
+ # the page, not on any network), so it is still delivered — the suppression is non-blob only.
+ download = _download(url="blob:https://example.com/abc")
+ page = _page_with_refetch()
+
+ saved = await _save_adopted_session_download(
+ download,
+ page,
+ tmp_path,
+ workflow_run_id="wr",
+ download_binding=DownloadBinding.SESSION_DIR,
+ eager_blob_bytes=PDF_BODY,
+ )
+
+ assert saved is not None and saved.exists()
+ assert saved.read_bytes() == PDF_BODY
+ page.context.request.get.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_save_as_raises_target_closed_falls_back_to_refetch(tmp_path) -> None:
download = _download()
diff --git a/tests/unit/test_download_dir_rebind.py b/tests/unit/test_download_dir_rebind.py
index fccef9454..7fbafe01e 100644
--- a/tests/unit/test_download_dir_rebind.py
+++ b/tests/unit/test_download_dir_rebind.py
@@ -15,8 +15,10 @@ import pytest
from skyvern.forge.sdk.api.files import get_download_dir, resolve_run_download_id
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.workflow.models.block import Block, CodeBlock, PrintPageBlock
+from skyvern.webeye.browser_artifacts import DownloadBinding
from skyvern.webeye.browser_factory import (
_apply_download_behaviour,
+ _create_headless_chromium,
rebind_download_dir,
set_download_file_listener,
)
@@ -236,6 +238,54 @@ async def test_apply_download_behaviour_falls_back_to_workflow_run_id() -> None:
assert params["downloadPath"] == get_download_dir("wr_y")
+async def test_connect_creator_skips_run_dir_setdownloadbehavior_for_session_dir() -> None:
+ """The generic ``browser_address`` reconnect path must not re-point a provider-owned remote
+ binding's downloads to the run dir. ``_connect_to_cdp_browser`` skips ``_apply_download_behaviour``
+ for SESSION_DIR so the provider-selected destination is preserved, and stamps the fresh artifacts
+ SESSION_DIR by construction (not a later relabel)."""
+ browser, cdp_session = _recording_browser()
+ browser.new_context = AsyncMock(return_value=MagicMock(pages=[]))
+ ctx = SkyvernContext(run_id="run_x", workflow_run_id="wr_y")
+
+ with (
+ patch("skyvern.webeye.browser_factory._connect_over_cdp_with_diagnostics", AsyncMock(return_value=browser)),
+ patch("skyvern.webeye.browser_factory.ensure_context", return_value=ctx),
+ ):
+ _, artifacts, _ = await _create_headless_chromium(
+ MagicMock(),
+ browser_address="ws://remote.example/cdp",
+ download_binding=DownloadBinding.SESSION_DIR,
+ )
+
+ sent_methods = [call.args[0] for call in cdp_session.send.await_args_list if call.args]
+ assert "Browser.setDownloadBehavior" not in sent_methods
+ assert artifacts.download_binding == DownloadBinding.SESSION_DIR
+
+
+async def test_connect_creator_binds_run_dir_setdownloadbehavior_for_run_dir() -> None:
+ """RUN_DIR (default local/OSS/vendor) still physically binds downloads to the run dir on connect —
+ the SESSION_DIR skip must not disable the ordinary run-scoped rebind."""
+ browser, cdp_session = _recording_browser()
+ browser.new_context = AsyncMock(return_value=MagicMock(pages=[]))
+ ctx = SkyvernContext(run_id="run_x", workflow_run_id="wr_y")
+
+ with (
+ patch("skyvern.webeye.browser_factory._connect_over_cdp_with_diagnostics", AsyncMock(return_value=browser)),
+ patch("skyvern.webeye.browser_factory.ensure_context", return_value=ctx),
+ ):
+ _, artifacts, _ = await _create_headless_chromium(
+ MagicMock(),
+ browser_address="ws://remote.example/cdp",
+ )
+
+ method, params = cdp_session.send.await_args.args
+ assert method == "Browser.setDownloadBehavior"
+ assert params["downloadPath"] == get_download_dir("run_x")
+ assert artifacts.download_binding == DownloadBinding.RUN_DIR
+
+
@pytest.mark.asyncio
async def test_listener_logs_run_identity_from_context(tmp_path: Path) -> None:
captured: dict[str, object] = {}
@@ -338,6 +388,30 @@ async def test_block_adoption_seam_rebinds_to_run_dir() -> None:
mock_app.BROWSER_MANAGER.get_or_create_for_workflow_run.assert_not_called()
+async def test_block_adoption_skips_rebind_when_session_dir_binding() -> None:
+ """A provider-owned remote binding preserves the provider-selected destination: the block adoption
+ seam must not re-send setDownloadBehavior to a run-scoped dir."""
+ browser, cdp_session = _recording_browser()
+ browser_state = MagicMock()
+ browser_state.browser_context.browser = browser
+ browser_state.browser_artifacts.download_binding = DownloadBinding.SESSION_DIR
+
+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
+ mock_app.PERSISTENT_SESSIONS_MANAGER.get_browser_state = AsyncMock(return_value=browser_state)
+ mock_app.BROWSER_MANAGER.get_or_create_for_workflow_run = AsyncMock()
+
+ result = await Block.get_or_create_browser_state(
+ MagicMock(),
+ workflow_run_id="wr_block",
+ organization_id="org_1",
+ browser_session_id="bs_block",
+ )
+
+ assert result is browser_state
+ cdp_session.send.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_block_adoption_seam_rebinds_via_context_page_without_owning_browser() -> None:
"""Persistent-context adoption (browser_context.browser is None) rebinds via the working page's CDP session."""
@@ -409,6 +483,32 @@ async def test_block_non_adoption_cache_hit_rebinds_to_run_dir() -> None:
assert params["downloadPath"].endswith("/wr_own")
+async def test_block_non_adoption_skips_rebind_when_session_dir_binding() -> None:
+ """Defense-in-depth: an own-browser state carrying a SESSION_DIR binding must not be rebound off its
+ provider-selected destination even on the non-adoption path."""
+
+ browser, cdp_session = _recording_browser()
+ browser_state = MagicMock()
+ browser_state.browser_context.browser = browser
+ browser_state.is_connected = MagicMock(return_value=True)
+ browser_state.browser_artifacts.download_binding = DownloadBinding.SESSION_DIR
+
+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
+ mock_app.BROWSER_MANAGER.get_for_workflow_run = MagicMock(return_value=browser_state)
+
+ result = await Block.get_or_create_browser_state(
+ MagicMock(),
+ workflow_run_id="wr_own",
+ organization_id=None,
+ browser_session_id=None,
+ download_run_id_override="wr_own",
+ )
+
+ assert result is browser_state
+ cdp_session.send.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_block_non_adoption_rebinds_when_org_id_missing() -> None:
"""browser_session_id set but organization_id None is still non-adoption -> rebind fires."""
diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.py
index 199d983eb..e595dd54b 100644
--- a/tests/unit/test_real_browser_manager.py
+++ b/tests/unit/test_real_browser_manager.py
@@ -21,7 +21,7 @@ from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.routes.streaming import registries
from skyvern.webeye import real_browser_manager
-from skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifact
+from skyvern.webeye.browser_artifacts import BrowserArtifacts, DownloadBinding, VideoArtifact
from skyvern.webeye.browser_engine import BrowserEngineMetadata, BrowserEngineSelection
from skyvern.webeye.browser_factory import set_popup_video_listener
from skyvern.webeye.real_browser_manager import RealBrowserManager, _PersistentSessionLease
@@ -1409,7 +1409,8 @@ async def test_pbs_adoption_rebinds_download_dir_without_an_interceptor() -> Non
SimpleNamespace, not MagicMock: the latter auto-creates the interceptor attribute."""
adopted_browser = MagicMock()
browser_context = SimpleNamespace(browser=adopted_browser)
- pbs_state = SimpleNamespace(browser_context=browser_context)
+ # A real BrowserState always carries browser_artifacts; default RUN_DIR keeps today's rebind path.
+ pbs_state = SimpleNamespace(browser_context=browser_context, browser_artifacts=BrowserArtifacts())
with patch("skyvern.webeye.real_browser_manager.rebind_download_dir", new_callable=AsyncMock) as mock_rebind:
await real_browser_manager._rebind_pbs_download_dir(pbs_state, "wfr_own_infra", "bs_own_infra")
@@ -1577,6 +1578,67 @@ async def test_non_pbs_workflow_run_does_not_rebind() -> None:
mock_rebind.assert_not_awaited()
+async def test_pbs_adoption_skips_rebind_when_session_dir_binding() -> None:
+ """A provider-owned remote binding must preserve the provider-selected destination: the run-dir
+ rebind must be skipped."""
+ manager = RealBrowserManager()
+ workflow_run = make_workflow_run("wfr_session")
+
+ adopted_browser = MagicMock()
+ pbs_state = MagicMock()
+ pbs_state.browser_context.browser = adopted_browser
+ pbs_state.browser_artifacts.download_binding = DownloadBinding.SESSION_DIR
+ pbs_state.get_working_page = AsyncMock(return_value=None)
+ pbs_state.get_or_create_page = AsyncMock()
+
+ with (
+ patch("skyvern.webeye.real_browser_manager.app") as mock_app,
+ patch("skyvern.webeye.real_browser_manager.rebind_download_dir", new_callable=AsyncMock) as mock_rebind,
+ ):
+ configure_browser_context_acquired_hook(mock_app)
+ mock_app.PERSISTENT_SESSIONS_MANAGER.get_browser_state = AsyncMock(return_value=pbs_state)
+ mock_app.PERSISTENT_SESSIONS_MANAGER.set_browser_state = AsyncMock()
+
+ await manager.get_or_create_for_workflow_run(
+ workflow_run=workflow_run,
+ url=None,
+ browser_session_id="bs_session",
+ )
+
+ mock_rebind.assert_not_awaited()
+
+
+async def test_pbs_adoption_rebinds_when_run_dir_binding() -> None:
+ """A RUN_DIR (local/OSS) adopted session keeps today's rebind: it is the only delivery path there."""
+ manager = RealBrowserManager()
+ workflow_run = make_workflow_run("wfr_run_dir")
+
+ adopted_browser = MagicMock()
+ pbs_state = MagicMock()
+ pbs_state.browser_context.browser = adopted_browser
+ pbs_state.browser_artifacts.download_binding = DownloadBinding.RUN_DIR
+ pbs_state.get_working_page = AsyncMock(return_value=None)
+ pbs_state.get_or_create_page = AsyncMock()
+
+ with (
+ patch("skyvern.webeye.real_browser_manager.app") as mock_app,
+ patch("skyvern.webeye.real_browser_manager.rebind_download_dir", new_callable=AsyncMock) as mock_rebind,
+ ):
+ configure_browser_context_acquired_hook(mock_app)
+ mock_app.PERSISTENT_SESSIONS_MANAGER.get_browser_state = AsyncMock(return_value=pbs_state)
+ mock_app.PERSISTENT_SESSIONS_MANAGER.set_browser_state = AsyncMock()
+
+ await manager.get_or_create_for_workflow_run(
+ workflow_run=workflow_run,
+ url=None,
+ browser_session_id="bs_run_dir",
+ )
+
+ mock_rebind.assert_awaited_once_with(adopted_browser, run_id="wfr_run_dir")
+
+
def _stale_pbs_browser_state(*, navigate_exc: Exception) -> MagicMock:
state = MagicMock()
page = MagicMock()
diff --git a/tests/unit/test_real_browser_state_reload.py b/tests/unit/test_real_browser_state_reload.py
index b8041fcd9..f6637ac0f 100644
--- a/tests/unit/test_real_browser_state_reload.py
+++ b/tests/unit/test_real_browser_state_reload.py
@@ -5,6 +5,7 @@ load → domcontentloaded → commit instead of hard-failing on SPA pages.
Degradation is scoped to extraction tasks only.
"""
+from collections.abc import Awaitable, Callable
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -13,6 +14,7 @@ from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from skyvern.constants import ScrapeType
from skyvern.exceptions import FailedToReloadPage
from skyvern.forge.agent import ForgeAgent
+from skyvern.webeye.browser_artifacts import BrowserArtifacts, DownloadBinding
from skyvern.webeye.real_browser_state import RealBrowserState
_AGENT_MODULE = "skyvern.forge.agent"
@@ -190,3 +192,179 @@ async def test_scrape_with_type_normal_no_reload_call() -> None:
)
bs.reload_page.assert_not_called()
+
+
+def _reconnect_state(binding: DownloadBinding) -> RealBrowserState:
+ state = RealBrowserState.__new__(RealBrowserState)
+ state.pw = AsyncMock()
+ state.browser_context = MagicMock()
+ state.engine_selection = MagicMock()
+ state.engine_selection.start_driver = AsyncMock(return_value=AsyncMock())
+ state.set_working_page = AsyncMock()
+ state.browser_artifacts = BrowserArtifacts(download_binding=binding)
+
+ async def _factory_rebuild(**kwargs: object) -> None:
+ # Model the authoritative creator seam: check_and_fix_state forwards the binding and the factory
+ # stamps it on the fresh artifacts (there is no post-hoc marker override on the state).
+ forwarded = kwargs.get("download_binding")
+ stamped = forwarded if isinstance(forwarded, DownloadBinding) else DownloadBinding.RUN_DIR
+ state.browser_artifacts = BrowserArtifacts(download_binding=stamped)
+
+ state.check_and_fix_state = _factory_rebuild # type: ignore[method-assign]
+ return state
+
+
+async def test_reconnect_preserves_session_dir_binding() -> None:
+ state = _reconnect_state(DownloadBinding.SESSION_DIR)
+ await state.reconnect(workflow_run_id="wr-1")
+ assert state.browser_artifacts.download_binding == DownloadBinding.SESSION_DIR
+
+
+async def test_reconnect_keeps_run_dir_binding() -> None:
+ state = _reconnect_state(DownloadBinding.RUN_DIR)
+ await state.reconnect(workflow_run_id="wr-1")
+ assert state.browser_artifacts.download_binding == DownloadBinding.RUN_DIR
+
+
+def _reconnect_state_capturing_check(binding: DownloadBinding, captured: dict[str, object]) -> RealBrowserState:
+ state = RealBrowserState.__new__(RealBrowserState)
+ state.pw = AsyncMock()
+ state.browser_context = MagicMock()
+ state.engine_selection = MagicMock()
+ state.engine_selection.start_driver = AsyncMock(return_value=AsyncMock())
+ state.set_working_page = AsyncMock()
+ state.browser_artifacts = BrowserArtifacts(download_binding=binding)
+
+ async def _capture(**kwargs: object) -> None:
+ captured.update(kwargs)
+
+ state.check_and_fix_state = _capture # type: ignore[method-assign]
+ return state
+
+
+async def test_reconnect_threads_session_dir_binding_into_check_and_fix_state() -> None:
+ """Metadata restore alone is not enough — reconnect must hand the SESSION_DIR binding to
+ check_and_fix_state so the factory skips the run-dir setDownloadBehavior rebind and preserves the
+ provider-selected destination instead of re-pointing and relabeling afterward."""
+ captured: dict[str, object] = {}
+ state = _reconnect_state_capturing_check(DownloadBinding.SESSION_DIR, captured)
+ await state.reconnect(workflow_run_id="wr-1")
+ assert captured.get("download_binding") == DownloadBinding.SESSION_DIR
+
+
+async def test_reconnect_threads_run_dir_binding_into_check_and_fix_state() -> None:
+ """A RUN_DIR session threads RUN_DIR so the ordinary run-scoped rebind still fires on reconnect."""
+ captured: dict[str, object] = {}
+ state = _reconnect_state_capturing_check(DownloadBinding.RUN_DIR, captured)
+ await state.reconnect(workflow_run_id="wr-1")
+ assert captured.get("download_binding") == DownloadBinding.RUN_DIR
+
+
+def _recreation_state(
+ binding: DownloadBinding, captured: dict[str, object]
+) -> tuple[RealBrowserState, Callable[..., Awaitable[tuple[object, BrowserArtifacts, object]]]]:
+ state = RealBrowserState.__new__(RealBrowserState)
+ state.pw = AsyncMock()
+ state.browser_context = None # force the check_and_fix_state recreation branch
+ state.engine_selection = None
+ state.browser_artifacts = BrowserArtifacts(download_binding=binding)
+ state.set_working_page = AsyncMock()
+ state.get_working_page = AsyncMock(return_value=MagicMock())
+
+ async def _fake_create(_playwright: object, **kwargs: object) -> tuple[object, BrowserArtifacts, object]:
+ captured.update(kwargs)
+ return MagicMock(pages=[MagicMock()]), BrowserArtifacts(), None
+
+ return state, _fake_create
+
+
+async def test_check_and_fix_state_recreation_preserves_session_dir_when_binding_omitted() -> None:
+ """Non-reconnect entry: a recreation entry point (get_or_create_page, retry paths) that calls
+ check_and_fix_state() without an explicit binding must not downgrade a live SESSION_DIR state to the
+ RUN_DIR default and rebind it off the provider-selected destination. The omitted binding derives
+ from the state's own prior artifacts."""
+ captured: dict[str, object] = {}
+ state, fake_create = _recreation_state(DownloadBinding.SESSION_DIR, captured)
+
+ with (
+ patch(
+ "skyvern.webeye.real_browser_state.BrowserContextFactory.create_browser_context",
+ new=fake_create,
+ ),
+ patch("skyvern.webeye.real_browser_state.skyvern_context.current", return_value=None),
+ ):
+ await state.check_and_fix_state(workflow_run_id="wr-1")
+
+ assert captured.get("download_binding") == DownloadBinding.SESSION_DIR
+
+
+async def test_check_and_fix_state_recreation_defaults_run_dir_for_run_dir_state() -> None:
+ """A RUN_DIR state omitting the binding still recreates as RUN_DIR — the sticky-derive must not
+ accidentally promote ordinary local/OSS/vendor states to SESSION_DIR."""
+ captured: dict[str, object] = {}
+ state, fake_create = _recreation_state(DownloadBinding.RUN_DIR, captured)
+
+ with (
+ patch(
+ "skyvern.webeye.real_browser_state.BrowserContextFactory.create_browser_context",
+ new=fake_create,
+ ),
+ patch("skyvern.webeye.real_browser_state.skyvern_context.current", return_value=None),
+ ):
+ await state.check_and_fix_state(workflow_run_id="wr-1")
+
+ assert captured.get("download_binding") == DownloadBinding.RUN_DIR
+
+
+async def test_check_and_fix_state_explicit_binding_overrides_prior_artifacts() -> None:
+ """An explicit binding still wins over the derived one (reconnect passes prior_download_binding)."""
+ captured: dict[str, object] = {}
+ state, fake_create = _recreation_state(DownloadBinding.RUN_DIR, captured)
+
+ with (
+ patch(
+ "skyvern.webeye.real_browser_state.BrowserContextFactory.create_browser_context",
+ new=fake_create,
+ ),
+ patch("skyvern.webeye.real_browser_state.skyvern_context.current", return_value=None),
+ ):
+ await state.check_and_fix_state(workflow_run_id="wr-1", download_binding=DownloadBinding.SESSION_DIR)
+
+ assert captured.get("download_binding") == DownloadBinding.SESSION_DIR
+
+
+async def test_check_and_fix_state_recreation_stamps_forwarded_binding_on_assigned_artifacts() -> None:
+ """Outer contract: on recreation, check_and_fix_state forwards the derived binding and the factory
+ stamps it on the fresh artifacts, so the state ends up SESSION_DIR — with no later override that
+ could mislabel a genuine provider change."""
+ state = RealBrowserState.__new__(RealBrowserState)
+ state.pw = AsyncMock()
+ state.browser_context = None
+ state.engine_selection = None
+ state.browser_artifacts = BrowserArtifacts(download_binding=DownloadBinding.SESSION_DIR)
+ state.set_working_page = AsyncMock()
+ state.get_working_page = AsyncMock(return_value=MagicMock())
+
+ async def _factory_stamps(_playwright: object, **kwargs: object) -> tuple[object, BrowserArtifacts, object]:
+ forwarded = kwargs.get("download_binding")
+ stamped = forwarded if isinstance(forwarded, DownloadBinding) else DownloadBinding.RUN_DIR
+ return MagicMock(pages=[MagicMock()]), BrowserArtifacts(download_binding=stamped), None
+
+ with (
+ patch(
+ "skyvern.webeye.real_browser_state.BrowserContextFactory.create_browser_context",
+ new=_factory_stamps,
+ ),
+ patch("skyvern.webeye.real_browser_state.skyvern_context.current", return_value=None),
+ ):
+ await state.check_and_fix_state(workflow_run_id="wr-1")
+
+ assert state.browser_artifacts.download_binding == DownloadBinding.SESSION_DIR