Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-11060: synthesize a real expect_download block from the reached-download target (#6617)
Andrew Neilsonc4551d98e336
diff --git a/skyvern/config.py b/skyvern/config.pyindex 44054c6b4..a5cbd99bc 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -165,6 +165,9 @@ class Settings(BaseSettings):# already registered into a block output), attach a typed reached-download target and steer# the agent to author one terminal download code block. Off (default) restores today's behavior.COPILOT_REACHED_DOWNLOAD_TARGET_AUTHOR_STEER_ENABLED: bool = False+ # On, a reached-download affordance compiles into the expect_download idiom in the code-block+ # synthesizer; off (default) restores today's bare-click synthesis. Per-rung gate.+ COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED: bool = False# Dispatch flag for the workflow copilot v2 (openai-agents-SDK rewrite).# Off = existing direct-LLM copilot at workflow_copilot_chat_post.# On = new agent-SDK path under skyvern.forge.sdk.copilot.diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 8c9d1b042..333d33a2d 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -527,7 +527,7 @@ def _synthesized_block_offer_prompt(ctx: CopilotContext | None) -> str:if not ctx.scout_trajectory:LOG.debug("copilot_synthesized_block_offer_skipped", reason="empty_trajectory")return ""- synthesized = synthesize_code_block(ctx.scout_trajectory)+ synthesized = synthesize_code_block(ctx.scout_trajectory, reached_download_target=ctx.reached_download_target)if synthesized is None:LOG.debug("copilot_synthesized_block_offer_skipped",diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex 69af890f4..145662e2b 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -16,12 +16,17 @@ from dataclasses import dataclass, fieldfrom typing import Anyfrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit+from skyvern.config import settingsfrom skyvern.forge.sdk.copilot.composition_evidence import SCOUT_INTERACTION_EVIDENCE_TOOL+from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTargetfrom skyvern.utils.strings import escape_code_fences_MAX_STEPS = 60_INDENT = " "+# Base name for the download var bound by `async with page.expect_download() as <name>:`.+_DOWNLOAD_VAR_BASE = "dl_info"+CREDENTIAL_FILL_TOOL_NAME = "fill_credential_field"_CREDENTIAL_FIELDS = frozenset({"username", "password", "totp"})@@ -65,6 +70,8 @@ _RESERVED_PARAM_NAMES = frozenset("json","html","Exception",+ _DOWNLOAD_VAR_BASE,+ f"{_DOWNLOAD_VAR_BASE}_file",})@@ -317,7 +324,10 @@ def _credential_param_key(interaction: Mapping[str, Any], used: set[str]) -> strdef synthesize_code_block(- trajectory: Sequence[Mapping[str, Any]], *, strict_selectors: bool = False+ trajectory: Sequence[Mapping[str, Any]],+ *,+ strict_selectors: bool = False,+ reached_download_target: ReachedDownloadTarget | None = None,) -> SynthesizedCodeBlock | None:"""Deterministically synthesize a code block from a scout trajectory, or None if empty."""if not trajectory:@@ -331,6 +341,7 @@ def synthesize_code_block(used_param_keys: set[str] = set()typed_param_keys: dict[tuple[str, str, str, str], str] = {}credential_param_keys: dict[str, str] = {}+ used_download_vars: set[str] = set()def append_step(description: str, action_type: str, line_start: int) -> None:steps.append(@@ -473,6 +484,26 @@ def synthesize_code_block(continueemitted += 1+ if (+ settings.COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED+ and reached_download_target is not None+ and not reached_download_target.already_registered+ and reached_download_target.selector+ ):+ # 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.+ 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))"+ )+if not lines:return None@@ -613,6 +644,12 @@ def render_synthesized_offer_text("`.username` / `.password` / `.totp` attributes the snippet reads (`.totp` is a fresh one-time ""code generated when the block starts). Never replace these attribute reads with literal values.")+ if "page.expect_download()" in synthesized.code:+ parts.append(+ "The snippet already fires the browser download (`async with page.expect_download()`) to the "+ "workflow output surface (`downloaded_files`). Do not re-fetch the file or place its bytes or URL "+ "in the reply; the data-capture step only needs to name the downloaded artifact, not refetch it."+ )if synthesized.notes:parts.append("Synthesis notes: " + "; ".join(synthesized.notes) + ".")if synthesized.steps:diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 4a3bbcd9c..b6a3dc8b3 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -1638,7 +1638,9 @@ def _maybe_synthesized_block_offer_msg(ctx: Any) -> dict[str, Any] | None:trajectory = getattr(ctx, "scout_trajectory", None) or []if not trajectory:return None- synthesized = synthesize_code_block(trajectory)+ synthesized = synthesize_code_block(+ trajectory, reached_download_target=getattr(ctx, "reached_download_target", None)+ )if synthesized is None:return Nonediff --git a/skyvern/forge/sdk/copilot/reached_download_target.py b/skyvern/forge/sdk/copilot/reached_download_target.pyindex 1b87097fb..445902ce5 100644--- a/skyvern/forge/sdk/copilot/reached_download_target.py+++ b/skyvern/forge/sdk/copilot/reached_download_target.py@@ -163,8 +163,7 @@ def derive_from_block_outputs(block_outputs_by_label: Any) -> ReachedDownloadTar_AUTHOR_DOWNLOAD_GUIDANCE = ("A correct click reached a download affordance on the current page. Author ONE terminal ""download code block that fires the browser download for the captured target using the "- "expect_download idiom (async with page.expect_download() as dl_info: await "- "page.click(<selector>)), not a static-fetch request and not another page re-evaluation. "+ "expect_download idiom, not a static-fetch request and not another page re-evaluation. ""The downloaded file is registered to the workflow output surface (downloaded_files); never ""place file bytes or URLs in the chat reply.")diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex f84bbf1d8..1ff644af4 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -36,6 +36,7 @@ from skyvern.library.skyvern_browser import SkyvernBrowserif TYPE_CHECKING:from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult+ from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTargetfrom skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcomefrom skyvern.forge.sdk.copilot.turn_halt import TurnHalt@@ -267,6 +268,9 @@ class AgentContext:# preserves repeats and ordering so code_block_synthesis can emit a faithful# linear Playwright trajectory.scout_trajectory: list[ScoutedInteraction] = field(default_factory=list)+ # Latest typed reached-download target from the scout steer; the synthesizer compiles the terminal+ # expect_download step from it. Selector is the observed download link, not necessarily a trajectory click.+ reached_download_target: ReachedDownloadTarget | None = Nonesynthesized_block_offered: bool = False# Source page of an in-flight scout action, captured before it may navigate away.pending_scout_source_url: str | None = Nonediff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.pyindex b678ee981..6ab571de1 100644--- a/skyvern/forge/sdk/copilot/tools/scouting.py+++ b/skyvern/forge/sdk/copilot/tools/scouting.py@@ -826,6 +826,14 @@ async def _maybe_attach_reached_download_target(returndata["reached_download_target"] = target.to_dict()data["reached_download_guidance"] = _reached_download_guidance_for(target)+ if settings.COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED and not target.already_registered:+ # The pure synthesizer compiles the terminal expect_download step from this typed object.+ ctx.reached_download_target = target+ if ctx.synthesized_block_offered and not ctx.update_workflow_called:+ # The prompt-side offer latched before this download target resolved, so it rendered the+ # non-download idiom. Reopen the latch once so the post-turn fallback re-fires carrying it.+ ctx.synthesized_block_offered = False+ LOG.info("copilot_synthesized_block_offer_latch_reset_for_download", url=url)LOG.info("copilot_reached_download_target_steer",url=url,diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 051b259f9..21e3c1007 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -11,16 +11,21 @@ import keywordimport sysfrom typing import Any+import pytest++from skyvern.config import settingsfrom skyvern.forge.sdk.copilot.code_block_preflight import preflight_code_blockfrom skyvern.forge.sdk.copilot.code_block_synthesis import (+ _DOWNLOAD_VAR_BASE,_MAX_STEPS,_SYNTHESIZED_BLOCK_LABEL,build_synthesized_artifact_metadata,render_synthesized_offer_text,synthesize_code_block,)+from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTargetfrom skyvern.forge.sdk.copilot.tools import _normalize_code_artifact_metadata-from skyvern.forge.sdk.workflow.models.block import CodeBlockStep+from skyvern.forge.sdk.workflow.models.block import CodeBlock, CodeBlockStepdef _interaction(tool_name: str, **fields: Any) -> dict[str, Any]:@@ -1138,3 +1143,150 @@ class TestOfferDemonstratesStructuredReturn:assert "keyed structure" in offerassert "inner_text" in offerassert 'return {"records":' in offer+++_DOWNLOAD_SELECTOR = '[href="/files/report.pdf"]'+++def _nav_click() -> dict[str, Any]:+ # The scout reaches the download page via a navigation click; the download affordance itself+ # is observed in nav_targets, so its selector is NOT this trajectory click.+ return _interaction("click", selector="div.stmt-row", source_url="https://example.com/bills")+++def _download_target(**fields: Any) -> ReachedDownloadTarget:+ base: dict[str, Any] = {+ "selector": _DOWNLOAD_SELECTOR,+ "affordance_text": "Download PDF",+ "download_kind": "extension",+ "source_step": "trajectory_recency",+ "already_registered": False,+ }+ base.update(fields)+ return ReachedDownloadTarget(**base)+++class TestDownloadRungSynthesis:+ def test_appended_terminal_step_compiled_from_typed_target(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+ 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+ # 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+ assert "div.stmt-row" not in download_step+ # A download does not navigate, so no trailing load-wait inside the appended step.+ assert 'wait_for_load_state("load")' not in download_step++ def test_already_registered_emits_no_download_step(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(already_registered=True, selector="")+ )+ assert result is not None+ assert "expect_download" not in result.code++ def test_flag_off_with_target_byte_identical_to_base(self, monkeypatch: pytest.MonkeyPatch) -> None:+ trajectory = [_nav_click()]+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", False)+ base = synthesize_code_block(trajectory)+ with_target = synthesize_code_block(trajectory, reached_download_target=_download_target())+ assert base is not None and with_target is not None+ assert base.code == with_target.code+ assert "expect_download" not in with_target.code++ def test_target_none_byte_identical_to_base(self, monkeypatch: pytest.MonkeyPatch) -> None:+ trajectory = [_nav_click()]+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)+ base = synthesize_code_block(trajectory)+ none_target = synthesize_code_block(trajectory, reached_download_target=None)+ assert base is not None and none_target is not None+ assert base.code == none_target.code+ assert "expect_download" not in none_target.code++ def test_non_download_trajectories_byte_identical_across_flag_states(self, monkeypatch: pytest.MonkeyPatch) -> None:+ trajectory = [+ _interaction("type_text", selector="#user", source_url="https://example.com/", typed_value="abc"),+ _interaction("select_option", selector="#state", value="CA"),+ _interaction(+ "fill_credential_field",+ selector="#pw",+ credential_id="cred_123",+ credential_field="password",+ credential_name="Login",+ ),+ _interaction("press_key", selector="#user", key="Enter"),+ _interaction("click", selector="#submit", source_url="https://example.com/"),+ ]+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", False)+ off = synthesize_code_block(trajectory)+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)+ on = synthesize_code_block(trajectory)+ assert off is not None and on is not None+ assert off.code == on.code+ assert "expect_download" not in on.code++ def test_user_param_named_dl_info_is_renamed_via_reserved_path(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)+ result = synthesize_code_block(+ [+ _interaction(+ "type_text",+ selector="#field",+ source_url="https://example.com/",+ typed_value="x",+ accessible_name=_DOWNLOAD_VAR_BASE,+ ),+ _nav_click(),+ ],+ reached_download_target=_download_target(),+ )+ assert result is not None+ param_keys = [p["key"] for p in result.parameters]+ assert _DOWNLOAD_VAR_BASE not in param_keys+ assert f"{_DOWNLOAD_VAR_BASE}_field" in param_keys+ assert f"async with page.expect_download() as {_DOWNLOAD_VAR_BASE}:" in result.code++ def test_emitted_download_snippet_is_safe_and_parses(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+ wrapped = "async def _block(page):\n" + result.code+ CodeBlock.is_safe_code(wrapped)+ 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:+ 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+ 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:+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)+ download = synthesize_code_block([_nav_click()], reached_download_target=_download_target())+ plain = synthesize_code_block([_interaction("click", selector="#go", source_url="https://example.com/")])+ assert download is not None and plain is not None+ assert "expect_download" in render_synthesized_offer_text(download)+ assert "expect_download" not in render_synthesized_offer_text(plain)++ def test_non_live_call_sites_compile_without_kwarg(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "COPILOT_DOWNLOAD_RUNG_SYNTHESIS_ENABLED", True)+ result = synthesize_code_block([_nav_click()])+ assert result is not None+ assert "expect_download" not in result.code