Skip to content

Automate browser based workflows with AI

SKY-11093: bind copilot synthesized download blocks so the file actually downloads (#6637)

Andrew Neilson4a2bdc3d0e2e
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index 145662e2b..943021052 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -492,17 +492,14 @@ def synthesize_code_block(
):
# The download affordance is observed in nav_targets, not necessarily a trajectory click, so the
# download is an appended terminal step compiled from the typed target — never an in-place click upgrade.
+ # Awaiting the download value lands the file in the run-scoped downloads dir; the execution-layer
+ # dir-diff registers the single file, so the synthesizer never save_as (which would double-register).
download_var = _unique_key(_DOWNLOAD_VAR_BASE, used_download_vars)
download_obj = _unique_key(f"{download_var}_file", used_download_vars)
lines.append(f"{_INDENT}async with page.expect_download() as {download_var}:")
lines.append(f"{_INDENT * 2}await page.locator({_py_str(reached_download_target.selector)}).click()")
lines.append(f"{_INDENT}{download_obj} = await {download_var}.value")
- # The captured file's parent is the persistent context's downloads_path (the run-scoped download
- # dir), so save_as there materializes a named, scannable file the execution-layer dir-diff registers.
- lines.append(
- f"{_INDENT}await {download_obj}.save_as("
- f"str((await {download_obj}.path()).parent / {download_obj}.suggested_filename))"
- )
+ lines.append(f"{_INDENT}await {download_obj}.path()")
if not lines:
return None
diff --git a/skyvern/forge/sdk/copilot/tools/guardrails.py b/skyvern/forge/sdk/copilot/tools/guardrails.py
index db178782f..4e0bc02e6 100644
--- a/skyvern/forge/sdk/copilot/tools/guardrails.py
+++ b/skyvern/forge/sdk/copilot/tools/guardrails.py
@@ -21,7 +21,7 @@ from skyvern.forge.sdk.copilot.output_policy import (
format_output_policy_tool_error,
output_policy_verdict_to_trace_data,
)
-from skyvern.forge.sdk.copilot.reached_download_target import code_is_download_intent
+from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget, code_is_download_intent
from skyvern.forge.sdk.copilot.request_policy import CREDENTIAL_DEFERRED_DRAFT_REASONS, RequestPolicy
from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.copilot.turn_intent import (
@@ -210,6 +210,69 @@ def _download_scout_required_error(copilot_ctx: Any, workflow_yaml: str | None)
return _DOWNLOAD_SCOUT_REQUIRED_STEERING
+def _submitted_code_blocks(workflow_yaml: str | None) -> list[str]:
+ codes: list[str] = []
+ for block in _workflow_yaml_blocks_by_label(workflow_yaml).values():
+ if block.get("block_type") != "code":
+ continue
+ code = block.get("code")
+ if isinstance(code, str):
+ codes.append(code)
+ return codes
+
+
+_DOWNLOAD_BINDING_REQUIRED_STEERING = (
+ "A correct scout-act reached a download affordance on the current page, but the authored block "
+ "does not fire the browser download. Author ONE terminal download code block that clicks the "
+ "captured target with the expect_download idiom; the captured selector is `{selector}`"
+ "{affordance_hint}. The terminal download step is compiled for you when you scout-act the "
+ "affordance, so re-author the block against the reached target rather than a static fetch."
+)
+_DOWNLOAD_BINDING_UNREACHABLE_HALT = (
+ "The reached download affordance could not be bound to a terminal download step after repeated "
+ "attempts. Tell the user you reached the download control but could not author the download step, "
+ "and ask them to confirm where the file downloads from; do not author a download-less block."
+)
+
+
+def _download_binding_required_error(ctx: AgentContext | None, workflow_yaml: str | None) -> str | None:
+ """Reject a code block authored after the scout reached a download affordance when that block does
+ not fire the browser download. Keyed on the typed `ctx.reached_download_target` the model cannot
+ edit, not on the submitted code form. Active in code-only browser mode."""
+ if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ return None
+ if ctx is None or workflow_yaml is None:
+ return None
+ target = getattr(ctx, "reached_download_target", None)
+ if not isinstance(target, ReachedDownloadTarget) or target.already_registered:
+ return None
+ if any(code_is_download_intent(code) for code in _submitted_code_blocks(workflow_yaml)):
+ return None
+ # Shared per-turn download-steering budget: this gate and _download_scout_required_error draw down the
+ # same ctx.download_scout_required_rejections counter (combined cap, not 3 per gate).
+ prior_rejections = int(getattr(ctx, "download_scout_required_rejections", 0) or 0)
+ if prior_rejections >= _DOWNLOAD_SCOUT_REQUIRED_MAX_REJECTIONS:
+ LOG.info(
+ "copilot download binding gate exhausted retries; halting honestly",
+ workflow_permanent_id=getattr(ctx, "workflow_permanent_id", None),
+ reached_download_selector=target.selector,
+ download_scout_required_rejections=prior_rejections,
+ surface="tool_pre_side_effect",
+ )
+ return _DOWNLOAD_BINDING_UNREACHABLE_HALT
+ if hasattr(ctx, "download_scout_required_rejections"):
+ ctx.download_scout_required_rejections = prior_rejections + 1
+ LOG.info(
+ "copilot download binding pre-side-effect rejected workflow",
+ workflow_permanent_id=getattr(ctx, "workflow_permanent_id", None),
+ reached_download_selector=target.selector,
+ download_scout_required_rejections=prior_rejections + 1,
+ surface="tool_pre_side_effect",
+ )
+ affordance_hint = f" (affordance text: {target.affordance_text})" if target.affordance_text else ""
+ return _DOWNLOAD_BINDING_REQUIRED_STEERING.format(selector=target.selector, affordance_hint=affordance_hint)
+
+
def _request_policy_tool_error(ctx: AgentContext, tool_name: str) -> CopilotToolBlockerSignal | None:
policy = getattr(ctx, "request_policy", None)
if not isinstance(policy, RequestPolicy):
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index 214df7ef1..3c0b3b4de 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -88,7 +88,7 @@ from .frontier import (
_stale_block_metadata_message,
_workflow_requires_canonical_persist,
)
-from .guardrails import _authority_tool_error, _download_scout_required_error
+from .guardrails import _authority_tool_error, _download_binding_required_error, _download_scout_required_error
LOG = structlog.get_logger()
@@ -1319,7 +1319,11 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)
if not _submitted_code_block_changed(code_block, prior_yaml):
return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)
- synthesized = synthesize_code_block(scout_trajectory, strict_selectors=True)
+ synthesized = synthesize_code_block(
+ scout_trajectory,
+ strict_selectors=True,
+ reached_download_target=getattr(ctx, "reached_download_target", None),
+ )
if synthesized is None:
return _SynthesizedCodeImpositionResult(
workflow_yaml=workflow_yaml,
@@ -2069,6 +2073,10 @@ async def _update_workflow(
if download_scout_error:
return {"ok": False, "error": download_scout_error}
+ download_binding_error = _download_binding_required_error(ctx, workflow_yaml)
+ if download_binding_error:
+ return {"ok": False, "error": download_binding_error}
+
composition_evidence_error = composition_page_evidence_error(ctx, workflow_yaml)
if composition_evidence_error:
LOG.info(
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index 6b86ac6d1..5314cb215 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -590,6 +590,91 @@ class TestCompiledAuthoringImposition:
assert "<fill: captured value>" not in block["code"]
assert 'await page.locator("#provInput").fill(str(provider_name))' in block["code"]
+ def _download_ctx(self) -> CopilotContext:
+ from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget
+
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "click",
+ "selector": "#statement-row",
+ "source_url": "https://example.com/billing",
+ "trajectory_index": 0,
+ }
+ ]
+ ctx.reached_download_target = ReachedDownloadTarget(
+ selector='a[href="/billing/statement.pdf"]',
+ affordance_text="View Printable Statement",
+ download_kind="attribute",
+ source_step="trajectory_recency",
+ already_registered=False,
+ )
+ return ctx
+
+ @pytest.mark.asyncio
+ async def test_imposition_forwards_reached_target_and_emits_download_terminal(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from skyvern.config import settings
+
+ _stub_successful_update(monkeypatch)
+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)
+ ctx = self._download_ctx()
+ submitted = _yaml(
+ """
+ title: Statement download
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: download_statement
+ code: |
+ await page.locator("#statement-row").click()
+ """
+ )
+
+ result = await _update_workflow({"workflow_yaml": submitted}, ctx)
+
+ assert result["ok"] is True
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ assert isinstance(parsed, dict)
+ block = _single_code_block(parsed)
+ assert "async with page.expect_download()" in block["code"]
+ assert "/billing/statement.pdf" in block["code"]
+ assert "save_as" not in block["code"]
+ assert result["data"]["imposed_substitutions"]["block_label"] == "download_statement"
+
+ @pytest.mark.asyncio
+ async def test_imposed_download_terminal_clears_binding_gate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.config import settings
+
+ _stub_successful_update(monkeypatch)
+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)
+ ctx = self._download_ctx()
+ ctx.flow_evidence = [
+ {
+ "evidence": {"source_tool": "scout_interaction", "interaction_selector": "#statement-row"},
+ "reached_via": "interaction",
+ }
+ ]
+ submitted = _yaml(
+ """
+ title: Statement download
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: download_statement
+ code: |
+ await page.locator("#statement-row").click()
+ """
+ )
+
+ result = await _update_workflow({"workflow_yaml": submitted}, ctx)
+
+ assert result["ok"] is True
+ block = _single_code_block(parse_workflow_yaml(ctx.workflow_yaml))
+ assert "async with page.expect_download()" in block["code"]
+
@pytest.mark.asyncio
async def test_unchanged_prior_code_does_not_impose(self, monkeypatch: pytest.MonkeyPatch) -> None:
_stub_successful_update(monkeypatch)
diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.py
index 21e3c1007..131c36648 100644
--- a/tests/unit/test_copilot_code_block_synthesis.py
+++ b/tests/unit/test_copilot_code_block_synthesis.py
@@ -1174,11 +1174,9 @@ class TestDownloadRungSynthesis:
assert f"async with page.expect_download() as {_DOWNLOAD_VAR_BASE}:" in result.code
download_obj = f"{_DOWNLOAD_VAR_BASE}_file"
assert f"{download_obj} = await {_DOWNLOAD_VAR_BASE}.value" in result.code
- assert (
- f"await {download_obj}.save_as("
- f"str((await {download_obj}.path()).parent / {download_obj}.suggested_filename))"
- ) in result.code
- assert ".value.save_as(" not in result.code
+ assert f"await {download_obj}.path()" in result.code
+ # The execution-layer dir-diff registers the single landed file, so the synthesizer never save_as.
+ assert "save_as" not in result.code
# The click inside expect_download targets the TYPED download selector, not the navigation click.
download_step = result.code.split("async with page.expect_download")[1]
assert 'await page.locator("[href=\\"/files/report.pdf\\"]").click()' in download_step
@@ -1264,17 +1262,16 @@ class TestDownloadRungSynthesis:
assert not any(d.code == "SYNTAX_ERROR" for d in preflight_code_block(result.code, parameter_keys=()))
ast.parse(wrapped)
- def test_download_snippet_save_as_lands_file_in_run_dir(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def test_download_snippet_awaits_completion_without_save_as(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)
result = synthesize_code_block([_nav_click()], reached_download_target=_download_target())
assert result is not None
download_obj = f"{_DOWNLOAD_VAR_BASE}_file"
assert result.code.count(f"{download_obj} = await {_DOWNLOAD_VAR_BASE}.value") == 1
- assert (
- f"await {download_obj}.save_as("
- f"str((await {download_obj}.path()).parent / {download_obj}.suggested_filename))"
- ) in result.code
- assert ".value.path()" not in result.code
+ # Awaiting the path() completes the download into the run-scoped dir; the SKY-10937 dir-diff
+ # registers the single file, so a synthesizer save_as would double-register.
+ assert f"await {download_obj}.path()" in result.code
+ assert "save_as" not in result.code
CodeBlock.is_safe_code("async def _block(page):\n" + result.code)
def test_download_offer_text_only_present_for_download_snippet(self, monkeypatch: pytest.MonkeyPatch) -> None: