@240xu/dsh-message-ops 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js CHANGED
@@ -30,6 +30,24 @@ window.__ModuleLoader__.load({
30
30
  const MSG_COALESCE_MS = 1000
31
31
  var __messagesMemo = { url: null, at: 0, p: null, settled: false }
32
32
  var invalidateMessagesMemo = () => { __messagesMemo = { url: null, at: 0, p: null, settled: false } }
33
+ const SYNTHETIC_TURN_STYLE_ID = 'dsh-message-ops-synthetic-turn-hide'
34
+ const syncSyntheticTurnStyle = (messages) => {
35
+ if (typeof document === 'undefined' || !document.head) return
36
+ const turns = new Set()
37
+ for (const m of messages || []) {
38
+ if (m && m.syntheticTurn === true && Number.isSafeInteger(m.turn)) turns.add(m.turn)
39
+ }
40
+ let tag = document.getElementById(SYNTHETIC_TURN_STYLE_ID)
41
+ if (turns.size === 0) { if (tag) tag.remove(); return }
42
+ if (!tag) {
43
+ tag = document.createElement('style')
44
+ tag.id = SYNTHETIC_TURN_STYLE_ID
45
+ document.head.appendChild(tag)
46
+ }
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')
50
+ }
33
51
  const emitChanged = () => {
34
52
  // 数据变了:连同本地缓存一起作废(否则 8s TTL 会让 openSession 后的
35
53
  // scan 拿旧 payload 重算隐藏 = 「回滚了但界面没变」)。
@@ -129,6 +147,60 @@ window.__ModuleLoader__.load({
129
147
  'undo.none.redo': '没有可恢复的回滚',
130
148
  'redo.label': '恢复上一条被回滚的消息',
131
149
  'redo.desc': '把回滚掉的消息重新放回对话',
150
+ 'panel.messages': '消息',
151
+ 'panel.trash': '回收站',
152
+ 'panel.search': '搜索当前会话',
153
+ 'panel.searchHint': '搜索全文,不只是摘要',
154
+ 'panel.all': '全部',
155
+ 'panel.user': '用户',
156
+ 'panel.assistant': '助手',
157
+ 'panel.tool': '工具',
158
+ 'panel.includeShadowed': '含已回滚',
159
+ 'panel.loading': '正在读取…',
160
+ 'panel.loadFail': '读取失败:',
161
+ 'panel.searchFail': '搜索失败:',
162
+ 'panel.empty': '没有可显示的消息。',
163
+ 'panel.noMatch': '没有匹配结果。',
164
+ 'panel.selectHint': '选择一条消息,查看全文和操作。',
165
+ 'panel.detailLoading': '正在读取全文…',
166
+ 'panel.shadowed': '已回滚',
167
+ 'panel.running': '会话正在运行:回滚、删除、分支需先停止。',
168
+ 'panel.revert': '回滚到此条',
169
+ 'panel.revertHint': '包含此条及其后的可见消息',
170
+ 'panel.revertConfirmTitle': '回滚到 #{seq}?',
171
+ 'panel.revertConfirmBody': '将遮蔽 #{start}–#{end} 的 {n} 条消息,其中可见 {v} 条;日志仍保留,可恢复。',
172
+ 'panel.deleteConfirmTitle': '仅删除 #{seq}?',
173
+ 'panel.deleteConfirmBody': '将遮蔽这 1 条消息,其他内容不动;日志仍保留,可恢复。',
174
+ 'panel.confirmRevert': '确认回滚',
175
+ 'panel.confirmDeleteOne': '确认删除',
176
+ 'panel.retry': '重试',
177
+ 'panel.searching': '搜索中…',
178
+ 'panel.deleteSessionImpact': '共 {n} 条消息;移入回收站后 7 天内可恢复。',
179
+ 'panel.deleteUnavailable': '会话信息尚未就绪,暂不能删除。',
180
+ 'panel.delete': '仅删除此条',
181
+ 'panel.deleteHint': '只遮蔽这一条,其他消息不动',
182
+ 'panel.branch': '从此条分支',
183
+ 'panel.branchHint': '复制到此条为止的内容为新会话',
184
+ 'panel.branchDone': '分支已创建:{id}',
185
+ 'panel.openNew': '打开新会话',
186
+ 'panel.revertDone': '回滚已生效',
187
+ 'panel.deleteDone': '删除已生效',
188
+ 'panel.count': '共 {n} 条 · 可见 {v} · 已回滚 {s}',
189
+ 'panel.deleteSession': '删除整条会话',
190
+ 'panel.deleteSessionHint': '移入回收站,7 天内可恢复。请输入标题确认:',
191
+ 'panel.cancel': '取消',
192
+ 'panel.confirmDelete': '确认删除',
193
+ 'panel.deleting': '删除中…',
194
+ 'panel.deleted': '会话已移入回收站',
195
+ 'panel.trashEmpty': '回收站是空的。',
196
+ 'panel.untitled': '未命名会话',
197
+ 'panel.restore': '恢复',
198
+ 'panel.purge': '永久删除',
199
+ 'panel.purgeConfirm': '再点一次永久删除',
200
+ 'panel.restored': '会话已恢复',
201
+ 'panel.purged': '回收站条目已永久删除',
202
+ 'panel.expires': '到期',
203
+ 'panel.busy': '处理中…',
132
204
  'menu.ops': '消息操作',
133
205
  }
134
206
 
@@ -189,6 +261,60 @@ window.__ModuleLoader__.load({
189
261
  'undo.none.redo': 'No revert to redo',
190
262
  'redo.label': 'Restore the last reverted message',
191
263
  'redo.desc': 'Put the reverted message back into the conversation',
264
+ 'panel.messages': 'Messages',
265
+ 'panel.trash': 'Trash',
266
+ 'panel.search': 'Search this session',
267
+ 'panel.searchHint': 'Search full text, not just snippets',
268
+ 'panel.all': 'All',
269
+ 'panel.user': 'User',
270
+ 'panel.assistant': 'Assistant',
271
+ 'panel.tool': 'Tool',
272
+ 'panel.includeShadowed': 'Include shadowed',
273
+ 'panel.loading': 'Loading…',
274
+ 'panel.loadFail': 'Failed to load: ',
275
+ 'panel.searchFail': 'Search failed: ',
276
+ 'panel.empty': 'No messages to show.',
277
+ 'panel.noMatch': 'No matches.',
278
+ 'panel.selectHint': 'Pick a message to see its full text and actions.',
279
+ 'panel.detailLoading': 'Loading full text…',
280
+ 'panel.shadowed': 'reverted',
281
+ 'panel.running': 'Session is running: stop it before revert, delete, or branch.',
282
+ 'panel.revert': 'Revert to here',
283
+ 'panel.revertHint': 'Includes this message and all visible messages after it',
284
+ 'panel.revertConfirmTitle': 'Revert to #{seq}?',
285
+ 'panel.revertConfirmBody': 'This shadows {n} messages (#{start}–#{end}), including {v} visible. The log stays append-only and can be restored.',
286
+ 'panel.deleteConfirmTitle': 'Delete only #{seq}?',
287
+ 'panel.deleteConfirmBody': 'This shadows this one message; everything else stays. The log stays append-only and can be restored.',
288
+ 'panel.confirmRevert': 'Confirm revert',
289
+ 'panel.confirmDeleteOne': 'Confirm delete',
290
+ 'panel.retry': 'Retry',
291
+ 'panel.searching': 'Searching…',
292
+ 'panel.deleteSessionImpact': 'Total {n} messages; recoverable from trash for 7 days.',
293
+ 'panel.deleteUnavailable': 'Session details are not ready yet; deletion is disabled.',
294
+ 'panel.delete': 'Delete only this',
295
+ 'panel.deleteHint': 'Shadows only this message',
296
+ 'panel.branch': 'Branch from here',
297
+ 'panel.branchHint': 'Copy everything through this message into a new session',
298
+ 'panel.branchDone': 'Branched: {id}',
299
+ 'panel.openNew': 'Open new session',
300
+ 'panel.revertDone': 'Revert applied',
301
+ 'panel.deleteDone': 'Delete applied',
302
+ 'panel.count': 'Total {n} · visible {v} · shadowed {s}',
303
+ 'panel.deleteSession': 'Delete whole session',
304
+ 'panel.deleteSessionHint': 'Moves it to trash for 7 days. Type the title to confirm:',
305
+ 'panel.cancel': 'Cancel',
306
+ 'panel.confirmDelete': 'Delete',
307
+ 'panel.deleting': 'Deleting…',
308
+ 'panel.deleted': 'Session moved to trash',
309
+ 'panel.trashEmpty': 'Trash is empty.',
310
+ 'panel.untitled': 'Untitled session',
311
+ 'panel.restore': 'Restore',
312
+ 'panel.purge': 'Delete forever',
313
+ 'panel.purgeConfirm': 'Click again to delete forever',
314
+ 'panel.restored': 'Session restored',
315
+ 'panel.purged': 'Trash entry permanently deleted',
316
+ 'panel.expires': 'expires',
317
+ 'panel.busy': 'Working…',
192
318
  'menu.ops': 'Message ops',
193
319
  }
194
320
 
@@ -433,9 +559,15 @@ window.__ModuleLoader__.load({
433
559
  // branch 在上面已 return,故 done.restore 分支在此不可达,一并删掉。
434
560
  const okMsg = mode === 'revert' ? t('done.revert') : t('done.delete')
435
561
  // 0.4.0 composer 回填(opencode 式):回滚用户消息 → 原文回填输入框,「编辑重发」零按钮
436
- if (mode === 'revert' && pickedMsg && pickedMsg.role === 'user' && pickedMsg.fullText
437
- && __inputActions && typeof __inputActions.setDraft === 'function') {
438
- try { __inputActions.setDraft(pickedMsg.fullText) } catch { /* 回填失败不阻断成功反馈 */ }
562
+ // 0.11.3:必须走统一出口,且要落盘 —— 直接 setDraft 会被随后的
563
+ // openSession 用 localStorage 里的旧草稿覆盖(见 refillComposer 注释)。
564
+ if (mode === 'revert' && pickedMsg && pickedMsg.role === 'user' && pickedMsg.fullText) {
565
+ try {
566
+ if (__inputActions && typeof __inputActions.setDraft === 'function') {
567
+ __inputActions.setDraft(pickedMsg.fullText)
568
+ if (typeof __inputActions.persistDraft === 'function') __inputActions.persistDraft()
569
+ }
570
+ } catch (e) { console.warn('[message-ops] refill failed:', e) }
439
571
  }
440
572
  setDoneMsg(okMsg)
441
573
  setBusyMsg('')
@@ -592,6 +724,924 @@ window.__ModuleLoader__.load({
592
724
  ])
593
725
  }
594
726
 
727
+ // --- A · 功能主义抽屉 -------------------------------------------------------
728
+
729
+ const PANEL_ROW_H = 46
730
+ const PANEL_SEARCH_LIMIT = 100
731
+
732
+ function fmtClock(value) {
733
+ if (typeof value !== 'number') return ''
734
+ try {
735
+ return new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
736
+ } catch { return '' }
737
+ }
738
+
739
+ function roleCode(role) {
740
+ if (role === 'user') return 'U'
741
+ if (role === 'assistant') return 'A'
742
+ if (role === 'tool') return 'T'
743
+ return 'S'
744
+ }
745
+
746
+ function focusablesIn(root) {
747
+ if (!root || typeof root.querySelectorAll !== 'function') return []
748
+ const selector = 'button:not([disabled]),[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'
749
+ return Array.prototype.slice.call(root.querySelectorAll(selector)).filter((el) => {
750
+ if (el.getAttribute('aria-hidden') === 'true') return false
751
+ return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0
752
+ })
753
+ }
754
+
755
+ function ensurePanelStyle() {
756
+ try {
757
+ if (document.getElementById('dsh-message-ops-panel-style')) return
758
+ const tag = document.createElement('style')
759
+ tag.id = 'dsh-message-ops-panel-style'
760
+ tag.textContent = [
761
+ '.mopsPanelScrim{position:fixed;inset:0;z-index:1200;background:rgba(15,17,21,.18);display:flex;justify-content:flex-end}',
762
+ '.mopsPanel{width:560px;max-width:100vw;height:100%;display:flex;flex-direction:column;background:var(--dsw-alias-bg-primary,#fff);color:var(--dsw-alias-label-primary,#0f1115);border-left:1px solid var(--dsw-alias-border-l2,#e6e6e6);box-shadow:-16px 0 48px rgba(15,17,21,.14);font-family:inherit;font-size:13px;line-height:1.45}',
763
+ '.mopsPanel *{box-sizing:border-box}',
764
+ '.mopsPanel button{font:inherit;color:inherit;border-radius:0}',
765
+ '.mopsPanelHead{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;padding:16px 18px 12px;border-bottom:1px solid var(--dsw-alias-border-l2,#e6e6e6)}',
766
+ '.mopsPanelKicker{font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
767
+ '.mopsPanelTitle{font-size:15px;font-weight:600;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:420px}',
768
+ '.mopsPanelSub{font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-top:2px}',
769
+ '.mopsPanelClose{width:30px;height:30px;border:1px solid var(--dsw-alias-border-l2,#e6e6e6);background:transparent;cursor:pointer;font-size:16px;line-height:1;flex:none}',
770
+ '.mopsPanelClose:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(15,17,21,.06))}',
771
+ '.mopsTabs{display:flex;border-bottom:1px solid var(--dsw-alias-border-l2,#e6e6e6)}',
772
+ '.mopsTab{flex:1;padding:9px 12px;border:0;border-bottom:2px solid transparent;background:transparent;cursor:pointer;font-size:12px;color:var(--dsw-alias-label-secondary,#6b6b70)}',
773
+ '.mopsTab.on{border-bottom-color:var(--dsw-alias-brand-primary,#4d6bfe);color:var(--dsw-alias-label-primary,#0f1115);font-weight:600}',
774
+ '.mopsSearchRow{display:flex;gap:8px;padding:12px 18px 8px}',
775
+ '.mopsSearch{flex:1;min-width:0;height:32px;border:1px solid var(--dsw-alias-border-l2,#d8d8d8);background:transparent;color:inherit;padding:0 9px;font:inherit;font-size:12px;outline:none}',
776
+ '.mopsSearch:focus{border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
777
+ '.mopsChips{display:flex;gap:6px;padding:0 18px 10px;flex-wrap:wrap;align-items:center}',
778
+ '.mopsChip{height:26px;padding:0 9px;border:1px solid var(--dsw-alias-border-l2,#d8d8d8);background:transparent;cursor:pointer;font-size:11px;color:var(--dsw-alias-label-secondary,#6b6b70)}',
779
+ '.mopsChip.on{border-color:var(--dsw-alias-label-primary,#0f1115);background:var(--dsw-alias-label-primary,#0f1115);color:var(--dsw-alias-bg-primary,#fff)}',
780
+ '.mopsToggle{display:inline-flex;align-items:center;gap:5px;font-size:11px;color:var(--dsw-alias-label-secondary,#6b6b70);margin-left:auto;cursor:pointer}',
781
+ '.mopsToggle input{accent-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
782
+ '.mopsList{flex:1;min-height:0;overflow-y:auto;position:relative;border-top:1px solid var(--dsw-alias-border-l1,#efefef)}',
783
+ '.mopsList:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d6bfe);outline-offset:-2px}',
784
+ '.mopsRow{position:absolute;left:0;right:0;display:grid;grid-template-columns:44px 26px minmax(0,1fr) 48px;align-items:center;gap:8px;width:100%;border:0;border-bottom:1px solid var(--dsw-alias-border-l1,#f0f0f0);background:transparent;text-align:left;cursor:pointer;padding:0 12px 0 18px;color:inherit;font:inherit}',
785
+ '.mopsRow:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(15,17,21,.045))}',
786
+ '.mopsRow.on{background:rgba(77,107,254,.08);box-shadow:inset 2px 0 0 var(--dsw-alias-brand-primary,#4d6bfe)}',
787
+ '.mopsRow.shadowed{opacity:.42}',
788
+ '.mopsSeq{font-variant-numeric:tabular-nums;font-size:10px;color:var(--dsw-alias-label-tertiary,#9a9aa0)}',
789
+ '.mopsRole{width:20px;height:20px;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--dsw-alias-border-l2,#d8d8d8);font-size:9px;font-weight:600;color:var(--dsw-alias-label-secondary,#6b6b70)}',
790
+ '.mopsSnippet{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}',
791
+ '.mopsClock{font-size:10px;color:var(--dsw-alias-label-tertiary,#9a9aa0);text-align:right;font-variant-numeric:tabular-nums}',
792
+ '.mopsEmpty{padding:28px 18px;color:var(--dsw-alias-label-tertiary,#8a8a8e);font-size:12px}',
793
+ '.mopsErrorState{display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap;color:var(--dsw-alias-state-error-primary,#c63b32)}',
794
+ '.mopsErrorState .mopsAction{flex:none}',
795
+ '.mopsDetail{flex:none;max-height:37%;overflow-y:auto;border-top:1px solid var(--dsw-alias-border-l2,#e6e6e6);padding:12px 18px 10px;background:var(--dsw-alias-bg-secondary,#fafafa)}',
796
+ '.mopsDetailMeta{display:flex;gap:8px;align-items:center;font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-bottom:6px}',
797
+ '.mopsDetailText{margin:0;white-space:pre-wrap;word-break:break-word;max-height:108px;overflow:auto;font-family:inherit;font-size:12px;line-height:1.55;color:var(--dsw-alias-label-primary,#0f1115)}',
798
+ '.mopsDetailHint{padding:10px 0 14px;color:var(--dsw-alias-label-tertiary,#8a8a8e);font-size:12px}',
799
+ '.mopsActions{display:flex;gap:6px;flex-wrap:wrap;margin-top:10px}',
800
+ '.mopsActionConfirm{display:flex;flex-direction:column;gap:7px;margin-top:10px;padding:10px;border:1px solid var(--dsw-alias-border-l2,#e6e6e6);background:var(--dsw-alias-bg-primary,#fff)}',
801
+ '.mopsImpactTitle{font-size:12px;font-weight:600}',
802
+ '.mopsImpact{font-size:11px;line-height:1.5;color:var(--dsw-alias-label-secondary,#6b6b70)}',
803
+ '.mopsAction{height:30px;padding:0 10px;border:1px solid var(--dsw-alias-border-l2,#cfcfcf);background:transparent;cursor:pointer;font-size:11px}',
804
+ '.mopsAction:hover:not(:disabled){border-color:var(--dsw-alias-label-primary,#0f1115)}',
805
+ '.mopsAction.primary{border-color:var(--dsw-alias-label-primary,#0f1115);background:var(--dsw-alias-label-primary,#0f1115);color:var(--dsw-alias-bg-primary,#fff)}',
806
+ '.mopsAction.danger{border-color:var(--dsw-alias-state-error-primary,#c63b32);color:var(--dsw-alias-state-error-primary,#c63b32)}',
807
+ '.mopsAction:disabled{opacity:.35;cursor:default}',
808
+ '.mopsPanelFoot{flex:none;display:flex;align-items:center;gap:10px;justify-content:space-between;padding:10px 18px;border-top:1px solid var(--dsw-alias-border-l2,#e6e6e6);background:var(--dsw-alias-bg-primary,#fff)}',
809
+ '.mopsCount{font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
810
+ '.mopsDanger{border:1px solid var(--dsw-alias-state-error-primary,#c63b32);background:transparent;color:var(--dsw-alias-state-error-primary,#c63b32);height:28px;padding:0 9px;cursor:pointer;font-size:11px}',
811
+ '.mopsDanger:hover{background:rgba(198,59,50,.06)}',
812
+ '.mopsBanner{padding:7px 18px;font-size:11px;border-bottom:1px solid var(--dsw-alias-border-l1,#efefef)}',
813
+ '.mopsBanner.warn{color:var(--dsw-alias-state-warn-primary,#9a6500);background:rgba(154,101,0,.06)}',
814
+ '.mopsBanner.err{color:var(--dsw-alias-state-error-primary,#c63b32);background:rgba(198,59,50,.06)}',
815
+ '.mopsBanner.ok{color:var(--dsw-alias-state-success-primary,#2f7d4a);background:rgba(47,125,74,.06)}',
816
+ '.mopsConfirm{position:absolute;inset:0;z-index:2;background:var(--dsw-alias-bg-primary,#fff);display:flex;flex-direction:column;justify-content:center;padding:28px 24px;gap:10px}',
817
+ '.mopsConfirm h3{margin:0;font-size:15px}',
818
+ '.mopsConfirm p{margin:0;font-size:12px;color:var(--dsw-alias-label-secondary,#6b6b70)}',
819
+ '.mopsConfirm p.mopsImpact{font-size:11px}',
820
+ '.mopsConfirm .mopsBanner{margin:0 -24px;border-top:1px solid var(--dsw-alias-border-l1,#efefef);border-bottom:1px solid var(--dsw-alias-border-l1,#efefef)}',
821
+ '.mopsConfirm input{height:34px;border:1px solid var(--dsw-alias-border-l2,#d8d8d8);background:transparent;color:inherit;padding:0 9px;font:inherit;font-size:13px}',
822
+ '.mopsConfirm input:disabled{opacity:.5}',
823
+ '.mopsConfirmRow{display:flex;gap:8px;margin-top:4px}',
824
+ '.mopsTrashItem{display:flex;align-items:center;gap:10px;padding:11px 18px;border-bottom:1px solid var(--dsw-alias-border-l1,#f0f0f0)}',
825
+ '.mopsTrashMain{flex:1;min-width:0}',
826
+ '.mopsTrashTitle{font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
827
+ '.mopsTrashMeta{font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-top:2px}',
828
+ '@media(max-width:760px){.mopsPanel{width:100vw;border-left:0}.mopsDetail{max-height:42%}}',
829
+ ].join('')
830
+ document.head.appendChild(tag)
831
+ } catch { /* style failure must not break the panel */ }
832
+ }
833
+
834
+ function OpsPanel(props) {
835
+ const t = (props && props.t) || __t
836
+ useLocaleRevision()
837
+ const [open, setOpen] = useState(false)
838
+ const [target, setTarget] = useState(null)
839
+ const [state, setState] = useState('idle')
840
+ const [loadError, setLoadError] = useState(null)
841
+ const [messages, setMessages] = useState([])
842
+ const [query, setQuery] = useState('')
843
+ const [role, setRole] = useState('all')
844
+ const [includeShadowed, setIncludeShadowed] = useState(false)
845
+ const [picked, setPicked] = useState(null)
846
+ const [detail, setDetail] = useState('')
847
+ const [detailState, setDetailState] = useState('idle')
848
+ const [tab, setTab] = useState('messages')
849
+ const [hits, setHits] = useState(null)
850
+ const [searching, setSearching] = useState(false)
851
+ const [trash, setTrash] = useState([])
852
+ const [trashState, setTrashState] = useState('idle')
853
+ const [trashError, setTrashError] = useState(null)
854
+ const [confirmDelete, setConfirmDelete] = useState(false)
855
+ const [confirmTitle, setConfirmTitle] = useState('')
856
+ const [deleteError, setDeleteError] = useState(null)
857
+ const [confirmAction, setConfirmAction] = useState(null)
858
+ const [purgeId, setPurgeId] = useState(null)
859
+ const [childId, setChildId] = useState(null)
860
+ const [busy, setBusy] = useState('')
861
+ const [error, setError] = useState(null)
862
+ const [done, setDone] = useState('')
863
+ const [scrollTop, setScrollTop] = useState(0)
864
+ const [viewport, setViewport] = useState(480)
865
+ const listRef = useRef(null)
866
+ const searchRef = useRef(null)
867
+ const panelRef = useRef(null)
868
+ const scrimRef = useRef(null)
869
+ const confirmRef = useRef(null)
870
+ const actionConfirmRef = useRef(null)
871
+ const triggerRef = useRef(null)
872
+ const deleteBtnRef = useRef(null)
873
+ const revertBtnRef = useRef(null)
874
+ const deleteOneBtnRef = useRef(null)
875
+ const detailReq = useRef(0)
876
+ const loadSeqRef = useRef(0)
877
+ const trashSeqRef = useRef(0)
878
+ const openRef = useRef(false)
879
+ const sessionRef = useRef(null)
880
+ openRef.current = open
881
+ sessionRef.current = target && target.sessionId ? target.sessionId : null
882
+
883
+ useEffect(() => {
884
+ ensurePanelStyle()
885
+ const handler = (e) => {
886
+ const d = e && e.detail ? e.detail : {}
887
+ if (!d.sessionId) return
888
+ const active = document.activeElement
889
+ if (!panelRef.current || !panelRef.current.contains(active)) triggerRef.current = active
890
+ loadSeqRef.current += 1
891
+ trashSeqRef.current += 1
892
+ detailReq.current += 1
893
+ setTarget({ sessionId: d.sessionId, title: d.title || null, running: d.running === true })
894
+ setOpen(true)
895
+ setState('loading')
896
+ setLoadError(null)
897
+ setMessages([])
898
+ setHits(null)
899
+ setQuery('')
900
+ setRole('all')
901
+ setIncludeShadowed(false)
902
+ setPicked(null)
903
+ setDetail('')
904
+ setDetailState('idle')
905
+ setTab('messages')
906
+ setTrash([])
907
+ setTrashState('idle')
908
+ setTrashError(null)
909
+ setConfirmDelete(false)
910
+ setConfirmTitle('')
911
+ setDeleteError(null)
912
+ setConfirmAction(null)
913
+ setPurgeId(null)
914
+ setChildId(null)
915
+ setError(null)
916
+ setDone('')
917
+ setScrollTop(0)
918
+ }
919
+ window.addEventListener(EVENT, handler)
920
+ return () => window.removeEventListener(EVENT, handler)
921
+ }, [])
922
+
923
+ const sid = target && target.sessionId
924
+
925
+ const loadMessages = useCallback(async (quiet) => {
926
+ if (!sid) return
927
+ const requestId = ++loadSeqRef.current
928
+ const requestSid = sid
929
+ if (!quiet) { setState('loading'); setLoadError(null) }
930
+ try {
931
+ const data = await fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(requestSid) + '&view=compact')
932
+ if (requestId !== loadSeqRef.current) return
933
+ setMessages(Array.isArray(data.messages) ? data.messages : [])
934
+ setTarget((prev) => prev && prev.sessionId === requestSid ? {
935
+ ...prev,
936
+ running: data.running === true,
937
+ title: prev.title || (data.session && data.session.title) || null,
938
+ expectedTitle: (data.session && data.session.confirmTitle) || prev.expectedTitle || prev.title || prev.sessionId,
939
+ } : prev)
940
+ setLoadError(null)
941
+ setError(null)
942
+ setState('ready')
943
+ } catch (reason) {
944
+ if (requestId !== loadSeqRef.current) return
945
+ const message = t('panel.loadFail') + (reason && reason.message ? reason.message : String(reason))
946
+ if (quiet) setError(message)
947
+ else { setLoadError(message); setState('error') }
948
+ }
949
+ }, [sid, t])
950
+
951
+ useEffect(() => {
952
+ if (!open || !sid) return
953
+ loadMessages(false)
954
+ }, [open, sid, loadMessages])
955
+
956
+ useEffect(() => {
957
+ if (!open || tab !== 'messages') return
958
+ const q = query.trim()
959
+ if (!q) { setHits(null); setSearching(false); return }
960
+ setSearching(true)
961
+ let cancelled = false
962
+ const timer = setTimeout(() => {
963
+ setError(null)
964
+ const url = '/api/message-ops/search?sessionId=' + encodeURIComponent(sid)
965
+ + '&q=' + encodeURIComponent(q)
966
+ + (role !== 'all' ? '&role=' + encodeURIComponent(role) : '')
967
+ + '&limit=' + PANEL_SEARCH_LIMIT
968
+ fetch(url)
969
+ .then((res) => res.json().catch(() => null).then((data) => ({ res, data })))
970
+ .then(({ res, data }) => {
971
+ if (cancelled) return
972
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
973
+ setHits(Array.isArray(data.results) ? data.results : [])
974
+ setError(null)
975
+ })
976
+ .catch((reason) => {
977
+ if (!cancelled) setError(t('panel.searchFail') + (reason && reason.message ? reason.message : String(reason)))
978
+ })
979
+ .finally(() => { if (!cancelled) setSearching(false) })
980
+ }, 200)
981
+ return () => { cancelled = true; clearTimeout(timer) }
982
+ }, [open, tab, sid, query, role, t])
983
+
984
+ const loadTrash = useCallback(async () => {
985
+ const requestId = ++trashSeqRef.current
986
+ setTrashState('loading')
987
+ setTrashError(null)
988
+ try {
989
+ const res = await fetch('/api/message-ops/session/trash')
990
+ const data = await res.json().catch(() => null)
991
+ if (requestId !== trashSeqRef.current) return
992
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
993
+ setTrash(Array.isArray(data.entries) ? data.entries : [])
994
+ setTrashError(null)
995
+ setTrashState('ready')
996
+ } catch (reason) {
997
+ if (requestId !== trashSeqRef.current) return
998
+ setTrashError(t('panel.loadFail') + (reason && reason.message ? reason.message : String(reason)))
999
+ setTrashState('error')
1000
+ }
1001
+ }, [t])
1002
+
1003
+ useEffect(() => {
1004
+ if (open && tab === 'trash') loadTrash()
1005
+ }, [open, tab, loadTrash])
1006
+
1007
+ const close = useCallback(() => {
1008
+ if (busy) return
1009
+ loadSeqRef.current += 1
1010
+ trashSeqRef.current += 1
1011
+ detailReq.current += 1
1012
+ setOpen(false)
1013
+ setTarget(null)
1014
+ setPicked(null)
1015
+ setConfirmDelete(false)
1016
+ setConfirmAction(null)
1017
+ setDeleteError(null)
1018
+ setLoadError(null)
1019
+ setTrashError(null)
1020
+ }, [busy])
1021
+
1022
+ const closeConfirm = useCallback(() => {
1023
+ if (busy === 'session-delete') return
1024
+ setConfirmDelete(false)
1025
+ setConfirmTitle('')
1026
+ setDeleteError(null)
1027
+ setTimeout(() => {
1028
+ const el = deleteBtnRef.current
1029
+ if (el && !el.disabled) el.focus()
1030
+ else if (panelRef.current) panelRef.current.focus()
1031
+ }, 0)
1032
+ }, [busy])
1033
+
1034
+ const cancelAction = useCallback(() => {
1035
+ if (busy) return
1036
+ const mode = confirmAction
1037
+ setConfirmAction(null)
1038
+ setTimeout(() => {
1039
+ const targetRef = mode === 'revert' ? revertBtnRef.current : deleteOneBtnRef.current
1040
+ if (targetRef && !targetRef.disabled) targetRef.focus()
1041
+ else if (panelRef.current) panelRef.current.focus()
1042
+ }, 0)
1043
+ }, [busy, confirmAction])
1044
+
1045
+ useEffect(() => {
1046
+ if (!open) return undefined
1047
+ const onKey = (e) => {
1048
+ if (e.key === 'Escape') {
1049
+ if (busy) return
1050
+ if (confirmDelete) closeConfirm()
1051
+ else if (confirmAction) cancelAction()
1052
+ else close()
1053
+ } else if (e.key === '/') {
1054
+ if (confirmDelete || confirmAction) return
1055
+ const el = e.target
1056
+ const tag = el && el.tagName
1057
+ if (el && (tag === 'INPUT' || tag === 'TEXTAREA' || el.isContentEditable)) return
1058
+ e.preventDefault()
1059
+ if (searchRef.current) searchRef.current.focus()
1060
+ }
1061
+ }
1062
+ window.addEventListener('keydown', onKey)
1063
+ return () => window.removeEventListener('keydown', onKey)
1064
+ }, [open, busy, confirmDelete, confirmAction, close, closeConfirm, cancelAction])
1065
+
1066
+ useEffect(() => {
1067
+ if (!open) return undefined
1068
+ if (!triggerRef.current) triggerRef.current = document.activeElement
1069
+ const timer = setTimeout(() => {
1070
+ if (searchRef.current) searchRef.current.focus()
1071
+ else if (panelRef.current) panelRef.current.focus()
1072
+ }, 0)
1073
+ const scrim = scrimRef.current
1074
+ const parent = scrim && scrim.parentElement
1075
+ const hidden = []
1076
+ if (parent) {
1077
+ for (const child of Array.from(parent.children)) {
1078
+ if (child === scrim || child.tagName === 'SCRIPT' || child.tagName === 'STYLE') continue
1079
+ hidden.push({ child, inert: child.hasAttribute('inert'), aria: child.getAttribute('aria-hidden') })
1080
+ child.setAttribute('inert', '')
1081
+ child.setAttribute('aria-hidden', 'true')
1082
+ }
1083
+ }
1084
+ return () => {
1085
+ clearTimeout(timer)
1086
+ for (const item of hidden) {
1087
+ if (!item.inert) item.child.removeAttribute('inert')
1088
+ if (item.aria === null) item.child.removeAttribute('aria-hidden')
1089
+ else item.child.setAttribute('aria-hidden', item.aria)
1090
+ }
1091
+ if (openRef.current) return
1092
+ const trigger = triggerRef.current
1093
+ triggerRef.current = null
1094
+ if (trigger && typeof trigger.focus === 'function') {
1095
+ setTimeout(() => { try { trigger.focus() } catch { /* detached trigger */ } }, 0)
1096
+ }
1097
+ }
1098
+ }, [open, sid])
1099
+
1100
+ useEffect(() => {
1101
+ if (!open) return undefined
1102
+ const onKeyDown = (e) => {
1103
+ if (e.key !== 'Tab') return
1104
+ const scope = confirmDelete ? confirmRef.current : (confirmAction ? actionConfirmRef.current : panelRef.current)
1105
+ if (!scope) return
1106
+ const nodes = focusablesIn(scope)
1107
+ if (!nodes.length) {
1108
+ e.preventDefault()
1109
+ scope.focus()
1110
+ return
1111
+ }
1112
+ const first = nodes[0]
1113
+ const last = nodes[nodes.length - 1]
1114
+ const active = document.activeElement
1115
+ if (active === scope || !scope.contains(active)) {
1116
+ e.preventDefault()
1117
+ const fallback = e.shiftKey ? last : first
1118
+ fallback.focus()
1119
+ } else if (e.shiftKey && active === first) {
1120
+ e.preventDefault()
1121
+ last.focus()
1122
+ } else if (!e.shiftKey && active === last) {
1123
+ e.preventDefault()
1124
+ first.focus()
1125
+ }
1126
+ }
1127
+ document.addEventListener('keydown', onKeyDown, true)
1128
+ return () => document.removeEventListener('keydown', onKeyDown, true)
1129
+ }, [open, confirmDelete, confirmAction])
1130
+
1131
+ useEffect(() => {
1132
+ if (!open) return
1133
+ if (confirmDelete) {
1134
+ const input = confirmRef.current && confirmRef.current.querySelector('input')
1135
+ if (input) input.focus()
1136
+ } else if (confirmAction) {
1137
+ const first = actionConfirmRef.current && actionConfirmRef.current.querySelector('button')
1138
+ if (first) first.focus()
1139
+ }
1140
+ }, [open, confirmDelete, confirmAction])
1141
+
1142
+ const baseRows = query.trim() ? (hits || []) : messages
1143
+ const rows = baseRows
1144
+ .filter((m) => m && m.role !== 'system'
1145
+ && (role === 'all' || m.role === role)
1146
+ && (includeShadowed || !m.shadowed))
1147
+ .sort((a, b) => b.seq - a.seq)
1148
+ const activeIndex = picked ? rows.findIndex((m) => m.seq === picked.seq) : -1
1149
+
1150
+ const clearPick = () => {
1151
+ detailReq.current += 1
1152
+ setPicked(null)
1153
+ setDetail('')
1154
+ setDetailState('idle')
1155
+ setConfirmAction(null)
1156
+ }
1157
+
1158
+ const previewRow = (m) => {
1159
+ if (!m) return
1160
+ detailReq.current += 1
1161
+ setPicked(m)
1162
+ setDetail(m.snippet || '')
1163
+ setDetailState('ready')
1164
+ setConfirmAction(null)
1165
+ setDone('')
1166
+ }
1167
+
1168
+ const scrollRowIntoView = (index) => {
1169
+ const el = listRef.current
1170
+ if (!el) return
1171
+ const top = index * PANEL_ROW_H
1172
+ const view = el.clientHeight || viewport
1173
+ let next = el.scrollTop
1174
+ if (top < next) next = top
1175
+ else if (top + PANEL_ROW_H > next + view) next = top + PANEL_ROW_H - view
1176
+ if (next !== el.scrollTop) {
1177
+ el.scrollTop = next
1178
+ setScrollTop(next)
1179
+ }
1180
+ }
1181
+
1182
+ const handleListKeyDown = (e) => {
1183
+ if (!rows.length) return
1184
+ const page = Math.max(1, Math.floor((listRef.current && listRef.current.clientHeight || viewport) / PANEL_ROW_H) - 1)
1185
+ let next = activeIndex
1186
+ if (e.key === 'ArrowDown') next = activeIndex < 0 ? 0 : Math.min(rows.length - 1, activeIndex + 1)
1187
+ else if (e.key === 'ArrowUp') next = activeIndex < 0 ? rows.length - 1 : Math.max(0, activeIndex - 1)
1188
+ else if (e.key === 'Home') next = 0
1189
+ else if (e.key === 'End') next = rows.length - 1
1190
+ else if (e.key === 'PageDown') next = activeIndex < 0 ? 0 : Math.min(rows.length - 1, activeIndex + page)
1191
+ else if (e.key === 'PageUp') next = activeIndex < 0 ? rows.length - 1 : Math.max(0, activeIndex - page)
1192
+ else if (e.key === 'Enter' || e.key === ' ') {
1193
+ e.preventDefault()
1194
+ const row = rows[activeIndex >= 0 ? activeIndex : 0]
1195
+ if (row) { pick(row); if (listRef.current) listRef.current.focus() }
1196
+ return
1197
+ } else {
1198
+ return
1199
+ }
1200
+ e.preventDefault()
1201
+ const row = rows[next]
1202
+ if (!row) return
1203
+ previewRow(row)
1204
+ scrollRowIntoView(next)
1205
+ }
1206
+
1207
+ useEffect(() => {
1208
+ if (!open || tab !== 'messages') return undefined
1209
+ const el = listRef.current
1210
+ if (!el) return undefined
1211
+ const measure = () => setViewport(el.clientHeight || 480)
1212
+ measure()
1213
+ if (typeof ResizeObserver === 'undefined') return undefined
1214
+ const ro = new ResizeObserver(measure)
1215
+ ro.observe(el)
1216
+ return () => ro.disconnect()
1217
+ }, [open, tab, rows.length])
1218
+
1219
+ useEffect(() => {
1220
+ if (!open || tab !== 'messages') return
1221
+ const el = listRef.current
1222
+ if (!el) return
1223
+ const max = Math.max(0, rows.length * PANEL_ROW_H - (el.clientHeight || viewport))
1224
+ if (el.scrollTop > max) {
1225
+ el.scrollTop = max
1226
+ setScrollTop(max)
1227
+ }
1228
+ }, [open, tab, rows.length, viewport])
1229
+
1230
+ const pick = useCallback((m) => {
1231
+ if (!m || busy) return
1232
+ setConfirmAction(null)
1233
+ setPicked(m)
1234
+ setDetail(m.snippet || '')
1235
+ setDetailState('loading')
1236
+ setDone('')
1237
+ const req = ++detailReq.current
1238
+ fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(sid) + '&seq=' + encodeURIComponent(m.seq))
1239
+ .then((res) => res.json().catch(() => null).then((data) => ({ res, data })))
1240
+ .then(({ res, data }) => {
1241
+ if (req !== detailReq.current) return
1242
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1243
+ setDetail(typeof data.text === 'string' && data.text ? data.text : (m.snippet || ''))
1244
+ setDetailState('ready')
1245
+ })
1246
+ .catch(() => {
1247
+ if (req !== detailReq.current) return
1248
+ setDetail(m.snippet || '')
1249
+ setDetailState('ready')
1250
+ })
1251
+ }, [busy, sid])
1252
+
1253
+ const runAction = useCallback(async (mode, confirmed) => {
1254
+ if (!target || !picked || busy) return
1255
+ if (target.running && mode !== 'branch') return
1256
+ if ((mode === 'revert' || mode === 'delete') && confirmed !== true) return
1257
+ const actionSid = target.sessionId
1258
+ setBusy(mode)
1259
+ setError(null)
1260
+ setDone('')
1261
+ try {
1262
+ if (mode === 'branch') {
1263
+ const forkPath = pickForkPath(__sessionsSvc)
1264
+ if (forkPath.kind !== 'official') throw new Error(t('fork.unavailable'))
1265
+ const created = await forkPath.fork({ sessionId: target.sessionId, atSeq: picked.seq, increaseTitle: true })
1266
+ if (sessionRef.current !== actionSid) return
1267
+ setChildId(created || null)
1268
+ setDone(t('panel.branchDone', { id: String(created || '') }))
1269
+ notifyDone(t('panel.branchDone', { id: String(created || '') }))
1270
+ return
1271
+ }
1272
+ const res = await fetch('/api/message-ops/' + mode, {
1273
+ method: 'POST',
1274
+ headers: { 'content-type': 'application/json' },
1275
+ body: JSON.stringify({ sessionId: target.sessionId, seq: picked.seq }),
1276
+ })
1277
+ const data = await res.json().catch(() => null)
1278
+ if (sessionRef.current !== actionSid) return
1279
+ if (!res.ok || !data || data.ok !== true) {
1280
+ if (res.status === 409) setTarget((prev) => prev ? { ...prev, running: true } : prev)
1281
+ throw new Error((data && data.error) || ('HTTP ' + res.status))
1282
+ }
1283
+ if (mode === 'revert') {
1284
+ setMessages((prev) => prev.map((m) => (m.seq >= picked.seq ? { ...m, shadowed: true, visible: false } : m)))
1285
+ if (picked.role === 'user') {
1286
+ try { refillComposer(target.sessionId, picked.seq) } catch { /* non-blocking */ }
1287
+ }
1288
+ } else {
1289
+ setMessages((prev) => prev.map((m) => (m.seq === picked.seq ? { ...m, shadowed: true, visible: false } : m)))
1290
+ }
1291
+ const msg = t(mode === 'revert' ? 'panel.revertDone' : 'panel.deleteDone')
1292
+ setDone(msg)
1293
+ setConfirmAction(null)
1294
+ setTimeout(() => { if (listRef.current) listRef.current.focus() }, 0)
1295
+ notifyDone(msg)
1296
+ emitChanged()
1297
+ try {
1298
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(target.sessionId)
1299
+ } catch { /* view rebuild is best effort */ }
1300
+ setTimeout(() => { loadMessages(true).catch(() => {}) }, 650)
1301
+ } catch (reason) {
1302
+ if (sessionRef.current !== actionSid) return
1303
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1304
+ } finally {
1305
+ setBusy('')
1306
+ }
1307
+ }, [target, picked, busy, t, loadMessages])
1308
+
1309
+ const deleteSession = useCallback(async () => {
1310
+ if (!target || busy || target.running) return
1311
+ const expected = target.expectedTitle || ''
1312
+ if (!expected || confirmTitle.trim() !== expected) return
1313
+ const actionSid = target.sessionId
1314
+ setBusy('session-delete')
1315
+ setDeleteError(null)
1316
+ setDone('')
1317
+ try {
1318
+ const res = await fetch('/api/message-ops/session/delete', {
1319
+ method: 'POST',
1320
+ headers: { 'content-type': 'application/json' },
1321
+ body: JSON.stringify({ sessionId: target.sessionId, confirmTitle: confirmTitle }),
1322
+ })
1323
+ const data = await res.json().catch(() => null)
1324
+ if (sessionRef.current !== actionSid) return
1325
+ if (!res.ok || !data || data.ok !== true) {
1326
+ if (res.status === 409) setTarget((prev) => prev ? { ...prev, running: true } : prev)
1327
+ throw new Error((data && data.error) || ('HTTP ' + res.status))
1328
+ }
1329
+ setConfirmDelete(false)
1330
+ setDone(t('panel.deleted'))
1331
+ notifyDone(t('panel.deleted'))
1332
+ emitChanged()
1333
+ setTimeout(() => { try { window.location.reload() } catch { /* non-browser guard */ } }, 700)
1334
+ } catch (reason) {
1335
+ if (sessionRef.current !== actionSid) return
1336
+ setDeleteError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1337
+ } finally {
1338
+ setBusy('')
1339
+ }
1340
+ }, [target, busy, confirmTitle, t])
1341
+
1342
+ const restoreEntry = useCallback(async (trashId) => {
1343
+ if (busy) return
1344
+ setBusy('restore:' + trashId)
1345
+ setError(null)
1346
+ setDone('')
1347
+ try {
1348
+ const res = await fetch('/api/message-ops/session/restore', {
1349
+ method: 'POST',
1350
+ headers: { 'content-type': 'application/json' },
1351
+ body: JSON.stringify({ trashId }),
1352
+ })
1353
+ const data = await res.json().catch(() => null)
1354
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1355
+ setTrash((prev) => prev.filter((x) => x.trashId !== trashId))
1356
+ setDone(t('panel.restored'))
1357
+ notifyDone(t('panel.restored'))
1358
+ emitChanged()
1359
+ setTimeout(() => { try { window.location.reload() } catch { /* non-browser guard */ } }, 700)
1360
+ } catch (reason) {
1361
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1362
+ } finally {
1363
+ setBusy('')
1364
+ }
1365
+ }, [busy, t])
1366
+
1367
+ const purgeEntry = useCallback(async (trashId) => {
1368
+ if (busy) return
1369
+ if (purgeId !== trashId) { setPurgeId(trashId); return }
1370
+ setBusy('purge:' + trashId)
1371
+ setError(null)
1372
+ setDone('')
1373
+ try {
1374
+ const res = await fetch('/api/message-ops/session/purge', {
1375
+ method: 'POST',
1376
+ headers: { 'content-type': 'application/json' },
1377
+ body: JSON.stringify({ trashId }),
1378
+ })
1379
+ const data = await res.json().catch(() => null)
1380
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1381
+ setTrash((prev) => prev.filter((x) => x.trashId !== trashId))
1382
+ setPurgeId(null)
1383
+ setDone(t('panel.purged'))
1384
+ notifyDone(t('panel.purged'))
1385
+ } catch (reason) {
1386
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1387
+ } finally {
1388
+ setBusy('')
1389
+ }
1390
+ }, [busy, purgeId, t])
1391
+
1392
+ if (!open) return null
1393
+
1394
+ const pickedLive = picked ? (messages.find((m) => m.seq === picked.seq) || picked) : null
1395
+ const canAct = !busy && !target.running && pickedLive && !pickedLive.shadowed
1396
+ const visibleCount = messages.filter((m) => m.role !== 'system' && m.visible && !m.shadowed).length
1397
+ const shadowedCount = messages.filter((m) => m.role !== 'system' && m.shadowed).length
1398
+ const totalCount = messages.filter((m) => m.role !== 'system').length
1399
+ const revertImpact = pickedLive
1400
+ ? messages.filter((m) => m.role !== 'system' && !m.shadowed && m.seq >= pickedLive.seq)
1401
+ : []
1402
+ const revertCount = revertImpact.length
1403
+ const revertVisibleCount = revertImpact.filter((m) => m.visible).length
1404
+ const revertEnd = revertImpact.reduce((max, m) => Math.max(max, m.seq), pickedLive ? pickedLive.seq : 0)
1405
+ const expectedDeleteTitle = target.expectedTitle || ''
1406
+ const deleteBlockedReason = target.running
1407
+ ? t('panel.running')
1408
+ : state !== 'ready'
1409
+ ? (state === 'error' ? t('panel.loadFail') : t('panel.loading'))
1410
+ : !expectedDeleteTitle ? t('panel.deleteUnavailable') : ''
1411
+ const canConfirmDelete = !busy && state === 'ready' && !target.running && !!expectedDeleteTitle
1412
+ && confirmTitle.trim() === expectedDeleteTitle
1413
+ const start = Math.min(Math.max(0, rows.length - 1), Math.max(0, Math.floor(scrollTop / PANEL_ROW_H) - 6))
1414
+ const end = Math.min(rows.length, start + Math.ceil(viewport / PANEL_ROW_H) + 12)
1415
+ const windowRows = rows.slice(start, end)
1416
+ const activeRendered = picked && windowRows.some((m) => m.seq === picked.seq)
1417
+ const showSearchLoading = searching && query.trim().length > 0
1418
+
1419
+ return React.createElement('div', {
1420
+ className: 'mopsPanelScrim', role: 'presentation', ref: scrimRef,
1421
+ onMouseDown: (e) => { if (e.target === e.currentTarget) close() },
1422
+ },
1423
+ React.createElement('section', {
1424
+ className: 'mopsPanel', role: 'dialog', 'aria-modal': 'true',
1425
+ 'aria-labelledby': 'mops-panel-title', 'aria-describedby': 'mops-panel-session',
1426
+ 'aria-busy': busy || state === 'loading' ? 'true' : undefined,
1427
+ tabIndex: -1, ref: panelRef,
1428
+ style: { position: 'relative' },
1429
+ },
1430
+ React.createElement('header', { className: 'mopsPanelHead' },
1431
+ React.createElement('div', { style: { minWidth: 0 } },
1432
+ React.createElement('div', { className: 'mopsPanelKicker' }, t('dialog.title')),
1433
+ React.createElement('div', { className: 'mopsPanelTitle', id: 'mops-panel-title' }, target.title || target.expectedTitle || target.sessionId),
1434
+ React.createElement('div', { className: 'mopsPanelSub', id: 'mops-panel-session' }, target.sessionId)),
1435
+ React.createElement('button', {
1436
+ type: 'button', className: 'mopsPanelClose', title: t('dialog.cancel'),
1437
+ 'aria-label': t('dialog.cancel'),
1438
+ onClick: close, disabled: !!busy,
1439
+ }, '×')),
1440
+ React.createElement('div', { className: 'mopsTabs' },
1441
+ React.createElement('button', {
1442
+ type: 'button', className: 'mopsTab' + (tab === 'messages' ? ' on' : ''),
1443
+ onClick: () => { setTab('messages'); setConfirmDelete(false); setConfirmAction(null); setDeleteError(null) },
1444
+ }, t('panel.messages') + ' ' + totalCount),
1445
+ React.createElement('button', {
1446
+ type: 'button', className: 'mopsTab' + (tab === 'trash' ? ' on' : ''),
1447
+ onClick: () => { setTab('trash'); setConfirmDelete(false); setConfirmAction(null); setDeleteError(null) },
1448
+ }, t('panel.trash') + (trash.length ? ' ' + trash.length : ''))),
1449
+ target.running && tab === 'messages'
1450
+ ? React.createElement('div', { className: 'mopsBanner warn' }, t('panel.running')) : null,
1451
+ error ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, error) : null,
1452
+ done ? React.createElement('div', { className: 'mopsBanner ok' }, done,
1453
+ childId ? React.createElement('button', {
1454
+ type: 'button', className: 'mopsAction primary', style: { marginLeft: 10 },
1455
+ onClick: () => { try { if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(childId) } catch { /* best effort */ } },
1456
+ }, t('panel.openNew')) : null) : null,
1457
+ tab === 'messages'
1458
+ ? React.createElement(React.Fragment, null,
1459
+ React.createElement('div', { className: 'mopsSearchRow' },
1460
+ React.createElement('input', {
1461
+ ref: searchRef, className: 'mopsSearch', value: query,
1462
+ placeholder: t('panel.searchHint'), 'aria-label': t('panel.search'),
1463
+ onChange: (e) => { setQuery(e.target.value); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1464
+ })),
1465
+ React.createElement('div', { className: 'mopsChips' },
1466
+ ['all', 'user', 'assistant', 'tool'].map((key) => React.createElement('button', {
1467
+ key, type: 'button', className: 'mopsChip' + (role === key ? ' on' : ''),
1468
+ onClick: () => { setRole(key); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1469
+ }, t('panel.' + key))),
1470
+ React.createElement('label', { className: 'mopsToggle' },
1471
+ React.createElement('input', {
1472
+ type: 'checkbox', checked: includeShadowed,
1473
+ onChange: (e) => { setIncludeShadowed(e.target.checked); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1474
+ }), t('panel.includeShadowed'))),
1475
+ React.createElement('div', {
1476
+ className: 'mopsList', ref: listRef,
1477
+ role: state === 'ready' && rows.length ? 'listbox' : 'region',
1478
+ tabIndex: state === 'ready' && rows.length ? 0 : -1,
1479
+ 'aria-label': t('panel.messages'),
1480
+ 'aria-busy': state === 'loading' || showSearchLoading ? 'true' : undefined,
1481
+ 'aria-activedescendant': state === 'ready' && activeRendered ? 'mops-opt-' + picked.seq : undefined,
1482
+ onKeyDown: handleListKeyDown,
1483
+ onScroll: (e) => setScrollTop(e.currentTarget.scrollTop),
1484
+ },
1485
+ state === 'loading' || state === 'idle'
1486
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1487
+ : state === 'error'
1488
+ ? React.createElement('div', { className: 'mopsEmpty mopsErrorState', role: 'alert' },
1489
+ React.createElement('span', null, loadError || t('panel.loadFail')),
1490
+ React.createElement('button', {
1491
+ type: 'button', className: 'mopsAction',
1492
+ onClick: () => { loadMessages(false); setTimeout(() => { if (searchRef.current) searchRef.current.focus() }, 0) },
1493
+ }, t('panel.retry')))
1494
+ : rows.length === 0
1495
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, showSearchLoading ? t('panel.searching') : (query.trim() ? t('panel.noMatch') : t('panel.empty')))
1496
+ : React.createElement('div', { style: { height: rows.length * PANEL_ROW_H, position: 'relative' } },
1497
+ windowRows.map((m, i) => React.createElement('div', {
1498
+ key: m.seq, id: 'mops-opt-' + m.seq, role: 'option',
1499
+ 'aria-selected': pickedLive && pickedLive.seq === m.seq,
1500
+ 'aria-setsize': rows.length, 'aria-posinset': start + i + 1,
1501
+ tabIndex: -1,
1502
+ className: 'mopsRow' + (pickedLive && pickedLive.seq === m.seq ? ' on' : '') + (m.shadowed ? ' shadowed' : ''),
1503
+ style: { top: (start + i) * PANEL_ROW_H, height: PANEL_ROW_H },
1504
+ onClick: () => { pick(m); if (listRef.current) listRef.current.focus() },
1505
+ title: '#' + m.seq + ' ' + (m.role || '') + ' · ' + (m.snippet || ''),
1506
+ 'aria-label': '#' + m.seq + ' ' + (m.role || '') + (m.shadowed ? ' ' + t('panel.shadowed') : '') + ' · ' + (m.snippet || '') + (m.time ? ' · ' + fmtClock(m.time) : ''),
1507
+ },
1508
+ React.createElement('span', { className: 'mopsSeq' }, '#' + m.seq),
1509
+ React.createElement('span', { className: 'mopsRole' }, roleCode(m.role)),
1510
+ React.createElement('span', { className: 'mopsSnippet' }, m.snippet || '—'),
1511
+ React.createElement('span', { className: 'mopsClock' }, fmtClock(m.time)))))),
1512
+ React.createElement('div', { className: 'mopsDetail' },
1513
+ pickedLive
1514
+ ? React.createElement(React.Fragment, null,
1515
+ React.createElement('div', { className: 'mopsDetailMeta' },
1516
+ React.createElement('span', null, '#' + pickedLive.seq),
1517
+ React.createElement('span', null, pickedLive.role || ''),
1518
+ pickedLive.shadowed ? React.createElement('span', null, t('panel.shadowed')) : null,
1519
+ pickedLive.time ? React.createElement('span', null, fmtClock(pickedLive.time)) : null),
1520
+ React.createElement('pre', { className: 'mopsDetailText' },
1521
+ detailState === 'loading' ? t('panel.detailLoading') : (detail || pickedLive.snippet || '—')),
1522
+ React.createElement('div', { className: 'mopsActions' },
1523
+ React.createElement('button', {
1524
+ type: 'button', className: 'mopsAction primary', disabled: !canAct || !!confirmAction,
1525
+ ref: revertBtnRef,
1526
+ onClick: () => setConfirmAction('revert'),
1527
+ title: t('panel.revertHint'),
1528
+ }, t('panel.revert') + (revertCount ? ' · ' + revertCount : '')),
1529
+ React.createElement('button', {
1530
+ type: 'button', className: 'mopsAction danger', disabled: !canAct || !!confirmAction,
1531
+ ref: deleteOneBtnRef,
1532
+ onClick: () => setConfirmAction('delete'), title: t('panel.deleteHint'),
1533
+ }, t('panel.delete')),
1534
+ React.createElement('button', {
1535
+ type: 'button', className: 'mopsAction', disabled: !canAct || !!confirmAction,
1536
+ onClick: () => runAction('branch'), title: t('panel.branchHint'),
1537
+ }, t('panel.branch'))),
1538
+ confirmAction
1539
+ ? React.createElement('div', {
1540
+ className: 'mopsActionConfirm', ref: actionConfirmRef, role: 'group', tabIndex: -1,
1541
+ 'aria-labelledby': 'mops-action-confirm-title',
1542
+ },
1543
+ React.createElement('div', { className: 'mopsImpactTitle', id: 'mops-action-confirm-title' },
1544
+ t(confirmAction === 'revert' ? 'panel.revertConfirmTitle' : 'panel.deleteConfirmTitle', { seq: String(pickedLive.seq) })),
1545
+ React.createElement('div', { className: 'mopsImpact' },
1546
+ confirmAction === 'revert'
1547
+ ? t('panel.revertConfirmBody', {
1548
+ start: String(pickedLive.seq), end: String(revertEnd),
1549
+ n: String(revertCount), v: String(revertVisibleCount),
1550
+ })
1551
+ : t('panel.deleteConfirmBody')),
1552
+ React.createElement('div', { className: 'mopsConfirmRow' },
1553
+ React.createElement('button', {
1554
+ type: 'button', className: 'mopsAction', onClick: cancelAction, disabled: !!busy,
1555
+ }, t('panel.cancel')),
1556
+ React.createElement('button', {
1557
+ type: 'button', className: 'mopsAction danger',
1558
+ onClick: () => runAction(confirmAction, true),
1559
+ disabled: !!busy || !canAct,
1560
+ }, busy === confirmAction ? t('panel.busy') : t(confirmAction === 'revert' ? 'panel.confirmRevert' : 'panel.confirmDeleteOne'))))
1561
+ : null)
1562
+ : React.createElement('div', { className: 'mopsDetailHint' }, t('panel.selectHint'))),
1563
+ React.createElement('footer', { className: 'mopsPanelFoot' },
1564
+ React.createElement('span', { className: 'mopsCount' },
1565
+ t('panel.count', { n: String(totalCount), v: String(visibleCount), s: String(shadowedCount) })),
1566
+ React.createElement('button', {
1567
+ type: 'button', className: 'mopsDanger', ref: deleteBtnRef,
1568
+ disabled: !!busy || !!deleteBlockedReason,
1569
+ title: deleteBlockedReason || undefined,
1570
+ onClick: () => {
1571
+ setConfirmTitle('')
1572
+ setDeleteError(null)
1573
+ setConfirmAction(null)
1574
+ setConfirmDelete(true)
1575
+ },
1576
+ }, t('panel.deleteSession'))),
1577
+ confirmDelete
1578
+ ? React.createElement('div', {
1579
+ className: 'mopsConfirm', ref: confirmRef, role: 'alertdialog', 'aria-modal': 'true',
1580
+ 'aria-labelledby': 'mops-delete-title', 'aria-describedby': 'mops-delete-hint mops-delete-impact',
1581
+ tabIndex: -1,
1582
+ },
1583
+ React.createElement('h3', { id: 'mops-delete-title' }, t('panel.deleteSession')),
1584
+ React.createElement('p', { id: 'mops-delete-hint' }, t('panel.deleteSessionHint')),
1585
+ React.createElement('p', { className: 'mopsImpact', id: 'mops-delete-impact' },
1586
+ t('panel.deleteSessionImpact', { n: String(totalCount) })),
1587
+ target.running ? React.createElement('div', { className: 'mopsBanner warn', role: 'status' }, t('panel.running')) : null,
1588
+ deleteError ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, deleteError) : null,
1589
+ React.createElement('input', {
1590
+ id: 'mops-delete-title-input', value: confirmTitle, autoFocus: true,
1591
+ 'aria-label': t('panel.deleteSessionHint'),
1592
+ 'aria-describedby': 'mops-delete-hint',
1593
+ placeholder: expectedDeleteTitle || target.title || target.sessionId,
1594
+ disabled: !!busy || target.running || !expectedDeleteTitle,
1595
+ onChange: (e) => setConfirmTitle(e.target.value),
1596
+ onKeyDown: (e) => {
1597
+ if (e.key === 'Enter') {
1598
+ e.preventDefault()
1599
+ if (canConfirmDelete) deleteSession()
1600
+ } else if (e.key === 'Escape') {
1601
+ e.preventDefault()
1602
+ e.stopPropagation()
1603
+ closeConfirm()
1604
+ }
1605
+ },
1606
+ }),
1607
+ React.createElement('div', { className: 'mopsConfirmRow' },
1608
+ React.createElement('button', {
1609
+ type: 'button', className: 'mopsAction',
1610
+ onClick: closeConfirm, disabled: busy === 'session-delete',
1611
+ }, t('panel.cancel')),
1612
+ React.createElement('button', {
1613
+ type: 'button', className: 'mopsAction danger',
1614
+ disabled: !canConfirmDelete,
1615
+ onClick: deleteSession,
1616
+ }, busy === 'session-delete' ? t('panel.deleting') : t('panel.confirmDelete'))))
1617
+ : null)
1618
+ : React.createElement('div', { className: 'mopsList', style: { borderTop: 0 }, 'aria-busy': trashState === 'loading' ? 'true' : undefined },
1619
+ trashState === 'loading' || trashState === 'idle'
1620
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1621
+ : trashState === 'error'
1622
+ ? React.createElement('div', { className: 'mopsEmpty mopsErrorState', role: 'alert' },
1623
+ React.createElement('span', null, trashError || t('panel.loadFail')),
1624
+ React.createElement('button', {
1625
+ type: 'button', className: 'mopsAction',
1626
+ onClick: () => { loadTrash(); setTimeout(() => { if (panelRef.current) panelRef.current.focus() }, 0) },
1627
+ }, t('panel.retry')))
1628
+ : trash.length === 0
1629
+ ? React.createElement('div', { className: 'mopsEmpty' }, t('panel.trashEmpty'))
1630
+ : trash.map((item) => React.createElement('div', { className: 'mopsTrashItem', key: item.trashId },
1631
+ React.createElement('div', { className: 'mopsTrashMain' },
1632
+ React.createElement('div', { className: 'mopsTrashTitle' }, item.title || t('panel.untitled')),
1633
+ React.createElement('div', { className: 'mopsTrashMeta' },
1634
+ item.sessionId + (item.expiresAt ? ' · ' + t('panel.expires') + ' ' + new Date(item.expiresAt).toLocaleDateString() : ''))),
1635
+ React.createElement('button', {
1636
+ type: 'button', className: 'mopsAction', disabled: !!busy,
1637
+ onClick: () => restoreEntry(item.trashId),
1638
+ }, busy === 'restore:' + item.trashId ? t('panel.busy') : t('panel.restore')),
1639
+ React.createElement('button', {
1640
+ type: 'button', className: 'mopsAction danger', disabled: !!busy,
1641
+ onClick: () => purgeEntry(item.trashId),
1642
+ }, busy === 'purge:' + item.trashId ? t('panel.busy') : (purgeId === item.trashId ? t('panel.purgeConfirm') : t('panel.purge'))))))))
1643
+ }
1644
+
595
1645
  // --- 头部按钮 ---------------------------------------------------------------
596
1646
 
597
1647
  // 0.3.0 分支双路径选择:0.2.0+ 官方 sessions.fork({atSeq}) 优先。
@@ -920,6 +1970,7 @@ window.__ModuleLoader__.load({
920
1970
  }, [styleInjected])
921
1971
 
922
1972
  useEffect(() => {
1973
+ syncSyntheticTurnStyle([])
923
1974
  let alive = true
924
1975
  const onChange = () => load()
925
1976
  window.addEventListener(CHANGED_EVENT, onChange)
@@ -941,6 +1992,7 @@ window.__ModuleLoader__.load({
941
1992
  if (reqSeq !== reqSeqRef.current || reqSeq <= landedSeqRef.current) return
942
1993
  landedSeqRef.current = reqSeq
943
1994
  const msgs = data.messages || []
1995
+ syncSyntheticTurnStyle(msgs)
944
1996
  const act = activeMarkers(msgs)
945
1997
  setMarkers(act)
946
1998
  // 0.5.2(P2):标题口径 = 标记 range 内 visible=false 的去重 seq 数
@@ -974,6 +2026,7 @@ window.__ModuleLoader__.load({
974
2026
  return () => {
975
2027
  alive = false
976
2028
  loadRef.current = () => {}
2029
+ syncSyntheticTurnStyle([])
977
2030
  window.removeEventListener(CHANGED_EVENT, onChange)
978
2031
  }
979
2032
  }, [sessionId])
@@ -1773,7 +2826,10 @@ window.__ModuleLoader__.load({
1773
2826
  if (!cache || !Array.isArray(cache.rows)) return null
1774
2827
  for (var i = cache.rows.length - 1; i >= 0; i--) {
1775
2828
  var r = cache.rows[i]
1776
- if (r && r.seq != null && r.visible) return r
2829
+ // 0.11.3:必须同时排除 shadowed。只用 visible 会在「回滚刚落盘、索引还没刷新」
2830
+ // 的窗口里再次选中已被遮蔽的 seq → 服务端 409
2831
+ // `surface replace: start seq N not found in surface`(实测 2026-10-25)。
2832
+ if (r && r.seq != null && r.visible && r.shadowed !== true) return r
1777
2833
  }
1778
2834
  return null
1779
2835
  }
@@ -1811,6 +2867,15 @@ window.__ModuleLoader__.load({
1811
2867
  *
1812
2868
  * 0.9.6 统一出口 —— 此前「5 个入口只有 2 个回填」的事故史见 README「历史事故记录」#5。
1813
2869
  *
2870
+ * 0.11.3 修「回滚成功但输入框还是空的」:
2871
+ * 宿主 `inputActions.setDraft()` **只改编辑器,不落 localStorage**;
2872
+ * 只有 `persistDraft()`(→ 内部 persistCurrentDraft)才写
2873
+ * `dsh.conversation.<sessionId>`。而所有回滚入口紧接着都调
2874
+ * `openSession()` 重挂会话视图,挂载时 shell 会
2875
+ * `setDraft(readConversationDraft(sessionId))` —— 从 localStorage 重读。
2876
+ * 于是刚回填的文本被旧草稿(常见为空)覆盖回去,用户看到的就是空输入框。
2877
+ * 修法:回填后立刻 `persistDraft()` 落盘,让重建读到的就是同一份草稿。
2878
+ *
1814
2879
  * 取文本规则:rowsCache 里 seq <= boundary 的最后一条带 fullText 的行。
1815
2880
  * - /undo → boundary 就是被回滚的那条用户消息 → 取到它自己 ✓
1816
2881
  * - AI 时钟按钮 → boundary 是 AI 消息 seq → 取到它之前那条用户消息 ✓
@@ -1826,6 +2891,10 @@ window.__ModuleLoader__.load({
1826
2891
  if (!rows.length) return false
1827
2892
  if (!__inputActions || typeof __inputActions.setDraft !== 'function') return false
1828
2893
  __inputActions.setDraft(rows[rows.length - 1].fullText)
2894
+ // 关键:不落盘的话,紧随其后的 openSession 会从 localStorage 读回旧草稿。
2895
+ if (typeof __inputActions.persistDraft === 'function') {
2896
+ try { __inputActions.persistDraft() } catch (e) { console.warn('[message-ops] persistDraft failed:', e) }
2897
+ }
1829
2898
  return true
1830
2899
  } catch (e) {
1831
2900
  // 原来这里 `catch {}` 完全静默 —— 失败了连痕迹都没有,排查时看不到
@@ -1852,6 +2921,15 @@ window.__ModuleLoader__.load({
1852
2921
  .then(async (res) => {
1853
2922
  const data = await res.json().catch(() => ({}))
1854
2923
  if (!res.ok || !data.ok) throw new Error(data.error || ('HTTP ' + res.status))
2924
+ // 0.11.3:立刻把本行标成已遮蔽,否则 afterWrite 的异步刷新窗里
2925
+ // 再点一次 /undo 仍会选中同一个 seq → 409。
2926
+ const rowsCache = __peekRowsCache ? __peekRowsCache() : null
2927
+ if (rowsCache && Array.isArray(rowsCache.rows)) {
2928
+ for (const r of rowsCache.rows) {
2929
+ if (r && typeof r.seq === 'number' && r.seq >= target.seq) r.shadowed = true
2930
+ }
2931
+ rowsCache.at = 0
2932
+ }
1855
2933
  refillComposer(rawSid, target.seq) // 先回填,再重建视图(与对话框一致)
1856
2934
  afterWrite(rawSid, __t('undo.done.undo'))
1857
2935
  })
@@ -1995,7 +3073,7 @@ window.__ModuleLoader__.load({
1995
3073
  ctx.slots.inject(OVERLAY_SLOT, () => ctx.slots.register({
1996
3074
  name: OVERLAY_SLOT, id: DIALOG_ID, order: 101,
1997
3075
  ...(__locale ? { locale: NS } : {}),
1998
- }, OpsDialog))
3076
+ }, window.__MOPS_LEGACY_DIALOG === true ? OpsDialog : OpsPanel))
1999
3077
  installSidebarOps()
2000
3078
  installUserRevertInjector()
2001
3079
  }