codex-browser-use 4.8.2 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/locators.js CHANGED
@@ -20,11 +20,47 @@ const SHARED_DOM_HELPERS = `
20
20
  if (!el || el.nodeType !== 1) return false;
21
21
  const win = el.ownerDocument?.defaultView || window;
22
22
  const style = win.getComputedStyle(el);
23
- if (!style || style.display === "none" || style.visibility === "hidden" || style.opacity === "0") return false;
23
+ const isCustomControl = el.tagName === "INPUT" && ["checkbox", "radio", "file"].includes((el.getAttribute("type") || "").toLowerCase());
24
+ if (!style || style.display === "none" || style.visibility === "hidden" || (style.opacity === "0" && !isCustomControl)) return false;
24
25
  const rect = el.getBoundingClientRect();
25
26
  return rect.width > 0 && rect.height > 0;
26
27
  };
27
28
 
29
+ const collectShadowRoots = (root) => {
30
+ const roots = [];
31
+ const seen = new Set();
32
+ const walk = (scope) => {
33
+ if (!scope || seen.has(scope)) return;
34
+ seen.add(scope);
35
+ const doc = scope.ownerDocument || (scope.nodeType === 9 ? scope : document);
36
+ if (typeof doc.createTreeWalker === "function" && typeof NodeFilter !== "undefined") {
37
+ const tw = doc.createTreeWalker(scope, NodeFilter.SHOW_ELEMENT);
38
+ for (let cur = scope.nodeType === 1 ? scope : tw.nextNode(); cur; cur = tw.nextNode()) {
39
+ if (cur.shadowRoot && !seen.has(cur.shadowRoot)) {
40
+ roots.push(cur.shadowRoot);
41
+ walk(cur.shadowRoot);
42
+ }
43
+ }
44
+ return;
45
+ }
46
+ const stack = [scope];
47
+ while (stack.length > 0) {
48
+ const cur = stack.pop();
49
+ if (!cur) continue;
50
+ if (cur.nodeType === 1 && cur.shadowRoot && !seen.has(cur.shadowRoot)) {
51
+ roots.push(cur.shadowRoot);
52
+ stack.push(cur.shadowRoot);
53
+ }
54
+ const children = cur.children || (cur.documentElement ? [cur.documentElement] : null);
55
+ if (children) {
56
+ for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]);
57
+ }
58
+ }
59
+ };
60
+ walk(root);
61
+ return roots;
62
+ };
63
+
28
64
  const deepElements = (root) => {
29
65
  const out = [];
30
66
  const stack = [root];
@@ -52,22 +88,18 @@ const SHARED_DOM_HELPERS = `
52
88
  const querySelectorAllDeep = (root, css) => {
53
89
  const matches = [];
54
90
  const seen = new Set();
55
- const visitRoot = (scope) => {
91
+ const runScope = (scope, isRoot) => {
56
92
  try {
57
93
  for (const el of scope.querySelectorAll(css)) {
58
94
  if (!seen.has(el)) { seen.add(el); matches.push(el); }
59
95
  }
60
96
  } catch (err) {
61
- if (scope === root) throw err;
62
- }
63
- for (const el of deepElements(scope)) {
64
- if (el.shadowRoot && !seen.has(el.shadowRoot)) {
65
- seen.add(el.shadowRoot);
66
- visitRoot(el.shadowRoot);
67
- }
97
+ if (isRoot) throw err;
68
98
  }
69
99
  };
70
- visitRoot(root);
100
+ runScope(root, true);
101
+ const shadows = collectShadowRoots(root);
102
+ for (let i = 0; i < shadows.length; i++) runScope(shadows[i], false);
71
103
  return matches;
72
104
  };
73
105
 
@@ -305,6 +337,21 @@ const SHARED_LOCATOR_RESOLVER = `
305
337
  cur += ch;
306
338
  continue;
307
339
  }
340
+ if (ch === "/" && /(?:text|name|has-text|has-not-text|label|placeholder|alt|title)=$/.test(cur)) {
341
+ cur += ch;
342
+ let rxEsc = false;
343
+ while (++i < input.length) {
344
+ const rch = input[i];
345
+ cur += rch;
346
+ if (rxEsc) { rxEsc = false; continue; }
347
+ if (rch === "\\\\") { rxEsc = true; continue; }
348
+ if (rch === "/") break;
349
+ }
350
+ while (i + 1 < input.length && /[dgimsuvy]/.test(input[i + 1])) {
351
+ cur += input[++i];
352
+ }
353
+ continue;
354
+ }
308
355
  if (ch === "(") {
309
356
  parenDepth++;
310
357
  cur += ch;
@@ -329,19 +376,109 @@ const SHARED_LOCATOR_RESOLVER = `
329
376
 
330
377
  const unquote = (s) => {
331
378
  const t = s.trim();
332
- if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
333
- return t.slice(1, -1);
379
+ if (t.startsWith('"') && t.endsWith('"')) {
380
+ try { return JSON.parse(t); } catch { return t.slice(1, -1); }
381
+ }
382
+ if (t.startsWith("'") && t.endsWith("'")) {
383
+ return t.slice(1, -1).replace(/\\\\(['\\\\])/g, "$1");
334
384
  }
335
385
  return t;
336
386
  };
337
387
 
388
+ const parseValueMatcher = (rawSpec, defaultExactWhenUnflagged) => {
389
+ const trimmed = String(rawSpec || "").trim();
390
+ const flagMatch = /^(.*?)\\[exact=(true|false)\\]$/.exec(trimmed);
391
+ const hasExactFlag = Boolean(flagMatch);
392
+ const explicitExact = flagMatch?.[2] === "true";
393
+ const body = (flagMatch ? flagMatch[1] : trimmed).trim();
394
+ const regex = parseRegexLiteral(body);
395
+ if (regex) {
396
+ return {
397
+ regex,
398
+ exact: false,
399
+ target: "",
400
+ targetLower: "",
401
+ test: (val) => regex.test(String(val || "")),
402
+ };
403
+ }
404
+ const hadQuotes = (body.startsWith('"') && body.endsWith('"')) || (body.startsWith("'") && body.endsWith("'"));
405
+ const target = unquote(body);
406
+ const targetLower = target.toLowerCase();
407
+ const exact = hasExactFlag ? explicitExact : (hadQuotes || defaultExactWhenUnflagged);
408
+ return {
409
+ regex: null,
410
+ exact,
411
+ target,
412
+ targetLower,
413
+ test: (val) => {
414
+ const s = String(val || "").trim();
415
+ return exact ? s === target : s.toLowerCase().includes(targetLower);
416
+ },
417
+ };
418
+ };
419
+
420
+ const ROLE_HINT_SELECTORS = {
421
+ button: 'button,summary,input[type="button"],input[type="submit"],input[type="reset"],input[type="image"],[role="button"]',
422
+ link: 'a[href],area[href],[role="link"]',
423
+ textbox: 'textarea,input:not([type]),input[type="text"],input[type="email"],input[type="password"],input[type="search"],input[type="tel"],input[type="url"],[role="textbox"]',
424
+ checkbox: 'input[type="checkbox"],[role="checkbox"]',
425
+ radio: 'input[type="radio"],[role="radio"]',
426
+ combobox: 'select,[role="combobox"]',
427
+ listbox: 'select,[role="listbox"]',
428
+ option: 'option,[role="option"]',
429
+ heading: 'h1,h2,h3,h4,h5,h6,[role="heading"]',
430
+ tab: '[role="tab"]',
431
+ listitem: 'li,[role="listitem"]',
432
+ row: 'tr,[role="row"]',
433
+ cell: 'td,[role="cell"]',
434
+ columnheader: 'th,[role="columnheader"]',
435
+ img: 'img,[role="img"]',
436
+ dialog: 'dialog,[role="dialog"]',
437
+ navigation: 'nav,[role="navigation"]',
438
+ main: 'main,[role="main"]',
439
+ form: 'form,[role="form"]',
440
+ menuitem: '[role="menuitem"]',
441
+ switch: '[role="switch"]',
442
+ slider: 'input[type="range"],[role="slider"]',
443
+ spinbutton: 'input[type="number"],[role="spinbutton"]',
444
+ };
445
+
338
446
  const querySingle = (scope, step) => {
339
447
  if (step.startsWith("text=")) {
340
- const rawText = step.slice(5).trim();
341
- const regex = parseRegexLiteral(rawText);
342
- const exact = !regex && ((rawText.startsWith('"') && rawText.endsWith('"')) || (rawText.startsWith("'") && rawText.endsWith("'")));
343
- const target = regex ? null : unquote(rawText);
344
- const matchesText = (val) => regex ? regex.test(val) : (exact ? val === target : val.includes(target));
448
+ const matcher = parseValueMatcher(step.slice(5), false);
449
+ const { regex, exact, target, targetLower } = matcher;
450
+ const matchesText = (val) => regex ? regex.test(val) : (exact ? val === target : val.toLowerCase().includes(targetLower));
451
+ const leafTextMatches = [];
452
+ const doc = scope.ownerDocument || (scope.nodeType === 9 ? scope : document);
453
+ if ((regex || target !== "") && typeof doc.createTreeWalker === "function" && typeof NodeFilter !== "undefined") {
454
+ const candidateSet = new Set();
455
+ const collectTextMatches = (treeScope) => {
456
+ const tw = doc.createTreeWalker(treeScope, NodeFilter.SHOW_TEXT);
457
+ for (let tn = tw.nextNode(); tn; tn = tw.nextNode()) {
458
+ const raw = tn.nodeValue;
459
+ if (!raw || !raw.trim()) continue;
460
+ if (!regex && !(exact ? raw.includes(target) : raw.toLowerCase().includes(targetLower))) continue;
461
+ let el = tn.parentElement;
462
+ for (let hops = 0; el && el.nodeType === 1 && hops < 4; hops++, el = el.parentElement) {
463
+ candidateSet.add(el);
464
+ if (el === treeScope) break;
465
+ }
466
+ }
467
+ };
468
+ collectTextMatches(scope);
469
+ const shadows = collectShadowRoots(scope);
470
+ for (let i = 0; i < shadows.length; i++) collectTextMatches(shadows[i]);
471
+ for (const el of candidateSet) {
472
+ const val = (el.innerText || el.textContent || "").replace(/\\s+/g, " ").trim();
473
+ if (matchesText(val)) leafTextMatches.push(el);
474
+ }
475
+ if (leafTextMatches.length > 0 || !regex) {
476
+ return leafTextMatches.filter((el) => !Array.from(el.children || []).some((child) => {
477
+ const val = (child.innerText || child.textContent || "").replace(/\\s+/g, " ").trim();
478
+ return matchesText(val);
479
+ }));
480
+ }
481
+ }
345
482
  const all = deepElements(scope).filter((el) => {
346
483
  const val = (el.innerText || el.textContent || "").replace(/\\s+/g, " ").trim();
347
484
  return matchesText(val);
@@ -352,14 +489,50 @@ const SHARED_LOCATOR_RESOLVER = `
352
489
  }));
353
490
  }
354
491
  if (step.startsWith("role=")) {
355
- const match = /^role=([a-zA-Z0-9_-]+)(?:\\[name=(?:"([^"]*)"|'([^']*)'|(\\/(?:\\\\.|[^/])+\\/[dgimsuvy]*))\\])?(?:\\[exact=(true|false)\\])?$/.exec(step);
356
- if (!match) throw new Error("Invalid role locator: " + step);
357
- const role = match[1].toLowerCase();
358
- const nameRegex = match[4] ? parseRegexLiteral(match[4]) : null;
359
- const name = nameRegex ? null : (match[2] !== undefined ? match[2] : match[3]);
360
- const exact = match[5] !== "false";
361
- return deepElements(scope).filter((el) => {
492
+ const roleHead = /^([a-zA-Z0-9_-]+)/.exec(step.slice(5));
493
+ if (!roleHead) throw new Error("Invalid role locator: " + step);
494
+ const role = roleHead[1].toLowerCase();
495
+ let rest = step.slice(5 + roleHead[1].length);
496
+ const attrs = Object.create(null);
497
+ while (rest.length > 0) {
498
+ const m = /^\\[([a-zA-Z0-9_-]+)=("(?:[^"\\\\]|\\\\.)*"|'(?:[^'\\\\]|\\\\.)*'|\\/(?:\\\\.|[^/])+\\/[dgimsuvy]*|[^\\]]+)\\]/.exec(rest);
499
+ if (!m) throw new Error("Invalid role locator: " + step);
500
+ attrs[m[1]] = m[2];
501
+ rest = rest.slice(m[0].length);
502
+ }
503
+ const nameRegex = attrs.name ? parseRegexLiteral(attrs.name) : null;
504
+ const name = !nameRegex && attrs.name !== undefined ? unquote(attrs.name) : undefined;
505
+ const exact = attrs.exact !== "false";
506
+ const hintSel = ROLE_HINT_SELECTORS[role];
507
+ const candidates = hintSel ? querySelectorAllDeep(scope, hintSel) : deepElements(scope);
508
+ return candidates.filter((el) => {
362
509
  if (implicitRoleOf(el) !== role) return false;
510
+ if (attrs.level !== undefined) {
511
+ const tagLvl = /^H([1-6])$/.exec(el.tagName || "");
512
+ const lvl = el.getAttribute("aria-level") || (tagLvl ? tagLvl[1] : null);
513
+ if (String(lvl) !== String(attrs.level)) return false;
514
+ }
515
+ if (attrs.checked !== undefined) {
516
+ const ariaC = el.getAttribute("aria-checked");
517
+ const actualC = ariaC !== null ? ariaC === "true" : Boolean(el.checked);
518
+ if (String(actualC) !== attrs.checked) return false;
519
+ }
520
+ if (attrs.selected !== undefined) {
521
+ const actualS = el.getAttribute("aria-selected") === "true" || Boolean(el.selected);
522
+ if (String(actualS) !== attrs.selected) return false;
523
+ }
524
+ if (attrs.expanded !== undefined) {
525
+ const actualE = el.getAttribute("aria-expanded") === "true" || (el.tagName === "DETAILS" && el.open);
526
+ if (String(actualE) !== attrs.expanded) return false;
527
+ }
528
+ if (attrs.pressed !== undefined) {
529
+ const actualP = el.getAttribute("aria-pressed") === "true";
530
+ if (String(actualP) !== attrs.pressed) return false;
531
+ }
532
+ if (attrs.disabled !== undefined) {
533
+ const actualD = isDisabledEl(el);
534
+ if (String(actualD) !== attrs.disabled) return false;
535
+ }
363
536
  if (nameRegex) return nameRegex.test(accessibleNameOf(el));
364
537
  if (name === undefined) return true;
365
538
  const actual = accessibleNameOf(el);
@@ -372,12 +545,33 @@ const SHARED_LOCATOR_RESOLVER = `
372
545
  return querySelectorAllDeep(scope, '[data-testid="' + escaped + '"],[data-test-id="' + escaped + '"],[data-test="' + escaped + '"]');
373
546
  }
374
547
  if (step.startsWith("label=")) {
375
- const wanted = unquote(step.slice(6));
376
- return deepElements(scope).filter((el) => labelTextFor(el) === wanted || (el.getAttribute("aria-label") || "").trim() === wanted);
548
+ const matcher = parseValueMatcher(step.slice(6), true);
549
+ const out = [];
550
+ const seen = new Set();
551
+ for (const el of querySelectorAllDeep(scope, '[aria-label],[aria-labelledby],input,select,textarea,button,[role="textbox"],[role="combobox"]')) {
552
+ if (!seen.has(el) && (matcher.test(labelTextFor(el)) || matcher.test(el.getAttribute("aria-label") || ""))) {
553
+ seen.add(el);
554
+ out.push(el);
555
+ }
556
+ }
557
+ if (out.length > 0) return out;
558
+ return deepElements(scope).filter((el) => matcher.test(labelTextFor(el)) || matcher.test(el.getAttribute("aria-label") || ""));
377
559
  }
378
560
  if (step.startsWith("placeholder=")) {
379
- const wanted = unquote(step.slice(12));
380
- return querySelectorAllDeep(scope, '[placeholder="' + CSS.escape(wanted) + '"]');
561
+ const rawSpec = step.slice(12);
562
+ const matcher = parseValueMatcher(rawSpec, true);
563
+ if (!matcher.regex && matcher.exact) {
564
+ return querySelectorAllDeep(scope, '[placeholder="' + CSS.escape(matcher.target) + '"]');
565
+ }
566
+ return querySelectorAllDeep(scope, "[placeholder]").filter((el) => matcher.test(el.getAttribute("placeholder") || ""));
567
+ }
568
+ if (step.startsWith("alt=")) {
569
+ const matcher = parseValueMatcher(step.slice(4), false);
570
+ return querySelectorAllDeep(scope, "[alt]").filter((el) => matcher.test(el.getAttribute("alt") || ""));
571
+ }
572
+ if (step.startsWith("title=")) {
573
+ const matcher = parseValueMatcher(step.slice(6), false);
574
+ return querySelectorAllDeep(scope, "[title]").filter((el) => matcher.test(el.getAttribute("title") || ""));
381
575
  }
382
576
  return querySelectorAllDeep(scope, step.startsWith("css=") ? step.slice(4) : step);
383
577
  };
@@ -837,6 +1031,8 @@ const SHARED_RUNNER_CORE = `
837
1031
  const control = element instanceof HTMLInputElement || element instanceof HTMLButtonElement ||
838
1032
  element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement ? element : null;
839
1033
  const accepted = new Set([element, ...(control?.labels ? Array.from(control.labels) : [])]);
1034
+ const rootInteractive = element.closest?.('a,button,input,select,textarea,summary,[role="button"],[role="link"],[role="checkbox"],[role="radio"],[role="switch"],[role="menuitem"],[role="tab"],[role="option"]');
1035
+ if (rootInteractive) accepted.add(rootInteractive);
840
1036
  const matchesTarget = (node) => {
841
1037
  for (let cur = node; cur; cur = cur.parentNode || cur.host) {
842
1038
  if (accepted.has(cur)) return true;
@@ -853,17 +1049,24 @@ const SHARED_RUNNER_CORE = `
853
1049
  { x: boxRight - dx, y: boxBottom - dy },
854
1050
  ];
855
1051
  let chosen = null;
856
- let firstHitTag = null;
1052
+ let firstHitEl = null;
857
1053
  for (const pt of points) {
858
1054
  const hit = elementFromPointDeep(doc, pt.x, pt.y);
859
- if (firstHitTag === null) firstHitTag = hit?.tagName?.toLowerCase() ?? null;
1055
+ if (firstHitEl === null) firstHitEl = hit ?? null;
860
1056
  if (hit && matchesTarget(hit)) {
861
1057
  chosen = pt;
862
1058
  break;
863
1059
  }
864
1060
  }
1061
+ const firstHitTag = firstHitEl?.tagName?.toLowerCase() ?? null;
865
1062
  if (!force && !chosen) {
866
- return fail("Locator element is covered by <" + (firstHitTag || "unknown") + ">: " + raw, "covered", true);
1063
+ const hitTag = firstHitTag || "unknown";
1064
+ const hitId = firstHitEl?.id ? "#" + firstHitEl.id : "";
1065
+ const hitCls = typeof firstHitEl?.className === "string" && firstHitEl.className.trim()
1066
+ ? "." + firstHitEl.className.trim().split(/\\s+/).slice(0, 2).join(".")
1067
+ : "";
1068
+ const hitRole = firstHitEl?.getAttribute?.("role") ? "[role=" + firstHitEl.getAttribute("role") + "]" : "";
1069
+ return fail("Locator element is covered by <" + hitTag + hitId + hitCls + hitRole + ">: " + raw, "covered", true);
867
1070
  }
868
1071
 
869
1072
  const pt = chosen || { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
@@ -1146,11 +1349,31 @@ export function hitTestFunctionDeclaration() {
1146
1349
  const oy = vv?.offsetTop ?? 0;
1147
1350
  const vw = vv?.width ?? win.innerWidth;
1148
1351
  const vh = vv?.height ?? win.innerHeight;
1149
- const left = Math.max(rect.left, ox);
1150
- const right = Math.min(rect.right, ox + vw);
1151
- const top = Math.max(rect.top, oy);
1152
- const bottom = Math.min(rect.bottom, oy + vh);
1153
- if (right <= left || bottom <= top) return { offscreen: true, width: rect.width, height: rect.height };
1352
+ let left = Math.max(rect.left, ox);
1353
+ let right = Math.min(rect.right, ox + vw);
1354
+ let top = Math.max(rect.top, oy);
1355
+ let bottom = Math.min(rect.bottom, oy + vh);
1356
+ if (right <= left || bottom <= top) {
1357
+ if (typeof el.scrollIntoView === "function") {
1358
+ el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
1359
+ const scrolledRect = el.getBoundingClientRect();
1360
+ if (scrolledRect && scrolledRect.width > 0 && scrolledRect.height > 0) {
1361
+ rect = scrolledRect;
1362
+ const nvv = win.visualViewport;
1363
+ const nox = nvv?.offsetLeft ?? 0;
1364
+ const noy = nvv?.offsetTop ?? 0;
1365
+ const nvw = nvv?.width ?? win.innerWidth;
1366
+ const nvh = nvv?.height ?? win.innerHeight;
1367
+ left = Math.max(rect.left, nox);
1368
+ right = Math.min(rect.right, nox + nvw);
1369
+ top = Math.max(rect.top, noy);
1370
+ bottom = Math.min(rect.bottom, noy + nvh);
1371
+ }
1372
+ }
1373
+ if (right <= left || bottom <= top) {
1374
+ return { offscreen: true, width: rect.width, height: rect.height };
1375
+ }
1376
+ }
1154
1377
 
1155
1378
  const control = el instanceof HTMLInputElement || el instanceof HTMLButtonElement ||
1156
1379
  el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement ? el : null;