@240xu/dsh-message-ops 0.12.0 → 0.13.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
@@ -6,7 +6,7 @@
6
6
  */
7
7
  window.__ModuleLoader__.load({
8
8
  id: '@240xu/dsh-message-ops',
9
- factory: (require) => {
9
+ factory: require => {
10
10
  const React = require('react')
11
11
  const { useCallback, useEffect, useRef, useState } = React
12
12
  const { Modal } = require('@deepseek-ai/dsh-client-ui-primitives')
@@ -29,31 +29,43 @@ window.__ModuleLoader__.load({
29
29
  // 否则「视图重建后重算隐藏」的 1600ms 兜底会被上一次响应吞掉。
30
30
  const MSG_COALESCE_MS = 1000
31
31
  var __messagesMemo = { url: null, at: 0, p: null, settled: false }
32
- var invalidateMessagesMemo = () => { __messagesMemo = { url: null, at: 0, p: null, settled: false } }
32
+ var invalidateMessagesMemo = () => {
33
+ __messagesMemo = { url: null, at: 0, p: null, settled: false }
34
+ }
33
35
  const SYNTHETIC_TURN_STYLE_ID = 'dsh-message-ops-synthetic-turn-hide'
34
- const syncSyntheticTurnStyle = (messages) => {
36
+ const syncSyntheticTurnStyle = messages => {
35
37
  if (typeof document === 'undefined' || !document.head) return
36
38
  const turns = new Set()
37
39
  for (const m of messages || []) {
38
40
  if (m && m.syntheticTurn === true && Number.isSafeInteger(m.turn)) turns.add(m.turn)
39
41
  }
40
42
  let tag = document.getElementById(SYNTHETIC_TURN_STYLE_ID)
41
- if (turns.size === 0) { if (tag) tag.remove(); return }
43
+ if (turns.size === 0) {
44
+ if (tag) tag.remove()
45
+ return
46
+ }
42
47
  if (!tag) {
43
48
  tag = document.createElement('style')
44
49
  tag.id = SYNTHETIC_TURN_STYLE_ID
45
50
  document.head.appendChild(tag)
46
51
  }
47
- tag.textContent = Array.from(turns).map((turn) =>
48
- '[data-chat-flow-kind="turn-process"][data-chat-turn="' + turn + '"]{display:none!important}'
49
- ).join('\n')
52
+ tag.textContent = Array.from(turns)
53
+ .map(turn => '[data-chat-flow-kind="turn-process"][data-chat-turn="' + turn + '"]{display:none!important}')
54
+ .join('\n')
50
55
  }
51
56
  const emitChanged = () => {
52
57
  // 数据变了:连同本地缓存一起作废(否则 8s TTL 会让 openSession 后的
53
58
  // scan 拿旧 payload 重算隐藏 = 「回滚了但界面没变」)。
54
59
  invalidateMessagesMemo()
55
- if (__peekRowsCache) { const c = __peekRowsCache(); if (c) c.at = 0 }
56
- try { window.dispatchEvent(new CustomEvent(CHANGED_EVENT)) } catch { /* noop */ }
60
+ if (__peekRowsCache) {
61
+ const c = __peekRowsCache()
62
+ if (c) c.at = 0
63
+ }
64
+ try {
65
+ window.dispatchEvent(new CustomEvent(CHANGED_EVENT))
66
+ } catch {
67
+ /* noop */
68
+ }
57
69
  }
58
70
  const NS = 'dsh-message-ops'
59
71
 
@@ -64,7 +76,7 @@ window.__ModuleLoader__.load({
64
76
  * - 只在 `ok:true` 时才留窗口:失败/非 2xx 立刻作废,免得把后续重试也吃掉;
65
77
  * - 1600ms 那档兜底刷新由调用方先 `invalidateMessagesMemo()` 再拉,保证是真网络。
66
78
  */
67
- var fetchMessagesJson = (rawUrl) => {
79
+ var fetchMessagesJson = rawUrl => {
68
80
  // 归一 sessionId 写法:本文件有的调用方传 `session-xxx`(dock / 对话框),
69
81
  // 有的传裸 uuid(fetchRows / /redo)。不归一就是两个缓存槽,合并直接失效。
70
82
  // 服务端两种写法都认(index.js "uuid or session-<uuid> form")。
@@ -73,14 +85,22 @@ window.__ModuleLoader__.load({
73
85
  if (m.url === url && m.p && (!m.settled || Date.now() - m.at < MSG_COALESCE_MS)) return m.p
74
86
  const entry = { url, at: Date.now(), p: null, settled: false }
75
87
  entry.p = fetch(url)
76
- .then((r) => r.json().catch(() => null).then((d) => ({ r, d })))
88
+ .then(r =>
89
+ r
90
+ .json()
91
+ .catch(() => null)
92
+ .then(d => ({ r, d })),
93
+ )
77
94
  .then(({ r, d }) => {
78
- if (!r.ok || !d || d.ok !== true) throw new Error((d && d.error) || ('HTTP ' + r.status))
95
+ if (!r.ok || !d || d.ok !== true) throw new Error((d && d.error) || 'HTTP ' + r.status)
79
96
  entry.settled = true
80
97
  entry.at = Date.now()
81
98
  return d
82
99
  })
83
- .catch((e) => { if (__messagesMemo === entry) invalidateMessagesMemo(); throw e })
100
+ .catch(e => {
101
+ if (__messagesMemo === entry) invalidateMessagesMemo()
102
+ throw e
103
+ })
84
104
  __messagesMemo = entry
85
105
  return entry.p
86
106
  }
@@ -109,8 +129,8 @@ window.__ModuleLoader__.load({
109
129
  'op.revertDesc': '遮蔽所选消息及其后所有可见内容;日志 append-only,可通过重新发送恢复语境。',
110
130
  'op.delete': '仅删除这一条',
111
131
  'op.deleteDesc': '仅遮蔽所选的一条消息;其余内容保持不变。',
112
- 'op.branch': '从此条分支为新会话',
113
- 'op.branchDesc': '复制所选消息(含)之前的全部事件为新会话(原会话不变,非破坏操作)。',
132
+ 'op.branch': '从此条分叉为新会话',
133
+ 'op.branchDesc': '把此条之前的对话复制到新会话,并把此条原文放回新会话输入框(原会话不变,非破坏操作)。',
114
134
  'slot.revert': '回滚到此条',
115
135
  'slot.revertUnmatched': '在日志里定位不到这条消息的 seq(通常是模型写的摘要与渲染文本偏差过大)——请改用「消息操作」对话框。',
116
136
  'slot.fork': '从此条分叉',
@@ -132,7 +152,7 @@ window.__ModuleLoader__.load({
132
152
  'done.revert': '回滚完成,刷新页面后生效',
133
153
  'done.delete': '删除完成,刷新页面后生效',
134
154
  'action.reload': '刷新页面',
135
- 'errorPrefix': '操作失败:',
155
+ errorPrefix: '操作失败:',
136
156
  'dock.title': '已回撤 {n} 条消息',
137
157
  'dock.expand': '展开回撤列表',
138
158
  'dock.collapse': '折叠回撤列表',
@@ -192,6 +212,7 @@ window.__ModuleLoader__.load({
192
212
  'panel.editDone': '原文已放回输入框',
193
213
  'panel.editEmpty': '这条消息没有可编辑的文本',
194
214
  'panel.editUnavailable': '编辑器不可写(会话可能正在运行或尚未挂载)',
215
+ 'panel.editNotReady': '全文尚未就绪(列表只带 160 字摘要)——请重试或改用回滚回填',
195
216
  'panel.openNew': '打开新会话',
196
217
  'panel.revertDone': '回滚已生效',
197
218
  'panel.deleteDone': '删除已生效',
@@ -230,20 +251,24 @@ window.__ModuleLoader__.load({
230
251
  'dialog.showMore': 'Show more ({n} older)',
231
252
  'dialog.more': '…(showing latest 200 of {n})',
232
253
  'op.revert': 'Revert: remove this message and everything after',
233
- 'op.revertDesc': 'Shadows the picked message and all later visible content; the log stays append-only so context can be restored by re-sending.',
254
+ 'op.revertDesc':
255
+ 'Shadows the picked message and all later visible content; the log stays append-only so context can be restored by re-sending.',
234
256
  'op.delete': 'Delete only this message',
235
257
  'op.deleteDesc': 'Shadows only the picked message; everything else stays.',
236
- 'op.branch': 'Branch into a new session from here',
237
- 'op.branchDesc': 'Copies everything up to and including the picked message into a new session (original untouched, non-destructive).',
258
+ 'op.branch': 'Fork into a new session from here',
259
+ 'op.branchDesc':
260
+ 'Copies the conversation above the picked message into a new session and puts this message back in the new composer (original untouched, non-destructive).',
238
261
  'slot.revert': 'Revert to here',
239
- '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.',
262
+ 'slot.revertUnmatched':
263
+ '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.',
240
264
  'slot.fork': 'Branch from here',
241
265
  'slot.forkHint': 'Copies the conversation above this message into a new session and puts this message back in the new composer',
242
266
  'slot.forkDone': 'Branched: new session {id}',
243
267
  'slot.forkUnavailable': 'Branch unavailable: the session is running, or the host provides no session/fork',
244
268
  'toast.openNew': 'Open new session',
245
269
  'fork.official': 'Branched (official fork): new session {id}',
246
- '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.',
270
+ 'fork.unavailable':
271
+ 'Built-in branch unavailable — usually because the session is running. Stop it and retry. Branching is provided by the dsh built-in session/fork.',
247
272
  'ack.revert': 'I understand: revert shadows the picked message and everything after it',
248
273
  'ack.delete': 'I understand: this message will be shadowed (kept in the log)',
249
274
  'confirm.revert': 'Revert',
@@ -256,7 +281,7 @@ window.__ModuleLoader__.load({
256
281
  'done.revert': 'Reverted; reload to apply',
257
282
  'done.delete': 'Deleted; reload to apply',
258
283
  'action.reload': 'Reload page',
259
- 'errorPrefix': 'Operation failed: ',
284
+ errorPrefix: 'Operation failed: ',
260
285
  'dock.title': '{n} rolled back messages',
261
286
  'dock.expand': 'Expand revert list',
262
287
  'dock.collapse': 'Collapse revert list',
@@ -296,7 +321,8 @@ window.__ModuleLoader__.load({
296
321
  'panel.revert': 'Revert to here',
297
322
  'panel.revertHint': 'Includes this message and all visible messages after it',
298
323
  'panel.revertConfirmTitle': 'Revert to #{seq}?',
299
- 'panel.revertConfirmBody': 'This shadows {n} messages (#{start}–#{end}), including {v} visible. The log stays append-only and can be restored.',
324
+ 'panel.revertConfirmBody':
325
+ 'This shadows {n} messages (#{start}–#{end}), including {v} visible. The log stays append-only and can be restored.',
300
326
  'panel.deleteConfirmTitle': 'Delete only #{seq}?',
301
327
  'panel.deleteConfirmBody': 'This shadows this one message; everything else stays. The log stays append-only and can be restored.',
302
328
  'panel.confirmRevert': 'Confirm revert',
@@ -316,6 +342,7 @@ window.__ModuleLoader__.load({
316
342
  'panel.editDone': 'Original text is back in the composer',
317
343
  'panel.editEmpty': 'This message has no editable text',
318
344
  'panel.editUnavailable': 'Composer is not writable (session may be running or not mounted)',
345
+ 'panel.editNotReady': 'Full text is not ready (the list only carries a 160-char snippet) — retry, or use revert to refill',
319
346
  'panel.openNew': 'Open new session',
320
347
  'panel.revertDone': 'Revert applied',
321
348
  'panel.deleteDone': 'Delete applied',
@@ -351,7 +378,7 @@ window.__ModuleLoader__.load({
351
378
  // 0.9.3:注入器闭包内 rowsCache 的只读出口。
352
379
  // rowsCache 声明在 installUserRevertInjector() 内(闭包私有),而 /undo 的
353
380
  // onPick 在模块级作用域 —— 直接引用会 ReferenceError,表现为点菜单毫无反应。
354
- var __peekRowsCache = null // 0.6.0:会话视图会话 id(RevertDock/MsgSlotActions 刷新)
381
+ var __peekRowsCache = null // 0.6.0:会话视图会话 id(RevertDock/MsgSlotActions 刷新)
355
382
  // messageId→seq 索引缓存(每会话一次拉取;0.3.0 assistant-actions 槽用)
356
383
  var __seqIndexCache = new Map()
357
384
  // messageId→全文缓存(0.5.0 消息引用用)
@@ -360,7 +387,9 @@ window.__ModuleLoader__.load({
360
387
  function localeFallbackLang() {
361
388
  if (typeof navigator === 'undefined') return 'zh'
362
389
  for (const tag of (navigator.languages || []).concat([navigator.language])) {
363
- const primary = String(tag || '').toLowerCase().split('-')[0]
390
+ const primary = String(tag || '')
391
+ .toLowerCase()
392
+ .split('-')[0]
364
393
  if (primary === 'zh' || primary === 'en') return primary
365
394
  }
366
395
  return 'zh'
@@ -383,65 +412,110 @@ window.__ModuleLoader__.load({
383
412
  const [, setRev] = useState(0)
384
413
  useEffect(() => {
385
414
  if (!__locale || typeof __locale.subscribe !== 'function') return undefined
386
- return __locale.subscribe(() => setRev((v) => v + 1))
415
+ return __locale.subscribe(() => setRev(v => v + 1))
387
416
  }, [])
388
417
  }
389
418
 
390
419
  // --- styles(仅 --dsw-* 主题令牌) ----------------------------------------
391
420
  const btnStyle = {
392
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
393
- width: 28, height: 28, padding: 0, border: 'none', borderRadius: 6,
421
+ display: 'inline-flex',
422
+ alignItems: 'center',
423
+ justifyContent: 'center',
424
+ width: 28,
425
+ height: 28,
426
+ padding: 0,
427
+ border: 'none',
428
+ borderRadius: 6,
394
429
  background: 'transparent',
395
- color: 'var(--dsw-alias-label-tertiary, #8a8a8e)', cursor: 'pointer', flex: 'none',
430
+ color: 'var(--dsw-alias-label-tertiary, #8a8a8e)',
431
+ cursor: 'pointer',
432
+ flex: 'none',
396
433
  }
397
434
  const metaStyle = {
398
- color: 'var(--dsw-alias-label-secondary, #8a8a8e)', fontSize: 13,
399
- lineHeight: '20px', margin: '0 0 8px', overflow: 'hidden', textOverflow: 'ellipsis',
435
+ color: 'var(--dsw-alias-label-secondary, #8a8a8e)',
436
+ fontSize: 13,
437
+ lineHeight: '20px',
438
+ margin: '0 0 8px',
439
+ overflow: 'hidden',
440
+ textOverflow: 'ellipsis',
400
441
  }
401
442
  const warnStyle = {
402
- color: 'var(--dsw-alias-state-warn-primary, #f5a524)', fontSize: 13,
403
- lineHeight: '20px', margin: '0 0 10px',
443
+ color: 'var(--dsw-alias-state-warn-primary, #f5a524)',
444
+ fontSize: 13,
445
+ lineHeight: '20px',
446
+ margin: '0 0 10px',
404
447
  }
405
448
  const errStyle = {
406
- color: 'var(--dsw-alias-state-error-primary, #e5484d)', fontSize: 12,
407
- lineHeight: '16px', marginTop: 8,
449
+ color: 'var(--dsw-alias-state-error-primary, #e5484d)',
450
+ fontSize: 12,
451
+ lineHeight: '16px',
452
+ marginTop: 8,
408
453
  }
409
454
  const statusStyle = {
410
- color: 'var(--dsw-alias-label-secondary, #8a8a8e)', fontSize: 12,
411
- lineHeight: '16px', marginTop: 8,
455
+ color: 'var(--dsw-alias-label-secondary, #8a8a8e)',
456
+ fontSize: 12,
457
+ lineHeight: '16px',
458
+ marginTop: 8,
412
459
  }
413
460
  const listStyle = {
414
- maxHeight: 260, overflowY: 'auto', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35))',
415
- borderRadius: 8, margin: '8px 0 4px', padding: '4px 0',
461
+ maxHeight: 260,
462
+ overflowY: 'auto',
463
+ border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35))',
464
+ borderRadius: 8,
465
+ margin: '8px 0 4px',
466
+ padding: '4px 0',
416
467
  }
417
468
  const rowStyle = {
418
- display: 'flex', alignItems: 'flex-start', gap: 8,
419
- padding: '4px 10px', fontSize: 13, lineHeight: '18px', cursor: 'pointer',
469
+ display: 'flex',
470
+ alignItems: 'flex-start',
471
+ gap: 8,
472
+ padding: '4px 10px',
473
+ fontSize: 13,
474
+ lineHeight: '18px',
475
+ cursor: 'pointer',
420
476
  }
421
477
  const descStyle = {
422
- color: 'var(--dsw-alias-label-secondary, #8a8a8e)', fontSize: 12,
423
- lineHeight: '17px', margin: '6px 0 0',
478
+ color: 'var(--dsw-alias-label-secondary, #8a8a8e)',
479
+ fontSize: 12,
480
+ lineHeight: '17px',
481
+ margin: '6px 0 0',
424
482
  }
425
483
  const cancelBtnStyle = {
426
- padding: '6px 14px', borderRadius: 8,
484
+ padding: '6px 14px',
485
+ borderRadius: 8,
427
486
  border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.4))',
428
- background: 'transparent', color: 'var(--dsw-alias-label-primary, inherit)',
429
- fontSize: 13, cursor: 'pointer', marginRight: 8,
487
+ background: 'transparent',
488
+ color: 'var(--dsw-alias-label-primary, inherit)',
489
+ fontSize: 13,
490
+ cursor: 'pointer',
491
+ marginRight: 8,
430
492
  }
431
493
  const primaryBtnStyle = {
432
- padding: '6px 14px', borderRadius: 8, border: 'none',
433
- background: 'var(--dsw-alias-brand-primary, #4d6bfe)', color: '#fff',
434
- fontSize: 13, cursor: 'pointer',
494
+ padding: '6px 14px',
495
+ borderRadius: 8,
496
+ border: 'none',
497
+ background: 'var(--dsw-alias-brand-primary, #4d6bfe)',
498
+ color: '#fff',
499
+ fontSize: 13,
500
+ cursor: 'pointer',
435
501
  }
436
502
  const dangerBtnStyle = {
437
- padding: '6px 14px', borderRadius: 8,
503
+ padding: '6px 14px',
504
+ borderRadius: 8,
438
505
  border: '1px solid var(--dsw-alias-state-error-primary, #e5484d)',
439
506
  background: 'var(--dsw-alias-state-error-primary, #e5484d)',
440
- color: '#fff', fontSize: 13, cursor: 'pointer',
507
+ color: '#fff',
508
+ fontSize: 13,
509
+ cursor: 'pointer',
441
510
  }
442
511
  const optStyle = {
443
- display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, lineHeight: '20px',
444
- color: 'var(--dsw-alias-label-primary, inherit)', marginTop: 10,
512
+ display: 'flex',
513
+ alignItems: 'center',
514
+ gap: 8,
515
+ fontSize: 13,
516
+ lineHeight: '20px',
517
+ color: 'var(--dsw-alias-label-primary, inherit)',
518
+ marginTop: 10,
445
519
  }
446
520
 
447
521
  // 头部按钮图标:三叉分支(git-branch 风格,16x16)。
@@ -451,47 +525,68 @@ window.__ModuleLoader__.load({
451
525
  // 「那个 svg 渲染有问题」)。必须 stroke + round cap/join。
452
526
  // 唯一数据源:所有图标入口(React 组件 / innerHTML 字符串)都从这里取,
453
527
  // 以免再次出现「一处改名、另一处仍用旧名 → d="undefined"」的回归。
454
- const BRANCH_PATH = 'M5 2.5a2 2 0 1 1-.9 3.78v3.44a2 2 0 1 1-1.2 0V6.28A2 2 0 1 1 5 2.5Zm0 1.2a.8.8 0 1 0 0 1.6.8.8 0 0 0 0-1.6ZM3.5 11.5a.8.8 0 1 0 1.6 0 .8.8 0 0 0-1.6 0ZM12.5 2.5a2 2 0 0 1 .6 3.9v.85c0 1.9-1.54 3.44-3.44 3.44H8.03a2 2 0 1 1 0-1.2h1.63a2.24 2.24 0 0 0 2.24-2.24V6.4a2 2 0 0 1 .6-3.9Zm0 1.2a.8.8 0 1 0 0 1.6.8.8 0 0 0 0-1.6Z'
528
+ const BRANCH_PATH =
529
+ 'M5 2.5a2 2 0 1 1-.9 3.78v3.44a2 2 0 1 1-1.2 0V6.28A2 2 0 1 1 5 2.5Zm0 1.2a.8.8 0 1 0 0 1.6.8.8 0 0 0 0-1.6ZM3.5 11.5a.8.8 0 1 0 1.6 0 .8.8 0 0 0-1.6 0ZM12.5 2.5a2 2 0 0 1 .6 3.9v.85c0 1.9-1.54 3.44-3.44 3.44H8.03a2 2 0 1 1 0-1.2h1.63a2.24 2.24 0 0 0 2.24-2.24V6.4a2 2 0 0 1 .6-3.9Zm0 1.2a.8.8 0 1 0 0 1.6.8.8 0 0 0 0-1.6Z'
455
530
  const BRANCH_STROKE = 1.4
456
531
 
457
532
  /** 生成分支图标的 SVG 标记(供 innerHTML 场景复用)。 */
458
533
  function branchIconMarkup(size) {
459
534
  const px = size || 16
460
- return '<svg width="' + px + '" height="' + px + '" viewBox="0 0 16 16" fill="none"'
461
- + ' xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"'
462
- + ' style="flex:none"><path d="' + BRANCH_PATH + '" fill="none"'
463
- + ' stroke="currentColor" stroke-width="' + BRANCH_STROKE + '"'
464
- + ' stroke-linecap="round" stroke-linejoin="round"/></svg>'
535
+ return (
536
+ '<svg width="' +
537
+ px +
538
+ '" height="' +
539
+ px +
540
+ '" viewBox="0 0 16 16" fill="none"' +
541
+ ' xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"' +
542
+ ' style="flex:none"><path d="' +
543
+ BRANCH_PATH +
544
+ '" fill="none"' +
545
+ ' stroke="currentColor" stroke-width="' +
546
+ BRANCH_STROKE +
547
+ '"' +
548
+ ' stroke-linecap="round" stroke-linejoin="round"/></svg>'
549
+ )
465
550
  }
466
551
 
467
552
  function BranchIcon() {
468
- return React.createElement('svg', {
469
- width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none',
470
- xmlns: 'http://www.w3.org/2000/svg',
471
- 'aria-hidden': 'true', focusable: 'false',
472
- }, React.createElement('path', {
473
- d: BRANCH_PATH,
474
- stroke: 'currentColor', strokeWidth: BRANCH_STROKE,
475
- strokeLinecap: 'round', strokeLinejoin: 'round',
476
- fill: 'none',
477
- }))
553
+ return React.createElement(
554
+ 'svg',
555
+ {
556
+ width: 16,
557
+ height: 16,
558
+ viewBox: '0 0 16 16',
559
+ fill: 'none',
560
+ xmlns: 'http://www.w3.org/2000/svg',
561
+ 'aria-hidden': 'true',
562
+ focusable: 'false',
563
+ },
564
+ React.createElement('path', {
565
+ d: BRANCH_PATH,
566
+ stroke: 'currentColor',
567
+ strokeWidth: BRANCH_STROKE,
568
+ strokeLinecap: 'round',
569
+ strokeLinejoin: 'round',
570
+ fill: 'none',
571
+ }),
572
+ )
478
573
  }
479
574
 
480
575
  // --- 共享对话框 -------------------------------------------------------------
481
576
  // 模块级缓存最近一次 target,事件驱动打开。
482
577
  const MAX_RENDER = 200
483
- const PAGE_SIZE = 50 // 低成本分批渲染:先渲 50 条,按钮渐进展开
578
+ const PAGE_SIZE = 50 // 低成本分批渲染:先渲 50 条,按钮渐进展开
484
579
 
485
580
  function OpsDialog(props) {
486
581
  const t = (props && props.t) || __t
487
582
  useLocaleRevision()
488
- const [target, setTarget] = useState(null) // {sessionId, title, running}
489
- const [state, setState] = useState('idle') // idle|loading|ready|busy|done
583
+ const [target, setTarget] = useState(null) // {sessionId, title, running}
584
+ const [state, setState] = useState('idle') // idle|loading|ready|busy|done
490
585
  const [messages, setMessages] = useState([])
491
586
  const [sessionMeta, setSessionMeta] = useState(null)
492
- const [picked, setPicked] = useState(null) // seq
493
- const [mode, setMode] = useState(null) // revert|delete|branch|restore
494
- const [childId, setChildId] = useState(null) // 官方 fork 成功后的子会话 id
587
+ const [picked, setPicked] = useState(null) // seq
588
+ const [mode, setMode] = useState(null) // revert|delete|branch|restore
589
+ const [childId, setChildId] = useState(null) // 官方 fork 成功后的子会话 id
495
590
  const [acknowledged, setAcknowledged] = useState(false)
496
591
  const [busyMsg, setBusyMsg] = useState('')
497
592
  const [renderLimit, setRenderLimit] = useState(PAGE_SIZE) // 已展开的渲染条数
@@ -499,15 +594,18 @@ window.__ModuleLoader__.load({
499
594
  const [error, setError] = useState(null)
500
595
 
501
596
  useEffect(() => {
502
- const handler = (e) => {
597
+ const handler = e => {
503
598
  const d = e && e.detail ? e.detail : {}
504
599
  setTarget({ sessionId: d.sessionId || null, title: d.title || null, running: d.running === true })
505
600
  setState('loading')
506
- setMessages([]); setSessionMeta(null)
601
+ setMessages([])
602
+ setSessionMeta(null)
507
603
  // 槽按钮预置:携带 seq(picked)与 mode 直接进入确认态
508
604
  setPicked(typeof d.seq === 'number' ? d.seq : null)
509
605
  setMode(typeof d.mode === 'string' ? d.mode : null)
510
- setAcknowledged(false); setError(null); setDoneMsg('')
606
+ setAcknowledged(false)
607
+ setError(null)
608
+ setDoneMsg('')
511
609
  setRenderLimit(PAGE_SIZE)
512
610
  }
513
611
  window.addEventListener(EVENT, handler)
@@ -518,48 +616,62 @@ window.__ModuleLoader__.load({
518
616
  if (state !== 'loading' || !target || !target.sessionId) return
519
617
  let cancelled = false
520
618
  fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(target.sessionId))
521
- .then((data) => {
619
+ .then(data => {
522
620
  if (cancelled) return
523
621
  if (!data || !data.ok) throw new Error(data && data.error ? data.error : `HTTP ${data && data.status}`)
524
622
  setMessages(data.messages || [])
525
623
  setSessionMeta(data.session || null)
526
- if (data.running === true) setTarget((prev) => ({ ...(prev || {}), running: true }))
624
+ if (data.running === true) setTarget(prev => ({ ...(prev || {}), running: true }))
527
625
  setState('ready')
528
626
  })
529
- .catch((reason) => {
627
+ .catch(reason => {
530
628
  if (cancelled) return
531
629
  setError(t('dialog.loadFail') + (reason && reason.message ? reason.message : String(reason)))
532
630
  setState('ready')
533
631
  })
534
- return () => { cancelled = true }
632
+ return () => {
633
+ cancelled = true
634
+ }
535
635
  }, [state, target, t])
536
636
 
537
637
  const close = useCallback(() => {
538
638
  if (state === 'busy') return
539
- setTarget(null); setError(null)
639
+ setTarget(null)
640
+ setError(null)
540
641
  }, [state])
541
642
 
542
- const pick = useCallback((m) => {
543
- if (state === 'busy') return
544
- setPicked(m.seq)
545
- setMode(null); setAcknowledged(false); setError(null)
546
- }, [state])
643
+ const pick = useCallback(
644
+ m => {
645
+ if (state === 'busy') return
646
+ setPicked(m.seq)
647
+ setMode(null)
648
+ setAcknowledged(false)
649
+ setError(null)
650
+ },
651
+ [state],
652
+ )
547
653
 
548
- const chooseMode = useCallback((m) => {
549
- if (picked == null || state === 'busy') return
550
- setMode(m); setAcknowledged(false); setError(null)
551
- }, [picked, state])
654
+ const chooseMode = useCallback(
655
+ m => {
656
+ if (picked == null || state === 'busy') return
657
+ setMode(m)
658
+ setAcknowledged(false)
659
+ setError(null)
660
+ },
661
+ [picked, state],
662
+ )
552
663
 
553
664
  const run = useCallback(() => {
554
665
  if (state === 'busy' || picked == null || !mode) return
555
666
  if (mode !== 'branch' && !acknowledged) return
556
667
  setBusyMsg(t('busy.' + (mode === 'revert' || mode === 'delete' ? mode : 'branch')))
557
- setState('busy'); setError(null)
668
+ setState('busy')
669
+ setError(null)
558
670
  if (mode === 'branch') {
559
671
  // 0.12.0:与面板/消息行同一实现 —— opencode 的 before 语义
560
672
  // (新会话不含此条,原文回新会话输入框)。只对用户消息成立;
561
673
  // 分支不再回落写盘(被删的磁盘 applyBranch 语义复盘见 README)。
562
- const pickedRow = picked != null ? messages.find((m) => m.seq === picked) : null
674
+ const pickedRow = picked != null ? messages.find(m => m.seq === picked) : null
563
675
  if (!pickedRow || pickedRow.role !== 'user') {
564
676
  setError(t('panel.branchUserOnly'))
565
677
  setBusyMsg('')
@@ -567,15 +679,17 @@ window.__ModuleLoader__.load({
567
679
  return
568
680
  }
569
681
  Promise.resolve()
570
- .then(() => forkFromUserMessage(target.sessionId, picked, pickedRow.fullText || pickedRow.snippet || '', pickedRow.turnStartSeq))
571
- .then((childId) => {
682
+ .then(() =>
683
+ forkFromUserMessage(target.sessionId, picked, pickedRow.fullText || pickedRow.snippet || '', pickedRow.turnStartSeq),
684
+ )
685
+ .then(childId => {
572
686
  setDoneMsg(t('fork.official', { id: String(childId || '') }))
573
687
  setBusyMsg('')
574
688
  setChildId(childId || null)
575
689
  setState('done')
576
690
  notifyDone(t('fork.official', { id: String(childId || '') }))
577
691
  })
578
- .catch((reason) => {
692
+ .catch(reason => {
579
693
  setError(String((reason && reason.message) || reason || t('fork.unavailable')))
580
694
  setBusyMsg('')
581
695
  setState('error')
@@ -585,14 +699,20 @@ window.__ModuleLoader__.load({
585
699
  const path = mode
586
700
  const body = { sessionId: target.sessionId, seq: picked }
587
701
  Promise.resolve()
588
- .then(() => fetch('/api/message-ops/' + path, {
589
- method: 'POST',
590
- headers: { 'content-type': 'application/json' },
591
- body: JSON.stringify(body),
592
- }))
593
- .then(async (res) => {
702
+ .then(() =>
703
+ fetch('/api/message-ops/' + path, {
704
+ method: 'POST',
705
+ headers: { 'content-type': 'application/json' },
706
+ body: JSON.stringify(body),
707
+ }),
708
+ )
709
+ .then(async res => {
594
710
  let data = {}
595
- try { data = await res.json() } catch { /* keep {} */ }
711
+ try {
712
+ data = await res.json()
713
+ } catch {
714
+ /* keep {} */
715
+ }
596
716
  if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`)
597
717
  // S6 修复(G-M1):不再 900ms 裸 location.reload。成功走 devkit
598
718
  // 标准 toast(无 devkit 时降级为对话框内 doneMsg),并提供手动
@@ -612,7 +732,9 @@ window.__ModuleLoader__.load({
612
732
  __inputActions.setDraft(pickedMsg.fullText)
613
733
  if (typeof __inputActions.persistDraft === 'function') __inputActions.persistDraft()
614
734
  }
615
- } catch (e) { console.warn('[message-ops] refill failed:', e) }
735
+ } catch (e) {
736
+ console.warn('[message-ops] refill failed:', e)
737
+ }
616
738
  }
617
739
  setDoneMsg(okMsg)
618
740
  setBusyMsg('')
@@ -623,9 +745,11 @@ window.__ModuleLoader__.load({
623
745
  // 重建视图(与 restoreRow 同款 openSession 模式),遮蔽即刻可见。
624
746
  try {
625
747
  if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(target.sessionId)
626
- } catch { /* 视图重建失败不阻断成功反馈 */ }
748
+ } catch {
749
+ /* 视图重建失败不阻断成功反馈 */
750
+ }
627
751
  })
628
- .catch((reason) => {
752
+ .catch(reason => {
629
753
  setBusyMsg('')
630
754
  setState('ready')
631
755
  setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
@@ -636,43 +760,75 @@ window.__ModuleLoader__.load({
636
760
 
637
761
  // 0.6.0:system prompt 行不可作为回滚/删除/分支目标(引擎拒之以 node0 守卫,
638
762
  // 但不该给用户一个必然500的选项)——列表直接排除 role=system。
639
- const visible = messages.filter((m) => m.visible !== false && m.role !== 'system')
763
+ const visible = messages.filter(m => m.visible !== false && m.role !== 'system')
640
764
  const shownBase = visible.slice(-MAX_RENDER)
641
765
  const hiddenCount = visible.length - shownBase.length
642
766
  // 分批渲染(评审 M1):只渲染 renderLimit 条,更早的留给「显示更多」
643
767
  // 渐进展开,避免 200 行 radio 列表一次进 DOM。
644
768
  const shown = shownBase.slice(-renderLimit)
645
769
  const pagedCount = shownBase.length - shown.length
646
- const pickedMsg = picked != null ? messages.find((m) => m.seq === picked) : null
770
+ const pickedMsg = picked != null ? messages.find(m => m.seq === picked) : null
647
771
 
648
772
  // 0.9.0 可发现性:操作区固定在**消息列表之前**。
649
773
  // 原先它在列表之后,而列表是 260px 滚动 + 分批渲染 50 条/页 ——
650
774
  // 未选中消息时三个 radio 完全不在视野内,用户以为「只有列表、没有操作」。
651
775
  // 未选中时给明确指引,而不是空着。
652
776
  const opsPanel = pickedMsg
653
- ? React.createElement('div', { key: 'ops', style: { margin: '8px 0 0' } },
654
- React.createElement('div', { style: { ...metaStyle, margin: '0 0 4px' } },
655
- t('dialog.pickedAs', { seq: String(pickedMsg.seq), text: (pickedMsg.snippet || '').slice(0, 60) })),
656
- ['revert', 'delete', 'branch'].map((m, i) => React.createElement('div', { key: m, style: { marginTop: i === 0 ? 6 : 4 } },
657
- React.createElement('label', { style: optStyle },
658
- React.createElement('input', {
659
- type: 'radio', name: 'dsh-message-ops-mode', checked: mode === m,
660
- onChange: () => chooseMode(m), disabled: state === 'busy',
661
- }),
662
- t('op.' + m)),
663
- mode === m ? React.createElement('div', { style: descStyle }, t('op.' + m + 'Desc')) : null,
664
- )),
777
+ ? React.createElement(
778
+ 'div',
779
+ { key: 'ops', style: { margin: '8px 0 0' } },
780
+ React.createElement(
781
+ 'div',
782
+ { style: { ...metaStyle, margin: '0 0 4px' } },
783
+ t('dialog.pickedAs', { seq: String(pickedMsg.seq), text: (pickedMsg.snippet || '').slice(0, 60) }),
784
+ ),
785
+ ['revert', 'delete', 'branch'].map((m, i) =>
786
+ React.createElement(
787
+ 'div',
788
+ { key: m, style: { marginTop: i === 0 ? 6 : 4 } },
789
+ React.createElement(
790
+ 'label',
791
+ { style: optStyle },
792
+ React.createElement('input', {
793
+ type: 'radio',
794
+ name: 'dsh-message-ops-mode',
795
+ checked: mode === m,
796
+ onChange: () => chooseMode(m),
797
+ disabled: state === 'busy',
798
+ }),
799
+ t('op.' + m),
800
+ ),
801
+ mode === m ? React.createElement('div', { style: descStyle }, t('op.' + m + 'Desc')) : null,
802
+ ),
803
+ ),
665
804
  mode && mode !== 'branch'
666
- ? React.createElement('label', { key: 'ack', style: optStyle },
805
+ ? React.createElement(
806
+ 'label',
807
+ { key: 'ack', style: optStyle },
667
808
  React.createElement('input', {
668
- type: 'checkbox', checked: acknowledged, disabled: state === 'busy',
669
- onChange: (e) => setAcknowledged(e.target.checked),
809
+ type: 'checkbox',
810
+ checked: acknowledged,
811
+ disabled: state === 'busy',
812
+ onChange: e => setAcknowledged(e.target.checked),
670
813
  }),
671
- t(mode === 'revert' ? 'ack.revert' : 'ack.delete'))
814
+ t(mode === 'revert' ? 'ack.revert' : 'ack.delete'),
815
+ )
672
816
  : null,
673
817
  )
674
- : React.createElement('div', { key: 'opshint', style: { ...metaStyle, margin: '8px 0 0', padding: '6px 8px', borderRadius: 6, background: 'var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.1))' } },
675
- t('dialog.pickFirst'))
818
+ : React.createElement(
819
+ 'div',
820
+ {
821
+ key: 'opshint',
822
+ style: {
823
+ ...metaStyle,
824
+ margin: '8px 0 0',
825
+ padding: '6px 8px',
826
+ borderRadius: 6,
827
+ background: 'var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.1))',
828
+ },
829
+ },
830
+ t('dialog.pickFirst'),
831
+ )
676
832
 
677
833
  let body
678
834
  if (state === 'loading') {
@@ -684,36 +840,67 @@ window.__ModuleLoader__.load({
684
840
  target.running ? React.createElement('div', { key: 'warn', style: warnStyle }, t('dialog.runningWarn')) : null,
685
841
  opsPanel,
686
842
  React.createElement('div', { key: 'pick', style: metaStyle }, t('dialog.pick')),
687
- React.createElement('div', { key: 'list', style: listStyle },
843
+ React.createElement(
844
+ 'div',
845
+ { key: 'list', style: listStyle },
688
846
  hiddenCount > 0
689
- ? React.createElement('div', { key: 'more', style: { ...rowStyle, cursor: 'default', color: 'var(--dsw-alias-label-secondary,#8a8a8e)' } },
690
- t('dialog.more', { n: String(visible.length) }))
847
+ ? React.createElement(
848
+ 'div',
849
+ { key: 'more', style: { ...rowStyle, cursor: 'default', color: 'var(--dsw-alias-label-secondary,#8a8a8e)' } },
850
+ t('dialog.more', { n: String(visible.length) }),
851
+ )
691
852
  : null,
692
853
  pagedCount > 0
693
- ? React.createElement('button', {
694
- key: 'show-more', type: 'button',
695
- style: { ...rowStyle, border: 'none', width: '100%', color: 'var(--dsw-alias-label-secondary,#8a8a8e)', cursor: 'pointer' },
696
- onClick: () => setRenderLimit((l) => Math.min(l + PAGE_SIZE, MAX_RENDER)),
697
- }, t('dialog.showMore', { n: String(pagedCount) }))
854
+ ? React.createElement(
855
+ 'button',
856
+ {
857
+ key: 'show-more',
858
+ type: 'button',
859
+ style: {
860
+ ...rowStyle,
861
+ border: 'none',
862
+ width: '100%',
863
+ color: 'var(--dsw-alias-label-secondary,#8a8a8e)',
864
+ cursor: 'pointer',
865
+ },
866
+ onClick: () => setRenderLimit(l => Math.min(l + PAGE_SIZE, MAX_RENDER)),
867
+ },
868
+ t('dialog.showMore', { n: String(pagedCount) }),
869
+ )
698
870
  : null,
699
- shown.map((m, i) => React.createElement('label', {
700
- key: m.seq + '-' + i, style: {
701
- ...rowStyle,
702
- background: picked === m.seq ? 'var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.14))' : 'transparent',
703
- },
704
- },
705
- React.createElement('input', {
706
- type: 'radio', name: 'dsh-message-ops-pick', checked: picked === m.seq,
707
- onChange: () => pick(m), disabled: state === 'busy',
708
- }),
709
- React.createElement('span', {
710
- style: {
711
- flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
712
- color: m.visible === false ? 'var(--dsw-alias-label-tertiary,#b0b0b4)' : 'inherit',
871
+ shown.map((m, i) =>
872
+ React.createElement(
873
+ 'label',
874
+ {
875
+ key: m.seq + '-' + i,
876
+ style: {
877
+ ...rowStyle,
878
+ background: picked === m.seq ? 'var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.14))' : 'transparent',
879
+ },
713
880
  },
714
- },
715
- '#' + m.seq + ' ' + (m.role || '') + ' · ' + (m.snippet || '') + (m.visible === false ? t('dialog.invisible') : '')),
716
- )),
881
+ React.createElement('input', {
882
+ type: 'radio',
883
+ name: 'dsh-message-ops-pick',
884
+ checked: picked === m.seq,
885
+ onChange: () => pick(m),
886
+ disabled: state === 'busy',
887
+ }),
888
+ React.createElement(
889
+ 'span',
890
+ {
891
+ style: {
892
+ flex: 1,
893
+ minWidth: 0,
894
+ overflow: 'hidden',
895
+ textOverflow: 'ellipsis',
896
+ whiteSpace: 'nowrap',
897
+ color: m.visible === false ? 'var(--dsw-alias-label-tertiary,#b0b0b4)' : 'inherit',
898
+ },
899
+ },
900
+ '#' + m.seq + ' ' + (m.role || '') + ' · ' + (m.snippet || '') + (m.visible === false ? t('dialog.invisible') : ''),
901
+ ),
902
+ ),
903
+ ),
717
904
  ),
718
905
  // 0.9.7:删掉列表**之后**的旧 opsPanel——0.9.0 把操作区挪到列表之前时
719
906
  // 没删旧位置,两组同名 radio(name='dsh-message-ops-mode')互抢,
@@ -721,52 +908,93 @@ window.__ModuleLoader__.load({
721
908
  ])
722
909
  }
723
910
 
724
- const canRun = state !== 'busy' && state !== 'loading' && picked != null && mode != null
725
- && (mode === 'branch' || acknowledged)
911
+ const canRun = state !== 'busy' && state !== 'loading' && picked != null && mode != null && (mode === 'branch' || acknowledged)
726
912
  const confirmLabel = busyMsg || (mode ? t('confirm.' + mode) : t('dialog.cancel'))
727
913
 
728
- return React.createElement(Modal, {
729
- open: true,
730
- onClose: close,
731
- title: t('dialog.title'),
732
- closeLabel: t('dialog.cancel'),
733
- description: t('dialog.session') + (target.title || target.sessionId || ''),
734
- footer: [
735
- React.createElement('button', {
736
- key: 'cancel', type: 'button', disabled: state === 'busy',
737
- onClick: close, style: { ...cancelBtnStyle, ...(state === 'busy' ? { opacity: 0.5, cursor: 'default' } : {}) },
738
- }, t('dialog.cancel')),
739
- React.createElement('button', {
740
- key: 'confirm', type: 'button', disabled: !canRun,
741
- onClick: run,
742
- style: {
743
- ...(mode === 'delete' || mode === 'revert' ? dangerBtnStyle : primaryBtnStyle),
744
- ...(!canRun ? { opacity: 0.5, cursor: 'default' } : {}),
745
- },
746
- }, confirmLabel),
747
- ...(state === 'done' && (mode === 'revert' || mode === 'delete') ? [React.createElement('button', {
748
- key: 'reload', type: 'button',
749
- onClick: () => { try { window.location.reload() } catch { /* non-browser guard */ } },
750
- style: primaryBtnStyle,
751
- }, t('action.reload'))] : []),
752
- ...(state === 'done' && mode === 'branch' && childId ? [React.createElement('button', {
753
- key: 'open-new', type: 'button',
754
- onClick: () => {
755
- try {
756
- // 0.2.0+:uiWorkspace.openSession 是宿主唯一打开通道
757
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(childId)
758
- } catch { /* 打开失败不阻断 */ }
759
- },
760
- style: primaryBtnStyle,
761
- }, t('toast.openNew'))] : []),
914
+ return React.createElement(
915
+ Modal,
916
+ {
917
+ open: true,
918
+ onClose: close,
919
+ title: t('dialog.title'),
920
+ closeLabel: t('dialog.cancel'),
921
+ description: t('dialog.session') + (target.title || target.sessionId || ''),
922
+ footer: [
923
+ React.createElement(
924
+ 'button',
925
+ {
926
+ key: 'cancel',
927
+ type: 'button',
928
+ disabled: state === 'busy',
929
+ onClick: close,
930
+ style: { ...cancelBtnStyle, ...(state === 'busy' ? { opacity: 0.5, cursor: 'default' } : {}) },
931
+ },
932
+ t('dialog.cancel'),
933
+ ),
934
+ React.createElement(
935
+ 'button',
936
+ {
937
+ key: 'confirm',
938
+ type: 'button',
939
+ disabled: !canRun,
940
+ onClick: run,
941
+ style: {
942
+ ...(mode === 'delete' || mode === 'revert' ? dangerBtnStyle : primaryBtnStyle),
943
+ ...(!canRun ? { opacity: 0.5, cursor: 'default' } : {}),
944
+ },
945
+ },
946
+ confirmLabel,
947
+ ),
948
+ ...(state === 'done' && (mode === 'revert' || mode === 'delete')
949
+ ? [
950
+ React.createElement(
951
+ 'button',
952
+ {
953
+ key: 'reload',
954
+ type: 'button',
955
+ onClick: () => {
956
+ try {
957
+ window.location.reload()
958
+ } catch {
959
+ /* non-browser guard */
960
+ }
961
+ },
962
+ style: primaryBtnStyle,
963
+ },
964
+ t('action.reload'),
965
+ ),
966
+ ]
967
+ : []),
968
+ ...(state === 'done' && mode === 'branch' && childId
969
+ ? [
970
+ React.createElement(
971
+ 'button',
972
+ {
973
+ key: 'open-new',
974
+ type: 'button',
975
+ onClick: () => {
976
+ try {
977
+ // 0.2.0+:uiWorkspace.openSession 是宿主唯一打开通道
978
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(childId)
979
+ } catch {
980
+ /* 打开失败不阻断 */
981
+ }
982
+ },
983
+ style: primaryBtnStyle,
984
+ },
985
+ t('toast.openNew'),
986
+ ),
987
+ ]
988
+ : []),
989
+ ],
990
+ },
991
+ [
992
+ React.createElement('div', { key: 'meta', style: metaStyle }, t('dialog.session'), target.sessionId || ''),
993
+ body,
994
+ doneMsg ? React.createElement('div', { key: 'done', style: statusStyle }, doneMsg) : null,
995
+ error ? React.createElement('div', { key: 'err', style: errStyle, role: 'alert' }, error) : null,
762
996
  ],
763
- }, [
764
- React.createElement('div', { key: 'meta', style: metaStyle },
765
- t('dialog.session'), target.sessionId || ''),
766
- body,
767
- doneMsg ? React.createElement('div', { key: 'done', style: statusStyle }, doneMsg) : null,
768
- error ? React.createElement('div', { key: 'err', style: errStyle, role: 'alert' }, error) : null,
769
- ])
997
+ )
770
998
  }
771
999
 
772
1000
  // --- A · 功能主义抽屉 -------------------------------------------------------
@@ -778,7 +1006,9 @@ window.__ModuleLoader__.load({
778
1006
  if (typeof value !== 'number') return ''
779
1007
  try {
780
1008
  return new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
781
- } catch { return '' }
1009
+ } catch {
1010
+ return ''
1011
+ }
782
1012
  }
783
1013
 
784
1014
  function roleCode(role) {
@@ -790,8 +1020,9 @@ window.__ModuleLoader__.load({
790
1020
 
791
1021
  function focusablesIn(root) {
792
1022
  if (!root || typeof root.querySelectorAll !== 'function') return []
793
- const selector = 'button:not([disabled]),[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'
794
- return Array.prototype.slice.call(root.querySelectorAll(selector)).filter((el) => {
1023
+ const selector =
1024
+ 'button:not([disabled]),[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'
1025
+ return Array.prototype.slice.call(root.querySelectorAll(selector)).filter(el => {
795
1026
  if (el.getAttribute('aria-hidden') === 'true') return false
796
1027
  return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0
797
1028
  })
@@ -876,7 +1107,9 @@ window.__ModuleLoader__.load({
876
1107
  '@media(max-width:760px){.mopsPanelScrim{padding:0}.mopsPanel{width:100%;height:100%;max-width:100%;max-height:100%;border:0}.mopsDetail{max-height:42%}}',
877
1108
  ].join('')
878
1109
  document.head.appendChild(tag)
879
- } catch { /* style failure must not break the panel */ }
1110
+ } catch {
1111
+ /* style failure must not break the panel */
1112
+ }
880
1113
  }
881
1114
 
882
1115
  function OpsPanel(props) {
@@ -893,6 +1126,8 @@ window.__ModuleLoader__.load({
893
1126
  const [picked, setPicked] = useState(null)
894
1127
  const [detail, setDetail] = useState('')
895
1128
  const [detailState, setDetailState] = useState('idle')
1129
+ // MED-5:detail 是**全文**还是 snippet 回退?只有全文才允许「编辑并重发」。
1130
+ const [detailFull, setDetailFull] = useState(false)
896
1131
  const [tab, setTab] = useState('messages')
897
1132
  const [hits, setHits] = useState(null)
898
1133
  const [searching, setSearching] = useState(false)
@@ -930,7 +1165,7 @@ window.__ModuleLoader__.load({
930
1165
 
931
1166
  useEffect(() => {
932
1167
  ensurePanelStyle()
933
- const handler = (e) => {
1168
+ const handler = e => {
934
1169
  const d = e && e.detail ? e.detail : {}
935
1170
  if (!d.sessionId) return
936
1171
  const active = document.activeElement
@@ -970,31 +1205,44 @@ window.__ModuleLoader__.load({
970
1205
 
971
1206
  const sid = target && target.sessionId
972
1207
 
973
- const loadMessages = useCallback(async (quiet) => {
974
- if (!sid) return
975
- const requestId = ++loadSeqRef.current
976
- const requestSid = sid
977
- if (!quiet) { setState('loading'); setLoadError(null) }
978
- try {
979
- const data = await fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(requestSid) + '&view=compact')
980
- if (requestId !== loadSeqRef.current) return
981
- setMessages(Array.isArray(data.messages) ? data.messages : [])
982
- setTarget((prev) => prev && prev.sessionId === requestSid ? {
983
- ...prev,
984
- running: data.running === true,
985
- title: prev.title || (data.session && data.session.title) || null,
986
- expectedTitle: (data.session && data.session.confirmTitle) || prev.expectedTitle || prev.title || prev.sessionId,
987
- } : prev)
988
- setLoadError(null)
989
- setError(null)
990
- setState('ready')
991
- } catch (reason) {
992
- if (requestId !== loadSeqRef.current) return
993
- const message = t('panel.loadFail') + (reason && reason.message ? reason.message : String(reason))
994
- if (quiet) setError(message)
995
- else { setLoadError(message); setState('error') }
996
- }
997
- }, [sid, t])
1208
+ const loadMessages = useCallback(
1209
+ async quiet => {
1210
+ if (!sid) return
1211
+ const requestId = ++loadSeqRef.current
1212
+ const requestSid = sid
1213
+ if (!quiet) {
1214
+ setState('loading')
1215
+ setLoadError(null)
1216
+ }
1217
+ try {
1218
+ const data = await fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(requestSid) + '&view=compact')
1219
+ if (requestId !== loadSeqRef.current) return
1220
+ setMessages(Array.isArray(data.messages) ? data.messages : [])
1221
+ setTarget(prev =>
1222
+ prev && prev.sessionId === requestSid
1223
+ ? {
1224
+ ...prev,
1225
+ running: data.running === true,
1226
+ title: prev.title || (data.session && data.session.title) || null,
1227
+ expectedTitle: (data.session && data.session.confirmTitle) || prev.expectedTitle || prev.title || prev.sessionId,
1228
+ }
1229
+ : prev,
1230
+ )
1231
+ setLoadError(null)
1232
+ setError(null)
1233
+ setState('ready')
1234
+ } catch (reason) {
1235
+ if (requestId !== loadSeqRef.current) return
1236
+ const message = t('panel.loadFail') + (reason && reason.message ? reason.message : String(reason))
1237
+ if (quiet) setError(message)
1238
+ else {
1239
+ setLoadError(message)
1240
+ setState('error')
1241
+ }
1242
+ }
1243
+ },
1244
+ [sid, t],
1245
+ )
998
1246
 
999
1247
  useEffect(() => {
1000
1248
  if (!open || !sid) return
@@ -1004,29 +1252,47 @@ window.__ModuleLoader__.load({
1004
1252
  useEffect(() => {
1005
1253
  if (!open || tab !== 'messages') return
1006
1254
  const q = query.trim()
1007
- if (!q) { setHits(null); setSearching(false); return }
1255
+ if (!q) {
1256
+ setHits(null)
1257
+ setSearching(false)
1258
+ return
1259
+ }
1008
1260
  setSearching(true)
1009
1261
  let cancelled = false
1010
1262
  const timer = setTimeout(() => {
1011
1263
  setError(null)
1012
- const url = '/api/message-ops/search?sessionId=' + encodeURIComponent(sid)
1013
- + '&q=' + encodeURIComponent(q)
1014
- + (role !== 'all' ? '&role=' + encodeURIComponent(role) : '')
1015
- + '&limit=' + PANEL_SEARCH_LIMIT
1264
+ const url =
1265
+ '/api/message-ops/search?sessionId=' +
1266
+ encodeURIComponent(sid) +
1267
+ '&q=' +
1268
+ encodeURIComponent(q) +
1269
+ (role !== 'all' ? '&role=' + encodeURIComponent(role) : '') +
1270
+ '&limit=' +
1271
+ PANEL_SEARCH_LIMIT
1016
1272
  fetch(url)
1017
- .then((res) => res.json().catch(() => null).then((data) => ({ res, data })))
1273
+ .then(res =>
1274
+ res
1275
+ .json()
1276
+ .catch(() => null)
1277
+ .then(data => ({ res, data })),
1278
+ )
1018
1279
  .then(({ res, data }) => {
1019
1280
  if (cancelled) return
1020
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1281
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
1021
1282
  setHits(Array.isArray(data.results) ? data.results : [])
1022
1283
  setError(null)
1023
1284
  })
1024
- .catch((reason) => {
1285
+ .catch(reason => {
1025
1286
  if (!cancelled) setError(t('panel.searchFail') + (reason && reason.message ? reason.message : String(reason)))
1026
1287
  })
1027
- .finally(() => { if (!cancelled) setSearching(false) })
1288
+ .finally(() => {
1289
+ if (!cancelled) setSearching(false)
1290
+ })
1028
1291
  }, 200)
1029
- return () => { cancelled = true; clearTimeout(timer) }
1292
+ return () => {
1293
+ cancelled = true
1294
+ clearTimeout(timer)
1295
+ }
1030
1296
  }, [open, tab, sid, query, role, t])
1031
1297
 
1032
1298
  const loadTrash = useCallback(async () => {
@@ -1037,7 +1303,7 @@ window.__ModuleLoader__.load({
1037
1303
  const res = await fetch('/api/message-ops/session/trash')
1038
1304
  const data = await res.json().catch(() => null)
1039
1305
  if (requestId !== trashSeqRef.current) return
1040
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1306
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
1041
1307
  setTrash(Array.isArray(data.entries) ? data.entries : [])
1042
1308
  setTrashError(null)
1043
1309
  setTrashState('ready')
@@ -1102,32 +1368,46 @@ window.__ModuleLoader__.load({
1102
1368
  * 语义上与 opencode 的「回撤 → 原文回到 composer」一致;区别是我们不预先回撤,
1103
1369
  * 由用户决定发不发(发了才产生新的分支上下文)。
1104
1370
  */
1105
- const startEdit = useCallback((text) => {
1106
- if (!target || busy) return
1107
- const body = typeof text === 'string' ? text : ''
1108
- if (!body) {
1109
- setError(t('panel.editEmpty'))
1110
- return
1111
- }
1112
- if (!__inputActions || typeof __inputActions.setDraft !== 'function') {
1113
- setError(t('panel.editUnavailable'))
1114
- return
1115
- }
1116
- try {
1117
- __inputActions.setDraft(body)
1118
- if (typeof __inputActions.persistDraft === 'function') __inputActions.persistDraft()
1119
- } catch (reason) {
1120
- setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1121
- return
1122
- }
1123
- setDone(t('panel.editDone'))
1124
- notifyDone(t('panel.editDone'))
1125
- close()
1126
- }, [target, busy, t, close])
1371
+ const startEdit = useCallback(
1372
+ text => {
1373
+ if (!target || busy) return
1374
+ const body = typeof text === 'string' ? text : ''
1375
+ if (!body) {
1376
+ setError(t('panel.editEmpty'))
1377
+ return
1378
+ }
1379
+ if (!__inputActions || typeof __inputActions.setDraft !== 'function') {
1380
+ setError(t('panel.editUnavailable'))
1381
+ return
1382
+ }
1383
+ try {
1384
+ __inputActions.setDraft(body)
1385
+ if (typeof __inputActions.persistDraft === 'function') __inputActions.persistDraft()
1386
+ } catch (reason) {
1387
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1388
+ return
1389
+ }
1390
+ // MED-4:`persistDraft` 存在 ≠ 真的落盘。宿主的 writer 由
1391
+ // `bindDraftPersistence` 在视图挂载时绑定;blank/hero 态或视图未挂载时
1392
+ // 该函数在但空转。于是「setDraft 改的是内存编辑器、随后 close() 关面板、
1393
+ // 宿主重挂会话时从 localStorage 读回旧草稿」→ 用户看到成功却什么都没了。
1394
+ // 判据不能靠函数存在,只能**回读**:写不进存储就当失败,不 close。
1395
+ const sidForDraft = target.sessionId
1396
+ const stored = readSessionDraft(sidForDraft)
1397
+ if (stored != null && stored !== body) {
1398
+ setError(t('panel.editUnavailable'))
1399
+ return
1400
+ }
1401
+ setDone(t('panel.editDone'))
1402
+ notifyDone(t('panel.editDone'))
1403
+ close()
1404
+ },
1405
+ [target, busy, t, close],
1406
+ )
1127
1407
 
1128
1408
  useEffect(() => {
1129
1409
  if (!open) return undefined
1130
- const onKey = (e) => {
1410
+ const onKey = e => {
1131
1411
  if (e.key === 'Escape') {
1132
1412
  if (busy) return
1133
1413
  if (confirmDelete) closeConfirm()
@@ -1193,13 +1473,15 @@ window.__ModuleLoader__.load({
1193
1473
  let scrollbarW = 0
1194
1474
  try {
1195
1475
  scrollbarW = window.innerWidth - document.documentElement.clientWidth
1196
- } catch { /* non-browser */ }
1476
+ } catch {
1477
+ /* non-browser */
1478
+ }
1197
1479
  if (body && body.style) {
1198
1480
  body.style.overflow = 'hidden'
1199
1481
  // 为被隐藏的经典滚动条补回等宽内边距,避免整页横向跳动。
1200
1482
  if (scrollbarW > 0) {
1201
1483
  const base = Number.parseFloat(getComputedStyle(body).paddingRight) || 0
1202
- body.style.paddingRight = (base + scrollbarW) + 'px'
1484
+ body.style.paddingRight = base + scrollbarW + 'px'
1203
1485
  }
1204
1486
  }
1205
1487
  return () => {
@@ -1217,16 +1499,22 @@ window.__ModuleLoader__.load({
1217
1499
  const trigger = triggerRef.current
1218
1500
  triggerRef.current = null
1219
1501
  if (trigger && typeof trigger.focus === 'function') {
1220
- setTimeout(() => { try { trigger.focus() } catch { /* detached trigger */ } }, 0)
1502
+ setTimeout(() => {
1503
+ try {
1504
+ trigger.focus()
1505
+ } catch {
1506
+ /* detached trigger */
1507
+ }
1508
+ }, 0)
1221
1509
  }
1222
1510
  }
1223
1511
  }, [open, sid])
1224
1512
 
1225
1513
  useEffect(() => {
1226
1514
  if (!open) return undefined
1227
- const onKeyDown = (e) => {
1515
+ const onKeyDown = e => {
1228
1516
  if (e.key !== 'Tab') return
1229
- const scope = confirmDelete ? confirmRef.current : (confirmAction ? actionConfirmRef.current : panelRef.current)
1517
+ const scope = confirmDelete ? confirmRef.current : confirmAction ? actionConfirmRef.current : panelRef.current
1230
1518
  if (!scope) return
1231
1519
  const nodes = focusablesIn(scope)
1232
1520
  if (!nodes.length) {
@@ -1264,33 +1552,33 @@ window.__ModuleLoader__.load({
1264
1552
  }
1265
1553
  }, [open, confirmDelete, confirmAction])
1266
1554
 
1267
- const baseRows = query.trim() ? (hits || []) : messages
1555
+ const baseRows = query.trim() ? hits || [] : messages
1268
1556
  const rows = baseRows
1269
- .filter((m) => m && m.role !== 'system'
1270
- && (role === 'all' || m.role === role)
1271
- && (includeShadowed || !m.shadowed))
1557
+ .filter(m => m && m.role !== 'system' && (role === 'all' || m.role === role) && (includeShadowed || !m.shadowed))
1272
1558
  .sort((a, b) => b.seq - a.seq)
1273
- const activeIndex = picked ? rows.findIndex((m) => m.seq === picked.seq) : -1
1559
+ const activeIndex = picked ? rows.findIndex(m => m.seq === picked.seq) : -1
1274
1560
 
1275
1561
  const clearPick = () => {
1276
1562
  detailReq.current += 1
1277
1563
  setPicked(null)
1278
1564
  setDetail('')
1565
+ setDetailFull(false)
1279
1566
  setDetailState('idle')
1280
1567
  setConfirmAction(null)
1281
1568
  }
1282
1569
 
1283
- const previewRow = (m) => {
1570
+ const previewRow = m => {
1284
1571
  if (!m) return
1285
1572
  detailReq.current += 1
1286
1573
  setPicked(m)
1287
1574
  setDetail(m.snippet || '')
1575
+ setDetailFull(false)
1288
1576
  setDetailState('ready')
1289
1577
  setConfirmAction(null)
1290
1578
  setDone('')
1291
1579
  }
1292
1580
 
1293
- const scrollRowIntoView = (index) => {
1581
+ const scrollRowIntoView = index => {
1294
1582
  const el = listRef.current
1295
1583
  if (!el) return
1296
1584
  const top = index * PANEL_ROW_H
@@ -1304,9 +1592,9 @@ window.__ModuleLoader__.load({
1304
1592
  }
1305
1593
  }
1306
1594
 
1307
- const handleListKeyDown = (e) => {
1595
+ const handleListKeyDown = e => {
1308
1596
  if (!rows.length) return
1309
- const page = Math.max(1, Math.floor((listRef.current && listRef.current.clientHeight || viewport) / PANEL_ROW_H) - 1)
1597
+ const page = Math.max(1, Math.floor(((listRef.current && listRef.current.clientHeight) || viewport) / PANEL_ROW_H) - 1)
1310
1598
  let next = activeIndex
1311
1599
  if (e.key === 'ArrowDown') next = activeIndex < 0 ? 0 : Math.min(rows.length - 1, activeIndex + 1)
1312
1600
  else if (e.key === 'ArrowUp') next = activeIndex < 0 ? rows.length - 1 : Math.max(0, activeIndex - 1)
@@ -1317,7 +1605,10 @@ window.__ModuleLoader__.load({
1317
1605
  else if (e.key === 'Enter' || e.key === ' ') {
1318
1606
  e.preventDefault()
1319
1607
  const row = rows[activeIndex >= 0 ? activeIndex : 0]
1320
- if (row) { pick(row); if (listRef.current) listRef.current.focus() }
1608
+ if (row) {
1609
+ pick(row)
1610
+ if (listRef.current) listRef.current.focus()
1611
+ }
1321
1612
  return
1322
1613
  } else {
1323
1614
  return
@@ -1352,86 +1643,111 @@ window.__ModuleLoader__.load({
1352
1643
  }
1353
1644
  }, [open, tab, rows.length, viewport])
1354
1645
 
1355
- const pick = useCallback((m) => {
1356
- if (!m || busy) return
1357
- setConfirmAction(null)
1358
- setPicked(m)
1359
- setDetail(m.snippet || '')
1360
- setDetailState('loading')
1361
- setDone('')
1362
- const req = ++detailReq.current
1363
- fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(sid) + '&seq=' + encodeURIComponent(m.seq))
1364
- .then((res) => res.json().catch(() => null).then((data) => ({ res, data })))
1365
- .then(({ res, data }) => {
1366
- if (req !== detailReq.current) return
1367
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1368
- setDetail(typeof data.text === 'string' && data.text ? data.text : (m.snippet || ''))
1369
- setDetailState('ready')
1370
- })
1371
- .catch(() => {
1372
- if (req !== detailReq.current) return
1373
- setDetail(m.snippet || '')
1374
- setDetailState('ready')
1375
- })
1376
- }, [busy, sid])
1646
+ const pick = useCallback(
1647
+ m => {
1648
+ if (!m || busy) return
1649
+ setConfirmAction(null)
1650
+ setPicked(m)
1651
+ setDetail(m.snippet || '')
1652
+ setDetailFull(false)
1653
+ setDetailState('loading')
1654
+ setDone('')
1655
+ const req = ++detailReq.current
1656
+ fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(sid) + '&seq=' + encodeURIComponent(m.seq))
1657
+ .then(res =>
1658
+ res
1659
+ .json()
1660
+ .catch(() => null)
1661
+ .then(data => ({ res, data })),
1662
+ )
1663
+ .then(({ res, data }) => {
1664
+ if (req !== detailReq.current) return
1665
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
1666
+ const full = typeof data.text === 'string' && data.text !== '' ? data.text : null
1667
+ setDetail(full ?? (m.snippet || ''))
1668
+ setDetailFull(full !== null)
1669
+ setDetailState('ready')
1670
+ })
1671
+ .catch(() => {
1672
+ if (req !== detailReq.current) return
1673
+ setDetail(m.snippet || '')
1674
+ setDetailFull(false) // 拉全文失败 → 只有截断的 snippet,不许冒充原文
1675
+ setDetailState('ready')
1676
+ })
1677
+ },
1678
+ [busy, sid],
1679
+ )
1377
1680
 
1378
- const runAction = useCallback(async (mode, confirmed) => {
1379
- if (!target || !picked || busy) return
1380
- if (target.running && mode !== 'branch') return
1381
- if ((mode === 'revert' || mode === 'delete') && confirmed !== true) return
1382
- const actionSid = target.sessionId
1383
- setBusy(mode)
1384
- setError(null)
1385
- setDone('')
1386
- try {
1387
- if (mode === 'branch') {
1388
- // 0.12.0:分叉 = opencode 的 before 语义(新会话不含此条,原文回输入框)。
1389
- // 非破坏操作,故不受 running 限制(官方 fork 会自己拒绝运行中源会话)。
1390
- // 取文本用 `detail`(该条全文,pick 时已按 seq 拉好);非用户消息不带文本。
1391
- const pickedRole = picked && picked.role
1392
- const created = await forkFromUserMessage(actionSid, picked.seq, pickedRole === 'user' ? detail : '', picked.turnStartSeq)
1681
+ const runAction = useCallback(
1682
+ async (mode, confirmed) => {
1683
+ if (!target || !picked || busy) return
1684
+ if (target.running && mode !== 'branch') return
1685
+ if ((mode === 'revert' || mode === 'delete') && confirmed !== true) return
1686
+ const actionSid = target.sessionId
1687
+ setBusy(mode)
1688
+ setError(null)
1689
+ setDone('')
1690
+ try {
1691
+ if (mode === 'branch') {
1692
+ // 0.12.0:分叉 = opencode 的 before 语义(新会话不含此条,原文回输入框)。
1693
+ // 非破坏操作,故不受 running 限制(官方 fork 会自己拒绝运行中源会话)。
1694
+ // 取文本用 `detail`(该条全文,pick 时已按 seq 拉好);非用户消息不带文本。
1695
+ const pickedRole = picked && picked.role
1696
+ const created = await forkFromUserMessage(actionSid, picked.seq, pickedRole === 'user' ? detail : '', picked.turnStartSeq)
1697
+ if (sessionRef.current !== actionSid) return
1698
+ setChildId(created || null)
1699
+ setDone(t('panel.branchDone', { id: String(created || '') }))
1700
+ notifyDone(t('panel.branchDone', { id: String(created || '') }))
1701
+ return
1702
+ }
1703
+ const res = await fetch('/api/message-ops/' + mode, {
1704
+ method: 'POST',
1705
+ headers: { 'content-type': 'application/json' },
1706
+ body: JSON.stringify({ sessionId: target.sessionId, seq: picked.seq }),
1707
+ })
1708
+ const data = await res.json().catch(() => null)
1393
1709
  if (sessionRef.current !== actionSid) return
1394
- setChildId(created || null)
1395
- setDone(t('panel.branchDone', { id: String(created || '') }))
1396
- notifyDone(t('panel.branchDone', { id: String(created || '') }))
1397
- return
1398
- }
1399
- const res = await fetch('/api/message-ops/' + mode, {
1400
- method: 'POST',
1401
- headers: { 'content-type': 'application/json' },
1402
- body: JSON.stringify({ sessionId: target.sessionId, seq: picked.seq }),
1403
- })
1404
- const data = await res.json().catch(() => null)
1405
- if (sessionRef.current !== actionSid) return
1406
- if (!res.ok || !data || data.ok !== true) {
1407
- if (res.status === 409) setTarget((prev) => prev ? { ...prev, running: true } : prev)
1408
- throw new Error((data && data.error) || ('HTTP ' + res.status))
1409
- }
1410
- if (mode === 'revert') {
1411
- setMessages((prev) => prev.map((m) => (m.seq >= picked.seq ? { ...m, shadowed: true, visible: false } : m)))
1412
- if (picked.role === 'user') {
1413
- try { refillComposer(target.sessionId, picked.seq) } catch { /* non-blocking */ }
1710
+ if (!res.ok || !data || data.ok !== true) {
1711
+ if (res.status === 409) setTarget(prev => (prev ? { ...prev, running: true } : prev))
1712
+ throw new Error((data && data.error) || 'HTTP ' + res.status)
1414
1713
  }
1415
- } else {
1416
- setMessages((prev) => prev.map((m) => (m.seq === picked.seq ? { ...m, shadowed: true, visible: false } : m)))
1714
+ if (mode === 'revert') {
1715
+ setMessages(prev => prev.map(m => (m.seq >= picked.seq ? { ...m, shadowed: true, visible: false } : m)))
1716
+ if (picked.role === 'user') {
1717
+ try {
1718
+ refillComposer(target.sessionId, picked.seq)
1719
+ } catch {
1720
+ /* non-blocking */
1721
+ }
1722
+ }
1723
+ } else {
1724
+ setMessages(prev => prev.map(m => (m.seq === picked.seq ? { ...m, shadowed: true, visible: false } : m)))
1725
+ }
1726
+ const msg = t(mode === 'revert' ? 'panel.revertDone' : 'panel.deleteDone')
1727
+ setDone(msg)
1728
+ setConfirmAction(null)
1729
+ setTimeout(() => {
1730
+ if (listRef.current) listRef.current.focus()
1731
+ }, 0)
1732
+ notifyDone(msg)
1733
+ emitChanged()
1734
+ try {
1735
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(target.sessionId)
1736
+ } catch {
1737
+ /* view rebuild is best effort */
1738
+ }
1739
+ setTimeout(() => {
1740
+ loadMessages(true).catch(() => {})
1741
+ }, 650)
1742
+ } catch (reason) {
1743
+ if (sessionRef.current !== actionSid) return
1744
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1745
+ } finally {
1746
+ setBusy('')
1417
1747
  }
1418
- const msg = t(mode === 'revert' ? 'panel.revertDone' : 'panel.deleteDone')
1419
- setDone(msg)
1420
- setConfirmAction(null)
1421
- setTimeout(() => { if (listRef.current) listRef.current.focus() }, 0)
1422
- notifyDone(msg)
1423
- emitChanged()
1424
- try {
1425
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(target.sessionId)
1426
- } catch { /* view rebuild is best effort */ }
1427
- setTimeout(() => { loadMessages(true).catch(() => {}) }, 650)
1428
- } catch (reason) {
1429
- if (sessionRef.current !== actionSid) return
1430
- setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1431
- } finally {
1432
- setBusy('')
1433
- }
1434
- }, [target, picked, busy, t, loadMessages])
1748
+ },
1749
+ [target, picked, busy, t, loadMessages],
1750
+ )
1435
1751
 
1436
1752
  const deleteSession = useCallback(async () => {
1437
1753
  if (!target || busy || target.running) return
@@ -1450,14 +1766,20 @@ window.__ModuleLoader__.load({
1450
1766
  const data = await res.json().catch(() => null)
1451
1767
  if (sessionRef.current !== actionSid) return
1452
1768
  if (!res.ok || !data || data.ok !== true) {
1453
- if (res.status === 409) setTarget((prev) => prev ? { ...prev, running: true } : prev)
1454
- throw new Error((data && data.error) || ('HTTP ' + res.status))
1769
+ if (res.status === 409) setTarget(prev => (prev ? { ...prev, running: true } : prev))
1770
+ throw new Error((data && data.error) || 'HTTP ' + res.status)
1455
1771
  }
1456
1772
  setConfirmDelete(false)
1457
1773
  setDone(t('panel.deleted'))
1458
1774
  notifyDone(t('panel.deleted'))
1459
1775
  emitChanged()
1460
- setTimeout(() => { try { window.location.reload() } catch { /* non-browser guard */ } }, 700)
1776
+ setTimeout(() => {
1777
+ try {
1778
+ window.location.reload()
1779
+ } catch {
1780
+ /* non-browser guard */
1781
+ }
1782
+ }, 700)
1461
1783
  } catch (reason) {
1462
1784
  if (sessionRef.current !== actionSid) return
1463
1785
  setDeleteError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
@@ -1466,68 +1788,81 @@ window.__ModuleLoader__.load({
1466
1788
  }
1467
1789
  }, [target, busy, confirmTitle, t])
1468
1790
 
1469
- const restoreEntry = useCallback(async (trashId) => {
1470
- if (busy) return
1471
- setBusy('restore:' + trashId)
1472
- setError(null)
1473
- setDone('')
1474
- try {
1475
- const res = await fetch('/api/message-ops/session/restore', {
1476
- method: 'POST',
1477
- headers: { 'content-type': 'application/json' },
1478
- body: JSON.stringify({ trashId }),
1479
- })
1480
- const data = await res.json().catch(() => null)
1481
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1482
- setTrash((prev) => prev.filter((x) => x.trashId !== trashId))
1483
- setDone(t('panel.restored'))
1484
- notifyDone(t('panel.restored'))
1485
- emitChanged()
1486
- setTimeout(() => { try { window.location.reload() } catch { /* non-browser guard */ } }, 700)
1487
- } catch (reason) {
1488
- setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1489
- } finally {
1490
- setBusy('')
1491
- }
1492
- }, [busy, t])
1791
+ const restoreEntry = useCallback(
1792
+ async trashId => {
1793
+ if (busy) return
1794
+ setBusy('restore:' + trashId)
1795
+ setError(null)
1796
+ setDone('')
1797
+ try {
1798
+ const res = await fetch('/api/message-ops/session/restore', {
1799
+ method: 'POST',
1800
+ headers: { 'content-type': 'application/json' },
1801
+ body: JSON.stringify({ trashId }),
1802
+ })
1803
+ const data = await res.json().catch(() => null)
1804
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
1805
+ setTrash(prev => prev.filter(x => x.trashId !== trashId))
1806
+ setDone(t('panel.restored'))
1807
+ notifyDone(t('panel.restored'))
1808
+ emitChanged()
1809
+ setTimeout(() => {
1810
+ try {
1811
+ window.location.reload()
1812
+ } catch {
1813
+ /* non-browser guard */
1814
+ }
1815
+ }, 700)
1816
+ } catch (reason) {
1817
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1818
+ } finally {
1819
+ setBusy('')
1820
+ }
1821
+ },
1822
+ [busy, t],
1823
+ )
1493
1824
 
1494
- const purgeEntry = useCallback(async (trashId) => {
1495
- if (busy) return
1496
- if (purgeId !== trashId) { setPurgeId(trashId); return }
1497
- setBusy('purge:' + trashId)
1498
- setError(null)
1499
- setDone('')
1500
- try {
1501
- const res = await fetch('/api/message-ops/session/purge', {
1502
- method: 'POST',
1503
- headers: { 'content-type': 'application/json' },
1504
- body: JSON.stringify({ trashId }),
1505
- })
1506
- const data = await res.json().catch(() => null)
1507
- if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1508
- setTrash((prev) => prev.filter((x) => x.trashId !== trashId))
1509
- setPurgeId(null)
1510
- setDone(t('panel.purged'))
1511
- notifyDone(t('panel.purged'))
1512
- } catch (reason) {
1513
- setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1514
- } finally {
1515
- setBusy('')
1516
- }
1517
- }, [busy, purgeId, t])
1825
+ const purgeEntry = useCallback(
1826
+ async trashId => {
1827
+ if (busy) return
1828
+ if (purgeId !== trashId) {
1829
+ setPurgeId(trashId)
1830
+ return
1831
+ }
1832
+ setBusy('purge:' + trashId)
1833
+ setError(null)
1834
+ setDone('')
1835
+ try {
1836
+ const res = await fetch('/api/message-ops/session/purge', {
1837
+ method: 'POST',
1838
+ headers: { 'content-type': 'application/json' },
1839
+ body: JSON.stringify({ trashId }),
1840
+ })
1841
+ const data = await res.json().catch(() => null)
1842
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || 'HTTP ' + res.status)
1843
+ setTrash(prev => prev.filter(x => x.trashId !== trashId))
1844
+ setPurgeId(null)
1845
+ setDone(t('panel.purged'))
1846
+ notifyDone(t('panel.purged'))
1847
+ } catch (reason) {
1848
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1849
+ } finally {
1850
+ setBusy('')
1851
+ }
1852
+ },
1853
+ [busy, purgeId, t],
1854
+ )
1518
1855
 
1519
1856
  if (!open) return null
1520
1857
 
1521
- const pickedLive = picked ? (messages.find((m) => m.seq === picked.seq) || picked) : null
1858
+ const pickedLive = picked ? messages.find(m => m.seq === picked.seq) || picked : null
1522
1859
  const canAct = !busy && !target.running && pickedLive && !pickedLive.shadowed
1523
- const visibleCount = messages.filter((m) => m.role !== 'system' && m.visible && !m.shadowed).length
1524
- const shadowedCount = messages.filter((m) => m.role !== 'system' && m.shadowed).length
1525
- const totalCount = messages.filter((m) => m.role !== 'system').length
1526
- const revertImpact = pickedLive
1527
- ? messages.filter((m) => m.role !== 'system' && !m.shadowed && m.seq >= pickedLive.seq)
1528
- : []
1860
+ const visibleCount = messages.filter(m => m.role !== 'system' && m.visible && !m.shadowed).length
1861
+ const shadowedCount = messages.filter(m => m.role !== 'system' && m.shadowed).length
1862
+ const totalCount = messages.filter(m => m.role !== 'system').length
1863
+ const revertImpact = pickedLive ? messages.filter(m => m.role !== 'system' && !m.shadowed && m.seq >= pickedLive.seq) : []
1529
1864
  const revertCount = revertImpact.length
1530
- const revertVisibleCount = revertImpact.filter((m) => m.visible).length
1865
+ const revertVisibleCount = revertImpact.filter(m => m.visible).length
1531
1866
  const revertEnd = revertImpact.reduce((max, m) => Math.max(max, m.seq), pickedLive ? pickedLive.seq : 0)
1532
1867
  const expectedDeleteTitle = target.expectedTitle || ''
1533
1868
  // 0.12.0:分叉/编辑只对**用户消息**成立(与 opencode 一致:fork 的语义是
@@ -1535,253 +1870,579 @@ window.__ModuleLoader__.load({
1535
1870
  const pickedIsUser = !!pickedLive && pickedLive.role === 'user'
1536
1871
  const canFork = !busy && !target.running && pickedIsUser && !pickedLive.shadowed && pickedLive.seq > 0
1537
1872
  const canEdit = pickedIsUser && !pickedLive.shadowed && state === 'ready' && !busy
1873
+ // MED-5:只有**真拉到全文**才允许编辑。detail 在 /text 失败时会退化成
1874
+ // snippet,而 snippet 被服务端硬截断到 160 字(session-file.js:331)——
1875
+ // 拿它冒充原文会让用户改完发出时静默丢掉后半段。
1876
+ const editTextReady = detailFull === true && typeof detail === 'string' && detail !== ''
1538
1877
  const deleteBlockedReason = target.running
1539
1878
  ? t('panel.running')
1540
1879
  : state !== 'ready'
1541
- ? (state === 'error' ? t('panel.loadFail') : t('panel.loading'))
1542
- : !expectedDeleteTitle ? t('panel.deleteUnavailable') : ''
1543
- const canConfirmDelete = !busy && state === 'ready' && !target.running && !!expectedDeleteTitle
1544
- && confirmTitle.trim() === expectedDeleteTitle
1880
+ ? state === 'error'
1881
+ ? t('panel.loadFail')
1882
+ : t('panel.loading')
1883
+ : !expectedDeleteTitle
1884
+ ? t('panel.deleteUnavailable')
1885
+ : ''
1886
+ const canConfirmDelete =
1887
+ !busy && state === 'ready' && !target.running && !!expectedDeleteTitle && confirmTitle.trim() === expectedDeleteTitle
1545
1888
  const start = Math.min(Math.max(0, rows.length - 1), Math.max(0, Math.floor(scrollTop / PANEL_ROW_H) - 6))
1546
1889
  const end = Math.min(rows.length, start + Math.ceil(viewport / PANEL_ROW_H) + 12)
1547
1890
  const windowRows = rows.slice(start, end)
1548
- const activeRendered = picked && windowRows.some((m) => m.seq === picked.seq)
1891
+ const activeRendered = picked && windowRows.some(m => m.seq === picked.seq)
1549
1892
  const showSearchLoading = searching && query.trim().length > 0
1550
1893
 
1551
- return React.createElement('div', {
1552
- className: 'mopsPanelScrim', role: 'presentation', ref: scrimRef,
1553
- onMouseDown: (e) => { if (e.target === e.currentTarget) close() },
1554
- },
1555
- React.createElement('section', {
1556
- className: 'mopsPanel', role: 'dialog', 'aria-modal': 'true',
1557
- 'aria-labelledby': 'mops-panel-title', 'aria-describedby': 'mops-panel-session',
1558
- 'aria-busy': busy || state === 'loading' ? 'true' : undefined,
1559
- tabIndex: -1, ref: panelRef,
1560
- style: { position: 'relative' },
1894
+ return React.createElement(
1895
+ 'div',
1896
+ {
1897
+ className: 'mopsPanelScrim',
1898
+ role: 'presentation',
1899
+ ref: scrimRef,
1900
+ onMouseDown: e => {
1901
+ if (e.target === e.currentTarget) close()
1902
+ },
1561
1903
  },
1562
- React.createElement('header', { className: 'mopsPanelHead' },
1563
- React.createElement('div', { style: { minWidth: 0 } },
1904
+ React.createElement(
1905
+ 'section',
1906
+ {
1907
+ className: 'mopsPanel',
1908
+ role: 'dialog',
1909
+ 'aria-modal': 'true',
1910
+ 'aria-labelledby': 'mops-panel-title',
1911
+ 'aria-describedby': 'mops-panel-session',
1912
+ 'aria-busy': busy || state === 'loading' ? 'true' : undefined,
1913
+ tabIndex: -1,
1914
+ ref: panelRef,
1915
+ style: { position: 'relative' },
1916
+ },
1917
+ React.createElement(
1918
+ 'header',
1919
+ { className: 'mopsPanelHead' },
1920
+ React.createElement(
1921
+ 'div',
1922
+ { style: { minWidth: 0 } },
1564
1923
  React.createElement('div', { className: 'mopsPanelKicker' }, t('dialog.title')),
1565
- React.createElement('div', { className: 'mopsPanelTitle', id: 'mops-panel-title' }, target.title || target.expectedTitle || target.sessionId),
1566
- React.createElement('div', { className: 'mopsPanelSub', id: 'mops-panel-session' }, target.sessionId)),
1567
- React.createElement('button', {
1568
- type: 'button', className: 'mopsPanelClose', title: t('dialog.cancel'),
1569
- 'aria-label': t('dialog.cancel'),
1570
- onClick: close, disabled: !!busy,
1571
- }, '×')),
1572
- React.createElement('div', { className: 'mopsTabs' },
1573
- React.createElement('button', {
1574
- type: 'button', className: 'mopsTab' + (tab === 'messages' ? ' on' : ''),
1575
- onClick: () => { setTab('messages'); setConfirmDelete(false); setConfirmAction(null); setDeleteError(null) },
1576
- }, t('panel.messages') + ' ' + totalCount),
1577
- React.createElement('button', {
1578
- type: 'button', className: 'mopsTab' + (tab === 'trash' ? ' on' : ''),
1579
- onClick: () => { setTab('trash'); setConfirmDelete(false); setConfirmAction(null); setDeleteError(null) },
1580
- }, t('panel.trash') + (trash.length ? ' ' + trash.length : ''))),
1581
- target.running && tab === 'messages'
1582
- ? React.createElement('div', { className: 'mopsBanner warn' }, t('panel.running')) : null,
1924
+ React.createElement(
1925
+ 'div',
1926
+ { className: 'mopsPanelTitle', id: 'mops-panel-title' },
1927
+ target.title || target.expectedTitle || target.sessionId,
1928
+ ),
1929
+ React.createElement('div', { className: 'mopsPanelSub', id: 'mops-panel-session' }, target.sessionId),
1930
+ ),
1931
+ React.createElement(
1932
+ 'button',
1933
+ {
1934
+ type: 'button',
1935
+ className: 'mopsPanelClose',
1936
+ title: t('dialog.cancel'),
1937
+ 'aria-label': t('dialog.cancel'),
1938
+ onClick: close,
1939
+ disabled: !!busy,
1940
+ },
1941
+ '×',
1942
+ ),
1943
+ ),
1944
+ React.createElement(
1945
+ 'div',
1946
+ { className: 'mopsTabs' },
1947
+ React.createElement(
1948
+ 'button',
1949
+ {
1950
+ type: 'button',
1951
+ className: 'mopsTab' + (tab === 'messages' ? ' on' : ''),
1952
+ onClick: () => {
1953
+ setTab('messages')
1954
+ setConfirmDelete(false)
1955
+ setConfirmAction(null)
1956
+ setDeleteError(null)
1957
+ },
1958
+ },
1959
+ t('panel.messages') + ' ' + totalCount,
1960
+ ),
1961
+ React.createElement(
1962
+ 'button',
1963
+ {
1964
+ type: 'button',
1965
+ className: 'mopsTab' + (tab === 'trash' ? ' on' : ''),
1966
+ onClick: () => {
1967
+ setTab('trash')
1968
+ setConfirmDelete(false)
1969
+ setConfirmAction(null)
1970
+ setDeleteError(null)
1971
+ },
1972
+ },
1973
+ t('panel.trash') + (trash.length ? ' ' + trash.length : ''),
1974
+ ),
1975
+ ),
1976
+ target.running && tab === 'messages' ? React.createElement('div', { className: 'mopsBanner warn' }, t('panel.running')) : null,
1583
1977
  error ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, error) : null,
1584
- done ? React.createElement('div', { className: 'mopsBanner ok' }, done,
1585
- childId ? React.createElement('button', {
1586
- type: 'button', className: 'mopsAction primary', style: { marginLeft: 10 },
1587
- onClick: () => { try { if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(childId) } catch { /* best effort */ } },
1588
- }, t('panel.openNew')) : null) : null,
1978
+ done
1979
+ ? React.createElement(
1980
+ 'div',
1981
+ { className: 'mopsBanner ok' },
1982
+ done,
1983
+ childId
1984
+ ? React.createElement(
1985
+ 'button',
1986
+ {
1987
+ type: 'button',
1988
+ className: 'mopsAction primary',
1989
+ style: { marginLeft: 10 },
1990
+ onClick: () => {
1991
+ try {
1992
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(childId)
1993
+ } catch {
1994
+ /* best effort */
1995
+ }
1996
+ },
1997
+ },
1998
+ t('panel.openNew'),
1999
+ )
2000
+ : null,
2001
+ )
2002
+ : null,
1589
2003
  tab === 'messages'
1590
- ? React.createElement(React.Fragment, null,
1591
- React.createElement('div', { className: 'mopsSearchRow' },
1592
- React.createElement('input', {
1593
- ref: searchRef, className: 'mopsSearch', value: query,
1594
- placeholder: t('panel.searchHint'), 'aria-label': t('panel.search'),
1595
- onChange: (e) => { setQuery(e.target.value); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1596
- })),
1597
- React.createElement('div', { className: 'mopsChips' },
1598
- ['all', 'user', 'assistant', 'tool'].map((key) => React.createElement('button', {
1599
- key, type: 'button', className: 'mopsChip' + (role === key ? ' on' : ''),
1600
- onClick: () => { setRole(key); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1601
- }, t('panel.' + key))),
1602
- React.createElement('label', { className: 'mopsToggle' },
2004
+ ? React.createElement(
2005
+ React.Fragment,
2006
+ null,
2007
+ React.createElement(
2008
+ 'div',
2009
+ { className: 'mopsSearchRow' },
1603
2010
  React.createElement('input', {
1604
- type: 'checkbox', checked: includeShadowed,
1605
- onChange: (e) => { setIncludeShadowed(e.target.checked); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1606
- }), t('panel.includeShadowed'))),
1607
- React.createElement('div', {
1608
- className: 'mopsList', ref: listRef,
1609
- role: state === 'ready' && rows.length ? 'listbox' : 'region',
1610
- tabIndex: state === 'ready' && rows.length ? 0 : -1,
1611
- 'aria-label': t('panel.messages'),
1612
- 'aria-busy': state === 'loading' || showSearchLoading ? 'true' : undefined,
1613
- 'aria-activedescendant': state === 'ready' && activeRendered ? 'mops-opt-' + picked.seq : undefined,
1614
- onKeyDown: handleListKeyDown,
1615
- onScroll: (e) => setScrollTop(e.currentTarget.scrollTop),
1616
- },
1617
- state === 'loading' || state === 'idle'
1618
- ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1619
- : state === 'error'
1620
- ? React.createElement('div', { className: 'mopsEmpty mopsErrorState', role: 'alert' },
1621
- React.createElement('span', null, loadError || t('panel.loadFail')),
1622
- React.createElement('button', {
1623
- type: 'button', className: 'mopsAction',
1624
- onClick: () => { loadMessages(false); setTimeout(() => { if (searchRef.current) searchRef.current.focus() }, 0) },
1625
- }, t('panel.retry')))
1626
- : rows.length === 0
1627
- ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, showSearchLoading ? t('panel.searching') : (query.trim() ? t('panel.noMatch') : t('panel.empty')))
1628
- : React.createElement('div', { style: { height: rows.length * PANEL_ROW_H, position: 'relative' } },
1629
- windowRows.map((m, i) => React.createElement('div', {
1630
- key: m.seq, id: 'mops-opt-' + m.seq, role: 'option',
1631
- 'aria-selected': pickedLive && pickedLive.seq === m.seq,
1632
- 'aria-setsize': rows.length, 'aria-posinset': start + i + 1,
1633
- tabIndex: -1,
1634
- className: 'mopsRow' + (pickedLive && pickedLive.seq === m.seq ? ' on' : '') + (m.shadowed ? ' shadowed' : ''),
1635
- style: { top: (start + i) * PANEL_ROW_H, height: PANEL_ROW_H },
1636
- onClick: () => { pick(m); if (listRef.current) listRef.current.focus() },
1637
- title: '#' + m.seq + ' ' + (m.role || '') + ' · ' + (m.snippet || ''),
1638
- 'aria-label': '#' + m.seq + ' ' + (m.role || '') + (m.shadowed ? ' ' + t('panel.shadowed') : '') + ' · ' + (m.snippet || '') + (m.time ? ' · ' + fmtClock(m.time) : ''),
1639
- },
1640
- React.createElement('span', { className: 'mopsSeq' }, '#' + m.seq),
1641
- React.createElement('span', { className: 'mopsRole' }, roleCode(m.role)),
1642
- React.createElement('span', { className: 'mopsSnippet' }, m.snippet || '—'),
1643
- React.createElement('span', { className: 'mopsClock' }, fmtClock(m.time)))))),
1644
- React.createElement('div', { className: 'mopsDetail' },
1645
- pickedLive
1646
- ? React.createElement(React.Fragment, null,
1647
- React.createElement('div', { className: 'mopsDetailMeta' },
1648
- React.createElement('span', null, '#' + pickedLive.seq),
1649
- React.createElement('span', null, pickedLive.role || ''),
1650
- pickedLive.shadowed ? React.createElement('span', null, t('panel.shadowed')) : null,
1651
- pickedLive.time ? React.createElement('span', null, fmtClock(pickedLive.time)) : null),
1652
- React.createElement('pre', { className: 'mopsDetailText' },
1653
- detailState === 'loading' ? t('panel.detailLoading') : (detail || pickedLive.snippet || '—')),
1654
- React.createElement('div', { className: 'mopsActions' },
1655
- React.createElement('button', {
1656
- type: 'button', className: 'mopsAction primary', disabled: !canAct || !!confirmAction,
1657
- ref: revertBtnRef,
1658
- onClick: () => setConfirmAction('revert'),
1659
- title: t('panel.revertHint'),
1660
- }, t('panel.revert') + (revertCount ? ' · ' + revertCount : '')),
1661
- React.createElement('button', {
1662
- type: 'button', className: 'mopsAction danger', disabled: !canAct || !!confirmAction,
1663
- ref: deleteOneBtnRef,
1664
- onClick: () => setConfirmAction('delete'), title: t('panel.deleteHint'),
1665
- }, t('panel.delete')),
1666
- // 0.12.0:编辑只对用户消息可用 —— 直接把原文交回编辑器。
1667
- // 无二次确认:它不改日志,只改草稿。
1668
- React.createElement('button', {
1669
- type: 'button', className: 'mopsAction', disabled: !canEdit,
1670
- title: pickedIsUser ? t('panel.editHint') : t('panel.branchUserOnly'),
1671
- onClick: () => startEdit(detail || pickedLive.snippet || ''),
1672
- }, t('panel.edit')),
1673
- // 分叉同样只对用户消息可用(AI 消息没有可回填的原文),
1674
- // 语义 = opencode 的 before:新会话不含此条,原文进新会话输入框。
1675
- React.createElement('button', {
1676
- type: 'button', className: 'mopsAction', disabled: !canFork || !!confirmAction,
1677
- onClick: () => runAction('branch'),
1678
- title: pickedIsUser ? t('panel.branchHint') : t('panel.branchUserOnly'),
1679
- }, t('panel.branch'))),
1680
- confirmAction
1681
- ? React.createElement('div', {
1682
- className: 'mopsActionConfirm', ref: actionConfirmRef, role: 'group', tabIndex: -1,
1683
- 'aria-labelledby': 'mops-action-confirm-title',
1684
- },
1685
- React.createElement('div', { className: 'mopsImpactTitle', id: 'mops-action-confirm-title' },
1686
- t(confirmAction === 'revert' ? 'panel.revertConfirmTitle' : 'panel.deleteConfirmTitle', { seq: String(pickedLive.seq) })),
1687
- React.createElement('div', { className: 'mopsImpact' },
1688
- confirmAction === 'revert'
1689
- ? t('panel.revertConfirmBody', {
1690
- start: String(pickedLive.seq), end: String(revertEnd),
1691
- n: String(revertCount), v: String(revertVisibleCount),
1692
- })
1693
- : t('panel.deleteConfirmBody')),
1694
- React.createElement('div', { className: 'mopsConfirmRow' },
1695
- React.createElement('button', {
1696
- type: 'button', className: 'mopsAction', onClick: cancelAction, disabled: !!busy,
1697
- }, t('panel.cancel')),
1698
- React.createElement('button', {
1699
- type: 'button', className: 'mopsAction danger',
1700
- onClick: () => runAction(confirmAction, true),
1701
- disabled: !!busy || !canAct,
1702
- }, busy === confirmAction ? t('panel.busy') : t(confirmAction === 'revert' ? 'panel.confirmRevert' : 'panel.confirmDeleteOne'))))
1703
- : null)
1704
- : React.createElement('div', { className: 'mopsDetailHint' }, t('panel.selectHint'))),
1705
- React.createElement('footer', { className: 'mopsPanelFoot' },
1706
- React.createElement('span', { className: 'mopsCount' },
1707
- t('panel.count', { n: String(totalCount), v: String(visibleCount), s: String(shadowedCount) })),
1708
- React.createElement('button', {
1709
- type: 'button', className: 'mopsDanger', ref: deleteBtnRef,
1710
- disabled: !!busy || !!deleteBlockedReason,
1711
- title: deleteBlockedReason || undefined,
1712
- onClick: () => {
1713
- setConfirmTitle('')
1714
- setDeleteError(null)
1715
- setConfirmAction(null)
1716
- setConfirmDelete(true)
1717
- },
1718
- }, t('panel.deleteSession'))),
1719
- confirmDelete
1720
- ? React.createElement('div', {
1721
- className: 'mopsConfirm', ref: confirmRef, role: 'alertdialog', 'aria-modal': 'true',
1722
- 'aria-labelledby': 'mops-delete-title', 'aria-describedby': 'mops-delete-hint mops-delete-impact',
1723
- tabIndex: -1,
1724
- },
1725
- React.createElement('h3', { id: 'mops-delete-title' }, t('panel.deleteSession')),
1726
- React.createElement('p', { id: 'mops-delete-hint' }, t('panel.deleteSessionHint')),
1727
- React.createElement('p', { className: 'mopsImpact', id: 'mops-delete-impact' },
1728
- t('panel.deleteSessionImpact', { n: String(totalCount) })),
1729
- target.running ? React.createElement('div', { className: 'mopsBanner warn', role: 'status' }, t('panel.running')) : null,
1730
- deleteError ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, deleteError) : null,
2011
+ ref: searchRef,
2012
+ className: 'mopsSearch',
2013
+ value: query,
2014
+ placeholder: t('panel.searchHint'),
2015
+ 'aria-label': t('panel.search'),
2016
+ onChange: e => {
2017
+ setQuery(e.target.value)
2018
+ clearPick()
2019
+ setScrollTop(0)
2020
+ if (listRef.current) listRef.current.scrollTop = 0
2021
+ },
2022
+ }),
2023
+ ),
2024
+ React.createElement(
2025
+ 'div',
2026
+ { className: 'mopsChips' },
2027
+ ['all', 'user', 'assistant', 'tool'].map(key =>
2028
+ React.createElement(
2029
+ 'button',
2030
+ {
2031
+ key,
2032
+ type: 'button',
2033
+ className: 'mopsChip' + (role === key ? ' on' : ''),
2034
+ onClick: () => {
2035
+ setRole(key)
2036
+ clearPick()
2037
+ setScrollTop(0)
2038
+ if (listRef.current) listRef.current.scrollTop = 0
2039
+ },
2040
+ },
2041
+ t('panel.' + key),
2042
+ ),
2043
+ ),
2044
+ React.createElement(
2045
+ 'label',
2046
+ { className: 'mopsToggle' },
1731
2047
  React.createElement('input', {
1732
- id: 'mops-delete-title-input', value: confirmTitle, autoFocus: true,
1733
- 'aria-label': t('panel.deleteSessionHint'),
1734
- 'aria-describedby': 'mops-delete-hint',
1735
- placeholder: expectedDeleteTitle || target.title || target.sessionId,
1736
- disabled: !!busy || target.running || !expectedDeleteTitle,
1737
- onChange: (e) => setConfirmTitle(e.target.value),
1738
- onKeyDown: (e) => {
1739
- if (e.key === 'Enter') {
1740
- e.preventDefault()
1741
- if (canConfirmDelete) deleteSession()
1742
- } else if (e.key === 'Escape') {
1743
- e.preventDefault()
1744
- e.stopPropagation()
1745
- closeConfirm()
1746
- }
2048
+ type: 'checkbox',
2049
+ checked: includeShadowed,
2050
+ onChange: e => {
2051
+ setIncludeShadowed(e.target.checked)
2052
+ clearPick()
2053
+ setScrollTop(0)
2054
+ if (listRef.current) listRef.current.scrollTop = 0
1747
2055
  },
1748
2056
  }),
1749
- React.createElement('div', { className: 'mopsConfirmRow' },
1750
- React.createElement('button', {
1751
- type: 'button', className: 'mopsAction',
1752
- onClick: closeConfirm, disabled: busy === 'session-delete',
1753
- }, t('panel.cancel')),
1754
- React.createElement('button', {
1755
- type: 'button', className: 'mopsAction danger',
1756
- disabled: !canConfirmDelete,
1757
- onClick: deleteSession,
1758
- }, busy === 'session-delete' ? t('panel.deleting') : t('panel.confirmDelete'))))
1759
- : null)
1760
- : React.createElement('div', { className: 'mopsList', style: { borderTop: 0 }, 'aria-busy': trashState === 'loading' ? 'true' : undefined },
2057
+ t('panel.includeShadowed'),
2058
+ ),
2059
+ ),
2060
+ React.createElement(
2061
+ 'div',
2062
+ {
2063
+ className: 'mopsList',
2064
+ ref: listRef,
2065
+ role: state === 'ready' && rows.length ? 'listbox' : 'region',
2066
+ tabIndex: state === 'ready' && rows.length ? 0 : -1,
2067
+ 'aria-label': t('panel.messages'),
2068
+ 'aria-busy': state === 'loading' || showSearchLoading ? 'true' : undefined,
2069
+ 'aria-activedescendant': state === 'ready' && activeRendered ? 'mops-opt-' + picked.seq : undefined,
2070
+ onKeyDown: handleListKeyDown,
2071
+ onScroll: e => setScrollTop(e.currentTarget.scrollTop),
2072
+ },
2073
+ state === 'loading' || state === 'idle'
2074
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
2075
+ : state === 'error'
2076
+ ? React.createElement(
2077
+ 'div',
2078
+ { className: 'mopsEmpty mopsErrorState', role: 'alert' },
2079
+ React.createElement('span', null, loadError || t('panel.loadFail')),
2080
+ React.createElement(
2081
+ 'button',
2082
+ {
2083
+ type: 'button',
2084
+ className: 'mopsAction',
2085
+ onClick: () => {
2086
+ loadMessages(false)
2087
+ setTimeout(() => {
2088
+ if (searchRef.current) searchRef.current.focus()
2089
+ }, 0)
2090
+ },
2091
+ },
2092
+ t('panel.retry'),
2093
+ ),
2094
+ )
2095
+ : rows.length === 0
2096
+ ? React.createElement(
2097
+ 'div',
2098
+ { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' },
2099
+ showSearchLoading ? t('panel.searching') : query.trim() ? t('panel.noMatch') : t('panel.empty'),
2100
+ )
2101
+ : React.createElement(
2102
+ 'div',
2103
+ { style: { height: rows.length * PANEL_ROW_H, position: 'relative' } },
2104
+ windowRows.map((m, i) =>
2105
+ React.createElement(
2106
+ 'div',
2107
+ {
2108
+ key: m.seq,
2109
+ id: 'mops-opt-' + m.seq,
2110
+ role: 'option',
2111
+ 'aria-selected': pickedLive && pickedLive.seq === m.seq,
2112
+ 'aria-setsize': rows.length,
2113
+ 'aria-posinset': start + i + 1,
2114
+ tabIndex: -1,
2115
+ className:
2116
+ 'mopsRow' + (pickedLive && pickedLive.seq === m.seq ? ' on' : '') + (m.shadowed ? ' shadowed' : ''),
2117
+ style: { top: (start + i) * PANEL_ROW_H, height: PANEL_ROW_H },
2118
+ onClick: () => {
2119
+ pick(m)
2120
+ if (listRef.current) listRef.current.focus()
2121
+ },
2122
+ title: '#' + m.seq + ' ' + (m.role || '') + ' · ' + (m.snippet || ''),
2123
+ 'aria-label':
2124
+ '#' +
2125
+ m.seq +
2126
+ ' ' +
2127
+ (m.role || '') +
2128
+ (m.shadowed ? ' ' + t('panel.shadowed') : '') +
2129
+ ' · ' +
2130
+ (m.snippet || '') +
2131
+ (m.time ? ' · ' + fmtClock(m.time) : ''),
2132
+ },
2133
+ React.createElement('span', { className: 'mopsSeq' }, '#' + m.seq),
2134
+ React.createElement('span', { className: 'mopsRole' }, roleCode(m.role)),
2135
+ React.createElement('span', { className: 'mopsSnippet' }, m.snippet || '—'),
2136
+ React.createElement('span', { className: 'mopsClock' }, fmtClock(m.time)),
2137
+ ),
2138
+ ),
2139
+ ),
2140
+ ),
2141
+ React.createElement(
2142
+ 'div',
2143
+ { className: 'mopsDetail' },
2144
+ pickedLive
2145
+ ? React.createElement(
2146
+ React.Fragment,
2147
+ null,
2148
+ React.createElement(
2149
+ 'div',
2150
+ { className: 'mopsDetailMeta' },
2151
+ React.createElement('span', null, '#' + pickedLive.seq),
2152
+ React.createElement('span', null, pickedLive.role || ''),
2153
+ pickedLive.shadowed ? React.createElement('span', null, t('panel.shadowed')) : null,
2154
+ pickedLive.time ? React.createElement('span', null, fmtClock(pickedLive.time)) : null,
2155
+ ),
2156
+ React.createElement(
2157
+ 'pre',
2158
+ { className: 'mopsDetailText' },
2159
+ detailState === 'loading' ? t('panel.detailLoading') : detail || pickedLive.snippet || '—',
2160
+ ),
2161
+ React.createElement(
2162
+ 'div',
2163
+ { className: 'mopsActions' },
2164
+ React.createElement(
2165
+ 'button',
2166
+ {
2167
+ type: 'button',
2168
+ className: 'mopsAction primary',
2169
+ disabled: !canAct || !!confirmAction,
2170
+ ref: revertBtnRef,
2171
+ onClick: () => setConfirmAction('revert'),
2172
+ title: t('panel.revertHint'),
2173
+ },
2174
+ t('panel.revert') + (revertCount ? ' · ' + revertCount : ''),
2175
+ ),
2176
+ React.createElement(
2177
+ 'button',
2178
+ {
2179
+ type: 'button',
2180
+ className: 'mopsAction danger',
2181
+ disabled: !canAct || !!confirmAction,
2182
+ ref: deleteOneBtnRef,
2183
+ onClick: () => setConfirmAction('delete'),
2184
+ title: t('panel.deleteHint'),
2185
+ },
2186
+ t('panel.delete'),
2187
+ ),
2188
+ // 0.12.0:编辑只对用户消息可用 —— 直接把原文交回编辑器。
2189
+ // 无二次确认:它不改日志,只改草稿。
2190
+ React.createElement(
2191
+ 'button',
2192
+ {
2193
+ type: 'button',
2194
+ className: 'mopsAction',
2195
+ disabled: !canEdit || !editTextReady,
2196
+ title: !pickedIsUser
2197
+ ? t('panel.branchUserOnly')
2198
+ : !editTextReady
2199
+ ? t('panel.editNotReady')
2200
+ : t('panel.editHint'),
2201
+ onClick: () => startEdit(detail),
2202
+ },
2203
+ t('panel.edit'),
2204
+ ),
2205
+ // 分叉同样只对用户消息可用(AI 消息没有可回填的原文),
2206
+ // 语义 = opencode 的 before:新会话不含此条,原文进新会话输入框。
2207
+ React.createElement(
2208
+ 'button',
2209
+ {
2210
+ type: 'button',
2211
+ className: 'mopsAction',
2212
+ disabled: !canFork || !!confirmAction,
2213
+ onClick: () => runAction('branch'),
2214
+ title: pickedIsUser ? t('panel.branchHint') : t('panel.branchUserOnly'),
2215
+ },
2216
+ t('panel.branch'),
2217
+ ),
2218
+ ),
2219
+ confirmAction
2220
+ ? React.createElement(
2221
+ 'div',
2222
+ {
2223
+ className: 'mopsActionConfirm',
2224
+ ref: actionConfirmRef,
2225
+ role: 'group',
2226
+ tabIndex: -1,
2227
+ 'aria-labelledby': 'mops-action-confirm-title',
2228
+ },
2229
+ React.createElement(
2230
+ 'div',
2231
+ { className: 'mopsImpactTitle', id: 'mops-action-confirm-title' },
2232
+ t(confirmAction === 'revert' ? 'panel.revertConfirmTitle' : 'panel.deleteConfirmTitle', {
2233
+ seq: String(pickedLive.seq),
2234
+ }),
2235
+ ),
2236
+ React.createElement(
2237
+ 'div',
2238
+ { className: 'mopsImpact' },
2239
+ confirmAction === 'revert'
2240
+ ? t('panel.revertConfirmBody', {
2241
+ start: String(pickedLive.seq),
2242
+ end: String(revertEnd),
2243
+ n: String(revertCount),
2244
+ v: String(revertVisibleCount),
2245
+ })
2246
+ : t('panel.deleteConfirmBody'),
2247
+ ),
2248
+ React.createElement(
2249
+ 'div',
2250
+ { className: 'mopsConfirmRow' },
2251
+ React.createElement(
2252
+ 'button',
2253
+ {
2254
+ type: 'button',
2255
+ className: 'mopsAction',
2256
+ onClick: cancelAction,
2257
+ disabled: !!busy,
2258
+ },
2259
+ t('panel.cancel'),
2260
+ ),
2261
+ React.createElement(
2262
+ 'button',
2263
+ {
2264
+ type: 'button',
2265
+ className: 'mopsAction danger',
2266
+ onClick: () => runAction(confirmAction, true),
2267
+ disabled: !!busy || !canAct,
2268
+ },
2269
+ busy === confirmAction
2270
+ ? t('panel.busy')
2271
+ : t(confirmAction === 'revert' ? 'panel.confirmRevert' : 'panel.confirmDeleteOne'),
2272
+ ),
2273
+ ),
2274
+ )
2275
+ : null,
2276
+ )
2277
+ : React.createElement('div', { className: 'mopsDetailHint' }, t('panel.selectHint')),
2278
+ ),
2279
+ React.createElement(
2280
+ 'footer',
2281
+ { className: 'mopsPanelFoot' },
2282
+ React.createElement(
2283
+ 'span',
2284
+ { className: 'mopsCount' },
2285
+ t('panel.count', { n: String(totalCount), v: String(visibleCount), s: String(shadowedCount) }),
2286
+ ),
2287
+ React.createElement(
2288
+ 'button',
2289
+ {
2290
+ type: 'button',
2291
+ className: 'mopsDanger',
2292
+ ref: deleteBtnRef,
2293
+ disabled: !!busy || !!deleteBlockedReason,
2294
+ title: deleteBlockedReason || undefined,
2295
+ onClick: () => {
2296
+ setConfirmTitle('')
2297
+ setDeleteError(null)
2298
+ setConfirmAction(null)
2299
+ setConfirmDelete(true)
2300
+ },
2301
+ },
2302
+ t('panel.deleteSession'),
2303
+ ),
2304
+ ),
2305
+ confirmDelete
2306
+ ? React.createElement(
2307
+ 'div',
2308
+ {
2309
+ className: 'mopsConfirm',
2310
+ ref: confirmRef,
2311
+ role: 'alertdialog',
2312
+ 'aria-modal': 'true',
2313
+ 'aria-labelledby': 'mops-delete-title',
2314
+ 'aria-describedby': 'mops-delete-hint mops-delete-impact',
2315
+ tabIndex: -1,
2316
+ },
2317
+ React.createElement('h3', { id: 'mops-delete-title' }, t('panel.deleteSession')),
2318
+ React.createElement('p', { id: 'mops-delete-hint' }, t('panel.deleteSessionHint')),
2319
+ React.createElement(
2320
+ 'p',
2321
+ { className: 'mopsImpact', id: 'mops-delete-impact' },
2322
+ t('panel.deleteSessionImpact', { n: String(totalCount) }),
2323
+ ),
2324
+ target.running
2325
+ ? React.createElement('div', { className: 'mopsBanner warn', role: 'status' }, t('panel.running'))
2326
+ : null,
2327
+ deleteError ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, deleteError) : null,
2328
+ React.createElement('input', {
2329
+ id: 'mops-delete-title-input',
2330
+ value: confirmTitle,
2331
+ autoFocus: true,
2332
+ 'aria-label': t('panel.deleteSessionHint'),
2333
+ 'aria-describedby': 'mops-delete-hint',
2334
+ placeholder: expectedDeleteTitle || target.title || target.sessionId,
2335
+ disabled: !!busy || target.running || !expectedDeleteTitle,
2336
+ onChange: e => setConfirmTitle(e.target.value),
2337
+ onKeyDown: e => {
2338
+ if (e.key === 'Enter') {
2339
+ e.preventDefault()
2340
+ if (canConfirmDelete) deleteSession()
2341
+ } else if (e.key === 'Escape') {
2342
+ e.preventDefault()
2343
+ e.stopPropagation()
2344
+ closeConfirm()
2345
+ }
2346
+ },
2347
+ }),
2348
+ React.createElement(
2349
+ 'div',
2350
+ { className: 'mopsConfirmRow' },
2351
+ React.createElement(
2352
+ 'button',
2353
+ {
2354
+ type: 'button',
2355
+ className: 'mopsAction',
2356
+ onClick: closeConfirm,
2357
+ disabled: busy === 'session-delete',
2358
+ },
2359
+ t('panel.cancel'),
2360
+ ),
2361
+ React.createElement(
2362
+ 'button',
2363
+ {
2364
+ type: 'button',
2365
+ className: 'mopsAction danger',
2366
+ disabled: !canConfirmDelete,
2367
+ onClick: deleteSession,
2368
+ },
2369
+ busy === 'session-delete' ? t('panel.deleting') : t('panel.confirmDelete'),
2370
+ ),
2371
+ ),
2372
+ )
2373
+ : null,
2374
+ )
2375
+ : React.createElement(
2376
+ 'div',
2377
+ { className: 'mopsList', style: { borderTop: 0 }, 'aria-busy': trashState === 'loading' ? 'true' : undefined },
1761
2378
  trashState === 'loading' || trashState === 'idle'
1762
2379
  ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1763
2380
  : trashState === 'error'
1764
- ? React.createElement('div', { className: 'mopsEmpty mopsErrorState', role: 'alert' },
2381
+ ? React.createElement(
2382
+ 'div',
2383
+ { className: 'mopsEmpty mopsErrorState', role: 'alert' },
1765
2384
  React.createElement('span', null, trashError || t('panel.loadFail')),
1766
- React.createElement('button', {
1767
- type: 'button', className: 'mopsAction',
1768
- onClick: () => { loadTrash(); setTimeout(() => { if (panelRef.current) panelRef.current.focus() }, 0) },
1769
- }, t('panel.retry')))
2385
+ React.createElement(
2386
+ 'button',
2387
+ {
2388
+ type: 'button',
2389
+ className: 'mopsAction',
2390
+ onClick: () => {
2391
+ loadTrash()
2392
+ setTimeout(() => {
2393
+ if (panelRef.current) panelRef.current.focus()
2394
+ }, 0)
2395
+ },
2396
+ },
2397
+ t('panel.retry'),
2398
+ ),
2399
+ )
1770
2400
  : trash.length === 0
1771
2401
  ? React.createElement('div', { className: 'mopsEmpty' }, t('panel.trashEmpty'))
1772
- : trash.map((item) => React.createElement('div', { className: 'mopsTrashItem', key: item.trashId },
1773
- React.createElement('div', { className: 'mopsTrashMain' },
1774
- React.createElement('div', { className: 'mopsTrashTitle' }, item.title || t('panel.untitled')),
1775
- React.createElement('div', { className: 'mopsTrashMeta' },
1776
- item.sessionId + (item.expiresAt ? ' · ' + t('panel.expires') + ' ' + new Date(item.expiresAt).toLocaleDateString() : ''))),
1777
- React.createElement('button', {
1778
- type: 'button', className: 'mopsAction', disabled: !!busy,
1779
- onClick: () => restoreEntry(item.trashId),
1780
- }, busy === 'restore:' + item.trashId ? t('panel.busy') : t('panel.restore')),
1781
- React.createElement('button', {
1782
- type: 'button', className: 'mopsAction danger', disabled: !!busy,
1783
- onClick: () => purgeEntry(item.trashId),
1784
- }, busy === 'purge:' + item.trashId ? t('panel.busy') : (purgeId === item.trashId ? t('panel.purgeConfirm') : t('panel.purge'))))))))
2402
+ : trash.map(item =>
2403
+ React.createElement(
2404
+ 'div',
2405
+ { className: 'mopsTrashItem', key: item.trashId },
2406
+ React.createElement(
2407
+ 'div',
2408
+ { className: 'mopsTrashMain' },
2409
+ React.createElement('div', { className: 'mopsTrashTitle' }, item.title || t('panel.untitled')),
2410
+ React.createElement(
2411
+ 'div',
2412
+ { className: 'mopsTrashMeta' },
2413
+ item.sessionId +
2414
+ (item.expiresAt ? ' · ' + t('panel.expires') + ' ' + new Date(item.expiresAt).toLocaleDateString() : ''),
2415
+ ),
2416
+ ),
2417
+ React.createElement(
2418
+ 'button',
2419
+ {
2420
+ type: 'button',
2421
+ className: 'mopsAction',
2422
+ disabled: !!busy,
2423
+ onClick: () => restoreEntry(item.trashId),
2424
+ },
2425
+ busy === 'restore:' + item.trashId ? t('panel.busy') : t('panel.restore'),
2426
+ ),
2427
+ React.createElement(
2428
+ 'button',
2429
+ {
2430
+ type: 'button',
2431
+ className: 'mopsAction danger',
2432
+ disabled: !!busy,
2433
+ onClick: () => purgeEntry(item.trashId),
2434
+ },
2435
+ busy === 'purge:' + item.trashId
2436
+ ? t('panel.busy')
2437
+ : purgeId === item.trashId
2438
+ ? t('panel.purgeConfirm')
2439
+ : t('panel.purge'),
2440
+ ),
2441
+ ),
2442
+ ),
2443
+ ),
2444
+ ),
2445
+ )
1785
2446
  }
1786
2447
 
1787
2448
  // --- 头部按钮 ---------------------------------------------------------------
@@ -1832,24 +2493,41 @@ window.__ModuleLoader__.load({
1832
2493
  * 为什么不能靠 aria-label:官方文案有 8 种语言(zh/en/ja/es/fr/de/ru/pt),
1833
2494
  * 逐个匹配等于把 i18n 表抄进来。也不能靠 class:CSS Modules 会哈希前缀
1834
2495
  * (实测 0.2.0-rc.2 是 `xzv4MW_`,0.2.1 起变过)。
1835
- * 唯一稳定的是**图标几何**:官方 `IconBranchOutline16` 的 path d 是常量
1836
- * (packages/client/ui-primitives/src/icons/index.tsx:149)。
1837
- * 我们自己的分叉按钮复用同一 path,所以必须显式排除。
2496
+ *
2497
+ * ⚠️ 也不能靠 `<path d="…">`(0.12.0 的错误做法,0.13.1 修):0.2.2-alpha.2 的
2498
+ * 图标已改为 **sprite 复用**,官方组件长这样(见已安装 app bundle 的工厂函数):
2499
+ *
2500
+ * <svg data-icon="dsw-icon-branch-outline-regular" aria-hidden="true">
2501
+ * <use href="#dsw-icon-branch-outline-regular"/>
2502
+ * </svg>
2503
+ *
2504
+ * DOM 里**根本没有 `<path>`**,`M13.0762…` 在整个已安装 dsh 里 0 次命中。
2505
+ * 唯一稳定的是 `data-icon` 的 id:`dsw-icon-${name}-${size}`(工厂 `Qv`),
2506
+ * name 来自 ui-primitives 的图标表,属契约级常量。
2507
+ *
2508
+ * 我们自己的分叉按钮也故意用同一图标,所以必须按 class 显式排除。
1838
2509
  *
1839
2510
  * @param btn - 候选按钮(任意元素;非 button 的宿主节点返回 false)
1840
2511
  * @returns 是否官方 branch 按钮
1841
2512
  */
1842
- const HOST_BRANCH_D_PREFIX = 'M13.0762 1.37207'
2513
+ const HOST_BRANCH_ICON_ID = 'dsw-icon-branch-outline-regular'
1843
2514
  const HOST_BRANCH_CLASS = 'mopsUserFork'
1844
2515
  function isHostBranchButton(btn) {
1845
2516
  if (!btn || typeof btn.querySelector !== 'function') return false
1846
2517
  const cls = String((btn.classList && btn.classList.value) || btn.className || '')
1847
2518
  if (cls.split(/\s+/).includes(HOST_BRANCH_CLASS)) return false
2519
+ // 首选 sprite 形态:<svg data-icon="dsw-icon-branch-outline-regular">
2520
+ const svg = btn.querySelector('svg')
2521
+ if (svg && svg.getAttribute('data-icon') === HOST_BRANCH_ICON_ID) return true
2522
+ // 兼容旧宿主的内联 path 形态(0.2.0-rc.x):仍接受官方几何前缀
1848
2523
  const path = btn.querySelector('svg path')
1849
2524
  const d = path ? path.getAttribute('d') || '' : ''
1850
2525
  return d.startsWith(HOST_BRANCH_D_PREFIX)
1851
2526
  }
1852
2527
 
2528
+ /** 旧宿主的内联 path 几何前缀(仅作兼容回退,不是主判据)。 */
2529
+ const HOST_BRANCH_D_PREFIX = 'M13.0762 1.37207'
2530
+
1853
2531
  /**
1854
2532
  * 把文本预置成某个会话的草稿(新会话刚 fork 出来时输入框是空的)。
1855
2533
  *
@@ -1870,6 +2548,26 @@ window.__ModuleLoader__.load({
1870
2548
  }
1871
2549
  }
1872
2550
 
2551
+ /**
2552
+ * 读回某会话的已保存草稿文本(宿主同一存储键)。
2553
+ * @param sessionId - 会话 id
2554
+ * @returns 文本;存储里没有该会话、或格式不可解析时返回 null
2555
+ */
2556
+ function readSessionDraft(sessionId) {
2557
+ try {
2558
+ if (!sessionId || typeof localStorage === 'undefined') return null
2559
+ const raw = localStorage.getItem(FORK_SESSION_STORAGE_PREFIX + sessionId)
2560
+ if (raw == null) return null
2561
+ const parsed = JSON.parse(raw)
2562
+ const draft = parsed && typeof parsed === 'object' ? parsed.draft : undefined
2563
+ if (typeof draft === 'string') return draft
2564
+ if (draft && typeof draft === 'object' && typeof draft.text === 'string') return draft.text
2565
+ return null
2566
+ } catch {
2567
+ return null
2568
+ }
2569
+ }
2570
+
1873
2571
  /** 打开会话(宿主唯一通道)。childId 需要 `session-` 前缀才不会抛 unknown session。 */
1874
2572
  function openSessionById(sessionId) {
1875
2573
  try {
@@ -1907,27 +2605,38 @@ window.__ModuleLoader__.load({
1907
2605
  try {
1908
2606
  const dk = window.__dshDevkit
1909
2607
  if (dk && typeof dk.toast === 'function') dk.toast(msg, { kind: kind || 'ok' })
1910
- } catch { /* toast 缺席不阻断成功反馈 */ }
2608
+ } catch {
2609
+ /* toast 缺席不阻断成功反馈 */
2610
+ }
1911
2611
  }
1912
2612
 
1913
2613
  function OpsButton(props) {
1914
2614
  const { sessionId, useSessions } = props
1915
2615
  const t = (props && props.t) || __t
1916
2616
  useLocaleRevision()
1917
- const sessions = useSessions ? useSessions((s) => s) : undefined
2617
+ const sessions = useSessions ? useSessions(s => s) : undefined
1918
2618
  const summary = sessions && sessions.byId ? sessions.byId[sessionId] : undefined
1919
2619
  const running = summary ? summary.running === true : false
1920
2620
 
1921
2621
  const openDialog = useCallback(() => {
1922
- window.dispatchEvent(new CustomEvent(EVENT, {
1923
- detail: { sessionId, title: summary && summary.title ? summary.title : null, running },
1924
- }))
2622
+ window.dispatchEvent(
2623
+ new CustomEvent(EVENT, {
2624
+ detail: { sessionId, title: summary && summary.title ? summary.title : null, running },
2625
+ }),
2626
+ )
1925
2627
  }, [sessionId, summary, running])
1926
2628
 
1927
- return React.createElement('button', {
1928
- type: 'button', title: t('button.title'), 'aria-label': t('button.title'),
1929
- style: btnStyle, onClick: openDialog,
1930
- }, React.createElement(BranchIcon))
2629
+ return React.createElement(
2630
+ 'button',
2631
+ {
2632
+ type: 'button',
2633
+ title: t('button.title'),
2634
+ 'aria-label': t('button.title'),
2635
+ style: btnStyle,
2636
+ onClick: openDialog,
2637
+ },
2638
+ React.createElement(BranchIcon),
2639
+ )
1931
2640
  }
1932
2641
 
1933
2642
  // 官方图标适配:0.2.0 primitives 的 IconClock 与原生操作行同款;
@@ -1938,22 +2647,38 @@ window.__ModuleLoader__.load({
1938
2647
  try {
1939
2648
  const P = require('@deepseek-ai/dsh-client-ui-primitives')
1940
2649
  IconClock = P && P.IconClockOutlineRegular
1941
- } catch { /* fallback below */ }
1942
- if (!IconClock) IconClock = function ClockFallback() {
1943
- // 官方 IconClockOutlineArtwork 1:1 路径( Regular = 1px stroke)
1944
- return React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, stroke: 'currentColor', strokeWidth: 1 },
1945
- React.createElement('path', { d: 'M8 14C11.3137 14 14 11.3137 14 8C14 4.68629 11.3137 2 8 2C4.68629 2 2 4.68629 2 8C2 11.3137 4.68629 14 8 14Z' }),
1946
- React.createElement('path', { d: 'M8 4.31V8.46L11 10.08' }))
2650
+ } catch {
2651
+ /* fallback below */
1947
2652
  }
2653
+ if (!IconClock)
2654
+ IconClock = function ClockFallback() {
2655
+ // 官方 IconClockOutlineArtwork 1:1 路径( Regular = 1px stroke)
2656
+ return React.createElement(
2657
+ 'svg',
2658
+ { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, stroke: 'currentColor', strokeWidth: 1 },
2659
+ React.createElement('path', {
2660
+ d: 'M8 14C11.3137 14 14 11.3137 14 8C14 4.68629 11.3137 2 8 2C4.68629 2 2 4.68629 2 8C2 11.3137 4.68629 14 8 14Z',
2661
+ }),
2662
+ React.createElement('path', { d: 'M8 4.31V8.46L11 10.08' }),
2663
+ )
2664
+ }
1948
2665
  var IconQuote = null
1949
2666
  try {
1950
2667
  const P2 = require('@deepseek-ai/dsh-client-ui-primitives')
1951
2668
  IconQuote = P2 && (P2.IconChatOutlineRegular || P2.IconCopyOutlineRegular)
1952
- } catch { /* fallback below */ }
1953
- if (!IconQuote) IconQuote = function QuoteFallback() {
1954
- return React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, stroke: 'currentColor', strokeWidth: 1 },
1955
- React.createElement('path', { d: 'M3 6.5A3.5 3.5 0 0 1 6.5 3H7v1.5h-.5A2 2 0 0 0 4.5 6.5V7H7v3.5H3V6.5ZM9 6.5A3.5 3.5 0 0 1 12.5 3H13v1.5h-.5A2 2 0 0 0 10.5 6.5V7H13v3.5H9V6.5Z' }))
2669
+ } catch {
2670
+ /* fallback below */
1956
2671
  }
2672
+ if (!IconQuote)
2673
+ IconQuote = function QuoteFallback() {
2674
+ return React.createElement(
2675
+ 'svg',
2676
+ { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true, stroke: 'currentColor', strokeWidth: 1 },
2677
+ React.createElement('path', {
2678
+ d: 'M3 6.5A3.5 3.5 0 0 1 6.5 3H7v1.5h-.5A2 2 0 0 0 4.5 6.5V7H7v3.5H3V6.5ZM9 6.5A3.5 3.5 0 0 1 12.5 3H13v1.5h-.5A2 2 0 0 0 10.5 6.5V7H13v3.5H9V6.5Z',
2679
+ }),
2680
+ )
2681
+ }
1957
2682
 
1958
2683
  // --- 0.3.0 assistant-actions 官方槽:每条 AI 消息旁的原生回撤按钮 ------------
1959
2684
  // 契约(dsh-cordis-client-runner):scope session,条目组件收 { messageId } +
@@ -1967,7 +2692,7 @@ window.__ModuleLoader__.load({
1967
2692
  const t = (props && props.t) || __t
1968
2693
  useLocaleRevision()
1969
2694
  if (inputActions && typeof inputActions.setDraft === 'function') __inputActions = inputActions
1970
- const sessions = useSessions ? useSessions((s) => s) : undefined
2695
+ const sessions = useSessions ? useSessions(s => s) : undefined
1971
2696
  const summary = sessions && sessions.byId ? sessions.byId[sessionId] : undefined
1972
2697
  const running = summary ? summary.running === true : false
1973
2698
  const [seq, setSeq] = React.useState(null)
@@ -1977,7 +2702,7 @@ window.__ModuleLoader__.load({
1977
2702
  // 没有回撤/引用按钮」—— 已经挂载的槽位 effect 不会因缓存被换而重跑。
1978
2703
  const [idxRev, setIdxRev] = React.useState(0)
1979
2704
  React.useEffect(() => {
1980
- const onIdx = () => setIdxRev((v) => v + 1)
2705
+ const onIdx = () => setIdxRev(v => v + 1)
1981
2706
  window.addEventListener(SEQ_INDEX_EVENT, onIdx)
1982
2707
  return () => window.removeEventListener(SEQ_INDEX_EVENT, onIdx)
1983
2708
  }, [])
@@ -1986,31 +2711,35 @@ window.__ModuleLoader__.load({
1986
2711
  let alive = true
1987
2712
  let retried = false
1988
2713
  const load = () => {
1989
- const p = fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId))
1990
- .then((data) => {
1991
- const index = new Map()
1992
- const full = new Map()
1993
- for (const m of (data && data.messages) || []) {
1994
- // 0.5.2(P2):同 id 取**最早** seq——与服务端 buildSeqIndex 口径一致
1995
- // (重试链取最早可见节点;此前内联 set 覆盖=取最大,双实现分裂)
1996
- if (m && m.id != null && !index.has(String(m.id))) index.set(String(m.id), m.seq)
1997
- if (m && m.id != null && m.fullText) full.set(String(m.id), m.fullText)
1998
- }
1999
- __seqIndexCache.set(sessionId, index)
2000
- __fullTextCache.set(sessionId, full)
2001
- return index
2002
- })
2714
+ const p = fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId)).then(data => {
2715
+ const index = new Map()
2716
+ const full = new Map()
2717
+ for (const m of (data && data.messages) || []) {
2718
+ // 0.5.2(P2):同 id 取**最早** seq——与服务端 buildSeqIndex 口径一致
2719
+ // (重试链取最早可见节点;此前内联 set 覆盖=取最大,双实现分裂)
2720
+ if (m && m.id != null && !index.has(String(m.id))) index.set(String(m.id), m.seq)
2721
+ if (m && m.id != null && m.fullText) full.set(String(m.id), m.fullText)
2722
+ }
2723
+ __seqIndexCache.set(sessionId, index)
2724
+ __fullTextCache.set(sessionId, full)
2725
+ return index
2726
+ })
2003
2727
  __seqIndexCache.set(sessionId, p)
2004
2728
  // 0.5.2(P2):失败必须清缓存——否则 rejected promise 被永久缓存,
2005
2729
  // 该会话按钮/dock 到刷新页面为止全部失效
2006
2730
  // 0.9.7:只在缓存里还是**我们这条** promise 时才删(syncSeqIndex 可能已换掉)
2007
- p.catch(() => { if (__seqIndexCache.get(sessionId) === p) __seqIndexCache.delete(sessionId) })
2731
+ p.catch(() => {
2732
+ if (__seqIndexCache.get(sessionId) === p) __seqIndexCache.delete(sessionId)
2733
+ })
2008
2734
  return p
2009
2735
  }
2010
- const resolve = (index) => {
2736
+ const resolve = index => {
2011
2737
  if (!alive) return
2012
2738
  const hit = index && index.get(String(messageId))
2013
- if (typeof hit === 'number') { setSeq(hit); return }
2739
+ if (typeof hit === 'number') {
2740
+ setSeq(hit)
2741
+ return
2742
+ }
2014
2743
  // 0.9.7(P4):索引里没有这个 messageId = 会话已增长(或索引过期)。
2015
2744
  // 旧实现这里**什么都不做**,`seq` 永远是 null → 组件 return null →
2016
2745
  // 按钮再也不渲染。现在失效并重拉一次(retried 保证不自旋);
@@ -2019,13 +2748,20 @@ window.__ModuleLoader__.load({
2019
2748
  retried = true
2020
2749
  __seqIndexCache.delete(sessionId)
2021
2750
  __fullTextCache.delete(sessionId)
2022
- load().then(resolve).catch(() => {})
2751
+ load()
2752
+ .then(resolve)
2753
+ .catch(() => {})
2023
2754
  }
2024
2755
  const cached = __seqIndexCache.get(sessionId)
2025
2756
  if (cached && typeof cached.then === 'function') cached.then(resolve).catch(() => {})
2026
2757
  else if (cached) resolve(cached)
2027
- else load().then(resolve).catch(() => {})
2028
- return () => { alive = false }
2758
+ else
2759
+ load()
2760
+ .then(resolve)
2761
+ .catch(() => {})
2762
+ return () => {
2763
+ alive = false
2764
+ }
2029
2765
  }, [messageId, sessionId, idxRev])
2030
2766
 
2031
2767
  // 原文(引用用):seq 解析后按需取全文
@@ -2033,14 +2769,16 @@ window.__ModuleLoader__.load({
2033
2769
  if (seq == null || !sessionId) return
2034
2770
  let alive = true
2035
2771
  const cached = __fullTextCache.get(sessionId)
2036
- const resolve = (full) => {
2772
+ const resolve = full => {
2037
2773
  if (!alive) return
2038
2774
  const hit = full && full.get(String(messageId))
2039
2775
  if (typeof hit === 'string') setFullText(hit)
2040
2776
  }
2041
2777
  if (cached && typeof cached.then === 'function') cached.then(resolve).catch(() => {})
2042
2778
  else if (cached) resolve(cached)
2043
- return () => { alive = false }
2779
+ return () => {
2780
+ alive = false
2781
+ }
2044
2782
  }, [seq, messageId, sessionId])
2045
2783
 
2046
2784
  // 0.5.0 回撤后的视图刷新:openSession(reveal) 重建会话视图 → 遮蔽立即呈现。
@@ -2051,7 +2789,9 @@ window.__ModuleLoader__.load({
2051
2789
  __uiWorkspace.openSession(sessionId)
2052
2790
  return true
2053
2791
  }
2054
- } catch { /* fallthrough */ }
2792
+ } catch {
2793
+ /* fallthrough */
2794
+ }
2055
2795
  return false
2056
2796
  }
2057
2797
 
@@ -2061,14 +2801,21 @@ window.__ModuleLoader__.load({
2061
2801
  // 0.5.2(P2):Promise.resolve 包裹——fetch/stringify 同步抛出也转为
2062
2802
  // rejection 落进 finally,busy 永不卡死
2063
2803
  Promise.resolve()
2064
- .then(() => fetch('/api/message-ops/revert', {
2065
- method: 'POST', headers: { 'content-type': 'application/json' },
2066
- body: JSON.stringify({ sessionId, seq }),
2067
- }))
2068
- .then(async (res) => {
2804
+ .then(() =>
2805
+ fetch('/api/message-ops/revert', {
2806
+ method: 'POST',
2807
+ headers: { 'content-type': 'application/json' },
2808
+ body: JSON.stringify({ sessionId, seq }),
2809
+ }),
2810
+ )
2811
+ .then(async res => {
2069
2812
  let data = {}
2070
- try { data = await res.json() } catch { /* keep {} */ }
2071
- if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
2813
+ try {
2814
+ data = await res.json()
2815
+ } catch {
2816
+ /* keep {} */
2817
+ }
2818
+ if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
2072
2819
  notifyDone(t('done.revert'))
2073
2820
  // 0.9.6:回填被删掉的那句用户原文(边界是 AI 消息时取它之前那条用户消息)。
2074
2821
  // 此前这个入口完全不回填 —— 表现就是「回滚成功但消息框空着」。
@@ -2076,7 +2823,7 @@ window.__ModuleLoader__.load({
2076
2823
  revealSession()
2077
2824
  emitChanged()
2078
2825
  })
2079
- .catch((reason) => {
2826
+ .catch(reason => {
2080
2827
  notifyDone(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
2081
2828
  })
2082
2829
  .finally(() => setBusy(null))
@@ -2090,17 +2837,27 @@ window.__ModuleLoader__.load({
2090
2837
  return
2091
2838
  }
2092
2839
  const span = inputActions.captureInsertion()
2093
- const insertQuote = (text) => {
2094
- if (text == null || text === '') { notifyDone(t('quote.unavailable'), 'warn'); return }
2095
- const quoted = text.split('\n').map((l) => '> ' + l).join('\n') + '\n\n'
2840
+ const insertQuote = text => {
2841
+ if (text == null || text === '') {
2842
+ notifyDone(t('quote.unavailable'), 'warn')
2843
+ return
2844
+ }
2845
+ const quoted =
2846
+ text
2847
+ .split('\n')
2848
+ .map(l => '> ' + l)
2849
+ .join('\n') + '\n\n'
2096
2850
  const ok = inputActions.insertText(quoted, span)
2097
2851
  notifyDone(ok ? t('quote.done') : t('quote.unavailable'), ok ? 'ok' : 'warn')
2098
2852
  }
2099
2853
  // assistant 消息 fullText 恒 null(列表不携带)→ 按 seq 向服务端取单条全文
2100
- if (fullText != null && fullText !== '') { insertQuote(fullText); return }
2854
+ if (fullText != null && fullText !== '') {
2855
+ insertQuote(fullText)
2856
+ return
2857
+ }
2101
2858
  fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(sessionId) + '&seq=' + encodeURIComponent(seq))
2102
- .then((r) => (r.ok ? r.json() : null))
2103
- .then((d) => insertQuote(d && d.ok && typeof d.text === 'string' ? d.text : null))
2859
+ .then(r => (r.ok ? r.json() : null))
2860
+ .then(d => insertQuote(d && d.ok && typeof d.text === 'string' ? d.text : null))
2104
2861
  .catch(() => insertQuote(null))
2105
2862
  } catch (e) {
2106
2863
  notifyDone(t('errorPrefix') + (e && e.message ? e.message : String(e)), 'error')
@@ -2108,16 +2865,35 @@ window.__ModuleLoader__.load({
2108
2865
  }
2109
2866
 
2110
2867
  if (seq == null) return null
2111
- const act = (icon, label, mode, onClick, disabled) => React.createElement('button', {
2112
- type: 'button', title: running && mode === 'revert' ? t('dialog.runningWarn') : label,
2113
- 'aria-label': label, disabled: !!disabled,
2114
- style: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
2115
- minWidth: 44, minHeight: 44, padding: 0, border: 'none', background: 'transparent',
2116
- color: 'inherit', opacity: busy && busy !== mode ? 0.4 : running && mode === 'revert' ? 0.35 : 0.72,
2117
- cursor: disabled ? 'default' : 'pointer', borderRadius: 6 },
2118
- onClick,
2119
- }, icon)
2120
- return React.createElement('span', { style: { display: 'inline-flex', gap: 0 } },
2868
+ const act = (icon, label, mode, onClick, disabled) =>
2869
+ React.createElement(
2870
+ 'button',
2871
+ {
2872
+ type: 'button',
2873
+ title: running && mode === 'revert' ? t('dialog.runningWarn') : label,
2874
+ 'aria-label': label,
2875
+ disabled: !!disabled,
2876
+ style: {
2877
+ display: 'inline-flex',
2878
+ alignItems: 'center',
2879
+ justifyContent: 'center',
2880
+ minWidth: 44,
2881
+ minHeight: 44,
2882
+ padding: 0,
2883
+ border: 'none',
2884
+ background: 'transparent',
2885
+ color: 'inherit',
2886
+ opacity: busy && busy !== mode ? 0.4 : running && mode === 'revert' ? 0.35 : 0.72,
2887
+ cursor: disabled ? 'default' : 'pointer',
2888
+ borderRadius: 6,
2889
+ },
2890
+ onClick,
2891
+ },
2892
+ icon,
2893
+ )
2894
+ return React.createElement(
2895
+ 'span',
2896
+ { style: { display: 'inline-flex', gap: 0 } },
2121
2897
  act(React.createElement(IconClock, { size: 16 }), t('slot.revert'), 'revert', runRevert, running),
2122
2898
  act(React.createElement(IconQuote, { size: 16 }), t('slot.quote'), 'quote', runQuote, false),
2123
2899
  )
@@ -2135,9 +2911,9 @@ window.__ModuleLoader__.load({
2135
2911
  // SessionRevert.commit() → revert:null → affordance 消失)。
2136
2912
  // 我们是 append-only,marker 不会真消失,所以由服务端按
2137
2913
  // 「marker 之后有无 source.kind==='user' 的真实输入」算出 committed。
2138
- return (msgs || []).filter((m) =>
2139
- m.marker && m.sourceKind !== 'compact-checkpoint'
2140
- && m.restoreComplete !== true && m.committed !== true)
2914
+ return (msgs || []).filter(
2915
+ m => m.marker && m.sourceKind !== 'compact-checkpoint' && m.restoreComplete !== true && m.committed !== true,
2916
+ )
2141
2917
  }
2142
2918
 
2143
2919
  /**
@@ -2169,7 +2945,7 @@ window.__ModuleLoader__.load({
2169
2945
  const t = (props && props.t) || __t
2170
2946
  useLocaleRevision()
2171
2947
  if (inputActions && typeof inputActions.setDraft === 'function') __inputActions = inputActions
2172
- const sessions = useSessions ? useSessions((s) => s) : undefined
2948
+ const sessions = useSessions ? useSessions(s => s) : undefined
2173
2949
  const summary = sessions && sessions.byId ? sessions.byId[sessionId] : undefined
2174
2950
  const running = summary ? summary.running === true : false
2175
2951
  // F1 主路径:宿主 activity 信号(见下方 effect);null = 无 useSessions 或尚无活动
@@ -2192,7 +2968,10 @@ window.__ModuleLoader__.load({
2192
2968
  // opencode SessionRevertDock 视觉(v2 布局,DSH 令牌等价映射)
2193
2969
  useEffect(() => {
2194
2970
  if (styleInjected || typeof document === 'undefined') return
2195
- if (document.getElementById('dsh-message-ops-dock-style')) { setStyleInjected(true); return }
2971
+ if (document.getElementById('dsh-message-ops-dock-style')) {
2972
+ setStyleInjected(true)
2973
+ return
2974
+ }
2196
2975
  const tag = document.createElement('style')
2197
2976
  tag.id = 'dsh-message-ops-dock-style'
2198
2977
  tag.textContent = [
@@ -2232,31 +3011,31 @@ window.__ModuleLoader__.load({
2232
3011
  // emitChanged() 自己就是先 invalidate 再发事件,这里同款红线。
2233
3012
  invalidateMessagesMemo()
2234
3013
  return fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId))
2235
- .then((data) => {
2236
- if (!alive || !data || !data.ok) return
2237
- // R2:只有**最新发起且仍未被更新的请求**的结果才允许落地。
2238
- // 注意不能只看 reqSeq 是否等于当前发起序号 —— 后发请求若失败(fetchMessagesJson
2239
- // 对非 2xx / ok!==true 会 throw,被下面 catch 吞掉),它的序号已被占用,
2240
- // 先发那次**成功的**好响应就会被这里丢弃 → markers 停在旧值且无重试。
2241
- // 故另记一个「已落地序号」,失败不回滚它。
2242
- if (reqSeq !== reqSeqRef.current || reqSeq <= landedSeqRef.current) return
2243
- landedSeqRef.current = reqSeq
2244
- const msgs = data.messages || []
2245
- syncSyntheticTurnStyle(msgs)
2246
- const act = activeMarkers(msgs)
2247
- setMarkers(act)
2248
- // 0.5.2(P2):标题口径 = 标记 range 内 visible=false 的去重 seq 数
2249
- const seen = new Set()
2250
- for (const mk of act) {
2251
- const start = mk.range && typeof mk.range.start === 'number' ? mk.range.start : mk.seq
2252
- const end = mk.range && typeof mk.range.end === 'number' ? mk.range.end : start
2253
- for (const m of msgs) {
2254
- if (m && m.visible === false && typeof m.seq === 'number' && m.seq >= start && m.seq <= end) seen.add(m.seq)
3014
+ .then(data => {
3015
+ if (!alive || !data || !data.ok) return
3016
+ // R2:只有**最新发起且仍未被更新的请求**的结果才允许落地。
3017
+ // 注意不能只看 reqSeq 是否等于当前发起序号 —— 后发请求若失败(fetchMessagesJson
3018
+ // 对非 2xx / ok!==true 会 throw,被下面 catch 吞掉),它的序号已被占用,
3019
+ // 先发那次**成功的**好响应就会被这里丢弃 → markers 停在旧值且无重试。
3020
+ // 故另记一个「已落地序号」,失败不回滚它。
3021
+ if (reqSeq !== reqSeqRef.current || reqSeq <= landedSeqRef.current) return
3022
+ landedSeqRef.current = reqSeq
3023
+ const msgs = data.messages || []
3024
+ syncSyntheticTurnStyle(msgs)
3025
+ const act = activeMarkers(msgs)
3026
+ setMarkers(act)
3027
+ // 0.5.2(P2):标题口径 = 标记 range 内 visible=false 的去重 seq 数
3028
+ const seen = new Set()
3029
+ for (const mk of act) {
3030
+ const start = mk.range && typeof mk.range.start === 'number' ? mk.range.start : mk.seq
3031
+ const end = mk.range && typeof mk.range.end === 'number' ? mk.range.end : start
3032
+ for (const m of msgs) {
3033
+ if (m && m.visible === false && typeof m.seq === 'number' && m.seq >= start && m.seq <= end) seen.add(m.seq)
3034
+ }
2255
3035
  }
2256
- }
2257
- setShadowCount(seen.size)
2258
- })
2259
- .catch(() => {})
3036
+ setShadowCount(seen.size)
3037
+ })
3038
+ .catch(() => {})
2260
3039
  }
2261
3040
 
2262
3041
  // F1(复审后重做):宿主在 user/message(source.kind==='user') 时会
@@ -2322,45 +3101,67 @@ window.__ModuleLoader__.load({
2322
3101
  if (step.reload) loadRef.current()
2323
3102
  }, [sessionId, activityAt])
2324
3103
 
2325
-
2326
3104
  // items 变化自动折叠(opencode createEffect 同款;必须在早退之前——Hooks 规则)
2327
- useEffect(() => { setOpen(false) }, [markers && markers.length, markers && markers[0] && markers[0].seq])
3105
+ useEffect(() => {
3106
+ setOpen(false)
3107
+ }, [markers && markers.length, markers && markers[0] && markers[0].seq])
2328
3108
  if (!markers || !markers.length) return null
2329
3109
 
2330
- const restoreRow = (row) => {
3110
+ const restoreRow = row => {
2331
3111
  if (restoring != null || running) return
2332
3112
  setRestoring(rowKey(row))
2333
3113
  Promise.resolve()
2334
- .then(() => fetch('/api/message-ops/restore', {
2335
- method: 'POST', headers: { 'content-type': 'application/json' },
2336
- // 0.8.0:upToSeq 存在 → 按轮步进恢复(只重放到该 seq)
2337
- body: JSON.stringify(row.upTo != null ? { sessionId, seq: row.seq, upToSeq: row.upTo } : { sessionId, seq: row.seq }),
2338
- }))
2339
- .then(async (res) => {
3114
+ .then(() =>
3115
+ fetch('/api/message-ops/restore', {
3116
+ method: 'POST',
3117
+ headers: { 'content-type': 'application/json' },
3118
+ // 0.8.0:upToSeq 存在 → 按轮步进恢复(只重放到该 seq)
3119
+ body: JSON.stringify(row.upTo != null ? { sessionId, seq: row.seq, upToSeq: row.upTo } : { sessionId, seq: row.seq }),
3120
+ }),
3121
+ )
3122
+ .then(async res => {
2340
3123
  let data = {}
2341
- try { data = await res.json() } catch { /* keep {} */ }
2342
- if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
2343
- notifyDone(t('done.restore', { n: String(data.restoredCount != null ? data.restoredCount : '?'), s: String(data.skipped != null ? data.skipped : 0) }))
3124
+ try {
3125
+ data = await res.json()
3126
+ } catch {
3127
+ /* keep {} */
3128
+ }
3129
+ if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
3130
+ notifyDone(
3131
+ t('done.restore', {
3132
+ n: String(data.restoredCount != null ? data.restoredCount : '?'),
3133
+ s: String(data.skipped != null ? data.skipped : 0),
3134
+ }),
3135
+ )
2344
3136
  setRestoring(null)
2345
3137
  // 0.5.0:恢复后重建会话视图(重放消息立即可见)
2346
3138
  try {
2347
3139
  if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sessionId)
2348
- } catch { /* fallthrough */ }
3140
+ } catch {
3141
+ /* fallthrough */
3142
+ }
2349
3143
  // 0.9.1:重放的消息带**新 seq**,被恢复的行必须解除 hidden;dock 的
2350
3144
  // marker 列表要按权威数据重算(restoreComplete 会变 true)后重拉。
2351
3145
  emitChanged()
2352
- for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(sessionId) }, delay)
3146
+ for (const delay of [150, 700, 1600])
3147
+ setTimeout(() => {
3148
+ if (__refreshSurface) __refreshSurface(sessionId)
3149
+ }, delay)
2353
3150
  const fresh = await fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId)).catch(() => null)
2354
3151
  if (fresh && fresh.ok) setMarkers(activeMarkers(fresh.messages || []))
2355
3152
  })
2356
- .catch((reason) => {
3153
+ .catch(reason => {
2357
3154
  notifyDone(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
2358
3155
  })
2359
3156
  .finally(() => setRestoring(null))
2360
3157
  }
2361
3158
 
2362
-
2363
- const headerKbd = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen((v) => !v) } }
3159
+ const headerKbd = e => {
3160
+ if (e.key === 'Enter' || e.key === ' ') {
3161
+ e.preventDefault()
3162
+ setOpen(v => !v)
3163
+ }
3164
+ }
2364
3165
  // 0.5.2(P2):标题报「被遮蔽消息数」而非标记数——一个 revert 可遮蔽数百条,
2365
3166
  // 用标记数会严重低报(0.4.2 文案引入的错口径);无 range 数据时回退标记数
2366
3167
  const label = t('dock.title', { n: String(shadowCount || markers.length) })
@@ -2368,19 +3169,28 @@ window.__ModuleLoader__.load({
2368
3169
 
2369
3170
  // 0.8.0:行 = 待恢复"轮"(对齐 opencode 按轮步进);无可重放轮的标记
2370
3171
  // 保留旧式整段行(空区间 → 停用 notice 路径)。restoring 键区分同标记多轮。
2371
- const rowKey = (row) => (row.upTo != null ? row.seq + ':' + row.upTo : String(row.seq))
2372
- const rowEl = (row) => React.createElement('div', { key: rowKey(row), className: 'mopsRdRow' },
2373
- React.createElement('span', { className: 'mopsRdRowText' }, '#' + row.seq + ' · ' + (row.snippet || '')),
2374
- React.createElement('button', {
2375
- type: 'button', className: 'mopsRdRestore', disabled: restoring != null || running,
2376
- // 0.10.2 专家组评估结论:唯一「严重度=高」的真实缺口是 restore 为**重放**语义 ——
2377
- // 消息带新 seq 落到会话末尾,**不会回到原位**(引擎 SurfaceOp 只有 append/replace,
2378
- // 不存在解除遮蔽的原语)。用户点下去看到消息"搬家到底部"会以为出 bug,
2379
- // 所以把语义写在按钮上,别让人靠猜。
2380
- title: t('dock.restoreHint'),
2381
- onClick: () => restoreRow(row),
2382
- }, restoring === rowKey(row) ? t('dock.restoring') : t('dock.restore')),
2383
- )
3172
+ const rowKey = row => (row.upTo != null ? row.seq + ':' + row.upTo : String(row.seq))
3173
+ const rowEl = row =>
3174
+ React.createElement(
3175
+ 'div',
3176
+ { key: rowKey(row), className: 'mopsRdRow' },
3177
+ React.createElement('span', { className: 'mopsRdRowText' }, '#' + row.seq + ' · ' + (row.snippet || '')),
3178
+ React.createElement(
3179
+ 'button',
3180
+ {
3181
+ type: 'button',
3182
+ className: 'mopsRdRestore',
3183
+ disabled: restoring != null || running,
3184
+ // 0.10.2 专家组评估结论:唯一「严重度=高」的真实缺口是 restore 为**重放**语义 ——
3185
+ // 消息带新 seq 落到会话末尾,**不会回到原位**(引擎 SurfaceOp 只有 append/replace,
3186
+ // 不存在解除遮蔽的原语)。用户点下去看到消息"搬家到底部"会以为出 bug,
3187
+ // 所以把语义写在按钮上,别让人靠猜。
3188
+ title: t('dock.restoreHint'),
3189
+ onClick: () => restoreRow(row),
3190
+ },
3191
+ restoring === rowKey(row) ? t('dock.restoring') : t('dock.restore'),
3192
+ ),
3193
+ )
2384
3194
  const dockRows = []
2385
3195
  for (const mk of markers || []) {
2386
3196
  if (Array.isArray(mk.pendingTurns) && mk.pendingTurns.length > 0) {
@@ -2392,26 +3202,74 @@ window.__ModuleLoader__.load({
2392
3202
  }
2393
3203
  }
2394
3204
 
2395
- const chevron = React.createElement('button', {
2396
- type: 'button', 'aria-label': open ? t('dock.collapse') : t('dock.expand'), 'aria-expanded': open,
2397
- className: 'mopsRdChevron',
2398
- onClick: (e) => { e.stopPropagation(); setOpen((v) => !v) },
2399
- }, React.createElement('svg', { width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none',
2400
- style: { transform: open ? 'rotate(0deg)' : 'rotate(180deg)', transition: 'transform .15s ease' } },
2401
- React.createElement('path', { d: 'M4 6l4 4 4-4', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round' })))
2402
-
2403
- return React.createElement('div', { className: 'mopsRd', role: 'region', 'aria-label': label },
2404
- React.createElement('div', {
2405
- className: 'mopsRdHead', role: 'button', tabIndex: 0,
2406
- onClick: () => setOpen((v) => !v), onKeyDown: headerKbd,
3205
+ const chevron = React.createElement(
3206
+ 'button',
3207
+ {
3208
+ type: 'button',
3209
+ 'aria-label': open ? t('dock.collapse') : t('dock.expand'),
3210
+ 'aria-expanded': open,
3211
+ className: 'mopsRdChevron',
3212
+ onClick: e => {
3213
+ e.stopPropagation()
3214
+ setOpen(v => !v)
3215
+ },
2407
3216
  },
2408
- React.createElement('span', { className: 'mopsRdIcon' },
2409
- React.createElement('svg', { width: 15, height: 15, viewBox: '0 0 16 16', fill: 'none' },
2410
- React.createElement('path', { d: 'M2.5 8a5.5 5.5 0 1 0 1.6-3.9', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round' }),
2411
- React.createElement('path', { d: 'M2.2 2.8v3h3', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round' }))),
3217
+ React.createElement(
3218
+ 'svg',
3219
+ {
3220
+ width: 14,
3221
+ height: 14,
3222
+ viewBox: '0 0 16 16',
3223
+ fill: 'none',
3224
+ style: { transform: open ? 'rotate(0deg)' : 'rotate(180deg)', transition: 'transform .15s ease' },
3225
+ },
3226
+ React.createElement('path', {
3227
+ d: 'M4 6l4 4 4-4',
3228
+ stroke: 'currentColor',
3229
+ strokeWidth: 1.3,
3230
+ strokeLinecap: 'round',
3231
+ strokeLinejoin: 'round',
3232
+ }),
3233
+ ),
3234
+ )
3235
+
3236
+ return React.createElement(
3237
+ 'div',
3238
+ { className: 'mopsRd', role: 'region', 'aria-label': label },
3239
+ React.createElement(
3240
+ 'div',
3241
+ {
3242
+ className: 'mopsRdHead',
3243
+ role: 'button',
3244
+ tabIndex: 0,
3245
+ onClick: () => setOpen(v => !v),
3246
+ onKeyDown: headerKbd,
3247
+ },
3248
+ React.createElement(
3249
+ 'span',
3250
+ { className: 'mopsRdIcon' },
3251
+ React.createElement(
3252
+ 'svg',
3253
+ { width: 15, height: 15, viewBox: '0 0 16 16', fill: 'none' },
3254
+ React.createElement('path', {
3255
+ d: 'M2.5 8a5.5 5.5 0 1 0 1.6-3.9',
3256
+ stroke: 'currentColor',
3257
+ strokeWidth: 1.2,
3258
+ strokeLinecap: 'round',
3259
+ }),
3260
+ React.createElement('path', {
3261
+ d: 'M2.2 2.8v3h3',
3262
+ stroke: 'currentColor',
3263
+ strokeWidth: 1.2,
3264
+ strokeLinecap: 'round',
3265
+ strokeLinejoin: 'round',
3266
+ }),
3267
+ ),
3268
+ ),
2412
3269
  React.createElement('span', { className: 'mopsRdLabel' + (open ? '' : ' mopsRdLabelCollapsed') }, label),
2413
3270
  open ? null : React.createElement('span', { className: 'mopsRdPreview' }, preview),
2414
- React.createElement('span', { style: { marginLeft: 'auto', flex: 'none' } }, chevron)),
3271
+ React.createElement('span', { style: { marginLeft: 'auto', flex: 'none' } }, chevron),
3272
+ ),
2415
3273
  open ? React.createElement('div', { className: 'mopsRdList' }, dockRows.map(rowEl)) : null,
2416
3274
  )
2417
3275
  }
@@ -2435,7 +3293,7 @@ window.__ModuleLoader__.load({
2435
3293
  window.__MOPS_USER_REVERT_INSTALLED = true
2436
3294
  var rowsCache = { sid: null, rows: null, at: 0 }
2437
3295
  __peekRowsCache = () => rowsCache
2438
- var norm = (x) => String(x || '').replace(/\s+/g, '')
3296
+ var norm = x => String(x || '').replace(/\s+/g, '')
2439
3297
 
2440
3298
  // 0.9.7(P4):messageId→seq / 全文索引挂在**同一个 dataSig** 上。
2441
3299
  // 旧实现每会话只写一次、仅失败时 delete —— 会话增长后新 assistant 消息的
@@ -2449,7 +3307,7 @@ window.__ModuleLoader__.load({
2449
3307
  __seqDataSig = sig
2450
3308
  const index = new Map()
2451
3309
  const full = new Map()
2452
- for (const m of (messages || [])) {
3310
+ for (const m of messages || []) {
2453
3311
  if (!m || m.id == null) continue
2454
3312
  const k = String(m.id)
2455
3313
  // 同 id 取**最早** seq —— 与槽位自己的 buildSeqIndex 口径一致
@@ -2461,17 +3319,21 @@ window.__ModuleLoader__.load({
2461
3319
  __seqIndexCache.set(key, index)
2462
3320
  __fullTextCache.set(key, full)
2463
3321
  }
2464
- try { window.dispatchEvent(new CustomEvent(SEQ_INDEX_EVENT)) } catch { /* non-browser */ }
3322
+ try {
3323
+ window.dispatchEvent(new CustomEvent(SEQ_INDEX_EVENT))
3324
+ } catch {
3325
+ /* non-browser */
3326
+ }
2465
3327
  }
2466
3328
 
2467
- var fetchRows = (sidIn) => {
3329
+ var fetchRows = sidIn => {
2468
3330
  // 0.9.7:统一按**裸 uuid** 作缓存键。调用方有的传 `session-xxx`(scan /
2469
3331
  // /undo 的 rawSid)有的传裸 uuid(/redo 的 bareSessionId)—— 混用会让
2470
3332
  // rowsCache.sid 在两个键之间来回横跳,每次都是缓存未命中(白白多发 GET)。
2471
3333
  const sid = bareSessionId(sidIn)
2472
3334
  if (rowsCache.sid === sid && rowsCache.rows && Date.now() - rowsCache.at < 8000) return Promise.resolve(rowsCache)
2473
3335
  return fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
2474
- .then((d) => {
3336
+ .then(d => {
2475
3337
  // 宿主会把 <system-reminder> / runtime context 等也记为 role=user 的行,
2476
3338
  // DOM 里并不渲染成"我的消息"块 —— 必须滤掉,否则按序配对会错位(0.7.0 根因)。
2477
3339
  // 注意:对话框的「可回滚目标」列表仍应过滤 visible(那是另一套语义)。
@@ -2482,11 +3344,21 @@ window.__ModuleLoader__.load({
2482
3344
  // 否则 `Background job 是我自己的问题` 这种真人输入会被误杀
2483
3345
  // (曾用 ^background job\b,测试当场抓到这个误杀)。
2484
3346
  // 样本里没出现过的模式(已停止 / User feedback:)一律**不加** —— 没证据就不猜。
2485
- 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 || ''))
3347
+ const injected = raw =>
3348
+ /^<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(
3349
+ String(raw || ''),
3350
+ )
2486
3351
  const rows = ((d && d.messages) || [])
2487
- .filter((m) => m && m.role === 'user')
2488
- .map((m) => ({ seq: m.seq, sn: norm(m.snippet), raw: String(m.snippet == null ? '' : m.snippet), fullText: m.fullText ?? null, visible: m.visible !== false, turnStartSeq: m.turnStartSeq ?? null }))
2489
- .filter((r) => r.sn && !injected(r.raw))
3352
+ .filter(m => m && m.role === 'user')
3353
+ .map(m => ({
3354
+ seq: m.seq,
3355
+ sn: norm(m.snippet),
3356
+ raw: String(m.snippet == null ? '' : m.snippet),
3357
+ fullText: m.fullText ?? null,
3358
+ visible: m.visible !== false,
3359
+ turnStartSeq: m.turnStartSeq ?? null,
3360
+ }))
3361
+ .filter(r => r.sn && !injected(r.raw))
2490
3362
  // 0.9.1:同时产出 node-key 查表索引(隐藏 transcript 用)
2491
3363
  const idx = buildIndex(d)
2492
3364
  rowsCache = { sid: sid, rows: rows, idx: idx, at: Date.now() }
@@ -2500,37 +3372,37 @@ window.__ModuleLoader__.load({
2500
3372
  // dsh transcript 刻意不折叠(surface.d.ts:51-63 "replacement copies stay
2501
3373
  // model-only"),回滚只能在渲染层按 `data-chat-node-key` 精确查表(零启发式)。
2502
3374
  // 背景长文与「40 字符前缀匹配」事故见 README「0.9.1 / 0.9.2 · 回滚「真的生效了」」。
2503
- var parseNodeKey = (k) => {
2504
- var m = /^(\d+):/.exec(k || '');
2505
- if (!m) return null;
2506
- var digits = m[1].length;
2507
- var kindLen = Number(m[1]);
2508
- var start = digits + 1;
2509
- if (!Number.isSafeInteger(kindLen) || kindLen <= 0 || k.length < start + kindLen) return null;
2510
- return { kind: k.slice(start, start + kindLen), id: k.slice(start + kindLen) };
2511
- };
3375
+ var parseNodeKey = k => {
3376
+ var m = /^(\d+):/.exec(k || '')
3377
+ if (!m) return null
3378
+ var digits = m[1].length
3379
+ var kindLen = Number(m[1])
3380
+ var start = digits + 1
3381
+ if (!Number.isSafeInteger(kindLen) || kindLen <= 0 || k.length < start + kindLen) return null
3382
+ return { kind: k.slice(start, start + kindLen), id: k.slice(start + kindLen) }
3383
+ }
2512
3384
 
2513
3385
  /**
2514
3386
  * 从 /api/message-ops/messages 的响应构建全部查表。
2515
- * 两条铁律:① 索引只认唯一 id;② 缺数据一律返回 undefined(调用方保持可见)。
2516
- */
2517
- var buildIndex = (payload) => {
3387
+ * 两条铁律:① 索引只认唯一 id;② 缺数据一律返回 undefined(调用方保持可见)。
3388
+ */
3389
+ var buildIndex = payload => {
2518
3390
  var list = (payload && payload.messages) || []
2519
3391
  // 0.9.1:回合页脚/过程条不是消息,用 turn/end 的 seq 定位(边界常落在 turn 内部,
2520
3392
  // 用 turn/start 会漏判该回合的页脚)
2521
- var turnEnd = (payload && payload.turnEndSeq) || null;
2522
- var byMessageId = new Map();
2523
- var byTurnStep = new Map();
2524
- var byCallId = new Map();
2525
- var byTurn = new Map();
2526
- var shadowed = new Set(); // 落在 replace 区间内 = 已被回滚(transcript 藏行判据)
2527
- var visibleTurns = new Set(); // 含至少一条**未被遮蔽**消息的 turn 号(回合 chrome)
2528
- var dupByMessageId = new Map();
3393
+ var turnEnd = (payload && payload.turnEndSeq) || null
3394
+ var byMessageId = new Map()
3395
+ var byTurnStep = new Map()
3396
+ var byCallId = new Map()
3397
+ var byTurn = new Map()
3398
+ var shadowed = new Set() // 落在 replace 区间内 = 已被回滚(transcript 藏行判据)
3399
+ var visibleTurns = new Set() // 含至少一条**未被遮蔽**消息的 turn 号(回合 chrome)
3400
+ var dupByMessageId = new Map()
2529
3401
  for (var i = 0; i < list.length; i++) {
2530
- var m = list[i];
2531
- if (!m || typeof m.seq !== 'number') continue;
3402
+ var m = list[i]
3403
+ if (!m || typeof m.seq !== 'number') continue
2532
3404
  if (m.id != null) {
2533
- var k = String(m.id);
3405
+ var k = String(m.id)
2534
3406
  // restore 是「重放」语义 → 原件与副本可能同 id 并存。
2535
3407
  // 0.9.1:不再「保留最早」,而是收集**全部** seq,隐藏判据取「任一 seq 越过
2536
3408
  // fence」。回放副本才是当前 surface 上的那条,用最早的 seq 判会让
@@ -2539,32 +3411,34 @@ window.__ModuleLoader__.load({
2539
3411
  const arr = dupByMessageId.get(k) || [byMessageId.get(k)]
2540
3412
  arr.push(m.seq)
2541
3413
  dupByMessageId.set(k, arr)
2542
- byMessageId.set(k, m.seq) // 指向最新的
2543
- } else { byMessageId.set(k, m.seq) }
3414
+ byMessageId.set(k, m.seq) // 指向最新的
3415
+ } else {
3416
+ byMessageId.set(k, m.seq)
3417
+ }
2544
3418
  }
2545
3419
  if (m.type === 'assistant/message' && m.turn != null && m.step != null) {
2546
- byTurnStep.set(m.turn + ':' + m.step, m.seq);
3420
+ byTurnStep.set(m.turn + ':' + m.step, m.seq)
2547
3421
  }
2548
- if (m.type === 'tool/call' && m.id != null) byCallId.set(String(m.id), m.seq);
2549
- if (m.turn != null && !byTurn.has(String(m.turn))) byTurn.set(String(m.turn), m.seq);
3422
+ if (m.type === 'tool/call' && m.id != null) byCallId.set(String(m.id), m.seq)
3423
+ if (m.turn != null && !byTurn.has(String(m.turn))) byTurn.set(String(m.turn), m.seq)
2550
3424
  // 0.9.6:藏行判据用 shadowed(replace 区间),**不用** m.visible(模型 surface)。
2551
3425
  // visible 在 live 路径下对 tool/call 恒 false → 拿它当判据会把整页工具行全藏,
2552
3426
  // 故这里连集合都不建(判据样本见 test/surface-visibility.test.js)。
2553
- if (m.shadowed === true) shadowed.add(m.seq);
2554
- else if (m.turn != null) visibleTurns.add(String(m.turn));
3427
+ if (m.shadowed === true) shadowed.add(m.seq)
3428
+ else if (m.turn != null) visibleTurns.add(String(m.turn))
2555
3429
  }
2556
3430
  // turnEnd 优先:它对「该 turn 内一条消息都没有」的情况仍然有效
2557
3431
  if (turnEnd) for (const k in turnEnd) if (Object.prototype.hasOwnProperty.call(turnEnd, k)) byTurn.set(k, turnEnd[k])
2558
- return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, shadowed, visibleTurns, total: list.length };
2559
- };
3432
+ return { byMessageId, dupByMessageId, byTurnStep, byCallId, byTurn, shadowed, visibleTurns, total: list.length }
3433
+ }
2560
3434
 
2561
3435
  /** node-key → { seq, all }(all = 同 id 的全部 seq,处理 restore 重放副本)。 */
2562
3436
  var seqOfNodeKey = (key, idx) => {
2563
- var parsed = parseNodeKey(key);
2564
- if (!parsed || !idx) return null;
2565
- var id = parsed.id;
3437
+ var parsed = parseNodeKey(key)
3438
+ if (!parsed || !idx) return null
3439
+ var id = parsed.id
2566
3440
  switch (parsed.kind) {
2567
- case 'input-message': // user / steering / turn-trigger
3441
+ case 'input-message': // user / steering / turn-trigger
2568
3442
  case 'developer-message':
2569
3443
  case 'trajectory-note': {
2570
3444
  const hit = idx.byMessageId.get(id)
@@ -2590,9 +3464,9 @@ window.__ModuleLoader__.load({
2590
3464
  return hit === undefined ? null : { kind: parsed.kind, seq: hit, all: [hit], turn: id }
2591
3465
  }
2592
3466
  default:
2593
- return null; // compaction / command / workflow-run 等不参与
3467
+ return null // compaction / command / workflow-run 等不参与
2594
3468
  }
2595
- };
3469
+ }
2596
3470
 
2597
3471
  /**
2598
3472
  * 把 transcript 行按模型 surface 可见性打上 hidden。
@@ -2604,46 +3478,49 @@ window.__ModuleLoader__.load({
2604
3478
  * 是唯一会误藏用户内容的路径。
2605
3479
  */
2606
3480
  var applySurfaceVisibility = (root, idx) => {
2607
- if (!idx) return { hidden: 0, unresolved: 0, shown: 0 };
3481
+ if (!idx) return { hidden: 0, unresolved: 0, shown: 0 }
2608
3482
  // 0.9.7(P2-1):root 既可传 document/元素(调用方自查),也可直接传
2609
3483
  // 已经查好的行集合 —— ensureAssign 每次都要算 rows.length 当签名,
2610
3484
  // 传集合避免同一次扫描里 querySelectorAll 跑两遍。
2611
- var rows = (root && typeof root.querySelectorAll === 'function')
2612
- ? root.querySelectorAll('[data-chat-node-key]')
2613
- : (root || document.querySelectorAll('[data-chat-node-key]'));
2614
- var hidden = 0, unresolved = 0, shown = 0;
3485
+ var rows =
3486
+ root && typeof root.querySelectorAll === 'function'
3487
+ ? root.querySelectorAll('[data-chat-node-key]')
3488
+ : root || document.querySelectorAll('[data-chat-node-key]')
3489
+ var hidden = 0,
3490
+ unresolved = 0,
3491
+ shown = 0
2615
3492
  for (var i = 0; i < rows.length; i++) {
2616
- var row = rows[i];
3493
+ var row = rows[i]
2617
3494
  // 0.9.6 藏行判据 = **replace 区间(shadowed)**;revertFences→visible→shadowed
2618
3495
  // 演进史(含 4792/4793 全藏事故)见 README「历史事故记录」#4。
2619
- var hit = seqOfNodeKey(row.getAttribute('data-chat-node-key'), idx);
3496
+ var hit = seqOfNodeKey(row.getAttribute('data-chat-node-key'), idx)
2620
3497
  // 0.9.7(P2-1)幂等跳写:判据与执行时机**一字未改**,只在
2621
3498
  // 「目标状态 ≠ 当前状态」时才碰属性 —— 省掉全表几百次无效写。
2622
3499
  if (hit === null) {
2623
- unresolved++;
2624
- if (row.hasAttribute('hidden')) row.removeAttribute('hidden');
2625
- continue;
3500
+ unresolved++
3501
+ if (row.hasAttribute('hidden')) row.removeAttribute('hidden')
3502
+ continue
2626
3503
  }
2627
- var shouldHide;
3504
+ var shouldHide
2628
3505
  if (hit.turn !== undefined) {
2629
3506
  // 回合 chrome:本 turn 还有未被遮蔽的消息就露出
2630
- shouldHide = !idx.visibleTurns.has(String(hit.turn));
3507
+ shouldHide = !idx.visibleTurns.has(String(hit.turn))
2631
3508
  } else {
2632
3509
  // 消息/工具类:**是否落在 replace 区间内**(= 被回滚掉了)。
2633
3510
  // ⚠️ 不能用 visible(模型 surface)——live 路径下 tool/call 恒不在 surface,
2634
3511
  // 会把整页工具行全藏(实测 157 行藏 152 行)。
2635
- shouldHide = idx.shadowed.has(hit.seq);
3512
+ shouldHide = idx.shadowed.has(hit.seq)
2636
3513
  }
2637
3514
  if (shouldHide) {
2638
- hidden++;
2639
- if (row.getAttribute('hidden') !== 'until-found') row.setAttribute('hidden', 'until-found');
3515
+ hidden++
3516
+ if (row.getAttribute('hidden') !== 'until-found') row.setAttribute('hidden', 'until-found')
2640
3517
  } else {
2641
- shown++;
2642
- if (row.hasAttribute('hidden')) row.removeAttribute('hidden');
3518
+ shown++
3519
+ if (row.hasAttribute('hidden')) row.removeAttribute('hidden')
2643
3520
  }
2644
3521
  }
2645
- return { hidden, unresolved, shown };
2646
- };
3522
+ return { hidden, unresolved, shown }
3523
+ }
2647
3524
 
2648
3525
  // 用户消息锚点:优先官方 Sixlwa_userRow(含 .xzv4MW_actions),回退 flow-kind 属性
2649
3526
  // 锚点 = 每条用户消息自己的容器(一个块只算一次):
@@ -2651,12 +3528,18 @@ window.__ModuleLoader__.load({
2651
3528
  var userAnchors = () => {
2652
3529
  const out = []
2653
3530
  const seen = new Set()
2654
- const add = (el) => { if (el && !seen.has(el)) { seen.add(el); out.push(el) } }
3531
+ const add = el => {
3532
+ if (el && !seen.has(el)) {
3533
+ seen.add(el)
3534
+ out.push(el)
3535
+ }
3536
+ }
2655
3537
  const rows = Array.from(document.querySelectorAll('[class*="xzv4MW_actions"]'))
2656
3538
  for (const r of rows) {
2657
- const block = r.closest('[data-chat-flow-kind="user"]')
2658
- || r.closest('[class*="_userRow"], [class*="_userStack"], [class*="_bubble"]')
2659
- || r.parentElement
3539
+ const block =
3540
+ r.closest('[data-chat-flow-kind="user"]') ||
3541
+ r.closest('[class*="_userRow"], [class*="_userStack"], [class*="_bubble"]') ||
3542
+ r.parentElement
2660
3543
  // 0.9.0:只按**稳定属性** + hash-immune 类名后缀判定,不再匹配 CSS-module
2661
3544
  // 生成的前缀(`Sixlwa_*`)。dsh 0.2.0-rc.2 的哈希已变为 `EvIC1a_flowItem`,
2662
3545
  // 旧前缀正则把所有块都滤掉 → anchors 为空 → 按钮拿不到 seq → 点击必失败。
@@ -2690,7 +3573,7 @@ window.__ModuleLoader__.load({
2690
3573
  }
2691
3574
  }
2692
3575
  /** 块内全部插件按钮一起同步(回滚 / 分叉同一动作行)。 */
2693
- var syncBlockButtons = (block) => {
3576
+ var syncBlockButtons = block => {
2694
3577
  if (!block || !block.querySelectorAll) return
2695
3578
  for (const b of block.querySelectorAll('.mopsUserRevert, .mopsUserFork')) syncEnabled(block, b)
2696
3579
  }
@@ -2698,7 +3581,7 @@ window.__ModuleLoader__.load({
2698
3581
  const idx = cache && cache.idx
2699
3582
  if (!idx) return
2700
3583
  // 0.9.1:node-key 查表,替代旧的 40 字符前缀包含匹配(实测 4 条错 2 条)
2701
- for (const b of (anchors || userAnchors())) {
3584
+ for (const b of anchors || userAnchors()) {
2702
3585
  b.removeAttribute('data-mops-seq')
2703
3586
  b.removeAttribute('data-mops-unmatched')
2704
3587
  const hit = seqOfNodeKey(b.getAttribute('data-chat-node-key'), idx)
@@ -2726,32 +3609,35 @@ window.__ModuleLoader__.load({
2726
3609
  // 摘牌后 node-key 相同但打标为空,靠这里发现)
2727
3610
  // 🔴 applySurfaceVisibility 仍然**无条件**执行,藏行判据与时机一字未改。
2728
3611
  var assignSig = null
2729
- var anchorSigOf = (anchors) => {
3612
+ var anchorSigOf = anchors => {
2730
3613
  let s = ''
2731
3614
  for (let i = 0; i < anchors.length; i++) {
2732
3615
  const b = anchors[i]
2733
- s += (b.getAttribute('data-chat-node-key') || '') + '=' +
2734
- (b.getAttribute('data-mops-seq') || (b.hasAttribute('data-mops-unmatched') ? '?' : '-')) + ','
3616
+ s +=
3617
+ (b.getAttribute('data-chat-node-key') || '') +
3618
+ '=' +
3619
+ (b.getAttribute('data-mops-seq') || (b.hasAttribute('data-mops-unmatched') ? '?' : '-')) +
3620
+ ','
2735
3621
  }
2736
3622
  return s
2737
3623
  }
2738
- var sigOf = (sid, dataSig, rowsLen, anchors) =>
2739
- bareSessionId(sid) + '|' + dataSig + '|' + rowsLen + '|' + anchorSigOf(anchors)
2740
- var ensureAssign = (sid) => fetchRows(sid).then((cache) => {
2741
- if (!cache || !cache.idx) return cache
2742
- const idx = cache.idx
2743
- const rows = document.querySelectorAll('[data-chat-node-key]')
2744
- const dataSig = idx.total + '/' + idx.shadowed.size + '/' + idx.visibleTurns.size
2745
- const anchors = userAnchors()
2746
- const before = sigOf(sid, dataSig, rows.length, anchors)
2747
- if (before !== assignSig) {
2748
- assignSeqs(sid, cache, anchors)
2749
- // 存**改写之后**的真实签名:下一次直接相等就跳过,不用跑两轮才收敛
2750
- assignSig = sigOf(sid, dataSig, rows.length, anchors)
2751
- }
2752
- applySurfaceVisibility(rows, idx)
2753
- return cache
2754
- })
3624
+ var sigOf = (sid, dataSig, rowsLen, anchors) => bareSessionId(sid) + '|' + dataSig + '|' + rowsLen + '|' + anchorSigOf(anchors)
3625
+ var ensureAssign = sid =>
3626
+ fetchRows(sid).then(cache => {
3627
+ if (!cache || !cache.idx) return cache
3628
+ const idx = cache.idx
3629
+ const rows = document.querySelectorAll('[data-chat-node-key]')
3630
+ const dataSig = idx.total + '/' + idx.shadowed.size + '/' + idx.visibleTurns.size
3631
+ const anchors = userAnchors()
3632
+ const before = sigOf(sid, dataSig, rows.length, anchors)
3633
+ if (before !== assignSig) {
3634
+ assignSeqs(sid, cache, anchors)
3635
+ // 存**改写之后**的真实签名:下一次直接相等就跳过,不用跑两轮才收敛
3636
+ assignSig = sigOf(sid, dataSig, rows.length, anchors)
3637
+ }
3638
+ applySurfaceVisibility(rows, idx)
3639
+ return cache
3640
+ })
2755
3641
  // 0.7.0:点击时先**同步完成**配对(打标是异步 fetch 的结果,
2756
3642
  // 早先点在未打标的按钮上会静默失败 = 用户反馈的"点了没用")。
2757
3643
  var runUserRevert = (btn, block) => {
@@ -2761,43 +3647,57 @@ window.__ModuleLoader__.load({
2761
3647
  Promise.resolve()
2762
3648
  .then(() => ensureAssign(sid))
2763
3649
  .then(() => fetchRows(sid))
2764
- .then((cache) => {
2765
- const rows = cache && cache.rows
2766
- // 0.9.1:seq 来自 node-key 精确查表,**不再**做文本前缀匹配验证
2767
- // (旧的前缀包含匹配实测 4 条错 2 条 —— "继续" 命中 "继续,…")。
2768
- const seq = Number(block.getAttribute('data-mops-seq'))
2769
- const row = rows && rows.find((r) => r.seq === seq)
2770
- if (!row) {
2771
- ensureAssign(sid)
2772
- notifyDone(__t('errorPrefix') + (__t('revert.unresolved') || 'revert target verification failed'), 'error')
2773
- return
2774
- }
2775
- btn.disabled = true
2776
- Promise.resolve()
2777
- .then(() => fetch('/api/message-ops/revert', {
2778
- method: 'POST', headers: { 'content-type': 'application/json' },
2779
- body: JSON.stringify({ sessionId: sid, seq: row.seq }),
2780
- }))
2781
- .then(async (res) => {
2782
- let data = {}
2783
- try { data = await res.json() } catch { /* keep {} */ }
2784
- if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
2785
- notifyDone(__t('done.revert'))
2786
- // 0.9.6:统一回填出口 —— 这个入口原先也不回填
2787
- refillComposer(sid, row.seq)
2788
- emitChanged()
2789
- try {
2790
- if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
2791
- } catch { /* 视图重建失败不阻断 */ }
2792
- // 0.9.1:视图重建后重新拉权威可见性并隐藏被遮蔽的行。
2793
- // openSession 会重挂 DOM,旧节点上的 hidden 属性随之失效,必须重刷。
2794
- if (rowsCache) rowsCache.at = 0
2795
- for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(sid) }, delay)
2796
- })
2797
- .catch((reason) => {
2798
- notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
2799
- })
2800
- .finally(() => { btn.disabled = false })
3650
+ .then(cache => {
3651
+ const rows = cache && cache.rows
3652
+ // 0.9.1:seq 来自 node-key 精确查表,**不再**做文本前缀匹配验证
3653
+ // (旧的前缀包含匹配实测 4 条错 2 条 —— "继续" 命中 "继续,…")。
3654
+ const seq = Number(block.getAttribute('data-mops-seq'))
3655
+ const row = rows && rows.find(r => r.seq === seq)
3656
+ if (!row) {
3657
+ ensureAssign(sid)
3658
+ notifyDone(__t('errorPrefix') + __t('slot.revertUnmatched'), 'error')
3659
+ return
3660
+ }
3661
+ btn.disabled = true
3662
+ Promise.resolve()
3663
+ .then(() =>
3664
+ fetch('/api/message-ops/revert', {
3665
+ method: 'POST',
3666
+ headers: { 'content-type': 'application/json' },
3667
+ body: JSON.stringify({ sessionId: sid, seq: row.seq }),
3668
+ }),
3669
+ )
3670
+ .then(async res => {
3671
+ let data = {}
3672
+ try {
3673
+ data = await res.json()
3674
+ } catch {
3675
+ /* keep {} */
3676
+ }
3677
+ if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
3678
+ notifyDone(__t('done.revert'))
3679
+ // 0.9.6:统一回填出口 —— 这个入口原先也不回填
3680
+ refillComposer(sid, row.seq)
3681
+ emitChanged()
3682
+ try {
3683
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(sid)
3684
+ } catch {
3685
+ /* 视图重建失败不阻断 */
3686
+ }
3687
+ // 0.9.1:视图重建后重新拉权威可见性并隐藏被遮蔽的行。
3688
+ // openSession 会重挂 DOM,旧节点上的 hidden 属性随之失效,必须重刷。
3689
+ if (rowsCache) rowsCache.at = 0
3690
+ for (const delay of [150, 700, 1600])
3691
+ setTimeout(() => {
3692
+ if (__refreshSurface) __refreshSurface(sid)
3693
+ }, delay)
3694
+ })
3695
+ .catch(reason => {
3696
+ notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
3697
+ })
3698
+ .finally(() => {
3699
+ btn.disabled = false
3700
+ })
2801
3701
  })
2802
3702
  }
2803
3703
  /**
@@ -2816,12 +3716,12 @@ window.__ModuleLoader__.load({
2816
3716
  Promise.resolve()
2817
3717
  .then(() => ensureAssign(sid))
2818
3718
  .then(() => fetchRows(sid))
2819
- .then(async (cache) => {
3719
+ .then(async cache => {
2820
3720
  const rows = cache && cache.rows
2821
3721
  const seq = Number(block.getAttribute('data-mops-seq'))
2822
- const row = rows && rows.find((r) => r.seq === seq)
3722
+ const row = rows && rows.find(r => r.seq === seq)
2823
3723
  if (!row) {
2824
- notifyDone(__t('errorPrefix') + (__t('revert.unresolved') || 'fork target verification failed'), 'error')
3724
+ notifyDone(__t('errorPrefix') + __t('slot.revertUnmatched'), 'error')
2825
3725
  return
2826
3726
  }
2827
3727
  if (!(seq > 0)) {
@@ -2831,22 +3731,28 @@ window.__ModuleLoader__.load({
2831
3731
  let text = typeof row.fullText === 'string' ? row.fullText : ''
2832
3732
  if (!text) {
2833
3733
  try {
2834
- const res = await fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(bareSessionId(sid)) + '&seq=' + encodeURIComponent(seq))
3734
+ const res = await fetch(
3735
+ '/api/message-ops/text?sessionId=' + encodeURIComponent(bareSessionId(sid)) + '&seq=' + encodeURIComponent(seq),
3736
+ )
2835
3737
  const data = res.ok ? await res.json().catch(() => null) : null
2836
3738
  if (data && data.ok && typeof data.text === 'string') text = data.text
2837
- } catch { /* 取全文失败:分叉照做,只是输入框留空 */ }
3739
+ } catch {
3740
+ /* 取全文失败:分叉照做,只是输入框留空 */
3741
+ }
2838
3742
  }
2839
3743
  const childId = await forkFromUserMessage(sid, seq, text, row.turnStartSeq)
2840
3744
  notifyDone(__t('slot.forkDone', { id: String(childId || '') }))
2841
3745
  if (childId) openSessionById(childId)
2842
3746
  })
2843
- .catch((reason) => {
3747
+ .catch(reason => {
2844
3748
  notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error')
2845
3749
  })
2846
- .finally(() => { btn.disabled = false })
3750
+ .finally(() => {
3751
+ btn.disabled = false
3752
+ })
2847
3753
  }
2848
3754
 
2849
- var ensureBtn = (block) => {
3755
+ var ensureBtn = block => {
2850
3756
  // 官方动作行(含 Copy):把按钮放到这一行里,与 Copy 同级
2851
3757
  let host = block.querySelector('[class*="xzv4MW_actions"]')
2852
3758
  if (!host) {
@@ -2861,9 +3767,11 @@ window.__ModuleLoader__.load({
2861
3767
  btn.className = 'mopsUserRevert'
2862
3768
  btn.title = __t('slot.revert')
2863
3769
  btn.setAttribute('aria-label', __t('slot.revert'))
2864
- btn.innerHTML = '<svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M2.5 8a5.5 5.5 0 1 0 1.6-3.9" stroke="currentColor" stroke-width="1.2"/><path d="M2.2 2.8v3h3" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>'
2865
- btn.addEventListener('click', (e) => {
2866
- e.preventDefault(); e.stopPropagation()
3770
+ btn.innerHTML =
3771
+ '<svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M2.5 8a5.5 5.5 0 1 0 1.6-3.9" stroke="currentColor" stroke-width="1.2"/><path d="M2.2 2.8v3h3" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>'
3772
+ btn.addEventListener('click', e => {
3773
+ e.preventDefault()
3774
+ e.stopPropagation()
2867
3775
  if (btn.disabled) return
2868
3776
  runUserRevert(btn, block)
2869
3777
  })
@@ -2876,7 +3784,7 @@ window.__ModuleLoader__.load({
2876
3784
  }
2877
3785
 
2878
3786
  /** 0.12.0 分叉按钮:与回滚按钮**同一动作行**(opencode 把 fork 放在 copy/undo 同组)。 */
2879
- var ensureForkBtn = (block) => {
3787
+ var ensureForkBtn = block => {
2880
3788
  let host = block.querySelector('[class*="xzv4MW_actions"]')
2881
3789
  if (!host) {
2882
3790
  host = document.createElement('div')
@@ -2891,9 +3799,11 @@ window.__ModuleLoader__.load({
2891
3799
  btn.title = __t('slot.forkHint')
2892
3800
  btn.setAttribute('aria-label', __t('slot.fork'))
2893
3801
  // 官方 IconBranchOutline16 的 1:1 路径(packages/client/ui-primitives/src/icons/index.tsx:149)
2894
- btn.innerHTML = '<svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="none"><path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" d="M13.0762 1.37207C14.0846 1.37228 14.9021 2.19077 14.9023 3.19922C14.9022 4.20772 14.0847 5.02518 13.0762 5.02539C12.2967 5.02539 11.6325 4.53691 11.3701 3.84961H4.35547C4.79397 4.26458 5.15861 4.7644 5.41699 5.33496L7.10645 9.06738C7.88526 10.7875 9.55104 11.9228 11.4189 12.0371C11.7085 11.4109 12.3411 10.9756 13.0762 10.9756C14.0843 10.9759 14.9023 11.7936 14.9023 12.8018C14.9023 13.81 14.0843 14.6277 13.0762 14.6279C12.2534 14.6279 11.5574 14.0832 11.3291 13.335C8.9868 13.1879 6.89981 11.7612 5.92285 9.60352L4.23242 5.87109C3.67503 4.64033 2.44878 3.84961 1.09766 3.84961V2.54883C1.10665 2.54883 1.11601 2.54975 1.125 2.5498L11.3701 2.54883C11.6326 1.86151 12.2969 1.37207 13.0762 1.37207ZM13.0762 12.2764C12.7858 12.2764 12.5508 12.5114 12.5508 12.8018C12.5508 13.0921 12.7858 13.3281 13.0762 13.3281C13.3664 13.3279 13.6025 13.092 13.6025 12.8018C13.6025 12.5115 13.3664 12.2766 13.0762 12.2764ZM13.0762 2.67285C12.7855 2.67285 12.55 2.90861 12.5498 3.19922C12.5499 3.48987 12.7855 3.72559 13.0762 3.72559C13.3667 3.72538 13.6024 3.48975 13.6025 3.19922C13.6023 2.90874 13.3666 2.67306 13.0762 2.67285Z"/></svg>'
2895
- btn.addEventListener('click', (e) => {
2896
- e.preventDefault(); e.stopPropagation()
3802
+ btn.innerHTML =
3803
+ '<svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="none"><path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" d="M13.0762 1.37207C14.0846 1.37228 14.9021 2.19077 14.9023 3.19922C14.9022 4.20772 14.0847 5.02518 13.0762 5.02539C12.2967 5.02539 11.6325 4.53691 11.3701 3.84961H4.35547C4.79397 4.26458 5.15861 4.7644 5.41699 5.33496L7.10645 9.06738C7.88526 10.7875 9.55104 11.9228 11.4189 12.0371C11.7085 11.4109 12.3411 10.9756 13.0762 10.9756C14.0843 10.9759 14.9023 11.7936 14.9023 12.8018C14.9023 13.81 14.0843 14.6277 13.0762 14.6279C12.2534 14.6279 11.5574 14.0832 11.3291 13.335C8.9868 13.1879 6.89981 11.7612 5.92285 9.60352L4.23242 5.87109C3.67503 4.64033 2.44878 3.84961 1.09766 3.84961V2.54883C1.10665 2.54883 1.11601 2.54975 1.125 2.5498L11.3701 2.54883C11.6326 1.86151 12.2969 1.37207 13.0762 1.37207ZM13.0762 12.2764C12.7858 12.2764 12.5508 12.5114 12.5508 12.8018C12.5508 13.0921 12.7858 13.3281 13.0762 13.3281C13.3664 13.3279 13.6025 13.092 13.6025 12.8018C13.6025 12.5115 13.3664 12.2766 13.0762 12.2764ZM13.0762 2.67285C12.7855 2.67285 12.55 2.90861 12.5498 3.19922C12.5499 3.48987 12.7855 3.72559 13.0762 3.72559C13.3667 3.72538 13.6024 3.48975 13.6025 3.19922C13.6023 2.90874 13.3666 2.67306 13.0762 2.67285Z"/></svg>'
3804
+ btn.addEventListener('click', e => {
3805
+ e.preventDefault()
3806
+ e.stopPropagation()
2897
3807
  if (btn.disabled) return
2898
3808
  runUserFork(btn, block)
2899
3809
  })
@@ -2902,7 +3812,7 @@ window.__ModuleLoader__.load({
2902
3812
  return btn
2903
3813
  }
2904
3814
  // 两个按钮的顺序由 DOM 顺序决定:回滚在前(破坏性更高),分叉在后(非破坏)。
2905
- var ensureUserActions = (block) => {
3815
+ var ensureUserActions = block => {
2906
3816
  ensureBtn(block)
2907
3817
  ensureForkBtn(block)
2908
3818
  }
@@ -2913,25 +3823,32 @@ window.__ModuleLoader__.load({
2913
3823
  // 共享窗口里的新鲜载荷先把隐藏刷对,不必等兜底那一发。
2914
3824
  var refreshTimer = null
2915
3825
  var refreshDeadline = 0
2916
- __refreshSurface = (sid) => {
3826
+ __refreshSurface = sid => {
2917
3827
  const id = sid || __currentSessionId
2918
3828
  if (!id) return
2919
- if (rowsCache) rowsCache.at = 0 // 强制重取权威数据
3829
+ if (rowsCache) rowsCache.at = 0 // 强制重取权威数据
2920
3830
  const now = Date.now()
2921
3831
  if (!refreshTimer) refreshDeadline = now + 1500
2922
3832
  clearTimeout(refreshTimer)
2923
- refreshTimer = setTimeout(() => {
2924
- refreshTimer = null
2925
- try {
2926
- // 会话已切走就别把旧会话的 idx 刷到新会话的 DOM 上
2927
- if (bareSessionId(__currentSessionId) !== bareSessionId(id)) return
2928
- invalidateMessagesMemo() // 兜底档必须是真网络,不许吃缓存
2929
- if (rowsCache) rowsCache.at = 0
2930
- fetchRows(id)
2931
- .then((cache) => { if (cache && cache.idx) applySurfaceVisibility(document, cache.idx) })
2932
- .catch(() => {})
2933
- } catch { /* noop */ }
2934
- }, Math.max(0, refreshDeadline - now))
3833
+ refreshTimer = setTimeout(
3834
+ () => {
3835
+ refreshTimer = null
3836
+ try {
3837
+ // 会话已切走就别把旧会话的 idx 刷到新会话的 DOM 上
3838
+ if (bareSessionId(__currentSessionId) !== bareSessionId(id)) return
3839
+ invalidateMessagesMemo() // 兜底档必须是真网络,不许吃缓存
3840
+ if (rowsCache) rowsCache.at = 0
3841
+ fetchRows(id)
3842
+ .then(cache => {
3843
+ if (cache && cache.idx) applySurfaceVisibility(document, cache.idx)
3844
+ })
3845
+ .catch(() => {})
3846
+ } catch {
3847
+ /* noop */
3848
+ }
3849
+ },
3850
+ Math.max(0, refreshDeadline - now),
3851
+ )
2935
3852
  }
2936
3853
  var scan = () => {
2937
3854
  try {
@@ -2944,7 +3861,9 @@ window.__ModuleLoader__.load({
2944
3861
  // 打标后 transcript 再变化(openSession 重建 / 分页 / restore 重放)
2945
3862
  // 就再也不会重算隐藏,导致「界面停在旧状态,必须重载页面才对」。
2946
3863
  ensureAssign(sid)
2947
- } catch { /* 注入失败不影响会话 */ }
3864
+ } catch {
3865
+ /* 注入失败不影响会话 */
3866
+ }
2948
3867
  }
2949
3868
  /**
2950
3869
  * 0.12.0 隐藏官方 assistant turn-tail 上的 branch 按钮。
@@ -2974,16 +3893,22 @@ window.__ModuleLoader__.load({
2974
3893
  }
2975
3894
 
2976
3895
  // 触发:hover / 滚动 / DOM 变化 / 变更事件
2977
- document.addEventListener('mouseover', (e) => {
2978
- try {
2979
- if (!e || !e.target || !e.target.closest) return
2980
- if (!__currentSessionId) return
2981
- const block = e.target.closest('[class*="Sixlwa_userRow"], [data-chat-flow-kind="user"]')
2982
- if (!block) return
2983
- ensureUserActions(block)
2984
- if (!block.hasAttribute('data-mops-seq')) ensureAssign(__currentSessionId)
2985
- } catch { /* noop */ }
2986
- }, { passive: true })
3896
+ document.addEventListener(
3897
+ 'mouseover',
3898
+ e => {
3899
+ try {
3900
+ if (!e || !e.target || !e.target.closest) return
3901
+ if (!__currentSessionId) return
3902
+ const block = e.target.closest('[class*="Sixlwa_userRow"], [data-chat-flow-kind="user"]')
3903
+ if (!block) return
3904
+ ensureUserActions(block)
3905
+ if (!block.hasAttribute('data-mops-seq')) ensureAssign(__currentSessionId)
3906
+ } catch {
3907
+ /* noop */
3908
+ }
3909
+ },
3910
+ { passive: true },
3911
+ )
2987
3912
  window.addEventListener('scroll', scan, { passive: true })
2988
3913
  try {
2989
3914
  // 0.9.7(P1-2)回调过滤 + maxWait。
@@ -3011,36 +3936,56 @@ window.__ModuleLoader__.load({
3011
3936
  return
3012
3937
  }
3013
3938
  clearTimeout(scan._t)
3014
- scan._t = setTimeout(() => { scan._t = null; scanPendingSince = 0; scan() }, 200)
3939
+ scan._t = setTimeout(() => {
3940
+ scan._t = null
3941
+ scanPendingSince = 0
3942
+ scan()
3943
+ }, 200)
3015
3944
  }
3016
- var mo = new MutationObserver((records) => {
3945
+ var mo = new MutationObserver(records => {
3017
3946
  try {
3018
3947
  for (var i = 0; i < records.length; i++) {
3019
3948
  var rec = records[i]
3020
3949
  if (rec.type === 'attributes') {
3021
3950
  var tgt = rec.target
3022
- if (tgt && tgt.nodeType === 1 && typeof tgt.matches === 'function' && tgt.matches(MO_SEL)) { scheduleScan(); return }
3951
+ if (tgt && tgt.nodeType === 1 && typeof tgt.matches === 'function' && tgt.matches(MO_SEL)) {
3952
+ scheduleScan()
3953
+ return
3954
+ }
3023
3955
  continue
3024
3956
  }
3025
3957
  var added = rec.addedNodes
3026
3958
  for (var j = 0; j < added.length; j++) {
3027
3959
  var n = added[j]
3028
3960
  if (!n || n.nodeType !== 1) continue
3029
- if ((typeof n.matches === 'function' && n.matches(MO_SEL))
3030
- || (typeof n.querySelector === 'function' && n.querySelector(MO_SEL))) { scheduleScan(); return }
3961
+ if (
3962
+ (typeof n.matches === 'function' && n.matches(MO_SEL)) ||
3963
+ (typeof n.querySelector === 'function' && n.querySelector(MO_SEL))
3964
+ ) {
3965
+ scheduleScan()
3966
+ return
3967
+ }
3031
3968
  }
3032
3969
  }
3033
- } catch { scheduleScan() }
3970
+ } catch {
3971
+ scheduleScan()
3972
+ }
3034
3973
  })
3035
3974
  mo.observe(document.body, {
3036
- childList: true, subtree: true,
3037
- attributes: true, attributeFilter: ['data-chat-node-key'],
3975
+ childList: true,
3976
+ subtree: true,
3977
+ attributes: true,
3978
+ attributeFilter: ['data-chat-node-key'],
3038
3979
  })
3039
- } catch { /* noop */ }
3980
+ } catch {
3981
+ /* noop */
3982
+ }
3040
3983
  window.addEventListener(CHANGED_EVENT, () => {
3041
3984
  try {
3042
- document.querySelectorAll('[data-mops-seq]').forEach((b) => b.removeAttribute('data-mops-seq'))
3043
- } catch { /* noop */ }
3985
+ document.querySelectorAll('[data-mops-seq]').forEach(b => b.removeAttribute('data-mops-seq'))
3986
+ } catch {
3987
+ /* noop */
3988
+ }
3044
3989
  })
3045
3990
  // 样式:与官方 action 按钮同款(28px、ghost),可见性继承宿主动作行
3046
3991
  try {
@@ -3058,7 +4003,9 @@ window.__ModuleLoader__.load({
3058
4003
  ].join('')
3059
4004
  document.head.appendChild(tag)
3060
4005
  }
3061
- } catch { /* style 注入失败不影响功能 */ }
4006
+ } catch {
4007
+ /* style 注入失败不影响功能 */
4008
+ }
3062
4009
  }
3063
4010
 
3064
4011
  function ensureSidebarOpsItem() {
@@ -3072,18 +4019,29 @@ window.__ModuleLoader__.load({
3072
4019
  item.setAttribute('role', 'menuitem')
3073
4020
  item.setAttribute('data-dsh-message-ops', '1')
3074
4021
  item.style.cssText = [
3075
- 'display:flex', 'align-items:center', 'gap:8px', 'width:100%',
3076
- 'padding:6px 12px', 'border:none', 'background:transparent',
4022
+ 'display:flex',
4023
+ 'align-items:center',
4024
+ 'gap:8px',
4025
+ 'width:100%',
4026
+ 'padding:6px 12px',
4027
+ 'border:none',
4028
+ 'background:transparent',
3077
4029
  'color:var(--dsw-alias-label-primary,inherit)',
3078
- 'font:inherit', 'font-size:13px', 'line-height:20px',
3079
- 'text-align:left', 'border-radius:6px', 'cursor:pointer',
4030
+ 'font:inherit',
4031
+ 'font-size:13px',
4032
+ 'line-height:20px',
4033
+ 'text-align:left',
4034
+ 'border-radius:6px',
4035
+ 'cursor:pointer',
3080
4036
  ].join(';')
3081
4037
  item.innerHTML = branchIconMarkup(16) + '<span></span>'
3082
4038
  item.querySelector('span').textContent = __t('menu.ops')
3083
4039
  item.addEventListener('mouseenter', function () {
3084
4040
  item.style.background = 'var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.14))'
3085
4041
  })
3086
- item.addEventListener('mouseleave', function () { item.style.background = 'transparent' })
4042
+ item.addEventListener('mouseleave', function () {
4043
+ item.style.background = 'transparent'
4044
+ })
3087
4045
  item.addEventListener('click', function () {
3088
4046
  var titleEl = row.querySelector('[class*=title]')
3089
4047
  var title = titleEl ? String(titleEl.innerText || '').trim() : ''
@@ -3111,7 +4069,11 @@ window.__ModuleLoader__.load({
3111
4069
  function installSidebarOps() {
3112
4070
  if (window.__dshMessageOpsSidebarInstalled) return
3113
4071
  window.__dshMessageOpsSidebarInstalled = true
3114
- try { ensureSidebarOpsItem() } catch (e) { /* never crash the UI */ }
4072
+ try {
4073
+ ensureSidebarOpsItem()
4074
+ } catch (e) {
4075
+ /* never crash the UI */
4076
+ }
3115
4077
  // 观察范围收窄(评审 M2):仍需 observe document.body(会话行菜单由宿主
3116
4078
  // React 动态渲染在侧栏任意挂载点,安装期无法锚定稳定容器),但回调改为
3117
4079
  // 精确过滤——只有新增节点本身就是(或包含)[role=menu] 时才调度探测,
@@ -3123,7 +4085,11 @@ window.__ModuleLoader__.load({
3123
4085
  pending = true
3124
4086
  setTimeout(function () {
3125
4087
  pending = false
3126
- try { ensureSidebarOpsItem() } catch (e) { /* never crash the UI */ }
4088
+ try {
4089
+ ensureSidebarOpsItem()
4090
+ } catch (e) {
4091
+ /* never crash the UI */
4092
+ }
3127
4093
  }, 0)
3128
4094
  }
3129
4095
  var observer = new MutationObserver(function (mutations) {
@@ -3134,10 +4100,16 @@ window.__ModuleLoader__.load({
3134
4100
  if (n.nodeType !== 1) continue
3135
4101
  var isMenu = false
3136
4102
  try {
3137
- isMenu = (typeof n.matches === 'function' && n.matches('[role=menu]'))
3138
- || (typeof n.querySelector === 'function' && n.querySelector('[role=menu]') !== null)
3139
- } catch (e) { isMenu = false }
3140
- if (isMenu) { scheduleEnsure(); return }
4103
+ isMenu =
4104
+ (typeof n.matches === 'function' && n.matches('[role=menu]')) ||
4105
+ (typeof n.querySelector === 'function' && n.querySelector('[role=menu]') !== null)
4106
+ } catch (e) {
4107
+ isMenu = false
4108
+ }
4109
+ if (isMenu) {
4110
+ scheduleEnsure()
4111
+ return
4112
+ }
3141
4113
  }
3142
4114
  }
3143
4115
  })
@@ -3153,10 +4125,11 @@ window.__ModuleLoader__.load({
3153
4125
  if (typeof locale.register === 'function') {
3154
4126
  ctx.effect(() => locale.register(NS, { zh: zhDict, en: enDict }))
3155
4127
  }
3156
- } catch { /* namespace already registered: keep existing copy */ }
4128
+ } catch {
4129
+ /* namespace already registered: keep existing copy */
4130
+ }
3157
4131
  }
3158
4132
 
3159
-
3160
4133
  // ═══ 0.9.3 /undo —— opencode 招牌交互 ═════════════════════════════════════
3161
4134
  //
3162
4135
  // 「我说的那句话不对」→ 一个命令 → 消息从 transcript 消失 + 原文回输入框。
@@ -3197,7 +4170,7 @@ window.__ModuleLoader__.load({
3197
4170
 
3198
4171
  /** 执行 undo/redo。返回 true 表示确实动过盘。 */
3199
4172
  /** __currentSessionId 来自 DOM dataset,可能带 `session-` 前缀;API 只要裸 uuid。 */
3200
- var bareSessionId = (id) => String(id || '').replace(/^session-/, '')
4173
+ var bareSessionId = id => String(id || '').replace(/^session-/, '')
3201
4174
  /** 写盘成功后的统一收尾:通知、刷新、重放隐藏。 */
3202
4175
  /**
3203
4176
  * 写盘成功后的统一收尾。
@@ -3220,7 +4193,10 @@ window.__ModuleLoader__.load({
3220
4193
  if (window.__MOPS_DEBUG) console.warn('[message-ops] openSession failed:', e)
3221
4194
  }
3222
4195
  const bare = bareSessionId(rawSid)
3223
- for (const delay of [150, 700, 1600]) setTimeout(() => { if (__refreshSurface) __refreshSurface(bare) }, delay)
4196
+ for (const delay of [150, 700, 1600])
4197
+ setTimeout(() => {
4198
+ if (__refreshSurface) __refreshSurface(bare)
4199
+ }, delay)
3224
4200
  }
3225
4201
 
3226
4202
  /**
@@ -3248,13 +4224,17 @@ window.__ModuleLoader__.load({
3248
4224
  if (!cache || !Array.isArray(cache.rows)) return false
3249
4225
  const want = bareSessionId(rawSid)
3250
4226
  if (bareSessionId(cache.sid) !== want) return false
3251
- const rows = cache.rows.filter((r) => r && typeof r.seq === 'number' && r.seq <= boundarySeq && r.fullText)
4227
+ const rows = cache.rows.filter(r => r && typeof r.seq === 'number' && r.seq <= boundarySeq && r.fullText)
3252
4228
  if (!rows.length) return false
3253
4229
  if (!__inputActions || typeof __inputActions.setDraft !== 'function') return false
3254
4230
  __inputActions.setDraft(rows[rows.length - 1].fullText)
3255
4231
  // 关键:不落盘的话,紧随其后的 openSession 会从 localStorage 读回旧草稿。
3256
4232
  if (typeof __inputActions.persistDraft === 'function') {
3257
- try { __inputActions.persistDraft() } catch (e) { console.warn('[message-ops] persistDraft failed:', e) }
4233
+ try {
4234
+ __inputActions.persistDraft()
4235
+ } catch (e) {
4236
+ console.warn('[message-ops] persistDraft failed:', e)
4237
+ }
3258
4238
  }
3259
4239
  return true
3260
4240
  } catch (e) {
@@ -3272,16 +4252,23 @@ window.__ModuleLoader__.load({
3272
4252
  var runUndo = () => {
3273
4253
  const rawSid = __currentSessionId
3274
4254
  const sid = bareSessionId(rawSid)
3275
- if (!sid) { notifyDone(__t('undo.none') || '没有可回滚的消息', 'error'); return false }
4255
+ if (!sid) {
4256
+ notifyDone(__t('undo.none') || '没有可回滚的消息', 'error')
4257
+ return false
4258
+ }
3276
4259
  const target = lastRevertable()
3277
- if (!target) { notifyDone(__t('undo.none') || '没有可回滚的消息', 'error'); return false }
4260
+ if (!target) {
4261
+ notifyDone(__t('undo.none') || '没有可回滚的消息', 'error')
4262
+ return false
4263
+ }
3278
4264
  fetch('/api/message-ops/revert', {
3279
- method: 'POST', headers: { 'content-type': 'application/json' },
4265
+ method: 'POST',
4266
+ headers: { 'content-type': 'application/json' },
3280
4267
  body: JSON.stringify({ sessionId: sid, seq: target.seq }),
3281
4268
  })
3282
- .then(async (res) => {
4269
+ .then(async res => {
3283
4270
  const data = await res.json().catch(() => ({}))
3284
- if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
4271
+ if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
3285
4272
  // 0.11.3:立刻把本行标成已遮蔽,否则 afterWrite 的异步刷新窗里
3286
4273
  // 再点一次 /undo 仍会选中同一个 seq → 409。
3287
4274
  const rowsCache = __peekRowsCache ? __peekRowsCache() : null
@@ -3291,10 +4278,10 @@ window.__ModuleLoader__.load({
3291
4278
  }
3292
4279
  rowsCache.at = 0
3293
4280
  }
3294
- refillComposer(rawSid, target.seq) // 先回填,再重建视图(与对话框一致)
4281
+ refillComposer(rawSid, target.seq) // 先回填,再重建视图(与对话框一致)
3295
4282
  afterWrite(rawSid, __t('undo.done.undo'))
3296
4283
  })
3297
- .catch((reason) => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
4284
+ .catch(reason => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
3298
4285
  return true
3299
4286
  }
3300
4287
 
@@ -3310,27 +4297,31 @@ window.__ModuleLoader__.load({
3310
4297
  const sid = bareSessionId(rawSid)
3311
4298
  if (!sid) return false
3312
4299
  fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sid))
3313
- .then((d) => {
4300
+ .then(d => {
3314
4301
  if (!d || !d.ok) throw new Error((d && d.error) || 'messages unavailable')
3315
4302
  const markers = activeMarkers(d.messages || [])
3316
- if (!markers.length) { notifyDone(__t('undo.none.redo') || '没有可恢复的回滚', 'error'); return null }
3317
- const mk = markers[markers.length - 1] // 最新一条未恢复标记
4303
+ if (!markers.length) {
4304
+ notifyDone(__t('undo.none.redo') || '没有可恢复的回滚', 'error')
4305
+ return null
4306
+ }
4307
+ const mk = markers[markers.length - 1] // 最新一条未恢复标记
3318
4308
  return fetch('/api/message-ops/restore', {
3319
- method: 'POST', headers: { 'content-type': 'application/json' },
4309
+ method: 'POST',
4310
+ headers: { 'content-type': 'application/json' },
3320
4311
  body: JSON.stringify({ sessionId: sid, seq: mk.seq }),
3321
- }).then(async (res) => {
4312
+ }).then(async res => {
3322
4313
  const data = await res.json().catch(() => ({}))
3323
- if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
4314
+ if (!res.ok || !data.ok) throw new Error(data.error || 'HTTP ' + res.status)
3324
4315
  // afterWrite 契约:rawSid 必须带 session- 前缀(传裸 uuid 会抛
3325
4316
  // `sessions.retain: unknown session` 并被外层 catch 静默吞掉)
3326
4317
  afterWrite(rawSid, __t('undo.done.redo'))
3327
4318
  })
3328
4319
  })
3329
- .catch((reason) => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
4320
+ .catch(reason => notifyDone(__t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)), 'error'))
3330
4321
  return true
3331
4322
  }
3332
4323
 
3333
- var runUndoRedo = (kind) => (kind === 'redo' ? runRedo() : runUndo())
4324
+ var runUndoRedo = kind => (kind === 'redo' ? runRedo() : runUndo())
3334
4325
 
3335
4326
  /** 注册 /undo /redo 到官方斜杠管线。服务缺失时安静 no-op。 */
3336
4327
  var __undoRegistered = false
@@ -3338,107 +4329,153 @@ window.__ModuleLoader__.load({
3338
4329
  if (__undoRegistered || !it || typeof it.registerSource !== 'function') return
3339
4330
  __undoRegistered = true
3340
4331
  try {
3341
- ctx.effect(() => it.registerSource({
3342
- trigger: '/',
3343
- name: __undoSourceName,
3344
- order: 20,
3345
- showGroupTitle: true,
3346
- // ⚠️ 必须返回 **Promise**:宿主在 InputTriggerController.fetchCandidates 里
3347
- // 直接 `source.candidates(...).then(...)`,同步返回数组会抛
3348
- // `source.candidates(...).then is not a function`,整个菜单静默失效。
3349
- candidates: async (session, req) => {
3350
- const q = String((req && req.query) || '').trim().toLowerCase()
3351
- return UNDO_CANDIDATES
3352
- .filter((c) => !q || c.name.includes(q))
3353
- .map((c) => ({
4332
+ ctx.effect(() =>
4333
+ it.registerSource({
4334
+ trigger: '/',
4335
+ name: __undoSourceName,
4336
+ order: 20,
4337
+ showGroupTitle: true,
4338
+ // ⚠️ 必须返回 **Promise**:宿主在 InputTriggerController.fetchCandidates 里
4339
+ // 直接 `source.candidates(...).then(...)`,同步返回数组会抛
4340
+ // `source.candidates(...).then is not a function`,整个菜单静默失效。
4341
+ candidates: async (session, req) => {
4342
+ const q = String((req && req.query) || '')
4343
+ .trim()
4344
+ .toLowerCase()
4345
+ return UNDO_CANDIDATES.filter(c => !q || c.name.includes(q)).map(c => ({
3354
4346
  name: c.name,
3355
4347
  icon: c.icon,
3356
- label: c.name === 'undo'
3357
- ? (__t('undo.label') || '回滚上一条消息')
3358
- : (__t('redo.label') || '恢复上一条被回滚的消息'),
3359
- description: c.name === 'undo'
3360
- ? (__t('undo.desc') || '移除最后一条用户消息,原文回填输入框')
3361
- : (__t('redo.desc') || '把回滚掉的消息重新放回对话'),
4348
+ label: c.name === 'undo' ? __t('undo.label') || '回滚上一条消息' : __t('redo.label') || '恢复上一条被回滚的消息',
4349
+ description:
4350
+ c.name === 'undo'
4351
+ ? __t('undo.desc') || '移除最后一条用户消息,原文回填输入框'
4352
+ : __t('redo.desc') || '把回滚掉的消息重新放回对话',
3362
4353
  value: c.value,
3363
4354
  }))
3364
- },
3365
- onPick: (pick) => {
3366
- const v = pick && pick.candidate && pick.candidate.value
3367
- if (v !== 'undo' && v !== 'redo') return undefined
3368
- runUndoRedo(v)
3369
- return 'handled'
3370
- },
3371
- // Enter 直接执行:`/undo` 不必先在菜单里选中
3372
- matchEnter: (session, line) => {
3373
- const t = String(line || '').trim().toLowerCase()
3374
- if (t !== '/undo' && t !== '/redo') return undefined
3375
- runUndoRedo(t === '/redo' ? 'redo' : 'undo')
3376
- return 'handled'
3377
- },
3378
- }))
4355
+ },
4356
+ onPick: pick => {
4357
+ const v = pick && pick.candidate && pick.candidate.value
4358
+ if (v !== 'undo' && v !== 'redo') return undefined
4359
+ runUndoRedo(v)
4360
+ return 'handled'
4361
+ },
4362
+ // Enter 直接执行:`/undo` 不必先在菜单里选中
4363
+ matchEnter: (session, line) => {
4364
+ const t = String(line || '')
4365
+ .trim()
4366
+ .toLowerCase()
4367
+ if (t !== '/undo' && t !== '/redo') return undefined
4368
+ runUndoRedo(t === '/redo' ? 'redo' : 'undo')
4369
+ return 'handled'
4370
+ },
4371
+ }),
4372
+ )
3379
4373
  } catch (e) {
3380
4374
  __undoRegistered = false
3381
4375
  if (window.__MOPS_DEBUG) console.warn('[message-ops] /undo 注册失败:', e)
3382
4376
  }
3383
4377
  }
3384
4378
 
3385
- var registerUndoSlash = (ctx) => {
4379
+ var registerUndoSlash = ctx => {
3386
4380
  // ⚠️ cordis 的 inject 回调**第一个参数是服务本身**,不是 ctx。
3387
4381
  // 早先写成 `registerUndoSlash(sub.ctx || sub)` → 在服务对象上找 .get
3388
4382
  // 必然是 undefined → 静默不注册(表现为 /undo 根本不出现)。
3389
4383
  const it = typeof ctx.get === 'function' ? ctx.get('inputTriggers') : null
3390
- if (it) { doRegisterUndoSlash(ctx, it); return }
4384
+ if (it) {
4385
+ doRegisterUndoSlash(ctx, it)
4386
+ return
4387
+ }
3391
4388
  try {
3392
4389
  // ⚠️ cordis inject 回调收到的是**注入命名空间**,服务在其同名字段下
3393
4390
  // (与本文件 `ctx.inject(['uiWorkspace'], sub => sub.uiWorkspace || sub)` 同模式)。
3394
4391
  // 直接把 sub 当服务用会抛 `cannot get property "registerSource" without inject`。
3395
- ctx.inject(['inputTriggers'], (sub) => {
4392
+ ctx.inject(['inputTriggers'], sub => {
3396
4393
  doRegisterUndoSlash(ctx, sub && (sub.inputTriggers || sub))
3397
4394
  })
3398
- } catch (e) {
3399
- }
4395
+ } catch (e) {}
3400
4396
  }
3401
4397
 
3402
4398
  function apply(ctx) {
3403
4399
  __sessionsSvc = ctx.get('sessions')
3404
4400
  __uiWorkspace = typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : null
3405
4401
  if (!__uiWorkspace) {
3406
- try { ctx.inject(['uiWorkspace'], (sub) => { __uiWorkspace = sub.uiWorkspace || sub }) } catch { /* 0.1.x 无此服务 */ }
4402
+ try {
4403
+ ctx.inject(['uiWorkspace'], sub => {
4404
+ __uiWorkspace = sub.uiWorkspace || sub
4405
+ })
4406
+ } catch {
4407
+ /* 0.1.x 无此服务 */
4408
+ }
3407
4409
  }
3408
4410
  if (!__sessionsSvc) {
3409
- ctx.inject(['sessions'], (sub) => { __sessionsSvc = sub.sessions })
4411
+ ctx.inject(['sessions'], sub => {
4412
+ __sessionsSvc = sub.sessions
4413
+ })
3410
4414
  }
3411
4415
  registerUndoSlash(ctx)
3412
4416
  adoptLocale(ctx.get('locale'), ctx)
3413
4417
  if (!__locale) {
3414
- ctx.inject(['locale'], (sub) => {
4418
+ ctx.inject(['locale'], sub => {
3415
4419
  adoptLocale(sub.locale, ctx)
3416
4420
  refreshSidebarOpsLabel()
3417
4421
  })
3418
4422
  }
3419
4423
  ctx.on('locale/change', refreshSidebarOpsLabel)
3420
- if (window.__MOPS_DISABLE_HEADER !== true) ctx.slots.inject(SLOT, () => ctx.slots.register({
3421
- name: SLOT, id: ROW_ID, order: 31,
3422
- ...(__locale ? { locale: NS } : {}),
3423
- }, OpsButton))
4424
+ if (window.__MOPS_DISABLE_HEADER !== true)
4425
+ ctx.slots.inject(SLOT, () =>
4426
+ ctx.slots.register(
4427
+ {
4428
+ name: SLOT,
4429
+ id: ROW_ID,
4430
+ order: 31,
4431
+ ...(__locale ? { locale: NS } : {}),
4432
+ },
4433
+ OpsButton,
4434
+ ),
4435
+ )
3424
4436
  // 0.3.0:每条 AI 消息旁的原生回撤按钮(0.1.x 无此槽,inject 自动 no-op)
3425
- ctx.slots.inject(CHAT_ACTIONS_SLOT, () => ctx.slots.register({
3426
- name: CHAT_ACTIONS_SLOT, id: CHAT_ACTIONS_ID, order: 20,
3427
- ...(__locale ? { locale: NS } : {}),
3428
- }, MsgSlotActions))
4437
+ ctx.slots.inject(CHAT_ACTIONS_SLOT, () =>
4438
+ ctx.slots.register(
4439
+ {
4440
+ name: CHAT_ACTIONS_SLOT,
4441
+ id: CHAT_ACTIONS_ID,
4442
+ order: 20,
4443
+ ...(__locale ? { locale: NS } : {}),
4444
+ },
4445
+ MsgSlotActions,
4446
+ ),
4447
+ )
3429
4448
  // 0.4.0:composer 上方回撤 dock(0.1.x 无此槽自动 no-op)
3430
- ctx.slots.inject(INPUT_DOCK_SLOT, () => ctx.slots.register({
3431
- name: INPUT_DOCK_SLOT, id: INPUT_DOCK_ID, order: 10,
3432
- ...(__locale ? { locale: NS } : {}),
3433
- }, RevertDock))
3434
- ctx.slots.inject(OVERLAY_SLOT, () => ctx.slots.register({
3435
- name: OVERLAY_SLOT, id: DIALOG_ID, order: 101,
3436
- ...(__locale ? { locale: NS } : {}),
3437
- }, window.__MOPS_LEGACY_DIALOG === true ? OpsDialog : OpsPanel))
4449
+ ctx.slots.inject(INPUT_DOCK_SLOT, () =>
4450
+ ctx.slots.register(
4451
+ {
4452
+ name: INPUT_DOCK_SLOT,
4453
+ id: INPUT_DOCK_ID,
4454
+ order: 10,
4455
+ ...(__locale ? { locale: NS } : {}),
4456
+ },
4457
+ RevertDock,
4458
+ ),
4459
+ )
4460
+ ctx.slots.inject(OVERLAY_SLOT, () =>
4461
+ ctx.slots.register(
4462
+ {
4463
+ name: OVERLAY_SLOT,
4464
+ id: DIALOG_ID,
4465
+ order: 101,
4466
+ ...(__locale ? { locale: NS } : {}),
4467
+ },
4468
+ window.__MOPS_LEGACY_DIALOG === true ? OpsDialog : OpsPanel,
4469
+ ),
4470
+ )
3438
4471
  installSidebarOps()
3439
4472
  installUserRevertInjector()
3440
4473
  }
3441
4474
 
3442
- return { apply, inject: ['slots'], __test: { activityTransition, forkBoundaryBefore, isHostBranchButton, writeSessionDraft, HOST_BRANCH_D_PREFIX } }
4475
+ return {
4476
+ apply,
4477
+ inject: ['slots'],
4478
+ __test: { activityTransition, forkBoundaryBefore, isHostBranchButton, writeSessionDraft, HOST_BRANCH_ICON_ID, HOST_BRANCH_D_PREFIX },
4479
+ }
3443
4480
  },
3444
4481
  })