@240xu/dsh-message-ops 0.11.2 → 0.11.4

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
@@ -89,16 +89,45 @@ dsh plugin --profile web add file:C:/path/to/dsh-message-ops
89
89
  | POST | `/api/message-ops/session/restore` | `{trashId}` 从回收站恢复目录与投影/工作区元数据 |
90
90
  | POST | `/api/message-ops/session/purge` | `{trashId}` 永久删除(唯一 destructive 操作) |
91
91
 
92
+ ### 0.11.4 · turn 游标对齐真正生效(会话损坏 P0 续)
93
+
94
+ - **`alignLiveTurnCursor` 此前从未执行**:插件 `export const inject = []`
95
+ (tools 是可选增强,故意不声明硬依赖),因此 `ctx.agents` **属性恒为 undefined**,
96
+ 旧实现只读属性 → 恒返回 false。合成 turn 占用编号后宿主 idle agent 的
97
+ `phase.lastTurn` 不推进,下一条真实消息复用同一 turn 号,日志落成
98
+ `turn/start does not open the expected turn`,整份会话不可加载。
99
+ 改为属性优先、`ctx.get("agents")` 兜底(与 `resolveSession` 同取法)。
100
+ - 回归测试:`ctx.agents` 缺失必须走 `ctx.get`;游标已领先时不得回退。
101
+
102
+ ### 0.11.3 · 区间编码、回填落盘与会话损坏修复
103
+
104
+ - **`sourceEventSeqs` 区间语义修正(数据正确性)**:宿主用 `encodeSeqRanges` 把连续
105
+ ≥3 个 seq 无损压缩成 `[start, end]` 闭区间,读盘时 `decodeSeqRanges` 再展开。
106
+ 0.11.2 的 `flat(Infinity)` 会把 `[[3, 6]]` 变成 `3, 6`,丢掉 4、5,写出的 marker
107
+ 被引擎判 `missing 4, 5`。改为 `expandSourceSeqs()` 按闭区间展开并保持首次出现顺序。
108
+ - **`postamble` 幂等(会话损坏 P0)**:旧实现成功路径与 catch 各写一次
109
+ `noticeWindowPostamble`;postamble/flush 自身抛错时 catch 再写一遍,落成
110
+ `step/end,turn/end,step/end,turn/end`,宿主读盘直接判
111
+ `step/end does not match an open turn and step`,整份会话变 corrupt。
112
+ 改为 `closeWindow()` 单点 + `closed` 标志。
113
+ - **composer 回填落盘(「回滚成功但输入框是空的」)**:宿主 `inputActions.setDraft()`
114
+ 只改编辑器、不写 `localStorage`;紧随其后的 `openSession()` 会用
115
+ `readConversationDraft()` 从旧草稿重读并覆盖。回填后补 `persistDraft()`。
116
+ 对话框入口同理。
117
+ - **`lastRevertable` 排除 `shadowed`**:只判 `visible` 时,回滚刚落盘、索引未刷新的
118
+ 窗口里会再次选中同一 seq → 409 `surface replace: start seq N not found in surface`。
119
+ `/undo` 成功后同时就地标记 `seq >= target` 行为 shadowed。
120
+
92
121
  ### 0.11.2 · 合成 turn 竞态与历史日志兼容修复
93
122
 
94
123
  - 修复回滚在 live 会话中可能产生**重复 turn**:`opsCommit` / `opsRestore` 在取得
95
124
  live session 后改用 `session.log` 重算 turn 窗口,不再信任可能已过期的磁盘快照。
96
125
  - 合成 turn 成功闭合后对齐宿主 idle agent 的 `lastTurn`,防止下一条真实消息复用同一 turn。
97
126
  - `planNoticeWindow` 遇到「turn 已开但 step 未开」直接 409,不再嵌套非法合成 turn。
98
- - `applySurfaceReplace` / `buildMarkerEvent` 对 `sourceEventSeqs` 做扁平化、去重和整数校验,
99
- 杜绝 `[[start,end]]` 旧伤继续写入。
100
- - 旧日志中已存在的嵌套 `sourceEventSeqs` 与 tool/result replacement 非 content 字段
101
- 需用维护脚本修复;本版本保证不再产生该类记录。
127
+ - `applySurfaceReplace` / `buildMarkerEvent` 对 `sourceEventSeqs` 去重和整数校验(0.11.3 起改为正确展开区间),
128
+ 区间成员不再丢失。
129
+ - 旧日志中的区间式 `sourceEventSeqs`(`[[start,end]]`)在 0.11.3 已确认是宿主合法编码,
130
+ 无需维护脚本;tool/result replacement 非 content 字段仍需按需修复。
102
131
  - 契约测试在无本地 `sessionfix` 夹具时自动跳过,不再硬依赖个人绝对路径。
103
132
 
104
133
  ### 0.11.0 · 方向 A 面板 + 会话回收站
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-message-ops",
3
- "version": "0.11.2",
3
+ "version": "0.11.4",
4
4
  "description": "DSH web 插件:消息级回滚 / 删除 / 恢复(补 dsh 官方没有的部分)。分支与导出用官方内置能力。",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/client.js CHANGED
@@ -559,9 +559,15 @@ window.__ModuleLoader__.load({
559
559
  // branch 在上面已 return,故 done.restore 分支在此不可达,一并删掉。
560
560
  const okMsg = mode === 'revert' ? t('done.revert') : t('done.delete')
561
561
  // 0.4.0 composer 回填(opencode 式):回滚用户消息 → 原文回填输入框,「编辑重发」零按钮
562
- if (mode === 'revert' && pickedMsg && pickedMsg.role === 'user' && pickedMsg.fullText
563
- && __inputActions && typeof __inputActions.setDraft === 'function') {
564
- try { __inputActions.setDraft(pickedMsg.fullText) } catch { /* 回填失败不阻断成功反馈 */ }
562
+ // 0.11.3:必须走统一出口,且要落盘 —— 直接 setDraft 会被随后的
563
+ // openSession 用 localStorage 里的旧草稿覆盖(见 refillComposer 注释)。
564
+ if (mode === 'revert' && pickedMsg && pickedMsg.role === 'user' && pickedMsg.fullText) {
565
+ try {
566
+ if (__inputActions && typeof __inputActions.setDraft === 'function') {
567
+ __inputActions.setDraft(pickedMsg.fullText)
568
+ if (typeof __inputActions.persistDraft === 'function') __inputActions.persistDraft()
569
+ }
570
+ } catch (e) { console.warn('[message-ops] refill failed:', e) }
565
571
  }
566
572
  setDoneMsg(okMsg)
567
573
  setBusyMsg('')
@@ -2820,7 +2826,10 @@ window.__ModuleLoader__.load({
2820
2826
  if (!cache || !Array.isArray(cache.rows)) return null
2821
2827
  for (var i = cache.rows.length - 1; i >= 0; i--) {
2822
2828
  var r = cache.rows[i]
2823
- if (r && r.seq != null && r.visible) return r
2829
+ // 0.11.3:必须同时排除 shadowed。只用 visible 会在「回滚刚落盘、索引还没刷新」
2830
+ // 的窗口里再次选中已被遮蔽的 seq → 服务端 409
2831
+ // `surface replace: start seq N not found in surface`(实测 2026-10-25)。
2832
+ if (r && r.seq != null && r.visible && r.shadowed !== true) return r
2824
2833
  }
2825
2834
  return null
2826
2835
  }
@@ -2858,6 +2867,15 @@ window.__ModuleLoader__.load({
2858
2867
  *
2859
2868
  * 0.9.6 统一出口 —— 此前「5 个入口只有 2 个回填」的事故史见 README「历史事故记录」#5。
2860
2869
  *
2870
+ * 0.11.3 修「回滚成功但输入框还是空的」:
2871
+ * 宿主 `inputActions.setDraft()` **只改编辑器,不落 localStorage**;
2872
+ * 只有 `persistDraft()`(→ 内部 persistCurrentDraft)才写
2873
+ * `dsh.conversation.<sessionId>`。而所有回滚入口紧接着都调
2874
+ * `openSession()` 重挂会话视图,挂载时 shell 会
2875
+ * `setDraft(readConversationDraft(sessionId))` —— 从 localStorage 重读。
2876
+ * 于是刚回填的文本被旧草稿(常见为空)覆盖回去,用户看到的就是空输入框。
2877
+ * 修法:回填后立刻 `persistDraft()` 落盘,让重建读到的就是同一份草稿。
2878
+ *
2861
2879
  * 取文本规则:rowsCache 里 seq <= boundary 的最后一条带 fullText 的行。
2862
2880
  * - /undo → boundary 就是被回滚的那条用户消息 → 取到它自己 ✓
2863
2881
  * - AI 时钟按钮 → boundary 是 AI 消息 seq → 取到它之前那条用户消息 ✓
@@ -2873,6 +2891,10 @@ window.__ModuleLoader__.load({
2873
2891
  if (!rows.length) return false
2874
2892
  if (!__inputActions || typeof __inputActions.setDraft !== 'function') return false
2875
2893
  __inputActions.setDraft(rows[rows.length - 1].fullText)
2894
+ // 关键:不落盘的话,紧随其后的 openSession 会从 localStorage 读回旧草稿。
2895
+ if (typeof __inputActions.persistDraft === 'function') {
2896
+ try { __inputActions.persistDraft() } catch (e) { console.warn('[message-ops] persistDraft failed:', e) }
2897
+ }
2876
2898
  return true
2877
2899
  } catch (e) {
2878
2900
  // 原来这里 `catch {}` 完全静默 —— 失败了连痕迹都没有,排查时看不到
@@ -2899,6 +2921,15 @@ window.__ModuleLoader__.load({
2899
2921
  .then(async (res) => {
2900
2922
  const data = await res.json().catch(() => ({}))
2901
2923
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
2924
+ // 0.11.3:立刻把本行标成已遮蔽,否则 afterWrite 的异步刷新窗里
2925
+ // 再点一次 /undo 仍会选中同一个 seq → 409。
2926
+ const rowsCache = __peekRowsCache ? __peekRowsCache() : null
2927
+ if (rowsCache && Array.isArray(rowsCache.rows)) {
2928
+ for (const r of rowsCache.rows) {
2929
+ if (r && typeof r.seq === 'number' && r.seq >= target.seq) r.shadowed = true
2930
+ }
2931
+ rowsCache.at = 0
2932
+ }
2902
2933
  refillComposer(rawSid, target.seq) // 先回填,再重建视图(与对话框一致)
2903
2934
  afterWrite(rawSid, __t('undo.done.undo'))
2904
2935
  })
package/src/index.js CHANGED
@@ -647,11 +647,26 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
647
647
  // turn(0.8.2 注释锁定的「后半操作被 409 锁拒」形态),随后原样抛出,
648
648
  // 由路由层按既有 OpsError 映射。append-only 引擎无「删除已落事件」能力,
649
649
  // 闭合孤儿窗口是最小且可被动校验的整理。
650
+ // 0.11.3 P0:postamble 只能写一次。
651
+ // 旧实现把 `for (const post of postamble) session.append(...)` 同时放在 try
652
+ // 成功路径和 catch 里;一旦**成功路径的 postamble 自身**抛错(引擎已接受
653
+ // step/end,第二个 turn/end 被拒 / flush 失败),catch 会再写一遍 →
654
+ // 日志落成 `step/end, turn/end, step/end, turn/end`。宿主读盘直接判
655
+ // `step/end does not match an open turn and step`,整份会话变 corrupt
656
+ // (实测 session-5b49db5b seq 806-809)。用 closed 标志保证闭环只发生一次。
657
+ let closed = false
658
+ const closeWindow = () => {
659
+ if (closed) return
660
+ closed = true
661
+ for (const post of noticeWindowPostamble(win)) {
662
+ try { session.append(post.kind, post.data) } catch { /* 引擎拒:维持原错误/继续 */ }
663
+ }
664
+ }
650
665
  try {
651
666
  for (const pre of noticeWindowPreamble(win)) session.append(pre.kind, pre.data);
652
667
  const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep);
653
- // 必须闭合:否则引擎内存里 turn 16 永远开着 → isRunning 恒真 → 后续操作全被 409
654
- for (const post of noticeWindowPostamble(win)) session.append(post.kind, post.data);
668
+ // 必须闭合:否则引擎内存里 turn 永远开着 → isRunning 恒真 → 后续操作全被 409
669
+ closeWindow()
655
670
  if (win.synthetic) alignLiveTurnCursor(targetCtx, session, win.turn);
656
671
  flushSessions(targetCtx, session);
657
672
  return {
@@ -661,10 +676,8 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
661
676
  eventSeq: event && event.seq != null ? event.seq : null,
662
677
  };
663
678
  } catch (err) {
664
- // 孤儿整理失败不再包一层也不会更糟(append 已失败态);原错误照抛。
665
- for (const post of noticeWindowPostamble(win)) {
666
- try { session.append(post.kind, post.data); } catch { /* postamble 被引擎拒:维持原错误上抛 */ }
667
- }
679
+ // 只补闭合**尚未发生**的窗口;已闭合过就绝不再写第二遍。
680
+ closeWindow()
668
681
  throw err;
669
682
  }
670
683
  } finally {
package/src/ops-core.js CHANGED
@@ -239,7 +239,15 @@ export function deriveTurnStep(events) {
239
239
  /** 合成 turn 落盘后,把宿主 idle agent 的 turn 游标对齐到该 turn(否则下一条真实消息会重号)。 */
240
240
  export function alignLiveTurnCursor(ctx, session, turn) {
241
241
  if (!Number.isSafeInteger(turn) || turn < 1 || !session || typeof session.id !== "string") return false;
242
- const agent = ctx && ctx.agents && typeof ctx.agents.get === "function" ? ctx.agents.get(session.id) : undefined;
242
+ // 0.11.4:插件 `inject` 故意留空(tools 是可选增强),因此 `ctx.agents`
243
+ // **属性访问恒为 undefined** —— 旧实现只写 `ctx.agents`,这条对齐从来没执行过。
244
+ // 实测 `ctx.get("agents")` 在 HTTP 请求期可解析(同 resolveSession 的取法),
245
+ // 故属性优先、ctx.get 兜底。
246
+ let agents = null;
247
+ try { if (ctx && ctx.agents) agents = ctx.agents; } catch { /* getter threw */ }
248
+ if (!agents) { try { agents = ctx && typeof ctx.get === "function" ? ctx.get("agents") : null; } catch { /* absent */ } }
249
+ let agent = null;
250
+ try { agent = agents && typeof agents.get === "function" ? agents.get(session.id) : null; } catch { /* registry miss */ }
243
251
  if (!agent || agent.phase?.kind !== "idle" || typeof agent.setPhase !== "function") return false;
244
252
  const lastTurn = Number.isSafeInteger(agent.phase.lastTurn) ? agent.phase.lastTurn : 0;
245
253
  if (lastTurn >= turn) return false;
@@ -300,11 +308,47 @@ export function noticeWindowPostamble(win) {
300
308
  ];
301
309
  }
302
310
 
311
+ /**
312
+ * 展开 `sourceEventSeqs` 的存储形态为宿主内存态整数序列。
313
+ *
314
+ * ⚠️ 宿主把**连续 ≥3 个** seq 无损压缩成 `[start, end]` 闭区间对
315
+ * (dsh-session/lib/index.js `encodeSeqRanges`,读盘 `decodeSeqRanges` 再展开)。
316
+ * 因此 `[[780, 782]]` 表示 **780、781、782 三个**节点,不是「两个端点」。
317
+ * 早期版本用 `flat(Infinity)` 处理 —— 会把 `[3, 6]` 变成 `3, 6`,
318
+ * 丢掉区间内的 4、5,写出的 marker 被引擎判 `sourceEventSeqs must include
319
+ * every shadowed surface node; missing 4, 5` 而 500/409。
320
+ *
321
+ * @param {unknown} value 存储形态(整数与/或 `[start, end]` 闭区间)
322
+ * @returns {number[]} 去重后保持首次出现顺序的整数序列
323
+ */
324
+ export function expandSourceSeqs(value) {
325
+ const out = [];
326
+ const seen = new Set();
327
+ const push = (seq) => {
328
+ if (!Number.isSafeInteger(seq)) throw new OpsError("surface replace sources must be integer seqs", 500);
329
+ if (seen.has(seq)) return;
330
+ seen.add(seq);
331
+ out.push(seq);
332
+ };
333
+ for (const entry of Array.isArray(value) ? value : []) {
334
+ if (Array.isArray(entry)) {
335
+ if (entry.length !== 2) throw new OpsError("surface replace source ranges must be [start, end] pairs", 500);
336
+ const [start, end] = entry;
337
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end < start) {
338
+ throw new OpsError("surface replace source ranges require integer start <= end", 500);
339
+ }
340
+ for (let seq = start; seq <= end; seq += 1) push(seq);
341
+ } else {
342
+ push(entry);
343
+ }
344
+ }
345
+ return out;
346
+ }
347
+
303
348
  export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs, noticeText, turnStep) {
304
349
  const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0
305
350
  ? turnStep : { turn: 1, step: 1 };
306
- const sources = [...new Set((Array.isArray(sourceEventSeqs) ? sourceEventSeqs : []).flat(Infinity))];
307
- if (!sources.every(Number.isSafeInteger)) throw new OpsError("surface replace sources must be integer seqs", 500);
351
+ const sources = expandSourceSeqs(sourceEventSeqs);
308
352
  const data = { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", source: messageSource("system", 4), content: [{ type: "text", text: noticeText }] } };
309
353
  if (replaceShape) {
310
354
  return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs: sources });
@@ -888,8 +932,7 @@ export function nextSeqFrom(events) {
888
932
 
889
933
  /** 磁盘回撤/删除标记事件(字段镜像引擎金标准:type/seq/time/data/sourceEventSeqs/surfaceOp)。 */
890
934
  export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs, version = 4 }) {
891
- const sources = [...new Set((Array.isArray(shadowedSeqs) ? shadowedSeqs : []).flat(Infinity))];
892
- if (!sources.every(Number.isSafeInteger)) throw new OpsError("surface replace sources must be integer seqs", 500);
935
+ const sources = expandSourceSeqs(shadowedSeqs);
893
936
  return {
894
937
  type: "system/message",
895
938
  seq,