cdp-page-scanner.ts 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  1. import type { InteractiveElement } from './browser-core-contracts.js';
  2. import { buildSemanticPageTree, type SemanticPageTree } from './browser-semantic-tree.js';
  3. import type { BrowserTransport } from './browser-transport.js';
  4. import {
  5. BROWSER_TIMEOUTS,
  6. isBrowserOperationInterruption,
  7. throwIfAborted,
  8. withTimeout,
  9. } from './operation-timeout.js';
  10. import {
  11. CONTAINER_TAGS,
  12. INTERACTIVE_ROLES,
  13. INTERACTIVE_TAGS,
  14. REQUIRED_COMPUTED_STYLES,
  15. SKIP_TAGS,
  16. SVG_ELEMENTS,
  17. type AXNode,
  18. type DOMNode,
  19. type DOMSnapshotResult,
  20. type SnapshotNode,
  21. } from './cdp-helper-contracts.js';
  22. export const DEFAULT_VIEWPORT = { width: 800, height: 600 };
  23. type ScannerCommand = (
  24. method: string,
  25. params?: Record<string, unknown>,
  26. timeoutMs?: number,
  27. signal?: AbortSignal,
  28. ) => Promise<unknown>;
  29. type JavaScriptFallbackElement = Omit<InteractiveElement, 'backendNodeId'> & {
  30. readonly backendNodeId?: number;
  31. };
  32. const browserInputDiagnosticLogger = {
  33. info(fields: Record<string, unknown>): void {
  34. if (process.env.MAVIS_BROWSER_DEBUG === '1') console.info(fields);
  35. },
  36. };
  37. function rethrowBrowserInterruption(error: unknown): void {
  38. if (isBrowserOperationInterruption(error)) throw error;
  39. }
  40. /**
  41. * Mature DOMSnapshot + DOM + AX + Runtime-listener page understanding.
  42. *
  43. * CDPHelper owns transport lifecycle and input primitives. This collaborator
  44. * owns only the page scan and semantic fusion algorithm so every provider uses
  45. * the same implementation without growing CDPHelper beyond the source-size gate.
  46. */
  47. export class CDPPageScanner {
  48. private lastSemanticPageTree: SemanticPageTree | null = null;
  49. constructor(
  50. private readonly transport: BrowserTransport,
  51. private readonly ensurePageAttached: (signal?: AbortSignal) => Promise<boolean>,
  52. private readonly command: ScannerCommand,
  53. ) {}
  54. reset(): void {
  55. this.lastSemanticPageTree = null;
  56. }
  57. getLastSemanticPageTree(): SemanticPageTree | null {
  58. return this.lastSemanticPageTree;
  59. }
  60. private buildSemanticPageTreeSafely(
  61. input: Parameters<typeof buildSemanticPageTree>[0],
  62. ): SemanticPageTree | null {
  63. if (process.env.MAVIS_BROWSER_SEMANTIC_TREE_V1 === '0') return null;
  64. try {
  65. return buildSemanticPageTree(input);
  66. } catch (error) {
  67. console.warn('Failed to build browser semantic tree; keeping legacy ElementMap:', error);
  68. return null;
  69. }
  70. }
  71. private ensureAttached(signal?: AbortSignal): Promise<boolean> {
  72. return this.ensurePageAttached(signal);
  73. }
  74. private sendCommand(
  75. method: string,
  76. params?: Record<string, unknown>,
  77. timeoutMs = BROWSER_TIMEOUTS.cdpCommand,
  78. signal?: AbortSignal,
  79. ): Promise<unknown> {
  80. return this.command(method, params, timeoutMs, signal);
  81. }
  82. private async resolveJavaScriptFallbackElements(
  83. elements: readonly JavaScriptFallbackElement[],
  84. signal: AbortSignal,
  85. ): Promise<InteractiveElement[]> {
  86. if (elements.length === 0) return [];
  87. const document = (await this.sendCommand(
  88. 'DOM.getDocument',
  89. { depth: 0, pierce: true },
  90. BROWSER_TIMEOUTS.cdpCommand,
  91. signal,
  92. )) as { root?: { nodeId?: number } };
  93. const rootNodeId = document.root?.nodeId;
  94. if (!rootNodeId) return [];
  95. const resolved: InteractiveElement[] = [];
  96. for (const element of elements) {
  97. if (Number.isFinite(element.backendNodeId) && Number(element.backendNodeId) > 0) {
  98. resolved.push(element as InteractiveElement);
  99. continue;
  100. }
  101. if (!element.selector) continue;
  102. try {
  103. const match = (await this.sendCommand(
  104. 'DOM.querySelectorAll',
  105. { nodeId: rootNodeId, selector: element.selector },
  106. BROWSER_TIMEOUTS.cdpCommand,
  107. signal,
  108. )) as { nodeIds?: number[] };
  109. if (match.nodeIds?.length !== 1) continue;
  110. const [nodeId] = match.nodeIds;
  111. if (!nodeId) continue;
  112. const description = (await this.sendCommand(
  113. 'DOM.describeNode',
  114. { nodeId },
  115. BROWSER_TIMEOUTS.cdpCommand,
  116. signal,
  117. )) as { node?: { backendNodeId?: number } };
  118. const backendNodeId = description.node?.backendNodeId;
  119. if (!backendNodeId) continue;
  120. resolved.push({ ...element, backendNodeId });
  121. } catch (error) {
  122. rethrowBrowserInterruption(error);
  123. }
  124. }
  125. return resolved;
  126. }
  127. async scan(signal: AbortSignal): Promise<InteractiveElement[]> {
  128. throwIfAborted(signal);
  129. const startedAt = Date.now();
  130. const logPhase = (phase: string, extra: Record<string, unknown> = {}) => {
  131. browserInputDiagnosticLogger.info({
  132. msg: '[EmbeddedBrowserOperation] cdp-scan-phase',
  133. phase,
  134. browserSessionId: this.transport.sessionId,
  135. durationMs: Date.now() - startedAt,
  136. ...extra,
  137. });
  138. };
  139. // Try to connect CDP; return silently on failure.
  140. logPhase('start');
  141. const attached = await this.ensureAttached(signal).catch((error) => {
  142. rethrowBrowserInterruption(error);
  143. return false;
  144. });
  145. if (!attached) return [];
  146. logPhase('attached');
  147. try {
  148. // Enable required CDP domains.
  149. await Promise.all([
  150. this.sendCommand('DOM.enable', undefined, BROWSER_TIMEOUTS.cdpCommand, signal).catch(
  151. (error) => {
  152. rethrowBrowserInterruption(error);
  153. },
  154. ),
  155. this.sendCommand(
  156. 'DOMSnapshot.enable',
  157. undefined,
  158. BROWSER_TIMEOUTS.cdpCommand,
  159. signal,
  160. ).catch((error) => {
  161. rethrowBrowserInterruption(error);
  162. }),
  163. this.sendCommand(
  164. 'Accessibility.enable',
  165. undefined,
  166. BROWSER_TIMEOUTS.cdpCommand,
  167. signal,
  168. ).catch((error) => {
  169. rethrowBrowserInterruption(error);
  170. }),
  171. this.sendCommand('Page.enable', undefined, BROWSER_TIMEOUTS.cdpCommand, signal).catch(
  172. (error) => {
  173. rethrowBrowserInterruption(error);
  174. },
  175. ),
  176. ]);
  177. throwIfAborted(signal);
  178. logPhase('domains-enabled');
  179. // 1. Fetch the three data sources and detect JS event listeners in parallel.
  180. const [
  181. snapshotResult,
  182. domTreeResult,
  183. axTreeResult,
  184. jsListenerBackendIds,
  185. viewportInfo,
  186. snapshotToCssScale,
  187. ] = await Promise.all([
  188. // DOMSnapshot.captureSnapshot: Fetch layout information and computed styles.
  189. this.captureSnapshot(signal).catch((e) => {
  190. rethrowBrowserInterruption(e);
  191. console.warn('Failed to capture snapshot:', e);
  192. return null;
  193. }),
  194. // DOM.getDocument: Fetch the full DOM tree.
  195. this.sendCommand(
  196. 'DOM.getDocument',
  197. { depth: -1, pierce: true },
  198. BROWSER_TIMEOUTS.cdpCommand,
  199. signal,
  200. ).catch((e) => {
  201. rethrowBrowserInterruption(e);
  202. console.warn('Failed to get DOM document:', e);
  203. return null;
  204. }) as Promise<{ root: DOMNode } | null>,
  205. // Accessibility.getFullAXTree: Fetch the accessibility tree.
  206. this.sendCommand(
  207. 'Accessibility.getFullAXTree',
  208. undefined,
  209. BROWSER_TIMEOUTS.cdpCommand,
  210. signal,
  211. ).catch((e) => {
  212. rethrowBrowserInterruption(e);
  213. console.warn('Failed to get AX tree:', e);
  214. return null;
  215. }) as Promise<{ nodes: AXNode[] } | null>,
  216. // Detect JS event listeners.
  217. this.detectJSEventListeners(signal).catch((error) => {
  218. rethrowBrowserInterruption(error);
  219. return new Set<number>();
  220. }),
  221. // Get viewport information, including scroll offsets.
  222. withTimeout(
  223. (commandSignal) =>
  224. this.transport.evaluate<{
  225. width: number;
  226. height: number;
  227. scrollX: number;
  228. scrollY: number;
  229. pageHeight: number;
  230. pageWidth: number;
  231. }>(
  232. `({
  233. width: window.innerWidth,
  234. height: window.innerHeight,
  235. scrollX: window.scrollX,
  236. scrollY: window.scrollY,
  237. pageHeight: Math.max(
  238. document.body.scrollHeight,
  239. document.documentElement.scrollHeight,
  240. document.body.offsetHeight,
  241. document.documentElement.offsetHeight
  242. ),
  243. pageWidth: Math.max(
  244. document.body.scrollWidth,
  245. document.documentElement.scrollWidth,
  246. document.body.offsetWidth,
  247. document.documentElement.offsetWidth
  248. )
  249. })`,
  250. {
  251. signal: commandSignal,
  252. timeoutMs: BROWSER_TIMEOUTS.cdpCommand,
  253. },
  254. ),
  255. BROWSER_TIMEOUTS.cdpCommand,
  256. 'Browser viewport inspection',
  257. { signal },
  258. ).catch((error) => {
  259. rethrowBrowserInterruption(error);
  260. return {
  261. width: DEFAULT_VIEWPORT.width,
  262. height: DEFAULT_VIEWPORT.height,
  263. scrollX: 0,
  264. scrollY: 0,
  265. pageHeight: DEFAULT_VIEWPORT.height,
  266. pageWidth: DEFAULT_VIEWPORT.width,
  267. };
  268. }),
  269. // Electron/Chromium DOMSnapshot layout uses legacy viewport units; convert to CSS viewport units.
  270. this.getSnapshotToCssScale(signal).catch((error) => {
  271. rethrowBrowserInterruption(error);
  272. return 1;
  273. }),
  274. ]);
  275. throwIfAborted(signal);
  276. logPhase('sources-settled', {
  277. hasSnapshot: snapshotResult !== null,
  278. hasDomTree: domTreeResult !== null,
  279. axNodeCount: axTreeResult?.nodes?.length ?? 0,
  280. jsListenerCount: jsListenerBackendIds.size,
  281. });
  282. // 2. DOMSnapshot bounds use each Document's coordinates; normalize legacy units, scroll offsets, and viewport.
  283. const mainFrameId = domTreeResult?.root?.frameId ?? 'main';
  284. const snapshotLookup = this.buildSnapshotLookup(
  285. snapshotResult,
  286. mainFrameId,
  287. snapshotToCssScale,
  288. );
  289. // 3. Build the AX tree lookup (backendDOMNodeId → AX node).
  290. const axTreeLookup = new Map<number, AXNode>();
  291. if (axTreeResult?.nodes) {
  292. for (const node of axTreeResult.nodes) {
  293. if (node.backendDOMNodeId) {
  294. axTreeLookup.set(node.backendDOMNodeId, node);
  295. }
  296. }
  297. }
  298. // 4. Traverse the DOM tree and collect interactive elements.
  299. const elements: InteractiveElement[] = [];
  300. const processedBackendIds = new Set<number>();
  301. if (domTreeResult?.root) {
  302. await this.traverseDOMTree(
  303. domTreeResult.root,
  304. elements,
  305. processedBackendIds,
  306. snapshotLookup,
  307. axTreeLookup,
  308. jsListenerBackendIds,
  309. viewportInfo,
  310. mainFrameId,
  311. [],
  312. signal,
  313. );
  314. }
  315. // 5. If DOM traversal found no elements, supplement it with a JavaScript scan.
  316. if (elements.length === 0) {
  317. const jsElements = await this.scanInteractiveElementsViaJS(viewportInfo, signal);
  318. elements.push(...jsElements);
  319. }
  320. // 6. Sort by position, top to bottom and left to right.
  321. elements.sort((a, b) => {
  322. const yDiff = a.boundingBox.y - b.boundingBox.y;
  323. if (Math.abs(yDiff) > 10) return yDiff;
  324. return a.boundingBox.x - b.boundingBox.x;
  325. });
  326. // 7. Reassign indices.
  327. elements.forEach((el, idx) => {
  328. el.index = idx;
  329. });
  330. this.lastSemanticPageTree = this.buildSemanticPageTreeSafely({
  331. mainFrameId,
  332. domRoot: domTreeResult?.root,
  333. axNodes: axTreeResult?.nodes ?? [],
  334. snapshotLookup,
  335. interactiveElements: elements,
  336. });
  337. logPhase('complete', { interactiveElementCount: elements.length });
  338. return elements;
  339. } catch (error) {
  340. rethrowBrowserInterruption(error);
  341. logPhase('primary-failed', {
  342. error: error instanceof Error ? error.message : String(error),
  343. });
  344. console.warn('Failed to get interactive elements:', error);
  345. // Fall back to a pure JS scan.
  346. try {
  347. const viewportInfo = await withTimeout(
  348. (commandSignal) =>
  349. this.transport.evaluate<{
  350. width: number;
  351. height: number;
  352. scrollX: number;
  353. scrollY: number;
  354. }>(
  355. `({
  356. width: window.innerWidth,
  357. height: window.innerHeight,
  358. scrollX: window.scrollX,
  359. scrollY: window.scrollY
  360. })`,
  361. {
  362. signal: commandSignal,
  363. timeoutMs: BROWSER_TIMEOUTS.cdpCommand,
  364. },
  365. ),
  366. BROWSER_TIMEOUTS.cdpCommand,
  367. 'Browser viewport fallback inspection',
  368. { signal },
  369. ).catch((fallbackError) => {
  370. rethrowBrowserInterruption(fallbackError);
  371. return {
  372. width: DEFAULT_VIEWPORT.width,
  373. height: DEFAULT_VIEWPORT.height,
  374. scrollX: 0,
  375. scrollY: 0,
  376. };
  377. });
  378. throwIfAborted(signal);
  379. const elements = await this.scanInteractiveElementsViaJS(viewportInfo, signal);
  380. this.lastSemanticPageTree = this.buildSemanticPageTreeSafely({
  381. mainFrameId: 'main',
  382. interactiveElements: elements,
  383. });
  384. logPhase('fallback-complete', { interactiveElementCount: elements.length });
  385. return elements;
  386. } catch (fallbackError) {
  387. rethrowBrowserInterruption(fallbackError);
  388. logPhase('fallback-failed');
  389. return [];
  390. }
  391. }
  392. }
  393. /**
  394. * Capture a page snapshot using DOMSnapshot.captureSnapshot.
  395. */
  396. private async captureSnapshot(signal?: AbortSignal): Promise<DOMSnapshotResult | null> {
  397. const result = (await this.sendCommand(
  398. 'DOMSnapshot.captureSnapshot',
  399. {
  400. computedStyles: REQUIRED_COMPUTED_STYLES,
  401. includePaintOrder: true,
  402. includeDOMRects: true,
  403. includeBlendedBackgroundColors: false,
  404. includeTextColorOpacities: false,
  405. },
  406. BROWSER_TIMEOUTS.cdpCommand,
  407. signal,
  408. )) as DOMSnapshotResult;
  409. return result;
  410. }
  411. /**
  412. * DOMSnapshot layout and Page.getLayoutMetrics' deprecated viewport share legacy units. Compare
  413. * legacy/CSS viewports to derive the conversion ratio; this is not the system devicePixelRatio.
  414. */
  415. private async getSnapshotToCssScale(signal?: AbortSignal): Promise<number> {
  416. try {
  417. const metrics = (await this.sendCommand(
  418. 'Page.getLayoutMetrics',
  419. undefined,
  420. BROWSER_TIMEOUTS.cdpCommand,
  421. signal,
  422. )) as {
  423. visualViewport?: { clientWidth?: number };
  424. cssVisualViewport?: { clientWidth?: number };
  425. };
  426. const legacyWidth = Number(metrics.visualViewport?.clientWidth);
  427. const cssWidth = Number(metrics.cssVisualViewport?.clientWidth);
  428. if (legacyWidth > 0 && cssWidth > 0) {
  429. const scale = legacyWidth / cssWidth;
  430. if (Number.isFinite(scale) && scale > 0) return scale;
  431. }
  432. } catch (error) {
  433. rethrowBrowserInterruption(error);
  434. // captureSnapshot itself can still be used with the protocol default scale.
  435. }
  436. return 1;
  437. }
  438. /**
  439. * Build the snapshot lookup (backendNodeId → layout information).
  440. * @param snapshot DOMSnapshot result.
  441. * @param mainFrameId Main frame CDP id.
  442. */
  443. buildSnapshotLookup(
  444. snapshot: DOMSnapshotResult | null,
  445. mainFrameId: string,
  446. snapshotToCssScale = 1,
  447. ): Map<number, SnapshotNode> {
  448. const lookup = new Map<number, SnapshotNode>();
  449. if (!snapshot?.documents) return lookup;
  450. const strings = snapshot.strings || [];
  451. const scale =
  452. Number.isFinite(snapshotToCssScale) && snapshotToCssScale > 0 ? snapshotToCssScale : 1;
  453. for (let documentIndex = 0; documentIndex < snapshot.documents.length; documentIndex += 1) {
  454. const document = snapshot.documents[documentIndex];
  455. if (!document) continue;
  456. const nodes = document.nodes;
  457. const layout = document.layout;
  458. const documentFrameId =
  459. document.frameId !== undefined ? strings[document.frameId] : undefined;
  460. const isMainDocument =
  461. documentIndex === 0 || (documentFrameId !== undefined && documentFrameId === mainFrameId);
  462. const scrollOffsetX = Number.isFinite(document.scrollOffsetX)
  463. ? Number(document.scrollOffsetX)
  464. : 0;
  465. const scrollOffsetY = Number.isFinite(document.scrollOffsetY)
  466. ? Number(document.scrollOffsetY)
  467. : 0;
  468. const coordinateSpace = isMainDocument ? 'main-frame-viewport' : 'frame-local';
  469. if (!nodes?.backendNodeId) continue;
  470. // Build the nodeIndex → layoutIndex mapping.
  471. const layoutIndexMap = new Map<number, number>();
  472. if (layout?.nodeIndex) {
  473. for (let i = 0; i < layout.nodeIndex.length; i++) {
  474. const nodeIndex = layout.nodeIndex[i];
  475. if (nodeIndex !== undefined && !layoutIndexMap.has(nodeIndex)) {
  476. layoutIndexMap.set(nodeIndex, i);
  477. }
  478. }
  479. }
  480. // Traverse all nodes.
  481. for (let i = 0; i < nodes.backendNodeId.length; i++) {
  482. const backendNodeId = nodes.backendNodeId[i];
  483. // Check whether the node is clickable.
  484. let isClickable = false;
  485. if (nodes.isClickable?.index) {
  486. isClickable = nodes.isClickable.index.includes(i);
  487. }
  488. // Get layout information.
  489. let bounds: { x: number; y: number; width: number; height: number } | null = null;
  490. const computedStyles: Record<string, string> = {};
  491. let paintOrder: number | null = null;
  492. const layoutIdx = layoutIndexMap.get(i);
  493. if (layoutIdx !== undefined && layout) {
  494. // For the main document, subtract scroll offsets in the same units, then convert to main-frame viewport CSS
  495. // coordinates using the legacy/CSS ratio. Child documents remain frame-local until DOM.getContentQuads converts them.
  496. if (layout.bounds && layoutIdx < layout.bounds.length) {
  497. const b = layout.bounds[layoutIdx];
  498. if (b && b.length >= 4) {
  499. bounds = {
  500. x: (b[0]! - scrollOffsetX) / scale,
  501. y: (b[1]! - scrollOffsetY) / scale,
  502. width: b[2]! / scale,
  503. height: b[3]! / scale,
  504. };
  505. }
  506. }
  507. // Parse computed styles.
  508. if (layout.styles && layoutIdx < layout.styles.length) {
  509. const styleIndices = layout.styles[layoutIdx];
  510. if (styleIndices) {
  511. for (let j = 0; j < styleIndices.length && j < REQUIRED_COMPUTED_STYLES.length; j++) {
  512. const styleIndex = styleIndices[j];
  513. const styleName = REQUIRED_COMPUTED_STYLES[j];
  514. if (
  515. styleName !== undefined &&
  516. styleIndex !== undefined &&
  517. styleIndex >= 0 &&
  518. styleIndex < strings.length
  519. ) {
  520. computedStyles[styleName] = strings[styleIndex] ?? '';
  521. }
  522. }
  523. }
  524. }
  525. // Parse paint order.
  526. if (layout.paintOrders && layoutIdx < layout.paintOrders.length) {
  527. paintOrder = layout.paintOrders[layoutIdx] ?? null;
  528. }
  529. }
  530. if (backendNodeId === undefined) continue;
  531. lookup.set(backendNodeId, {
  532. bounds,
  533. coordinateSpace,
  534. computedStyles,
  535. isClickable,
  536. paintOrder,
  537. frameId: documentFrameId || mainFrameId,
  538. });
  539. }
  540. }
  541. return lookup;
  542. }
  543. /**
  544. * DOM.getContentQuads returns viewport-relative CSS quads, reliably mapping child-frame elements
  545. * to the main-frame viewport. Union multiple fragments into one bounding box; callers fail closed
  546. * on protocol errors.
  547. */
  548. async getViewportBoundsByBackendNodeId(
  549. backendNodeId: number,
  550. signal?: AbortSignal,
  551. ): Promise<{ x: number; y: number; width: number; height: number } | null> {
  552. try {
  553. const result = (await this.sendCommand(
  554. 'DOM.getContentQuads',
  555. { backendNodeId },
  556. BROWSER_TIMEOUTS.cdpCommand,
  557. signal,
  558. )) as { quads?: number[][] };
  559. const coordinates = (result.quads ?? [])
  560. .filter((quad) => Array.isArray(quad) && quad.length >= 8)
  561. .flatMap((quad) => quad.slice(0, 8));
  562. if (coordinates.length < 8 || coordinates.some((value) => !Number.isFinite(value))) {
  563. return null;
  564. }
  565. const xs = coordinates.filter((_, index) => index % 2 === 0);
  566. const ys = coordinates.filter((_, index) => index % 2 === 1);
  567. const left = Math.min(...xs);
  568. const right = Math.max(...xs);
  569. const top = Math.min(...ys);
  570. const bottom = Math.max(...ys);
  571. if (right <= left || bottom <= top) return null;
  572. return { x: left, y: top, width: right - left, height: bottom - top };
  573. } catch (error) {
  574. rethrowBrowserInterruption(error);
  575. return null;
  576. }
  577. }
  578. /**
  579. * Detect JavaScript event listeners using CDP's getEventListeners API (requires
  580. * includeCommandLineAPI).
  581. */
  582. private async detectJSEventListeners(signal?: AbortSignal): Promise<Set<number>> {
  583. const backendIds = new Set<number>();
  584. try {
  585. // Use Runtime.evaluate with includeCommandLineAPI to access getEventListeners.
  586. const result = (await this.sendCommand(
  587. 'Runtime.evaluate',
  588. {
  589. expression: `
  590. (function() {
  591. if (typeof getEventListeners !== 'function') {
  592. return null;
  593. }
  594. const elementsWithListeners = new Set();
  595. const allElements = document.querySelectorAll('*');
  596. const explicitCandidateSelector = [
  597. 'button', 'a[href]', 'input', 'textarea', 'select',
  598. '[role]', '[tabindex]', '[contenteditable="true"]',
  599. '[data-action]', '[data-command]', '[data-testid]'
  600. ].join(',');
  601. const delegatedEventTypes = [
  602. 'click', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'touchstart'
  603. ];
  604. const genericLeafTags = new Set(['DIV', 'SPAN', 'LI', 'P']);
  605. const globalDelegationRoots = new Set([
  606. document.documentElement,
  607. document.body
  608. ]);
  609. const isVisibleCandidate = (candidate) => {
  610. const style = getComputedStyle(candidate);
  611. if (style.display === 'none' || style.visibility === 'hidden' ||
  612. Number.parseFloat(style.opacity || '1') <= 0 ||
  613. style.pointerEvents === 'none') return false;
  614. const rect = candidate.getBoundingClientRect();
  615. return rect.width > 0 && rect.height > 0;
  616. };
  617. const hasFrameworkActionSignal = (candidate) => {
  618. for (const attribute of candidate.attributes) {
  619. const name = attribute.name.toLowerCase();
  620. if (/^(?:onclick|onmousedown|onmouseup|ng-click|data-(?:action|command|click|event|handler))$/.test(name) ||
  621. /^(?:@|v-on:|x-on:)click$/.test(name) ||
  622. name.startsWith('hx-')) return true;
  623. }
  624. return false;
  625. };
  626. const isScopedDelegatedLeaf = (candidate, listenerRoot) => {
  627. if (globalDelegationRoots.has(listenerRoot) || !isVisibleCandidate(candidate)) {
  628. return false;
  629. }
  630. const style = getComputedStyle(candidate);
  631. if (style.cursor === 'pointer' || hasFrameworkActionSignal(candidate)) return true;
  632. if (!genericLeafTags.has(candidate.tagName) && !candidate.tagName.includes('-')) {
  633. return false;
  634. }
  635. const semanticText = (
  636. candidate.getAttribute('aria-label') ||
  637. candidate.getAttribute('title') ||
  638. candidate.textContent || ''
  639. ).trim();
  640. if (!semanticText) return false;
  641. return !Array.from(candidate.children).some((child) =>
  642. isVisibleCandidate(child) && (child.textContent || '').trim().length > 0
  643. );
  644. };
  645. const addCandidate = (candidate) => {
  646. if (elementsWithListeners.size < 500) elementsWithListeners.add(candidate);
  647. };
  648. for (const el of allElements) {
  649. try {
  650. const listeners = getEventListeners(el);
  651. if (delegatedEventTypes.some((type) => listeners[type]?.length)) {
  652. const delegatedCandidates = new Set();
  653. for (const candidate of el.querySelectorAll(explicitCandidateSelector)) {
  654. if (isVisibleCandidate(candidate)) delegatedCandidates.add(candidate);
  655. }
  656. // A scoped delegation root often targets a plain div/span/li with
  657. // no ARIA or framework-specific attribute. Promote visible,
  658. // text-bearing leaves generically; never apply this broad signal to
  659. // html/body because global delegation would turn page prose into
  660. // controls.
  661. for (const candidate of el.querySelectorAll('div,span,li,p,*')) {
  662. if (isScopedDelegatedLeaf(candidate, el)) delegatedCandidates.add(candidate);
  663. if (delegatedCandidates.size >= 200) break;
  664. }
  665. // Preserve direct listeners. When a scoped listener has concrete
  666. // delegated descendants, do not expose the structural ancestor as
  667. // a competing control.
  668. if (delegatedCandidates.size === 0 ||
  669. el.matches(explicitCandidateSelector) ||
  670. getComputedStyle(el).cursor === 'pointer' ||
  671. hasFrameworkActionSignal(el)) {
  672. addCandidate(el);
  673. }
  674. for (const candidate of delegatedCandidates) {
  675. addCandidate(candidate);
  676. if (elementsWithListeners.size >= 500) break;
  677. }
  678. }
  679. } catch (e) {
  680. // Ignore errors for individual elements.
  681. }
  682. }
  683. return Array.from(elementsWithListeners);
  684. })()
  685. `,
  686. includeCommandLineAPI: true,
  687. returnByValue: false,
  688. },
  689. BROWSER_TIMEOUTS.cdpCommand,
  690. signal,
  691. )) as { result?: { objectId?: string } };
  692. const objectId = result?.result?.objectId;
  693. if (!objectId) return backendIds;
  694. // Get array properties.
  695. const propsResult = (await this.sendCommand(
  696. 'Runtime.getProperties',
  697. { objectId, ownProperties: true },
  698. BROWSER_TIMEOUTS.cdpCommand,
  699. signal,
  700. )) as { result?: Array<{ name: string; value?: { objectId?: string } }> };
  701. // Get each element's backendNodeId.
  702. const elementObjectIds: string[] = [];
  703. for (const prop of propsResult.result || []) {
  704. if (prop.name && /^\d+$/.test(prop.name) && prop.value?.objectId) {
  705. elementObjectIds.push(prop.value.objectId);
  706. }
  707. }
  708. // Fetch backendNodeIds in parallel.
  709. const nodePromises = elementObjectIds.map(async (objId) => {
  710. try {
  711. const nodeInfo = (await this.sendCommand(
  712. 'DOM.describeNode',
  713. { objectId: objId },
  714. BROWSER_TIMEOUTS.cdpCommand,
  715. signal,
  716. )) as { node?: { backendNodeId?: number } };
  717. return nodeInfo?.node?.backendNodeId;
  718. } catch (error) {
  719. rethrowBrowserInterruption(error);
  720. return undefined;
  721. }
  722. });
  723. const nodeIds = await Promise.all(nodePromises);
  724. for (const id of nodeIds) {
  725. if (id !== undefined) {
  726. backendIds.add(id);
  727. }
  728. }
  729. // Release objects.
  730. try {
  731. await this.sendCommand(
  732. 'Runtime.releaseObject',
  733. { objectId },
  734. BROWSER_TIMEOUTS.cdpCommand,
  735. signal,
  736. );
  737. } catch (error) {
  738. rethrowBrowserInterruption(error);
  739. // Ignore release errors.
  740. }
  741. } catch (error) {
  742. rethrowBrowserInterruption(error);
  743. console.warn('Failed to detect JS event listeners:', error);
  744. }
  745. return backendIds;
  746. }
  747. /**
  748. * Traverse the DOM tree and collect interactive elements.
  749. */
  750. private axBooleanProperty(axNode: AXNode | undefined, name: string): boolean {
  751. return (
  752. axNode?.properties?.some(
  753. (property) => property.name === name && property.value?.value === true,
  754. ) === true
  755. );
  756. }
  757. private axHasEnabledProperty(axNode: AXNode | undefined, name: string): boolean {
  758. return (
  759. axNode?.properties?.some(
  760. (property) => property.name === name && property.value?.value !== false,
  761. ) === true
  762. );
  763. }
  764. private isVirtualEditorProxy(node: DOMNode, axNode: AXNode | undefined): boolean {
  765. const tagName = node.nodeName?.toLowerCase() || '';
  766. const inputType = this.getNodeAttribute(node, 'type')?.toLowerCase() || '';
  767. const role = (axNode?.role?.value || this.getNodeAttribute(node, 'role') || '').toLowerCase();
  768. const editableNode =
  769. tagName === 'textarea' ||
  770. (tagName === 'input' && inputType !== 'hidden') ||
  771. this.getNodeAttribute(node, 'contenteditable') === 'true';
  772. return (
  773. editableNode &&
  774. (role === 'textbox' || role === 'searchbox') &&
  775. (this.axBooleanProperty(axNode, 'focused') ||
  776. (this.axBooleanProperty(axNode, 'focusable') &&
  777. (this.axHasEnabledProperty(axNode, 'editable') ||
  778. this.axBooleanProperty(axNode, 'settable'))))
  779. );
  780. }
  781. private findVisibleVirtualEditorHost(
  782. ancestors: readonly DOMNode[],
  783. snapshotLookup: Map<number, SnapshotNode>,
  784. viewportInfo: { width: number; height: number; scrollX: number; scrollY: number },
  785. frameId: string,
  786. ): { node: DOMNode; snapshotNode: SnapshotNode } | null {
  787. for (let index = ancestors.length - 1; index >= 0; index -= 1) {
  788. const candidate = ancestors[index];
  789. if (!candidate) continue;
  790. const tagName = candidate.nodeName?.toLowerCase() || '';
  791. if (
  792. candidate.nodeType !== 1 ||
  793. CONTAINER_TAGS.has(tagName) ||
  794. (candidate.frameId && candidate.frameId !== frameId)
  795. ) {
  796. continue;
  797. }
  798. const snapshotNode = snapshotLookup.get(candidate.backendNodeId);
  799. if (
  800. this.isElementVisible(snapshotNode, viewportInfo) &&
  801. snapshotNode?.bounds &&
  802. snapshotNode.bounds.width >= 16 &&
  803. snapshotNode.bounds.height >= 16
  804. ) {
  805. return { node: candidate, snapshotNode };
  806. }
  807. }
  808. return null;
  809. }
  810. private createVirtualEditorElement(
  811. proxyNode: DOMNode,
  812. hostNode: DOMNode,
  813. hostSnapshotNode: SnapshotNode,
  814. axNode: AXNode,
  815. viewportInfo: { width: number; height: number; scrollX: number; scrollY: number },
  816. index: number,
  817. frameId: string,
  818. ): InteractiveElement | null {
  819. const element = this.createInteractiveElement(
  820. proxyNode,
  821. hostSnapshotNode,
  822. axNode,
  823. viewportInfo,
  824. index,
  825. frameId,
  826. );
  827. if (!element) return null;
  828. return {
  829. ...element,
  830. backendNodeId: hostNode.backendNodeId,
  831. semanticBackendNodeId: proxyNode.backendNodeId,
  832. selector: `[data-backend-node-id="${hostNode.backendNodeId}"]`,
  833. inputStrategy: 'focused-keyboard',
  834. };
  835. }
  836. async traverseDOMTree(
  837. node: DOMNode,
  838. elements: InteractiveElement[],
  839. processedBackendIds: Set<number>,
  840. snapshotLookup: Map<number, SnapshotNode>,
  841. axTreeLookup: Map<number, AXNode>,
  842. jsListenerBackendIds: Set<number>,
  843. viewportInfo: { width: number; height: number; scrollX: number; scrollY: number },
  844. frameId: string,
  845. ancestors: readonly DOMNode[] = [],
  846. signal?: AbortSignal,
  847. ): Promise<void> {
  848. if (signal?.aborted) return;
  849. // Skip nodes already processed.
  850. if (processedBackendIds.has(node.backendNodeId)) return;
  851. processedBackendIds.add(node.backendNodeId);
  852. const tagName = node.nodeName?.toLowerCase() || '';
  853. // Skip text and comment nodes (nodeType: 1=Element, 3=Text, 8=Comment).
  854. if (node.nodeType === 3 || node.nodeType === 8) {
  855. return;
  856. }
  857. // Tags to skip entirely, including their descendants.
  858. if (SKIP_TAGS.has(tagName) || SVG_ELEMENTS.has(tagName)) {
  859. return;
  860. }
  861. // Runtime listener discovery can promote a custom div/section out of the
  862. // structural-container bucket. This is required for direct and delegated
  863. // application controls that have no native tag/role/tabindex signal.
  864. const hasJSEventListener = jsListenerBackendIds.has(node.backendNodeId);
  865. const isContainer = CONTAINER_TAGS.has(tagName) && !hasJSEventListener;
  866. if (!isContainer) {
  867. // Get snapshot information.
  868. let snapshotNode = snapshotLookup.get(node.backendNodeId);
  869. // Get AX node information.
  870. const axNode = axTreeLookup.get(node.backendNodeId);
  871. // Check whether the element is interactive.
  872. const isInteractive = this.isElementInteractive(
  873. node,
  874. snapshotNode,
  875. axNode,
  876. hasJSEventListener,
  877. );
  878. // Only issue additional CDP quad queries for interactive child-frame nodes, avoiding a round trip per DOM node.
  879. if (isInteractive && snapshotNode?.coordinateSpace === 'frame-local') {
  880. const viewportBounds = await this.getViewportBoundsByBackendNodeId(
  881. node.backendNodeId,
  882. signal,
  883. );
  884. snapshotNode = viewportBounds
  885. ? {
  886. ...snapshotNode,
  887. bounds: viewportBounds,
  888. coordinateSpace: 'main-frame-viewport',
  889. }
  890. : {
  891. ...snapshotNode,
  892. coordinateSpace: 'unavailable',
  893. };
  894. }
  895. // Check element visibility.
  896. const isVisible = this.isElementVisible(snapshotNode, viewportInfo);
  897. // Add visible, interactive elements to the results.
  898. if (isVisible && isInteractive) {
  899. const element = this.createInteractiveElement(
  900. node,
  901. snapshotNode,
  902. axNode,
  903. viewportInfo,
  904. elements.length,
  905. node.frameId ?? frameId,
  906. hasJSEventListener,
  907. );
  908. if (element) {
  909. elements.push(element);
  910. }
  911. } else if (isInteractive && axNode && this.isVirtualEditorProxy(node, axNode)) {
  912. const host = this.findVisibleVirtualEditorHost(
  913. ancestors,
  914. snapshotLookup,
  915. viewportInfo,
  916. node.frameId ?? frameId,
  917. );
  918. if (host) {
  919. let hostSnapshotNode = host.snapshotNode;
  920. if (hostSnapshotNode.coordinateSpace === 'frame-local') {
  921. const viewportBounds = await this.getViewportBoundsByBackendNodeId(
  922. host.node.backendNodeId,
  923. signal,
  924. );
  925. hostSnapshotNode = viewportBounds
  926. ? {
  927. ...hostSnapshotNode,
  928. bounds: viewportBounds,
  929. coordinateSpace: 'main-frame-viewport',
  930. }
  931. : {
  932. ...hostSnapshotNode,
  933. coordinateSpace: 'unavailable',
  934. };
  935. }
  936. const existingIndex = elements.findIndex(
  937. (element) => element.backendNodeId === host.node.backendNodeId,
  938. );
  939. const element = this.createVirtualEditorElement(
  940. node,
  941. host.node,
  942. hostSnapshotNode,
  943. axNode,
  944. viewportInfo,
  945. existingIndex >= 0 ? existingIndex : elements.length,
  946. node.frameId ?? frameId,
  947. );
  948. if (element) {
  949. if (existingIndex >= 0) elements[existingIndex] = element;
  950. else elements.push(element);
  951. }
  952. }
  953. }
  954. }
  955. // Recursively process child nodes.
  956. if (node.children) {
  957. for (const child of node.children) {
  958. await this.traverseDOMTree(
  959. child,
  960. elements,
  961. processedBackendIds,
  962. snapshotLookup,
  963. axTreeLookup,
  964. jsListenerBackendIds,
  965. viewportInfo,
  966. child.frameId ?? frameId,
  967. [...ancestors, node],
  968. signal,
  969. );
  970. }
  971. }
  972. // Process shadow DOM.
  973. if (node.shadowRoots) {
  974. for (const shadowRoot of node.shadowRoots) {
  975. await this.traverseDOMTree(
  976. shadowRoot,
  977. elements,
  978. processedBackendIds,
  979. snapshotLookup,
  980. axTreeLookup,
  981. jsListenerBackendIds,
  982. viewportInfo,
  983. shadowRoot.frameId ?? frameId,
  984. [...ancestors, node],
  985. signal,
  986. );
  987. }
  988. }
  989. // Process iframe contentDocument.
  990. if (node.contentDocument) {
  991. await this.traverseDOMTree(
  992. node.contentDocument,
  993. elements,
  994. processedBackendIds,
  995. snapshotLookup,
  996. axTreeLookup,
  997. jsListenerBackendIds,
  998. viewportInfo,
  999. node.contentDocument.frameId ?? node.frameId ?? frameId,
  1000. [],
  1001. signal,
  1002. );
  1003. }
  1004. }
  1005. /**
  1006. * Check element visibility.
  1007. */
  1008. isElementVisible(
  1009. snapshotNode: SnapshotNode | undefined,
  1010. viewportInfo: { width: number; height: number; scrollX: number; scrollY: number },
  1011. ): boolean {
  1012. if (!snapshotNode?.bounds) return false;
  1013. const { bounds, computedStyles } = snapshotNode;
  1014. // Check dimensions.
  1015. if (bounds.width <= 0 || bounds.height <= 0) return false;
  1016. // Check CSS visibility.
  1017. const display = computedStyles.display?.toLowerCase();
  1018. const visibility = computedStyles.visibility?.toLowerCase();
  1019. const opacity = computedStyles.opacity;
  1020. if (display === 'none') return false;
  1021. if (visibility === 'hidden') return false;
  1022. if (opacity !== undefined) {
  1023. const opacityValue = parseFloat(opacity);
  1024. if (!isNaN(opacityValue) && opacityValue <= 0) return false;
  1025. }
  1026. // Keep child-frame refs whose coordinates cannot be converted, but do not expose their rect to the model later.
  1027. if (snapshotNode.coordinateSpace === 'unavailable') return true;
  1028. // Check whether the element is in the viewport, allowing a margin.
  1029. const threshold = 1000; // Allow elements within 1000px outside the viewport.
  1030. const viewportRight = viewportInfo.width;
  1031. // Keep vertically offscreen controls discoverable so the Core can scroll
  1032. // them into view. Horizontally detached nodes are commonly focus traps or
  1033. // hidden editor proxies and must remain excluded.
  1034. const isInActionableDocument =
  1035. bounds.x < viewportRight + threshold &&
  1036. bounds.x + bounds.width > -threshold &&
  1037. bounds.y + bounds.height > -threshold;
  1038. return isInActionableDocument;
  1039. }
  1040. /**
  1041. * Search-related keywords (following browser-use).
  1042. */
  1043. private static readonly SEARCH_INDICATORS = new Set([
  1044. 'search',
  1045. 'magnify',
  1046. 'glass',
  1047. 'lookup',
  1048. 'find',
  1049. 'query',
  1050. 'search-icon',
  1051. 'search-btn',
  1052. 'search-button',
  1053. 'searchbox',
  1054. ]);
  1055. /**
  1056. * Check whether the element is search-related.
  1057. */
  1058. private isSearchElement(node: DOMNode): boolean {
  1059. // Check class.
  1060. const className = this.getNodeAttribute(node, 'class')?.toLowerCase() || '';
  1061. const classList = className.split(/\s+/);
  1062. for (const cls of classList) {
  1063. for (const indicator of CDPPageScanner.SEARCH_INDICATORS) {
  1064. if (cls.includes(indicator)) return true;
  1065. }
  1066. }
  1067. // Check id.
  1068. const id = this.getNodeAttribute(node, 'id')?.toLowerCase() || '';
  1069. for (const indicator of CDPPageScanner.SEARCH_INDICATORS) {
  1070. if (id.includes(indicator)) return true;
  1071. }
  1072. // Check data attributes.
  1073. if (node.attributes) {
  1074. for (let i = 0; i < node.attributes.length; i += 2) {
  1075. const attrName = node.attributes[i];
  1076. const attrValue = node.attributes[i + 1]?.toLowerCase() || '';
  1077. if (attrName?.startsWith('data-')) {
  1078. for (const indicator of CDPPageScanner.SEARCH_INDICATORS) {
  1079. if (attrValue.includes(indicator)) return true;
  1080. }
  1081. }
  1082. }
  1083. }
  1084. return false;
  1085. }
  1086. /**
  1087. * Check whether the element is an interactive icon (a small 10–50px element).
  1088. */
  1089. private isInteractiveIcon(node: DOMNode, snapshotNode: SnapshotNode | undefined): boolean {
  1090. if (!snapshotNode?.bounds) return false;
  1091. const { width, height } = snapshotNode.bounds;
  1092. // Check icon dimensions (10–50px).
  1093. if (width < 10 || width > 50 || height < 10 || height > 50) {
  1094. return false;
  1095. }
  1096. // Check for interaction-related attributes.
  1097. const hasInteractiveAttr =
  1098. this.getNodeAttribute(node, 'class') !== null ||
  1099. this.getNodeAttribute(node, 'role') !== null ||
  1100. this.getNodeAttribute(node, 'onclick') !== null ||
  1101. this.getNodeAttribute(node, 'data-action') !== null ||
  1102. this.getNodeAttribute(node, 'aria-label') !== null;
  1103. return hasInteractiveAttr;
  1104. }
  1105. /**
  1106. * Some rich editors expose only a visible activation surface until the first click. The real
  1107. * input/contenteditable is mounted or focused afterwards. Keep this signal narrow: the surface
  1108. * must explicitly render a text cursor and carry a semantic name; execution still fails closed
  1109. * unless clicking it produces an editable focus inside the surface.
  1110. */
  1111. private isTextEntryActivationSurface(
  1112. node: DOMNode,
  1113. snapshotNode: SnapshotNode | undefined,
  1114. axNode: AXNode | undefined,
  1115. ): boolean {
  1116. const tagName = node.nodeName?.toLowerCase() || '';
  1117. if (tagName !== 'div' && tagName !== 'span') return false;
  1118. if (snapshotNode?.computedStyles?.cursor !== 'text') return false;
  1119. const role = (axNode?.role?.value || this.getNodeAttribute(node, 'role') || '').toLowerCase();
  1120. if (role && role !== 'generic' && role !== 'none' && role !== 'textbox') return false;
  1121. const semanticName =
  1122. axNode?.name?.value ||
  1123. this.getNodeAttribute(node, 'aria-label') ||
  1124. this.getNodeAttribute(node, 'title') ||
  1125. this.getNodeAttribute(node, 'placeholder') ||
  1126. '';
  1127. return semanticName.trim().length > 0;
  1128. }
  1129. /**
  1130. * Check element interactivity, following browser-use's ClickableElementDetector.
  1131. */
  1132. isElementInteractive(
  1133. node: DOMNode,
  1134. snapshotNode: SnapshotNode | undefined,
  1135. axNode: AXNode | undefined,
  1136. hasJSClickListener: boolean,
  1137. ): boolean {
  1138. const tagName = node.nodeName?.toLowerCase() || '';
  1139. // 0. Exclude text and non-element nodes.
  1140. if (tagName === '#text' || tagName === '#comment' || node.nodeType !== 1) {
  1141. return false;
  1142. }
  1143. // 1. Check JS event listeners (highest priority).
  1144. if (hasJSClickListener) return true;
  1145. // 1.1 AX ignored only means the accessibility tree does not expose the
  1146. // node; it cannot override positive Runtime listener evidence above.
  1147. if (axNode?.ignored) return false;
  1148. // 2. Check natively interactive tags.
  1149. if (INTERACTIVE_TAGS.has(tagName)) return true;
  1150. // 3. Check ARIA role.
  1151. const role = this.getNodeAttribute(node, 'role')?.toLowerCase();
  1152. if (role && INTERACTIVE_ROLES.has(role)) return true;
  1153. // 4. Check AX tree role, excluding generic and none.
  1154. if (axNode?.role?.value) {
  1155. const axRole = axNode.role.value.toLowerCase();
  1156. // generic and none are not truly interactive roles.
  1157. if (axRole !== 'generic' && axRole !== 'none' && INTERACTIVE_ROLES.has(axRole)) {
  1158. return true;
  1159. }
  1160. }
  1161. // 5. Check contenteditable.
  1162. if (this.getNodeAttribute(node, 'contenteditable') === 'true') return true;
  1163. // 6. Check tabindex (other than -1).
  1164. const tabindex = this.getNodeAttribute(node, 'tabindex');
  1165. if (tabindex !== null && tabindex !== '-1') return true;
  1166. // 7. Check event attributes such as onclick.
  1167. const eventAttrs = [
  1168. 'onclick',
  1169. 'onmousedown',
  1170. 'onmouseup',
  1171. 'onkeydown',
  1172. 'onkeyup',
  1173. 'ontouchstart',
  1174. ];
  1175. for (const attr of eventAttrs) {
  1176. if (this.getNodeAttribute(node, attr) !== null) return true;
  1177. }
  1178. // 8. Check search elements (following browser-use).
  1179. if (this.isSearchElement(node)) return true;
  1180. // 9. Check interactive icons (small 10–50px elements).
  1181. if (this.isInteractiveIcon(node, snapshotNode)) return true;
  1182. // 9.1 Check rich-text editor surfaces that mount/focus their actual input proxy only after a click.
  1183. if (
  1184. this.isTextEntryActivationSurface(node, snapshotNode, axNode) &&
  1185. (snapshotNode?.isClickable === true ||
  1186. this.axBooleanProperty(axNode, 'focusable') ||
  1187. this.getNodeAttribute(node, 'tabindex') !== null)
  1188. ) {
  1189. return true;
  1190. }
  1191. // 10. Check cursor: pointer, requiring additional interaction signals.
  1192. const hasCursorPointer = snapshotNode?.computedStyles?.cursor === 'pointer';
  1193. // 11. Check the snapshot's isClickable flag.
  1194. // Note: isClickable can produce false positives; combine it with other signals.
  1195. const isClickable = snapshotNode?.isClickable === true;
  1196. // 12. Check AX properties.
  1197. let hasInteractiveAxProp = false;
  1198. if (axNode?.properties) {
  1199. for (const prop of axNode.properties) {
  1200. // Editable or settable, excluding focusable because many elements are focusable.
  1201. if (['editable', 'settable'].includes(prop.name) && prop.value?.value === true) {
  1202. hasInteractiveAxProp = true;
  1203. break;
  1204. }
  1205. // Interaction-state properties: their presence indicates interactivity.
  1206. if (['checked', 'expanded', 'pressed', 'selected'].includes(prop.name)) {
  1207. hasInteractiveAxProp = true;
  1208. break;
  1209. }
  1210. }
  1211. }
  1212. // Generic elements such as div/span require multiple signals to count as interactive.
  1213. if (tagName === 'div' || tagName === 'span') {
  1214. // Require at least two signals or an explicit interaction attribute.
  1215. const signals = [hasCursorPointer, isClickable, hasInteractiveAxProp].filter(Boolean).length;
  1216. if (signals >= 2 || hasInteractiveAxProp) {
  1217. return true;
  1218. }
  1219. return false;
  1220. }
  1221. // For other elements, any signal is sufficient.
  1222. if (hasCursorPointer || isClickable || hasInteractiveAxProp) {
  1223. return true;
  1224. }
  1225. // 13. Check for labels containing form controls.
  1226. if (tagName === 'label') {
  1227. // Skip labels with a for attribute to avoid duplicates.
  1228. if (this.getNodeAttribute(node, 'for')) return false;
  1229. if (this.hasFormControlDescendant(node)) return true;
  1230. }
  1231. // 14. Check iframes; those larger than 100x100 may require interaction.
  1232. if ((tagName === 'iframe' || tagName === 'frame') && snapshotNode?.bounds) {
  1233. if (snapshotNode.bounds.width > 100 && snapshotNode.bounds.height > 100) {
  1234. return true;
  1235. }
  1236. }
  1237. return false;
  1238. }
  1239. /**
  1240. * Get node attributes.
  1241. */
  1242. private getNodeAttribute(node: DOMNode, name: string): string | null {
  1243. if (!node.attributes) return null;
  1244. for (let i = 0; i < node.attributes.length; i += 2) {
  1245. if (node.attributes[i] === name) {
  1246. return node.attributes[i + 1] || '';
  1247. }
  1248. }
  1249. return null;
  1250. }
  1251. /**
  1252. * Check whether the node contains descendant form controls.
  1253. */
  1254. private hasFormControlDescendant(node: DOMNode, maxDepth = 2): boolean {
  1255. if (maxDepth <= 0) return false;
  1256. if (!node.children) return false;
  1257. for (const child of node.children) {
  1258. const tag = child.nodeName?.toLowerCase();
  1259. if (tag === 'input' || tag === 'select' || tag === 'textarea') {
  1260. return true;
  1261. }
  1262. if (this.hasFormControlDescendant(child, maxDepth - 1)) {
  1263. return true;
  1264. }
  1265. }
  1266. return false;
  1267. }
  1268. /**
  1269. * Create an interactive element object.
  1270. */
  1271. private createInteractiveElement(
  1272. node: DOMNode,
  1273. snapshotNode: SnapshotNode | undefined,
  1274. axNode: AXNode | undefined,
  1275. viewportInfo: { width: number; height: number; scrollX: number; scrollY: number },
  1276. index: number,
  1277. frameId: string,
  1278. runtimeDiscovered = false,
  1279. ): InteractiveElement | null {
  1280. const bounds = snapshotNode?.bounds;
  1281. if (!bounds) return null;
  1282. const tagName = node.nodeName?.toLowerCase() || '';
  1283. const textEntryActivationSurface = this.isTextEntryActivationSurface(
  1284. node,
  1285. snapshotNode,
  1286. axNode,
  1287. );
  1288. // Get the element type.
  1289. let type = tagName;
  1290. if (textEntryActivationSurface) {
  1291. type = 'textbox';
  1292. } else if (axNode?.role?.value) {
  1293. type = axNode.role.value.toLowerCase();
  1294. } else {
  1295. const role = this.getNodeAttribute(node, 'role');
  1296. if (role) type = role.toLowerCase();
  1297. }
  1298. // Get the element text.
  1299. let text = '';
  1300. if (axNode?.name?.value) {
  1301. text = axNode.name.value;
  1302. } else {
  1303. text =
  1304. this.getNodeAttribute(node, 'aria-label') ||
  1305. this.getNodeAttribute(node, 'title') ||
  1306. this.getNodeAttribute(node, 'placeholder') ||
  1307. this.getNodeAttribute(node, 'alt') ||
  1308. '';
  1309. }
  1310. if (!text && runtimeDiscovered) text = this.getDescendantText(node);
  1311. text = text.slice(0, 100).trim();
  1312. // Filter empty generic elements with no text or meaningful attributes.
  1313. // These are usually container divs with no interaction value for the LLM.
  1314. if (!runtimeDiscovered && (type === 'generic' || type === 'none') && !text) {
  1315. // Check for meaningful attributes.
  1316. const meaningfulAttrs = [
  1317. 'aria-label',
  1318. 'title',
  1319. 'data-testid',
  1320. 'data-action',
  1321. 'onclick',
  1322. 'tabindex',
  1323. 'draggable',
  1324. ];
  1325. const hasMeaningfulAttr = meaningfulAttrs.some(
  1326. (attr) => this.getNodeAttribute(node, attr) !== null,
  1327. );
  1328. // Check whether the element is small (possibly an icon button).
  1329. const isSmallElement = bounds.width <= 60 && bounds.height <= 60;
  1330. // Filter elements with no meaningful attributes unless they are small.
  1331. if (!hasMeaningfulAttr && !isSmallElement) {
  1332. return null;
  1333. }
  1334. }
  1335. // Generate a selector, preferring backendNodeId.
  1336. const selector = `[data-backend-node-id="${node.backendNodeId}"]`;
  1337. // Compute normalized coordinates.
  1338. const centerX = bounds.x + bounds.width / 2;
  1339. const centerY = bounds.y + bounds.height / 2;
  1340. const hasViewportCoordinates = snapshotNode?.coordinateSpace === 'main-frame-viewport';
  1341. const normalizedX = hasViewportCoordinates
  1342. ? Math.round((centerX / viewportInfo.width) * 1000) / 1000
  1343. : 0;
  1344. const normalizedY = hasViewportCoordinates
  1345. ? Math.round((centerY / viewportInfo.height) * 1000) / 1000
  1346. : 0;
  1347. // Check whether the element is in the viewport.
  1348. const isInViewport =
  1349. hasViewportCoordinates &&
  1350. bounds.y < viewportInfo.height &&
  1351. bounds.y + bounds.height > 0 &&
  1352. bounds.x < viewportInfo.width &&
  1353. bounds.x + bounds.width > 0;
  1354. // Collect attributes.
  1355. const attributes: Record<string, string> = {};
  1356. const attrNames = [
  1357. 'id',
  1358. 'class',
  1359. 'data-testid',
  1360. 'data-action',
  1361. 'href',
  1362. 'src',
  1363. 'placeholder',
  1364. 'value',
  1365. 'aria-label',
  1366. 'aria-expanded',
  1367. 'aria-selected',
  1368. 'aria-checked',
  1369. 'aria-pressed',
  1370. 'type',
  1371. 'target',
  1372. 'name',
  1373. 'role',
  1374. 'contenteditable',
  1375. 'tabindex',
  1376. 'draggable',
  1377. ];
  1378. for (const attrName of attrNames) {
  1379. const val = this.getNodeAttribute(node, attrName);
  1380. if (val) attributes[attrName] = val;
  1381. }
  1382. // Check whether the element is disabled.
  1383. const isDisabled =
  1384. this.getNodeAttribute(node, 'disabled') !== null ||
  1385. this.getNodeAttribute(node, 'aria-disabled') === 'true';
  1386. return {
  1387. index,
  1388. backendNodeId: node.backendNodeId,
  1389. frameId,
  1390. selector,
  1391. tag: tagName,
  1392. type,
  1393. text,
  1394. normalizedPosition: { x: normalizedX, y: normalizedY },
  1395. boundingBox: {
  1396. x: Math.round(bounds.x),
  1397. y: Math.round(bounds.y),
  1398. width: Math.round(bounds.width),
  1399. height: Math.round(bounds.height),
  1400. },
  1401. coordinateSpace: hasViewportCoordinates ? 'main-frame-viewport' : 'unavailable',
  1402. isInViewport,
  1403. isInteractable: !isDisabled,
  1404. attributes,
  1405. paintOrder: snapshotNode?.paintOrder ?? undefined,
  1406. ...(textEntryActivationSurface ? { inputStrategy: 'focused-keyboard' as const } : {}),
  1407. };
  1408. }
  1409. private getDescendantText(node: DOMNode): string {
  1410. let text = '';
  1411. const visit = (current: DOMNode): void => {
  1412. if (text.length >= 200) return;
  1413. if (current.nodeType === 3 && current.nodeValue) text += ` ${current.nodeValue}`;
  1414. for (const child of current.children ?? []) visit(child);
  1415. for (const shadowRoot of current.shadowRoots ?? []) visit(shadowRoot);
  1416. };
  1417. visit(node);
  1418. return text.replace(/\s+/gu, ' ').trim();
  1419. }
  1420. /**
  1421. * Generate a unique selector.
  1422. */
  1423. private generateSelector(node: DOMNode): string {
  1424. const tagName = node.nodeName?.toLowerCase() || 'div';
  1425. // Prefer id.
  1426. const id = this.getNodeAttribute(node, 'id');
  1427. if (id && /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(id)) {
  1428. return `#${id}`;
  1429. }
  1430. // Use data-testid.
  1431. const testId = this.getNodeAttribute(node, 'data-testid');
  1432. if (testId) {
  1433. return `[data-testid="${testId}"]`;
  1434. }
  1435. // Use aria-label.
  1436. const ariaLabel = this.getNodeAttribute(node, 'aria-label');
  1437. if (ariaLabel) {
  1438. return `${tagName}[aria-label="${ariaLabel.replace(/"/g, '\\"')}"]`;
  1439. }
  1440. // Use name.
  1441. const name = this.getNodeAttribute(node, 'name');
  1442. if (name) {
  1443. return `${tagName}[name="${name}"]`;
  1444. }
  1445. // Fall back to backendNodeId.
  1446. return `[data-backend-node-id="${node.backendNodeId}"]`;
  1447. }
  1448. /**
  1449. * Scan interactive elements using JavaScript as a fallback when CDP methods fail.
  1450. */
  1451. private async scanInteractiveElementsViaJS(
  1452. _viewportInfo: {
  1453. width: number;
  1454. height: number;
  1455. scrollX: number;
  1456. scrollY: number;
  1457. },
  1458. signal: AbortSignal,
  1459. ): Promise<InteractiveElement[]> {
  1460. try {
  1461. const elements = (await withTimeout(
  1462. (commandSignal) =>
  1463. this.transport.evaluate(
  1464. `
  1465. (function() {
  1466. const viewportWidth = window.innerWidth;
  1467. const viewportHeight = window.innerHeight;
  1468. const elements = [];
  1469. const processedElements = new WeakSet();
  1470. // Generate a unique selector.
  1471. function getUniqueSelector(el) {
  1472. if (el.id && /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(el.id)) {
  1473. const selector = '#' + CSS.escape(el.id);
  1474. if (document.querySelectorAll(selector).length === 1) return selector;
  1475. }
  1476. if (el.dataset.testid) {
  1477. const selector = '[data-testid="' + CSS.escape(el.dataset.testid) + '"]';
  1478. if (document.querySelectorAll(selector).length === 1) return selector;
  1479. }
  1480. const ariaLabel = el.getAttribute('aria-label');
  1481. if (ariaLabel) {
  1482. const tag = el.tagName.toLowerCase();
  1483. const selector = tag + '[aria-label="' + CSS.escape(ariaLabel) + '"]';
  1484. if (document.querySelectorAll(selector).length === 1) return selector;
  1485. }
  1486. if (el.name) {
  1487. const tag = el.tagName.toLowerCase();
  1488. const selector = tag + '[name="' + CSS.escape(el.name) + '"]';
  1489. if (document.querySelectorAll(selector).length === 1) return selector;
  1490. }
  1491. // Build a path selector.
  1492. const path = [];
  1493. let current = el;
  1494. while (current && current !== document.body && path.length < 4) {
  1495. let sel = current.tagName.toLowerCase();
  1496. if (current.id && /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(current.id)) {
  1497. path.unshift('#' + CSS.escape(current.id));
  1498. break;
  1499. }
  1500. const parent = current.parentElement;
  1501. if (parent) {
  1502. const siblings = Array.from(parent.children).filter(c => c.tagName === current.tagName);
  1503. if (siblings.length > 1) {
  1504. sel += ':nth-of-type(' + (siblings.indexOf(current) + 1) + ')';
  1505. }
  1506. }
  1507. path.unshift(sel);
  1508. current = current.parentElement;
  1509. }
  1510. return path.join(' > ');
  1511. }
  1512. // Get element text.
  1513. function getElementText(el) {
  1514. const ariaLabel = el.getAttribute('aria-label');
  1515. if (ariaLabel) return ariaLabel.trim().slice(0, 100);
  1516. const title = el.getAttribute('title');
  1517. if (title) return title.trim().slice(0, 100);
  1518. const placeholder = el.getAttribute('placeholder');
  1519. if (placeholder) return placeholder.trim().slice(0, 100);
  1520. const text = el.innerText?.trim();
  1521. if (text) return text.slice(0, 100);
  1522. if (el.tagName === 'IMG') return el.alt?.trim().slice(0, 100) || '';
  1523. return '';
  1524. }
  1525. // Detect nested form controls.
  1526. function hasFormControlDescendant(el, maxDepth = 2) {
  1527. if (maxDepth <= 0) return false;
  1528. for (const child of el.children) {
  1529. const tag = child.tagName.toLowerCase();
  1530. if (tag === 'input' || tag === 'select' || tag === 'textarea') return true;
  1531. if (hasFormControlDescendant(child, maxDepth - 1)) return true;
  1532. }
  1533. return false;
  1534. }
  1535. // Determine whether the element is interactive.
  1536. function isInteractive(el) {
  1537. const tag = el.tagName.toLowerCase();
  1538. if (tag === 'html' || tag === 'body') return { interactive: false };
  1539. // Natively interactive tags.
  1540. const interactiveTags = new Set([
  1541. 'button', 'input', 'select', 'textarea', 'a',
  1542. 'details', 'summary', 'option', 'optgroup', 'video', 'audio'
  1543. ]);
  1544. if (interactiveTags.has(tag)) return { interactive: true, type: tag };
  1545. // ARIA roles
  1546. const role = el.getAttribute('role');
  1547. const interactiveRoles = new Set([
  1548. 'button', 'link', 'menuitem', 'option', 'radio', 'checkbox',
  1549. 'tab', 'textbox', 'combobox', 'slider', 'spinbutton', 'search',
  1550. 'searchbox', 'switch', 'gridcell', 'row', 'cell', 'treeitem'
  1551. ]);
  1552. if (role && interactiveRoles.has(role)) return { interactive: true, type: role };
  1553. // contenteditable
  1554. if (el.getAttribute('contenteditable') === 'true') return { interactive: true, type: 'editable' };
  1555. // tabindex
  1556. const tabIndex = el.getAttribute('tabindex');
  1557. if (tabIndex !== null && tabIndex !== '-1') return { interactive: true, type: 'focusable' };
  1558. // Event attributes such as onclick.
  1559. if (el.hasAttribute('onclick') || el.onclick !== null) return { interactive: true, type: 'clickable' };
  1560. const eventAttrs = ['onmousedown', 'onmouseup', 'onkeydown', 'onkeyup', 'ontouchstart'];
  1561. for (const attr of eventAttrs) {
  1562. if (el.hasAttribute(attr)) return { interactive: true, type: 'clickable' };
  1563. }
  1564. // cursor: pointer
  1565. const style = window.getComputedStyle(el);
  1566. if (style.cursor === 'pointer') return { interactive: true, type: 'clickable' };
  1567. // label contains form controls.
  1568. if (tag === 'label') {
  1569. if (el.hasAttribute('for')) return { interactive: false };
  1570. if (hasFormControlDescendant(el, 2)) return { interactive: true, type: 'label' };
  1571. }
  1572. // span contains form controls.
  1573. if (tag === 'span' && hasFormControlDescendant(el, 2)) return { interactive: true, type: 'wrapper' };
  1574. // Interaction-state attributes.
  1575. const stateAttrs = ['aria-expanded', 'aria-pressed', 'aria-selected', 'aria-checked'];
  1576. for (const attr of stateAttrs) {
  1577. if (el.hasAttribute(attr)) return { interactive: true, type: 'stateful' };
  1578. }
  1579. return { interactive: false };
  1580. }
  1581. // Add the element.
  1582. function addElement(el, type, text) {
  1583. if (processedElements.has(el)) return false;
  1584. const rect = el.getBoundingClientRect();
  1585. if (rect.width === 0 || rect.height === 0) return false;
  1586. const style = window.getComputedStyle(el);
  1587. if (style.display === 'none' || style.visibility === 'hidden') return false;
  1588. if (parseFloat(style.opacity) === 0) return false;
  1589. processedElements.add(el);
  1590. elements.push({
  1591. index: elements.length,
  1592. selector: getUniqueSelector(el),
  1593. tag: el.tagName.toLowerCase(),
  1594. type: type,
  1595. text: text || getElementText(el),
  1596. normalizedPosition: {
  1597. x: Math.round(((rect.left + rect.width / 2) / viewportWidth) * 1000) / 1000,
  1598. y: Math.round(((rect.top + rect.height / 2) / viewportHeight) * 1000) / 1000
  1599. },
  1600. boundingBox: {
  1601. x: Math.round(rect.left),
  1602. y: Math.round(rect.top),
  1603. width: Math.round(rect.width),
  1604. height: Math.round(rect.height)
  1605. },
  1606. coordinateSpace: 'main-frame-viewport',
  1607. isInViewport: rect.top < viewportHeight && rect.bottom > 0 && rect.left < viewportWidth && rect.right > 0,
  1608. isInteractable: !el.disabled,
  1609. attributes: {}
  1610. });
  1611. return true;
  1612. }
  1613. // Traverse the DOM.
  1614. const walker = document.createTreeWalker(
  1615. document.body,
  1616. NodeFilter.SHOW_ELEMENT,
  1617. {
  1618. acceptNode: function(node) {
  1619. const style = window.getComputedStyle(node);
  1620. if (style.display === 'none' || style.visibility === 'hidden') {
  1621. return NodeFilter.FILTER_REJECT;
  1622. }
  1623. return NodeFilter.FILTER_ACCEPT;
  1624. }
  1625. }
  1626. );
  1627. let node;
  1628. while (node = walker.nextNode()) {
  1629. const result = isInteractive(node);
  1630. if (result.interactive) {
  1631. addElement(node, result.type, '');
  1632. }
  1633. }
  1634. return elements;
  1635. })()
  1636. `,
  1637. {
  1638. signal: commandSignal,
  1639. timeoutMs: BROWSER_TIMEOUTS.cdpCommand,
  1640. },
  1641. ),
  1642. BROWSER_TIMEOUTS.cdpCommand,
  1643. 'Browser JavaScript element scan',
  1644. { signal },
  1645. )) as JavaScriptFallbackElement[];
  1646. return Array.isArray(elements)
  1647. ? await this.resolveJavaScriptFallbackElements(elements, signal)
  1648. : [];
  1649. } catch (error) {
  1650. rethrowBrowserInterruption(error);
  1651. console.warn('Failed to scan interactive elements via JS:', error);
  1652. return [];
  1653. }
  1654. }
  1655. }