dsh-chrome-bridge 1.20.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.
- package/README.en.md +6 -2
- package/README.md +6 -2
- package/client.js +110 -29
- package/core/ext.js +119 -0
- package/core/hosts.js +277 -0
- package/core/locale.js +8 -0
- package/core/receipt.js +56 -0
- package/core/session.js +157 -0
- package/core/shots.js +56 -0
- package/core/tooldef.js +142 -0
- package/core/transport.js +212 -0
- package/core/upload.js +59 -0
- package/devtools.js +18 -8
- package/download.js +879 -60
- package/drag.js +38 -20
- package/features/frames.js +58 -0
- package/features/gif.js +203 -0
- package/features/index.js +1 -0
- package/features/mock-har.js +85 -0
- package/features/record.js +225 -0
- package/i18n/en.js +168 -16
- package/i18n/ru.js +168 -16
- package/i18n/zh.js +168 -16
- package/image-guard.js +13 -6
- package/index.js +17 -1155
- package/locale/ru.json +7 -0
- package/nav.js +43 -5
- package/package.json +8 -1
- package/panel.js +10 -1
- package/refs.js +275 -230
- package/setup.js +214 -46
- package/tools/click.js +58 -0
- package/tools/devtools.js +61 -0
- package/tools/dialog.js +22 -0
- package/tools/download.js +50 -0
- package/tools/drag.js +61 -0
- package/tools/eval.js +22 -0
- package/tools/fill.js +77 -0
- package/tools/handoff.js +40 -0
- package/tools/index.js +38 -0
- package/tools/input.js +147 -0
- package/tools/nav.js +57 -0
- package/tools/read.js +87 -0
- package/tools/record.js +120 -0
- package/tools/screenshot.js +223 -0
- package/tools/tabs.js +131 -0
- package/tools/wait.js +56 -0
- package/vendor/cb +616 -35
- package/vendor/extension/_locales/en/messages.json +3 -0
- package/vendor/extension/_locales/ru/messages.json +3 -0
- package/vendor/extension/_locales/zh_CN/messages.json +3 -0
- package/vendor/extension/_locales/zh_TW/messages.json +3 -0
- package/vendor/extension/background.js +2 -1969
- package/vendor/extension/confirm.css +148 -0
- package/vendor/extension/confirm.html +49 -0
- package/vendor/extension/confirm.js +188 -0
- package/vendor/extension/in-page-cursor.js +599 -0
- package/vendor/extension/manifest.json +11 -2
- package/vendor/extension/popup.css +99 -5
- package/vendor/extension/popup.html +28 -2
- package/vendor/extension/popup.js +430 -45
- package/vendor/extension/sw/boot.js +111 -0
- package/vendor/extension/sw/cdp.js +411 -0
- package/vendor/extension/sw/chooser.js +192 -0
- package/vendor/extension/sw/confirm.js +608 -0
- package/vendor/extension/sw/cursor.js +241 -0
- package/vendor/extension/sw/dispatch.js +129 -0
- package/vendor/extension/sw/download.js +279 -0
- package/vendor/extension/sw/fetch-hub.js +224 -0
- package/vendor/extension/sw/frames.js +651 -0
- package/vendor/extension/sw/imaging.js +361 -0
- package/vendor/extension/sw/native.js +111 -0
- package/vendor/extension/sw/net-tools.js +525 -0
- package/vendor/extension/sw/ops.js +829 -0
- package/vendor/extension/sw/popup-api.js +303 -0
- package/vendor/extension/sw/profile.js +166 -0
- package/vendor/extension/sw/record.js +494 -0
- package/vendor/extension/sw/state.js +161 -0
- package/vendor/extension/sw/tabui.js +219 -0
- package/vendor/extension/sw/util.js +166 -0
- package/vendor/extension/sw/welcome.js +26 -0
- package/vendor/extension/sw/windows.js +94 -0
- package/vendor/extension/welcome.css +189 -0
- package/vendor/extension/welcome.html +70 -0
- package/vendor/extension/welcome.js +157 -0
- package/vendor/host/host.js +476 -71
- package/vendor/in-page-cursor.js +309 -37
- package/vendor/skill/SKILL.md +34 -16
package/core/hosts.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { listHostEntries, STALE_MS, STORE_EXT_IDS } from '../setup.js'
|
|
5
|
+
export { STALE_MS }
|
|
6
|
+
import { t } from './locale.js'
|
|
7
|
+
|
|
8
|
+
const WIN = process.platform === 'win32'
|
|
9
|
+
const UID = typeof process.getuid === 'function' ? process.getuid() : null
|
|
10
|
+
|
|
11
|
+
export function bridgeDir() {
|
|
12
|
+
return process.env.DSH_BRIDGE_DIR || (WIN ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${UID ?? 'user'}`)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function tokenLines(tokenFile) {
|
|
16
|
+
try { return fs.readFileSync(tokenFile, 'utf8').split('\n').map((l) => l.trim()) } catch { return [] }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 比较点分版本号(如 2.0.0 > 1.16.0);无法解析的版本排在合法版本之后 */
|
|
20
|
+
export function compareVersion(a, b) {
|
|
21
|
+
const parse = (v) => (/^\d+(?:\.\d+)*$/.test(String(v || '').trim())
|
|
22
|
+
? String(v).trim().split('.').map(Number)
|
|
23
|
+
: null)
|
|
24
|
+
const pa = parse(a)
|
|
25
|
+
const pb = parse(b)
|
|
26
|
+
if (!pa && !pb) return 0
|
|
27
|
+
if (!pa) return -1
|
|
28
|
+
if (!pb) return 1
|
|
29
|
+
const len = Math.max(pa.length, pb.length)
|
|
30
|
+
for (let i = 0; i < len; i++) {
|
|
31
|
+
const diff = (pa[i] || 0) - (pb[i] || 0)
|
|
32
|
+
if (diff !== 0) return diff
|
|
33
|
+
}
|
|
34
|
+
return 0
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function extInstallKind(extId) {
|
|
38
|
+
if (!extId) return 'unknown'
|
|
39
|
+
return STORE_EXT_IDS.includes(extId) ? 'store' : 'unpacked'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function preferHigherVersion(a, b) {
|
|
43
|
+
return compareVersion(a.extVersion, b.extVersion)
|
|
44
|
+
|| (Number(a.extConnected !== false) - Number(b.extConnected !== false))
|
|
45
|
+
|| ((Number(a.focusedAt) || 0) - (Number(b.focusedAt) || 0))
|
|
46
|
+
|| ((Number(a.lastSeenAt) || 0) - (Number(b.lastSeenAt) || 0))
|
|
47
|
+
|| ((Number(a.startedAt) || 0) - (Number(b.startedAt) || 0))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isDuplicatePair(a, b) {
|
|
51
|
+
if (a.id && b.id && a.id === b.id) return 'sameInstanceId'
|
|
52
|
+
if (a.pid && b.pid && a.pid === b.pid && a.socket && b.socket && a.socket === b.socket) return 'samePid'
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isPossibleDuplicatePair(a, b) {
|
|
57
|
+
if (a.id && b.id && a.id === b.id) return false
|
|
58
|
+
const ba = String(a.browser || '').trim().toLowerCase()
|
|
59
|
+
const bb = String(b.browser || '').trim().toLowerCase()
|
|
60
|
+
if (!ba || ba !== bb) return false
|
|
61
|
+
const ka = extInstallKind(a.extId)
|
|
62
|
+
const kb = extInstallKind(b.extId)
|
|
63
|
+
return ka !== 'unknown' && kb !== 'unknown' && ka !== kb
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function sortHosts(list) {
|
|
67
|
+
return [...list].sort((a, b) =>
|
|
68
|
+
(Number(b.extConnected !== false) - Number(a.extConnected !== false))
|
|
69
|
+
|| (Number(!b.possibleDuplicate) - Number(!a.possibleDuplicate))
|
|
70
|
+
|| ((Number(b.focusedAt) || 0) - (Number(a.focusedAt) || 0))
|
|
71
|
+
|| ((Number(b.lastSeenAt) || 0) - (Number(a.lastSeenAt) || 0))
|
|
72
|
+
|| ((Number(a.startedAt) || 0) - (Number(b.startedAt) || 0)))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 扫描存活宿主:仅对相同 instanceId(或相同 pid+socket)合并去重;
|
|
77
|
+
* 同浏览器下不同 instanceId 的商店版与解压版全部保留,仅给较低版本标 possibleDuplicate。
|
|
78
|
+
*/
|
|
79
|
+
export function scanHosts({ dir } = {}) {
|
|
80
|
+
const targetDir = dir || bridgeDir()
|
|
81
|
+
const raw = listHostEntries(targetDir)
|
|
82
|
+
const kept = []
|
|
83
|
+
const duplicates = []
|
|
84
|
+
|
|
85
|
+
for (const item of raw) {
|
|
86
|
+
const normalized = {
|
|
87
|
+
id: String(item.id || `pid-${item.pid}`),
|
|
88
|
+
pid: item.pid,
|
|
89
|
+
socket: item.socket,
|
|
90
|
+
token: item.token,
|
|
91
|
+
extId: String(item.extId || ''),
|
|
92
|
+
extVersion: String(item.extVersion || ''),
|
|
93
|
+
browser: String(item.browser || ''),
|
|
94
|
+
label: String(item.label || ''),
|
|
95
|
+
hostHash: String(item.hostHash || ''),
|
|
96
|
+
startedAt: Number(item.startedAt) || 0,
|
|
97
|
+
lastSeenAt: Number(item.lastSeenAt) || 0,
|
|
98
|
+
focusedAt: Number(item.focusedAt) || 0,
|
|
99
|
+
extConnected: item.extConnected !== false,
|
|
100
|
+
isPrimary: Boolean(item.isPrimary),
|
|
101
|
+
installKind: extInstallKind(item.extId),
|
|
102
|
+
registryFile: item.registryFile,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
let dupIdx = -1
|
|
106
|
+
let dupReason = null
|
|
107
|
+
for (let i = 0; i < kept.length; i++) {
|
|
108
|
+
const reason = isDuplicatePair(kept[i], normalized)
|
|
109
|
+
if (reason) { dupIdx = i; dupReason = reason; break }
|
|
110
|
+
}
|
|
111
|
+
if (dupIdx < 0) {
|
|
112
|
+
kept.push(normalized)
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const existing = kept[dupIdx]
|
|
117
|
+
const winner = preferHigherVersion(normalized, existing) > 0 ? normalized : existing
|
|
118
|
+
const loser = winner === normalized ? existing : normalized
|
|
119
|
+
const info = {
|
|
120
|
+
reason: dupReason,
|
|
121
|
+
keptId: winner.id,
|
|
122
|
+
keptVersion: winner.extVersion,
|
|
123
|
+
keptKind: winner.installKind,
|
|
124
|
+
droppedId: loser.id,
|
|
125
|
+
droppedPid: loser.pid,
|
|
126
|
+
droppedExtId: loser.extId,
|
|
127
|
+
droppedVersion: loser.extVersion,
|
|
128
|
+
droppedKind: loser.installKind,
|
|
129
|
+
browser: winner.browser || loser.browser || '',
|
|
130
|
+
}
|
|
131
|
+
duplicates.push(info)
|
|
132
|
+
kept[dupIdx] = { ...winner, duplicate: info }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const possibleDuplicates = []
|
|
136
|
+
for (let i = 0; i < kept.length; i++) {
|
|
137
|
+
for (let j = i + 1; j < kept.length; j++) {
|
|
138
|
+
if (!isPossibleDuplicatePair(kept[i], kept[j])) continue
|
|
139
|
+
const higher = preferHigherVersion(kept[j], kept[i]) > 0 ? kept[j] : kept[i]
|
|
140
|
+
const lower = higher === kept[j] ? kept[i] : kept[j]
|
|
141
|
+
lower.possibleDuplicate = true
|
|
142
|
+
possibleDuplicates.push({
|
|
143
|
+
reason: 'unpackedAndStore',
|
|
144
|
+
higherId: higher.id,
|
|
145
|
+
higherVersion: higher.extVersion,
|
|
146
|
+
higherKind: higher.installKind,
|
|
147
|
+
lowerId: lower.id,
|
|
148
|
+
lowerVersion: lower.extVersion,
|
|
149
|
+
lowerKind: lower.installKind,
|
|
150
|
+
browser: higher.browser || lower.browser || '',
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const sorted = sortHosts(kept)
|
|
156
|
+
let topFocused = null
|
|
157
|
+
for (const h of sorted) {
|
|
158
|
+
if (h.focusedAt > 0 && (!topFocused || h.focusedAt > topFocused.focusedAt)) topFocused = h
|
|
159
|
+
}
|
|
160
|
+
const hosts = sorted.map((h, i) => ({
|
|
161
|
+
...h,
|
|
162
|
+
focused: h === topFocused,
|
|
163
|
+
default: i === 0,
|
|
164
|
+
}))
|
|
165
|
+
return { hosts, duplicates, possibleDuplicates, dir: targetDir }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function listProfiles(options = {}) {
|
|
169
|
+
return scanHosts(options).hosts
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function isMultiHost({ dir } = {}) {
|
|
173
|
+
const useEnv = !dir || path.resolve(dir) === path.resolve(bridgeDir())
|
|
174
|
+
if (useEnv && process.env.DSH_BRIDGE_SOCK) return false
|
|
175
|
+
return scanHosts({ dir }).hosts.length > 1
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function matchHost(hosts, query) {
|
|
179
|
+
const q = String(query || '').trim().toLowerCase()
|
|
180
|
+
if (!q) return null
|
|
181
|
+
const fields = (h) => [
|
|
182
|
+
String(h.id || '').toLowerCase(),
|
|
183
|
+
String(h.label || '').toLowerCase(),
|
|
184
|
+
String(h.browser || '').toLowerCase(),
|
|
185
|
+
String(h.pid || ''),
|
|
186
|
+
]
|
|
187
|
+
// 第一轮:按 id / label / browser / pid 精确匹配
|
|
188
|
+
for (let idx = 0; idx < 4; idx++) {
|
|
189
|
+
const hit = hosts.find((h) => {
|
|
190
|
+
const val = fields(h)[idx]
|
|
191
|
+
return val && val === q
|
|
192
|
+
})
|
|
193
|
+
if (hit) return hit
|
|
194
|
+
}
|
|
195
|
+
// 第二轮:按 id / label / browser 前缀匹配
|
|
196
|
+
for (let idx = 0; idx < 3; idx++) {
|
|
197
|
+
const hit = hosts.find((h) => {
|
|
198
|
+
const val = fields(h)[idx]
|
|
199
|
+
return val && val.startsWith(q)
|
|
200
|
+
})
|
|
201
|
+
if (hit) return hit
|
|
202
|
+
}
|
|
203
|
+
return null
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function legacyEndpoint(dir) {
|
|
207
|
+
const d = dir || bridgeDir()
|
|
208
|
+
const useEnv = !dir || path.resolve(dir) === path.resolve(bridgeDir())
|
|
209
|
+
const tokenFile = (useEnv && process.env.DSH_BRIDGE_TOKEN) || path.join(d, 'dsh-bridge.token')
|
|
210
|
+
const lines = tokenLines(tokenFile)
|
|
211
|
+
const socket = (useEnv && process.env.DSH_BRIDGE_SOCK) || (WIN ? lines[1] || null : path.join(d, 'dsh-bridge.sock'))
|
|
212
|
+
return {
|
|
213
|
+
id: null,
|
|
214
|
+
dir: d,
|
|
215
|
+
tokenFile,
|
|
216
|
+
socket,
|
|
217
|
+
token: lines[0] || null,
|
|
218
|
+
legacy: true,
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 解析本次操作应路由到哪个宿主:
|
|
224
|
+
* 1. 显式传入的 profile / host(id / label / browser 精确或前缀匹配)
|
|
225
|
+
* 2. 若设置了 DSH_BRIDGE_SOCK 且未显式指定 profile,保持单入口兼容
|
|
226
|
+
* 3. 当前会话上次绑定且仍存活的宿主 sessionHost
|
|
227
|
+
* 4. 最近聚焦(focusedAt 最大)→ 最近活跃(lastSeenAt 最大)的存活宿主
|
|
228
|
+
* 5. 回退兼容旧单一路径 dsh-bridge.sock / dsh-bridge.token
|
|
229
|
+
*/
|
|
230
|
+
export function resolveHost({ profile, host, sessionHost, dir } = {}) {
|
|
231
|
+
const d = dir || bridgeDir()
|
|
232
|
+
const useEnv = !dir || path.resolve(dir) === path.resolve(bridgeDir())
|
|
233
|
+
const explicit = profile !== undefined && profile !== null && profile !== '' ? profile : host
|
|
234
|
+
if (explicit && typeof explicit === 'object' && explicit.socket) {
|
|
235
|
+
return { dir: d, legacy: false, ...explicit }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const { hosts } = scanHosts({ dir: d })
|
|
239
|
+
|
|
240
|
+
if (explicit !== undefined && explicit !== null && String(explicit).trim() !== '') {
|
|
241
|
+
const found = matchHost(hosts, explicit)
|
|
242
|
+
if (found) return { ...found, dir: d, legacy: false }
|
|
243
|
+
throw new Error(t('err.hostNotFound', { profile: String(explicit).trim() }))
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (useEnv && process.env.DSH_BRIDGE_SOCK) {
|
|
247
|
+
return legacyEndpoint(d)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (sessionHost) {
|
|
251
|
+
const found = hosts.find((h) => h.id === sessionHost) || matchHost(hosts, sessionHost)
|
|
252
|
+
if (found) return { ...found, dir: d, legacy: false }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (hosts.length > 0) {
|
|
256
|
+
return { ...hosts[0], dir: d, legacy: false }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return legacyEndpoint(d)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** 解析纯数字 / "active" / "profile:tabId" 复合标签页标识 */
|
|
263
|
+
export function parseTabRef(tab) {
|
|
264
|
+
if (tab === undefined || tab === null || tab === '') return { host: null, tab: null }
|
|
265
|
+
const raw = String(tab).trim()
|
|
266
|
+
const idx = raw.lastIndexOf(':')
|
|
267
|
+
if (idx > 0) {
|
|
268
|
+
return { host: raw.slice(0, idx).trim() || null, tab: raw.slice(idx + 1).trim() }
|
|
269
|
+
}
|
|
270
|
+
return { host: null, tab: raw }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** 单宿主或 DSH_BRIDGE_SOCK 时输出纯数字,多宿主并存时输出 profile:tabId */
|
|
274
|
+
export function formatTabId(tabId, hostId, multiHost = false) {
|
|
275
|
+
if (multiHost && hostId) return `${hostId}:${tabId}`
|
|
276
|
+
return String(tabId)
|
|
277
|
+
}
|
package/core/locale.js
ADDED
package/core/receipt.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { call } from './transport.js'
|
|
2
|
+
import { short } from './tooldef.js'
|
|
3
|
+
import { t } from './locale.js'
|
|
4
|
+
|
|
5
|
+
const ACTION_STATE_JS = `(() => {
|
|
6
|
+
const live = [];
|
|
7
|
+
for (const el of document.querySelectorAll('[role="alert"], [aria-live="assertive"], [aria-live="polite"]')) {
|
|
8
|
+
const style = getComputedStyle(el);
|
|
9
|
+
if (!el.getClientRects().length || style.visibility !== 'visible' || style.opacity === '0' ||
|
|
10
|
+
el.checkVisibility?.({ opacityProperty: true, visibilityProperty: true }) === false) continue;
|
|
11
|
+
const text = (el.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 120);
|
|
12
|
+
if (text && !live.includes(text)) live.push(text);
|
|
13
|
+
if (live.length >= 30) break;
|
|
14
|
+
}
|
|
15
|
+
return { url: location.href, title: document.title, live };
|
|
16
|
+
})()`
|
|
17
|
+
|
|
18
|
+
export async function probeState(tabId) {
|
|
19
|
+
try {
|
|
20
|
+
return (await call('eval', { tabId, expression: ACTION_STATE_JS, userGesture: false }, 850, true)).value
|
|
21
|
+
} catch {}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function actionReceipt(tabId, before, result) {
|
|
25
|
+
try {
|
|
26
|
+
const [after, info] = await Promise.all([
|
|
27
|
+
probeState(tabId),
|
|
28
|
+
call('info', { tabId }, 850, true).catch(() => null),
|
|
29
|
+
])
|
|
30
|
+
const lines = []
|
|
31
|
+
const page = after?.url !== undefined ? after : result?.url !== undefined ? result : info
|
|
32
|
+
if (before && page?.url !== undefined && (page.url !== before.url || page.title !== before.title)) {
|
|
33
|
+
lines.push(`→ ${[short(page.title, 100), short(page.url, 250)].filter(Boolean).join(' ')}`)
|
|
34
|
+
}
|
|
35
|
+
if (result?.openedTabs?.length) {
|
|
36
|
+
const tabs = result.openedTabs.slice(0, 4).map((tb) => `[${tb.tabId ?? tb.id}] ${short(tb.url, 120)}`)
|
|
37
|
+
if (result.openedTabs.length > tabs.length) tabs.push(`+${result.openedTabs.length - tabs.length}`)
|
|
38
|
+
lines.push(t('res.action.tabs', { tabs: tabs.join(' · ') }))
|
|
39
|
+
}
|
|
40
|
+
const notes = []
|
|
41
|
+
if (result?.occluded) {
|
|
42
|
+
const { tag, text } = result.occluded
|
|
43
|
+
notes.push(t('res.action.occluded', { target: [short(tag, 30), short(text, 80)].filter(Boolean).join(' ') || '—' }))
|
|
44
|
+
}
|
|
45
|
+
const dialog = result?.pendingDialog ?? info?.pendingDialog
|
|
46
|
+
if (dialog) notes.push(t('res.action.dialog', { type: short(dialog.type), message: short(dialog.message, 120) }))
|
|
47
|
+
if (Array.isArray(before?.live) && Array.isArray(after?.live)) {
|
|
48
|
+
const update = after.live.find((text) => !before.live.includes(text))
|
|
49
|
+
if (update) notes.push(t('res.action.live', { text: short(update, 120) }))
|
|
50
|
+
}
|
|
51
|
+
if (notes.length) lines.push(notes.join(' · '))
|
|
52
|
+
return lines.length ? '\n' + lines.join('\n') : ''
|
|
53
|
+
} catch {
|
|
54
|
+
return ''
|
|
55
|
+
}
|
|
56
|
+
}
|
package/core/session.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { call, callInfo, setSessionHostGetter } from './transport.js'
|
|
3
|
+
import { parseTabRef, resolveHost } from './hosts.js'
|
|
4
|
+
import { t } from './locale.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 每个会话「正在用的标签页」:它自己打开的,或者它点名操作过的。不传 tab 时就接着用它;
|
|
8
|
+
* 一个都没有就报错 —— 绝不默认去动用户正在看的标签页(以前省略等于 active:模型没传 tab,
|
|
9
|
+
* 就把用户正在编辑的页面跳走了)。明确传 "active" 照旧:那是模型按用户的话有意要动当前页。
|
|
10
|
+
*/
|
|
11
|
+
export const SESSION_TTL = 24 * 60 * 60_000
|
|
12
|
+
export const CHOOSER_TTL = 10 * 60_000
|
|
13
|
+
const MAP_LIMIT = 256
|
|
14
|
+
|
|
15
|
+
export function pruneEntries(map, ttl) {
|
|
16
|
+
const cutoff = Date.now() - ttl
|
|
17
|
+
for (const [key, entry] of map) {
|
|
18
|
+
if (entry.at >= cutoff && map.size <= MAP_LIMIT) break
|
|
19
|
+
map.delete(key)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function remember(map, key, value, ttl) {
|
|
24
|
+
map.delete(key)
|
|
25
|
+
map.set(key, { value, at: Date.now() })
|
|
26
|
+
pruneEntries(map, ttl)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const currentTab = new Map()
|
|
30
|
+
export const currentHost = new Map()
|
|
31
|
+
export const sessionKey = () => (callInfo.getStore() || {}).session || 'default'
|
|
32
|
+
|
|
33
|
+
export function rememberHost(hostId) {
|
|
34
|
+
if (hostId) remember(currentHost, sessionKey(), String(hostId), SESSION_TTL)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function getSessionHost() {
|
|
38
|
+
pruneEntries(currentHost, SESSION_TTL)
|
|
39
|
+
const entry = currentHost.get(sessionKey())
|
|
40
|
+
return entry ? entry.value : null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function getSessionTab() {
|
|
44
|
+
pruneEntries(currentTab, SESSION_TTL)
|
|
45
|
+
const entry = currentTab.get(sessionKey())
|
|
46
|
+
return entry ? { id: entry.value, host: entry.host || null } : null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function bindCallHost(hostId) {
|
|
50
|
+
const store = callInfo.getStore()
|
|
51
|
+
if (store && hostId) store.host = String(hostId)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
setSessionHostGetter(getSessionHost)
|
|
55
|
+
|
|
56
|
+
export function rememberTab(id, hostId = null) {
|
|
57
|
+
const resolvedHost = hostId || callInfo.getStore()?.host || getSessionHost() || null
|
|
58
|
+
const key = sessionKey()
|
|
59
|
+
currentTab.delete(key)
|
|
60
|
+
currentTab.set(key, { value: Number(id), host: resolvedHost, at: Date.now() })
|
|
61
|
+
pruneEntries(currentTab, SESSION_TTL)
|
|
62
|
+
if (resolvedHost) rememberHost(resolvedHost)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 标签页关掉了:谁正在用它,谁就忘掉它 */
|
|
66
|
+
export function forgetTab(id, hostId = null) {
|
|
67
|
+
const targetHost = hostId || callInfo.getStore()?.host || null
|
|
68
|
+
for (const [key, entry] of currentTab) {
|
|
69
|
+
if (entry.value === Number(id) && (!targetHost || !entry.host || entry.host === targetHost)) {
|
|
70
|
+
currentTab.delete(key)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
for (const key of chooserIds.keys()) if (key.endsWith(`:${Number(id)}`)) chooserIds.delete(key)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function resolveTab(tab, userTab) {
|
|
77
|
+
if (tab !== undefined && tab !== null && tab !== '') {
|
|
78
|
+
const parsed = parseTabRef(tab)
|
|
79
|
+
const isActive = String(parsed.tab) === 'active'
|
|
80
|
+
const id = isActive ? null : Number(parsed.tab)
|
|
81
|
+
if (!isActive && !Number.isInteger(id)) throw new Error(t('err.badTab', { tab }))
|
|
82
|
+
|
|
83
|
+
const resolved = parsed.host
|
|
84
|
+
? resolveHost({ profile: parsed.host })
|
|
85
|
+
: resolveHost({ sessionHost: getSessionHost() })
|
|
86
|
+
const hostId = resolved.id || null
|
|
87
|
+
if (hostId) {
|
|
88
|
+
bindCallHost(hostId)
|
|
89
|
+
rememberHost(hostId)
|
|
90
|
+
}
|
|
91
|
+
if (isActive) {
|
|
92
|
+
const active = userTab(await call('tabs', {}, 60000, false, hostId ? { host: hostId } : {}))
|
|
93
|
+
if (!active) throw new Error(t('err.noActiveTab'))
|
|
94
|
+
rememberTab(active.id, hostId)
|
|
95
|
+
return active.id
|
|
96
|
+
}
|
|
97
|
+
rememberTab(id, hostId)
|
|
98
|
+
return id
|
|
99
|
+
}
|
|
100
|
+
pruneEntries(currentTab, SESSION_TTL)
|
|
101
|
+
const key = sessionKey()
|
|
102
|
+
const entry = currentTab.get(key)
|
|
103
|
+
if (entry) {
|
|
104
|
+
const id = entry.value
|
|
105
|
+
const hostId = entry.host || getSessionHost() || null
|
|
106
|
+
if (hostId) bindCallHost(hostId)
|
|
107
|
+
const exists = (await call('tabs', {}, 60000, false, hostId ? { host: hostId } : {})).some((tb) => tb.id === id)
|
|
108
|
+
if (currentTab.get(key) === entry) {
|
|
109
|
+
if (exists) rememberTab(id, hostId)
|
|
110
|
+
else currentTab.delete(key)
|
|
111
|
+
}
|
|
112
|
+
if (exists) return id
|
|
113
|
+
}
|
|
114
|
+
throw new Error(t('err.noTab'))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** DSH 没有正式文档说 exec 里有什么,几个可能的位置都试一下;拿不到就按进程算一个会话 */
|
|
118
|
+
export function sessionOf(exec) {
|
|
119
|
+
const a = exec && exec.agent
|
|
120
|
+
const v = (exec && exec.sessionId) || (a && (a.sessionId || (a.session && a.session.id) || a.id))
|
|
121
|
+
return typeof v === 'string' || typeof v === 'number' ? String(v) : null
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** DSH 的会话投影服务(读会话现在的工作目录用);apply 里 inject 到了才有 */
|
|
125
|
+
let projections = null
|
|
126
|
+
|
|
127
|
+
export function setProjections(value) {
|
|
128
|
+
projections = value
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 会话现在的工作目录:先看 DSH 的 workingDirectory 投影(会话里切过目录就是新的),没有再用会话头里
|
|
133
|
+
* 建会话时的目录。都拿不到返回空串。写法同 dsh-video-preview 的 sessionCwd。
|
|
134
|
+
*/
|
|
135
|
+
export function sessionCwd(exec) {
|
|
136
|
+
const session = exec && exec.agent && exec.agent.session
|
|
137
|
+
let cwd
|
|
138
|
+
try {
|
|
139
|
+
cwd = projections && session && projections.stateOf(session, 'workingDirectory')
|
|
140
|
+
} catch { /* 没装这个投影 */ }
|
|
141
|
+
if (typeof cwd !== 'string' || !cwd) cwd = session && session.header && session.header.cwd
|
|
142
|
+
return typeof cwd === 'string' && path.isAbsolute(cwd) ? cwd : ''
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 点击 / 按键让页面要选文件时,扩展已把系统的选文件窗口拦下、回一个 id。记在「会话 + 标签页」名下:
|
|
147
|
+
* 之后这个会话 upload 不给目标就带着它去,别的会话拿不到(不会把文件塞进人家刚点开的框)。
|
|
148
|
+
*/
|
|
149
|
+
export const chooserIds = new Map()
|
|
150
|
+
export const chooserKey = (tabId) => `${sessionKey()}:${Number(tabId)}`
|
|
151
|
+
|
|
152
|
+
export const lastActionAt = new Map()
|
|
153
|
+
export function recordAction(tabId) {
|
|
154
|
+
lastActionAt.delete(tabId)
|
|
155
|
+
lastActionAt.set(tabId, Date.now())
|
|
156
|
+
if (lastActionAt.size > 256) lastActionAt.delete(lastActionAt.keys().next().value)
|
|
157
|
+
}
|
package/core/shots.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import crypto from 'node:crypto'
|
|
5
|
+
import { SESSION_TTL } from './session.js'
|
|
6
|
+
import { t } from './locale.js'
|
|
7
|
+
|
|
8
|
+
const UID = typeof process.getuid === 'function' ? process.getuid() : null
|
|
9
|
+
const { O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW } = fs.constants
|
|
10
|
+
|
|
11
|
+
// ── 截图:把图直接给模型看 ──────────────────────────────────────────────────
|
|
12
|
+
|
|
13
|
+
/** render 是同步的,所以 execute 把附件引用存在这里,render 取出来用。 */
|
|
14
|
+
export const shotRefs = new Map()
|
|
15
|
+
|
|
16
|
+
export function cleanOldShots() {
|
|
17
|
+
const dir = os.tmpdir()
|
|
18
|
+
const cutoff = Date.now() - SESSION_TTL
|
|
19
|
+
try {
|
|
20
|
+
for (const name of fs.readdirSync(dir)) {
|
|
21
|
+
if (!/^dsh-shot-.*\.(?:png|jpg)$/.test(name)) continue
|
|
22
|
+
const file = path.join(dir, name)
|
|
23
|
+
try {
|
|
24
|
+
const stat = fs.lstatSync(file)
|
|
25
|
+
if (stat.isFile() && (UID === null || stat.uid === UID) && stat.mtimeMs < cutoff) fs.unlinkSync(file)
|
|
26
|
+
} catch {}
|
|
27
|
+
}
|
|
28
|
+
} catch {}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function saveShotResult(r, { mode, isJpeg, getAttachments }) {
|
|
32
|
+
const buf = Buffer.from(r.data, 'base64')
|
|
33
|
+
const where = `${r.title || ''} ${r.url || ''}`.trim()
|
|
34
|
+
const note = t('res.shot.note', { mode, size: `${Math.round(buf.length / 1024)}KB`, where })
|
|
35
|
+
|
|
36
|
+
const attachments = getAttachments()
|
|
37
|
+
if (attachments) {
|
|
38
|
+
try {
|
|
39
|
+
const [ref] = await attachments.saveImages([{
|
|
40
|
+
data: buf,
|
|
41
|
+
mediaType: isJpeg ? 'image/jpeg' : 'image/png',
|
|
42
|
+
name: `page-${Date.now()}.${isJpeg ? 'jpg' : 'png'}`,
|
|
43
|
+
}])
|
|
44
|
+
const token = crypto.randomUUID()
|
|
45
|
+
shotRefs.set(token, ref)
|
|
46
|
+
if (shotRefs.size > 20) shotRefs.delete(shotRefs.keys().next().value)
|
|
47
|
+
return { text: note, token }
|
|
48
|
+
} catch {
|
|
49
|
+
// 存不进附件库就退回文件,别让截图功能整个挂掉
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
cleanOldShots()
|
|
53
|
+
const file = path.join(os.tmpdir(), `dsh-shot-${crypto.randomUUID()}.${isJpeg ? 'jpg' : 'png'}`)
|
|
54
|
+
fs.writeFileSync(file, buf, { flag: O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, mode: 0o600 })
|
|
55
|
+
return { text: note + t('res.shot.saved', { file }), token: '' }
|
|
56
|
+
}
|