browser-semantic-tree.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import type {
  2. BrowserInteractiveElement,
  3. BrowserAXNode as AXNode,
  4. BrowserDOMNode as DOMNode,
  5. BrowserSnapshotNode as SnapshotNode,
  6. } from './browser-core-contracts.js';
  7. import { CanonicalNodeRegistry } from './browser-semantic-registry.js';
  8. export { CanonicalNodeRegistry } from './browser-semantic-registry.js';
  9. export { serializeSemanticTreePage } from './browser-semantic-serializer.js';
  10. export type SemanticNodeProvenance = 'dom' | 'snapshot' | 'ax';
  11. export interface CanonicalNode {
  12. key: string;
  13. frameId: string;
  14. backendNodeId?: number;
  15. dom?: DOMNode;
  16. layout?: SnapshotNode;
  17. ax?: AXNode;
  18. target?: BrowserInteractiveElement;
  19. domParentKey?: string;
  20. axParentKey?: string;
  21. semanticSourceKey?: string;
  22. provenance: Set<SemanticNodeProvenance>;
  23. }
  24. export interface SemanticNode {
  25. id: string;
  26. role: string;
  27. name?: string;
  28. text?: string;
  29. level?: number;
  30. state?: Record<string, boolean | string>;
  31. targetKey?: string;
  32. rect?: { x: number; y: number; width: number; height: number };
  33. coordinateSpace?: 'main-frame-viewport' | 'unavailable';
  34. inputStrategy?: 'focused-keyboard';
  35. provenance: SemanticNodeProvenance[];
  36. children: SemanticNode[];
  37. }
  38. export interface SemanticPageTree {
  39. version: 1;
  40. roots: SemanticNode[];
  41. stats: {
  42. canonicalNodeCount: number;
  43. semanticNodeCount: number;
  44. actionableCount: number;
  45. semanticOnlyCount: number;
  46. collapsedCount: number;
  47. };
  48. truncated: boolean;
  49. }
  50. export interface AgentSemanticNode {
  51. role: string;
  52. name?: string;
  53. text?: string;
  54. level?: number;
  55. state?: Record<string, boolean | string>;
  56. ref?: string;
  57. frame?: string;
  58. rect?: { x: number; y: number; width: number; height: number };
  59. actionable?: true;
  60. children?: AgentSemanticNode[];
  61. }
  62. export interface AgentSemanticTreePage {
  63. version: 1;
  64. roots: AgentSemanticNode[];
  65. truncated: boolean;
  66. }
  67. export interface SemanticTreeBuildInput {
  68. mainFrameId: string;
  69. domRoot?: DOMNode | null;
  70. axNodes?: readonly AXNode[];
  71. snapshotLookup?: ReadonlyMap<number, SnapshotNode>;
  72. interactiveElements?: readonly BrowserInteractiveElement[];
  73. }
  74. export interface SemanticTargetRef {
  75. ref: string;
  76. frameRef: string;
  77. }
  78. const STRUCTURAL_ROLES = new Set([
  79. 'document',
  80. 'main',
  81. 'navigation',
  82. 'region',
  83. 'article',
  84. 'form',
  85. 'dialog',
  86. 'alertdialog',
  87. 'heading',
  88. 'list',
  89. 'listitem',
  90. 'table',
  91. 'row',
  92. 'cell',
  93. 'columnheader',
  94. 'rowheader',
  95. 'group',
  96. ]);
  97. const TEXT_CONTEXT_ROLES = new Set([
  98. 'paragraph',
  99. 'label',
  100. 'caption',
  101. 'note',
  102. 'status',
  103. 'alert',
  104. 'description',
  105. ]);
  106. const DESCENDANT_TEXT_EXCLUDED_ROLES = new Set([
  107. 'document',
  108. 'main',
  109. 'navigation',
  110. 'region',
  111. 'article',
  112. 'form',
  113. 'dialog',
  114. 'alertdialog',
  115. 'list',
  116. 'table',
  117. 'row',
  118. 'group',
  119. ]);
  120. const TAG_ROLES: Record<string, string> = {
  121. '#document': 'document',
  122. main: 'main',
  123. nav: 'navigation',
  124. section: 'region',
  125. article: 'article',
  126. form: 'form',
  127. dialog: 'dialog',
  128. h1: 'heading',
  129. h2: 'heading',
  130. h3: 'heading',
  131. h4: 'heading',
  132. h5: 'heading',
  133. h6: 'heading',
  134. ul: 'list',
  135. ol: 'list',
  136. li: 'listitem',
  137. table: 'table',
  138. tr: 'row',
  139. td: 'cell',
  140. th: 'columnheader',
  141. p: 'paragraph',
  142. label: 'label',
  143. caption: 'caption',
  144. button: 'button',
  145. a: 'link',
  146. textarea: 'textbox',
  147. select: 'combobox',
  148. option: 'option',
  149. };
  150. const AX_STATE_PROPERTIES = new Set([
  151. 'busy',
  152. 'checked',
  153. 'disabled',
  154. 'editable',
  155. 'expanded',
  156. 'focusable',
  157. 'focused',
  158. 'invalid',
  159. 'multiline',
  160. 'multiselectable',
  161. 'pressed',
  162. 'readonly',
  163. 'required',
  164. 'selected',
  165. ]);
  166. function attributes(node: DOMNode | undefined): Record<string, string> {
  167. const values = node?.attributes ?? [];
  168. const result: Record<string, string> = {};
  169. for (let index = 0; index + 1 < values.length; index += 2) {
  170. const key = values[index];
  171. const value = values[index + 1];
  172. if (key) result[key.toLowerCase()] = value ?? '';
  173. }
  174. return result;
  175. }
  176. function cleanText(value: unknown, maxLength = 300): string {
  177. if (typeof value !== 'string') return '';
  178. return value.replace(/\s+/gu, ' ').trim().slice(0, maxLength);
  179. }
  180. function descendantText(node: DOMNode | undefined, maxLength = 300): string {
  181. if (!node) return '';
  182. let result = '';
  183. const visit = (current: DOMNode): void => {
  184. if (result.length >= maxLength) return;
  185. if (current.nodeType === 3 && current.nodeValue) {
  186. result += ` ${current.nodeValue}`;
  187. return;
  188. }
  189. for (const child of current.children ?? []) visit(child);
  190. for (const shadowRoot of current.shadowRoots ?? []) visit(shadowRoot);
  191. if (current.contentDocument) visit(current.contentDocument);
  192. };
  193. visit(node);
  194. return cleanText(result, maxLength);
  195. }
  196. function axPropertyValue(node: AXNode | undefined, name: string): unknown {
  197. return node?.properties?.find((property) => property.name === name)?.value?.value;
  198. }
  199. function semanticRole(node: CanonicalNode, semanticSource: CanonicalNode | undefined): string {
  200. const axRole = cleanText(
  201. semanticSource?.ax?.role?.value ?? node.ax?.role?.value,
  202. 80,
  203. ).toLowerCase();
  204. if (axRole && axRole !== 'none' && axRole !== 'generic') return axRole;
  205. const targetRole = cleanText(node.target?.type, 80).toLowerCase();
  206. if (targetRole && targetRole !== 'none' && targetRole !== 'generic') return targetRole;
  207. const domAttributes = attributes(semanticSource?.dom ?? node.dom);
  208. const explicitRole = cleanText(domAttributes.role, 80).toLowerCase();
  209. if (explicitRole && explicitRole !== 'none' && explicitRole !== 'generic') return explicitRole;
  210. const tag = (
  211. semanticSource?.dom?.nodeName ??
  212. node.dom?.nodeName ??
  213. node.target?.tag ??
  214. ''
  215. ).toLowerCase();
  216. if (tag === 'input') {
  217. const inputType = (domAttributes.type ?? node.target?.attributes.type ?? 'text').toLowerCase();
  218. if (inputType === 'checkbox' || inputType === 'radio') return inputType;
  219. if (inputType === 'submit' || inputType === 'button' || inputType === 'reset') return 'button';
  220. return 'textbox';
  221. }
  222. return TAG_ROLES[tag] ?? 'generic';
  223. }
  224. function semanticName(
  225. node: CanonicalNode,
  226. semanticSource: CanonicalNode | undefined,
  227. role: string,
  228. ): string {
  229. const source = semanticSource ?? node;
  230. const sourceAttributes = attributes(source.dom);
  231. const targetAttributes = node.target?.attributes ?? {};
  232. const mayUseDescendantText = !DESCENDANT_TEXT_EXCLUDED_ROLES.has(role);
  233. return cleanText(
  234. source.ax?.name?.value ??
  235. node.ax?.name?.value ??
  236. node.target?.text ??
  237. sourceAttributes['aria-label'] ??
  238. targetAttributes['aria-label'] ??
  239. sourceAttributes.title ??
  240. targetAttributes.title ??
  241. sourceAttributes.placeholder ??
  242. targetAttributes.placeholder ??
  243. sourceAttributes.alt ??
  244. targetAttributes.alt ??
  245. (mayUseDescendantText ? descendantText(source.dom ?? node.dom) : ''),
  246. );
  247. }
  248. function semanticDescription(
  249. node: CanonicalNode,
  250. semanticSource: CanonicalNode | undefined,
  251. ): string {
  252. return cleanText(semanticSource?.ax?.description?.value ?? node.ax?.description?.value);
  253. }
  254. function headingLevel(
  255. node: CanonicalNode,
  256. semanticSource: CanonicalNode | undefined,
  257. ): number | undefined {
  258. const axLevel = axPropertyValue(semanticSource?.ax ?? node.ax, 'level');
  259. if (typeof axLevel === 'number' && Number.isFinite(axLevel) && axLevel > 0) return axLevel;
  260. const tag = (semanticSource?.dom?.nodeName ?? node.dom?.nodeName ?? '').toLowerCase();
  261. const match = /^h([1-6])$/u.exec(tag);
  262. return match ? Number(match[1]) : undefined;
  263. }
  264. function semanticState(
  265. node: CanonicalNode,
  266. semanticSource: CanonicalNode | undefined,
  267. ): Record<string, boolean | string> | undefined {
  268. const state: Record<string, boolean | string> = {};
  269. const axNode = semanticSource?.ax ?? node.ax;
  270. for (const property of axNode?.properties ?? []) {
  271. if (!AX_STATE_PROPERTIES.has(property.name)) continue;
  272. const value = property.value?.value;
  273. if (typeof value === 'boolean' || typeof value === 'string') state[property.name] = value;
  274. }
  275. const targetAttributes = node.target?.attributes ?? {};
  276. for (const [attribute, key] of [
  277. ['aria-expanded', 'expanded'],
  278. ['aria-selected', 'selected'],
  279. ['aria-checked', 'checked'],
  280. ['aria-pressed', 'pressed'],
  281. ['aria-invalid', 'invalid'],
  282. ['aria-required', 'required'],
  283. ] as const) {
  284. const value = targetAttributes[attribute];
  285. if (value === 'true' || value === 'false') state[key] = value === 'true';
  286. else if (value) state[key] = value;
  287. }
  288. return Object.keys(state).length > 0 ? state : undefined;
  289. }
  290. function isMeaningfulNode(
  291. role: string,
  292. name: string,
  293. description: string,
  294. state: Record<string, boolean | string> | undefined,
  295. actionable: boolean,
  296. ): boolean {
  297. if (actionable) return true;
  298. if (STRUCTURAL_ROLES.has(role)) return role !== 'group' || Boolean(name);
  299. if (TEXT_CONTEXT_ROLES.has(role)) return Boolean(name || description);
  300. return Boolean(state) && role !== 'generic';
  301. }
  302. function isSemanticallyHidden(node: CanonicalNode): boolean {
  303. if (node.target) return false;
  304. const domAttributes = attributes(node.dom);
  305. if ('hidden' in domAttributes || domAttributes['aria-hidden'] === 'true') return true;
  306. if (
  307. node.dom?.nodeName?.toLowerCase() === 'input' &&
  308. domAttributes.type?.toLowerCase() === 'hidden'
  309. ) {
  310. return true;
  311. }
  312. const styles = node.layout?.computedStyles;
  313. return (
  314. styles?.display === 'none' ||
  315. styles?.visibility === 'hidden' ||
  316. Number.parseFloat(styles?.opacity ?? '1') <= 0
  317. );
  318. }
  319. export function buildSemanticPageTree(input: SemanticTreeBuildInput): SemanticPageTree {
  320. const registry = new CanonicalNodeRegistry(input.mainFrameId);
  321. if (input.domRoot) registry.addDOMTree(input.domRoot);
  322. registry.addSnapshotRecords(input.snapshotLookup ?? new Map());
  323. registry.addAXTree(input.axNodes ?? []);
  324. registry.addInteractiveElements(input.interactiveElements ?? []);
  325. const canonicalNodes = registry.values();
  326. const aliasedSemanticSources = new Set(
  327. canonicalNodes
  328. .map((node) => node.semanticSourceKey)
  329. .filter((key): key is string => typeof key === 'string'),
  330. );
  331. const semanticByKey = new Map<string, SemanticNode>();
  332. let collapsedCount = 0;
  333. for (const canonical of canonicalNodes) {
  334. if (canonical.dom?.nodeType === 3 || canonical.dom?.nodeType === 8) continue;
  335. if (canonical.ax?.ignored && !canonical.target) continue;
  336. if (isSemanticallyHidden(canonical)) continue;
  337. if (aliasedSemanticSources.has(canonical.key) && !canonical.target) continue;
  338. const semanticSource = canonical.semanticSourceKey
  339. ? registry.get(canonical.semanticSourceKey)
  340. : undefined;
  341. const role = semanticRole(canonical, semanticSource);
  342. const name = semanticName(canonical, semanticSource, role);
  343. const description = semanticDescription(canonical, semanticSource);
  344. const state = semanticState(canonical, semanticSource);
  345. if (!isMeaningfulNode(role, name, description, state, Boolean(canonical.target))) {
  346. collapsedCount += 1;
  347. continue;
  348. }
  349. const level = role === 'heading' ? headingLevel(canonical, semanticSource) : undefined;
  350. const provenance = new Set(canonical.provenance);
  351. for (const source of semanticSource?.provenance ?? []) provenance.add(source);
  352. semanticByKey.set(canonical.key, {
  353. id: canonical.key,
  354. role,
  355. ...(name ? { name } : {}),
  356. ...(description ? { text: description } : {}),
  357. ...(level ? { level } : {}),
  358. ...(state ? { state } : {}),
  359. ...(canonical.target
  360. ? {
  361. targetKey: canonical.key,
  362. rect: { ...canonical.target.boundingBox },
  363. coordinateSpace:
  364. canonical.target.coordinateSpace === 'unavailable'
  365. ? ('unavailable' as const)
  366. : ('main-frame-viewport' as const),
  367. ...(canonical.target.inputStrategy
  368. ? { inputStrategy: canonical.target.inputStrategy }
  369. : {}),
  370. }
  371. : {}),
  372. provenance: [...provenance],
  373. children: [],
  374. });
  375. }
  376. const roots: SemanticNode[] = [];
  377. const nearestSemanticParent = (canonical: CanonicalNode): SemanticNode | undefined => {
  378. const visited = new Set<string>();
  379. // DOM ancestry preserves concrete region/form ownership. AX remains the fallback for
  380. // semantic-only nodes and relationships that have no DOM-backed parent.
  381. let parentKey = canonical.domParentKey ?? canonical.axParentKey;
  382. while (parentKey && !visited.has(parentKey)) {
  383. visited.add(parentKey);
  384. const semantic = semanticByKey.get(parentKey);
  385. if (semantic) return semantic;
  386. const parent = registry.get(parentKey);
  387. parentKey = parent?.domParentKey ?? parent?.axParentKey;
  388. }
  389. return undefined;
  390. };
  391. for (const canonical of canonicalNodes) {
  392. const semantic = semanticByKey.get(canonical.key);
  393. if (!semantic) continue;
  394. const parent = nearestSemanticParent(canonical);
  395. if (parent && parent !== semantic) parent.children.push(semantic);
  396. else roots.push(semantic);
  397. }
  398. const semanticNodeCount = semanticByKey.size;
  399. const actionableCount = [...semanticByKey.values()].filter((node) => node.targetKey).length;
  400. return {
  401. version: 1,
  402. roots,
  403. stats: {
  404. canonicalNodeCount: canonicalNodes.length,
  405. semanticNodeCount,
  406. actionableCount,
  407. semanticOnlyCount: semanticNodeCount - actionableCount,
  408. collapsedCount,
  409. },
  410. truncated: false,
  411. };
  412. }