dsh-notify-say 0.4.63 → 0.4.65
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/CHANGELOG.md +8 -0
- package/lib/index.js +371 -53
- package/package.json +1 -1
- package/test/idle-gate-contract.test.mjs +145 -0
- package/test/idle-gate-timing.test.mjs +231 -0
- package/test/jobs-api-contract.test.mjs +61 -0
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,14 @@
|
|
|
3
3
|
> 本文件由 `tools/release-build.ps1` 从开发提交自动生成,**请勿手工编辑**。
|
|
4
4
|
> 只列面向使用者的变更(新增功能与修复),不含内部维护提交。
|
|
5
5
|
|
|
6
|
+
## v0.4.65 — 2026-10-19
|
|
7
|
+
|
|
8
|
+
- fix(idle-gate): v0.4.65 —— 空闲门改成可靠状态机,真机验证通过
|
|
9
|
+
|
|
10
|
+
## v0.4.64 — 2026-10-19
|
|
11
|
+
|
|
12
|
+
- fix(idle-gate): v0.4.64 —— jobs.list 传参错误导致空闲门从未生效
|
|
13
|
+
|
|
6
14
|
## v0.4.63 — 2026-10-19
|
|
7
15
|
|
|
8
16
|
- feat(notify): v0.4.63 —— 前台完成也能立刻跳(长轮询)
|
package/lib/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
+
|
|
2
3
|
* dsh-notify-say — Host half(官方插件规范形态)。
|
|
3
4
|
*
|
|
4
5
|
* 证据基础(0.1.7-rc.2 app.asar 一手抽取,均存 scratch/asar-extract/):
|
|
@@ -868,8 +869,8 @@ export function apply(ctx, config) {
|
|
|
868
869
|
|
|
869
870
|
// 会话状态桥实例:notify() 往里写,HTTP route 往外读(client 半侧消费)。
|
|
870
871
|
// 进程内、不落盘 —— 重启后"刚才那条通知"就该失效,这是正确语义。
|
|
871
|
-
const bridge = createSessionBridge();
|
|
872
|
-
// ⚠️ v0.4.63:长轮询的挂起响应必须在卸载时结束,
|
|
872
|
+
const bridge = createSessionBridge();
|
|
873
|
+
// ⚠️ v0.4.63:长轮询的挂起响应必须在卸载时结束,
|
|
873
874
|
// 否则热重载会留下永远等不到响应的连接(2026-10-18 那次崩溃同源)。
|
|
874
875
|
|
|
875
876
|
// 配置 route:client 设置卡片读写音量/音色/开关。
|
|
@@ -1058,7 +1059,10 @@ export function apply(ctx, config) {
|
|
|
1058
1059
|
appendNotifyLog(`[plan] kind=${aKind} source=${String(source)} `
|
|
1059
1060
|
+ `audioSource=${String(cfg.audioSource)} voice=${String(cfg.voice)} `
|
|
1060
1061
|
+ `wantSound=${String(wantSound)} showToast=${String(cfg.showToast)} `
|
|
1061
|
-
+ `byKind=${JSON.stringify(cfg.audioSourceByKind || {})}`
|
|
1062
|
+
+ `byKind=${JSON.stringify(cfg.audioSourceByKind || {})}`
|
|
1063
|
+
// v0.4.65:带上会话 id —— 之前没有,"哪个会话播的"只能靠时间猜。
|
|
1064
|
+
// 空闲门 flush 与直接播报都走到这里,演示也用它当证据。
|
|
1065
|
+
+ ` sess=${sessionKey(session)}`);
|
|
1062
1066
|
|
|
1063
1067
|
// ── TTS:零下载也能说话 ──────────────────────────────────────────────
|
|
1064
1068
|
if (wantSound && source === 'tts') {
|
|
@@ -1249,6 +1253,35 @@ function hasVoiceLine(psKind) {
|
|
|
1249
1253
|
}
|
|
1250
1254
|
|
|
1251
1255
|
/** 读宿主服务(非 strict:容许由其它作用域提供;任何失败都返回 undefined)。 */
|
|
1256
|
+
/**
|
|
1257
|
+
* 读 turnBoundary 投影 —— 空闲门的**权威**判定依据(v0.4.65)。
|
|
1258
|
+
*
|
|
1259
|
+
* 返回形态(2026-10-19 实测,真实宿主数据):
|
|
1260
|
+
* { openTurnStartSeq: number|null, lastStepStartSeq, lastStepBoundary, lastTurn }
|
|
1261
|
+
*
|
|
1262
|
+
* 实测对照:idle 会话 openTurnStartSeq=null;running 会话 openTurnStartSeq=16165。
|
|
1263
|
+
* 两者完全一致,所以拿它代替不可靠的 agent.status 判断。
|
|
1264
|
+
*
|
|
1265
|
+
* @returns {{open: number|null, lastTurn: number}|null}
|
|
1266
|
+
* null 表示读不到 —— 调用方**必须**当"未知"处理,绝不能当"空闲"。
|
|
1267
|
+
*/
|
|
1268
|
+
function turnBoundaryOf(session) {
|
|
1269
|
+
try {
|
|
1270
|
+
const proj = svc('sessionProjections');
|
|
1271
|
+
if (!proj || typeof proj.stateOf !== 'function') return null;
|
|
1272
|
+
const b = proj.stateOf(session, 'turnBoundary');
|
|
1273
|
+
if (!b || typeof b !== 'object') return null;
|
|
1274
|
+
return {
|
|
1275
|
+
open: b.openTurnStartSeq === null || b.openTurnStartSeq === undefined
|
|
1276
|
+
? null
|
|
1277
|
+
: b.openTurnStartSeq,
|
|
1278
|
+
lastTurn: typeof b.lastTurn === 'number' ? b.lastTurn : 0,
|
|
1279
|
+
};
|
|
1280
|
+
} catch {
|
|
1281
|
+
return null;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1252
1285
|
function svc(name) {
|
|
1253
1286
|
try { return ctx.get(name, false); } catch { return undefined; }
|
|
1254
1287
|
}
|
|
@@ -1263,7 +1296,19 @@ function hasVoiceLine(psKind) {
|
|
|
1263
1296
|
let agents = [];
|
|
1264
1297
|
try {
|
|
1265
1298
|
const js = svc('jobs');
|
|
1266
|
-
if (js && typeof js.list === 'function')
|
|
1299
|
+
if (js && typeof js.list === 'function') {
|
|
1300
|
+
// ⚠️ 必须传 **agent.id 字符串**,不能传 agent 对象。
|
|
1301
|
+
// DSH 官方用法是 jobs.list(agent?.id)(见 app.asar 的 updateTaskControl),
|
|
1302
|
+
// 传对象会让它返回空数组 → 空闲门永远判定「没有在飞工作」→
|
|
1303
|
+
// 回合一结束就播报(2026-10-19 用户演示空闲门时实测抓到)。
|
|
1304
|
+
// 单测没发现:测试直接喂 collectInFlight 的假数据,绕过了本函数。
|
|
1305
|
+
//
|
|
1306
|
+
// 另照官方做法补查「无 agent 的全局任务」——有些后台任务不属于任何 agent。
|
|
1307
|
+
const aid = agent && agent.id !== undefined ? agent.id : undefined;
|
|
1308
|
+
const mine = js.list(aid) || [];
|
|
1309
|
+
const glob = aid === undefined ? [] : (js.list(undefined) || []);
|
|
1310
|
+
jobs = mine.concat(glob);
|
|
1311
|
+
}
|
|
1267
1312
|
} catch (e) {
|
|
1268
1313
|
console.warn('[dsh-notify-say] jobs.list failed: ' + String((e && e.message) || e));
|
|
1269
1314
|
}
|
|
@@ -1273,7 +1318,28 @@ function hasVoiceLine(psKind) {
|
|
|
1273
1318
|
} catch (e) {
|
|
1274
1319
|
console.warn('[dsh-notify-say] agents.list failed: ' + String((e && e.message) || e));
|
|
1275
1320
|
}
|
|
1276
|
-
|
|
1321
|
+
// ⚠️ v0.4.65:对齐 DSH 官方的 hasDesktopActiveTasks ——
|
|
1322
|
+
// 它还检查 agent.inbox 里有没有排队的下一轮/下一步:
|
|
1323
|
+
// agent.status === "running"
|
|
1324
|
+
// || agent.inbox.nextTurn.length > 0
|
|
1325
|
+
// || agent.inbox.nextStep.length > 0
|
|
1326
|
+
// 后两个表示"马上要干活"(比如子任务返回后主 Agent 立刻续跑)。
|
|
1327
|
+
// 不查它们就会出现"刚播完成,Agent 又开始干"的误报。
|
|
1328
|
+
//
|
|
1329
|
+
// inbox 的形状不确定(可能是包装对象,nextTurn/nextStep 在原型链上),
|
|
1330
|
+
// 所以**读不到就不算有活** —— 宁可少拦一次,也不能因为读不到而永远不播。
|
|
1331
|
+
try {
|
|
1332
|
+
const ib = agent && agent.inbox;
|
|
1333
|
+
if (ib) {
|
|
1334
|
+
const nt = ib.nextTurn;
|
|
1335
|
+
const ns = ib.nextStep;
|
|
1336
|
+
if ((Array.isArray(nt) && nt.length > 0) || (Array.isArray(ns) && ns.length > 0)) {
|
|
1337
|
+
jobs.push({ id: "inbox", label: "queued", status: "running" });
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
} catch { /* inbox 不可读:忽略,不因此判定有活 */ }
|
|
1341
|
+
|
|
1342
|
+
return collectInFlight(jobs, agents, agent && agent.id);
|
|
1277
1343
|
}
|
|
1278
1344
|
|
|
1279
1345
|
/**
|
|
@@ -1310,10 +1376,42 @@ function hasVoiceLine(psKind) {
|
|
|
1310
1376
|
}
|
|
1311
1377
|
|
|
1312
1378
|
/** 实际播报(按会话去抖 + 可选跨会话冷却;返回是否真的发出)。 */
|
|
1313
|
-
|
|
1379
|
+
/**
|
|
1380
|
+
* 已完成播报的事件键(会话 → 最近一个已播的 turn)。
|
|
1381
|
+
*
|
|
1382
|
+
* 用途:**事件级互斥**。同一个完成的 evKey 只允许播一次,
|
|
1383
|
+
* 防止「空闲门 flush」和「agent/status 直接播」两条路径各播一遍
|
|
1384
|
+
* (2026-10-19 真机实测:用户听到了两个语音)。
|
|
1385
|
+
*
|
|
1386
|
+
* 为什么不用时间去抖:时间窗口语义模糊 —— 分不清"同一件事"和
|
|
1387
|
+
* "两件相邻的事"。事件键能精确区分。
|
|
1388
|
+
*/
|
|
1389
|
+
const lastEmittedKey = new Map();
|
|
1390
|
+
|
|
1391
|
+
/**
|
|
1392
|
+
* 播报统一的**唯一出口**。
|
|
1393
|
+
*
|
|
1394
|
+
* @param {object} session
|
|
1395
|
+
* @param {string} psKind done / fail / chime
|
|
1396
|
+
* @param {string} title
|
|
1397
|
+
* @param {string} body
|
|
1398
|
+
* @param {string} [evKey] 事件标识(同一事件只播一次);缺省则不去重
|
|
1399
|
+
* @returns {boolean} 是否真的播了
|
|
1400
|
+
*/
|
|
1401
|
+
function emitDone(session, psKind, title, body, evKey) {
|
|
1314
1402
|
const key = sessionKey(session);
|
|
1315
1403
|
const now = Date.now();
|
|
1316
1404
|
|
|
1405
|
+
// ── 第零级:事件级互斥(v0.4.65)─────────────────────────────────────
|
|
1406
|
+
// 同一个完成事件,不管从哪条路径进来,只播一次。
|
|
1407
|
+
if (evKey) {
|
|
1408
|
+
const seen = lastEmittedKey.get(key);
|
|
1409
|
+
if (seen === evKey) {
|
|
1410
|
+
skipLog('duplicate-event', psKind, session, `evKey=${evKey} already emitted`);
|
|
1411
|
+
return false;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1317
1415
|
// ── 第一级:同会话去抖 ────────────────────────────────────────────────
|
|
1318
1416
|
// 语义:同一会话连续完成多次,只提醒最后一次(几乎是噪音)。
|
|
1319
1417
|
// 可调为 0 表示关闭 —— 有人希望"每个结果都听见"。
|
|
@@ -1346,6 +1444,7 @@ function hasVoiceLine(psKind) {
|
|
|
1346
1444
|
|
|
1347
1445
|
rememberAt(lastTurnNotify, key, now);
|
|
1348
1446
|
lastAnyNotifyAt = now;
|
|
1447
|
+
if (evKey) lastEmittedKey.set(key, evKey);
|
|
1349
1448
|
notify(psKind, title, body, session);
|
|
1350
1449
|
return true;
|
|
1351
1450
|
}
|
|
@@ -1359,18 +1458,99 @@ function hasVoiceLine(psKind) {
|
|
|
1359
1458
|
}
|
|
1360
1459
|
|
|
1361
1460
|
/** 兑现挂起项:播报一次。viaTimeout 表示是超时兜底(文案加提示,不误导为"全部完成")。 */
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1461
|
+
/**
|
|
1462
|
+
* 放行一个挂起项并播报。
|
|
1463
|
+
*
|
|
1464
|
+
* ## viaTimeout = true 时的行为(v0.4.65 重写)
|
|
1465
|
+
*
|
|
1466
|
+
* 超时不等于完成。必须**当场复查**工作树:
|
|
1467
|
+
* · 真的空了 → 正常播"完成"
|
|
1468
|
+
* · 还在跑 → 播**不同的提醒文案**,绝不谎报完成
|
|
1469
|
+
* · 状态未知 → 播提醒 + 记诊断
|
|
1470
|
+
*
|
|
1471
|
+
* 用户方案原话:「超时先重新检查工作树。如果仍有任务运行,不得朗读
|
|
1472
|
+
* "任务已完成"。状态未知时记录诊断信息;如需要超时提醒,使用与
|
|
1473
|
+
* "全部完成"不同的提示文案。」
|
|
1474
|
+
*/
|
|
1475
|
+
/**
|
|
1476
|
+
* 放行挂起项并播报「完成」。**只有确认工作树真的空了才允许调用。**
|
|
1477
|
+
*
|
|
1478
|
+
* 超时路径不走这里 —— 超时走 notifyProgress(不消耗完成通知)。
|
|
1479
|
+
*/
|
|
1480
|
+
function flushPending(id) {
|
|
1481
|
+
const p = pendingDone.get(id);
|
|
1482
|
+
if (!p) return;
|
|
1483
|
+
clearTimeout(p.timer);
|
|
1484
|
+
if (p.recheckTimer) clearTimeout(p.recheckTimer);
|
|
1485
|
+
pendingDone.delete(id);
|
|
1486
|
+
appendNotifyLog(`[flush] idle-gate kind=${p.psKind} sess=${sessionKey(p.session)} worktree-idle`);
|
|
1487
|
+
// evKey 用「这一轮的序号」:同一轮无论哪条路径都算同一个事件。
|
|
1488
|
+
emitDone(p.session, p.psKind, p.title, p.body, p.evKey || undefined);
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
/**
|
|
1492
|
+
* 超时兜底:**发进度提醒,但不消耗完成通知**(v0.4.65 第 1 批 1.7)。
|
|
1493
|
+
*
|
|
1494
|
+
* 规则(用户方案):
|
|
1495
|
+
* · 超时先复查工作树
|
|
1496
|
+
* · 若真的空了 → 直接走 flush(这就是正常完成)
|
|
1497
|
+
* · 仍在跑 / 状态未知 → 播**进度提醒**(文案明确不含"完成"),
|
|
1498
|
+
* 最多一次;pending **保留**,等真正空闲时再播完成
|
|
1499
|
+
*
|
|
1500
|
+
* 进度提醒之后仍会留一个周期性复查,保证最终空闲时能播完成。
|
|
1501
|
+
*/
|
|
1502
|
+
function onIdleGateTimeout(id) {
|
|
1503
|
+
const p = pendingDone.get(id);
|
|
1504
|
+
if (!p) return;
|
|
1505
|
+
|
|
1506
|
+
// 先复查:也许刚好已经空了
|
|
1507
|
+
let stillBusy = null; // null = 未知
|
|
1508
|
+
try {
|
|
1509
|
+
const as = svc('agents');
|
|
1510
|
+
const agent = as && typeof as.get === 'function' ? as.get(id) : undefined;
|
|
1511
|
+
if (agent) {
|
|
1512
|
+
const inflight = inFlightOf(agent);
|
|
1513
|
+
const tb = turnBoundaryOf(agent.session);
|
|
1514
|
+
if (tb && tb.open !== null) {
|
|
1515
|
+
stillBusy = true;
|
|
1516
|
+
} else {
|
|
1517
|
+
stillBusy = inflight.length > 0;
|
|
1518
|
+
}
|
|
1519
|
+
if (inflight.length > 0) p.inflight = inflight;
|
|
1520
|
+
}
|
|
1521
|
+
} catch { stillBusy = null; }
|
|
1522
|
+
|
|
1523
|
+
if (stillBusy === false) {
|
|
1524
|
+
// 复查确认真空闲 → 这是正常完成,走 flush
|
|
1525
|
+
appendNotifyLog(`[idle-gate] timeout recheck: idle now id=${id}`);
|
|
1526
|
+
flushPending(id);
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
// 仍在跑或未知 → 进度提醒(最多一次),pending 保留
|
|
1531
|
+
const reason = stillBusy === true ? 'timeout-still-running' : 'timeout-unknown';
|
|
1532
|
+
const n = (p.inflight && p.inflight.length) || 0;
|
|
1533
|
+
|
|
1534
|
+
if (!p.progressNotified) {
|
|
1535
|
+
p.progressNotified = true;
|
|
1536
|
+
const txt = stillBusy === true
|
|
1537
|
+
? `已经跑了一段时间,还有 ${n} 个任务在进行中 —— 这不是完成提醒`
|
|
1538
|
+
: '已经跑了一段时间,暂时查不到进度 —— 这不是完成提醒';
|
|
1539
|
+
appendNotifyLog(`[progress] idle-gate kind=${p.psKind} sess=${sessionKey(p.session)} ${reason} inflight=${n}`);
|
|
1540
|
+
// 进度提醒走独立的 kind 语义:ps1 里用 chime(不播"完成"语音)
|
|
1541
|
+
notify('chime', p.title, txt, p.session);
|
|
1542
|
+
} else {
|
|
1543
|
+
appendNotifyLog(`[idle-gate] timeout again, progress already sent id=${id}`);
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
// 留一个复查定时器:等它真正空闲时还能播完成。
|
|
1547
|
+
// 间隔用 idleGateTimeoutMs 的一半(下限 60 秒),避免太频繁。
|
|
1548
|
+
const again = Math.max(60_000, Math.round(cfg.idleGateTimeoutMs / 2));
|
|
1549
|
+
p.recheckTimer = setTimeout(() => {
|
|
1550
|
+
try { onIdleGateTimeout(id); } catch { /* 单次失败不影响后续 */ }
|
|
1551
|
+
}, again);
|
|
1552
|
+
if (p.recheckTimer && typeof p.recheckTimer.unref === 'function') p.recheckTimer.unref();
|
|
1553
|
+
}
|
|
1374
1554
|
|
|
1375
1555
|
/**
|
|
1376
1556
|
* 空闲门:工作树空闲就播报,否则挂起等待。
|
|
@@ -1378,19 +1558,50 @@ function hasVoiceLine(psKind) {
|
|
|
1378
1558
|
*/
|
|
1379
1559
|
function scheduleOrNotify(session, agent, psKind, title, body) {
|
|
1380
1560
|
const id = sessionKey(session);
|
|
1561
|
+
|
|
1562
|
+
// 事件标识:同一轮的完成必须用同一个 evKey,
|
|
1563
|
+
// 这样「空闲门 flush」与「agent/status 直接播」两条路径才会互斥。
|
|
1564
|
+
const tbNow = turnBoundaryOf(session);
|
|
1565
|
+
const evKey = tbNow ? `turn:${id}:${tbNow.lastTurn}` : undefined;
|
|
1566
|
+
|
|
1381
1567
|
const inflight = inFlightOf(agent);
|
|
1568
|
+
|
|
1569
|
+
// ⚠️ v0.4.65:**合并**,不是各播一次。
|
|
1570
|
+
// 同一会话已有挂起项时,说明这次完成是「上一轮的后继」
|
|
1571
|
+
// (子任务返回后 Agent 内部续跑完成)。两条路径各播一次就会重复 ——
|
|
1572
|
+
// 2026-10-19 真机实测:用户听到了两个语音。
|
|
1573
|
+
// 正确做法:更新挂起项的内容,最终只播一次(用户方案要求)。
|
|
1574
|
+
const existing = pendingDone.get(id);
|
|
1575
|
+
if (existing) {
|
|
1576
|
+
existing.psKind = psKind;
|
|
1577
|
+
existing.title = title;
|
|
1578
|
+
existing.body = body;
|
|
1579
|
+
existing.inflight = inflight;
|
|
1580
|
+
if (inflight.length === 0) {
|
|
1581
|
+
// 工作树已空 → 合并后播一次(内容用最新的)
|
|
1582
|
+
flushPending(id);
|
|
1583
|
+
} else {
|
|
1584
|
+
skipLog('idle-gate-merge', psKind, session,
|
|
1585
|
+
`merged into pending, still ${inflight.length} inflight`);
|
|
1586
|
+
}
|
|
1587
|
+
return;
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1382
1590
|
if (inflight.length === 0) {
|
|
1383
1591
|
clearPending(id);
|
|
1384
|
-
emitDone(session, psKind, title, body);
|
|
1592
|
+
emitDone(session, psKind, title, body, evKey);
|
|
1385
1593
|
return;
|
|
1386
1594
|
}
|
|
1595
|
+
|
|
1387
1596
|
clearPending(id);
|
|
1388
|
-
const timer = setTimeout(() =>
|
|
1597
|
+
const timer = setTimeout(() => { try { onIdleGateTimeout(id); } catch { /* 兜底失败不影响主流程 */ } }, cfg.idleGateTimeoutMs);
|
|
1389
1598
|
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
1390
|
-
pendingDone.set(id, {
|
|
1599
|
+
pendingDone.set(id, {
|
|
1600
|
+
session, psKind, title, body, timer, inflight,
|
|
1601
|
+
// 挂起时就把 evKey 定下来:flush 时用它做互斥键。
|
|
1602
|
+
evKey,
|
|
1603
|
+
});
|
|
1391
1604
|
// 双写:console(宿主 stdout,开发/测试断言用)+ notify.log(用户与事后排查用)。
|
|
1392
|
-
// 之前只写 console,导致用户问"刚才怎么没响"时在 notify.log 里查不到任何痕迹;
|
|
1393
|
-
// 但**不能**用 notify.log 取代 console —— 既有测试与宿主日志都依赖这一行。
|
|
1394
1605
|
console.log(`[dsh-notify-say] idle-gate: 挂起完成播报,等待 ${inflight.length} 项在飞工作 `
|
|
1395
1606
|
+ `(${inflight.map((i) => i.kind + ':' + i.id).join(', ')})`);
|
|
1396
1607
|
skipLog('idle-gate-hold', psKind, session,
|
|
@@ -1402,26 +1613,74 @@ function hasVoiceLine(psKind) {
|
|
|
1402
1613
|
* 三种归宿:① 主会话已重新 running → 取消(用户已在交互);② 工作树空闲 → 播报;
|
|
1403
1614
|
* ③ agent 已消失 → 视为结束,播报。
|
|
1404
1615
|
*/
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1616
|
+
/**
|
|
1617
|
+
* 重估所有挂起项(由 jobs 事件 / agent/status 触发)。
|
|
1618
|
+
*
|
|
1619
|
+
* ## 判定顺序(v0.4.65 重写)
|
|
1620
|
+
*
|
|
1621
|
+
* 每个挂起项按下面顺序判,**任何一步"不确定"都不许放行**:
|
|
1622
|
+
*
|
|
1623
|
+
* ① 拿 agent;拿不到 → 不是"完成",记诊断,保留待下次(原先误 flush)
|
|
1624
|
+
* ② 读 turnBoundary;读不到 → 同上,保留
|
|
1625
|
+
* ③ lastTurn > 挂起时的 lastTurn → 新一轮开始了 → 作废(不是播报)
|
|
1626
|
+
* ④ openTurnStartSeq !== null → 有轮次进行中 → 保留等待
|
|
1627
|
+
* ⑤ 还有在飞工作 → 保留等待
|
|
1628
|
+
* ⑥ 以上都过(真空闲且无活)→ flush 播报一次
|
|
1629
|
+
*
|
|
1630
|
+
* ## 为什么"agent 拿不到"不能当完成
|
|
1631
|
+
*
|
|
1632
|
+
* 原先写 `if (!agent) flushPending(...)` —— 把"查不到状态"当成"工作树空了"。
|
|
1633
|
+
* 用户方案明确要求:"状态无法查询时不得当成工作树完成"。
|
|
1634
|
+
* 现在改为保留 + 记诊断,由超时兜底或下次事件重试。
|
|
1635
|
+
*/
|
|
1636
|
+
function reevaluatePending(trigger) {
|
|
1637
|
+
if (pendingDone.size === 0) return;
|
|
1638
|
+
for (const id of [...pendingDone.keys()]) {
|
|
1639
|
+
const p = pendingDone.get(id);
|
|
1640
|
+
if (!p) continue;
|
|
1641
|
+
|
|
1642
|
+
// ① agent
|
|
1643
|
+
let agent;
|
|
1644
|
+
try {
|
|
1645
|
+
const as = svc('agents');
|
|
1646
|
+
agent = as && typeof as.get === 'function' ? as.get(id) : undefined;
|
|
1647
|
+
} catch { agent = undefined; }
|
|
1648
|
+
if (!agent) {
|
|
1649
|
+
// 不等于完成 —— 可能只是注册表暂时读不到。保留,等下次或超时。
|
|
1650
|
+
appendNotifyLog(`[idle-gate] pending kept: agent unavailable id=${id} trigger=${trigger}`, { detail: true });
|
|
1651
|
+
continue;
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
// ② turnBoundary(权威信号)
|
|
1655
|
+
const tb = turnBoundaryOf(agent.session);
|
|
1656
|
+
if (!tb) {
|
|
1657
|
+
appendNotifyLog(`[idle-gate] pending kept: turnBoundary unavailable id=${id} trigger=${trigger}`, { detail: true });
|
|
1658
|
+
continue;
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
// ⚠️ v0.4.65:**不再**用 lastTurn 递增判断「用户发了新消息」。
|
|
1662
|
+
// 实测证伪:主 Agent 处理子任务返回时内部续跑,lastTurn 也会递增
|
|
1663
|
+
// (2026-10-19 日志:pending dropped turn 9->10,但用户什么都没发)。
|
|
1664
|
+
// 按需求约定「不能用间接信号猜测用户输入」→ 保守退化:保留 pending,
|
|
1665
|
+
// 后续结果合并,最终稳定空闲时最多播一次。
|
|
1666
|
+
// 代价:用户真发新消息时旧通知会补播一次(危害小于误作废)。
|
|
1667
|
+
|
|
1668
|
+
// ④ 轮次还开着 → 还在干,留着
|
|
1669
|
+
if (tb.open !== null) {
|
|
1670
|
+
continue;
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
// ⑤ 还有在飞工作 → 留着(把最新快照记下来,日志与超时判断都用它)
|
|
1674
|
+
const inflight = inFlightOf(agent);
|
|
1675
|
+
if (inflight.length > 0) {
|
|
1676
|
+
p.inflight = inflight;
|
|
1677
|
+
continue;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// ⑥ 真的空闲了 → 播报一次
|
|
1681
|
+
flushPending(id);
|
|
1422
1682
|
}
|
|
1423
1683
|
}
|
|
1424
|
-
}
|
|
1425
1684
|
|
|
1426
1685
|
/** completed / error / blocked / 其它 四分支 → 文案 + 门控 → 交给空闲门。 */
|
|
1427
1686
|
function handleDone(session, agent, kind) {
|
|
@@ -1589,6 +1848,27 @@ function hasVoiceLine(psKind) {
|
|
|
1589
1848
|
// 重载完成后会打印差值,让"漏播"可被区分出来。
|
|
1590
1849
|
// 不影响任何播报行为。
|
|
1591
1850
|
bumpEventCount()
|
|
1851
|
+
// v0.4.65 诊断:记录事件类型与关键字段,用于判断 turn/start 的来源
|
|
1852
|
+
try {
|
|
1853
|
+
recentEvents.push({
|
|
1854
|
+
t: Date.now(),
|
|
1855
|
+
type: event && event.type,
|
|
1856
|
+
sess: session && session.id,
|
|
1857
|
+
// 只保留小的标量字段,避免把正文也记进去
|
|
1858
|
+
data: (() => {
|
|
1859
|
+
const d = event && event.data;
|
|
1860
|
+
if (!d || typeof d !== 'object') return d;
|
|
1861
|
+
const out = {};
|
|
1862
|
+
for (const k of Object.keys(d)) {
|
|
1863
|
+
const v = d[k];
|
|
1864
|
+
if (v === null || ['string','number','boolean'].includes(typeof v)) out[k] = v;
|
|
1865
|
+
else if (typeof v === 'object') out[k] = '{obj:' + Object.keys(v).slice(0,6).join(',') + '}';
|
|
1866
|
+
}
|
|
1867
|
+
return out;
|
|
1868
|
+
})(),
|
|
1869
|
+
});
|
|
1870
|
+
if (recentEvents.length > 40) recentEvents.shift();
|
|
1871
|
+
} catch { /* 诊断不影响主流程 */ }
|
|
1592
1872
|
try {
|
|
1593
1873
|
const type = event && event.type;
|
|
1594
1874
|
if (type === 'turn/end') {
|
|
@@ -1617,8 +1897,16 @@ function hasVoiceLine(psKind) {
|
|
|
1617
1897
|
const prev = prevStatus.get(id);
|
|
1618
1898
|
// 有界记账(值带时间戳,供 TTL 清理用;读边沿时取 .status)
|
|
1619
1899
|
rememberBounded(prevStatus, id, { status, at: Date.now() }, Date.now(), (v) => v && v.at);
|
|
1620
|
-
|
|
1621
|
-
|
|
1900
|
+
// ⚠️ v0.4.65:done-edge 事件**不能**先 reevaluate,否则同一事件里
|
|
1901
|
+
// 会先 flush 旧挂起项(播一次)、再走 handleDone(又播一次)——
|
|
1902
|
+
// 2026-10-19 实测用户听到两个语音,就是这么来的。
|
|
1903
|
+
// 规则:本轮结束的边沿 → 交给 handleDone 统一处理(它会创建或合并 pending);
|
|
1904
|
+
// 其它状态变化(子代理结束等)→ 重估挂起项,唤醒等待中的通知。
|
|
1905
|
+
const isDoneEdge = status === 'idle' && prev && prev.status === 'running';
|
|
1906
|
+
const willHandleDone = isDoneEdge && shouldNotifySession(agent.session);
|
|
1907
|
+
if (!willHandleDone) {
|
|
1908
|
+
reevaluatePending('agent/status');
|
|
1909
|
+
}
|
|
1622
1910
|
if (status !== 'idle' || !prev || prev.status !== 'running') return;
|
|
1623
1911
|
if (!shouldNotifySession(agent.session)) {
|
|
1624
1912
|
// 这是**最常见**的一类"不播":子代理会话完成、而 subagents=false。
|
|
@@ -1637,17 +1925,39 @@ function hasVoiceLine(psKind) {
|
|
|
1637
1925
|
}, { global: true });
|
|
1638
1926
|
|
|
1639
1927
|
// ── 后台任务可见集变化 → 重估挂起项("最后一个任务结束"的唤醒路径)────────
|
|
1928
|
+
//
|
|
1929
|
+
// ⚠️ 2026-10-19 实测修正:ctx.jobs **没有 onJobsChanged 方法**。
|
|
1930
|
+
// 之前写 `if (typeof js.onJobsChanged === "function")` 条件永远不成立,
|
|
1931
|
+
// 于是订阅被静默跳过 → 空闲门挂起后没有任何唤醒路径 →
|
|
1932
|
+
// 只能等 idleGateTimeoutMs(10 分钟)兜底,产出的是 timeout-fallback。
|
|
1933
|
+
//
|
|
1934
|
+
// DSH 官方用法(app.asar 的 streamJobRows):
|
|
1935
|
+
// registry.events.subscribe({ owners: "all" }, (event) => { ... })
|
|
1936
|
+
// `events` 是**属性**不是方法。
|
|
1937
|
+
//
|
|
1938
|
+
// 保留 onJobsChanged 旧路径:万一别的 DSH 版本提供它,照样能用。
|
|
1640
1939
|
try {
|
|
1641
1940
|
const js = svc('jobs');
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1941
|
+
const onAny = () => {
|
|
1942
|
+
try { reevaluatePending('jobs-changed'); } catch (e) {
|
|
1943
|
+
console.warn('[dsh-notify-say] jobs-changed reevaluate failed: ' + String((e && e.message) || e));
|
|
1944
|
+
}
|
|
1945
|
+
};
|
|
1946
|
+
if (js && js.events && typeof js.events.subscribe === 'function') {
|
|
1947
|
+
ctx.effect(() => js.events.subscribe({ owners: 'all' }, (event) => {
|
|
1948
|
+
// 输出流事件太频繁,与"任务是否结束"无关,直接忽略。
|
|
1949
|
+
if (event && event.type === 'output') return;
|
|
1950
|
+
onAny();
|
|
1951
|
+
}), 'dsh-notify-say: jobs-events');
|
|
1952
|
+
} else if (js && typeof js.onJobsChanged === 'function') {
|
|
1953
|
+
// 旧版兜底路径(实测当前 DSH 没有,但保留以防版本差异)。
|
|
1954
|
+
ctx.effect(() => js.onJobsChanged(onAny), 'dsh-notify-say: jobs-changed');
|
|
1955
|
+
} else {
|
|
1956
|
+
console.warn('[dsh-notify-say] 订阅 jobs 变化失败:既没有 jobs.events.subscribe,也没有 onJobsChanged。'
|
|
1957
|
+
+ ' 空闲门将只能依赖 idleGateTimeoutMs 兜底(会产出 timeout-fallback)。');
|
|
1648
1958
|
}
|
|
1649
1959
|
} catch (e) {
|
|
1650
|
-
console.warn('[dsh-notify-say] jobs
|
|
1960
|
+
console.warn('[dsh-notify-say] 订阅 jobs 变化抛错: ' + String((e && e.message) || e));
|
|
1651
1961
|
}
|
|
1652
1962
|
|
|
1653
1963
|
// ── 卸载清理:挂起计时器与状态(监听器由插件 fiber 自动回收)──────────────
|
|
@@ -1738,8 +2048,8 @@ function hasVoiceLine(psKind) {
|
|
|
1738
2048
|
// (外部审阅 2026-10-18 指出。)
|
|
1739
2049
|
const isWriteRoute =
|
|
1740
2050
|
(head === 'config' && /\/set\b/.test(pathname))
|
|
1741
|
-
|| head === 'consume'
|
|
1742
|
-
// v0.4.63:/ack 只摘一条(前台跳转后确认),同样是写操作
|
|
2051
|
+
|| head === 'consume'
|
|
2052
|
+
// v0.4.63:/ack 只摘一条(前台跳转后确认),同样是写操作
|
|
1743
2053
|
|| head === 'ack'
|
|
1744
2054
|
|| head === 'diagnostics'
|
|
1745
2055
|
|| (head === 'voicepacks' && (/\/install\b/.test(pathname) || /\/uninstall\b/.test(pathname)))
|
|
@@ -1863,6 +2173,14 @@ function hasVoiceLine(psKind) {
|
|
|
1863
2173
|
//
|
|
1864
2174
|
// 为什么必须 POST:它会**写文件**。用 GET 的话,
|
|
1865
2175
|
// 任意网页放个 <img src=".../diagnostics"> 就能让本机反复生成文件。
|
|
2176
|
+
// ── 服务方法探针(v0.4.65 诊断用,只读)──────────────────────
|
|
2177
|
+
//
|
|
2178
|
+
// 空闲门的唤醒依赖 js.onJobsChanged 回调。若该方法不存在,
|
|
2179
|
+
// 订阅处会静默跳过 → 挂起项永远醒不过来(只能等 10 分钟超时)。
|
|
2180
|
+
// 这个端点把真实可用的方法名列出来,避免靠猜。
|
|
2181
|
+
// 诊断:验证 agents.get(会话id) 能不能拿到 agent(reevaluatePending 依赖它)
|
|
2182
|
+
// 诊断:turnBoundary 投影的真实结构(空闲门要用它判轮次)
|
|
2183
|
+
// 诊断:agent.inbox 能否读(空闲门要对齐官方 hasDesktopActiveTasks)
|
|
1866
2184
|
if (head === 'diagnostics') {
|
|
1867
2185
|
if (String((req && req.method) || 'GET').toUpperCase() !== 'POST') {
|
|
1868
2186
|
try {
|
|
@@ -2257,4 +2575,4 @@ export const fingerprint = (() => {
|
|
|
2257
2575
|
})();
|
|
2258
2576
|
|
|
2259
2577
|
|
|
2260
|
-
|
|
2578
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-notify-say",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.65",
|
|
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",
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 更新契约测试:`lastTurn` 递增判定已被删除(第 1 批 1.5)。
|
|
3
|
+
*
|
|
4
|
+
* ## 背景
|
|
5
|
+
*
|
|
6
|
+
* 原 K3 断言「必须有 lastTurn > p.lastTurn → 作废」这条规则。
|
|
7
|
+
* 但 2026-10-19 真机实测证伪了它:
|
|
8
|
+
*
|
|
9
|
+
* 20:12:02 [idle-gate] pending dropped: new turn started turn 9->10
|
|
10
|
+
* (用户什么都没发,是 Agent 处理子任务返回时内部续跑)
|
|
11
|
+
*
|
|
12
|
+
* 按需求约定「不能用间接信号猜测用户输入」,该判定已删除。
|
|
13
|
+
* 所以契约测试要**反过来断言:这个判定必须不存在**(防止有人再加回去)。
|
|
14
|
+
*/
|
|
15
|
+
import { test } from 'node:test';
|
|
16
|
+
import assert from 'node:assert/strict';
|
|
17
|
+
import { readFileSync } from 'node:fs';
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
import { dirname, join } from 'node:path';
|
|
20
|
+
|
|
21
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
22
|
+
const INDEX = readFileSync(join(ROOT, 'lib/index.js'), 'utf8');
|
|
23
|
+
|
|
24
|
+
function fnBody(sig) {
|
|
25
|
+
const lines = INDEX.split(/\r?\n/);
|
|
26
|
+
const i = lines.findIndex((l) => l.includes(sig));
|
|
27
|
+
assert.ok(i >= 0, '找不到函数: ' + sig);
|
|
28
|
+
const indent = (lines[i].match(/^(\s*)/) || ['', ''])[1];
|
|
29
|
+
let j = -1;
|
|
30
|
+
for (let k = i + 1; k < lines.length; k++) {
|
|
31
|
+
if (lines[k] === indent + '}') { j = k; break; }
|
|
32
|
+
}
|
|
33
|
+
assert.ok(j > i, '找不到函数终点: ' + sig);
|
|
34
|
+
return lines.slice(i, j + 1).join('\n');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ══ 已删除的规则(反断言,防回归)══════════════════════════════════════
|
|
38
|
+
test('K3: 不得再用 lastTurn 递增判定「用户新消息」(已实测证伪)', () => {
|
|
39
|
+
const body = fnBody('function reevaluatePending(trigger) {');
|
|
40
|
+
assert.doesNotMatch(body, /tb\.lastTurn\s*>\s*p\.lastTurn/,
|
|
41
|
+
'lastTurn 递增不能当用户输入证据 —— 主 Agent 处理子任务返回时内部续跑也会递增');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('K3b: 不得出现「pending dropped: new turn started」的日志', () => {
|
|
45
|
+
// 该日志随判定一起删除。若它回来,说明有人把误判加回去了。
|
|
46
|
+
assert.doesNotMatch(INDEX, /pending dropped: new turn started/,
|
|
47
|
+
'这条日志对应被证伪的判定,不该存在');
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// ══ 保留的规则 ═════════════════════════════════════════════════════════
|
|
51
|
+
test('K1: 不得因 agent.status === running 就 clearPending', () => {
|
|
52
|
+
const body = fnBody('function reevaluatePending(trigger) {');
|
|
53
|
+
assert.doesNotMatch(body, /agent\.status\s*===\s*'running'\)\s*\{\s*clearPending/,
|
|
54
|
+
'主 Agent 处理子任务返回时也是 running(T3 的规则)');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('K2: agent 拿不到时必须保留(continue),不能 flush', () => {
|
|
58
|
+
const body = fnBody('function reevaluatePending(trigger) {');
|
|
59
|
+
const idx = body.indexOf('if (!agent)');
|
|
60
|
+
assert.ok(idx > 0, '要有 agent 判空');
|
|
61
|
+
const seg = body.slice(idx, idx + 400);
|
|
62
|
+
assert.match(seg, /continue/, 'agent 读不到 ≠ 完成,必须保留(T12)');
|
|
63
|
+
assert.doesNotMatch(seg, /flushPending/, 'agent 读不到时绝不能 flush');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test('K4: 轮次还开着(open !== null)→ 保留,不播', () => {
|
|
67
|
+
const body = fnBody('function reevaluatePending(trigger) {');
|
|
68
|
+
assert.match(body, /tb\.open\s*!==\s*null/, '要有"轮次进行中"判定(T3)');
|
|
69
|
+
const idx = body.indexOf('tb.open !== null');
|
|
70
|
+
const seg = body.slice(idx, idx + 200);
|
|
71
|
+
assert.match(seg, /continue/, '轮次开着要继续等');
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('K5: 只有工作树为空才 flushPending', () => {
|
|
75
|
+
const body = fnBody('function reevaluatePending(trigger) {');
|
|
76
|
+
assert.match(body, /inflight\.length > 0/, '要有在飞判定(T7)');
|
|
77
|
+
const lastFlush = body.lastIndexOf('flushPending(id)');
|
|
78
|
+
assert.ok(lastFlush > 0, '必须存在最终的 flushPending');
|
|
79
|
+
assert.ok(lastFlush > body.indexOf('inflight.length > 0'),
|
|
80
|
+
'flush 必须在"还有在飞工作"判定之后(先排除才放行)');
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('K6: 超时走 onIdleGateTimeout(进度提醒),不直接消耗完成通知', () => {
|
|
84
|
+
// 定时器必须指向 onIdleGateTimeout
|
|
85
|
+
assert.match(INDEX, /setTimeout\(\(\) => \{ try \{ onIdleGateTimeout\(id\); \}/,
|
|
86
|
+
'超时定时器必须走进度提醒路径');
|
|
87
|
+
|
|
88
|
+
const body = fnBody('function onIdleGateTimeout(id) {');
|
|
89
|
+
assert.match(body, /progressNotified/, '进度提醒最多一次');
|
|
90
|
+
assert.match(body, /这不是完成提醒/, '文案必须明确否定"完成"');
|
|
91
|
+
// 关键:进度提醒路径不能 delete pending
|
|
92
|
+
const progressBranch = body.slice(body.indexOf('if (!p.progressNotified)'), body.indexOf('recheckTimer'));
|
|
93
|
+
assert.doesNotMatch(progressBranch, /pendingDone\.delete/,
|
|
94
|
+
'进度提醒**不得**消耗 pending —— 真正完成时还要再播一次');
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('K7: flushPending 不再接受 viaTimeout 参数(职责已拆分)', () => {
|
|
98
|
+
const body = fnBody('function flushPending(id) {');
|
|
99
|
+
assert.doesNotMatch(body, /viaTimeout/,
|
|
100
|
+
'viaTimeout 已拆到 onIdleGateTimeout,flushPending 只管"真完成"');
|
|
101
|
+
assert.match(body, /worktree-idle/, 'flush 的 reason 固定是 worktree-idle');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('K8: turnBoundaryOf 读不到要返回 null', () => {
|
|
105
|
+
const body = fnBody('function turnBoundaryOf(session) {');
|
|
106
|
+
assert.match(body, /catch/, '必须自己兜异常');
|
|
107
|
+
assert.match(body, /return null/, '失败返回 null');
|
|
108
|
+
assert.match(body, /openTurnStartSeq/, '要读 openTurnStartSeq');
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('K9: 对齐官方 hasDesktopActiveTasks —— 要查 inbox 排队', () => {
|
|
112
|
+
const body = fnBody('function inFlightOf(agent) {');
|
|
113
|
+
assert.match(body, /inbox/, '官方还会查 agent.inbox.nextTurn / nextStep(防"刚播完成又开始干")');
|
|
114
|
+
assert.match(body, /nextTurn/, '要查 nextTurn');
|
|
115
|
+
assert.match(body, /nextStep/, '要查 nextStep');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test('K10: inbox 读不到时不能判定"有活"(防永远不播)', () => {
|
|
119
|
+
const body = fnBody('function inFlightOf(agent) {');
|
|
120
|
+
const idx = body.indexOf('inbox');
|
|
121
|
+
assert.ok(idx > 0);
|
|
122
|
+
// 该段必须包在 try/catch 里,且注释说明"读不到不算有活"
|
|
123
|
+
const seg = body.slice(Math.max(0, idx - 400), idx + 800);
|
|
124
|
+
assert.match(seg, /catch/, 'inbox 读取要兜异常');
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// ══ 互斥(2026-10-19 真机抓到重复播报)══════════════════════════════════
|
|
128
|
+
test('K11: emitDone 必须有事件级互斥(同一 evKey 只播一次)', () => {
|
|
129
|
+
const body = fnBody('function emitDone(session, psKind, title, body, evKey) {');
|
|
130
|
+
assert.match(body, /lastEmittedKey/, '要有事件级去重表');
|
|
131
|
+
assert.match(body, /seen === evKey/, '同一 evKey 要拦下');
|
|
132
|
+
assert.match(body, /duplicate-event/, '拦下时要留痕');
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('K12: 两条播报路径必须用同一个 evKey(同一轮互斥)', () => {
|
|
136
|
+
// scheduleOrNotify 生成的 evKey
|
|
137
|
+
const sched = fnBody('function scheduleOrNotify(session, agent, psKind, title, body) {');
|
|
138
|
+
assert.match(sched, /const evKey = tbNow \?/, 'scheduleOrNotify 要生成 evKey');
|
|
139
|
+
assert.match(sched, /emitDone\(session, psKind, title, body, evKey\)/, '直接播报要带 evKey');
|
|
140
|
+
assert.match(sched, /evKey,/, 'pending 要存 evKey');
|
|
141
|
+
|
|
142
|
+
// flushPending 用 pending 里存的 evKey
|
|
143
|
+
const flush = fnBody('function flushPending(id) {');
|
|
144
|
+
assert.match(flush, /p\.evKey/, 'flush 要用 pending 里的 evKey');
|
|
145
|
+
});
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 空闲门 v2 的确定性时序测试(2026-10-19 方案第六节 12 条验收)。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么必须"确定性模拟"而不是只跑真实流程
|
|
5
|
+
*
|
|
6
|
+
* 空闲门的 bug 全都出在**时序**上(子任务恰好结束、主 Agent 恰好 running、
|
|
7
|
+
* 事件重复触发……)。真实流程无法稳定复现这些交错,而它们恰恰是最容易错的。
|
|
8
|
+
*
|
|
9
|
+
* 所以这里搭一个**最小可控环境**:
|
|
10
|
+
* · 假 agents 服务(可任意设 status / session)
|
|
11
|
+
* · 假 sessionProjections(可任意设 turnBoundary)
|
|
12
|
+
* · 假 jobs 服务(可任意设 in-flight 列表)
|
|
13
|
+
* · 假 notify(记录**实际播报次数与文案** —— 不是看日志字符串)
|
|
14
|
+
*
|
|
15
|
+
* 然后用事件序列驱动,断言:
|
|
16
|
+
* · 挂起期间 notify 调用次数 == 0
|
|
17
|
+
* · 挂起项是否还在(pendingDone 大小)
|
|
18
|
+
* · 最终播报次数恰好 1
|
|
19
|
+
* · 播报文案是否正确(超时不能念"完成")
|
|
20
|
+
*/
|
|
21
|
+
import { test } from 'node:test';
|
|
22
|
+
import assert from 'node:assert/strict';
|
|
23
|
+
|
|
24
|
+
// ── 从 lib/index.js 里取出纯逻辑片段来测 ────────────────────────────────
|
|
25
|
+
// 说明:空闲门逻辑嵌在 apply(ctx, config) 内部,无法直接 import。
|
|
26
|
+
// 这里刻意**复刻一份等价实现**,用于验证判定顺序。
|
|
27
|
+
// ⚠️ 复刻与实现的同步由 jobs-api-contract.test.mjs 的静态断言盯着
|
|
28
|
+
// (断言实现里必须存在本文件验证的那几条规则)。
|
|
29
|
+
// TODO(v0.4.66): 把空闲门抽成 lib/idle-gate.js 纯模块,直接 import 测,不再复刻。
|
|
30
|
+
|
|
31
|
+
const JUMP = Object.freeze({ FLUSH: 'flush', DROP: 'drop', KEEP: 'keep' });
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 空闲门判定(与 index.js 的 reevaluatePending 逐条对应)。
|
|
35
|
+
*
|
|
36
|
+
* @param {object} p 挂起项 { lastTurn, inflight }
|
|
37
|
+
* @param {object} env { agent, turnBoundary, inFlight }
|
|
38
|
+
* @returns {{action: string, reason: string}}
|
|
39
|
+
*/
|
|
40
|
+
function decidePending(p, env) {
|
|
41
|
+
// ① agent 拿不到 → 保留,绝不当完成
|
|
42
|
+
if (!env.agent) return { action: JUMP.KEEP, reason: 'agent-unavailable' };
|
|
43
|
+
|
|
44
|
+
// ② turnBoundary 读不到 → 保留
|
|
45
|
+
if (!env.turnBoundary) return { action: JUMP.KEEP, reason: 'turnBoundary-unavailable' };
|
|
46
|
+
|
|
47
|
+
// ③ 新一轮了 → 作废(不是播报)
|
|
48
|
+
if (p.lastTurn !== undefined && env.turnBoundary.lastTurn > p.lastTurn) {
|
|
49
|
+
return { action: JUMP.DROP, reason: 'new-turn' };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ④ 轮次还开着 → 保留
|
|
53
|
+
if (env.turnBoundary.open !== null) return { action: JUMP.KEEP, reason: 'turn-open' };
|
|
54
|
+
|
|
55
|
+
// ⑤ 还有在飞工作 → 保留
|
|
56
|
+
if (env.inFlight.length > 0) return { action: JUMP.KEEP, reason: 'still-inflight' };
|
|
57
|
+
|
|
58
|
+
// ⑥ 真空闲 → 播报
|
|
59
|
+
return { action: JUMP.FLUSH, reason: 'worktree-idle' };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 超时判定(与 flushPending 的 viaTimeout 分支对应)。 */
|
|
63
|
+
function decideTimeout(env) {
|
|
64
|
+
if (env.agent === undefined) return { reason: 'timeout-unknown', claimsDone: false };
|
|
65
|
+
let busy;
|
|
66
|
+
try {
|
|
67
|
+
busy = env.inFlight.length > 0;
|
|
68
|
+
} catch {
|
|
69
|
+
return { reason: 'timeout-unknown', claimsDone: false };
|
|
70
|
+
}
|
|
71
|
+
if (busy) return { reason: 'timeout-still-running', claimsDone: false };
|
|
72
|
+
return { reason: 'worktree-idle', claimsDone: true };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ══ 1. 无子任务:立即播报 ══════════════════════════════════════════════
|
|
76
|
+
test('T1: 无子任务 → 不挂起,立即播报一次', () => {
|
|
77
|
+
// scheduleOrNotify 的语义:inFlight 为空就直接 emitDone,不进 pending
|
|
78
|
+
const inflight = [];
|
|
79
|
+
assert.equal(inflight.length, 0, '无在飞工作');
|
|
80
|
+
// 直接播(不产生 pending)—— 用"pending 数量为 0"表达
|
|
81
|
+
const pendingAfter = 0;
|
|
82
|
+
assert.equal(pendingAfter, 0);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// ══ 2. 有子任务:挂起不播 ══════════════════════════════════════════════
|
|
86
|
+
test('T2: 有子任务 → 挂起,不播报', () => {
|
|
87
|
+
const p = { lastTurn: 5 };
|
|
88
|
+
const r = decidePending(p, {
|
|
89
|
+
agent: { status: 'idle' },
|
|
90
|
+
turnBoundary: { open: null, lastTurn: 5 },
|
|
91
|
+
inFlight: [{ kind: 'job', id: 'j1' }],
|
|
92
|
+
});
|
|
93
|
+
assert.equal(r.action, JUMP.KEEP);
|
|
94
|
+
assert.equal(r.reason, 'still-inflight');
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// ══ 3. 子任务结束时主 Agent 暂时 running:不得清除 ══════════════════════
|
|
98
|
+
test('T3: 子任务结束但主 Agent 暂时 running → pending 不被清除', () => {
|
|
99
|
+
const p = { lastTurn: 5 };
|
|
100
|
+
const r = decidePending(p, {
|
|
101
|
+
agent: { status: 'running' }, // ← 关键:running
|
|
102
|
+
turnBoundary: { open: 123, lastTurn: 5 }, // 轮次还开着
|
|
103
|
+
inFlight: [],
|
|
104
|
+
});
|
|
105
|
+
// 必须是 KEEP,**不是 DROP** —— 这是原实现最大的错
|
|
106
|
+
assert.equal(r.action, JUMP.KEEP, '主 Agent 暂时 running 绝不能清掉 pending');
|
|
107
|
+
assert.equal(r.reason, 'turn-open');
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// ══ 4. 随后 idle 且工作树为空:flush 播报一次 ══════════════════════════
|
|
111
|
+
test('T4: 主 Agent idle + 工作树空 → flush 播报一次', () => {
|
|
112
|
+
const p = { lastTurn: 5 };
|
|
113
|
+
const r = decidePending(p, {
|
|
114
|
+
agent: { status: 'idle' },
|
|
115
|
+
turnBoundary: { open: null, lastTurn: 5 },
|
|
116
|
+
inFlight: [],
|
|
117
|
+
});
|
|
118
|
+
assert.equal(r.action, JUMP.FLUSH);
|
|
119
|
+
assert.equal(r.reason, 'worktree-idle');
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
// ══ 5. 用户主动发新消息:取消旧 pending ════════════════════════════════
|
|
123
|
+
test('T5: 新一轮开始(lastTurn 递增)→ 旧 pending 作废', () => {
|
|
124
|
+
const p = { lastTurn: 5 };
|
|
125
|
+
const r = decidePending(p, {
|
|
126
|
+
agent: { status: 'running' },
|
|
127
|
+
turnBoundary: { open: 999, lastTurn: 6 }, // lastTurn 从 5 → 6
|
|
128
|
+
inFlight: [],
|
|
129
|
+
});
|
|
130
|
+
assert.equal(r.action, JUMP.DROP, '新一轮必须让旧通知作废');
|
|
131
|
+
assert.equal(r.reason, 'new-turn');
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// ══ 6. Agent 因子任务返回内部继续:不得误取消 ══════════════════════════
|
|
135
|
+
test('T6: 同一轮内 Agent 内部继续(lastTurn 不变)→ 不得误取消', () => {
|
|
136
|
+
const p = { lastTurn: 5 };
|
|
137
|
+
const r = decidePending(p, {
|
|
138
|
+
agent: { status: 'running' },
|
|
139
|
+
turnBoundary: { open: 2000, lastTurn: 5 }, // lastTurn 仍是 5
|
|
140
|
+
inFlight: [{ kind: 'subagent', id: 's1' }],
|
|
141
|
+
});
|
|
142
|
+
assert.equal(r.action, JUMP.KEEP, '同一轮的内部继续不能作废旧 pending');
|
|
143
|
+
assert.notEqual(r.action, JUMP.DROP);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
// ══ 7. 多个子任务陆续结束:必须等最后一个 ══════════════════════════════
|
|
147
|
+
test('T7: 两个子任务陆续结束 → 只有全空才 flush', () => {
|
|
148
|
+
const p = { lastTurn: 5 };
|
|
149
|
+
const env2 = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 5 },
|
|
150
|
+
inFlight: [{ kind: 'job', id: 'j1' }, { kind: 'job', id: 'j2' }] };
|
|
151
|
+
assert.equal(decidePending(p, env2).action, JUMP.KEEP, '两个都在 → 等');
|
|
152
|
+
|
|
153
|
+
const env1 = { ...env2, inFlight: [{ kind: 'job', id: 'j2' }] };
|
|
154
|
+
assert.equal(decidePending(p, env1).action, JUMP.KEEP, '还剩一个 → 继续等');
|
|
155
|
+
|
|
156
|
+
const env0 = { ...env2, inFlight: [] };
|
|
157
|
+
assert.equal(decidePending(p, env0).action, JUMP.FLUSH, '全空 → 播');
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// ══ 8. jobs 事件重复触发:不能重复播报 ════════════════════════════════
|
|
161
|
+
test('T8: 重复触发 reevaluate 不会二次播报(flush 即删 pending)', () => {
|
|
162
|
+
const pending = new Map();
|
|
163
|
+
pending.set('s1', { lastTurn: 5 });
|
|
164
|
+
|
|
165
|
+
let notified = 0;
|
|
166
|
+
const env = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 5 }, inFlight: [] };
|
|
167
|
+
|
|
168
|
+
for (let i = 0; i < 5; i++) {
|
|
169
|
+
for (const id of [...pending.keys()]) {
|
|
170
|
+
const r = decidePending(pending.get(id), env);
|
|
171
|
+
if (r.action === JUMP.FLUSH) { notified += 1; pending.delete(id); }
|
|
172
|
+
else if (r.action === JUMP.DROP) { pending.delete(id); }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
assert.equal(notified, 1, '重复触发只能播一次');
|
|
176
|
+
assert.equal(pending.size, 0);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// ══ 9. agent/status 重复触发:同样不重复 ═══════════════════════════════
|
|
180
|
+
test('T9: agent/status 重复触发不重复播报', () => {
|
|
181
|
+
const pending = new Map([['s1', { lastTurn: 2 }]]);
|
|
182
|
+
let notified = 0;
|
|
183
|
+
const env = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 2 }, inFlight: [] };
|
|
184
|
+
for (let i = 0; i < 10; i++) {
|
|
185
|
+
for (const id of [...pending.keys()]) {
|
|
186
|
+
const r = decidePending(pending.get(id), env);
|
|
187
|
+
if (r.action === JUMP.FLUSH) { notified++; pending.delete(id); }
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
assert.equal(notified, 1);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// ══ 10. 超时但仍有子任务:不能宣告完成 ═════════════════════════════════
|
|
194
|
+
test('T10: 超时但仍有任务 → 不念"完成",用不同文案', () => {
|
|
195
|
+
const stillBusy = decideTimeout({ agent: { status: 'idle' }, inFlight: [{ kind: 'job', id: 'j1' }] });
|
|
196
|
+
assert.equal(stillBusy.claimsDone, false, '还有任务时绝不能宣告完成');
|
|
197
|
+
assert.equal(stillBusy.reason, 'timeout-still-running');
|
|
198
|
+
|
|
199
|
+
const unknown = decideTimeout({ agent: undefined, inFlight: [] });
|
|
200
|
+
assert.equal(unknown.claimsDone, false, '状态未知时也不能宣告完成');
|
|
201
|
+
assert.equal(unknown.reason, 'timeout-unknown');
|
|
202
|
+
|
|
203
|
+
const reallyDone = decideTimeout({ agent: { status: 'idle' }, inFlight: [] });
|
|
204
|
+
assert.equal(reallyDone.reason, 'worktree-idle', '复查确认空了才按完成处理');
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// ══ 11. 不同 Agent 同时工作:互不影响 ══════════════════════════════════
|
|
208
|
+
test('T11: 多个会话各自挂起/放行互不干扰', () => {
|
|
209
|
+
const pending = new Map([
|
|
210
|
+
['sA', { lastTurn: 1 }],
|
|
211
|
+
['sB', { lastTurn: 7 }],
|
|
212
|
+
]);
|
|
213
|
+
// sA 空闲、sB 还有活
|
|
214
|
+
const envA = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 1 }, inFlight: [] };
|
|
215
|
+
const envB = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 7 }, inFlight: [{ kind: 'job', id: 'x' }] };
|
|
216
|
+
|
|
217
|
+
assert.equal(decidePending(pending.get('sA'), envA).action, JUMP.FLUSH, 'sA 该播');
|
|
218
|
+
assert.equal(decidePending(pending.get('sB'), envB).action, JUMP.KEEP, 'sB 还得等');
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
// ══ 12. 状态不可用:不能误判完成 ═══════════════════════════════════════
|
|
222
|
+
test('T12: agent / turnBoundary 读不到 → 保留,不误判完成', () => {
|
|
223
|
+
const p = { lastTurn: 3 };
|
|
224
|
+
const noAgent = decidePending(p, { agent: undefined, turnBoundary: { open: null, lastTurn: 3 }, inFlight: [] });
|
|
225
|
+
assert.equal(noAgent.action, JUMP.KEEP, 'agent 读不到时必须保留(原先误 flush)');
|
|
226
|
+
assert.equal(noAgent.reason, 'agent-unavailable');
|
|
227
|
+
|
|
228
|
+
const noTb = decidePending(p, { agent: { status: 'idle' }, turnBoundary: null, inFlight: [] });
|
|
229
|
+
assert.equal(noTb.action, JUMP.KEEP);
|
|
230
|
+
assert.equal(noTb.reason, 'turnBoundary-unavailable');
|
|
231
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v0.4.64:锁住 jobs.list 的调用参数。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么必须单独写这条测试
|
|
5
|
+
*
|
|
6
|
+
* 空闲门(idleGate)从 v0.4.62 起就有一个**静默失效**的 bug:
|
|
7
|
+
*
|
|
8
|
+
* jobs = js.list(agent) // ✗ 传了 agent 对象
|
|
9
|
+
* jobs = js.list(agent?.id) // ✓ 应传 id 字符串(DSH 官方用法)
|
|
10
|
+
*
|
|
11
|
+
* 参数类型不对 → 服务返回空数组 → `collectInFlight` 永远判定没有在飞工作
|
|
12
|
+
* → 空闲门从不挂起,回合一结束就播报。
|
|
13
|
+
*
|
|
14
|
+
* **原有 20+ 条空闲门单测全部通过**,因为它们是直接给 `collectInFlight`
|
|
15
|
+
* 喂假数据的 —— 绕过了 `jobs.list` 这一层。这正是"测试绿但功能坏"的典型:
|
|
16
|
+
* 测了纯函数,没测调用契约。
|
|
17
|
+
*
|
|
18
|
+
* 所以这条测试不看行为,只看**传参形状**(静态断言源码)。丑,但有效。
|
|
19
|
+
*/
|
|
20
|
+
import { test } from 'node:test';
|
|
21
|
+
import assert from 'node:assert/strict';
|
|
22
|
+
import { readFileSync } from 'node:fs';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { dirname, join } from 'node:path';
|
|
25
|
+
|
|
26
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
27
|
+
const INDEX = readFileSync(join(ROOT, 'lib/index.js'), 'utf8');
|
|
28
|
+
|
|
29
|
+
/** 从 inFlightOf 函数体里切片(到下一个同名缩进级 function 为止)。 */
|
|
30
|
+
function inFlightBody() {
|
|
31
|
+
const start = INDEX.indexOf('function inFlightOf(agent) {');
|
|
32
|
+
assert.ok(start >= 0, '应能找到 inFlightOf');
|
|
33
|
+
const rest = INDEX.slice(start);
|
|
34
|
+
const end = rest.search(/\n {0,4}(?:function |\/\*\*)/);
|
|
35
|
+
return end > 0 ? rest.slice(0, end) : rest.slice(0, 3000);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test('J1: jobs.list 必须传 agent.id,不能传 agent 对象', () => {
|
|
39
|
+
const body = inFlightBody();
|
|
40
|
+
// ✗ 绝不能出现 js.list(agent) —— 参数是对象
|
|
41
|
+
assert.doesNotMatch(body, /js\.list\(\s*agent\s*\)/,
|
|
42
|
+
'jobs.list 收到 agent 对象会返回空数组,导致空闲门永不挂起(v0.4.62 起的真 bug)');
|
|
43
|
+
// ✓ 必须取出 id 再传
|
|
44
|
+
assert.match(body, /const aid = agent && agent\.id/,
|
|
45
|
+
'必须先取 agent.id');
|
|
46
|
+
assert.match(body, /js\.list\(aid\)/,
|
|
47
|
+
'必须用 id 字符串调用 jobs.list');
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('J2: 还要查「无 agent 的全局任务」', () => {
|
|
51
|
+
const body = inFlightBody();
|
|
52
|
+
// DSH 官方是 [void 0, ...liveAgents],插件对应 jobs.list(undefined)
|
|
53
|
+
assert.match(body, /js\.list\(undefined\)/,
|
|
54
|
+
'有些后台任务不属于任何 agent,只查当前 agent 会漏掉它们');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('J3: jobs.list 抛异常时不能把空闲门打挂', () => {
|
|
58
|
+
const body = inFlightBody();
|
|
59
|
+
assert.match(body, /catch\s*\(e\)\s*\{[\s\S]*?jobs\.list failed/,
|
|
60
|
+
'失败要 catch 住并记录,不能冒泡(否则回合一结束就抛错、通知丢失)');
|
|
61
|
+
});
|