Skip to content

Automate browser based workflows with AI

Only upload live-view screenshots while someone is actually watching (#7677)

pedrohsdb9af227c6e539
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index a7c6c94ec..d087cfeae 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -806,6 +806,20 @@ class AgentFunction:
routers so the default returns False."""
return False
+ async def mark_streaming_viewer_active(self, organization_id: str, file_name: str) -> None:
+ """Record that a live-view consumer is currently polling this stream key.
+
+ Cloud overrides this with a TTL'd presence marker that frame publishers
+ consult via should_publish_streaming_frame. OSS no-op: frames always publish."""
+ return None
+
+ async def should_publish_streaming_frame(self, organization_id: str, file_name: str) -> bool:
+ """Whether a frame publisher should capture+upload a frame for this stream key.
+
+ Cloud gates this on viewer presence so unwatched runs skip uploads entirely.
+ OSS default keeps the historical always-publish behavior."""
+ return True
+
async def resolve_recording_video_size(
self,
current_size: dict[str, int] | None,
diff --git a/skyvern/forge/sdk/artifact/storage/azure.py b/skyvern/forge/sdk/artifact/storage/azure.py
index e4d0d1d6a..6edb7f437 100644
--- a/skyvern/forge/sdk/artifact/storage/azure.py
+++ b/skyvern/forge/sdk/artifact/storage/azure.py
@@ -169,7 +169,7 @@ class AzureStorage(BaseStorage):
)
await self.async_client.upload_file_from_path(artifact.uri, path, tier=tier, tags=tags)
- async def save_streaming_file(self, organization_id: str, file_name: str) -> None:
+ async def save_streaming_file(self, organization_id: str, file_name: str) -> bool | None:
from_path = f"{get_skyvern_temp_dir()}/{organization_id}/{file_name}"
to_path = f"azure://{settings.AZURE_STORAGE_CONTAINER_SCREENSHOTS}/{settings.ENV}/{organization_id}/{file_name}"
tier = await self._get_storage_tier_for_org(organization_id)
@@ -184,6 +184,7 @@ class AzureStorage(BaseStorage):
tags=tags,
)
await self.async_client.upload_file_from_path(to_path, from_path, tier=tier, tags=tags)
+ return None
async def get_streaming_file(self, organization_id: str, file_name: str, use_default: bool = True) -> bytes | None:
path = f"azure://{settings.AZURE_STORAGE_CONTAINER_SCREENSHOTS}/{settings.ENV}/{organization_id}/{file_name}"
diff --git a/skyvern/forge/sdk/artifact/storage/base.py b/skyvern/forge/sdk/artifact/storage/base.py
index df115f2ea..102642fb7 100644
--- a/skyvern/forge/sdk/artifact/storage/base.py
+++ b/skyvern/forge/sdk/artifact/storage/base.py
@@ -173,8 +173,9 @@ class BaseStorage(ABC):
pass
@abstractmethod
- async def save_streaming_file(self, organization_id: str, file_name: str) -> None:
- pass
+ async def save_streaming_file(self, organization_id: str, file_name: str) -> bool | None:
+ """None/True means the frame was uploaded; False means a gate intentionally skipped it,
+ so callers must not record a skipped frame as published."""
@abstractmethod
async def get_streaming_file(self, organization_id: str, file_name: str) -> bytes | None:
diff --git a/skyvern/forge/sdk/artifact/storage/gcs.py b/skyvern/forge/sdk/artifact/storage/gcs.py
index febb30f0a..891129133 100644
--- a/skyvern/forge/sdk/artifact/storage/gcs.py
+++ b/skyvern/forge/sdk/artifact/storage/gcs.py
@@ -173,7 +173,7 @@ class GcsStorage(BaseStorage):
)
await self.async_client.upload_file_from_path(artifact.uri, path, storage_class=storage_class, tags=tags)
- async def save_streaming_file(self, organization_id: str, file_name: str) -> None:
+ async def save_streaming_file(self, organization_id: str, file_name: str) -> bool | None:
from_path = f"{get_skyvern_temp_dir()}/{organization_id}/{file_name}"
to_path = f"gs://{settings.GCS_BUCKET_SCREENSHOTS}/{settings.ENV}/{organization_id}/{file_name}"
storage_class = await self._get_storage_class_for_org(organization_id)
@@ -188,6 +188,7 @@ class GcsStorage(BaseStorage):
tags=tags,
)
await self.async_client.upload_file_from_path(to_path, from_path, storage_class=storage_class, tags=tags)
+ return None
async def get_streaming_file(self, organization_id: str, file_name: str, use_default: bool = True) -> bytes | None:
path = f"gs://{settings.GCS_BUCKET_SCREENSHOTS}/{settings.ENV}/{organization_id}/{file_name}"
diff --git a/skyvern/forge/sdk/artifact/storage/local.py b/skyvern/forge/sdk/artifact/storage/local.py
index 29339a14c..f762ae22a 100644
--- a/skyvern/forge/sdk/artifact/storage/local.py
+++ b/skyvern/forge/sdk/artifact/storage/local.py
@@ -181,8 +181,8 @@ class LocalStorage(BaseStorage):
async def get_share_links(self, artifacts: list[Artifact]) -> list[str] | None:
return [artifact.uri for artifact in artifacts] or None
- async def save_streaming_file(self, organization_id: str, file_name: str) -> None:
- return
+ async def save_streaming_file(self, organization_id: str, file_name: str) -> bool | None:
+ return None
async def get_streaming_file(self, organization_id: str, file_name: str) -> bytes | None:
# make the directory if it doesn't exist
diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.py
index b3a1d2711..6092f626f 100644
--- a/skyvern/forge/sdk/artifact/storage/s3.py
+++ b/skyvern/forge/sdk/artifact/storage/s3.py
@@ -242,7 +242,7 @@ class S3Storage(BaseStorage):
)
await self.async_client.upload_file_from_path(artifact.uri, path, storage_class=sc)
- async def save_streaming_file(self, organization_id: str, file_name: str) -> None:
+ async def save_streaming_file(self, organization_id: str, file_name: str) -> bool | None:
from_path = f"{get_skyvern_temp_dir()}/{organization_id}/{file_name}"
to_path = f"s3://{settings.AWS_S3_BUCKET_SCREENSHOTS}/{settings.ENV}/{organization_id}/{file_name}"
sc = await self._get_storage_class_for_org(organization_id, settings.AWS_S3_BUCKET_SCREENSHOTS)
@@ -255,6 +255,7 @@ class S3Storage(BaseStorage):
storage_class=sc,
)
await self.async_client.upload_file_from_path(to_path, from_path, storage_class=sc)
+ return None
async def get_streaming_file(self, organization_id: str, file_name: str, use_default: bool = True) -> bytes | None:
path = f"s3://{settings.AWS_S3_BUCKET_SCREENSHOTS}/{settings.ENV}/{organization_id}/{file_name}"
diff --git a/skyvern/forge/sdk/routes/streaming/screenshot.py b/skyvern/forge/sdk/routes/streaming/screenshot.py
index 0876c9473..6ce17c33d 100644
--- a/skyvern/forge/sdk/routes/streaming/screenshot.py
+++ b/skyvern/forge/sdk/routes/streaming/screenshot.py
@@ -29,6 +29,7 @@ from skyvern.forge.sdk.schemas.persistent_browser_sessions import is_final_statu
from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.forge.sdk.services.org_auth_service import get_current_org
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.webeye.cdp_frame_publisher import stream_key_for_task, stream_key_for_workflow_run
LOG = structlog.get_logger()
STREAMING_TIMEOUT = 300
@@ -112,9 +113,10 @@ async def task_stream(
return
if task.status == TaskStatus.running:
- file_name = f"{task_id}.png"
+ file_name = stream_key_for_task(task_id)
if task.workflow_run_id:
- file_name = f"{task.workflow_run_id}.png"
+ file_name = stream_key_for_workflow_run(task.workflow_run_id)
+ await app.AGENT_FUNCTION.mark_streaming_viewer_active(organization_id, file_name)
screenshot = await app.STORAGE.get_streaming_file(organization_id, file_name)
if screenshot:
encoded_screenshot = base64.b64encode(screenshot).decode("utf-8")
@@ -247,7 +249,8 @@ async def workflow_run_streaming(
return
if workflow_run.status in (WorkflowRunStatus.running, WorkflowRunStatus.paused):
- file_name = f"{workflow_run_id}.png"
+ file_name = stream_key_for_workflow_run(workflow_run_id)
+ await app.AGENT_FUNCTION.mark_streaming_viewer_active(organization_id, file_name)
screenshot = await app.STORAGE.get_streaming_file(organization_id, file_name)
if screenshot:
encoded_screenshot = base64.b64encode(screenshot).decode("utf-8")
diff --git a/skyvern/webeye/cdp_frame_publisher.py b/skyvern/webeye/cdp_frame_publisher.py
index 88ba99e95..dad3d293c 100644
--- a/skyvern/webeye/cdp_frame_publisher.py
+++ b/skyvern/webeye/cdp_frame_publisher.py
@@ -109,6 +109,9 @@ class CDPFramePublisher:
# dedupe identical frames without losing a retry on transient upload
# failure.
self._last_published_digest: bytes | None = None
+ # Warn once per publisher on unexpected gate errors so a miswired hook is
+ # visible instead of silently reverting to unconditional publishing.
+ self._warned_gate_failure = False
@property
def stream_key(self) -> str:
@@ -200,6 +203,10 @@ class CDPFramePublisher:
return False
async def _publish_one_frame(self) -> None:
+ # Gate before capture: skipping the CDP screenshot saves browser CPU, not
+ # just the upload. Fail-open — a broken gate must not blank the live view.
+ if not await self._viewer_wants_frames():
+ return
page = await self._browser_state.get_working_page()
if page is None:
return
@@ -266,6 +273,22 @@ class CDPFramePublisher:
# transient upload failure retries instead of getting deduped away.
self._last_published_digest = digest
+ async def _viewer_wants_frames(self) -> bool:
+ try:
+ return bool(
+ await app.AGENT_FUNCTION.should_publish_streaming_frame(self._organization_id, self._stream_key)
+ )
+ except Exception:
+ if not self._warned_gate_failure:
+ self._warned_gate_failure = True
+ LOG.warning(
+ "Streaming gate check failed; publishing unconditionally",
+ stream_key=self._stream_key,
+ organization_id=self._organization_id,
+ exc_info=True,
+ )
+ return True
+
def _log_cdp_open_failure(self, exc: BaseException) -> None:
"""Log a ``new_cdp_session`` failure at the severity its cause warrants.
@@ -293,7 +316,7 @@ class CDPFramePublisher:
)
async def _write_frame(self, data: bytes) -> bool:
- """Persist one frame; True iff both the local write and the upload succeeded."""
+ """Persist one frame; True iff the local write and a real (non-gated) upload both succeeded."""
temp_dir = Path(get_skyvern_temp_dir()) / self._organization_id
try:
# Blocking I/O runs on a worker thread so a large flush does not
@@ -311,7 +334,7 @@ class CDPFramePublisher:
# Local-disk storage reads the temp file directly; remote object-storage
# backends need an explicit upload.
try:
- await app.STORAGE.save_streaming_file(self._organization_id, self._stream_key)
+ upload_result = await app.STORAGE.save_streaming_file(self._organization_id, self._stream_key)
except Exception:
LOG.debug(
"save_streaming_file failed; will retry on next iteration",
@@ -320,6 +343,10 @@ class CDPFramePublisher:
exc_info=True,
)
return False
+ # A gate skip (False) is a normal no-viewer outcome, not a failure: don't advance the
+ # dedupe digest, or an unchanged page could be suppressed when a viewer later attaches.
+ if upload_result is False:
+ return False
return True
async def _detach_cdp_session(self) -> None:
diff --git a/tests/unit/test_worker_cdp_frame_publisher.py b/tests/unit/test_worker_cdp_frame_publisher.py
index c1af532c7..29be61dea 100644
--- a/tests/unit/test_worker_cdp_frame_publisher.py
+++ b/tests/unit/test_worker_cdp_frame_publisher.py
@@ -74,7 +74,10 @@ def streaming_temp_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
@pytest.fixture
def fake_storage(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:
save_mock = AsyncMock()
- fake_app = SimpleNamespace(STORAGE=SimpleNamespace(save_streaming_file=save_mock))
+ fake_app = SimpleNamespace(
+ STORAGE=SimpleNamespace(save_streaming_file=save_mock),
+ AGENT_FUNCTION=SimpleNamespace(should_publish_streaming_frame=AsyncMock(return_value=True)),
+ )
monkeypatch.setattr(publisher_module, "app", fake_app)
return save_mock
@@ -603,3 +606,78 @@ def test_write_frame_atomically_cleans_tempfile_on_replace_failure(
assert not (target_dir / "wr_x.png").exists()
leftovers = [p for p in target_dir.iterdir() if p.name.startswith(".") and p.suffix == ".tmp"]
assert leftovers == []
+
+
+async def test_gate_closed_skips_capture_and_upload(streaming_temp_dir: Path, fake_storage: AsyncMock) -> None:
+ session = _make_cdp_session([b"framebytes"])
+ page = _make_page_with_session(session)
+ pub = CDPFramePublisher(
+ browser_state=_make_browser_state(page),
+ stream_key=STREAM_KEY,
+ organization_id=ORG_ID,
+ )
+ gate = AsyncMock(return_value=False)
+ publisher_module.app.AGENT_FUNCTION = SimpleNamespace(should_publish_streaming_frame=gate)
+
+ await _drive_publish_once(pub)
+
+ gate.assert_awaited_once_with(ORG_ID, STREAM_KEY)
+ page.context.new_cdp_session.assert_not_awaited()
+ fake_storage.assert_not_awaited()
+ assert not _stream_path(streaming_temp_dir).exists()
+
+
+async def test_gate_open_publishes_normally(streaming_temp_dir: Path, fake_storage: AsyncMock) -> None:
+ session = _make_cdp_session([b"framebytes"])
+ page = _make_page_with_session(session)
+ pub = CDPFramePublisher(
+ browser_state=_make_browser_state(page),
+ stream_key=STREAM_KEY,
+ organization_id=ORG_ID,
+ )
+ gate = AsyncMock(return_value=True)
+ publisher_module.app.AGENT_FUNCTION = SimpleNamespace(should_publish_streaming_frame=gate)
+
+ await _drive_publish_once(pub)
+
+ gate.assert_awaited_once_with(ORG_ID, STREAM_KEY)
+ fake_storage.assert_awaited_once_with(ORG_ID, STREAM_KEY)
+
+
+async def test_gate_error_fails_open_and_publishes(streaming_temp_dir: Path, fake_storage: AsyncMock) -> None:
+ session = _make_cdp_session([b"framebytes"])
+ page = _make_page_with_session(session)
+ pub = CDPFramePublisher(
+ browser_state=_make_browser_state(page),
+ stream_key=STREAM_KEY,
+ organization_id=ORG_ID,
+ )
+ gate = AsyncMock(side_effect=RuntimeError("gate backend down"))
+ publisher_module.app.AGENT_FUNCTION = SimpleNamespace(should_publish_streaming_frame=gate)
+
+ await _drive_publish_once(pub)
+
+ fake_storage.assert_awaited_once_with(ORG_ID, STREAM_KEY)
+
+
+async def test_gated_skip_does_not_advance_dedupe_digest(streaming_temp_dir: Path, fake_storage: AsyncMock) -> None:
+ session = _make_cdp_session([b"framebytes"])
+ page = _make_page_with_session(session)
+ pub = CDPFramePublisher(
+ browser_state=_make_browser_state(page),
+ stream_key=STREAM_KEY,
+ organization_id=ORG_ID,
+ )
+ # First save is gated at the storage chokepoint (False), second is a real upload.
+ fake_storage.side_effect = [False, None]
+
+ await _drive_publish_once(pub)
+ assert pub._last_published_digest is None
+
+ await _drive_publish_once(pub)
+ assert pub._last_published_digest is not None
+ assert fake_storage.await_count == 2