@andy.ian/dsh-homing 2.2.2 → 2.3.1

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.
@@ -71,6 +71,10 @@ export function createRestartFlow({
71
71
  setRestarting(true);
72
72
  setStopping(true);
73
73
  persist();
74
+ // 注意:这里不用「在 try 里 return、finally 清理」的写法。
75
+ // 那种写法下 finally 永远带着 pending return 退出,V8 会记成一个永远走不到的
76
+ // 分支(覆盖率卡在 98%)。改成先算结果、最后统一返回,行为完全一致。
77
+ let result;
74
78
  try {
75
79
  log('开始重启:终止 DSH 进程');
76
80
  await killDsh();
@@ -79,29 +83,39 @@ export function createRestartFlow({
79
83
  const upgrade = await waitForUpgrade();
80
84
  if (upgrade && upgrade.upgrading) log('检测到升级进行中,等待安装完成');
81
85
 
82
- log('启动 DSH');
83
- setChild(launch());
86
+ // 安装器可能已经把 DSH 拉起来了(electron-updater 安装完会自动启动应用),
87
+ // 先探一次,避免再启动一个实例。
88
+ const beforeLaunch = await probe();
89
+ if (beforeLaunch && beforeLaunch.running) {
90
+ log('DSH 已恢复(启动步骤由安装器完成),跳过启动');
91
+ result = { ok: true, pids: beforeLaunch.pids ?? [] };
92
+ } else {
93
+ log('启动 DSH');
94
+ setChild(launch());
84
95
 
85
- const deadline = now() + deadlineMs;
86
- while (now() < deadline) {
87
- await sleep(pollMs);
88
- const info = await probe();
89
- if (info && info.running) {
90
- log('重启完成:DSH 已恢复(PID ' + (info.pids ?? []).join(',') + ')');
91
- return { ok: true, pids: info.pids ?? [] };
96
+ const deadline = now() + deadlineMs;
97
+ result = { ok: false, error: 'dsh-not-back' };
98
+ while (now() < deadline) {
99
+ await sleep(pollMs);
100
+ const info = await probe();
101
+ if (info && info.running) {
102
+ log('重启完成:DSH 已恢复(PID ' + (info.pids ?? []).join(',') + ')');
103
+ result = { ok: true, pids: info.pids ?? [] };
104
+ break;
105
+ }
92
106
  }
107
+ if (!result.ok) log('重启后 ' + Math.round(deadlineMs / 1000) + ' 秒内 DSH 未恢复');
93
108
  }
94
- log('重启后 ' + Math.round(deadlineMs / 1000) + ' 秒内 DSH 未恢复');
95
- return { ok: false, error: 'dsh-not-back' };
96
109
  } catch (error) {
97
110
  log('重启失败:' + (error?.message ?? String(error)));
98
- return { ok: false, error: error?.message ?? String(error) };
111
+ result = { ok: false, error: error?.message ?? String(error) };
99
112
  } finally {
100
113
  inFlight = false;
101
114
  setRestarting(false);
102
115
  setStopping(false);
103
116
  persist();
104
117
  }
118
+ return result;
105
119
  }
106
120
 
107
121
  return {
@@ -20,7 +20,7 @@ export function parseVersion(text) {
20
20
  minor: Number(match[2]),
21
21
  patch: Number(match[3]),
22
22
  pre: match[4] ? Number(match[4]) : 0,
23
- raw: String(text ?? ''),
23
+ raw: String(text),
24
24
  };
25
25
  }
26
26
 
@@ -70,3 +70,120 @@ export function decideUpgrade({ installerRunning, pendingFileName, installedVers
70
70
  }
71
71
  return { upgrading: true, reason: 'pending-newer' };
72
72
  }
73
+
74
+ /**
75
+ * 是否真的应该「为升级而等待」(阻塞重启/拉起)。
76
+ *
77
+ * 只有两种情况值得等:
78
+ * 1. 安装器进程正在跑(installer-running)—— electron-updater 会替换文件并自行拉起应用;
79
+ * 2. 可执行文件暂时不存在(exeMissing)—— 正在被覆盖,此刻拉起也没有东西可启动。
80
+ *
81
+ * 仅仅是「下载好了更新包」(pending-newer / pending-fresh)不阻塞:
82
+ * 下载 ≠ 安装。被强制结束的 DSH 不会自己去运行安装器,等下去没有任何东西会恢复 DSH。
83
+ * 真实事故:2026-11-14 20:07 点强制重启后,DSH 被杀,守护进程因为 pending-newer
84
+ * 一直等安装完成(最长 30 分钟),DSH 实际是用户手动点开的。
85
+ *
86
+ * @param {object} input
87
+ * @param {boolean} [input.upgrading] decideUpgrade 的结论
88
+ * @param {string} [input.reason] decideUpgrade 的原因
89
+ * @param {boolean} [input.exeMissing] 可执行文件当前是否缺失
90
+ * @returns {boolean}
91
+ */
92
+ export function shouldWaitForUpgrade({ upgrading, reason, exeMissing = false } = {}) {
93
+ if (exeMissing) return true;
94
+ if (!upgrading) return false;
95
+ return reason === 'installer-running';
96
+ }
97
+
98
+ /**
99
+ * 从 `reg query ...Uninstall /s /f <名字> /v DisplayVersion` 的输出里挑出本产品的版本。
100
+ *
101
+ * 为什么不能直接取第一个 DisplayVersion:`/f` 匹配的是数据里出现该字符串的任意项,
102
+ * 本机实测同一份输出里混着 3.2.21、0.2.2-rc.3、1.0 三个版本(不同产品的卸载项),
103
+ * 取第一个会得到完全无关的版本号。
104
+ *
105
+ * 策略:按 HKEY 分块,优先选 InstallLocation 与 DSH 安装目录一致的块;
106
+ * 都不匹配时退回到"看起来属于 DSH"的第一块,最后才是第一个版本号。
107
+ *
108
+ * @param {string} output - reg.exe 的 stdout
109
+ * @param {string} [exePath] - DSH 的可执行文件路径(用于匹配 InstallLocation)
110
+ * @returns {string} 版本号,找不到返回空串
111
+ */
112
+ export function pickDisplayVersion(output, exePath) {
113
+ const text = String(output ?? '');
114
+ if (text.trim() === '') return '';
115
+ const exeDir = (() => {
116
+ const raw = String(exePath ?? '').trim();
117
+ if (raw === '') return '';
118
+ const cut = raw.replace(/[\\/][^\\/]+$/u, '');
119
+ // 统一成反斜杠再比较:调用方给的可能是 C:/a/b.exe,注册表里是 C:\a\b.exe
120
+ return cut.toLowerCase().replace(/\//gu, '\\').replace(/\\+$/u, '');
121
+ })();
122
+
123
+ const blocks = [];
124
+ let current = null;
125
+ for (const line of text.split(/\r?\n/u)) {
126
+ const keyMatch = /^(HKEY_[^ ]+)/iu.exec(line.trim());
127
+ if (keyMatch) {
128
+ current = { key: keyMatch[1], version: '', location: '' };
129
+ blocks.push(current);
130
+ continue;
131
+ }
132
+ const versionMatch = /DisplayVersion\s+REG_SZ\s+(\S+)/iu.exec(line);
133
+ if (versionMatch && current) current.version = versionMatch[1].trim();
134
+ const locationMatch = /InstallLocation\s+REG_SZ\s+(.+)$/iu.exec(line);
135
+ if (locationMatch && current) current.location = locationMatch[1].trim();
136
+ }
137
+ const withVersion = blocks.filter((block) => block.version !== '');
138
+ if (withVersion.length === 0) {
139
+ // 输出结构异常时退回整体正则,至少不丢信息
140
+ return (/DisplayVersion\s+REG_SZ\s+(\S+)/iu.exec(text)?.[1] ?? '').trim();
141
+ }
142
+ if (exeDir !== '') {
143
+ const sameInstall = withVersion.find((block) => {
144
+ const location = block.location.toLowerCase().replace(/\//gu, '\\').replace(/\\+$/u, '');
145
+ return location !== '' && (location === exeDir || exeDir.startsWith(location) || location.startsWith(exeDir));
146
+ });
147
+ if (sameInstall) return sameInstall.version;
148
+ }
149
+ return withVersion[0].version;
150
+ }
151
+
152
+ /**
153
+ * 从 `reg query ...Uninstall /s /f <名字>` 的输出里,找出属于指定 exe 的卸载项键名。
154
+ *
155
+ * 为什么要这一步:同一份输出里会出现多个含「DeepSeek Harness」的卸载项,
156
+ * 而 DisplayVersion 各不相同(本机就有 3.2.21 / 0.2.2-rc.3 / 1.0)。
157
+ * 只有 InstallLocation / UninstallString / DisplayIcon 指向这个安装目录的,才是本产品。
158
+ *
159
+ * @param {string} output - reg.exe 的 stdout
160
+ * @param {string} [exePath] - DSH 的可执行文件路径
161
+ * @returns {string} 键名,找不到返回空串
162
+ */
163
+ export function pickInstallKey(output, exePath) {
164
+ const text = String(output ?? '');
165
+ // 统一成反斜杠再比较:调用方传进来的 exePath 可能是 C:/a/b.exe,注册表里是 C:\a\b.exe
166
+ const normalize = (value) => String(value ?? '').trim().toLowerCase().replace(/\//gu, '\\').replace(/\\+$/u, '');
167
+ const exe = normalize(exePath);
168
+ if (text.trim() === '' || exe === '') return '';
169
+ const exeDir = exe.replace(/\\[^\\]+$/u, '');
170
+
171
+ let current = null;
172
+ const blocks = [];
173
+ for (const line of text.split(/\r?\n/u)) {
174
+ const keyMatch = /^(HKEY_[^ ]+)/iu.exec(line.trim());
175
+ if (keyMatch) {
176
+ current = { key: keyMatch[1], paths: [] };
177
+ blocks.push(current);
178
+ continue;
179
+ }
180
+ if (current === null) continue;
181
+ const valueMatch = /(?:InstallLocation|UninstallString|QuietUninstallString|DisplayIcon)\s+REG_(?:SZ|EXPAND_SZ)\s+(.+)$/iu.exec(line);
182
+ if (valueMatch) {
183
+ const value = normalize(String(valueMatch[1]).replace(/"/gu, ''));
184
+ if (value !== '') current.paths.push(value);
185
+ }
186
+ }
187
+ const hit = blocks.find((block) => block.paths.some((value) => value.startsWith(exeDir) || value.includes(exeDir)));
188
+ return hit?.key ?? '';
189
+ }
@@ -38,7 +38,7 @@ import http from 'node:http'
38
38
  import { spawn, spawnSync } from 'node:child_process'
39
39
  import { fileURLToPath } from 'node:url'
40
40
  import { rootOf, authorizeRestart, isInManagedTree } from './lib/process-tree.mjs'
41
- import { decideUpgrade } from './lib/update-state.mjs'
41
+ import { decideUpgrade, shouldWaitForUpgrade, pickDisplayVersion, pickInstallKey } from './lib/update-state.mjs'
42
42
  import { startHidden, startViaCim, ancestorMatches, chainNames } from './lib/detach.mjs'
43
43
  import { systemExe, powershellExe } from '../../lib/exec-path.mjs'
44
44
  import { createLogWriter } from '../../lib/log-file.mjs'
@@ -444,9 +444,31 @@ function pendingPackage(cacheDir) {
444
444
  }
445
445
  }
446
446
 
447
- let installedVersionCache = null
447
+ /**
448
+ * 已安装的 DSH 版本。
449
+ *
450
+ * 必须按 exe 的 mtime/size 失效缓存:DSH 会自我升级(electron-updater 替换 exe),
451
+ * 而守护进程是长驻进程。旧实现把版本号永久缓存一次,于是升级后它仍认为装的是老版本,
452
+ * 把「与已安装版本相同的残留安装包」当成新版本,进而无限期「等待升级」。
453
+ * 2026-11-14 事故即此:守护进程 11-08 启动时缓存了老版本,11-13 升级到 0.2.2-rc.3
454
+ * 后缓存没有更新,重启时就一直停在 pending-newer。
455
+ */
456
+ let installedVersionCache = { key: '', version: null }
457
+
458
+ function installedVersionCacheKey() {
459
+ if (!exePath) return ''
460
+ try {
461
+ const stat = fs.statSync(exePath)
462
+ return `${stat.mtimeMs}:${stat.size}`
463
+ } catch {
464
+ return ''
465
+ }
466
+ }
467
+
448
468
  function installedVersion() {
449
- if (installedVersionCache !== null) return installedVersionCache
469
+ const key = installedVersionCacheKey()
470
+ if (installedVersionCache.version !== null && installedVersionCache.key === key) return installedVersionCache.version
471
+ let version = null
450
472
  // 纯 Node 读取:app.asar 头部的 package.json(含 rc 后缀,如 0.2.1-rc.5)
451
473
  try {
452
474
  const asar = path.join(exePath ? path.dirname(exePath) : '', 'resources', 'app.asar')
@@ -462,42 +484,70 @@ function installedVersion() {
462
484
  if (entry && entry.size > 0) {
463
485
  const buf = Buffer.alloc(entry.size)
464
486
  fs.readSync(fd, buf, 0, entry.size, 16 + headerSize + Number(entry.offset))
465
- const json = JSON.parse(buf.toString('utf8'))
466
- if (json.version) installedVersionCache = String(json.version).trim()
487
+ const raw = buf.toString('utf8')
488
+ // 这个构建把 package.json 存成了 `");\n{...` 的模块片段,从第一个 { 开始解析
489
+ const json = JSON.parse(raw.slice(raw.indexOf('{')))
490
+ if (json.version) version = String(json.version).trim()
467
491
  }
468
492
  } finally {
469
493
  fs.closeSync(fd)
470
494
  }
471
495
  } catch {
472
- installedVersionCache = null
496
+ version = null
473
497
  }
474
498
  // 兜底:注册表里的 DisplayVersion(reg.exe,不是 PowerShell)
475
- if (!installedVersionCache) {
476
- try {
477
- const out = spawnSync(REG, ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall', '/s', '/f', 'DeepSeek Harness', '/v', 'DisplayVersion'], { encoding: 'utf8', timeout: 5000, windowsHide: true })
478
- installedVersionCache = (/DisplayVersion\s+REG_SZ\s+(\S+)/u.exec(out.stdout ?? '')?.[1] ?? '').trim() || null
479
- } catch {
480
- installedVersionCache = null
499
+ if (!version) {
500
+ version = installedVersionFromRegistry()
501
+ }
502
+ installedVersionCache = { key, version }
503
+ return version
504
+ }
505
+
506
+ /** 从卸载项注册表读版本:先按安装路径找到属于这个 exe 的键,再读它的 DisplayVersion。 */
507
+ function installedVersionFromRegistry() {
508
+ const root = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
509
+ try {
510
+ const listed = spawnSync(REG, ['query', root, '/s', '/f', 'DeepSeek Harness'], { encoding: 'utf8', timeout: 8000, windowsHide: true })
511
+ const key = pickInstallKey(listed.stdout ?? '', exePath)
512
+ if (key !== '') {
513
+ const detail = spawnSync(REG, ['query', key, '/v', 'DisplayVersion'], { encoding: 'utf8', timeout: 5000, windowsHide: true })
514
+ const version = pickDisplayVersion(detail.stdout ?? '', exePath)
515
+ if (version !== '') return version
481
516
  }
517
+ // 没定位到键时退回按版本挑(可能挑到别的产品,只作日志参考)
518
+ const fallback = spawnSync(REG, ['query', root, '/s', '/f', 'DeepSeek Harness', '/v', 'DisplayVersion'], { encoding: 'utf8', timeout: 8000, windowsHide: true })
519
+ return pickDisplayVersion(fallback.stdout ?? '', exePath) || null
520
+ } catch {
521
+ return null
482
522
  }
483
- return installedVersionCache
484
523
  }
485
524
 
525
+ const UPGRADE_WAIT_MS = 10 * 60_000
526
+
486
527
  async function waitForUpgrade() {
487
528
  const cacheDir = updaterCacheDir()
529
+ const deadline = Date.now() + UPGRADE_WAIT_MS
488
530
  let announced = false
489
- for (let i = 0; i < 900; i += 1) {
531
+ for (;;) {
490
532
  const exeMissing = exePath ? !fs.existsSync(exePath) : false
533
+ const installerRunning = cacheDir ? installerProcessRunning(cacheDir) : false
491
534
  const pending = cacheDir ? pendingPackage(cacheDir) : null
492
535
  const verdict = decideUpgrade({
493
- installerRunning: cacheDir ? installerProcessRunning(cacheDir) : false,
536
+ installerRunning,
494
537
  pendingFileName: pending?.fileName ?? null,
495
538
  installedVersion: installedVersion(),
496
539
  pendingAgeSeconds: pending?.ageSeconds ?? null,
497
540
  })
498
- if (!verdict.upgrading && !exeMissing) {
499
- if (announced) log('升级结束(' + verdict.reason + '),继续拉起流程')
500
- return { upgrading: announced, reason: verdict.reason }
541
+ // 只有「安装器真的在跑」或「exe 正被替换」才值得等。
542
+ // 仅仅是下载了更新包(pending-newer)不阻塞:没有安装器,等下去 DSH 也不会自己起来。
543
+ if (!shouldWaitForUpgrade({ upgrading: verdict.upgrading, reason: verdict.reason, exeMissing })) {
544
+ if (announced) log('升级结束(' + (exeMissing ? 'exe-missing' : verdict.reason) + '),继续拉起流程')
545
+ else if (verdict.upgrading) log('发现已下载的更新包(' + verdict.reason + ')但安装器未运行,不阻塞拉起')
546
+ return { upgrading: false, reason: verdict.reason }
547
+ }
548
+ if (Date.now() >= deadline) {
549
+ log('升级等待超时(' + Math.round(UPGRADE_WAIT_MS / 60_000) + ' 分钟),按未升级处理并继续拉起')
550
+ return { upgrading: true, reason: 'timeout' }
501
551
  }
502
552
  if (!announced) {
503
553
  announced = true
@@ -505,8 +555,6 @@ async function waitForUpgrade() {
505
555
  }
506
556
  await new Promise((resolve) => setTimeout(resolve, 2000))
507
557
  }
508
- log('升级检测超时(30 分钟),按未升级处理')
509
- return { upgrading: true, reason: 'timeout' }
510
558
  }
511
559
 
512
560
  function launch() {
@@ -21,11 +21,14 @@ export function createPolicyRunner({
21
21
  specPath,
22
22
  log = () => {},
23
23
  audit = () => {},
24
+ /** 测试缝:直接提供配置读取函数,用来覆盖「配置读取返回异常形状」的兜底分支 */
25
+ readSpec,
24
26
  }) {
25
27
  // 统一成 { ok, spec, errors, source } 形状:内联 spec 也要包一层,否则 specNow() 取不到
26
- const currentSpec = specPath
27
- ? createSpecWatcher(specPath)
28
- : () => (spec ? { ok: true, spec, errors: [], source: 'inline' } : { ok: true, spec: DEFAULT_SPEC, errors: [], source: 'default' });
28
+ const currentSpec = readSpec
29
+ ?? (specPath
30
+ ? createSpecWatcher(specPath)
31
+ : () => (spec ? { ok: true, spec, errors: [], source: 'inline' } : { ok: true, spec: DEFAULT_SPEC, errors: [], source: 'default' }));
29
32
 
30
33
  let state = idleState('未排队');
31
34
  let inFlight = false;
@@ -85,7 +88,7 @@ export function createPolicyRunner({
85
88
  return input.busyNow;
86
89
  }
87
90
 
88
- async function executeTrigger(activeGeneration) {
91
+ async function executeTrigger() {
89
92
  const spec0 = specNow();
90
93
  inFlight = true;
91
94
  try {
@@ -102,7 +105,8 @@ export function createPolicyRunner({
102
105
  attempt += 1;
103
106
  log('触发失败,' + spec0.retry.delayMs + 'ms 后重试(第 ' + attempt + ' 次)');
104
107
  await new Promise((resolve) => setTimeout(resolve, spec0.retry.delayMs));
105
- if (generation !== activeGeneration) return null;
108
+ // 这里不需要再检查 generation:queue/force/cancel 在 inFlight 期间都不会改动它
109
+ // (queue 和 force 直接返回 busy,cancel 要求 state.active),所以检查是死代码。
106
110
  const recheck = recheckBeforeTrigger(state, spec0, readInput(), 'recheckBeforeRetry');
107
111
  if (recheck.cancelled) {
108
112
  // 取消本次触发,但排队不能就此结束:重新拉起调度循环继续等安静窗口
@@ -29,13 +29,14 @@ export function createRestartService({
29
29
  controlToken = () => '',
30
30
  statusTimeoutMs = 3000,
31
31
  postTimeoutMs = 5000,
32
+ requestFn = http.request,
32
33
  } = {}) {
33
34
  const portOf = () => (typeof port === 'function' ? port() : port)
34
35
 
35
36
  /** GET /status(失败返回 null,调用方按"守护进程未运行"处理) */
36
37
  function status() {
37
38
  return new Promise((resolve) => {
38
- const request = http.request({ host, port: portOf(), path: '/status', method: 'GET', timeout: statusTimeoutMs, agent: false }, (up) => {
39
+ const request = requestFn({ host, port: portOf(), path: '/status', method: 'GET', timeout: statusTimeoutMs, agent: false }, (up) => {
39
40
  const chunks = [];
40
41
  up.on('data', (chunk) => chunks.push(chunk));
41
42
  up.on('end', () => resolve(readJson(up, chunks)));
@@ -49,7 +50,7 @@ export function createRestartService({
49
50
  /** GET /health(轻量探活:不 spawn 进程、不读文件) */
50
51
  function health() {
51
52
  return new Promise((resolve) => {
52
- const request = http.request({ host, port: portOf(), path: '/health', method: 'GET', timeout: statusTimeoutMs, agent: false }, (up) => {
53
+ const request = requestFn({ host, port: portOf(), path: '/health', method: 'GET', timeout: statusTimeoutMs, agent: false }, (up) => {
53
54
  const chunks = [];
54
55
  up.on('data', (chunk) => chunks.push(chunk));
55
56
  up.on('end', () => resolve(readJson(up, chunks)));
@@ -63,7 +64,7 @@ export function createRestartService({
63
64
  /** POST 任意路径;返回 { ok, body, error? },不抛异常 */
64
65
  function post(pathAndQuery) {
65
66
  return new Promise((resolve) => {
66
- const request = http.request({
67
+ const request = requestFn({
67
68
  host,
68
69
  port: portOf(),
69
70
  path: pathAndQuery,
@@ -44,11 +44,17 @@ export function shouldRestartDaemon({
44
44
  return recent.length < maxRestarts
45
45
  }
46
46
 
47
- function spawnDaemonDetached({ pluginRoot }) {
47
+ /**
48
+ * 拉起守护进程(默认实现)。
49
+ *
50
+ * `spawnFn` / `portOf` / `resolveEntry` 可注入:真实调用会启动一个守护进程,
51
+ * 测试里必须能替换掉,否则既不能覆盖失败分支,也会污染机器上的真实进程。
52
+ */
53
+ export function spawnDaemonDetached({ pluginRoot, spawnFn = spawn, portOf = resolveRestartPort, resolveEntry = findNodeRuntime }) {
48
54
  return new Promise((resolve) => {
49
55
  try {
50
56
  const entry = path.join(pluginRoot, 'bin', 'restart-daemon.mjs')
51
- const child = spawn(findNodeRuntime(), [entry, '--detach', '--control', String(resolveRestartPort())], {
57
+ const child = spawnFn(resolveEntry(), [entry, '--detach', '--control', String(portOf())], {
52
58
  detached: true,
53
59
  stdio: 'ignore',
54
60
  windowsHide: true,