Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-12613: Add selection-shaped routes to the typed binding corrective (#7567)
Andrew Neilsona89e503b7012
diff --git a/skyvern/forge/sdk/copilot/authoring_parameter_binding.py b/skyvern/forge/sdk/copilot/authoring_parameter_binding.pyindex e863cd572..a0dc9c2a4 100644--- a/skyvern/forge/sdk/copilot/authoring_parameter_binding.py+++ b/skyvern/forge/sdk/copilot/authoring_parameter_binding.py@@ -12,8 +12,14 @@ AuthoringParameterBindingMatchBasis = Literal["exact_authored_selector","grounded_input_correspondence","unique_ephemeral_value",+ "scouted_selection_value",+ "scouted_option_value",]-AuthoringParameterBindingTerminalTool = Literal["click", "press_key"]+AuthoringParameterBindingTerminalTool = Literal["click", "press_key", "select_option"]++_SELECTION_MATCH_BASES: frozenset[AuthoringParameterBindingMatchBasis] = frozenset(+ {"scouted_selection_value", "scouted_option_value"}+)class AuthoringParameterFieldBinding(BaseModel):@@ -172,6 +178,64 @@ def authored_selector_parameter_bindings(code: str, declared_keys: set[str]) ->return bindings+def _formatted_value_name(node: ast.AST) -> str | None:+ if isinstance(node, ast.Name):+ return node.id+ if isinstance(node, ast.Call) and len(node.args) == 1 and isinstance(node.args[0], ast.Name):+ return node.args[0].id+ return None+++def _templated_locator_declared_key(receiver: ast.AST, declared_keys: set[str]) -> str | None:+ if not isinstance(receiver, ast.Call) or not isinstance(receiver.func, ast.Attribute):+ return None+ if not isinstance(receiver.func.value, ast.Name) or receiver.func.value.id != "page":+ return None+ joined: ast.AST | None = None+ if receiver.func.attr == "locator" and len(receiver.args) == 1:+ joined = receiver.args[0]+ elif receiver.func.attr == "get_by_role":+ for keyword_arg in receiver.keywords:+ if keyword_arg.arg == "name":+ joined = keyword_arg.value+ if not isinstance(joined, ast.JoinedStr):+ return None+ keys: set[str] = set()+ for value in joined.values:+ if not isinstance(value, ast.FormattedValue):+ continue+ name = _formatted_value_name(value.value)+ if name is None:+ return None+ if name in declared_keys:+ keys.add(name)+ if len(keys) != 1:+ return None+ return next(iter(keys))+++def authored_selection_parameter_bindings(code: str, declared_keys: set[str]) -> dict[str, set[str]] | None:+ try:+ tree = ast.parse(code)+ except SyntaxError:+ return None+ bindings: dict[str, set[str]] = {}+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):+ continue+ if node.func.attr == "click":+ key = _templated_locator_declared_key(node.func.value, declared_keys)+ if key is None:+ continue+ bindings.setdefault(ast.unparse(node.func.value), set()).add(key)+ elif node.func.attr == "select_option":+ selector = _literal_locator_selector(node.func.value)+ parameter_key = _fill_parameter_key(node)+ if selector and parameter_key in declared_keys:+ bindings.setdefault(selector, set()).add(parameter_key)+ return bindings++def authoring_parameter_binding_directive_consumed(directive: AuthoringParameterBindingDirective,snapshot: AuthoringParameterBindingSnapshot,@@ -192,9 +256,17 @@ def authoring_parameter_binding_directive_consumed(declared_keys = {binding.declared_key for binding in snapshot.field_bindings}if not declared_keys.issubset(parameter_keys):return False- authored = authored_selector_parameter_bindings(code, declared_keys)- if authored is None:+ fill_authored = authored_selector_parameter_bindings(code, declared_keys)+ if fill_authored is None:+ return False+ selection_needed = any(binding.match_basis in _SELECTION_MATCH_BASES for binding in snapshot.field_bindings)+ selection_authored = authored_selection_parameter_bindings(code, declared_keys) if selection_needed else {}+ if selection_authored is None:return Falsereturn all(- binding.declared_key in authored.get(binding.field_selector, set()) for binding in snapshot.field_bindings+ binding.declared_key+ in (selection_authored if binding.match_basis in _SELECTION_MATCH_BASES else fill_authored).get(+ binding.field_selector, set()+ )+ for binding in snapshot.field_bindings)diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex 2fc393a04..c8561a731 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -363,10 +363,15 @@ def _captured_trajectory_index(interaction: Mapping[str, Any], position: int) ->return raw_index if isinstance(raw_index, int) and raw_index >= 0 else position+class _ValidatedSnapshotBindings(NamedTuple):+ fill_by_index: dict[int, tuple[str, str]]+ select_option_by_index: dict[int, str]++def _validated_authoring_parameter_binding_snapshot(snapshot: AuthoringParameterBindingSnapshot,trajectory: Sequence[Mapping[str, Any]],-) -> dict[int, tuple[str, str]] | None:+) -> _ValidatedSnapshotBindings | None:if not snapshot.field_bindings:return Noneterminal_matches = [@@ -393,7 +398,8 @@ def _validated_authoring_parameter_binding_snapshot()if expected != snapshot.fingerprint:return None- by_index: dict[int, tuple[str, str]] = {}+ fill_by_index: dict[int, tuple[str, str]] = {}+ select_option_by_index: dict[int, str] = {}declared_keys: set[str] = set()selectors: set[str] = set()for binding in snapshot.field_bindings:@@ -418,12 +424,27 @@ def _validated_authoring_parameter_binding_snapshot(field_position, interaction = field_matches[0]if _binding_source_origin(str(interaction.get("source_url") or "")) != snapshot.source_origin:return None+ if binding.match_basis == "scouted_selection_value":+ if str(interaction.get("tool_name") or "") != "click":+ return None+ if templated_selection_locator_binding(interaction) != (binding.declared_key, binding.field_selector):+ return None+ continue+ if binding.match_basis == "scouted_option_value":+ if str(interaction.get("tool_name") or "") != "select_option":+ return None+ if str(interaction.get("selector") or "").strip() != binding.field_selector:+ return None+ if not selection_option_value_admissible(str(interaction.get("value") or "").strip(), binding.declared_key):+ return None+ select_option_by_index[field_position] = binding.declared_key+ continueif str(interaction.get("tool_name") or "") != "type_text":return Noneif str(interaction.get("selector") or "").strip() != binding.field_selector:return None- by_index[field_position] = (binding.declared_key, binding.field_selector)- return by_index+ fill_by_index[field_position] = (binding.declared_key, binding.field_selector)+ return _ValidatedSnapshotBindings(fill_by_index, select_option_by_index)def _validated_submit_rung_binding(@@ -837,6 +858,38 @@ def build_input_templated_locator(return None+def templated_selection_locator_binding(interaction: Mapping[str, Any]) -> tuple[str, str] | None:+ """(declared_key, canonical templated-locator expression) for a click whose stamped+ input_correspondences template exactly one declared-key hole. None when the click is untemplatable+ or witnesses more than one hole. The canonical expression is the join key shared with the consumption+ recognizer, so a re-authored templated click and this snapshot binding agree by construction."""+ plan = _input_templating_plan(interaction)+ if plan is None or len(plan.holes) != 1:+ return None+ key = str(plan.holes[0].get("input_key") or "")+ if not key:+ return None+ expr = build_input_templated_locator(+ surface=plan.surface, selector=plan.selector, role=plan.role, name=plan.name, holes=plan.holes+ )+ if expr is None:+ return None+ try:+ canonical = ast.unparse(ast.parse(expr, mode="eval").body)+ except SyntaxError:+ return None+ return key, canonical+++def selection_option_value_admissible(value: str, key: str) -> bool:+ return (+ value == value.strip()+ and len(value) >= _WITNESS_MIN_VALUE_LEN+ and bool(_WITNESS_SAFE_CHARSET_RE.fullmatch(value))+ and _witness_key_is_safe(key)+ )++def _ordered_holes(raw: str, holes: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]] | None:positioned: list[tuple[int, Mapping[str, Any]]] = []for hole in holes:@@ -1393,14 +1446,17 @@ def synthesize_code_block(grounded_binding_count = sum(1 for interaction in trajectory if "submit_rung_binding" in interaction)if grounded_binding_count > 1 or (grounded_binding_count and parameter_binding_snapshot is not None):return None- snapshot_bindings_by_index = (+ validated_snapshot_bindings = (_validated_authoring_parameter_binding_snapshot(parameter_binding_snapshot, trajectory)if parameter_binding_snapshot is not None- else {}+ else _ValidatedSnapshotBindings({}, {}))- if parameter_binding_snapshot is not None and snapshot_bindings_by_index is None:+ if parameter_binding_snapshot is not None and validated_snapshot_bindings is None:return None- snapshot_bindings_by_index = snapshot_bindings_by_index or {}+ if validated_snapshot_bindings is None:+ validated_snapshot_bindings = _ValidatedSnapshotBindings({}, {})+ snapshot_bindings_by_index = validated_snapshot_bindings.fill_by_index+ snapshot_select_option_by_index = validated_snapshot_bindings.select_option_by_indexsnapshot_recovery_bindings = ([binding for binding in parameter_binding_snapshot.field_bindings if binding.field_trajectory_index is None]if parameter_binding_snapshot is not None@@ -1907,6 +1963,7 @@ def synthesize_code_block(lines.append(f"{action_indent}await {locator}.fill({credential_param_key}.{credential_field})")record_emission(trajectory_index, tool_name, "fill", locator, line_start=line_start)elif tool_name == "select_option":+ emit_snapshot_recovery(trajectory_index, action_indent)value = str(interaction.get("value") or "").strip()if not value:notes.append("dropped a select_option interaction with no recorded value")@@ -1914,7 +1971,14 @@ def synthesize_code_block({"trajectory_index": trajectory_index, "tool_name": tool_name, "reason_code": "missing_value"})continue- lines.append(f"{action_indent}await {locator}.select_option({_py_str(value)})")+ bound_key = snapshot_select_option_by_index.get(trajectory_index)+ if bound_key is not None:+ if bound_key not in used_param_keys:+ used_param_keys.add(bound_key)+ parameters.append({"key": bound_key})+ lines.append(f"{action_indent}await {locator}.select_option(str({bound_key}))")+ else:+ lines.append(f"{action_indent}await {locator}.select_option({_py_str(value)})")lines.append(f"{action_indent}await page.wait_for_load_state({_py_str(_DOMCONTENTLOADED)})")record_emission(trajectory_index, tool_name, "select_option", locator, line_start=line_start)append_step(f"Select {value} in {_step_target(interaction)}", "select_option", line_start)diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex e0be04a71..57b7b3dde 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -114,9 +114,11 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (produce_covered_static_return_envelope,render_missing_rung_call_sources,render_obligation_findings,+ selection_option_value_admissible,spine_partition_findings,synthesize_code_block,synthesize_code_block_with_extraction,+ templated_selection_locator_binding,uncovered_required_emitted_interactions,uncovered_rung_records,)@@ -2343,6 +2345,111 @@ class _AuthoringParameterBindingResolution(NamedTuple):directive: AuthoringParameterBindingDirective | None+class _SelectionBindingRecord(NamedTuple):+ declared_key: str+ match_basis: AuthoringParameterBindingMatchBasis+ field_selector: str+ trajectory_index: int+ terminal_tool: AuthoringParameterBindingTerminalTool+ terminal_selector: str+++def _selection_parameter_binding_resolution(+ ctx: AgentContext,+ *,+ target_keys: Sequence[str],+ ephemeral_values: Mapping[str, Any],+ structural_key: str,+ source_origin: str,+) -> _AuthoringParameterBindingResolution:+ trajectory = ctx.scout_trajectory+ if not isinstance(trajectory, list) or not trajectory:+ return _AuthoringParameterBindingResolution(None, None)+ target = set(target_keys)+ admitted: list[_SelectionBindingRecord] = []+ for position, interaction in enumerate(trajectory):+ if not isinstance(interaction, Mapping):+ continue+ if url_origin(str(interaction.get("source_url") or "").strip()) != source_origin:+ continue+ tool = str(interaction.get("tool_name") or "")+ index = _scout_trajectory_index(interaction, position)+ if tool == "click":+ templated = templated_selection_locator_binding(interaction)+ if templated is None:+ continue+ key, join_selector = templated+ if key in target:+ admitted.append(+ _SelectionBindingRecord(+ key,+ "scouted_selection_value",+ join_selector,+ index,+ "click",+ str(interaction.get("selector") or "").strip(),+ )+ )+ elif tool == "select_option":+ value = str(interaction.get("value") or "").strip()+ selector = _safe_selector_repair_atom(interaction.get("selector"))+ if not value or not selector:+ continue+ for key in target_keys:+ key_value = ephemeral_values.get(key)+ if isinstance(key_value, str) and key_value == value and selection_option_value_admissible(value, key):+ admitted.append(+ _SelectionBindingRecord(key, "scouted_option_value", selector, index, "select_option", selector)+ )+ if not admitted:+ return _AuthoringParameterBindingResolution(None, None)+ directive = build_authoring_parameter_binding_directive(+ structural_key=structural_key,+ source_origin=source_origin,+ candidates=[+ AuthoringParameterBindingCandidate(declared_key=record.declared_key, field_selector=record.field_selector)+ for record in admitted+ ],+ )+ resolved: list[AuthoringParameterFieldBinding] = []+ for key in target_keys:+ matches = [record for record in admitted if record.declared_key == key]+ if len(matches) != 1:+ return _AuthoringParameterBindingResolution(None, directive)+ record = matches[0]+ resolved.append(+ AuthoringParameterFieldBinding(+ declared_key=key,+ field_selector=record.field_selector,+ field_trajectory_index=record.trajectory_index,+ match_basis=record.match_basis,+ )+ )+ if len({binding.field_selector for binding in resolved}) != len(resolved):+ return _AuthoringParameterBindingResolution(None, directive)+ terminal_record = max(admitted, key=lambda record: record.trajectory_index)+ terminal = AuthoringParameterTerminalBinding(+ tool_name=terminal_record.terminal_tool,+ trajectory_index=terminal_record.trajectory_index,+ selector=terminal_record.terminal_selector,+ )+ snapshot = build_authoring_parameter_binding_snapshot(+ structural_key=structural_key,+ source_origin=source_origin,+ field_bindings=resolved,+ terminal=terminal,+ )+ LOG.info(+ "copilot recorded outcome selection rung bound",+ binding_fingerprint=snapshot.fingerprint,+ parameter_keys=[binding.declared_key for binding in snapshot.field_bindings],+ binding_count=len(snapshot.field_bindings),+ terminal_tool=snapshot.terminal.tool_name,+ terminal_trajectory_index=snapshot.terminal.trajectory_index,+ )+ return _AuthoringParameterBindingResolution(snapshot, directive)++def _pending_authoring_parameter_binding_directive(ctx: AgentContext,) -> tuple[CodeAuthoringRepairContext, AuthoringParameterBindingDirective] | None:@@ -2423,6 +2530,7 @@ def _authoring_parameter_binding_resolution(snapshots: list[AuthoringParameterBindingSnapshot] = []candidate_pairs: list[AuthoringParameterBindingCandidate] = []+ any_active_fields = Falsefor form in forms:if not isinstance(form, Mapping):continue@@ -2430,6 +2538,7 @@ def _authoring_parameter_binding_resolution(active_fields = [field for field in fields if field.get("disabled") is not True and str(field.get("selector") or "").strip()]+ any_active_fields = any_active_fields or bool(active_fields)field_selectors = {str(field.get("selector") or "").strip() for field in active_fields}submit_selectors = {str(control.get("selector") or "").strip()@@ -2555,6 +2664,17 @@ def _authoring_parameter_binding_resolution(else None)if len(unique_snapshots) != 1:+ if not any_active_fields:+ selection = _selection_parameter_binding_resolution(+ ctx,+ target_keys=target_keys,+ ephemeral_values=ephemeral_values,+ structural_key=structural_key,+ source_origin=source_origin,+ )+ if selection.snapshot is not None:+ return selection+ return _AuthoringParameterBindingResolution(None, directive or selection.directive)return _AuthoringParameterBindingResolution(None, directive)snapshot = next(iter(unique_snapshots.values()))LOG.info(diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex 4a54b4d19..57a5a14bf 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -1611,6 +1611,200 @@ class TestCodeRepairProgressClassification:assert code.index(fill) < code.index(terminal_call)assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is None+ @pytest.mark.asyncio+ async def test_selection_shaped_binding_references_declared_keys_without_fillable_surface(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = _definition_contract_ctx()+ _enable_imposition(ctx)+ submitted = _yaml(+ """+ title: Retrieve statement rows+ workflow_definition:+ parameters:+ - {parameter_type: workflow, key: account_number, workflow_parameter_type: string, default_value: "AC12345"}+ - {parameter_type: workflow, key: billing_start_date, workflow_parameter_type: string, default_value: "2026-08-01"}+ blocks:+ - block_type: code+ label: open_statement_rows+ parameter_keys: []+ code: |+ await page.locator("[data-account=\\"AC12345\\"]").click()+ await page.locator("[data-range=\\"2026-08-01\\"]").click()+ """+ )+ for _ in range(2):+ assert (await _update_workflow({"workflow_yaml": submitted}, ctx))["ok"] is False+ assert arm_recorded_outcome_grounding_requirement(ctx) is not None+ source_url = "https://example.com/statements"+ values = {"account_number": "AC12345", "billing_start_date": "2026-08-01"}+ ctx.scout_trajectory = [+ {+ "tool_name": "click",+ "selector": '[data-account="AC12345"]',+ "source_url": source_url,+ "trajectory_index": 0,+ },+ {+ "tool_name": "click",+ "selector": '[data-range="2026-08-01"]',+ "source_url": source_url,+ "trajectory_index": 1,+ },+ ]+ ctx.composition_page_evidence = {+ "source_tool": "inspect_page_for_composition",+ "current_url": source_url,+ "forms": [],+ }+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True++ result = await _update_workflow(+ {"workflow_yaml": submitted, "parameters": values},+ ctx,+ allow_missing_credentials=True,+ )++ assert result["ok"] is True+ parsed = parse_workflow_yaml(ctx.workflow_yaml)+ assert isinstance(parsed, dict)+ block = next(block for block in workflow_blocks(parsed) if block.get("label") == "open_statement_rows")+ code = str(block["code"])+ assert 'f"[data-account=\\"{account_number}\\"]"' in code+ assert 'f"[data-range=\\"{billing_start_date}\\"]"' in code+ assert set(block["parameter_keys"]) == {"account_number", "billing_start_date"}+ assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is None+ assert ctx.authoring_parameter_binding_snapshot is not None++ def test_selection_resolution_binds_witnessed_click_value(self) -> None:+ ctx = SimpleNamespace(+ scout_trajectory=[+ {+ "tool_name": "click",+ "selector": '[data-account="100245"]',+ "source_url": "https://example.com/statements",+ "trajectory_index": 0,+ }+ ]+ )+ for interaction in ctx.scout_trajectory:+ interaction["input_correspondences"] = code_block_synthesis_module.input_correspondences_for_interaction(+ interaction, {"account_number": "100245"}+ )+ resolution = workflow_update_module._selection_parameter_binding_resolution(+ ctx,+ target_keys=["account_number"],+ ephemeral_values={"account_number": "100245"},+ structural_key="definition-reject",+ source_origin="https://example.com",+ )+ assert resolution.snapshot is not None+ binding = resolution.snapshot.field_bindings[0]+ assert binding.declared_key == "account_number"+ assert binding.match_basis == "scouted_selection_value"++ def test_selection_resolution_rejects_prose_echo_without_scouted_interaction(self) -> None:+ ctx = SimpleNamespace(+ scout_trajectory=[+ {+ "tool_name": "click",+ "selector": "#unrelated-open-button",+ "source_url": "https://example.com/statements",+ "trajectory_index": 0,+ }+ ]+ )+ for interaction in ctx.scout_trajectory:+ interaction["input_correspondences"] = code_block_synthesis_module.input_correspondences_for_interaction(+ interaction, {"account_number": "100245"}+ )+ resolution = workflow_update_module._selection_parameter_binding_resolution(+ ctx,+ target_keys=["account_number"],+ ephemeral_values={"account_number": "100245"},+ structural_key="definition-reject",+ source_origin="https://example.com",+ )+ assert resolution.snapshot is None+ assert resolution.directive is None++ def test_selection_resolution_short_value_below_witness_bar_does_not_bind(self) -> None:+ ctx = SimpleNamespace(+ scout_trajectory=[+ {+ "tool_name": "select_option",+ "selector": "#plan",+ "value": "US",+ "source_url": "https://example.com/statements",+ "trajectory_index": 0,+ }+ ]+ )+ resolution = workflow_update_module._selection_parameter_binding_resolution(+ ctx,+ target_keys=["region"],+ ephemeral_values={"region": "US"},+ structural_key="definition-reject",+ source_origin="https://example.com",+ )+ assert resolution.snapshot is None+ assert resolution.directive is None++ def test_selection_resolution_multiple_matches_yield_candidates_without_snapshot(self) -> None:+ trajectory = [+ {+ "tool_name": "click",+ "selector": '[data-account="100245"]',+ "source_url": "https://example.com/statements",+ "trajectory_index": 0,+ },+ {+ "tool_name": "click",+ "selector": '[data-ref="100245"]',+ "source_url": "https://example.com/statements",+ "trajectory_index": 1,+ },+ ]+ for interaction in trajectory:+ interaction["input_correspondences"] = code_block_synthesis_module.input_correspondences_for_interaction(+ interaction, {"account_number": "100245"}+ )+ ctx = SimpleNamespace(scout_trajectory=trajectory)+ resolution = workflow_update_module._selection_parameter_binding_resolution(+ ctx,+ target_keys=["account_number"],+ ephemeral_values={"account_number": "100245"},+ structural_key="definition-reject",+ source_origin="https://example.com",+ )+ assert resolution.snapshot is None+ assert resolution.directive is not None++ def test_selection_resolution_cross_origin_click_is_not_admitted(self) -> None:+ trajectory = [+ {+ "tool_name": "click",+ "selector": '[data-account="100245"]',+ "source_url": "https://other.example.org/statements",+ "trajectory_index": 0,+ }+ ]+ for interaction in trajectory:+ interaction["input_correspondences"] = code_block_synthesis_module.input_correspondences_for_interaction(+ interaction, {"account_number": "100245"}+ )+ ctx = SimpleNamespace(scout_trajectory=trajectory)+ resolution = workflow_update_module._selection_parameter_binding_resolution(+ ctx,+ target_keys=["account_number"],+ ephemeral_values={"account_number": "100245"},+ structural_key="definition-reject",+ source_origin="https://example.com",+ )+ assert resolution.snapshot is None+ assert resolution.directive is None+@pytest.mark.asyncioasync def test_corrective_pass_satisfies_definition_and_scouted_spine_gates_jointly(self, monkeypatch: pytest.MonkeyPatchdiff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 981911220..ed5c1df7a 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -18,9 +18,12 @@ from typing import Anyimport pytestfrom skyvern.forge.sdk.copilot.authoring_parameter_binding import (+ _SELECTION_MATCH_BASES,AuthoringParameterBindingCandidate,AuthoringParameterFieldBinding,AuthoringParameterTerminalBinding,+ authored_selection_parameter_bindings,+ authored_selector_parameter_bindings,authoring_parameter_binding_directive_consumed,build_authoring_parameter_binding_directive,build_authoring_parameter_binding_snapshot,@@ -63,6 +66,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (synthesize_code_block,synthesize_code_block_with_extraction,synthesize_extraction_suffix,+ templated_selection_locator_binding,uncovered_required_emitted_interactions,witness_prelude_lines,)@@ -353,6 +357,172 @@ def test_authoring_parameter_snapshot_fails_closed_when_terminal_identity_changeassert synthesize_code_block(trajectory, strict_selectors=True, parameter_binding_snapshot=snapshot) is None+def _templated_selection_click(selector: str, key: str, value: str, index: int) -> dict[str, Any]:+ interaction = _interaction(+ "click", selector=selector, source_url="https://example.com/list", trajectory_index=index+ )+ interaction["input_correspondences"] = input_correspondences_for_interaction(interaction, {key: value})+ return interaction+++def test_authored_selection_bindings_recognizes_templated_click_and_select_option() -> None:+ code = (+ 'await page.locator(f"[data-account=\\"{account_number}\\"]").click()\n'+ 'await page.locator("#plan").select_option(str(plan_tier))\n'+ )+ bindings = authored_selection_parameter_bindings(code, {"account_number", "plan_tier"})+ assert bindings is not None+ assert bindings.get("#plan") == {"plan_tier"}+ assert {key for keys in bindings.values() for key in keys} == {"account_number", "plan_tier"}+ assert authored_selector_parameter_bindings(code, {"account_number", "plan_tier"}) == {}+++def test_authored_selection_bindings_ignores_literal_only_click() -> None:+ code = 'await page.locator("#row-account-AC12345").click()\n'+ assert authored_selection_parameter_bindings(code, {"account_number"}) == {}+++def test_authoring_parameter_directive_consumed_via_templated_click() -> None:+ click = _templated_selection_click('[data-account="AC12345"]', "account_number", "AC12345", 0)+ key, join = templated_selection_locator_binding(click)+ assert key == "account_number"+ snapshot = build_authoring_parameter_binding_snapshot(+ structural_key="definition-reject",+ source_origin="https://example.com",+ field_bindings=[+ AuthoringParameterFieldBinding(+ declared_key="account_number",+ field_selector=join,+ field_trajectory_index=0,+ match_basis="scouted_selection_value",+ )+ ],+ terminal=AuthoringParameterTerminalBinding(+ tool_name="click", trajectory_index=0, selector='[data-account="AC12345"]'+ ),+ )+ directive = build_authoring_parameter_binding_directive(+ structural_key="definition-reject",+ source_origin="https://example.com",+ candidates=[AuthoringParameterBindingCandidate(declared_key="account_number", field_selector=join)],+ )+ consumed_code = 'await page.locator(f"[data-account=\\"{account_number}\\"]").click()'+ assert authoring_parameter_binding_directive_consumed(+ directive, snapshot, code=consumed_code, parameter_keys=["account_number"]+ )+ assert not authoring_parameter_binding_directive_consumed(+ directive,+ snapshot,+ code='await page.locator("#row-account-AC12345").click()',+ parameter_keys=["account_number"],+ )+++def test_authoring_parameter_directive_consumed_via_select_option_value_argument() -> None:+ snapshot = build_authoring_parameter_binding_snapshot(+ structural_key="definition-reject",+ source_origin="https://example.com",+ field_bindings=[+ AuthoringParameterFieldBinding(+ declared_key="plan_tier",+ field_selector="#plan",+ field_trajectory_index=0,+ match_basis="scouted_option_value",+ )+ ],+ terminal=AuthoringParameterTerminalBinding(tool_name="select_option", trajectory_index=0, selector="#plan"),+ )+ directive = build_authoring_parameter_binding_directive(+ structural_key="definition-reject",+ source_origin="https://example.com",+ candidates=[AuthoringParameterBindingCandidate(declared_key="plan_tier", field_selector="#plan")],+ )+ assert authoring_parameter_binding_directive_consumed(+ directive,+ snapshot,+ code='await page.locator("#plan").select_option(str(plan_tier))',+ parameter_keys=["plan_tier"],+ )+ assert not authoring_parameter_binding_directive_consumed(+ directive,+ snapshot,+ code='await page.locator("#plan").select_option("premium")',+ parameter_keys=["plan_tier"],+ )+++def test_selection_snapshot_click_binding_references_declared_key() -> None:+ click = _templated_selection_click('[data-account="AC12345"]', "account_number", "AC12345", 0)+ _key, join = templated_selection_locator_binding(click)+ snapshot = build_authoring_parameter_binding_snapshot(+ structural_key="definition-reject",+ source_origin="https://example.com",+ field_bindings=[+ AuthoringParameterFieldBinding(+ declared_key="account_number",+ field_selector=join,+ field_trajectory_index=0,+ match_basis="scouted_selection_value",+ )+ ],+ terminal=AuthoringParameterTerminalBinding(+ tool_name="click", trajectory_index=0, selector='[data-account="AC12345"]'+ ),+ )+ result = synthesize_code_block([click], strict_selectors=True, parameter_binding_snapshot=snapshot)+ assert result is not None+ assert 'page.locator(f"[data-account=\\"{account_number}\\"]").click()' in result.code+ assert ".fill(" not in result.code+++def test_selection_snapshot_select_option_binds_value_argument() -> None:+ select = _interaction(+ "select_option", selector="#plan", value="premium", source_url="https://example.com/list", trajectory_index=0+ )+ snapshot = build_authoring_parameter_binding_snapshot(+ structural_key="definition-reject",+ source_origin="https://example.com",+ field_bindings=[+ AuthoringParameterFieldBinding(+ declared_key="plan_tier",+ field_selector="#plan",+ field_trajectory_index=0,+ match_basis="scouted_option_value",+ )+ ],+ terminal=AuthoringParameterTerminalBinding(tool_name="select_option", trajectory_index=0, selector="#plan"),+ )+ result = synthesize_code_block([select], strict_selectors=True, parameter_binding_snapshot=snapshot)+ assert result is not None+ assert 'page.locator("#plan").select_option(str(plan_tier))' in result.code+ assert '"premium"' not in result.code+ assert result.parameters == [{"key": "plan_tier"}]+++def test_fill_snapshot_never_emits_select_option_value_binding() -> None:+ trajectory = [+ _interaction("type_text", selector="#location", source_url="https://example.com/form", trajectory_index=7),+ _interaction("click", selector="#submit", source_url="https://example.com/form", trajectory_index=9),+ ]+ snapshot = build_authoring_parameter_binding_snapshot(+ structural_key="definition-reject",+ source_origin="https://example.com",+ field_bindings=[+ AuthoringParameterFieldBinding(+ declared_key="search_location",+ field_selector="#location",+ field_trajectory_index=7,+ match_basis="unique_ephemeral_value",+ )+ ],+ terminal=AuthoringParameterTerminalBinding(tool_name="click", trajectory_index=9, selector="#submit"),+ )+ result = synthesize_code_block(trajectory, strict_selectors=True, parameter_binding_snapshot=snapshot)+ assert result is not None+ assert ".select_option(" not in result.code+ assert snapshot.terminal.tool_name not in _SELECTION_MATCH_BASES++def _extraction_plan() -> RequestedOutputExtractionPlan:return RequestedOutputExtractionPlan(requested_output_paths=(