@240xu/dsh-message-ops 0.9.4 → 0.9.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-message-ops",
3
- "version": "0.9.4",
3
+ "version": "0.9.6",
4
4
  "description": "DSH web 插件:消息级回滚 / 删除 / 恢复(补 dsh 官方没有的部分)。分支与导出用官方内置能力。",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/client.js CHANGED
@@ -141,6 +141,7 @@ window.__ModuleLoader__.load({
141
141
  'undo.done.undo': '已回滚上一条消息',
142
142
  'undo.done.redo': '已恢复上一条被回滚的消息',
143
143
  'undo.none': '没有可回滚的消息',
144
+ 'undo.none.redo': '没有可恢复的回滚',
144
145
  'redo.label': '恢复上一条被回滚的消息',
145
146
  'redo.desc': '把回滚掉的消息重新放回对话',
146
147
  'menu.ops': 'Message ops',
@@ -702,6 +703,9 @@ window.__ModuleLoader__.load({
702
703
  try { data = await res.json() } catch { /* keep {} */ }
703
704
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
704
705
  notifyDone(t('done.revert'))
706
+ // 0.9.6:回填被删掉的那句用户原文(边界是 AI 消息时取它之前那条用户消息)。
707
+ // 此前这个入口完全不回填 —— 表现就是「回滚成功但消息框空着」。
708
+ refillComposer(sessionId, seq)
705
709
  revealSession()
706
710
  emitChanged()
707
711
  })
@@ -961,7 +965,27 @@ window.__ModuleLoader__.load({
961
965
  // 被回滚遮蔽的消息 → 配对候选与 DOM 块零交集。
962
966
  // 修法:DOM 配对必须覆盖全部 user 行(含遮蔽态)。
963
967
  // 注意:对话框的「可回滚目标」列表仍应过滤 visible(那是另一套语义)。
964
- const injected = (raw) => /^<system-reminder|current\s+runtime\s+context|^<system-Reminder/i.test(String(raw || ''))
968
+ // 0.9.6:原先只排 system-reminder / runtime context 两种,
969
+ // 但宿主把 `background job …`、`Agent … sent a message:`、
970
+ // `Background subagent … finished`、`[model changed: …]` 也记成 role=user,
971
+ // 于是 /undo 会把**通知行**当目标 —— 回滚范围与回填文本都变成通知内容
972
+ // (378 会话普查:38 个 10% 命中;实测 2188f4ac 目标是
973
+ // "Background subagent f09a18f6… finished…",而用户那句在 seq829)。
974
+ // 稳妥做法本该在服务端打 injected 标志,先在客户端补齐正则。
975
+ // 0.9.6:原先只排 system-reminder / runtime context 两种,但宿主把通知也
976
+ // 记成 role=user,/undo 会把**通知行**当目标 —— 回滚范围与回填文本都变成
977
+ // 通知内容(378 会话普查 38 个 10% 命中;实测 2188f4ac 目标是
978
+ // "Background subagent f09a18f6… finished…",用户那句其实在 seq829)。
979
+ //
980
+ // 正则**按 120 份日志的真实样本**收紧,不靠猜:
981
+ // 256 × <system-reminder>… 128 × background job bash-358 (…
982
+ // 38 × [model changed: … 26 × Background subagent <uuid>
983
+ // 21 × Agent <uuid> sent a message:
984
+ // 关键约束:id 后必须跟得上具体形态([\w-]+ / [0-9a-f]{8}-),
985
+ // 否则 `Background job 是我自己的问题` 这种真人输入会被误杀
986
+ // (曾用 ^background job\b,测试当场抓到这个误杀)。
987
+ // 样本里没出现过的模式(已停止 / User feedback:)一律**不加** —— 没证据就不猜。
988
+ const injected = (raw) => /^<system-reminder|current\s+runtime\s+context|^<system-Reminder|^background job\s+[\w-]+|^Background subagent\s+[0-9a-f]{8}-|^Agent\s+[0-9a-f]{8}-|^\[model changed:/i.test(String(raw || ''))
965
989
  const rows = ((d && d.messages) || [])
966
990
  .filter((m) => m && m.role === 'user')
967
991
  .map((m) => ({ seq: m.seq, sn: norm(m.snippet), raw: String(m.snippet == null ? '' : m.snippet), fullText: m.fullText ?? null, visible: m.visible !== false }))
@@ -1014,8 +1038,9 @@ window.__ModuleLoader__.load({
1014
1038
  var byTurnStep = new Map();
1015
1039
  var byCallId = new Map();
1016
1040
  var byTurn = new Map();
1017
- var visible = new Set(); // 在模型 surface 上的 seq
1018
- var visibleTurns = new Set(); // 含至少一条可见消息的 turn 号
1041
+ var visible = new Set(); // 在模型 surface 上(仅用于「可回滚目标」)
1042
+ var shadowed = new Set(); // 落在 replace 区间内 = 已被回滚(transcript 藏行判据)
1043
+ var visibleTurns = new Set(); // 含至少一条**未被遮蔽**消息的 turn 号(回合 chrome)
1019
1044
  var dupMessageId = 0
1020
1045
  var dupByMessageId = new Map();
1021
1046
  for (var i = 0; i < list.length; i++) {
@@ -1040,14 +1065,15 @@ window.__ModuleLoader__.load({
1040
1065
  }
1041
1066
  if (m.type === 'tool/call' && m.id != null) byCallId.set(String(m.id), m.seq);
1042
1067
  if (m.turn != null && !byTurn.has(String(m.turn))) byTurn.set(String(m.turn), m.seq);
1043
- if (m.visible === true) {
1044
- visible.add(m.seq);
1045
- if (m.turn != null) visibleTurns.add(String(m.turn));
1046
- }
1068
+ if (m.visible === true) visible.add(m.seq);
1069
+ // 0.9.6:藏行判据改用 shadowed(replace 区间),**不用** visible(模型 surface)。
1070
+ // visible 在 live 路径下对 tool/call 恒 false → 会把整页工具行全藏。
1071
+ if (m.shadowed === true) shadowed.add(m.seq);
1072
+ else if (m.turn != null) visibleTurns.add(String(m.turn));
1047
1073
  }
1048
1074
  // turnEnd 优先:它对「该 turn 内一条消息都没有」的情况仍然有效
1049
1075
  if (turnEnd) for (const k in turnEnd) if (Object.prototype.hasOwnProperty.call(turnEnd, k)) byTurn.set(k, turnEnd[k])
1050
- return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, visible, visibleTurns, dupMessageId, total: list.length };
1076
+ return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, visible, shadowed, visibleTurns, dupMessageId, total: list.length };
1051
1077
  };
1052
1078
 
1053
1079
  /** node-key → { seq, all }(all = 同 id 的全部 seq,处理 restore 重放副本)。 */
@@ -1101,6 +1127,9 @@ window.__ModuleLoader__.load({
1101
1127
  var hidden = 0, unresolved = 0, shown = 0;
1102
1128
  for (var i = 0; i < rows.length; i++) {
1103
1129
  var row = rows[i];
1130
+ // 0.9.6 判据:**replace 区间(shadowed)**。
1131
+ // 演进:revertFences 塌缩(离散区间→min,全藏)→ visible(模型 surface,
1132
+ // live 路径下 tool/call 全藏)→ 现在的 shadowed(恒定、与会话活跃无关)。
1104
1133
  // 0.9.4 判据(见下):**模型 surface**。此前用 revertFences 塌缩成
1105
1134
  // `seq >= min(fences)`,在一个有 19 个**离散** marker 的会话里
1106
1135
  // min fence=10 → seq>=10 全藏 → 4792/4793 全被隐藏 → 正文几乎空白
@@ -1109,11 +1138,13 @@ window.__ModuleLoader__.load({
1109
1138
  if (hit === null) { unresolved++; row.removeAttribute('hidden'); continue; }
1110
1139
  var shouldHide;
1111
1140
  if (hit.turn !== undefined) {
1112
- // 回合 chrome:这个 turn 还有可见消息就露出来
1141
+ // 回合 chrome:本 turn 还有未被遮蔽的消息就露出
1113
1142
  shouldHide = !idx.visibleTurns.has(String(hit.turn));
1114
1143
  } else {
1115
- // 消息类:直接问「它在模型 surface 上吗」
1116
- shouldHide = !idx.visible.has(hit.seq);
1144
+ // 消息/工具类:**是否落在 replace 区间内**(= 被回滚掉了)。
1145
+ // ⚠️ 不能用 visible(模型 surface)——live 路径下 tool/call 恒不在 surface,
1146
+ // 会把整页工具行全藏(实测 157 行藏 152 行)。
1147
+ shouldHide = idx.shadowed.has(hit.seq);
1117
1148
  }
1118
1149
  if (shouldHide) { hidden++; row.setAttribute('hidden', 'until-found'); }
1119
1150
  else { shown++; row.removeAttribute('hidden'); }
@@ -1223,6 +1254,8 @@ window.__ModuleLoader__.load({
1223
1254
  try { data = await res.json() } catch { /* keep {} */ }
1224
1255
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
1225
1256
  notifyDone(__t('done.revert'))
1257
+ // 0.9.6:统一回填出口 —— 这个入口原先也不回填
1258
+ refillComposer(sid, row.seq)
1226
1259
  try { window.dispatchEvent(new Event(CHANGED_EVENT)) } catch { /* non-browser */ }
1227
1260
  try {
1228
1261
  if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
@@ -1454,41 +1487,117 @@ window.__ModuleLoader__.load({
1454
1487
  /** 执行 undo/redo。返回 true 表示确实动过盘。 */
1455
1488
  /** __currentSessionId 来自 DOM dataset,可能带 `session-` 前缀;API 只要裸 uuid。 */
1456
1489
  var bareSessionId = (id) => String(id || '').replace(/^session-/, '')
1457
- var runUndoRedo = (kind) => {
1458
- const sid = bareSessionId(__currentSessionId)
1459
- if (!sid) return false
1460
- const target = lastRevertable()
1461
- if (!target) {
1462
- notifyDone(__t('undo.none') || '没有可回滚的消息', 'error')
1490
+ /** 写盘成功后的统一收尾:通知、刷新、重放隐藏。 */
1491
+ /**
1492
+ * 写盘成功后的统一收尾。
1493
+ *
1494
+ * ⚠️ `rawSid` 必须是**带 `session-` 前缀**的 id:`uiWorkspace.openSession`
1495
+ * 内部 `sessions.retain(bare)` 只认 `session-<uuid>`(manager.js resolveTarget),
1496
+ * 传裸 uuid 会抛 `unknown session <bare>` —— 而外层 `catch { }` 静默吞掉,
1497
+ * 结果「视图重建」这条路径**从来没生效过**,只剩 150/700/1600ms 的 DOM 打补丁。
1498
+ * 本文件其它调用点(对话框 :403、:684、:858、:1229)传的都是带前缀的,
1499
+ * 只有 /undo /redo 因为先 `bareSessionId` 而传错。
1500
+ */
1501
+ var afterWrite = (rawSid, okMsg) => {
1502
+ notifyDone(okMsg)
1503
+ try { window.dispatchEvent(new Event(CHANGED_EVENT)) } catch { /* non-browser */ }
1504
+ try {
1505
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(rawSid)
1506
+ } catch (e) {
1507
+ if (window.__MOPS_DEBUG) console.warn('[message-ops] openSession failed:', e)
1508
+ }
1509
+ if (__peekRowsCache) { const c = __peekRowsCache(); if (c) c.at = 0 }
1510
+ const bare = bareSessionId(rawSid)
1511
+ for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(bare) }, delay)
1512
+ }
1513
+
1514
+ /**
1515
+ * 回填 composer(opencode 语义:回滚后把被删掉的那句原文还给输入框)。
1516
+ *
1517
+ * 0.9.6 统一出口 —— 此前 5 个回滚/恢复入口里只有 2 个回填
1518
+ * (对话框 :403 与 /undo :1495),悬停回滚按钮、AI 时钟按钮、dock Restore、
1519
+ * /redo **全部不回填**,表现正是「回滚成功了但消息框是空的」。
1520
+ *
1521
+ * 取文本规则:rowsCache 里 seq <= boundary 的最后一条带 fullText 的行。
1522
+ * - /undo → boundary 就是被回滚的那条用户消息 → 取到它自己 ✓
1523
+ * - AI 时钟按钮 → boundary 是 AI 消息 seq → 取到它之前那条用户消息 ✓
1524
+ * 会话不匹配时直接放弃(不跨会话写,避免串台)。
1525
+ */
1526
+ var refillComposer = (rawSid, boundarySeq) => {
1527
+ try {
1528
+ const cache = __peekRowsCache ? __peekRowsCache() : null
1529
+ if (!cache || !Array.isArray(cache.rows)) return false
1530
+ const want = bareSessionId(rawSid)
1531
+ if (bareSessionId(cache.sid) !== want) return false
1532
+ const rows = cache.rows.filter((r) => r && typeof r.seq === 'number' && r.seq <= boundarySeq && r.fullText)
1533
+ if (!rows.length) return false
1534
+ if (!__inputActions || typeof __inputActions.setDraft !== 'function') return false
1535
+ __inputActions.setDraft(rows[rows.length - 1].fullText)
1536
+ return true
1537
+ } catch (e) {
1538
+ // 原来这里 `catch {}` 完全静默 —— 失败了连痕迹都没有,排查时看不到
1539
+ console.warn('[message-ops] setDraft failed:', e)
1463
1540
  return false
1464
1541
  }
1465
- const verb = kind === 'redo' ? 'restore' : 'revert'
1466
- fetch('/api/message-ops/' + verb, {
1542
+ }
1543
+
1544
+ /**
1545
+ * /undo —— 回滚最后一条**在模型 surface 上**的用户消息,原文回填输入框。
1546
+ * 目标必须是 surface 上的那条:restore 是「重放」语义,副本带新 seq 落在日志
1547
+ * 尾部但不在 surface 上,服务端会以 `surface replace: start seq N not found in surface` 拒绝。
1548
+ */
1549
+ var runUndo = () => {
1550
+ const rawSid = __currentSessionId
1551
+ const sid = bareSessionId(rawSid)
1552
+ if (!sid) { notifyDone(__t('undo.none') || '没有可回滚的消息', 'error'); return false }
1553
+ const target = lastRevertable()
1554
+ if (!target) { notifyDone(__t('undo.none') || '没有可回滚的消息', 'error'); return false }
1555
+ fetch('/api/message-ops/revert', {
1467
1556
  method: 'POST', headers: { 'content-type': 'application/json' },
1468
1557
  body: JSON.stringify({ sessionId: sid, seq: target.seq }),
1469
1558
  })
1470
1559
  .then(async (res) => {
1471
- let data = {}
1472
- try { data = await res.json() } catch { /* keep {} */ }
1560
+ const data = await res.json().catch(() => ({}))
1473
1561
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
1474
- notifyDone(kind === 'redo' ? __t('undo.done.redo') : __t('undo.done.undo'))
1475
- // opencode 语义:回滚后**原文回输入框**,用户可改后重发
1476
- if (kind !== 'redo' && target.fullText && __inputActions && typeof __inputActions.setDraft === 'function') {
1477
- try { __inputActions.setDraft(target.fullText) } catch { /* 回填失败不阻断 */ }
1478
- }
1479
- try { window.dispatchEvent(new Event(CHANGED_EVENT)) } catch { /* non-browser */ }
1480
- try {
1481
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
1482
- } catch { /* 视图重建失败不阻断 */ }
1483
- if (__peekRowsCache) { const c = __peekRowsCache(); if (c) c.at = 0 }
1484
- for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(sid) }, delay)
1562
+ refillComposer(rawSid, target.seq) // 先回填,再重建视图(与对话框一致)
1563
+ afterWrite(rawSid, __t('undo.done.undo'))
1485
1564
  })
1486
- .catch((reason) => {
1487
- notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
1565
+ .catch((reason) => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
1566
+ return true
1567
+ }
1568
+
1569
+ /**
1570
+ * /redo —— 恢复**最新一条未恢复的 marker**。
1571
+ *
1572
+ * ⚠️ 0.9.5 修正:先前把 `lastRevertable()`(用户**消息** seq)传给 /restore,
1573
+ * 但 `opsRestore` 走 `planRestore(events, restoreSeq)` —— 它要的是 **marker seq**
1574
+ * (dock 传的 row.seq 就来自 activeMarkers)。传消息 seq 会找不到 marker 空转。
1575
+ */
1576
+ var runRedo = () => {
1577
+ const sid = bareSessionId(__currentSessionId)
1578
+ if (!sid) return false
1579
+ fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
1580
+ .then((r) => (r.ok ? r.json() : null))
1581
+ .then((d) => {
1582
+ if (!d || !d.ok) throw new Error((d && d.error) || 'messages unavailable')
1583
+ const markers = activeMarkers(d.messages || [])
1584
+ if (!markers.length) { notifyDone(__t('undo.none.redo') || '没有可恢复的回滚', 'error'); return null }
1585
+ const mk = markers[markers.length - 1] // 最新一条未恢复标记
1586
+ return fetch('/api/message-ops/restore', {
1587
+ method: 'POST', headers: { 'content-type': 'application/json' },
1588
+ body: JSON.stringify({ sessionId: sid, seq: mk.seq }),
1589
+ }).then(async (res) => {
1590
+ const data = await res.json().catch(() => ({}))
1591
+ if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
1592
+ afterWrite(sid, __t('undo.done.redo'))
1593
+ })
1488
1594
  })
1595
+ .catch((reason) => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
1489
1596
  return true
1490
1597
  }
1491
1598
 
1599
+ var runUndoRedo = (kind) => (kind === 'redo' ? runRedo() : runUndo())
1600
+
1492
1601
  /** 注册 /undo /redo 到官方斜杠管线。服务缺失时安静 no-op。 */
1493
1602
  var __undoRegistered = false
1494
1603
  var doRegisterUndoSlash = (ctx, it) => {
package/src/index.js CHANGED
@@ -266,6 +266,17 @@ async function opsList(targetCtx, sessionId) {
266
266
  let visibleCount = 0;
267
267
  for (const m of messages) {
268
268
  m.visible = visibleNodes ? visibleNodes.has(m.seq) : !shadowed.has(m.seq);
269
+ // 0.9.6:**shadowed 与 visible 是两套语义,不能混用。**
270
+ //
271
+ // visible = 「是否在**模型 surface** 上」—— 两条路径还不一致:
272
+ // live → live.surface.nodes(tool/call 根本不是 surface 节点 → 恒 false)
273
+ // fallback → !computeShadowed(seq)
274
+ // 拿它做 transcript 藏行判据会把整页工具行全藏(实测 157 行藏 152 行)。
275
+ //
276
+ // shadowed = 「是否落在任一 replace 区间内」—— 这才是「回滚掉的东西」,
277
+ // 且**与会话是否活跃无关**,恒由 computeShadowed(events) 算出。
278
+ // transcript 藏行必须用它;visible 只留给「可回滚目标」(lastRevertable)。
279
+ m.shadowed = shadowed.has(m.seq);
269
280
  if (m.visible) visibleCount++;
270
281
  }
271
282
  // 0.8.0 按轮步进:为每个回撤/删除标记附恢复进度与"待恢复轮"。
@@ -424,7 +435,7 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
424
435
  const result = applyRestore(acq.session, plan, {
425
436
  flush: () => { flushSessions(targetCtx, acq.session); },
426
437
  });
427
- for (const post of noticeWindowPostamble(winR)) acq.session.append(post.kind, post.data);
438
+ for (const post of noticeWindowPostamble(win)) acq.session.append(post.kind, post.data);
428
439
  return { ok: true, ...result, discarded: plan.discard === true, upToSeq: plan.upToSeq, restoredSourceSeqs: plan.replayable.map((i) => i.seq), range: { startSeq: plan.startSeq, endSeq: plan.endSeq } };
429
440
  } finally {
430
441
  acq.release();
package/src/ops-core.js CHANGED
@@ -153,6 +153,27 @@ export function replayEventData(item, ts, version = 4) {
153
153
  source: messageSource("assistant", version),
154
154
  content: [{ type: "text", text: item.text }],
155
155
  },
156
+ // ⚠️ v4 契约 `stream: AssistantStreamRecord[]` **非可选**
157
+ // (SessionEventMap,见 dsh-agent-preset-registry/lib/typert.host.js:647)。
158
+ //
159
+ // 缺它的后果不是「格式闸拒绝」——格式闸对 stream 只有 Array.isArray 守卫,
160
+ // 会放行——而是**运行期炸在投影层**:
161
+ // dsh-token-meter/lib/types/usage-projection.js:65 usageOf()
162
+ // → data.usage === undefined 时回落到
163
+ // dsh-llm/lib/index.js:1412 lastAssistantStreamChunk(stream, 'usage')
164
+ // → `for (index = stream.length - 1; ...)` ← stream 是 undefined
165
+ // → TypeError: Cannot read properties of undefined (reading 'length')
166
+ // 抛出点没有 try/catch:
167
+ // - 历史加载 → dsh-session-query/lib/index.js:482 → UI「Failed to load history」→ **正文 0 行**
168
+ // - 控制流基线 → dsh-api-session-controller/lib/index.js:1178 → 逸出 async* →
169
+ // `[session-controller] control stream failed`(一个坏会话打死全站控制流)
170
+ //
171
+ // `stream: []` 是**已实测安全**的取值:
172
+ // expandAssistantStream([]) → [] → assertCurrentAssistantStreams 里 timed.length===0 直接 continue,
173
+ // 跳过 content/usage/replayState 的 deepStrictEqual 校验;UI 走 message.content 渲染,不依赖 stream。
174
+ // ⚠️ 反面教材:不要写「半填充流」(如只放 message-end/usage chunk)——
175
+ // 一旦 timed.length !== 0,宿主要求 blocks()/usage/replayState 与 message 全部深等,做不全就是新的写坏。
176
+ stream: [],
156
177
  };
157
178
  }
158
179
 
@@ -0,0 +1,106 @@
1
+ /**
2
+ * 0.9.6 composer 回填(「回滚了但消息框是空的」)。
3
+ *
4
+ * 专家组定案的三条根因:
5
+ * R2 5 个回滚入口里只有 2 个回填 → 统一 refillComposer 出口
6
+ * R4 afterWrite 把**裸 uuid** 传给 openSession → `unknown session` 必抛且被
7
+ * `catch {}` 静默吞掉 → 视图重建从没生效过
8
+ * R1 目标会选到宿主注入的伪 user 行(通知),回填文本不是用户写的那句
9
+ */
10
+ import test from 'node:test'
11
+ import assert from 'node:assert/strict'
12
+ import { readFileSync } from 'node:fs'
13
+ import { fileURLToPath } from 'node:url'
14
+ import { dirname, join } from 'node:path'
15
+
16
+ const src = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'client.js'), 'utf8')
17
+
18
+ /** 与 refillComposer 同构的边界选择 */
19
+ const pickForRefill = (rows, boundarySeq) => {
20
+ const hit = rows.filter((r) => r && typeof r.seq === 'number' && r.seq <= boundarySeq && r.fullText)
21
+ return hit.length ? hit[hit.length - 1] : null
22
+ }
23
+
24
+ /** 与 client.js 的 injected 同构(从源码里截出正则字面量校验覆盖面) */
25
+ const injectedSource = (() => {
26
+ const m = src.match(/const injected = \(raw\) => (\/[\s\S]*?\/[gimsuy]*)\.test/)
27
+ return m ? new RegExp(m[1].slice(1, m[1].lastIndexOf('/')), m[1].slice(m[1].lastIndexOf('/') + 1)) : null
28
+ })()
29
+
30
+ test('/undo:boundary 就是被回滚那条 → 回填它自己', () => {
31
+ const rows = [
32
+ { seq: 8, fullText: '第一句' },
33
+ { seq: 54, fullText: '要撤销的这句' },
34
+ { seq: 89, fullText: '重放副本' },
35
+ ]
36
+ assert.equal(pickForRefill(rows, 54).fullText, '要撤销的这句')
37
+ })
38
+
39
+ test('AI 时钟按钮:boundary 是 AI 消息 → 取它之前那条用户消息', () => {
40
+ const rows = [
41
+ { seq: 8, fullText: '我问的问题' },
42
+ { seq: 18, fullText: null }, // assistant 没有 fullText
43
+ { seq: 54, fullText: '下一句' },
44
+ ]
45
+ // boundary = 18(AI 消息 seq)
46
+ assert.equal(pickForRefill(rows, 18).seq, 8, '取边界之前最后一条带全文的')
47
+ // 边界之后的不该被取到
48
+ assert.equal(pickForRefill(rows, 54).seq, 54)
49
+ })
50
+
51
+ test('无可用行 → 返回 null(调用方不回填,不写空串)', () => {
52
+ assert.equal(pickForRefill([], 100), null)
53
+ assert.equal(pickForRefill([{ seq: 5, fullText: null }], 100), null)
54
+ assert.equal(pickForRefill([{ seq: 500, fullText: 'x' }], 100), null, '只在边界之后的不能被取到')
55
+ })
56
+
57
+ test('R4:afterWrite 必须传带 session- 前缀的 id 给 openSession', () => {
58
+ const m = src.match(/var afterWrite = \([\s\S]*?\n \}/)
59
+ assert.ok(m, '找不到 afterWrite')
60
+ assert.ok(/openSession\(rawSid\)/.test(m[0]),
61
+ 'openSession 收到裸 uuid 会抛 `sessions.retain: unknown session`,外层 catch {} 静默 → 视图重建从未生效')
62
+ assert.ok(!/openSession\(bare\)|openSession\(bareSessionId/.test(m[0]),
63
+ '不得传裸 id')
64
+ })
65
+
66
+ test('R2:所有 revert 入口都接了 refillComposer', () => {
67
+ const calls = (src.match(/\brefillComposer\(/g) || []).length
68
+ // 三个回滚入口:runUndo(/undo) + runRevert(AI 时钟) + runUserRevert(悬停)
69
+ // 注意:定义写法是 `refillComposer = (`,不匹配 `refillComposer(`
70
+ assert.equal(calls, 3, `refillComposer 调用 ${calls} 处,应为 3 个回滚入口`)
71
+ assert.ok(/var refillComposer = \(/.test(src), '缺 refillComposer 定义')
72
+ // 反例:restore / redo 不该回填(它们是加回内容,不是删)
73
+ const redo = src.match(/var runRedo = \(\) => \{[\s\S]*?\n \}/)
74
+ assert.ok(redo && !/refillComposer\(/.test(redo[0]), '/redo 不应回填 composer')
75
+ })
76
+
77
+ test('R1:injected 必须挡住宿主注入的伪 user 通知行', () => {
78
+ assert.ok(injectedSource, '源码里找不到 injected 正则')
79
+ const shouldBlock = [
80
+ '<system-reminder>系统提示</system-reminder>',
81
+ 'current runtime context 如下',
82
+ // 全部取自 120 份日志的真实样本
83
+ 'background job bash-358 (bash: END=$((SECONDS+2700)); i=0\nwhile ...',
84
+ 'Agent b813ff57-de81-426b-8519-3a6e3b83f9ef sent a message: 完成了',
85
+ 'Background subagent b813ff57-de81-426b-8519-3a6e3b83f9ef finished and will do no further work',
86
+ '[model changed: assistant turns above this point were generated by a different model]',
87
+ ]
88
+ const shouldAllow = [
89
+ '查询一下所有智能体的进度吧',
90
+ '分配几个子代理把模型广场的模型价格什么的做好',
91
+ 'agent 是什么意思',
92
+ 'Background job 是我自己的问题',
93
+ 'background job 是我自己的问题',
94
+ 'Agent 变成名词的用法呢',
95
+ '后台任务 background 作业怎么理解',
96
+ ]
97
+ for (const s of shouldBlock) assert.ok(injectedSource.test(s), `应被排除: ${s.slice(0, 40)}`)
98
+ for (const s of shouldAllow) assert.ok(!injectedSource.test(s), `不应被误杀: ${s.slice(0, 40)}`)
99
+ })
100
+
101
+ test('R2:不再用静默 catch 吞掉 setDraft 失败', () => {
102
+ const m = src.match(/var refillComposer = [\s\S]*?\n \}/)
103
+ assert.ok(m, '找不到 refillComposer')
104
+ assert.ok(/console\.warn/.test(m[0]), 'setDraft 失败必须留痕,原先 catch {} 完全静默')
105
+ assert.ok(!/catch \{ \/\* 回填失败不阻断 \*\/ \}/.test(m[0]))
106
+ })
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 0.9.5 /redo 的 seq 契约 —— 回归「传了消息 seq 导致空转」。
3
+ *
4
+ * `POST /api/message-ops/restore` 的 seq 是 **marker seq**:
5
+ * opsRestore(targetCtx, sessionId, restoreSeq, ...)
6
+ * → restoreProgress(events, restoreSeq) / planRestore(events, restoreSeq, ...)
7
+ * dock 传的 row.seq 来自 activeMarkers(marker 行)。
8
+ *
9
+ * 0.9.4 之前 /redo 传的是 lastRevertable() —— 那是**用户消息** seq,
10
+ * planRestore 找不到对应 marker → 计划为空 → 恢复不发生。
11
+ */
12
+ import test from 'node:test'
13
+ import assert from 'node:assert/strict'
14
+
15
+ const activeMarkers = (msgs) => (msgs || []).filter(
16
+ (m) => m.marker && m.sourceKind !== 'compact-checkpoint' && m.restoreComplete !== true,
17
+ )
18
+
19
+ const FIXTURE = [
20
+ { seq: 8, type: 'user/message', marker: false, visible: true },
21
+ { seq: 63, type: 'system/message', marker: true, range: { start: 54, end: 54 }, restoreComplete: true },
22
+ { seq: 76, type: 'system/message', marker: true, range: { start: 70, end: 70 }, restoreComplete: false },
23
+ { seq: 90, type: 'user/message', marker: false, visible: false },
24
+ ]
25
+
26
+ test('activeMarkers 只留未恢复、且非 compact-checkpoint 的 marker', () => {
27
+ const ms = activeMarkers(FIXTURE)
28
+ assert.equal(ms.length, 1)
29
+ assert.equal(ms[0].seq, 76)
30
+ })
31
+
32
+ test('/redo 必须传 marker seq,不是消息 seq', () => {
33
+ const markers = activeMarkers(FIXTURE)
34
+ const redoTarget = markers[markers.length - 1]
35
+ assert.equal(redoTarget.seq, 76, 'redo 目标 = 最新未恢复 marker')
36
+ // 反例:旧实现取最后一条用户消息
37
+ const messageTarget = FIXTURE.filter((m) => m.type === 'user/message').slice(-1)[0]
38
+ assert.notEqual(messageTarget.seq, redoTarget.seq,
39
+ '消息 seq 与 marker seq 不同 —— 混用会让 planRestore 找不到 marker')
40
+ assert.equal(redoTarget.marker, true, 'redo 目标必须是 marker')
41
+ })
42
+
43
+ test('全部恢复完毕 → 不发请求,给出无事可做的提示', () => {
44
+ const done = FIXTURE.map((m) => ({ ...m, restoreComplete: true }))
45
+ assert.equal(activeMarkers(done).length, 0, 'activeMarkers 为空 → 应短路')
46
+ })
47
+
48
+ test('/undo 与 /redo 的目标集合互不重叠', () => {
49
+ // undo 取 surface 上最后一条用户消息;redo 取最新未恢复 marker
50
+ const undoTarget = FIXTURE.filter((m) => m.type === 'user/message' && m.visible).slice(-1)[0]
51
+ const redoTarget = activeMarkers(FIXTURE).slice(-1)[0]
52
+ assert.equal(undoTarget.seq, 8)
53
+ assert.equal(redoTarget.seq, 76)
54
+ assert.notEqual(undoTarget.seq, redoTarget.seq)
55
+ })
@@ -0,0 +1,62 @@
1
+ /**
2
+ * 0.9.6 回归:重放 assistant 必须带 v4 必填字段 `data.stream`。
3
+ *
4
+ * 事故(专家组定位):replayEventData 漏写 stream → 宿主投影层
5
+ * dsh-token-meter/lib/types/usage-projection.js:65 usageOf()
6
+ * → data.usage === undefined 回落到
7
+ * dsh-llm/lib/index.js:1412 lastAssistantStreamChunk(stream,'usage')
8
+ * → `stream.length` on undefined → TypeError
9
+ * 抛出点无 try/catch,两个后果:
10
+ * - 历史加载失败 → 正文 0 行(dsh-session-query/lib/index.js:482)
11
+ * - 控制流基线失败 → 全站 `[session-controller] control stream failed`
12
+ * (dsh-api-session-controller/lib/index.js:1178,一个坏会话打死全站)
13
+ *
14
+ * 格式闸拦不住它:v3→v4 闸对 stream 只有 Array.isArray 守卫,缺失即跳过。
15
+ * 所以必须在这里锁契约。
16
+ */
17
+ import test from 'node:test'
18
+ import assert from 'node:assert/strict'
19
+ import { replayEventData } from '../src/ops-core.js'
20
+
21
+ const TS = { turn: 4, step: 2 }
22
+ const ASSISTANT_ITEM = { type: 'assistant/message', text: '重放的助手回答' }
23
+
24
+ test('重放 assistant 必须带 stream,且是数组', () => {
25
+ const data = replayEventData(ASSISTANT_ITEM, TS, 4)
26
+ assert.ok('stream' in data, '缺 data.stream —— 宿主投影会在 stream.length 上抛 TypeError')
27
+ assert.ok(Array.isArray(data.stream), 'stream 必须是 AssistantStreamRecord[]')
28
+ })
29
+
30
+ test('stream 只能是空数组:半填充流会触发宿主 deepStrictEqual 全量校验', () => {
31
+ const data = replayEventData(ASSISTANT_ITEM, TS, 4)
32
+ // 空数组 → expandAssistantStream([])→[] → assertCurrentAssistantStreams 直接 continue
33
+ // 一旦有条目,宿主要求 blocks()/usage/replayState 与 message 全部深等,做不全=新的写坏
34
+ assert.equal(data.stream.length, 0)
35
+ })
36
+
37
+ test('user 重放保持摊平契约,不带 stream(宿主只对 assistant 要求)', () => {
38
+ const data = replayEventData({ type: 'user/message', text: '原文' }, TS, 4)
39
+ assert.equal(data.role, 'user')
40
+ assert.ok(Array.isArray(data.content), 'user 本体摊平在 data 顶层(v4 契约)')
41
+ assert.ok(!('message' in data), 'user 不应包一层 message')
42
+ })
43
+
44
+ test('assistant 本体包一层 message(与 user 的摊平相反)', () => {
45
+ const data = replayEventData(ASSISTANT_ITEM, TS, 4)
46
+ assert.ok(data.message && typeof data.message === 'object')
47
+ assert.equal(data.message.role, 'assistant')
48
+ assert.equal(data.turn, 4)
49
+ assert.equal(data.step, 2)
50
+ })
51
+
52
+ test('缺 turn/step 仍被拒绝(不能写出注定无法加载的事件)', () => {
53
+ assert.throws(() => replayEventData(ASSISTANT_ITEM, null, 4), /turn\/step/)
54
+ assert.throws(() => replayEventData(ASSISTANT_ITEM, { turn: 0, step: 1 }, 4), /turn\/step/)
55
+ })
56
+
57
+ test('回归:index.js 里不能出现 winR 笔误(live restore 会 ReferenceError)', async () => {
58
+ const { readFileSync } = await import('node:fs')
59
+ const src = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8')
60
+ const winR = (src.match(/\bwinR\b/g) || []).length
61
+ assert.equal(winR, 0, `存在 ${winR} 处 winR —— opsRestore 的 live 分支会抛 ReferenceError`)
62
+ })