@240xu/dsh-message-ops 0.9.0 → 0.9.3

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/README.md CHANGED
@@ -484,3 +484,118 @@ opencode 实测:展开行 = 每条被遮蔽消息一行,点行**只恢复该
484
484
 
485
485
  `surfaceOp: replace` 的 notice **不会**渲染成对话行(`dsh-client-ui-chat/lib/client.js:9370`
486
486
  只渲染 `surfaceOp==="append"`),这是设计如此 —— 回撤提示由输入框上方的贴条负责。
487
+
488
+ ---
489
+
490
+ ## 0.9.1 / 0.9.2 · 回滚「真的生效了」
491
+
492
+ ### 问题:回滚对用户是无效的(0.9.0 及以前)
493
+
494
+ 浏览器实测发现:点回滚后 **dock 计数变了,但消息在界面上���行没变**。
495
+
496
+ 根因(源码 + 实测双重证实):**dsh 刻意把「模型可见」和「人类 transcript」分成两套**。
497
+ `surface.d.ts:51-63` 明写:
498
+
499
+ > *Append-origin events are that transcript's durable source material; **replacement copies stay model-only**.*
500
+
501
+ 即 `surfaceOp: {op:'replace'}` 只折叠**模型 surface**(实测 393→13 节点,模型侧确实生效),
502
+ 但前端 transcript **不施加遮蔽**,被遮蔽消息照常渲染且完全可见 —— 连我们的 replace
503
+ marker 自身都不渲染(`systemMessageDefinition.buildViewNode` 对 `surfaceOp !== 'append'`
504
+ 直接 `return null`,`dsh-client-ui-chat/lib/client.js:9370`)。
505
+
506
+ 所以之前那句「回滚已完成」是**误判**:只验了日志写入与 dock 计数,没验用户眼���。
507
+
508
+ ### 解法:渲染层按 node-key 精确映射
509
+
510
+ 每一行渲染节点带 `data-chat-node-key`,形态 `<len>:<kind><id>`,而 `<id>` 就是日志事件的字段:
511
+
512
+ | 行 kind | `<id>` | 查表 |
513
+ |---|---|---|
514
+ | `user` / `steering` | messageId | `byMessageId` |
515
+ | `assistant-step` | `<turn>:<step>` | `byTurnStep` |
516
+ | `tool-call` | callId | `byCallId` |
517
+ | `turn-tail` / `turn-process` / `turn-error` | turn 号 | `byTurn` ← **turn/end 的 seq** |
518
+ | `developer-message` | messageId | `byMessageId` |
519
+
520
+ 配合服务端的 `revertFences` / `turnEndSeq`,客户端做**精确查表 + fence 比较**,
521
+ 命中则 `row.setAttribute('hidden', 'until-found')`。
522
+
523
+ `hidden="until-found"` 与宿主 `useSearchableHidden` 同款:Ctrl+F 仍能搜到,
524
+ 且宿主的分页锚点选择器 `[data-chat-paging-anchor]:not(:empty):not([hidden])`
525
+ 会自动跳过,滚动恢复不受影响。
526
+
527
+ ### 三个踩过的坑(都有回归测试锁住)
528
+
529
+ 1. **不能用 `visible` 当隐藏判据**。`visible` 是「是否在模型 surface 上」,而
530
+ `tool/call` / `turn/*` / `model/*` **根本不是 surface 节点**,它们永远 `visible=false`
531
+ —— 照抄会把**所有**工具调用行永久藏掉(实测 3/3 全被误藏)。
532
+ 正确口径是 `reverted`(= opencode 的「边界及其后」:`messages.slice(0, boundaryIndex)`)。
533
+ 2. **回合页脚不是消息**,锚到 `turn/end` 的 seq,永远不在 `reverted` 集合里,
534
+ 所以判据必须**直接对 fence 数组比较**。
535
+ 且要用 `turn/end` 而非 `turn/start` —— 回撤边界常落在某个 turn **内部**。
536
+ 3. **旧的 40 字符前缀包含匹配**实测 4 条错 2 条(「继续」命中「继续,…」),
537
+ 已整体删除,改为 node-key 查表。
538
+
539
+ ### 实测结果
540
+
541
+ ```
542
+ 回滚后: hidden 5(user + turn-process×2 + turn-tail×2)
543
+ 被回滚消息 disappears from DOM ✅
544
+ 该轮之后的助手回答也消失 ✅
545
+ 更早的消息完好 ✅
546
+ 恢复后: hidden 0,dock 消失,消息全部回来 ✅
547
+ 查表命中率: unresolved 0 / mismatch 0 / hiddenButNotReverted 0 ✅
548
+ ```
549
+
550
+ ### 已知限制
551
+
552
+ - **restore 是「重放」语义**(dsh 无 unshadow 原语,见 README 上文的机制说明),
553
+ 所以「恢复后再回滚」的复合场景下,重放副本的行可能不被识别为 user 行。
554
+ - `restore` 后界面需要触发刷新才更新(已接 `__refreshSurface` 钩子 + MutationObserver,
555
+ 但极少数情况下仍需重载页面)。
556
+
557
+ ---
558
+
559
+ ## 0.9.3 · `/undo` —— 复刻 opencode 的招牌交互
560
+
561
+ 「我说的那句话不对」→ 打 `/undo` → 消息从 transcript 消失 + **原文回填输入框**。
562
+
563
+ 走**官方斜杠管线**(`ctx.inputTriggers.registerSource`),不自己劫持键盘,
564
+ 所以菜单分组、搜索、Enter 裁决、composer 状态机全由宿主负责。
565
+
566
+ ```js
567
+ ctx.inject(['inputTriggers'], (sub) => {
568
+ doRegisterUndoSlash(ctx, sub.inputTriggers || sub) // ⚠️ 见下方坑 2
569
+ })
570
+ ```
571
+
572
+ ### 注册路径踩过的四个坑
573
+
574
+ 1. **`candidates` 必须返回 Promise**。宿主在 `InputTriggerController.fetchCandidates`
575
+ 里直接 `source.candidates(...).then(...)`,同步返回数���会抛
576
+ `source.candidates(...).then is not a function`,**整个菜单静默失效**。
577
+ 2. **cordis `inject` 回调收到的是「注入命名空间」,服务在其同名字段下**
578
+ (与本文件 `sub.uiWorkspace || sub` 同模式)。把 `sub` 直接当服务用会抛
579
+ `cannot get property "registerSource" without inject`。
580
+ 3. **`rowsCache` 是注入器闭包私有的**(`installUserRevertInjector()` 内)。
581
+ `/undo` 的 `onPick` 在模块级作用域,直接引用会 ReferenceError,
582
+ 表现为「点菜单毫无反应」。需要 `__peekRowsCache()` 出口。
583
+ 4. **`__currentSessionId` 来自 DOM dataset,可能带 `session-` 前缀**,
584
+ 而 API 只要裸 uuid → 请求静默失败。
585
+
586
+ ### 目标必须挑 surface 上的那条
587
+
588
+ `restore` 是「重放」语义 → 原件被遮蔽、副本带**新 seq** 落在日志尾部。
589
+ 无脑取最后一条会挑到副本,而副本不在模型 surface 上,服务端以
590
+ `surface replace: start seq N not found in surface` 拒绝(实测)。
591
+ 回滚的前提就是「目标在 surface 上」,所以先筛 `visible`。
592
+
593
+ ### 实测
594
+
595
+ ```
596
+ composer 输入 /und → 官方菜单出现「回滚上一条消息 undo 移除最后一条用户消息,原文回填输入框」
597
+ 点击 → 目标 = seq 8(surface 上的那条,不是重放副本)
598
+ → 转��成功,dock 计数 13
599
+ → 原文「分配几个子代理把模型广场的模型价格什么的做好…」回填进 composer ✅
600
+ → transcript:24 行中 22 行 hidden,被回滚消息从正文消失 ✅
601
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-message-ops",
3
- "version": "0.9.0",
3
+ "version": "0.9.3",
4
4
  "description": "DSH web 插件:消息级回滚 / 删除 / 恢复(补 dsh 官方没有的部分)。分支与导出用官方内置能力。",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/client.js CHANGED
@@ -136,6 +136,13 @@ window.__ModuleLoader__.load({
136
136
  'slot.quote': 'Quote to composer',
137
137
  'quote.done': 'Quoted into composer',
138
138
  'quote.unavailable': 'Quote unavailable (composer locked or no full text)',
139
+ 'undo.label': '回滚上一条消息',
140
+ 'undo.desc': '移除最后一条用户消息,原文回填输入框',
141
+ 'undo.done.undo': '已回滚上一条消息',
142
+ 'undo.done.redo': '已恢复上一条被回滚的消息',
143
+ 'undo.none': '没有可回滚的消息',
144
+ 'redo.label': '恢复上一条被回滚的消息',
145
+ 'redo.desc': '把回滚掉的消息重新放回对话',
139
146
  'menu.ops': 'Message ops',
140
147
  }
141
148
 
@@ -143,7 +150,16 @@ window.__ModuleLoader__.load({
143
150
  var __sessionsSvc = null
144
151
  var __inputActions = null // 0.4.0: 从 session 槽捕获(InputActions.setDraft → composer 回填)
145
152
  var __uiWorkspace = null
146
- var __currentSessionId = null // 0.6.0:会话视图会话 id(RevertDock/MsgSlotActions 刷新)
153
+ var __currentSessionId = null
154
+ // 0.9.1:视图重建后刷新 transcript 可见性的钩子。
155
+ // 之前 restore 路径里直接调 scan(),但 scan 定义在注入器的闭包里,
156
+ // dock 组件根本取不到 —— `typeof scan === 'function'` 静默跳过了,
157
+ // 结果「恢复后消息回来了但仍被藏 / dock 计数不变」,必须重载页面才对。
158
+ var __refreshSurface = null
159
+ // 0.9.3:注入器闭包内 rowsCache 的只读出口。
160
+ // rowsCache 声明在 installUserRevertInjector() 内(闭包私有),而 /undo 的
161
+ // onPick 在模块级作用域 —— 直接引用会 ReferenceError,表现为点菜单毫无反应。
162
+ var __peekRowsCache = null // 0.6.0:会话视图会话 id(RevertDock/MsgSlotActions 刷新)
147
163
  // messageId→seq 索引缓存(每会话一次拉取;0.3.0 assistant-actions 槽用)
148
164
  var __seqIndexCache = new Map()
149
165
  // messageId→全文缓存(0.5.0 消息引用用)
@@ -840,6 +856,12 @@ window.__ModuleLoader__.load({
840
856
  try {
841
857
  if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sessionId)
842
858
  } catch { /* fallthrough */ }
859
+ // 0.9.1:重放的消息带**新 seq**,被恢复的行必须解除 hidden,
860
+ // 同时 dock 的权威 marker 列表要重拉。
861
+ try { window.dispatchEvent(new Event(CHANGED_EVENT)) } catch { /* non-browser */ }
862
+ // 0.9.1:重放的消息带**新 seq**,被恢复的行必须解除 hidden;
863
+ // 同时 dock 的 marker 列表要按权威数据重算(restoreComplete 会变 true)。
864
+ for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(sessionId) }, delay)
843
865
  const fresh = await fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId)).then((r) => (r.ok ? r.json() : null)).catch(() => null)
844
866
  if (fresh && fresh.ok) setMarkers(activeMarkers(fresh.messages || []))
845
867
  })
@@ -921,9 +943,10 @@ window.__ModuleLoader__.load({
921
943
  if (window.__MOPS_USER_REVERT_INSTALLED) return
922
944
  window.__MOPS_USER_REVERT_INSTALLED = true
923
945
  var rowsCache = { sid: null, rows: null, at: 0 }
946
+ __peekRowsCache = () => rowsCache
924
947
  var norm = (x) => String(x || '').replace(/\s+/g, '')
925
948
  var fetchRows = (sid) => {
926
- if (rowsCache.sid === sid && rowsCache.rows && Date.now() - rowsCache.at < 8000) return Promise.resolve(rowsCache.rows)
949
+ if (rowsCache.sid === sid && rowsCache.rows && Date.now() - rowsCache.at < 8000) return Promise.resolve(rowsCache)
927
950
  return fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
928
951
  .then((r) => (r.ok ? r.json() : null))
929
952
  .then((d) => {
@@ -941,13 +964,162 @@ window.__ModuleLoader__.load({
941
964
  const injected = (raw) => /^<system-reminder|current\s+runtime\s+context|^<system-Reminder/i.test(String(raw || ''))
942
965
  const rows = ((d && d.messages) || [])
943
966
  .filter((m) => m && m.role === 'user')
944
- .map((m) => ({ seq: m.seq, sn: norm(m.snippet), raw: String(m.snippet == null ? '' : m.snippet) }))
967
+ .map((m) => ({ seq: m.seq, sn: norm(m.snippet), raw: String(m.snippet == null ? '' : m.snippet), fullText: m.fullText ?? null, visible: m.visible !== false }))
945
968
  .filter((r) => r.sn && !injected(r.raw))
946
- rowsCache = { sid: sid, rows: rows, at: Date.now() }
947
- return rows
969
+ // 0.9.1:同时产出 node-key 查表索引(隐藏 transcript 用)
970
+ const idx = buildIndex(d)
971
+ rowsCache = { sid: sid, rows: rows, idx: idx, at: Date.now() }
972
+ return rowsCache
948
973
  })
949
- .catch(() => rowsCache.sid === sid ? rowsCache.rows : null)
974
+ .catch(() => (rowsCache.sid === sid ? rowsCache : null))
950
975
  }
976
+
977
+ // ═══ 0.9.1 宿主 node-key ↔ 日志 seq 的精确映射 ═══════════════════════════
978
+ //
979
+ // 背景(浏览器实测 + 源码核实):dsh 的 transcript **刻意不做 surface 折叠**。
980
+ // 官方 surface.d.ts:51-63 明写 "replacement copies stay model-only" ——
981
+ // 我们写的 surfaceOp replace 只折叠**模型 surface**(实测 393→13 节点),
982
+ // 被遮蔽的消息在人类 transcript 里**照常渲染且完全可见**,连 marker 本身
983
+ // 都不渲染(systemMessageDefinition 对 surfaceOp !== 'append' 直接 return null)。
984
+ // 所以要让回滚「看得见」,只能在渲染层处理。
985
+ //
986
+ // 好消息:每一行的 `data-chat-node-key` 形如 `<len>:<kind><id>`,而 <id>
987
+ // 就是日志事件的字段(user → messageId、assistant-step → `<turn>:<step>`、
988
+ // tool-call → callId、turn-* → turn 号),客户端本来就已经建了
989
+ // messageId → seq 索引(__seqIndexCache)。**精确查表,零启发式。**
990
+ //
991
+ // 旧实现用「40 字符前缀包含匹配」配对 DOM 与日志,实测 4 条里错 2 条
992
+ // ("继续" 命中了 "继续,…"),已整体删除。
993
+ var parseNodeKey = (k) => {
994
+ var m = /^(\d+):/.exec(k || '');
995
+ if (!m) return null;
996
+ var digits = m[1].length;
997
+ var kindLen = Number(m[1]);
998
+ var start = digits + 1;
999
+ if (!Number.isSafeInteger(kindLen) || kindLen <= 0 || k.length < start + kindLen) return null;
1000
+ return { kind: k.slice(start, start + kindLen), id: k.slice(start + kindLen) };
1001
+ };
1002
+
1003
+ /**
1004
+ * 从 /api/message-ops/messages 的响应构建全部查表。
1005
+ * 三条铁律:① 索引只认唯一 id;② 缺数据一律返回 undefined(调用方保持可见);
1006
+ * ③ visible 集合只收显式 true。
1007
+ */
1008
+ var buildIndex = (payload) => {
1009
+ var list = (payload && payload.messages) || []
1010
+ // 0.9.1:回合页脚/过程条不是消息,用 turn/end 的 seq 定位(边界常落在 turn 内部,
1011
+ // 用 turn/start 会漏判该回合的页脚)
1012
+ var turnEnd = (payload && payload.turnEndSeq) || null;
1013
+ var byMessageId = new Map();
1014
+ var byTurnStep = new Map();
1015
+ var byCallId = new Map();
1016
+ var byTurn = new Map();
1017
+ var visible = new Set();
1018
+ var reverted = new Set();
1019
+ var dupMessageId = 0
1020
+ var dupByMessageId = new Map();
1021
+ // 回合页脚/过程条锚到 turn/end 的 seq —— 那是**非消息**事件,永远不会出现在
1022
+ // reverted 集合里,所以隐藏判据必须直接对 fence 比较,不能用集合成员。
1023
+ var fences = Array.isArray(payload && payload.revertFences)
1024
+ ? payload.revertFences.filter(function (n) { return Number.isSafeInteger(n); })
1025
+ : [];
1026
+ for (var i = 0; i < list.length; i++) {
1027
+ var m = list[i];
1028
+ if (!m || typeof m.seq !== 'number') continue;
1029
+ if (m.id != null) {
1030
+ var k = String(m.id);
1031
+ // restore 是「重放」语义 → 原件与副本可能同 id 并存。
1032
+ // 0.9.1:不再「保留最早」,而是收集**全部** seq,隐藏判据取「任一 seq 越过
1033
+ // fence」。回放副本才是当前 surface 上的那条,用最早的 seq 判会让
1034
+ // 「恢复后再回滚」漏藏(实测 fence=70、副本 seq=70、原件 seq=54)。
1035
+ if (byMessageId.has(k)) {
1036
+ dupMessageId++
1037
+ const arr = dupByMessageId.get(k) || [byMessageId.get(k)]
1038
+ arr.push(m.seq)
1039
+ dupByMessageId.set(k, arr)
1040
+ byMessageId.set(k, m.seq) // 指向最新的
1041
+ } else { byMessageId.set(k, m.seq) }
1042
+ byMessageId.set(k, m.seq);
1043
+ }
1044
+ if (m.type === 'assistant/message' && m.turn != null && m.step != null) {
1045
+ byTurnStep.set(m.turn + ':' + m.step, m.seq);
1046
+ }
1047
+ if (m.type === 'tool/call' && m.id != null) byCallId.set(String(m.id), m.seq);
1048
+ if (m.turn != null && !byTurn.has(String(m.turn))) byTurn.set(String(m.turn), m.seq);
1049
+ if (m.visible === true) visible.add(m.seq);
1050
+ // 0.9.1:reverted 才是「该藏」的口径(见 index.js 的注释:visible 会误藏
1051
+ // 所有非 surface 事件行,如 tool/call)
1052
+ if (m.reverted === true) reverted.add(m.seq);
1053
+ }
1054
+ // turnEnd 优先:它对「该 turn 内一条消息都没有」的情况仍然有效
1055
+ if (turnEnd) for (const k in turnEnd) if (Object.prototype.hasOwnProperty.call(turnEnd, k)) byTurn.set(k, turnEnd[k])
1056
+ return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, visible, reverted, fences, dupMessageId, total: list.length };
1057
+ };
1058
+
1059
+ /** node-key → { seq, all }(all = 同 id 的全部 seq,处理 restore 重放副本)。 */
1060
+ var seqOfNodeKey = (key, idx) => {
1061
+ var parsed = parseNodeKey(key);
1062
+ if (!parsed || !idx) return null;
1063
+ var id = parsed.id;
1064
+ switch (parsed.kind) {
1065
+ case 'input-message': // user / steering / turn-trigger
1066
+ case 'developer-message':
1067
+ case 'trajectory-note': {
1068
+ const hit = idx.byMessageId.get(id)
1069
+ if (hit === undefined) return null
1070
+ return { seq: hit, all: idx.dupByMessageId.get(id) || [hit] }
1071
+ }
1072
+ case 'assistant-step': {
1073
+ const hit = idx.byTurnStep.get(id)
1074
+ return hit === undefined ? null : { seq: hit, all: [hit] }
1075
+ }
1076
+ case 'tool-call': {
1077
+ const hit = idx.byCallId.get(id)
1078
+ return hit === undefined ? null : { seq: hit, all: [hit] }
1079
+ }
1080
+ case 'turn-tail':
1081
+ case 'turn-process':
1082
+ case 'turn-error':
1083
+ case 'turn-max-tokens':
1084
+ case 'model-retry': {
1085
+ const hit = idx.byTurn.get(id)
1086
+ return hit === undefined ? null : { seq: hit, all: [hit] }
1087
+ }
1088
+ default:
1089
+ return null; // compaction / command / workflow-run 等不参与
1090
+ }
1091
+ };
1092
+
1093
+ /**
1094
+ * 把 transcript 行按模型 surface 可见性打上 hidden。
1095
+ * 用 `hidden="until-found"`(与宿主 useSearchableHidden 同款):Ctrl+F 仍能搜到,
1096
+ * 且宿主的分页锚点选择器 `[data-chat-paging-anchor]:not(:empty):not([hidden])`
1097
+ * 会自动跳过这些行,滚动恢复不受影响。
1098
+ *
1099
+ * ⚠️ `seq == null` ⇒ **移除 hidden**(保持可见)。把「查不到」当成「被遮蔽」
1100
+ * 是唯一会误藏用户内容的路径。
1101
+ */
1102
+ var applySurfaceVisibility = (root, idx) => {
1103
+ if (!idx) return { hidden: 0, unresolved: 0, shown: 0 };
1104
+ var rows = (root || document).querySelectorAll('[data-chat-node-key]');
1105
+ var hidden = 0, unresolved = 0, shown = 0;
1106
+ for (var i = 0; i < rows.length; i++) {
1107
+ var row = rows[i];
1108
+ // ⚠️ seqOfNodeKey 返回 `{ seq, all }`(all = 同 id 的全部 seq,
1109
+ // 处理 restore 重放副本),不是标量。曾经在多 seq 改造时漏改这里,
1110
+ // 导致 `{...} >= f` 恒为 false → **静默一个都不藏,也不报错**。
1111
+ var hit = seqOfNodeKey(row.getAttribute('data-chat-node-key'), idx);
1112
+ if (hit === null) { unresolved++; row.removeAttribute('hidden'); continue; }
1113
+ var cands = (hit.all && hit.all.length) ? hit.all : [hit.seq];
1114
+ var isReverted = idx.fences.length
1115
+ ? cands.some(function (q) { return idx.fences.some(function (f) { return q >= f; }); })
1116
+ : cands.some(function (q) { return idx.reverted.has(q); });
1117
+ if (isReverted) { hidden++; row.setAttribute('hidden', 'until-found'); }
1118
+ else { shown++; row.removeAttribute('hidden'); }
1119
+ }
1120
+ return { hidden, unresolved, shown };
1121
+ };
1122
+
951
1123
  // 用户消息锚点:优先官方 Sixlwa_userRow(含 .xzv4MW_actions),回退 flow-kind 属性
952
1124
  // 锚点 = 每条用户消息自己的容器(一个块只算一次):
953
1125
  // 从官方动作行 .xzv4MW_actions 反查最近的消息容器,最贴近"一条消息"的粒度。
@@ -992,37 +1164,33 @@ window.__ModuleLoader__.load({
992
1164
  btn.setAttribute('data-mops-unmatched', '1')
993
1165
  }
994
1166
  }
995
- var assignSeqs = (sid, rows) => {
996
- if (!rows) return
997
- const blocks = userAnchors()
998
- let ri = 0
999
- var missed = 0
1000
- for (const b of blocks) {
1167
+ var assignSeqs = (sid, cache) => {
1168
+ const idx = cache && cache.idx
1169
+ if (!idx) return
1170
+ // 0.9.1:node-key 查表,替代旧的 40 字符前缀包含匹配(实测 4 条错 2 条)
1171
+ for (const b of userAnchors()) {
1001
1172
  b.removeAttribute('data-mops-seq')
1002
1173
  b.removeAttribute('data-mops-unmatched')
1003
- const head = norm((b.innerText || '').slice(0, 240))
1004
- let hit = -1
1005
- for (let j = ri; j < rows.length; j++) {
1006
- const a = (rows[j].sn || '').slice(0, 40)
1007
- const b = (head || '').slice(0, 40)
1008
- if (a && b && (head.includes(a) || rows[j].sn.includes(b))) { hit = j; break }
1009
- }
1010
- if (hit >= 0) { b.setAttribute('data-mops-seq', String(rows[hit].seq)); ri = hit + 1 }
1011
- syncEnabled(b, b.querySelector && b.querySelector('.mopsUserRevert'))
1012
- if (false) {
1013
- // 0.9.0:配不上就**如实标记**而不是留一个点了才报错的装饰按钮。
1014
- // 已知局限:配对是前 40 字子串包含,模型自己写的摘要与宿主渲染文本
1015
- // 措辞漂移(实测 playwright/playright)就会失配。
1016
- missed++
1174
+ const hit = seqOfNodeKey(b.getAttribute('data-chat-node-key'), idx)
1175
+ const seq = hit === null ? null : hit.seq
1176
+ if (seq === null || seq === undefined) {
1017
1177
  b.setAttribute('data-mops-unmatched', '1')
1178
+ syncEnabled(b, b.querySelector && b.querySelector('.mopsUserRevert'))
1179
+ continue
1018
1180
  }
1181
+ b.setAttribute('data-mops-seq', String(seq))
1182
+ syncEnabled(b, b.querySelector && b.querySelector('.mopsUserRevert'))
1019
1183
  }
1020
- return missed
1021
1184
  }
1022
1185
  // 按钮可用性在 assignSeqs 内部**同步**更新(与打标同一次循环)——
1023
1186
  // 之前放在 fetch 回调里做事后全局扫描,会与 DOM 注入/重排竞态,导致
1024
1187
  // 块已打上 seq 而按钮仍是禁用态(实测:block seq=[8,54],按钮 disabled=true)。
1025
- var ensureAssign = (sid) => fetchRows(sid).then((rows) => assignSeqs(sid, rows))
1188
+ // 按钮可用性与 transcript 隐藏都在这里统一落地(同一批数据,避免竞态)
1189
+ var ensureAssign = (sid) => fetchRows(sid).then((cache) => {
1190
+ assignSeqs(sid, cache)
1191
+ if (cache && cache.idx) applySurfaceVisibility(document, cache.idx)
1192
+ return cache
1193
+ })
1026
1194
  // 0.7.0:点击时先**同步完成**配对(打标是异步 fetch 的结果,
1027
1195
  // 早先点在未打标的按钮上会静默失败 = 用户反馈的"点了没用")。
1028
1196
  var runUserRevert = (btn, block) => {
@@ -1032,15 +1200,15 @@ window.__ModuleLoader__.load({
1032
1200
  Promise.resolve()
1033
1201
  .then(() => ensureAssign(sid))
1034
1202
  .then(() => fetchRows(sid))
1035
- .then((rows) => {
1203
+ .then((cache) => {
1204
+ const rows = cache && cache.rows
1205
+ // 0.9.1:seq 来自 node-key 精确查表,**不再**做文本前缀匹配验证
1206
+ // (旧的前缀包含匹配实测 4 条错 2 条 —— "继续" 命中 "继续,…")。
1036
1207
  const seq = Number(block.getAttribute('data-mops-seq'))
1037
- const head = norm((block.innerText || '').slice(0, 240))
1038
1208
  const row = rows && rows.find((r) => r.seq === seq)
1039
- const a2 = (row && row.sn || '').slice(0, 40)
1040
- const b2 = (head || '').slice(0, 40)
1041
- if (!row || !head || !(head.includes(a2) || row.sn.includes(b2))) {
1209
+ if (!row) {
1042
1210
  ensureAssign(sid)
1043
- notifyDone(__t('errorPrefix') + 'revert target verification failed', 'error')
1211
+ notifyDone(__t('errorPrefix') + (__t('revert.unresolved') || 'revert target verification failed'), 'error')
1044
1212
  return
1045
1213
  }
1046
1214
  btn.disabled = true
@@ -1058,6 +1226,10 @@ window.__ModuleLoader__.load({
1058
1226
  try {
1059
1227
  if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
1060
1228
  } catch { /* 视图重建失败不阻断 */ }
1229
+ // 0.9.1:视图重建后重新拉权威可见性并隐藏被遮蔽的行。
1230
+ // openSession 会重挂 DOM,旧节点上的 hidden 属性随之失效,必须重刷。
1231
+ if (rowsCache) rowsCache.at = 0
1232
+ for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(sid) }, delay)
1061
1233
  })
1062
1234
  .catch((reason) => {
1063
1235
  notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
@@ -1089,13 +1261,22 @@ window.__ModuleLoader__.load({
1089
1261
  host.appendChild(btn)
1090
1262
  return btn
1091
1263
  }
1264
+ __refreshSurface = (sid) => {
1265
+ const id = sid || __currentSessionId
1266
+ if (!id) return
1267
+ if (rowsCache) rowsCache.at = 0 // 强制重取权威数据
1268
+ try { fetchRows(id).then((cache) => { if (cache && cache.idx) applySurfaceVisibility(document, cache.idx) }) } catch { /* noop */ }
1269
+ }
1092
1270
  var scan = () => {
1093
1271
  try {
1094
1272
  const sid = __currentSessionId
1095
1273
  if (!sid) return
1096
1274
  const blocks = userAnchors()
1097
1275
  for (const b of blocks) ensureBtn(b)
1098
- if (blocks.some((b) => !b.hasAttribute('data-mops-seq'))) ensureAssign(sid)
1276
+ // 0.9.1:**始终**刷新(原先只在按钮未打标时刷)——
1277
+ // 打标后 transcript 再变化(openSession 重建 / 分页 / restore 重放)
1278
+ // 就再也不会重算隐藏,导致「界面停在旧状态,必须重载页面才对」。
1279
+ ensureAssign(sid)
1099
1280
  } catch { /* 注入失败不影响会话 */ }
1100
1281
  }
1101
1282
  // 触发:hover / 滚动 / DOM 变化 / 变更事件
@@ -1233,6 +1414,147 @@ window.__ModuleLoader__.load({
1233
1414
  } catch { /* namespace already registered: keep existing copy */ }
1234
1415
  }
1235
1416
 
1417
+
1418
+ // ═══ 0.9.3 /undo —— opencode 招牌交互 ═════════════════════════════════════
1419
+ //
1420
+ // 「我说的那句话不对」→ 一个命令 → 消息从 transcript 消失 + 原文回输入框。
1421
+ // 走**官方斜杠命令管线**(`ctx.inputTriggers.registerSource`),不自己劫持键盘,
1422
+ // 因此:菜单分组、搜索、Enter 裁决、composer 状态机全部由宿主负责。
1423
+ //
1424
+ // 契约(dsh-client-ui-input-trigger/lib/types/client/contract.d.ts):
1425
+ // registerSource({ trigger:'/', name, candidates(session,req), onPick(pick),
1426
+ // matchEnter?(session,line,signal,envelope) })
1427
+ // PickOutcome = {claim} | {insert} | {text,continue?} | 'handled' | undefined
1428
+ // undefined = 「不是我的」,交回管线;'handled' = 已消费,**不要**当成消���发出去。
1429
+ var UNDO_CANDIDATES = [
1430
+ { name: 'undo', value: 'undo', icon: 'undo' },
1431
+ { name: 'redo', value: 'redo', icon: 'redo' },
1432
+ ]
1433
+ var __undoSourceName = 'message-ops'
1434
+
1435
+ /**
1436
+ * 找到当前会话里最后一条**可回滚**的用户消息。
1437
+ *
1438
+ * ⚠️ 必须挑 surface 上的那一条。`restore` 是「重放」语义 → 原件被遮蔽、副本带**新 seq**
1439
+ * 落在日志尾部。若无脑取最后一条,就会挑到那个副本,而副本不在模型 surface 上,
1440
+ * 服务端会以 `surface replace: start seq N not found in surface` 拒绝(实测)。
1441
+ * 回滚的前提就是「目标在 surface 上」,所以先筛 visible。
1442
+ */
1443
+ var lastRevertable = () => {
1444
+ const cache = __peekRowsCache ? __peekRowsCache() : null
1445
+ if (!cache || !Array.isArray(cache.rows)) return null
1446
+ for (var i = cache.rows.length - 1; i >= 0; i--) {
1447
+ var r = cache.rows[i]
1448
+ if (r && r.seq != null && r.visible) return r
1449
+ }
1450
+ return null
1451
+ }
1452
+
1453
+ /** 执行 undo/redo。返回 true 表示确实动过盘。 */
1454
+ /** __currentSessionId 来自 DOM dataset,可能带 `session-` 前缀;API 只要裸 uuid。 */
1455
+ var bareSessionId = (id) => String(id || '').replace(/^session-/, '')
1456
+ var runUndoRedo = (kind) => {
1457
+ const sid = bareSessionId(__currentSessionId)
1458
+ if (!sid) return false
1459
+ const target = lastRevertable()
1460
+ if (!target) {
1461
+ notifyDone(__t('undo.none') || '没有可回滚的消息', 'error')
1462
+ return false
1463
+ }
1464
+ const verb = kind === 'redo' ? 'restore' : 'revert'
1465
+ fetch('/api/message-ops/' + verb, {
1466
+ method: 'POST', headers: { 'content-type': 'application/json' },
1467
+ body: JSON.stringify({ sessionId: sid, seq: target.seq }),
1468
+ })
1469
+ .then(async (res) => {
1470
+ let data = {}
1471
+ try { data = await res.json() } catch { /* keep {} */ }
1472
+ if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
1473
+ notifyDone(kind === 'redo' ? __t('undo.done.redo') : __t('undo.done.undo'))
1474
+ // opencode 语义:回滚后**原文回输入框**,用户可改后重发
1475
+ if (kind !== 'redo' && target.fullText && __inputActions && typeof __inputActions.setDraft === 'function') {
1476
+ try { __inputActions.setDraft(target.fullText) } catch { /* 回填失败不阻断 */ }
1477
+ }
1478
+ try { window.dispatchEvent(new Event(CHANGED_EVENT)) } catch { /* non-browser */ }
1479
+ try {
1480
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
1481
+ } catch { /* 视图重建失败不阻断 */ }
1482
+ if (__peekRowsCache) { const c = __peekRowsCache(); if (c) c.at = 0 }
1483
+ for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(sid) }, delay)
1484
+ })
1485
+ .catch((reason) => {
1486
+ notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
1487
+ })
1488
+ return true
1489
+ }
1490
+
1491
+ /** 注册 /undo /redo 到官方斜杠管线。服务缺失时安静 no-op。 */
1492
+ var __undoRegistered = false
1493
+ var doRegisterUndoSlash = (ctx, it) => {
1494
+ if (__undoRegistered || !it || typeof it.registerSource !== 'function') return
1495
+ __undoRegistered = true
1496
+ try {
1497
+ ctx.effect(() => it.registerSource({
1498
+ trigger: '/',
1499
+ name: __undoSourceName,
1500
+ order: 20,
1501
+ showGroupTitle: true,
1502
+ // ⚠️ 必须返回 **Promise**:宿主在 InputTriggerController.fetchCandidates 里
1503
+ // 直接 `source.candidates(...).then(...)`,同步返回数组会抛
1504
+ // `source.candidates(...).then is not a function`,整个菜单静默失效。
1505
+ candidates: async (session, req) => {
1506
+ const q = String((req && req.query) || '').trim().toLowerCase()
1507
+ return UNDO_CANDIDATES
1508
+ .filter((c) => !q || c.name.includes(q))
1509
+ .map((c) => ({
1510
+ name: c.name,
1511
+ icon: c.icon,
1512
+ label: c.name === 'undo'
1513
+ ? (__t('undo.label') || '回滚上一条消息')
1514
+ : (__t('redo.label') || '恢复上一条被回滚的消息'),
1515
+ description: c.name === 'undo'
1516
+ ? (__t('undo.desc') || '移除最后一条用户消息,原文回填输入框')
1517
+ : (__t('redo.desc') || '把回滚掉的消息重新放回对话'),
1518
+ value: c.value,
1519
+ }))
1520
+ },
1521
+ onPick: (pick) => {
1522
+ const v = pick && pick.candidate && pick.candidate.value
1523
+ if (v !== 'undo' && v !== 'redo') return undefined
1524
+ runUndoRedo(v)
1525
+ return 'handled'
1526
+ },
1527
+ // Enter 直接执行:`/undo` 不必先在菜单里选中
1528
+ matchEnter: (session, line) => {
1529
+ const t = String(line || '').trim().toLowerCase()
1530
+ if (t !== '/undo' && t !== '/redo') return undefined
1531
+ runUndoRedo(t === '/redo' ? 'redo' : 'undo')
1532
+ return 'handled'
1533
+ },
1534
+ }))
1535
+ } catch (e) {
1536
+ __undoRegistered = false
1537
+ if (window.__MOPS_DEBUG) console.warn('[message-ops] /undo 注册失败:', e)
1538
+ }
1539
+ }
1540
+
1541
+ var registerUndoSlash = (ctx) => {
1542
+ // ⚠️ cordis 的 inject 回调**第一个参数是服务本身**,不是 ctx。
1543
+ // 早先写成 `registerUndoSlash(sub.ctx || sub)` → 在服务对象上找 .get
1544
+ // 必然是 undefined → 静默不注册(表现为 /undo 根本不出现)。
1545
+ const it = typeof ctx.get === 'function' ? ctx.get('inputTriggers') : null
1546
+ if (it) { doRegisterUndoSlash(ctx, it); return }
1547
+ try {
1548
+ // ⚠️ cordis inject 回调收到的是**注入命名空间**,服务在其同名字段下
1549
+ // (与本文件 `ctx.inject(['uiWorkspace'], sub => sub.uiWorkspace || sub)` 同模式)。
1550
+ // 直接把 sub 当服务用会抛 `cannot get property "registerSource" without inject`。
1551
+ ctx.inject(['inputTriggers'], (sub) => {
1552
+ doRegisterUndoSlash(ctx, sub && (sub.inputTriggers || sub))
1553
+ })
1554
+ } catch (e) {
1555
+ }
1556
+ }
1557
+
1236
1558
  function apply(ctx) {
1237
1559
  __sessionsSvc = ctx.get('sessions')
1238
1560
  __uiWorkspace = typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : null
@@ -1242,6 +1564,7 @@ window.__ModuleLoader__.load({
1242
1564
  if (!__sessionsSvc) {
1243
1565
  ctx.inject(['sessions'], (sub) => { __sessionsSvc = sub.sessions })
1244
1566
  }
1567
+ registerUndoSlash(ctx)
1245
1568
  adoptLocale(ctx.get('locale'), ctx)
1246
1569
  if (!__locale) {
1247
1570
  ctx.inject(['locale'], (sub) => {
package/src/index.js CHANGED
@@ -24,7 +24,7 @@
24
24
 
25
25
  import { zstdCompressSync } from "node:zlib";
26
26
  import { open as openFile, truncate as truncateFile, stat as statFile } from "node:fs/promises";
27
- import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFile, readSessionFileAsync, listMessages, computeShadowed, messageText } from "./session-file.js";
27
+ import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFile, readSessionFileAsync, listMessages, computeShadowed, messageText, turnBounds } from "./session-file.js";
28
28
  import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble,
29
29
  OpsError, planRevert, planDelete, planRestore, applyRestore, applySurfaceReplace,
30
30
  restoreProgress, pendingRestoreTurns,
@@ -277,6 +277,15 @@ async function opsList(targetCtx, sessionId) {
277
277
  const t = messageText(e);
278
278
  if (t && t.trim()) seqText.set(e.seq, t.trim().replace(/\s+/g, " ").slice(0, 80));
279
279
  }
280
+ // 0.9.1:**reverted** = opencode 语义「回撤边界及其后」。
281
+ //
282
+ // ⚠️ 不能用 `visible` 当隐藏判据 —— `visible` 是「是否在模型 surface 上」,
283
+ // 而 tool/call / turn/* / model/* **根本不是 surface 节点**(SURFACE_TYPES 只有
284
+ // system|user|developer|assistant/message 与 tool/result),它们永远 visible=false。
285
+ // 照抄会把**所有**工���调用行永久藏掉(实测 3/3 全被误藏)。
286
+ //
287
+ // 正确口径:每个活跃回撤标记的 range.start 之后的全部 seq 都算已回撤
288
+ // —— 这正是 opencode 的 `messages.slice(0, boundaryIndex)`(边界自己也不显示)。
280
289
  for (const m of messages) {
281
290
  if (!m || m.marker !== true) continue;
282
291
  const prog = restoreProgress(events, m.seq);
@@ -288,6 +297,34 @@ async function opsList(targetCtx, sessionId) {
288
297
  preview: seqText.get(t.turnSeq) || ('#' + t.turnSeq),
289
298
  }));
290
299
  }
300
+
301
+ // 0.9.1:**reverted** = opencode 语义「回撤边界及其后」。
302
+ //
303
+ // ⚠️ 不能用 `visible` 当隐藏判据 —— `visible` 是「是否在模型 surface 上」,
304
+ // 而 tool/call / turn/* / model/* **根本不是 surface 节点**(SURFACE_TYPES 只有
305
+ // system|user|developer|assistant/message 与 tool/result),它们永远 visible=false。
306
+ // 照抄会把**所有**工具调用行永久藏掉(实测 3/3 全被误藏)。
307
+ //
308
+ // 正确口径:每个**未恢复**的回撤标记 range.start 之后的全部 seq 都算已回撤 ——
309
+ // 这正是 opencode 的 `messages.slice(0, boundaryIndex)`(边界自己也不显示)。
310
+ const revertFences = messages
311
+ .filter((m) => m && m.marker === true && m.restoreComplete === false
312
+ && m.range && typeof m.range.start === 'number')
313
+ .map((m) => m.range.start);
314
+ for (const m of messages) {
315
+ m.reverted = typeof m.seq === 'number' && revertFences.some((start) => m.seq >= start);
316
+ }
317
+ // 0.9.1:回合页脚/过程条的 node-key id 就是 turn 号,而它们**不是消息**,
318
+ // 无法用「首个带 turn 字段的消息」定位(该 turn 内可能一条消息都没有,
319
+ // 实测 turn 2 就映射不到)。这里直接给 turn/start 的 seq 映射表。
320
+ const bounds = turnBounds(events);
321
+ // 用 **turn/end 的 seq** 而不是 turn/start:回撤边界常落在某个 turn **内部**
322
+ // (实测边界 seq 54 在 turn 2 的 [51..62] 之间)。用起始 seq 会漏判该回合的页脚,
323
+ // 用结束 seq 则「边界之前完全在前」的回合自然落选。
324
+ const turnEndSeq = {};
325
+ for (const [turn, seq] of bounds.ends) turnEndSeq[turn] = seq;
326
+ for (const [turn, seq] of bounds.starts) if (!(turn in turnEndSeq)) turnEndSeq[turn] = seq;
327
+
291
328
  return {
292
329
  ok: true,
293
330
  session: { id: header.id, createdAt: header.createdAt, parentSession: header.parentSession ?? null },
@@ -295,6 +332,8 @@ async function opsList(targetCtx, sessionId) {
295
332
  runningSource: __runningSource,
296
333
  total: messages.length,
297
334
  visibleCount,
335
+ turnEndSeq,
336
+ revertFences,
298
337
  messages,
299
338
  };
300
339
  }
@@ -164,6 +164,29 @@ export function newSessionId() {
164
164
  }
165
165
 
166
166
  /** 从事件流提取消息级列表(user/assistant/system message + tool/call 摘要)。 */
167
+ /**
168
+ * turn 号 → 该 turn 首/末事件 seq 的映射。
169
+ *
170
+ * 0.9.1:宿主把「回合页脚/过程条/错误」渲染成 node-key 为 `9:turn-tail<turn>` /
171
+ * `12:turn-process<turn>` / `10:turn-error<turn>` 的行 —— 它们的 id 就是 turn 号,
172
+ * 不带 seq。回滚边界落在某个 turn 之后时,这些行也必须一起藏,否则会留下
173
+ * 「孤立的分支/复制按钮」,视觉上像"只回滚了一半"。
174
+ *
175
+ * @returns {{starts: Map<number, number>, ends: Map<number, number>}}
176
+ */
177
+ export function turnBounds(events) {
178
+ const starts = new Map();
179
+ const ends = new Map();
180
+ for (const e of events) {
181
+ if (!e || typeof e.seq !== "number") continue;
182
+ const t = e.data && e.data.turn;
183
+ if (!Number.isSafeInteger(t)) continue;
184
+ if (e.type === "turn/start") starts.set(t, e.seq);
185
+ else if (e.type === "turn/end") ends.set(t, e.seq);
186
+ }
187
+ return { starts, ends };
188
+ }
189
+
167
190
  export function listMessages(events) {
168
191
  const messages = [];
169
192
  for (const e of events) {
@@ -193,13 +216,18 @@ export function listMessages(events) {
193
216
  ? e.data.restoresSeq : null,
194
217
  time: e.time ?? null,
195
218
  turn: (e.data && e.data.turn) ?? null,
219
+ // 0.9.1:assistant 节点的宿主 node-key 是 `14:assistant-step<turn>:<step>`,
220
+ // 没有 step 就无法把渲染行映射回日志 seq → 回滚时助手回答藏不掉。
221
+ step: (e.data && e.data.step) ?? null,
196
222
  });
197
223
  } else if (e.type === "tool/call") {
198
224
  const d = e.data || {};
199
225
  const name = d.name || (d.call && d.call.name) || "tool";
200
226
  messages.push({
201
227
  seq: e.seq, type: "tool/call", role: "tool", snippet: `[tool] ${name}`,
202
- time: e.time ?? null, turn: d.turn ?? null,
228
+ time: e.time ?? null, turn: d.turn ?? null, step: d.step ?? null,
229
+ // 0.9.1:工具节点的宿主 node-key 是 `9:tool-call<callId>`
230
+ id: d.callId ?? null,
203
231
  });
204
232
  }
205
233
  }
@@ -15,8 +15,8 @@ import { zstdCompressSync } from 'node:zlib'
15
15
  import { createRequire } from 'node:module'
16
16
  import { join, dirname } from 'node:path'
17
17
 
18
- import { decodeFrames, parseRows } from '/data/data/com.termux/files/home/dsh-plugins-src/dsh-seqguard/lib/seqcore.js'
19
- import { officialValidate } from '/data/data/com.termux/files/home/dsh-plugins-src/dsh-seqguard/lib/v4gate.mjs'
18
+ import { decodeFrames, parseRows } from '/data/data/com.termux/files/home/dsh-plugins-src/sessionfix/lib/seqcore.js'
19
+ import { officialValidate } from '/data/data/com.termux/files/home/dsh-plugins-src/sessionfix/lib/v4gate.mjs'
20
20
  import {
21
21
  planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble,
22
22
  buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planRestore, restoreProgress,
@@ -0,0 +1,166 @@
1
+ /**
2
+ * 0.9.1 transcript 可见性映射 —— 回归锁死。
3
+ *
4
+ * 背景:dsh 的 transcript **刻意不做 surface 折叠**(surface.d.ts:51-63
5
+ * "replacement copies stay model-only")。回滚要「看得见」只能在渲染层处理,
6
+ * 而唯一可靠的行↔日志映射是 `data-chat-node-key` 里内嵌的官方 id。
7
+ *
8
+ * 本文件锁三件事:
9
+ * ① node-key 解析与查表(含 assistant-step 一 node 两行)
10
+ * ② **不能用 `visible` 当隐藏判据** —— tool/call 等非 surface 事件永远 visible=false,
11
+ * 照抄会把所有工具调用行永久藏掉(实测 3/3 全被误藏)
12
+ * ③ 查不到时保持可见,绝不误藏
13
+ */
14
+ import test from 'node:test'
15
+ import assert from 'node:assert/strict'
16
+
17
+ /** 与 client.js 的 parseNodeKey / buildIndex / seqOfNodeKey 同构 */
18
+ function parseNodeKey(k) {
19
+ const m = /^(\d+):/.exec(k || '')
20
+ if (!m) return null
21
+ const digits = m[1].length
22
+ const kindLen = Number(m[1])
23
+ const start = digits + 1
24
+ if (!Number.isSafeInteger(kindLen) || kindLen <= 0 || k.length < start + kindLen) return null
25
+ return { kind: k.slice(start, start + kindLen), id: k.slice(start + kindLen) }
26
+ }
27
+
28
+ function buildIndex(list) {
29
+ const dupByMessageId = new Map()
30
+ const byMessageId = new Map(), byTurnStep = new Map(), byCallId = new Map(), byTurn = new Map()
31
+ const visible = new Set(), reverted = new Set()
32
+ let dupMessageId = 0
33
+ for (const m of list || []) {
34
+ if (!m || typeof m.seq !== 'number') continue
35
+ if (m.id != null) {
36
+ const k = String(m.id)
37
+ if (byMessageId.has(k)) {
38
+ dupMessageId++
39
+ const arr = dupByMessageId.get(k) || [byMessageId.get(k)]
40
+ arr.push(m.seq); dupByMessageId.set(k, arr); byMessageId.set(k, m.seq)
41
+ } else { byMessageId.set(k, m.seq) }
42
+ }
43
+ if (m.type === 'assistant/message' && m.turn != null && m.step != null) byTurnStep.set(m.turn + ':' + m.step, m.seq)
44
+ if (m.type === 'tool/call' && m.id != null) byCallId.set(String(m.id), m.seq)
45
+ if (m.turn != null && !byTurn.has(String(m.turn))) byTurn.set(String(m.turn), m.seq)
46
+ if (m.visible === true) visible.add(m.seq)
47
+ if (m.reverted === true) reverted.add(m.seq)
48
+ }
49
+ return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, visible, reverted, dupMessageId, total: (list || []).length }
50
+ }
51
+
52
+ function seqOfNodeKey(key, idx) {
53
+ const p = parseNodeKey(key)
54
+ if (!p || !idx) return null
55
+ switch (p.kind) {
56
+ case 'input-message': case 'developer-message': case 'trajectory-note': {
57
+ const h = idx.byMessageId.get(p.id)
58
+ return h === undefined ? null : { seq: h, all: idx.dupByMessageId.get(p.id) || [h] }
59
+ }
60
+ case 'assistant-step': { const h = idx.byTurnStep.get(p.id); return h === undefined ? null : { seq: h, all: [h] } }
61
+ case 'tool-call': { const h = idx.byCallId.get(p.id); return h === undefined ? null : { seq: h, all: [h] } }
62
+ case 'turn-tail': case 'turn-process': case 'turn-error': case 'turn-max-tokens': case 'model-retry': {
63
+ const h = idx.byTurn.get(p.id); return h === undefined ? null : { seq: h, all: [h] }
64
+ }
65
+ default: return null
66
+ }
67
+ }
68
+
69
+ // ── 真实形状的语料(取自分支会话 session-0da37218)─────────────────────────
70
+ const K = {
71
+ user: (id) => `13:input-message${id}`,
72
+ step: (t, s) => `14:assistant-step${t}:${s}`,
73
+ tool: (id) => `9:tool-call${id}`,
74
+ tail: (t) => `9:turn-tail${t}`,
75
+ process: (t) => `12:turn-process${t}`,
76
+ dev: (id) => `17:developer-message${id}`,
77
+ }
78
+ const CORPUS = [
79
+ { seq: 8, type: 'user/message', id: '8b5093a5-205e-4108-a886-00981bbd57da', visible: true, reverted: false },
80
+ { seq: 18, type: 'assistant/message', id: 'a1', turn: 1, step: 1, visible: true, reverted: false },
81
+ { seq: 19, type: 'tool/call', id: 'call_2a9430d7030b4c04a75e7e87', turn: 1, step: 1, visible: false, reverted: false },
82
+ { seq: 21, type: 'tool/call', id: 'call_2da69ea515e64d6181458e2f', turn: 1, step: 2, visible: false, reverted: false },
83
+ { seq: 25, type: 'assistant/message', id: 'a2', turn: 1, step: 2, visible: true, reverted: false },
84
+ { seq: 26, type: 'tool/call', id: 'call_c30c0f21878a43f0926c77a9', turn: 1, step: 2, visible: false, reverted: false },
85
+ { seq: 54, type: 'user/message', id: '71921f48-3f8a-4f97-951f-122cfd64cb2e', visible: true, reverted: true },
86
+ { seq: 63, type: 'system/message', id: 'm1', visible: true, reverted: false, marker: true, range: { start: 54, end: 54 } },
87
+ ]
88
+
89
+ test('parseNodeKey:解析 <len>:<kind><id>', () => {
90
+ assert.deepEqual(parseNodeKey(K.user('abc')), { kind: 'input-message', id: 'abc' })
91
+ assert.deepEqual(parseNodeKey(K.step(1, 2)), { kind: 'assistant-step', id: '1:2' })
92
+ assert.deepEqual(parseNodeKey(K.tail(3)), { kind: 'turn-tail', id: '3' })
93
+ assert.equal(parseNodeKey(''), null)
94
+ assert.equal(parseNodeKey('garbage'), null)
95
+ assert.equal(parseNodeKey('99:tool-call'), null, '声明长度超出字符串 → null')
96
+ })
97
+
98
+ test('查表:六种行全部命中真实 seq', () => {
99
+ const idx = buildIndex(CORPUS)
100
+ assert.equal(seqOfNodeKey(K.user('8b5093a5-205e-4108-a886-00981bbd57da'), idx)?.seq, 8)
101
+ assert.equal(seqOfNodeKey(K.step(1, 1), idx)?.seq, 18)
102
+ assert.equal(seqOfNodeKey(K.tool('call_2a9430d7030b4c04a75e7e87'), idx)?.seq, 19)
103
+ assert.equal(seqOfNodeKey(K.tail(1), idx)?.seq, 18, 'turn 号映射到该 turn 首个带 turn 字段的消息 seq(回合页脚不是消息,用锚点近似)')
104
+ assert.equal(seqOfNodeKey(K.dev('nope'), idx), null, '未知 id → null')
105
+ })
106
+
107
+ test('回归:用 visible 当隐藏判据会误藏全部工具调用行', () => {
108
+ const idx = buildIndex(CORPUS)
109
+ const wronglyHidden = ['call_2a9430d7030b4c04a75e7e87', 'call_2da69ea515e64d6181458e2f', 'call_c30c0f21878a43f0926c77a9']
110
+ .filter((id) => !idx.visible.has(seqOfNodeKey(K.tool(id), idx)?.seq))
111
+ assert.equal(wronglyHidden.length, 3, '三个 tool-call 都 visible=false —— 这就是为什么不能用 visible')
112
+ // 用 reverted 则一个都不该被误藏
113
+ const withReverted = wronglyHidden.filter((id) => idx.reverted.has(seqOfNodeKey(K.tool(id), idx)?.seq))
114
+ assert.equal(withReverted.length, 0)
115
+ })
116
+
117
+ test('reverted 口径:只藏边界及其后', () => {
118
+ const idx = buildIndex(CORPUS)
119
+ assert.equal(idx.reverted.has(54), true, '边界消息自己也要藏(opencode slice(0, boundaryIndex))')
120
+ assert.equal(idx.reverted.has(26), false, '边界之前的不藏')
121
+ assert.equal(idx.reverted.has(8), false)
122
+ })
123
+
124
+ test('查不到时返回 null → 调用方保持可见(绝不误藏)', () => {
125
+ const idx = buildIndex(CORPUS)
126
+ assert.equal(seqOfNodeKey(K.user('00000000-0000-0000-0000-000000000000'), idx), null)
127
+ assert.equal(seqOfNodeKey(K.step(9, 9), idx), null)
128
+ assert.equal(seqOfNodeKey(K.tail(9), idx), null)
129
+ })
130
+
131
+ test('compaction / command 等不参与映射(它们不是回撤对象)', () => {
132
+ const idx = buildIndex(CORPUS)
133
+ assert.equal(seqOfNodeKey('9:compactionxx', idx), null)
134
+ assert.equal(seqOfNodeKey('7:commandyy', idx), null)
135
+ })
136
+
137
+ test('重复 messageId(restore 重放)保留全部 seq,指向最新', () => {
138
+ const idx = buildIndex([
139
+ { seq: 5, type: 'user/message', id: 'dup', visible: true },
140
+ { seq: 99, type: 'user/message', id: 'dup', visible: true }, // 重放副本
141
+ ])
142
+ assert.equal(idx.byMessageId.get('dup'), 99, '指向最新(当前 surface 上的那条)')
143
+ assert.deepEqual(idx.dupByMessageId.get('dup'), [5, 99])
144
+ assert.equal(idx.dupMessageId, 1)
145
+ })
146
+
147
+ test('回归:恢复后再回滚,副本必须被藏(用最早 seq 判会漏)', () => {
148
+ // fence=70;原件 seq=54、restore 副本 seq=70
149
+ const idx = buildIndex([
150
+ { seq: 54, type: 'user/message', id: 'x', visible: true },
151
+ { seq: 70, type: 'user/message', id: 'x', visible: true },
152
+ ])
153
+ idx.fences = [70]
154
+ const hit = seqOfNodeKey(K.user('x'), idx)
155
+ const cands = hit.all
156
+ const hiddenByEarliestOnly = idx.fences.some((f) => cands[0] >= f) // 54 >= 70 → false
157
+ const hiddenByAny = idx.fences.some((f) => cands.some((q) => q >= f)) // 70 >= 70 → true
158
+ assert.equal(hiddenByEarliestOnly, false, '只用最早 seq 会漏藏')
159
+ assert.equal(hiddenByAny, true, '任一 seq 越过 fence 就要藏')
160
+ })
161
+
162
+ test('空/畸形 payload 不抛异常', () => {
163
+ const idx = buildIndex(undefined)
164
+ assert.equal(idx.total, 0)
165
+ assert.equal(seqOfNodeKey(K.user('x'), idx), null)
166
+ })
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 0.9.3 /undo 的纯逻辑回归。
3
+ *
4
+ * /undo 走官方斜杠管线 `ctx.inputTriggers.registerSource`,注册路径踩过四个坑,
5
+ * 全部锁在这里(宿主侧的契约坑无法用单测覆盖,故此文件锁「我方判定」那一半)。
6
+ */
7
+ import test from 'node:test'
8
+ import assert from 'node:assert/strict'
9
+
10
+ const bare = (id) => String(id || '').replace(/^session-/, '')
11
+ const pickLastVisible = (rows) => {
12
+ for (let i = rows.length - 1; i >= 0; i--) if (rows[i] && rows[i].seq != null && rows[i].visible) return rows[i]
13
+ return null
14
+ }
15
+ const shouldHide = (cands, fences, reverted) =>
16
+ fences.length ? cands.some((q) => fences.some((f) => q >= f)) : cands.some((q) => reverted.has(q))
17
+
18
+ test('sessionId 归一化:DOM dataset 带 session- 前缀', () => {
19
+ assert.equal(bare('session-0da37218-2672-48b7-adaa-7735af4adee2'), '0da37218-2672-48b7-adaa-7735af4adee2')
20
+ assert.equal(bare('0da37218-2672'), '0da37218-2672')
21
+ assert.equal(bare(null), '')
22
+ })
23
+
24
+ test('回归:__currentSessionId 带前缀会让 API 请求静默失败', () => {
25
+ // 送 "session-<uuid>" 给 /api/message-ops/revert 会落不到会话目录
26
+ assert.notEqual(bare('session-x'), 'session-x')
27
+ })
28
+
29
+ test('lastRevertable 必须挑 surface 上的那条', () => {
30
+ const rows = [
31
+ { seq: 8, visible: true },
32
+ { seq: 54, visible: true },
33
+ { seq: 70, visible: false }, // restore 重放副本:不在模型 surface 上
34
+ ]
35
+ // 无脑取最后一条 → 70 → 服务端报 "start seq 70 not found in surface"(实测���
36
+ assert.equal(rows[rows.length - 1].seq, 70)
37
+ // 正确:取最后一条 visible
38
+ assert.equal(pickLastVisible(rows).seq, 54)
39
+ })
40
+
41
+ test('没有 surface 上的用户消息 → 返回 null,不发请求', () => {
42
+ assert.equal(pickLastVisible([{ seq: 8, visible: false }]), null)
43
+ assert.equal(pickLastVisible([]), null)
44
+ })
45
+
46
+ test('fence 判定:边界及其后都藏', () => {
47
+ assert.equal(shouldHide([8], [8], new Set()), true)
48
+ assert.equal(shouldHide([7], [8], new Set()), false)
49
+ assert.equal(shouldHide([70], [70, 8], new Set()), true, '多个 fence 取并集')
50
+ assert.equal(shouldHide([54], [70, 8], new Set()), true)
51
+ assert.equal(shouldHide([7], [70, 8], new Set()), false)
52
+ })
53
+
54
+ test('fence 为空时退回 reverted 集合', () => {
55
+ assert.equal(shouldHide([54], [], new Set([54, 63])), true)
56
+ assert.equal(shouldHide([8], [], new Set([54, 63])), false)
57
+ })
58
+
59
+ test('空 fences + 空 reverted → 全部可见', () => {
60
+ assert.equal(shouldHide([1, 2, 3], [], new Set()), false)
61
+ })