Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Verify checkbox toggles instead of navigating in chain_click label/coordinate fallbacks (SKY-12543) (#7483)
LawyZheng119843855573
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex a5709f41f..e90a5edd4 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -5294,13 +5294,45 @@ async def chain_click(locator=locator,)+ # Only for a single click does "state unchanged" reliably mean "the+ # click was a no-op": any repeated click toggles the checkbox more+ # than once, so its final state is not a dependable no-op signal.+ # Gate the checkbox verification on a single click and fold it into+ # the shared coordinate -> JS ladder below instead of a parallel one.+ verify_checkbox_toggle = click_count == 1 and await skyvern_element.is_checkbox()+ checked_before = await skyvern_element.is_checked(timeout=timeout) if verify_checkbox_toggle else None++ coordinate_error: Exception | None = Nonetry:await skyvern_element.coordinate_click(page=page, click_count=click_count)+ except Exception as e:+ coordinate_error = e++ if verify_checkbox_toggle:+ checked_after = await skyvern_element.is_checked(timeout=timeout)+ state_known = checked_before is not None and checked_after is not None+ if state_known and checked_after != checked_before:+ action_results.append(ActionSuccess())+ return action_results+ if not state_known:+ # Unknown post-click state (detached/navigated): a second+ # click risks a double toggle, so never fall through to JS.+ if coordinate_error is None:+ action_results.append(ActionSuccess())+ else:+ action_results.append(+ ActionFailure(+ FailToClick(action.element_id, anchor="coordinate_click", msg=str(coordinate_error))+ )+ )+ return action_results+ # State known and unchanged: a provable no-op, safe to JS-click.+ elif coordinate_error is None:action_results.append(ActionSuccess())return action_results- except Exception as e:+ else:action_results.append(- ActionFailure(FailToClick(action.element_id, anchor="coordinate_click", msg=str(e)))+ ActionFailure(FailToClick(action.element_id, anchor="coordinate_click", msg=str(coordinate_error))))LOG.info(@@ -5311,12 +5343,27 @@ async def chain_click()try:await skyvern_element.click_in_javascript()- action_results.append(ActionSuccess())- return action_resultsexcept Exception as e:action_results.append(ActionFailure(FailToClick(action.element_id, anchor="self_js", msg=str(e))))return action_results+ if verify_checkbox_toggle:+ checked_after_js = await skyvern_element.is_checked(timeout=timeout)+ if checked_after_js is None or checked_after_js == checked_before:+ action_results.append(+ ActionFailure(+ FailToClick(+ action.element_id,+ anchor="self_js",+ msg="checkbox state unchanged after coordinate and JS click",+ )+ )+ )+ return action_results++ action_results.append(ActionSuccess())+ return action_results+try:LOG.debug("Chain click: verifying the blocking element is parent or sibling of the target element",diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.pyindex 0983ae60d..948825ba9 100644--- a/skyvern/webeye/utils/dom.py+++ b/skyvern/webeye/utils/dom.py@@ -206,6 +206,14 @@ class SkyvernElement:button_type = await self.get_attr("type")return button_type == "radio"+ async def is_checked(self, timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS) -> bool | None:+ # Live checked state via the DOM property; None when it can't be read+ # (e.g. the element detached after navigation). Never raises.+ try:+ return await self.get_locator().is_checked(timeout=timeout)+ except Exception:+ return None+async def is_btn_input(self) -> bool:tag_name = self.get_tag_name()if tag_name != InteractiveElement.INPUT:@@ -774,6 +782,16 @@ class SkyvernElement:return await dom.get_skyvern_element_by_id(unique_id)+ @staticmethod+ async def _label_click_forwards_to_descendant(label_locator: Locator) -> bool:+ # HTML forwards a <label> click to its control only when the pointer does not+ # land on interactive content nested inside; an <a href>/<button> descendant+ # handles the click itself (navigating) instead of toggling the control.+ try:+ return await label_locator.locator("a[href], button").count() > 0+ except Exception:+ return False+async def find_bound_label_by_attr_id(self, timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS) -> Locator | None:if self.get_tag_name() == "label":return None@@ -785,6 +803,8 @@ class SkyvernElement:locator = self.get_frame().locator(f"label[for='{element_id}']")cnt = await locator.count()if cnt == 1:+ if await self._label_click_forwards_to_descendant(locator):+ return Nonereturn locatorreturn None@@ -809,6 +829,9 @@ class SkyvernElement:if tag_name.lower() != "label":return None+ if await self._label_click_forwards_to_descendant(parent_locator):+ return None+return parent_locatorasync def find_selectable_child(self, dom: DomUtil) -> SkyvernElement | None:diff --git a/tests/unit/test_bound_label_anchor_filtering.py b/tests/unit/test_bound_label_anchor_filtering.pynew file mode 100644index 000000000..ff41fde62--- /dev/null+++ b/tests/unit/test_bound_label_anchor_filtering.py@@ -0,0 +1,107 @@+"""Slice 1 (SKY-12543): the bound-label fallbacks must not return a ``<label>``+whose click would be stolen by a nested interactive descendant (an ``<a href>``+or ``<button>``).++HTML label semantics forward a label click to the bound control only when the+pointer does not land on interactive content nested inside the label. A custom+checkout checkbox whose visually-hidden ``<input>`` is bound to a label that+wraps the terms-and-conditions ``<a href>`` therefore navigates to the terms+page instead of toggling — the loop-to-max-steps failure in SKY-12543.+"""++from __future__ import annotations++from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.webeye.utils.dom import SkyvernElement+++def _make_descendant_locator(interactive_count: int) -> MagicMock:+ descendant = MagicMock()+ descendant.count = AsyncMock(return_value=interactive_count)+ return descendant+++def _make_label_locator(interactive_count: int) -> MagicMock:+ label = MagicMock()+ label.count = AsyncMock(return_value=1)+ label.locator = MagicMock(return_value=_make_descendant_locator(interactive_count))+ return label+++def _make_input_for_attr_id(label_locator: MagicMock, element_id: str = "accept_tos") -> SkyvernElement:+ elem = object.__new__(SkyvernElement)+ elem.get_tag_name = MagicMock(return_value="input") # type: ignore[method-assign]+ elem.get_attr = AsyncMock(return_value=element_id) # type: ignore[method-assign]+ frame = MagicMock()+ frame.locator = MagicMock(return_value=label_locator)+ elem.get_frame = MagicMock(return_value=frame) # type: ignore[method-assign]+ return elem+++def _make_parent_label_locator(interactive_count: int, tag: str = "LABEL") -> MagicMock:+ parent = MagicMock()+ parent.count = AsyncMock(return_value=1)+ parent.evaluate = AsyncMock(return_value=tag)+ parent.locator = MagicMock(return_value=_make_descendant_locator(interactive_count))+ return parent+++def _make_input_for_direct_parent(parent_locator: MagicMock) -> SkyvernElement:+ elem = object.__new__(SkyvernElement)+ elem.get_tag_name = MagicMock(return_value="input") # type: ignore[method-assign]+ self_locator = MagicMock()+ self_locator.locator = MagicMock(return_value=parent_locator)+ elem.get_locator = MagicMock(return_value=self_locator) # type: ignore[method-assign]+ return elem+++class TestFindBoundLabelByAttrIdAnchorFiltering:+ @pytest.mark.asyncio+ async def test_label_wrapping_anchor_href_is_rejected(self) -> None:+ elem = _make_input_for_attr_id(_make_label_locator(interactive_count=1))+ assert await elem.find_bound_label_by_attr_id() is None++ @pytest.mark.asyncio+ async def test_ordinary_label_without_interactive_descendant_is_usable(self) -> None:+ label = _make_label_locator(interactive_count=0)+ elem = _make_input_for_attr_id(label)+ assert await elem.find_bound_label_by_attr_id() is label++ @pytest.mark.asyncio+ async def test_guard_selector_covers_anchor_and_button(self) -> None:+ label = _make_label_locator(interactive_count=0)+ elem = _make_input_for_attr_id(label)+ await elem.find_bound_label_by_attr_id()+ selector = label.locator.call_args.args[0]+ assert "a[href]" in selector+ assert "button" in selector++ @pytest.mark.asyncio+ async def test_no_matching_label_skips_descendant_check(self) -> None:+ label = MagicMock()+ label.count = AsyncMock(return_value=0)+ label.locator = MagicMock()+ elem = _make_input_for_attr_id(label)+ assert await elem.find_bound_label_by_attr_id() is None+ label.locator.assert_not_called()+++class TestFindBoundLabelByDirectParentAnchorFiltering:+ @pytest.mark.asyncio+ async def test_wrapping_label_with_anchor_is_rejected(self) -> None:+ elem = _make_input_for_direct_parent(_make_parent_label_locator(interactive_count=1))+ assert await elem.find_bound_label_by_direct_parent() is None++ @pytest.mark.asyncio+ async def test_wrapping_label_with_only_checkbox_is_usable(self) -> None:+ parent = _make_parent_label_locator(interactive_count=0)+ elem = _make_input_for_direct_parent(parent)+ assert await elem.find_bound_label_by_direct_parent() is parent++ @pytest.mark.asyncio+ async def test_non_label_parent_returns_none(self) -> None:+ elem = _make_input_for_direct_parent(_make_parent_label_locator(interactive_count=0, tag="DIV"))+ assert await elem.find_bound_label_by_direct_parent() is Nonediff --git a/tests/unit/test_chain_click_blocked_anchor_navigation.py b/tests/unit/test_chain_click_blocked_anchor_navigation.pyindex 62d8095cd..6e46c4073 100644--- a/tests/unit/test_chain_click_blocked_anchor_navigation.py+++ b/tests/unit/test_chain_click_blocked_anchor_navigation.py@@ -303,6 +303,12 @@ class TestChainClickBlockedAnchorNavigation:action_y: int | None = None,action_download: bool = False,navigate_result: str | None = "https://portal.example.com/billpay",+ is_checkbox: bool = False,+ checked_states: list[bool | None] | None = None,+ coordinate_raises: bool = False,+ js_mock: AsyncMock | None = None,+ is_checked_mock: AsyncMock | None = None,+ repeat: int = 1,) -> tuple[list, AsyncMock, AsyncMock]:"""Invoke chain_click through the ``blocking_element is None`` pathwith tightly-scoped stubs. Returns (results, coordinate_click_mock,@@ -360,8 +366,17 @@ class TestChainClickBlockedAnchorNavigation:elem.find_bound_label_by_direct_parent = AsyncMock(return_value=None) # type: ignore[method-assign]elem.is_visible = AsyncMock(return_value=True) # type: ignore[method-assign]elem.find_blocking_element = AsyncMock(return_value=(None, blocked)) # type: ignore[method-assign]- elem.coordinate_click = AsyncMock(return_value=None) # type: ignore[method-assign]- elem.click_in_javascript = AsyncMock(return_value=None) # type: ignore[method-assign]+ elem.coordinate_click = AsyncMock( # type: ignore[method-assign]+ side_effect=RuntimeError("coordinate click failed") if coordinate_raises else None+ )+ elem.click_in_javascript = js_mock if js_mock is not None else AsyncMock(return_value=None) # type: ignore[method-assign]+ elem.is_checkbox = AsyncMock(return_value=is_checkbox) # type: ignore[method-assign]+ if is_checked_mock is not None:+ elem.is_checked = is_checked_mock # type: ignore[method-assign]+ elif checked_states is not None:+ elem.is_checked = AsyncMock(side_effect=list(checked_states)) # type: ignore[method-assign]+ else:+ elem.is_checked = AsyncMock(return_value=None) # type: ignore[method-assign]try_navigate = AsyncMock(return_value=navigate_result)elem.try_navigate_via_href = try_navigate # type: ignore[method-assign]@@ -380,6 +395,7 @@ class TestChainClickBlockedAnchorNavigation:download=action_download,x=action_x,y=action_y,+ repeat=repeat,)results = await handler_module.chain_click(@@ -504,3 +520,223 @@ class TestChainClickBlockedAnchorNavigation:def test_dom_module_exports_try_navigate_via_href() -> None:"""Sanity check that the helper is a method on ``SkyvernElement``."""assert hasattr(dom_module.SkyvernElement, "try_navigate_via_href")+++class TestChainClickCheckboxCoordinateVerification:+ """Slice 2 wired through the real ``chain_click`` production branch: a+ checkbox that reaches the coordinate fallback is state-verified, and+ non-checkbox elements keep the plain coordinate behavior."""++ _run_chain_click = staticmethod(TestChainClickBlockedAnchorNavigation._run_chain_click)++ @pytest.mark.asyncio+ async def test_checkbox_coordinate_noop_recovers_via_js(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=True,+ tag=InteractiveElement.INPUT,+ href=None,+ is_checkbox=True,+ checked_states=[False, False, True],+ js_mock=js_mock,+ )+ coord_click.assert_awaited_once()+ js_mock.assert_awaited_once()+ assert results and isinstance(results[-1], ActionSuccess)++ @pytest.mark.asyncio+ async def test_checkbox_coordinate_toggle_skips_double_click(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=False,+ tag=InteractiveElement.INPUT,+ href=None,+ is_checkbox=True,+ checked_states=[False, True],+ js_mock=js_mock,+ )+ coord_click.assert_awaited_once()+ js_mock.assert_not_called()+ assert results and isinstance(results[-1], ActionSuccess)++ @pytest.mark.asyncio+ async def test_checkbox_provable_noop_reports_failure_not_false_success(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from skyvern.webeye.actions.responses import ActionFailure++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=True,+ tag=InteractiveElement.INPUT,+ href=None,+ is_checkbox=True,+ checked_states=[False, False, False],+ js_mock=js_mock,+ )+ js_mock.assert_awaited_once()+ assert results and isinstance(results[-1], ActionFailure)++ @pytest.mark.asyncio+ async def test_non_checkbox_keeps_plain_coordinate_path(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=False,+ tag=InteractiveElement.BUTTON,+ href=None,+ is_checkbox=False,+ js_mock=js_mock,+ )+ coord_click.assert_awaited_once()+ js_mock.assert_not_called()+ assert results and isinstance(results[-1], ActionSuccess)++ @pytest.mark.asyncio+ async def test_multi_click_checkbox_skips_state_verified_fallback(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # A double-click toggles a checkbox twice and lands on the original state.+ # The single-click state-verified fallback would misread that net-zero+ # change as a no-op and add a wrong third JS toggle, so click_count > 1+ # must keep the plain coordinate path and never consult is_checked.+ from skyvern.webeye.actions.responses import ActionSuccess++ js_mock = AsyncMock(return_value=None)+ is_checked_mock = AsyncMock(side_effect=[False, False, True])+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=False,+ tag=InteractiveElement.INPUT,+ href=None,+ is_checkbox=True,+ repeat=2,+ js_mock=js_mock,+ is_checked_mock=is_checked_mock,+ )+ coord_click.assert_awaited_once()+ is_checked_mock.assert_not_called()+ js_mock.assert_not_called()+ assert results and isinstance(results[-1], ActionSuccess)++ @pytest.mark.asyncio+ async def test_checkbox_initially_checked_toggles_off_skips_js(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # A checkbox that starts checked and flips off is a confirmed toggle:+ # success is decided by the state change, not a hardcoded ``checked is True``.+ from skyvern.webeye.actions.responses import ActionSuccess++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=True,+ tag=InteractiveElement.INPUT,+ href=None,+ is_checkbox=True,+ checked_states=[True, False],+ js_mock=js_mock,+ )+ coord_click.assert_awaited_once()+ js_mock.assert_not_called()+ assert results and isinstance(results[-1], ActionSuccess)++ @pytest.mark.asyncio+ async def test_checkbox_unknown_post_state_reports_success_without_js(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Coordinate click did not raise but the post-click state is unreadable+ # (detached/navigated): report success and never risk a second toggle.+ from skyvern.webeye.actions.responses import ActionSuccess++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=True,+ tag=InteractiveElement.INPUT,+ href=None,+ is_checkbox=True,+ checked_states=[False, None],+ js_mock=js_mock,+ )+ coord_click.assert_awaited_once()+ js_mock.assert_not_called()+ assert results and isinstance(results[-1], ActionSuccess)++ @pytest.mark.asyncio+ async def test_checkbox_coordinate_raises_and_unknown_state_fails_without_js(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Coordinate click raised and the post-click state is unreadable: the+ # click may or may not have landed, so a JS retry risks a double toggle.+ # Report the coordinate failure and stop.+ from skyvern.webeye.actions.responses import ActionFailure++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=True,+ tag=InteractiveElement.INPUT,+ href=None,+ is_checkbox=True,+ checked_states=[False, None],+ coordinate_raises=True,+ js_mock=js_mock,+ )+ coord_click.assert_awaited_once()+ js_mock.assert_not_called()+ assert results and isinstance(results[-1], ActionFailure)+ assert "coordinate_click" in results[-1].exception_message++ @pytest.mark.asyncio+ async def test_checkbox_coordinate_raises_but_provable_noop_recovers_via_js(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Coordinate click raised yet the state is provably unchanged (both reads+ # known and equal): a single JS toggle is the missing click, not a double.+ from skyvern.webeye.actions.responses import ActionSuccess++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=True,+ tag=InteractiveElement.INPUT,+ href=None,+ is_checkbox=True,+ checked_states=[False, False, True],+ coordinate_raises=True,+ js_mock=js_mock,+ )+ coord_click.assert_awaited_once()+ js_mock.assert_awaited_once()+ assert results and isinstance(results[-1], ActionSuccess)++ @pytest.mark.asyncio+ async def test_non_checkbox_coordinate_raises_then_js_succeeds_two_result_shape(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Parity guard for the shared ladder: a non-checkbox whose coordinate+ # click raises but JS click succeeds must still append the coordinate+ # failure *and* the JS success, in that order.+ from skyvern.webeye.actions.responses import ActionFailure, ActionSuccess++ js_mock = AsyncMock(return_value=None)+ results, coord_click, _ = await self._run_chain_click(+ monkeypatch,+ blocked=False,+ tag=InteractiveElement.BUTTON,+ href=None,+ is_checkbox=False,+ coordinate_raises=True,+ js_mock=js_mock,+ )+ coord_click.assert_awaited_once()+ js_mock.assert_awaited_once()+ assert isinstance(results[-2], ActionFailure)+ assert "coordinate_click" in results[-2].exception_message+ assert isinstance(results[-1], ActionSuccess)