Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-11140): harden copilot code downloads (#6688)
Andrew Neilson90cf3c54ef23
diff --git a/skyvern/forge/sdk/copilot/code_block_security.py b/skyvern/forge/sdk/copilot/code_block_security.pynew file mode 100644index 000000000..3b68bd370--- /dev/null+++ b/skyvern/forge/sdk/copilot/code_block_security.py@@ -0,0 +1,114 @@+from __future__ import annotations++import ast+from collections.abc import Collection, Iterable+from dataclasses import dataclass++COPILOT_CODE_SECURITY_FAILURE_CATEGORY = "COPILOT_CODE_SECURITY"++_AUTHOR_ATTR_REASONS = {+ "request": "AUTHOR_PAGE_REQUEST",+ "context": "AUTHOR_PAGE_CONTEXT",+ "evaluate": "AUTHOR_PAGE_EVALUATE",+ "evaluate_handle": "AUTHOR_PAGE_EVALUATE",+}+_RUNTIME_ATTR_REASONS = {+ "request": "RUNTIME_PAGE_REQUEST",+ "context": "RUNTIME_PAGE_CONTEXT",+ "evaluate": "RUNTIME_PAGE_EVALUATE",+ "evaluate_handle": "RUNTIME_PAGE_EVALUATE",+}+++@dataclass(frozen=True)+class CodeBlockSecurityInput:+ label: str+ code: str+++class CodeBlockSecurityError(str):+ block_label: str+ reason_code: str+ surface: str++ def __new__(cls, message: str, *, block_label: str, reason_code: str, surface: str) -> CodeBlockSecurityError:+ item = str.__new__(cls, message)+ item.block_label = block_label+ item.reason_code = reason_code+ item.surface = surface+ return item++ def to_failure_category(self) -> dict[str, str | float]:+ return {+ "category": COPILOT_CODE_SECURITY_FAILURE_CATEGORY,+ "reason_code": self.reason_code,+ "confidence_float": 0.99,+ "reasoning": f"{self.reason_code}: blocked {self.surface} before browser dispatch",+ }+++def author_time_code_security_errors(*, label: str, code: str) -> list[CodeBlockSecurityError]:+ try:+ tree = ast.parse(code)+ except SyntaxError:+ return []+ return _security_errors_for_tree(label, tree, _AUTHOR_ATTR_REASONS)+++def runtime_code_security_errors(+ blocks: Iterable[CodeBlockSecurityInput],+ *,+ selected_labels: Collection[str] | None = None,+) -> list[CodeBlockSecurityError]:+ selected = set(selected_labels) if selected_labels is not None else None+ errors: list[CodeBlockSecurityError] = []+ for block in blocks:+ if selected is not None and block.label not in selected:+ continue+ try:+ tree = ast.parse(block.code)+ except SyntaxError:+ errors.append(_error(block.label, "RUNTIME_SYNTAX_ERROR"))+ continue+ errors.extend(_security_errors_for_tree(block.label, tree, _RUNTIME_ATTR_REASONS))+ return errors+++def _security_errors_for_tree(label: str, tree: ast.AST, attr_reasons: dict[str, str]) -> list[CodeBlockSecurityError]:+ errors: list[CodeBlockSecurityError] = []+ seen: set[str] = set()+ for node in ast.walk(tree):+ # This AST layer catches direct attribute access. The sandbox's unresolved-name,+ # private-attribute, and builtins restrictions remain the backstop for dynamic forms.+ if isinstance(node, ast.Attribute) and node.attr in attr_reasons:+ reason = attr_reasons[node.attr]+ if reason not in seen:+ errors.append(_error(label, reason))+ seen.add(reason)+ return errors+++def _error(label: str, reason_code: str) -> CodeBlockSecurityError:+ surface = _surface_for_reason(reason_code)+ return CodeBlockSecurityError(+ _message_for_reason(label=label, reason_code=reason_code, surface=surface),+ block_label=label,+ reason_code=reason_code,+ surface=surface,+ )+++def _surface_for_reason(reason_code: str) -> str:+ if reason_code.endswith("PAGE_REQUEST"):+ return "page.request"+ if reason_code.endswith("PAGE_CONTEXT"):+ return "page.context"+ if reason_code.endswith("PAGE_EVALUATE"):+ return "page.evaluate"+ return "python_ast"+++def _message_for_reason(*, label: str, reason_code: str, surface: str) -> str:+ if reason_code.startswith("AUTHOR_"):+ return f"Code block `{label}` failed the Copilot code security check: {surface} is not allowed."+ return f"Code block `{label}` was blocked before browser dispatch: {surface} is not allowed at Copilot runtime."diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex 88a1d771f..b530405b4 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -788,12 +788,18 @@ def synthesize_code_block(# 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).+ # Return a JSON-safe filename summary too; artifact IDs/URLs are injected by the execution layer.download_var = _unique_key(_DOWNLOAD_VAR_BASE, used_download_vars)download_obj = _unique_key(f"{download_var}_file", used_download_vars)+ download_filename = _unique_key(_DOWNLOAD_FILENAME_VAR_BASE, 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")+ lines.append(f"{_INDENT}{download_filename} = {download_obj}.suggested_filename")lines.append(f"{_INDENT}await {download_obj}.path()")+ lines.append(f"{_INDENT}return {{")+ lines.append(f'{_INDENT * 2}"downloaded_file_name": {download_filename},')+ lines.append(f"{_INDENT}}}")if not lines:return Nonediff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex bb71e38ca..24206213c 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -23,6 +23,11 @@ from skyvern.forge.sdk.copilot.blocker_signal import (clear_blocker_signal_for_reason_codes,stash_blocker_signal,)+from skyvern.forge.sdk.copilot.code_block_security import (+ COPILOT_CODE_SECURITY_FAILURE_CATEGORY,+ CodeBlockSecurityInput,+ runtime_code_security_errors,+)from skyvern.forge.sdk.copilot.code_block_synthesis import (code_contains_credential_fill,trajectory_has_credential_fill,@@ -81,6 +86,7 @@ from skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yamlfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotRunOutcomeUpdate, WorkflowCopilotStreamMessageTypefrom skyvern.forge.sdk.settings_manager import SettingsManagerfrom skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException+from skyvern.forge.sdk.workflow.models.block import CodeBlockfrom skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatusfrom skyvern.schemas.workflows import BlockTypefrom skyvern.webeye.navigation import is_skip_inner_retry_error@@ -696,6 +702,120 @@ def _labels_replay_login_fill(labels_to_execute: list[str], workflow: Workflow |return isinstance(code, str) and code_contains_credential_fill(code)+def _runtime_code_security_failure_for_selected_labels(+ workflow: Workflow,+ *,+ block_labels: list[str],+ labels_to_execute: list[str],+ frontier_start_label: str | None,+) -> dict[str, Any] | None:+ code_blocks = _selected_code_security_inputs(+ _workflow_definition_blocks_for_code_security(workflow.workflow_definition),+ selected_labels=set(labels_to_execute),+ )+ errors = runtime_code_security_errors(code_blocks)+ if not errors:+ return None++ failure_reason = "Copilot runtime blocked unsafe synthesized code before browser dispatch."+ return {+ "ok": False,+ "error": failure_reason,+ "data": {+ "workflow_run_id": None,+ "overall_status": "failed",+ "failure_reason": failure_reason,+ "requested_block_labels": list(block_labels),+ "executed_block_labels": [],+ "planned_block_labels": list(labels_to_execute),+ "frontier_start_label": frontier_start_label,+ "blocks": [],+ "failure_categories": [error.to_failure_category() for error in errors],+ "failure_category": COPILOT_CODE_SECURITY_FAILURE_CATEGORY,+ },+ }+++def _workflow_definition_blocks_for_code_security(workflow_definition: Any) -> list[Any]:+ if isinstance(workflow_definition, Mapping):+ blocks = workflow_definition.get("blocks")+ else:+ blocks = getattr(workflow_definition, "blocks", None)+ return list(blocks) if isinstance(blocks, list) else []+++def _selected_code_security_inputs(+ blocks: list[Any],+ *,+ selected_labels: set[str],+ include_descendants: bool = False,+) -> list[CodeBlockSecurityInput]:+ code_blocks: list[CodeBlockSecurityInput] = []+ for block in blocks:+ if isinstance(block, Mapping):+ label = str(block.get("label") or "")+ selected = include_descendants or label in selected_labels+ block_type = str(block.get("block_type") or "").lower()+ code = block.get("code")+ if block_type == BlockType.CODE.value and selected and isinstance(code, str):+ code_blocks.append(CodeBlockSecurityInput(label=label, code=code))+ code_blocks.extend(+ _selected_code_security_inputs(+ _mapping_child_blocks(block),+ selected_labels=selected_labels,+ include_descendants=selected,+ )+ )+ continue+ label = str(getattr(block, "label", "") or "")+ selected = include_descendants or label in selected_labels+ if isinstance(block, CodeBlock) and selected:+ code_blocks.append(CodeBlockSecurityInput(label=block.label, code=block.code))+ if children := _typed_child_blocks(block):+ code_blocks.extend(+ _selected_code_security_inputs(+ children,+ selected_labels=selected_labels,+ include_descendants=selected,+ )+ )+ return code_blocks+++def _mapping_child_blocks(block: Mapping[str, Any]) -> list[Any]:+ children: list[Any] = []+ for key in ("loop_blocks", "blocks"):+ value = block.get(key)+ if isinstance(value, list):+ children.extend(value)+ for key in ("branch_conditions", "branches", "ordered_branches"):+ branches = block.get(key)+ if not isinstance(branches, list):+ continue+ for branch in branches:+ if isinstance(branch, Mapping):+ children.extend(_mapping_child_blocks(branch))+ return children+++def _typed_child_blocks(block: Any) -> list[Any]:+ children: list[Any] = []+ for key in ("loop_blocks", "blocks"):+ value = getattr(block, key, None)+ if isinstance(value, list):+ children.extend(value)+ for key in ("branch_conditions", "branches", "ordered_branches"):+ branches = getattr(block, key, None)+ if not isinstance(branches, list):+ continue+ for branch in branches:+ if isinstance(branch, Mapping):+ children.extend(_mapping_child_blocks(branch))+ else:+ children.extend(_typed_child_blocks(branch))+ return children++async def _run_blocks_and_collect_debug(params: dict[str, Any],ctx: CopilotContext,@@ -744,6 +864,20 @@ async def _run_blocks_and_collect_debug(if not workflow:return {"ok": False, "error": f"Workflow not found: {ctx.workflow_permanent_id}"}+ for label in block_labels:+ if not workflow.get_output_parameter(label):+ return {"ok": False, "error": f"Block label not found in saved workflow: {label!r}"}++ runtime_security_failure = _runtime_code_security_failure_for_selected_labels(+ workflow,+ block_labels=list(block_labels),+ labels_to_execute=labels_to_execute,+ frontier_start_label=frontier_start_label,+ )+ if runtime_security_failure is not None:+ ctx.last_executed_block_labels = []+ return runtime_security_failure+credential_ids = list(dict.fromkeys(_extract_credential_ids_from_tool_value(params.get("parameters") or {})@@ -761,10 +895,6 @@ async def _run_blocks_and_collect_debug(if credential_error is not None:return {"ok": False, "error": credential_error}- for label in block_labels:- if not workflow.get_output_parameter(label):- return {"ok": False, "error": f"Block label not found in saved workflow: {label!r}"}-from skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBodyfrom skyvern.services import workflow_servicediff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex a6c9ee74f..21f333f7d 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -18,8 +18,11 @@ from skyvern.forge.sdk.api.llm.schema_validator import validate_schemafrom skyvern.forge.sdk.copilot.attribution import resolve_copilot_created_by_stampfrom skyvern.forge.sdk.copilot.blocker_signal import clear_terminal_evidence_on_workflow_editfrom skyvern.forge.sdk.copilot.code_block_preflight import sandbox_unresolved_name_diagnostics+from skyvern.forge.sdk.copilot.code_block_security import CodeBlockSecurityError, author_time_code_security_errorsfrom skyvern.forge.sdk.copilot.code_block_steps import apply_derived_code_block_steps, fill_code_block_prompts_in_yamlfrom skyvern.forge.sdk.copilot.code_block_synthesis import (+ _SYNTHESIZED_BLOCK_LABEL,+ SynthesisDiagnostics,artifact_dependency_id,artifact_observation_ref_id,synthesize_code_block,@@ -46,7 +49,11 @@ 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 REGISTERED_DOWNLOAD_OUTPUT_KEYS+from skyvern.forge.sdk.copilot.reached_download_target import (+ REGISTERED_DOWNLOAD_OUTPUT_KEYS,+ ReachedDownloadTarget,+ code_is_download_intent,+)from skyvern.forge.sdk.copilot.runtime import AgentContext, ScoutedInteractionfrom skyvern.forge.sdk.copilot.streaming_adapter import emit_workflow_draft, maybe_emit_design_endfrom skyvern.forge.sdk.copilot.tracing_setup import copilot_span@@ -689,13 +696,13 @@ def _artifact_id_for_block_label(label: str) -> str:return f"code_artifact:{_artifact_label_fragment(label)}"-def _code_block_safety_errors(workflow_yaml: str | None, prior_yaml: str | None) -> list[str]:+def _code_block_safety_errors(workflow_yaml: str | None, prior_yaml: str | None) -> list[str | CodeBlockSecurityError]:"""Run the sandbox's static safety rule on new/changed code blocks before any run.Label-scoped diff so legacy code blocks the model did not touch cannot wedgeevery subsequent update."""prior_blocks = _workflow_yaml_code_blocks_by_label(prior_yaml)- errors: list[str] = []+ errors: list[str | CodeBlockSecurityError] = []for label, block in _workflow_yaml_code_blocks_by_label(workflow_yaml).items():code = str(block.get("code") or "")if not code.strip():@@ -719,6 +726,7 @@ def _code_block_safety_errors(workflow_yaml: str | None, prior_yaml: str | None)"code-block parameter keys, `json`, `re`, `html`, `asyncio.sleep`, and its explicit safe helper ""namespace. `Exception` is the only available exception type.")+ errors.extend(author_time_code_security_errors(label=label, code=code))unresolved_diagnostics = sandbox_unresolved_name_diagnostics(code, parameter_keys=parameter_keys)errors.extend(f"Code block `{label}` failed the sandbox name check: {item.message}" for item in unresolved_diagnostics@@ -789,6 +797,52 @@ def _submitted_code_block_changed(block: Mapping[str, Any], prior_yaml: str | Noreturn True+def _should_impose_after_update_attempt(ctx: AgentContext) -> bool:+ target = ctx.reached_download_target+ return isinstance(target, ReachedDownloadTarget) and not target.already_registered and bool(target.selector.strip())+++def _select_synthesized_imposition_code_block(+ code_blocks: list[dict[str, Any]],+ *,+ prior_yaml: str | None,+) -> dict[str, Any] | None:+ if len(code_blocks) == 1:+ return code_blocks[0]++ synthesized_label_matches = [+ block for block in code_blocks if str(block.get("label") or "").strip() == _SYNTHESIZED_BLOCK_LABEL+ ]+ if len(synthesized_label_matches) == 1:+ synthesized_block = synthesized_label_matches[0]+ if not code_is_download_intent(str(synthesized_block.get("code") or "")):+ return synthesized_block+ return None+ if synthesized_label_matches:+ return None++ changed_blocks = [block for block in code_blocks if _submitted_code_block_changed(block, prior_yaml)]+ if len(changed_blocks) == 1:+ return changed_blocks[0]++ changed_without_download_intent = [+ block for block in changed_blocks if not code_is_download_intent(str(block.get("code") or ""))+ ]+ if len(changed_without_download_intent) == 1:+ return changed_without_download_intent[0]+ return None+++def _is_ignorable_entry_opener_drop(dropped: Mapping[str, Any], diagnostics: SynthesisDiagnostics) -> bool:+ return (+ dropped.get("reason_code") == "ambiguous_bare_selector"+ and dropped.get("tool_name") == "click"+ and dropped.get("trajectory_index") == 0+ and str(dropped.get("selector") or "").strip() in {"button", "role=button"}+ and bool(diagnostics.locator_provenance)+ )++def _wrapped_code_ast(code: str) -> ast.AST | None:body = "\n".join(f" {line}" for line in code.splitlines())if not body.strip():@@ -1319,7 +1373,7 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)- if getattr(ctx, "update_workflow_called", False):+ if ctx.update_workflow_called and not _should_impose_after_update_attempt(ctx):return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)scout_trajectory = getattr(ctx, "scout_trajectory", None)@@ -1333,19 +1387,19 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)if not isinstance(parsed, dict):return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)code_blocks = _workflow_code_blocks(parsed)- if len(code_blocks) != 1:+ prior_source, prior_yaml = _prior_yaml_source(ctx)+ code_block = _select_synthesized_imposition_code_block(code_blocks, prior_yaml=prior_yaml)+ if code_block is None:return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)- code_block = code_blocks[0]submitted_code = str(code_block.get("code") or "")- prior_source, prior_yaml = _prior_yaml_source(ctx)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,- reached_download_target=getattr(ctx, "reached_download_target", None),+ reached_download_target=ctx.reached_download_target,)if synthesized is None:return _SynthesizedCodeImpositionResult(@@ -1358,6 +1412,8 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)if diagnostics.truncated:violations.append("Unable to impose synthesized code block: scout trajectory was truncated.")for dropped in diagnostics.dropped_interactions:+ if _is_ignorable_entry_opener_drop(dropped, diagnostics):+ continuereason = str(dropped.get("reason_code") or "unknown")tool_name = str(dropped.get("tool_name") or "unknown")index = dropped.get("trajectory_index", "?")@@ -1734,12 +1790,15 @@ def _code_uses_expect_download(code: str) -> bool:def _dict_keys(node: ast.expr) -> set[str]:if isinstance(node, ast.Await):return _dict_keys(node.value)- if not isinstance(node, ast.Dict):- return set()- return {key.value for key in node.keys if isinstance(key, ast.Constant) and isinstance(key.value, str)}+ if isinstance(node, ast.Dict):+ return {key.value for key in node.keys if isinstance(key, ast.Constant) and isinstance(key.value, str)}+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "dict" and not node.args:+ return {keyword.arg for keyword in node.keywords if keyword.arg is not None}+ return set()_REGISTERED_DOWNLOAD_OUTPUT_KEY_SET = frozenset(REGISTERED_DOWNLOAD_OUTPUT_KEYS)+_DOWNLOAD_DESCRIPTOR_LEAK_KEY_SET = frozenset({"downloaded_file_path", "download_url"})def _code_returns_registration_keys(code: str) -> bool:@@ -1760,6 +1819,26 @@ def _code_returns_registration_keys(code: str) -> bool:return False+def _code_returns_download_descriptor_leak_keys(code: str) -> bool:+ """Detect simple top-level descriptor returns; execution-registered artifacts remain+ the authoritative download proof."""+ try:+ tree = ast.parse(textwrap.dedent(code).strip() or "pass")+ except SyntaxError:+ return False+ leak_key_locals: set[str] = set()+ for node in _iter_top_level_scope(tree.body):+ if isinstance(node, ast.Return) and node.value is not None:+ if _dict_keys(node.value) & _DOWNLOAD_DESCRIPTOR_LEAK_KEY_SET:+ return True+ if isinstance(node.value, ast.Name) and node.value.id in leak_key_locals:+ return True+ if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):+ if _dict_keys(node.value) & _DOWNLOAD_DESCRIPTOR_LEAK_KEY_SET:+ leak_key_locals.add(node.targets[0].id)+ return False++def _artifact_declares_registration_keys(artifact: Mapping[str, Any]) -> bool:for field_name in ("claimed_outcomes", "terminal_verifier_expectations"):for row in _artifact_rows(artifact.get(field_name)):@@ -1805,6 +1884,11 @@ def _download_return_shape_error(label: str, artifact: Mapping[str, Any], code:'small keyed descriptor instead (for example `return {"saved_as": dl_info.value.suggested_filename}`) and '"let the expect_download idiom register the file.")+ if _code_returns_download_descriptor_leak_keys(code):+ return (+ f"Code block `{label}` returns raw download path/URL descriptor keys. Return only non-sensitive summary "+ "fields such as the suggested filename; the execution layer injects artifact URLs and IDs."+ )return Nonediff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 41aeeba34..e8878694d 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -4274,6 +4274,8 @@ async def wrapper({default_args}):downloaded_files,current_context.loop_internal_state if current_context else None,)+ if downloaded_files and not isinstance(result, dict):+ result = {"value": result} if result is not None else {}if downloaded_files and isinstance(result, dict):result["downloaded_files"] = [fi.model_dump() for fi in downloaded_files]result["downloaded_file_urls"] = [fi.url for fi in downloaded_files]diff --git a/tests/unit/test_code_block_downloads.py b/tests/unit/test_code_block_downloads.pyindex d78fe13b2..87cc85fb9 100644--- a/tests/unit/test_code_block_downloads.py+++ b/tests/unit/test_code_block_downloads.py@@ -135,6 +135,41 @@ async def test_code_block_registers_downloads_into_output(assert output["downloaded_file_artifact_ids"] == ["a_dl_1"]+async def test_code_block_wraps_non_dict_output_before_attaching_downloads(+ monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str+) -> None:+ skyvern_context.set(SkyvernContext(organization_id="o_1", workflow_run_id="wr_1", run_id="wr_1"))++ file_info = FileInfo(+ url="https://api.example.com/v1/artifacts/a_dl_1/content?artifact_name=invoice.pdf",+ filename="invoice.pdf",+ checksum="deadbeef",+ artifact_id="a_dl_1",+ modified_at=datetime(2026, 6, 14, 12, 0, tzinfo=UTC),+ )+ _fake_storage_app(+ monkeypatch,+ save=AsyncMock(),+ get=AsyncMock(side_effect=[[], [file_info]]),+ )+ _wire_block_runtime(monkeypatch)++ block = CodeBlock(+ label="code_download",+ code="return 'ok'",+ output_parameter=_output_parameter("code_out"),+ )+ result = await block.execute(workflow_run_id="wr_1", workflow_run_block_id="", organization_id="o_1")++ assert result.success is True+ output = result.output_parameter_value+ assert output["value"] == "ok"+ assert output["downloaded_files"] == [file_info.model_dump()]+ assert output["downloaded_file_urls"] == [file_info.url]+ assert output["downloaded_file_artifact_ids"] == ["a_dl_1"]++@pytest.mark.asyncioasync def test_code_block_without_downloads_has_no_download_keys(monkeypatch: pytest.MonkeyPatch, _isolated_download_path: strdiff --git a/tests/unit/test_copilot_code_artifact_metadata_violations.py b/tests/unit/test_copilot_code_artifact_metadata_violations.pyindex 9bccae589..29c06a533 100644--- a/tests/unit/test_copilot_code_artifact_metadata_violations.py+++ b/tests/unit/test_copilot_code_artifact_metadata_violations.py@@ -1075,6 +1075,25 @@ class TestDownloadReturnShape:assert "downloaded_files" in errorassert "self-certifies" in error+ def test_idiom_but_returns_raw_path_or_url_descriptor_keys_is_rejected(self) -> None:+ code = """+ async with page.expect_download() as dl_info:+ await page.click("a#statement-pdf")+ payload = dict(+ download_url="https://example.com/statement.pdf",+ downloaded_file_path=await dl_info.value.path(),+ downloaded_file_name="statement.pdf",+ )+ return payload+ """+ normalized, error = _normalize_code_artifact_metadata(+ [_download_intent_metadata("dl_block")],+ _extraction_code_block_yaml("dl_block", code),+ )+ assert normalized == {}+ assert error is not None+ assert "raw download path/URL descriptor keys" in error+def test_self_asserted_keys_detected_without_goal_path_declaration(self) -> None:code = """await page.click("a#statement-pdf")diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex d2dd6a430..af50b1bd5 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -670,6 +670,31 @@ class TestCompiledAuthoringImposition: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_reached_download_target_still_imposes_after_prior_update_attempt(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = self._download_ctx()+ ctx.update_workflow_called = True+ 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.asyncioasync def test_imposition_carries_reached_download_target_to_synthesized_code(self, monkeypatch: pytest.MonkeyPatch@@ -713,6 +738,79 @@ class TestCompiledAuthoringImposition:assert "expect_download" in block["code"]assert 'await page.locator("[href=\\"/files/report.pdf\\"]").click()' in block["code"]+ def test_imposition_targets_synthesized_label_in_multi_code_workflow(self) -> None:+ ctx = self._download_ctx()+ workflow_yaml = _yaml(+ """+ title: Statement download+ workflow_definition:+ blocks:+ - block_type: code+ label: summarize_statement+ code: |+ return {"status": "ready"}+ - block_type: code+ label: scout_synthesized_browser_steps+ code: |+ await page.locator("#statement-row").click()+ """+ )++ result = workflow_update_module._maybe_impose_synthesized_code_block(workflow_yaml, ctx)++ assert result.violations == []+ parsed = parse_workflow_yaml(result.workflow_yaml)+ assert isinstance(parsed, dict)+ blocks = {str(block.get("label")): block for block in workflow_blocks(parsed)}+ assert blocks["summarize_statement"]["code"].strip() == 'return {"status": "ready"}'+ assert "async with page.expect_download()" in blocks["scout_synthesized_browser_steps"]["code"]++ def test_prior_synthesized_label_prevents_unrelated_multi_code_imposition(self) -> None:+ ctx = self._download_ctx()+ prior_yaml = _yaml(+ """+ title: Statement download+ workflow_definition:+ blocks:+ - block_type: code+ label: summarize_statement+ code: |+ return {"status": "ready"}+ - block_type: code+ label: scout_synthesized_browser_steps+ code: |+ await page.locator("#statement-row").click()+ """+ )+ submitted_yaml = _yaml(+ """+ title: Statement download+ workflow_definition:+ blocks:+ - block_type: code+ label: summarize_statement+ code: |+ return {"status": "edited"}+ - block_type: code+ label: scout_synthesized_browser_steps+ code: |+ await page.locator("#statement-row").click()+ """+ )+ ctx.workflow_yaml = prior_yaml++ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted_yaml, ctx)++ assert result.violations == []+ assert result.substitutions is None+ parsed = parse_workflow_yaml(result.workflow_yaml)+ assert isinstance(parsed, dict)+ blocks = {str(block.get("label")): block for block in workflow_blocks(parsed)}+ assert blocks["summarize_statement"]["code"].strip() == 'return {"status": "edited"}'+ assert blocks["scout_synthesized_browser_steps"]["code"].strip() == (+ 'await page.locator("#statement-row").click()'+ )+@pytest.mark.asyncioasync 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.pyindex cbbd95107..7d620a070 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -1319,6 +1319,10 @@ class TestDownloadRungSynthesis:download_obj = f"{_DOWNLOAD_VAR_BASE}_file"assert f"{download_obj} = await {_DOWNLOAD_VAR_BASE}.value" in result.codeassert f"await {download_obj}.path()" in result.code+ assert '"downloaded_file_name": downloaded_file_name' in result.code+ assert '"download_url"' not in result.code+ assert '"downloaded_file_path"' not in result.code+ assert '"downloaded_files"' not 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.@@ -1395,8 +1399,13 @@ class TestDownloadRungSynthesis:download_obj = f"{_DOWNLOAD_VAR_BASE}_file"assert result.code.count(f"{download_obj} = await {_DOWNLOAD_VAR_BASE}.value") == 1# 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.+ # registers the single file when available; the returned summary keeps the filename JSON-safe.assert f"await {download_obj}.path()" in result.code+ assert "return {" in result.code+ assert '"downloaded_file_name": downloaded_file_name' in result.code+ assert '"downloaded_file_path"' not in result.code+ assert '"download_url"' not in result.code+ assert '"downloaded_files"' not in result.codeassert "save_as" not in result.codeCodeBlock.is_safe_code("async def _block(page):\n" + result.code)