Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-11170 Re-anchor role+name bare-selector clicks in strict synthesis (#6733)
Andrew Neilson9ba9f28dd317
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex 6f8dbe201..c9e55342d 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -315,6 +315,20 @@ def _locator_expr(parsed_strict = _parse_role_name(selector)ambiguous_role = parsed_strict is not None and not parsed_strict[1]if ambiguous_role or _is_bare_ambiguous_selector(selector):+ if role and name:+ expr = _get_by_role_expr(role, name)+ if diagnostics is not None:+ diagnostics.locator_provenance.append(+ {+ "trajectory_index": trajectory_index if trajectory_index is not None else -1,+ "selector": selector,+ "emitted_literal": expr,+ "source": "aria_role_name",+ "role": role,+ "name": name,+ }+ )+ return exprnotes.append(f"dropped an interaction with an ambiguous bare selector {selector!r}")if diagnostics is not None:diagnostics.dropped_interactions.append(diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex dd113836c..2bf5d8411 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -29,6 +29,7 @@ from skyvern.forge.sdk.copilot.code_block_steps import apply_derived_code_block_from skyvern.forge.sdk.copilot.code_block_synthesis import (_SYNTHESIZED_BLOCK_LABEL,SynthesisDiagnostics,+ _get_by_role_expr,artifact_dependency_id,artifact_observation_ref_id,synthesize_code_block,@@ -1115,6 +1116,17 @@ def _is_ignorable_entry_opener_drop(dropped: Mapping[str, Any], diagnostics: Syn)+def _locator_provenance_is_self_validating(provenance: Mapping[str, Any]) -> bool:+ source = provenance.get("source")+ if source == "selector":+ return provenance.get("selector") == provenance.get("emitted_literal")+ if source == "aria_role_name":+ role = str(provenance.get("role") or "")+ name = str(provenance.get("name") or "")+ return bool(role) and bool(name) and _get_by_role_expr(role, name) == provenance.get("emitted_literal")+ return False++def _submitted_suffix_after_synthesized_code(submitted_code: str, synthesized_code: str) -> str:# Preserve a pure suffix appended after the synthesized steps. Returns empty for# prepended extraction scaffolding; that shape is handled by preserve_submitted_extraction.@@ -2093,7 +2105,7 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext)f"Unable to impose synthesized code block: dropped scout interaction {index} from `{tool_name}` ({reason}).")for provenance in diagnostics.locator_provenance:- if provenance.get("source") != "selector" or provenance.get("selector") != provenance.get("emitted_literal"):+ if not _locator_provenance_is_self_validating(provenance):violations.append("Unable to impose synthesized code block: locator provenance was not byte-equal.")breakdiff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex d9e349c9e..5c6e72c57 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -13,6 +13,7 @@ import pytestimport yamlfrom skyvern.forge.sdk.copilot.blocker_signal import assert_clean_user_facing_text+from skyvern.forge.sdk.copilot.code_block_synthesis import _get_by_role_exprfrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget@@ -1922,6 +1923,124 @@ class TestCompiledAuthoringImposition:assert "other_sku_456" in str(block.get("code") or "")assert "str(search)" not in str(block.get("code") or "")+ def _role_name_nav_download_ctx(self) -> CopilotContext:+ 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,+ },+ {+ "tool_name": "click",+ "selector": "a",+ "source_url": "https://example.com/billing",+ "role": "link",+ "accessible_name": "View Printable Statement",+ },+ ]+ 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++ def test_role_name_bare_nav_click_imposes_with_emitted_get_by_role(self) -> None:+ ctx = self._role_name_nav_download_ctx()+ workflow_yaml = _yaml(+ """+ title: Statement download+ workflow_definition:+ blocks:+ - block_type: code+ label: download_statement+ code: |+ await page.locator("#statement-row").click()+ """+ )++ result = workflow_update_module._maybe_impose_synthesized_code_block(workflow_yaml, ctx)++ assert result.violations == []+ block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))+ assert 'await page.get_by_role("link", name="View Printable Statement").click()' in block["code"]+ assert "async with page.expect_download()" in block["code"]+ assert "/billing/statement.pdf" in block["code"]++ def test_anchorless_bare_nav_click_still_blocks_imposition(self) -> None:+ ctx = self._role_name_nav_download_ctx()+ ctx.scout_trajectory[1].pop("role")+ ctx.scout_trajectory[1].pop("accessible_name")+ workflow_yaml = _yaml(+ """+ title: Statement download+ workflow_definition:+ blocks:+ - block_type: code+ label: download_statement+ code: |+ await page.locator("#statement-row").click()+ """+ )++ result = workflow_update_module._maybe_impose_synthesized_code_block(workflow_yaml, ctx)++ assert any("ambiguous_bare_selector" in violation for violation in result.violations)++ def test_provenance_gate_admits_self_validating_aria_role_name(self) -> None:+ entry = {+ "trajectory_index": 1,+ "selector": "a",+ "emitted_literal": _get_by_role_expr("link", "View Statements"),+ "source": "aria_role_name",+ "role": "link",+ "name": "View Statements",+ }+ assert workflow_update_module._locator_provenance_is_self_validating(entry) is True++ def test_provenance_gate_rejects_tampered_aria_role_name(self) -> None:+ tampered_literal = {+ "selector": "a",+ "emitted_literal": 'page.get_by_role("link", name="Spoofed")',+ "source": "aria_role_name",+ "role": "link",+ "name": "View Statements",+ }+ tampered_role = {+ "selector": "a",+ "emitted_literal": _get_by_role_expr("link", "View Statements"),+ "source": "aria_role_name",+ "role": "button",+ "name": "View Statements",+ }+ assert workflow_update_module._locator_provenance_is_self_validating(tampered_literal) is False+ assert workflow_update_module._locator_provenance_is_self_validating(tampered_role) is False++ def test_provenance_gate_keeps_selector_byte_equality(self) -> None:+ assert (+ workflow_update_module._locator_provenance_is_self_validating(+ {"selector": "#row", "emitted_literal": "#row", "source": "selector"}+ )+ is True+ )+ assert (+ workflow_update_module._locator_provenance_is_self_validating(+ {"selector": "#row", "emitted_literal": "#other", "source": "selector"}+ )+ is False+ )+ assert (+ workflow_update_module._locator_provenance_is_self_validating(+ {"selector": "#row", "emitted_literal": "#row", "source": "first_fallback"}+ )+ is False+ )+def test_direct_literal_rewrite_preserves_unicode_prefix_offsets() -> None:code = textwrap.dedent(diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 230120d07..f88cbcd8f 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -19,6 +19,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (_MAX_STEPS,_SYNTHESIZED_BLOCK_LABEL,CREDENTIAL_FILL_TOOL_NAME,+ _get_by_role_expr,build_synthesized_artifact_metadata,code_contains_credential_fill,is_optional_dismissal_only_trajectory,@@ -249,6 +250,81 @@ class TestLocatorSynthesis:assert 'await page.locator("*[data-id]").click()' in result.codeassert ".first" not in result.code+ def test_strict_bare_selector_with_role_name_reanchors_to_get_by_role(self) -> None:+ trajectory = [+ _interaction("click", selector="#statement-row", source_url="https://example.com/billing"),+ _interaction(+ "click",+ selector="a",+ source_url="https://example.com/billing",+ role="link",+ accessible_name="View Statements",+ ),+ ]+ result = synthesize_code_block(trajectory, strict_selectors=True)+ assert result is not None+ assert 'await page.get_by_role("link", name="View Statements").click()' in result.code+ assert ".first" not in result.code+ assert result.diagnostics.dropped_interactions == []+ provenance = [p for p in result.diagnostics.locator_provenance if p.get("source") == "aria_role_name"]+ assert provenance == [+ {+ "trajectory_index": 1,+ "selector": "a",+ "emitted_literal": _get_by_role_expr("link", "View Statements"),+ "source": "aria_role_name",+ "role": "link",+ "name": "View Statements",+ }+ ]++ def test_strict_bare_role_selector_with_name_reanchors_to_get_by_role(self) -> None:+ trajectory = [+ _interaction("click", selector="#open", source_url="https://example.com/home"),+ _interaction(+ "click",+ selector="role=link",+ source_url="https://example.com/home",+ role="link",+ accessible_name="Continue",+ ),+ ]+ result = synthesize_code_block(trajectory, strict_selectors=True)+ assert result is not None+ assert 'await page.get_by_role("link", name="Continue").click()' in result.code+ assert result.diagnostics.dropped_interactions == []++ def test_strict_bare_selector_without_role_name_is_still_dropped(self) -> None:+ trajectory = [+ _interaction("click", selector="#open-login", source_url="https://example.com/home"),+ _interaction("click", selector="a", source_url="https://example.com/account"),+ ]+ result = synthesize_code_block(trajectory, strict_selectors=True)+ assert result is not None+ assert "get_by_role" not in result.code+ dropped = [+ d for d in result.diagnostics.dropped_interactions if d.get("reason_code") == "ambiguous_bare_selector"+ ]+ assert dropped++ def test_strict_reanchor_escapes_quotes_and_newlines_in_name(self) -> None:+ trajectory = [+ _interaction("click", selector="#open", source_url="https://example.com/home"),+ _interaction(+ "click",+ selector="a",+ source_url="https://example.com/home",+ role="link",+ accessible_name='Say "hi"\nplease',+ ),+ ]+ result = synthesize_code_block(trajectory, strict_selectors=True)+ assert result is not None+ assert result.diagnostics.dropped_interactions == []+ emitted = _get_by_role_expr("link", 'Say "hi"\nplease')+ assert "\n" not in emitted+ assert f"await {emitted}.click()" in result.code+class TestActionSynthesis:def test_type_text_becomes_param_slot_fill(self) -> None: