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
@@ -0,0 +1,251 @@
1
+ import { evaluate } from './cdp.js'
2
+ import { getOps } from './ops.js'
3
+ import { formatRedactedRow, isSensitiveField, scanPage } from './frames.js'
4
+ import { getRecentSecrets, isOpaqueOrigin, makeSecretRedactor, originOf, pageAccess } from './page-access.js'
5
+ import { S } from './state.js'
6
+ import { areAllFramesAllowed, hasProtectedSites } from './confirm.js'
7
+ import { RELEASED_MSG } from './cursor.js'
8
+ import { timeLeft } from './util.js'
9
+
10
+ function rowKeys(rows) {
11
+ const seen = new Map()
12
+ return rows.map(row => {
13
+ const key = row.ref != null ? 'ref:' + row.ref : row.key || JSON.stringify([row.framePath, row.crossPath, row.line])
14
+ const n = seen.get(key) || 0
15
+ seen.set(key, n + 1)
16
+ return key + ':' + n
17
+ })
18
+ }
19
+
20
+ function diffRows(previous, next, keysForRows = rowKeys) {
21
+ const oldKeys = keysForRows(previous), keys = keysForRows(next)
22
+ const old = new Map(oldKeys.map((key, i) => [key, previous[i]]))
23
+ const current = new Set(keys)
24
+ const surviving = oldKeys.filter(key => current.has(key))
25
+ let index = 0
26
+ const out = []
27
+ for (const [i, key] of keys.entries()) {
28
+ const row = next[i], prior = old.get(key)
29
+ const moved = prior && surviving[index++] !== key
30
+ if (!prior || moved || row.line !== prior.line) out.push({ ...row, line: (prior ? '[~] ' : '[+] ') + (row.line || '') })
31
+ old.delete(key)
32
+ }
33
+ for (const row of old.values()) out.push({ ...(row.raw && { raw: row.raw }), ref: row.ref, line: '[-] ' + (row.line || '') })
34
+ return out
35
+ }
36
+
37
+ function sliceRows(rows, args, cursor) {
38
+ const limit = Math.min(2000, Math.max(1, Math.trunc(args.limit) || 300))
39
+ const maxChars = Math.min(65536, Math.max(1, Math.trunc(args.maxChars) || 8000))
40
+ const maxLine = args.mode === 'page' ? Math.min(120, maxChars) : maxChars
41
+ const page = []
42
+ let chars = 0
43
+ for (const row of rows.slice(cursor, cursor + limit)) {
44
+ const length = Math.min(maxLine, (row.line || '').length) + Number(page.length > 0)
45
+ if (page.length && chars + length > maxChars) break
46
+ page.push({ ...(row.ref !== undefined && { ref: row.ref }), ...(row.crossPath && { crossPath: row.crossPath }), ...(row.framePath && { framePath: row.framePath }), ...(args.swRedact && row.raw && { raw: row.raw }),
47
+ line: row.line == null ? null : row.line.slice(0, maxLine) })
48
+ chars += length
49
+ }
50
+ const nextCursor = cursor + page.length, more = Math.max(0, rows.length - nextCursor)
51
+ return { page, more, nextCursor }
52
+ }
53
+
54
+ // Serialized once per document. Scans stay local, including the baseline for diffs.
55
+ function installScanner(scan, rowKeys, diffRows, sliceRows, maskField) {
56
+ const cache = new Map()
57
+ window.__dshScan = { version: 3, read(args, cached = false) {
58
+ const { selector, scope = 'all', query = '', mode = 'interactive', diff, autoObserve } = args
59
+ const cursor = Math.max(0, Math.trunc(args.cursor) || 0)
60
+ const key = JSON.stringify([selector || '', scope, query, mode])
61
+ const swKey = Boolean(args.swRedact)
62
+ let state = cache.get(key)
63
+ const switchingToSwRedact = Boolean(swKey && state && !state.swKey)
64
+ if (!state || (!cursor && !cached) || switchingToSwRedact) {
65
+ const next = scan(selector, scope, query, null, { mode, maskField, ...(swKey ? { swRedact: true } : {}) })
66
+ if (next.error) return next
67
+ if (!state || switchingToSwRedact || state.url !== next.url || state.documentId !== next.documentId) {
68
+ state = { snapshotId: crypto.randomUUID?.() || Array.from(crypto.getRandomValues(new Uint32Array(4))).join('-'), revision: 0, rows: [], previous: null }
69
+ }
70
+ const changed = !state.revision || state.swKey !== swKey || state.title !== next.title || state.count !== next.count ||
71
+ state.outside !== next.outside || state.capped !== next.capped || state.rows.length !== next.rows.length ||
72
+ next.rows.some((r, i) => r.line !== state.rows[i].line || r.ref !== state.rows[i].ref || String(r.crossPath) !== String(state.rows[i].crossPath))
73
+ if (changed) {
74
+ state.previous = { revision: state.revision, rows: state.rows }
75
+ Object.assign(state, next, { swKey, revision: state.revision + 1, paths: next.rows.filter(r => r.crossPath).map(r => r.crossPath) })
76
+ }
77
+ cache.delete(key)
78
+ cache.set(key, state)
79
+ if (cache.size > 8) cache.delete(cache.keys().next().value)
80
+ }
81
+ let rows = state.rows, diffMode = 'full'
82
+ if (diff && cursor && state.diffPage) {
83
+ rows = state.diffPage.rows
84
+ diffMode = state.diffPage.mode
85
+ } else if (diff && args.prevSnapshotId === state.snapshotId) {
86
+ if (args.prevRevision === state.revision) { rows = []; diffMode = 'unchanged' }
87
+ else if (args.prevRevision === state.previous?.revision) { rows = diffRows(state.previous.rows, rows, rowKeys); diffMode = 'diff' }
88
+ }
89
+ const { page, more, nextCursor } = sliceRows(rows, args, cursor)
90
+ if (!cursor) state.diffPage = diff && more ? { rows, mode: diffMode } : null
91
+ const { snapshotId, revision, documentId, url, title, count, outside, capped, selfOrigin, rawTitle, rawUrl } = state
92
+ return { snapshotId, revision, documentId, url, title, count, outside, capped, diffMode, selfOrigin,
93
+ ...(swKey && { rawTitle, rawUrl }),
94
+ paths: !autoObserve ? state.paths : undefined, unchanged: diffMode === 'unchanged', lines: page.map(r => r.line).filter(Boolean),
95
+ ...((!autoObserve || swKey) && { rows: page }),
96
+ nextCursor, more, totalRows: rows.length }
97
+ } }
98
+ }
99
+
100
+ export async function snapshotScan({ tabId, timeoutMs = 15000, controlEpoch, ...args }) {
101
+ const id = Number(tabId), deadline = Date.now() + timeoutMs
102
+ const auto = args.autoObserve === true
103
+ const startEpoch = Number.isInteger(controlEpoch) ? controlEpoch : (S.controlEpoch.get(id) || 0)
104
+ const startReleaseAll = S.releaseAllEpoch
105
+ const skip = info => ({ skipped: true, reason: info.reason, url: info.url || '', title: info.title || '' })
106
+ const released = () => S.paused || S.releasing.has(id) || S.releaseAllEpoch !== startReleaseAll || (S.controlEpoch.get(id) || 0) !== startEpoch || (auto && !S.attached.has(id))
107
+ if (auto && released()) return skip({ reason: 'detached' })
108
+ const guard = () => { if (released()) throw new Error(RELEASED_MSG) }
109
+ const access = { autoObserve: auto, expectedOrigin: args.expectedOrigin }
110
+ const page = await pageAccess(id, access)
111
+ if (page.reason) {
112
+ if (auto) return skip(page)
113
+ throw new Error(page.reason === 'protected' ? 'USER_DENIED_SENSITIVE' : page.reason)
114
+ }
115
+ if (auto && released()) return skip({ reason: 'detached' })
116
+ const origin = originOf(page.url)
117
+ const opaque = isOpaqueOrigin(origin)
118
+ const recent = getRecentSecrets(id, origin)
119
+ // Never pass cached secrets into any page world; request untrimmed raw fields and redact in SW.
120
+ const scanArgs = recent.length ? { ...args, swRedact: true } : args
121
+ const check = opaque ? `location.href === ${JSON.stringify(page.url)}` : `location.origin === ${JSON.stringify(origin)}`
122
+ const read = `window.__dshScan.read(${JSON.stringify(scanArgs)})`
123
+ const miss = 'DSH_SCANNER_MISSING'
124
+ let result
125
+ try {
126
+ result = await evaluate(id, `${check} && (window.__dshScan?.version === 3 ? ${read} : '${miss}')`, false, timeLeft(deadline), guard)
127
+ if (result === miss) {
128
+ result = await evaluate(id, `${check} && ((${installScanner})(${scanPage}, ${rowKeys}, ${diffRows}, ${sliceRows}, ${isSensitiveField}), ${read})`, false, timeLeft(deadline), guard)
129
+ }
130
+ if (!auto && (result?.paths?.length || S.frameSnapshots.has(result?.snapshotId)) && getOps().frameSnapshot) {
131
+ result = await withFrames(id, scanArgs, result, check, deadline, guard)
132
+ }
133
+ } catch (error) {
134
+ if (auto && released()) return skip({ reason: 'detached' })
135
+ throw error
136
+ }
137
+ if (result) delete result.paths
138
+ if (auto && released()) return skip({ reason: 'detached' })
139
+ const genBeforeAfter = S.frameGeneration.get(id)
140
+ const after = await pageAccess(id, { ...access, expectedOrigin: origin, ...(opaque ? { expectedUrl: page.url } : {}) })
141
+ if (!after.reason && hasProtectedSites() && genBeforeAfter !== S.frameGeneration.get(id)) {
142
+ if (!await areAllFramesAllowed(id, auto)) {
143
+ after.reason = 'protected'
144
+ after.url = originOf(after.url)
145
+ after.title = ''
146
+ }
147
+ }
148
+ if (after.reason || result === false) {
149
+ if (auto) return skip(after.reason ? after : { ...after, title: '', reason: 'origin_changed' })
150
+ throw new Error(after.reason === 'protected' ? 'USER_DENIED_SENSITIVE' : '页面已变化')
151
+ }
152
+ const selfOrigin = typeof result?.selfOrigin === 'string' ? result.selfOrigin : ''
153
+ const sandboxedOpaque = result && typeof result === 'object' && 'selfOrigin' in result && isOpaqueOrigin(selfOrigin)
154
+ if (sandboxedOpaque) S.recentSecrets.delete(id)
155
+ const postRecent = sandboxedOpaque ? [] : [...new Set([...recent, ...getRecentSecrets(id, origin)])]
156
+ if (result && typeof result === 'object') {
157
+ if (postRecent.length) {
158
+ const redactText = makeSecretRedactor(postRecent, 4)
159
+ const redactMeta = makeSecretRedactor(postRecent, 6)
160
+ const redactUrl = (u) => {
161
+ const s = String(u ?? '')
162
+ try {
163
+ const p = new URL(s)
164
+ if (p.origin && p.origin !== 'null') return p.origin + redactText(p.pathname + p.search + p.hash)
165
+ } catch {}
166
+ if (s.startsWith('/')) return redactText(s)
167
+ return redactMeta(s)
168
+ }
169
+ if (result.rawUrl !== undefined) result.url = (result.rawUrl && result.rawUrl.tooLong) ? origin : redactUrl(result.rawUrl)
170
+ else if (typeof result.url === 'string') result.url = redactUrl(result.url)
171
+ if (result.rawTitle !== undefined) result.title = (result.rawTitle && result.rawTitle.tooLong) ? '••••' : redactMeta(result.rawTitle)
172
+ else if (typeof result.title === 'string') result.title = redactMeta(result.title)
173
+ if (Array.isArray(result.rows)) {
174
+ result.rows = result.rows.map(r => r ? formatRedactedRow(r, redactText, redactUrl, args.mode, true) : r)
175
+ result.lines = result.rows.map(r => r?.line).filter(Boolean)
176
+ } else if (Array.isArray(result.lines)) {
177
+ result.lines = result.lines.map(redactText)
178
+ }
179
+ } else if (Array.isArray(result.rows)) {
180
+ result.rows = result.rows.map(r => {
181
+ if (!r || !r.raw) return r
182
+ const { raw: _raw, ...rest } = r
183
+ return rest
184
+ })
185
+ }
186
+ delete result.rawTitle
187
+ delete result.rawUrl
188
+ delete result.selfOrigin
189
+ if (auto) delete result.rows
190
+ }
191
+ return result
192
+ }
193
+
194
+ // Keep cross-origin content exclusively in the worker. Only the main document's rows
195
+ // are cached in its page world. Unresolved crossPath markers keep the legacy merge contract.
196
+ async function withFrames(id, args, main, check, deadline, guard) {
197
+ const key = main.snapshotId
198
+ let state = S.frameSnapshots.get(key)
199
+ const cursor = Math.max(0, Math.trunc(args.cursor) || 0)
200
+ if (!state || !cursor) {
201
+ let mainRows = state?.mainRows
202
+ if (!mainRows || state.mainRevision !== main.revision) {
203
+ mainRows = []
204
+ let offset = 0
205
+ do {
206
+ const pageArgs = { ...args, diff: false, limit: 2000, maxChars: 65536, cursor: offset }
207
+ const data = await evaluate(id, `${check} && window.__dshScan?.read(${JSON.stringify(pageArgs)}, true)`, false, timeLeft(deadline), guard)
208
+ if (data?.snapshotId !== key || data.revision !== main.revision) throw new Error('快照已变化,请重试')
209
+ mainRows.push(...data.rows)
210
+ offset = data.more ? data.nextCursor : 0
211
+ } while (offset)
212
+ }
213
+ const groups = main.paths.length ? (await getOps().frameSnapshot({ tabId: id, mode: args.mode, scope: args.scope, query: args.query,
214
+ paths: main.paths, timeoutMs: timeLeft(deadline) })).groups : []
215
+ const paths = new Map()
216
+ let count = main.count, outside = main.outside, capped = main.capped
217
+ for (const group of groups) {
218
+ const path = group.path.join('.')
219
+ if (!paths.has(path)) paths.set(path, [])
220
+ paths.get(path).push(...group.rows.map(row => ({ ...row, framePath: group.path })))
221
+ count += group.count
222
+ outside += group.outside
223
+ capped ||= group.capped
224
+ }
225
+ const rows = mainRows.flatMap(row => paths.get(row.crossPath?.join('.')) || [row])
226
+ const changed = !state || state.mainRevision !== main.revision || state.count !== count ||
227
+ state.outside !== outside || state.capped !== capped || state.rows.length !== rows.length ||
228
+ rows.some((r, i) => r.ref !== state.rows[i].ref || r.line !== state.rows[i].line || String(r.framePath) !== String(state.rows[i].framePath))
229
+ if (changed) {
230
+ // A worker restart or eviction creates a new baseline, so an old revision can never match.
231
+ state = { tabId: id, snapshotId: state?.snapshotId || crypto.randomUUID(), rows, mainRows, mainRevision: main.revision, count, outside, capped,
232
+ revision: (state?.revision || 0) + 1, previous: state && { revision: state.revision, rows: state.rows } }
233
+ }
234
+ S.frameSnapshots.delete(key)
235
+ S.frameSnapshots.set(key, state)
236
+ if (S.frameSnapshots.size > 4) S.frameSnapshots.delete(S.frameSnapshots.keys().next().value)
237
+ state.page = state.rows
238
+ state.mode = 'full'
239
+ if (args.diff && args.prevSnapshotId === state.snapshotId) {
240
+ if (args.prevRevision === state.revision) { state.page = []; state.mode = 'unchanged' }
241
+ else if (state.previous && args.prevRevision === state.previous.revision) {
242
+ state.page = diffRows(state.previous.rows, state.rows)
243
+ state.mode = 'diff'
244
+ }
245
+ }
246
+ }
247
+ const { page, nextCursor, more } = sliceRows(state.page, args, cursor)
248
+ return { ...main, rows: page, lines: page.map(r => r.line).filter(Boolean), count: state.count,
249
+ outside: state.outside, capped: state.capped, snapshotId: state.snapshotId, revision: state.revision, diffMode: state.mode,
250
+ unchanged: state.mode === 'unchanged', more, nextCursor, totalRows: state.page.length }
251
+ }
@@ -12,11 +12,11 @@ const NET_MAX = 400
12
12
 
13
13
  const MAX_INBOX_BYTES = 64 * 1024 * 1024
14
14
 
15
- const TAKEOVER_OPS = new Set(['click', 'clickEl', 'clickText', 'type', 'key', 'select', 'hover', 'scroll', 'clickAndDownload'])
16
- const HANDOFF_LOCKED = new Set([...TAKEOVER_OPS, 'upload', 'focus', 'nav', 'eval', 'cdp', 'dialog'])
15
+ const TAKEOVER_OPS = new Set(['click', 'clickEl', 'clickText', 'type', 'key', 'select', 'hover', 'scroll', 'clickAndDownload', 'act', 'dragGesture'])
16
+ const HANDOFF_LOCKED = new Set([...TAKEOVER_OPS, 'upload', 'focus', 'nav', 'historyNav', 'eval', 'cdp', 'dialog'])
17
17
 
18
- const QUEUED = new Set([...TAKEOVER_OPS, 'focus', 'upload', 'nav', 'cursor'])
19
- const OPEN_TRACKED = new Set(['click', 'clickEl', 'clickText', 'key', 'nav'])
18
+ const QUEUED = new Set([...TAKEOVER_OPS, 'focus', 'upload', 'nav', 'historyNav', 'cursor'])
19
+ const OPEN_TRACKED = new Set(['click', 'clickEl', 'clickText', 'key', 'nav', 'act'])
20
20
 
21
21
  const PAUSE_ALLOWED = new Set(['version', 'reload', 'ping', 'logs', 'diagnostics', 'detach', 'panel'])
22
22
  const PAUSED_MSG = '用户在 DSH Bridge 弹窗里暂停了浏览器控制——请用户点开扩展图标、打开「允许 DSH 控制」后再试'
@@ -30,7 +30,7 @@ const QUIET_CDP = new Set(['Emulation.setFocusEmulationEnabled', 'Page.getNaviga
30
30
 
31
31
  const ACTIVITY_MAX = 80
32
32
 
33
- const DETACH_IDLE_MS = 60_000
33
+ const DETACH_IDLE_MS = 300_000
34
34
 
35
35
  function freshState() {
36
36
  return {
@@ -73,12 +73,26 @@ function freshState() {
73
73
  inboxSweep: undefined,
74
74
 
75
75
  agentInputUntil: new Map(),
76
+ agentInputKindUntil: new Map(),
77
+ agentInputEvents: new Map(),
78
+ pageAgentUntil: new Map(),
79
+ postReleaseAt: new Map(),
80
+ controlEpoch: new Map(),
81
+ releaseAllEpoch: 0,
82
+ releasing: new Set(),
83
+ attachSeq: new Map(),
76
84
  userTakeover: new Map(),
77
85
 
78
86
  tabQueues: new Map(),
79
87
  tabSessions: new Map(),
80
88
  /** 最近观测到的标签页主帧网址(供事件采集、Mock 与录屏同步核验来源) */
81
89
  tabUrl: new Map(),
90
+ frameGeneration: new Map(),
91
+ mainNavGeneration: new Map(),
92
+ mainDocuments: new Map(),
93
+ frameSnapshots: new Map(),
94
+ /** tabId → { origin, expiresAt, values: Set<string> }:短期保留最近敏感输入以覆盖提交后的自动快照 */
95
+ recentSecrets: new Map(),
82
96
 
83
97
  /** 宿主自报的状态(pid、socket 是否在听、最近一次被调用) */
84
98
  hostInfo: null,
@@ -89,6 +103,9 @@ function freshState() {
89
103
 
90
104
  /** 用户在弹窗里关了「页面里显示光标」:真实点击照做,只是不画那只蓝色光标 */
91
105
  showCursor: true,
106
+ cursorPace: 'fast',
107
+ lastCursorPace: 'fast',
108
+ cursorPrefsWrite: Promise.resolve(),
92
109
  /** 用户关了「在单独窗口里干活」:新开的页回到用户当前窗口(后台标签页,不抢焦点) */
93
110
  ownWindow: true,
94
111
 
@@ -126,8 +143,10 @@ function freshState() {
126
143
  /** 页内光标:注入过一次就记住,导航后失效要重注;位置按标签页记着,换了页面从原处接着出现 */
127
144
  cursorReady: new Set(),
128
145
  cursorPos: new Map(),
146
+ cursorInjectSeq: new Map(),
129
147
 
130
148
  activeDownload: null,
149
+ protectedListEpoch: 0,
131
150
 
132
151
  recentTabs: new Map(),
133
152
  prefsReady: null,
@@ -104,7 +104,7 @@ async function ensureGroup(tabId, sessionKey = 'cli') {
104
104
  const color = S.sessionColors.get(sessionKey)
105
105
  const id = Number(tabId)
106
106
  if (S.groupedTabs.has(id)) return
107
- const tab = await chrome.tabs.get(id).catch(() => null)
107
+ const tab = typeof chrome.tabs?.get === 'function' ? await chrome.tabs.get(id).catch(() => null) : null
108
108
  if (!tab || tab.pinned) return
109
109
  const wid = tab.windowId
110
110
  const previous = S.groupQueues.get(wid) || Promise.resolve()
@@ -116,7 +116,7 @@ async function ensureGroup(tabId, sessionKey = 'cli') {
116
116
  }
117
117
 
118
118
  async function groupInWindow(id, wid, sessionKey, color) {
119
- const tab = await chrome.tabs.get(id).catch(() => null)
119
+ const tab = typeof chrome.tabs?.get === 'function' ? await chrome.tabs.get(id).catch(() => null) : null
120
120
  if (!tab || tab.pinned || tab.windowId !== wid) return
121
121
  const key = wid + '/' + sessionKey
122
122
  if (tab.groupId >= 0) {
@@ -164,6 +164,7 @@ async function unmarkTab(tabId) {
164
164
  updateBadge()
165
165
  S.cursorReady.delete(id) // 必修:不清的话,松手后小鼠标灭了就再也不亮(页面里的光标其实还在)
166
166
  S.cursorPos.delete(id) // 松手后再接手,光标从新目标处冒出来,不从老地方飞
167
+ S.pageAgentUntil.delete(id)
167
168
  await hidePageCursor(id) // 尽力把页内光标收掉(松手不留痕)
168
169
  await markCursor(id, false)
169
170
  if ((S.tabEpoch.get(id) || 0) !== epoch) return // 期间又被 mark 了,别拆
@@ -192,6 +193,13 @@ async function reconcileGroups() {
192
193
  catch { attachedIds.delete(id); continue }
193
194
  rememberAttached(id)
194
195
  S.lastUsed.set(id, Date.now())
196
+ await chrome.debugger.sendCommand?.({ tabId: id }, 'Page.getFrameTree', {}).then((res) => {
197
+ const f = res?.frameTree?.frame
198
+ if (f?.id) {
199
+ S.mainDocuments.set(id, { id: f.id, loaderId: f.loaderId })
200
+ if (typeof f.url === 'string' && f.url) S.tabUrl.set(id, f.url)
201
+ }
202
+ }).catch(() => {})
195
203
  await installInputListener(id)
196
204
  }
197
205
  updateBadge()
@@ -1,4 +1,4 @@
1
- // 页内光标浮层(v5)—— 让用户一眼看出 DSH 在页面里干什么,人一伸手它就让路
1
+ // 页内光标浮层(v6)—— 让用户一眼看出 DSH 在页面里干什么,人一伸手它就让路
2
2
  //
3
3
  // 不是系统光标,是注进页面的一层 DOM。扩展用 Runtime.evaluate 或
4
4
  // chrome.scripting.executeScript({ files: ['in-page-cursor.js'], world: 'MAIN' }) 注入一次,之后调:
@@ -40,7 +40,7 @@
40
40
  // * 系统开了「减少动态效果」就不做动画
41
41
 
42
42
  (() => {
43
- const VERSION = 5;
43
+ const VERSION = 6;
44
44
  const TAG = 'dsh-cursor';
45
45
  const BAR_TAG = 'dsh-handoff';
46
46
  const prev = window.__dshCursor;
@@ -190,9 +190,13 @@
190
190
  let x = keep ? keep.x : null;
191
191
  let y = keep ? keep.y : null;
192
192
  let shown = false;
193
+ let hiding = false;
193
194
  let idleTimer = 0;
194
195
  let dormantTimer = 0;
195
196
  let labelTimer = 0;
197
+ let hideTimer = 0;
198
+ let hideAnim = null;
199
+ let nearTimer = 0;
196
200
  let glide = null;
197
201
  let agentUntil = carry && carry.agentUntil > Date.now() ? carry.agentUntil : 0;
198
202
  let taken = carry && carry.taken ? carry.taken : null; // { at, type }:人最近一次接手
@@ -235,10 +239,23 @@
235
239
  tag.classList.toggle('fy', py > vh() - 56);
236
240
  wheel.classList.toggle('low', py < 34);
237
241
  };
238
- /** 人的鼠标凑到 72px 以内:几乎透明,别挡人看字 */
242
+ /** 人的鼠标凑到 72px 以内:几乎透明,别挡人看字;4 秒过期后自动恢复 */
239
243
  const near = () => {
240
- const on = !!lastUser && x !== null && Date.now() - lastUser.at < 4000 && Math.hypot(lastUser.x - x, lastUser.y - y) < 72;
244
+ clearTimeout(nearTimer);
245
+ nearTimer = 0;
246
+ const left = lastUser ? 4000 - (Date.now() - lastUser.at) : 0;
247
+ const on = left > 0 && x !== null && Math.hypot(lastUser.x - x, lastUser.y - y) < 72;
241
248
  cur.classList.toggle('near', on);
249
+ if (on) nearTimer = setTimeout(() => { nearTimer = 0; cur.classList.remove('near'); }, left + 20);
250
+ };
251
+ const cancelHide = () => {
252
+ hiding = false;
253
+ clearTimeout(hideTimer);
254
+ hideTimer = 0;
255
+ if (hideAnim) {
256
+ try { hideAnim.cancel(); } catch {}
257
+ hideAnim = null;
258
+ }
242
259
  };
243
260
  const wake = () => {
244
261
  cur.classList.remove('idle', 'dormant', 'yield');
@@ -268,6 +285,7 @@
268
285
  };
269
286
 
270
287
  const place = (px, py) => {
288
+ cancelHide();
271
289
  raise();
272
290
  if (glide) { glide.cancel(); glide = null; }
273
291
  x = Math.round(px); y = Math.round(py);
@@ -292,6 +310,7 @@
292
310
 
293
311
  const move = (px, py, opts = {}) => {
294
312
  px = Math.round(px); py = Math.round(py);
313
+ cancelHide();
295
314
  raise();
296
315
  wake();
297
316
  if (x === null) { place(px, py); return 0; }
@@ -304,8 +323,8 @@
304
323
  appear();
305
324
  const dx = px - from.x, dy = py - from.y;
306
325
  const dist = Math.hypot(dx, dy);
307
- if (dist < 2 || reduce()) return 0;
308
- const duration = Math.round(opts.duration != null ? opts.duration : Math.min(620, 240 + dist * 0.42));
326
+ if (dist < 2 || opts.duration === 0 || reduce()) return 0;
327
+ const duration = Math.round(opts.duration != null ? opts.duration : Math.min(260, 110 + dist * 0.18));
309
328
  if (opts.straight) { // 拖拽:匀速直线,跟真实的拖动步子对齐
310
329
  glide = cur.animate([{ transform: at(from.x, from.y) }, { transform: at(px, py) }], { duration, easing: 'linear' });
311
330
  return duration;
@@ -350,6 +369,7 @@
350
369
  };
351
370
 
352
371
  const press = () => {
372
+ if (hiding || !shown) return;
353
373
  wake();
354
374
  if (reduce()) return;
355
375
  arrow.animate([
@@ -375,16 +395,18 @@
375
395
  };
376
396
 
377
397
  const click = (px, py, count = 1) => {
398
+ if (hiding || !shown) return;
378
399
  if (px == null) { px = x; py = y; }
379
400
  press();
380
401
  const n = Math.max(1, Math.min(3, Number(count) || 1));
381
402
  for (let i = 0; i < n; i++) ripple(Math.round(px), Math.round(py), i * 130);
382
403
  };
383
404
 
384
- const down = () => { wake(); cur.classList.add('down'); if (!reduce()) arrow.animate([{ transform: 'scale(1)' }, { transform: 'scale(.88)' }], { duration: 120, fill: 'forwards' }); };
385
- const up = () => { wake(); cur.classList.remove('down'); arrow.getAnimations().forEach((a) => a.cancel()); };
405
+ const down = () => { if (hiding || !shown) return; wake(); cur.classList.add('down'); if (!reduce()) arrow.animate([{ transform: 'scale(1)' }, { transform: 'scale(.88)' }], { duration: 120, fill: 'forwards' }); };
406
+ const up = () => { if (hiding || !shown) return; wake(); cur.classList.remove('down'); arrow.getAnimations().forEach((a) => a.cancel()); };
386
407
 
387
408
  const label = (text, ms = 2600) => {
409
+ if (hiding) return;
388
410
  wake();
389
411
  what.textContent = text == null ? '' : String(text);
390
412
  tag.classList.toggle('open', !!what.textContent);
@@ -394,6 +416,7 @@
394
416
  };
395
417
 
396
418
  const scroll = (dy = 1) => {
419
+ if (hiding || !shown) return;
397
420
  wake();
398
421
  wheelPath.setAttribute('d', dy < 0 ? 'M3 7.5 6 4.5 9 7.5' : 'M3 4.5 6 7.5 9 4.5');
399
422
  if (reduce()) return;
@@ -410,9 +433,22 @@
410
433
  clearTimeout(idleTimer);
411
434
  clearTimeout(dormantTimer);
412
435
  clearTimeout(labelTimer);
413
- if (reduce() || !shown) { host.remove(); return; }
414
- cur.animate([{ opacity: getComputedStyle(cur).opacity }, { opacity: 0 }], { duration: 180, fill: 'forwards' });
415
- setTimeout(() => host.remove(), 200);
436
+ clearTimeout(nearTimer);
437
+ nearTimer = 0;
438
+ cancelHide();
439
+ hiding = true;
440
+ const wasShown = shown;
441
+ shown = false;
442
+ if (reduce() || !wasShown || !host.isConnected) { host.remove(); return; }
443
+ hideAnim = cur.animate([{ opacity: getComputedStyle(cur).opacity }, { opacity: 0 }], { duration: 180, fill: 'forwards' });
444
+ hideTimer = setTimeout(() => {
445
+ hideTimer = 0;
446
+ if (hideAnim) {
447
+ try { hideAnim.cancel(); } catch {}
448
+ hideAnim = null;
449
+ }
450
+ host.remove();
451
+ }, 200);
416
452
  };
417
453
 
418
454
  const pos = () => (x === null ? null : { x, y });
@@ -583,6 +619,8 @@
583
619
  clearTimeout(idleTimer);
584
620
  clearTimeout(dormantTimer);
585
621
  clearTimeout(labelTimer);
622
+ clearTimeout(nearTimer);
623
+ cancelHide();
586
624
  removeBar(false);
587
625
  host.remove();
588
626
  };
@@ -12,16 +12,17 @@ whenToUse: 任务要在"用户已经登录的那个浏览器"里做事情,或
12
12
 
13
13
  ## 首选:`browser_*` 原生工具
14
14
 
15
- 装了 Chrome Bridge 插件就有这 15 个工具,比走 shell 快、也不用引号转义:
15
+ 装了 Chrome Bridge 插件就有这 16 个工具,比走 shell 快、也不用引号转义:
16
16
 
17
17
  | 工具 | 用途 |
18
18
  |---|---|
19
- | `browser_tabs` | 列 / 找 / 开 / 关 / 切标签页(**先拿 tabId**);`action=profiles` 列出所有已连接的浏览器 / Profile,`profile` 指定目标 |
20
- | `browser_read` | **`what=snapshot` 给能点/能填的元素编号 [N]**(要操作页面先调它;同源 iframe 里的元素也在里面,夹在 `[iframe] … ↓` 和 `[/iframe]` 之间;跨站 iframe 由扩展在隔离世界扫描,元素编号是高位号(≥ 10001,和主文档不冲突),照样用 `ref` 操作);`scope=viewport` 只看当前屏、`diff=true` 只回和上次快照的差异、`query` 过滤;一页 300 项,没列完用 `limit` / `cursor` 翻页;`text` 读可见文字;`markdown` 转 Markdown;`table` 抽表格;`html` / `attr` / `info`(info 会告诉你有没有弹窗挡着) |
21
- | `browser_click` | 按 `ref`(编号,最稳)/ `selector` / `text` / 坐标点(真实鼠标事件);`button` 选 `left` / `right` / `middle`,`count: 2` 双击;跨站 iframe 里也能点;结果会附带**遮挡告警**和 `window.open` 新开页的 `tabId` |
22
- | `browser_input` | `type` / `fill`(清空后填)/ `check`(勾选或取消)/ `key` / `select` / `upload` / `focus` / `hover` / `scroll`(支持按 `ref`/`selector` 滚指定容器;跨站 iframe 内的输入、选择、悬停、滚动也能用,传文件不行) |
23
- | `browser_fill` | **一次填一整张表**:`fields` 是 `[{ ref, value }]`(复选框写 **`{ ref, action: "check", checked }`**、下拉 `{ ref, action: "select", value }`),最多 30 项;给 `submitRef` 就填完顺手点提交 |
24
- | `browser_nav` | `go` 跳转 / `back` 后退 / `forward` 前进 / `reload` 刷新,都等加载完 |
19
+ | `browser_tabs` | 列 / 找 / 开 / 关 / 切标签页(**先拿 tabId**;`open` 默认 `wait="dom"` 并自动带 `observe="diff"`);`action=profiles` 列出所有已连接的浏览器 / Profile,`profile` 指定目标 |
20
+ | `browser_read` | **`what=snapshot` 给能点/能填的元素编号 [N]**(同源和跨站 iframe 均支持,跨站编号 ≥ 10001);新增 `mode="page"` 混排标题正文与交互元素,支持 `scope=viewport`、页内 `diff=true`、`query` 过滤与 `limit`/`cursor` 翻页;还有 `text` / `markdown` / `table` / `html` / `attr` / `info` |
21
+ | `browser_click` | 单跳极速点击:按 `ref`(最稳)/ `selector` / `text` / 坐标点;支持 `button`、`count`、`expect` 动作后条件等待与默认 `observe="diff"` 自动回看变化;报告遮挡告警和 `window.open` 新开页 |
22
+ | `browser_input` | `type`(支持 `clear` / `submit`) / `fill` / `check` / `key` / `select` / `upload` / `focus` / `hover` / 极速 `scroll`,默认 `observe="diff"`;跨站 iframe 内除上传外全支持 |
23
+ | `browser_fill` | **一次填一整张表**:`fields` 是 `[{ ref, value }]`(复选框 `{ ref, action: "check", checked }`、下拉 `action: "select"`),最多 30 项;支持 `submitRef`、`expect` 与默认 `observe="diff"` |
24
+ | `browser_nav` | `go` 跳转 / `back` 后退 / `forward` 前进 / `reload` 刷新,默认 `wait="dom"`(可选 `load`/`idle`/`none`)、支持 `expect` 与默认 `observe="diff"` |
25
+ | `browser_batch` | **一次调用连贯执行 1–12 步安全操作**(仅限 `click`/`type`/`key`/`select`/`check`/`fill`/`hover`/`scroll`/`wait`/`nav`),仅在批次末尾观察一次页面,大幅省思考回合;遇跳转(含同 URL 刷新)、弹窗、受保护网站、报错或人工接管立刻停步 |
25
26
  | `browser_screenshot` | 截图,**图片直接返回给你看**(`viewport` / `full` / `element`,默认 JPEG)。**`marks: true`** 给可点元素画编号(Set-of-Mark)并附图例,适合元素多、编号难对上的页面;**`maxWidth`** 默认 1280、等比缩小省 token,`0` 关闭 |
26
27
  | `browser_eval` | 页面里跑 JS(不带 user gesture) |
27
28
  | `browser_wait` | 等 `selector` 元素 / `text` 文字 / `url` 网址 / `responseUrl` 某个请求出现;`network: "idle"` 等网络空闲、`newTab: true` 等新开标签页、`gone=true` 等它消失(加载圈) |