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

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
 
@@ -592,6 +718,924 @@ window.__ModuleLoader__.load({
592
718
  ])
593
719
  }
594
720
 
721
+ // --- A · 功能主义抽屉 -------------------------------------------------------
722
+
723
+ const PANEL_ROW_H = 46
724
+ const PANEL_SEARCH_LIMIT = 100
725
+
726
+ function fmtClock(value) {
727
+ if (typeof value !== 'number') return ''
728
+ try {
729
+ return new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
730
+ } catch { return '' }
731
+ }
732
+
733
+ function roleCode(role) {
734
+ if (role === 'user') return 'U'
735
+ if (role === 'assistant') return 'A'
736
+ if (role === 'tool') return 'T'
737
+ return 'S'
738
+ }
739
+
740
+ function focusablesIn(root) {
741
+ if (!root || typeof root.querySelectorAll !== 'function') return []
742
+ const selector = 'button:not([disabled]),[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'
743
+ return Array.prototype.slice.call(root.querySelectorAll(selector)).filter((el) => {
744
+ if (el.getAttribute('aria-hidden') === 'true') return false
745
+ return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0
746
+ })
747
+ }
748
+
749
+ function ensurePanelStyle() {
750
+ try {
751
+ if (document.getElementById('dsh-message-ops-panel-style')) return
752
+ const tag = document.createElement('style')
753
+ tag.id = 'dsh-message-ops-panel-style'
754
+ tag.textContent = [
755
+ '.mopsPanelScrim{position:fixed;inset:0;z-index:1200;background:rgba(15,17,21,.18);display:flex;justify-content:flex-end}',
756
+ '.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}',
757
+ '.mopsPanel *{box-sizing:border-box}',
758
+ '.mopsPanel button{font:inherit;color:inherit;border-radius:0}',
759
+ '.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)}',
760
+ '.mopsPanelKicker{font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
761
+ '.mopsPanelTitle{font-size:15px;font-weight:600;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:420px}',
762
+ '.mopsPanelSub{font-size:11px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-top:2px}',
763
+ '.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}',
764
+ '.mopsPanelClose:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(15,17,21,.06))}',
765
+ '.mopsTabs{display:flex;border-bottom:1px solid var(--dsw-alias-border-l2,#e6e6e6)}',
766
+ '.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)}',
767
+ '.mopsTab.on{border-bottom-color:var(--dsw-alias-brand-primary,#4d6bfe);color:var(--dsw-alias-label-primary,#0f1115);font-weight:600}',
768
+ '.mopsSearchRow{display:flex;gap:8px;padding:12px 18px 8px}',
769
+ '.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}',
770
+ '.mopsSearch:focus{border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
771
+ '.mopsChips{display:flex;gap:6px;padding:0 18px 10px;flex-wrap:wrap;align-items:center}',
772
+ '.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)}',
773
+ '.mopsChip.on{border-color:var(--dsw-alias-label-primary,#0f1115);background:var(--dsw-alias-label-primary,#0f1115);color:var(--dsw-alias-bg-primary,#fff)}',
774
+ '.mopsToggle{display:inline-flex;align-items:center;gap:5px;font-size:11px;color:var(--dsw-alias-label-secondary,#6b6b70);margin-left:auto;cursor:pointer}',
775
+ '.mopsToggle input{accent-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
776
+ '.mopsList{flex:1;min-height:0;overflow-y:auto;position:relative;border-top:1px solid var(--dsw-alias-border-l1,#efefef)}',
777
+ '.mopsList:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d6bfe);outline-offset:-2px}',
778
+ '.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}',
779
+ '.mopsRow:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(15,17,21,.045))}',
780
+ '.mopsRow.on{background:rgba(77,107,254,.08);box-shadow:inset 2px 0 0 var(--dsw-alias-brand-primary,#4d6bfe)}',
781
+ '.mopsRow.shadowed{opacity:.42}',
782
+ '.mopsSeq{font-variant-numeric:tabular-nums;font-size:10px;color:var(--dsw-alias-label-tertiary,#9a9aa0)}',
783
+ '.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)}',
784
+ '.mopsSnippet{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}',
785
+ '.mopsClock{font-size:10px;color:var(--dsw-alias-label-tertiary,#9a9aa0);text-align:right;font-variant-numeric:tabular-nums}',
786
+ '.mopsEmpty{padding:28px 18px;color:var(--dsw-alias-label-tertiary,#8a8a8e);font-size:12px}',
787
+ '.mopsErrorState{display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap;color:var(--dsw-alias-state-error-primary,#c63b32)}',
788
+ '.mopsErrorState .mopsAction{flex:none}',
789
+ '.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)}',
790
+ '.mopsDetailMeta{display:flex;gap:8px;align-items:center;font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-bottom:6px}',
791
+ '.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)}',
792
+ '.mopsDetailHint{padding:10px 0 14px;color:var(--dsw-alias-label-tertiary,#8a8a8e);font-size:12px}',
793
+ '.mopsActions{display:flex;gap:6px;flex-wrap:wrap;margin-top:10px}',
794
+ '.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)}',
795
+ '.mopsImpactTitle{font-size:12px;font-weight:600}',
796
+ '.mopsImpact{font-size:11px;line-height:1.5;color:var(--dsw-alias-label-secondary,#6b6b70)}',
797
+ '.mopsAction{height:30px;padding:0 10px;border:1px solid var(--dsw-alias-border-l2,#cfcfcf);background:transparent;cursor:pointer;font-size:11px}',
798
+ '.mopsAction:hover:not(:disabled){border-color:var(--dsw-alias-label-primary,#0f1115)}',
799
+ '.mopsAction.primary{border-color:var(--dsw-alias-label-primary,#0f1115);background:var(--dsw-alias-label-primary,#0f1115);color:var(--dsw-alias-bg-primary,#fff)}',
800
+ '.mopsAction.danger{border-color:var(--dsw-alias-state-error-primary,#c63b32);color:var(--dsw-alias-state-error-primary,#c63b32)}',
801
+ '.mopsAction:disabled{opacity:.35;cursor:default}',
802
+ '.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)}',
803
+ '.mopsCount{font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8a8e)}',
804
+ '.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}',
805
+ '.mopsDanger:hover{background:rgba(198,59,50,.06)}',
806
+ '.mopsBanner{padding:7px 18px;font-size:11px;border-bottom:1px solid var(--dsw-alias-border-l1,#efefef)}',
807
+ '.mopsBanner.warn{color:var(--dsw-alias-state-warn-primary,#9a6500);background:rgba(154,101,0,.06)}',
808
+ '.mopsBanner.err{color:var(--dsw-alias-state-error-primary,#c63b32);background:rgba(198,59,50,.06)}',
809
+ '.mopsBanner.ok{color:var(--dsw-alias-state-success-primary,#2f7d4a);background:rgba(47,125,74,.06)}',
810
+ '.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}',
811
+ '.mopsConfirm h3{margin:0;font-size:15px}',
812
+ '.mopsConfirm p{margin:0;font-size:12px;color:var(--dsw-alias-label-secondary,#6b6b70)}',
813
+ '.mopsConfirm p.mopsImpact{font-size:11px}',
814
+ '.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)}',
815
+ '.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}',
816
+ '.mopsConfirm input:disabled{opacity:.5}',
817
+ '.mopsConfirmRow{display:flex;gap:8px;margin-top:4px}',
818
+ '.mopsTrashItem{display:flex;align-items:center;gap:10px;padding:11px 18px;border-bottom:1px solid var(--dsw-alias-border-l1,#f0f0f0)}',
819
+ '.mopsTrashMain{flex:1;min-width:0}',
820
+ '.mopsTrashTitle{font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
821
+ '.mopsTrashMeta{font-size:10px;color:var(--dsw-alias-label-tertiary,#8a8a8e);margin-top:2px}',
822
+ '@media(max-width:760px){.mopsPanel{width:100vw;border-left:0}.mopsDetail{max-height:42%}}',
823
+ ].join('')
824
+ document.head.appendChild(tag)
825
+ } catch { /* style failure must not break the panel */ }
826
+ }
827
+
828
+ function OpsPanel(props) {
829
+ const t = (props && props.t) || __t
830
+ useLocaleRevision()
831
+ const [open, setOpen] = useState(false)
832
+ const [target, setTarget] = useState(null)
833
+ const [state, setState] = useState('idle')
834
+ const [loadError, setLoadError] = useState(null)
835
+ const [messages, setMessages] = useState([])
836
+ const [query, setQuery] = useState('')
837
+ const [role, setRole] = useState('all')
838
+ const [includeShadowed, setIncludeShadowed] = useState(false)
839
+ const [picked, setPicked] = useState(null)
840
+ const [detail, setDetail] = useState('')
841
+ const [detailState, setDetailState] = useState('idle')
842
+ const [tab, setTab] = useState('messages')
843
+ const [hits, setHits] = useState(null)
844
+ const [searching, setSearching] = useState(false)
845
+ const [trash, setTrash] = useState([])
846
+ const [trashState, setTrashState] = useState('idle')
847
+ const [trashError, setTrashError] = useState(null)
848
+ const [confirmDelete, setConfirmDelete] = useState(false)
849
+ const [confirmTitle, setConfirmTitle] = useState('')
850
+ const [deleteError, setDeleteError] = useState(null)
851
+ const [confirmAction, setConfirmAction] = useState(null)
852
+ const [purgeId, setPurgeId] = useState(null)
853
+ const [childId, setChildId] = useState(null)
854
+ const [busy, setBusy] = useState('')
855
+ const [error, setError] = useState(null)
856
+ const [done, setDone] = useState('')
857
+ const [scrollTop, setScrollTop] = useState(0)
858
+ const [viewport, setViewport] = useState(480)
859
+ const listRef = useRef(null)
860
+ const searchRef = useRef(null)
861
+ const panelRef = useRef(null)
862
+ const scrimRef = useRef(null)
863
+ const confirmRef = useRef(null)
864
+ const actionConfirmRef = useRef(null)
865
+ const triggerRef = useRef(null)
866
+ const deleteBtnRef = useRef(null)
867
+ const revertBtnRef = useRef(null)
868
+ const deleteOneBtnRef = useRef(null)
869
+ const detailReq = useRef(0)
870
+ const loadSeqRef = useRef(0)
871
+ const trashSeqRef = useRef(0)
872
+ const openRef = useRef(false)
873
+ const sessionRef = useRef(null)
874
+ openRef.current = open
875
+ sessionRef.current = target && target.sessionId ? target.sessionId : null
876
+
877
+ useEffect(() => {
878
+ ensurePanelStyle()
879
+ const handler = (e) => {
880
+ const d = e && e.detail ? e.detail : {}
881
+ if (!d.sessionId) return
882
+ const active = document.activeElement
883
+ if (!panelRef.current || !panelRef.current.contains(active)) triggerRef.current = active
884
+ loadSeqRef.current += 1
885
+ trashSeqRef.current += 1
886
+ detailReq.current += 1
887
+ setTarget({ sessionId: d.sessionId, title: d.title || null, running: d.running === true })
888
+ setOpen(true)
889
+ setState('loading')
890
+ setLoadError(null)
891
+ setMessages([])
892
+ setHits(null)
893
+ setQuery('')
894
+ setRole('all')
895
+ setIncludeShadowed(false)
896
+ setPicked(null)
897
+ setDetail('')
898
+ setDetailState('idle')
899
+ setTab('messages')
900
+ setTrash([])
901
+ setTrashState('idle')
902
+ setTrashError(null)
903
+ setConfirmDelete(false)
904
+ setConfirmTitle('')
905
+ setDeleteError(null)
906
+ setConfirmAction(null)
907
+ setPurgeId(null)
908
+ setChildId(null)
909
+ setError(null)
910
+ setDone('')
911
+ setScrollTop(0)
912
+ }
913
+ window.addEventListener(EVENT, handler)
914
+ return () => window.removeEventListener(EVENT, handler)
915
+ }, [])
916
+
917
+ const sid = target && target.sessionId
918
+
919
+ const loadMessages = useCallback(async (quiet) => {
920
+ if (!sid) return
921
+ const requestId = ++loadSeqRef.current
922
+ const requestSid = sid
923
+ if (!quiet) { setState('loading'); setLoadError(null) }
924
+ try {
925
+ const data = await fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(requestSid) + '&view=compact')
926
+ if (requestId !== loadSeqRef.current) return
927
+ setMessages(Array.isArray(data.messages) ? data.messages : [])
928
+ setTarget((prev) => prev && prev.sessionId === requestSid ? {
929
+ ...prev,
930
+ running: data.running === true,
931
+ title: prev.title || (data.session && data.session.title) || null,
932
+ expectedTitle: (data.session && data.session.confirmTitle) || prev.expectedTitle || prev.title || prev.sessionId,
933
+ } : prev)
934
+ setLoadError(null)
935
+ setError(null)
936
+ setState('ready')
937
+ } catch (reason) {
938
+ if (requestId !== loadSeqRef.current) return
939
+ const message = t('panel.loadFail') + (reason && reason.message ? reason.message : String(reason))
940
+ if (quiet) setError(message)
941
+ else { setLoadError(message); setState('error') }
942
+ }
943
+ }, [sid, t])
944
+
945
+ useEffect(() => {
946
+ if (!open || !sid) return
947
+ loadMessages(false)
948
+ }, [open, sid, loadMessages])
949
+
950
+ useEffect(() => {
951
+ if (!open || tab !== 'messages') return
952
+ const q = query.trim()
953
+ if (!q) { setHits(null); setSearching(false); return }
954
+ setSearching(true)
955
+ let cancelled = false
956
+ const timer = setTimeout(() => {
957
+ setError(null)
958
+ const url = '/api/message-ops/search?sessionId=' + encodeURIComponent(sid)
959
+ + '&q=' + encodeURIComponent(q)
960
+ + (role !== 'all' ? '&role=' + encodeURIComponent(role) : '')
961
+ + '&limit=' + PANEL_SEARCH_LIMIT
962
+ fetch(url)
963
+ .then((res) => res.json().catch(() => null).then((data) => ({ res, data })))
964
+ .then(({ res, data }) => {
965
+ if (cancelled) return
966
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
967
+ setHits(Array.isArray(data.results) ? data.results : [])
968
+ setError(null)
969
+ })
970
+ .catch((reason) => {
971
+ if (!cancelled) setError(t('panel.searchFail') + (reason && reason.message ? reason.message : String(reason)))
972
+ })
973
+ .finally(() => { if (!cancelled) setSearching(false) })
974
+ }, 200)
975
+ return () => { cancelled = true; clearTimeout(timer) }
976
+ }, [open, tab, sid, query, role, t])
977
+
978
+ const loadTrash = useCallback(async () => {
979
+ const requestId = ++trashSeqRef.current
980
+ setTrashState('loading')
981
+ setTrashError(null)
982
+ try {
983
+ const res = await fetch('/api/message-ops/session/trash')
984
+ const data = await res.json().catch(() => null)
985
+ if (requestId !== trashSeqRef.current) return
986
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
987
+ setTrash(Array.isArray(data.entries) ? data.entries : [])
988
+ setTrashError(null)
989
+ setTrashState('ready')
990
+ } catch (reason) {
991
+ if (requestId !== trashSeqRef.current) return
992
+ setTrashError(t('panel.loadFail') + (reason && reason.message ? reason.message : String(reason)))
993
+ setTrashState('error')
994
+ }
995
+ }, [t])
996
+
997
+ useEffect(() => {
998
+ if (open && tab === 'trash') loadTrash()
999
+ }, [open, tab, loadTrash])
1000
+
1001
+ const close = useCallback(() => {
1002
+ if (busy) return
1003
+ loadSeqRef.current += 1
1004
+ trashSeqRef.current += 1
1005
+ detailReq.current += 1
1006
+ setOpen(false)
1007
+ setTarget(null)
1008
+ setPicked(null)
1009
+ setConfirmDelete(false)
1010
+ setConfirmAction(null)
1011
+ setDeleteError(null)
1012
+ setLoadError(null)
1013
+ setTrashError(null)
1014
+ }, [busy])
1015
+
1016
+ const closeConfirm = useCallback(() => {
1017
+ if (busy === 'session-delete') return
1018
+ setConfirmDelete(false)
1019
+ setConfirmTitle('')
1020
+ setDeleteError(null)
1021
+ setTimeout(() => {
1022
+ const el = deleteBtnRef.current
1023
+ if (el && !el.disabled) el.focus()
1024
+ else if (panelRef.current) panelRef.current.focus()
1025
+ }, 0)
1026
+ }, [busy])
1027
+
1028
+ const cancelAction = useCallback(() => {
1029
+ if (busy) return
1030
+ const mode = confirmAction
1031
+ setConfirmAction(null)
1032
+ setTimeout(() => {
1033
+ const targetRef = mode === 'revert' ? revertBtnRef.current : deleteOneBtnRef.current
1034
+ if (targetRef && !targetRef.disabled) targetRef.focus()
1035
+ else if (panelRef.current) panelRef.current.focus()
1036
+ }, 0)
1037
+ }, [busy, confirmAction])
1038
+
1039
+ useEffect(() => {
1040
+ if (!open) return undefined
1041
+ const onKey = (e) => {
1042
+ if (e.key === 'Escape') {
1043
+ if (busy) return
1044
+ if (confirmDelete) closeConfirm()
1045
+ else if (confirmAction) cancelAction()
1046
+ else close()
1047
+ } else if (e.key === '/') {
1048
+ if (confirmDelete || confirmAction) return
1049
+ const el = e.target
1050
+ const tag = el && el.tagName
1051
+ if (el && (tag === 'INPUT' || tag === 'TEXTAREA' || el.isContentEditable)) return
1052
+ e.preventDefault()
1053
+ if (searchRef.current) searchRef.current.focus()
1054
+ }
1055
+ }
1056
+ window.addEventListener('keydown', onKey)
1057
+ return () => window.removeEventListener('keydown', onKey)
1058
+ }, [open, busy, confirmDelete, confirmAction, close, closeConfirm, cancelAction])
1059
+
1060
+ useEffect(() => {
1061
+ if (!open) return undefined
1062
+ if (!triggerRef.current) triggerRef.current = document.activeElement
1063
+ const timer = setTimeout(() => {
1064
+ if (searchRef.current) searchRef.current.focus()
1065
+ else if (panelRef.current) panelRef.current.focus()
1066
+ }, 0)
1067
+ const scrim = scrimRef.current
1068
+ const parent = scrim && scrim.parentElement
1069
+ const hidden = []
1070
+ if (parent) {
1071
+ for (const child of Array.from(parent.children)) {
1072
+ if (child === scrim || child.tagName === 'SCRIPT' || child.tagName === 'STYLE') continue
1073
+ hidden.push({ child, inert: child.hasAttribute('inert'), aria: child.getAttribute('aria-hidden') })
1074
+ child.setAttribute('inert', '')
1075
+ child.setAttribute('aria-hidden', 'true')
1076
+ }
1077
+ }
1078
+ return () => {
1079
+ clearTimeout(timer)
1080
+ for (const item of hidden) {
1081
+ if (!item.inert) item.child.removeAttribute('inert')
1082
+ if (item.aria === null) item.child.removeAttribute('aria-hidden')
1083
+ else item.child.setAttribute('aria-hidden', item.aria)
1084
+ }
1085
+ if (openRef.current) return
1086
+ const trigger = triggerRef.current
1087
+ triggerRef.current = null
1088
+ if (trigger && typeof trigger.focus === 'function') {
1089
+ setTimeout(() => { try { trigger.focus() } catch { /* detached trigger */ } }, 0)
1090
+ }
1091
+ }
1092
+ }, [open, sid])
1093
+
1094
+ useEffect(() => {
1095
+ if (!open) return undefined
1096
+ const onKeyDown = (e) => {
1097
+ if (e.key !== 'Tab') return
1098
+ const scope = confirmDelete ? confirmRef.current : (confirmAction ? actionConfirmRef.current : panelRef.current)
1099
+ if (!scope) return
1100
+ const nodes = focusablesIn(scope)
1101
+ if (!nodes.length) {
1102
+ e.preventDefault()
1103
+ scope.focus()
1104
+ return
1105
+ }
1106
+ const first = nodes[0]
1107
+ const last = nodes[nodes.length - 1]
1108
+ const active = document.activeElement
1109
+ if (active === scope || !scope.contains(active)) {
1110
+ e.preventDefault()
1111
+ const fallback = e.shiftKey ? last : first
1112
+ fallback.focus()
1113
+ } else if (e.shiftKey && active === first) {
1114
+ e.preventDefault()
1115
+ last.focus()
1116
+ } else if (!e.shiftKey && active === last) {
1117
+ e.preventDefault()
1118
+ first.focus()
1119
+ }
1120
+ }
1121
+ document.addEventListener('keydown', onKeyDown, true)
1122
+ return () => document.removeEventListener('keydown', onKeyDown, true)
1123
+ }, [open, confirmDelete, confirmAction])
1124
+
1125
+ useEffect(() => {
1126
+ if (!open) return
1127
+ if (confirmDelete) {
1128
+ const input = confirmRef.current && confirmRef.current.querySelector('input')
1129
+ if (input) input.focus()
1130
+ } else if (confirmAction) {
1131
+ const first = actionConfirmRef.current && actionConfirmRef.current.querySelector('button')
1132
+ if (first) first.focus()
1133
+ }
1134
+ }, [open, confirmDelete, confirmAction])
1135
+
1136
+ const baseRows = query.trim() ? (hits || []) : messages
1137
+ const rows = baseRows
1138
+ .filter((m) => m && m.role !== 'system'
1139
+ && (role === 'all' || m.role === role)
1140
+ && (includeShadowed || !m.shadowed))
1141
+ .sort((a, b) => b.seq - a.seq)
1142
+ const activeIndex = picked ? rows.findIndex((m) => m.seq === picked.seq) : -1
1143
+
1144
+ const clearPick = () => {
1145
+ detailReq.current += 1
1146
+ setPicked(null)
1147
+ setDetail('')
1148
+ setDetailState('idle')
1149
+ setConfirmAction(null)
1150
+ }
1151
+
1152
+ const previewRow = (m) => {
1153
+ if (!m) return
1154
+ detailReq.current += 1
1155
+ setPicked(m)
1156
+ setDetail(m.snippet || '')
1157
+ setDetailState('ready')
1158
+ setConfirmAction(null)
1159
+ setDone('')
1160
+ }
1161
+
1162
+ const scrollRowIntoView = (index) => {
1163
+ const el = listRef.current
1164
+ if (!el) return
1165
+ const top = index * PANEL_ROW_H
1166
+ const view = el.clientHeight || viewport
1167
+ let next = el.scrollTop
1168
+ if (top < next) next = top
1169
+ else if (top + PANEL_ROW_H > next + view) next = top + PANEL_ROW_H - view
1170
+ if (next !== el.scrollTop) {
1171
+ el.scrollTop = next
1172
+ setScrollTop(next)
1173
+ }
1174
+ }
1175
+
1176
+ const handleListKeyDown = (e) => {
1177
+ if (!rows.length) return
1178
+ const page = Math.max(1, Math.floor((listRef.current && listRef.current.clientHeight || viewport) / PANEL_ROW_H) - 1)
1179
+ let next = activeIndex
1180
+ if (e.key === 'ArrowDown') next = activeIndex < 0 ? 0 : Math.min(rows.length - 1, activeIndex + 1)
1181
+ else if (e.key === 'ArrowUp') next = activeIndex < 0 ? rows.length - 1 : Math.max(0, activeIndex - 1)
1182
+ else if (e.key === 'Home') next = 0
1183
+ else if (e.key === 'End') next = rows.length - 1
1184
+ else if (e.key === 'PageDown') next = activeIndex < 0 ? 0 : Math.min(rows.length - 1, activeIndex + page)
1185
+ else if (e.key === 'PageUp') next = activeIndex < 0 ? rows.length - 1 : Math.max(0, activeIndex - page)
1186
+ else if (e.key === 'Enter' || e.key === ' ') {
1187
+ e.preventDefault()
1188
+ const row = rows[activeIndex >= 0 ? activeIndex : 0]
1189
+ if (row) { pick(row); if (listRef.current) listRef.current.focus() }
1190
+ return
1191
+ } else {
1192
+ return
1193
+ }
1194
+ e.preventDefault()
1195
+ const row = rows[next]
1196
+ if (!row) return
1197
+ previewRow(row)
1198
+ scrollRowIntoView(next)
1199
+ }
1200
+
1201
+ useEffect(() => {
1202
+ if (!open || tab !== 'messages') return undefined
1203
+ const el = listRef.current
1204
+ if (!el) return undefined
1205
+ const measure = () => setViewport(el.clientHeight || 480)
1206
+ measure()
1207
+ if (typeof ResizeObserver === 'undefined') return undefined
1208
+ const ro = new ResizeObserver(measure)
1209
+ ro.observe(el)
1210
+ return () => ro.disconnect()
1211
+ }, [open, tab, rows.length])
1212
+
1213
+ useEffect(() => {
1214
+ if (!open || tab !== 'messages') return
1215
+ const el = listRef.current
1216
+ if (!el) return
1217
+ const max = Math.max(0, rows.length * PANEL_ROW_H - (el.clientHeight || viewport))
1218
+ if (el.scrollTop > max) {
1219
+ el.scrollTop = max
1220
+ setScrollTop(max)
1221
+ }
1222
+ }, [open, tab, rows.length, viewport])
1223
+
1224
+ const pick = useCallback((m) => {
1225
+ if (!m || busy) return
1226
+ setConfirmAction(null)
1227
+ setPicked(m)
1228
+ setDetail(m.snippet || '')
1229
+ setDetailState('loading')
1230
+ setDone('')
1231
+ const req = ++detailReq.current
1232
+ fetch('/api/message-ops/text?sessionId=' + encodeURIComponent(sid) + '&seq=' + encodeURIComponent(m.seq))
1233
+ .then((res) => res.json().catch(() => null).then((data) => ({ res, data })))
1234
+ .then(({ res, data }) => {
1235
+ if (req !== detailReq.current) return
1236
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1237
+ setDetail(typeof data.text === 'string' && data.text ? data.text : (m.snippet || ''))
1238
+ setDetailState('ready')
1239
+ })
1240
+ .catch(() => {
1241
+ if (req !== detailReq.current) return
1242
+ setDetail(m.snippet || '')
1243
+ setDetailState('ready')
1244
+ })
1245
+ }, [busy, sid])
1246
+
1247
+ const runAction = useCallback(async (mode, confirmed) => {
1248
+ if (!target || !picked || busy) return
1249
+ if (target.running && mode !== 'branch') return
1250
+ if ((mode === 'revert' || mode === 'delete') && confirmed !== true) return
1251
+ const actionSid = target.sessionId
1252
+ setBusy(mode)
1253
+ setError(null)
1254
+ setDone('')
1255
+ try {
1256
+ if (mode === 'branch') {
1257
+ const forkPath = pickForkPath(__sessionsSvc)
1258
+ if (forkPath.kind !== 'official') throw new Error(t('fork.unavailable'))
1259
+ const created = await forkPath.fork({ sessionId: target.sessionId, atSeq: picked.seq, increaseTitle: true })
1260
+ if (sessionRef.current !== actionSid) return
1261
+ setChildId(created || null)
1262
+ setDone(t('panel.branchDone', { id: String(created || '') }))
1263
+ notifyDone(t('panel.branchDone', { id: String(created || '') }))
1264
+ return
1265
+ }
1266
+ const res = await fetch('/api/message-ops/' + mode, {
1267
+ method: 'POST',
1268
+ headers: { 'content-type': 'application/json' },
1269
+ body: JSON.stringify({ sessionId: target.sessionId, seq: picked.seq }),
1270
+ })
1271
+ const data = await res.json().catch(() => null)
1272
+ if (sessionRef.current !== actionSid) return
1273
+ if (!res.ok || !data || data.ok !== true) {
1274
+ if (res.status === 409) setTarget((prev) => prev ? { ...prev, running: true } : prev)
1275
+ throw new Error((data && data.error) || ('HTTP ' + res.status))
1276
+ }
1277
+ if (mode === 'revert') {
1278
+ setMessages((prev) => prev.map((m) => (m.seq >= picked.seq ? { ...m, shadowed: true, visible: false } : m)))
1279
+ if (picked.role === 'user') {
1280
+ try { refillComposer(target.sessionId, picked.seq) } catch { /* non-blocking */ }
1281
+ }
1282
+ } else {
1283
+ setMessages((prev) => prev.map((m) => (m.seq === picked.seq ? { ...m, shadowed: true, visible: false } : m)))
1284
+ }
1285
+ const msg = t(mode === 'revert' ? 'panel.revertDone' : 'panel.deleteDone')
1286
+ setDone(msg)
1287
+ setConfirmAction(null)
1288
+ setTimeout(() => { if (listRef.current) listRef.current.focus() }, 0)
1289
+ notifyDone(msg)
1290
+ emitChanged()
1291
+ try {
1292
+ if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(target.sessionId)
1293
+ } catch { /* view rebuild is best effort */ }
1294
+ setTimeout(() => { loadMessages(true).catch(() => {}) }, 650)
1295
+ } catch (reason) {
1296
+ if (sessionRef.current !== actionSid) return
1297
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1298
+ } finally {
1299
+ setBusy('')
1300
+ }
1301
+ }, [target, picked, busy, t, loadMessages])
1302
+
1303
+ const deleteSession = useCallback(async () => {
1304
+ if (!target || busy || target.running) return
1305
+ const expected = target.expectedTitle || ''
1306
+ if (!expected || confirmTitle.trim() !== expected) return
1307
+ const actionSid = target.sessionId
1308
+ setBusy('session-delete')
1309
+ setDeleteError(null)
1310
+ setDone('')
1311
+ try {
1312
+ const res = await fetch('/api/message-ops/session/delete', {
1313
+ method: 'POST',
1314
+ headers: { 'content-type': 'application/json' },
1315
+ body: JSON.stringify({ sessionId: target.sessionId, confirmTitle: confirmTitle }),
1316
+ })
1317
+ const data = await res.json().catch(() => null)
1318
+ if (sessionRef.current !== actionSid) return
1319
+ if (!res.ok || !data || data.ok !== true) {
1320
+ if (res.status === 409) setTarget((prev) => prev ? { ...prev, running: true } : prev)
1321
+ throw new Error((data && data.error) || ('HTTP ' + res.status))
1322
+ }
1323
+ setConfirmDelete(false)
1324
+ setDone(t('panel.deleted'))
1325
+ notifyDone(t('panel.deleted'))
1326
+ emitChanged()
1327
+ setTimeout(() => { try { window.location.reload() } catch { /* non-browser guard */ } }, 700)
1328
+ } catch (reason) {
1329
+ if (sessionRef.current !== actionSid) return
1330
+ setDeleteError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1331
+ } finally {
1332
+ setBusy('')
1333
+ }
1334
+ }, [target, busy, confirmTitle, t])
1335
+
1336
+ const restoreEntry = useCallback(async (trashId) => {
1337
+ if (busy) return
1338
+ setBusy('restore:' + trashId)
1339
+ setError(null)
1340
+ setDone('')
1341
+ try {
1342
+ const res = await fetch('/api/message-ops/session/restore', {
1343
+ method: 'POST',
1344
+ headers: { 'content-type': 'application/json' },
1345
+ body: JSON.stringify({ trashId }),
1346
+ })
1347
+ const data = await res.json().catch(() => null)
1348
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1349
+ setTrash((prev) => prev.filter((x) => x.trashId !== trashId))
1350
+ setDone(t('panel.restored'))
1351
+ notifyDone(t('panel.restored'))
1352
+ emitChanged()
1353
+ setTimeout(() => { try { window.location.reload() } catch { /* non-browser guard */ } }, 700)
1354
+ } catch (reason) {
1355
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1356
+ } finally {
1357
+ setBusy('')
1358
+ }
1359
+ }, [busy, t])
1360
+
1361
+ const purgeEntry = useCallback(async (trashId) => {
1362
+ if (busy) return
1363
+ if (purgeId !== trashId) { setPurgeId(trashId); return }
1364
+ setBusy('purge:' + trashId)
1365
+ setError(null)
1366
+ setDone('')
1367
+ try {
1368
+ const res = await fetch('/api/message-ops/session/purge', {
1369
+ method: 'POST',
1370
+ headers: { 'content-type': 'application/json' },
1371
+ body: JSON.stringify({ trashId }),
1372
+ })
1373
+ const data = await res.json().catch(() => null)
1374
+ if (!res.ok || !data || data.ok !== true) throw new Error((data && data.error) || ('HTTP ' + res.status))
1375
+ setTrash((prev) => prev.filter((x) => x.trashId !== trashId))
1376
+ setPurgeId(null)
1377
+ setDone(t('panel.purged'))
1378
+ notifyDone(t('panel.purged'))
1379
+ } catch (reason) {
1380
+ setError(t('errorPrefix') + (reason && reason.message ? reason.message : String(reason)))
1381
+ } finally {
1382
+ setBusy('')
1383
+ }
1384
+ }, [busy, purgeId, t])
1385
+
1386
+ if (!open) return null
1387
+
1388
+ const pickedLive = picked ? (messages.find((m) => m.seq === picked.seq) || picked) : null
1389
+ const canAct = !busy && !target.running && pickedLive && !pickedLive.shadowed
1390
+ const visibleCount = messages.filter((m) => m.role !== 'system' && m.visible && !m.shadowed).length
1391
+ const shadowedCount = messages.filter((m) => m.role !== 'system' && m.shadowed).length
1392
+ const totalCount = messages.filter((m) => m.role !== 'system').length
1393
+ const revertImpact = pickedLive
1394
+ ? messages.filter((m) => m.role !== 'system' && !m.shadowed && m.seq >= pickedLive.seq)
1395
+ : []
1396
+ const revertCount = revertImpact.length
1397
+ const revertVisibleCount = revertImpact.filter((m) => m.visible).length
1398
+ const revertEnd = revertImpact.reduce((max, m) => Math.max(max, m.seq), pickedLive ? pickedLive.seq : 0)
1399
+ const expectedDeleteTitle = target.expectedTitle || ''
1400
+ const deleteBlockedReason = target.running
1401
+ ? t('panel.running')
1402
+ : state !== 'ready'
1403
+ ? (state === 'error' ? t('panel.loadFail') : t('panel.loading'))
1404
+ : !expectedDeleteTitle ? t('panel.deleteUnavailable') : ''
1405
+ const canConfirmDelete = !busy && state === 'ready' && !target.running && !!expectedDeleteTitle
1406
+ && confirmTitle.trim() === expectedDeleteTitle
1407
+ const start = Math.min(Math.max(0, rows.length - 1), Math.max(0, Math.floor(scrollTop / PANEL_ROW_H) - 6))
1408
+ const end = Math.min(rows.length, start + Math.ceil(viewport / PANEL_ROW_H) + 12)
1409
+ const windowRows = rows.slice(start, end)
1410
+ const activeRendered = picked && windowRows.some((m) => m.seq === picked.seq)
1411
+ const showSearchLoading = searching && query.trim().length > 0
1412
+
1413
+ return React.createElement('div', {
1414
+ className: 'mopsPanelScrim', role: 'presentation', ref: scrimRef,
1415
+ onMouseDown: (e) => { if (e.target === e.currentTarget) close() },
1416
+ },
1417
+ React.createElement('section', {
1418
+ className: 'mopsPanel', role: 'dialog', 'aria-modal': 'true',
1419
+ 'aria-labelledby': 'mops-panel-title', 'aria-describedby': 'mops-panel-session',
1420
+ 'aria-busy': busy || state === 'loading' ? 'true' : undefined,
1421
+ tabIndex: -1, ref: panelRef,
1422
+ style: { position: 'relative' },
1423
+ },
1424
+ React.createElement('header', { className: 'mopsPanelHead' },
1425
+ React.createElement('div', { style: { minWidth: 0 } },
1426
+ React.createElement('div', { className: 'mopsPanelKicker' }, t('dialog.title')),
1427
+ React.createElement('div', { className: 'mopsPanelTitle', id: 'mops-panel-title' }, target.title || target.expectedTitle || target.sessionId),
1428
+ React.createElement('div', { className: 'mopsPanelSub', id: 'mops-panel-session' }, target.sessionId)),
1429
+ React.createElement('button', {
1430
+ type: 'button', className: 'mopsPanelClose', title: t('dialog.cancel'),
1431
+ 'aria-label': t('dialog.cancel'),
1432
+ onClick: close, disabled: !!busy,
1433
+ }, '×')),
1434
+ React.createElement('div', { className: 'mopsTabs' },
1435
+ React.createElement('button', {
1436
+ type: 'button', className: 'mopsTab' + (tab === 'messages' ? ' on' : ''),
1437
+ onClick: () => { setTab('messages'); setConfirmDelete(false); setConfirmAction(null); setDeleteError(null) },
1438
+ }, t('panel.messages') + ' ' + totalCount),
1439
+ React.createElement('button', {
1440
+ type: 'button', className: 'mopsTab' + (tab === 'trash' ? ' on' : ''),
1441
+ onClick: () => { setTab('trash'); setConfirmDelete(false); setConfirmAction(null); setDeleteError(null) },
1442
+ }, t('panel.trash') + (trash.length ? ' ' + trash.length : ''))),
1443
+ target.running && tab === 'messages'
1444
+ ? React.createElement('div', { className: 'mopsBanner warn' }, t('panel.running')) : null,
1445
+ error ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, error) : null,
1446
+ done ? React.createElement('div', { className: 'mopsBanner ok' }, done,
1447
+ childId ? React.createElement('button', {
1448
+ type: 'button', className: 'mopsAction primary', style: { marginLeft: 10 },
1449
+ onClick: () => { try { if (__uiWorkspace && typeof __uiWorkspace.openSession === 'function') __uiWorkspace.openSession(childId) } catch { /* best effort */ } },
1450
+ }, t('panel.openNew')) : null) : null,
1451
+ tab === 'messages'
1452
+ ? React.createElement(React.Fragment, null,
1453
+ React.createElement('div', { className: 'mopsSearchRow' },
1454
+ React.createElement('input', {
1455
+ ref: searchRef, className: 'mopsSearch', value: query,
1456
+ placeholder: t('panel.searchHint'), 'aria-label': t('panel.search'),
1457
+ onChange: (e) => { setQuery(e.target.value); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1458
+ })),
1459
+ React.createElement('div', { className: 'mopsChips' },
1460
+ ['all', 'user', 'assistant', 'tool'].map((key) => React.createElement('button', {
1461
+ key, type: 'button', className: 'mopsChip' + (role === key ? ' on' : ''),
1462
+ onClick: () => { setRole(key); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1463
+ }, t('panel.' + key))),
1464
+ React.createElement('label', { className: 'mopsToggle' },
1465
+ React.createElement('input', {
1466
+ type: 'checkbox', checked: includeShadowed,
1467
+ onChange: (e) => { setIncludeShadowed(e.target.checked); clearPick(); setScrollTop(0); if (listRef.current) listRef.current.scrollTop = 0 },
1468
+ }), t('panel.includeShadowed'))),
1469
+ React.createElement('div', {
1470
+ className: 'mopsList', ref: listRef,
1471
+ role: state === 'ready' && rows.length ? 'listbox' : 'region',
1472
+ tabIndex: state === 'ready' && rows.length ? 0 : -1,
1473
+ 'aria-label': t('panel.messages'),
1474
+ 'aria-busy': state === 'loading' || showSearchLoading ? 'true' : undefined,
1475
+ 'aria-activedescendant': state === 'ready' && activeRendered ? 'mops-opt-' + picked.seq : undefined,
1476
+ onKeyDown: handleListKeyDown,
1477
+ onScroll: (e) => setScrollTop(e.currentTarget.scrollTop),
1478
+ },
1479
+ state === 'loading' || state === 'idle'
1480
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1481
+ : state === 'error'
1482
+ ? React.createElement('div', { className: 'mopsEmpty mopsErrorState', role: 'alert' },
1483
+ React.createElement('span', null, loadError || t('panel.loadFail')),
1484
+ React.createElement('button', {
1485
+ type: 'button', className: 'mopsAction',
1486
+ onClick: () => { loadMessages(false); setTimeout(() => { if (searchRef.current) searchRef.current.focus() }, 0) },
1487
+ }, t('panel.retry')))
1488
+ : rows.length === 0
1489
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, showSearchLoading ? t('panel.searching') : (query.trim() ? t('panel.noMatch') : t('panel.empty')))
1490
+ : React.createElement('div', { style: { height: rows.length * PANEL_ROW_H, position: 'relative' } },
1491
+ windowRows.map((m, i) => React.createElement('div', {
1492
+ key: m.seq, id: 'mops-opt-' + m.seq, role: 'option',
1493
+ 'aria-selected': pickedLive && pickedLive.seq === m.seq,
1494
+ 'aria-setsize': rows.length, 'aria-posinset': start + i + 1,
1495
+ tabIndex: -1,
1496
+ className: 'mopsRow' + (pickedLive && pickedLive.seq === m.seq ? ' on' : '') + (m.shadowed ? ' shadowed' : ''),
1497
+ style: { top: (start + i) * PANEL_ROW_H, height: PANEL_ROW_H },
1498
+ onClick: () => { pick(m); if (listRef.current) listRef.current.focus() },
1499
+ title: '#' + m.seq + ' ' + (m.role || '') + ' · ' + (m.snippet || ''),
1500
+ 'aria-label': '#' + m.seq + ' ' + (m.role || '') + (m.shadowed ? ' ' + t('panel.shadowed') : '') + ' · ' + (m.snippet || '') + (m.time ? ' · ' + fmtClock(m.time) : ''),
1501
+ },
1502
+ React.createElement('span', { className: 'mopsSeq' }, '#' + m.seq),
1503
+ React.createElement('span', { className: 'mopsRole' }, roleCode(m.role)),
1504
+ React.createElement('span', { className: 'mopsSnippet' }, m.snippet || '—'),
1505
+ React.createElement('span', { className: 'mopsClock' }, fmtClock(m.time)))))),
1506
+ React.createElement('div', { className: 'mopsDetail' },
1507
+ pickedLive
1508
+ ? React.createElement(React.Fragment, null,
1509
+ React.createElement('div', { className: 'mopsDetailMeta' },
1510
+ React.createElement('span', null, '#' + pickedLive.seq),
1511
+ React.createElement('span', null, pickedLive.role || ''),
1512
+ pickedLive.shadowed ? React.createElement('span', null, t('panel.shadowed')) : null,
1513
+ pickedLive.time ? React.createElement('span', null, fmtClock(pickedLive.time)) : null),
1514
+ React.createElement('pre', { className: 'mopsDetailText' },
1515
+ detailState === 'loading' ? t('panel.detailLoading') : (detail || pickedLive.snippet || '—')),
1516
+ React.createElement('div', { className: 'mopsActions' },
1517
+ React.createElement('button', {
1518
+ type: 'button', className: 'mopsAction primary', disabled: !canAct || !!confirmAction,
1519
+ ref: revertBtnRef,
1520
+ onClick: () => setConfirmAction('revert'),
1521
+ title: t('panel.revertHint'),
1522
+ }, t('panel.revert') + (revertCount ? ' · ' + revertCount : '')),
1523
+ React.createElement('button', {
1524
+ type: 'button', className: 'mopsAction danger', disabled: !canAct || !!confirmAction,
1525
+ ref: deleteOneBtnRef,
1526
+ onClick: () => setConfirmAction('delete'), title: t('panel.deleteHint'),
1527
+ }, t('panel.delete')),
1528
+ React.createElement('button', {
1529
+ type: 'button', className: 'mopsAction', disabled: !canAct || !!confirmAction,
1530
+ onClick: () => runAction('branch'), title: t('panel.branchHint'),
1531
+ }, t('panel.branch'))),
1532
+ confirmAction
1533
+ ? React.createElement('div', {
1534
+ className: 'mopsActionConfirm', ref: actionConfirmRef, role: 'group', tabIndex: -1,
1535
+ 'aria-labelledby': 'mops-action-confirm-title',
1536
+ },
1537
+ React.createElement('div', { className: 'mopsImpactTitle', id: 'mops-action-confirm-title' },
1538
+ t(confirmAction === 'revert' ? 'panel.revertConfirmTitle' : 'panel.deleteConfirmTitle', { seq: String(pickedLive.seq) })),
1539
+ React.createElement('div', { className: 'mopsImpact' },
1540
+ confirmAction === 'revert'
1541
+ ? t('panel.revertConfirmBody', {
1542
+ start: String(pickedLive.seq), end: String(revertEnd),
1543
+ n: String(revertCount), v: String(revertVisibleCount),
1544
+ })
1545
+ : t('panel.deleteConfirmBody')),
1546
+ React.createElement('div', { className: 'mopsConfirmRow' },
1547
+ React.createElement('button', {
1548
+ type: 'button', className: 'mopsAction', onClick: cancelAction, disabled: !!busy,
1549
+ }, t('panel.cancel')),
1550
+ React.createElement('button', {
1551
+ type: 'button', className: 'mopsAction danger',
1552
+ onClick: () => runAction(confirmAction, true),
1553
+ disabled: !!busy || !canAct,
1554
+ }, busy === confirmAction ? t('panel.busy') : t(confirmAction === 'revert' ? 'panel.confirmRevert' : 'panel.confirmDeleteOne'))))
1555
+ : null)
1556
+ : React.createElement('div', { className: 'mopsDetailHint' }, t('panel.selectHint'))),
1557
+ React.createElement('footer', { className: 'mopsPanelFoot' },
1558
+ React.createElement('span', { className: 'mopsCount' },
1559
+ t('panel.count', { n: String(totalCount), v: String(visibleCount), s: String(shadowedCount) })),
1560
+ React.createElement('button', {
1561
+ type: 'button', className: 'mopsDanger', ref: deleteBtnRef,
1562
+ disabled: !!busy || !!deleteBlockedReason,
1563
+ title: deleteBlockedReason || undefined,
1564
+ onClick: () => {
1565
+ setConfirmTitle('')
1566
+ setDeleteError(null)
1567
+ setConfirmAction(null)
1568
+ setConfirmDelete(true)
1569
+ },
1570
+ }, t('panel.deleteSession'))),
1571
+ confirmDelete
1572
+ ? React.createElement('div', {
1573
+ className: 'mopsConfirm', ref: confirmRef, role: 'alertdialog', 'aria-modal': 'true',
1574
+ 'aria-labelledby': 'mops-delete-title', 'aria-describedby': 'mops-delete-hint mops-delete-impact',
1575
+ tabIndex: -1,
1576
+ },
1577
+ React.createElement('h3', { id: 'mops-delete-title' }, t('panel.deleteSession')),
1578
+ React.createElement('p', { id: 'mops-delete-hint' }, t('panel.deleteSessionHint')),
1579
+ React.createElement('p', { className: 'mopsImpact', id: 'mops-delete-impact' },
1580
+ t('panel.deleteSessionImpact', { n: String(totalCount) })),
1581
+ target.running ? React.createElement('div', { className: 'mopsBanner warn', role: 'status' }, t('panel.running')) : null,
1582
+ deleteError ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, deleteError) : null,
1583
+ React.createElement('input', {
1584
+ id: 'mops-delete-title-input', value: confirmTitle, autoFocus: true,
1585
+ 'aria-label': t('panel.deleteSessionHint'),
1586
+ 'aria-describedby': 'mops-delete-hint',
1587
+ placeholder: expectedDeleteTitle || target.title || target.sessionId,
1588
+ disabled: !!busy || target.running || !expectedDeleteTitle,
1589
+ onChange: (e) => setConfirmTitle(e.target.value),
1590
+ onKeyDown: (e) => {
1591
+ if (e.key === 'Enter') {
1592
+ e.preventDefault()
1593
+ if (canConfirmDelete) deleteSession()
1594
+ } else if (e.key === 'Escape') {
1595
+ e.preventDefault()
1596
+ e.stopPropagation()
1597
+ closeConfirm()
1598
+ }
1599
+ },
1600
+ }),
1601
+ React.createElement('div', { className: 'mopsConfirmRow' },
1602
+ React.createElement('button', {
1603
+ type: 'button', className: 'mopsAction',
1604
+ onClick: closeConfirm, disabled: busy === 'session-delete',
1605
+ }, t('panel.cancel')),
1606
+ React.createElement('button', {
1607
+ type: 'button', className: 'mopsAction danger',
1608
+ disabled: !canConfirmDelete,
1609
+ onClick: deleteSession,
1610
+ }, busy === 'session-delete' ? t('panel.deleting') : t('panel.confirmDelete'))))
1611
+ : null)
1612
+ : React.createElement('div', { className: 'mopsList', style: { borderTop: 0 }, 'aria-busy': trashState === 'loading' ? 'true' : undefined },
1613
+ trashState === 'loading' || trashState === 'idle'
1614
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1615
+ : trashState === 'error'
1616
+ ? React.createElement('div', { className: 'mopsEmpty mopsErrorState', role: 'alert' },
1617
+ React.createElement('span', null, trashError || t('panel.loadFail')),
1618
+ React.createElement('button', {
1619
+ type: 'button', className: 'mopsAction',
1620
+ onClick: () => { loadTrash(); setTimeout(() => { if (panelRef.current) panelRef.current.focus() }, 0) },
1621
+ }, t('panel.retry')))
1622
+ : trash.length === 0
1623
+ ? React.createElement('div', { className: 'mopsEmpty' }, t('panel.trashEmpty'))
1624
+ : trash.map((item) => React.createElement('div', { className: 'mopsTrashItem', key: item.trashId },
1625
+ React.createElement('div', { className: 'mopsTrashMain' },
1626
+ React.createElement('div', { className: 'mopsTrashTitle' }, item.title || t('panel.untitled')),
1627
+ React.createElement('div', { className: 'mopsTrashMeta' },
1628
+ item.sessionId + (item.expiresAt ? ' · ' + t('panel.expires') + ' ' + new Date(item.expiresAt).toLocaleDateString() : ''))),
1629
+ React.createElement('button', {
1630
+ type: 'button', className: 'mopsAction', disabled: !!busy,
1631
+ onClick: () => restoreEntry(item.trashId),
1632
+ }, busy === 'restore:' + item.trashId ? t('panel.busy') : t('panel.restore')),
1633
+ React.createElement('button', {
1634
+ type: 'button', className: 'mopsAction danger', disabled: !!busy,
1635
+ onClick: () => purgeEntry(item.trashId),
1636
+ }, busy === 'purge:' + item.trashId ? t('panel.busy') : (purgeId === item.trashId ? t('panel.purgeConfirm') : t('panel.purge'))))))))
1637
+ }
1638
+
595
1639
  // --- 头部按钮 ---------------------------------------------------------------
596
1640
 
597
1641
  // 0.3.0 分支双路径选择:0.2.0+ 官方 sessions.fork({atSeq}) 优先。
@@ -920,6 +1964,7 @@ window.__ModuleLoader__.load({
920
1964
  }, [styleInjected])
921
1965
 
922
1966
  useEffect(() => {
1967
+ syncSyntheticTurnStyle([])
923
1968
  let alive = true
924
1969
  const onChange = () => load()
925
1970
  window.addEventListener(CHANGED_EVENT, onChange)
@@ -941,6 +1986,7 @@ window.__ModuleLoader__.load({
941
1986
  if (reqSeq !== reqSeqRef.current || reqSeq <= landedSeqRef.current) return
942
1987
  landedSeqRef.current = reqSeq
943
1988
  const msgs = data.messages || []
1989
+ syncSyntheticTurnStyle(msgs)
944
1990
  const act = activeMarkers(msgs)
945
1991
  setMarkers(act)
946
1992
  // 0.5.2(P2):标题口径 = 标记 range 内 visible=false 的去重 seq 数
@@ -974,6 +2020,7 @@ window.__ModuleLoader__.load({
974
2020
  return () => {
975
2021
  alive = false
976
2022
  loadRef.current = () => {}
2023
+ syncSyntheticTurnStyle([])
977
2024
  window.removeEventListener(CHANGED_EVENT, onChange)
978
2025
  }
979
2026
  }, [sessionId])
@@ -1995,7 +3042,7 @@ window.__ModuleLoader__.load({
1995
3042
  ctx.slots.inject(OVERLAY_SLOT, () => ctx.slots.register({
1996
3043
  name: OVERLAY_SLOT, id: DIALOG_ID, order: 101,
1997
3044
  ...(__locale ? { locale: NS } : {}),
1998
- }, OpsDialog))
3045
+ }, window.__MOPS_LEGACY_DIALOG === true ? OpsDialog : OpsPanel))
1999
3046
  installSidebarOps()
2000
3047
  installUserRevertInjector()
2001
3048
  }