Skip to content

Automate browser based workflows with AI

Stop answer-tile clicks from being reported failed or toggled off (#8983)

Shuchang Zheng63c63855d793
diff --git a/skyvern/core/script_generations/real_skyvern_page_ai.py b/skyvern/core/script_generations/real_skyvern_page_ai.py
index 3a02a2c52..bee83c74c 100644
--- a/skyvern/core/script_generations/real_skyvern_page_ai.py
+++ b/skyvern/core/script_generations/real_skyvern_page_ai.py
@@ -242,10 +242,10 @@ class RealSkyvernPageAi(SkyvernPageAi):
if ep_id is not None:
v3_parent_episode_id = ep_id
- # Set when a setup already performed the interaction before raising SkyvernActionFailed,
- # so the except block below can tell a genuine AI miss (safe to retry on selector) apart
- # from a setup failure that already mutated the page (retrying would repeat side effects).
- setup_performed_before_failure = False
+ # Set when the failure must not be retried as a raw selector click: a setup already
+ # performed the interaction (retrying would repeat side effects), or the handler refused
+ # the click and asked to stop (skip_remaining_actions), e.g. to wait for explicit intent.
+ raw_retry_unsafe = False
try:
# Build the element tree of the current page for the prompt
context = skyvern_context.ensure_context()
@@ -302,7 +302,7 @@ class RealSkyvernPageAi(SkyvernPageAi):
setup_results = await setup(action, self.page, self.scraped_page, task, step)
if setup_results:
if setup_results[-1].success is False:
- setup_performed_before_failure = setup_results[-1].setup_performed
+ raw_retry_unsafe = setup_results[-1].setup_performed
raise SkyvernActionFailed(
setup_results[-1].exception_message or "Click action setup returned success=False"
)
@@ -311,7 +311,7 @@ class RealSkyvernPageAi(SkyvernPageAi):
if setup_result is None:
result = await handle_click_action(action, self.page, self.scraped_page, task, step)
if result and result[-1].success is False:
- setup_performed_before_failure = result[-1].setup_performed
+ raw_retry_unsafe = result[-1].setup_performed or result[-1].skip_remaining_actions
raise SkyvernActionFailed(result[-1].exception_message or "Click action returned success=False")
if result and isinstance(result[-1], ActionAbort):
# handle_click_action's own ClickContext.desired_state guard can suppress
@@ -349,12 +349,11 @@ class RealSkyvernPageAi(SkyvernPageAi):
except SkyvernActionFailed:
if selector is None:
raise
- if setup_performed_before_failure:
- # The setup already mutated the page (e.g. clicked, toggled, or navigated) before
- # this failure — a raw click on `selector` would repeat that side effect rather
- # than recover from it, so surface the failure instead of retrying.
+ if raw_retry_unsafe:
+ # A raw click on `selector` would repeat a side effect the setup already caused, or
+ # override the handler's refusal, so surface the failure instead of retrying.
LOG.warning(
- "AI click setup already performed the interaction before failing; not retrying with a raw click",
+ "AI click failure must not be retried with a raw click; surfacing it",
selector=selector,
intention=intention,
)
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index c63f4ab8a..faa8b4c83 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -241,6 +241,10 @@ from skyvern.webeye.cdp_download_interceptor import (
redacted_exception_origin,
settle_browser_downloads_for_context,
)
+from skyvern.webeye.dom_inspection import (
+ is_static_listbox_option_snapshot,
+ read_static_listbox_option_snapshot,
+)
from skyvern.webeye.main_world_eval import evaluate_in_main_world
from skyvern.webeye.navigation import (
clear_task_nav_error_code,
@@ -6349,6 +6353,10 @@ async def _is_paste_text_action_enabled(task: Task) -> bool:
return False
+async def _has_static_option_role(element: SkyvernElement) -> bool:
+ return (await element.get_attr("role", mode="static") or "").strip().casefold() == "option"
+
+
def check_for_invalid_web_action(
action: actions.Action,
page: Page,
@@ -6640,6 +6648,61 @@ async def _is_single_select_option_highlight(element: SkyvernElement) -> bool:
return (await multiselectable.get_attribute("aria-multiselectable") or "").strip().casefold() != "true"
+async def _is_static_listbox_option(element: SkyvernElement) -> bool:
+ try:
+ snapshot = await read_static_listbox_option_snapshot(element.get_frame(), await element.get_element_handler())
+ except Exception:
+ LOG.debug("Static listbox option snapshot read failed; treating as not static", element_id=element.get_id())
+ return False
+ is_static = is_static_listbox_option_snapshot(snapshot)
+ if (
+ isinstance(snapshot, dict)
+ and snapshot.get("isOption") is True
+ and snapshot.get("inListbox") is True
+ and not is_static
+ ):
+ LOG.info("Option is not a static listbox option", element_id=element.get_id(), snapshot=snapshot)
+ return is_static
+
+
+def _static_listbox_replan_failure(action: actions.ClickAction, message: str) -> ActionFailure:
+ result = ActionFailure(FailToClick(action.element_id, msg=message))
+ result.skip_remaining_actions = True
+ return result
+
+
+async def _resolve_static_listbox_container_target(
+ action: actions.ClickAction, element: SkyvernElement, dom: DomUtil
+) -> SkyvernElement | ActionFailure | None:
+ try:
+ options = await element.get_locator().locator('[role="option"]').all()
+ if not options:
+ return None
+ for option in options:
+ # A hidden option means the container is collapsed; its click may be what expands it.
+ if not await option.is_visible():
+ return None
+ snapshot = await read_static_listbox_option_snapshot(
+ element.get_frame(), await option.element_handle(timeout=settings.BROWSER_ACTION_TIMEOUT_MS)
+ )
+ if not is_static_listbox_option_snapshot(snapshot):
+ return None
+ if len(options) != 1:
+ return _static_listbox_replan_failure(
+ action,
+ "This static listbox already exposes multiple options. Click the intended option directly; "
+ "clicking the container may select an arbitrary option.",
+ )
+ option_id = await options[0].get_attribute(SKYVERN_ID_ATTR)
+ target = await dom.safe_get_skyvern_element_by_id(option_id) if option_id else None
+ if target is None or not await _is_static_listbox_option(target) or await target.is_disabled(dynamic=True):
+ return _static_listbox_replan_failure(action, "The static listbox option is unavailable; rescrape it.")
+ return target
+ except Exception:
+ LOG.debug("Static listbox container inspection failed", element_id=element.get_id())
+ return None
+
+
class _GridRowSelection(StrEnum):
"""Row-selection state of a checkbox's grid context. NOT_GRID_ROW: not a grid row-selection
control, so native ``checked`` is the whole truth. SELECTED/UNSELECTED: the closest row's
@@ -6985,7 +7048,9 @@ class _EffectiveClickState(NamedTuple):
control_type: str | None
-async def _resolve_live_click_state(element: SkyvernElement) -> _EffectiveClickState:
+async def _resolve_live_click_state(
+ element: SkyvernElement, *, trust_static_listbox: bool = False
+) -> _EffectiveClickState:
"""Read one generic, live selected/checked state and control type snapshot.
``checked`` is None when no boolean observable is readable (unknown control, malformed value,
or a detached/unreadable element), so the caller falls open to an ordinary click. Native radio
@@ -7008,9 +7073,11 @@ async def _resolve_live_click_state(element: SkyvernElement) -> _EffectiveClickS
if parsed is None:
continue
if aria_attr == "aria-selected" and parsed and await _is_single_select_option_highlight(element):
- # A single-select option's aria-selected="true" is a keyboard highlight, not committed
- # state, so leave it unreadable and let the physical click commit the selection.
- return _EffectiveClickState(checked=None, control_type=None)
+ if not (trust_static_listbox and await _is_static_listbox_option(element)):
+ # A single-select option's aria-selected="true" is a keyboard highlight, not committed
+ # state, so leave it unreadable and let the physical click commit the selection.
+ return _EffectiveClickState(checked=None, control_type=None)
+ LOG.info("Trusting aria-selected on a static listbox option", element_id=element.get_id())
return _EffectiveClickState(checked=parsed, control_type=None)
return _EffectiveClickState(checked=None, control_type=None)
except Exception:
@@ -7356,7 +7423,12 @@ async def _input_type_or_none(element: SkyvernElement) -> str | None:
async def _apply_desired_click_state(
- action: actions.ClickAction, element: SkyvernElement, desired_state: bool, dom: DomUtil
+ action: actions.ClickAction,
+ element: SkyvernElement,
+ desired_state: bool,
+ dom: DomUtil,
+ *,
+ trust_static_listbox: bool = False,
) -> list[ActionResult] | None:
"""Drive a selectable control to an explicit terminal state idempotently. Returns
[ActionAbort()] to suppress the physical click -- when the control already matches the desired
@@ -7372,7 +7444,7 @@ async def _apply_desired_click_state(
element_type = await _input_type_or_none(element)
if element_type == "checkbox":
return await _apply_checkbox_desired_click_state(action, element, desired_state)
- state = await _resolve_live_click_state(element)
+ state = await _resolve_live_click_state(element, trust_static_listbox=trust_static_listbox)
if state.checked is None:
LOG.info("No readable selected state, continuing the normal click", action=action)
return None
@@ -7465,6 +7537,7 @@ async def handle_click_action(
action_phase.mark_action_phase(ActionPhase.RESOLVE_ELEMENT)
skyvern_element = await dom.get_skyvern_element_by_id(action.element_id)
action_phase.mark_action_phase(ActionPhase.PRE_CLICK_CHECKS)
+ static_listbox_fix = await _has_static_option_role(skyvern_element)
# Wait after getting element to allow any dynamic changes
await asyncio.sleep(get_wait_time(wait_config, "post_click_delay", default=0.3))
@@ -7475,7 +7548,11 @@ async def handle_click_action(
# single ordinary click for a custom-control mismatch or an unreadable state.
if action.click_context is not None and action.click_context.desired_state is not None:
desired_state_result = await _apply_desired_click_state(
- action, skyvern_element, action.click_context.desired_state, dom
+ action,
+ skyvern_element,
+ action.click_context.desired_state,
+ dom,
+ trust_static_listbox=static_listbox_fix and action.repeat == 1,
)
if desired_state_result is not None:
return desired_state_result
@@ -7489,12 +7566,17 @@ async def handle_click_action(
)
if child is not None:
skyvern_element = child
+ static_listbox_fix = await _has_static_option_role(skyvern_element)
# Retarget moved the click to the descendant that will actually receive it, so re-run
# the same guard on the child: the pre-retarget pass observed the (unreadable) wrapper
# and fell open, and without this the retargeted child could still be re-toggled.
if action.click_context is not None and action.click_context.desired_state is not None:
desired_state_result = await _apply_desired_click_state(
- action, skyvern_element, action.click_context.desired_state, dom
+ action,
+ skyvern_element,
+ action.click_context.desired_state,
+ dom,
+ trust_static_listbox=static_listbox_fix and action.repeat == 1,
)
if desired_state_result is not None:
return desired_state_result
@@ -7506,6 +7588,47 @@ async def handle_click_action(
)
return [ActionFailure(InteractWithDisabledElement(skyvern_element.get_id()))]
+ if (await skyvern_element.get_attr("role", mode="static") or "").strip().casefold() == "listbox":
+ target = await _resolve_static_listbox_container_target(action, skyvern_element, dom)
+ if isinstance(target, ActionFailure):
+ return [target]
+ if target is not None:
+ skyvern_element = target
+ action.element_id = target.get_id()
+ # Keep the persisted selector on the option that is clicked; scripts replay get_xpath().
+ action.xpath = None
+ action.skyvern_element_data = {
+ **target.get_element_dict(),
+ "page_url": (action.skyvern_element_data or {}).get("page_url"),
+ }
+ action.skyvern_element_hash = dom.scraped_page.id_to_element_hash.get(action.element_id)
+ static_listbox_fix = True
+ if action.click_context is not None and action.click_context.desired_state is not None:
+ desired_state_result = await _apply_desired_click_state(
+ action,
+ target,
+ action.click_context.desired_state,
+ dom,
+ trust_static_listbox=action.repeat == 1,
+ )
+ if desired_state_result is not None:
+ return desired_state_result
+
+ if (
+ static_listbox_fix
+ and action.repeat == 1
+ and (action.click_context is None or action.click_context.desired_state is None)
+ and await _is_static_listbox_option(skyvern_element)
+ and (await _resolve_live_click_state(skyvern_element, trust_static_listbox=True)).checked is True
+ ):
+ return [
+ _static_listbox_replan_failure(
+ action,
+ "This option is already selected. Set click_context.desired_state=true to keep it selected "
+ "or false to deselect it.",
+ )
+ ]
+
# Skip scroll_into_view when a SCROLL action just completed on THIS element.
# The scroll may have positioned the page or a container at the bottom to enable
# T&C buttons; element.scrollIntoView() would undo that positioning.
@@ -7565,6 +7688,11 @@ async def handle_click_action(
remove_download_probe = _register_false_click_download_probe(page, false_click_download_observed)
has_onclick_attr = await skyvern_element.has_attr("onclick", mode="static")
+ bypass_static_listbox_option = (
+ static_listbox_fix
+ and await _has_static_option_role(skyvern_element)
+ and await _is_static_listbox_option(skyvern_element)
+ )
action_phase.mark_action_phase(ActionPhase.CLICK)
results = await chain_click(
task,
@@ -7615,6 +7743,13 @@ async def handle_click_action(
)
return results
+ if bypass_static_listbox_option:
+ LOG.info(
+ "Static listbox option click; bypassing the dropdown sequential-click rescrape",
+ element_id=skyvern_element.get_id(),
+ )
+ return results
+
if sequential_click_result := await handle_sequential_click_with_submit_bypass(
action=action,
action_history=results,
diff --git a/skyvern/webeye/dom_inspection.py b/skyvern/webeye/dom_inspection.py
index e2aee0ddb..1a73fc483 100644
--- a/skyvern/webeye/dom_inspection.py
+++ b/skyvern/webeye/dom_inspection.py
@@ -53,6 +53,132 @@ _READ_LOCATOR_SELECTED_STATE = """
}
"""
+_READ_STATIC_LISTBOX_OPTION_SNAPSHOT = r"""
+(el) => {
+ const empty = {
+ isOption: false,
+ inListbox: false,
+ popupSemanticsNearby: false,
+ ownedByTrigger: false,
+ activeDescendantRef: false,
+ layered: false,
+ textEntrySibling: false,
+ openPopupOnPage: false,
+ };
+ try {
+ const parentOf = (n) => n.parentElement || (n.getRootNode() instanceof ShadowRoot ? n.getRootNode().host : null);
+ const roots = [];
+ for (let r = el.getRootNode(); r; r = (r instanceof ShadowRoot ? r.host.getRootNode() : null)) roots.push(r);
+ const isOption = (el.getAttribute('role') || '').trim().toLowerCase() === 'option';
+ const listbox = el.closest('[role="listbox"]');
+ if (listbox === null) { return Object.assign({}, empty, { isOption: isOption }); }
+
+ const hasPopupSelector = '[aria-haspopup]:not([aria-haspopup="false"]):not([aria-haspopup=""])';
+ const popupSelector = '[role="combobox"], [aria-expanded], ' + hasPopupSelector;
+ let popupSemanticsNearby = false;
+ for (let node = el; node !== null; node = parentOf(node)) {
+ if (node.matches(popupSelector)) { popupSemanticsNearby = true; break; }
+ if (node === listbox) {
+ let ancestor = parentOf(listbox);
+ for (let i = 0; i < 3 && ancestor !== null; i++, ancestor = parentOf(ancestor)) {
+ if (ancestor.matches(popupSelector)) { popupSemanticsNearby = true; break; }
+ }
+ break;
+ }
+ }
+
+ const optionId = el.id;
+ const triggerSelector = popupSelector
+ + ', button, input, select, textarea, [role="button"], [role="textbox"], [role="searchbox"]';
+ const ownedByTrigger = roots.some((root) =>
+ Array.from(root.querySelectorAll('[aria-controls], [aria-owns]')).some((owner) =>
+ owner.matches(triggerSelector)
+ && ['aria-controls', 'aria-owns'].some((attribute) =>
+ (owner.getAttribute(attribute) || '').trim().split(/\s+/).filter(Boolean).some((token) => {
+ const node = root.getElementById(token);
+ return node === listbox
+ || node === el
+ || (node !== null && node.contains(listbox) && owner.matches(popupSelector));
+ })
+ )
+ )
+ );
+
+ const activeDescendantRef = optionId !== '' && roots.some((root) =>
+ Array.from(root.querySelectorAll('[aria-activedescendant]')).some((owner) =>
+ owner.getAttribute('aria-activedescendant') === optionId
+ )
+ );
+
+ const dialogSelector = 'dialog, [role="dialog"], [role="alertdialog"], [aria-modal="true"]';
+ const hasPopoverBeforeDialog = function (node) {
+ for (let ancestor = node; ancestor !== null; ancestor = parentOf(ancestor)) {
+ if (ancestor.matches(dialogSelector)) { return false; }
+ if (ancestor.matches('[popover]')) { return true; }
+ }
+ return false;
+ };
+ let layered = false;
+ let layerNode = listbox;
+ let inspectedNodes = 0;
+ // Keep the window short: page-level positioning would disable the fix; stop at dialogs so modal forms stay static.
+ for (; inspectedNodes < 4 && layerNode !== null; layerNode = parentOf(layerNode)) {
+ if (layerNode.matches(dialogSelector)) { break; }
+ const view = layerNode.ownerDocument.defaultView;
+ const style = view ? view.getComputedStyle(layerNode) : null;
+ if (style && style.display === 'contents') { continue; }
+ inspectedNodes++;
+ const position = style ? style.position : '';
+ if (position === 'fixed' || position === 'absolute' || hasPopoverBeforeDialog(layerNode)) {
+ layered = true;
+ break;
+ }
+ }
+
+ const parent = listbox.parentElement;
+ const textEntrySibling = parent !== null && Array.from(parent.querySelectorAll(
+ 'input:not([type=hidden]):not([type=checkbox]):not([type=radio]):not([type=button])'
+ + ':not([type=submit]):not([type=reset]), textarea, [role="textbox"], [role="searchbox"], '
+ + '[contenteditable="true"]'
+ )).some((textEntry) => !listbox.contains(textEntry));
+
+ const openPopupSelector = '[aria-expanded="true"][role="combobox"], [aria-expanded="true"]'
+ + hasPopupSelector;
+ const openPopupOnPage = roots.some((root) => root.querySelector(openPopupSelector) !== null);
+ return {
+ isOption: isOption,
+ inListbox: true,
+ popupSemanticsNearby: popupSemanticsNearby,
+ ownedByTrigger: ownedByTrigger,
+ activeDescendantRef: activeDescendantRef,
+ layered: layered,
+ textEntrySibling: textEntrySibling,
+ openPopupOnPage: openPopupOnPage,
+ };
+ } catch (error) {
+ return empty;
+ }
+}
+"""
+
+_MUST_BE_TRUE = ("isOption", "inListbox")
+_MUST_BE_FALSE = (
+ "popupSemanticsNearby",
+ "ownedByTrigger",
+ "activeDescendantRef",
+ "layered",
+ "textEntrySibling",
+ "openPopupOnPage",
+)
+
+
+def is_static_listbox_option_snapshot(snapshot: object) -> bool:
+ return (
+ isinstance(snapshot, dict)
+ and all(snapshot.get(key) is True for key in _MUST_BE_TRUE)
+ and all(snapshot.get(key) is False for key in _MUST_BE_FALSE)
+ )
+
async def read_current_url(frame: Page | Frame) -> str | None:
value = await SkyvernFrame.evaluate(frame=frame, expression=_READ_CURRENT_URL)
@@ -69,6 +195,10 @@ async def read_locator_selected_state(locator: Locator, *, timeout: float | None
return value if isinstance(value, bool) else None
+async def read_static_listbox_option_snapshot(frame: Page | Frame, element: ElementHandle) -> object:
+ return await SkyvernFrame.evaluate(frame=frame, expression=_READ_STATIC_LISTBOX_OPTION_SNAPSHOT, arg=element)
+
+
async def read_locator_is_content_editable(locator: Locator, *, timeout: float | None = None) -> bool | None:
value = await locator.evaluate(_READ_LOCATOR_IS_CONTENT_EDITABLE, timeout=timeout)
return value if isinstance(value, bool) else None
diff --git a/tests/unit/test_ai_click_empty_actions.py b/tests/unit/test_ai_click_empty_actions.py
index 2397b3a24..31bf37bfc 100644
--- a/tests/unit/test_ai_click_empty_actions.py
+++ b/tests/unit/test_ai_click_empty_actions.py
@@ -380,3 +380,49 @@ class TestAiSelectOptionHandlerFailures:
handle_select.assert_awaited_once()
mock_page.locator.assert_not_called()
+
+
+class TestAiClickHandlerRefusal:
+ """A click the handler refuses with skip_remaining_actions must not be retried as a raw selector click."""
+
+ async def _ai_click(self, mock_page, mock_scraped_page, mock_context, mock_app, handler_result):
+ from skyvern.webeye.actions.actions import ClickAction
+
+ action = ClickAction(element_id="opt")
+ page_ai = RealSkyvernPageAi(mock_scraped_page, mock_page)
+ result = handler_result(action) if callable(handler_result) else handler_result
+ with (
+ patch.object(page_ai, "_refresh_scraped_page", new_callable=AsyncMock),
+ patch(f"{MODULE}.skyvern_context.ensure_context", return_value=mock_context),
+ patch(f"{MODULE}.app", mock_app),
+ patch(f"{MODULE}.prompt_engine.load_prompt", return_value="mock_prompt"),
+ patch(f"{MODULE}._resolve_assist_llm_handler", new_callable=AsyncMock) as resolve,
+ patch(f"{MODULE}.parse_actions", return_value=[action]),
+ patch(f"{MODULE}.ActionHandler.get_setup_for_action_type", return_value=None),
+ patch(f"{MODULE}.handle_click_action", new=AsyncMock(return_value=[result])),
+ ):
+ resolve.return_value = AsyncMock(return_value={"actions": [{"action_type": "CLICK"}]})
+ return await page_ai.ai_click(selector="xpath=//div[@id='opt']", intention="Pick the answer")
+
+ @pytest.mark.asyncio
+ async def test_refusal_with_skip_remaining_actions_is_not_retried_with_selector(
+ self, mock_page, mock_scraped_page, mock_context, mock_app
+ ):
+ from skyvern.webeye.actions import handler as click_handler
+
+ def refusal(action):
+ return click_handler._static_listbox_replan_failure(action, "This option is already selected.")
+
+ with pytest.raises(SkyvernActionFailed):
+ await self._ai_click(mock_page, mock_scraped_page, mock_context, mock_app, refusal)
+ mock_page.locator.return_value.click.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_recoverable_click_failure_still_falls_back_to_selector(
+ self, mock_page, mock_scraped_page, mock_context, mock_app
+ ):
+ failure = ActionFailure(Exception("element moved"))
+ assert not failure.skip_remaining_actions and not failure.setup_performed
+ result = await self._ai_click(mock_page, mock_scraped_page, mock_context, mock_app, failure)
+ assert result == "xpath=//div[@id='opt']"
+ mock_page.locator.return_value.click.assert_awaited_once()
diff --git a/tests/unit/test_browser_effect_sink_enumeration.py b/tests/unit/test_browser_effect_sink_enumeration.py
index 2b985b9b5..008aafeed 100644
--- a/tests/unit/test_browser_effect_sink_enumeration.py
+++ b/tests/unit/test_browser_effect_sink_enumeration.py
@@ -55,7 +55,7 @@ _DISCOVERED_BROWSER_API_CALLS = {
{"dispatch_event": 1, "down": 3, "evaluate": 1, "fill": 3, "press": 1, "up": 3}
),
"skyvern/webeye/dialog_handler.py": Counter({"accept": 3, "dismiss": 1}),
- "skyvern/webeye/dom_inspection.py": Counter({"evaluate": 6}),
+ "skyvern/webeye/dom_inspection.py": Counter({"evaluate": 7}),
"skyvern/webeye/utils/dom.py": Counter(
{
"check": 2,
@@ -144,6 +144,8 @@ _EVALUATE_CALLERS = {
"read_current_url": 1,
# locator-scoped live selected/checked read for the cached click guard (SKY-14051)
"read_locator_selected_state": 1,
+ # read-only static-listbox option snapshot read (pre-click classification)
+ "read_static_listbox_option_snapshot": 1,
# locator-scoped live isContentEditable read; routes blocks nested in an editing host to the atomic fill
"read_locator_is_content_editable": 1,
"read_locator_tag_name": 1,
@@ -269,21 +271,21 @@ def test_discovered_browser_api_lower_bound_is_stable() -> None:
}
assert observed == _DISCOVERED_BROWSER_API_CALLS
- assert sum(sum(methods.values()) for methods in observed.values()) == 212
+ assert sum(sum(methods.values()) for methods in observed.values()) == 213
handler_candidates = _candidate_signatures("skyvern/webeye/actions/handler.py", _CANDIDATE_METHODS)
classified_non_browser = Counter(
{signature: count for signature, count in handler_candidates.items() if signature in _NON_BROWSER_CANDIDATES}
)
assert classified_non_browser == _NON_BROWSER_CANDIDATES
assert sum(_NON_BROWSER_CANDIDATES.values()) == 7
- assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 205
+ assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 206
def test_every_raw_evaluate_call_is_classified() -> None:
observed = {path: callers for path in _owned_source_paths() if (callers := _callers_for_method(path, "evaluate"))}
assert observed == _EVALUATE_CALLERS
- assert sum(sum(callers.values()) for callers in observed.values()) == 41
+ assert sum(sum(callers.values()) for callers in observed.values()) == 42
def test_every_cdp_dispatch_is_classified_by_exact_command() -> None:
diff --git a/tests/unit/test_click_desired_state.py b/tests/unit/test_click_desired_state.py
index 4923f4b4b..bc5a92dcd 100644
--- a/tests/unit/test_click_desired_state.py
+++ b/tests/unit/test_click_desired_state.py
@@ -24,8 +24,13 @@ from playwright.async_api import Page, async_playwright
from skyvern.webeye.actions import handler
from skyvern.webeye.actions.actions import ActionStatus, ClickAction, ClickContext
from skyvern.webeye.actions.responses import ActionAbort, ActionFailure, ActionResult, ActionSuccess, StaleActionAbort
+from skyvern.webeye.dom_inspection import (
+ _READ_STATIC_LISTBOX_OPTION_SNAPSHOT,
+ is_static_listbox_option_snapshot,
+)
from skyvern.webeye.utils import dom as dom_utils
from skyvern.webeye.utils.dom import SkyvernElement
+from tests.unit._workflow_block_engine_fakes import FakeExperimentationProvider
from tests.unit.scoped_asyncio import ScopedAsyncio
@@ -290,6 +295,7 @@ class FakeAncestorLocator:
_GRID_SNAPSHOT_DEFAULT = object()
+_STATIC_LISTBOX_SNAPSHOT_DEFAULT = object()
def _non_grid_row_snapshot() -> dict[str, object]:
@@ -317,16 +323,23 @@ class FakeElementLocator:
multiselectable_ancestor: str | None,
grid_snapshot: object = _GRID_SNAPSHOT_DEFAULT,
grid_snapshot_error: Exception | None = None,
+ static_listbox_snapshot: object = _STATIC_LISTBOX_SNAPSHOT_DEFAULT,
) -> None:
self._multiselectable_ancestor = multiselectable_ancestor
self._grid_snapshot = grid_snapshot
self._grid_snapshot_error = grid_snapshot_error
+ self._static_listbox_snapshot = static_listbox_snapshot
def locator(self, selector: str) -> FakeAncestorLocator:
assert selector == "xpath=ancestor-or-self::*[@aria-multiselectable][1]"
return FakeAncestorLocator(self._multiselectable_ancestor)
- async def evaluate(self, expression: str, *args: object) -> object:
+ async def evaluate(self, expression: str, *args: object, **kwargs: object) -> object:
+ if expression == _READ_STATIC_LISTBOX_OPTION_SNAPSHOT:
+ if self._static_listbox_snapshot is _STATIC_LISTBOX_SNAPSHOT_DEFAULT:
+ raise AssertionError("unexpected static-listbox snapshot read")
+ return self._static_listbox_snapshot
+ assert expression == handler._GRID_ROW_SNAPSHOT_JS
if self._grid_snapshot_error is not None:
raise self._grid_snapshot_error
if self._grid_snapshot is _GRID_SNAPSHOT_DEFAULT:
@@ -353,6 +366,7 @@ class FakeToggleElement:
multiselectable_ancestor: str | None = None,
grid_snapshot: object = _GRID_SNAPSHOT_DEFAULT,
grid_snapshot_error: Exception | None = None,
+ static_listbox_snapshot: object = _STATIC_LISTBOX_SNAPSHOT_DEFAULT,
) -> None:
self._tag_name = tag_name
self._attributes = attributes or {}
@@ -361,7 +375,12 @@ class FakeToggleElement:
self._type_results = list(type_results) if type_results is not None else None
self.type_read_count = 0
self._attr_error = attr_error
- self._locator = FakeElementLocator(multiselectable_ancestor, grid_snapshot, grid_snapshot_error)
+ self._locator = FakeElementLocator(
+ multiselectable_ancestor,
+ grid_snapshot,
+ grid_snapshot_error,
+ static_listbox_snapshot,
+ )
def get_tag_name(self) -> str:
return self._tag_name
@@ -400,8 +419,8 @@ class FakeToggleElement:
async def has_attr(self, attr_name: str, mode: str = "auto") -> bool:
return False
- def get_frame(self) -> MagicMock:
- return MagicMock()
+ def get_frame(self) -> FakeElementLocator:
+ return self._locator
async def is_explicit_submit(self) -> bool:
return False
@@ -524,6 +543,21 @@ async def test_apply_single_select_option_aria_selected_false_desired_false_supp
assert result is not None and len(result) == 1 and isinstance(result[0], ActionAbort)
+async def test_apply_static_single_select_option_suppresses_only_when_trusted() -> None:
+ element = FakeToggleElement(
+ "div",
+ {"role": "option", "aria-selected": "true"},
+ static_listbox_snapshot=_static_listbox_snapshot(),
+ )
+
+ trusted = await handler._apply_desired_click_state(
+ _click_action(), element, True, MagicMock(), trust_static_listbox=True
+ )
+ assert trusted is not None and len(trusted) == 1 and isinstance(trusted[0], ActionAbort)
+ assert await handler._apply_desired_click_state(_click_action(), element, True, MagicMock()) is None
+
+
@pytest.mark.asyncio
async def test_apply_custom_control_mismatch_false_falls_through_without_checking() -> None:
element = FakeToggleElement("button", {"aria-pressed": "true"})
@@ -1299,6 +1333,327 @@ def _grid_snapshot(**overrides: object) -> dict[str, object]:
return snapshot
+def _static_listbox_snapshot(**overrides: object) -> dict[str, object]:
+ snapshot: dict[str, object] = {
+ "isOption": True,
+ "inListbox": True,
+ "popupSemanticsNearby": False,
+ "ownedByTrigger": False,
+ "activeDescendantRef": False,
+ "layered": False,
+ "textEntrySibling": False,
+ "openPopupOnPage": False,
+ }
+ snapshot.update(overrides)
+ return snapshot
+
+
+ ("snapshot", "expected"),
+ [
+ pytest.param(_static_listbox_snapshot(), True, id="all-clear"),
+ *[
+ pytest.param(_static_listbox_snapshot(**{key: True}), False, id=key)
+ for key in (
+ "popupSemanticsNearby",
+ "ownedByTrigger",
+ "activeDescendantRef",
+ "layered",
+ "textEntrySibling",
+ "openPopupOnPage",
+ )
+ ],
+ pytest.param(["not", "a", "snapshot"], False, id="non-dict"),
+ pytest.param(
+ {key: value for key, value in _static_listbox_snapshot().items() if key != "layered"},
+ False,
+ id="missing-key",
+ ),
+ pytest.param(_static_listbox_snapshot(layered=0), False, id="non-bool-value"),
+ ],
+)
+def test_static_listbox_option_snapshot_classification(snapshot: object, expected: bool) -> None:
+ assert is_static_listbox_option_snapshot(snapshot) is expected
+
+
+ ("html", "expected"),
+ [
+ pytest.param(
+ '<label aria-owns="choices">Choice X</label>'
+ '<div role="listbox" id="choices"><a role="option" id="option-a">Option A</a></div>',
+ True,
+ id="static-label-owned-tile",
+ ),
+ pytest.param(
+ '<dialog open role="dialog"><label aria-owns="choices">Choice X</label>'
+ '<div role="listbox" id="choices"><a role="option" id="option-a">Option A</a></div></dialog>',
+ True,
+ id="static-tile-in-dialog",
+ ),
+ pytest.param(
+ '<input role="combobox" aria-expanded="true" aria-controls="choices">'
+ '<div role="listbox" id="choices"><div role="option" id="option-a">Option A</div></div>',
+ False,
+ id="combobox-controls-listbox",
+ ),
+ pytest.param(
+ '<div role="listbox" aria-activedescendant="option-a">'
+ '<div role="option" id="option-a" aria-selected="true">Option A</div></div>',
+ False,
+ id="listbox-active-descendant-highlight",
+ ),
+ pytest.param(
+ '<button aria-expanded="true" aria-controls="popup">Choice X</button>'
+ '<div id="popup"><div role="listbox">'
+ '<div role="option" id="option-a">Option A</div></div></div>',
+ False,
+ id="trigger-controls-wrapper",
+ ),
+ pytest.param(
+ '<div style="position: absolute"><div style="display: contents"><div style="display: contents">'
+ '<div style="display: contents"><div role="listbox">'
+ '<div role="option" id="option-a">Option A</div></div></div></div></div></div>',
+ False,
+ id="aria-less-positioned-popup",
+ ),
+ pytest.param(
+ '<x-picker aria-haspopup="listbox"></x-picker>'
+ "<script>"
+ "const root = document.querySelector('x-picker').attachShadow({mode: 'open'});"
+ 'root.innerHTML = \'<div role="listbox"><div role="option" id="option-a">Option A</div></div>\';'
+ "</script>",
+ False,
+ id="shadow-host-popup-semantics",
+ ),
+ pytest.param(
+ "<x-picker></x-picker>"
+ "<script>"
+ "const root = document.querySelector('x-picker').attachShadow({mode: 'open'});"
+ 'root.innerHTML = \'<div role="listbox"><div role="option" id="option-a">Option A</div></div>\';'
+ "</script>",
+ True,
+ id="static-shadow-root-tile",
+ ),
+ ],
+)
+@_skip_no_browser
+async def test_static_listbox_option_real_dom_matrix(html: str, expected: bool) -> None:
+ async with _grid_fixture_page(html) as page:
+ static = {"id": "option-a", "tagName": "div", "attributes": {"role": "option", "id": "option-a"}}
+ element = SkyvernElement(page.locator("#option-a"), page, static)
+ assert await handler._is_static_listbox_option(element) is expected
+
+
+ ("frame_html", "expected"),
+ [
+ pytest.param('<div role="listbox"><div role="option" id="option-a">A</div></div>', True, id="static"),
+ pytest.param(
+ '<button aria-haspopup="listbox" aria-controls="choices">Open</button>'
+ '<div role="listbox" id="choices"><div role="option" id="option-a">A</div></div>',
+ False,
+ id="popup",
+ ),
+ ],
+)
+@_skip_no_browser
+async def test_static_listbox_option_classified_inside_iframe(frame_html: str, expected: bool) -> None:
+ async with _grid_fixture_page(f"<iframe id='child' srcdoc='{frame_html}'></iframe>") as page:
+ frame = await (await page.wait_for_selector("#child")).content_frame()
+ assert frame is not None
+ await frame.wait_for_selector("#option-a")
+ static = {"id": "option-a", "tagName": "div", "attributes": {"role": "option", "id": "option-a"}}
+ element = SkyvernElement(frame.locator("#option-a"), frame, static)
+ assert await handler._is_static_listbox_option(element) is expected
+
+
+ (
+ "target",
+ "selected",
+ "desired_state",
+ "context",
+ "expected_selected",
+ "expected_failure",
+ "option_count",
+ "repeat",
+ ),
+ [
+ pytest.param("option-a", True, None, "static", True, True, 2, 1, id="ambiguous-selected-option"),
+ pytest.param("option-a", True, None, "static", True, False, 2, 2, id="explicit-double-click-selected-option"),
+ pytest.param(
+ "option-a", True, True, "static", True, False, 2, 2, id="explicit-double-click-selected-desired-true"
+ ),
+ pytest.param("choices", False, None, "static", False, True, 2, 1, id="ambiguous-container"),
+ pytest.param("choices", False, None, "static", True, False, 1, 1, id="unique-option-container"),
+ pytest.param("choices", True, None, "static", True, True, 1, 1, id="unique-selected-container"),
+ pytest.param("choices", True, False, "static", False, False, 1, 1, id="unique-container-deselect"),
+ pytest.param("unmapped-option", False, None, "static", False, True, 1, 1, id="stale-container-option"),
+ pytest.param("wrapper", True, None, "static", True, True, 2, 1, id="disabled-wrapper-retarget"),
+ pytest.param("choices", False, None, "trigger", False, False, 2, 1, id="popup-container"),
+ pytest.param("option-a", True, False, "static", False, False, 2, 1, id="intentional-deselect"),
+ pytest.param("option-a", False, None, "static", True, False, 2, 1, id="first-selection"),
+ pytest.param("option-a", True, True, "static", True, False, 2, 1, id="explicit-selected-state"),
+ pytest.param("option-a", True, True, "trigger", False, False, 2, 1, id="popup-highlight-needs-click"),
+ pytest.param("option-a", True, None, "trigger", False, False, 2, 1, id="popup-option-reclick-legacy"),
+ pytest.param("option-a", True, None, "focus", False, False, 2, 1, id="focus-only-reclick-legacy"),
+ pytest.param("outside", False, None, "static", False, False, 2, 1, id="unrelated-click-legacy"),
+ pytest.param("choices", False, None, "display-none", False, False, 1, 1, id="hidden-unique-container-expands"),
+ pytest.param("choices", False, None, "display-none", False, False, 2, 1, id="hidden-container-expands"),
+ pytest.param("choices", False, None, "visibility-hidden", False, False, 2, 1, id="invisible-container-expands"),
+ pytest.param("choices", False, None, "partly-hidden", False, False, 2, 1, id="partly-hidden-container-expands"),
+ ],
+)
+@_skip_no_browser
+async def test_static_listbox_click_preserves_field_state(
+ monkeypatch: pytest.MonkeyPatch,
+ target: str,
+ selected: bool,
+ desired_state: bool | None,
+ context: str,
+ expected_selected: bool,
+ expected_failure: bool,
+ option_count: int,
+ repeat: int,
+) -> None:
+ trigger = '<button aria-haspopup="listbox" aria-controls="choices">Open</button>' if context == "trigger" else ""
+ active_descendant = ' aria-activedescendant="option-a"' if context == "focus" else ""
+ collapsed = context in ("display-none", "visibility-hidden", "partly-hidden")
+ hidden_style = "visibility:hidden" if context == "visibility-hidden" else "display:none"
+ option_a_style = hidden_style if context in ("display-none", "visibility-hidden") else ""
+ option_b_style = hidden_style if collapsed else ""
+ placeholder = '<div id="placeholder" style="height:60px">Choose an answer</div>' if collapsed else ""
+ html = (
+ trigger
+ + '<button id="outside">Outside</button>'
+ + f'<div role="listbox" id="choices" style="width:200px"{active_descendant}>'
+ + placeholder
+ + f'<div role="option" id="option-a" aria-selected="{str(selected).lower()}" style="{option_a_style}">'
+ + "Option A</div>"
+ + f'<div role="option" id="option-b" aria-selected="false" style="{option_b_style}">Option B</div></div>'
+ + '<div role="listbox"><div role="option" id="next-answer" aria-selected="false">Next answer</div></div>'
+ + "<script>document.querySelectorAll('[role=option]').forEach(el => el.onclick = () => "
+ + "el.setAttribute('aria-selected', el.getAttribute('aria-selected') !== 'true'));"
+ + "document.querySelectorAll('[role=option]').forEach(el => el.ondblclick = () => "
+ + "el.setAttribute('data-activated', 'true'));"
+ + "const placeholder = document.getElementById('placeholder');"
+ + "if (placeholder) placeholder.onclick = () => document.querySelectorAll('#choices [role=option]')"
+ + ".forEach(el => el.removeAttribute('style'));</script>"
+ )
+ async with _grid_fixture_page(html) as page:
+ if option_count == 1:
+ await page.locator("#option-b").evaluate("el => el.remove()")
+ if target == "wrapper":
+ await page.locator("#option-a").evaluate(
+ "el => { const wrapper = document.createElement('div'); wrapper.id = 'wrapper';"
+ " wrapper.setAttribute('aria-disabled', 'true'); el.replaceWith(wrapper); wrapper.append(el); }"
+ )
+ elements = {}
+ for element_id, tag, attributes in (
+ ("choices", "div", {"role": "listbox"}),
+ ("option-a", "div", {"role": "option"}),
+ ("option-b", "div", {"role": "option"}),
+ ("outside", "button", {}),
+ ):
+ if element_id == "option-b" and option_count == 1:
+ continue
+ await page.locator(f"#{element_id}").evaluate("(el) => el.setAttribute('unique_id', el.id)")
+ elements[element_id] = SkyvernElement(
+ page.locator(f"#{element_id}"),
+ page,
+ {
+ "id": element_id,
+ "tagName": tag,
+ "attributes": attributes,
+ "interactable": True,
+ "xpath": f"//*[@id='{element_id}']",
+ },
+ )
+ if target == "wrapper":
+ elements["wrapper"] = SkyvernElement(
+ page.locator("#wrapper"),
+ page,
+ {"id": "wrapper", "tagName": "div", "children": [elements["option-a"].get_element_dict()]},
+ )
+ retarget_expected = target == "choices" and option_count == 1 and context == "static"
+ if target == "unmapped-option":
+ await page.locator("#option-a").evaluate("el => el.setAttribute('unique_id', 'missing')")
+ target = "choices"
+ dom = MagicMock()
+ dom.get_skyvern_element_by_id = AsyncMock(side_effect=lambda element_id: elements[element_id])
+ dom.safe_get_skyvern_element_by_id = AsyncMock(side_effect=lambda element_id: elements.get(element_id))
+ dom.scraped_page = SimpleNamespace(id_to_element_hash={eid: f"hash-{eid}" for eid in elements})
+ incremental = MagicMock()
+ incremental.start_listen_dom_increment = AsyncMock()
+ incremental.stop_listen_dom_increment = AsyncMock()
+ frame = MagicMock()
+ frame.get_disabled_from_style = AsyncMock(return_value=False)
+ frame.scroll_element_into_view = AsyncMock()
+
+ async def physical_click(*args: object, **kwargs: object) -> list[ActionResult]:
+ click_action, element = args[3], args[4]
+ assert isinstance(click_action, ClickAction) and isinstance(element, SkyvernElement)
+ await handler._locator_click(element.get_locator(), handler._get_click_count(click_action))
+ return [ActionSuccess()]
+
+ async def legacy_followup(**kwargs: object) -> None:
+ await page.locator("#next-answer").click()
+
+ provider = FakeExperimentationProvider()
+ task = MagicMock(task_id="tsk_1", workflow_run_id="wr_1", organization_id="o_1", workflow_permanent_id="wpid_1")
+ monkeypatch.setattr(handler, "asyncio", ScopedAsyncio(sleep=AsyncMock()))
+ monkeypatch.setattr(handler.app, "EXPERIMENTATION_PROVIDER", provider)
+ with (
+ patch.object(handler, "DomUtil", return_value=dom),
+ patch.object(handler, "get_or_create_wait_config", new=AsyncMock(return_value=None)),
+ patch.object(handler, "chain_click", new=physical_click),
+ patch.object(handler, "resolve_engine_selection_for_task", return_value=None),
+ patch.object(handler.SkyvernFrame, "create_instance", new=AsyncMock(return_value=frame)),
+ patch.object(handler, "IncrementalScrapePage", return_value=incremental),
+ patch.object(handler, "handle_sequential_click_with_submit_bypass", new=legacy_followup),
+ ):
+ planned = elements[target].get_element_dict() if target in elements else {}
+ action = ClickAction(
+ element_id=target,
+ repeat=repeat,
+ click_context=ClickContext(desired_state=desired_state),
+ skyvern_element_data={**planned, "page_url": "http://fixture.test/"} if planned else None,
+ skyvern_element_hash=f"hash-{target}",
+ xpath=planned.get("xpath") if target == "choices" else None,
+ )
+ results = await handler.handle_click_action(action, page, MagicMock(), task, MagicMock())
+
+ assert (await page.locator("#option-a").get_attribute("aria-selected") == "true") is expected_selected
+ assert any(isinstance(result, ActionFailure) for result in results) is expected_failure
+ legacy_path = not expected_failure and (context != "static" or target == "outside")
+ assert (await page.locator("#next-answer").get_attribute("aria-selected") == "true") is legacy_path
+ assert all(call[0] != "FIX_STATIC_LISTBOX_OPTION_CLICK" for call in provider.calls)
+ activated = await page.locator("#option-a").get_attribute("data-activated") == "true"
+ assert activated is (repeat == 2 and not expected_failure)
+ if target == "choices":
+ final_id = "option-a" if retarget_expected else "choices"
+ assert action.element_id == final_id
+ assert action.get_xpath() == f"//*[@id='{final_id}']"
+ assert await page.locator(f"xpath={action.get_xpath()}").get_attribute("id") == final_id
+ assert action.skyvern_element_data is not None
+ assert action.skyvern_element_data["attributes"]["role"] == ("option" if retarget_expected else "listbox")
+ assert action.skyvern_element_data["page_url"] == "http://fixture.test/"
+ assert action.skyvern_element_hash == f"hash-{final_id}"
+ if collapsed:
+ assert await page.locator("#option-a").is_visible()
+ if option_count == 2:
+ assert await page.locator("#option-b").is_visible()
+ assert await page.locator("#option-b").get_attribute("aria-selected") == "false"
+ if expected_failure:
+ assert results[-1].skip_remaining_actions is True
+ if option_count == 2:
+ assert await page.locator("#option-b").get_attribute("aria-selected") == "false"
+
+
# --- _classify_grid_row_selection — pure classifier, no browser --------------
@@ -1916,7 +2271,7 @@ def _real_checkbox_element(page: Page, css_id: str) -> SkyvernElement:
@contextlib.asynccontextmanager
-async def _grid_fixture_page() -> AsyncIterator[Page]:
+async def _grid_fixture_page(html: str = _GRID_FIXTURE_HTML) -> AsyncIterator[Page]:
async with async_playwright() as pw:
browser = await pw.chromium.launch(headless=True, args=["--use-mock-keychain", "--password-store=basic"])
try:
@@ -1924,7 +2279,7 @@ async def _grid_fixture_page() -> AsyncIterator[Page]:
# visible region; per-element clip tests rely on their own `.clip-window`, not the viewport.
context = await browser.new_context(viewport={"width": 1280, "height": 2400})
page = await context.new_page()
- await page.set_content(_GRID_FIXTURE_HTML)
+ await page.set_content(html)
yield page
finally:
await browser.close()
diff --git a/tests/unit/test_disabled_control_readiness.py b/tests/unit/test_disabled_control_readiness.py
index 5d947959d..a54cbd603 100644
--- a/tests/unit/test_disabled_control_readiness.py
+++ b/tests/unit/test_disabled_control_readiness.py
@@ -95,6 +95,7 @@ async def test_skyvern_element_click_classifies_permanently_disabled_control() -
async def test_click_handler_classifies_control_that_stays_disabled() -> None:
element = MagicMock()
element.get_id.return_value = "control"
+ element.get_attr = AsyncMock(return_value=None)
element.is_disabled = AsyncMock(return_value=True)
dom = MagicMock()
dom.get_skyvern_element_by_id = AsyncMock(return_value=element)
diff --git a/tests/unit/webeye/test_dom_inspection.py b/tests/unit/webeye/test_dom_inspection.py
index facee3159..94fc25d9f 100644
--- a/tests/unit/webeye/test_dom_inspection.py
+++ b/tests/unit/webeye/test_dom_inspection.py
@@ -51,6 +51,7 @@ def test_dom_inspection_interface_accepts_no_caller_supplied_code() -> None:
"read_current_url",
"read_locator_is_content_editable",
"read_locator_selected_state",
+ "read_static_listbox_option_snapshot",
"read_locator_tag_name",
"read_resolved_anchor_href",
"read_whether_link_or_button",