# coding: utf-8 # Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. # Modifications Copyright 2026 ThinkFlowLab # SPDX-License-Identifier: Apache-2.0 """In-page policy probe: wait for the page to settle, then describe every visible control once. Called through ``BrowserAgentRuntime._evaluate_page_js`` as ``(params) => Promise``. The stamp attribute ``data-opens1a=`` is both the element's identity across ticks and the unique selector that PageState registers; a control keeps its number for as long as its node stays in the document. The probe reads the light DOM of the top document only: controls inside shadow roots or iframes are not listed, although an overlay hosting them can still appear as another control's ``blocked_by``. """ from __future__ import annotations STAMP_ATTRIBUTE = "data-opens1a" POLICY_PROBE_JS = r"""(params = {}) => new Promise((resolve) => { const ATTR = params.stamp_attribute || 'data-opens1a'; const after = params.after || null; const limits = { load: Number(params.load_timeout_ms || 3000), settle: Number(params.settle_ms || 500), quiet: Number(params.quiet_ms || 60), autocomplete: Number(params.autocomplete_ms || 900), items: Number(params.max_items || 250), text: Number(params.text_chars || 6000), allText: Boolean(params.all_text), // the whole document's text, not only the viewport's }; const t0 = performance.now(); let loadMs = 0; const nextId = () => (window.__ojwProbeSeq = (window.__ojwProbeSeq || 0) + 1); const byId = (id) => document.querySelector('[' + ATTR + '="' + id + '"]'); const stampCount = (id) => document.querySelectorAll('[' + ATTR + '="' + id + '"]').length; const SKIPPED_INPUT_TYPES = new Set(['password', 'file', 'hidden']); const ROLES = new Set(['button', 'link', 'checkbox', 'radio', 'switch', 'tab', 'menuitem', 'menuitemradio', 'option', 'gridcell', 'combobox', 'textbox', 'searchbox', 'spinbutton']); const INPUT_ROLES = { checkbox: 'checkbox', radio: 'radio', button: 'button', submit: 'button', reset: 'button', image: 'button', search: 'searchbox', number: 'spinbutton', text: 'textbox', email: 'textbox', url: 'textbox', tel: 'textbox', date: 'textbox', 'datetime-local': 'textbox', month: 'textbox', time: 'textbox', week: 'textbox', }; const EDITABLE_ROLES = new Set(['textbox', 'searchbox', 'spinbutton']); const CANDIDATES = 'a[href], button, input, textarea, select, summary, [contenteditable="true"], ' + [...ROLES].map((r) => '[role="' + r + '"]').join(', '); const acceptsInput = (e) => !SKIPPED_INPUT_TYPES.has(e.type); const rendered = (e) => e.checkVisibility({checkOpacity: true, checkVisibilityCSS: true}) && !e.closest('[aria-hidden="true"], [inert]'); const overlapsViewport = (r) => r.width > 0 && r.height > 0 && r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth; const centreInViewport = (r) => { const x = r.left + r.width / 2, y = r.top + r.height / 2; return r.width > 0 && r.height > 0 && x >= 0 && y >= 0 && x < innerWidth && y < innerHeight; }; const roleOf = (e) => { const declared = e.getAttribute('role'); if (ROLES.has(declared)) return declared; switch (e.tagName) { case 'BUTTON': case 'SUMMARY': return 'button'; case 'A': return 'link'; case 'SELECT': return 'combobox'; case 'TEXTAREA': return 'textbox'; case 'INPUT': return INPUT_ROLES[e.type] || null; default: return e.isContentEditable ? 'textbox' : null; } }; // Sites ship escaped markup as page text (Allrecipes renders a literal `` in its recipe cards' // fallback markup); concatenated into an accessible name it buries the words that identify the card behind a // URL. Drop tag-shaped runs, the unclosed trailing one a truncated name leaves included. const cleanName = (text) => String(text) .replace(/<[a-zA-Z/!][^>]*>/g, ' ') .replace(/<[a-zA-Z/!][^>]*$/, ' ') .replace(/\s+/g, ' ') .trim(); const accessibleName = (root) => { const visited = new Set(); const nameOf = (e) => { if (!e || visited.has(e)) return ''; visited.add(e); const fromIdRefs = (attr) => (e.getAttribute(attr) || '').split(/\s+/).filter(Boolean) .map((id) => nameOf(document.getElementById(id))).filter(Boolean).join(' '); const fromChildren = () => [...e.childNodes].map((n) => n.nodeType === Node.TEXT_NODE ? n.textContent : n.nodeType === Node.ELEMENT_NODE && n.getAttribute('aria-hidden') !== 'true' ? nameOf(n) : '').join(' '); const buttonInput = e.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes(e.type); const sources = [ () => fromIdRefs('aria-labelledby'), () => e.getAttribute('aria-label'), () => [...(e.labels || [])].map((l) => nameOf(l)).filter(Boolean).join(' '), () => (buttonInput ? e.value : ''), () => e.getAttribute('alt'), () => (e.tagName === 'INPUT' ? '' : fromChildren()), () => e.getAttribute('title'), () => e.getAttribute('placeholder'), ]; for (const source of sources) { const found = cleanName(source() || ''); if (found) return found; } return ''; }; return nameOf(root); }; const regionOf = (e) => { const dialog = e.closest('dialog, [role="dialog"], [role="alertdialog"]'); if (dialog) return 'dialog:' + (accessibleName(dialog) || 'unnamed').slice(0, 60); const list = e.closest('[role="menu"], [role="listbox"], [role="grid"]'); return list ? list.getAttribute('role') + ':' + accessibleName(list).slice(0, 60) : ''; }; const clickPoint = (r) => ({ // A click has to land inside the viewport; clamp the centre point to it so an element that is only // partly on-screen (its centre in-viewport check already passed) still hit-tests at a real spot. x: Math.max(0, Math.min(innerWidth - 1, r.left + r.width / 2)), y: Math.max(0, Math.min(innerHeight - 1, r.top + r.height / 2)), }); const ownLabel = (e) => (e.labels && e.labels[0]) || e.closest('label') || null; // What a real click at ``e``'s clickable point would actually hit. ``null`` means the point resolves to // ``e`` itself, a descendant (an icon inside a button), an ancestor (``e`` is the descendant), or ``e``'s // own associated ``