Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
RBAC v2 slice 6 part 1: detect the downgrade pause once (SKY-18910) (#9048)
Aaron Perezad49492afefb
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex 60fa6d8ad..3808c15d3 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -1693,6 +1693,20 @@ class InputToReadonlyElement(SkyvernException):)+class ScrollMadeNoProgress(SkyvernException):+ def __init__(self, element_id: str, direction: str, boundary: str | None = None):+ reason = (+ f" because the content is already scrolled to the {boundary}"+ if boundary+ else " and the content did not move"+ )+ super().__init__(+ f"Scrolling {direction} from element(id={element_id}) revealed no new content{reason}. "+ "Repeating this scroll will not change the page: work with the content already visible, "+ "scroll the other direction, or interact with a different element."+ )++class FailedToParseActionInstruction(SkyvernException):def __init__(self, reason: str | None, error_type: str | None):super().__init__(diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 8440b951f..b3a89e1a8 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -6272,8 +6272,8 @@ class ForgeAgent:# Skip sleep and post-action artifacts for page-level SCROLL to preserve# scroll-driven JS state. Many pages enable buttons only while scrolled to# bottom (e.g. T&C "Agree" buttons) and re-disable them after any delay or- # programmatic scroll. Sub-container scrolls (strategies 1 & 2) don't affect- # page position, so they keep normal sleep and artifact recording.+ # programmatic scroll. Sub-container scrolls don't affect page position, so they+ # keep normal sleep and artifact recording.is_page_level_scroll = action.action_type == ActionType.SCROLL and any(r.success and isinstance(r.data, dict) and r.data.get("page_level_scroll") for r in results)diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.pyindex 422732210..a030171b9 100644--- a/skyvern/forge/request_logging.py+++ b/skyvern/forge/request_logging.py@@ -204,13 +204,13 @@ def integration_platform_from_user_agent(user_agent: str | None) -> str | None:return Nonevalue = user_agent.casefold()- if "zapier" in value:+ if re.search(r"(?<![\w-])zapier(?![\w-])", value):return "zapier"- if "n8n" in value:+ if re.search(r"(?<![\w-])n8n(?![\w-])", value):return "n8n"if value.startswith("make/") or re.search(r"\bmake\.com\b", value) or "integromat" in value:return "make"- if "workato" in value:+ if re.search(r"(?<![\w-])workato(?![\w-])", value):return "workato"return "other"diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex cfc522637..a05059df0 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -17,7 +17,7 @@ from contextvars import ContextVarfrom datetime import UTC, datetime, timedelta, timezonefrom enum import StrEnumfrom pathlib import Path-from typing import Any, AsyncIterator, Awaitable, Callable, List, NamedTuple, TypedDict, TypeGuard, cast+from typing import Any, AsyncIterator, Awaitable, Callable, List, Literal, NamedTuple, TypedDict, TypeGuard, castimport structlogfrom cachetools import TTLCache@@ -35,7 +35,7 @@ from playwright.async_api import (Request,Response,)-from pydantic import BaseModel, field_validator+from pydantic import BaseModel, ConfigDict, Field, field_validatorfrom skyvern.config import settingsfrom skyvern.constants import (@@ -100,6 +100,7 @@ from skyvern.exceptions import (PhoneNumberInputCountryCodeMismatch,PhoneNumberInputMismatch,ScreenshotTargetClosed,+ ScrollMadeNoProgress,SecretInputMismatch,SkyvernException,SkyvernHTTPException,@@ -285,6 +286,7 @@ from skyvern.webeye.utils.dom import ()from skyvern.webeye.utils.flutter_semantics import FLUTTER_TEXT_FIELD_JS, FRAME_SETTLE_TIMEOUT_SECONDS, TWO_FRAMES_JSfrom skyvern.webeye.utils.page import (+ ElementScrollMetrics,SkyvernFrame,_all_page_frames,_blob_url_origin,@@ -11626,6 +11628,34 @@ async def handle_extract_action(return [ActionFailure(exception=Exception("No data extraction goal"))]+class ScrollContainerOutcome(BaseModel):+ """What ``scrollNearestScrollableContainer()`` in domUtils.js did.++ The metrics are absent for the "page" and "none" modes, where no container was scrolled.+ """++ model_config = ConfigDict(populate_by_name=True)++ mode: Literal["container", "page", "none"]+ scrolled: bool = False+ scroll_top: float | None = Field(default=None, alias="scrollTop")+ client_height: float | None = Field(default=None, alias="clientHeight")+ scroll_height: float | None = Field(default=None, alias="scrollHeight")++ def boundary(self, direction: str) -> str | None:+ """The end the content is pinned against, or None when it stalled somewhere in between."""+ if self.scroll_top is None or self.client_height is None or self.scroll_height is None:+ return None+ if direction == "up":+ return "top" if self.scroll_top <= 0 else None+ metrics = ElementScrollMetrics(+ scroll_top=self.scroll_top,+ client_height=self.client_height,+ scroll_height=self.scroll_height,+ )+ return "bottom" if metrics.at_bottom else None++@traced(name="skyvern.agent.action.scroll")async def handle_scroll_action(action: actions.ScrollAction,@@ -11639,18 +11669,20 @@ async def handle_scroll_action(if action.element_id:# Element-based scrolling from extract-action prompt. Uses# scrollNearestScrollableContainer() from domUtils.js which walks the DOM to find- # the nearest scrollable ancestor or sibling container relative to the element.- # Returns: truthy value if scrolled (true for sub-container, "page" for page-level),- # false if nothing was scrollable.+ # the nearest scrollable container relative to the element — the element itself, a+ # viewport inside it, an ancestor, or an ancestor's sibling — and reports whether+ # that container's scroll position actually moved.scroll_direction = "down" if action.scroll_y >= 0 else "up"- scroll_result = False+ scroll_result = ScrollContainerOutcome(mode="none")dom = DomUtil(scraped_page=scraped_page, page=page)skyvern_element = await dom.safe_get_skyvern_element_by_id(action.element_id)if skyvern_element:try:- scroll_result = await skyvern_element.locator.evaluate(- "(el, direction) => scrollNearestScrollableContainer(el, direction)",- scroll_direction,+ scroll_result = ScrollContainerOutcome.model_validate(+ await skyvern_element.locator.evaluate(+ "(el, direction) => scrollNearestScrollableContainer(el, direction)",+ scroll_direction,+ ))except Exception:LOG.warning(@@ -11661,7 +11693,28 @@ async def handle_scroll_action(else:LOG.warning("Could not resolve element for scroll action", element_id=action.element_id)- if scroll_result == "page":+ if scroll_result.mode == "container" and not scroll_result.scrolled:+ # The container was found but would not move, so the scrape after this action shows+ # the same content. Reporting success here is what let a run spend its whole runtime+ # re-scrolling an exhausted container; the planner needs to see that it is stuck.+ LOG.info(+ "Container scroll revealed no new content",+ element_id=action.element_id,+ direction=scroll_direction,+ scroll_top=scroll_result.scroll_top,+ )+ return [+ ActionFailure(+ ScrollMadeNoProgress(+ element_id=action.element_id,+ direction=scroll_direction,+ boundary=scroll_result.boundary(scroll_direction),+ ),+ stop_execution_on_failure=False,+ )+ ]++ if scroll_result.mode == "page":# No scrollable sub-container found, but the page itself is scrollable.# Use incremental mouse.wheel events at the center of the viewport to# simulate natural user scrolling. This fires native wheel/scroll events@@ -11681,8 +11734,13 @@ async def handle_scroll_action(# Dynamically compute iterations based on remaining scrollable distance# so we reach the bottom even on very long T&C pages.scroll_info = await page.evaluate(- "() => ({ scrollHeight: document.documentElement.scrollHeight,"- " scrollTop: window.pageYOffset, innerHeight: window.innerHeight })"+ "() => { let node = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2);"+ " while (node && node !== document.body && node !== document.documentElement) {"+ " const style = window.getComputedStyle(node);"+ " if ((style.overflowY === 'auto' || style.overflowY === 'scroll') && node.scrollHeight > node.clientHeight) break;"+ " node = node.parentElement; }"+ " return { scrollHeight: document.documentElement.scrollHeight, scrollTop: window.pageYOffset,"+ " innerHeight: window.innerHeight, centerScrollTop: node && node !== document.body && node !== document.documentElement ? node.scrollTop : null }; }")if scroll_direction == "down":remaining = scroll_info["scrollHeight"] - scroll_info["scrollTop"] - scroll_info["innerHeight"]@@ -11706,6 +11764,42 @@ async def handle_scroll_action(# Wait for page JS to process scroll events (e.g. enabling buttons)await page.wait_for_timeout(500)+ settled_scroll = await page.evaluate(+ "() => { let node = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2);"+ " while (node && node !== document.body && node !== document.documentElement) {"+ " const style = window.getComputedStyle(node);"+ " if ((style.overflowY === 'auto' || style.overflowY === 'scroll') && node.scrollHeight > node.clientHeight) break;"+ " node = node.parentElement; }"+ " return { scrollTop: window.pageYOffset,"+ " centerScrollTop: node && node !== document.body && node !== document.documentElement ? node.scrollTop : null }; }"+ )+ settled_scroll_top = settled_scroll["scrollTop"]+ center_container_moved = (+ scroll_info["centerScrollTop"] is not None+ and settled_scroll["centerScrollTop"] is not None+ and settled_scroll["centerScrollTop"] != scroll_info["centerScrollTop"]+ )+ if settled_scroll_top == scroll_info["scrollTop"] and not center_container_moved:+ LOG.info(+ "Page-level scroll revealed no new content",+ element_id=action.element_id,+ direction=scroll_direction,+ scroll_top=settled_scroll_top,+ )+ # A page that still had room but would not move is scroll-locked (an open modal+ # or dropdown), which is a different thing to tell the planner than "at the end".+ at_boundary = remaining <= 1+ return [+ ActionFailure(+ ScrollMadeNoProgress(+ element_id=action.element_id,+ direction=scroll_direction,+ boundary=("bottom" if scroll_direction == "down" else "top") if at_boundary else None,+ ),+ stop_execution_on_failure=False,+ )+ ]+# Record which element was just deliberately scrolled. The click handler# checks this to skip scroll_into_view() for the SAME element, which# would use element.scrollIntoView() to center it — undoing the@@ -11715,8 +11809,11 @@ async def handle_scroll_action("(id) => { window.__skyvernScrolledElementId = id; }",action.element_id,)+ if settled_scroll_top == scroll_info["scrollTop"]:+ # The center-point wheel was consumed by an overlay rather than the page.+ return [ActionSuccess(data={"container_scroll": True})]return [ActionSuccess(data={"page_level_scroll": True})]- elif scroll_result:+ elif scroll_result.mode == "container":# Sub-container was scrolled successfully. Record the element ID so# the click handler skips scroll_into_view() for this element — same# protection as page-level scrolls. Without this, element.scrollIntoView()@@ -11732,6 +11829,9 @@ async def handle_scroll_action("Could not find scrollable container near element, falling back to mouse wheel",element_id=action.element_id,)+ # No progress verdict on this path: the wheel lands wherever the cursor already is,+ # so an unrelated container under it can absorb the scroll and the window offset+ # alone cannot tell a real move from a no-op.await EventStrategyFactory.scroll_by(page, action.scroll_x, action.scroll_y)elif action.x and action.y:# Coordinate-based scrolling from CUA/UI-TARS agentsdiff --git a/skyvern/webeye/scraper/domUtils.js b/skyvern/webeye/scraper/domUtils.jsindex 01faae2cd..1d3e62a98 100644--- a/skyvern/webeye/scraper/domUtils.js+++ b/skyvern/webeye/scraper/domUtils.js@@ -3288,14 +3288,38 @@ function isWindowScrollable() {return true;}+const OPTION_LIST_ROLES = ["listbox", "menu", "combobox", "tree"];+const OPTION_LIST_SELECTOR = OPTION_LIST_ROLES.map(+ (role) => `[role="${role}"]`,+).join(",");+const OPTION_ITEM_SELECTOR = [+ '[role="option"]',+ '[role="menuitem"]',+ '[role="menuitemradio"]',+ '[role="menuitemcheckbox"]',+ '[role="treeitem"]',+].join(",");+// A scroll viewport sits a level or two under the control that owns it, so a shallow sweep finds+// it; the bounds keep getComputedStyle off every node of a large subtree.+const SCROLLABLE_DESCENDANT_MAX_DEPTH = 5;+const SCROLLABLE_DESCENDANT_MAX_NODES = 200;+// One option row of the previous viewport stays on screen, so consecutive scrapes overlap and the+// agent can tell the list moved rather than jumped.+const OPTION_LIST_STEP_RATIO = 0.85;+/*** Find the nearest scrollable container relative to the given element and scroll it.- * Three strategies in priority order:- * 1) Walk up from element to find a scrollable ancestor (element is inside container)- * 2) Walk up the DOM checking siblings at each level (element is beside container)- * 3) Fall back to page-level scrolling (for pages where the body itself scrolls,+ * Strategies in priority order:+ * 1) The element itself+ * 2) A scrollable descendant of an option list (a virtualized listbox clips its content+ * and delegates scrollTop to a viewport DIV inside it)+ * 3) Walk up from element to find a scrollable ancestor (element is inside container)+ * 4) Walk up the DOM checking siblings at each level (element is beside container)+ * 5) Fall back to page-level scrolling (for pages where the body itself scrolls,* e.g. T&C pages with no scrollable sub-container)- * Returns: true (sub-container scrolled), "page" (page-level scroll needed), or false (nothing scrollable).+ * Returns {mode, scrolled, scrollTop, clientHeight, scrollHeight}, where mode is "container"+ * (a sub-container was scrolled), "page" (the caller must scroll the page itself) or "none"+ * (nothing scrollable). `scrolled` reports whether the scroll position actually moved.*/function scrollNearestScrollableContainer(element, direction) {function isContainerScrollable(node) {@@ -3309,16 +3333,64 @@ function scrollNearestScrollableContainer(element, direction) {);}- // Strategy 1: walk up from element to find a scrollable ancestor- let target = element;- while (target && target !== document.documentElement) {- if (isContainerScrollable(target)) break;- target = target.parentElement;+ // Breadth-first so the outermost viewport inside `root` wins — for a virtualized list that is+ // the node owning scrollTop, not the sized inner spacer it holds.+ function findScrollableDescendant(root) {+ let frontier = Array.from(root.children || []);+ let visited = 0;+ for (+ let depth = 0;+ depth < SCROLLABLE_DESCENDANT_MAX_DEPTH && frontier.length;+ depth+++ ) {+ const next = [];+ for (const node of frontier) {+ if (visited++ >= SCROLLABLE_DESCENDANT_MAX_NODES) return null;+ if (isContainerScrollable(node)) return node;+ next.push(...Array.from(node.children || []));+ }+ frontier = next;+ }+ return null;+ }++ // Whether `node` presents a set of discrete options rather than prose.+ function isOptionList(node) {+ if (!node || !node.getAttribute) return false;+ const role = (node.getAttribute("role") || "").toLowerCase();+ if (OPTION_LIST_ROLES.includes(role)) return true;+ if (node.tagName && node.tagName.toLowerCase() === "select") return true;+ const item = node.querySelector && node.querySelector(OPTION_ITEM_SELECTOR);+ return Boolean(item && !item.closest(OPTION_LIST_SELECTOR));}- // Strategy 2: walk up the DOM checking siblings at each level- if (!target || target === document.documentElement) {- target = null;+ let target = isContainerScrollable(element) ? element : null;+ const optionListItem = element.closest(OPTION_ITEM_SELECTOR);+ let targetUsesOptionListPaging = Boolean(+ optionListItem && optionListItem.closest(OPTION_LIST_SELECTOR),+ );++ // Strategy 2: a scroll viewport inside a targeted option list. Other wrappers keep+ // the old ancestor-first behavior so an inner textarea cannot steal their scroll.+ if (!target && isOptionList(element)) {+ target = findScrollableDescendant(element);+ targetUsesOptionListPaging = target !== null;+ }++ // Strategy 3: walk up from element to find a scrollable ancestor+ if (!target) {+ let level = element.parentElement;+ while (level && level !== document.documentElement) {+ if (isContainerScrollable(level)) {+ target = level;+ break;+ }+ level = level.parentElement;+ }+ }++ // Strategy 4: walk up the DOM checking siblings at each level+ if (!target) {let level = element.parentElement;while (level && level !== document.documentElement && !target) {for (const child of level.children) {@@ -3333,25 +3405,40 @@ function scrollNearestScrollableContainer(element, direction) {// Scroll the sub-container if foundif (target) {- if (direction === "down") {- target.scrollTop = target.scrollHeight;+ const before = target.scrollTop;+ let destination;+ if (isOptionList(target) || targetUsesOptionListPaging) {+ // A virtualized option list renders only the rows in view, so jumping to an extreme+ // skips every option in between and a mid-list option can never be reached. Advance+ // one viewport per call instead.+ const stepPx = Math.max(+ 1,+ Math.floor(target.clientHeight * OPTION_LIST_STEP_RATIO),+ );+ destination = direction === "down" ? before + stepPx : before - stepPx;+ } else if (direction === "down") {+ destination = target.scrollHeight;} else {- target.scrollTop = 0;+ destination = 0;}- return true;+ target.scrollTo({ top: destination, behavior: "instant" });+ return {+ mode: "container",+ // Re-reading the clamped position tells us whether anything moved rather than whether we asked.+ scrolled: target.scrollTop !== before,+ scrollTop: target.scrollTop,+ clientHeight: target.clientHeight,+ scrollHeight: target.scrollHeight,+ };}- // Strategy 3: fall back to page-level scrolling when no sub-container exists.+ // Strategy 5: fall back to page-level scrolling when no sub-container exists.// Many pages (e.g. T&C agreements) render content inline with the page body- // as the only scrollable area. Return "page" to signal the Python handler to+ // as the only scrollable area. Report "page" to signal the Python handler to// use mouse.wheel events for native browser scrolling, which reliably triggers// page JavaScript (IntersectionObserver, scroll listeners) that programmatic// scrollTo/scrollTop methods may not.- if (isWindowScrollable()) {- return "page";- }-- return false;+ return { mode: isWindowScrollable() ? "page" : "none", scrolled: false };}function scrollToElementBottom(element, page_by_page = false) {diff --git a/tests/unit/test_browser_effect_sink_enumeration.py b/tests/unit/test_browser_effect_sink_enumeration.pyindex c75ceb483..2cdc6ec76 100644--- a/tests/unit/test_browser_effect_sink_enumeration.py+++ b/tests/unit/test_browser_effect_sink_enumeration.py@@ -27,8 +27,8 @@ _DISCOVERED_BROWSER_API_CALLS = {# 6 = 5 prior + the bounded v4 FileDownloadBlock synchronous popup close (SKY-15371)."close": 6,"dblclick": 2,- # 18 = 16 prior + the read-only Flutter text-field probe and two-frame wait around a credential write.- "evaluate": 18,+ # 19 = 18 prior + the read-only window offset read behind the page-level scroll progress check.+ "evaluate": 19,"fill": 2,# 5 = 4 prior + the focus that lets a Flutter text field start editing before a credential write."focus": 5,@@ -138,7 +138,9 @@ _EVALUATE_CALLERS = {"_normal_select_readback_contradicts": 1,"_probe_tel_browser_validity": 1,"handle_click_action": 2,- "handle_scroll_action": 4,+ # 5 = 4 prior + the read-only window offset read that decides whether a page-level+ # scroll revealed anything (SKY-18891)+ "handle_scroll_action": 5,}),"skyvern/webeye/dom_inspection.py": Counter(@@ -273,21 +275,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()) == 217+ assert sum(sum(methods.values()) for methods in observed.values()) == 218handler_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_CANDIDATESassert sum(_NON_BROWSER_CANDIDATES.values()) == 7- assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 210+ assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 211def 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()) == 46+ assert sum(sum(callers.values()) for callers in observed.values()) == 47def test_every_cdp_dispatch_is_classified_by_exact_command() -> None:diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.pyindex d4d8696d7..181a590c2 100644--- a/tests/unit/test_request_logging.py+++ b/tests/unit/test_request_logging.py@@ -79,11 +79,19 @@ class TestClientIpFromHeaders:("user_agent", "expected"),[("Zapier", "zapier"),+ ("zApIeR/1.0", "zapier"),+ ("curl/8.0 (Zapier/1.0)", "zapier"),+ ("zapier-evil", "other"),("n8n", "n8n"),+ ("N8N/1.0", "n8n"),+ ("not-n8n", "other"),+ ("curl/8.0 build-xn8nq", "other"),("make.com", "make"),("Make/production", "make"),("Integromat", "make"),("Workato", "workato"),+ ("wOrKaTo/1.0", "workato"),+ ("not-workato", "other"),("Mozilla/5.0", "other"),("Power Automate", "other"),("Pipedream", "other"),diff --git a/tests/unit/test_scroll_action_progress.py b/tests/unit/test_scroll_action_progress.pynew file mode 100644index 000000000..3da3f9a06--- /dev/null+++ b/tests/unit/test_scroll_action_progress.py@@ -0,0 +1,348 @@+"""SCROLL action progress against a real DOM (SKY-18891).++``handle_scroll_action`` drives ``scrollNearestScrollableContainer`` from domUtils.js, so these+tests run the real JS in a real Chromium page: a fake DOM cannot reproduce ``scrollTop`` clamping,+``overflow`` resolution, or a virtualized list's re-render on scroll, which is exactly where the+reported bug lived.++Covered contracts:+ * an open virtualized dropdown whose scroll viewport is a DESCENDANT of the targeted listbox+ scrolls that viewport, not the page behind it;+ * the list advances roughly one viewport per action, so a mid-list option stays reachable+ instead of being skipped by a jump to the first/last row;+ * a scroll that moves nothing reports failure, so the planner stops repeating it;+ * scrolls on wrappers do not get stolen by nested textareas;+ * prose containers with embedded controls still reach their bottom in one smooth-scroll action;+ * page-level wheel fallback recognizes when a center-point overlay consumed the wheel.+"""++from __future__ import annotations++import contextlib+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any+from unittest.mock import MagicMock, patch++import pytest+from playwright.async_api import Page, async_playwright++from skyvern.webeye.actions import handler+from skyvern.webeye.actions.actions import ScrollAction+from skyvern.webeye.actions.responses import ActionResult+from skyvern.webeye.utils.dom import SkyvernElement+from skyvern.webeye.utils.page import JS_FUNCTION_DEFS+++def _has_playwright_browser() -> bool:+ try:+ from playwright.sync_api import sync_playwright # noqa: PLC0415++ with sync_playwright() as playwright:+ return Path(playwright.chromium.executable_path).exists()+ except Exception:+ return False+++_skip_no_browser = pytest.mark.skipif(+ not _has_playwright_browser(),+ reason="Requires Playwright browsers installed (run: playwright install chromium)",+)++# "United States" sits deep in the list, like the country dropdown in the report: a jump to either+# extreme lands on "Afghanistan" or "Zimbabwe" and never shows it.+_COUNTRIES = (+ ["Afghanistan", "Albania", "Algeria", "American Samoa"]+ + [f"Country {index:03d}" for index in range(220)]+ + ["United States", "Uruguay", "Uzbekistan", "Vanuatu", "Vietnam", "Yemen", "Zambia", "Zimbabwe"]+)+_ROW_HEIGHT = 30+_VIEWPORT_ROWS = 7++# A virtualized listbox: the targeted role=listbox clips its content, and the element that actually+# owns scrollTop is the viewport DIV inside it. Only the rows in view are rendered, so scrolling+# past them loses the options in between. The tall filler below keeps the page itself scrollable,+# which is what the old code wheeled instead of the list.+_DROPDOWN_HTML = f"""+<html><body style="margin:0">+ <div id="country-listbox" role="listbox" aria-label="Country"+ style="overflow:hidden;height:{_ROW_HEIGHT * _VIEWPORT_ROWS}px;width:300px">+ <div id="viewport" style="overflow-y:auto;height:100%;position:relative">+ <div id="spacer" style="height:{_ROW_HEIGHT * len(_COUNTRIES)}px;position:relative"></div>+ </div>+ </div>+ <div style="height:4000px">filler</div>+ <script>+ const COUNTRIES = {_COUNTRIES!r};+ const ROW_HEIGHT = {_ROW_HEIGHT};+ const viewport = document.getElementById("viewport");+ const spacer = document.getElementById("spacer");+ function render() {{+ const first = Math.floor(viewport.scrollTop / ROW_HEIGHT);+ const last = Math.min(COUNTRIES.length, first + {_VIEWPORT_ROWS} + 1);+ spacer.replaceChildren();+ for (let index = first; index < last; index++) {{+ const row = document.createElement("div");+ row.id = "option-" + index;+ row.setAttribute("role", "option");+ row.style.cssText =+ "position:absolute;height:" + ROW_HEIGHT + "px;top:" + index * ROW_HEIGHT + "px";+ row.textContent = COUNTRIES[index];+ spacer.appendChild(row);+ }}+ }}+ viewport.addEventListener("scroll", render);+ render();+ </script>+</body></html>+""".replace("'", '"')++# A terms & conditions box: prose in a scrollable container, no option semantics anywhere. One+# SCROLL must still take it all the way to the bottom, which is what enables the accept button.+_TERMS_HTML = """+<html><body style="margin:0">+ <div id="terms" style="overflow-y:auto;scroll-behavior:smooth;height:200px;width:400px">+ <p style="height:3000px">Terms and conditions.</p>+ <select><option>English</option></select>+ <div role="menu"><button role="menuitem">Language</button></div>+ </div>+ <button id="accept" disabled>Accept</button>+</body></html>+"""++_CLOSED_OPTION_CONTROLS_MODAL_HTML = """+<html><body style="margin:0">+ <div id="modal" style="overflow-y:auto;height:200px;width:400px">+ <select id="native-select"><option>English</option></select>+ <div id="combobox" role="combobox" aria-expanded="false">Choose an option</div>+ <div style="height:3000px">Modal content</div>+ </div>+</body></html>+"""++_TEXTAREA_PANEL_HTML = """+<html><body style="margin:0">+ <div id="panel" style="overflow-y:auto;height:200px;width:400px">+ <div style="height:30px">Panel content</div>+ <div id="wrapper"><textarea id="inner" style="overflow-y:auto;height:80px;width:350px"></textarea></div>+ <div style="height:2000px">More panel content</div>+ </div>+ <div style="height:1000px">Page filler</div>+</body></html>+"""++# Terms rendered inline with the page body as the only scrollable area — the case the page-level+# wheel fallback exists for, since no sub-container is scrollable near the button.+_INLINE_TERMS_HTML = """+<html><body style="margin:0">+ <p style="height:4000px">Terms and conditions.</p>+ <button id="accept" disabled>Accept</button>+</body></html>+"""++# The center-point wheel can hit a nested portal overlay outside the target element's subtree.+_CENTER_OVERLAY_HTML = """+<html><body style="margin:0">+ <p style="height:4000px">Terms and conditions.</p>+ <button id="accept" disabled>Accept</button>+ <div style="position:fixed;left:400px;top:200px;z-index:10">+ <div id="overlay-panel" style="overflow-y:auto;height:400px;width:480px;background:white">+ <div style="height:10000px">Overlay content</div>+ </div>+ </div>+</body></html>+"""+++async def _fixture_page(html: str) -> AsyncIterator[Page]:+ async with async_playwright() as pw:+ browser = await pw.chromium.launch(headless=True, args=["--use-mock-keychain", "--password-store=basic"])+ try:+ context = await browser.new_context(viewport={"width": 1280, "height": 800})+ page = await context.new_page()+ await page.set_content(html)+ # handle_scroll_action evaluates scrollNearestScrollableContainer as a page global, so+ # the page needs the same domUtils bundle the scraper injects in production.+ await page.evaluate(JS_FUNCTION_DEFS)+ yield page+ finally:+ await browser.close()+++async def _scroll(page: Page, css: str, direction: str = "down") -> list[ActionResult]:+ """Run the real handler, stubbing only the element-id -> locator lookup."""++ element_id = css.lstrip("#")+ static: dict[str, Any] = {"id": element_id, "tagName": "div", "attributes": {}}++ class _StubDom:+ async def safe_get_skyvern_element_by_id(self, _: str) -> SkyvernElement:+ return SkyvernElement(page.locator(css), page, static)++ action = ScrollAction(element_id=element_id, scroll_x=0, scroll_y=500 if direction == "down" else -500)+ with patch.object(handler, "DomUtil", lambda **_: _StubDom()):+ return await handler.handle_scroll_action(+ action=action,+ page=page,+ scraped_page=MagicMock(),+ task=MagicMock(),+ step=MagicMock(),+ )+++async def _visible_options(page: Page) -> list[str]:+ # The fixture re-renders its rows from the scroll event, which fires a frame after scrollTop+ # changes, so wait until the rendered rows match the current scroll position before reading.+ await page.wait_for_function(+ "() => { const viewport = document.getElementById('viewport');"+ " const first = document.querySelector('#spacer [role=option]');"+ f" return !!first && first.offsetTop === Math.floor(viewport.scrollTop / {_ROW_HEIGHT}) * {_ROW_HEIGHT}; }}"+ )+ return await page.evaluate(+ "() => Array.from(document.querySelectorAll('#spacer [role=option]')).map((row) => row.textContent)"+ )+++@_skip_no_browser+async def test_virtualized_dropdown_scrolls_the_list_not_the_page() -> None:+ async with _fixture_page(_DROPDOWN_HTML) as page:+ before = await _visible_options(page)+ assert before[0] == "Afghanistan"++ results = await _scroll(page, "#country-listbox")++ assert results[-1].success, results+ after = await _visible_options(page)+ assert after != before, "the open dropdown did not scroll at all"+ assert after[0] != _COUNTRIES[-_VIEWPORT_ROWS], f"scroll jumped to the end of the list: {after}"+ assert await page.evaluate("() => window.scrollY") == 0, "the page scrolled instead of the list"+++@_skip_no_browser+async def test_virtualized_dropdown_scroll_from_option_row_does_not_jump_to_end() -> None:+ async with _fixture_page(_DROPDOWN_HTML) as page:+ results = await _scroll(page, "#option-0")++ assert results[-1].success, results+ scroll_top, max_scroll = await page.locator("#viewport").evaluate(+ "el => [el.scrollTop, el.scrollHeight - el.clientHeight]"+ )+ assert 0 < scroll_top < max_scroll, "scrolling from an option row jumped to the end"+++@_skip_no_browser+async def test_virtualized_dropdown_walks_to_a_mid_list_option_without_skipping() -> None:+ async with _fixture_page(_DROPDOWN_HTML) as page:+ target_index = _COUNTRIES.index("United States")+ # Generous: the contract under test is that the walk terminates and shows everything on+ # the way, not the exact step size.+ max_scrolls = len(_COUNTRIES)+ seen: set[str] = set()++ for _ in range(max_scrolls):+ options = await _visible_options(page)+ seen.update(options)+ if "United States" in options:+ break+ results = await _scroll(page, "#country-listbox")+ assert results[-1].success, results+ else:+ pytest.fail(f"never reached index {target_index} in {max_scrolls} scrolls")++ # The reported bug was a scroll that skipped the options in between, so the agent could+ # never read them. Every option above the target must have been on screen on the way down.+ assert set(_COUNTRIES[:target_index]) <= seen+++@_skip_no_browser+async def test_scroll_at_the_end_of_the_list_reports_failure() -> None:+ async with _fixture_page(_DROPDOWN_HTML) as page:+ await page.evaluate("() => { const v = document.getElementById('viewport'); v.scrollTop = v.scrollHeight; }")+ pinned = await _visible_options(page)++ results = await _scroll(page, "#country-listbox")++ assert not results[-1].success, "a scroll that revealed nothing reported success"+ assert "revealed no new content" in (results[-1].exception_message or "")+ assert results[-1].stop_execution_on_failure is False+ assert await _visible_options(page) == pinned+++@_skip_no_browser+async def test_page_level_scroll_reports_progress_then_failure_at_the_bottom() -> None:+ async with _fixture_page(_INLINE_TERMS_HTML) as page:+ first = await _scroll(page, "#accept")++ assert first[-1].success, first+ settled = await page.evaluate("() => window.scrollY")+ assert settled > 0, "the page-level fallback did not scroll the page"++ repeat = await _scroll(page, "#accept")++ assert not repeat[-1].success, "a page-level scroll that moved nothing reported success"+ assert "revealed no new content" in (repeat[-1].exception_message or "")+ assert await page.evaluate("() => window.scrollY") == settled+++@_skip_no_browser+async def test_prose_container_still_reaches_its_bottom_in_one_action() -> None:+ async with _fixture_page(_TERMS_HTML) as page:+ results = await _scroll(page, "#terms")++ assert results[-1].success, results+ assert await page.evaluate(+ "() => { const t = document.getElementById('terms');"+ " return t.scrollTop + t.clientHeight >= t.scrollHeight - 1; }"+ ), "the terms box did not reach its bottom"+++@_skip_no_browser[email protected]("css", ["#native-select", "#combobox"])+async def test_closed_option_control_scrolls_ancestor_modal_to_bottom(css: str) -> None:+ async with _fixture_page(_CLOSED_OPTION_CONTROLS_MODAL_HTML) as page:+ results = await _scroll(page, css)++ assert results[-1].success, results+ assert await page.locator("#modal").evaluate("el => el.scrollTop + el.clientHeight >= el.scrollHeight - 1"), (+ "the modal did not reach its bottom"+ )+++@_skip_no_browser+async def test_wrapper_scrolls_its_panel_not_a_nested_textarea() -> None:+ async with _fixture_page(_TEXTAREA_PANEL_HTML) as page:+ await page.locator("#inner").fill("\n".join(f"line {index}" for index in range(100)))+ await page.evaluate(+ "() => { document.getElementById('inner').scrollTop = 0; document.getElementById('panel').scrollTop = 0; }"+ )+ assert await page.locator("#inner").evaluate("el => el.scrollHeight > el.clientHeight")++ results = await _scroll(page, "#wrapper")++ assert results[-1].success, results+ assert await page.locator("#panel").evaluate("el => el.scrollTop + el.clientHeight >= el.scrollHeight - 1"), (+ "the panel did not scroll to its bottom"+ )+ assert await page.locator("#inner").evaluate("el => el.scrollTop") == 0+++@_skip_no_browser+async def test_page_level_wheel_recognizes_progress_in_center_overlay() -> None:+ async with _fixture_page(_CENTER_OVERLAY_HTML) as page:+ results = await _scroll(page, "#accept")++ assert results[-1].success, results+ assert await page.evaluate("() => window.scrollY") == 0+ assert await page.locator("#overlay-panel").evaluate("el => el.scrollTop") > 0+ assert results[-1].data == {"container_scroll": True}+ assert await page.evaluate("() => window.__skyvernScrolledElementId") == "accept"