@240xu/dsh-message-ops 0.9.5 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js CHANGED
@@ -1,16 +1,8 @@
1
1
  /* global window, document, fetch, navigator */
2
2
  /**
3
3
  * dsh-message-ops 客户端:会话头部按钮 + 共享操作对话框 + 侧栏行菜单项。
4
- *
5
- * 一个对话框承载三种操作(回滚 / 删除 / 分支):
6
- * - 拉取 GET /api/message-ops/messages 展示消息级列表(可见性已标注)
7
- * - 回滚/删除为破坏性操作:需勾选风险确认(回滚仍可通过再次发送恢复,
8
- * 删除为遮蔽语义;日志永远 append-only,原事件保留)
9
- * - 分支为唯一非破坏操作:无需确认,成功后提示新会话 id 并刷新列表
10
- * 回滚/删除成功后整页刷新(surface 变化需要会话重渲染)。
11
- *
12
- * 结构照抄 @huanlin/dsh-plugin-session-delete 的成熟模式:slots.inject
13
- * 延迟注册(宿主晚声明也不白屏)、locale 服务 zh/en、DOM 注入侧栏菜单。
4
+ * 一个对话框承载回滚 / 删除 / 分支三种操作;日志 append-only,遮蔽可恢复。
5
+ * 结构照抄 @huanlin/dsh-plugin-session-delete。事故复盘见 README「历史事故记录」#1。
14
6
  */
15
7
  window.__ModuleLoader__.load({
16
8
  id: '@240xu/dsh-message-ops',
@@ -28,9 +20,58 @@ window.__ModuleLoader__.load({
28
20
  const EVENT = 'dsh-message-ops:open'
29
21
  // 0.5.2(P2):回滚/恢复成功后广播 → RevertDock 重拉标记(否则 dock 只在切会话时刷新)
30
22
  const CHANGED_EVENT = 'dsh-message-ops:changed'
31
- const emitChanged = () => { try { window.dispatchEvent(new CustomEvent(CHANGED_EVENT)) } catch { /* noop */ } }
23
+ // 0.9.7(P4):messageId→seq 索引失效(dataSig 变化)—— 已挂载的
24
+ // MsgSlotActions 靠它重跑解析 effect,否则「新 AI 消息旁没有按钮」。
25
+ const SEQ_INDEX_EVENT = 'dsh-message-ops:seq-index'
26
+ // 0.9.7(P0-2 读合并):一次写操作会同时触发 150/700/1600ms 三连 +
27
+ // RevertDock 的 CHANGED 重拉 + openSession 后 MO 调度的 scan(5~6 次 GET)。
28
+ // 同一会话在此窗口内的请求共享同一个 promise;窗口**必须 < 1600ms**,
29
+ // 否则「视图重建后重算隐藏」的 1600ms 兜底会被上一次响应吞掉。
30
+ const MSG_COALESCE_MS = 1000
31
+ var __messagesMemo = { url: null, at: 0, p: null, settled: false }
32
+ var invalidateMessagesMemo = () => { __messagesMemo = { url: null, at: 0, p: null, settled: false } }
33
+ const emitChanged = () => {
34
+ // 数据变了:连同本地缓存一起作废(否则 8s TTL 会让 openSession 后的
35
+ // scan 拿旧 payload 重算隐藏 = 「回滚了但界面没变」)。
36
+ invalidateMessagesMemo()
37
+ if (__peekRowsCache) { const c = __peekRowsCache(); if (c) c.at = 0 }
38
+ try { window.dispatchEvent(new CustomEvent(CHANGED_EVENT)) } catch { /* noop */ }
39
+ }
32
40
  const NS = 'dsh-message-ops'
33
41
 
42
+ /**
43
+ * GET /api/message-ops/messages 的唯一出口(0.9.7 读合并)。
44
+ * - 并发调用共享同一个 promise;
45
+ * - 已结算的响应在 MSG_COALESCE_MS 内复用(一次写操作的 5~6 路重拉 → 1~2 次网络);
46
+ * - 只在 `ok:true` 时才留窗口:失败/非 2xx 立刻作废,免得把后续重试也吃掉;
47
+ * - 1600ms 那档兜底刷新由调用方先 `invalidateMessagesMemo()` 再拉,保证是真网络。
48
+ */
49
+ var fetchMessagesJson = (rawUrl) => {
50
+ // 归一 sessionId 写法:本文件有的调用方传 `session-xxx`(dock / 对话框),
51
+ // 有的传裸 uuid(fetchRows / /redo)。不归一就是两个缓存槽,合并直接失效。
52
+ // 服务端两种写法都认(index.js "uuid or session-<uuid> form")。
53
+ const url = String(rawUrl).replace(/([?&]sessionId=)session-/, '$1')
54
+ const m = __messagesMemo
55
+ if (m.url === url && m.p && (!m.settled || Date.now() - m.at < MSG_COALESCE_MS)) return m.p
56
+ const entry = { url, at: Date.now(), p: null, settled: false }
57
+ entry.p = fetch(url)
58
+ .then((r) => r.json().catch(() => null).then((d) => ({ r, d })))
59
+ .then(({ r, d }) => {
60
+ if (!r.ok || !d || d.ok !== true) throw new Error((d && d.error) || ('HTTP ' + r.status))
61
+ entry.settled = true
62
+ entry.at = Date.now()
63
+ return d
64
+ })
65
+ .catch((e) => { if (__messagesMemo === entry) invalidateMessagesMemo(); throw e })
66
+ __messagesMemo = entry
67
+ return entry.p
68
+ }
69
+
70
+ // 0.9.7(P0-4):zh/en 两本字典 key 集合**必须一致且顺序一致**——宿主 locale
71
+ // 的 translate() 按「活跃语言 → en」回退链查表(zh 回退 en,en 无回退),
72
+ // 所以缺 key 不一定看得见:zh 缺 → 落到 en(0.9.x 这批 en 值是中文,
73
+ // zh 用户"碰巧"正常);en 缺 → 直接把 key 当文案显示。
74
+ // 反过来 en 值写成中文时,英文用户会看到中文。测试锁死了两侧 key 序列相等。
34
75
  const zhDict = {
35
76
  'button.title': '消息操作(回滚/删除/分支)',
36
77
  'dialog.title': '消息操作',
@@ -42,7 +83,7 @@ window.__ModuleLoader__.load({
42
83
  'dialog.runningWarn': '⚠ 会话正在运行:请先停止该会话再执行回滚/删除/分支。',
43
84
  'dialog.pick': '选择一条消息:',
44
85
  'dialog.pickFirst': '第 1 步 · 在下方选择一条消息,第 2 步在这里选择操作。',
45
- 'dialog.pickedAs': '已选 #{seq} · {{text}}',
86
+ 'dialog.pickedAs': '已选 #{seq} · {text}',
46
87
  'dialog.invisible': '(已遮蔽,仅日志可见)',
47
88
  'dialog.showMore': '显示更多(剩余 {n} 条)',
48
89
  'dialog.more': '…(仅显示最近 200 条,共 {n} 条)',
@@ -52,6 +93,11 @@ window.__ModuleLoader__.load({
52
93
  'op.deleteDesc': '仅遮蔽所选的一条消息;其余内容保持不变。',
53
94
  'op.branch': '从此条分支为新会话',
54
95
  'op.branchDesc': '复制所选消息(含)之前的全部事件为新会话(原会话不变,非破坏操作)。',
96
+ 'slot.revert': '回滚到此条',
97
+ 'slot.revertUnmatched': '在日志里定位不到这条消息的 seq(通常是模型写的摘要与渲染文本偏差过大)——请改用「消息操作」对话框。',
98
+ 'toast.openNew': '打开新会话',
99
+ 'fork.official': '分支完成:新会话 {id}',
100
+ 'fork.unavailable': '官方分支不可用:通常是因为会话正在运行,请先停止会话后重试。分支功能由 dsh 内置的 session/fork 提供。',
55
101
  'ack.revert': '我已了解:回滚会遮蔽所选消息及其后的全部内容',
56
102
  'ack.delete': '我已了解:将遮蔽这一条消息(日志中仍保留)',
57
103
  'confirm.revert': '回滚',
@@ -60,27 +106,28 @@ window.__ModuleLoader__.load({
60
106
  'busy.revert': '回滚中…',
61
107
  'busy.delete': '删除中…',
62
108
  'busy.branch': '分支中…',
63
- 'done.branch': '分支完成:新会话 {id}(列表刷新后可见)',
109
+ 'done.restore': '恢复完成:重放 {n} 条,跳过不可重放 {s} 条',
64
110
  'done.revert': '回滚完成,刷新页面后生效',
65
111
  'done.delete': '删除完成,刷新页面后生效',
66
112
  'action.reload': '刷新页面',
67
113
  'errorPrefix': '操作失败:',
68
- 'slot.revert': '回滚到此条',
69
- 'slot.delete': '删除此条',
70
- 'slot.branch': '从此分支',
71
- 'toast.openNew': '打开新会话',
72
- 'fork.official': '分支完成:新会话 {id}',
73
- 'fork.unavailable': '官方分支不可用:通常是因为会话正在运行,请先停止会话后重试。分支功能由 dsh 内置的 session/fork 提供。',
74
- 'done.restore': '恢复完成:重放 {n} 条,跳过不可重放 {s} 条',
75
- 'busy.restore': '恢复中…',
76
114
  'dock.title': '已回撤 {n} 条消息',
77
115
  'dock.expand': '展开回撤列表',
78
116
  'dock.collapse': '折叠回撤列表',
117
+ 'dock.shadowedN': '{n} 条已遮蔽',
79
118
  'dock.restore': '恢复',
80
119
  'dock.restoring': '恢复中…',
81
120
  'slot.quote': '引用到输入框',
82
121
  'quote.done': '已引用到输入框',
83
122
  'quote.unavailable': '引用不可用(输入框不可写或无全文)',
123
+ 'undo.label': '回滚上一条消息',
124
+ 'undo.desc': '移除最后一条用户消息,原文回填输入框',
125
+ 'undo.done.undo': '已回滚上一条消息',
126
+ 'undo.done.redo': '已恢复上一条被回滚的消息',
127
+ 'undo.none': '没有可回滚的消息',
128
+ 'undo.none.redo': '没有可恢复的回滚',
129
+ 'redo.label': '恢复上一条被回滚的消息',
130
+ 'redo.desc': '把回滚掉的消息重新放回对话',
84
131
  'menu.ops': '消息操作',
85
132
  }
86
133
 
@@ -95,7 +142,7 @@ window.__ModuleLoader__.load({
95
142
  'dialog.runningWarn': '⚠ Session is running: stop it before revert / delete / branch.',
96
143
  'dialog.pick': 'Pick a message:',
97
144
  'dialog.pickFirst': 'Step 1 · pick a message below, then choose an operation here.',
98
- 'dialog.pickedAs': 'Selected #${seq} · ${text}',
145
+ 'dialog.pickedAs': 'Selected #{seq} · {text}',
99
146
  'dialog.invisible': ' (shadowed, log-only)',
100
147
  'dialog.showMore': 'Show more ({n} older)',
101
148
  'dialog.more': '…(showing latest 200 of {n})',
@@ -107,8 +154,6 @@ window.__ModuleLoader__.load({
107
154
  'op.branchDesc': 'Copies everything up to and including the picked message into a new session (original untouched, non-destructive).',
108
155
  'slot.revert': 'Revert to here',
109
156
  'slot.revertUnmatched': 'Cannot locate this message seq in the log (usually the model-written summary drifted too far from the rendered text) — use the Message ops dialog instead.',
110
- 'slot.delete': 'Delete this message',
111
- 'slot.branch': 'Branch from here',
112
157
  'toast.openNew': 'Open new session',
113
158
  'fork.official': 'Branched (official fork): new session {id}',
114
159
  'fork.unavailable': 'Built-in branch unavailable — usually because the session is running. Stop it and retry. Branching is provided by the dsh built-in session/fork.',
@@ -120,9 +165,7 @@ window.__ModuleLoader__.load({
120
165
  'busy.revert': 'Reverting…',
121
166
  'busy.delete': 'Deleting…',
122
167
  'busy.branch': 'Branching…',
123
- 'done.branch': 'Branched: new session {id} (visible after list refresh)',
124
168
  'done.restore': 'Restored: replayed {n}, skipped non-replayable {s}',
125
- 'busy.restore': 'Restoring…',
126
169
  'done.revert': 'Reverted; reload to apply',
127
170
  'done.delete': 'Deleted; reload to apply',
128
171
  'action.reload': 'Reload page',
@@ -136,14 +179,14 @@ window.__ModuleLoader__.load({
136
179
  'slot.quote': 'Quote to composer',
137
180
  'quote.done': 'Quoted into composer',
138
181
  '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
- 'undo.none.redo': '没有可恢复的回滚',
145
- 'redo.label': '恢复上一条被回滚的消息',
146
- 'redo.desc': '把回滚掉的消息重新放回对话',
182
+ 'undo.label': 'Undo last message',
183
+ 'undo.desc': 'Remove the last user message and put its original text back into the composer',
184
+ 'undo.done.undo': 'Undid the last message',
185
+ 'undo.done.redo': 'Restored the last reverted message',
186
+ 'undo.none': 'No message to undo',
187
+ 'undo.none.redo': 'No revert to redo',
188
+ 'redo.label': 'Restore the last reverted message',
189
+ 'redo.desc': 'Put the reverted message back into the conversation',
147
190
  'menu.ops': 'Message ops',
148
191
  }
149
192
 
@@ -303,8 +346,7 @@ window.__ModuleLoader__.load({
303
346
  useEffect(() => {
304
347
  if (state !== 'loading' || !target || !target.sessionId) return
305
348
  let cancelled = false
306
- fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(target.sessionId))
307
- .then((r) => r.json())
349
+ fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(target.sessionId))
308
350
  .then((data) => {
309
351
  if (cancelled) return
310
352
  if (!data || !data.ok) throw new Error(data && data.error ? data.error : `HTTP ${data && data.status}`)
@@ -343,11 +385,8 @@ window.__ModuleLoader__.load({
343
385
  setBusyMsg(t('busy.' + (mode === 'revert' || mode === 'delete' ? mode : 'branch')))
344
386
  setState('busy'); setError(null)
345
387
  if (mode === 'branch') {
346
- // 0.9.0:分支**只走官方** sessions.fork({atSeq})。
347
- // 原先有一条「官方失败 → 磁盘 applyBranch」的回落,但那个实现语义是错的:
348
- // 它删掉 isSeeded(官方 fork 设 true)、不写 inheritedEventCount、
349
- // 也不调 buildForkSeed 补 step/turn closers → 产出的子会话边界可能悬空。
350
- // 官方 fork 失败通常意味着源会话正在运行,正确做法是拒绝而非绕过引擎写盘。
388
+ // 0.9.0:分支**只走官方** sessions.fork({atSeq});失败即拒绝(源会话多半在
389
+ // 运行),不再回落写盘 —— 被删的磁盘 applyBranch 语义复盘见 README「为什么不重复造轮子」。
351
390
  const forkPath = pickForkPath(__sessionsSvc)
352
391
  if (forkPath.kind !== 'official') {
353
392
  setError(t('fork.unavailable'))
@@ -385,8 +424,12 @@ window.__ModuleLoader__.load({
385
424
  // S6 修复(G-M1):不再 900ms 裸 location.reload。成功走 devkit
386
425
  // 标准 toast(无 devkit 时降级为对话框内 doneMsg),并提供手动
387
426
  // 「刷新页面」按钮。
388
- ? t('done.restore', { n: String(data.restoredCount != null ? data.restoredCount : '?'), s: String(data.skipped != null ? data.skipped : 0) })
389
- : t(mode === 'revert' ? 'done.revert' : 'done.delete')
427
+ // 0.9.7:补回 ec862d6(0.9.0) 误删的 `const okMsg =`——留下悬挂的
428
+ // `? :` 会让成功路径抛 ReferenceError 落进 .catch(用户看到「操作失败」,
429
+ // notifyDone/emitChanged/openSession/回填全不执行),失败路径则恒走
430
+ // `?` 分支把成功文案当错误抛出。对话框 mode 只有 revert|delete|branch,
431
+ // branch 在上面已 return,故 done.restore 分支在此不可达,一并删掉。
432
+ const okMsg = mode === 'revert' ? t('done.revert') : t('done.delete')
390
433
  // 0.4.0 composer 回填(opencode 式):回滚用户消息 → 原文回填输入框,「编辑重发」零按钮
391
434
  if (mode === 'revert' && pickedMsg && pickedMsg.role === 'user' && pickedMsg.fullText
392
435
  && __inputActions && typeof __inputActions.setDraft === 'function') {
@@ -493,7 +536,9 @@ window.__ModuleLoader__.load({
493
536
  '#' + m.seq + ' ' + (m.role || '') + ' · ' + (m.snippet || '') + (m.visible === false ? t('dialog.invisible') : '')),
494
537
  )),
495
538
  ),
496
- opsPanel,
539
+ // 0.9.7:删掉列表**之后**的旧 opsPanel——0.9.0 把操作区挪到列表之前时
540
+ // 没删旧位置,两组同名 radio(name='dsh-message-ops-mode')互抢,
541
+ // checked 状态在两份 DOM 之间互相顶掉。
497
542
  ])
498
543
  }
499
544
 
@@ -626,20 +671,20 @@ window.__ModuleLoader__.load({
626
671
  const [seq, setSeq] = React.useState(null)
627
672
  const [fullText, setFullText] = React.useState(null)
628
673
  const [busy, setBusy] = React.useState(null) // 'revert' | null(S11 双提交防护)
674
+ // 0.9.7(P4):索引被 dataSig 重建后要重跑解析,否则「新 AI 消息旁
675
+ // 没有回撤/引用按钮」—— 已经挂载的槽位 effect 不会因缓存被换而重跑。
676
+ const [idxRev, setIdxRev] = React.useState(0)
677
+ React.useEffect(() => {
678
+ const onIdx = () => setIdxRev((v) => v + 1)
679
+ window.addEventListener(SEQ_INDEX_EVENT, onIdx)
680
+ return () => window.removeEventListener(SEQ_INDEX_EVENT, onIdx)
681
+ }, [])
629
682
  React.useEffect(() => {
630
683
  if (!messageId || !sessionId) return
631
684
  let alive = true
632
- const cached = __seqIndexCache.get(sessionId)
633
- const resolve = (index) => {
634
- if (!alive) return
635
- const hit = index && index.get(String(messageId))
636
- if (typeof hit === 'number') setSeq(hit)
637
- }
638
- if (cached && typeof cached.then === 'function') cached.then(resolve).catch(() => {})
639
- else if (cached) resolve(cached)
640
- else {
641
- const p = fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId))
642
- .then((r) => (r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status))))
685
+ let retried = false
686
+ const load = () => {
687
+ const p = fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId))
643
688
  .then((data) => {
644
689
  const index = new Map()
645
690
  const full = new Map()
@@ -656,10 +701,30 @@ window.__ModuleLoader__.load({
656
701
  __seqIndexCache.set(sessionId, p)
657
702
  // 0.5.2(P2):失败必须清缓存——否则 rejected promise 被永久缓存,
658
703
  // 该会话按钮/dock 到刷新页面为止全部失效
659
- p.then(resolve).catch(() => { __seqIndexCache.delete(sessionId) })
704
+ // 0.9.7:只在缓存里还是**我们这条** promise 时才删(syncSeqIndex 可能已换掉)
705
+ p.catch(() => { if (__seqIndexCache.get(sessionId) === p) __seqIndexCache.delete(sessionId) })
706
+ return p
707
+ }
708
+ const resolve = (index) => {
709
+ if (!alive) return
710
+ const hit = index && index.get(String(messageId))
711
+ if (typeof hit === 'number') { setSeq(hit); return }
712
+ // 0.9.7(P4):索引里没有这个 messageId = 会话已增长(或索引过期)。
713
+ // 旧实现这里**什么都不做**,`seq` 永远是 null → 组件 return null →
714
+ // 按钮再也不渲染。现在失效并重拉一次(retried 保证不自旋);
715
+ // 复用 fetchMessagesJson 的 1s 合并窗口,连续上新不会打爆请求。
716
+ if (retried) return
717
+ retried = true
718
+ __seqIndexCache.delete(sessionId)
719
+ __fullTextCache.delete(sessionId)
720
+ load().then(resolve).catch(() => {})
660
721
  }
722
+ const cached = __seqIndexCache.get(sessionId)
723
+ if (cached && typeof cached.then === 'function') cached.then(resolve).catch(() => {})
724
+ else if (cached) resolve(cached)
725
+ else load().then(resolve).catch(() => {})
661
726
  return () => { alive = false }
662
- }, [messageId, sessionId])
727
+ }, [messageId, sessionId, idxRev])
663
728
 
664
729
  // 原文(引用用):seq 解析后按需取全文
665
730
  React.useEffect(() => {
@@ -703,6 +768,9 @@ window.__ModuleLoader__.load({
703
768
  try { data = await res.json() } catch { /* keep {} */ }
704
769
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
705
770
  notifyDone(t('done.revert'))
771
+ // 0.9.6:回填被删掉的那句用户原文(边界是 AI 消息时取它之前那条用户消息)。
772
+ // 此前这个入口完全不回填 —— 表现就是「回滚成功但消息框空着」。
773
+ refillComposer(sessionId, seq)
706
774
  revealSession()
707
775
  emitChanged()
708
776
  })
@@ -760,7 +828,14 @@ window.__ModuleLoader__.load({
760
828
  // (按 restoredSourceSeqs 进度算;旧 notice 无该字段 → 服务端视为整段已恢复)。
761
829
  // 旧的"行内 restoresSeq 集合"客户端判定已删除——按轮步进下部分恢复的标记
762
830
  // 也带 restoresSeq,旧逻辑会把它们误杀(实测:第一轮恢复后整条消失)。
763
- return (msgs || []).filter((m) => m.marker && m.sourceKind !== 'compact-checkpoint' && m.restoreComplete !== true)
831
+ // 0.10.1:再排掉**已提交**的 marker —— 对齐 opencode
832
+ // (用户发出下一条真实消息后,opencode 在 Session.prompt 里自动
833
+ // SessionRevert.commit() → revert:null → affordance 消失)。
834
+ // 我们是 append-only,marker 不会真消失,所以由服务端按
835
+ // 「marker 之后有无 source.kind==='user' 的真实输入」算出 committed。
836
+ return (msgs || []).filter((m) =>
837
+ m.marker && m.sourceKind !== 'compact-checkpoint'
838
+ && m.restoreComplete !== true && m.committed !== true)
764
839
  }
765
840
 
766
841
  function RevertDock(props) {
@@ -812,8 +887,7 @@ window.__ModuleLoader__.load({
812
887
  let alive = true
813
888
  const onChange = () => load()
814
889
  window.addEventListener(CHANGED_EVENT, onChange)
815
- const load = () => fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId))
816
- .then((r) => (r.ok ? r.json() : null))
890
+ const load = () => fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId))
817
891
  .then((data) => {
818
892
  if (!alive || !data || !data.ok) return
819
893
  const msgs = data.messages || []
@@ -857,13 +931,11 @@ window.__ModuleLoader__.load({
857
931
  try {
858
932
  if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sessionId)
859
933
  } catch { /* fallthrough */ }
860
- // 0.9.1:重放的消息带**新 seq**,被恢复的行必须解除 hidden,
861
- // 同时 dock 的权威 marker 列表要重拉。
862
- try { window.dispatchEvent(new Event(CHANGED_EVENT)) } catch { /* non-browser */ }
863
- // 0.9.1:重放的消息带**新 seq**,被恢复的行必须解除 hidden;
864
- // 同时 dock 的 marker 列表要按权威数据重算(restoreComplete 会变 true)。
934
+ // 0.9.1:重放的消息带**新 seq**,被恢复的行必须解除 hidden;dock 的
935
+ // marker 列表要按权威数据重算(restoreComplete 会变 true)后重拉。
936
+ emitChanged()
865
937
  for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(sessionId) }, delay)
866
- const fresh = await fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId)).then((r) => (r.ok ? r.json() : null)).catch(() => null)
938
+ const fresh = await fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId)).catch(() => null)
867
939
  if (fresh && fresh.ok) setMarkers(activeMarkers(fresh.messages || []))
868
940
  })
869
941
  .catch((reason) => {
@@ -935,34 +1007,62 @@ window.__ModuleLoader__.load({
935
1007
  }
936
1008
 
937
1009
  // --- 0.7.0 用户消息「回滚」按钮(DOM 注入,挂在官方动作行内)-------------------
938
- // 0.6.0 的教训(用户实测反馈):absolute 覆盖在气泡上 = 压住文字、布局乱;
939
- // 且 opacity:0 + :hover 在触屏上永远不显形(点不了)。
940
1010
  // 官方用户消息的动作行 = .xzv4MW_actions(含 Copy,height28,位于消息下方 16px),
941
- // 可见性由宿主 [data-actions-reveal] 控制。0.7.0:把按钮 append 进该行,
942
- // 与 Copy 同级同层,可见性天然继承宿主动作行(不再自己玩 hover)。
1011
+ // 可见性由宿主 [data-actions-reveal] 控制。把按钮 append 进该行、与 Copy 同级同层,
1012
+ // 可见性天然继承宿主动作行(不再自己玩 hover)。0.6.0 的 absolute 覆盖教训见 README「历史事故记录」#2。
943
1013
  function installUserRevertInjector() {
944
1014
  if (window.__MOPS_USER_REVERT_INSTALLED) return
945
1015
  window.__MOPS_USER_REVERT_INSTALLED = true
946
1016
  var rowsCache = { sid: null, rows: null, at: 0 }
947
1017
  __peekRowsCache = () => rowsCache
948
1018
  var norm = (x) => String(x || '').replace(/\s+/g, '')
949
- var fetchRows = (sid) => {
1019
+
1020
+ // 0.9.7(P4):messageId→seq / 全文索引挂在**同一个 dataSig** 上。
1021
+ // 旧实现每会话只写一次、仅失败时 delete —— 会话增长后新 assistant 消息的
1022
+ // messageId 不在索引里,`seq == null` → MsgSlotActions 直接 return null,
1023
+ // 那条消息旁的回撤/引用按钮**再也不渲染**。dataSig 变了就用手里这份全量
1024
+ // 载荷就地重建(零额外请求),并广播 SEQ_INDEX_EVENT 让已挂载的槽位重跑解析。
1025
+ var __seqDataSig = null
1026
+ var syncSeqIndex = (sid, messages, idx) => {
1027
+ const sig = sid + '/' + idx.total + '/' + idx.shadowed.size + '/' + idx.visibleTurns.size
1028
+ if (sig === __seqDataSig) return
1029
+ __seqDataSig = sig
1030
+ const index = new Map()
1031
+ const full = new Map()
1032
+ for (const m of (messages || [])) {
1033
+ if (!m || m.id == null) continue
1034
+ const k = String(m.id)
1035
+ // 同 id 取**最早** seq —— 与槽位自己的 buildSeqIndex 口径一致
1036
+ // (隐藏判据 buildIndex 取最新,两套语义不能混)。
1037
+ if (!index.has(k)) index.set(k, m.seq)
1038
+ if (m.fullText) full.set(k, m.fullText)
1039
+ }
1040
+ for (const key of [sid, 'session-' + sid]) {
1041
+ __seqIndexCache.set(key, index)
1042
+ __fullTextCache.set(key, full)
1043
+ }
1044
+ try { window.dispatchEvent(new CustomEvent(SEQ_INDEX_EVENT)) } catch { /* non-browser */ }
1045
+ }
1046
+
1047
+ var fetchRows = (sidIn) => {
1048
+ // 0.9.7:统一按**裸 uuid** 作缓存键。调用方有的传 `session-xxx`(scan /
1049
+ // /undo 的 rawSid)有的传裸 uuid(/redo 的 bareSessionId)—— 混用会让
1050
+ // rowsCache.sid 在两个键之间来回横跳,每次都是缓存未命中(白白多发 GET)。
1051
+ const sid = bareSessionId(sidIn)
950
1052
  if (rowsCache.sid === sid && rowsCache.rows && Date.now() - rowsCache.at < 8000) return Promise.resolve(rowsCache)
951
- return fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
952
- .then((r) => (r.ok ? r.json() : null))
1053
+ return fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
953
1054
  .then((d) => {
954
1055
  // 宿主会把 <system-reminder> / runtime context 等也记为 role=user 的行,
955
- // DOM 里并不渲���成"我的消息"块 —— 必须滤掉,否则按序配对会错位(0.7.0 根因)。
956
- //
957
- // 0.9.0 两个实机 bug(浏览器实测:4 个按钮 data-mops-seq 全为 null,点击必失败):
958
- // ① 正则跑在 norm() 之后的串上,而 norm 是 replace(/\s+/g,'') —— 删掉**全部**空白,
959
- // `current\s+runtime\s+context` 永远匹配不上 → runtime-context 伪行漏进配对。
960
- // 修法:injected() 改判**原始 snippet**。
961
- // ② 过滤了 `m.visible !== false`,但宿主聊天视图**不施��**遮蔽模型,照常渲染
962
- // 被回滚遮蔽的消息 → 配对候选与 DOM 块零交集。
963
- // 修法:DOM 配对必须覆盖全部 user 行(含遮蔽态)。
964
- // 注意:对话框的「可回滚目标」列表仍应过滤 visible(那是另一套语义)。
965
- const injected = (raw) => /^<system-reminder|current\s+runtime\s+context|^<system-Reminder/i.test(String(raw || ''))
1056
+ // DOM 里并不渲染成"我的消息"块 —— 必须滤掉,否则按序配对会错位(0.7.0 根因)。
1057
+ // 注意:对话框的「可回滚目标」列表仍应过滤 visible(那是另一套语义)。
1058
+ // 稳妥做法本该在服务端打 injected 标志,先在客户端补齐正则。
1059
+ // 判据一律用**原始 snippet**(norm() 删掉全部空白,正则必然失配)。
1060
+ // 0.9.0 / 0.9.6 两轮事故复盘 + 120 份日志普查样本见 README「历史事故记录」#3。
1061
+ // 关键约束:id 后必须跟得上具体形态([\w-]+ / [0-9a-f]{8}-),
1062
+ // 否则 `Background job 是我自己的问题` 这种真人输入会被误杀
1063
+ // (曾用 ^background job\b,测试当场抓到这个误杀)。
1064
+ // 样本里没出现过的模式(已停止 / User feedback:)一律**不加** —— 没证据就不猜。
1065
+ 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 || ''))
966
1066
  const rows = ((d && d.messages) || [])
967
1067
  .filter((m) => m && m.role === 'user')
968
1068
  .map((m) => ({ seq: m.seq, sn: norm(m.snippet), raw: String(m.snippet == null ? '' : m.snippet), fullText: m.fullText ?? null, visible: m.visible !== false }))
@@ -970,27 +1070,16 @@ window.__ModuleLoader__.load({
970
1070
  // 0.9.1:同时产出 node-key 查表索引(隐藏 transcript 用)
971
1071
  const idx = buildIndex(d)
972
1072
  rowsCache = { sid: sid, rows: rows, idx: idx, at: Date.now() }
1073
+ syncSeqIndex(sid, d && d.messages, idx)
973
1074
  return rowsCache
974
1075
  })
975
1076
  .catch(() => (rowsCache.sid === sid ? rowsCache : null))
976
1077
  }
977
1078
 
978
1079
  // ═══ 0.9.1 宿主 node-key ↔ 日志 seq 的精确映射 ═══════════════════════════
979
- //
980
- // 背景(浏览器实测 + 源码核实):dsh 的 transcript **刻意不做 surface 折叠**。
981
- // 官方 surface.d.ts:51-63 明写 "replacement copies stay model-only" ——
982
- // 我们写的 surfaceOp replace 只折叠**模型 surface**(实测 393→13 节点),
983
- // 被遮蔽的消息在人类 transcript 里**照常渲染且完全可见**,连 marker 本身
984
- // 都不渲染(systemMessageDefinition 对 surfaceOp !== 'append' 直接 return null)。
985
- // 所以要让回滚「看得见」,只能在渲染层处理。
986
- //
987
- // 好消息:每一行的 `data-chat-node-key` 形如 `<len>:<kind><id>`,而 <id>
988
- // 就是日志事件的字段(user → messageId、assistant-step → `<turn>:<step>`、
989
- // tool-call → callId、turn-* → turn 号),客户端本来就已经建了
990
- // messageId → seq 索引(__seqIndexCache)。**精确查表,零启发式。**
991
- //
992
- // 旧实现用「40 字符前缀包含匹配」配对 DOM 与日志,实测 4 条里错 2 条
993
- // ("继续" 命中了 "继续,…"),已整体删除。
1080
+ // dsh transcript 刻意不折叠(surface.d.ts:51-63 "replacement copies stay
1081
+ // model-only"),回滚只能在渲染层按 `data-chat-node-key` 精确查表(零启发式)。
1082
+ // 背景长文与「40 字符前缀匹配」事故见 README「0.9.1 / 0.9.2 · 回滚「真的生效了」」。
994
1083
  var parseNodeKey = (k) => {
995
1084
  var m = /^(\d+):/.exec(k || '');
996
1085
  if (!m) return null;
@@ -1003,9 +1092,8 @@ window.__ModuleLoader__.load({
1003
1092
 
1004
1093
  /**
1005
1094
  * 从 /api/message-ops/messages 的响应构建全部查表。
1006
- * 三条铁律:① 索引只认唯一 id;② 缺数据一律返回 undefined(调用方保持可见);
1007
- * ③ visible 集合只收显式 true。
1008
- */
1095
+ * 两条铁律:① 索引只认唯一 id;② 缺数据一律返回 undefined(调用方保持可见)。
1096
+ */
1009
1097
  var buildIndex = (payload) => {
1010
1098
  var list = (payload && payload.messages) || []
1011
1099
  // 0.9.1:回合页脚/过程条不是消息,用 turn/end 的 seq 定位(边界常落在 turn 内部,
@@ -1015,9 +1103,8 @@ window.__ModuleLoader__.load({
1015
1103
  var byTurnStep = new Map();
1016
1104
  var byCallId = new Map();
1017
1105
  var byTurn = new Map();
1018
- var visible = new Set(); // 在模型 surface 上的 seq
1019
- var visibleTurns = new Set(); // 含至少一条可见消息的 turn 号
1020
- var dupMessageId = 0
1106
+ var shadowed = new Set(); // 落在 replace 区间内 = 已被回滚(transcript 藏行判据)
1107
+ var visibleTurns = new Set(); // 含至少一条**未被遮蔽**消息的 turn 号(回合 chrome)
1021
1108
  var dupByMessageId = new Map();
1022
1109
  for (var i = 0; i < list.length; i++) {
1023
1110
  var m = list[i];
@@ -1029,7 +1116,6 @@ window.__ModuleLoader__.load({
1029
1116
  // fence」。回放副本才是当前 surface 上的那条,用最早的 seq 判会让
1030
1117
  // 「恢复后再回滚」漏藏(实测 fence=70、副本 seq=70、原件 seq=54)。
1031
1118
  if (byMessageId.has(k)) {
1032
- dupMessageId++
1033
1119
  const arr = dupByMessageId.get(k) || [byMessageId.get(k)]
1034
1120
  arr.push(m.seq)
1035
1121
  dupByMessageId.set(k, arr)
@@ -1041,14 +1127,15 @@ window.__ModuleLoader__.load({
1041
1127
  }
1042
1128
  if (m.type === 'tool/call' && m.id != null) byCallId.set(String(m.id), m.seq);
1043
1129
  if (m.turn != null && !byTurn.has(String(m.turn))) byTurn.set(String(m.turn), m.seq);
1044
- if (m.visible === true) {
1045
- visible.add(m.seq);
1046
- if (m.turn != null) visibleTurns.add(String(m.turn));
1047
- }
1130
+ // 0.9.6:藏行判据用 shadowed(replace 区间),**不用** m.visible(模型 surface)。
1131
+ // visible 在 live 路径下对 tool/call 恒 false → 拿它当判据会把整页工具行全藏,
1132
+ // 故这里连集合都不建(判据样本见 test/surface-visibility.test.js)。
1133
+ if (m.shadowed === true) shadowed.add(m.seq);
1134
+ else if (m.turn != null) visibleTurns.add(String(m.turn));
1048
1135
  }
1049
1136
  // turnEnd 优先:它对「该 turn 内一条消息都没有」的情况仍然有效
1050
1137
  if (turnEnd) for (const k in turnEnd) if (Object.prototype.hasOwnProperty.call(turnEnd, k)) byTurn.set(k, turnEnd[k])
1051
- return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, visible, visibleTurns, dupMessageId, total: list.length };
1138
+ return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, shadowed, visibleTurns, total: list.length };
1052
1139
  };
1053
1140
 
1054
1141
  /** node-key → { seq, all }(all = 同 id 的全部 seq,处理 restore 重放副本)。 */
@@ -1098,26 +1185,42 @@ window.__ModuleLoader__.load({
1098
1185
  */
1099
1186
  var applySurfaceVisibility = (root, idx) => {
1100
1187
  if (!idx) return { hidden: 0, unresolved: 0, shown: 0 };
1101
- var rows = (root || document).querySelectorAll('[data-chat-node-key]');
1188
+ // 0.9.7(P2-1):root 既可传 document/元素(调用方自查),也可直接传
1189
+ // 已经查好的行集合 —— ensureAssign 每次都要算 rows.length 当签名,
1190
+ // 传集合避免同一次扫描里 querySelectorAll 跑两遍。
1191
+ var rows = (root && typeof root.querySelectorAll === 'function')
1192
+ ? root.querySelectorAll('[data-chat-node-key]')
1193
+ : (root || document.querySelectorAll('[data-chat-node-key]'));
1102
1194
  var hidden = 0, unresolved = 0, shown = 0;
1103
1195
  for (var i = 0; i < rows.length; i++) {
1104
1196
  var row = rows[i];
1105
- // 0.9.4 判据(见下):**模型 surface**。此前用 revertFences 塌缩成
1106
- // `seq >= min(fences)`,在一个有 19 个**离散** marker 的会话里
1107
- // min fence=10 → seq>=10 全藏 → 4792/4793 全被隐藏 → 正文几乎空白
1108
- // (截图复现)。改用 visible 后与宿主 visibleCount 精确吻合。
1197
+ // 0.9.6 藏行判据 = **replace 区间(shadowed)**;revertFences→visible→shadowed
1198
+ // 演进史(含 4792/4793 全藏事故)见 README「历史事故记录」#4。
1109
1199
  var hit = seqOfNodeKey(row.getAttribute('data-chat-node-key'), idx);
1110
- if (hit === null) { unresolved++; row.removeAttribute('hidden'); continue; }
1200
+ // 0.9.7(P2-1)幂等跳写:判据与执行时机**一字未改**,只在
1201
+ // 「目标状态 ≠ 当前状态」时才碰属性 —— 省掉全表几百次无效写。
1202
+ if (hit === null) {
1203
+ unresolved++;
1204
+ if (row.hasAttribute('hidden')) row.removeAttribute('hidden');
1205
+ continue;
1206
+ }
1111
1207
  var shouldHide;
1112
1208
  if (hit.turn !== undefined) {
1113
- // 回合 chrome:这个 turn 还有可见消息就露出来
1209
+ // 回合 chrome:本 turn 还有未被遮蔽的消息就露出
1114
1210
  shouldHide = !idx.visibleTurns.has(String(hit.turn));
1115
1211
  } else {
1116
- // 消息类:直接问「它在模型 surface 上吗」
1117
- shouldHide = !idx.visible.has(hit.seq);
1212
+ // 消息/工具类:**是否落在 replace 区间内**(= 被回滚掉了)。
1213
+ // ⚠️ 不能用 visible(模型 surface)——live 路径下 tool/call 恒不在 surface,
1214
+ // 会把整页工具行全藏(实测 157 行藏 152 行)。
1215
+ shouldHide = idx.shadowed.has(hit.seq);
1216
+ }
1217
+ if (shouldHide) {
1218
+ hidden++;
1219
+ if (row.getAttribute('hidden') !== 'until-found') row.setAttribute('hidden', 'until-found');
1220
+ } else {
1221
+ shown++;
1222
+ if (row.hasAttribute('hidden')) row.removeAttribute('hidden');
1118
1223
  }
1119
- if (shouldHide) { hidden++; row.setAttribute('hidden', 'until-found'); }
1120
- else { shown++; row.removeAttribute('hidden'); }
1121
1224
  }
1122
1225
  return { hidden, unresolved, shown };
1123
1226
  };
@@ -1166,11 +1269,11 @@ window.__ModuleLoader__.load({
1166
1269
  btn.setAttribute('data-mops-unmatched', '1')
1167
1270
  }
1168
1271
  }
1169
- var assignSeqs = (sid, cache) => {
1272
+ var assignSeqs = (sid, cache, anchors) => {
1170
1273
  const idx = cache && cache.idx
1171
1274
  if (!idx) return
1172
1275
  // 0.9.1:node-key 查表,替代旧的 40 字符前缀包含匹配(实测 4 条错 2 条)
1173
- for (const b of userAnchors()) {
1276
+ for (const b of (anchors || userAnchors())) {
1174
1277
  b.removeAttribute('data-mops-seq')
1175
1278
  b.removeAttribute('data-mops-unmatched')
1176
1279
  const hit = seqOfNodeKey(b.getAttribute('data-chat-node-key'), idx)
@@ -1188,9 +1291,40 @@ window.__ModuleLoader__.load({
1188
1291
  // 之前放在 fetch 回调里做事后全局扫描,会与 DOM 注入/重排竞态,导致
1189
1292
  // 块已打上 seq 而按钮仍是禁用态(实测:block seq=[8,54],按钮 disabled=true)。
1190
1293
  // 按钮可用性与 transcript 隐藏都在这里统一落地(同一批数据,避免竞态)
1294
+ //
1295
+ // 0.9.7(P2-1)三签名门控。scan **无条件**调 ensureAssign 是故意的
1296
+ // (早先做成「只在没打标时刷」→ 界面停在旧状态),所以门控只放在
1297
+ // assignSeqs 的全量 DOM 改写上,三者全等才跳过:
1298
+ // dataSig —— idx.total / shadowed.size / visibleTurns.size(数据变了必须重算)
1299
+ // domSig —— transcript 行数(行集合变了必须重算)
1300
+ // anchorSig —— 每个 user 块的 node-key + 打标状态(宿主重建块 / CHANGED
1301
+ // 摘牌后 node-key 相同但打标为空,靠这里发现)
1302
+ // 🔴 applySurfaceVisibility 仍然**无条件**执行,藏行判据与时机一字未改。
1303
+ var assignSig = null
1304
+ var anchorSigOf = (anchors) => {
1305
+ let s = ''
1306
+ for (let i = 0; i < anchors.length; i++) {
1307
+ const b = anchors[i]
1308
+ s += (b.getAttribute('data-chat-node-key') || '') + '=' +
1309
+ (b.getAttribute('data-mops-seq') || (b.hasAttribute('data-mops-unmatched') ? '?' : '-')) + ','
1310
+ }
1311
+ return s
1312
+ }
1313
+ var sigOf = (sid, dataSig, rowsLen, anchors) =>
1314
+ bareSessionId(sid) + '|' + dataSig + '|' + rowsLen + '|' + anchorSigOf(anchors)
1191
1315
  var ensureAssign = (sid) => fetchRows(sid).then((cache) => {
1192
- assignSeqs(sid, cache)
1193
- if (cache && cache.idx) applySurfaceVisibility(document, cache.idx)
1316
+ if (!cache || !cache.idx) return cache
1317
+ const idx = cache.idx
1318
+ const rows = document.querySelectorAll('[data-chat-node-key]')
1319
+ const dataSig = idx.total + '/' + idx.shadowed.size + '/' + idx.visibleTurns.size
1320
+ const anchors = userAnchors()
1321
+ const before = sigOf(sid, dataSig, rows.length, anchors)
1322
+ if (before !== assignSig) {
1323
+ assignSeqs(sid, cache, anchors)
1324
+ // 存**改写之后**的真实签名:下一次直接相等就跳过,不用跑两轮才收敛
1325
+ assignSig = sigOf(sid, dataSig, rows.length, anchors)
1326
+ }
1327
+ applySurfaceVisibility(rows, idx)
1194
1328
  return cache
1195
1329
  })
1196
1330
  // 0.7.0:点击时先**同步完成**配对(打标是异步 fetch 的结果,
@@ -1224,7 +1358,9 @@ window.__ModuleLoader__.load({
1224
1358
  try { data = await res.json() } catch { /* keep {} */ }
1225
1359
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
1226
1360
  notifyDone(__t('done.revert'))
1227
- try { window.dispatchEvent(new Event(CHANGED_EVENT)) } catch { /* non-browser */ }
1361
+ // 0.9.6:统一回填出口 —— 这个入口原先也不回填
1362
+ refillComposer(sid, row.seq)
1363
+ emitChanged()
1228
1364
  try {
1229
1365
  if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
1230
1366
  } catch { /* 视图重建失败不阻断 */ }
@@ -1261,13 +1397,38 @@ window.__ModuleLoader__.load({
1261
1397
  runUserRevert(btn, block)
1262
1398
  })
1263
1399
  host.appendChild(btn)
1400
+ // 0.9.7(P2-1):新按钮按块的**当前**打标状态立刻同步一次。
1401
+ // 门控之后 assignSeqs 可能被跳过(签名未变),靠这里保证「宿主重建了
1402
+ // 动作行 → 按钮重新挂上」这种情况仍然是 disabled/title 正确的。
1403
+ syncEnabled(block, btn)
1264
1404
  return btn
1265
1405
  }
1406
+ // 0.9.7(P0-2 读合并):把 150/700/1600ms 三档并成**一次**真网络请求,
1407
+ // 落点 = 本 burst 第一档 + 1500ms ≈ 原来的 1600ms 那一档。
1408
+ // 🔴 红线:这一档是「视图重建后重算隐藏」的兜底,绝不能砍成 0。
1409
+ // 调用当下立刻 rowsCache.at = 0 —— openSession 触发的那次 scan 因此能用
1410
+ // 共享窗口里的新鲜载荷先把隐藏刷对,不必等兜底那一发。
1411
+ var refreshTimer = null
1412
+ var refreshDeadline = 0
1266
1413
  __refreshSurface = (sid) => {
1267
1414
  const id = sid || __currentSessionId
1268
1415
  if (!id) return
1269
1416
  if (rowsCache) rowsCache.at = 0 // 强制重取权威数据
1270
- try { fetchRows(id).then((cache) => { if (cache && cache.idx) applySurfaceVisibility(document, cache.idx) }) } catch { /* noop */ }
1417
+ const now = Date.now()
1418
+ if (!refreshTimer) refreshDeadline = now + 1500
1419
+ clearTimeout(refreshTimer)
1420
+ refreshTimer = setTimeout(() => {
1421
+ refreshTimer = null
1422
+ try {
1423
+ // 会话已切走就别把旧会话的 idx 刷到新会话的 DOM 上
1424
+ if (bareSessionId(__currentSessionId) !== bareSessionId(id)) return
1425
+ invalidateMessagesMemo() // 兜底档必须是真网络,不许吃缓存
1426
+ if (rowsCache) rowsCache.at = 0
1427
+ fetchRows(id)
1428
+ .then((cache) => { if (cache && cache.idx) applySurfaceVisibility(document, cache.idx) })
1429
+ .catch(() => {})
1430
+ } catch { /* noop */ }
1431
+ }, Math.max(0, refreshDeadline - now))
1271
1432
  }
1272
1433
  var scan = () => {
1273
1434
  try {
@@ -1294,8 +1455,56 @@ window.__ModuleLoader__.load({
1294
1455
  }, { passive: true })
1295
1456
  window.addEventListener('scroll', scan, { passive: true })
1296
1457
  try {
1297
- var mo = new MutationObserver(() => { clearTimeout(scan._t); scan._t = setTimeout(scan, 200) })
1298
- mo.observe(document.body, { childList: true, subtree: true })
1458
+ // 0.9.7(P1-2)回调过滤 + maxWait。
1459
+ // ① 过滤:整个 document.body 的 childList 海量 mutation(流式文本、
1460
+ // chunk 重排)里,绝大多数与「打标 / 藏行」无关。只认本插件真正
1461
+ // 关心的四类节点。🔴 判据宁可**漏判放行**(多扫一次 ~0.4ms)也不可
1462
+ // 误杀 —— 漏了就是「遮蔽行不更新」。新增子树可能是祖先容器,
1463
+ // matches() 与 querySelector() 两者都试;过滤自身抛错一律放行。
1464
+ // ② 防抖 trailing 200ms + maxWait 1000ms:纯 trailing 在连续 mutation
1465
+ // 下会**无限推迟**,流式输出时新挂载的遮蔽行会长时间保持可见 ——
1466
+ // 这是正确性问题,不只是性能。
1467
+ // ③ attributeFilter 只盯 data-chat-node-key:本插件不写该属性(写的是
1468
+ // data-mops-seq / hidden),所以不会被自己触发成环。
1469
+ var MO_SEL = '[data-chat-node-key],[data-chat-flow-kind="user"],[class*="xzv4MW_actions"],[class*="_userRow"]'
1470
+ var scanPendingSince = 0
1471
+ var scheduleScan = () => {
1472
+ var now = Date.now()
1473
+ if (!scan._t) {
1474
+ scanPendingSince = now
1475
+ } else if (now - scanPendingSince >= 1000) {
1476
+ clearTimeout(scan._t)
1477
+ scan._t = null
1478
+ scanPendingSince = 0
1479
+ scan()
1480
+ return
1481
+ }
1482
+ clearTimeout(scan._t)
1483
+ scan._t = setTimeout(() => { scan._t = null; scanPendingSince = 0; scan() }, 200)
1484
+ }
1485
+ var mo = new MutationObserver((records) => {
1486
+ try {
1487
+ for (var i = 0; i < records.length; i++) {
1488
+ var rec = records[i]
1489
+ if (rec.type === 'attributes') {
1490
+ var tgt = rec.target
1491
+ if (tgt && tgt.nodeType === 1 && typeof tgt.matches === 'function' && tgt.matches(MO_SEL)) { scheduleScan(); return }
1492
+ continue
1493
+ }
1494
+ var added = rec.addedNodes
1495
+ for (var j = 0; j < added.length; j++) {
1496
+ var n = added[j]
1497
+ if (!n || n.nodeType !== 1) continue
1498
+ if ((typeof n.matches === 'function' && n.matches(MO_SEL))
1499
+ || (typeof n.querySelector === 'function' && n.querySelector(MO_SEL))) { scheduleScan(); return }
1500
+ }
1501
+ }
1502
+ } catch { scheduleScan() }
1503
+ })
1504
+ mo.observe(document.body, {
1505
+ childList: true, subtree: true,
1506
+ attributes: true, attributeFilter: ['data-chat-node-key'],
1507
+ })
1299
1508
  } catch { /* noop */ }
1300
1509
  window.addEventListener(CHANGED_EVENT, () => {
1301
1510
  try {
@@ -1456,14 +1665,56 @@ window.__ModuleLoader__.load({
1456
1665
  /** __currentSessionId 来自 DOM dataset,可能带 `session-` 前缀;API 只要裸 uuid。 */
1457
1666
  var bareSessionId = (id) => String(id || '').replace(/^session-/, '')
1458
1667
  /** 写盘成功后的统一收尾:通知、刷新、重放隐藏。 */
1459
- var afterWrite = (sid, okMsg) => {
1668
+ /**
1669
+ * 写盘成功后的统一收尾。
1670
+ *
1671
+ * ⚠️ `rawSid` 必须是**带 `session-` 前缀**的 id:`uiWorkspace.openSession`
1672
+ * 内部 `sessions.retain(bare)` 只认 `session-<uuid>`(manager.js resolveTarget),
1673
+ * 传裸 uuid 会抛 `unknown session <bare>` —— 而外层 `catch { }` 静默吞掉,
1674
+ * 结果「视图重建」这条路径**从来没生效过**,只剩 150/700/1600ms 的 DOM 打补丁。
1675
+ * 本文件其它调用点(对话框 :403、:684、:858、:1229)传的都是带前缀的,
1676
+ * 只有 /undo /redo 因为先 `bareSessionId` 而传错。
1677
+ */
1678
+ var afterWrite = (rawSid, okMsg) => {
1460
1679
  notifyDone(okMsg)
1461
- try { window.dispatchEvent(new Event(CHANGED_EVENT)) } catch { /* non-browser */ }
1680
+ // emitChanged = 作废消息读缓存 + 清 rowsCache TTL + 广播 CHANGED
1681
+ // (dock 重拉 / 已打标 seq 摘牌),一次写只做一次。
1682
+ emitChanged()
1462
1683
  try {
1463
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
1464
- } catch { /* 视图重建失败不阻断 */ }
1465
- if (__peekRowsCache) { const c = __peekRowsCache(); if (c) c.at = 0 }
1466
- for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(sid) }, delay)
1684
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(rawSid)
1685
+ } catch (e) {
1686
+ if (window.__MOPS_DEBUG) console.warn('[message-ops] openSession failed:', e)
1687
+ }
1688
+ const bare = bareSessionId(rawSid)
1689
+ for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(bare) }, delay)
1690
+ }
1691
+
1692
+ /**
1693
+ * 回填 composer(opencode 语义:回滚后把被删掉的那句原文还给输入框)。
1694
+ *
1695
+ * 0.9.6 统一出口 —— 此前「5 个入口只有 2 个回填」的事故史见 README「历史事故记录」#5。
1696
+ *
1697
+ * 取文本规则:rowsCache 里 seq <= boundary 的最后一条带 fullText 的行。
1698
+ * - /undo → boundary 就是被回滚的那条用户消息 → 取到它自己 ✓
1699
+ * - AI 时钟按钮 → boundary 是 AI 消息 seq → 取到它之前那条用户消息 ✓
1700
+ * 会话不匹配时直接放弃(不跨会话写,避免串台)。
1701
+ */
1702
+ var refillComposer = (rawSid, boundarySeq) => {
1703
+ try {
1704
+ const cache = __peekRowsCache ? __peekRowsCache() : null
1705
+ if (!cache || !Array.isArray(cache.rows)) return false
1706
+ const want = bareSessionId(rawSid)
1707
+ if (bareSessionId(cache.sid) !== want) return false
1708
+ const rows = cache.rows.filter((r) => r && typeof r.seq === 'number' && r.seq <= boundarySeq && r.fullText)
1709
+ if (!rows.length) return false
1710
+ if (!__inputActions || typeof __inputActions.setDraft !== 'function') return false
1711
+ __inputActions.setDraft(rows[rows.length - 1].fullText)
1712
+ return true
1713
+ } catch (e) {
1714
+ // 原来这里 `catch {}` 完全静默 —— 失败了连痕迹都没有,排查时看不到
1715
+ console.warn('[message-ops] setDraft failed:', e)
1716
+ return false
1717
+ }
1467
1718
  }
1468
1719
 
1469
1720
  /**
@@ -1472,8 +1723,9 @@ window.__ModuleLoader__.load({
1472
1723
  * 尾部但不在 surface 上,服务端会以 `surface replace: start seq N not found in surface` 拒绝。
1473
1724
  */
1474
1725
  var runUndo = () => {
1475
- const sid = bareSessionId(__currentSessionId)
1476
- if (!sid) return false
1726
+ const rawSid = __currentSessionId
1727
+ const sid = bareSessionId(rawSid)
1728
+ if (!sid) { notifyDone(__t('undo.none') || '没有可回滚的消息', 'error'); return false }
1477
1729
  const target = lastRevertable()
1478
1730
  if (!target) { notifyDone(__t('undo.none') || '没有可回滚的消息', 'error'); return false }
1479
1731
  fetch('/api/message-ops/revert', {
@@ -1483,11 +1735,8 @@ window.__ModuleLoader__.load({
1483
1735
  .then(async (res) => {
1484
1736
  const data = await res.json().catch(() => ({}))
1485
1737
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
1486
- afterWrite(sid, __t('undo.done.undo'))
1487
- // opencode 语义:回滚后**原文回输入框**,用户可改后重发
1488
- if (target.fullText && __inputActions && typeof __inputActions.setDraft === 'function') {
1489
- try { __inputActions.setDraft(target.fullText) } catch { /* 回填失败不阻断 */ }
1490
- }
1738
+ refillComposer(rawSid, target.seq) // 先回填,再重建视图(与对话框一致)
1739
+ afterWrite(rawSid, __t('undo.done.undo'))
1491
1740
  })
1492
1741
  .catch((reason) => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
1493
1742
  return true
@@ -1501,10 +1750,10 @@ window.__ModuleLoader__.load({
1501
1750
  * (dock 传的 row.seq 就来自 activeMarkers)。传消息 seq 会找不到 marker 空转。
1502
1751
  */
1503
1752
  var runRedo = () => {
1504
- const sid = bareSessionId(__currentSessionId)
1753
+ const rawSid = __currentSessionId
1754
+ const sid = bareSessionId(rawSid)
1505
1755
  if (!sid) return false
1506
- fetch('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
1507
- .then((r) => (r.ok ? r.json() : null))
1756
+ fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
1508
1757
  .then((d) => {
1509
1758
  if (!d || !d.ok) throw new Error((d && d.error) || 'messages unavailable')
1510
1759
  const markers = activeMarkers(d.messages || [])
@@ -1516,7 +1765,9 @@ window.__ModuleLoader__.load({
1516
1765
  }).then(async (res) => {
1517
1766
  const data = await res.json().catch(() => ({}))
1518
1767
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
1519
- afterWrite(sid, __t('undo.done.redo'))
1768
+ // afterWrite 契约:rawSid 必须带 session- 前缀(传裸 uuid 会抛
1769
+ // `sessions.retain: unknown session` 并被外层 catch 静默吞掉)
1770
+ afterWrite(rawSid, __t('undo.done.redo'))
1520
1771
  })
1521
1772
  })
1522
1773
  .catch((reason) => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))