turbo-browser-mcp 0.7.3 → 0.7.4

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.
@@ -33,6 +33,10 @@ const LOCAL_UI_RE =
33
33
 
34
34
  const APPLY_LABEL_RE = /^apply(\s+now)?(?![\p{L}\p{N}_])/iu;
35
35
 
36
+ // Non-submitting buttons that merely open an inline reply/edit form (e.g. dev.to Reply/Edit buttons that load a form via XHR POST).
37
+ const EDITOR_OPEN_LABEL_RE =
38
+ /^(reply(\s+to\b.*)?|edit(\s+(comment|post|reply|article|message|profile|bio))?|write\s+a\s+reply|add\s+a?\s*comment|leave\s+a?\s*comment|trả\s*lời|chỉnh\s*sửa|sửa)(?![\p{L}\p{N}_])/iu;
39
+
36
40
  // smart_fill_form submitButtons: never list these, even when type=submit.
37
41
  const SUBMIT_CAND_NEG_RE =
38
42
  /^(clear|reset|remove|delete|cancel|close|discard|xóa|xoá|hủy|huỷ|đóng|bỏ\s+qua)(?![\p{L}\p{N}_])/iu;
@@ -3875,7 +3879,8 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
3875
3879
  const isCustomCombobox = (el) =>
3876
3880
  Boolean(
3877
3881
  el &&
3878
- (el.getAttribute('role') || '').toLowerCase() === 'combobox' &&
3882
+ ((el.getAttribute('role') || '').toLowerCase() === 'combobox' ||
3883
+ (el.getAttribute('aria-haspopup') || '').toLowerCase() === 'listbox') &&
3879
3884
  !['SELECT'].includes(el.tagName) &&
3880
3885
  !el.isContentEditable
3881
3886
  );
@@ -4876,7 +4881,7 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
4876
4881
 
4877
4882
  const hasSelToken = (el, idx) => getSelOrder(el, idx) >= 0;
4878
4883
 
4879
- const combos = queryAllDeep(document, '[role="combobox"]').filter((el) => {
4884
+ const combos = queryAllDeep(document, '[role="combobox"], [aria-haspopup="listbox"]').filter((el) => {
4880
4885
  if (el.tagName === 'SELECT') return false;
4881
4886
  if (!fieldSpec.all && !fieldSpec._again && el.getAttribute('data-tbm-combo-claimed') === '1') return false;
4882
4887
  if (
@@ -4897,7 +4902,17 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
4897
4902
  }
4898
4903
  const st = getComputedStyle(el);
4899
4904
  const r = el.getBoundingClientRect();
4900
- return st.display !== 'none' && st.visibility !== 'hidden' && Number(st.opacity) !== 0 && r.width > 0 && r.height > 0;
4905
+ if (st.display === 'none' || st.visibility === 'hidden') return false;
4906
+ // react-select dummy/search inputs can have opacity 0 or 1px width inside a visible control wrapper.
4907
+ if (el.tagName === 'INPUT' && (Number(st.opacity) === 0 || r.width === 0 || r.height === 0)) {
4908
+ const ctrl = el.closest('[class*="control" i], [class*="select" i], [class*="combobox" i]');
4909
+ if (ctrl) {
4910
+ const cr = ctrl.getBoundingClientRect();
4911
+ const cst = getComputedStyle(ctrl);
4912
+ return cst.display !== 'none' && cst.visibility !== 'hidden' && cr.width > 0 && cr.height > 0;
4913
+ }
4914
+ }
4915
+ return Number(st.opacity) !== 0 && r.width > 0 && r.height > 0;
4901
4916
  });
4902
4917
 
4903
4918
  const keys = Array.isArray(fieldSpec.keys) ? fieldSpec.keys : fieldSpec.keys ? [fieldSpec.keys] : [];
@@ -4980,19 +4995,58 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
4980
4995
  return composedText(refNode, true) || refNode?.innerText || '';
4981
4996
  })
4982
4997
  .join(' ');
4998
+ const ownLabels = el.labels && el.labels.length > 0
4999
+ ? [...el.labels].map((l) => composedText(l) || l.innerText).join(' ')
5000
+ : '';
5001
+ const nearComboLabel = (() => {
5002
+ const COMBO_FIELD_SEL =
5003
+ 'input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="image"]):not([type="reset"]), textarea, select, [role="combobox"], [aria-haspopup="listbox"]';
5004
+ let cur = el;
5005
+ let prevChild = el;
5006
+ for (let up = 0; up < 4 && cur.parentElement; up++) {
5007
+ cur = cur.parentElement;
5008
+ let fields = 0;
5009
+ try {
5010
+ const all = [...cur.querySelectorAll(COMBO_FIELD_SEL)];
5011
+ const hasComboRole = all.some((n) => (n.getAttribute('role') || '').toLowerCase() === 'combobox');
5012
+ // Count a combobox wrapper, its inner input, and its companion listbox toggle button as one control.
5013
+ fields = all.filter(
5014
+ (n) =>
5015
+ !(hasComboRole && n.tagName === 'BUTTON' && (n.getAttribute('aria-haspopup') || '').toLowerCase() === 'listbox' && (n.getAttribute('role') || '').toLowerCase() !== 'combobox') &&
5016
+ !all.some((other) => other !== n && other.contains(n))
5017
+ ).length;
5018
+ } catch {}
5019
+ if (fields > 1) break;
5020
+ for (const c of cur.querySelectorAll('label, [class*="label" i]')) {
5021
+ if (c.contains(el)) continue;
5022
+ const forId = c.getAttribute?.('for');
5023
+ if (forId && forId !== el.id && document.getElementById(forId) && !cur.contains(document.getElementById(forId))) continue;
5024
+ const t = clean(c.innerText || c.textContent).replace(/\s*[*\uFF0A]+$/, '');
5025
+ if (t && t.length <= 80 && /[\p{L}\p{N}]/u.test(t)) return t;
5026
+ }
5027
+ const sib = prevChild.previousElementSibling;
5028
+ if (sib && !sib.matches(COMBO_FIELD_SEL) && !sib.querySelector(COMBO_FIELD_SEL)) {
5029
+ const t = clean(sib.innerText || sib.textContent).replace(/\s*[*\uFF0A]+$/, '');
5030
+ if (t && t.length <= 60 && /[\p{L}\p{N}]/u.test(t)) return t;
5031
+ }
5032
+ prevChild = cur;
5033
+ }
5034
+ return '';
5035
+ })();
4983
5036
  const prev = el.previousElementSibling;
4984
5037
  const prevTxt =
4985
5038
  prev && !prev.matches('button, input, select, textarea, a, [role="button"], [role="combobox"]')
4986
5039
  ? (composedText(prev) || prev.innerText)
4987
5040
  : '';
4988
- const blk = closestComposed(el, '[class*="field"], [class*="Field"], .form-group, [role="listitem"]');
5041
+ const blk = closestComposed(el, '[class*="field"], [class*="Field"], .form-group, [role="listitem"], [class*="select" i], [class*="combobox" i], [class*="autocomplete" i]');
4989
5042
  let blkTxt = '';
4990
5043
  let blkLblTxt = '';
4991
5044
  if (blk) {
4992
- const siblings = queryAllDeep(
5045
+ const rawSibs = queryAllDeep(
4993
5046
  blk,
4994
- 'input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]):not([type="file"]), textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="combobox"]'
5047
+ 'input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]):not([type="file"]), textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="combobox"], [aria-haspopup="listbox"]'
4995
5048
  );
5049
+ const siblings = rawSibs.filter((n) => !rawSibs.some((other) => other !== n && other.contains(n)));
4996
5050
  if (siblings.length <= 1) {
4997
5051
  blkTxt = composedText(blk, false, el) || composedText(blk) || blk.innerText;
4998
5052
  const innerLbl = blk.querySelector('label');
@@ -5009,6 +5063,8 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
5009
5063
  el.getAttribute('name'),
5010
5064
  el.getAttribute('id'),
5011
5065
  lblBy,
5066
+ ownLabels,
5067
+ nearComboLabel,
5012
5068
  wrapLblClean,
5013
5069
  hostAttr,
5014
5070
  prevTxt,
@@ -5176,7 +5232,7 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
5176
5232
  const optionScopes = frameInfo.isMain ? [frameInfo.frame] : [frameInfo.frame, page.mainFrame()];
5177
5233
  const stopBeforeSubmit = spec.stopBeforeSubmit !== false;
5178
5234
 
5179
- const clickWidgetSafely = async (loc) => {
5235
+ const clickWidgetSafely = async (loc, isComboTrigger = false) => {
5180
5236
  await withFrameSubmitGuard(frameInfo.frame, async () => {
5181
5237
  if (stopBeforeSubmit) {
5182
5238
  await loc
@@ -5192,11 +5248,68 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
5192
5248
  })
5193
5249
  .catch(() => {});
5194
5250
  }
5195
- await loc.click({ timeout: 2500 });
5251
+ try {
5252
+ await loc.click({ timeout: isComboTrigger ? 1200 : 2500 });
5253
+ } catch (err) {
5254
+ if (!isComboTrigger) throw err;
5255
+ // In react-select / Headless UI / MUI, the inner <input role="combobox"> may be covered by a placeholder
5256
+ // or value container, or have a companion toggle button: click the control wrapper / toggle button and focus.
5257
+ await loc.evaluate((el) => {
5258
+ const ctrl =
5259
+ el.closest?.('[class*="control" i], [role="combobox"], [class*="select" i], [class*="combobox" i], [class*="autocomplete" i]') ||
5260
+ el.parentElement ||
5261
+ el;
5262
+ const toggleBtn =
5263
+ ctrl !== el && ctrl.querySelector?.('button[aria-haspopup="listbox"], button[aria-label*="open" i], [class*="indicator" i]');
5264
+ const target = toggleBtn || ctrl;
5265
+ for (const evt of ['mousedown', 'mouseup', 'click']) {
5266
+ target.dispatchEvent(new MouseEvent(evt, { bubbles: true, cancelable: true, view: window }));
5267
+ }
5268
+ if (typeof el.focus === 'function') el.focus();
5269
+ });
5270
+ }
5196
5271
  });
5197
5272
  };
5198
5273
 
5199
- const tryPickEnabledOption = async () => {
5274
+ const verifySelfInputCommit = async () => {
5275
+ return comboLoc
5276
+ .evaluate((el, wanted) => {
5277
+ const clean = (v) => String(v || '').replace(/\s+/g, ' ').trim().toLowerCase();
5278
+ const w = clean(wanted);
5279
+ if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA') return true;
5280
+ if (el.getAttribute('aria-expanded') === 'false') return true;
5281
+ const attrs = [el.getAttribute('data-value'), el.getAttribute('data-selected'), el.getAttribute('aria-valuetext')];
5282
+ if (attrs.some((v) => clean(v) === w)) return true;
5283
+ const doc = el.ownerDocument || document;
5284
+ const listId = el.getAttribute('aria-controls') || el.getAttribute('aria-owns');
5285
+ const listEl = listId ? doc.getElementById(listId) : null;
5286
+ if (listId && (!listEl || listEl.hidden || getComputedStyle(listEl).display === 'none')) return true;
5287
+ const scope = el.form || doc;
5288
+ for (const h of scope.querySelectorAll('input[type="hidden"], input:not([role="combobox"])')) {
5289
+ if (h !== el && clean(h.value) === w) return true;
5290
+ }
5291
+ for (const opt of doc.querySelectorAll('[role="option"], [cmdk-item], [data-radix-collection-item], [class*="option" i]')) {
5292
+ if (
5293
+ (opt.getAttribute('aria-selected') === 'true' ||
5294
+ opt.getAttribute('data-state') === 'checked' ||
5295
+ opt.getAttribute('data-selected') === 'true' ||
5296
+ /\bselected\b/i.test(opt.className || '')) &&
5297
+ clean(opt.textContent).includes(w)
5298
+ ) {
5299
+ return true;
5300
+ }
5301
+ }
5302
+ const visibleOptions = [...doc.querySelectorAll('[role="option"], [cmdk-item], [data-radix-collection-item]')].filter((o) => {
5303
+ const r = o.getBoundingClientRect();
5304
+ const st = getComputedStyle(o);
5305
+ return r.width > 0 && r.height > 0 && st.display !== 'none' && st.visibility !== 'hidden';
5306
+ });
5307
+ return visibleOptions.length === 0;
5308
+ }, comboWanted)
5309
+ .catch(() => true);
5310
+ };
5311
+
5312
+ const tryPickEnabledOption = async (requireCommitCheck = false) => {
5200
5313
  let sawDisabledMatch = false;
5201
5314
  let anyVisibleOption = false;
5202
5315
  for (const scope of optionScopes) {
@@ -5237,9 +5350,78 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
5237
5350
  continue;
5238
5351
  }
5239
5352
  await clickWidgetSafely(nth);
5353
+ if (requireCommitCheck && !(await verifySelfInputCommit())) {
5354
+ return { clicked: false, sawDisabledMatch, anyVisibleOption };
5355
+ }
5240
5356
  return { clicked: true, sawDisabledMatch, anyVisibleOption };
5241
5357
  }
5242
5358
  }
5359
+
5360
+ // Fallback for custom portaled combobox items (cmdk, Radix collection items, react-select v3/v4, or ul[role=listbox] > li without role=option).
5361
+ const customMatch = await scope
5362
+ .evaluate((wanted) => {
5363
+ const clean = (s) => String(s || '').replace(/\s+/g, ' ').trim();
5364
+ const wLower = clean(wanted).toLowerCase();
5365
+ if (!wLower) return { hit: false, anyVis: false, disabled: false };
5366
+ for (const old of document.querySelectorAll('[data-tbm-portal-opt]')) {
5367
+ old.removeAttribute('data-tbm-portal-opt');
5368
+ }
5369
+ const CUSTOM_OPT_SEL =
5370
+ '[cmdk-item], [data-radix-collection-item], [class*="react-select__option"], [class*="-option"]:not(select), [role="listbox"] > li, [role="listbox"] > button, [role="listbox"] > div[tabindex], [role="menu"] [role="menuitem"], [role="menu"] [role="menuitemradio"]';
5371
+ const nodes = [...document.querySelectorAll(CUSTOM_OPT_SEL)];
5372
+ let anyVis = false;
5373
+ let best = null;
5374
+ let bestTier = 0;
5375
+ let sawDis = false;
5376
+ for (const node of nodes) {
5377
+ if (node.getAttribute('role') === 'combobox') continue;
5378
+ const r = node.getBoundingClientRect();
5379
+ const st = getComputedStyle(node);
5380
+ if (r.width <= 0 || r.height <= 0 || st.display === 'none' || st.visibility === 'hidden' || Number(st.opacity) === 0) continue;
5381
+ anyVis = true;
5382
+ const txt = clean(node.innerText || node.textContent);
5383
+ const val = clean(node.getAttribute('data-value') || '');
5384
+ const tLower = txt.toLowerCase();
5385
+ const vLower = val.toLowerCase();
5386
+ let tier = 0;
5387
+ if (tLower === wLower || vLower === wLower) tier = 3;
5388
+ else if (tLower.startsWith(wLower) || vLower.startsWith(wLower)) tier = 2;
5389
+ else if (tLower.includes(wLower) || vLower.includes(wLower)) tier = 1;
5390
+ if (tier === 0) continue;
5391
+ const dis = Boolean(
5392
+ node.disabled ||
5393
+ node.getAttribute('aria-disabled') === 'true' ||
5394
+ node.getAttribute('data-disabled') === 'true' ||
5395
+ node.hasAttribute('data-disabled') && node.getAttribute('data-disabled') !== 'false' ||
5396
+ node.closest('[aria-disabled="true"]')
5397
+ );
5398
+ if (dis) {
5399
+ sawDis = true;
5400
+ continue;
5401
+ }
5402
+ if (tier > bestTier) {
5403
+ bestTier = tier;
5404
+ best = node;
5405
+ if (tier === 3) break;
5406
+ }
5407
+ }
5408
+ if (best) {
5409
+ best.setAttribute('data-tbm-portal-opt', '1');
5410
+ return { hit: true, anyVis: true, disabled: false };
5411
+ }
5412
+ return { hit: false, anyVis, disabled: sawDis };
5413
+ }, comboWanted)
5414
+ .catch(() => ({ hit: false, anyVis: false, disabled: false }));
5415
+ if (customMatch.anyVis) anyVisibleOption = true;
5416
+ if (customMatch.disabled) sawDisabledMatch = true;
5417
+ if (customMatch.hit) {
5418
+ const optLoc = scope.locator('[data-tbm-portal-opt="1"]').first();
5419
+ await clickWidgetSafely(optLoc);
5420
+ if (requireCommitCheck && !(await verifySelfInputCommit())) {
5421
+ return { clicked: false, sawDisabledMatch, anyVisibleOption };
5422
+ }
5423
+ return { clicked: true, sawDisabledMatch, anyVisibleOption };
5424
+ }
5243
5425
  }
5244
5426
  return { clicked: false, sawDisabledMatch, anyVisibleOption };
5245
5427
  };
@@ -5257,12 +5439,13 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
5257
5439
  } else if (preCheck.sawDisabledMatch) {
5258
5440
  // Target option is still disabled in the already-open dropdown
5259
5441
  } else if (!preCheck.anyVisibleOption) {
5260
- await clickWidgetSafely(comboLoc);
5442
+ await clickWidgetSafely(comboLoc, true);
5261
5443
  }
5262
5444
  } else {
5263
- await clickWidgetSafely(comboLoc);
5445
+ await clickWidgetSafely(comboLoc, true);
5264
5446
  }
5265
5447
 
5448
+ // Wait briefly for options to appear; if a search input is already ready in the portal or trigger, move to typing quickly.
5266
5449
  if (!clickedOption) {
5267
5450
  for (let attempt = 0; attempt < 18; attempt++) {
5268
5451
  const pollRes = await tryPickEnabledOption();
@@ -5275,39 +5458,133 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
5275
5458
  await comboLoc.evaluate((el) => el.setAttribute('data-tbm-combo-open', '1')).catch(() => {});
5276
5459
  break;
5277
5460
  }
5278
- // The list is open but the option is not rendered (paged, windowed or filtered list):
5279
- // stop polling and go to the search box / keyboard steps below.
5280
- if (pollRes.anyVisibleOption && attempt >= 2) break;
5461
+ if (attempt >= 2) {
5462
+ if (pollRes.anyVisibleOption) break;
5463
+ const hasSearchBoxReady = await comboLoc
5464
+ .evaluate((el) => {
5465
+ const doc = el.ownerDocument || document;
5466
+ if (el.matches?.('input, textarea') && !el.readOnly && !el.disabled) return true;
5467
+ if (doc.activeElement && doc.activeElement !== el && doc.activeElement.matches?.('input, textarea')) return true;
5468
+ return Boolean(doc.querySelector('[cmdk-input], [role="dialog"] input, [data-radix-popper-content-wrapper] input, [role="listbox"] input'));
5469
+ })
5470
+ .catch(() => false);
5471
+ if (hasSearchBoxReady) break;
5472
+ }
5281
5473
  await page.waitForTimeout(35);
5282
5474
  }
5283
5475
  }
5284
5476
 
5285
5477
  if (!clickedOption) {
5286
- // Portaled lists with their own search box: the box is focused on open, or sits next to
5287
- // the listbox named by aria-controls. Type the wanted text there, then pick the option.
5288
- const searchHandle = await comboLoc.evaluateHandle((el) => {
5289
- const isText = (n) => Boolean(n && n !== el && n.matches?.(
5290
- 'input:not([type]), input[type="text"], input[type="search"], textarea') && !n.readOnly && !n.disabled);
5291
- const doc = el.ownerDocument;
5292
- if (isText(doc.activeElement)) return doc.activeElement;
5293
- const id = el.getAttribute('aria-controls') || el.getAttribute('aria-owns');
5294
- let box = id ? doc.getElementById(id) : null;
5295
- for (let up = 0; box && up < 3; up++, box = box.parentElement) {
5296
- const input = [...box.querySelectorAll('input, textarea')].find(isText);
5297
- if (input) return input;
5298
- }
5299
- return null;
5300
- }).catch(() => null);
5478
+ // Portaled searchable comboboxes (Radix/cmdk, MUI Autocomplete, Headless UI Combobox, react-select):
5479
+ // locate the search input in the portal, aria-controls container, combobox wrapper, or trigger itself,
5480
+ // type the filter query, and click the matching option in the portal.
5481
+ const searchHandle = await comboLoc
5482
+ .evaluateHandle((el) => {
5483
+ const isEditableInput = (n) => {
5484
+ if (!n || !n.matches?.('input:not([type]), input[type="text"], input[type="search"], input[role="combobox"], [cmdk-input], textarea')) {
5485
+ return false;
5486
+ }
5487
+ if (n.readOnly || n.disabled || n.getAttribute('aria-disabled') === 'true') return false;
5488
+ const st = getComputedStyle(n);
5489
+ if (st.display === 'none' || st.visibility === 'hidden') return false;
5490
+ const r = n.getBoundingClientRect();
5491
+ if (r.width === 0 || r.height === 0) {
5492
+ const ctrl = n.closest('[class*="control" i], [class*="select" i], [class*="combobox" i]');
5493
+ if (!ctrl) return false;
5494
+ const cr = ctrl.getBoundingClientRect();
5495
+ return cr.width > 0 && cr.height > 0;
5496
+ }
5497
+ return true;
5498
+ };
5499
+ const doc = el.ownerDocument || document;
5500
+ // 1. Focused search input inside the newly opened portal
5501
+ if (doc.activeElement && doc.activeElement !== el && isEditableInput(doc.activeElement)) {
5502
+ return doc.activeElement;
5503
+ }
5504
+ // 2. Input linked via aria-controls / aria-owns on el or its wrapper
5505
+ const ctrlSource = el.hasAttribute('aria-controls') || el.hasAttribute('aria-owns')
5506
+ ? el
5507
+ : el.closest?.('[aria-controls], [aria-owns]') || el.querySelector?.('[aria-controls], [aria-owns]');
5508
+ const id = ctrlSource ? (ctrlSource.getAttribute('aria-controls') || ctrlSource.getAttribute('aria-owns')) : '';
5509
+ let box = id ? doc.getElementById(id) : null;
5510
+ for (let up = 0; box && box !== doc.body && box.tagName !== 'FORM' && up < 4; up++, box = box.parentElement) {
5511
+ const input = [...box.querySelectorAll('input, textarea')].find((n) => n !== el && isEditableInput(n));
5512
+ if (input) return input;
5513
+ }
5514
+ // 3. Input inside el itself or its immediate combobox control wrapper (react-select, Headless UI, MUI)
5515
+ if (!el.matches?.('input, textarea')) {
5516
+ const innerInput = [...el.querySelectorAll('input, textarea')].find(isEditableInput);
5517
+ if (innerInput) return innerInput;
5518
+ const ctrlWrap = el.closest?.('[role="combobox"], [class*="select" i], [class*="combobox" i], [class*="autocomplete" i]');
5519
+ if (ctrlWrap) {
5520
+ const wrapInput = [...ctrlWrap.querySelectorAll('input, textarea')].find(isEditableInput);
5521
+ if (wrapInput) return wrapInput;
5522
+ }
5523
+ }
5524
+ // 4. Input inside any visible open portal / popover / dialog / listbox container
5525
+ const PORTAL_SEL =
5526
+ '[data-radix-popper-content-wrapper], [cmdk-root], [role="dialog"], [data-headlessui-state*="open" i], [class*="portal" i], [class*="popover" i], [class*="popper" i], [class*="dropdown" i], [class*="menu" i]';
5527
+ for (const portal of doc.querySelectorAll(PORTAL_SEL)) {
5528
+ if (portal.contains(el)) continue;
5529
+ const pr = portal.getBoundingClientRect();
5530
+ const pst = getComputedStyle(portal);
5531
+ if (pr.width <= 0 || pr.height <= 0 || pst.display === 'none' || pst.visibility === 'hidden') continue;
5532
+ const hasListOrCmdk = Boolean(
5533
+ portal.querySelector('[role="listbox"], [role="option"], [cmdk-list], [cmdk-item], [cmdk-input], [data-radix-collection-item], [class*="option" i]')
5534
+ );
5535
+ if (!hasListOrCmdk) continue;
5536
+ const portalInput = [...portal.querySelectorAll('input, textarea')].find(isEditableInput);
5537
+ if (portalInput) return portalInput;
5538
+ }
5539
+ // 5. Any visible [cmdk-input] or search input adjacent to a visible [role="listbox"]
5540
+ for (const lb of doc.querySelectorAll('[role="listbox"], [cmdk-list]')) {
5541
+ const lr = lb.getBoundingClientRect();
5542
+ const lst = getComputedStyle(lb);
5543
+ if (lr.width <= 0 || lr.height <= 0 || lst.display === 'none' || lst.visibility === 'hidden') continue;
5544
+ let anc = lb.parentElement;
5545
+ for (let up = 0; anc && anc !== doc.body && anc.tagName !== 'FORM' && up < 3; up++, anc = anc.parentElement) {
5546
+ const adjInput = [...anc.querySelectorAll('input, textarea')].find((n) => n !== el && isEditableInput(n));
5547
+ if (adjInput) return adjInput;
5548
+ }
5549
+ }
5550
+ // 6. Trigger el itself is a searchable <input role="combobox"> (MUI Autocomplete, Headless UI, react-select)
5551
+ if (isEditableInput(el)) return el;
5552
+ return null;
5553
+ })
5554
+ .catch(() => null);
5301
5555
  const searchEl = searchHandle?.asElement?.() || null;
5302
5556
  if (searchEl) {
5303
- await searchEl.fill(comboWanted).catch(() => {});
5557
+ const isSelfInput = await comboLoc.evaluate((el, s) => el === s, searchEl).catch(() => false);
5558
+ await searchEl.focus().catch(() => {});
5559
+ await searchEl.fill(comboWanted).catch(async () => {
5560
+ await searchEl.evaluate((inp, val) => {
5561
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
5562
+ if (setter) setter.call(inp, val);
5563
+ else inp.value = val;
5564
+ inp.dispatchEvent(new InputEvent('input', { bubbles: true, data: val, inputType: 'insertText' }));
5565
+ inp.dispatchEvent(new Event('change', { bubbles: true }));
5566
+ }, comboWanted).catch(() => {});
5567
+ });
5304
5568
  for (let attempt = 0; attempt < 18 && !clickedOption; attempt++) {
5305
- const pollRes = await tryPickEnabledOption();
5569
+ const pollRes = await tryPickEnabledOption(isSelfInput);
5306
5570
  if (pollRes.clicked) {
5307
5571
  clickedOption = true;
5308
5572
  await comboLoc.evaluate((el) => el.removeAttribute('data-tbm-combo-open')).catch(() => {});
5309
- } else if (pollRes.sawDisabledMatch) {
5310
5573
  break;
5574
+ }
5575
+ if (pollRes.sawDisabledMatch) {
5576
+ break;
5577
+ }
5578
+ // If .fill() did not trigger a keystroke-based filter after 3 polls, type with real key events once.
5579
+ if (attempt === 3) {
5580
+ await searchEl.focus().catch(() => {});
5581
+ await searchEl.evaluate((inp) => {
5582
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
5583
+ if (setter) setter.call(inp, '');
5584
+ else inp.value = '';
5585
+ inp.dispatchEvent(new Event('input', { bubbles: true }));
5586
+ }).catch(() => {});
5587
+ await page.keyboard.type(comboWanted).catch(() => {});
5311
5588
  } else {
5312
5589
  await page.waitForTimeout(35);
5313
5590
  }
@@ -5316,6 +5593,50 @@ export async function smartFillForm(page, spec = {}, previousLinesSet = null) {
5316
5593
  await searchHandle?.dispose?.().catch(() => {});
5317
5594
  }
5318
5595
 
5596
+ if (!clickedOption) {
5597
+ // Scrollable virtualized listbox (e.g. react-window / MUI virtualized 200+ options mounted on scroll).
5598
+ const hasScrollableListbox = await page
5599
+ .evaluate(() => {
5600
+ for (const lb of document.querySelectorAll('[role="listbox"], [cmdk-list]')) {
5601
+ const r = lb.getBoundingClientRect();
5602
+ if (r.width <= 0 || r.height <= 0) continue;
5603
+ const candidates = [lb, ...lb.querySelectorAll('*')];
5604
+ for (const c of candidates) {
5605
+ if (c.scrollHeight > c.clientHeight + 16) return true;
5606
+ }
5607
+ }
5608
+ return false;
5609
+ })
5610
+ .catch(() => false);
5611
+ if (hasScrollableListbox) {
5612
+ for (let step = 0; step < 45 && !clickedOption; step++) {
5613
+ const moved = await page
5614
+ .evaluate(() => {
5615
+ for (const lb of document.querySelectorAll('[role="listbox"], [cmdk-list]')) {
5616
+ const r = lb.getBoundingClientRect();
5617
+ if (r.width <= 0 || r.height <= 0) continue;
5618
+ const scroller = [lb, ...lb.querySelectorAll('*')].find((c) => c.scrollHeight > c.clientHeight + 16);
5619
+ if (!scroller) continue;
5620
+ const before = scroller.scrollTop;
5621
+ scroller.scrollTop = before + Math.max(140, Math.floor(scroller.clientHeight * 0.9));
5622
+ scroller.dispatchEvent(new Event('scroll', { bubbles: true }));
5623
+ return scroller.scrollTop !== before;
5624
+ }
5625
+ return false;
5626
+ })
5627
+ .catch(() => false);
5628
+ await page.waitForTimeout(15);
5629
+ const pollRes = await tryPickEnabledOption();
5630
+ if (pollRes.clicked) {
5631
+ clickedOption = true;
5632
+ await comboLoc.evaluate((el) => el.removeAttribute('data-tbm-combo-open')).catch(() => {});
5633
+ break;
5634
+ }
5635
+ if (!moved) break;
5636
+ }
5637
+ }
5638
+ }
5639
+
5319
5640
  if (!clickedOption) {
5320
5641
  // Windowed lists may have no matching DOM option until keyboard navigation.
5321
5642
  const inner = comboLoc.locator('input:not([type="hidden"]), textarea').first();
@@ -5900,118 +6221,397 @@ function watchActionNavigation(page, timeout) {
5900
6221
  }
5901
6222
 
5902
6223
  /**
5903
- * Scroll-and-collect for virtualized feeds: reads innerText of every element matching `selector`, scrolls (the
5904
- * nearest scrollable ancestor of the first match, else the window), repeats, and returns the unique items.
5905
- * One round trip; the loop runs inside the page. Dedupe is by a cheap text hash.
6224
+ * Scroll-and-collect for virtualized feeds and multi-page lists/tables: reads matching elements (`selector`),
6225
+ * optionally scrolls `scrolls` times per page, optionally clicks a pagination control (`nextText` / `nextSelector`,
6226
+ * up to `maxPages` pages, stopping when Next disappears or is disabled), and returns deduplicated items.
5906
6227
  */
5907
6228
  export async function collectItems(page, step = {}) {
5908
6229
  const selector = String(step.selector || '');
5909
6230
  if (!selector) throw new Error('collect requires selector.');
5910
- const scrolls = Math.min(60, Math.max(0, Number.isFinite(Number(step.scrolls)) ? Number(step.scrolls) : 5));
6231
+ const nextSelector = step.nextSelector ? String(step.nextSelector).trim() : '';
6232
+ const nextText = step.nextText ? String(step.nextText).trim() : '';
6233
+ const hasPagination = Boolean(nextSelector || nextText || Number(step.maxPages) > 1);
6234
+ const maxPages = hasPagination ? Math.min(50, Math.max(1, Number(step.maxPages) || 10)) : 1;
6235
+ const scrolls = Math.min(
6236
+ 60,
6237
+ Math.max(0, Number.isFinite(Number(step.scrolls)) ? Number(step.scrolls) : hasPagination ? 0 : 5)
6238
+ );
5911
6239
  const waitMs = Math.min(5000, Math.max(0, Number.isFinite(Number(step.waitMs)) ? Number(step.waitMs) : 400));
5912
6240
  const maxItems = Math.min(2000, Math.max(1, Number(step.maxItems) || 100));
5913
6241
  const maxChars = Math.max(200, Number(step.maxChars) || 8000);
5914
- const fields = Array.isArray(step.fields) ? step.fields.filter((f) => f === 'text' || f === 'href' || f === 'id') : [];
6242
+ const rawFields = Array.isArray(step.fields) ? step.fields.map((f) => String(f || '').trim()).filter(Boolean) : [];
6243
+ const tableJsonMode = step.format === 'table_json';
5915
6244
  const sub = String(step.itemSelector || step.textSelector || '');
5916
6245
  const t0 = Date.now();
5917
- const r = await page.evaluate(
5918
- async ({ sel, sub, scrolls: nScrolls, waitMs: wait, maxItems: cap, maxChars: charCap, fields: want }) => {
5919
- const hash = (s) => {
5920
- let h = 5381;
5921
- for (let i = 0; i < s.length; i++) h = ((h * 33) ^ s.charCodeAt(i)) | 0;
5922
- return `${s.length}:${h}`;
5923
- };
5924
- const seen = new Set(); // per call only: nothing survives between collect calls or navigations
5925
- const items = [];
5926
- let chars = 0;
5927
- let full = false;
5928
- let matched = 0;
5929
- const read = () => {
5930
- let added = 0;
5931
- const els = document.querySelectorAll(sel);
5932
- matched = Math.max(matched, els.length);
5933
- for (const el of els) {
5934
- if (full) break;
5935
- const tEl = sub ? el.querySelector(sub) : el;
5936
- if (!tEl) continue;
5937
- const text = (tEl.innerText || '').replace(/[ \t]+/g, ' ').replace(/\n\s*\n+/g, '\n').trim().slice(0, 1500);
5938
- if (!text) continue;
5939
- const key = hash(text.replace(/\s+/g, ' ').trim());
5940
- if (seen.has(key)) continue;
5941
- seen.add(key);
5942
- let item = text;
5943
- if (want.length) {
5944
- item = {};
5945
- for (const f of want) {
5946
- if (f === 'text') item.text = text;
5947
- else if (f === 'id') {
5948
- const v = el.id || el.getAttribute('data-id');
5949
- if (v) item.id = v;
5950
- } else if (f === 'href') {
5951
- // textSelector on (or inside) a link: that link's URL, not the row's first anchor (an upvote link).
5952
- const own = sub ? tEl.closest('a[href]') : null;
5953
- const v = (own || (el.matches('a[href]') ? el : el.querySelector('a[href]')))?.href;
5954
- if (v) item.href = v;
5955
- }
5956
- }
5957
- if (!Object.keys(item).length) item = text;
6246
+
6247
+ const seenKeys = new Set();
6248
+ const allItems = [];
6249
+ let totalChars = 0;
6250
+ let totalScrolls = 0;
6251
+ let full = false;
6252
+ let maxMatchedOnAnyPage = 0;
6253
+ let pagesVisited = 0;
6254
+
6255
+ for (let pageNum = 1; pageNum <= maxPages; pageNum++) {
6256
+ const pageRes = await page.evaluate(
6257
+ async ({
6258
+ sel,
6259
+ sub,
6260
+ scrolls: nScrolls,
6261
+ waitMs: wait,
6262
+ maxItems: cap,
6263
+ maxChars: charCap,
6264
+ fields: want,
6265
+ tableJson,
6266
+ seenArr,
6267
+ curCount,
6268
+ curChars,
6269
+ }) => {
6270
+ const clean = (s) => String(s || '').replace(/\s+/g, ' ').trim();
6271
+ const parseCellVal = (raw) => {
6272
+ const s = clean(raw);
6273
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(s)) {
6274
+ const n = Number(s);
6275
+ if (Number.isFinite(n)) return n;
5958
6276
  }
6277
+ return s;
6278
+ };
6279
+ const tableHeadersFor = (tbl) => {
6280
+ if (!tbl) return [];
6281
+ const headRows = [...tbl.querySelectorAll('thead tr')];
6282
+ const hdrTr = headRows.length > 0 ? headRows[headRows.length - 1] : tbl.querySelector('tr');
6283
+ if (!hdrTr) return [];
6284
+ const cells = [...hdrTr.children].filter((c) => c.tagName === 'TH' || c.tagName === 'TD');
6285
+ if (headRows.length === 0 && !cells.some((c) => c.tagName === 'TH')) return [];
6286
+ return cells.map((c, idx) => clean(c.innerText || c.textContent) || `col${idx + 1}`);
6287
+ };
6288
+ const isBuiltInFieldsOnly =
6289
+ want.length > 0 && want.every((f) => f === 'text' || f === 'href' || f === 'id');
6290
+ const hash = (s) => {
6291
+ let h = 5381;
6292
+ for (let i = 0; i < s.length; i++) h = ((h * 33) ^ s.charCodeAt(i)) | 0;
6293
+ return `${s.length}:${h}`;
6294
+ };
6295
+ const seen = new Set(seenArr);
6296
+ const pageItems = [];
6297
+ const newKeys = [];
6298
+ let count = curCount;
6299
+ let chars = curChars;
6300
+ let isFull = false;
6301
+ let matched = 0;
6302
+
6303
+ const addCandidate = (item, keyStr) => {
6304
+ if (isFull || !keyStr) return false;
6305
+ const key = hash(keyStr);
6306
+ if (seen.has(key)) return false;
5959
6307
  const size = typeof item === 'string' ? item.length : JSON.stringify(item).length;
5960
- if (items.length >= cap || chars + size > charCap) {
5961
- full = true;
5962
- break;
6308
+ if (count >= cap || chars + size > charCap) {
6309
+ isFull = true;
6310
+ return false;
5963
6311
  }
5964
- items.push(item);
6312
+ seen.add(key);
6313
+ newKeys.push(key);
6314
+ pageItems.push(item);
6315
+ count++;
5965
6316
  chars += size;
5966
- added++;
5967
- }
5968
- return added;
5969
- };
5970
- const scroller = () => {
5971
- const first = document.querySelector(sel);
5972
- for (let p = first?.parentElement; p && p !== document.body; p = p.parentElement) {
5973
- const st = getComputedStyle(p);
5974
- if (/(auto|scroll)/.test(st.overflowY) && p.scrollHeight > p.clientHeight + 4) return p;
5975
- }
5976
- return null;
5977
- };
5978
- read();
5979
- if (!matched) {
5980
- // Rows rendered a beat after domcontentloaded: poll briefly before declaring the page empty.
5981
- for (let k = 0; k < 6 && !matched; k++) {
5982
- await new Promise((res) => setTimeout(res, 150));
5983
- read();
6317
+ return true;
6318
+ };
6319
+
6320
+ const read = () => {
6321
+ let added = 0;
6322
+ const rawEls = [...document.querySelectorAll(sel)];
6323
+ const els = [];
6324
+ for (const el of rawEls) {
6325
+ if (el.tagName === 'TABLE') {
6326
+ const bodyRows = [...el.querySelectorAll('tbody tr')];
6327
+ if (bodyRows.length > 0) els.push(...bodyRows);
6328
+ else els.push(...[...el.querySelectorAll('tr')].filter((tr) => !tr.closest('thead, tfoot')));
6329
+ } else {
6330
+ els.push(el);
6331
+ }
6332
+ }
6333
+ matched = Math.max(matched, els.length);
6334
+ for (const el of els) {
6335
+ if (isFull) break;
6336
+ const isTableRow = el.tagName === 'TR';
6337
+ if (isTableRow && (tableJson || (want.length > 0 && !isBuiltInFieldsOnly))) {
6338
+ if (el.closest('thead, tfoot')) continue;
6339
+ const directCells = [...el.children].filter((c) => c.tagName === 'TD' || c.tagName === 'TH');
6340
+ if (directCells.length === 0 || directCells.every((c) => c.tagName === 'TH')) continue;
6341
+ const tbl = el.closest('table');
6342
+ const headers = tableHeadersFor(tbl);
6343
+ const rowObj = {};
6344
+ directCells.forEach((cell, idx) => {
6345
+ const colName = headers[idx] || want[idx] || `col${idx + 1}`;
6346
+ rowObj[colName] = parseCellVal(cell.innerText || cell.textContent);
6347
+ });
6348
+ let outObj = rowObj;
6349
+ if (want.length > 0 && !tableJson) {
6350
+ outObj = {};
6351
+ for (const f of want) {
6352
+ const hitKey = Object.keys(rowObj).find((k) => k.toLowerCase() === f.toLowerCase());
6353
+ if (hitKey !== undefined) outObj[hitKey] = rowObj[hitKey];
6354
+ }
6355
+ if (Object.keys(outObj).length === 0) outObj = rowObj;
6356
+ }
6357
+ if (addCandidate(outObj, JSON.stringify(outObj))) added++;
6358
+ continue;
6359
+ }
6360
+
6361
+ const tEl = sub ? el.querySelector(sub) : el;
6362
+ if (!tEl) continue;
6363
+ const text = (tEl.innerText || '')
6364
+ .replace(/[ \t]+/g, ' ')
6365
+ .replace(/\n\s*\n+/g, '\n')
6366
+ .trim()
6367
+ .slice(0, 1500);
6368
+ if (!text) continue;
6369
+ const keyStr = text.replace(/\s+/g, ' ').trim();
6370
+ let item = text;
6371
+ if (want.length) {
6372
+ item = {};
6373
+ for (const f of want) {
6374
+ if (f === 'text') item.text = text;
6375
+ else if (f === 'id') {
6376
+ const v = el.id || el.getAttribute('data-id');
6377
+ if (v) item.id = v;
6378
+ } else if (f === 'href') {
6379
+ const own = sub ? tEl.closest('a[href]') : null;
6380
+ const v = (own || (el.matches('a[href]') ? el : el.querySelector('a[href]')))?.href;
6381
+ if (v) item.href = v;
6382
+ }
6383
+ }
6384
+ if (!Object.keys(item).length) item = text;
6385
+ }
6386
+ if (addCandidate(item, keyStr)) added++;
6387
+ }
6388
+ return added;
6389
+ };
6390
+
6391
+ const scroller = () => {
6392
+ const first = document.querySelector(sel);
6393
+ for (let p = first?.parentElement; p && p !== document.body; p = p.parentElement) {
6394
+ const st = getComputedStyle(p);
6395
+ if (/(auto|scroll)/.test(st.overflowY) && p.scrollHeight > p.clientHeight + 4) return p;
6396
+ }
6397
+ return null;
6398
+ };
6399
+
6400
+ let pageAdded = read();
6401
+ if (!matched) {
6402
+ for (let k = 0; k < 6 && !matched; k++) {
6403
+ await new Promise((res) => setTimeout(res, 150));
6404
+ pageAdded += read();
6405
+ }
5984
6406
  }
5985
- }
5986
- let done = 0;
5987
- let idle = 0;
5988
- for (let i = 0; i < nScrolls && !full; i++) {
5989
- const box = scroller();
5990
- const before = box ? box.scrollTop : window.scrollY;
5991
- const step = Math.max(200, Math.floor((box ? box.clientHeight : window.innerHeight) * 0.9));
5992
- if (box) box.scrollTop = before + step;
5993
- else window.scrollBy(0, step);
5994
- done++;
5995
- // Wait for two frames (scroll handlers render on the next frame), then waitMs.
5996
- await new Promise((res) => requestAnimationFrame(() => requestAnimationFrame(res)));
5997
- await new Promise((res) => setTimeout(res, wait));
5998
- const moved = (box ? box.scrollTop : window.scrollY) !== before;
5999
- let added = read();
6000
- // Slow renderers (busy page, slow device) may not have swapped items in yet: give them one more wait
6001
- // before scrolling again, otherwise the next scroll skips the items that were about to appear.
6002
- if (moved && added === 0) {
6003
- await new Promise((res) => setTimeout(res, Math.max(wait, 150)));
6004
- added = read();
6407
+ let done = 0;
6408
+ let idle = 0;
6409
+ for (let i = 0; i < nScrolls && !isFull; i++) {
6410
+ const box = scroller();
6411
+ const before = box ? box.scrollTop : window.scrollY;
6412
+ const stepPx = Math.max(200, Math.floor((box ? box.clientHeight : window.innerHeight) * 0.9));
6413
+ if (box) box.scrollTop = before + stepPx;
6414
+ else window.scrollBy(0, stepPx);
6415
+ done++;
6416
+ await new Promise((res) => requestAnimationFrame(() => requestAnimationFrame(res)));
6417
+ await new Promise((res) => setTimeout(res, wait));
6418
+ const moved = (box ? box.scrollTop : window.scrollY) !== before;
6419
+ let added = read();
6420
+ if (moved && added === 0) {
6421
+ await new Promise((res) => setTimeout(res, Math.max(wait, 150)));
6422
+ added = read();
6423
+ }
6424
+ pageAdded += added;
6425
+ idle = added === 0 && !moved ? idle + 1 : added === 0 ? idle : 0;
6426
+ if (idle >= 1) break;
6005
6427
  }
6006
- idle = added === 0 && !moved ? idle + 1 : added === 0 ? idle : 0;
6007
- if (idle >= 1) break;
6428
+ return {
6429
+ pageItems,
6430
+ newKeys,
6431
+ scrolls: done,
6432
+ full: isFull,
6433
+ matched,
6434
+ pageAdded,
6435
+ chars,
6436
+ };
6437
+ },
6438
+ {
6439
+ sel: selector,
6440
+ sub,
6441
+ scrolls,
6442
+ waitMs,
6443
+ maxItems,
6444
+ maxChars,
6445
+ fields: rawFields,
6446
+ tableJson: tableJsonMode,
6447
+ seenArr: [...seenKeys],
6448
+ curCount: allItems.length,
6449
+ curChars: totalChars,
6008
6450
  }
6009
- return { items, scrolls: done, truncated: full, matched };
6010
- },
6011
- { sel: selector, sub, scrolls, waitMs, maxItems, maxChars, fields }
6012
- );
6013
- const res = { ok: true, action: 'collect', count: r.items.length, scrolls: r.scrolls, truncated: r.truncated, items: r.items, elapsedMs: Date.now() - t0 };
6014
- if (!r.items.length) res.note = r.matched ? `${r.matched} elements matched but none had text` : 'selector matched 0 elements';
6451
+ );
6452
+
6453
+ pagesVisited = pageNum;
6454
+ for (const k of pageRes.newKeys) seenKeys.add(k);
6455
+ allItems.push(...pageRes.pageItems);
6456
+ totalChars = pageRes.chars;
6457
+ totalScrolls += pageRes.scrolls;
6458
+ full = pageRes.full;
6459
+ maxMatchedOnAnyPage = Math.max(maxMatchedOnAnyPage, pageRes.matched);
6460
+
6461
+ if (full || pageNum >= maxPages) break;
6462
+
6463
+ // Locate and validate the Next pagination button/link.
6464
+ const hasNext = await page
6465
+ .evaluate(
6466
+ ({ nextSel, nextTxt, nextPageNum }) => {
6467
+ const clean = (s) => String(s || '').replace(/\s+/g, ' ').trim();
6468
+ for (const old of document.querySelectorAll('[data-tbm-collect-next]')) {
6469
+ old.removeAttribute('data-tbm-collect-next');
6470
+ }
6471
+ const isVisible = (el) => {
6472
+ if (!el || el.nodeType !== 1) return false;
6473
+ const r = el.getBoundingClientRect();
6474
+ if (r.width <= 0 || r.height <= 0) return false;
6475
+ const st = getComputedStyle(el);
6476
+ return st.display !== 'none' && st.visibility !== 'hidden' && Number(st.opacity) !== 0;
6477
+ };
6478
+ const isDisabled = (el) => {
6479
+ let cur = el;
6480
+ for (let d = 0; cur && cur.nodeType === 1 && d < 4; d++, cur = cur.parentElement) {
6481
+ if (
6482
+ cur.disabled ||
6483
+ Boolean(cur.matches?.(':disabled')) ||
6484
+ cur.getAttribute('aria-disabled') === 'true' ||
6485
+ cur.hasAttribute('disabled') ||
6486
+ /\bdisabled\b/i.test(typeof cur.className === 'string' ? cur.className : '')
6487
+ ) {
6488
+ return true;
6489
+ }
6490
+ }
6491
+ const tag = (el.tagName || '').toUpperCase();
6492
+ if (tag === 'A') {
6493
+ const href = (el.getAttribute('href') || '').trim();
6494
+ if (!href && !el.hasAttribute('onclick') && el.getAttribute('role') !== 'button') {
6495
+ // Anchor without href or click handler is often an inactive pagination item
6496
+ }
6497
+ }
6498
+ return false;
6499
+ };
6500
+
6501
+ if (nextSel) {
6502
+ const matches = [...document.querySelectorAll(nextSel)].filter(isVisible);
6503
+ const enabled = matches.find((el) => !isDisabled(el));
6504
+ if (!enabled) return false;
6505
+ enabled.setAttribute('data-tbm-collect-next', '1');
6506
+ return true;
6507
+ }
6508
+
6509
+ const ACT_SEL =
6510
+ 'a[href], button, input[type="button"], input[type="submit"], [role="button"], [role="link"], [onclick]';
6511
+ const candidates = [...document.querySelectorAll(ACT_SEL)].filter(isVisible);
6512
+
6513
+ if (nextTxt) {
6514
+ const want = clean(nextTxt).toLowerCase();
6515
+ const scored = [];
6516
+ let sawAnyMatch = false;
6517
+ for (const el of candidates) {
6518
+ const labels = [
6519
+ clean(el.innerText || el.textContent),
6520
+ clean(el.getAttribute('aria-label')),
6521
+ clean(el.getAttribute('title')),
6522
+ clean(el.value),
6523
+ ].filter(Boolean);
6524
+ let tier = 0;
6525
+ for (const l of labels) {
6526
+ const ll = l.toLowerCase();
6527
+ if (ll === want) {
6528
+ tier = 3;
6529
+ break;
6530
+ }
6531
+ if (ll.startsWith(want) || ll.endsWith(want)) tier = Math.max(tier, 2);
6532
+ else if (ll.includes(want)) tier = Math.max(tier, 1);
6533
+ }
6534
+ if (tier > 0) {
6535
+ sawAnyMatch = true;
6536
+ if (!isDisabled(el)) scored.push({ el, tier });
6537
+ }
6538
+ }
6539
+ if (scored.length > 0) {
6540
+ scored.sort((a, b) => b.tier - a.tier);
6541
+ scored[0].el.setAttribute('data-tbm-collect-next', '1');
6542
+ return true;
6543
+ }
6544
+ // If a matching Next control exists on the page but is disabled, stop immediately.
6545
+ if (sawAnyMatch) return false;
6546
+ }
6547
+
6548
+ // Fallback for numbered pagination links ("Page 2", "2", or ?page=2) when nextText is generic ("Next"/"Page") or maxPages > 1.
6549
+ if (!nextTxt || /^(next(\s+page)?|page|[>›»])$/i.test(clean(nextTxt))) {
6550
+ const wantPageLbl = `page ${nextPageNum}`;
6551
+ const wantNumStr = String(nextPageNum);
6552
+ const pageRe = new RegExp(`[?&]page=${nextPageNum}(?:[&#]|$)`, 'i');
6553
+ for (const el of candidates) {
6554
+ if (isDisabled(el)) continue;
6555
+ const txt = clean(el.innerText || el.textContent).toLowerCase();
6556
+ const aria = clean(el.getAttribute('aria-label')).toLowerCase();
6557
+ const href = el.getAttribute('href') || '';
6558
+ if (
6559
+ txt === wantPageLbl ||
6560
+ aria === wantPageLbl ||
6561
+ ((txt === wantNumStr || pageRe.test(href)) &&
6562
+ Boolean(el.closest('nav, [role="navigation"], [class*="pag" i], ul, ol') || pageRe.test(href)))
6563
+ ) {
6564
+ el.setAttribute('data-tbm-collect-next', '1');
6565
+ return true;
6566
+ }
6567
+ }
6568
+ }
6569
+
6570
+ return false;
6571
+ },
6572
+ { nextSel: nextSelector, nextTxt: nextText, nextPageNum: pageNum + 1 }
6573
+ )
6574
+ .catch(() => false);
6575
+
6576
+ if (!hasNext) break;
6577
+
6578
+ const urlBefore = page.url();
6579
+ const firstKeyBefore = pageRes.newKeys[0] || '';
6580
+ const navWatch = watchActionNavigation(page, DEFAULT_TIMEOUT_MS);
6581
+ const actWatch = watchActivity(page);
6582
+ try {
6583
+ const nextLoc = page.locator('[data-tbm-collect-next="1"]').first();
6584
+ await nextLoc.click({ timeout: 2500 });
6585
+ await navWatch.finish();
6586
+ await actWatch.settle({ minMs: Math.min(waitMs, 60), capMs: Math.max(waitMs, 800) });
6587
+ } catch {
6588
+ break;
6589
+ } finally {
6590
+ navWatch.remove();
6591
+ actWatch.remove();
6592
+ }
6593
+
6594
+ // If neither URL changed nor any new items appeared on the previous page, guard against infinite loops on no-op buttons.
6595
+ if (pageNum > 1 && pageRes.pageAdded === 0 && page.url() === urlBefore && !firstKeyBefore) {
6596
+ break;
6597
+ }
6598
+ }
6599
+
6600
+ const res = {
6601
+ ok: true,
6602
+ action: 'collect',
6603
+ count: allItems.length,
6604
+ scrolls: totalScrolls,
6605
+ ...(hasPagination ? { pages: pagesVisited } : {}),
6606
+ truncated: full,
6607
+ items: allItems,
6608
+ elapsedMs: Date.now() - t0,
6609
+ };
6610
+ if (!allItems.length) {
6611
+ res.note = maxMatchedOnAnyPage
6612
+ ? `${maxMatchedOnAnyPage} elements matched but none had text`
6613
+ : 'selector matched 0 elements';
6614
+ }
6015
6615
  return res;
6016
6616
  }
6017
6617
 
@@ -6062,7 +6662,7 @@ async function executeSingleAction(page, rawParams = {}) {
6062
6662
  const params = { ...rawParams, allowSubmit };
6063
6663
  if (params.ref) await assertCurrentDocumentRef(page, params.ref);
6064
6664
  if (params.targetRef) await assertCurrentDocumentRef(page, params.targetRef);
6065
- const silentState = { count: 0, wantKind: false, clickKind: '' };
6665
+ const silentState = { count: 0, wantKind: false, clickKind: '', editorOpen: false };
6066
6666
  const enabled = params.observeAftermath ?? (process.env.TURBO_BROWSER_OBSERVE_AFTERMATH === 'true');
6067
6667
  const observer = enabled && ['click', 'dblclick'].includes(params.action) ? observeClickAftermath(page, () => silentState.clickKind) : null;
6068
6668
  const navigation = params.returnSnapshot && ['click', 'dblclick', 'press'].includes(params.action)
@@ -6104,6 +6704,7 @@ async function executeSingleAction(page, rawParams = {}) {
6104
6704
  try { const u = new URL(request.url()); host = u.host; reqPath = u.pathname; } catch { return; }
6105
6705
  if (isBackgroundRequest(request, { pageUrl: page.url(), readNavigation: getNavigation })) return;
6106
6706
  // An allowed submit was the point of the click: the agent knows it submitted, no late warning.
6707
+ if (silentState.editorOpen) return;
6107
6708
  if (returned && params.allowSubmit === true) return;
6108
6709
  if (returned) parkLate(page, `possibleSubmit: ${request.method()} ${host}${reqPath.slice(0, 60)}`);
6109
6710
  else mutating.push({ method: request.method(), host });
@@ -6150,12 +6751,16 @@ async function executeSingleAction(page, rawParams = {}) {
6150
6751
  returned = true;
6151
6752
  if (clickAction) {
6152
6753
  const ok = completed && res && typeof res === 'object' && !res.blocked;
6754
+ if (silentState.editorOpen && res?.aftermath && !res.aftermath.navigated) {
6755
+ res.aftermath.unexpectedSubmit = false;
6756
+ delete res.aftermath.warning;
6757
+ }
6153
6758
  const seen = observer ? (res?.aftermath?.mutatingRequests || []).map((r) => ({ method: r.method, host: (() => { try { return new URL(r.url).host; } catch { return ''; } })() })) : mutating;
6154
- if (ok && seen.length && params.allowSubmit !== true) {
6759
+ if (ok && seen.length && params.allowSubmit !== true && !silentState.editorOpen) {
6155
6760
  res.possibleSubmit = true;
6156
6761
  res.request = `${seen[0].method} ${seen[0].host}`;
6157
6762
  }
6158
- if (observer || !ok || params.allowSubmit === true) { watchOpen = false; page.off('request', onMutating); }
6763
+ if (observer || !ok || params.allowSubmit === true || silentState.editorOpen) { watchOpen = false; page.off('request', onMutating); }
6159
6764
  else {
6160
6765
  const off = () => { watchOpen = false; page.off('request', onMutating); };
6161
6766
  const t = setTimeout(off, 800);
@@ -7304,6 +7909,13 @@ ${el.value || ''}`.toLowerCase();
7304
7909
  };
7305
7910
  }
7306
7911
  isSafeLocatorClick = Boolean(meta.isSafeSubmit);
7912
+ const cleanMetaLbl = String(meta.label || '').replace(/^[^\p{L}\p{N}]+/u, '').trim();
7913
+ if (
7914
+ (cleanMetaLbl && EDITOR_OPEN_LABEL_RE.test(cleanMetaLbl)) ||
7915
+ (typeof params.text === 'string' && EDITOR_OPEN_LABEL_RE.test(params.text.trim()))
7916
+ ) {
7917
+ silentState.editorOpen = true;
7918
+ }
7307
7919
  await locator.scrollIntoViewIfNeeded({ timeout }).catch(() => {});
7308
7920
  const box = await locator.boundingBox().catch(() => null);
7309
7921
  if (box && box.width > 0 && box.height > 0) {
@@ -7936,7 +8548,7 @@ export async function actFast(page, params = {}, previousLinesSet = null) {
7936
8548
  query: params.snapshotQuery,
7937
8549
  afterNavOrSubmit: Boolean(
7938
8550
  allowSubmit ||
7939
- res.outcome ||
8551
+ res.outcome === 'navigated' ||
7940
8552
  res.url ||
7941
8553
  ['reload', 'back', 'forward'].includes(params.action)
7942
8554
  ),
@@ -8229,9 +8841,172 @@ export async function extractCleanText(page, options = {}) {
8229
8841
  const maxChars = Math.max(1, Number(options.maxChars) || 6000);
8230
8842
  const includeFrames = options.includeFrames !== false;
8231
8843
  let selector = options.selector || null;
8232
- const format = options.format === 'markdown' ? 'markdown' : 'text';
8844
+ const format =
8845
+ options.format === 'markdown'
8846
+ ? 'markdown'
8847
+ : options.format === 'table_json'
8848
+ ? 'table_json'
8849
+ : 'text';
8233
8850
 
8234
8851
  const frames = includeFrames ? getAllFrames(page) : getAllFrames(page).slice(0, 1);
8852
+
8853
+ if (format === 'table_json') {
8854
+ const allRows = [];
8855
+ for (const frameInfo of frames) {
8856
+ const frameRows = await frameInfo.frame
8857
+ .evaluate((sel) => {
8858
+ const clean = (s) => String(s || '').replace(/\s+/g, ' ').trim();
8859
+ const parseCellVal = (raw) => {
8860
+ const s = clean(raw);
8861
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(s)) {
8862
+ const n = Number(s);
8863
+ if (Number.isFinite(n)) return n;
8864
+ }
8865
+ return s;
8866
+ };
8867
+ const getSR = (node) => node?.shadowRoot || window.__tbmGetShadowRoot?.(node) || null;
8868
+ const findDeepAll = (rootNode, query) => {
8869
+ const seen = new Set();
8870
+ const out = [];
8871
+ const stack = [rootNode];
8872
+ while (stack.length > 0) {
8873
+ const cur = stack.shift();
8874
+ if (!cur) continue;
8875
+ const sr = getSR(cur);
8876
+ if (sr) stack.push(sr);
8877
+ if (!cur.querySelectorAll) continue;
8878
+ let matches = [];
8879
+ try {
8880
+ matches = cur.querySelectorAll(query);
8881
+ } catch {
8882
+ return out;
8883
+ }
8884
+ for (const m of matches) {
8885
+ if (!seen.has(m)) {
8886
+ seen.add(m);
8887
+ out.push(m);
8888
+ }
8889
+ }
8890
+ for (const el of cur.querySelectorAll('*')) {
8891
+ const elSr = getSR(el);
8892
+ if (elSr) stack.push(elSr);
8893
+ }
8894
+ }
8895
+ return out;
8896
+ };
8897
+ const isHidden = (el) => {
8898
+ let cur = el;
8899
+ while (cur && cur.nodeType === 1) {
8900
+ if (cur.hasAttribute('hidden') || cur.getAttribute('aria-hidden') === 'true') return true;
8901
+ try {
8902
+ const st = getComputedStyle(cur);
8903
+ if (st.display === 'none' || st.visibility === 'hidden' || Number(st.opacity) === 0) return true;
8904
+ } catch {}
8905
+ const rn = cur.getRootNode?.();
8906
+ cur = cur.parentElement || (rn instanceof ShadowRoot ? rn.host : null);
8907
+ }
8908
+ return false;
8909
+ };
8910
+ const extractTableRows = (tbl, onlyRows = null) => {
8911
+ const headRows = [...tbl.querySelectorAll('thead tr')].filter((tr) => !isHidden(tr));
8912
+ let hdrTr = headRows.length > 0 ? headRows[headRows.length - 1] : null;
8913
+ if (!hdrTr) {
8914
+ const firstTr = [...tbl.querySelectorAll('tr')].find((tr) => !isHidden(tr));
8915
+ if (firstTr && [...firstTr.children].some((c) => c.tagName === 'TH')) hdrTr = firstTr;
8916
+ }
8917
+ const headers = hdrTr
8918
+ ? [...hdrTr.children]
8919
+ .filter((c) => (c.tagName === 'TH' || c.tagName === 'TD') && !isHidden(c))
8920
+ .map((c, idx) => clean(c.innerText || c.textContent) || `col${idx + 1}`)
8921
+ : [];
8922
+ const candidateTrs =
8923
+ onlyRows ||
8924
+ ([...tbl.querySelectorAll('tbody tr')].length > 0
8925
+ ? [...tbl.querySelectorAll('tbody tr')]
8926
+ : [...tbl.querySelectorAll('tr')].filter((tr) => !tr.closest('thead, tfoot')));
8927
+ const out = [];
8928
+ for (const tr of candidateTrs) {
8929
+ if (tr === hdrTr || isHidden(tr)) continue;
8930
+ const cells = [...tr.children].filter((c) => (c.tagName === 'TD' || c.tagName === 'TH') && !isHidden(c));
8931
+ if (cells.length === 0) continue;
8932
+ if (cells.every((c) => c.tagName === 'TH')) continue;
8933
+ const rowObj = {};
8934
+ let hasContent = false;
8935
+ cells.forEach((cell, idx) => {
8936
+ const key = headers[idx] || `col${idx + 1}`;
8937
+ const val = parseCellVal(cell.innerText || cell.textContent);
8938
+ if (val !== '') hasContent = true;
8939
+ rowObj[key] = val;
8940
+ });
8941
+ if (hasContent) out.push(rowObj);
8942
+ }
8943
+ return out;
8944
+ };
8945
+
8946
+ const rows = [];
8947
+ if (sel) {
8948
+ const matched = findDeepAll(document, sel).filter((el) => !isHidden(el));
8949
+ const directTrs = matched.filter((el) => el.tagName === 'TR');
8950
+ if (directTrs.length > 0) {
8951
+ const byTable = new Map();
8952
+ for (const tr of directTrs) {
8953
+ const tbl = tr.closest('table') || document.body;
8954
+ if (!byTable.has(tbl)) byTable.set(tbl, []);
8955
+ byTable.get(tbl).push(tr);
8956
+ }
8957
+ for (const [tbl, trList] of byTable.entries()) {
8958
+ rows.push(...extractTableRows(tbl, trList));
8959
+ }
8960
+ return rows;
8961
+ }
8962
+ for (const m of matched) {
8963
+ if (m.tagName === 'TABLE') {
8964
+ rows.push(...extractTableRows(m));
8965
+ } else if (m.tagName === 'TBODY') {
8966
+ const tbl = m.closest('table') || m;
8967
+ rows.push(...extractTableRows(tbl, [...m.querySelectorAll('tr')]));
8968
+ } else {
8969
+ for (const tbl of findDeepAll(m, 'table').filter((t) => !isHidden(t))) {
8970
+ rows.push(...extractTableRows(tbl));
8971
+ }
8972
+ }
8973
+ }
8974
+ return rows;
8975
+ }
8976
+ const root =
8977
+ findDeepAll(document, 'main, article, [role="main"]').find((el) => !isHidden(el) && el.querySelector('table')) ||
8978
+ document.body;
8979
+ if (!root) return rows;
8980
+ for (const tbl of findDeepAll(root, 'table').filter((t) => !isHidden(t))) {
8981
+ rows.push(...extractTableRows(tbl));
8982
+ }
8983
+ return rows;
8984
+ }, selector)
8985
+ .catch(() => []);
8986
+ if (Array.isArray(frameRows) && frameRows.length > 0) {
8987
+ allRows.push(...frameRows);
8988
+ }
8989
+ }
8990
+ const title = await page.title().catch(() => '');
8991
+ const full = JSON.stringify(allRows);
8992
+ const MARK = '\n... [truncated]';
8993
+ const truncated = full.length > maxChars;
8994
+ const text = truncated ? `${full.slice(0, Math.max(0, maxChars - MARK.length))}${MARK}` : full;
8995
+ const savedPath = writeSaveFile(options.savePath, full);
8996
+ return {
8997
+ text,
8998
+ rows: allRows,
8999
+ rowCount: allRows.length,
9000
+ fullChars: savedPath && truncated ? full.length : undefined,
9001
+ url: page.url(),
9002
+ title,
9003
+ format,
9004
+ truncated,
9005
+ charCount: text.length,
9006
+ savePath: savedPath,
9007
+ ...(allRows.length === 0 ? { note: 'no visible table rows found' } : {}),
9008
+ };
9009
+ }
8235
9010
  let sections = [];
8236
9011
 
8237
9012
  const runAll = async () => {