Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Persist run-end HAR encounters and page identity (SKY-18366) (#9024)
LawyZhenge6cfd4546847
diff --git a/skyvern/webeye/scraper/domUtils.js b/skyvern/webeye/scraper/domUtils.jsindex 3c97c9945..01faae2cd 100644--- a/skyvern/webeye/scraper/domUtils.js+++ b/skyvern/webeye/scraper/domUtils.js@@ -1895,27 +1895,38 @@ if (window.elementIdCounter === undefined) {window.elementIdCounter = new SafeCounter();}-// generate a unique id for the element-// length is 4, the first character is from the frame index, the last 3 characters are from the counter,+const UNIQUE_ID_CHARACTERS =+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+const UNIQUE_ID_COUNTER_LENGTH = 3;++// The frame index in base 62 that starts every id this window mints, or null while it has no frame index.+// Every window's counter starts at 1, so one character modulo 62 would give frame 62 the main frame's ids.+function uniqueIdFramePrefix() {+ const base = UNIQUE_ID_CHARACTERS.length;+ let frameIndex = window.GlobalSkyvernFrameIndex;+ if (frameIndex === undefined || frameIndex < 0) return null;+ let prefix = UNIQUE_ID_CHARACTERS[frameIndex % base];+ frameIndex = Math.floor(frameIndex / base);+ // The page can overwrite the global: Infinity would never floor to 0, so the loop stops past safe integers.+ while (Number.isSafeInteger(frameIndex) && frameIndex > 0) {+ prefix = UNIQUE_ID_CHARACTERS[frameIndex % base] + prefix;+ frameIndex = Math.floor(frameIndex / base);+ }+ return prefix;+}++// generate a unique id for the element: the frame prefix, then the last 3 characters from the counterasync function uniqueId() {- const characters =- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+ const characters = UNIQUE_ID_CHARACTERS;const base = characters.length;const extraCharacters = "~!@#$%^&*()-_+=";const extraBase = extraCharacters.length;- let result = "";-- if (- window.GlobalSkyvernFrameIndex === undefined ||- window.GlobalSkyvernFrameIndex < 0- ) {+ let result = uniqueIdFramePrefix();+ if (result === null) {const randomIndex = Math.floor(Math.random() * extraBase);- result += extraCharacters[randomIndex];- } else {- const c1 = window.GlobalSkyvernFrameIndex % base;- result += characters[c1];+ result = extraCharacters[randomIndex];}const countPart =@@ -1930,6 +1941,28 @@ async function uniqueId() {return result;}+// The shape of an id a frame below index 238,328 minted. Other values are left alone: the page's own, and the+// symbol-led ids a window mints while it has no frame index.+const MINTED_UNIQUE_ID = /^[A-Za-z0-9]{4,6}$/;++// A child document can hold copies of nodes another frame already tagged, so a minted id is kept only when+// this window minted it; a node the page moves between frames is given a new id once.+async function ownUniqueId(element) {+ const existing = element.getAttribute("unique_id");+ const prefix = uniqueIdFramePrefix();+ if (+ existing &&+ (prefix === null ||+ !MINTED_UNIQUE_ID.test(existing) ||+ existing.slice(0, -UNIQUE_ID_COUNTER_LENGTH) === prefix)+ ) {+ return existing;+ }+ const fresh = await uniqueId();+ element.setAttribute("unique_id", fresh);+ return fresh;+}+const ENRICHED_ELEMENT_TEXT_LIMIT = 120;function truncateEnrichedText(value) {@@ -2363,8 +2396,7 @@ async function buildElementObject(budget.remaining -= maxOptions;}}- var element_id = element.getAttribute("unique_id") ?? (await uniqueId());- element.setAttribute("unique_id", element_id);+ var element_id = await ownUniqueId(element);// Inputs can appear after the stamp pass while the asynchronous tree build runs.if (!element.hasAttribute("data-skyvern-otp-box") &&@@ -2509,13 +2541,7 @@ async function buildElementObject(let isInShadowRoot = element.getRootNode() instanceof ShadowRoot;if (isInShadowRoot) {let shadowHostEle = element.getRootNode().host;- let shadowHostId = shadowHostEle.getAttribute("unique_id");- // assign shadowHostId to the shadowHost element if it doesn't have unique_id- if (!shadowHostId) {- shadowHostId = await uniqueId();- shadowHostEle.setAttribute("unique_id", shadowHostId);- }- elementObj.shadowHost = shadowHostId;+ elementObj.shadowHost = await ownUniqueId(shadowHostEle);}// get options for select element or for listbox elementdiff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.pyindex c0b765561..225e31a21 100644--- a/skyvern/webeye/scraper/scraper.py+++ b/skyvern/webeye/scraper/scraper.py@@ -318,6 +318,9 @@ def build_element_dict(if previous_frame is not None and previous_frame != element["frame"]:cross_frame_collision_ids.add(element_id)colliding_frame_pairs.add((previous_frame, element["frame"]))+ # Frames arrive breadth-first, parents before children, so the first owner is the likelier target, and a+ # frame's copy of its own iframe cannot re-point that iframe into its subtree and loop the frame chain.+ continue# get_interactable_element_tree marks each interactable element with a SKYVERN_ID_ATTR attributeid_to_css_dict[element_id] = f"[{SKYVERN_ID_ATTR}='{element_id}']"id_to_element_dict[element_id] = element@@ -328,10 +331,10 @@ def build_element_dict(if cross_frame_collision_ids:iframe_collision_count = len(cross_frame_collision_ids & {element["frame"] for element in elements})- # Only an overwritten iframe entry can turn an element's frame chain into a loop.+ # A shared iframe id is the collision that can misroute an element's frame chain.log = LOG.warning if iframe_collision_count else LOG.infolog(- "Element ids collide across frames; the later frame's element replaces the earlier one",+ "Element ids collide across frames; the earlier frame's element is kept",collision_count=len(cross_frame_collision_ids),iframe_collision_count=iframe_collision_count,frame_pairs=sorted(colliding_frame_pairs)[:MAX_LOGGED_FRAME_COLLISION_PAIRS],diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.pyindex 69ed773a7..8ddbce752 100644--- a/skyvern/webeye/utils/dom.py+++ b/skyvern/webeye/utils/dom.py@@ -171,8 +171,8 @@ async def resolve_locator(iframe_path: list[str] = []while frame != "main.frame":- # Element ids are reused across frames, so a later frame's copy can overwrite an iframe's entry and- # point the chain back at itself. This loop never awaits, so a cycle would block the event loop.+ # A chain can still loop when an iframe element is missing from the scraped elements and a descendant+ # frame holds an element with that iframe's id. This loop never awaits, so a cycle would block the event loop.if frame in iframe_path or len(iframe_path) >= MAX_FRAME_CHAIN_DEPTH:LOG.warning("Frame chain of the scraped element loops or exceeds the depth cap",diff --git a/tests/unit/test_dom_scrape_crash_guards.js b/tests/unit/test_dom_scrape_crash_guards.jsindex 5bd35a6f4..d9d975219 100644--- a/tests/unit/test_dom_scrape_crash_guards.js+++ b/tests/unit/test_dom_scrape_crash_guards.js@@ -199,35 +199,47 @@ test("isElementVisible: display:contents parent containing an option does not ov// Exercise the actual serializer, including copied attributes and the live value property.(async () => {const vm = require("vm");- const context = {- window: { GlobalSkyvernFrameIndex: 0 },- ShadowRoot: global.ShadowRoot,- __captureDestinationFacts: false,- getPseudoContent: () => "",- getElementText: () => "",- enrichValidationState: () => {},- };- for (const name of [- "checkDisabledFromStyle",- "checkRequiredFromStyle",- "isHoverOnlyElement",- "isDatePickerSelector",- "isDivComboboxDropdown",- "isDropdownButton",- "isAngularDropdown",- "isAngularMaterialDatePicker",- "isSelect2Dropdown",- "isSelect2MultiChoice",- "isReadonlyInputDropdown",- ])- context[name] = () => false;- vm.createContext(context);const helper = src.includes("// BEGIN OTP INPUT PRIVACY")? src.split("// BEGIN OTP INPUT PRIVACY")[1].split("// END OTP INPUT PRIVACY")[0]: extract("isOtpInputValueSecret");- vm.runInContext(helper + "\nasync " + extract("buildElementObject"), context);+ const serializerContext = (window, overrides) => {+ const serializer = {+ window,+ ShadowRoot: global.ShadowRoot,+ __captureDestinationFacts: false,+ getPseudoContent: () => "",+ getElementText: () => "",+ enrichValidationState: () => {},+ ...overrides,+ };+ for (const name of [+ "checkDisabledFromStyle",+ "checkRequiredFromStyle",+ "isHoverOnlyElement",+ "isDatePickerSelector",+ "isDivComboboxDropdown",+ "isDropdownButton",+ "isAngularDropdown",+ "isAngularMaterialDatePicker",+ "isSelect2Dropdown",+ "isSelect2MultiChoice",+ "isReadonlyInputDropdown",+ ])+ serializer[name] = () => false;+ vm.createContext(serializer);+ vm.runInContext(+ helper + "\nasync " + extract("buildElementObject"),+ serializer,+ );+ return serializer;+ };+ // These fixtures name their nodes by id; the real id wiring is covered by the id checks below.+ const context = serializerContext(+ { GlobalSkyvernFrameIndex: 0 },+ { ownUniqueId: async (element) => element.getAttribute("unique_id") },+ );for (const [name, attributes, value, count, flagged, expected] of [["marked", { "data-skyvern-otp-box": "1" }, "7", 0, false, "*"],["unmarked alone", {}, "8", 0, false, "8"],@@ -647,6 +659,174 @@ test("isElementVisible: display:contents parent containing an option does not ov);});}+ // Each frame is its own window whose element counter starts at 1, as in a browser.+ const extractConst = (name) =>+ src.match(new RegExp(`^const ${name} =[^;]*;`, "m"))[0];+ const idCode = [+ extractConst("UNIQUE_ID_CHARACTERS"),+ extractConst("UNIQUE_ID_COUNTER_LENGTH"),+ extractConst("MINTED_UNIQUE_ID"),+ extract("uniqueIdFramePrefix"),+ "async " + extract("uniqueId"),+ "async " + extract("ownUniqueId"),+ ].join("\n");+ const idWindow = (frameIndex) => {+ const windowContext = {+ window: {+ GlobalSkyvernFrameIndex: frameIndex,+ elementIdCounter: {+ value: 0,+ async add() {+ return ++this.value;+ },+ },+ },+ };+ vm.createContext(windowContext);+ vm.runInContext(idCode, windowContext);+ return windowContext;+ };+ const tagged = (id) => ({+ _attributes: id ? { unique_id: id } : {},+ getAttribute(name) {+ return this._attributes[name] ?? null;+ },+ setAttribute(name, value) {+ this._attributes[name] = value;+ },+ });+ const ownIds = async (win, nodes) => {+ const ids = [];+ for (const node of nodes) ids.push(await win.ownUniqueId(node));+ return ids;+ };++ const frameIndexes = [0, 1, 61, 62, 63, 124, 3843, 3844];+ const idsByFrame = {};+ for (const frameIndex of frameIndexes) {+ const win = idWindow(frameIndex);+ idsByFrame[frameIndex] = await ownIds(+ win,+ Array.from({ length: 70 }, () => tagged()),+ );+ }+ test("uniqueId: frames 62 apart never share an element id", () => {+ const all = Object.values(idsByFrame).flat();+ assert(+ new Set(all).size === all.length,+ "two frames produced the same element id",+ );+ });+ test("uniqueId: frames below 62 keep their ids, and the prefix grows at 62 and 3844", () => {+ const firstIds = frameIndexes.map(+ (frameIndex) => idsByFrame[frameIndex][0],+ );+ const expected = [+ "AAAB",+ "BAAB",+ "9AAB",+ "BAAAB",+ "BBAAB",+ "CAAAB",+ "99AAB",+ "BAAAAB",+ ];+ assert(+ JSON.stringify(firstIds) === JSON.stringify(expected),+ `got ${firstIds}`,+ );+ });++ const parent = idWindow(0);+ const parentNodes = Array.from({ length: 5 }, () => tagged());+ const parentIds = await ownIds(parent, parentNodes);+ const child = idWindow(5);+ const copies = parentIds.map((id) => tagged(id));+ const childIds = await ownIds(child, copies);+ const childRescrape = await ownIds(child, copies);+ const parentRescrape = await ownIds(parent, parentNodes);+ test("ownUniqueId: a child frame's copy of tagged parent nodes gets the child's own ids", () => {+ assert(+ childIds.every((id) => id.startsWith("F") && id.length === 4),+ `child ids ${childIds} do not carry frame 5's prefix`,+ );+ assert(+ new Set([...parentIds, ...childIds]).size === 10,+ "a copy still shares an id with its original",+ );+ });+ test("ownUniqueId: re-scraping a window keeps every id it minted", () => {+ assert(+ JSON.stringify(childRescrape) === JSON.stringify(childIds) &&+ JSON.stringify(parentRescrape) === JSON.stringify(parentIds),+ "a re-scrape changed an id",+ );+ });+ const untracked = tagged("AAAB");+ await idWindow(undefined).ownUniqueId(untracked);+ const pageOwned = ["SEX_INPUT", "box-0", "unrelated"].map((id) => tagged(id));+ const pageOwnedIds = await ownIds(idWindow(0), pageOwned);+ test("ownUniqueId: ids it did not mint are kept, with no frame index or when the page set them", () => {+ assert(+ untracked.getAttribute("unique_id") === "AAAB",+ "a window without a frame index replaced an id",+ );+ assert(+ JSON.stringify(pageOwnedIds) ===+ JSON.stringify(["SEX_INPUT", "box-0", "unrelated"]),+ `page-set ids were replaced: ${pageOwnedIds}`,+ );+ });+ // The real serializer and id wiring in frame 5, whose DOM holds copies the main frame already tagged.+ const framedSerializer = serializerContext(+ {+ GlobalSkyvernFrameIndex: 5,+ elementIdCounter: {+ value: 0,+ async add() {+ return ++this.value;+ },+ },+ },+ {},+ );+ vm.runInContext(idCode, framedSerializer);+ const copiedNode = (id) => {+ const node = el({ tagName: "div", attributes: { unique_id: id } });+ node.attributes = [{ name: "unique_id", value: id }];+ node.setAttribute = (name, value) => {+ node._attributes[name] = value;+ };+ return node;+ };+ const copied = copiedNode("AAAC");+ const copiedHost = copiedNode("AAAD");+ const shadowChild = copiedNode("AAAE");+ const shadowRoot = new global.ShadowRoot();+ shadowRoot.host = copiedHost;+ shadowChild.getRootNode = () => shadowRoot;+ const copiedObject = await framedSerializer.buildElementObject(+ "AAAB",+ copied,+ true,+ );+ const shadowChildObject = await framedSerializer.buildElementObject(+ "AAAB",+ shadowChild,+ true,+ );+ test("buildElementObject: a copied node and a copied shadow host get this frame's ids", () => {+ assert(+ copiedObject.id.startsWith("F") &&+ copied.getAttribute("unique_id") === copiedObject.id,+ `copied node kept ${copiedObject.id}`,+ );+ assert(+ shadowChildObject.shadowHost.startsWith("F") &&+ copiedHost.getAttribute("unique_id") === shadowChildObject.shadowHost,+ `copied shadow host kept ${shadowChildObject.shadowHost}`,+ );+ });console.log(`\n${passed + failed} tests: ${passed} passed, ${failed} failed`);process.exit(failed > 0 ? 1 : 0);})().catch((error) => {diff --git a/tests/unit/test_iframe_e2e.py b/tests/unit/test_iframe_e2e.pyindex cbadd87d2..d5ab8f1d4 100644--- a/tests/unit/test_iframe_e2e.py+++ b/tests/unit/test_iframe_e2e.py@@ -18,7 +18,10 @@ import pytest_asynciofrom playwright.async_api import async_playwrightfrom skyvern.core.script_generations.skyvern_page_ai import SkyvernPageAi+from skyvern.forge.sdk.core import skyvern_context+from skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.library.skyvern_browser_page import SkyvernBrowserPage+from skyvern.webeye.scraper.scraper import get_interactable_element_treedef _has_playwright_browser() -> bool:@@ -198,6 +201,42 @@ class TestFrameListE2E:assert "empty" in names+_MAIN_FRAME_IDS_JS = "(nodes) => nodes.map((node) => node.getAttribute('unique_id'))"+++def _tree_ids(nodes: list[dict]) -> list[str]:+ return [id_ for node in nodes for id_ in [node.get("id"), *_tree_ids(node.get("children") or [])] if id_]+++class TestScrapedElementIdsE2E:+ @pytest.mark.asyncio+ async def test_a_frame_holding_copies_of_tagged_main_frame_nodes_gives_each_copy_its_own_id(+ self, browser_page: _TestPage+ ) -> None:+ page = browser_page.page+ with skyvern_context.scoped(SkyvernContext()):+ await get_interactable_element_tree(page)+ main_frame_ids = await page.eval_on_selector_all("[unique_id]", _MAIN_FRAME_IDS_JS)+ # The copies include an iframe element, the shape that used to loop the frame chain.+ await page.evaluate(+ """() => {+ const frameDocument = document.getElementById("payment-frame").contentDocument;+ for (const selector of ["#main-input", "#main-btn", "#empty-frame"]) {+ frameDocument.body.append(document.querySelector(selector).cloneNode(true));+ }+ }"""+ )+ await page.frame_locator("#payment-frame").frame_locator("#empty-frame").locator("p").wait_for()+ elements, element_tree, _ = await get_interactable_element_tree(page)++ element_ids = [element["id"] for element in elements]+ tree_ids = _tree_ids(element_tree)+ assert len(element_ids) == len(set(element_ids))+ assert len(tree_ids) == len(set(tree_ids))+ assert set(main_frame_ids) <= set(element_ids)+ assert await page.eval_on_selector_all("[unique_id]", _MAIN_FRAME_IDS_JS) == main_frame_ids++# ---------------------------------------------------------------------------# E2E: interactions INSIDE an iframe# ---------------------------------------------------------------------------diff --git a/tests/unit/test_stale_context_guards.py b/tests/unit/test_stale_context_guards.pyindex 45c217ab8..b5dbd48d8 100644--- a/tests/unit/test_stale_context_guards.py+++ b/tests/unit/test_stale_context_guards.py@@ -254,6 +254,14 @@ class _BoundedLookups(dict):return super().__getitem__(key)+def _frame_map(owning_frame_by_id: dict[str, str]) -> MagicMock:+ scraped_page = MagicMock()+ scraped_page.id_to_element_dict = _BoundedLookups(+ {element_id: {"id": element_id, "frame": frame} for element_id, frame in owning_frame_by_id.items()}+ )+ return scraped_page++def _scraped_frames(elements: list[tuple[str, str]]) -> MagicMock:"""(element id, owning frame) pairs in scrape order, merged by the same build_element_dict a scrape uses."""_, id_to_element_dict, _, _, _ = scraper_module.build_element_dict(@@ -264,8 +272,7 @@ def _scraped_frames(elements: list[tuple[str, str]]) -> MagicMock:return scraped_page-# A frame's document holds a copy of an already-tagged node whose id is an iframe's, so the later frame's-# copy replaces the iframe's entry and the chain points back into itself.+# A frame's document holds a copy of an already-tagged node whose id is an iframe's._SELF_LOOP = [("AAAB", "main.frame"), ("AAAB", "AAAB"), ("AAAC", "AAAB")]_TWO_FRAME_LOOP = [("AAAB", "main.frame"), ("AAAC", "AAAB"), ("AAAB", "AAAC"), ("AAAD", "AAAC")]_TOO_DEEP = [(f"F{depth}", f"F{depth - 1}" if depth else "main.frame") for depth in range(MAX_FRAME_CHAIN_DEPTH + 1)]@@ -282,14 +289,23 @@ async def test_resolve_locator_classifies_a_looping_frame_chain_as_missing_eleme) -> None:page = MagicMock()page.query_selector = AsyncMock(return_value=None)+ # Merged later-wins, so the copied iframe ids loop. A map can still loop when an iframe is missing from the+ # scraped elements, which is what the guard is for.with pytest.raises(FrameChainLoop) as raised:- await resolve_locator(_scraped_frames(elements), page, target_frame, "[unique_id='ZZZZ']")+ await resolve_locator(_frame_map(dict(elements)), page, target_frame, "[unique_id='ZZZZ']")# The action handler's known-failure branch catches MissingElement, which is what keeps the run alive.assert isinstance(raised.value, MissingElement)@pytest.mark.asyncio-async def test_resolve_locator_walks_a_nested_iframe_chain_from_the_outside_in() -> None:+ "elements",+ [[("AAAB", "main.frame"), ("AAAC", "AAAB"), ("AAAD", "AAAC")], _TWO_FRAME_LOOP],+ ids=["plain-chain", "inner-frame-holds-a-copy-of-the-outer-iframe"],+)+async def test_resolve_locator_walks_a_nested_iframe_chain_from_the_outside_in(+ elements: list[tuple[str, str]],+) -> None:inner = MagicMock()outer = MagicMock()outer.query_selector = AsyncMock(@@ -299,9 +315,7 @@ async def test_resolve_locator_walks_a_nested_iframe_chain_from_the_outside_in()page.query_selector = AsyncMock(side_effect=lambda selector: _frame_handler(outer) if selector == "[unique_id='AAAB']" else None)- scraped = _scraped_frames([("AAAB", "main.frame"), ("AAAC", "AAAB"), ("AAAD", "AAAC")])-- _, frame = await resolve_locator(scraped, page, "AAAC", "[unique_id='AAAD']")+ _, frame = await resolve_locator(_scraped_frames(elements), page, "AAAC", "[unique_id='AAAD']")assert frame is inner@@ -318,31 +332,28 @@ async def test_resolve_locator_walks_a_nested_iframe_chain_from_the_outside_in()0,("main.frame", "AAAB"),),- (- # Every element of frame AAAB is overwritten too, so no winning element still names it as its frame.- [("AAAB", "main.frame"), ("AAAC", "AAAB"), ("AAAB", "AAAD"), ("AAAC", "AAAD")],- "warning",- 2,- 1,- ("AAAB", "AAAD"),- ),],- ids=["iframe-id-overwritten", "plain-node-overwritten", "iframe-with-no-surviving-element"],+ ids=["iframe-id-shared", "plain-node-id-shared"],)-def test_build_element_dict_reports_cross_frame_id_collisions_without_changing_the_winner(+def test_build_element_dict_keeps_the_main_frame_element_when_a_later_frame_reuses_its_id(elements: list[tuple[str, str]],level: str,collision_count: int,iframe_collision_count: int,frame_pair: tuple[str, str],) -> None:+ scraped = [{"id": element_id, "frame": frame, "tagName": "div"} for element_id, frame in elements]with capture_logs() as logs:- _, id_to_element_dict, _, _, _ = scraper_module.build_element_dict(- [{"id": element_id, "frame": frame, "tagName": "div"} for element_id, frame in elements]- )-- later_frame_by_id = dict(elements)- assert {element_id: element["frame"] for element_id, element in id_to_element_dict.items()} == later_frame_by_id+ _, id_to_element_dict, id_to_frame_dict, id_to_element_hash, _ = scraper_module.build_element_dict(scraped)++ first_by_id: dict[str, dict] = {}+ for element in scraped:+ first_by_id.setdefault(element["id"], element)+ assert id_to_element_dict == first_by_id+ assert id_to_frame_dict == {element_id: element["frame"] for element_id, element in first_by_id.items()}+ assert id_to_element_hash == {+ element_id: scraper_module.hash_element(element) for element_id, element in first_by_id.items()+ }collisions = [log for log in logs if log["event"].startswith("Element ids collide across frames")]assert len(collisions) == 1assert collisions[0]["log_level"] == level