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
package/core/transport.js CHANGED
@@ -4,7 +4,7 @@ import path from 'node:path'
4
4
  import crypto from 'node:crypto'
5
5
  import { AsyncLocalStorage } from 'node:async_hooks'
6
6
  import { installHint, assistInstall } from '../setup.js'
7
- import { bridgeDir, resolveHost, tokenLines } from './hosts.js'
7
+ import { bridgeDir, resolveHost } from './hosts.js'
8
8
  import { t } from './locale.js'
9
9
 
10
10
  // socket / token / 日志都在只有当前用户进得去的 /tmp/dsh-bridge-<uid>/(和宿主、cb 同一个约定):
@@ -15,6 +15,13 @@ const WIN = process.platform === 'win32'
15
15
  const UID = typeof process.getuid === 'function' ? process.getuid() : null
16
16
 
17
17
  let sessionHostGetter = null
18
+ let forgetClosedTab = null
19
+ let cachedEndpoint
20
+ const ENDPOINT_TTL_MS = 1000
21
+
22
+ export function setClosedTabHandler(fn) {
23
+ forgetClosedTab = fn
24
+ }
18
25
  export function setSessionHostGetter(fn) {
19
26
  sessionHostGetter = typeof fn === 'function' ? fn : null
20
27
  }
@@ -22,9 +29,22 @@ export function setSessionHostGetter(fn) {
22
29
  // 统一按 host/profile、当前调用上下文(callInfo.host)、会话绑定宿主、最近聚焦宿主或旧单路径解析目标。
23
30
  export function resolveEndpoint(host) {
24
31
  const store = callInfo.getStore()
25
- const explicit = host !== undefined && host !== null && host !== '' ? host : (store?.host || null)
26
- const sessionHost = !explicit && sessionHostGetter ? sessionHostGetter() : null
27
- return resolveHost({ host: explicit, sessionHost })
32
+ const selectedHost = host || store?.host || null
33
+ const explicit = Boolean(selectedHost)
34
+ const sessionHost = !selectedHost && sessionHostGetter ? sessionHostGetter() : null
35
+ const env = JSON.stringify([bridgeDir(), process.env.DSH_BRIDGE_SOCK, process.env.DSH_BRIDGE_TOKEN])
36
+ const route = selectedHost || sessionHost
37
+ if (cachedEndpoint?.env === env && performance.now() < cachedEndpoint.until &&
38
+ cachedEndpoint.explicit === explicit &&
39
+ (cachedEndpoint.route === route || (route !== null && route === cachedEndpoint.endpoint.id))) {
40
+ return cachedEndpoint.endpoint
41
+ }
42
+ cachedEndpoint = undefined
43
+ const endpoint = resolveHost({ host: selectedHost, sessionHost })
44
+ if (typeof route !== 'object' || route === null) {
45
+ cachedEndpoint = { route, explicit, env, endpoint, until: performance.now() + ENDPOINT_TTL_MS }
46
+ }
47
+ return endpoint
28
48
  }
29
49
 
30
50
  /** 宿主起没起:socket 文件在不在;Windows 看 token 文件或注册表里有没有管道名(宿主退出时会删掉) */
@@ -108,6 +128,21 @@ const HINT = () => installHint() + firstAid()
108
128
  */
109
129
  export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {}) {
110
130
  const hint = () => (quiet ? '' : HINT())
131
+ const store = callInfo.getStore()
132
+ if (store?.batch?.tabId === args.tabId && Number.isInteger(store?.batch?.controlEpoch)) {
133
+ args = { ...args, controlEpoch: store.batch.controlEpoch }
134
+ if (op === 'eval') args.requireControl = true
135
+ if (store.batch.stopOnNav && ['act', 'click', 'dragGesture', 'waitCondition', 'networkIdle'].includes(op) &&
136
+ (store.batch.expectedUrlHash || store.batch.expectedDocToken != null || Number.isInteger(store.batch.expectedNavGen))) {
137
+ if (store.batch.expectedUrlHash && args.expectedUrlHash === undefined) args.expectedUrlHash = store.batch.expectedUrlHash
138
+ if (store.batch.expectedDocToken != null && args.expectedDocToken === undefined) {
139
+ args.expectedDocToken = store.batch.expectedDocToken
140
+ }
141
+ if (Number.isInteger(store.batch.expectedNavGen) && args.expectedNavGen === undefined) {
142
+ args.expectedNavGen = store.batch.expectedNavGen
143
+ }
144
+ }
145
+ }
111
146
  return new Promise((resolve, reject) => {
112
147
  let endpoint
113
148
  try {
@@ -115,12 +150,16 @@ export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {})
115
150
  } catch (e) {
116
151
  return reject(e)
117
152
  }
153
+ const fail = (error) => {
154
+ if (cachedEndpoint?.endpoint === endpoint) cachedEndpoint = undefined
155
+ reject(error)
156
+ }
118
157
  const { socket, tokenFile, dir } = endpoint
119
158
  if (!hostUp(endpoint)) {
120
- return reject(new Error(t('err.bridgeDown', { sock: socket || tokenFile || dir, hint: hint() })))
159
+ return fail(new Error(t('err.bridgeDown', { sock: socket || tokenFile || dir, hint: hint() })))
121
160
  }
122
- try { checkDir(WIN ? dir : path.dirname(socket)) } catch (e) { return reject(e) }
123
- const token = endpoint.token || (tokenFile ? tokenLines(tokenFile)[0] : null) || null
161
+ try { checkDir(WIN ? dir : path.dirname(socket)) } catch (e) { return fail(e) }
162
+ const token = endpoint.token || null
124
163
  const id = crypto.randomUUID()
125
164
  const sock = net.connect(socket)
126
165
  let acc = ''
@@ -134,10 +173,9 @@ export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {})
134
173
  fn(v)
135
174
  }
136
175
  sock.setEncoding('utf8')
137
- const store = callInfo.getStore()
138
176
  let client = BASE_CLIENT
139
177
  if (store) {
140
- const { host: _host, ...rest } = store
178
+ const { host: _host, batch: _batch, ...rest } = store
141
179
  client = rest
142
180
  }
143
181
  // timeoutMs 也带给宿主:它按这个等扩展,不再一律 45 秒(等元素、截图这类慢操作以前必定被它掐掉)
@@ -147,23 +185,35 @@ export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {})
147
185
  const i = acc.indexOf('\n')
148
186
  if (i < 0) return
149
187
  let msg
150
- try { msg = JSON.parse(acc.slice(0, i)) } catch { return finish(reject, new Error(t('err.badJson'))) }
188
+ try { msg = JSON.parse(acc.slice(0, i)) } catch { return finish(fail, new Error(t('err.badJson'))) }
151
189
  if (msg.ok) return finish(resolve, msg.result)
152
190
  const message = String(msg.error || t('err.unknownHostError'))
191
+ const tabId = args.tabId ?? args.openerTabId
192
+ if (tabId != null && /No tab with id|tab (?:has been |was |is )?closed|标签页已经不存在|标签页(?:已被|已|被)关闭|вкладка закрыта/i.test(message)) {
193
+ forgetClosedTab?.(tabId, endpoint.id)
194
+ const error = new Error(t('err.noTab'))
195
+ error.code = 'NO_TAB'
196
+ return finish(fail, error)
197
+ }
153
198
  if (message.startsWith('USER_ACTIVE ')) {
154
199
  const error = new Error(t('err.userActive'))
155
200
  error.code = 'USER_ACTIVE'
156
- return finish(reject, error)
201
+ return finish(fail, error)
157
202
  }
158
203
  if (message.startsWith('USER_DENIED_SENSITIVE')) {
159
204
  const error = new Error(t('err.userDeniedSensitive'))
160
205
  error.code = 'USER_DENIED_SENSITIVE'
161
- return finish(reject, error)
206
+ return finish(fail, error)
162
207
  }
163
208
  if (message.startsWith('CONFIRM_LATE')) {
164
209
  const error = new Error(t('err.confirmLate'))
165
210
  error.code = 'CONFIRM_LATE'
166
- return finish(reject, error)
211
+ return finish(fail, error)
212
+ }
213
+ if (message.startsWith('BATCH_NAVIGATED')) {
214
+ const error = new Error(message)
215
+ error.code = 'BATCH_NAVIGATED'
216
+ return finish(fail, error)
167
217
  }
168
218
  const disconnected = /扩展未连接|扩展.{0,12}(?:没装|未装|被停用)|extension.{0,20}(?:not connected|not installed|disabled)/i
169
219
  const hostTimeout = /扩展 (\d+ms) 没回|CDP .+? (\d+) 秒没回应/i.exec(message)
@@ -172,19 +222,19 @@ export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {})
172
222
  : message + (disconnected.test(message) ? hint() : '')
173
223
  const failure = new Error(error)
174
224
  if (hostTimeout) failure.code = 'EXTENSION_TIMEOUT'
175
- finish(reject, failure)
225
+ finish(fail, failure)
176
226
  })
177
227
  sock.on('error', (e) => {
178
228
  const message = e.code === 'ECONNREFUSED' ? t('err.staleSocket')
179
229
  : ['ECONNRESET', 'EPIPE'].includes(e.code) ? t('err.closed')
180
230
  : t('err.connect', { message: e.message, hint: hint() })
181
- finish(reject, new Error(message))
231
+ finish(fail, new Error(message))
182
232
  })
183
- sock.on('close', () => finish(reject, new Error(t('err.closed'))))
233
+ sock.on('close', () => finish(fail, new Error(t('err.closed'))))
184
234
  timer = setTimeout(() => {
185
235
  const err = new Error(t('err.timeout', { ms: `${timeoutMs}ms` }))
186
236
  err.code = 'EXTENSION_TIMEOUT'
187
- finish(reject, err)
237
+ finish(fail, err)
188
238
  }, timeoutMs)
189
239
  })
190
240
  }
package/drag.js CHANGED
@@ -47,10 +47,10 @@ const elementJs = (end) =>
47
47
  : 'null'
48
48
 
49
49
  const isElementEnd = (end) => hasRef(end) || !!end.selector || !!end.text
50
- const describe = (end) =>
51
- hasRef(end)
50
+ export const describeDragEnd = (end) =>
51
+ end.label || (hasRef(end)
52
52
  ? `[${end.ref}]`
53
- : end.selector || (end.text ? tt('res.drag.quotedText', { text: end.text }) : `(${end.x}, ${end.y})`)
53
+ : end.selector || (end.text ? tt('res.drag.quotedText', { text: end.text }) : `(${end.x}, ${end.y})`))
54
54
 
55
55
  /** 一次 eval 算出两端的视口坐标,顺带判断是不是原生拖放。 */
56
56
  const PLAN_JS = (from, to) => `(async () => {
@@ -59,31 +59,93 @@ const PLAN_JS = (from, to) => `(async () => {
59
59
  if (${isElementEnd(from)} && !src) return { missing: 'from' };
60
60
  if (${isElementEnd(to)} && !dst) return { missing: 'to' };
61
61
  if (src && src === dst) return { same: true };
62
+ const sx0 = window.scrollX || 0, sy0 = window.scrollY || 0;
63
+ const scrollWithFrames = (el) => {
64
+ const frames = [];
65
+ for (let w = el.ownerDocument && el.ownerDocument.defaultView; w && w !== window && w.frameElement; w = w.parent) frames.push(w.frameElement);
66
+ for (let i = frames.length - 1; i >= 0; i--) frames[i].scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'instant' });
67
+ el.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'instant' });
68
+ };
62
69
  if (src) {
63
- src.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'instant' });
70
+ scrollWithFrames(src);
64
71
  // 后台标签页会暂停 rAF,定时器兜底
65
72
  await new Promise((res) => { requestAnimationFrame(() => requestAnimationFrame(res)); setTimeout(res, 120); });
66
73
  }
67
- const mid = (el) => { const r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; };
68
- const a = src ? mid(src) : { x: ${Number(from.x) || 0}, y: ${Number(from.y) || 0} };
69
- const b = dst ? mid(dst) : { x: ${Number(to.x) || 0}, y: ${Number(to.y) || 0} };
70
- const hit = src || document.elementFromPoint(a.x, a.y);
74
+ const mid = (el) => {
75
+ const r = el.getBoundingClientRect();
76
+ let left = r.left, top = r.top;
77
+ for (let w = el.ownerDocument && el.ownerDocument.defaultView; w && w !== window && w.frameElement; w = w.parent) {
78
+ const f = w.frameElement;
79
+ const fr = f.getBoundingClientRect();
80
+ const fs = f.ownerDocument.defaultView.getComputedStyle(f);
81
+ left += fr.left + f.clientLeft + (parseFloat(fs.paddingLeft) || 0);
82
+ top += fr.top + f.clientTop + (parseFloat(fs.paddingTop) || 0);
83
+ }
84
+ return { x: left + r.width / 2, y: top + r.height / 2 };
85
+ };
86
+ const deepHit = (doc, px, py) => {
87
+ let curDoc = doc, cx = px, cy = py, el = null;
88
+ for (let depth = 0; depth < 8 && curDoc; depth++) {
89
+ el = curDoc.elementFromPoint ? curDoc.elementFromPoint(cx, cy) : null;
90
+ if (!el || (el.tagName !== 'IFRAME' && el.tagName !== 'FRAME')) break;
91
+ let childDoc = null;
92
+ try { childDoc = el.contentDocument; } catch {}
93
+ if (!childDoc) break;
94
+ const fr = el.getBoundingClientRect();
95
+ const fs = (el.ownerDocument && el.ownerDocument.defaultView ? el.ownerDocument.defaultView : window).getComputedStyle(el);
96
+ cx -= fr.left + (el.clientLeft || 0) + (parseFloat(fs && fs.paddingLeft) || 0);
97
+ cy -= fr.top + (el.clientTop || 0) + (parseFloat(fs && fs.paddingTop) || 0);
98
+ curDoc = childDoc;
99
+ }
100
+ return el;
101
+ };
102
+ const dx = (window.scrollX || 0) - sx0, dy = (window.scrollY || 0) - sy0;
103
+ const a = src ? mid(src) : { x: ${Number(from.x) || 0} - (${Boolean(from.crossFrame)} ? dx : 0), y: ${Number(from.y) || 0} - (${Boolean(from.crossFrame)} ? dy : 0) };
104
+ const b = dst ? mid(dst) : { x: ${Number(to.x) || 0} - (${Boolean(to.crossFrame)} ? dx : 0), y: ${Number(to.y) || 0} - (${Boolean(to.crossFrame)} ? dy : 0) };
105
+ const hit = src || deepHit(document, a.x, a.y);
71
106
  const native = !!(hit && hit.closest && hit.closest('[draggable="true"]'));
72
- const inView = (p) => p.x >= 0 && p.y >= 0 && p.x <= innerWidth && p.y <= innerHeight;
107
+ const inView = (p) => p.x >= 0 && p.y >= 0 && p.x < innerWidth && p.y < innerHeight;
73
108
  return { a, b, native, aIn: inView(a), bIn: inView(b) };
74
109
  })()`
75
110
 
76
- /** HTML5 原生拖放:页面里合成整套 DragEvent。 */
111
+ /** HTML5 原生拖放:页面里合成整套 DragEvent(支持同源 iframe 与 shadow DOM 目标)。 */
77
112
  const NATIVE_JS = (from, to, a, b) => `(() => {
78
- const start = ${elementJs(from)} || document.elementFromPoint(${a.x}, ${a.y});
79
- const src = start.closest('[draggable="true"]') || start;
80
- const tgt = ${elementJs(to)} || document.elementFromPoint(${b.x}, ${b.y});
81
- if (!tgt) return { error: 'no-target' };
113
+ const deepHit = (doc, px, py) => {
114
+ let curDoc = doc, cx = px, cy = py, el = null;
115
+ for (let depth = 0; depth < 8 && curDoc; depth++) {
116
+ el = curDoc.elementFromPoint ? curDoc.elementFromPoint(cx, cy) : null;
117
+ if (!el || (el.tagName !== 'IFRAME' && el.tagName !== 'FRAME')) break;
118
+ let childDoc = null;
119
+ try { childDoc = el.contentDocument; } catch {}
120
+ if (!childDoc) break;
121
+ const fr = el.getBoundingClientRect();
122
+ const fs = (el.ownerDocument && el.ownerDocument.defaultView ? el.ownerDocument.defaultView : window).getComputedStyle(el);
123
+ cx -= fr.left + (el.clientLeft || 0) + (parseFloat(fs && fs.paddingLeft) || 0);
124
+ cy -= fr.top + (el.clientTop || 0) + (parseFloat(fs && fs.paddingTop) || 0);
125
+ curDoc = childDoc;
126
+ }
127
+ return { el, pt: { x: cx, y: cy } };
128
+ };
129
+ const startHit = ${isElementEnd(from)} ? { el: ${elementJs(from)}, pt: null } : deepHit(document, ${a.x}, ${a.y});
130
+ const start = startHit.el || document.elementFromPoint(${a.x}, ${a.y});
131
+ const src = start && start.closest ? (start.closest('[draggable="true"]') || start) : start;
132
+ const endHit = ${isElementEnd(to)} ? { el: ${elementJs(to)}, pt: null } : deepHit(document, ${b.x}, ${b.y});
133
+ const tgt = endHit.el || document.elementFromPoint(${b.x}, ${b.y});
134
+ if (!src || !tgt) return { error: 'no-target' };
82
135
  const dt = new DataTransfer();
83
- const fire = (el, type, p) => el.dispatchEvent(new DragEvent(type, {
84
- bubbles: true, cancelable: true, composed: true, clientX: p.x, clientY: p.y, dataTransfer: dt,
85
- }));
86
- const A = { x: ${a.x}, y: ${a.y} }, B = { x: ${b.x}, y: ${b.y} };
136
+ const ptOf = (el, fallback) => {
137
+ if (!el || typeof el.getBoundingClientRect !== 'function') return fallback;
138
+ const r = el.getBoundingClientRect();
139
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
140
+ };
141
+ const fire = (el, type, p) => {
142
+ const ViewDragEvent = (el.ownerDocument && el.ownerDocument.defaultView && el.ownerDocument.defaultView.DragEvent) || DragEvent;
143
+ return el.dispatchEvent(new ViewDragEvent(type, {
144
+ bubbles: true, cancelable: true, composed: true, clientX: p.x, clientY: p.y, dataTransfer: dt,
145
+ }));
146
+ };
147
+ const A = ${isElementEnd(from)} ? ptOf(src, { x: ${a.x}, y: ${a.y} }) : (startHit.pt || { x: ${a.x}, y: ${a.y} });
148
+ const B = ${isElementEnd(to)} ? ptOf(tgt, { x: ${b.x}, y: ${b.y} }) : (endHit.pt || { x: ${b.x}, y: ${b.y} });
87
149
  try {
88
150
  fire(src, 'dragstart', A);
89
151
  fire(tgt, 'dragenter', B);
@@ -101,43 +163,49 @@ const NATIVE_JS = (from, to, a, b) => `(() => {
101
163
  * 让用户看得见在拖什么;任何一步出错都不影响真实拖拽
102
164
  */
103
165
  export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
104
- const plan = (await call('eval', { tabId, expression: PLAN_JS(from, to), userGesture: false })).value
166
+ const planRes = await call('eval', { tabId, expression: PLAN_JS(from, to), userGesture: false, requireControl: true })
167
+ const plan = planRes && planRes.value
168
+ const epochArg = Number.isInteger(planRes && planRes.controlEpoch) ? { controlEpoch: planRes.controlEpoch } : {}
105
169
  if (!plan) throw new Error(tt('err.dragNoAnswer'))
106
170
  if (plan.missing) {
107
171
  const end = plan.missing === 'from' ? from : to
108
172
  throw new Error(
109
173
  tt('err.dragNotFound', {
110
174
  end: plan.missing === 'from' ? tt('which.start') : tt('which.end'),
111
- desc: describe(end),
175
+ desc: describeDragEnd(end),
112
176
  }) + (hasRef(end) ? tt('err.dragRefStale') : ''),
113
177
  )
114
178
  }
115
179
  if (plan.same) {
116
- throw new Error(tt('err.dragSame', { from: describe(from), to: describe(to) }))
180
+ throw new Error(tt('err.dragSame', { from: describeDragEnd(from), to: describeDragEnd(to) }))
117
181
  }
118
182
  const { a, b } = plan
119
- if (!plan.bIn) throw new Error(tt('err.dragOffscreen', { to: describe(to) }))
183
+ if (plan.aIn === false) throw new Error(tt('err.dragStartOffscreen', { from: describeDragEnd(from) }))
184
+ if (!plan.bIn) throw new Error(tt('err.dragOffscreen', { to: describeDragEnd(to) }))
185
+ if ((from.crossFrame && to.crossFrame) || ((plan.native || from.draggable) && (from.crossFrame || to.crossFrame))) {
186
+ throw new Error(tt('err.dragCrossFrameUnsupported'))
187
+ }
120
188
 
121
189
  const cur = async (fn) => {
122
190
  if (!cursor) return 0
123
191
  try { return Number(await fn(cursor)) || 0 } catch { return 0 }
124
192
  }
125
193
  // 光标先滑到起点亮名牌,到位了再按下
126
- if (cursor) await sleep(Math.min(700, await cur((c) => c.move(a.x, a.y, { label: tt('res.drag.label', { from: describe(from), to: describe(to) }) }))) + 60)
194
+ if (cursor) await sleep(Math.min(700, await cur((c) => c.move(a.x, a.y, { label: tt('res.drag.label', { from: describeDragEnd(from), to: describeDragEnd(to) }), ...epochArg }))) + 60)
127
195
 
128
196
  if (plan.native) {
129
197
  let r
130
198
  try {
131
- await cur((c) => c.down())
132
- await sleep(await cur((c) => c.move(b.x, b.y, { duration: 420, straight: true })))
133
- r = (await call('eval', { tabId, expression: NATIVE_JS(from, to, a, b) })).value
199
+ await cur((c) => c.down(epochArg))
200
+ await sleep(await cur((c) => c.move(b.x, b.y, { duration: 420, straight: true, ...epochArg })))
201
+ r = (await call('eval', { tabId, expression: NATIVE_JS(from, to, a, b), requireControl: true, ...epochArg })).value
134
202
  } finally {
135
- await cur((c) => c.up())
203
+ await cur((c) => c.up(epochArg))
136
204
  }
137
205
  if (r && r.error) throw new Error(tt('err.dragNoTarget'))
138
206
  return tt('res.drag.doneHtml5', {
139
- from: describe(from),
140
- to: describe(to),
207
+ from: describeDragEnd(from),
208
+ to: describeDragEnd(to),
141
209
  verdict: r && r.accepted ? tt('res.drag.accepted') : tt('res.drag.notAccepted'),
142
210
  })
143
211
  }
@@ -146,15 +214,20 @@ export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
146
214
  tabId,
147
215
  method: 'Input.dispatchMouseEvent',
148
216
  params: { type, x: Math.round(p.x), y: Math.round(p.y), ...extra },
217
+ ...epochArg,
149
218
  })
150
219
  await mouse('mouseMoved', a, { button: 'none', buttons: 0 })
151
220
  let point = a
221
+ let pressed = false
222
+ let pressAttachSeq = null
152
223
  let moved = false
153
224
  try {
154
- await cur((c) => c.down())
155
- await mouse('mousePressed', a, { button: 'left', buttons: 1, clickCount: 1 })
225
+ await cur((c) => c.down(epochArg))
226
+ const pressRes = await mouse('mousePressed', a, { button: 'left', buttons: 1, clickCount: 1 })
227
+ pressed = true
228
+ if (Number.isInteger(pressRes && pressRes.attachSeq)) pressAttachSeq = pressRes.attachSeq
156
229
  const n = Math.max(2, Math.min(60, Number(steps) || 12))
157
- await cur((c) => c.move(b.x, b.y, { duration: n * 24, straight: true }))
230
+ await cur((c) => c.move(b.x, b.y, { duration: n * 24, straight: true, ...epochArg }))
158
231
  for (let i = 1; i <= n; i++) {
159
232
  point = { x: a.x + ((b.x - a.x) * i) / n, y: a.y + ((b.y - a.y) * i) / n }
160
233
  await mouse('mouseMoved', point, { button: 'left', buttons: 1 })
@@ -163,16 +236,25 @@ export async function drag(call, tabId, from, to, { steps = 12, cursor } = {}) {
163
236
  moved = true
164
237
  } finally {
165
238
  try {
166
- await mouse('mouseReleased', point, { button: 'left', buttons: 0, clickCount: 1 })
239
+ if (pressed) {
240
+ const releaseArg = Number.isInteger(pressAttachSeq) ? { releaseOnlyForAttachSeq: pressAttachSeq } : epochArg
241
+ const rel = await call('cdp', {
242
+ tabId,
243
+ method: 'Input.dispatchMouseEvent',
244
+ params: { type: 'mouseReleased', x: Math.round(point.x), y: Math.round(point.y), button: 'left', buttons: 0, clickCount: 1 },
245
+ ...releaseArg,
246
+ })
247
+ if (moved && rel && rel.skipped) throw new Error(tt('err.dragAborted'))
248
+ }
167
249
  } catch (error) {
168
250
  if (moved) throw error
169
251
  } finally {
170
- await cur((c) => c.up())
252
+ await cur((c) => c.up(epochArg))
171
253
  }
172
254
  }
173
255
  return tt('res.drag.doneCoords', {
174
- from: describe(from),
175
- to: describe(to),
256
+ from: describeDragEnd(from),
257
+ to: describeDragEnd(to),
176
258
  x1: Math.round(a.x),
177
259
  y1: Math.round(a.y),
178
260
  x2: Math.round(b.x),
@@ -23,10 +23,13 @@ export async function frameField(call, tabId, operation, args) {
23
23
  throw new Error(tt(errors[result] || 'err.fieldRejected'))
24
24
  }
25
25
 
26
- export async function mergeFrameSnapshot(call, tabId, v, scope, query) {
26
+ export async function mergeFrameSnapshot(call, tabId, v, scope, query, mode = 'interactive') {
27
27
  const paths = v.rows.filter(row => row.crossPath).map(row => row.crossPath)
28
28
  if (paths.length) {
29
- const extra = await frameOp(call, 'frameSnapshot', tabId, { paths, scope, query: query.trim().toLowerCase() })
29
+ const extra = await frameOp(call, 'frameSnapshot', tabId, {
30
+ paths, scope, query: query.trim().toLowerCase(),
31
+ ...(mode && mode !== 'interactive' ? { mode } : {}),
32
+ })
30
33
  const byPath = new Map()
31
34
  for (const group of extra?.groups || []) {
32
35
  const key = group.path.join('.')
package/i18n/en.js CHANGED
@@ -57,7 +57,7 @@ export default {
57
57
  'param.ref': 'Element ref: the [N] numbers listed by browser_read(what=snapshot). Most reliable — when you have a ref, do not guess a selector',
58
58
 
59
59
  // ── browser_tabs ───────────────────────────────────────────────────────
60
- 'tool.tabs.desc': 'List / find / open / close / switch Chrome tabs. Every other browser_* tool takes a tab argument, so call this first to get an id. It drives the user\'s real Chrome (logins intact) and never spins up a clean browser. Pages opened with open go by default into a separate "DSH work window" in the background without stealing focus, so the page the user is looking at is left alone.',
60
+ 'tool.tabs.desc': 'List / find / open / close / switch Chrome tabs. Every other browser_* tool takes a tab argument, so call this first to get an id. It drives the user\'s real Chrome (logins intact) and never spins up a clean browser. Pages opened with open go by default into a separate "DSH work window" in the background without stealing focus, so the page the user is looking at is left alone. Use page changes in the action receipt. Use browser_batch for a known sequence.',
61
61
  'tool.tabs.action': 'list all; find filters by title/URL; open opens a new tab (background work window by default); close closes it; activate brings it to the front (that pulls the window in front of the user — do not use it unless asked); profiles lists all connected Chrome profiles/browsers',
62
62
  'tool.tabs.query': 'Keyword for action=find (matches title or URL)',
63
63
  'tool.tabs.url': 'URL to open when action=open',
@@ -71,7 +71,7 @@ export default {
71
71
  'tool.read.limit': "Snapshot rows per page (default 300). Other reads use characters (default 6000).",
72
72
 
73
73
  // ── browser_click ──────────────────────────────────────────────────────
74
- 'tool.click.desc': 'Click something on the page. Most reliable is ref (the number browser_read what=snapshot gave you); next selector or text (find by visible text); failing that, fall back to x/y coordinates. It sends real mouse events (can trigger new windows, dialogs, focus), not synthetic JS clicks. A small cursor appears on the user\'s screen while clicking.',
74
+ 'tool.click.desc': 'Click something on the page. Most reliable is ref (the number browser_read what=snapshot gave you); next selector or text (find by visible text); failing that, fall back to x/y coordinates. It sends real mouse events (can trigger new windows, dialogs, focus), not synthetic JS clicks. A small cursor appears on the user\'s screen while clicking. Use page changes in the action receipt. Use browser_batch for a known sequence.',
75
75
  'tool.click.selector': 'CSS selector',
76
76
  'tool.click.text': 'Find the element by its visible text and click it (survives redesigns better than a selector)',
77
77
  'tool.click.x': 'Viewport X coordinate (with y)',
@@ -79,7 +79,7 @@ export default {
79
79
  'tool.click.count': 'Number of clicks; default 1 (2 = double click)',
80
80
 
81
81
  // ── browser_input ──────────────────────────────────────────────────────
82
- 'tool.input.desc': 'Type into the page: type enters text (focusing selector first if given), key presses keys (combos like meta+a work), select picks a dropdown option, upload attaches files, focus focuses, hover hovers, scroll scrolls the page or a container, fill replaces text, and check sets the checked state.',
82
+ 'tool.input.desc': 'Type into the page: type enters text (focusing selector first if given), key presses keys (combos like meta+a work), select picks a dropdown option, upload attaches files, focus focuses, hover hovers, scroll scrolls the page or a container, fill replaces text, and check sets the checked state. Use page changes in the action receipt. Use browser_batch for a known sequence.',
83
83
  'tool.input.action': 'Input action to perform',
84
84
  'tool.input.text': "Text to enter with type or fill.",
85
85
  'tool.input.ref': '%ref; can replace selector',
@@ -93,7 +93,7 @@ export default {
93
93
  'tool.input.y': 'Viewport Y for action=hover when no selector is given',
94
94
 
95
95
  // ── browser_nav ────────────────────────────────────────────────────────
96
- 'tool.nav.desc': 'Go to a URL (action=go, the default), or go back, forward or reload. All of them wait for the page to finish loading.',
96
+ 'tool.nav.desc': "Go to a URL (action=go by default), go back or forward, or reload. Go waits for document readiness by default. Use page changes in the action receipt. Use browser_batch for a known sequence.",
97
97
  'tool.nav.action': 'go navigates to url (default); back / forward / reload need no url',
98
98
  'tool.nav.url': 'Target URL when action=go',
99
99
 
@@ -117,12 +117,12 @@ export default {
117
117
  'tool.wait.timeoutMs': 'Timeout in milliseconds; default 15000, max %max',
118
118
 
119
119
  // ── browser_dialog ─────────────────────────────────────────────────────
120
- 'tool.dialog.desc': 'Handle alert / confirm / prompt dialogs. A blocking dialog freezes every later action on the page, so when browser_read(what=info) reports one, call this first.',
120
+ 'tool.dialog.desc': 'Handle alert / confirm / prompt dialogs. A blocking dialog freezes every later action on the page, so when browser_read(what=info) reports one, call this first. Use page changes in the action receipt. Use browser_batch for a known sequence.',
121
121
  'tool.dialog.action': 'accept confirms, dismiss cancels',
122
122
  'tool.dialog.text': 'Text to enter into a prompt dialog',
123
123
 
124
124
  // ── browser_drag ───────────────────────────────────────────────────────
125
- 'tool.drag.desc': 'Drag something to another place: sortable lists, kanban cards, sliders, canvases and so on. Give the start and the end each as a ref (snapshot number), selector, text (visible text) or x/y coordinates; drop zones ("drop here" boxes) usually have no ref, so toText is the easiest way to find them. Both HTML5 draggable drag-and-drop and mouse-driven components are handled; screenshot or read the page afterwards to confirm the result.',
125
+ 'tool.drag.desc': 'Drag something to another place: sortable lists, kanban cards, sliders, canvases and so on. Give the start and the end each as a ref (snapshot number), selector, text (visible text) or x/y coordinates; drop zones ("drop here" boxes) usually have no ref, so toText is the easiest way to find them. Both HTML5 draggable drag-and-drop and mouse-driven components are handled. Use page changes in the action receipt. Use browser_batch for a known sequence.',
126
126
  'tool.drag.fromRef': 'Start: %ref',
127
127
  'tool.drag.fromSelector': 'Start: CSS selector',
128
128
  'tool.drag.fromText': 'Start: find the element by visible text',
@@ -255,7 +255,10 @@ export default {
255
255
  'err.dragNotFound': 'could not find the %end: %desc',
256
256
  'err.dragRefStale': ' (the ref may be stale; take a fresh snapshot)',
257
257
  'err.dragSame': 'start %from and end %to resolve to the same element — be more specific (ref or selector)',
258
+ 'err.dragStartOffscreen': 'start %from is off screen — scroll so that both start and end are visible',
258
259
  'err.dragOffscreen': 'end %to is off screen — scroll so that both start and end are visible',
260
+ 'err.dragCrossFrameUnsupported': 'cross-origin iframe HTML5 drag-and-drop or dragging between two cross-origin iframes is not supported',
261
+ 'err.dragAborted': 'drag was interrupted before mouse release (tab released or detached)',
259
262
  'err.dragNoTarget': 'there is no element at the end point',
260
263
  'res.drag.doneHtml5': 'dragged %from → %to (HTML5 drag and drop%verdict)',
261
264
  'res.drag.accepted': '; the target accepted it',
@@ -358,7 +361,7 @@ export default {
358
361
  'tool.read.query': "Filter snapshot text, roles and values, ignoring case.",
359
362
  'tool.read.cursor': "Resume a snapshot from this row offset, default 0.",
360
363
  'tool.input.checked': "Desired checked state for check.",
361
- 'tool.fill.desc': "Fill text fields, select options or set checkbox states by snapshot ref. Stops on the first failure. Optionally click a submit button after all fields succeed.",
364
+ 'tool.fill.desc': "Fill text fields, select options or set checkbox states by snapshot ref. Stops on the first failure. Optionally click a submit button after all fields succeed. Use page changes in the action receipt. Use browser_batch for a known sequence.",
362
365
  'tool.fill.fields': "1–30 fields in order. Use value for fill (default) and select, and checked for check.",
363
366
  'tool.fill.submitRef': "Click this ref only after every field succeeds.",
364
367
  'tool.screenshot.quality': "JPEG quality from 1 to 100, default 75.",
@@ -459,4 +462,31 @@ export default {
459
462
  'res.shot.marksUnavailable': '\nlegend (image unmarked): %legend%more',
460
463
  'res.shot.marksMore': '… (%count more)',
461
464
  'res.shot.marksEmpty': 'no markable elements in viewport',
465
+ 'card.batch': "Browser batch",
466
+ 'param.observe': "Observe after the action. The default diff shows changes or the viewport when there is no baseline. Choose viewport, page with prose and refs, or none.",
467
+ 'param.expect': "Optional post-action condition. Supply exactly one of selector, text, or url. Set gone to wait for it to disappear.",
468
+ 'param.navWait': "Navigation wait phase. The default dom waits for document readiness, load for full load, idle for network quiet, and none returns immediately.",
469
+ 'tool.input.clear': "Clear the target before typing.",
470
+ 'tool.input.submit': "Press Enter after typing.",
471
+ 'tool.read.mode': "Snapshot defaults to interactive elements. Page mode interleaves short prose and interactive refs in reading order.",
472
+ 'tool.batch.desc': "Run 1–12 known steps in order on one tab. Stops on errors, dialogs, and by default navigation. Observes once at the end.",
473
+ 'tool.batch.steps': "Supports click, type, key, select, check, fill, hover, scroll, wait, and nav. Use the matching single-tool parameters.",
474
+ 'tool.batch.stopOnNav': "Stop after navigation. Defaults to true.",
475
+ 'err.batchCount': "Provide 1 to 12 batch steps.",
476
+ 'err.batchOptions': "Invalid batch stopOnNav or observe option.",
477
+ 'err.batchStep': "Invalid step action or parameters.",
478
+ 'err.batchControl': "Could not verify control of this tab.",
479
+ 'err.expect': "Expect requires exactly one valid selector, text, or url condition.",
480
+ 'err.navWait': "Wait must be dom, load, idle, or none.",
481
+ 'res.hint.steps': "%n steps",
482
+ 'res.batch.completed': "Completed the first %count steps.",
483
+ 'res.batch.stopped': "Stopped at step %step (%reason).",
484
+ 'res.batch.dialog': "a dialog opened",
485
+ 'res.batch.navigated': "the page navigated",
486
+ 'res.batch.unverified': "could not verify page state",
487
+ 'res.action.unchanged': "Page elements unchanged.",
488
+ 'res.action.expectMet': "Expected condition met.",
489
+ 'res.action.expectUnmet': "Expected condition unmet.",
490
+ 'res.action.refHint': " A similar element is now [%candidate].",
491
+ 'res.batch.protected': "the page is protected",
462
492
  }