dsh-chrome-bridge 1.19.0 → 2.0.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 (89) hide show
  1. package/README.en.md +6 -2
  2. package/README.md +6 -2
  3. package/client.js +110 -29
  4. package/core/ext.js +119 -0
  5. package/core/hosts.js +277 -0
  6. package/core/locale.js +8 -0
  7. package/core/receipt.js +56 -0
  8. package/core/session.js +157 -0
  9. package/core/shots.js +56 -0
  10. package/core/tooldef.js +142 -0
  11. package/core/transport.js +212 -0
  12. package/core/upload.js +59 -0
  13. package/devtools.js +37 -16
  14. package/download.js +895 -69
  15. package/drag.js +68 -30
  16. package/features/frames.js +58 -0
  17. package/features/gif.js +203 -0
  18. package/features/index.js +1 -0
  19. package/features/mock-har.js +85 -0
  20. package/features/record.js +225 -0
  21. package/i18n/en.js +312 -16
  22. package/i18n/index.js +17 -0
  23. package/i18n/ru.js +312 -16
  24. package/i18n/zh.js +310 -14
  25. package/image-guard.js +13 -6
  26. package/index.js +21 -1073
  27. package/locale/ru.json +7 -0
  28. package/nav.js +56 -10
  29. package/package.json +8 -1
  30. package/panel.js +14 -4
  31. package/refs.js +293 -240
  32. package/setup.js +248 -74
  33. package/tools/click.js +58 -0
  34. package/tools/devtools.js +61 -0
  35. package/tools/dialog.js +22 -0
  36. package/tools/download.js +50 -0
  37. package/tools/drag.js +61 -0
  38. package/tools/eval.js +22 -0
  39. package/tools/fill.js +77 -0
  40. package/tools/handoff.js +40 -0
  41. package/tools/index.js +38 -0
  42. package/tools/input.js +147 -0
  43. package/tools/nav.js +57 -0
  44. package/tools/read.js +87 -0
  45. package/tools/record.js +120 -0
  46. package/tools/screenshot.js +223 -0
  47. package/tools/tabs.js +131 -0
  48. package/tools/wait.js +56 -0
  49. package/vendor/cb +616 -35
  50. package/vendor/extension/_locales/en/messages.json +3 -0
  51. package/vendor/extension/_locales/ru/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  53. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  54. package/vendor/extension/background.js +2 -1969
  55. package/vendor/extension/confirm.css +148 -0
  56. package/vendor/extension/confirm.html +49 -0
  57. package/vendor/extension/confirm.js +188 -0
  58. package/vendor/extension/in-page-cursor.js +599 -0
  59. package/vendor/extension/manifest.json +11 -2
  60. package/vendor/extension/popup.css +99 -5
  61. package/vendor/extension/popup.html +28 -2
  62. package/vendor/extension/popup.js +430 -45
  63. package/vendor/extension/sw/boot.js +111 -0
  64. package/vendor/extension/sw/cdp.js +411 -0
  65. package/vendor/extension/sw/chooser.js +192 -0
  66. package/vendor/extension/sw/confirm.js +608 -0
  67. package/vendor/extension/sw/cursor.js +241 -0
  68. package/vendor/extension/sw/dispatch.js +129 -0
  69. package/vendor/extension/sw/download.js +279 -0
  70. package/vendor/extension/sw/fetch-hub.js +224 -0
  71. package/vendor/extension/sw/frames.js +651 -0
  72. package/vendor/extension/sw/imaging.js +361 -0
  73. package/vendor/extension/sw/native.js +111 -0
  74. package/vendor/extension/sw/net-tools.js +525 -0
  75. package/vendor/extension/sw/ops.js +829 -0
  76. package/vendor/extension/sw/popup-api.js +303 -0
  77. package/vendor/extension/sw/profile.js +166 -0
  78. package/vendor/extension/sw/record.js +494 -0
  79. package/vendor/extension/sw/state.js +161 -0
  80. package/vendor/extension/sw/tabui.js +219 -0
  81. package/vendor/extension/sw/util.js +166 -0
  82. package/vendor/extension/sw/welcome.js +26 -0
  83. package/vendor/extension/sw/windows.js +94 -0
  84. package/vendor/extension/welcome.css +189 -0
  85. package/vendor/extension/welcome.html +70 -0
  86. package/vendor/extension/welcome.js +157 -0
  87. package/vendor/host/host.js +476 -71
  88. package/vendor/in-page-cursor.js +309 -37
  89. package/vendor/skill/SKILL.md +34 -16
@@ -1,1970 +1,3 @@
1
- /**
2
- * DSH Bridge — MV3 service worker
3
- *
4
- * 常驻连原生宿主(connectNative)。宿主由 Chrome 拉起,同时开一个 Unix socket
5
- * 给 DSH 的 `cb` CLI 用,于是 DSH 就能像原生工具一样操作你正在用的 Chrome。
6
- *
7
- * 关键点:
8
- * - 不用点 Connect,装一次永久可用(service worker 自愈 + alarms 保活)
9
- * - 所有点击/输入都走 CDP Input.* → 真实事件(有 userGesture,弹窗不被拦)
10
- * - 大结果自动分片(native messaging 单条消息有上限)
11
- */
1
+ import { boot } from './sw/boot.js'
12
2
 
13
- const HOST_NAME = 'com.dsh.bridge'
14
- const CDP_VERSION = '1.3'
15
- const RECONNECT_MS = 800
16
- const RECONNECT_MAX_MS = 30_000 // 宿主一直起不来(Node 没了、注册文件坏了)时,重连间隔指数退避到这里封顶
17
- const CHUNK_CHARS = 200 * 1024 // 单条 native 消息正文上限(保守取值)
18
-
19
- let port = null
20
- let connecting = false
21
- let retryMs = RECONNECT_MS
22
-
23
- /** 已 attach CDP 的 tabId */
24
- const attached = new Set()
25
- /** 正在等待 loadEventFired 的 tabId → resolve */
26
- const loadWaiters = new Map()
27
- /** 分片接收缓冲:id → string[] */
28
- const inbox = new Map()
29
- /** SW 日志环(CLI 可读,免得去 chrome://extensions 开控制台) */
30
- const LOG = []
31
- const CONSOLE = []
32
- /** 被 alert/confirm 挡住的标签页:tabId → {type, message} */
33
- const dialogs = new Map()
34
- /**
35
- * 模型点了「上传」之类的按钮、页面要选文件:tabId → {id, owner, mode, backendNodeId, frameId, at, ready, doc, folder}。
36
- * 那一下的系统选文件窗口已经拦下(不弹出来,DSH 也点不动它);点击回话把 id 交给插件,
37
- * 插件 upload 不给选择器时带着这个 id 来,文件就塞给这个框(只认点它的那个请求拿到的 id)。
38
- * id 是随机串:扩展重载后从头来也不会和插件手里的旧 id 撞上。
39
- */
40
- const choosers = new Map()
41
- /** 正在拦截的标签页:只在插件明确要求的那一下点击 / 按键里开,结束就关(用户自己点上传照常弹窗口) */
42
- const chooserArmed = new Set()
43
- /** 正开着拦截的那个请求:tabId → 随机串。拦下的框记在它名下,同一标签页的别的请求拿不到 */
44
- const chooserOwner = new Map()
45
- /** 同一标签页带拦截的点击 / 按键排队一个个来:两个会话同时点,不会把一个框算到两个请求头上 */
46
- const chooserLocks = new Map()
47
- /** 网页用的是拦不下来的那种选文件窗口(showOpenFilePicker 之类,拦了只会把它取消):tabId → 时刻,这之后一阵不再拦 */
48
- const chooserSkip = new Map()
49
- const CHOOSER_TTL_MS = 10 * 60_000
50
- const CHOOSER_SKIP_MS = 5 * 60_000
51
- const CHOOSER_WAIT_MS = 100
52
-
53
- /** 网络请求环形缓冲(Network 域在 attach 时就 enable 了) */
54
- const NET = []
55
- const netPending = new Map()
56
- const NET_MAX = 400
57
-
58
- function log(...args) {
59
- const line = new Date().toISOString().slice(11, 19) + ' ' + args.map(a =>
60
- typeof a === 'string' ? a : (() => { try { return JSON.stringify(a) } catch { return String(a) } })()
61
- ).join(' ')
62
- LOG.push(line)
63
- if (LOG.length > 400) LOG.shift()
64
- console.log(line)
65
- }
66
-
67
- // ── 与原生宿主的连接 ────────────────────────────────────────────────────────
68
-
69
- function connect() {
70
- if (port || connecting) return
71
- connecting = true
72
- try {
73
- port = chrome.runtime.connectNative(HOST_NAME)
74
- } catch (e) {
75
- connecting = false
76
- log('connectNative 失败:', String(e))
77
- return
78
- }
79
- connecting = false
80
-
81
- port.onMessage.addListener((msg) => {
82
- retryMs = RECONNECT_MS // 宿主回过话才算真连上(connectNative 本身总是「成功」),退避清零
83
- if (msg && msg.id && msg.chunk) {
84
- const buf = inbox.get(msg.id) || []
85
- buf[msg.chunk.seq] = msg.data
86
- inbox.set(msg.id, buf)
87
- if (buf.filter(Boolean).length >= msg.chunk.total) {
88
- inbox.delete(msg.id)
89
- try { handle(JSON.parse(buf.join(''))) } catch (e) { log('重组失败:', String(e)) }
90
- }
91
- return
92
- }
93
- handle(msg)
94
- })
95
-
96
- port.onDisconnect.addListener(() => {
97
- const err = chrome.runtime.lastError
98
- if (err) log('原生宿主断开:', err.message)
99
- port = null
100
- hostInfo = null
101
- for (const id of [...attached]) {
102
- chrome.debugger.detach({ tabId: id }).catch(() => {})
103
- }
104
- attached.clear()
105
- updateBadge()
106
- setTimeout(connect, retryMs)
107
- retryMs = Math.min(retryMs * 2, RECONNECT_MAX_MS)
108
- })
109
-
110
- log('已连上原生宿主')
111
- // 主动报到:宿主靠它判断扩展是否在线(否则宿主刚起来时会误判"扩展未连接")
112
- post({ hello: true, version: chrome.runtime.getManifest().version })
113
- post({ hostPing: true })
114
- // connectNative 本身总是「成功」,宿主起不来要等 onDisconnect —— 稳住一会儿再把角标的 ! 收掉
115
- setTimeout(() => { if (port) updateBadge() }, 1500)
116
- }
117
-
118
- function post(msg) {
119
- if (!port) return false
120
- try {
121
- const s = JSON.stringify(msg)
122
- if (s.length <= CHUNK_CHARS) {
123
- port.postMessage(msg)
124
- return true
125
- }
126
- const total = Math.ceil(s.length / CHUNK_CHARS)
127
- for (let i = 0; i < total; i++) {
128
- port.postMessage({ id: msg.id, chunk: { seq: i, total }, data: s.slice(i * CHUNK_CHARS, (i + 1) * CHUNK_CHARS) })
129
- }
130
- return true
131
- } catch (e) {
132
- log('postMessage 失败:', String(e))
133
- return false
134
- }
135
- }
136
-
137
- /** 把 CDP 的英文报错翻成人能用的提示 */
138
- function friendly(e) {
139
- const m = String((e && e.message) || e)
140
- // 我们自己的报错(开头一个大写记号,插件按它换成各语言的话)原样过:FILE_ACCESS_OFF 里带着 chrome://extensions 地址
141
- if (/^(FILE_ACCESS_OFF|NO_FILE_CHOOSER|MULTI_NOT_ALLOWED|USER_PICKED|FOLDER_INPUT) /.test(m)) return e
142
- if (m.includes('chrome://') || m.includes('Cannot access a chrome')) {
143
- return new Error('这个标签页是 chrome:// 内部页,浏览器禁止注入。用 cb tabs 挑一个 http/https 的标签页')
144
- }
145
- if (m.includes('No tab with id')) return new Error('标签页已经不存在了(可能被关掉了)')
146
- if (m.includes('Another debugger is already attached') || m.includes('Cannot attach')) {
147
- return new Error('这个标签页被别的调试器占着(多半是 DevTools 开着)——关掉 DevTools 再试')
148
- }
149
- if (m.includes('Detached while handling command') || m.includes('Debugger is not attached')) {
150
- return new Error('这个标签页空闲被断开了(或页面刚导航过)——直接重试即可,会自动重连')
151
- }
152
- if (m.includes('Cannot find context with specified id')) return new Error('页面刚跳转过,执行上下文没了——重试一次')
153
- if (m.includes('No dialog is showing')) return new Error('当前没有弹窗挡着(可能被 Chrome 推迟到标签页获得焦点时才弹)')
154
- return e instanceof Error ? e : new Error(m)
155
- }
156
-
157
- async function handle(msg) {
158
- if (!msg) return
159
- if (msg.hostPong) { hostInfo = { ...msg, at: Date.now() }; return }
160
- if (!msg.op) return
161
- const { id, op, args = {}, client } = msg
162
- const t0 = Date.now()
163
- try {
164
- const fn = OPS[op]
165
- if (!fn) throw new Error(`未知操作: ${op}`)
166
- await prefsReady // worker 刚起来时先把「暂停」读出来,别让这段空档漏过去
167
- if (!OWN_PAGE_OK.has(op) && (await touchesOwnPage(op, args))) {
168
- throw new Error('扩展页面(chrome-extension://,包括 DSH Bridge 自己的弹窗页)不能被自动化操作')
169
- }
170
- if (paused && !PAUSE_ALLOWED.has(op)) throw new Error(PAUSED_MSG)
171
- const result = await fn(args)
172
- post({ id, ok: true, result })
173
- track(client, op, args, result, null, Date.now() - t0)
174
- } catch (e) {
175
- const err = friendly(e).message
176
- post({ id, ok: false, error: err })
177
- track(client, op, args, null, err, Date.now() - t0)
178
- }
179
- }
180
-
181
- // ── 弹窗用的账本:哪些会话在用、动了哪些标签页、最近做了什么 ────────────────
182
- // 全在内存里:service worker 有原生端口连着,平时不会被挂起;真重启了就从零记,不要紧。
183
-
184
- /** 宿主自报的状态(pid、socket 是否在听、最近一次被调用) */
185
- let hostInfo = null
186
- /** 用户在弹窗里按了暂停:除了这几个,其它操作一律拒绝 */
187
- let paused = false
188
- const PAUSE_ALLOWED = new Set(['version', 'reload', 'ping', 'logs', 'detach', 'panel'])
189
- const PAUSED_MSG = '用户在 DSH Bridge 弹窗里暂停了浏览器控制——请用户点开扩展图标、打开「允许 DSH 控制」后再试'
190
-
191
- /** 碰到扩展页面也允许的:只是松手 / 关掉,不往里注入、不发输入 */
192
- const OWN_PAGE_OK = new Set(['detach', 'close'])
193
-
194
- /**
195
- * 这个网址是不是扩展页面:只看协议头(不分大小写)。URL 解析会吃掉的东西先去掉再比:
196
- * 任何位置的 tab / 换行,开头的空白和控制字符。网址别处(查询串之类)出现 chrome-extension: 不算。
197
- */
198
- const isExtUrl = (v) => typeof v === 'string' &&
199
- /^chrome-extension:/i.test(v.replace(/[\t\n\r]/g, '').replace(/^[\x00-\x20]+/, ''))
200
-
201
- /**
202
- * 扩展页面任何时候(不只是暂停时)都不让碰:弹窗页 popup.html 要是被当成标签页打开、再往里跑脚本,
203
- * 就能 chrome.runtime.sendMessage 自己把「暂停」解除。打开、跳转过去、CDP 参数里带它、对它所在的
204
- * 标签页做任何事(注入 / 截图 / 输入)都算。
205
- */
206
- async function touchesOwnPage(op, args) {
207
- if ((op === 'open' || op === 'nav') && isExtUrl(args.url)) return true
208
- // CDP 只看网址类参数(Page.navigate、Target.createTarget 的 url 之类),不扫表达式等别的文本
209
- const p = op === 'cdp' && args.params
210
- if (p && typeof p === 'object' && Object.keys(p).some((k) => /url$/i.test(k) && isExtUrl(p[k]))) return true
211
- if (args.tabId == null) return false
212
- try {
213
- const t = await chrome.tabs.get(Number(args.tabId))
214
- return isExtUrl(t.url) || isExtUrl(t.pendingUrl)
215
- } catch {
216
- return false
217
- }
218
- }
219
- /** 用户在弹窗里关了「页面里显示光标」:真实点击照做,只是不画那只蓝色光标 */
220
- let showCursor = true
221
- /** 用户关了「在单独窗口里干活」:新开的页回到用户当前窗口(后台标签页,不抢焦点) */
222
- let ownWindow = true
223
- const prefsReady = chrome.storage.local.get(['paused', 'showCursor', 'ownWindow']).then((v) => {
224
- paused = !!(v && v.paused)
225
- showCursor = !(v && v.showCursor === false)
226
- ownWindow = !(v && v.ownWindow === false)
227
- updateBadge()
228
- }).catch(() => {})
229
-
230
- /** 受控标签页里,扩展自己的页面(弹窗被当成网页打开时)不算数 */
231
- const controlledCount = () => [...attached].filter((id) => !ownTabs.has(id)).length
232
-
233
- /** 不算「动作」的内部操作(版本检查、焦点模拟、光标跟随……) */
234
- const QUIET_OPS = new Set(['version', 'reload', 'ping', 'logs', 'panel'])
235
- const QUIET_CDP = new Set(['Emulation.setFocusEmulationEnabled', 'Page.getNavigationHistory'])
236
-
237
- /** 会话 key → { key, kind, session, pid, first, last, ops, errors, tabs:Set } */
238
- const SESSIONS = new Map()
239
- /** 最近动作:DSH 的一次工具调用算一条(同一个 callId 的多个 op 合并),cb 命令行一个 op 一条 */
240
- const ACTIVITY = []
241
- const ACTIVITY_MAX = 80
242
-
243
- function clientKey(c) {
244
- if (!c) return 'cli'
245
- const kind = c.kind || 'dsh'
246
- return c.session ? `${kind}:${c.session}` : `${kind}:pid${c.pid || '?'}`
247
- }
248
-
249
- /** 通过 open 打开的扩展自己的页面(弹窗页):对它们的操作不记账 */
250
- const ownTabs = new Set()
251
-
252
- function track(client, op, args, result, error, ms) {
253
- if (QUIET_OPS.has(op)) return
254
- if (op === 'open' && String(args.url || '').startsWith(`chrome-extension://${chrome.runtime.id}/`)) {
255
- if (result && result.tabId != null) ownTabs.add(Number(result.tabId))
256
- return
257
- }
258
- if (args.tabId != null && ownTabs.has(Number(args.tabId))) return
259
- // CDP 的原始报错是一段 JSON({"code":-32000,"message":"…"}),弹窗里只留 message
260
- if (error && error.trim().startsWith('{')) {
261
- try { error = JSON.parse(error).message || error } catch {}
262
- }
263
- if (op === 'cdp' && QUIET_CDP.has(args.method)) return
264
- const now = Date.now()
265
- const key = clientKey(client)
266
- let s = SESSIONS.get(key)
267
- if (!s) {
268
- s = { key, kind: client ? client.kind || 'dsh' : 'cli', session: (client && client.session) || null,
269
- pid: (client && client.pid) || null, first: now, last: 0, ops: 0, errors: 0, tabs: new Set() }
270
- SESSIONS.set(key, s)
271
- }
272
- s.last = now
273
- s.ops++
274
- if (error) s.errors++
275
- const tabId = args.tabId != null ? Number(args.tabId) : result && result.tabId != null ? Number(result.tabId) : null
276
- if (tabId != null) {
277
- if (op === 'close') s.tabs.delete(tabId)
278
- else s.tabs.add(tabId)
279
- }
280
-
281
- const call = client && client.call
282
- const prev = call ? ACTIVITY.find((a) => a.call === call) : null
283
- if (prev) {
284
- prev.last = now
285
- prev.ops++
286
- prev.ms += ms
287
- if (tabId != null && prev.tabId == null) prev.tabId = tabId
288
- if (error) { prev.ok = false; prev.error = error }
289
- return
290
- }
291
- ACTIVITY.push({
292
- at: now, last: now, key, call: call || null, tool: (client && client.tool) || null,
293
- hint: (client && client.hint) || '', op: op === 'cdp' ? `cdp:${args.method}` : op,
294
- tabId, ok: !error, error: error || undefined, ms, ops: 1,
295
- })
296
- if (ACTIVITY.length > ACTIVITY_MAX) ACTIVITY.shift()
297
- }
298
-
299
- /** 工具栏图标角标:受控标签页数;暂停 ⏸;宿主断了 ! */
300
- function updateBadge() {
301
- try {
302
- const n = controlledCount()
303
- let text = n ? String(n) : ''
304
- let color = '#4D6BFE'
305
- if (paused) { text = '⏸'; color = '#B7791F' } else if (!port) { text = '!'; color = '#E5484D' }
306
- chrome.action.setBadgeText({ text })
307
- chrome.action.setBadgeBackgroundColor({ color })
308
- if (chrome.action.setBadgeTextColor) chrome.action.setBadgeTextColor({ color: '#FFFFFF' })
309
- } catch {}
310
- }
311
-
312
- // ── CDP 基础设施 ────────────────────────────────────────────────────────────
313
-
314
- // 标签页最后被用到的时间 —— 空闲了就断开,别让 Chrome 一直挂着"正在调试"提示条
315
- const lastUsed = new Map()
316
- const DETACH_IDLE_MS = 60_000
317
-
318
- async function detachIdle() {
319
- const now = Date.now()
320
- for (const tabId of [...attached]) {
321
- if (now - (lastUsed.get(tabId) || 0) < DETACH_IDLE_MS) continue
322
- if (inflight.has(tabId)) continue // 有 CDP 调用在飞(长 evaluate、截图…)
323
- if (loadWaiters.has(tabId)) continue // 正在等页面加载完成
324
-
325
- try { await chrome.debugger.detach({ tabId }) } catch {}
326
- attached.delete(tabId)
327
- lastUsed.delete(tabId)
328
- await unmarkTab(tabId)
329
- }
330
- }
331
-
332
- // ── 正在被控制的标签页:自动分组 + 扩展图标上的 🖱 角标 ──────────────────────
333
- // 用户在标签栏上一眼就能看出"agent 正在动哪几个页面",松手(空闲断开 / 显式 detach /
334
- // 关掉标签页 / 点掉 Chrome 那条调试提示)就自动还原,不留痕。
335
-
336
- // 用户看得见的两处文字(标签组名、工具栏图标的悬停提示)跟 Chrome 的界面语言走:zh* 中文、ru* 俄文、其它英文。
337
- // 认「我们的组」时几种语言的组名、以及老版本的「DSH agent 正在操作」都算,换了语言或升级后老组照样会被拆掉。
338
- const UI_LANG = (() => {
339
- let l = ''
340
- try { l = String(chrome.i18n.getUILanguage() || '').toLowerCase() } catch {}
341
- return l.startsWith('zh') ? 'zh' : l.startsWith('ru') ? 'ru' : 'en'
342
- })()
343
- const GROUP_TITLES = { zh: 'DSH 正在操作', en: 'DSH at work', ru: 'DSH работает' }
344
- const GROUP_TITLE = GROUP_TITLES[UI_LANG]
345
- const OUR_GROUP_TITLES = new Set([...Object.values(GROUP_TITLES), 'DSH agent 正在操作'])
346
- const CURSOR_TAB_TITLE = {
347
- zh: 'DSH 正在操作这个标签页(页面里有它的光标)',
348
- en: 'DSH is working in this tab (its cursor is on the page)',
349
- ru: 'DSH работает в этой вкладке (его курсор на странице)',
350
- }[UI_LANG]
351
- const CURSOR_ICON = { 16: 'icons/cursor16.png', 32: 'icons/cursor32.png', 48: 'icons/cursor48.png' }
352
- // 标签页上的小鼠标:把页面 favicon 临时换成它(data URL,绕开页面 CSP 与 web_accessible_resources)
353
- const CURSOR_FAVICON = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAGUElEQVR4AbRWbWxUVRA9u9vutnQFFFNogZogIhFqqQnGEgiEEKIoJYoEP6pCTPhjoiJCGmKboBQqIWmAP5KYEKApWIRCoRSxlCpiUWIQGiiS8EMK/bBBoZZtl919z3Nudzfb7ZYQis297907M3fmzJl5t+vEwD8HRZK7wm/tNbl9+EOB4r26bt/unu/3+9dzllCZwikw/wuIeAAMlJ86fHha7bUOd6Hb7S60bdvX29srIG4CibenaGgj1qEyTO7urlhXexrYUmHjg1IbR38CPB7PGp/PJxAehtMZ2XI59CFnES90Os+TnJw8SwLL5tYGjvxoo+YUkJqauioQCJwA3kml3sVJAz6HOOIABJNJudNmYNuyYXHqXd1gYcXnFmpPu/Jse1d3uCQPhY1YAMzlrtOy4DAACAKcxADt9T500kJ1gx0pyXpg4ZAbNA4AMXDYisyoIQsICQSjkxloX1VvYVlREH+2p6yy7eo7YTYeuEETAlB8xgTjQ2tiMG+z1oaKDV+HUHXCirDxwA2aEACTZ7bkgSjUA+oFzcg6FJZ/ezyE/XXWkBo0IQBWgRk7wDhm2vwibHBPhW3zoTVl0gvE0k8DOFjvfKAGTQhAQZSloqv2eltsBjFg1owsRizWRG/ZVB4LovK7UKQk992ggwKgbw3AYubMWqBgsu7biwfpJAP1mpXHQijeFsTVG577btBBAPTV3woh2gvKNKjMiUTrCCNixQrLgmTpwpUQ1pbdxZ6jwQgbsQ1qcMc+EgKQgcUH/UKZMa6YpwTgPQHJojpKJZON5NBB9sieIyFU1ARjGtTcGQPiDRDQn7l4bDpSpkFGknNuYbLm3uhsEIxtZAYA2ZJ9hA29y6sDWLCiB3trkRcIHKijb92e/a7wxABoqWwUNPrmhrER3dMmAkxZU91fR71spSs/FMClq8681taOFylO4oyOxACYXWy9bdY2WmuiUKaqtxgxUzIzAQOK9uA0zNCXbJ592om0tGFzGFkAoiwkBGCQ01Lowc6HnHCCtbXCX4WRcW9kADZ+7MbGlW58yVm6ygPNTas92LTGg+M7hsHn6zk/YsSirfz/EQ3OY0gIQN+1UKvWkcyVmsmaKUpnkXPVWWxQJF/InuTEiJTWfY8Oa/tmlLd972Np7XtudZ4pPHPm10/S0uYtA3r/BQ4HjHH4kRAAmJkdyRz8M1kTOFnInqgjfWuxQC15B8oPB82ytbW1MStr+eZx45aWjh+/ZMPsWcVVeXnrDgDu68DPXTSSIT1xxSFvfPUfhgGbHc7UlK3pB9Z0ypMOfPFRMizJY/SyOd8cwoU/LOTm5hQAXe3AiGt9M/MGcLQDaLjFKH7OaHCuByuBVEyMpozFBTDlKSdKWGdpsrlWCQwDLIVkWu9it/Pn23PXr+9/AajpAWrvALt91Ctwv8wpMyMxA1SZeptvW/FtvPGyCy0tNypP/nCq+K1X2MiGAek4yY5YOXcphPOXLaSnp68G8pPphikImpncDhwJARhzHo0kp8xHpXVUZGUVlM2dU/z9hLG9TVPZcLIzDNEvsfIJ7KwKgL8rn29p+Wo+BUTK5z1GHACX7XTCnjLREa1zCWs+IbO3aezYxZsBfwvgbW1uvry9YGFfL+i/JgmAgKgXzl0K4nf2w+jRj68BlrgZOy4GJTEjTjks1Nx8ZftU1vjNBcnQt61svd7894EkNlbj30Do1vTpK+t1sWRPdsGwIIdhusTEjv19LACd+s3IT0YGiaczRkwX6f7c3A/r29v/2pk/x9/UdfPsaq/3tWWArxU4Fe7i2l4g0CWbdxclwVLqpCDEntBvRrDVfrvIh3EcUh/cNwBWfbcfSLuZkVFQ4vW+9PbMGYUHAR9pb7xJf9SZu5FJeu5kZCwuyyED0yYngQIYDVPIecaFbUWp6Ojo3AHcpYQn7zFiGZAZfdV0AyPbADe/40diMjchZEOnDfzERv4jFsrWejCN93zOZCe2FKUweAomPeFvGjPm9TLgEbIVPaezA2Y8ALIgEvfx263TtclA0NUpeeSw1uS4uysj49XNbW0d5Vs/S2XgVAbuvXi68ReWbd57QE8nUKfzso+cHfCOByADHWCWBrnWksVP6hsI0tWRmbm41OGYO9PhmD3b6120fOaMokNAEq/ds+qZAA8O5oMq4D8AAAD//zouHuEAAAAGSURBVAMAYX64YuQ3mpYAAAAASUVORK5CYII='
354
- const IDLE_ICON = { 16: 'icons/icon16.png', 32: 'icons/icon32.png', 48: 'icons/icon48.png' }
355
- const groupedTabs = new Map() // tabId -> groupId(只记我们自己建的组)
356
- const ourGroup = new Map() // windowId -> groupId(标签组是 per-window 的)
357
- const tabEpoch = new Map() // tabId -> 递增序号,用来发现"mark 与 unmark 撞车"
358
-
359
- /** 受控标签页的 favicon 换成小鼠标(松手还原)。页面导航后 favicon 自然复原,下次控制再补。 */
360
- async function setTabFavicon(tabId, on) {
361
- try {
362
- await chrome.scripting.executeScript({
363
- target: { tabId: Number(tabId) },
364
- func: (on, href) => {
365
- const ID = 'dsh-bridge-cursor-favicon'
366
- const OFF = 'data-dsh-bridge-rel'
367
- const old = document.getElementById(ID)
368
- if (!on) {
369
- // 把页面自己的图标 link 换回来(rel 改回去 Chrome 就会重算);
370
- // 页面一个都没写、靠默认 /favicon.ico 的,光删掉我们的 Chrome 不换回去 —— 补一个指向默认图标的
371
- const parked = [...document.querySelectorAll(`link[${OFF}]`)]
372
- if (!old && !parked.length) return
373
- if (old) old.remove()
374
- for (const l of parked) { l.rel = l.getAttribute(OFF); l.removeAttribute(OFF) }
375
- if (!parked.length && !document.querySelector('link[rel~="icon"]')) {
376
- const d = document.createElement('link')
377
- d.rel = 'icon'
378
- d.href = '/favicon.ico'
379
- d.setAttribute('data-dsh-bridge', 'restore')
380
- document.head.appendChild(d)
381
- }
382
- return
383
- }
384
- if (old) return
385
- // 页面自己有图标的话 Chrome 会优先用它,我们的小鼠标挂不上去 —— 先把它们的 rel 停掉,松手时原样恢复
386
- for (const l of document.querySelectorAll('link[rel~="icon"]')) {
387
- l.setAttribute(OFF, l.rel)
388
- l.rel = 'dsh-bridge-parked-icon'
389
- }
390
- const l = document.createElement('link')
391
- l.id = ID
392
- l.rel = 'icon'
393
- l.type = 'image/png'
394
- l.href = href
395
- document.head.appendChild(l)
396
- },
397
- args: [on, CURSOR_FAVICON],
398
- })
399
- } catch {}
400
- }
401
-
402
- async function markTab(tabId) {
403
- const id = Number(tabId)
404
- tabEpoch.set(id, (tabEpoch.get(id) || 0) + 1)
405
- updateBadge()
406
- // 分组 = "这个标签页正在被操作";标签上的小鼠标只跟页内光标走(markCursor)
407
- await ensureGroup(id)
408
- }
409
-
410
- /**
411
- * 同一个窗口里的受控标签页共用**同一个组**(不然同时操作 3 个标签页会出现 3 个同名蓝组)。
412
- * 优先复用:内存里记的组 id → 按标题找本窗口现成的组 → 都没有才新建。
413
- * 用户自己固定的、已经在用户自己分组里的标签页不动:分组会取消固定、把它挪出原来的组,松手时也还原不回去。
414
- */
415
- async function ensureGroup(tabId) {
416
- const id = Number(tabId)
417
- if (groupedTabs.has(id)) return
418
- let tab = null
419
- try { tab = await chrome.tabs.get(id) } catch {}
420
- if (!tab || tab.pinned) return
421
- const wid = tab.windowId
422
- if (tab.groupId >= 0) {
423
- let g = null
424
- try { g = await chrome.tabGroups.get(tab.groupId) } catch {}
425
- if (!g || !OUR_GROUP_TITLES.has(g.title)) return // 用户自己的组
426
- groupedTabs.set(id, tab.groupId) // 本来就在我们的组里(worker 重启过之类)
427
- ourGroup.set(wid, tab.groupId)
428
- return
429
- }
430
- const candidates = []
431
- if (ourGroup.has(wid)) candidates.push(ourGroup.get(wid))
432
- try {
433
- // 只找本窗口的:按标题跨窗口复用,会把标签页拽到别的窗口去
434
- for (const g of await chrome.tabGroups.query({ windowId: wid })) {
435
- if (OUR_GROUP_TITLES.has(g.title) && !candidates.includes(g.id)) candidates.push(g.id)
436
- }
437
- } catch {}
438
- for (const gid of candidates) {
439
- try {
440
- if ((await chrome.tabGroups.get(gid)).windowId !== wid) continue // 记着的组被拖去了别的窗口
441
- await chrome.tabs.group({ tabIds: [id], groupId: gid })
442
- groupedTabs.set(id, gid)
443
- ourGroup.set(wid, gid)
444
- await chrome.tabGroups.update(gid, { title: GROUP_TITLE, color: 'blue' })
445
- return
446
- } catch {}
447
- }
448
- try {
449
- // 新建的组一定要指明在它自己的窗口:不写的话 Chrome 建在「当前窗口」,会把别的窗口里的标签页(比如干活窗口里的)拽过来
450
- const gid = await chrome.tabs.group({ tabIds: [id], createProperties: { windowId: wid } })
451
- groupedTabs.set(id, gid)
452
- ourGroup.set(wid, gid)
453
- await chrome.tabGroups.update(gid, { title: GROUP_TITLE, color: 'blue' })
454
- } catch (e) {
455
- console.log('[dsh-bridge] 分组失败(不影响干活):', String(e && e.message || e))
456
- }
457
- }
458
-
459
- async function unmarkTab(tabId) {
460
- const id = Number(tabId)
461
- const epoch = tabEpoch.get(id) || 0 // 竞态守卫:await 期间如果有新的 mark,就放弃这次 unmark
462
- updateBadge()
463
- cursorReady.delete(id) // 必修:不清的话,松手后小鼠标灭了就再也不亮(页面里的光标其实还在)
464
- cursorPos.delete(id) // 松手后再接手,光标从新目标处冒出来,不从老地方飞
465
- await hidePageCursor(id) // 尽力把页内光标收掉(松手不留痕)
466
- await markCursor(id, false)
467
- if ((tabEpoch.get(id) || 0) !== epoch) return // 期间又被 mark 了,别拆
468
- if (!groupedTabs.has(id)) return
469
- const gid = groupedTabs.get(id)
470
- groupedTabs.delete(id)
471
- try {
472
- // 用户中途把它拖进了自己的组:那是用户的组,别拆
473
- if ((await chrome.tabs.get(id)).groupId === gid) await chrome.tabs.ungroup([id])
474
- } catch {}
475
- }
476
-
477
- /**
478
- * 自愈:service worker 会被 Chrome 随时挂起、扩展重载也会清掉内存里的分组表,
479
- * 但 Chrome 那边的组是持久的。所以启动时对一遍账:
480
- * · 还挂着调试会话的标签页 → 认领回分组表(继续归我们管)
481
- * · 已经没会话、却还留在我们组里的(几种语言的组名、老版本的组名都算)→ 拆掉还原(别留孤儿组和残留角标)
482
- */
483
- async function reconcileGroups() {
484
- try {
485
- const groups = (await chrome.tabGroups.query({})).filter((g) => OUR_GROUP_TITLES.has(g.title))
486
- if (!groups.length) return
487
- let attachedIds = new Set()
488
- try {
489
- const targets = await chrome.debugger.getTargets()
490
- attachedIds = new Set(targets.filter(t => t.attached && t.tabId != null).map(t => t.tabId))
491
- } catch {}
492
- for (const g of groups) {
493
- const tabs = await chrome.tabs.query({ groupId: g.id })
494
- for (const t of tabs) {
495
- if (attachedIds.has(t.id)) {
496
- groupedTabs.set(t.id, g.id)
497
- if (t.windowId != null) ourGroup.set(t.windowId, g.id)
498
- } else if (!attached.has(t.id)) { // 重新确认一次:启动瞬间并发进来的 op 别被误拆
499
- groupedTabs.set(t.id, g.id) // 先认领,unmarkTab 才会真的去拆
500
- await unmarkTab(t.id)
501
- }
502
- }
503
- }
504
- } catch (e) {
505
- console.log('[dsh-bridge] 分组对账失败(不影响干活):', String(e && e.message || e))
506
- }
507
- }
508
-
509
- // ── DSH 自己的干活窗口 ──────────────────────────────────────────────────────
510
-
511
- /**
512
- * 新开的页默认放进一个单独的 Chrome 窗口:同一个用户资料,登录状态都在,但不往用户正在用的窗口里塞标签页。
513
- * 窗口在后台开(不抢焦点),之后新开的页都进它;用户把它关了,下次再开一个。
514
- * 普通和隐身各用各的:用户正在隐身窗口里,新页就开进隐身的干活窗口,不把隐身的事带进普通的 Cookie 和历史记录(反过来也一样)。
515
- * 窗口 id 记在 storage.session:worker 被挂起再起来还认得;浏览器重启就清空(id 也变了)。
516
- */
517
- const agentWindows = { normal: null, incognito: null }
518
- /** DSH 在干活窗口里开的标签页:用户自己拖进来的页不算,不能把它切走 */
519
- const agentTabs = new Set()
520
- const agentWindowReady = chrome.storage.session.get(['agentWindows', 'agentTabs']).then((v) => {
521
- Object.assign(agentWindows, (v && v.agentWindows) || {})
522
- for (const id of (v && v.agentTabs) || []) agentTabs.add(id)
523
- }).catch(() => {})
524
-
525
- function saveAgentWindows() {
526
- chrome.storage.session.set({ agentWindows: { ...agentWindows }, agentTabs: [...agentTabs] }).catch(() => {})
527
- }
528
-
529
- function forgetAgentWindow(id) {
530
- let changed = false
531
- for (const k of Object.keys(agentWindows)) if (agentWindows[k] === id) { agentWindows[k] = null; changed = true }
532
- if (changed) saveAgentWindows()
533
- }
534
-
535
- /** 这一种(normal / incognito)的干活窗口还在就回它的 id,没了(被关掉、浏览器重启过)回 null */
536
- async function agentWindow(mode) {
537
- await agentWindowReady
538
- const id = agentWindows[mode]
539
- if (id == null) return null
540
- try {
541
- const w = await chrome.windows.get(id)
542
- if (w && w.type === 'normal' && !!w.incognito === (mode === 'incognito')) return w.id
543
- } catch {}
544
- forgetAgentWindow(id)
545
- return null
546
- }
547
-
548
- /** 现在还在的干活窗口(两种都算),列标签页时标出来用 */
549
- async function agentWindowIds() {
550
- return new Set((await Promise.all(['normal', 'incognito'].map(agentWindow))).filter((id) => id != null))
551
- }
552
-
553
- /** 开页排队:两个会话同时开页时,后来的等前一个开完(窗口建好了)再往里加,不另开第二个窗口 */
554
- let agentWindowQueue = Promise.resolve()
555
-
556
- function openInAgentWindow(url) {
557
- const run = agentWindowQueue.then(() => openInAgentWindowNow(url))
558
- agentWindowQueue = run.catch(() => {})
559
- return run
560
- }
561
-
562
- function rememberAgentTab(t) {
563
- agentTabs.add(t.id)
564
- saveAgentWindows()
565
- return t
566
- }
567
-
568
- async function openInAgentWindowNow(url) {
569
- // 用户最后在用的普通窗口:隐身与否跟它走,新窗口的大小也照它
570
- let cur = null
571
- try { cur = await chrome.windows.getLastFocused({ windowTypes: ['normal'] }) } catch {}
572
- const incognito = !!(cur && cur.incognito)
573
- const mode = incognito ? 'incognito' : 'normal'
574
- const wid = await agentWindow(mode)
575
- if (wid != null) {
576
- try {
577
- // 窗口里正显示的是 DSH 开的页就切到新页(偷看一眼就是最新的);不动窗口焦点。
578
- // 正显示的是用户自己拖进来的页:别把它切走,新页在后台开
579
- const [shown] = await chrome.tabs.query({ windowId: wid, active: true })
580
- return rememberAgentTab(await chrome.tabs.create({ windowId: wid, url, active: !shown || agentTabs.has(shown.id) }))
581
- } catch (e) {
582
- // 刚好在这一下被关掉了:下面重开一个。窗口还在就是别的错(比如网址不让开),照实报
583
- if (await chrome.windows.get(wid).then(() => true, () => false)) throw e
584
- forgetAgentWindow(wid)
585
- }
586
- }
587
- // 跟用户当前窗口一样大、错开一点;最大化 / 全屏的不照抄,交给 Chrome 默认
588
- const props = { url, focused: false, type: 'normal', incognito }
589
- let w
590
- if (cur && cur.state === 'normal' && cur.width && cur.height) {
591
- try {
592
- w = await chrome.windows.create({ ...props, left: cur.left + 40, top: cur.top + 40, width: cur.width, height: cur.height })
593
- } catch {} // 窗口贴着屏幕边,错开以后一半到了屏幕外,Chrome 不让开:交给它自己摆
594
- }
595
- if (!w) w = await chrome.windows.create(props)
596
- agentWindows[mode] = w.id
597
- return rememberAgentTab(w.tabs[0])
598
- }
599
-
600
- async function ensure(tabId) {
601
- if (paused) throw new Error(PAUSED_MSG) // 暂停中不再接管任何标签页(进行中的操作也不会重新 attach)
602
- lastUsed.set(Number(tabId), Date.now())
603
- if (!attached.has(tabId)) {
604
- try {
605
- await chrome.debugger.attach({ tabId: Number(tabId) }, CDP_VERSION)
606
- } catch (e) {
607
- if (!String(e && e.message || e).includes('Already attached')) throw e
608
- }
609
- attached.add(Number(tabId))
610
- // Runtime.enable 会把接上之前的 console 和 JS 报错补发一遍(V8 自己存着),Log.enable 同理补发浏览器日志
611
- for (const d of ['Page', 'DOM', 'Runtime', 'Network', 'Log']) {
612
- try { await chrome.debugger.sendCommand({ tabId: Number(tabId) }, d + '.enable', {}) } catch {}
613
- }
614
- // 后台标签页 / 被挡住的窗口里页面是 hidden,不开焦点模拟的话 CDP 鼠标键盘事件会被直接丢掉
615
- try { await chrome.debugger.sendCommand({ tabId: Number(tabId) }, 'Emulation.setFocusEmulationEnabled', { enabled: true }) } catch {}
616
- await markTab(tabId)
617
- }
618
- return Number(tabId)
619
- }
620
-
621
- /**
622
- * 「允许访问文件网址」开没开:Chrome 默认关;关着时 DOM.setFileInputFiles 只回一句 Not allowed(issue #7)。
623
- * 用户在扩展详情里切换这个开关,Chrome 会把扩展整个重载,所以这里不用缓存也不会过期。
624
- */
625
- async function fileAccess() {
626
- try { return await chrome.extension.isAllowedFileSchemeAccess() } catch { return null }
627
- }
628
-
629
- function fileAccessError() {
630
- const url = `chrome://extensions/?id=${chrome.runtime.id}`
631
- return new Error(`FILE_ACCESS_OFF ${url} 扩展没开「允许访问文件网址」,Chrome 不让它把电脑上的文件塞进网页:在 ${url} 打开「允许访问文件网址」,扩展会自动重载,几秒后再上传`)
632
- }
633
-
634
- /**
635
- * 插件明确要求时(点击 / 按键带 chooser: true),在发鼠标 / 键盘事件之前调:这一下要是让页面打开系统的选文件窗口,
636
- * 就拦下来记进 choosers。没开文件访问时不拦(拦了也塞不进去,不如让窗口照常弹出来给用户自己选)。
637
- * 老插件、cb 命令行不带这个标记,一律不拦。返回这次开没开成。
638
- */
639
- async function armChooser(tabId) {
640
- const id = Number(tabId)
641
- if ((await fileAccess()) !== true) return false
642
- const skip = chooserSkip.get(id)
643
- if (skip && Date.now() - skip < CHOOSER_SKIP_MS) return false
644
- try {
645
- // 每次都发:主动松手 / 空闲断开 / 宿主重连以后调试会话是新的,旧会话里开的拦截已经没了
646
- await chrome.debugger.sendCommand({ tabId: id }, 'Page.setInterceptFileChooserDialog', { enabled: true })
647
- } catch { return false }
648
- chooserArmed.add(id)
649
- return true
650
- }
651
-
652
- /** 这一下点击 / 按键做完就关拦截:之后页面(或用户自己)再打开选文件窗口,照常弹出来 */
653
- async function disarmChooser(tabId) {
654
- const id = Number(tabId)
655
- if (!chooserArmed.delete(id)) return
656
- try { await chrome.debugger.sendCommand({ tabId: id }, 'Page.setInterceptFileChooserDialog', { enabled: false }) } catch {}
657
- }
658
-
659
- /** 这个请求(token)拦下的框,回给插件的那一份;等它查完是不是选文件夹、属于哪个文档 */
660
- async function chooserFor(tabId, token) {
661
- const id = Number(tabId)
662
- const c = choosers.get(id)
663
- if (!c || c.owner !== token) return undefined
664
- await c.ready
665
- if (choosers.get(id) !== c) return undefined
666
- if (!c.backendNodeId) return { unsupported: true }
667
- if (c.folder) { dropChooser(id, c); return { folder: true } }
668
- return { id: c.id, mode: c.mode }
669
- }
670
-
671
- /** 等 Page.fileChooserOpened 的:tabId → resolve */
672
- const chooserWaiters = new Map()
673
-
674
- /**
675
- * Page.fileChooserOpened 在松开鼠标的回包之后才到(本机无头 Chrome 实测紧跟着、0 毫秒):拦截开着时等一小会儿,
676
- * 来了马上走;页面没要选文件就等满 ms。
677
- */
678
- async function waitChooser(tabId, token, ms = CHOOSER_WAIT_MS) {
679
- const id = Number(tabId)
680
- const has = () => { const c = choosers.get(id); return !!c && c.owner === token }
681
- if (has() || !chooserArmed.has(id)) return
682
- await new Promise((resolve) => {
683
- const tm = setTimeout(done, ms)
684
- function done() { clearTimeout(tm); if (chooserWaiters.get(id) === done) chooserWaiters.delete(id); resolve() }
685
- chooserWaiters.set(id, done)
686
- })
687
- }
688
-
689
- /** 某个框所在文档的 loaderId(找不到这个框就用主框架的):换过页就对不上 */
690
- async function docOf(tabId, frameId, sendFn) {
691
- try {
692
- const { frameTree } = await sendFn(tabId, 'Page.getFrameTree', {})
693
- let main = null
694
- const walk = (t) => {
695
- if (!t || !t.frame) return null
696
- if (!t.frame.parentId) main = main || t.frame
697
- if (t.frame.id === frameId) return t.frame
698
- for (const ch of t.childFrames || []) { const f = walk(ch); if (f) return f }
699
- return null
700
- }
701
- const f = walk(frameTree) || main
702
- return f ? `${f.id}:${f.loaderId}` : null
703
- } catch { return null }
704
- }
705
-
706
- /** DOM.describeNode 回来的节点有没有某个属性 */
707
- function hasAttr(node, name) {
708
- const a = (node && node.attributes) || []
709
- for (let i = 0; i < a.length; i += 2) if (String(a[i]).toLowerCase() === name) return true
710
- return false
711
- }
712
-
713
- /** DOM.describeNode 回来的节点某个属性的值(没有回 null) */
714
- function attrValue(node, name) {
715
- const a = (node && node.attributes) || []
716
- for (let i = 0; i < a.length; i += 2) if (String(a[i]).toLowerCase() === name) return String(a[i + 1])
717
- return null
718
- }
719
-
720
- /** 节点是不是「选文件夹」的框(webkitdirectory:塞普通文件进去,Chrome 会当目录去枚举,什么也传不上) */
721
- function isFolderNode(node) { return hasAttr(node, 'webkitdirectory') }
722
-
723
- /** 放开对拦下那个框的引用(见 inspectChooser 的 hold) */
724
- function releaseHold(tabId, c) {
725
- if (!c || !c.hold) return
726
- try { chrome.debugger.sendCommand({ tabId: Number(tabId) }, 'Runtime.releaseObjectGroup', { objectGroup: c.hold }).catch(() => {}) } catch {}
727
- }
728
-
729
- /** 删掉这个标签页拦下的框(给了 c 就只在还是这一条时删),顺手放开引用 */
730
- function dropChooser(tabId, c) {
731
- const id = Number(tabId)
732
- const cur = choosers.get(id)
733
- if (!cur || (c && cur !== c)) return
734
- choosers.delete(id)
735
- releaseHold(id, cur)
736
- }
737
-
738
- /**
739
- * 文件框现在的样子:还在不在页面上、里面已有哪些文件、拦下以后有没有人自己点开 / 选过(watch 时装上记数)。
740
- * 记数挂在节点上的 key 下:拦下那一下的点击早过去了,之后再有 click / change 就是别人(用户、页面)动过它。查不到回 null
741
- */
742
- async function inputState(tabId, backendNodeId, sendFn, key, watch = false) {
743
- const objectGroup = `dsh-chooser-${crypto.randomUUID()}`
744
- try {
745
- const { object } = await sendFn(tabId, 'DOM.resolveNode', { backendNodeId, objectGroup })
746
- const { result } = await sendFn(tabId, 'Runtime.callFunctionOn', {
747
- objectId: object.objectId, returnByValue: true, arguments: [{ value: key }, { value: watch }],
748
- functionDeclaration: `function (k, watch) {
749
- const el = this
750
- if (watch) { el[k] = 0; for (const t of ['click', 'change']) el.addEventListener(t, () => { el[k]++ }, true) }
751
- return { on: el.isConnected, touched: typeof el[k] === 'number' ? el[k] : -1,
752
- files: [...(el.files || [])].map((f) => f.name + '/' + f.size + '/' + f.lastModified).join('|') }
753
- }`,
754
- })
755
- return (result && result.value) || null
756
- } catch { return null } finally {
757
- Promise.resolve().then(() => sendFn(tabId, 'Runtime.releaseObjectGroup', { objectGroup })).catch(() => {})
758
- }
759
- }
760
-
761
- /** 拦下框以后马上查:是不是「选文件夹」,属于哪个文档,框里原来有哪些文件 */
762
- async function inspectChooser(tabId, c) {
763
- const raw = (_t, method, params) => chrome.debugger.sendCommand({ tabId }, method, params)
764
- if (c.backendNodeId) {
765
- // 先抓住这个框:很多网站在点击函数里现造一个 input、不插进页面也不留引用,拦下以后没人拿着它,
766
- // 模型想文件的工夫浏览器一回收就没了(实测强制回收后上传报「没在等」)。用完 / 换掉 / 换页 / 断开时放开
767
- c.hold = `dsh-hold-${c.id}`
768
- try { await raw(tabId, 'DOM.resolveNode', { backendNodeId: c.backendNodeId, objectGroup: c.hold }) } catch {}
769
- try {
770
- const { node } = await raw(tabId, 'DOM.describeNode', { backendNodeId: c.backendNodeId })
771
- c.folder = isFolderNode(node)
772
- } catch {}
773
- c.state = await inputState(tabId, c.backendNodeId, raw, c.key, true)
774
- }
775
- c.doc = await docOf(tabId, c.frameId, raw)
776
- if (choosers.get(tabId) !== c) releaseHold(tabId, c) // 查的工夫已经被新框顶掉 / 换页了
777
- }
778
-
779
- /**
780
- * 插件要求时,把一下点击 / 按键包在拦截里:排队 → 开 → 做 → 等一小会儿看页面要不要选文件 → 关。
781
- * 回 { ...做的结果, fileChooser }(没要选文件就没有这个字段)。
782
- */
783
- async function withChooser(tabId, want, fn) {
784
- if (!want) return fn()
785
- const id = Number(tabId)
786
- const prev = chooserLocks.get(id) || Promise.resolve()
787
- let release
788
- const mine = new Promise((r) => { release = r })
789
- const chain = prev.then(() => mine)
790
- chooserLocks.set(id, chain)
791
- await prev
792
- const token = crypto.randomUUID()
793
- let r
794
- try {
795
- chooserOwner.set(id, token)
796
- await armChooser(id)
797
- r = await fn()
798
- await waitChooser(id, token)
799
- } finally {
800
- await disarmChooser(id) // 关拦截的回包到了,之前拦下的 Page.fileChooserOpened 也都到了
801
- if (chooserOwner.get(id) === token) chooserOwner.delete(id)
802
- release()
803
- if (chooserLocks.get(id) === chain) chooserLocks.delete(id)
804
- }
805
- const fileChooser = await chooserFor(id, token)
806
- return fileChooser ? { ...r, fileChooser } : r
807
- }
808
-
809
- // 正在执行的 CDP 调用计数:空闲断开不能把"正干着活"的标签页掐了
810
- const inflight = new Map()
811
-
812
- /** 慢的 CDP 命令单独放宽:整页 / 大页面截图 15 秒常常不够 */
813
- const CDP_TIMEOUT_MS = { 'Page.captureScreenshot': 60_000 }
814
-
815
- async function send(tabId, method, params, timeoutMs = CDP_TIMEOUT_MS[method] || 15000) {
816
- const id = Number(tabId)
817
- // 每条命令前都重查暂停:用户中途按了暂停,进行中的点击 / 输入不再往下发
818
- if (paused) throw new Error(PAUSED_MSG)
819
- // 必修:以前只有 evaluate 之前才 ensure,key/hover/scroll/dialog 这些直接 send 的 op
820
- // 在空闲松手后永远失败。统一在这里 ensure:既能自动重连,也顺带刷新 lastUsed。
821
- await ensure(id)
822
- inflight.set(id, (inflight.get(id) || 0) + 1)
823
- const p = chrome.debugger.sendCommand({ tabId: id }, method, params || {})
824
- try {
825
- // 兜底:任何 CDP 命令都不该把 op 挂死(历史上 mouseWheel 就不回包)
826
- return await Promise.race([
827
- p,
828
- new Promise((_, rej) => setTimeout(() => rej(new Error(`CDP ${method} ${Math.round(timeoutMs / 1000)} 秒没回应`)), timeoutMs)),
829
- ])
830
- } finally {
831
- const n = (inflight.get(id) || 1) - 1
832
- if (n <= 0) inflight.delete(id); else inflight.set(id, n)
833
- }
834
- }
835
-
836
- /**
837
- * 发出去、不要求回包的 CDP 命令。
838
- * 实测:Input.dispatchMouseEvent 的 mouseWheel 在 Chrome 155 上**事件生效但不回包**,
839
- * 用 send() 等回复会把 scroll 挂死(客户端 45 秒超时)。这里等一小会儿就走。
840
- */
841
- async function sendNoReply(tabId, method, params, graceMs = 1500) {
842
- const id = Number(tabId)
843
- if (paused) throw new Error(PAUSED_MSG)
844
- await ensure(id)
845
- inflight.set(id, (inflight.get(id) || 0) + 1)
846
- try {
847
- await Promise.race([
848
- chrome.debugger.sendCommand({ tabId: id }, method, params || {}).catch(() => {}),
849
- new Promise((res) => setTimeout(res, graceMs)),
850
- ])
851
- } finally {
852
- const n = (inflight.get(id) || 1) - 1
853
- if (n <= 0) inflight.delete(id); else inflight.set(id, n)
854
- }
855
- }
856
-
857
- /** 等页面加载的标签页关掉了 / 调试器断开了:立刻让 nav 失败,别白等到超时、还报「已到」 */
858
- function failLoadWaiter(tabId, why) {
859
- const w = loadWaiters.get(tabId)
860
- if (!w) return
861
- loadWaiters.delete(tabId)
862
- clearTimeout(w.timer)
863
- w.reject(new Error(why))
864
- }
865
-
866
- chrome.debugger.onDetach.addListener((src, reason) => {
867
- if (src && src.tabId != null) {
868
- failLoadWaiter(src.tabId, reason === 'target_closed' ? '标签页在加载中被关掉了' : '等页面加载时调试器被断开了(多半是点掉了 Chrome 的调试提示条)')
869
- attached.delete(src.tabId)
870
- lastUsed.delete(src.tabId)
871
- chooserArmed.delete(src.tabId) // 拦截跟着调试会话没了;拦下的那个框(choosers)不用删,节点 id 换会话照样认
872
- unmarkTab(src.tabId).catch((e) => log('unmark 失败:', String(e && e.message || e))) // 用户点掉调试提示也算松手
873
- }
874
- })
875
-
876
- chrome.debugger.onEvent.addListener((src, method, params) => {
877
- if (method === 'Page.loadEventFired') {
878
- cursorReady.delete(src.tabId)
879
- markCursor(src.tabId, false).catch(() => {}) // 导航后页内光标没了,标签上的小鼠标跟着灭
880
- const w = loadWaiters.get(src.tabId)
881
- if (w) { loadWaiters.delete(src.tabId); clearTimeout(w.timer); w.resolve() }
882
- }
883
- if (method === 'Page.javascriptDialogOpening') {
884
- dialogs.set(src.tabId, { type: params.type, message: params.message, at: Date.now() })
885
- }
886
- if (method === 'Page.javascriptDialogClosed') {
887
- dialogs.delete(src.tabId)
888
- }
889
- if (method === 'Page.fileChooserOpened') {
890
- // 没有 backendNodeId:不是 <input type=file>(showOpenFilePicker 这类),拦下来等于给网页取消了,也塞不进去。
891
- // 记下来回话里说清楚,这个标签页之后一阵不再拦,模型再点一次就会照常弹出系统窗口
892
- if (!params.backendNodeId) chooserSkip.set(src.tabId, Date.now())
893
- const c = {
894
- id: crypto.randomUUID(), key: `__dshPick_${Date.now()}_${Math.random().toString(36).slice(2)}`, owner: chooserOwner.get(src.tabId), mode: params.mode,
895
- backendNodeId: params.backendNodeId || null, frameId: params.frameId || null, at: Date.now(),
896
- }
897
- releaseHold(src.tabId, choosers.get(src.tabId)) // 同一标签页新框顶掉旧框
898
- c.ready = inspectChooser(src.tabId, c)
899
- choosers.set(src.tabId, c)
900
- const w = chooserWaiters.get(src.tabId)
901
- if (w) w()
902
- }
903
- if (method === 'Page.frameNavigated' && params.frame && !params.frame.parentId) {
904
- dropChooser(src.tabId) // 换页了,原来那个文件框也没了
905
- chooserSkip.delete(src.tabId)
906
- }
907
- if (method === 'Network.requestWillBeSent') {
908
- // WebSocket/SSE 这类连接永不 finished,netPending 得有个上限(NET 有 400,它原来没有)
909
- if (netPending.size > NET_MAX) {
910
- const oldest = netPending.keys().next().value
911
- netPending.delete(oldest)
912
- }
913
- netPending.set(params.requestId, {
914
- id: params.requestId, tabId: src.tabId, method: params.request.method, url: params.request.url,
915
- type: params.type, at: Date.now(),
916
- })
917
- }
918
- if (method === 'Network.responseReceived') {
919
- const p = netPending.get(params.requestId)
920
- if (p) { p.status = params.response.status; p.mime = params.response.mimeType }
921
- }
922
- if (method === 'Network.loadingFinished' || method === 'Network.loadingFailed') {
923
- const p = netPending.get(params.requestId)
924
- if (p) {
925
- p.ms = Date.now() - p.at
926
- if (method === 'Network.loadingFailed') p.failed = params.errorText
927
- NET.push(p)
928
- if (NET.length > NET_MAX) NET.shift()
929
- netPending.delete(params.requestId)
930
- }
931
- }
932
- if (method === 'Runtime.consoleAPICalled') {
933
- const args = params.args || []
934
- const f = params.stackTrace && params.stackTrace.callFrames && params.stackTrace.callFrames[0]
935
- const item = { tabId: src.tabId, level: params.type, kind: 'console', text: args.map(fmtArg).join(' '),
936
- at: params.timestamp, where: f && f.url ? `${f.url}:${f.lineNumber + 1}` : '' }
937
- // 调试器接上前打的旧消息是 V8 补发的,补发不带对象预览(只剩 "Object")——回页面里展开一下
938
- if (pushConsole(item) && args.some(needsExpand)) {
939
- expandArgs(src.tabId, args).then((t) => { item.text = t.slice(0, 2000) }).catch(() => {})
940
- }
941
- }
942
- if (method === 'Runtime.exceptionThrown') {
943
- // 没被 catch 的 JS 报错 —— 调试网页时最要紧的一类,console API 那条路收不到
944
- const d = params.exceptionDetails || {}
945
- pushConsole({ tabId: src.tabId, level: 'error', kind: 'exception',
946
- text: (d.exception && (d.exception.description || d.exception.value)) || d.text || 'Uncaught',
947
- at: params.timestamp, where: d.url ? `${d.url}:${(d.lineNumber || 0) + 1}` : '' })
948
- }
949
- if (method === 'Log.entryAdded') {
950
- // 浏览器自己报的:请求失败、CSP 拦截、废弃 API 警告……
951
- const e = params.entry || {}
952
- if (e.level !== 'verbose') {
953
- pushConsole({ tabId: src.tabId, level: e.level, kind: e.source || 'browser', text: e.text || '',
954
- at: e.timestamp, where: e.url || '' })
955
- }
956
- }
957
- })
958
-
959
- /** console 参数 → 一段字。对象/数组用 V8 带的预览拼成 {a: 1, b: "x"},不然只看得到 "Object"。 */
960
- function fmtArg(a) {
961
- if (a.value !== undefined) return typeof a.value === 'string' ? a.value : JSON.stringify(a.value)
962
- if (a.unserializableValue) return a.unserializableValue
963
- const p = a.preview
964
- if (p && p.properties && (p.subtype === 'array' || (p.type === 'object' && !p.subtype))) {
965
- const val = (x) => (x.type === 'string' ? JSON.stringify(x.value) : x.value ?? x.type)
966
- const more = p.overflow ? ', …' : ''
967
- return p.subtype === 'array'
968
- ? `[${p.properties.map(val).join(', ')}${more}]`
969
- : `{${p.properties.map((x) => `${x.name}: ${val(x)}`).join(', ')}${more}}`
970
- }
971
- return a.description || a.type
972
- }
973
-
974
- const needsExpand = (a) => a.objectId && !a.preview && a.type === 'object' && (!a.subtype || a.subtype === 'array')
975
-
976
- /** 页内把对象拼成和预览一样的样子:{a: 1, b: "x"} / [1, 2] */
977
- const EXPAND_FN = `function () {
978
- const v = (x) => typeof x === 'string' ? JSON.stringify(x) : x === null ? 'null'
979
- : Array.isArray(x) ? 'Array(' + x.length + ')'
980
- : typeof x === 'object' ? ((x.constructor && x.constructor.name) || 'Object')
981
- : typeof x === 'function' ? 'ƒ' : String(x);
982
- if (Array.isArray(this)) return '[' + this.slice(0, 20).map(v).join(', ') + (this.length > 20 ? ', …' : '') + ']';
983
- const ks = Object.keys(this);
984
- return '{' + ks.slice(0, 20).map((k) => k + ': ' + v(this[k])).join(', ') + (ks.length > 20 ? ', …' : '') + '}';
985
- }`
986
-
987
- async function expandArgs(tabId, args) {
988
- const parts = []
989
- for (const a of args) {
990
- if (!needsExpand(a)) { parts.push(fmtArg(a)); continue }
991
- try {
992
- const r = await chrome.debugger.sendCommand({ tabId }, 'Runtime.callFunctionOn',
993
- { objectId: a.objectId, functionDeclaration: EXPAND_FN, returnByValue: true, silent: true })
994
- parts.push(r && r.result && typeof r.result.value === 'string' ? r.result.value : fmtArg(a))
995
- } catch {
996
- parts.push(fmtArg(a))
997
- }
998
- }
999
- return parts.join(' ')
1000
- }
1001
-
1002
- /** 重新 attach 时 V8 会把旧消息补发一遍 —— 按「标签页 + 时间 + 内容」去重。 */
1003
- function pushConsole(item) {
1004
- item.text = String(item.text || '').slice(0, 2000)
1005
- item.at = Math.round(Number(item.at) || Date.now())
1006
- item.key = item.text // 去重按原始文字比:text 之后可能被 expandArgs 改写
1007
- const dup = CONSOLE.some(c => c.tabId === item.tabId && c.at === item.at && c.key === item.key)
1008
- if (dup) return false
1009
- CONSOLE.push(item)
1010
- if (CONSOLE.length > 300) CONSOLE.shift()
1011
- return true
1012
- }
1013
-
1014
- /**
1015
- * 注入表达式并取值(有异常就抛,别把 undefined 当成功)。
1016
- * userGesture 只给要它的(模型自己的 eval):读页面、找元素、画光标都不带,不白送页面一次「用户激活」。
1017
- */
1018
- async function evaluate(tabId, expression, userGesture = false) {
1019
- await ensure(tabId)
1020
- const r = await send(tabId, 'Runtime.evaluate', {
1021
- expression,
1022
- returnByValue: true,
1023
- awaitPromise: true,
1024
- userGesture: !!userGesture,
1025
- })
1026
- if (r.exceptionDetails) {
1027
- const d = r.exceptionDetails
1028
- throw new Error((d.exception && (d.exception.description || d.exception.value)) || d.text || '页面 JS 抛异常')
1029
- }
1030
- return r.result ? r.result.value : undefined
1031
- }
1032
-
1033
- /** 页内找一个元素的中点(顺带滚动到可视区),返回视口坐标 */
1034
- const POINT_HELPER = `
1035
- const __dsh_norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
1036
- const __dsh_visible = (el) => {
1037
- const r = el.getBoundingClientRect();
1038
- if (r.width < 1 || r.height < 1) return false;
1039
- const st = getComputedStyle(el);
1040
- if (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0) return false;
1041
- return true;
1042
- };
1043
- const __dsh_point = (el) => {
1044
- el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
1045
- return new Promise((res) => {
1046
- let done = false;
1047
- const finish = () => {
1048
- if (done) return;
1049
- done = true;
1050
- const r = el.getBoundingClientRect();
1051
- res({ x: r.left + r.width / 2, y: r.top + r.height / 2,
1052
- tag: el.tagName.toLowerCase(),
1053
- // 输入框没 innerText,退到 aria-label / placeholder;密码框的 value 绝不拿出来(会上名牌、进工具结果)
1054
- text: __dsh_norm(el.innerText || (el.type === 'password' ? '' : el.value) || el.getAttribute('aria-label') ||
1055
- el.getAttribute('placeholder') || el.getAttribute('title') || el.getAttribute('alt') || '').slice(0, 80) });
1056
- };
1057
- // 后台标签页里 Chrome 会暂停 requestAnimationFrame —— 只等 rAF 的话这个 Promise
1058
- // 永远不 resolve,整个 click-el / click-text 就卡死(45 秒超时、还不回话)。
1059
- // 所以 rAF 之外再挂一个定时器兜底。
1060
- requestAnimationFrame(() => requestAnimationFrame(finish));
1061
- setTimeout(finish, 120);
1062
- });
1063
- };
1064
- `
1065
-
1066
- async function pointOf(tabId, finderJs) {
1067
- const pt = await evaluate(tabId, `(async () => { ${POINT_HELPER} ${finderJs} })()`)
1068
- if (!pt) throw new Error('没找到目标元素(可能不可见或文字不匹配)')
1069
- return pt
1070
- }
1071
-
1072
- /** 页内光标:注入过一次就记住,导航后失效要重注;位置按标签页记着,换了页面从原处接着出现 */
1073
- const cursorReady = new Set()
1074
- const cursorPos = new Map()
1075
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
1076
-
1077
- async function injectCursor(tabId, script) {
1078
- if (!script || !showCursor) return false
1079
- const id = Number(tabId)
1080
- if (!cursorReady.has(id)) {
1081
- await evaluate(tabId, script)
1082
- const p = cursorPos.get(id)
1083
- if (p) await evaluate(tabId, `window.__dshCursor.pos() || window.__dshCursor.place(${p.x}, ${p.y})`).catch(() => {})
1084
- cursorReady.add(id)
1085
- // 语义:标签页上出现小鼠标 = 这个页面里真的有一只鼠标(页内光标已就位)
1086
- await markCursor(tabId, true)
1087
- }
1088
- return true
1089
- }
1090
-
1091
- /**
1092
- * 调页内光标。cursorReady 可能已经过期(页面刚跳走、loadEventFired 还没到;或者页面里还是旧版光标),
1093
- * 所以表达式里先探一下 v3 光标在不在,不在就重注一次再来。光标装不上返回 undefined。
1094
- */
1095
- async function cursorDo(tabId, script, expr) {
1096
- const id = Number(tabId)
1097
- const NONE = '__dsh_no_cursor__'
1098
- const probe = `((window.__dshCursor && window.__dshCursor.version >= 3) ? (${expr}) : ${JSON.stringify(NONE)})`
1099
- if (!cursorReady.has(id) && !(await injectCursor(tabId, script))) return undefined
1100
- let r = await evaluate(tabId, probe)
1101
- if (r === NONE) {
1102
- cursorReady.delete(id)
1103
- if (!(await injectCursor(tabId, script))) return undefined
1104
- r = await evaluate(tabId, probe)
1105
- }
1106
- return r === NONE ? undefined : r
1107
- }
1108
-
1109
- /** 光标滑到 (x, y),可顺带亮出名牌文字。返回滑行时长 ms;光标装不上返回 null(不影响真实操作)。 */
1110
- async function cursorMove(tabId, script, x, y, opts = {}) {
1111
- const px = Math.round(Number(x))
1112
- const py = Math.round(Number(y))
1113
- const mo = { straight: !!opts.straight }
1114
- if (opts.duration != null) mo.duration = Math.max(0, Math.round(Number(opts.duration)))
1115
- const say = opts.label ? `c.label(${JSON.stringify(String(opts.label).slice(0, 80))});` : ''
1116
- try {
1117
- const d = await cursorDo(tabId, script, `(() => { const c = window.__dshCursor; ${say} return c.move(${px}, ${py}, ${JSON.stringify(mo)}) })()`)
1118
- if (d === undefined) return null
1119
- cursorPos.set(Number(tabId), { x: px, y: py })
1120
- return Number(d) || 0
1121
- } catch { return null }
1122
- }
1123
-
1124
- /** 光标的其它表情(click / down / up / label / scroll):只在光标已经在页面里时做,出错不管 */
1125
- async function cursorFx(tabId, expr) {
1126
- if (!cursorReady.has(Number(tabId))) return undefined
1127
- try { return await cursorDo(tabId, '', expr) } catch { return undefined }
1128
- }
1129
-
1130
- /** 等光标飞到位:人眼先看到"要点这儿",再发真实事件 */
1131
- const settle = (d) => sleep(Math.min(700, Math.max(120, d || 0)) + 40)
1132
-
1133
- /** 用 scripting 在 MAIN world 收掉页内光标(不依赖 CDP,调试器已断开时也能收)。 */
1134
- async function hidePageCursor(tabId) {
1135
- try {
1136
- await chrome.scripting.executeScript({
1137
- target: { tabId: Number(tabId) },
1138
- world: 'MAIN',
1139
- func: () => { try { window.__dshCursor && window.__dshCursor.hide() } catch {} },
1140
- })
1141
- } catch {}
1142
- }
1143
-
1144
- /** 标签上的小鼠标只跟"页内光标在不在":在 → 亮;hide / 导航 / 松手 → 灭。 */
1145
- async function markCursor(tabId, on) {
1146
- const id = Number(tabId)
1147
- try {
1148
- await chrome.action.setIcon({ tabId: id, path: on ? CURSOR_ICON : IDLE_ICON })
1149
- await chrome.action.setTitle({ tabId: id, title: on ? CURSOR_TAB_TITLE : '' })
1150
- } catch {}
1151
- await setTabFavicon(id, on)
1152
- }
1153
-
1154
- async function clickPoint(tabId, x, y, opts = {}) {
1155
- const n = Number(opts.clickCount || 1)
1156
- const button = opts.button || 'left'
1157
- const base = { x: Math.round(x), y: Math.round(y), button, clickCount: n }
1158
-
1159
- // 先让光标飞过去,人眼看得见,再发真实点击
1160
- if (opts.cursor && opts.cursor.script) {
1161
- const d = await cursorMove(tabId, opts.cursor.script, base.x, base.y, { label: opts.cursor.label })
1162
- if (d !== null) {
1163
- await settle(d)
1164
- await cursorFx(tabId, `(window.__dshCursor.click(${base.x}, ${base.y}, ${n}), 1)`)
1165
- }
1166
- }
1167
-
1168
- await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mouseMoved', buttons: 0 })
1169
- await new Promise(r => setTimeout(r, 12))
1170
- return withChooser(tabId, opts.chooser, async () => {
1171
- await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mousePressed', buttons: 1 })
1172
- await new Promise(r => setTimeout(r, 24))
1173
- await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mouseReleased', buttons: 0 })
1174
- return { x: base.x, y: base.y, button }
1175
- })
1176
- }
1177
-
1178
- const MODS = { alt: 1, ctrl: 2, meta: 4, shift: 8 }
1179
- const NAMED_KEYS = {
1180
- enter: ['Enter', 'Enter', 13, '\r'], tab: ['Tab', 'Tab', 9], escape: ['Escape', 'Escape', 27],
1181
- esc: ['Escape', 'Escape', 27], backspace: ['Backspace', 'Backspace', 8],
1182
- delete: ['Delete', 'Delete', 46], arrowup: ['ArrowUp', 'ArrowUp', 38], arrowdown: ['ArrowDown', 'ArrowDown', 40],
1183
- arrowleft: ['ArrowLeft', 'ArrowLeft', 37], arrowright: ['ArrowRight', 'ArrowRight', 39],
1184
- home: ['Home', 'Home', 36], end: ['End', 'End', 35], pageup: ['PageUp', 'PageUp', 33],
1185
- pagedown: ['PageDown', 'PageDown', 34], space: [' ', 'Space', 32, ' '],
1186
- }
1187
-
1188
- async function pressKey(tabId, spec) {
1189
- const parts = String(spec).split('+').map(s => s.trim()).filter(Boolean)
1190
- const keyName = parts.pop()
1191
- let modifiers = 0
1192
- for (const p of parts) {
1193
- const m = MODS[p.toLowerCase()]
1194
- if (!m) throw new Error(`不认识修饰键: ${p}(可用 alt/ctrl/meta/shift)`)
1195
- modifiers |= m
1196
- }
1197
- const lower = keyName.toLowerCase()
1198
- let key, code, keyCode, text
1199
- if (NAMED_KEYS[lower]) {
1200
- ;[key, code, keyCode, text] = NAMED_KEYS[lower]
1201
- } else if (keyName.length === 1) {
1202
- key = keyName
1203
- keyCode = keyName.toUpperCase().charCodeAt(0)
1204
- code = /[a-z]/i.test(keyName) ? 'Key' + keyName.toUpperCase()
1205
- : /[0-9]/.test(keyName) ? 'Digit' + keyName
1206
- : ''
1207
- text = keyName
1208
- } else {
1209
- throw new Error(`不认识按键: ${keyName}`)
1210
- }
1211
- const suppressText = modifiers !== 0 || !text
1212
- const base = { key, code, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode, modifiers }
1213
- await send(tabId, 'Input.dispatchKeyEvent', {
1214
- ...base, type: suppressText ? 'rawKeyDown' : 'keyDown',
1215
- ...(suppressText ? {} : { text, unmodifiedText: text }),
1216
- })
1217
- await new Promise(r => setTimeout(r, 12))
1218
- await send(tabId, 'Input.dispatchKeyEvent', { ...base, type: 'keyUp' })
1219
- return { key: spec, modifiers }
1220
- }
1221
-
1222
- // ── 操作表 ──────────────────────────────────────────────────────────────────
1223
-
1224
- const OPS = {
1225
- async ping() {
1226
- return { pong: true, at: Date.now(), attached: [...attached] }
1227
- },
1228
-
1229
- async version() {
1230
- return { version: chrome.runtime.getManifest().version, id: chrome.runtime.id }
1231
- },
1232
-
1233
- /**
1234
- * DSH 插件设置页用:读状态、暂停、开关光标、全部松手。
1235
- * 只开放「更安全」的方向:这条通道 DSH 里的模型也摸得到(cb / socket),
1236
- * 所以「恢复控制」不给 —— 那一下只能用户在 Chrome 的扩展面板里点。
1237
- */
1238
- async panel({ action = 'state', on } = {}) {
1239
- if (action === 'pause') {
1240
- if (!on) throw new Error('恢复控制只能在 Chrome 工具栏的 DSH Bridge 面板里打开')
1241
- await setPaused(true, 'DSH 设置页')
1242
- } else if (action === 'cursor') {
1243
- await setShowCursor(!!on, 'DSH 设置页')
1244
- } else if (action === 'window') {
1245
- await setOwnWindow(!!on, 'DSH 设置页')
1246
- } else if (action === 'releaseAll') {
1247
- await releaseAllTabs()
1248
- } else if (action !== 'state') {
1249
- throw new Error(`panel 不认识的 action: ${action}`)
1250
- }
1251
- const st = await buildState()
1252
- return {
1253
- version: st.version, id: chrome.runtime.id, paused: st.paused, showCursor: st.showCursor,
1254
- ownWindow: st.ownWindow, attachedCount: st.attachedCount,
1255
- sessions: st.sessions.filter((x) => x.tabs.some((t) => t.attached)).length,
1256
- tabs: [...st.sessions.flatMap((x) => x.tabs), ...st.orphans]
1257
- .filter((t) => t.attached).slice(0, 8).map((t) => ({ title: t.title, url: t.url })),
1258
- }
1259
- },
1260
-
1261
- /** 改完扩展代码:拷文件 → cb reload,不用去 chrome://extensions 点刷新 */
1262
- async reload() {
1263
- setTimeout(() => chrome.runtime.reload(), 250)
1264
- return { reloading: true }
1265
- },
1266
-
1267
- async logs({ limit = 60 } = {}) {
1268
- return { lines: LOG.slice(-limit) }
1269
- },
1270
-
1271
- async console({ limit = 40, tabId, clear = false } = {}) {
1272
- if (clear) {
1273
- for (let i = CONSOLE.length - 1; i >= 0; i--) {
1274
- if (tabId == null || CONSOLE[i].tabId === Number(tabId)) CONSOLE.splice(i, 1)
1275
- }
1276
- return { cleared: true }
1277
- }
1278
- const items = tabId != null ? CONSOLE.filter(c => c.tabId === Number(tabId)) : CONSOLE
1279
- return { items: items.slice(-limit) }
1280
- },
1281
-
1282
- async tabs() {
1283
- const tabs = await chrome.tabs.query({})
1284
- // 窗口不止一个时每个窗口都有一个 active:focused 标出用户最后在用的那个窗口,agentWindow 标出 DSH 的干活窗口
1285
- let focusedWin = null
1286
- try { focusedWin = (await chrome.windows.getLastFocused()).id } catch {}
1287
- const agentWins = await agentWindowIds()
1288
- // 刚开、服务器还没回第一个字节的页 url 是空的,要去的地址在 pendingUrl:不算上的话,刚开的慢页列不出来,
1289
- // 不传 tab 接着操作它也会报「没指定标签页」
1290
- return tabs
1291
- .map(t => ({ t, url: t.url || t.pendingUrl || '' }))
1292
- .filter(({ url }) => url && !url.startsWith('chrome-extension://'))
1293
- .map(({ t, url }) => ({
1294
- id: t.id, windowId: t.windowId, active: t.active, pinned: t.pinned,
1295
- focused: t.windowId === focusedWin, agentWindow: agentWins.has(t.windowId),
1296
- title: t.title, url, attached: attached.has(t.id),
1297
- // 这个标签页是不是被我们自动分进「🖱 DSH agent」组(面板和自检都用得上)
1298
- grouped: groupedTabs.has(t.id), groupId: t.groupId >= 0 ? t.groupId : null,
1299
- }))
1300
- },
1301
-
1302
- async attach({ tabId }) {
1303
- await ensure(tabId)
1304
- return { tabId: Number(tabId), attached: true }
1305
- },
1306
-
1307
- async detach({ tabId }) {
1308
- failLoadWaiter(Number(tabId), '等页面加载时被松手了') // 自己 detach 不会触发 onDetach,这里补上
1309
- try { await chrome.debugger.detach({ tabId: Number(tabId) }) } catch {}
1310
- attached.delete(Number(tabId))
1311
- lastUsed.delete(Number(tabId))
1312
- await unmarkTab(tabId)
1313
- return { tabId: Number(tabId), attached: false }
1314
- },
1315
-
1316
- async activate({ tabId }) {
1317
- const t = await chrome.tabs.get(Number(tabId))
1318
- await chrome.tabs.update(Number(tabId), { active: true })
1319
- await chrome.windows.update(t.windowId, { focused: true })
1320
- return { tabId: Number(tabId), windowId: t.windowId }
1321
- },
1322
-
1323
- async open({ url, active = false }) {
1324
- // 相对地址会被 tabs.create 按扩展自己的地址补全(example.com → chrome-extension://…/example.com),只收完整网址
1325
- if (url) { try { new URL(url) } catch { throw new Error(`要给完整网址(带 https://):${url}`) } }
1326
- // 默认开进 DSH 自己的窗口(后台,不抢焦点);用户关了「单独窗口」就在当前窗口后台开页。
1327
- // 两种都不顶掉用户正在看的标签页。active=true(cb open --front)是有意要它跳到眼前,照旧开在当前窗口
1328
- if (ownWindow && !active) {
1329
- const t = await openInAgentWindow(url)
1330
- return { tabId: t.id, url: t.pendingUrl || t.url || url || '', window: 'agent' }
1331
- }
1332
- const t = await chrome.tabs.create({ url, active: !!active })
1333
- return { tabId: t.id, url: t.url }
1334
- },
1335
-
1336
- async close({ tabId }) {
1337
- await chrome.tabs.remove(Number(tabId))
1338
- return { closed: Number(tabId) }
1339
- },
1340
-
1341
- async eval({ tabId, expression, userGesture = true }) {
1342
- return { value: await evaluate(tabId, expression, userGesture !== false) }
1343
- },
1344
-
1345
- async cdp({ tabId, method, params }) {
1346
- await ensure(tabId)
1347
- if (method === 'Page.navigateToHistoryEntry') {
1348
- // 后退 / 前进到历史里的扩展页面也算「导航到扩展页面」
1349
- const h = await send(tabId, 'Page.getNavigationHistory')
1350
- const e = (h.entries || []).find((x) => x.id === (params || {}).entryId)
1351
- if (e && isExtUrl(e.url)) throw new Error('扩展页面(chrome-extension://)不能被自动化操作')
1352
- }
1353
- return { result: await send(tabId, method, params || {}) }
1354
- },
1355
-
1356
- async nav({ tabId, url, wait = true, timeoutMs = 30000 }) {
1357
- const id = await ensure(tabId)
1358
- // 加载完 → loaded=true;超时 → loaded=false(照样返回,调用方提示「还没加载完」);
1359
- // 标签页关了 / 调试器断了 → failLoadWaiter 直接让它失败
1360
- let entry = null
1361
- const p = wait ? new Promise((resolve, reject) => {
1362
- entry = { resolve: () => resolve(true), reject, timer: null }
1363
- entry.timer = setTimeout(() => { if (loadWaiters.get(id) === entry) loadWaiters.delete(id); resolve(false) }, timeoutMs)
1364
- loadWaiters.set(id, entry)
1365
- }) : null
1366
- let r
1367
- try {
1368
- r = await send(id, 'Page.navigate', { url })
1369
- } catch (e) {
1370
- if (entry) { clearTimeout(entry.timer); if (loadWaiters.get(id) === entry) loadWaiters.delete(id) }
1371
- throw e
1372
- }
1373
- const loaded = p ? await p : null
1374
- const t = await chrome.tabs.get(id).catch(() => null)
1375
- return { url: (t && t.url) || url, title: t && t.title, frameId: r.frameId, waited: !!wait, loaded }
1376
- },
1377
-
1378
- async click({ tabId, x, y, clickCount, button, script, chooser }) {
1379
- return clickPoint(tabId, x, y, { clickCount, button, chooser, cursor: { script, label: `点击 (${Math.round(x)}, ${Math.round(y)})` } })
1380
- },
1381
-
1382
- async clickEl({ tabId, selector, script, chooser }) {
1383
- const pt = await pointOf(tabId, `
1384
- const el = document.querySelector(${JSON.stringify(selector)});
1385
- if (!el) return null;
1386
- let target = el;
1387
- const r0 = el.getBoundingClientRect();
1388
- if (r0.width < 1 || r0.height < 1) {
1389
- const inner = [...el.querySelectorAll('*')].find(__dsh_visible);
1390
- if (inner) target = inner;
1391
- }
1392
- if (!__dsh_visible(target) && !target.getBoundingClientRect().width) return null;
1393
- return __dsh_point(target);
1394
- `)
1395
- const hit = await clickPoint(tabId, pt.x, pt.y, { chooser, cursor: { script, label: `点击 ${pt.text || pt.tag}` } })
1396
- return { ...hit, target: pt }
1397
- },
1398
-
1399
- async clickText({ tabId, text, exact = true, index = 0, script, chooser }) {
1400
- const pt = await pointOf(tabId, `
1401
- const want = __dsh_norm(${JSON.stringify(text)});
1402
- const SEL = 'a,button,input,textarea,select,label,summary,[role=button],[role=link],[role=tab],[role=menuitem],[onclick],[contenteditable=true],li,td,th,h1,h2,h3,h4,span,div,p';
1403
- const all = [...document.querySelectorAll(SEL)].filter(__dsh_visible);
1404
- const label = (el) => __dsh_norm(el.innerText || (el.type === 'password' ? '' : el.value) || el.getAttribute('aria-label') || el.getAttribute('placeholder') || '');
1405
- let hit = all.filter((el) => label(el) === want);
1406
- if (!hit.length && ${exact ? 'false' : 'true'}) hit = all.filter((el) => label(el).includes(want));
1407
- if (!hit.length) return null;
1408
- hit.sort((a, b) => { const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); return ra.width * ra.height - rb.width * rb.height; });
1409
- const el = hit[Math.min(${Number(index) || 0}, hit.length - 1)];
1410
- // 元素框常常比可见按钮大得多(<a> 里塞满空白),点框中心会落在按钮外面。
1411
- // 所以先找承载这段文字的文本节点,用 Range 拿它的**精确**位置。
1412
- const textRect = (root, needle) => {
1413
- const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
1414
- let n;
1415
- while ((n = w.nextNode())) {
1416
- const t = __dsh_norm(n.nodeValue || '');
1417
- if (!t) continue;
1418
- if (t === needle || t.includes(needle)) {
1419
- const rg = document.createRange();
1420
- rg.selectNodeContents(n);
1421
- const rc = rg.getBoundingClientRect();
1422
- if (rc.width > 0 && rc.height > 0) return rc;
1423
- }
1424
- }
1425
- return null;
1426
- };
1427
- const tr = textRect(el, want);
1428
- if (tr) {
1429
- const pr = el.getBoundingClientRect();
1430
- return { x: Math.round(tr.x + tr.width / 2), y: Math.round(tr.y + tr.height / 2),
1431
- text: (el.innerText || '').trim().slice(0, 60), tag: el.tagName.toLowerCase(),
1432
- rect: [Math.round(pr.x), Math.round(pr.y), Math.round(pr.width), Math.round(pr.height)],
1433
- textRect: [Math.round(tr.x), Math.round(tr.y), Math.round(tr.width), Math.round(tr.height)] };
1434
- }
1435
- return __dsh_point(el);
1436
- `)
1437
- const hit = await clickPoint(tabId, pt.x, pt.y, { chooser, cursor: { script, label: `点击 ${pt.text || pt.tag}` } })
1438
- return { ...hit, target: pt }
1439
- },
1440
-
1441
- async type({ tabId, text, selector, script }) {
1442
- if (selector) await OPS.clickEl({ tabId, selector, script })
1443
- await ensure(tabId)
1444
- // 名牌写上在输什么。只有确认焦点落在普通(非密码)输入框里才亮原文:焦点在 shadow DOM / 同源 iframe 里
1445
- // 就往里找真正的焦点元素;找不到(跨域 iframe、关闭的 shadow root……)或者是密码样式的框,一律打码
1446
- const shown = JSON.stringify(text.length > 24 ? text.slice(0, 24) + '…' : text)
1447
- await cursorFx(tabId, `(() => {
1448
- let a = document.activeElement;
1449
- for (let i = 0; a && i < 32; i++) {
1450
- if (a.shadowRoot && a.shadowRoot.activeElement) { a = a.shadowRoot.activeElement; continue; }
1451
- if (a.tagName === 'IFRAME' || a.tagName === 'FRAME') { let d = null; try { d = a.contentDocument; } catch {} a = d && d.activeElement; continue; }
1452
- break;
1453
- }
1454
- let plain = false;
1455
- try {
1456
- const sec = (a.ownerDocument.defaultView || window).getComputedStyle(a).webkitTextSecurity || 'none';
1457
- plain = ((a.tagName === 'INPUT' && a.type !== 'password') || a.tagName === 'TEXTAREA' || a.isContentEditable) && sec === 'none';
1458
- } catch {}
1459
- window.__dshCursor.label(plain ? '输入「' + ${shown} + '」' : '输入 ••••••');
1460
- return 1;
1461
- })()`)
1462
- await send(tabId, 'Input.insertText', { text })
1463
- return { typed: text.length, selector: selector || null }
1464
- },
1465
-
1466
- // ── 读取类:让模型能"看"页面 ──────────────────────────────────────────────
1467
-
1468
- async text({ tabId, selector, limit = 8000 }) {
1469
- const js = selector
1470
- ? `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? (el.innerText || el.textContent || '') : null })()`
1471
- : `document.body ? (document.body.innerText || '') : ''`
1472
- const t = await evaluate(tabId, js)
1473
- if (t === null) throw new Error(`没找到元素: ${selector}`)
1474
- const s = String(t)
1475
- const cut = s.length > limit
1476
- return { text: cut ? s.slice(0, limit) + `\n…(截断,全文 ${s.length} 字)` : s, length: s.length, truncated: cut }
1477
- },
1478
-
1479
- async html({ tabId, selector = 'body', limit = 4000 }) {
1480
- const t = await evaluate(tabId, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? el.outerHTML : null })()`)
1481
- if (t === null) throw new Error(`没找到元素: ${selector}`)
1482
- const s = String(t)
1483
- const cut = s.length > limit
1484
- return { html: cut ? s.slice(0, limit) + `…(截断,全文 ${s.length} 字)` : s, length: s.length, truncated: cut }
1485
- },
1486
-
1487
- async attr({ tabId, selector, name }) {
1488
- const value = await evaluate(tabId, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? el.getAttribute(${JSON.stringify(name)}) : null })()`)
1489
- return { selector, name, value }
1490
- },
1491
-
1492
- async info({ tabId }) {
1493
- const t = await chrome.tabs.get(Number(tabId))
1494
- let viewport = null
1495
- try {
1496
- await ensure(tabId)
1497
- const m = await send(tabId, 'Page.getLayoutMetrics')
1498
- const v = m.cssVisualViewport
1499
- viewport = { w: Math.round(v.clientWidth), h: Math.round(v.clientHeight), scrollY: Math.round(v.pageY) }
1500
- } catch {}
1501
- return {
1502
- tabId: Number(tabId), url: t.url, title: t.title, status: t.status,
1503
- windowId: t.windowId, active: t.active, attached: attached.has(Number(tabId)),
1504
- viewport, pendingDialog: dialogs.get(Number(tabId)) || null,
1505
- }
1506
- },
1507
-
1508
- async waitFor({ tabId, selector, timeoutMs = 15000, visible = true }) {
1509
- const deadline = Date.now() + Number(timeoutMs)
1510
- const js = `(() => {
1511
- const el = document.querySelector(${JSON.stringify(selector)});
1512
- if (!el) return null;
1513
- const r = el.getBoundingClientRect();
1514
- const st = getComputedStyle(el);
1515
- const vis = r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none';
1516
- return { found: true, visible: vis, x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2), text: (el.innerText || '').trim().slice(0, 60) };
1517
- })()`
1518
- let last = null
1519
- while (Date.now() < deadline) {
1520
- last = await evaluate(tabId, js)
1521
- if (last && (!visible || last.visible)) return { ...last, waitedMs: Number(timeoutMs) - (deadline - Date.now()) }
1522
- await new Promise(r => setTimeout(r, 250))
1523
- }
1524
- throw new Error(`等了 ${timeoutMs}ms 还没等到 ${selector}${last ? '(元素在,但不可见)' : ''}`)
1525
- },
1526
-
1527
- // ── 输入类 ───────────────────────────────────────────────────────────────
1528
-
1529
- async hover({ tabId, x, y, selector, script }) {
1530
- let px = Number(x) || 0, py = Number(y) || 0, target = null
1531
- if (selector) {
1532
- const pt = await pointOf(tabId, `const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; return __dsh_point(el);`)
1533
- px = pt.x; py = pt.y; target = pt
1534
- }
1535
- if (script) {
1536
- const d = await cursorMove(tabId, script, px, py, { label: `悬停 ${target ? target.text || target.tag : `(${Math.round(px)}, ${Math.round(py)})`}` })
1537
- if (d !== null) await settle(d)
1538
- }
1539
- await send(tabId, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x: Math.round(px), y: Math.round(py), buttons: 0 })
1540
- return { x: Math.round(px), y: Math.round(py), target }
1541
- },
1542
-
1543
- async scroll({ tabId, x = 200, y = 200, deltaY = 600, deltaX = 0 }) {
1544
- const before = await evaluate(tabId, 'Math.round(window.scrollY)')
1545
- await cursorFx(tabId, `(window.__dshCursor.label(${JSON.stringify(deltaY < 0 ? '向上滚动' : '向下滚动')}, 1400), window.__dshCursor.scroll(${deltaY < 0 ? -1 : 1}), 1)`)
1546
- await sendNoReply(tabId, 'Input.dispatchMouseEvent', {
1547
- type: 'mouseWheel', x: Math.round(x), y: Math.round(y),
1548
- deltaX: Math.round(deltaX), deltaY: Math.round(deltaY),
1549
- })
1550
- let after = await evaluate(tabId, '({ scrollY: Math.round(window.scrollY), pageHeight: Math.round(document.documentElement.scrollHeight) })')
1551
- let via = 'wheel'
1552
- if (after.scrollY === before) {
1553
- // 后台/不可见标签页里 Chrome 不会为滚轮合成帧(实测 mouseWheel 事件发了但页面不动),
1554
- // 退回 JS 滚动 —— 想要的效果是"页面滚下去",不是"必须是合成事件"。
1555
- after = await evaluate(tabId, `(() => { window.scrollBy(0, ${Math.round(deltaY)}); return { scrollY: Math.round(window.scrollY), pageHeight: Math.round(document.documentElement.scrollHeight) } })()`)
1556
- via = 'js'
1557
- }
1558
- return { deltaY, via, ...after }
1559
- },
1560
-
1561
- async focus({ tabId, selector }) {
1562
- const ok = await evaluate(tabId, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return false; el.focus(); return document.activeElement === el })()`)
1563
- if (!ok) throw new Error(`聚焦失败: ${selector}`)
1564
- return { focused: selector }
1565
- },
1566
-
1567
- async select({ tabId, selector, value }) {
1568
- const r = await evaluate(tabId, `(() => {
1569
- const el = document.querySelector(${JSON.stringify(selector)});
1570
- if (!el) return { ok: false, why: '找不到元素' };
1571
- if (el.tagName !== 'SELECT') return { ok: false, why: '不是 <select> 元素' };
1572
- const opts = [...el.options];
1573
- const hit = opts.find(o => o.value === ${JSON.stringify(value)}) || opts.find(o => (o.textContent || '').trim() === ${JSON.stringify(value)});
1574
- if (!hit) return { ok: false, why: '没有这个选项', options: opts.map(o => o.value).slice(0, 20) };
1575
- el.value = hit.value;
1576
- el.dispatchEvent(new Event('input', { bubbles: true }));
1577
- el.dispatchEvent(new Event('change', { bubbles: true }));
1578
- return { ok: true, value: hit.value, label: (hit.textContent || '').trim() };
1579
- })()`)
1580
- if (!r.ok) throw new Error(`选择失败:${r.why}${r.options ? '(可选值:' + r.options.join(', ') + ')' : ''}`)
1581
- return r
1582
- },
1583
-
1584
- async upload({ tabId, selector, files, chooserId }) {
1585
- const list = Array.isArray(files) ? files : [files]
1586
- // 兜底(插件那边已按 realpath 卡过目录):只收绝对路径,任何一段以 . 开头(隐藏目录 / 文件、..)都不收。
1587
- // 绝对路径:/ 开头(Mac / Linux),或盘符 C:\ 和 \\server\share(Windows;以前只认 /,Windows 上一律被拒)
1588
- for (const f of list) {
1589
- const s = String(f)
1590
- const abs = s.startsWith('/') || /^[A-Za-z]:[\\/]/.test(s) || /^\\\\[^\\]/.test(s)
1591
- if (!abs || s.split(/[\\/]/).some((seg) => seg.startsWith('.'))) {
1592
- throw new Error(`不能上传这个路径(要绝对路径,且不能在隐藏目录里 / 是隐藏文件):${s}`)
1593
- }
1594
- }
1595
- await ensure(tabId)
1596
- if ((await fileAccess()) === false) throw fileAccessError()
1597
- const put = async (params) => {
1598
- try {
1599
- await send(tabId, 'DOM.setFileInputFiles', { files: list, ...params })
1600
- } catch (e) {
1601
- if (/Not allowed/.test(String(e && e.message || e))) throw fileAccessError()
1602
- throw e
1603
- }
1604
- }
1605
- if (!selector) {
1606
- // 没给选择器:塞给刚才拦下的选文件窗口对应的那个框(多半是藏起来的 <input type=file>)。
1607
- // 只认点击回话里给出的那个 id:同一个标签页别的会话后来又点开一个,不能把文件塞到人家的框里
1608
- const id = Number(tabId)
1609
- const c = choosers.get(id)
1610
- const none = () => new Error('NO_FILE_CHOOSER 页面现在没在等选文件:先点页面上的上传按钮,或者给出文件输入框的选择器')
1611
- if (c && Date.now() - c.at > CHOOSER_TTL_MS) dropChooser(id, c)
1612
- if (!c || !c.backendNodeId || c.folder || !chooserId || c.id !== String(chooserId) || Date.now() - c.at > CHOOSER_TTL_MS) throw none()
1613
- await c.ready
1614
- // 调试会话断开期间换过页(那时收不到 frameNavigated):文档对不上就当框没了,别往别的节点上塞
1615
- // 只删自己这条:等回包的工夫别的请求可能已经拦下了新框
1616
- const drop = () => dropChooser(id, c)
1617
- if (c.doc && (await docOf(id, c.frameId, send)) !== c.doc) { drop(); throw none() }
1618
- const st = await inputState(id, c.backendNodeId, send, c.key)
1619
- // 拦下时在页面上、现在不在了(弹层关了重开、被页面换掉了):别塞给脱离页面的旧节点。
1620
- // 拦下时就不在页面上的(脚本现造一个 input、不插进页面直接 click,很常见)照常塞
1621
- if (st && !st.on && c.state && c.state.on) { drop(); throw none() }
1622
- // 拦下以后用户自己点开过 / 选过(网页读完文件常把框清空,所以光比文件不够):别拿模型的文件把它盖掉
1623
- if (st && c.state && (st.touched > 0 || st.files !== c.state.files)) { drop(); throw new Error('USER_PICKED 拦下以后有人自己动过这个文件框(多半是用户自己选了文件),没有替换') }
1624
- if (c.mode === 'selectSingle' && list.length > 1) throw new Error(`MULTI_NOT_ALLOWED 这个文件框一次只收一个文件(给了 ${list.length} 个)`)
1625
- try {
1626
- await put({ backendNodeId: c.backendNodeId })
1627
- } catch (e) {
1628
- // 页面换过 / 那个框被删了:节点找不到
1629
- if (/No node|Could not find node|not found/i.test(String(e && e.message || e))) { drop(); throw none() }
1630
- throw e
1631
- }
1632
- drop()
1633
- return { selector: null, chooser: true, files: list }
1634
- }
1635
- const { root } = await send(tabId, 'DOM.getDocument', { depth: -1, pierce: true })
1636
- const { nodeId } = await send(tabId, 'DOM.querySelector', { nodeId: root.nodeId, selector })
1637
- if (!nodeId) throw new Error(`没找到文件输入框: ${selector}`)
1638
- const { node } = await send(tabId, 'DOM.describeNode', { nodeId })
1639
- if (isFolderNode(node)) throw new Error('FOLDER_INPUT 这是选文件夹的框(webkitdirectory),DSH 暂时没法替你选文件夹:请用户自己点它选')
1640
- // 单选的框塞多个,Chrome 只留第一个:别报「都交了」
1641
- // 选中的不是文件框(比如旁边显示文件名的文本框)就不管,让 Chrome 自己报「不是文件框」
1642
- const isFile = node && String(node.nodeName).toUpperCase() === 'INPUT' && String(attrValue(node, 'type') || '').toLowerCase() === 'file'
1643
- if (list.length > 1 && isFile && !hasAttr(node, 'multiple')) {
1644
- throw new Error(`MULTI_NOT_ALLOWED 这个文件框一次只收一个文件(给了 ${list.length} 个)`)
1645
- }
1646
- await put({ nodeId })
1647
- // 塞的正是拦下的那个框才算用掉;别的框(别的会话正等着的)留着
1648
- const c = choosers.get(Number(tabId))
1649
- if (c && node && c.backendNodeId === node.backendNodeId) dropChooser(tabId, c)
1650
- return { selector, files: list }
1651
- },
1652
-
1653
- /** 被 alert/confirm 挡住时用这个放行,否则页面会一直卡住 */
1654
- async dialog({ tabId, action, text }) {
1655
- const accept = action !== 'dismiss'
1656
- await send(tabId, 'Page.handleJavaScriptDialog', { accept, ...(text ? { promptText: text } : {}) })
1657
- dialogs.delete(Number(tabId))
1658
- return { action: accept ? 'accept' : 'dismiss' }
1659
- },
1660
-
1661
- async key({ tabId, key, times = 1, chooser }) {
1662
- await ensure(tabId)
1663
- // 焦点在「上传」按钮上按回车 / 空格也会弹选文件窗口
1664
- return withChooser(tabId, chooser, async () => {
1665
- const out = []
1666
- for (let i = 0; i < times; i++) out.push(await pressKey(tabId, key))
1667
- return { pressed: key, times, modifiers: out[0] && out[0].modifiers }
1668
- })
1669
- },
1670
-
1671
- async shot({ tabId, format = 'png', quality, full = false, selector }) {
1672
- await ensure(tabId)
1673
- const params = { format, captureBeyondViewport: !!full }
1674
- if (format === 'jpeg' && quality) params.quality = quality
1675
- let clip = null
1676
- if (selector) {
1677
- const rect = await evaluate(tabId, `(() => {
1678
- const el = document.querySelector(${JSON.stringify(selector)});
1679
- if (!el) return null;
1680
- el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
1681
- // 后台标签页会暂停 rAF —— 只等 rAF 会卡满 15 秒,定时器兜底(同 __dsh_point)
1682
- return new Promise((res) => {
1683
- let done = false;
1684
- const finish = () => {
1685
- if (done) return;
1686
- done = true;
1687
- const r = el.getBoundingClientRect();
1688
- res({ x: r.left, y: r.top, width: r.width, height: r.height });
1689
- };
1690
- requestAnimationFrame(() => requestAnimationFrame(finish));
1691
- setTimeout(finish, 120);
1692
- });
1693
- })()`)
1694
- if (!rect) throw new Error(`没找到元素: ${selector}`)
1695
- clip = { x: rect.x, y: rect.y, width: rect.width, height: rect.height, scale: 1 }
1696
- params.clip = clip
1697
- params.captureBeyondViewport = false
1698
- }
1699
- const r = await send(tabId, 'Page.captureScreenshot', params)
1700
- const t = await chrome.tabs.get(Number(tabId)).catch(() => null)
1701
- return { data: r.data, format, url: t && t.url, title: t && t.title, full: !!full, clip }
1702
- },
1703
-
1704
- async network({ tabId, limit = 40, filter, clear, reload = false, waitMs = 2500 }) {
1705
- // 只清这个标签页的;不给 tabId 才全清(别把别的标签页的记录也抹了)
1706
- const dropTab = (id) => { for (let i = NET.length - 1; i >= 0; i--) if (NET[i].tabId === id) NET.splice(i, 1) }
1707
- if (clear) { if (tabId != null) dropTab(Number(tabId)); else NET.length = 0; return { cleared: true } }
1708
- // Network 事件只在 attach 之后才有,所以先 attach;要历史就 --reload 刷一次
1709
- if (tabId != null && reload) {
1710
- await ensure(tabId)
1711
- dropTab(Number(tabId))
1712
- await send(tabId, 'Page.reload', {})
1713
- await new Promise(r => setTimeout(r, Number(waitMs)))
1714
- } else if (tabId != null) {
1715
- await ensure(tabId)
1716
- }
1717
- let items = tabId != null ? NET.filter(n => n.tabId === Number(tabId)) : NET
1718
- if (filter) items = items.filter(n => (n.url || '').includes(filter) || (n.method || '').includes(filter))
1719
- return {
1720
- items: items.slice(-limit).map(n => ({
1721
- id: n.id, method: n.method, status: n.status, url: n.url, type: n.type, mime: n.mime, ms: n.ms, failed: n.failed,
1722
- })),
1723
- }
1724
- },
1725
-
1726
- /**
1727
- * 录一段屏幕(CDP screencast),用来做演示 GIF。
1728
- * 帧以 base64 JPEG 返回;调用方自己写文件、自己合成。
1729
- */
1730
- async screencast({ tabId, durationMs = 5000, maxWidth = 900, quality = 70, maxFrames = 140 }) {
1731
- await ensure(tabId)
1732
- const id = Number(tabId)
1733
- const frames = []
1734
- const onEvent = (src, method, params) => {
1735
- if (src.tabId !== id) return
1736
- if (method !== 'Page.screencastFrame') return
1737
- frames.push(params.data)
1738
- chrome.debugger
1739
- .sendCommand({ tabId: id }, 'Page.screencastFrameAck', { sessionId: params.sessionId })
1740
- .catch(() => {})
1741
- }
1742
- chrome.debugger.onEvent.addListener(onEvent)
1743
- try {
1744
- await send(tabId, 'Page.startScreencast', {
1745
- format: 'jpeg', quality, maxWidth, maxHeight: Math.round(maxWidth * 1.4), everyNthFrame: 1,
1746
- })
1747
- const deadline = Date.now() + Number(durationMs)
1748
- // 帧太多会把一条 native message 撑爆(也拖慢回传),到上限就提前收工
1749
- while (Date.now() < deadline && frames.length < Number(maxFrames)) {
1750
- await new Promise((r) => setTimeout(r, 100))
1751
- }
1752
- await send(tabId, 'Page.stopScreencast')
1753
- } finally {
1754
- chrome.debugger.onEvent.removeListener(onEvent)
1755
- }
1756
- return { count: frames.length, frames }
1757
- },
1758
-
1759
- /** 页内光标:调用方把脚本内容传进来(每次都带也没事,注入过就不再执行),这里负责注入 + 调用 */
1760
- async cursor({ tabId, script, action, x, y, duration, straight, text }) {
1761
- const id = Number(tabId)
1762
- if (action === 'hide' || action === 'clear') {
1763
- try { await evaluate(tabId, 'window.__dshCursor && window.__dshCursor.hide()') }
1764
- finally { cursorReady.delete(id); cursorPos.delete(id); await markCursor(tabId, false) }
1765
- return { action }
1766
- }
1767
- if (!showCursor) return { action, skipped: '用户在弹窗里关了页内光标', duration: 0 }
1768
- const missing = () => new Error('光标脚本没装上(第一次调用要带 script)')
1769
- if (action === 'move' || action === 'click') {
1770
- const d = await cursorMove(tabId, script, x, y, { duration, straight, label: text })
1771
- if (d === null) throw missing()
1772
- if (action === 'click') {
1773
- await settle(d)
1774
- await cursorDo(tabId, script, `(window.__dshCursor.click(${Math.round(x)}, ${Math.round(y)}), 1)`)
1775
- }
1776
- return { action, x, y, duration: d }
1777
- }
1778
- const fx = { down: 'down()', up: 'up()', label: `label(${JSON.stringify(String(text || ''))})` }[action]
1779
- if (!fx) throw new Error(`不认识的光标动作: ${action}(move/click/down/up/label/hide/clear)`)
1780
- if ((await cursorDo(tabId, script, `(window.__dshCursor.${fx}, 1)`)) === undefined) throw missing()
1781
- return { action }
1782
- },
1783
- }
1784
-
1785
- // ── 弹窗(popup.html)的接口 ─────────────────────────────────────────────────
1786
-
1787
- async function buildState() {
1788
- if (port && (!hostInfo || Date.now() - hostInfo.at > 5000)) post({ hostPing: true })
1789
- const now = Date.now()
1790
- const tabInfo = new Map()
1791
- for (const t of await chrome.tabs.query({})) tabInfo.set(t.id, t)
1792
- const self = `chrome-extension://${chrome.runtime.id}/`
1793
- const tabView = (id) => {
1794
- const t = tabInfo.get(id)
1795
- if (!t || (t.url || '').startsWith(self)) return null // 弹窗页自己不算
1796
- return {
1797
- // 我们给受控标签页换上的小鼠标图标不是网站自己的,别拿来当它的图标
1798
- id, title: t.title || '', url: t.url || '', favIconUrl: t.favIconUrl === CURSOR_FAVICON ? '' : t.favIconUrl || '',
1799
- attached: attached.has(id), busy: inflight.has(id), lastUsed: lastUsed.get(id) || 0,
1800
- dialog: dialogs.get(id) || null,
1801
- }
1802
- }
1803
- const owned = new Set()
1804
- const sessions = []
1805
- for (const [k, s] of [...SESSIONS].sort((a, b) => b[1].last - a[1].last)) {
1806
- for (const id of s.tabs) if (!tabInfo.has(id)) s.tabs.delete(id)
1807
- const tabs = [...s.tabs].map(tabView).filter(Boolean)
1808
- .sort((a, b) => (b.attached - a.attached) || (b.lastUsed - a.lastUsed))
1809
- // 两小时没动静、手上也没有标签页的会话就不显示了
1810
- if (!tabs.some((t) => t.attached) && now - s.last > 2 * 3600e3) { SESSIONS.delete(k); continue }
1811
- tabs.forEach((t) => owned.add(t.id))
1812
- sessions.push({ key: s.key, kind: s.kind, session: s.session, pid: s.pid,
1813
- first: s.first, last: s.last, ops: s.ops, errors: s.errors, tabs })
1814
- }
1815
- const orphans = [...attached].filter((id) => !owned.has(id)).map(tabView).filter(Boolean)
1816
- return {
1817
- now,
1818
- version: chrome.runtime.getManifest().version,
1819
- connected: !!port,
1820
- paused,
1821
- host: hostInfo,
1822
- idleMs: DETACH_IDLE_MS,
1823
- attachedCount: controlledCount(),
1824
- showCursor,
1825
- ownWindow,
1826
- sessions,
1827
- orphans,
1828
- activity: ACTIVITY.slice(-30).reverse().map((a) => ({
1829
- ...a, title: a.tabId != null && tabInfo.has(a.tabId) ? tabInfo.get(a.tabId).title : '',
1830
- })),
1831
- }
1832
- }
1833
-
1834
- async function releaseTab(tabId) {
1835
- await OPS.detach({ tabId })
1836
- ACTIVITY.push({ at: Date.now(), last: Date.now(), key: 'user', call: null, tool: null, hint: '',
1837
- op: 'userRelease', tabId: Number(tabId), ok: true, ms: 0, ops: 1 })
1838
- if (ACTIVITY.length > ACTIVITY_MAX) ACTIVITY.shift()
1839
- }
1840
-
1841
- async function diagnostics() {
1842
- const st = await buildState()
1843
- const h = st.host
1844
- const lines = [
1845
- `DSH Bridge ${st.version}(${chrome.runtime.id})`,
1846
- `浏览器:${navigator.userAgent}`,
1847
- `宿主:${st.connected ? '已连接' : '没连上'}${h ? `,pid ${h.pid},socket ${h.socketOk ? '在听' : '没在听'}(${h.socket}),已处理 ${h.served} 次请求` : ''}`,
1848
- `暂停:${st.paused ? '是' : '否'};页内光标:${st.showCursor ? '显示' : '关闭'};新页开在:${st.ownWindow ? '单独窗口' : '当前窗口'};受控标签页:${st.attachedCount}`,
1849
- `会话:${st.sessions.map((s) => `${s.key}(${s.ops} 次操作,${s.errors} 次失败,${s.tabs.length} 个标签页)`).join(';') || '无'}`,
1850
- '',
1851
- '最近失败:',
1852
- ...ACTIVITY.filter((a) => !a.ok).slice(-10).map((a) =>
1853
- ` ${new Date(a.at).toTimeString().slice(0, 8)} ${a.tool || a.op} ${a.hint || ''} → ${a.error}`),
1854
- '',
1855
- '扩展日志(最近 30 行):',
1856
- ...LOG.slice(-30).map((l) => ` ${l}`),
1857
- ]
1858
- return lines.join('\n')
1859
- }
1860
-
1861
- // ── 用户开关(弹窗和 DSH 设置页共用)────────────────────────────────────────
1862
-
1863
- async function releaseAllTabs() {
1864
- for (const id of [...attached]) await releaseTab(id)
1865
- }
1866
-
1867
- /** where:谁按的(写进日志)。暂停时顺手全部松手。 */
1868
- async function setPaused(on, where) {
1869
- paused = !!on
1870
- await chrome.storage.local.set({ paused })
1871
- log(`${paused ? '暂停' : '恢复'}了浏览器控制(${where})`)
1872
- if (paused) await releaseAllTabs()
1873
- updateBadge()
1874
- }
1875
-
1876
- async function setShowCursor(on, where) {
1877
- showCursor = !!on
1878
- await chrome.storage.local.set({ showCursor })
1879
- log(`${showCursor ? '打开' : '关掉'}了页内光标(${where})`)
1880
- if (!showCursor) {
1881
- for (const id of [...cursorReady]) {
1882
- cursorReady.delete(id)
1883
- cursorPos.delete(id)
1884
- await hidePageCursor(id)
1885
- await markCursor(id, false)
1886
- }
1887
- }
1888
- }
1889
-
1890
- async function setOwnWindow(on, where) {
1891
- ownWindow = !!on
1892
- await chrome.storage.local.set({ ownWindow })
1893
- log(`新开的页改成开在${ownWindow ? '单独窗口' : '当前窗口'}(${where})`)
1894
- }
1895
-
1896
- chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
1897
- if (!msg || !msg.popup || sender.id !== chrome.runtime.id) return
1898
- const run = async () => {
1899
- switch (msg.popup) {
1900
- case 'state':
1901
- return buildState()
1902
- case 'reconnect':
1903
- if (port) { try { port.disconnect() } catch {} ; port = null; hostInfo = null }
1904
- connect()
1905
- await new Promise((r) => setTimeout(r, 700))
1906
- return buildState()
1907
- case 'release':
1908
- await releaseTab(msg.tabId)
1909
- return buildState()
1910
- case 'releaseAll':
1911
- await releaseAllTabs()
1912
- return buildState()
1913
- case 'focus':
1914
- await OPS.activate({ tabId: msg.tabId })
1915
- return buildState()
1916
- case 'pause':
1917
- // 解除暂停只认真正的工具栏弹窗(sender.tab 为空);弹窗页被当成普通标签页打开时不算
1918
- if (!msg.on && sender.tab) throw new Error('恢复控制只能在 Chrome 工具栏的 DSH Bridge 弹窗里点')
1919
- await setPaused(!!msg.on, '弹窗')
1920
- return buildState()
1921
- case 'cursor':
1922
- await setShowCursor(!!msg.on, '弹窗')
1923
- return buildState()
1924
- case 'window':
1925
- await setOwnWindow(!!msg.on, '弹窗')
1926
- return buildState()
1927
- case 'diagnostics':
1928
- return { text: await diagnostics() }
1929
- default:
1930
- throw new Error(`弹窗发了不认识的请求: ${msg.popup}`)
1931
- }
1932
- }
1933
- run().then(sendResponse, (e) => sendResponse({ error: String((e && e.message) || e) }))
1934
- return true
1935
- })
1936
-
1937
- // ── 保活 / 启动 ─────────────────────────────────────────────────────────────
1938
-
1939
- chrome.alarms.create('dsh-keepalive', { periodInMinutes: 1 })
1940
- chrome.alarms.onAlarm.addListener((a) => {
1941
- if (a.name !== 'dsh-keepalive') return
1942
- detachIdle().catch((e) => log('detachIdle 失败:', String(e && e.message || e))) // 空闲超过 60 秒的标签页断开调试
1943
- if (!port) connect()
1944
- else post({ id: 'ka-' + Date.now(), ok: true, keepalive: true })
1945
- })
1946
-
1947
- chrome.runtime.onStartup.addListener(connect)
1948
- chrome.runtime.onInstalled.addListener(connect)
1949
- // 每次 worker 起来都对一次账:认领还活着的分组、拆掉孤儿组和残留角标
1950
- reconcileGroups()
1951
- chrome.tabs.onRemoved.addListener((tabId) => {
1952
- for (const sess of SESSIONS.values()) sess.tabs.delete(tabId)
1953
- ownTabs.delete(tabId)
1954
- attached.delete(tabId)
1955
- updateBadge()
1956
- lastUsed.delete(tabId)
1957
- groupedTabs.delete(tabId) // 标签页都没了,组也轮不到我们拆
1958
- cursorReady.delete(tabId)
1959
- cursorPos.delete(tabId)
1960
- tabEpoch.delete(tabId)
1961
- dialogs.delete(tabId)
1962
- choosers.delete(tabId)
1963
- chooserSkip.delete(tabId)
1964
- failLoadWaiter(tabId, '标签页在加载中被关掉了')
1965
- if (agentTabs.delete(tabId)) saveAgentWindows()
1966
- })
1967
- chrome.windows.onRemoved.addListener((windowId) => {
1968
- forgetAgentWindow(windowId) // 干活窗口被关了:下次新开页再开一个
1969
- })
1970
- connect()
3
+ boot()