Skip to content

Automate browser based workflows with AI

SKY-11113: disambiguate bare role/tag selectors in copilot code-block synthesis (#6648)

Andrew Neilson318b506b70b8
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index c40aa1114..394bc8387 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -104,6 +104,10 @@ _POSITIONAL_RE = re.compile(
r":nth-of-type\(|:nth-child\(|:nth-last-of-type\(|:nth-last-child\(|>>\s*nth=|:first-child|:last-child"
)
+# A lone tag/role token (`button`, `a`) matches every such element, so a bare emission is not
+# unique under Playwright strict mode.
+_BARE_TAG_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9-]*$")
+
@dataclass
class SynthesisDiagnostics:
@@ -208,6 +212,12 @@ def _is_positional_selector(selector: str) -> bool:
return bool(_POSITIONAL_RE.search(selector))
+def _is_bare_ambiguous_selector(selector: str) -> bool:
+ """True when the captured selector is a lone tag/role token or the universal `*` with no qualifier."""
+ stripped = selector.strip()
+ return stripped == "*" or bool(_BARE_TAG_RE.match(stripped))
+
+
def _slug(value: str) -> str:
cleaned = re.sub(r"[^a-zA-Z0-9]+", "_", value.strip().lower()).strip("_")
if cleaned and cleaned[0].isdigit():
@@ -225,7 +235,8 @@ def _safe_param_base(value: str) -> str:
def _get_by_role_expr(role: str, name: str) -> str:
if name:
return f"page.get_by_role({_py_str(role)}, name={_py_str(name)})"
- return f"page.get_by_role({_py_str(role)})"
+ # A nameless role matches every element of that role; `.first` pins the scout's document-order pick.
+ return f"page.get_by_role({_py_str(role)}).first"
def _locator_expr(
@@ -260,6 +271,20 @@ def _locator_expr(
}
)
return ""
+ 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):
+ notes.append(f"dropped an interaction with an ambiguous bare selector {selector!r}")
+ if diagnostics is not None:
+ diagnostics.dropped_interactions.append(
+ {
+ "trajectory_index": trajectory_index if trajectory_index is not None else -1,
+ "tool_name": tool_name,
+ "selector": selector,
+ "reason_code": "ambiguous_bare_selector",
+ }
+ )
+ return ""
if diagnostics is not None:
diagnostics.locator_provenance.append(
{
@@ -290,6 +315,21 @@ def _locator_expr(
return _get_by_role_expr(role, name)
if _is_positional_selector(selector):
notes.append(f"low-confidence locator: positional selector {selector!r} with no role/name to anchor on")
+ return f"page.locator({_py_str(selector)})"
+ if _is_bare_ambiguous_selector(selector):
+ if role and name:
+ return _get_by_role_expr(role, name)
+ notes.append(f"disambiguated a bare {selector!r} selector to .first from scout document order")
+ 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": selector,
+ "source": "first_fallback",
+ }
+ )
+ return f"page.locator({_py_str(selector)}).first"
return f"page.locator({_py_str(selector)})"
if role and name:
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index 10639f430..a7c69d9ca 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -784,6 +784,10 @@ def _wrapped_code_ast(code: str) -> ast.AST | None:
def _is_page_locator_expression(value: ast.AST) -> bool:
+ # Peel a trailing `.first`/`.last` (the synthesizer's disambiguator for a bare role/tag selector)
+ # so literal-fill parameter binding still recognizes the underlying page locator.
+ while isinstance(value, ast.Attribute) and value.attr in {"first", "last"}:
+ value = value.value
if not isinstance(value, ast.Call) or not isinstance(value.func, ast.Attribute):
return False
if value.func.attr not in {"locator", "get_by_role"}:
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index c3d695c53..cf309a942 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -917,6 +917,22 @@ def test_direct_literal_rewrite_preserves_unicode_prefix_offsets() -> None:
)
+def test_literal_binding_sees_through_first_last_disambiguator() -> None:
+ code = textwrap.dedent(
+ """
+ await page.locator("input").first.fill("example_sku_123")
+ await page.get_by_role("textbox").last.type("example_sku_123")
+ """
+ ).strip()
+
+ assert workflow_update_module._submitted_fill_type_arguments(code) == ["example_sku_123", "example_sku_123"]
+
+ rewritten, used_keys = workflow_update_module._rewrite_direct_literal_fills(code, {"example_sku_123": "search"})
+ assert used_keys == ["search"]
+ assert 'await page.locator("input").first.fill(str(search))' in rewritten
+ assert 'await page.get_by_role("textbox").last.type(str(search))' in rewritten
+
+
def test_python_ast_offsets_are_utf8_byte_offsets_for_unicode_source() -> None:
code = 'await page.locator("#café-search-résumé").fill("example_sku_123")'
tree = workflow_update_module._wrapped_code_ast(code)
diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.py
index bb2dddf7c..2537ae4e6 100644
--- a/tests/unit/test_copilot_code_block_synthesis.py
+++ b/tests/unit/test_copilot_code_block_synthesis.py
@@ -132,7 +132,7 @@ class TestLocatorSynthesis:
assert 'await page.locator(".results .item").click()' in result.code
assert not any("low-confidence" in note for note in result.notes)
- def test_never_emits_first_or_last_callables(self) -> None:
+ def test_positional_role_name_anchor_does_not_emit_first(self) -> None:
result = synthesize_code_block(
[
_interaction(
@@ -146,6 +146,107 @@ class TestLocatorSynthesis:
assert ".first" not in result.code
assert ".last" not in result.code
+ def test_bare_tag_selector_disambiguated_to_first(self) -> None:
+ result = synthesize_code_block(
+ [_interaction("click", selector="button", source_url="https://example.com/login")]
+ )
+ assert result is not None
+ assert 'await page.locator("button").first.click()' in result.code
+ assert any("disambiguated a bare" in note for note in result.notes)
+ assert any(p.get("source") == "first_fallback" for p in result.diagnostics.locator_provenance)
+
+ def test_bare_role_no_name_disambiguated_to_first(self) -> None:
+ result = synthesize_code_block(
+ [_interaction("click", selector="role=button", source_url="https://example.com/login")]
+ )
+ assert result is not None
+ assert 'await page.get_by_role("button").first.click()' in result.code
+
+ def test_bare_selector_with_role_name_anchors_on_get_by_role(self) -> None:
+ result = synthesize_code_block(
+ [
+ _interaction(
+ "click",
+ selector="button",
+ source_url="https://example.com/login",
+ role="button",
+ accessible_name="Continue",
+ )
+ ]
+ )
+ assert result is not None
+ assert 'await page.get_by_role("button", name="Continue").click()' in result.code
+ assert ".first" not in result.code
+
+ def test_stable_selector_not_disambiguated_to_first(self) -> None:
+ for selector in ("#submit", '[name="email"]', '[data-testid="go"]', ".results .item"):
+ result = synthesize_code_block(
+ [_interaction("click", selector=selector, source_url="https://example.com/")]
+ )
+ assert result is not None
+ assert ".first" not in result.code, selector
+
+ def test_strict_imposed_refuses_ambiguous_bare_selector(self) -> None:
+ trajectory = [
+ _interaction("click", selector="#open-login", source_url="https://example.com/home"),
+ _interaction("click", selector="button", source_url="https://example.com/login"),
+ ]
+ result = synthesize_code_block(trajectory, strict_selectors=True)
+ assert result is not None
+ assert ".first" not in result.code
+ assert 'await page.locator("button").click()' 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_imposed_refuses_bare_role_no_name(self) -> None:
+ trajectory = [
+ _interaction("click", selector="#open-login", source_url="https://example.com/home"),
+ _interaction("click", selector="role=button", source_url="https://example.com/login"),
+ ]
+ result = synthesize_code_block(trajectory, strict_selectors=True)
+ assert result is not None
+ assert ".first" 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_two_bare_button_login_first_clicks_both_emit_first(self) -> None:
+ trajectory = [
+ _interaction("click", selector="button", source_url="https://example.com/login"),
+ _interaction("click", selector="button", source_url="https://example.com/login"),
+ ]
+ result = synthesize_code_block(trajectory)
+ assert result is not None
+ assert result.code.count('await page.locator("button").first.click()') == 2
+ ast.parse("async def _block(page):\n" + result.code)
+
+ def test_universal_selector_offered_with_first(self) -> None:
+ result = synthesize_code_block([_interaction("click", selector="*", source_url="https://example.com/p")])
+ assert result is not None
+ assert 'await page.locator("*").first.click()' in result.code
+ assert 'await page.locator("*").click()' not in result.code
+
+ def test_strict_imposed_refuses_universal_selector(self) -> None:
+ trajectory = [
+ _interaction("click", selector="#open", source_url="https://example.com/home"),
+ _interaction("click", selector="*", source_url="https://example.com/p"),
+ ]
+ result = synthesize_code_block(trajectory, strict_selectors=True)
+ assert result is not None
+ assert 'page.locator("*")' not in result.code
+ assert [d for d in result.diagnostics.dropped_interactions if d.get("reason_code") == "ambiguous_bare_selector"]
+
+ def test_attribute_qualified_universal_selector_not_disambiguated(self) -> None:
+ result = synthesize_code_block(
+ [_interaction("click", selector="*[data-id]", source_url="https://example.com/p")]
+ )
+ assert result is not None
+ assert 'await page.locator("*[data-id]").click()' in result.code
+ assert ".first" not in result.code
+
class TestActionSynthesis:
def test_type_text_becomes_param_slot_fill(self) -> None: