@240xu/dsh-message-ops 0.9.2 → 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
@@ -553,3 +553,49 @@ marker 自身都不渲染(`systemMessageDefinition.buildViewNode` 对 `surface
553
553
  所以「恢复后再回滚」的复合场景下,重放副本的行可能不被识别为 user 行。
554
554
  - `restore` 后界面需要触发刷新才更新(已接 `__refreshSurface` 钩子 + MutationObserver,
555
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.2",
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
 
@@ -148,7 +155,11 @@ window.__ModuleLoader__.load({
148
155
  // 之前 restore 路径里直接调 scan(),但 scan 定义在注入器的闭包里,
149
156
  // dock 组件根本取不到 —— `typeof scan === 'function'` 静默跳过了,
150
157
  // 结果「恢复后消息回来了但仍被藏 / dock 计数不变」,必须重载页面才对。
151
- var __refreshSurface = null // 0.6.0:会话视图会话 id(RevertDock/MsgSlotActions 刷新)
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 刷新)
152
163
  // messageId→seq 索引缓存(每会话一次拉取;0.3.0 assistant-actions 槽用)
153
164
  var __seqIndexCache = new Map()
154
165
  // messageId→全文缓存(0.5.0 消息引用用)
@@ -932,6 +943,7 @@ window.__ModuleLoader__.load({
932
943
  if (window.__MOPS_USER_REVERT_INSTALLED) return
933
944
  window.__MOPS_USER_REVERT_INSTALLED = true
934
945
  var rowsCache = { sid: null, rows: null, at: 0 }
946
+ __peekRowsCache = () => rowsCache
935
947
  var norm = (x) => String(x || '').replace(/\s+/g, '')
936
948
  var fetchRows = (sid) => {
937
949
  if (rowsCache.sid === sid && rowsCache.rows && Date.now() - rowsCache.at < 8000) return Promise.resolve(rowsCache)
@@ -952,7 +964,7 @@ window.__ModuleLoader__.load({
952
964
  const injected = (raw) => /^<system-reminder|current\s+runtime\s+context|^<system-Reminder/i.test(String(raw || ''))
953
965
  const rows = ((d && d.messages) || [])
954
966
  .filter((m) => m && m.role === 'user')
955
- .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 }))
956
968
  .filter((r) => r.sn && !injected(r.raw))
957
969
  // 0.9.1:同时产出 node-key 查表索引(隐藏 transcript 用)
958
970
  const idx = buildIndex(d)
@@ -1093,9 +1105,15 @@ window.__ModuleLoader__.load({
1093
1105
  var hidden = 0, unresolved = 0, shown = 0;
1094
1106
  for (var i = 0; i < rows.length; i++) {
1095
1107
  var row = rows[i];
1096
- var seq = seqOfNodeKey(row.getAttribute('data-chat-node-key'), idx);
1097
- if (seq === null) { unresolved++; row.removeAttribute('hidden'); continue; }
1098
- var isReverted = idx.fences.length ? idx.fences.some(function (f) { return seq >= f; }) : idx.reverted.has(seq)
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); });
1099
1117
  if (isReverted) { hidden++; row.setAttribute('hidden', 'until-found'); }
1100
1118
  else { shown++; row.removeAttribute('hidden'); }
1101
1119
  }
@@ -1396,6 +1414,147 @@ window.__ModuleLoader__.load({
1396
1414
  } catch { /* namespace already registered: keep existing copy */ }
1397
1415
  }
1398
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
+
1399
1558
  function apply(ctx) {
1400
1559
  __sessionsSvc = ctx.get('sessions')
1401
1560
  __uiWorkspace = typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : null
@@ -1405,6 +1564,7 @@ window.__ModuleLoader__.load({
1405
1564
  if (!__sessionsSvc) {
1406
1565
  ctx.inject(['sessions'], (sub) => { __sessionsSvc = sub.sessions })
1407
1566
  }
1567
+ registerUndoSlash(ctx)
1408
1568
  adoptLocale(ctx.get('locale'), ctx)
1409
1569
  if (!__locale) {
1410
1570
  ctx.inject(['locale'], (sub) => {
@@ -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
+ })