@andy.ian/dsh-homing 2.2.2 → 2.3.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.
@@ -10,6 +10,11 @@
10
10
  * - 守护进程空闲 IdleSeconds 后自行退出,不留孤儿
11
11
  *
12
12
  * 一个守护进程同一时刻服务一个客户端(插件),请求在客户端侧串行。
13
+ *
14
+ * 可测性:核心逻辑放在 createWindowRemote(options) 里,连接/启动/时钟/睡眠都可注入。
15
+ * 模块底部用默认依赖创建一个实例,并导出与之前完全相同的具名 API,
16
+ * 因此**不改变任何调用方行为**;测试则用假 socket 覆盖连接、超时、重试与断开路径,
17
+ * 不会真的拉起守护进程、不碰桌面。
13
18
  */
14
19
  import { spawn } from 'node:child_process'
15
20
  import net from 'node:net'
@@ -22,222 +27,291 @@ import { findNodeRuntime } from './node-runtime.mjs'
22
27
 
23
28
  const HERE = path.dirname(fileURLToPath(import.meta.url))
24
29
  const DAEMON = path.join(HERE, '..', 'bin', 'window-agent-daemon.mjs')
25
-
26
30
  const isWindows = process.platform === 'win32'
31
+ const DEFAULT_PIPE_NAME = socketName()
32
+ const DEFAULT_PIPE_PATH = socketPath(DEFAULT_PIPE_NAME)
33
+ const DEFAULT_TOKEN = loadOrCreateToken()
27
34
 
28
- const PIPE_NAME = socketName()
29
- const PIPE_PATH = socketPath(PIPE_NAME)
30
- const TOKEN = loadOrCreateToken()
31
-
32
- let socket = null
33
- let rl = null
34
- let socketGeneration = 0
35
- let seq = 0
36
- let pending = new Map()
37
- let chain = Promise.resolve()
38
- let restarts = 0
39
- let connecting = null
40
-
41
- const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms) })
42
-
43
- function fail(error) {
44
- for (const [, resolve] of pending) resolve({ ok: false, error: String(error?.message ?? error) })
45
- pending.clear()
46
- socket = null
47
- rl = null
48
- }
35
+ /**
36
+ * 创建窗口代理客户端。
37
+ * @param {object} [options]
38
+ * @param {(pipePath: string, timeoutMs: number) => Promise<any>} [options.connect]
39
+ * @param {Function} [options.spawnFn]
40
+ * @param {Function} [options.findRuntime]
41
+ * @param {string} [options.daemonEntry]
42
+ * @param {string} [options.pipeName]
43
+ * @param {string} [options.pipePath]
44
+ * @param {string} [options.token]
45
+ * @param {Function} [options.sleepFn]
46
+ * @param {Function} [options.now]
47
+ * @param {number} [options.spawnDeadlineMs]
48
+ * @param {number} [options.connectTimeoutMs]
49
+ */
50
+ export function createWindowRemote(options = {}) {
51
+ const pipeName = options.pipeName ?? DEFAULT_PIPE_NAME
52
+ const pipePath = options.pipePath ?? DEFAULT_PIPE_PATH
53
+ const token = options.token ?? DEFAULT_TOKEN
54
+ const daemonEntry = options.daemonEntry ?? DAEMON
55
+ const findRuntime = options.findRuntime ?? findNodeRuntime
56
+ const spawnFn = options.spawnFn ?? spawn
57
+ const sleepFn = options.sleepFn ?? ((ms) => new Promise((resolve) => { setTimeout(resolve, ms) }))
58
+ const now = options.now ?? Date.now
59
+ const spawnDeadlineMs = options.spawnDeadlineMs ?? 8000
60
+ const connectTimeoutMs = options.connectTimeoutMs ?? 400
61
+ const connect = options.connect ?? defaultConnect
49
62
 
50
- function attach(stream) {
51
- socket = stream
52
- socketGeneration += 1
53
- const generation = socketGeneration
54
- rl = readline.createInterface({ input: stream })
55
- rl.on('line', (line) => {
56
- const text = line.trim()
57
- if (!text.startsWith('{')) return
58
- let message = null
59
- try { message = JSON.parse(text) } catch { return }
60
- const resolve = pending.get(message.id)
61
- if (resolve === undefined) return
62
- pending.delete(message.id)
63
- resolve(message)
64
- })
65
- // 只处理"当前连接"的关闭;旧连接(超时被销毁后)不能清掉新连接的 pending
66
- stream.on('close', () => { if (generation === socketGeneration) fail(new Error('窗口代理连接已断开')) })
67
- stream.on('error', () => { if (generation === socketGeneration) fail(new Error('窗口代理连接错误')) })
68
- }
63
+ let socket = null
64
+ let rl = null
65
+ let socketGeneration = 0
66
+ let seq = 0
67
+ const pending = new Map()
68
+ let chain = Promise.resolve()
69
+ let restarts = 0
70
+ let connecting = null
71
+ let listInFlight = null
69
72
 
70
- function connectOnce(timeoutMs = 400) {
71
- return new Promise((resolve, reject) => {
72
- const stream = net.connect(PIPE_PATH)
73
- let settled = false
74
- const timer = setTimeout(() => {
75
- if (settled) return
76
- settled = true
77
- stream.destroy()
78
- reject(new Error('connect timeout'))
79
- }, timeoutMs)
80
- stream.once('connect', () => {
81
- if (settled) return
82
- settled = true
83
- clearTimeout(timer)
84
- resolve(stream)
85
- })
86
- stream.once('error', (error) => {
87
- if (settled) return
88
- settled = true
89
- clearTimeout(timer)
90
- reject(error)
73
+ /** 统一把挂起请求收敛成失败 /** 统一把挂起请求收敛成失败,并清掉连接(message 由调用方给出,无需再判空) */
74
+ function fail(message) {
75
+ const text = String(message)
76
+ for (const [, resolve] of pending) resolve({ ok: false, error: text })
77
+ pending.clear()
78
+ socket = null
79
+ rl = null
80
+ }
81
+
82
+ function attach(stream) {
83
+ socket = stream
84
+ socketGeneration += 1
85
+ const generation = socketGeneration
86
+ rl = readline.createInterface({ input: stream })
87
+ // readline 会把底层 stream 的 error 再 emit 一次;不接住就是未捕获异常,
88
+ // 可能把宿主进程带崩(2026-11-16 由测试发现)。真正的处理在下面 stream.on('error')。
89
+ rl.on('error', () => { /* 交给 stream 的 error 处理器 */ })
90
+ rl.on('line', (line) => {
91
+ const text = line.trim()
92
+ if (!text.startsWith('{')) return
93
+ let message = null
94
+ try { message = JSON.parse(text) } catch { return }
95
+ const resolve = pending.get(message.id)
96
+ if (resolve === undefined) return
97
+ pending.delete(message.id)
98
+ resolve(message)
91
99
  })
92
- })
93
- }
100
+ // 只处理"当前连接"的关闭;旧连接(超时被销毁后)不能清掉新连接的 pending
101
+ stream.on('close', () => { if (generation === socketGeneration) fail('窗口代理连接已断开') })
102
+ stream.on('error', () => { if (generation === socketGeneration) fail('窗口代理连接错误') })
103
+ }
94
104
 
95
- function spawnDaemon() {
96
- const idle = Number(process.env.DSH_AGENT_IDLE_SECONDS) || 300
97
- // 守护进程是 Node:可以安全使用 detached(PowerShell 5.1 在
98
- // DETACHED_PROCESS 下会直接退出,所以之前不能用 detached)。
99
- const child = spawn(
100
- findNodeRuntime(),
101
- [DAEMON],
102
- {
103
- windowsHide: true,
104
- detached: true,
105
- stdio: 'ignore',
106
- env: {
107
- ...process.env,
108
- DSH_AGENT_PIPE: PIPE_NAME,
109
- DSH_AGENT_TOKEN: TOKEN,
110
- DSH_AGENT_IDLE_SECONDS: String(idle),
111
- },
112
- },
113
- )
114
- child.unref()
115
- }
105
+ async function connectOnce(timeoutMs = connectTimeoutMs) {
106
+ return connect(pipePath, timeoutMs)
107
+ }
116
108
 
117
- async function ensureDaemon() {
118
- if (socket !== null && !socket.destroyed) return
119
- if (connecting !== null) {
120
- await connecting
121
- return
109
+ function spawnDaemon() {
110
+ const idle = Number(process.env.DSH_AGENT_IDLE_SECONDS) || 300
111
+ // 守护进程是 Node:可以安全使用 detached(PowerShell 5.1 在
112
+ // DETACHED_PROCESS 下会直接退出,所以之前不能用 detached)。
113
+ const child = spawnFn(
114
+ findRuntime(),
115
+ [daemonEntry],
116
+ {
117
+ windowsHide: true,
118
+ detached: true,
119
+ stdio: 'ignore',
120
+ env: {
121
+ ...process.env,
122
+ DSH_AGENT_PIPE: pipeName,
123
+ DSH_AGENT_TOKEN: token,
124
+ DSH_AGENT_IDLE_SECONDS: String(idle),
125
+ },
126
+ },
127
+ )
128
+ if (child && typeof child.unref === 'function') child.unref()
129
+ return child
122
130
  }
123
- connecting = (async () => {
124
- try {
125
- attach(await connectOnce())
131
+
132
+ async function ensureDaemon() {
133
+ if (socket !== null && !socket.destroyed) return
134
+ if (connecting !== null) {
135
+ await connecting
126
136
  return
127
- } catch { /* 没在跑,拉起守护进程 */ }
128
- restarts += 1
129
- spawnDaemon()
130
- const deadline = Date.now() + 8000
131
- let lastError = null
132
- while (Date.now() < deadline) {
137
+ }
138
+ connecting = (async () => {
133
139
  try {
134
140
  attach(await connectOnce())
135
141
  return
142
+ } catch { /* 没在跑,拉起守护进程 */ }
143
+ restarts += 1
144
+ spawnDaemon()
145
+ const deadline = now() + spawnDeadlineMs
146
+ let lastError = null
147
+ while (now() < deadline) {
148
+ try {
149
+ attach(await connectOnce())
150
+ return
151
+ } catch (error) {
152
+ lastError = error
153
+ await sleepFn(150)
154
+ }
155
+ }
156
+ throw new Error('窗口代理守护进程未启动:' + String(lastError?.message ?? lastError))
157
+ })()
158
+ try {
159
+ await connecting
160
+ } finally {
161
+ connecting = null
162
+ }
163
+ }
164
+
165
+ async function rawCall(request, timeoutMs) {
166
+ await ensureDaemon()
167
+ const id = String(++seq)
168
+ return new Promise((resolve) => {
169
+ const timer = setTimeout(() => {
170
+ pending.delete(id)
171
+ // 超时说明连接/守护进程可能已卡死:销毁套接字,下一次调用重新拉起
172
+ try { socket?.destroy() } catch { /* 忽略 */ }
173
+ socket = null
174
+ rl = null
175
+ resolve({ id, ok: false, error: 'timeout' })
176
+ }, timeoutMs)
177
+ pending.set(id, (message) => {
178
+ clearTimeout(timer)
179
+ resolve(message)
180
+ })
181
+ try {
182
+ socket.write(JSON.stringify({ id, token, ...request }) + '\n')
136
183
  } catch (error) {
137
- lastError = error
138
- await sleep(150)
184
+ clearTimeout(timer)
185
+ pending.delete(id)
186
+ resolve({ id, ok: false, error: String(error?.message ?? error) })
139
187
  }
188
+ })
189
+ }
190
+
191
+ /** 串行执行;任何异常都收敛成 {ok:false},绝不向上抛 */
192
+ function call(request, timeoutMs = 15_000) {
193
+ const next = chain
194
+ .then(() => rawCall(request, timeoutMs))
195
+ .catch((error) => ({ ok: false, error: String(error) }))
196
+ chain = next.then(() => undefined)
197
+ return next
198
+ }
199
+
200
+ /** 窗口列表:并发调用共享同一个请求,避免轮询把请求链塞满 */
201
+ function listWindows() {
202
+ if (listInFlight !== null) return listInFlight
203
+ listInFlight = (async () => {
204
+ const result = await call({ cmd: 'list' }, 8_000)
205
+ return {
206
+ ok: result.ok === true,
207
+ windows: Array.isArray(result.windows) ? result.windows : [],
208
+ screenWidth: Number(result.screenWidth) || 0,
209
+ screenHeight: Number(result.screenHeight) || 0,
210
+ error: result.error ?? null,
211
+ }
212
+ })()
213
+ return listInFlight.finally(() => { listInFlight = null })
214
+ }
215
+
216
+ async function captureWindow(hwnd, maxWidth = 1280) {
217
+ const result = await call({ cmd: 'capture', hwnd: String(hwnd), maxWidth: Number(maxWidth) || 1280 }, 20_000)
218
+ if (result.ok !== true || typeof result.data !== 'string') {
219
+ return { ok: false, error: result.error ?? '抓图失败' }
140
220
  }
141
- throw new Error('窗口代理守护进程未启动:' + String(lastError?.message ?? lastError))
142
- })()
143
- try {
144
- await connecting
145
- } finally {
146
- connecting = null
221
+ const buffer = Buffer.from(result.data, 'base64')
222
+ return { ok: true, width: Number(result.width) || 0, height: Number(result.height) || 0, buffer, bytes: buffer.length }
223
+ }
224
+
225
+ const clickWindow = (hwnd, x, y, button = 'left') => call({ cmd: 'click', hwnd: String(hwnd), x: Number(x) || 0, y: Number(y) || 0, button })
226
+ const wheelWindow = (hwnd, delta) => call({ cmd: 'wheel', hwnd: String(hwnd), delta: Number(delta) || 0 })
227
+ const keyWindow = (hwnd, { text = '', keys = [] } = {}) => call({ cmd: 'key', hwnd: String(hwnd), text: String(text), keys: Array.isArray(keys) ? keys : [] })
228
+ const focusWindow = (hwnd) => call({ cmd: 'focus', hwnd: String(hwnd) })
229
+ const closeWindow = (hwnd = '') => call({ cmd: 'close', hwnd: String(hwnd) })
230
+ const killWindow = (hwnd) => call({ cmd: 'kill', hwnd: String(hwnd) })
231
+ const rotateScreen = (mode, timeoutMs = 20_000) => call({ cmd: 'rotate', mode: String(mode) }, timeoutMs)
232
+ const restoreOrientation = (timeoutMs = 10_000) => call({ cmd: 'restore' }, timeoutMs)
233
+ const cursorPos = () => call({ cmd: 'cursor' })
234
+ const openPath = (filePath) => call({ cmd: 'open', path: String(filePath) }, 20_000)
235
+
236
+ /** 关闭连接(守护进程空闲后自行退出;不杀进程,避免影响其他客户端) */
237
+ function stopAgent() {
238
+ try {
239
+ if (socket !== null && !socket.destroyed) {
240
+ socket.write(JSON.stringify({ id: String(++seq), token, cmd: 'shutdown' }) + '\n')
241
+ socket.end()
242
+ }
243
+ } catch { /* 忽略 */ }
244
+ socket = null
245
+ rl = null
246
+ }
247
+
248
+ /** 主动请求守护进程退出(升级/测试用) */
249
+ async function shutdownDaemon() {
250
+ const result = await call({ cmd: 'shutdown' }, 5_000)
251
+ stopAgent()
252
+ return result
253
+ }
254
+
255
+ return {
256
+ ensureDaemon,
257
+ listWindows,
258
+ captureWindow,
259
+ clickWindow,
260
+ wheelWindow,
261
+ keyWindow,
262
+ focusWindow,
263
+ closeWindow,
264
+ killWindow,
265
+ rotateScreen,
266
+ restoreOrientation,
267
+ cursorPos,
268
+ openPath,
269
+ stopAgent,
270
+ shutdownDaemon,
271
+ isSupported: () => isWindows,
272
+ stats: () => ({ restarts, running: socket !== null, pipe: pipePath }),
147
273
  }
148
274
  }
149
275
 
150
- async function rawCall(request, timeoutMs) {
151
- await ensureDaemon()
152
- const id = String(++seq)
153
- return new Promise((resolve) => {
276
+ /**
277
+ * 默认连接实现:连本地命名管道 / Unix socket,带超时。
278
+ * 导出让测试能覆盖真实连接路径;`connectImpl` 可注入,用来覆盖超时分支。
279
+ */
280
+ export function defaultConnect(target, timeoutMs = 400, connectImpl = (value) => net.connect(value)) {
281
+ return new Promise((resolve, reject) => {
282
+ const stream = connectImpl(target)
154
283
  const timer = setTimeout(() => {
155
- pending.delete(id)
156
- // 超时说明连接/守护进程可能已卡死:销毁套接字,下一次调用重新拉起
157
- try { socket?.destroy() } catch { /* 忽略 */ }
158
- socket = null
159
- rl = null
160
- resolve({ id, ok: false, error: 'timeout' })
284
+ // 连上或出错时都会清掉定时器,所以这里只管超时本身
285
+ stream.destroy()
286
+ reject(new Error('connect timeout'))
161
287
  }, timeoutMs)
162
- pending.set(id, (message) => {
288
+ stream.once('connect', () => {
163
289
  clearTimeout(timer)
164
- resolve(message)
290
+ resolve(stream)
165
291
  })
166
- try {
167
- socket.write(JSON.stringify({ id, token: TOKEN, ...request }) + '\n')
168
- } catch (error) {
292
+ stream.once('error', (error) => {
169
293
  clearTimeout(timer)
170
- pending.delete(id)
171
- resolve({ id, ok: false, error: String(error?.message ?? error) })
172
- }
294
+ reject(error)
295
+ })
173
296
  })
174
297
  }
175
298
 
176
- /** 串行执行;任何异常都收敛成 {ok:false},绝不向上抛 */
177
- function call(request, timeoutMs = 15_000) {
178
- const next = chain
179
- .then(() => rawCall(request, timeoutMs))
180
- .catch((error) => ({ ok: false, error: String(error?.message ?? error) }))
181
- chain = next.then(() => undefined, () => undefined)
182
- return next
183
- }
299
+ // ---------- 默认实例:保持与之前完全相同的导出 API ----------
300
+ const defaultRemote = createWindowRemote()
184
301
 
185
- let listInFlight = null
186
-
187
- /** 窗口列表:并发调用共享同一个请求,避免轮询把请求链塞满 */
188
- export const listWindows = () => {
189
- if (listInFlight !== null) return listInFlight
190
- listInFlight = (async () => {
191
- const result = await call({ cmd: 'list' }, 8_000)
192
- return {
193
- ok: result.ok === true,
194
- windows: Array.isArray(result.windows) ? result.windows : [],
195
- screenWidth: Number(result.screenWidth) || 0,
196
- screenHeight: Number(result.screenHeight) || 0,
197
- error: result.error ?? null,
198
- }
199
- })()
200
- return listInFlight.finally(() => { listInFlight = null })
201
- }
202
-
203
- export const captureWindow = async (hwnd, maxWidth = 1280) => {
204
- const result = await call({ cmd: 'capture', hwnd: String(hwnd), maxWidth: Number(maxWidth) || 1280 }, 20_000)
205
- if (result.ok !== true || typeof result.data !== 'string') {
206
- return { ok: false, error: result.error ?? '抓图失败' }
207
- }
208
- const buffer = Buffer.from(result.data, 'base64')
209
- return { ok: true, width: Number(result.width) || 0, height: Number(result.height) || 0, buffer, bytes: buffer.length }
210
- }
211
-
212
- export const clickWindow = (hwnd, x, y, button = 'left') => call({ cmd: 'click', hwnd: String(hwnd), x: Number(x) || 0, y: Number(y) || 0, button })
213
- export const wheelWindow = (hwnd, delta) => call({ cmd: 'wheel', hwnd: String(hwnd), delta: Number(delta) || 0 })
214
- export const keyWindow = (hwnd, { text = '', keys = [] } = {}) => call({ cmd: 'key', hwnd: String(hwnd), text: String(text), keys: Array.isArray(keys) ? keys : [] })
215
- export const focusWindow = (hwnd) => call({ cmd: 'focus', hwnd: String(hwnd) })
216
- export const closeWindow = (hwnd = '') => call({ cmd: 'close', hwnd: String(hwnd) })
217
- export const killWindow = (hwnd) => call({ cmd: 'kill', hwnd: String(hwnd) })
218
- export const rotateScreen = (mode, timeoutMs = 20_000) => call({ cmd: 'rotate', mode: String(mode) }, timeoutMs)
219
- export const restoreOrientation = (timeoutMs = 10_000) => call({ cmd: 'restore' }, timeoutMs)
220
- export const cursorPos = () => call({ cmd: 'cursor' })
221
- export const openPath = (filePath) => call({ cmd: 'open', path: String(filePath) }, 20_000)
222
-
223
- export const isSupported = () => isWindows
224
- export const stats = () => ({ restarts, running: socket !== null, pipe: PIPE_PATH })
225
-
226
- /** 关闭连接(守护进程空闲后自行退出;不杀进程,避免影响其他客户端) */
227
- export function stopAgent() {
228
- try {
229
- if (socket !== null && !socket.destroyed) {
230
- socket.write(JSON.stringify({ id: String(++seq), token: TOKEN, cmd: 'shutdown' }) + '\n')
231
- socket.end()
232
- }
233
- } catch { /* 忽略 */ }
234
- socket = null
235
- rl = null
236
- }
237
-
238
- /** 主动请求守护进程退出(升级/测试用) */
239
- export async function shutdownDaemon() {
240
- const result = await call({ cmd: 'shutdown' }, 5_000)
241
- stopAgent()
242
- return result
243
- }
302
+ export const listWindows = defaultRemote.listWindows
303
+ export const captureWindow = defaultRemote.captureWindow
304
+ export const clickWindow = defaultRemote.clickWindow
305
+ export const wheelWindow = defaultRemote.wheelWindow
306
+ export const keyWindow = defaultRemote.keyWindow
307
+ export const focusWindow = defaultRemote.focusWindow
308
+ export const closeWindow = defaultRemote.closeWindow
309
+ export const killWindow = defaultRemote.killWindow
310
+ export const rotateScreen = defaultRemote.rotateScreen
311
+ export const restoreOrientation = defaultRemote.restoreOrientation
312
+ export const cursorPos = defaultRemote.cursorPos
313
+ export const openPath = defaultRemote.openPath
314
+ export const stopAgent = defaultRemote.stopAgent
315
+ export const shutdownDaemon = defaultRemote.shutdownDaemon
316
+ export const isSupported = defaultRemote.isSupported
317
+ export const stats = defaultRemote.stats
package/lib/ws-bridge.mjs CHANGED
@@ -58,7 +58,8 @@ export function bridge(client, tcp, { onClose } = {}) {
58
58
  if (typeof onClose === 'function') onClose()
59
59
  }
60
60
 
61
- const sendControl = (opcode, payload = Buffer.alloc(0)) => {
61
+ // 唯一调用点在 PING 分支,始终显式带 payload;不需要默认值
62
+ const sendControl = (opcode, payload) => {
62
63
  if (closed) return
63
64
  try { client.write(encodeFrame(payload, opcode)) } catch { finish() }
64
65
  }
@@ -100,7 +101,9 @@ export function bridge(client, tcp, { onClose } = {}) {
100
101
  if (fin) {
101
102
  const full = Buffer.concat(fragments)
102
103
  fragments = []
103
- if (!closed) tcp.write(full)
104
+ // tcp.write 可能抛错(对端已关闭)。必须在这里兜住:
105
+ // 抛到事件处理器外面会变成未捕获异常,可能拖垮宿主进程。
106
+ if (!closed) { try { tcp.write(full) } catch { finish() } }
104
107
  }
105
108
  continue
106
109
  }
@@ -109,7 +112,7 @@ export function bridge(client, tcp, { onClose } = {}) {
109
112
  if (fin) {
110
113
  const full = Buffer.concat(fragments)
111
114
  fragments = []
112
- if (!closed) tcp.write(full)
115
+ if (!closed) { try { tcp.write(full) } catch { finish() } }
113
116
  }
114
117
  continue
115
118
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.2.2",
3
+ "version": "2.3.0",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [
@@ -134,13 +134,32 @@
134
134
  var es = null;
135
135
  var gotFirst = false;
136
136
 
137
+ // 与服务端 lib/format-age.mjs 等价(浏览器里不能 import ESM)。
138
+ // 两边一致性由 test/unit.format-age.test.mjs 守住。
139
+ function formatAge(seconds) {
140
+ var value = Number(seconds);
141
+ if (!isFinite(value) || value < 0) return '未知';
142
+ if (value < 1) return '刚刚';
143
+ if (value < 60) return (Math.round(value * 10) / 10) + ' 秒前';
144
+ if (value < 3600) {
145
+ var minutes = Math.floor(value / 60);
146
+ var rest = Math.round(value % 60);
147
+ if (rest === 60) { minutes += 1; rest = 0; }
148
+ return rest === 0 ? (minutes + ' 分钟前') : (minutes + ' 分 ' + rest + ' 秒前');
149
+ }
150
+ var hours = Math.floor(value / 3600);
151
+ var tail = Math.round((value % 3600) / 60);
152
+ if (tail === 60) return ((hours + 1) + ' 小时前');
153
+ return tail === 0 ? (hours + ' 小时前') : (hours + ' 小时 ' + tail + ' 分前');
154
+ }
155
+
137
156
  function setBusy(state) {
138
157
  if (busy) busy.textContent = state.busy
139
158
  ? ('是(' + (state.sessions || []).length + ' 个会话运行中)')
140
159
  : '否(空闲)';
141
160
  if (!list) return;
142
161
  list.innerHTML = (state.sessions || []).map(function (item) {
143
- var line = '<li><b>' + (item.title || '(未命名)') + '</b> · ' + item.age + ' 秒前';
162
+ var line = '<li><b>' + (item.title || '(未命名)') + '</b> · 最后活动 ' + formatAge(item.age);
144
163
  if (item.cwd) line += '<br><span class="dim">' + item.cwd + '</span>';
145
164
  return line + '</li>';
146
165
  }).join('');
@@ -86,6 +86,28 @@ DSH 由守护进程启动,因此**是守护进程的子进程**。这带来一
86
86
  回归测试 `test/unit.daemon-stop.test.mjs` 会校验:
87
87
  CLI 可执行代码不含 `taskkill /T`,且 `main.mjs` 里杀 DSH 的全部 `taskkill` 调用均为逐 PID。
88
88
 
89
+ ## 升级等待(2026-11-14 修复)
90
+
91
+ electron-updater 会先把安装包下载到 `%LOCALAPPDATA%\@deepseek-aidsh-desktop-updater\pending\`,
92
+ **下载 ≠ 安装**。守护进程只在两种情况下等安装完成再拉起 DSH:
93
+
94
+ - 安装器进程正在运行(`installer-running`);
95
+ - DSH 的 exe 暂时不存在(`exe-missing`,正在被替换)。
96
+
97
+ 只是 `pending/` 里有更新包(`pending-newer` / `pending-fresh`)**不会**阻塞:
98
+ 被强制结束的 DSH 不会自己运行安装器,等下去没有任何东西会恢复 DSH。
99
+
100
+ > 历史事故:2026-11-14 20:07 强制重启后 DSH 被杀,守护进程一直停在「等待升级」,
101
+ > DSH 实际是用户手动点开的。
102
+ >
103
+ > 真正的根因不是「pending 里有包」,而是**已安装版本被永久缓存**:守护进程 11-08
104
+ > 启动时缓存了当时的版本,DSH 在 11-13 自我升级到 0.2.2-rc.3 后缓存没有刷新,
105
+ > 于是它把「与已安装版本相同的残留安装包」当成新版本(`pending-newer`)。
106
+ > 现在版本号按 exe 的 mtime/size 失效缓存;并且等待条件只看安装器/exe,
107
+ > 正确性不再依赖版本号读取。
108
+
109
+ 启动前会先探一次 DSH:如果安装器已经完成安装并拉起了应用,就跳过启动步骤,避免重复实例。
110
+
89
111
  ## 常用命令
90
112
 
91
113
  ```bash
@@ -84,14 +84,18 @@ export function buildCimStartScript({ command, args = [], cwd }) {
84
84
 
85
85
  /**
86
86
  * 用 CIM/WMI 创建进程(父进程 = WmiPrvSE.exe,与 DSH 进程树无关)
87
+ *
88
+ * `platform` / `runSync` 可注入:这两个是唯一的外部依赖,
89
+ * 注入后就能在任意平台上覆盖到"非 Windows 直接拒绝"和各条失败分支。
90
+ *
87
91
  * @returns {{ ok: boolean, how: string, pid?: number, error?: string }}
88
92
  */
89
- export function startViaCim({ command, args = [], cwd }) {
90
- if (process.platform !== 'win32') return { ok: false, how: 'cim', error: 'not-windows' };
93
+ export function startViaCim({ command, args = [], cwd, platform = process.platform, runSync = spawnSync }) {
94
+ if (platform !== 'win32') return { ok: false, how: 'cim', error: 'not-windows' };
91
95
  try {
92
96
  const ps = buildCimStartScript({ command, args, cwd });
93
97
  const encoded = Buffer.from(ps, 'utf16le').toString('base64');
94
- const out = spawnSync(powershellExe(), ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], {
98
+ const out = runSync(powershellExe(), ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], {
95
99
  encoding: 'utf8',
96
100
  windowsHide: true,
97
101
  timeout: 25_000,
@@ -110,10 +114,12 @@ export function startViaCim({ command, args = [], cwd }) {
110
114
  /**
111
115
  * 直接 spawn(Windows 上 windowsHide 会设置 CREATE_NO_WINDOW,无控制台)
112
116
  * 兜底路径:父进程是调用者,调用者退出后父 PID 消失。
117
+ *
118
+ * `spawnFn` 可注入,用来覆盖 spawn 抛异常的分支。
113
119
  */
114
- export function startHidden({ command, args = [], cwd }) {
120
+ export function startHidden({ command, args = [], cwd, spawnFn = spawn }) {
115
121
  try {
116
- const child = spawn(command, args, {
122
+ const child = spawnFn(command, args, {
117
123
  cwd: cwd ?? path.dirname(command),
118
124
  detached: true,
119
125
  stdio: 'ignore',