Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-12399): shadow-DOM-aware incremental dropdown detection with scoped fallback (#7516)
Aaron Perez5ecabeb125d9
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex 4f4eff65c..8a700a8b8 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -170,6 +170,7 @@ LOG = structlog.get_logger()UPLOAD_PENDING_FOLLOWUP_MESSAGE = "Upload is not complete yet. Continue the upload flow."FIX_TEL_INPUT_DIGIT_DROP_FLAG = "FIX_TEL_INPUT_DIGIT_DROP"+VERIFY_EMERGING_SELECT_PICK_FLAG = "VERIFY_EMERGING_SELECT_PICK"COLLAPSE_SELECT_FANOUT_FLAG = "COLLAPSE_SELECT_FANOUT"COLLAPSE_CUSTOM_SELECT_FANOUT_FLAG = "COLLAPSE_CUSTOM_SELECT_FANOUT"COLLAPSE_AUTOCOMPLETE_FANOUT_FLAG = "COLLAPSE_AUTOCOMPLETE_FANOUT"@@ -1200,6 +1201,10 @@ async def _is_tel_digit_fix_enabled(task: Task) -> bool:return await _is_org_flag_enabled(task, FIX_TEL_INPUT_DIGIT_DROP_FLAG, "tel-digit-fix")+async def _is_verify_emerging_select_pick_enabled(task: Task) -> bool:+ return await _is_org_flag_enabled(task, VERIFY_EMERGING_SELECT_PICK_FLAG, "verify-emerging-select-pick")++async def _resolve_collapse_xp_assignment(experimentation_provider: BaseExperimentationProvider,task: Task,@@ -7233,6 +7238,74 @@ def _collect_new_roots(element: dict, new_ids: set[str], out: list[dict]) -> Non_collect_new_roots(child, new_ids, out)+def _custom_select_fallback_subtrees(elements: list[dict], current_element_id: str) -> list[dict]:+ anchor: dict | None = None+ anchor_is_open = False+ listboxes: list[dict] = []+ anchor_descendant_listboxes: list[dict] = []+ all_nodes: list[dict] = []++ queue: deque[tuple[dict, bool, bool]] = deque((element, False, False) for element in elements)+ while queue:+ node, in_anchor, in_expanded_combobox = queue.popleft()+ if not isinstance(node, dict):+ continue+ attrs = node.get("attributes") or {}+ all_nodes.append(node)+ role = str(attrs.get("role") or "").lower()+ is_anchor = node.get("id") == current_element_id+ child_in_anchor = in_anchor or is_anchor+ expanded = str(attrs.get("aria-expanded") or "").lower() == "true"+ child_in_expanded_combobox = in_expanded_combobox or (role == "combobox" and expanded)++ if is_anchor:+ anchor = node+ anchor_is_open = expanded or in_expanded_combobox+ if role == "listbox":+ listboxes.append(node)+ if child_in_anchor:+ anchor_descendant_listboxes.append(node)++ for child in node.get("children") or []:+ queue.append((child, child_in_anchor, child_in_expanded_combobox))++ if anchor is None:+ return []++ anchor_attrs = anchor.get("attributes") or {}+ controlled_dom_ids = {+ reference+ for attribute_name in ("aria-controls", "aria-owns")+ for reference in str(anchor_attrs.get(attribute_name) or "").split()+ if reference+ }+ anchor_dom_id = str(anchor_attrs.get("id") or "")+ controlled_subtrees = [+ node+ for node in all_nodes+ if str((node.get("attributes") or {}).get("id") or "") in controlled_dom_ids+ and _custom_select_candidates_from_elements([node])+ ]+ if controlled_subtrees:+ return controlled_subtrees++ linked_listboxes = []+ for listbox in listboxes:+ attrs = listbox.get("attributes") or {}+ listbox_dom_id = str(attrs.get("id") or "")+ labelled_by = set(str(attrs.get("aria-labelledby") or "").split())+ if listbox_dom_id in controlled_dom_ids or (anchor_dom_id and anchor_dom_id in labelled_by):+ linked_listboxes.append(listbox)++ if linked_listboxes:+ return linked_listboxes+ if anchor_descendant_listboxes:+ return anchor_descendant_listboxes+ if len(listboxes) == 1 and anchor_is_open:+ return listboxes+ return []++@traced(name="skyvern.agent.dropdown.select_emerging")async def select_from_emerging_elements(current_element_id: str,@@ -7262,12 +7335,44 @@ async def select_from_emerging_elements(if (await dom_after_open.get_skyvern_element_by_id(element_id)).is_interactable()]+ fallback_element_subtrees: list[dict] = []+ if len(new_interactable_element_ids) == 0:+ # Resolve ownership from the untrimmed tree: trim_element_tree drops aria-controls /+ # aria-owns / aria-labelledby / the DOM id, which are exactly the linkage attributes this+ # fallback keys off, so resolving against the trimmed tree leaves it inert. Re-trim the+ # small resolved subtree set below so the prompt stays trimmed (no page-wide token cost).+ fallback_element_subtrees = _custom_select_fallback_subtrees(+ scraped_page_after_open.element_tree,+ current_element_id,+ )+ fallback_element_subtrees = trim_element_tree(copy.deepcopy(fallback_element_subtrees))+ fallback_candidates = _custom_select_candidates_from_elements(fallback_element_subtrees)+ fallback_candidate_ids: list[str] = []+ for candidate in fallback_candidates:+ fallback_id = candidate.get("element_id")+ if fallback_id is not None:+ fallback_candidate_ids.append(fallback_id)+ new_interactable_element_ids = [+ element_id+ for element_id in fallback_candidate_ids+ if (await dom_after_open.get_skyvern_element_by_id(element_id)).is_interactable()+ ]+ if new_interactable_element_ids:+ LOG.info(+ "Found current-page custom-select options after incremental detection returned no elements",+ current_element_id=current_element_id,+ fallback_option_count=len(new_interactable_element_ids),+ )+if len(new_interactable_element_ids) == 0:raise NoIncrementalElementFoundForCustomSelection(element_id=current_element_id)+ interactable_element_ids = set(new_interactable_element_ids)# Extract minimal subtrees rooted at new elements — avoids sending the full page DOM# which gets truncated on large pages, losing portal-rendered dropdown items.- new_element_subtrees = _extract_new_subtrees(scraped_page_after_open.element_tree_trimmed, new_element_ids)+ new_element_subtrees = fallback_element_subtrees or _extract_new_subtrees(+ scraped_page_after_open.element_tree_trimmed, new_element_ids+ )shadow_candidate_elements: list[dict] = []_ctx = skyvern_context.current()lean_enabled = bool(_ctx and _ctx.enable_lean_element_tree)@@ -7310,9 +7415,20 @@ async def select_from_emerging_elements(async def get_readback_scope_element() -> SkyvernElement | None:return await dom_after_open.get_skyvern_element_by_id(current_element_id)+ verify_pick_enabled = await _is_verify_emerging_select_pick_enabled(task)+ deterministic_candidates = _custom_select_candidates_from_elements(shadow_candidate_elements)+ if verify_pick_enabled:+ # Restrict deterministic matching to the elements the dropdown actually surfaced. Gated:+ # custom-widget option nodes are often not flagged interactable, so flag off keeps main's+ # behavior (all candidates) and this ramps with the off-list rejection below.+ deterministic_candidates = [+ candidate+ for candidate in deterministic_candidates+ if candidate.get("element_id") in interactable_element_ids+ ]deterministic_result = await _select_deterministic_custom_option(target_value=options.target_value,- get_option_candidates=lambda: _custom_select_candidates_from_elements(shadow_candidate_elements),+ get_option_candidates=lambda: deterministic_candidates,field_context=options.model_dump(),page=page,get_skyvern_element=dom_after_open.get_skyvern_element_by_id,@@ -7366,7 +7482,20 @@ async def select_from_emerging_elements(llm_value=value,),)- if not element_id or raw_action_type not in (ActionType.CLICK.value, ActionType.INPUT_TEXT.value):+ anchor_input_pick = raw_action_type == ActionType.INPUT_TEXT.value and element_id == current_element_id+ # A pick outside the elements the dropdown actually surfaced is a wrong-field click that used to+ # proceed on a warning. Rejecting it turns those silent successes into loud failures, so it ramps+ # behind a flag rather than shipping to every org at once.+ off_list = element_id not in interactable_element_ids and not anchor_input_pick+ if off_list and not verify_pick_enabled:+ # Keep the pre-flag warning so the reject rate is measurable before ramping the flag on.+ LOG.warning(+ "Emerging-select pick is outside the surfaced interactable elements; proceeding because the verify flag is off",+ element_id=element_id,+ current_element_id=current_element_id,+ )+ off_list_pick = off_list and verify_pick_enabled+ if not element_id or raw_action_type not in (ActionType.CLICK.value, ActionType.INPUT_TEXT.value) or off_list_pick:raise _no_match_exception_for_dropdown(reasoning=json_response.get("reasoning"),target_value=options.target_value,@@ -7375,14 +7504,6 @@ async def select_from_emerging_elements()action_type = ActionType(raw_action_type)- new_ids_set = set(new_interactable_element_ids)- if element_id not in new_ids_set:- LOG.warning(- "custom-select returned element outside new_interactable_element_ids",- selected_element_id=element_id,- new_interactable_count=len(new_ids_set),- )-if value is not None and action_type == ActionType.INPUT_TEXT:actual_value = get_actual_value_of_parameter_if_secret_with_task(task, value)LOG.info(diff --git a/skyvern/webeye/scraper/domUtils.js b/skyvern/webeye/scraper/domUtils.jsindex a3b3dbe1c..764f7da91 100644--- a/skyvern/webeye/scraper/domUtils.js+++ b/skyvern/webeye/scraper/domUtils.js@@ -2875,6 +2875,160 @@ function asyncSleepFor(ms) {return new Promise((resolve) => setTimeout(resolve, ms));}+const incrementalObserverAttributeFilter = [+ "class",+ "style",+ "hidden",+ "aria-expanded",+ "aria-hidden",+];+const maxIncrementalShadowRootDepth = 10;+const maxIncrementalShadowRootCount = 200;+const maxIncrementalShadowDiscoveryVisits = 4000;+const incrementalShadowDiscoveryBudgetMs = 25;++function getIncrementalObserverOptions() {+ return {+ attributes: true,+ attributeOldValue: true,+ childList: true,+ subtree: true,+ characterData: true,+ };+}++function getIncrementalOptionLikeElements(+ root,+ recurseObservedShadowRoots = false,+) {+ const selector =+ '[role="listbox"], [role="option"], [role="listbox"] li, [role="combobox"] li';+ const elements = [];+ const pending = [root];+ const visited = new Set();+ while (pending.length > 0) {+ const currentRoot = pending.pop();+ if (!currentRoot || visited.has(currentRoot)) continue;+ visited.add(currentRoot);+ if (currentRoot instanceof Element && currentRoot.matches(selector)) {+ elements.push(currentRoot);+ }+ if (currentRoot.querySelectorAll) {+ elements.push(...currentRoot.querySelectorAll(selector));+ }+ if (!recurseObservedShadowRoots) continue;+ const possibleHosts =+ currentRoot instanceof Element+ ? [currentRoot, ...currentRoot.querySelectorAll("*")]+ : [...currentRoot.querySelectorAll("*")];+ for (const possibleHost of possibleHosts) {+ if (+ possibleHost.shadowRoot &&+ window.globalObservedShadowRoots.has(possibleHost.shadowRoot)+ ) {+ pending.push(possibleHost.shadowRoot);+ }+ }+ }+ return elements;+}++function isIncrementalOptionSubtreeVisible(element) {+ return (+ !element.hidden &&+ element.getAttribute("aria-hidden") !== "true" &&+ isElementVisible(element)+ );+}++function trackIncrementalOptionVisibility(root) {+ for (const optionLikeElement of getIncrementalOptionLikeElements(root)) {+ let currentElement = optionLikeElement;+ while (currentElement instanceof Element) {+ if (window.globalIncrementalVisibilityMap.has(currentElement)) break;+ window.globalIncrementalVisibilityMap.set(+ currentElement,+ isIncrementalOptionSubtreeVisible(currentElement),+ );+ if (currentElement.parentElement) {+ currentElement = currentElement.parentElement;+ continue;+ }+ const currentRoot = currentElement.getRootNode();+ currentElement =+ currentRoot instanceof ShadowRoot ? currentRoot.host : null;+ }+ }+}++function observeIncrementalTarget(target) {+ window.globalObserverForDOMIncrement.observe(+ target,+ getIncrementalObserverOptions(),+ );+ trackIncrementalOptionVisibility(target);+}++function observeIncrementalShadowRoot(shadowRoot, countTowardBudget = true) {+ if (window.globalObservedShadowRoots.has(shadowRoot)) return;+ window.globalObservedShadowRoots.add(shadowRoot);+ if (countTowardBudget) {+ window.globalObservedShadowRootCount++;+ }+ observeIncrementalTarget(shadowRoot);+}++function discoverAndObserveOpenShadowRoots(+ startNode,+ initialDepth = 0,+ deadline = Number.POSITIVE_INFINITY,+ countTowardBudget = true,+) {+ const pending = [{ node: startNode, depth: initialDepth }];+ let currentIndex = 0;+ while (+ currentIndex < pending.length &&+ currentIndex < maxIncrementalShadowDiscoveryVisits &&+ (!countTowardBudget ||+ window.globalObservedShadowRootCount < maxIncrementalShadowRootCount) &&+ performance.now() < deadline+ ) {+ const { node, depth } = pending[currentIndex++];+ if (!node || depth > maxIncrementalShadowRootDepth) continue;++ if (+ node instanceof Element &&+ node.shadowRoot &&+ depth < maxIncrementalShadowRootDepth+ ) {+ const shadowRoot = node.shadowRoot;+ if (!window.globalObservedShadowRoots.has(shadowRoot)) {+ observeIncrementalShadowRoot(shadowRoot, countTowardBudget);+ }+ for (const child of shadowRoot.children) {+ pending.push({ node: child, depth: depth + 1 });+ }+ }++ if (node.children) {+ for (const child of node.children) {+ pending.push({ node: child, depth });+ }+ }+ }+}++function isNewlyVisibleIncrementalOptionSubtree(node) {+ const wasVisible = window.globalIncrementalVisibilityMap.get(node) ?? false;+ const isVisible = isIncrementalOptionSubtreeVisible(node);+ window.globalIncrementalVisibilityMap.set(node, isVisible);+ return (+ !wasVisible &&+ isVisible &&+ getIncrementalOptionLikeElements(node, true).length > 0+ );+}+async function addIncrementalNodeToMap(parentNode, childrenNode) {const maxParsedElement = 3000;const maxElementToWait = 100;@@ -2891,10 +3045,7 @@ async function addIncrementalNodeToMap(parentNode, childrenNode) {if (window.globalListnerFlag) {// calculate the depth of targetNode element for sortingconst depth = getElementDomDepth(parentNode);- let newNodesTreeList = [];- if (window.globalDomDepthMap.has(depth)) {- newNodesTreeList = window.globalDomDepthMap.get(depth);- }+ const parsedNodeTrees = [];try {for (const child of childrenNode) {@@ -2912,13 +3063,17 @@ async function addIncrementalNodeToMap(parentNode, childrenNode) {window.globalHoverStylesMap,);if (newNodeTree.length > 0) {- newNodesTreeList.push(...newNodeTree);+ parsedNodeTrees.push(...newNodeTree);}}} catch (error) {_jsConsoleError("Error building incremental element node:", error);}- window.globalDomDepthMap.set(depth, newNodesTreeList);+ const currentNodeTrees = window.globalDomDepthMap.get(depth) || [];+ window.globalDomDepthMap.set(depth, [+ ...currentNodeTrees,+ ...parsedNodeTrees,+ ]);}await window.globalParsedElementCounter.add();}@@ -2928,12 +3083,29 @@ if (window.globalObserverForDOMIncrement === undefined) {mutationsList,observer,) {+ const shadowDiscoveryDeadline =+ performance.now() + incrementalShadowDiscoveryBudgetMs;// TODO: how to detect duplicated recreate element?for (const mutation of mutationsList) {- const node = mutation.target;+ const node =+ mutation.target instanceof ShadowRoot+ ? mutation.target.host+ : mutation.target;if (node.nodeType === Node.TEXT_NODE) continue;const tagName = node.tagName?.toLowerCase();+ if (mutation.type === "childList") {+ for (const addedNode of mutation.addedNodes) {+ if (!(addedNode instanceof Element)) continue;+ trackIncrementalOptionVisibility(addedNode);+ discoverAndObserveOpenShadowRoots(+ addedNode,+ 0,+ shadowDiscoveryDeadline,+ );+ }+ }+// ignore unique_id change to avoid infinite loop about DOM changesif (mutation.attributeName === "unique_id") continue;@@ -2955,6 +3127,19 @@ if (window.globalObserverForDOMIncrement === undefined) {// we detect the element based on the following rulesswitch (mutation.type) {case "attributes": {+ if (+ incrementalObserverAttributeFilter.includes(+ mutation.attributeName,+ ) &&+ isNewlyVisibleIncrementalOptionSubtree(node)+ ) {+ window.globalOneTimeIncrementElements.push({+ targetNode: node,+ newNodes: [node],+ });+ await addIncrementalNodeToMap(node, [node]);+ break;+ }switch (mutation.attributeName) {case "hidden": {if (!node.hidden) {@@ -3050,25 +3235,48 @@ async function startGlobalIncrementalObserver(element = null) {window.globalOneTimeIncrementElements = [];await getHoverStylesMap();window.globalParsedElementCounter = new SafeCounter();+ window.globalIncrementalVisibilityMap = new WeakMap();+ window.globalObservedShadowRoots = new WeakSet();+ window.globalObservedShadowRootCount = 0;+ window.globalIncrementalObserverGeneration =+ (window.globalIncrementalObserverGeneration || 0) + 1;window.globalObserverForDOMIncrement.takeRecords(); // cleanup the older data- window.globalObserverForDOMIncrement.observe(document.body, {- attributes: true,- attributeOldValue: true,- childList: true,- subtree: true,- characterData: true,- });- // if the element is in shadow DOM, we need to observe the shadow DOM as well- if (element && element.getRootNode() instanceof ShadowRoot) {- window.globalObserverForDOMIncrement.observe(element.getRootNode(), {- attributes: true,- attributeOldValue: true,- childList: true,- subtree: true,- characterData: true,- });+ let composedTreeElement = element;+ let composedTreeDepth = 0;+ const composedTreeRoots = [];+ while (+ composedTreeElement instanceof Element &&+ composedTreeDepth < maxIncrementalShadowRootDepth+ ) {+ const root = composedTreeElement.getRootNode();+ if (!(root instanceof ShadowRoot)) break;+ observeIncrementalShadowRoot(root, false);+ composedTreeRoots.push({ root, depth: composedTreeDepth });+ composedTreeElement = root.host;+ composedTreeDepth++;+ }++ const anchorDiscoveryDeadline = performance.now() + 50;+ for (const { root, depth } of composedTreeRoots) {+ discoverAndObserveOpenShadowRoots(root, depth, anchorDiscoveryDeadline);}++ observeIncrementalTarget(document.body);+ const observerGeneration = window.globalIncrementalObserverGeneration;+ setTimeout(() => {+ if (+ !window.globalListnerFlag ||+ observerGeneration !== window.globalIncrementalObserverGeneration+ ) {+ return;+ }+ discoverAndObserveOpenShadowRoots(+ document.documentElement,+ 0,+ performance.now() + 50,+ );+ }, 0);}async function stopGlobalIncrementalObserver() {diff --git a/tests/unit/test_select_shadow_match.py b/tests/unit/test_select_shadow_match.pyindex 2024df225..c345dc219 100644--- a/tests/unit/test_select_shadow_match.py+++ b/tests/unit/test_select_shadow_match.py@@ -1,3 +1,4 @@+import copyfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, Mockfrom zoneinfo import ZoneInfo@@ -20,7 +21,7 @@ _SHADOW_OPTION = {def _shadow_task() -> SimpleNamespace:- return SimpleNamespace(navigation_goal="goal", navigation_payload={}, llm_key=None)+ return SimpleNamespace(navigation_goal="goal", navigation_payload={}, llm_key=None, organization_id=None)class _FakeSelectLocator:@@ -483,9 +484,7 @@ async def test_emerging_select_call_path_forwards_committed_value_to_shadow_matcclick=AsyncMock(),)dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock(return_value=selected_element))- llm_handler = AsyncMock(- return_value={"id": "different-id", "value": " committed value ", "action_type": "click"}- )+ llm_handler = AsyncMock(return_value={"id": "matched-id", "value": " committed value ", "action_type": "click"})monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))monkeypatch.setattr(handler, "json_to_html", Mock(return_value="<div>Committed Value</div>"))monkeypatch.setattr(handler, "_select_deterministic_custom_option", AsyncMock(return_value=None))@@ -521,6 +520,611 @@ async def test_emerging_select_call_path_forwards_committed_value_to_shadow_matcassert events[0]["match_agrees_with_llm"] is True+async def test_emerging_select_falls_back_to_visible_controlled_listbox_when_no_ids_are_new(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ anchor = {+ "id": "field-id",+ "tagName": "button",+ "attributes": {+ "aria-controls": "menu-dom-id",+ "aria-expanded": "true",+ "role": "combobox",+ },+ "interactable": True,+ "children": [],+ }+ listbox = {+ "id": "menu-id",+ "tagName": "div",+ "attributes": {"id": "menu-dom-id", "role": "listbox"},+ "children": [+ {+ "id": "option-a",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Alpha",+ "interactable": True,+ "children": [],+ },+ {+ "id": "option-hidden",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Beta",+ "interactable": False,+ "children": [],+ },+ {+ "id": "option-b",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Beta",+ "interactable": True,+ "children": [],+ },+ ],+ }+ tree = [anchor, listbox]+ ids = {+ "field-id": "[unique_id=field-id]",+ "menu-id": "[unique_id=menu-id]",+ "option-a": "[unique_id=option-a]",+ "option-hidden": "[unique_id=option-hidden]",+ "option-b": "[unique_id=option-b]",+ }++ def element_for_id(element_id: str) -> MagicMock:+ return MagicMock(+ is_interactable=Mock(return_value=element_id.startswith("option-") and element_id != "option-hidden")+ )++ dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock(side_effect=element_for_id))++ async def select_deterministically(**kwargs: object) -> tuple[handler.ActionSuccess, str]:+ get_option_candidates = kwargs["get_option_candidates"]+ assert callable(get_option_candidates)+ assert [candidate["label"] for candidate in get_option_candidates()] == ["Alpha", "Beta"]+ return handler.ActionSuccess(), "Beta"++ monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))+ deterministic_select = AsyncMock(side_effect=select_deterministically)+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", deterministic_select)+ llm_handler = AsyncMock()+ monkeypatch.setattr(+ handler.LLMAPIHandlerFactory,+ "get_override_llm_api_handler",+ Mock(return_value=llm_handler),+ )++ scraped_page = SimpleNamespace(id_to_css_dict=ids)+ scraped_page_after_open = SimpleNamespace(id_to_css_dict=ids, element_tree=tree, element_tree_trimmed=tree)+ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ result = await handler.select_from_emerging_elements(+ current_element_id="field-id",+ options=handler.CustomSelectPromptOptions(target_value="Beta"),+ page=MagicMock(),+ scraped_page=scraped_page,+ scraped_page_after_open=scraped_page_after_open,+ step=SimpleNamespace(step_id="step-1"),+ task=_shadow_task(),+ )++ assert isinstance(result, handler.ActionSuccess)+ deterministic_select.assert_awaited_once()+ llm_handler.assert_not_awaited()+++async def test_emerging_select_fallback_resolves_owned_listbox_when_trim_strips_ownership_attrs(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # A custom combobox whose listbox is linked by aria-controls. trim_element_tree drops+ # aria-controls / aria-owns / the DOM id from the trimmed tree, so ownership must be resolved+ # from the untrimmed element_tree — resolving it from the trimmed tree leaves the fallback inert.+ anchor = {+ "id": "field-id",+ "tagName": "button",+ "attributes": {"aria-controls": "menu-dom-id", "aria-expanded": "true", "role": "combobox"},+ "interactable": True,+ "children": [],+ }+ listbox = {+ "id": "menu-id",+ "tagName": "div",+ "attributes": {"id": "menu-dom-id", "role": "listbox"},+ "children": [+ {+ "id": "option-a",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Alpha",+ "interactable": True,+ "children": [],+ },+ {+ "id": "option-b",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Beta",+ "interactable": True,+ "children": [],+ },+ ],+ }+ element_tree = [anchor, listbox]+ element_tree_trimmed = handler.trim_element_tree(copy.deepcopy(element_tree))+ # Guard the premise: trim really removes the ownership signal the fallback keys off.+ assert "aria-controls" not in (element_tree_trimmed[0].get("attributes") or {})+ assert "id" not in (element_tree_trimmed[1].get("attributes") or {})++ ids = {+ "field-id": "[unique_id=field-id]",+ "menu-id": "[unique_id=menu-id]",+ "option-a": "[unique_id=option-a]",+ "option-b": "[unique_id=option-b]",+ }++ def element_for_id(element_id: str) -> MagicMock:+ return MagicMock(is_interactable=Mock(return_value=element_id.startswith("option-")))++ dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock(side_effect=element_for_id))++ async def select_deterministically(**kwargs: object) -> tuple[handler.ActionSuccess, str]:+ get_option_candidates = kwargs["get_option_candidates"]+ assert callable(get_option_candidates)+ assert [candidate["label"] for candidate in get_option_candidates()] == ["Alpha", "Beta"]+ return handler.ActionSuccess(), "Beta"++ monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))+ deterministic_select = AsyncMock(side_effect=select_deterministically)+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", deterministic_select)+ monkeypatch.setattr(+ handler.LLMAPIHandlerFactory,+ "get_override_llm_api_handler",+ Mock(return_value=AsyncMock()),+ )++ scraped_page = SimpleNamespace(id_to_css_dict=ids)+ scraped_page_after_open = SimpleNamespace(+ id_to_css_dict=ids,+ element_tree=element_tree,+ element_tree_trimmed=element_tree_trimmed,+ )+ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ result = await handler.select_from_emerging_elements(+ current_element_id="field-id",+ options=handler.CustomSelectPromptOptions(target_value="Beta"),+ page=MagicMock(),+ scraped_page=scraped_page,+ scraped_page_after_open=scraped_page_after_open,+ step=SimpleNamespace(step_id="step-1"),+ task=_shadow_task(),+ )++ assert isinstance(result, handler.ActionSuccess)+ deterministic_select.assert_awaited_once()+++async def test_emerging_select_keeps_off_list_candidate_for_deterministic_match_when_flag_off(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Option nodes in custom widgets are often not flagged interactable. With the verify flag off we+ # must not pre-filter deterministic candidates to the interactable set (main's behavior) — dropping+ # them there would regress selections that used to succeed.+ tree = [+ {+ "id": "option-x",+ "tagName": "div",+ "attributes": {"role": "option"},+ "text": "Alpha",+ "interactable": True,+ "children": [],+ },+ {+ "id": "option-y",+ "tagName": "div",+ "attributes": {"role": "option"},+ "text": "Beta",+ "children": [],+ },+ ]+ monkeypatch.setattr(handler, "_is_verify_emerging_select_pick_enabled", AsyncMock(return_value=False))+ dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock())+ monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))+ monkeypatch.setattr(handler, "json_to_html", Mock(return_value="<div role='option'>option</div>"))+ monkeypatch.setattr(handler.prompt_engine, "load_prompt", Mock(return_value="prompt"))+ llm_handler = AsyncMock()+ monkeypatch.setattr(+ handler.LLMAPIHandlerFactory,+ "get_override_llm_api_handler",+ Mock(return_value=llm_handler),+ )++ async def select_deterministically(**kwargs: object) -> tuple[handler.ActionSuccess, str]:+ get_option_candidates = kwargs["get_option_candidates"]+ assert callable(get_option_candidates)+ assert [candidate["element_id"] for candidate in get_option_candidates()] == ["option-x", "option-y"]+ return handler.ActionSuccess(), "Beta"++ deterministic_select = AsyncMock(side_effect=select_deterministically)+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", deterministic_select)++ scraped_page = SimpleNamespace(id_to_css_dict={})+ scraped_page_after_open = SimpleNamespace(+ id_to_css_dict={"option-x": "[unique_id=option-x]", "option-y": "[unique_id=option-y]"},+ element_tree_trimmed=tree,+ )+ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ result = await handler.select_from_emerging_elements(+ current_element_id="field-id",+ options=handler.CustomSelectPromptOptions(target_value="Beta"),+ page=MagicMock(),+ scraped_page=scraped_page,+ scraped_page_after_open=scraped_page_after_open,+ new_interactable_element_ids=["option-x"],+ step=SimpleNamespace(step_id="step-1"),+ task=_shadow_task(),+ )++ assert isinstance(result, handler.ActionSuccess)+ deterministic_select.assert_awaited_once()+ llm_handler.assert_not_awaited()++[email protected](("anchor_expanded", "expected"), [(False, []), (True, ["listbox-id"])])+def test_custom_select_fallback_requires_open_anchor_for_sole_listbox(+ anchor_expanded: bool,+ expected: list[str],+) -> None:+ tree = [+ {+ "id": "field-id",+ "tagName": "button",+ "attributes": {"aria-expanded": str(anchor_expanded).lower()},+ "children": [],+ },+ {+ "id": "listbox-id",+ "tagName": "div",+ "attributes": {"role": "listbox"},+ "children": [+ {+ "id": "option-id",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Alpha",+ "children": [],+ }+ ],+ },+ ]++ result = handler._custom_select_fallback_subtrees(tree, "field-id")++ assert [element["id"] for element in result] == expected+++def test_custom_select_fallback_accepts_sole_listbox_for_expanded_combobox_ancestor() -> None:+ tree = [+ {+ "id": "combobox-id",+ "tagName": "div",+ "attributes": {"aria-expanded": "true", "role": "combobox"},+ "children": [+ {+ "id": "field-id",+ "tagName": "input",+ "attributes": {},+ "children": [],+ }+ ],+ },+ {+ "id": "listbox-id",+ "tagName": "div",+ "attributes": {"role": "listbox"},+ "children": [+ {+ "id": "option-id",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Alpha",+ "children": [],+ }+ ],+ },+ ]++ result = handler._custom_select_fallback_subtrees(tree, "field-id")++ assert [element["id"] for element in result] == ["listbox-id"]+++async def test_emerging_select_rejects_page_global_options_without_owned_listbox(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ tree = [+ {+ "id": "field-id",+ "tagName": "button",+ "attributes": {"aria-expanded": "true", "role": "combobox"},+ "children": [],+ },+ {+ "id": "unrelated-option",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Wrong field",+ "children": [],+ },+ ]+ dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock())+ monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))+ scraped_page = SimpleNamespace(id_to_css_dict={"field-id": "[unique_id=field-id]"})+ scraped_page_after_open = SimpleNamespace(+ id_to_css_dict={"field-id": "[unique_id=field-id]"},+ element_tree=tree,+ element_tree_trimmed=tree,+ )++ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ with pytest.raises(handler.NoIncrementalElementFoundForCustomSelection):+ await handler.select_from_emerging_elements(+ current_element_id="field-id",+ options=handler.CustomSelectPromptOptions(target_value="Wrong field"),+ page=MagicMock(),+ scraped_page=scraped_page,+ scraped_page_after_open=scraped_page_after_open,+ step=SimpleNamespace(step_id="step-1"),+ task=_shadow_task(),+ )+++async def test_emerging_select_rejects_hidden_candidate_from_deterministic_and_llm_paths(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ tree = [+ {+ "id": "hidden-id",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Exact target",+ "children": [],+ },+ {+ "id": "visible-id",+ "tagName": "button",+ "attributes": {"role": "option"},+ "text": "Visible alternative",+ "children": [],+ },+ ]+ dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock())+ monkeypatch.setattr(handler, "_is_verify_emerging_select_pick_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))+ monkeypatch.setattr(handler, "json_to_html", Mock(return_value="<button role='option'>option</button>"))+ monkeypatch.setattr(handler.prompt_engine, "load_prompt", Mock(return_value="prompt"))+ llm_handler = AsyncMock(return_value={"id": "hidden-id", "value": "Exact target", "action_type": "click"})+ monkeypatch.setattr(+ handler.LLMAPIHandlerFactory,+ "get_override_llm_api_handler",+ Mock(return_value=llm_handler),+ )++ async def select_deterministically(**kwargs: object) -> None:+ get_option_candidates = kwargs["get_option_candidates"]+ assert callable(get_option_candidates)+ assert [candidate["element_id"] for candidate in get_option_candidates()] == ["visible-id"]+ return None++ monkeypatch.setattr(+ handler,+ "_select_deterministic_custom_option",+ AsyncMock(side_effect=select_deterministically),+ )+ scraped_page = SimpleNamespace(id_to_css_dict={})+ scraped_page_after_open = SimpleNamespace(+ id_to_css_dict={+ "hidden-id": "[unique_id=hidden-id]",+ "visible-id": "[unique_id=visible-id]",+ },+ element_tree_trimmed=tree,+ )++ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ with pytest.raises(handler.NoAvailableOptionFoundForCustomSelection):+ await handler.select_from_emerging_elements(+ current_element_id="field-id",+ options=handler.CustomSelectPromptOptions(target_value="Exact target"),+ page=MagicMock(),+ scraped_page=scraped_page,+ scraped_page_after_open=scraped_page_after_open,+ new_interactable_element_ids=["visible-id"],+ step=SimpleNamespace(step_id="step-1"),+ task=_shadow_task(),+ )++ dom_after_open.get_skyvern_element_by_id.assert_not_awaited()+++async def test_emerging_select_allows_input_text_on_anchor_element(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ anchor_input = MagicMock(+ scroll_into_view=AsyncMock(),+ get_tag_name=Mock(return_value="input"),+ get_locator=Mock(return_value=MagicMock()),+ is_readonly=AsyncMock(return_value=False),+ input_clear=AsyncMock(),+ input_sequentially=AsyncMock(),+ )+ dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock(return_value=anchor_input))+ llm_handler = AsyncMock(return_value={"id": "field-id", "value": "filter text", "action_type": "input_text"})+ monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))+ monkeypatch.setattr(handler, "json_to_html", Mock(return_value="<div>Option</div>"))+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", AsyncMock(return_value=None))+ monkeypatch.setattr(handler, "get_input_value", AsyncMock(return_value=""))+ monkeypatch.setattr(handler.prompt_engine, "load_prompt", Mock(return_value="prompt"))+ monkeypatch.setattr(+ handler.LLMAPIHandlerFactory,+ "get_override_llm_api_handler",+ Mock(return_value=llm_handler),+ )++ scraped_page = SimpleNamespace(id_to_css_dict={"field-id": "[unique_id=field-id]"})+ scraped_page_after_open = SimpleNamespace(+ id_to_css_dict={+ "field-id": "[unique_id=field-id]",+ "option-x": "[unique_id=option-x]",+ },+ element_tree_trimmed=[+ {+ "id": "option-x",+ "tagName": "div",+ "attributes": {"role": "option"},+ "text": "Other Option",+ "interactable": True,+ }+ ],+ )+ task = SimpleNamespace(+ navigation_goal="goal", navigation_payload={}, llm_key=None, workflow_run_id=None, organization_id=None+ )+ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ result = await handler.select_from_emerging_elements(+ current_element_id="field-id",+ options=handler.CustomSelectPromptOptions(target_value="filter text"),+ page=MagicMock(),+ scraped_page=scraped_page,+ scraped_page_after_open=scraped_page_after_open,+ new_interactable_element_ids=["option-x"],+ step=SimpleNamespace(step_id="step-1"),+ task=task,+ )++ assert isinstance(result, handler.ActionSuccess)+ anchor_input.input_clear.assert_awaited_once()+ anchor_input.input_sequentially.assert_awaited_once_with("filter text")+++async def test_emerging_select_rejects_input_text_on_element_outside_anchor_and_new_ids(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock())+ llm_handler = AsyncMock(return_value={"id": "stranger-id", "value": "filter text", "action_type": "input_text"})+ monkeypatch.setattr(handler, "_is_verify_emerging_select_pick_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))+ monkeypatch.setattr(handler, "json_to_html", Mock(return_value="<div>Option</div>"))+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", AsyncMock(return_value=None))+ monkeypatch.setattr(handler.prompt_engine, "load_prompt", Mock(return_value="prompt"))+ monkeypatch.setattr(+ handler.LLMAPIHandlerFactory,+ "get_override_llm_api_handler",+ Mock(return_value=llm_handler),+ )++ scraped_page = SimpleNamespace(id_to_css_dict={"field-id": "[unique_id=field-id]"})+ scraped_page_after_open = SimpleNamespace(+ id_to_css_dict={+ "field-id": "[unique_id=field-id]",+ "option-x": "[unique_id=option-x]",+ },+ element_tree_trimmed=[+ {+ "id": "option-x",+ "tagName": "div",+ "attributes": {"role": "option"},+ "text": "Other Option",+ "interactable": True,+ }+ ],+ )+ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ with pytest.raises(handler.NoAvailableOptionFoundForCustomSelection):+ await handler.select_from_emerging_elements(+ current_element_id="field-id",+ options=handler.CustomSelectPromptOptions(target_value="filter text"),+ page=MagicMock(),+ scraped_page=scraped_page,+ scraped_page_after_open=scraped_page_after_open,+ new_interactable_element_ids=["option-x"],+ step=SimpleNamespace(step_id="step-1"),+ task=_shadow_task(),+ )++ dom_after_open.get_skyvern_element_by_id.assert_not_awaited()+++async def test_emerging_select_off_list_pick_still_proceeds_when_flag_disabled(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Flag off keeps today's behavior: an off-list pick is still acted on rather than rejected, so+ # merging this cannot change any org's outcomes until the flag is ramped.+ selected_element = MagicMock(+ get_tag_name=Mock(return_value="div"),+ get_attr=AsyncMock(return_value=None),+ scroll_into_view=AsyncMock(),+ click=AsyncMock(),+ )+ dom_after_open = MagicMock(get_skyvern_element_by_id=AsyncMock(return_value=selected_element))+ llm_handler = AsyncMock(return_value={"id": "stranger-id", "value": None, "action_type": "click"})+ monkeypatch.setattr(handler, "_is_verify_emerging_select_pick_enabled", AsyncMock(return_value=False))+ monkeypatch.setattr(handler, "DomUtil", Mock(return_value=dom_after_open))+ monkeypatch.setattr(handler, "json_to_html", Mock(return_value="<div>Option</div>"))+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", AsyncMock(return_value=None))+ monkeypatch.setattr(handler.prompt_engine, "load_prompt", Mock(return_value="prompt"))+ monkeypatch.setattr(+ handler.LLMAPIHandlerFactory,+ "get_override_llm_api_handler",+ Mock(return_value=llm_handler),+ )++ scraped_page = SimpleNamespace(id_to_css_dict={"field-id": "[unique_id=field-id]"})+ scraped_page_after_open = SimpleNamespace(+ id_to_css_dict={+ "field-id": "[unique_id=field-id]",+ "option-x": "[unique_id=option-x]",+ },+ element_tree_trimmed=[+ {+ "id": "option-x",+ "tagName": "div",+ "attributes": {"role": "option"},+ "text": "Other Option",+ "interactable": True,+ }+ ],+ )+ with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):+ with structlog.testing.capture_logs() as logs:+ result = await handler.select_from_emerging_elements(+ current_element_id="field-id",+ options=handler.CustomSelectPromptOptions(target_value="filter text"),+ page=MagicMock(),+ scraped_page=scraped_page,+ scraped_page_after_open=scraped_page_after_open,+ new_interactable_element_ids=["option-x"],+ step=SimpleNamespace(step_id="step-1"),+ task=_shadow_task(),+ )++ assert isinstance(result, handler.ActionSuccess)+ selected_element.click.assert_awaited()+ # Flag off still emits telemetry so the reject rate is measurable before ramping the flag on.+ off_list_warnings = [+ log for log in logs if log.get("log_level") == "warning" and log.get("element_id") == "stranger-id"+ ]+ assert off_list_warnings++@pytest.mark.asyncioasync def test_dropdown_select_call_path_forwards_committed_value_to_shadow_match(monkeypatch: pytest.MonkeyPatch,