dsh-chrome-bridge 2.0.3 → 2.1.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.
Files changed (49) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/core/ext.js +8 -1
  4. package/core/hosts.js +3 -4
  5. package/core/receipt.js +228 -31
  6. package/core/session.js +11 -14
  7. package/core/tooldef.js +10 -1
  8. package/core/transport.js +67 -17
  9. package/drag.js +10 -10
  10. package/features/frames.js +5 -2
  11. package/i18n/en.js +34 -7
  12. package/i18n/ru.js +34 -7
  13. package/i18n/zh.js +34 -7
  14. package/nav.js +103 -32
  15. package/package.json +1 -1
  16. package/refs.js +309 -73
  17. package/tools/batch.js +311 -0
  18. package/tools/click.js +37 -11
  19. package/tools/dialog.js +19 -2
  20. package/tools/drag.js +31 -5
  21. package/tools/fill.js +71 -22
  22. package/tools/index.js +3 -1
  23. package/tools/input.js +97 -36
  24. package/tools/nav.js +46 -23
  25. package/tools/read.js +2 -0
  26. package/tools/tabs.js +16 -2
  27. package/tools/wait.js +14 -6
  28. package/vendor/extension/in-page-cursor.js +1 -1
  29. package/vendor/extension/manifest.json +1 -1
  30. package/vendor/extension/popup.css +1 -0
  31. package/vendor/extension/popup.html +6 -3
  32. package/vendor/extension/popup.js +19 -13
  33. package/vendor/extension/sw/actions.js +573 -0
  34. package/vendor/extension/sw/boot.js +2 -1
  35. package/vendor/extension/sw/cdp.js +139 -11
  36. package/vendor/extension/sw/conditions.js +176 -0
  37. package/vendor/extension/sw/confirm.js +39 -7
  38. package/vendor/extension/sw/cursor.js +176 -14
  39. package/vendor/extension/sw/dispatch.js +6 -1
  40. package/vendor/extension/sw/frames.js +543 -47
  41. package/vendor/extension/sw/lifecycle.js +82 -0
  42. package/vendor/extension/sw/ops.js +801 -139
  43. package/vendor/extension/sw/page-access.js +292 -0
  44. package/vendor/extension/sw/popup-api.js +28 -7
  45. package/vendor/extension/sw/snapshot.js +251 -0
  46. package/vendor/extension/sw/state.js +16 -5
  47. package/vendor/extension/sw/tabui.js +9 -2
  48. package/vendor/in-page-cursor.js +1 -1
  49. package/vendor/skill/SKILL.md +8 -7
@@ -1,4 +1,4 @@
1
- import { evaluate, send } from './cdp.js'
1
+ import { ensure, evaluate, send } from './cdp.js'
2
2
  import { withChooser } from './chooser.js'
3
3
  import { PAUSED_MSG, S } from './state.js'
4
4
  import { CURSOR_ICON, CURSOR_TAB_TITLE, IDLE_ICON, labels, setTabFavicon } from './tabui.js'
@@ -105,6 +105,23 @@ async function cursorMove(tabId, x, y, opts = {}) {
105
105
  }
106
106
  }
107
107
 
108
+ // Chrome's focus emulation makes document.hasFocus() unsuitable here.
109
+ async function moveForAction(tabId, x, y, opts) {
110
+ let foreground
111
+ try {
112
+ const tab = await chrome.tabs.get(Number(tabId))
113
+ if (tab.active === false) foreground = false
114
+ else if (tab.active === true) foreground = (await chrome.windows.get(tab.windowId)).focused
115
+ } catch {}
116
+ opts.check?.()
117
+ const d = await cursorMove(tabId, x, y, { ...opts, ...(foreground === false && { duration: 0 }) })
118
+ // Older hosts that cannot report foreground status keep the original demonstration timing.
119
+ if (d !== null && foreground !== false && (S.cursorPace === 'smooth' || foreground === undefined)) {
120
+ await (opts.deadline ? within(settle(d), timeLeft(opts.deadline), '等待光标超时') : settle(d))
121
+ }
122
+ return d
123
+ }
124
+
108
125
  /** 光标的其它表情(click / down / up / label / scroll):只在光标已经在页面里时做,出错不管 */
109
126
  async function cursorFx(tabId, expr, deadline) {
110
127
  if (!S.cursorReady.has(Number(tabId))) return undefined
@@ -441,6 +458,62 @@ function makeClickGuard(tabId, deadline, extraCheck) {
441
458
  }
442
459
  }
443
460
 
461
+ const DOC_HASH_JS = `function(u){const s=String(u||'');let h1=0x811c9dc5,h2=0x9e3779b9;for(let i=0;i<s.length;i++){const c=s.charCodeAt(i);h1=Math.imul(h1^c,0x01000193);h2=Math.imul(h2^c,0x85ebca6b)}return (h1>>>0).toString(16).padStart(8,'0')+(h2>>>0).toString(16).padStart(8,'0')}`
462
+ const validDocToken = (tok) => (typeof tok === 'number' && Number.isFinite(tok)) || (typeof tok === 'string' && tok.length > 0)
463
+
464
+ async function readDocBinding(id, timeoutMs = 400) {
465
+ let timer
466
+ try {
467
+ const res = await Promise.race([
468
+ chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
469
+ expression: `(() => {
470
+ const tok = globalThis.performance?.timeOrigin ?? (typeof window !== 'undefined' ? (window.__dshDocToken ||= Math.random().toString(36).slice(2)) : null);
471
+ const href = typeof location !== 'undefined' && location?.href ? location.href : '';
472
+ return ((typeof tok === 'number' && Number.isFinite(tok)) || (typeof tok === 'string' && tok.length > 0))
473
+ ? { expectedDocToken: tok, ...(href ? { expectedUrlHash: (${DOC_HASH_JS})(href) } : {}) }
474
+ : null;
475
+ })()`,
476
+ returnByValue: true,
477
+ }),
478
+ new Promise((resolve) => { timer = setTimeout(() => resolve(null), timeoutMs) }),
479
+ ])
480
+ if (!res || res.exceptionDetails || !('result' in res)) return { failed: true }
481
+ const val = res.result?.value
482
+ if (!val || typeof val !== 'object' || !validDocToken(val.expectedDocToken)) return { failed: true }
483
+ return { binding: val }
484
+ } catch {
485
+ return { failed: true }
486
+ } finally {
487
+ clearTimeout(timer)
488
+ }
489
+ }
490
+
491
+ async function docBindingOk(id, docBinding, timeoutMs = 300) {
492
+ let timer
493
+ try {
494
+ const res = await Promise.race([
495
+ chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
496
+ expression: `(() => {
497
+ const tok = globalThis.performance?.timeOrigin ?? (typeof window !== 'undefined' ? window.__dshDocToken : null);
498
+ const href = typeof location !== 'undefined' && location?.href ? location.href : '';
499
+ const hash = (${DOC_HASH_JS})(href);
500
+ return ((typeof tok === 'number' && Number.isFinite(tok)) || (typeof tok === 'string' && tok.length > 0)) &&
501
+ (${docBinding.expectedDocToken != null ? `tok === ${JSON.stringify(docBinding.expectedDocToken)}` : 'true'}) &&
502
+ (${docBinding.expectedUrl ? `href === ${JSON.stringify(docBinding.expectedUrl)}` : 'true'}) &&
503
+ (${docBinding.expectedUrlHash ? `hash === ${JSON.stringify(docBinding.expectedUrlHash)}` : 'true'});
504
+ })()`,
505
+ returnByValue: true,
506
+ }),
507
+ new Promise((resolve) => { timer = setTimeout(() => resolve(null), timeoutMs) }),
508
+ ])
509
+ return !res?.exceptionDetails && res?.result?.value === true
510
+ } catch {
511
+ return false
512
+ } finally {
513
+ clearTimeout(timer)
514
+ }
515
+ }
516
+
444
517
  async function clickPoint(tabId, x, y, opts = {}) {
445
518
  const id = Number(tabId)
446
519
  const n = Number(opts.clickCount || 1)
@@ -452,9 +525,8 @@ async function clickPoint(tabId, x, y, opts = {}) {
452
525
 
453
526
  // 先让光标飞过去,人眼看得见,再发真实点击
454
527
  if (opts.cursor && S.showCursor) {
455
- const d = await cursorMove(tabId, base.x, base.y, { label: opts.cursor.label, deadline: opts.deadline })
528
+ const d = await moveForAction(tabId, base.x, base.y, { label: opts.cursor.label, deadline: opts.deadline, check: opts.check })
456
529
  if (d !== null) {
457
- await (opts.deadline ? within(settle(d), budget(), '等待光标超时') : settle(d))
458
530
  if (typeof opts.check === 'function') opts.check()
459
531
  await cursorFx(tabId, `(window.__dshCursor.beginAgent && window.__dshCursor.beginAgent(1500), window.__dshCursor.click(${base.x}, ${base.y}, ${n}), 1)`, opts.deadline)
460
532
  if (S.cursorReady.has(id)) S.pageAgentUntil.set(id, Date.now() + 1500)
@@ -462,23 +534,67 @@ async function clickPoint(tabId, x, y, opts = {}) {
462
534
  }
463
535
 
464
536
  if (typeof opts.check === 'function') opts.check()
465
- await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mouseMoved', buttons: 0 }, budget(), opts.check)
537
+ const pressCheck = typeof opts.pressCheck === 'function' ? opts.pressCheck : opts.check
538
+ if (typeof opts.verifyFrames === 'function') await opts.verifyFrames()
539
+ if (typeof pressCheck === 'function') pressCheck()
540
+ await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mouseMoved', buttons: 0 }, budget(), pressCheck, opts.docBinding ? { docBinding: opts.docBinding } : undefined)
466
541
  await new Promise(r => setTimeout(r, 12))
467
542
  return withChooser(tabId, opts.chooser, async () => {
468
543
  if (typeof opts.check === 'function') opts.check()
469
- if (typeof opts.beforePress === 'function') {
470
- await opts.beforePress()
471
- if (typeof opts.check === 'function') opts.check()
544
+ if (typeof opts.beforePress === 'function') await opts.beforePress()
545
+ if (typeof opts.verifyFrames === 'function') await opts.verifyFrames()
546
+ if (typeof pressCheck === 'function') pressCheck()
547
+ let relBinding = opts.releaseBinding || opts.docBinding
548
+ let probedNavGen
549
+ if (!relBinding || !validDocToken(relBinding.expectedDocToken)) {
550
+ probedNavGen = S.mainNavGeneration.get(id) || 0
551
+ const probed = await readDocBinding(id, Math.min(400, budget() ?? 400))
552
+ if (probed.failed) throw new Error('无法核实当前文档状态,已中止输入')
553
+ relBinding = { ...probed.binding, ...relBinding, expectedDocToken: probed.binding.expectedDocToken }
554
+ if (typeof pressCheck === 'function') pressCheck()
472
555
  }
473
- const pressMeta = {}
474
- await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mousePressed', buttons: ({ left: 1, right: 2, middle: 4, back: 8, forward: 16 })[button] || 1 }, budget(), opts.check, pressMeta)
556
+ const relNavGen = opts.releaseNavGen ?? opts.expectedNavGen ?? probedNavGen
557
+ const bindErr = opts.docBinding ? 'BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤' : '无法核实当前文档状态,已中止输入'
558
+ const pressGuard = () => {
559
+ if (typeof pressCheck === 'function') pressCheck()
560
+ if (relNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== relNavGen) throw new Error(bindErr)
561
+ }
562
+ pressGuard()
563
+ const startReleaseAll = S.releaseAllEpoch
564
+ const prePressFrames = typeof opts.pressVerifyFramesOnly === 'function' ? opts.pressVerifyFramesOnly : opts.verifyFramesOnly
565
+ const pressMeta = {
566
+ docBinding: opts.docBinding ? { ...relBinding, ...opts.docBinding, expectedDocToken: opts.docBinding.expectedDocToken ?? relBinding.expectedDocToken } : relBinding,
567
+ ...(opts.docBinding ? {} : { docBindingError: bindErr }),
568
+ ...(typeof prePressFrames === 'function' ? { verifyFramesOnly: prePressFrames } : {}),
569
+ }
570
+ await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mousePressed', buttons: ({ left: 1, right: 2, middle: 4, back: 8, forward: 16 })[button] || 1 }, budget(), pressGuard, pressMeta)
475
571
  const pressSeq = pressMeta.attachSeq
476
572
  await new Promise(r => setTimeout(r, 24))
477
- // 仅在按下所属的同一个调试会话仍附着时补发 mouseReleased;已放开或换了新会话绝不重连也不跨会话释放
478
- if (!S.attached.has(id) || !pressSeq || S.attachSeq.get(id) !== pressSeq) {
573
+ const sessionOk = () => S.attached.has(id) && pressSeq && S.attachSeq.get(id) === pressSeq &&
574
+ !S.releasing.has(id) && !S.paused && S.releaseAllEpoch === startReleaseAll
575
+ if (!sessionOk()) {
576
+ if (typeof opts.check === 'function') opts.check()
577
+ throw new Error(RELEASED_MSG)
578
+ }
579
+ if (typeof opts.verifyFramesOnly === 'function') await opts.verifyFramesOnly()
580
+ // 仅在按下所属的同一个调试会话仍附着且未被放开/暂停时补发 mouseReleased;已放开或换了新会话绝不重连也不跨会话释放
581
+ if (!sessionOk()) {
479
582
  if (typeof opts.check === 'function') opts.check()
480
583
  throw new Error(RELEASED_MSG)
481
584
  }
585
+ if (relNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== relNavGen) {
586
+ return { x: base.x, y: base.y, button }
587
+ }
588
+ if (relBinding) {
589
+ if (!(await docBindingOk(id, relBinding, 300))) return { x: base.x, y: base.y, button }
590
+ if (!sessionOk()) {
591
+ if (typeof opts.check === 'function') opts.check()
592
+ throw new Error(RELEASED_MSG)
593
+ }
594
+ if (relNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== relNavGen) {
595
+ return { x: base.x, y: base.y, button }
596
+ }
597
+ }
482
598
  const relTimeout = opts.deadline ? Math.max(1, opts.deadline - Date.now()) : 15000
483
599
  let relTimer
484
600
  try {
@@ -530,17 +646,62 @@ async function pressKey(tabId, spec, opts = {}) {
530
646
  const id = Number(tabId)
531
647
  const budget = () => (opts.deadline !== undefined ? timeLeft(opts.deadline) : undefined)
532
648
  if (typeof opts.check === 'function') opts.check()
533
- const pressMeta = {}
649
+ let relBinding = opts.releaseBinding || opts.docBinding
650
+ let probedNavGen
651
+ if (!relBinding || !validDocToken(relBinding.expectedDocToken)) {
652
+ if (!S.attached.has(id)) {
653
+ await (budget() !== undefined ? within(ensure(id), budget(), '等待调试器超时') : ensure(id))
654
+ if (typeof opts.check === 'function') opts.check()
655
+ }
656
+ probedNavGen = S.mainNavGeneration.get(id) || 0
657
+ const probed = await readDocBinding(id, Math.min(400, budget() ?? 400))
658
+ if (probed.failed) throw new Error('无法核实当前文档状态,已中止输入')
659
+ relBinding = { ...probed.binding, ...relBinding, expectedDocToken: probed.binding.expectedDocToken }
660
+ if (typeof opts.check === 'function') opts.check()
661
+ }
662
+ const relNavGen = opts.releaseNavGen ?? opts.expectedNavGen ?? probedNavGen
663
+ const bindErr = opts.docBinding ? 'BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤' : '无法核实当前文档状态,已中止输入'
664
+ const keyGuard = () => {
665
+ if (typeof opts.check === 'function') opts.check()
666
+ if (relNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== relNavGen) throw new Error(bindErr)
667
+ }
668
+ keyGuard()
669
+ const startReleaseAll = S.releaseAllEpoch
670
+ const pressMeta = {
671
+ docBinding: opts.docBinding ? { ...relBinding, ...opts.docBinding, expectedDocToken: opts.docBinding.expectedDocToken ?? relBinding.expectedDocToken } : relBinding,
672
+ ...(opts.docBinding ? {} : { docBindingError: bindErr }),
673
+ ...(typeof opts.verifyFramesOnly === 'function' ? { verifyFramesOnly: opts.verifyFramesOnly } : {}),
674
+ }
534
675
  await send(tabId, 'Input.dispatchKeyEvent', {
535
676
  ...base, type: suppressText ? 'rawKeyDown' : 'keyDown',
536
677
  ...(suppressText ? {} : { text, unmodifiedText: text }),
537
- }, budget(), opts.check, pressMeta)
678
+ }, budget(), keyGuard, pressMeta)
538
679
  const pressSeq = pressMeta.attachSeq
539
680
  await new Promise(r => setTimeout(r, 12))
540
- if (!S.attached.has(id) || !pressSeq || S.attachSeq.get(id) !== pressSeq) {
681
+ const sessionOk = () => S.attached.has(id) && pressSeq && S.attachSeq.get(id) === pressSeq &&
682
+ !S.releasing.has(id) && !S.paused && S.releaseAllEpoch === startReleaseAll
683
+ if (!sessionOk()) {
541
684
  if (typeof opts.check === 'function') opts.check()
542
685
  throw new Error(RELEASED_MSG)
543
686
  }
687
+ if (typeof opts.verifyFramesOnly === 'function') await opts.verifyFramesOnly()
688
+ if (!sessionOk()) {
689
+ if (typeof opts.check === 'function') opts.check()
690
+ throw new Error(RELEASED_MSG)
691
+ }
692
+ if (relNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== relNavGen) {
693
+ return { key: spec, modifiers, navigated: true }
694
+ }
695
+ if (relBinding) {
696
+ if (!(await docBindingOk(id, relBinding, 300))) return { key: spec, modifiers, navigated: true }
697
+ if (!sessionOk()) {
698
+ if (typeof opts.check === 'function') opts.check()
699
+ throw new Error(RELEASED_MSG)
700
+ }
701
+ if (relNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== relNavGen) {
702
+ return { key: spec, modifiers, navigated: true }
703
+ }
704
+ }
544
705
  await chrome.debugger.sendCommand({ tabId: id }, 'Input.dispatchKeyEvent', { ...base, type: 'keyUp' })
545
706
  S.postReleaseAt.set(id, Date.now())
546
707
  return { key: spec, modifiers }
@@ -558,6 +719,7 @@ async function unmountHandoff(tabId, id) {
558
719
  }
559
720
 
560
721
  export {
722
+ moveForAction,
561
723
  RELEASED_MSG, bumpControlEpoch, injectCursor, cursorDo, cursorMove, cursorFx, settle, hidePageCursor, markCursor,
562
724
  installInputListener, mountHandoff, refreshControls, agentInputSpec, agentInputKinds, beginAgentInput, endAgentInput,
563
725
  cancelAgentInput, isAgentInputActive, agentInput, makeClickGuard, clickPoint, MODS, NAMED_KEYS, pressKey, unmountHandoff,
@@ -37,6 +37,7 @@ async function trackOpened(id, run, hasChooser = false) {
37
37
  }
38
38
  return { id: t.id, url, title: tab.title || '' }
39
39
  }))
40
+ if (result.receipt && result.openedTabs) result.receipt.openedTabs = result.openedTabs
40
41
  return result
41
42
  } finally {
42
43
  S.tabCreated.delete(listener)
@@ -75,9 +76,12 @@ async function handle(msg) {
75
76
  const isDragReleaseCleanup = op === 'cdp' && args.method === 'Input.dispatchMouseEvent' &&
76
77
  args.params?.type === 'mouseReleased' && Number.isInteger(args.releaseOnlyForAttachSeq)
77
78
  const controlledEval = op === 'eval' && args.requireControl === true
78
- const guardedOp = !isDragReleaseCleanup && (TAKEOVER_OPS.has(op) || rawInput || op === 'cursor' || controlledEval)
79
+ const guardedOp = !isDragReleaseCleanup && (TAKEOVER_OPS.has(op) || rawInput || op === 'cursor' || op === 'waitCondition' || op === 'networkIdle' || op === 'nav' || op === 'historyNav' || op === 'dialog' || controlledEval)
79
80
  const reqEpoch = Number.isInteger(tabId) ? (S.controlEpoch.get(tabId) || 0) : null
80
81
  const reqReleaseAll = S.releaseAllEpoch
82
+ if (isDragReleaseCleanup && !Number.isInteger(args.controlEpoch) && reqEpoch !== null) {
83
+ args.controlEpoch = reqEpoch
84
+ }
81
85
  const expectedEpoch = Number.isInteger(args.controlEpoch) ? args.controlEpoch : reqEpoch
82
86
  try {
83
87
  const ops = getOps()
@@ -123,6 +127,7 @@ async function handle(msg) {
123
127
  }
124
128
  if (args.timeoutMs !== undefined) args.timeoutMs = timeLeft(tExec + args.timeoutMs)
125
129
  if (Number.isInteger(tabId)) S.tabSessions.set(tabId, clientKey(client))
130
+ if (op === 'act') return fn(args) // tracks only its triggering action, before expect and receipt
126
131
  return OPEN_TRACKED.has(op) ? trackOpened(tabId, () => fn(args), Boolean(args.chooser)) : fn(args)
127
132
  }
128
133
  const result = await (QUEUED.has(op) || rawInput || controlledEval ? enqueue(tabId, run) : run())