dsh-notify-say 0.4.69 → 0.4.72

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/lib/index.js CHANGED
@@ -84,7 +84,7 @@
84
84
  * 主会话重新进入 running(用户已开始新一轮)则取消挂起。
85
85
  * 失败一律 fail-visible:判定异常时走主任务分支照常播报,不静默用户。
86
86
  */
87
- import { spawn } from 'node:child_process';
87
+ import { spawn, execFileSync } from 'node:child_process';
88
88
  import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync } from 'node:fs';
89
89
  import { fileURLToPath } from 'node:url';
90
90
  import { dirname, join } from 'node:path';
@@ -316,7 +316,7 @@ function normalizeConfig(raw) {
316
316
  for (const k of ['notifyOnComplete', 'notifyOnError', 'notifyOnBlocked', 'notifyOnAborted',
317
317
  'notifyOnApproval', 'notifyOnQuestion', 'voice', 'subagents', 'idleGate',
318
318
  // v0.4.68:子代理出错单独开关(完成可以合并,错误不能合并掉)
319
- 'notifyOnSubagentError', 'notifyOnMaxTokens',
319
+ 'notifyOnSubagentError', 'notifyOnMaxTokens', 'toastJumpSession',
320
320
  // v0.4.2
321
321
  'showToast', 'jumpWhenBackground', 'jumpWhenForeground', 'multiJumpRule',
322
322
  // v0.4.3:开发开关
@@ -690,6 +690,7 @@ export function effectiveForClient(c) {
690
690
  notifyOnError: g.notifyOnError,
691
691
  notifyOnSubagentError: g.notifyOnSubagentError,
692
692
  notifyOnMaxTokens: g.notifyOnMaxTokens,
693
+ toastJumpSession: g.toastJumpSession,
693
694
  notifyOnBlocked: g.notifyOnBlocked,
694
695
  notifyOnAborted: g.notifyOnAborted,
695
696
  notifyOnApproval: g.notifyOnApproval,
@@ -1080,6 +1081,10 @@ export function apply(ctx, config) {
1080
1081
  // 播报前现读配置:让 CLI/GUI 改的值立即生效,无需重载宿主。
1081
1082
  refreshConfig();
1082
1083
 
1084
+ // v0.4.70:本条通知对应的会话 id(精准跳转用)。
1085
+ // 只在开关开着且协议已注册时才会被 args 构造器采用;否则降级 dsh://open。
1086
+ const notifySid = session && session.id !== undefined ? String(session.id) : '';
1087
+
1083
1088
  // Toast 第三行:项目名(v0.4.62)。
1084
1089
  //
1085
1090
  // 只在"标题里没包含它"时才给 —— 否则标题已经是「优化0Deepseek…」,
@@ -1187,7 +1192,7 @@ export function apply(ctx, config) {
1187
1192
  ];
1188
1193
  if (vVoice) ttsArgs.push('-VoiceName', vVoice);
1189
1194
  // TTS 自己会出声,所以 notify.ps1 只负责弹窗(-NoSound)
1190
- if (wantToast) spawnNotify(notifyArgs(psKind, title, body, true, false, detail), psKind);
1195
+ if (wantToast) spawnNotify(notifyArgs(psKind, title, body, true, false, detail, notifySid), psKind);
1191
1196
  spawnTts(ttsArgs, psKind);
1192
1197
  return;
1193
1198
  }
@@ -1206,7 +1211,7 @@ export function apply(ctx, config) {
1206
1211
  // **不传 -Voice/-Mode**,并且 ps1 侧见到 -SystemSound 就跳过语音池
1207
1212
  // (否则 -Kind fail 会先选中 fail 池的 wav,永远走不到系统音效)。
1208
1213
  if (wantSound && source === 'system') {
1209
- const a = baseNotifyArgs(psKind, title, body, false, !wantToast, detail);
1214
+ const a = baseNotifyArgs(psKind, title, body, false, !wantToast, detail, notifySid);
1210
1215
  const explicitTone = kindOr(cfg.kindSystemSound, aKind, '');
1211
1216
  a.push('-SystemSound', explicitTone || 'auto');
1212
1217
  spawnNotify(a);
@@ -1222,7 +1227,7 @@ export function apply(ctx, config) {
1222
1227
  const kind = audioKindOf(psKind);
1223
1228
  const file = resolveCustomFile(kind, cfg);
1224
1229
  if (file) {
1225
- const a = baseNotifyArgs(psKind, title, body, false, !wantToast, detail);
1230
+ const a = baseNotifyArgs(psKind, title, body, false, !wantToast, detail, notifySid);
1226
1231
  a.push('-CustomFile', file);
1227
1232
  // v0.4.16:自定义音频的"标准化"是**可选**的。
1228
1233
  //
@@ -1236,7 +1241,7 @@ export function apply(ctx, config) {
1236
1241
  }
1237
1242
  // 没配文件:不要静默无声,退到系统提示音(audio-source 的回退链已算过,
1238
1243
  // 但这里再兜一次,防止 effectiveSource 的 hasCustomFile 判断与读取不一致)
1239
- const a2 = baseNotifyArgs(psKind, title, body, false, !wantToast, detail);
1244
+ const a2 = baseNotifyArgs(psKind, title, body, false, !wantToast, detail, notifySid);
1240
1245
  a2.push('-SystemSound', 'auto');
1241
1246
  spawnNotify(a2);
1242
1247
  return;
@@ -1245,11 +1250,13 @@ export function apply(ctx, config) {
1245
1250
  // ── 其余音源(bundled)走 dsh-notify.ps1 ──────────────────────────────
1246
1251
  // 第 5 个参数是 soundOnly(v0.4.59)。原来这里传的是 source,
1247
1252
  // 而 notifyArgs 只认 4 个参数 —— 那个多传的值一直被静默忽略。
1248
- spawnNotify(notifyArgs(psKind, title, body, !wantSound, !wantToast, detail), psKind);
1253
+ spawnNotify(notifyArgs(psKind, title, body, !wantSound, !wantToast, detail, notifySid), psKind);
1249
1254
  }
1250
1255
 
1251
1256
  /** 只有基础参数的 notify 调用(供 system 音源拼装)。 */
1252
- function baseNotifyArgs(psKind, title, body, noSound, soundOnly, detail) {
1257
+ function baseNotifyArgs(psKind, title, body, noSound, soundOnly, detail, sessionIdForArgs) {
1258
+ // v0.4.70:只在协议可用时才把会话 id 传给 ps1;否则继续用 dsh://open(降级)。
1259
+ const jumpSid = (cfg.toastJumpSession && jumpProtoState === 'ok' && sessionIdForArgs) ? sessionIdForArgs : '';
1253
1260
  const args = [
1254
1261
  '-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-File',
1255
1262
  SCRIPT_PATH, '-Kind', psKind, '-Title', title, '-Body', body,
@@ -1266,11 +1273,15 @@ export function apply(ctx, config) {
1266
1273
  // v0.4.34:把日志级别传给 ps1(它决定要不要把标题/正文写进日志)
1267
1274
  args.push('-LogLevel', cfg.logLevel === 'debug' ? 'debug' : 'info');
1268
1275
  args.push('-Volume', String(cfg.volume));
1276
+ // v0.4.70:会话 id 传给 ps1,让它写进 Toast 的 launch(精准跳转用)。
1277
+ if (jumpSid) args.push('-SessionId', String(jumpSid));
1269
1278
  return args;
1270
1279
  }
1271
1280
 
1272
1281
  /** 构造 dsh-notify.ps1 的参数。noSound=true 表示只弹窗不出声。 */
1273
- function notifyArgs(psKind, title, body, noSound, soundOnly, detail) {
1282
+ function notifyArgs(psKind, title, body, noSound, soundOnly, detail, sessionIdForArgs) {
1283
+ // v0.4.70:只在协议可用时才把会话 id 传给 ps1;否则继续用 dsh://open(降级)。
1284
+ const jumpSid = (cfg.toastJumpSession && jumpProtoState === 'ok' && sessionIdForArgs) ? sessionIdForArgs : '';
1274
1285
  const args = [
1275
1286
  '-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-File',
1276
1287
  SCRIPT_PATH, '-Kind', psKind, '-Title', title, '-Body', body,
@@ -1378,6 +1389,106 @@ function hasVoiceLine(psKind) {
1378
1389
  }
1379
1390
  }
1380
1391
 
1392
+ /**
1393
+ * 自定义协议名。Toast 的 launch 用它携带 session id(第 4 批)。
1394
+ *
1395
+ * 为什么不用 dsh:// —— DSH 本体是精确匹配 `dsh://open`,加参数连窗口都不拉。
1396
+ */
1397
+ const JUMP_PROTOCOL = 'dshnotify';
1398
+
1399
+ /**
1400
+ * 协议注册状态(进程内缓存,避免每次播报都查注册表)。
1401
+ *
1402
+ * unknown 还没检查过
1403
+ * ok 已注册且指向我们的处理器(可以用 dshnotify://)
1404
+ * failed 注册失败或指向别处(**必须降级到 dsh://open**)
1405
+ * off 开关关闭(用户没启用这个功能)
1406
+ */
1407
+ let jumpProtoState = 'unknown';
1408
+
1409
+ /** 待跳转的会话(Toast 点击写入,前端读取并消费)。v0.4.70 */
1410
+ let pendingJump = null;
1411
+
1412
+ /**
1413
+ * 注册自定义协议(HKCU,无需管理员)。
1414
+ *
1415
+ * 幂等:已存在且指向正确就直接标记 ok;指向别处则覆盖(那是我们的协议名)。
1416
+ *
1417
+ * @returns {boolean} 注册成功且可用
1418
+ */
1419
+ function registerJumpProtocol() {
1420
+ try {
1421
+ const handler = join(PLUGIN_ROOT, 'jump-handler.ps1');
1422
+ if (!existsSync(handler)) { jumpProtoState = 'failed'; return false; }
1423
+
1424
+ // PowerShell 路径与主脚本一致(POWERSHELL_EXE 已算好)
1425
+ const cmd = `"${POWERSHELL_EXE}" -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${handler}" "%1"`;
1426
+
1427
+ // 用 PowerShell 写注册表:避免引入额外依赖,且引号处理更稳。
1428
+ const ps = [
1429
+ `$k = 'HKCU:\\Software\\Classes\\' + '${JUMP_PROTOCOL}';`,
1430
+ 'if (-not (Test-Path $k)) { New-Item -Path $k -Force | Out-Null }',
1431
+ 'Set-ItemProperty -Path $k -Name "(default)" -Value "URL:DSH Notify Jump" -Force;',
1432
+ 'Set-ItemProperty -Path $k -Name "URL Protocol" -Value "" -Force;',
1433
+ `$c = Join-Path $k 'shell\\open\\command';`,
1434
+ 'if (-not (Test-Path $c)) { New-Item -Path $c -Force | Out-Null }',
1435
+ 'Set-ItemProperty -Path $c -Name "(default)" -Value $env:DSH_JUMP_CMD -Force;',
1436
+ ].join(' ');
1437
+
1438
+ execFileSync(POWERSHELL_EXE, [
1439
+ '-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden',
1440
+ '-Command', ps,
1441
+ ], {
1442
+ stdio: 'ignore',
1443
+ windowsHide: true,
1444
+ env: { ...process.env, DSH_JUMP_CMD: cmd },
1445
+ timeout: 15000,
1446
+ });
1447
+
1448
+ jumpProtoState = 'ok';
1449
+ appendNotifyLog(`[jump-proto] registered ${JUMP_PROTOCOL}:// -> jump-handler.ps1`);
1450
+ return true;
1451
+ } catch (e) {
1452
+ jumpProtoState = 'failed';
1453
+ appendNotifyLog(`[jump-proto] register FAILED: ` + String((e && e.message) || e).slice(0, 200));
1454
+ return false;
1455
+ }
1456
+ }
1457
+
1458
+ /**
1459
+ * 注销自定义协议(开关关闭 / 插件卸载时调用)。
1460
+ *
1461
+ * 只删自己那个键,绝不动别人的;删不掉也只记日志(不阻塞卸载)。
1462
+ */
1463
+ function unregisterJumpProtocol() {
1464
+ try {
1465
+ const ps = `$k = 'HKCU:\\Software\\Classes\\${JUMP_PROTOCOL}'; if (Test-Path $k) { Remove-Item $k -Recurse -Force }`;
1466
+ execFileSync(POWERSHELL_EXE, [
1467
+ '-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden',
1468
+ '-Command', ps,
1469
+ ], { stdio: 'ignore', windowsHide: true, timeout: 10000 });
1470
+ jumpProtoState = 'off';
1471
+ appendNotifyLog(`[jump-proto] unregistered ${JUMP_PROTOCOL}://`);
1472
+ } catch (e) {
1473
+ appendNotifyLog(`[jump-proto] unregister failed: ` + String((e && e.message) || e).slice(0, 120));
1474
+ }
1475
+ }
1476
+
1477
+ /**
1478
+ * 按当前开关同步协议状态(开着就注册,关了就注销)。
1479
+ *
1480
+ * @returns {boolean} 是否可用(决定 Toast 用哪种 launch)
1481
+ */
1482
+ function syncJumpProtocol() {
1483
+ if (!cfg.toastJumpSession) {
1484
+ if (jumpProtoState === 'ok') unregisterJumpProtocol();
1485
+ jumpProtoState = 'off';
1486
+ return false;
1487
+ }
1488
+ if (jumpProtoState === 'ok') return true;
1489
+ return registerJumpProtocol();
1490
+ }
1491
+
1381
1492
  function svc(name) {
1382
1493
  try { return ctx.get(name, false); } catch { return undefined; }
1383
1494
  }
@@ -2024,6 +2135,22 @@ function hasVoiceLine(psKind) {
2024
2135
  + `question=${cfg.notifyOnQuestion} voice=${cfg.voice}/${cfg.voiceMode} debounce=${Math.round(cfg.debounceMs / 1000)}s `
2025
2136
  + `idleGate=${cfg.idleGate} idleGateTimeout=${Math.round(cfg.idleGateTimeoutMs / 1000)}s)`);
2026
2137
 
2138
+ // ── 精准跳转:启动时同步协议注册状态(v0.4.70)────────────────────────
2139
+ //
2140
+ // 开关开着就注册 dshnotify://(HKCU,无需管理员);关着就确保已注销。
2141
+ // 注册失败会被降级为 dsh://open —— 「点了没反应」比「跳不到会话」更糟。
2142
+ try {
2143
+ // ⚠️ 必须先 refreshConfig:apply 刚跑时 cfg 还是模块初始值,
2144
+ // 用户在设置页开的 toastJumpSession 还没读进来 —— 不刷新会误判成关着
2145
+ // (2026-10-19 实测:日志出现 state=off,协议没注册)。
2146
+ refreshConfig();
2147
+ const okProto = syncJumpProtocol();
2148
+ appendNotifyLog(`[jump-proto] state=${jumpProtoState} usable=${okProto}`);
2149
+ } catch (e) {
2150
+ jumpProtoState = 'failed';
2151
+ appendNotifyLog('[jump-proto] sync failed: ' + String((e && e.message) || e));
2152
+ }
2153
+
2027
2154
  // ── 会话事件流:turn/end 记 reason + approval/asked、approval/decided 审计对 + 提问 ──
2028
2155
  ctx.on('session/event', (session, event) => {
2029
2156
  // v0.4.36:记一次"事件到达"。
@@ -2236,6 +2363,8 @@ function hasVoiceLine(psKind) {
2236
2363
  pendingDone.clear();
2237
2364
  prevStatus.clear();
2238
2365
  lastTurnEnd.clear();
2366
+ // v0.4.70:卸载时注销自定义协议,不在注册表留垃圾。
2367
+ try { if (jumpProtoState === 'ok') unregisterJumpProtocol(); } catch { /* 卸载期失败不影响退出 */ }
2239
2368
  // v0.4.63:长轮询的挂起响应也要结束掉。不做的后果是热重载后
2240
2369
  // 旧连接永远等不到响应,客户端不会再发新的 /wait(它以为还在等)。
2241
2370
  try { bridge.disposeAllWaiters(); } catch { /* 卸载期失败不影响退出 */ }
@@ -2321,11 +2450,73 @@ function hasVoiceLine(psKind) {
2321
2450
  || head === 'consume'
2322
2451
  // v0.4.63:/ack 只摘一条(前台跳转后确认),同样是写操作
2323
2452
  || head === 'ack'
2453
+ // v0.4.70:Toast 点击写入待跳转(写操作)
2454
+ || head === 'pending-jump'
2324
2455
  || head === 'diagnostics'
2325
2456
  || (head === 'voicepacks' && (/\/install\b/.test(pathname) || /\/uninstall\b/.test(pathname)))
2326
2457
  // v0.4.57:一次性自重载会 dispose 当前实例并重新求值模块,
2327
2458
  // 是不可逆副作用,按写操作处理。
2328
2459
  || head === 'reload';
2460
+ // ── 精准跳转:Toast 点击的待跳转会话(v0.4.70)────────────────
2461
+ //
2462
+ // jump-handler.ps1 收到 dshnotify://jump?session=xxx 后 POST 到这里,
2463
+ // 前端在窗口可见时 GET 并消费。
2464
+ //
2465
+ // 为什么需要它:点 Toast 走自有协议能**精确知道**是哪个会话,
2466
+ // 而 dsh://open 无法携带参数(DSH 本体硬编码精确匹配)。
2467
+ if (head === 'pending-jump') {
2468
+ const isPost = String((req && req.method) || 'GET').toUpperCase() === 'POST';
2469
+ try {
2470
+ if (isPost) {
2471
+ // 读 body(小 JSON)
2472
+ let rawBody = '';
2473
+ req.on('data', (c) => { if (rawBody.length < 4096) rawBody += c; });
2474
+ req.on('end', () => {
2475
+ try {
2476
+ const o = JSON.parse(rawBody || '{}');
2477
+ const sid = String(o.sessionId || '');
2478
+ // 白名单校验:只接受像会话 id 的字符串
2479
+ if (/^[A-Za-z0-9_-]{4,128}$/.test(sid)) {
2480
+ pendingJump = { sessionId: sid, at: Date.now() };
2481
+ appendNotifyLog(`[jump-click] session=${sid}`);
2482
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2483
+ res.end(JSON.stringify({ ok: true }));
2484
+ } else {
2485
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' });
2486
+ res.end(JSON.stringify({ ok: false, reason: 'bad-session-id' }));
2487
+ }
2488
+ } catch {
2489
+ try { res.writeHead(400); res.end('{}'); } catch { /* ignore */ }
2490
+ }
2491
+ });
2492
+ return;
2493
+ }
2494
+
2495
+ // GET:读并消费(一次性)
2496
+ const now = Date.now();
2497
+ let out = null;
2498
+ if (pendingJump && now - pendingJump.at <= 120000) {
2499
+ out = { sessionId: pendingJump.sessionId, at: pendingJump.at };
2500
+ pendingJump = null; // 消费即清,防重复跳
2501
+ appendNotifyLog(`[jump-consume] session=${out.sessionId} age=${Math.round((now - out.at) / 1000)}s`);
2502
+ } else if (pendingJump) {
2503
+ appendNotifyLog(`[jump-expired] session=${pendingJump.sessionId} `
2504
+ + `age=${Math.round((now - pendingJump.at) / 1000)}s (>120s)`);
2505
+ pendingJump = null;
2506
+ }
2507
+ if (out) {
2508
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2509
+ res.end(JSON.stringify(out));
2510
+ } else {
2511
+ res.writeHead(204, { 'cache-control': 'no-store' });
2512
+ res.end();
2513
+ }
2514
+ } catch {
2515
+ try { res.writeHead(500); res.end('{}'); } catch { /* ignore */ }
2516
+ }
2517
+ return;
2518
+ }
2519
+
2329
2520
  const guard = checkLocalOrigin(req, { write: isWriteRoute });
2330
2521
  if (!guard.ok) {
2331
2522
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-notify-say",
3
- "version": "0.4.69",
3
+ "version": "0.4.72",
4
4
  "description": "Desktop notifications for DSH Desktop that actually speak: Windows TTS out of the box (zero download), VOICEVOX voice packs optional, a selectable system-sound fallback, and an idle gate that waits for running subagents before saying the turn is done. Includes a settings-page GUI (sound source, per-event overrides, jump-back-to-session, cooldowns) and a self hot-reload for development.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,43 +1,51 @@
1
- /**
2
- * ESM loader stub:把 `node:child_process` 换成记录型假实现。
3
- *
4
- * 用途:`test/fail-route.test.mjs` 要断言 **lib/index.js 运行时到底给 ps1 传了什么参数**
5
- * (例如 error 回合是否真的传 `-Kind fail`)。若真去 spawn PowerShell:
6
- * ① 会弹 Toast / 出声,污染用户桌面;② 需要真实 SystemRoot,与同目录其他测试的
7
- * 隔离手法冲突(见踩坑 #424)。故在加载 lib 之前把这个模块注册为 loader,
8
- * 让 `spawn()` 只把参数记进 `globalThis.__SPAWN_CALLS`,不起任何进程。
9
- *
10
- * 为什么不用 monkey-patch:lib 用的是 ESM 具名导入
11
- * (`import { spawn } from 'node:child_process'`),导入绑定只读、不可重新赋值;
12
- * 只有 loader 层能在模块解析阶段替换它。
13
- *
14
- * 该文件**不是测试文件**(不以 .test. 命名),不会被 `node --test` 当用例执行。
15
- */
16
- export async function resolve(specifier, context, nextResolve) {
17
- if (specifier === 'node:child_process') {
18
- return { url: 'stub:child_process', shortCircuit: true };
19
- }
20
- return nextResolve(specifier, context);
21
- }
22
-
23
- export async function load(url, context, nextLoad) {
24
- if (url === 'stub:child_process') {
25
- const source = `
26
- // 记录每一次 spawn 的 (file, args) 供断言;返回一个不会真的启动进程的假句柄。
27
- export function spawn(file, args, options) {
28
- globalThis.__SPAWN_CALLS = globalThis.__SPAWN_CALLS || [];
29
- globalThis.__SPAWN_CALLS.push({ file, args: Array.isArray(args) ? args.slice() : args, options });
30
- return {
31
- pid: 424242,
32
- once() { return this; },
33
- on() { return this; },
34
- kill() { return true; },
35
- unref() { return this; },
36
- };
37
- }
38
- export default { spawn };
39
- `;
40
- return { format: 'module', shortCircuit: true, source };
41
- }
42
- return nextLoad(url, context);
43
- }
1
+ /**
2
+ * ESM loader stub:把 `node:child_process` 换成记录型假实现。
3
+ *
4
+ * 用途:`test/fail-route.test.mjs` 要断言 **lib/index.js 运行时到底给 ps1 传了什么参数**
5
+ * (例如 error 回合是否真的传 `-Kind fail`)。若真去 spawn PowerShell:
6
+ * ① 会弹 Toast / 出声,污染用户桌面;② 需要真实 SystemRoot,与同目录其他测试的
7
+ * 隔离手法冲突(见踩坑 #424)。故在加载 lib 之前把这个模块注册为 loader,
8
+ * 让 `spawn()` 只把参数记进 `globalThis.__SPAWN_CALLS`,不起任何进程。
9
+ *
10
+ * 为什么不用 monkey-patch:lib 用的是 ESM 具名导入
11
+ * (`import { spawn } from 'node:child_process'`),导入绑定只读、不可重新赋值;
12
+ * 只有 loader 层能在模块解析阶段替换它。
13
+ *
14
+ * 该文件**不是测试文件**(不以 .test. 命名),不会被 `node --test` 当用例执行。
15
+ */
16
+ export async function resolve(specifier, context, nextResolve) {
17
+ if (specifier === 'node:child_process') {
18
+ return { url: 'stub:child_process', shortCircuit: true };
19
+ }
20
+ return nextResolve(specifier, context);
21
+ }
22
+
23
+ export async function load(url, context, nextLoad) {
24
+ if (url === 'stub:child_process') {
25
+ const source = `
26
+ // 记录每一次 spawn 的 (file, args) 供断言;返回一个不会真的启动进程的假句柄。
27
+ export function spawn(file, args, options) {
28
+ globalThis.__SPAWN_CALLS = globalThis.__SPAWN_CALLS || [];
29
+ globalThis.__SPAWN_CALLS.push({ file, args: Array.isArray(args) ? args.slice() : args, options });
30
+ return {
31
+ pid: 424242,
32
+ once() { return this; },
33
+ on() { return this; },
34
+ kill() { return true; },
35
+ unref() { return this; },
36
+ };
37
+ }
38
+ // v0.4.70:插件新增 execFileSync(注册自定义协议时同步调 PowerShell)。
39
+ // 桩里也要提供,否则 import { execFileSync } 会在模块链接阶段报
40
+ // "does not provide an export named execFileSync"。同样只记录、不起进程。
41
+ export function execFileSync(file, args, options) {
42
+ globalThis.__SPAWN_CALLS = globalThis.__SPAWN_CALLS || [];
43
+ globalThis.__SPAWN_CALLS.push({ file, args: Array.isArray(args) ? args.slice() : args, options, sync: true });
44
+ return Buffer.from('');
45
+ }
46
+ export default { spawn, execFileSync };
47
+ `;
48
+ return { format: 'module', shortCircuit: true, source };
49
+ }
50
+ return nextLoad(url, context);
51
+ }
@@ -99,21 +99,31 @@ test('T9: consume 取走整个队列并清空,同时保留旧字段', () => {
99
99
  });
100
100
 
101
101
  // ══ T10-T12:规则选择 ═══════════════════════════════════════════════════
102
- test('T10: pickJumpTarget 三种规则 + 单会话不受规则影响', () => {
102
+ test('T10: pickJumpTarget 规则 + 单会话不受规则影响', () => {
103
103
  const fn = grab(CLIENT, 'function pickJumpTarget(list, rule) {', '\n }\n');
104
104
  assert.match(fn, /if \(list\.length === 1\) return list\[0\]/, '单会话必须直接返回它');
105
105
  assert.match(fn, /if \(rule === 'none'\) return null/, 'none 返回 null');
106
106
  assert.match(fn, /if \(rule === 'latest'\) return sorted\[sorted\.length - 1\]/, 'latest 取末尾');
107
- assert.match(fn, /return sorted\[0\]/, '默认(含未知规则)取最早');
107
+ assert.match(fn, /return sorted\[0\]/, 'earliest 取最早(也是 clicked 没命中时的兜底)');
108
108
  });
109
109
 
110
- test('T11: 默认规则是 earliest(服务端与客户端一致)', () => {
111
- assert.match(SCHEMA, /multiJumpRule: 'earliest'/, 'FIELD_DEFAULTS 必须是 earliest');
110
+ test('T11: 默认规则是 clicked(点哪个跳哪个)', () => {
111
+ // v0.4.70:默认从 earliest 改为 clicked —— 多会话时用户点的是具体某个 Toast,
112
+ // 按时间排序猜必然猜错。clicked 用 Toast 自带的 session id,精确。
113
+ assert.match(SCHEMA, /multiJumpRule: 'clicked'/, 'FIELD_DEFAULTS 必须是 clicked');
112
114
  // ⚠️ schemastery 没有 z.enum,必须是 union+const(踩坑:z.enum 直接 TypeError)
113
- assert.match(SCHEMA, /\.union\(\[z\.const\('earliest'\), z\.const\('latest'\), z\.const\('none'\)\]\)/, '三值用 union+const');
115
+ assert.match(SCHEMA, /\.union\(\[z\.const\('clicked'\), z\.const\('earliest'\), z\.const\('latest'\), z\.const\('none'\)\]\)/, '四值用 union+const');
114
116
  assert.doesNotMatch(SCHEMA, /z\.enum\(/, 'schemastery 不支持 z.enum');
115
- assert.match(CLIENT, /typeof v\.multiJumpRule === 'string' \? v\.multiJumpRule : 'earliest'/, '客户端兜底也得是 earliest');
116
- assert.match(CLIENT, /var curRule = typeof v\.multiJumpRule === 'string' \? v\.multiJumpRule : 'earliest'/, 'GUI 兜底也得是 earliest');
117
+ assert.match(CLIENT, /var curRule = typeof v\.multiJumpRule === 'string' \? v\.multiJumpRule : 'clicked'/, 'GUI 兜底也得是 clicked');
118
+ });
119
+
120
+ test('T11b: clicked 必须排在选项第一位(默认项)', () => {
121
+ const m = CLIENT.match(/var JUMP_RULES = \[([\s\S]*?)\]/);
122
+ assert.ok(m, '要有 JUMP_RULES');
123
+ assert.match(m[1], /\['clicked'/, 'clicked 要出现在选项里');
124
+ // 第一位 = 默认选中项
125
+ const first = m[1].match(/\['([a-z]+)'/);
126
+ assert.equal(first[1], 'clicked', 'clicked 必须在第一位');
117
127
  });
118
128
 
119
129
  test('T12: 客户端能同时吃新队列和旧单条响应', () => {
@@ -124,9 +134,44 @@ test('T12: 客户端能同时吃新队列和旧单条响应', () => {
124
134
  // ══ T13:配置透传链路 ══════════════════════════════════════════════════
125
135
  test('T13: multiJumpRule 在 schema/store/index 三处白名单与透传都在', () => {
126
136
  const store = readFileSync(join(ROOT, 'lib/config-store.js'), 'utf8');
127
- for (const [name, src] of [['config-store', store], ['index', INDEX]]) {
128
- assert.match(src, /jumpWhenForeground', 'multiJumpRule'/, name + ' 白名单');
129
- }
137
+
138
+ // v0.4.71 修正:multiJumpRule 之前被**错放进 BOOL_KEYS**(那是给 boolean 用的),
139
+ // sanitize 会按 boolean 校验并丢弃它 —— 保存设置时静默失效。
140
+ // 现在它必须在 RULES 里以「字符串枚举」的形式校验。
141
+ assert.doesNotMatch(store, /BOOL_KEYS[\s\S]{0,400}'multiJumpRule'/,
142
+ 'multiJumpRule 不能出现在 BOOL_KEYS 里(它是字符串,不是 boolean)');
143
+ assert.match(store, /multiJumpRule: \(v\) => \(\['clicked', 'earliest', 'latest', 'none'\]\.includes\(v\)/,
144
+ 'config-store 必须在 RULES 里按枚举校验 multiJumpRule');
145
+
146
+ // index.js 的 sanitize 白名单(normalizeConfig)仍要有它
147
+ assert.match(INDEX, /'jumpWhenForeground', 'multiJumpRule'/, 'index 白名单');
148
+
130
149
  assert.match(store, /multiJumpRule: cfg\.multiJumpRule,/, 'config-store 透传');
131
150
  assert.match(INDEX, /multiJumpRule: g\.multiJumpRule,/, 'effectiveForClient 透传');
132
151
  });
152
+
153
+ // ══ v0.4.71:前台点 Toast 也要跳 ════════════════════════════════════════
154
+ test('T14: 必须有 tryTopJump(不依赖 visibilitychange)', () => {
155
+ // 用户 2026-10-19 指出:窗口一直在前台时点 Toast,visibilitychange 不触发,
156
+ // 于是跳不过去。而"在前台点 Toast 直接过去看结果"恰恰是最省事的用法。
157
+ assert.match(CLIENT, /function tryTopJump\(\)/, '要有前台跳转入口');
158
+ const m = CLIENT.match(/function tryTopJump\(\)([\s\S]{0,900})/);
159
+ assert.ok(m, '能读到函数体');
160
+ assert.match(m[1], /fetchPendingJump\(\)/, '要读 pending-jump');
161
+ assert.match(m[1], /openSession\(/, '要真的跳');
162
+ assert.match(m[1], /lastTopJumpCheck/, '要有节流,避免 focus 抖动打爆请求');
163
+ });
164
+
165
+ test('T15: focus 与 mousedown 监听都要注册且要能移除', () => {
166
+ assert.match(CLIENT, /addEventListener\('focus', tryTopJump\)/, 'window focus 要监听');
167
+ assert.match(CLIENT, /addEventListener\('mousedown', tryTopJump/, 'document mousedown 要监听');
168
+ // 闭环:卸载时必须移除,否则热重载会叠监听
169
+ assert.match(CLIENT, /removeEventListener\('focus', tryTopJump\)/, '卸载要移除 focus');
170
+ assert.match(CLIENT, /removeEventListener\('mousedown', tryTopJump\)/, '卸载要移除 mousedown');
171
+ });
172
+
173
+ test('T16: 前台跳转必须有 120 秒过期保护', () => {
174
+ const m = CLIENT.match(/function tryTopJump\(\)([\s\S]{0,900})/);
175
+ assert.ok(m);
176
+ assert.match(m[1], /120000/, '超过 120 秒的点击不该跳(避免久等后突然跳走)');
177
+ });