Skip to content

Automate browser based workflows with AI

Route vendor hosted-browser sessions through the CDP proxy behind a flag (#7675)

Aaron Perez2d0a6f64a016
diff --git a/skyvern/forge/sdk/artifact/models.py b/skyvern/forge/sdk/artifact/models.py
index da306f728..b968ce7fd 100644
--- a/skyvern/forge/sdk/artifact/models.py
+++ b/skyvern/forge/sdk/artifact/models.py
@@ -27,6 +27,7 @@ class ArtifactType(StrEnum):
SCREENSHOT_LLM = "screenshot_llm"
SCREENSHOT_ACTION = "screenshot_action"
SCREENSHOT_FINAL = "screenshot_final"
+ SCREENSHOT_PROXY = "screenshot_proxy"
LLM_PROMPT = "llm_prompt"
LLM_REQUEST = "llm_request"
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index b6b83a3b0..b1929ca63 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -1308,8 +1308,8 @@ class PersistentBrowserSessionModel(Base):
ip_address = Column(String, nullable=True)
ecs_task_arn = Column(String, nullable=True)
# Server-side CDP routing. browser_address stays the client-facing proxy URL; these name the
- # upstream the proxy dials and the adapter that dials it. Never a credential — connect-time
- # credentials come from env — and never returned to clients (BrowserSessionResponse.
+ # upstream the proxy dials and the adapter that dials it. Never a long-lived operator
+ # credential; may carry a session-scoped token. Never returned to clients (BrowserSessionResponse.
# from_browser_session allowlists the client-facing fields).
upstream_cdp_url = Column(String, nullable=True)
browser_vendor = Column(String, nullable=True)
diff --git a/skyvern/forge/sdk/db/repositories/browser_sessions.py b/skyvern/forge/sdk/db/repositories/browser_sessions.py
index 804ffcc5c..f4384ad78 100644
--- a/skyvern/forge/sdk/db/repositories/browser_sessions.py
+++ b/skyvern/forge/sdk/db/repositories/browser_sessions.py
@@ -42,6 +42,15 @@ from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput
LOG = structlog.get_logger()
_UNSET = object()
+# A row with an upstream endpoint but no client-facing address yet is vendor-held (the vendor
+# owns the browser directly; the CDP proxy is the only way to reach it) and must stay off
+# customer-facing session surfaces. Self-hosted routed rows set both columns together, and
+# rows created before routing existed set neither — both cases stay visible.
+_VISIBLE_TO_CUSTOMER = or_(
+ PersistentBrowserSessionModel.upstream_cdp_url.is_(None),
+ PersistentBrowserSessionModel.browser_address.isnot(None),
+)
+
class BrowserSessionsRepository(BaseRepository):
"""Database operations for browser profiles and persistent browser sessions."""
@@ -441,6 +450,7 @@ class BrowserSessionsRepository(BaseRepository):
.filter_by(deleted_at=None)
.filter_by(completed_at=None)
.filter(PersistentBrowserSessionModel.created_at > naive_utc_now() - timedelta(hours=active_hours))
+ .filter(_VISIBLE_TO_CUSTOMER)
)
sessions = result.scalars().all()
return [PersistentBrowserSession.model_validate(session) for session in sessions]
@@ -468,6 +478,7 @@ class BrowserSessionsRepository(BaseRepository):
.filter_by(organization_id=organization_id)
.filter_by(deleted_at=None)
.filter(PersistentBrowserSessionModel.created_at > (naive_utc_now() - timedelta(hours=lookback_hours)))
+ .filter(_VISIBLE_TO_CUSTOMER)
.order_by(
open_first.asc(), # open sessions first
PersistentBrowserSessionModel.created_at.desc(), # then newest within each group
@@ -496,6 +507,7 @@ class BrowserSessionsRepository(BaseRepository):
.filter_by(organization_id=organization_id)
.filter_by(deleted_at=None)
.filter(PersistentBrowserSessionModel.created_at > (naive_utc_now() - timedelta(hours=lookback_hours)))
+ .filter(_VISIBLE_TO_CUSTOMER)
)
return (await session.execute(count_query)).scalar_one()
@@ -564,6 +576,34 @@ class BrowserSessionsRepository(BaseRepository):
await session.refresh(browser_session)
return PersistentBrowserSession.model_validate(browser_session)
+ @db_operation("create_vendor_cdp_browser_session")
+ async def create_vendor_cdp_browser_session(
+ self,
+ *,
+ organization_id: str,
+ upstream_cdp_url: str,
+ browser_vendor: str,
+ browser_id: str,
+ timeout_minutes: int,
+ ) -> PersistentBrowserSession:
+ """Create a row for a session the vendor already owns and holds directly, reachable only
+ through the CDP proxy. browser_address and runnable_* stay NULL so the row is excluded
+ from customer-facing session surfaces (see _VISIBLE_TO_CUSTOMER)."""
+ async with self.Session() as session:
+ browser_session = PersistentBrowserSessionModel(
+ organization_id=organization_id,
+ status="running",
+ started_at=naive_utc_now(),
+ timeout_minutes=timeout_minutes,
+ upstream_cdp_url=upstream_cdp_url,
+ browser_vendor=browser_vendor,
+ browser_id=browser_id,
+ )
+ session.add(browser_session)
+ await session.commit()
+ await session.refresh(browser_session)
+ return PersistentBrowserSession.model_validate(browser_session)
+
@db_operation("get_persistent_browser_session_unscoped")
async def get_persistent_browser_session_unscoped(self, session_id: str) -> PersistentBrowserSession | None:
"""Primary-key read without organization scoping, for trusted internal session
@@ -701,8 +741,8 @@ class BrowserSessionsRepository(BaseRepository):
"""Set the browser address for a persistent browser session.
browser_address is the client-facing (proxied) URL; upstream_cdp_url is the endpoint the
- CDP proxy dials and must never be handed to a client or carry a credential — connect-time
- credentials are injected from env at dial time.
+ CDP proxy dials and must never be handed to a client. It is never a long-lived operator
+ credential, though it may carry a session-scoped token.
"""
async with self.Session() as session:
persistent_browser_session = (
diff --git a/tests/unit/test_browser_session_address_write.py b/tests/unit/test_browser_session_address_write.py
index 95abe3d80..b1ccaffaf 100644
--- a/tests/unit/test_browser_session_address_write.py
+++ b/tests/unit/test_browser_session_address_write.py
@@ -1,15 +1,22 @@
-"""Tests for BrowserSessionsRepository.set_persistent_browser_session_browser_address()."""
+"""Tests for BrowserSessionsRepository routing-column behavior: address writes, vendor-held
+session creation, and customer-facing visibility filtering."""
-from unittest.mock import MagicMock
+from datetime import datetime
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now
+from skyvern.forge.sdk.db.models import Base, PersistentBrowserSessionModel
from skyvern.forge.sdk.db.repositories.browser_sessions import BrowserSessionsRepository
from tests.unit.conftest import MockAsyncSessionCtx, make_mock_session
UPSTREAM = "ws://10.0.0.7:9222/devtools/browser/b1"
PROXIED = "wss://proxy.example/pbs_123/token/devtools/browser/b1"
+VENDOR_UPSTREAM = "wss://connect.vendor.example?sessionId=deadbeef-1234"
+ORG_ID = "org_test"
async def _write_address(mock_session: MagicMock) -> None:
@@ -49,3 +56,118 @@ async def test_failed_address_write_never_renders_the_upstream_in_the_error() ->
await _write_address(mock_session)
assert UPSTREAM not in str(excinfo.value)
+
+
+async def test_create_vendor_cdp_browser_session_insert_shape() -> None:
+ """The vendor-held row is a single INSERT: running, timed, upstream-addressed, and left with
+ no client-facing address or runnable binding."""
+ mock_session = AsyncMock()
+ mock_session.add = MagicMock()
+ mock_session.commit = AsyncMock()
+ mock_session.refresh = AsyncMock()
+ repo = BrowserSessionsRepository(session_factory=lambda: MockAsyncSessionCtx(mock_session))
+
+ def _validate(model: object) -> MagicMock:
+ validated = MagicMock()
+ validated.status = model.status
+ validated.upstream_cdp_url = model.upstream_cdp_url
+ return validated
+
+ with patch(
+ "skyvern.forge.sdk.schemas.persistent_browser_sessions.PersistentBrowserSession.model_validate",
+ side_effect=_validate,
+ ):
+ result = await repo.create_vendor_cdp_browser_session(
+ organization_id=ORG_ID,
+ upstream_cdp_url=VENDOR_UPSTREAM,
+ browser_vendor="websocket",
+ browser_id="vendor-sess-1",
+ timeout_minutes=240,
+ )
+
+ inserted = mock_session.add.call_args.args[0]
+ assert inserted.organization_id == ORG_ID
+ assert inserted.status == "running"
+ assert inserted.started_at is not None
+ assert inserted.timeout_minutes == 240
+ assert inserted.upstream_cdp_url == VENDOR_UPSTREAM
+ assert inserted.browser_vendor == "websocket"
+ assert inserted.browser_id == "vendor-sess-1"
+ assert inserted.browser_address is None
+ assert inserted.runnable_type is None
+ assert inserted.runnable_id is None
+ assert result.status == "running"
+ assert result.upstream_cdp_url == VENDOR_UPSTREAM
+
+
+def _session_row(
+ session_id: str,
+ *,
+ upstream_cdp_url: str | None,
+ browser_address: str | None,
+ status: str = "running",
+ completed_at: datetime | None = None,
+) -> PersistentBrowserSessionModel:
+ now = naive_utc_now()
+ return PersistentBrowserSessionModel(
+ persistent_browser_session_id=session_id,
+ organization_id=ORG_ID,
+ status=status,
+ created_at=now,
+ started_at=now,
+ completed_at=completed_at,
+ upstream_cdp_url=upstream_cdp_url,
+ browser_address=browser_address,
+ )
+
+
+async def _repo_with_visibility_rows() -> BrowserSessionsRepository:
+ """A real (in-memory) engine, not a mock — the exclusion predicate is a SQL WHERE clause, and
+ a mocked session can't tell us whether it actually filters rows."""
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all, tables=[PersistentBrowserSessionModel.__table__])
+ session_factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with session_factory() as session:
+ session.add_all(
+ [
+ # Vendor-held: upstream set, no client-facing address yet — must be hidden.
+ _session_row("pbs_vendor", upstream_cdp_url=VENDOR_UPSTREAM, browser_address=None),
+ # Self-hosted routed: both set — still visible.
+ _session_row("pbs_self_hosted", upstream_cdp_url=UPSTREAM, browser_address=PROXIED),
+ # Pre-routing / legacy: neither set — still visible.
+ _session_row("pbs_pending", upstream_cdp_url=None, browser_address=None),
+ ]
+ )
+ await session.commit()
+ return BrowserSessionsRepository(session_factory=session_factory)
+
+
+async def test_get_active_sessions_hides_vendor_held_rows() -> None:
+ repo = await _repo_with_visibility_rows()
+
+ sessions = await repo.get_active_persistent_browser_sessions(ORG_ID)
+
+ ids = {session.persistent_browser_session_id for session in sessions}
+ assert ids == {"pbs_self_hosted", "pbs_pending"}
+
+
+async def test_get_history_hides_vendor_held_rows() -> None:
+ repo = await _repo_with_visibility_rows()
+
+ sessions = await repo.get_persistent_browser_sessions_history(ORG_ID)
+
+ ids = {session.persistent_browser_session_id for session in sessions}
+ assert ids == {"pbs_self_hosted", "pbs_pending"}
+
+
+async def test_get_history_count_hides_vendor_held_rows() -> None:
+ repo = await _repo_with_visibility_rows()
+
+ count = await repo.get_persistent_browser_sessions_history_count(ORG_ID)
+
+ assert count == 2