dsh-chrome-bridge 2.0.2 → 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 (53) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/core/ext.js +44 -15
  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 +118 -36
  10. package/features/frames.js +5 -2
  11. package/i18n/en.js +37 -7
  12. package/i18n/ru.js +37 -7
  13. package/i18n/zh.js +37 -7
  14. package/nav.js +103 -32
  15. package/package.json +1 -1
  16. package/refs.js +317 -77
  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 +52 -9
  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/screenshot.js +10 -1
  27. package/tools/tabs.js +16 -2
  28. package/tools/wait.js +14 -6
  29. package/vendor/cb +3 -2
  30. package/vendor/extension/in-page-cursor.js +49 -11
  31. package/vendor/extension/manifest.json +1 -1
  32. package/vendor/extension/popup.css +1 -0
  33. package/vendor/extension/popup.html +6 -3
  34. package/vendor/extension/popup.js +19 -13
  35. package/vendor/extension/sw/actions.js +573 -0
  36. package/vendor/extension/sw/boot.js +7 -1
  37. package/vendor/extension/sw/cdp.js +219 -33
  38. package/vendor/extension/sw/conditions.js +176 -0
  39. package/vendor/extension/sw/confirm.js +39 -7
  40. package/vendor/extension/sw/cursor.js +534 -49
  41. package/vendor/extension/sw/dispatch.js +43 -8
  42. package/vendor/extension/sw/frames.js +643 -49
  43. package/vendor/extension/sw/imaging.js +35 -17
  44. package/vendor/extension/sw/lifecycle.js +82 -0
  45. package/vendor/extension/sw/ops.js +1028 -148
  46. package/vendor/extension/sw/page-access.js +292 -0
  47. package/vendor/extension/sw/popup-api.js +42 -10
  48. package/vendor/extension/sw/record.js +22 -5
  49. package/vendor/extension/sw/snapshot.js +251 -0
  50. package/vendor/extension/sw/state.js +24 -5
  51. package/vendor/extension/sw/tabui.js +10 -2
  52. package/vendor/in-page-cursor.js +49 -11
  53. package/vendor/skill/SKILL.md +8 -7
@@ -1,19 +1,62 @@
1
- import { evaluate, send } from './cdp.js'
1
+ import { ensure, evaluate, send } from './cdp.js'
2
2
  import { withChooser } from './chooser.js'
3
- import { S } from './state.js'
3
+ import { PAUSED_MSG, S } from './state.js'
4
4
  import { CURSOR_ICON, CURSOR_TAB_TITLE, IDLE_ICON, labels, setTabFavicon } from './tabui.js'
5
5
  import { log, sleep, timeLeft, within } from './util.js'
6
6
 
7
- async function injectCursor(tabId) {
7
+ const isTimeoutError = (e) => /操作超时|等待光标超时|等待调试器超时/.test(String((e && e.message) || e))
8
+ const RELEASED_MSG = '控制已被用户放开,操作已中止'
9
+
10
+ function bumpControlEpoch(tabId) {
11
+ const id = Number(tabId)
12
+ const next = (S.controlEpoch.get(id) || 0) + 1
13
+ S.controlEpoch.set(id, next)
14
+ return next
15
+ }
16
+
17
+ async function injectCursor(tabId, deadline) {
8
18
  if (S.paused || !S.showCursor) return false
9
19
  const id = Number(tabId)
10
20
  if (!S.cursorReady.has(id)) {
11
- await chrome.scripting.executeScript({ target: { tabId: id }, world: 'MAIN', files: ['in-page-cursor.js'] })
21
+ const epoch = S.controlEpoch.get(id) || 0
22
+ const seq = (S.cursorInjectSeq.get(id) || 0) + 1
23
+ S.cursorInjectSeq.set(id, seq)
24
+ const budget = () => (deadline !== undefined ? timeLeft(deadline) : undefined)
25
+ const exec = chrome.scripting.executeScript({ target: { tabId: id }, world: 'MAIN', files: ['in-page-cursor.js'] })
26
+ try {
27
+ await (deadline !== undefined ? within(exec, budget(), '等待光标超时') : exec)
28
+ } catch (e) {
29
+ // 超时后如果注入稍晚落进页面,仅在没有更新一轮注入接手时主动收掉,避免误伤新光标
30
+ void Promise.resolve(exec).then(() => {
31
+ if (S.cursorInjectSeq.get(id) === seq &&
32
+ (!S.cursorReady.has(id) || S.paused || !S.showCursor || (S.controlEpoch.get(id) || 0) !== epoch)) {
33
+ return hidePageCursor(id)
34
+ }
35
+ }, () => {})
36
+ throw e
37
+ }
38
+ if (S.paused) {
39
+ if (S.cursorInjectSeq.get(id) === seq) void hidePageCursor(id)
40
+ throw new Error(PAUSED_MSG)
41
+ }
42
+ if (!S.showCursor || (S.controlEpoch.get(id) || 0) !== epoch || S.cursorInjectSeq.get(id) !== seq) {
43
+ if (S.cursorInjectSeq.get(id) === seq) void hidePageCursor(id)
44
+ return false
45
+ }
12
46
  const p = S.cursorPos.get(id)
13
- if (p) await evaluate(tabId, `window.__dshCursor.pos() || window.__dshCursor.place(${p.x}, ${p.y})`).catch(() => {})
47
+ if (p) await evaluate(tabId, `window.__dshCursor.pos() || window.__dshCursor.place(${p.x}, ${p.y})`, false, budget()).catch(() => {})
48
+ if (S.paused) {
49
+ if (S.cursorInjectSeq.get(id) === seq) void hidePageCursor(id)
50
+ throw new Error(PAUSED_MSG)
51
+ }
52
+ if (!S.showCursor || (S.controlEpoch.get(id) || 0) !== epoch || S.cursorInjectSeq.get(id) !== seq) {
53
+ if (S.cursorInjectSeq.get(id) === seq) void hidePageCursor(id)
54
+ return false
55
+ }
14
56
  S.cursorReady.add(id)
15
57
  // 语义:标签页上出现小鼠标 = 这个页面里真的有一只鼠标(页内光标已就位)
16
- await markCursor(tabId, true)
58
+ // 移出点击关键路径,防止 favicon 注入卡住队列;内部写入前复核接管代次
59
+ void markCursor(tabId, true, epoch)
17
60
  }
18
61
  return true
19
62
  }
@@ -26,11 +69,11 @@ async function cursorDo(tabId, expr, deadline) {
26
69
  const id = Number(tabId)
27
70
  const NONE = '__dsh_no_cursor__'
28
71
  const probe = `((window.__dshCursor && window.__dshCursor.version >= 4) ? (${expr}) : ${JSON.stringify(NONE)})`
29
- if (!S.cursorReady.has(id) && !(await injectCursor(tabId))) return undefined
72
+ if (!S.cursorReady.has(id) && !(await injectCursor(tabId, deadline))) return undefined
30
73
  let r = await evaluate(tabId, probe, false, deadline && timeLeft(deadline))
31
74
  if (r === NONE) {
32
75
  S.cursorReady.delete(id)
33
- if (!(await injectCursor(tabId))) return undefined
76
+ if (!(await injectCursor(tabId, deadline))) return undefined
34
77
  r = await evaluate(tabId, probe, false, deadline && timeLeft(deadline))
35
78
  }
36
79
  return r === NONE ? undefined : r
@@ -38,27 +81,58 @@ async function cursorDo(tabId, expr, deadline) {
38
81
 
39
82
  /** 光标滑到 (x, y),可顺带亮出名牌文字。返回滑行时长 ms;光标装不上返回 null(不影响真实操作)。 */
40
83
  async function cursorMove(tabId, x, y, opts = {}) {
84
+ const id = Number(tabId)
41
85
  const px = Math.round(Number(x))
42
86
  const py = Math.round(Number(y))
43
87
  const mo = { straight: !!opts.straight }
44
88
  if (opts.duration != null) mo.duration = Math.max(0, Math.round(Number(opts.duration)))
45
89
  const say = opts.label ? `c.label(${JSON.stringify(String(opts.label).slice(0, 80))});` : ''
90
+ const agent = opts.agentMs ? `c.beginAgent && c.beginAgent(${Math.round(opts.agentMs)});` : ''
91
+ const epoch = S.controlEpoch.get(id) || 0
46
92
  try {
47
- const d = await cursorDo(tabId, `(() => { const c = window.__dshCursor; ${say} return c.move(${px}, ${py}, ${JSON.stringify(mo)}) })()`, opts.deadline)
93
+ const d = await cursorDo(tabId, `(() => { const c = window.__dshCursor; ${agent} const dur = c.move(${px}, ${py}, ${JSON.stringify(mo)}); ${say} return dur })()`, opts.deadline)
48
94
  if (d === undefined) return null
49
- S.cursorPos.set(Number(tabId), { x: px, y: py })
95
+ if (!S.cursorReady.has(id) || S.paused || !S.showCursor || (S.controlEpoch.get(id) || 0) !== epoch) {
96
+ void hidePageCursor(id)
97
+ return null
98
+ }
99
+ S.cursorPos.set(id, { x: px, y: py })
100
+ if (opts.agentMs) S.pageAgentUntil.set(id, Date.now() + Math.round(opts.agentMs))
50
101
  return Number(d) || 0
51
- } catch { return null }
102
+ } catch (e) {
103
+ if (opts.deadline !== undefined && (Date.now() >= opts.deadline || isTimeoutError(e))) throw e
104
+ return null
105
+ }
106
+ }
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
52
123
  }
53
124
 
54
125
  /** 光标的其它表情(click / down / up / label / scroll):只在光标已经在页面里时做,出错不管 */
55
126
  async function cursorFx(tabId, expr, deadline) {
56
127
  if (!S.cursorReady.has(Number(tabId))) return undefined
57
- try { return await cursorDo(tabId, expr, deadline) } catch { return undefined }
128
+ try { return await cursorDo(tabId, expr, deadline) } catch (e) {
129
+ if (deadline !== undefined && (Date.now() >= deadline || isTimeoutError(e))) throw e
130
+ return undefined
131
+ }
58
132
  }
59
133
 
60
134
  /** 等光标飞到位:人眼先看到"要点这儿",再发真实事件 */
61
- const settle = (d) => sleep(Math.min(700, Math.max(120, d || 0)) + 40)
135
+ const settle = (d) => sleep(Math.min(280, Math.max(60, d || 0)) + 20)
62
136
 
63
137
  /** 用 scripting 在 MAIN world 收掉页内光标(不依赖 CDP,调试器已断开时也能收)。 */
64
138
  async function hidePageCursor(tabId) {
@@ -72,13 +146,25 @@ async function hidePageCursor(tabId) {
72
146
  }
73
147
 
74
148
  /** 标签上的小鼠标只跟"页内光标在不在":在 → 亮;hide / 导航 / 松手 → 灭。 */
75
- async function markCursor(tabId, on) {
149
+ async function markCursor(tabId, on, expectedEpoch) {
76
150
  const id = Number(tabId)
151
+ const stillValid = () => !on || expectedEpoch === undefined ||
152
+ (S.cursorReady.has(id) && S.showCursor && !S.paused && (S.controlEpoch.get(id) || 0) === expectedEpoch)
153
+ if (!stillValid()) return
77
154
  try {
78
155
  await chrome.action.setIcon({ tabId: id, path: on ? CURSOR_ICON : IDLE_ICON })
156
+ if (!stillValid()) return
79
157
  await chrome.action.setTitle({ tabId: id, title: on ? CURSOR_TAB_TITLE[S.UI_LANG] : '' })
80
158
  } catch {}
159
+ if (!stillValid()) return
81
160
  await setTabFavicon(id, on)
161
+ if (on && expectedEpoch !== undefined && !stillValid()) {
162
+ try {
163
+ await chrome.action.setIcon({ tabId: id, path: IDLE_ICON })
164
+ await chrome.action.setTitle({ tabId: id, title: '' })
165
+ } catch {}
166
+ await setTabFavicon(id, false)
167
+ }
82
168
  }
83
169
 
84
170
  async function installInputListener(tabId) {
@@ -86,11 +172,87 @@ async function installInputListener(tabId) {
86
172
  await chrome.scripting.executeScript({ target: { tabId, allFrames: true }, world: 'ISOLATED', injectImmediately: true, func: () => {
87
173
  if (globalThis.__dshInputInstalled) return
88
174
  globalThis.__dshInputInstalled = true
89
- let last = -Infinity
175
+ let lastRepeat = -Infinity
90
176
  const onInput = ev => {
91
- if (ev.isTrusted !== true || performance.now() - last < 200) return
92
- last = performance.now()
93
- chrome.runtime.sendMessage({ bridgeEvent: 'userInput', type: ev.type }).catch(() => {})
177
+ if (ev.isTrusted !== true) return
178
+ if (ev.repeat) {
179
+ const now = performance.now()
180
+ if (now - lastRepeat < 200) return
181
+ lastRepeat = now
182
+ }
183
+ let isTop = true
184
+ let coordsTop = true
185
+ let px = Number.isFinite(ev.clientX) ? ev.clientX : NaN
186
+ let py = Number.isFinite(ev.clientY) ? ev.clientY : NaN
187
+ try {
188
+ isTop = window === window.top
189
+ if (!isTop) {
190
+ const badTransform = (st) => {
191
+ if (!st) return false
192
+ const tf = st.transform
193
+ if (tf && tf !== 'none') {
194
+ const m = /^matrix\(\s*([+-]?[\d.eE]+)\s*,\s*0\s*,\s*0\s*,\s*([+-]?[\d.eE]+)\s*,/.exec(tf)
195
+ if (!m || !(Number(m[1]) > 0) || !(Number(m[2]) > 0)) return true
196
+ }
197
+ const rt = st.rotate
198
+ if (rt && rt !== 'none' && rt !== '0deg') return true
199
+ const sc = st.scale
200
+ if (sc && sc !== 'none') {
201
+ const nums = String(sc).trim().split(/\s+/).map(Number)
202
+ if (!nums.length || nums.some(n => !(n > 0))) return true
203
+ }
204
+ return false
205
+ }
206
+ let w = window
207
+ while (w && w !== window.top) {
208
+ const f = w.frameElement
209
+ if (!f) { coordsTop = false; break }
210
+ const fr = f.getBoundingClientRect()
211
+ const getCs = w.parent && typeof w.parent.getComputedStyle === 'function' ? (n) => w.parent.getComputedStyle(n) : null
212
+ const fs = getCs ? getCs(f) : null
213
+ let mirroredOrRotated = badTransform(fs)
214
+ if (!mirroredOrRotated && getCs) {
215
+ const nextAnc = (n) => {
216
+ if (!n) return null
217
+ if (n.assignedSlot) return n.assignedSlot
218
+ if (n.parentElement) return n.parentElement
219
+ const root = typeof n.getRootNode === 'function' ? n.getRootNode() : null
220
+ return root && root !== n ? (root.host || null) : null
221
+ }
222
+ let anc = nextAnc(f)
223
+ let steps = 0
224
+ for (; anc && steps < 64; steps++) {
225
+ if (badTransform(getCs(anc))) { mirroredOrRotated = true; break }
226
+ anc = nextAnc(anc)
227
+ }
228
+ if (anc) mirroredOrRotated = true
229
+ }
230
+ if (mirroredOrRotated) { coordsTop = false; break }
231
+ const sx = f.offsetWidth > 0 && Number.isFinite(fr.width) ? fr.width / f.offsetWidth : 1
232
+ const sy = f.offsetHeight > 0 && Number.isFinite(fr.height) ? fr.height / f.offsetHeight : 1
233
+ if (Number.isFinite(px) && Number.isFinite(py)) {
234
+ px = fr.left + sx * (px + (f.clientLeft || 0) + (parseFloat(fs && fs.paddingLeft) || 0))
235
+ py = fr.top + sy * (py + (f.clientTop || 0) + (parseFloat(fs && fs.paddingTop) || 0))
236
+ }
237
+ w = w.parent
238
+ }
239
+ }
240
+ } catch {
241
+ isTop = false
242
+ coordsTop = false
243
+ }
244
+ const msg = { bridgeEvent: 'userInput', type: ev.type, top: isTop, coordsTop }
245
+ if (ev.type === 'keydown') {
246
+ if (typeof ev.key === 'string') msg.key = ev.key
247
+ if (typeof ev.code === 'string') msg.code = ev.code
248
+ } else {
249
+ if (typeof ev.button === 'number') msg.button = ev.button
250
+ if (Number.isFinite(ev.clientX) && Number.isFinite(ev.clientY)) {
251
+ msg.x = Math.round(coordsTop ? px : ev.clientX)
252
+ msg.y = Math.round(coordsTop ? py : ev.clientY)
253
+ }
254
+ }
255
+ chrome.runtime.sendMessage(msg).catch(() => {})
94
256
  }
95
257
  for (const type of ['pointerdown', 'keydown']) window.addEventListener(type, onInput, { capture: true, passive: true })
96
258
  } })
@@ -137,43 +299,312 @@ function refreshControls(tabId) {
137
299
  if (S.activeHandoff?.tabId === tabId && !S.activeHandoff.settled) void mountHandoff(S.activeHandoff)
138
300
  }
139
301
 
140
- function beginAgentInput(tabId, ms = 1500) { S.agentInputUntil.set(Number(tabId), Date.now() + ms) }
141
- function endAgentInput(tabId, graceMs = 150) {
142
- if (S.attached.has(Number(tabId))) S.agentInputUntil.set(Number(tabId), Date.now() + graceMs)
143
- else S.agentInputUntil.delete(Number(tabId))
302
+ const BUTTON_INDEX = { left: 0, middle: 1, right: 2, back: 3, forward: 4 }
303
+
304
+ function agentInputSpec(method, params) {
305
+ if (method === 'Input.dispatchMouseEvent' && params?.type === 'mousePressed') {
306
+ const spec = { kind: 'pointerdown' }
307
+ if (params.button && Object.hasOwn(BUTTON_INDEX, params.button)) spec.button = BUTTON_INDEX[params.button]
308
+ if (Number.isFinite(Number(params.x)) && Number.isFinite(Number(params.y))) {
309
+ spec.x = Math.round(Number(params.x))
310
+ spec.y = Math.round(Number(params.y))
311
+ }
312
+ return [spec]
313
+ }
314
+ if (method === 'Input.dispatchTouchEvent' && params?.type === 'touchStart') return [{ kind: 'pointerdown' }]
315
+ if (method === 'Input.dispatchKeyEvent' && params?.type !== 'keyUp') {
316
+ const spec = { kind: 'keydown' }
317
+ if (typeof params?.key === 'string' && params.key) spec.key = params.key
318
+ if (typeof params?.code === 'string' && params.code) spec.code = params.code
319
+ return [spec]
320
+ }
321
+ if (method === 'Input.insertText') return []
322
+ if (typeof method === 'string' && method.startsWith('Input.')) {
323
+ if (method === 'Input.dispatchMouseEvent' || method === 'Input.dispatchTouchEvent' || method === 'Input.dispatchKeyEvent') return []
324
+ return [{ kind: 'pointerdown' }, { kind: 'keydown' }]
325
+ }
326
+ return []
327
+ }
328
+
329
+ function agentInputKinds(method, params) {
330
+ return agentInputSpec(method, params).map(s => s.kind)
331
+ }
332
+
333
+ function beginAgentInput(tabId, ms = 1500, kindsOrSpecs = ['pointerdown', 'keydown']) {
334
+ if (!kindsOrSpecs || !kindsOrSpecs.length) return []
335
+ const id = Number(tabId)
336
+ const now = Date.now()
337
+ const until = now + ms
338
+ const specs = kindsOrSpecs.map(item => (typeof item === 'string' ? { kind: item } : { ...item }))
339
+ S.agentInputUntil.set(id, Math.max(S.agentInputUntil.get(id) || 0, until))
340
+ const list = (S.agentInputEvents.get(id) || []).filter(e => e.expiresAt > now)
341
+ const tokens = []
342
+ for (const s of specs) {
343
+ S.agentInputKindUntil.set(`${id}:${s.kind}`, Math.max(S.agentInputKindUntil.get(`${id}:${s.kind}`) || 0, until))
344
+ const entry = { ...s, expiresAt: until }
345
+ list.push(entry)
346
+ tokens.push(entry)
347
+ }
348
+ S.agentInputEvents.set(id, list)
349
+ return tokens
350
+ }
351
+ function endAgentInput(tabId, graceMs = 150, kindsOrTokens = ['pointerdown', 'keydown']) {
352
+ if (!kindsOrTokens || !kindsOrTokens.length) return
353
+ const id = Number(tabId)
354
+ const now = Date.now()
355
+ if (S.attached.has(id)) {
356
+ const until = now + graceMs
357
+ const list = (S.agentInputEvents.get(id) || []).filter(e => e.expiresAt > now)
358
+ for (const item of kindsOrTokens) {
359
+ if (typeof item === 'string') {
360
+ S.agentInputKindUntil.set(`${id}:${item}`, until)
361
+ for (const e of list) if (e.kind === item) e.expiresAt = Math.min(e.expiresAt, until)
362
+ } else if (item && typeof item === 'object') {
363
+ item.expiresAt = Math.min(item.expiresAt, until)
364
+ S.agentInputKindUntil.set(`${id}:${item.kind}`, Math.max(until, ...list.filter(e => e.kind === item.kind).map(e => e.expiresAt)))
365
+ }
366
+ }
367
+ if (list.length) S.agentInputEvents.set(id, list)
368
+ else S.agentInputEvents.delete(id)
369
+ const maxUntil = Math.max(
370
+ S.agentInputKindUntil.get(`${id}:pointerdown`) || 0,
371
+ S.agentInputKindUntil.get(`${id}:keydown`) || 0,
372
+ )
373
+ if (maxUntil > 0) S.agentInputUntil.set(id, maxUntil)
374
+ } else {
375
+ S.agentInputUntil.delete(id)
376
+ S.agentInputKindUntil.delete(`${id}:pointerdown`)
377
+ S.agentInputKindUntil.delete(`${id}:keydown`)
378
+ S.agentInputEvents.delete(id)
379
+ }
144
380
  }
145
- async function agentInput(tabId, action) {
146
- beginAgentInput(tabId)
381
+ function cancelAgentInput(tabId, tokens) {
382
+ if (!tokens || !tokens.length) return
383
+ const id = Number(tabId)
384
+ const drop = new Set(tokens)
385
+ const list = (S.agentInputEvents.get(id) || []).filter(e => !drop.has(e) && e.expiresAt > Date.now())
386
+ if (list.length) {
387
+ S.agentInputEvents.set(id, list)
388
+ for (const k of ['pointerdown', 'keydown']) {
389
+ const untils = list.filter(e => e.kind === k).map(e => e.expiresAt)
390
+ if (untils.length) S.agentInputKindUntil.set(`${id}:${k}`, Math.max(...untils))
391
+ else S.agentInputKindUntil.delete(`${id}:${k}`)
392
+ }
393
+ S.agentInputUntil.set(id, Math.max(...list.map(e => e.expiresAt)))
394
+ } else {
395
+ S.agentInputEvents.delete(id)
396
+ S.agentInputKindUntil.delete(`${id}:pointerdown`)
397
+ S.agentInputKindUntil.delete(`${id}:keydown`)
398
+ S.agentInputUntil.delete(id)
399
+ }
400
+ }
401
+ function isAgentInputActive(tabId, msgOrKind, sender) {
402
+ const id = Number(tabId)
403
+ const now = Date.now()
404
+ if (now >= (S.agentInputUntil.get(id) || 0)) return false
405
+ const msg = typeof msgOrKind === 'string' ? { type: msgOrKind } : (msgOrKind || {})
406
+ const kind = msg.type
407
+ if (now >= (S.agentInputKindUntil.get(`${id}:${kind}`) || 0)) return false
408
+ const list = S.agentInputEvents.get(id)
409
+ if (!list || !list.length) return false
410
+ const hasTopCoords = msg.coordsTop === true || (msg.coordsTop !== false && msg.top !== false && (sender?.frameId == null || sender.frameId === 0))
411
+ const alive = list.filter(e => e.expiresAt > now)
412
+ const idx = alive.findIndex(e => {
413
+ if (e.kind !== kind) return false
414
+ if (kind === 'keydown') {
415
+ if (e.key != null || e.code != null) {
416
+ const keyHit = e.key != null && msg.key != null && msg.key.toLowerCase() === e.key.toLowerCase()
417
+ const codeHit = e.code != null && msg.code != null && msg.code === e.code
418
+ if (!keyHit && !codeHit) return false
419
+ }
420
+ } else if (kind === 'pointerdown') {
421
+ if (e.button != null && msg.button !== e.button) return false
422
+ // 顶层文档及已换算为顶层坐标的同源 iframe 均严格比对坐标;仅跨站子框局部坐标豁免
423
+ if (hasTopCoords && e.x != null && e.y != null) {
424
+ if (msg.x == null || msg.y == null || Math.hypot(msg.x - e.x, msg.y - e.y) > 16) return false
425
+ }
426
+ }
427
+ return true
428
+ })
429
+ if (idx < 0) {
430
+ if (alive.length) S.agentInputEvents.set(id, alive)
431
+ else S.agentInputEvents.delete(id)
432
+ return false
433
+ }
434
+ // 一次注入事件只消费一个配额,避免窗口内把紧接着的真人按键/点击也吞掉
435
+ alive.splice(idx, 1)
436
+ if (alive.length) S.agentInputEvents.set(id, alive)
437
+ else S.agentInputEvents.delete(id)
438
+ return true
439
+ }
440
+ async function agentInput(tabId, action, kinds = ['pointerdown', 'keydown']) {
441
+ if (!kinds || !kinds.length) return action()
442
+ const tokens = beginAgentInput(tabId, 1500, kinds)
147
443
  try { return await action() }
148
- finally { endAgentInput(tabId) }
444
+ finally { endAgentInput(tabId, 150, tokens) }
445
+ }
446
+
447
+ /** 动作发出前重查暂停、放开代次、人工接管与截止时间,防止光标滑行途中过期或与人撞车 */
448
+ function makeClickGuard(tabId, deadline, extraCheck) {
449
+ const id = Number(tabId)
450
+ const epoch = S.controlEpoch.get(id) || 0
451
+ return () => {
452
+ if (S.paused) throw new Error(PAUSED_MSG)
453
+ const user = S.userTakeover.get(id)
454
+ if (user && Date.now() - user.at <= 12000) throw new Error(`USER_ACTIVE ${user.type}`)
455
+ if ((S.controlEpoch.get(id) || 0) !== epoch) throw new Error(RELEASED_MSG)
456
+ if (deadline !== undefined) timeLeft(deadline)
457
+ if (typeof extraCheck === 'function') extraCheck()
458
+ }
459
+ }
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
+ }
149
515
  }
150
516
 
151
517
  async function clickPoint(tabId, x, y, opts = {}) {
518
+ const id = Number(tabId)
152
519
  const n = Number(opts.clickCount || 1)
153
520
  const button = opts.button || 'left'
154
521
  const budget = () => opts.deadline && timeLeft(opts.deadline)
155
522
  const base = { x: Math.round(x), y: Math.round(y), button, clickCount: n }
156
523
 
524
+ if (typeof opts.check === 'function') opts.check()
525
+
157
526
  // 先让光标飞过去,人眼看得见,再发真实点击
158
527
  if (opts.cursor && S.showCursor) {
159
- 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 })
160
529
  if (d !== null) {
161
- await (opts.deadline ? within(settle(d), budget(), '等待光标超时') : settle(d))
162
- await cursorFx(tabId, `(window.__dshCursor.click(${base.x}, ${base.y}, ${n}), 1)`, opts.deadline)
530
+ if (typeof opts.check === 'function') opts.check()
531
+ await cursorFx(tabId, `(window.__dshCursor.beginAgent && window.__dshCursor.beginAgent(1500), window.__dshCursor.click(${base.x}, ${base.y}, ${n}), 1)`, opts.deadline)
532
+ if (S.cursorReady.has(id)) S.pageAgentUntil.set(id, Date.now() + 1500)
163
533
  }
164
534
  }
165
535
 
166
- return agentInput(tabId, async () => {
536
+ if (typeof opts.check === 'function') 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)
541
+ await new Promise(r => setTimeout(r, 12))
542
+ return withChooser(tabId, opts.chooser, async () => {
167
543
  if (typeof opts.check === 'function') opts.check()
168
- await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mouseMoved', buttons: 0 }, budget())
169
- await new Promise(r => setTimeout(r, 12))
170
- return withChooser(tabId, opts.chooser, async () => {
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()
555
+ }
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)
571
+ const pressSeq = pressMeta.attachSeq
572
+ await new Promise(r => setTimeout(r, 24))
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()) {
171
582
  if (typeof opts.check === 'function') opts.check()
172
- await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mousePressed', buttons: ({ left: 1, right: 2, middle: 4, back: 8, forward: 16 })[button] || 1 }, budget())
173
- await new Promise(r => setTimeout(r, 24))
174
- await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mouseReleased', buttons: 0 }, opts.deadline ? Math.max(1, opts.deadline - Date.now()) : undefined)
583
+ throw new Error(RELEASED_MSG)
584
+ }
585
+ if (relNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== relNavGen) {
175
586
  return { x: base.x, y: base.y, button }
176
- })
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
+ }
598
+ const relTimeout = opts.deadline ? Math.max(1, opts.deadline - Date.now()) : 15000
599
+ let relTimer
600
+ try {
601
+ await Promise.race([
602
+ chrome.debugger.sendCommand({ tabId: id }, 'Input.dispatchMouseEvent', { ...base, type: 'mouseReleased', buttons: 0 }),
603
+ new Promise((_, rej) => { relTimer = setTimeout(() => rej(new Error(`CDP Input.dispatchMouseEvent ${Math.round(relTimeout / 1000)} 秒没回应`)), relTimeout) }),
604
+ ])
605
+ } finally { clearTimeout(relTimer) }
606
+ S.postReleaseAt.set(id, Date.now())
607
+ return { x: base.x, y: base.y, button }
177
608
  })
178
609
  }
179
610
 
@@ -187,7 +618,7 @@ const NAMED_KEYS = {
187
618
  pagedown: ['PageDown', 'PageDown', 34], space: [' ', 'Space', 32, ' '],
188
619
  }
189
620
 
190
- async function pressKey(tabId, spec) {
621
+ async function pressKey(tabId, spec, opts = {}) {
191
622
  const parts = String(spec).split('+').map(s => s.trim()).filter(Boolean)
192
623
  const keyName = parts.pop()
193
624
  let modifiers = 0
@@ -212,15 +643,68 @@ async function pressKey(tabId, spec) {
212
643
  }
213
644
  const suppressText = modifiers !== 0 || !text
214
645
  const base = { key, code, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode, modifiers }
215
- return agentInput(tabId, async () => {
216
- await send(tabId, 'Input.dispatchKeyEvent', {
217
- ...base, type: suppressText ? 'rawKeyDown' : 'keyDown',
218
- ...(suppressText ? {} : { text, unmodifiedText: text }),
219
- })
220
- await new Promise(r => setTimeout(r, 12))
221
- await send(tabId, 'Input.dispatchKeyEvent', { ...base, type: 'keyUp' })
222
- return { key: spec, modifiers }
223
- })
646
+ const id = Number(tabId)
647
+ const budget = () => (opts.deadline !== undefined ? timeLeft(opts.deadline) : undefined)
648
+ if (typeof opts.check === 'function') opts.check()
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
+ }
675
+ await send(tabId, 'Input.dispatchKeyEvent', {
676
+ ...base, type: suppressText ? 'rawKeyDown' : 'keyDown',
677
+ ...(suppressText ? {} : { text, unmodifiedText: text }),
678
+ }, budget(), keyGuard, pressMeta)
679
+ const pressSeq = pressMeta.attachSeq
680
+ await new Promise(r => setTimeout(r, 12))
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()) {
684
+ if (typeof opts.check === 'function') opts.check()
685
+ throw new Error(RELEASED_MSG)
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
+ }
705
+ await chrome.debugger.sendCommand({ tabId: id }, 'Input.dispatchKeyEvent', { ...base, type: 'keyUp' })
706
+ S.postReleaseAt.set(id, Date.now())
707
+ return { key: spec, modifiers }
224
708
  }
225
709
 
226
710
  async function unmountHandoff(tabId, id) {
@@ -235,7 +719,8 @@ async function unmountHandoff(tabId, id) {
235
719
  }
236
720
 
237
721
  export {
238
- injectCursor, cursorDo, cursorMove, cursorFx, settle, hidePageCursor, markCursor,
239
- installInputListener, mountHandoff, refreshControls, beginAgentInput, endAgentInput,
240
- agentInput, clickPoint, MODS, NAMED_KEYS, pressKey, unmountHandoff,
722
+ moveForAction,
723
+ RELEASED_MSG, bumpControlEpoch, injectCursor, cursorDo, cursorMove, cursorFx, settle, hidePageCursor, markCursor,
724
+ installInputListener, mountHandoff, refreshControls, agentInputSpec, agentInputKinds, beginAgentInput, endAgentInput,
725
+ cancelAgentInput, isAgentInputActive, agentInput, makeClickGuard, clickPoint, MODS, NAMED_KEYS, pressKey, unmountHandoff,
241
726
  }