Skip to content

Automate browser based workflows with AI

SKY-15305: Bind delayed session downloads into build-test output (#8358)

Andrew Neilson1e61a8b9c9b3
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index ce8345149..9307d3bea 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -239,10 +239,18 @@ class CodeBlockEngineFailure:
accepted_user_defined_error: UserDefinedError | None = None
+@dataclass(frozen=True)
+class CodeBlockDownloadOperationReceipt:
+ """Structured proof that the secure runner invoked the brokered download operation."""
+
+ operation: Literal["click_and_claim_download"] = "click_and_claim_download"
+
+
@dataclass
class CodeBlockEngineResult:
block_result: BlockResult | None
failure: CodeBlockEngineFailure | None
+ download_operation_receipt: CodeBlockDownloadOperationReceipt | None = None
def _remove_rect(element: dict) -> None:
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 05d1c0a0d..5a5060802 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -5105,6 +5105,7 @@ async def wrapper({default_args}):
session_bound: bool = False,
download_run_id: str | None = None,
download_binding_kind: str | None = None,
+ download_operation_invoked: bool = False,
) -> tuple[list[FileInfo] | None, set[str]]:
"""Register downloads, recording what the registered directory held on either side.
@@ -5123,6 +5124,7 @@ async def wrapper({default_args}):
workflow_run_block_id=workflow_run_block_id,
session_bound=session_bound,
download_run_id=download_run_id,
+ download_operation_invoked=download_operation_invoked,
)
finally:
with contained_effect(
@@ -5158,6 +5160,7 @@ async def wrapper({default_args}):
workflow_run_block_id: str,
session_bound: bool = False,
download_run_id: str | None = None,
+ download_operation_invoked: bool = False,
) -> tuple[list[FileInfo] | None, set[str]]:
"""Registered downloads, plus the names of files whose save storage skipped.
@@ -5224,6 +5227,7 @@ async def wrapper({default_args}):
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
run_id=storage_run_id,
+ download_operation_invoked=download_operation_invoked,
)
or registered_files
)
@@ -5236,12 +5240,14 @@ async def wrapper({default_args}):
workflow_run_id: str,
workflow_run_block_id: str,
run_id: str,
+ download_operation_invoked: bool = False,
) -> list[FileInfo] | None:
- """Registered downloads once an in-flight one lands, or ``None`` when none was in flight.
+ """Return a session download once its final watcher row becomes visible.
The watcher drops the partial's artifact row on Chrome's rename and writes the final row from
- the same event batch, in either order, so a vanished partial does not prove the final row is
- committed yet — hence the settle poll rather than a single re-read."""
+ the same event batch, in either order. A visible partial or a typed broker receipt therefore
+ authorizes the same bounded settle poll; neither a vanished partial nor completed browser
+ bytes alone prove that the final artifact row is committed."""
context = skyvern_context.current()
browser_session_id = context.browser_session_id if context else None
if not browser_session_id:
@@ -5251,18 +5257,19 @@ async def wrapper({default_args}):
organization_id=organization_id,
browser_session_id=browser_session_id,
)
- if not in_flight:
+ if not in_flight and not download_operation_invoked:
return None
- LOG.info(
- "Code block finished with a session download still in flight; waiting for it",
- workflow_run_id=workflow_run_id,
- workflow_run_block_id=workflow_run_block_id,
- browser_session_id=browser_session_id,
- in_flight_count=len(in_flight),
- )
- await wait_for_download_finished(
- downloading_files=in_flight, timeout=_CODE_BLOCK_SESSION_DOWNLOAD_WAIT_SECONDS
- )
+ if in_flight:
+ LOG.info(
+ "Code block finished with a session download still in flight; waiting for it",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ browser_session_id=browser_session_id,
+ in_flight_count=len(in_flight),
+ )
+ await wait_for_download_finished(
+ downloading_files=in_flight, timeout=_CODE_BLOCK_SESSION_DOWNLOAD_WAIT_SECONDS
+ )
for _ in range(_CODE_BLOCK_SESSION_DOWNLOAD_SETTLE_ATTEMPTS):
await self._claim_session_download_artifacts(
organization_id=organization_id,
@@ -7226,6 +7233,9 @@ async def wrapper({default_args}):
workflow_run_block_id=workflow_run_block_id,
session_bound=session_download_lane_active(browser_state),
download_run_id=resolved_download_id,
+ download_operation_invoked=(
+ secure_code_block_result.download_operation_receipt is not None
+ ),
)
secure_output, binding_failure_reason = await self._bind_and_grade_downloads(
engine="secure_runner",
diff --git a/tests/unit/test_code_block_downloads.py b/tests/unit/test_code_block_downloads.py
index 2467f6a89..881d200ec 100644
--- a/tests/unit/test_code_block_downloads.py
+++ b/tests/unit/test_code_block_downloads.py
@@ -38,6 +38,7 @@ from skyvern.forge.sdk.copilot.reached_download_target import (
block_output_has_registered_download,
code_is_download_intent,
)
+from skyvern.forge.sdk.copilot.tools.run_execution import build_test_evidence_packet
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.http_request_authorization import RunScopedRedirectHopAuthorizer
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
@@ -54,6 +55,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (
from skyvern.schemas.workflows import BlockResult, BlockStatus
from skyvern.webeye.browser_artifacts import BrowserArtifacts, DownloadBinding
from skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptor
+from tests.unit.copilot_test_helpers import make_copilot_ctx
_BLOCK_CREATED_AT = datetime(2026, 6, 14, 11, 0, tzinfo=UTC)
@@ -144,6 +146,7 @@ def _wire_secure_runner(
output: dict,
on_execute: Callable[[], None] | None = None,
downgrade: bool = False,
+ download_operation_invoked: bool = False,
) -> None:
"""Route execute() down the secure sidecar arm, whose returned payload is what the host binds.
@@ -162,7 +165,11 @@ def _wire_secure_runner(
on_execute()
if downgrade:
return None
- return SimpleNamespace(block_result=block_result, failure=None)
+ return SimpleNamespace(
+ block_result=block_result,
+ failure=None,
+ download_operation_receipt=object() if download_operation_invoked else None,
+ )
fake_app = block_module.app
fake_app.AGENT_FUNCTION.should_use_codeblock_runner = AsyncMock(return_value=True)
@@ -2300,6 +2307,146 @@ async def test_secure_runner_session_download_reaches_registration(
assert result.output_parameter_value["downloaded_file_urls"] == [_SESSION_FILE.url]
+async def test_secure_runner_typed_download_waits_for_delayed_final_session_row(
+ monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str
+) -> None:
+ """A completed typed download is sufficient reason to settle a delayed final watcher row even
+ after its partial marker has disappeared. The first empty read must not end the custody handoff."""
+ skyvern_context.set(_session_context())
+
+ # Baseline read, host pre-registration read, and first registration read are empty. The
+ # watcher row becomes visible only to the receipt-gated settle attempt.
+ reads = [[], [], [], [_SESSION_FILE]]
+
+ async def _get(**_kwargs: object) -> list[FileInfo]:
+ return reads.pop(0) if len(reads) > 1 else list(reads[0])
+
+ claim = AsyncMock(return_value=1)
+ in_flight = AsyncMock(return_value=[])
+ _fake_storage_app(
+ monkeypatch,
+ save=AsyncMock(),
+ get=AsyncMock(side_effect=_get),
+ claim=claim,
+ in_flight=in_flight,
+ )
+ _artifact_first_downloads(monkeypatch, enabled=True)
+ _wire_block_runtime(monkeypatch, download_binding=DownloadBinding.SESSION_DIR)
+ _wire_secure_runner(
+ monkeypatch,
+ output={"status": "ok"},
+ download_operation_invoked=True,
+ )
+
+ block = CodeBlock(
+ label="download_statement",
+ code='await click_and_claim_download(page, "a.download")',
+ output_parameter=_output_parameter("code_out"),
+ )
+ result = await block.execute(workflow_run_id="wr_1", workflow_run_block_id="", organization_id="o_1")
+
+ in_flight.assert_awaited_once()
+ assert claim.await_count == 2
+ assert result.success is True
+ assert result.output_parameter_value["downloaded_file_urls"] == [_SESSION_FILE.url]
+ assert result.output_parameter_value["downloaded_file_artifact_ids"] == [_SESSION_FILE.artifact_id]
+ persisted = _persisted_output()
+ assert isinstance(persisted, dict)
+ assert persisted["downloaded_file_artifact_ids"] == [_SESSION_FILE.artifact_id]
+
+ packet = build_test_evidence_packet(
+ make_copilot_ctx(),
+ {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_1",
+ "overall_status": "completed",
+ "requested_block_labels": ["download_statement"],
+ "executed_block_labels": ["download_statement"],
+ "blocks": [
+ {
+ "label": "download_statement",
+ "status": "completed",
+ "extracted_data": persisted,
+ }
+ ],
+ },
+ },
+ )
+ assert [download.artifact_id for download in packet.downloads] == [_SESSION_FILE.artifact_id]
+
+
+async def test_secure_runner_without_typed_download_does_not_settle_an_empty_session_row(
+ monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str
+) -> None:
+ skyvern_context.set(_session_context())
+
+ sleep = AsyncMock()
+ monkeypatch.setattr(block_module.asyncio, "sleep", sleep)
+ claim = AsyncMock(return_value=0)
+ _fake_storage_app(
+ monkeypatch,
+ save=AsyncMock(),
+ get=AsyncMock(return_value=[]),
+ claim=claim,
+ in_flight=AsyncMock(return_value=[]),
+ )
+ _artifact_first_downloads(monkeypatch, enabled=True)
+ _wire_block_runtime(monkeypatch, download_binding=DownloadBinding.SESSION_DIR)
+ _wire_secure_runner(monkeypatch, output={"status": "ok"})
+
+ block = CodeBlock(
+ label="read_page",
+ code="return {'status': 'ok'}",
+ output_parameter=_output_parameter("code_out"),
+ )
+ result = await block.execute(workflow_run_id="wr_1", workflow_run_block_id="", organization_id="o_1")
+
+ sleep.assert_not_awaited()
+ assert claim.await_count == 1
+ assert result.success is True
+ assert "downloaded_file_artifact_ids" not in result.output_parameter_value
+
+
+async def test_secure_runner_typed_download_with_no_final_row_is_bounded_and_invents_nothing(
+ monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str
+) -> None:
+ skyvern_context.set(_session_context())
+
+ sleep = AsyncMock()
+ monkeypatch.setattr(block_module.asyncio, "sleep", sleep)
+ claim = AsyncMock(return_value=0)
+ _fake_storage_app(
+ monkeypatch,
+ save=AsyncMock(),
+ get=AsyncMock(return_value=[]),
+ claim=claim,
+ in_flight=AsyncMock(return_value=[]),
+ )
+ _artifact_first_downloads(monkeypatch, enabled=True)
+ _wire_block_runtime(monkeypatch, download_binding=DownloadBinding.SESSION_DIR)
+ _wire_secure_runner(
+ monkeypatch,
+ output={"status": "ok"},
+ download_operation_invoked=True,
+ )
+
+ block = CodeBlock(
+ label="download_statement",
+ code='await click_and_claim_download(page, "a.download")',
+ output_parameter=_output_parameter("code_out"),
+ )
+ result = await block.execute(workflow_run_id="wr_1", workflow_run_block_id="", organization_id="o_1")
+
+ assert claim.await_count == 1 + block_module._CODE_BLOCK_SESSION_DOWNLOAD_SETTLE_ATTEMPTS
+ assert sleep.await_count == block_module._CODE_BLOCK_SESSION_DOWNLOAD_SETTLE_ATTEMPTS
+ assert result.success is True
+ assert "downloaded_file_artifact_ids" not in result.output_parameter_value
+
+
@pytest.mark.asyncio
async def test_in_flight_partial_is_never_bound_as_the_users_file(
monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str
diff --git a/tests/unit/test_copilot_build_test_outcome.py b/tests/unit/test_copilot_build_test_outcome.py
index 0a5a66693..62b287778 100644
--- a/tests/unit/test_copilot_build_test_outcome.py
+++ b/tests/unit/test_copilot_build_test_outcome.py
@@ -119,6 +119,31 @@ def test_run_blocks_outcome_records_requested_labels_and_shape_hashes() -> None:
assert outcome.block_shape_hashes == {"open": "h1", "search": "h2", "extract": "h3"}
+def test_registered_block_download_reaches_packet_without_parseable_artifact_evidence() -> None:
+ ctx = make_copilot_ctx()
+ ctx.registered_artifact_evidence = None
+ result = {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_1",
+ "overall_status": "completed",
+ "requested_block_labels": ["download_statement"],
+ "executed_block_labels": ["download_statement"],
+ "blocks": [
+ {
+ "label": "download_statement",
+ "status": "completed",
+ "extracted_data": {"downloaded_file_artifact_ids": ["a_dl_9"]},
+ }
+ ],
+ },
+ }
+
+ packet = build_test_evidence_packet(ctx, result)
+
+ assert [(download.artifact_id, download.file_name) for download in packet.downloads] == [("a_dl_9", None)]
+
+
def test_connect_failure_projects_through_recorded_outcome_and_packet() -> None:
ctx = make_copilot_ctx()
ctx.workflow_yaml = "title: preserved draft"