@240xu/dsh-message-ops 0.24.0 → 0.47.0

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.
@@ -0,0 +1,1478 @@
1
+ // ══ 30-panel · 操作面板(列表 / 全文预览 / 回撤 / 删除 / 分叉 / 会话删除) ══
2
+ /**
3
+ * 面板 Esc 的分层决策:busy 期间忽略 → 先退确认层 → 再清搜索 → 最后才关面板。
4
+ * 抽成纯函数是为了能真执行断言(原先埋在 onKey 闭包里,零测试)。
5
+ * @param {{busy: boolean, confirmDelete: boolean, confirmAction: string|null, query: string}} state
6
+ * @returns {'ignore'|'closeConfirm'|'cancelAction'|'clearQuery'|'close'}
7
+ */
8
+ function panelEscapeAction(state) {
9
+ const s = state || {}
10
+ if (s.busy) return 'ignore'
11
+ if (s.confirmDelete) return 'closeConfirm'
12
+ if (s.confirmAction) return 'cancelAction'
13
+ if (s.query && String(s.query).trim()) return 'clearQuery'
14
+ return 'close'
15
+ }
16
+
17
+ function OpsPanel(props) {
18
+ const t = (props && props.t) || __t
19
+ useLocaleRevision()
20
+ const [open, setOpen] = useState(false)
21
+ const [target, setTarget] = useState(null)
22
+ const [state, setState] = useState('idle')
23
+ const [loadError, setLoadError] = useState(null)
24
+ const [messages, setMessages] = useState([])
25
+ const [query, setQuery] = useState('')
26
+ const [role, setRole] = useState('all')
27
+ const [includeShadowed, setIncludeShadowed] = useState(false)
28
+ const [picked, setPicked] = useState(null)
29
+ const [detail, setDetail] = useState('')
30
+ const [detailState, setDetailState] = useState('idle')
31
+ // MED-5:detail 是**全文**还是 snippet 回退?只有全文才允许「编辑并重发」。
32
+ const [tab, setTab] = useState('messages')
33
+ const [hits, setHits] = useState(null)
34
+ const [searching, setSearching] = useState(false)
35
+ const [trash, setTrash] = useState([])
36
+ const [trashState, setTrashState] = useState('idle')
37
+ const [trashError, setTrashError] = useState(null)
38
+ const [confirmDelete, setConfirmDelete] = useState(false)
39
+ const [confirmTitle, setConfirmTitle] = useState('')
40
+ const [deleteError, setDeleteError] = useState(null)
41
+ const [confirmAction, setConfirmAction] = useState(null)
42
+ const [purgeId, setPurgeId] = useState(null)
43
+ const [childId, setChildId] = useState(null)
44
+ const [busy, setBusy] = useState('')
45
+ const [error, setError] = useState(null)
46
+ // 0.33.3(ui-live P2-2):动作错误与加载错误分开。旧实现共用一个 error,
47
+ // 1s 后的静默重查成功会 setError(null),把刚显示的 409 横幅清掉。
48
+ const [actionError, setActionError] = useState(null)
49
+ const [done, setDone] = useState('')
50
+ const [scrollTop, setScrollTop] = useState(0)
51
+ const [viewport, setViewport] = useState(480)
52
+ const listRef = useRef(null)
53
+ const scrollRaf = useRef(null)
54
+ const searchRef = useRef(null)
55
+ const panelRef = useRef(null)
56
+ const scrimRef = useRef(null)
57
+ const confirmRef = useRef(null)
58
+ const actionConfirmRef = useRef(null)
59
+ const triggerRef = useRef(null)
60
+ const deleteBtnRef = useRef(null)
61
+ const revertBtnRef = useRef(null)
62
+ const deleteOneBtnRef = useRef(null)
63
+ const detailReq = useRef(0)
64
+ const loadSeqRef = useRef(0)
65
+ const trashSeqRef = useRef(0)
66
+ const openRef = useRef(false)
67
+ const sessionRef = useRef(null)
68
+ openRef.current = open
69
+ sessionRef.current = target && target.sessionId ? target.sessionId : null
70
+
71
+ useEffect(() => {
72
+ ensurePanelStyle()
73
+ const handler = e => {
74
+ const d = e && e.detail ? e.detail : {}
75
+ if (!d.sessionId) return
76
+ const active = document.activeElement
77
+ if (!panelRef.current || !panelRef.current.contains(active)) triggerRef.current = active
78
+ loadSeqRef.current += 1
79
+ trashSeqRef.current += 1
80
+ detailReq.current += 1
81
+ setTarget({ sessionId: d.sessionId, title: d.title || null, running: d.running === true })
82
+ setOpen(true)
83
+ setState('loading')
84
+ setLoadError(null)
85
+ setMessages([])
86
+ setHits(null)
87
+ setQuery('')
88
+ setRole('all')
89
+ setIncludeShadowed(false)
90
+ setPicked(null)
91
+ setDetail('')
92
+ setDetailState('idle')
93
+ setTab('messages')
94
+ setTrash([])
95
+ setTrashState('idle')
96
+ setTrashError(null)
97
+ setConfirmDelete(false)
98
+ setConfirmTitle('')
99
+ setDeleteError(null)
100
+ setConfirmAction(null)
101
+ setPurgeId(null)
102
+ setChildId(null)
103
+ setError(null)
104
+ setActionError(null)
105
+ setDone('')
106
+ setScrollTop(0)
107
+ }
108
+ window.addEventListener(EVENT, handler)
109
+ return () => window.removeEventListener(EVENT, handler)
110
+ }, [])
111
+
112
+ // 0.33.3(ui-live P1-2):面板是独立 slot,拿不到 sessionId;会话切换由 dock
113
+ // 广播。继续开着等于「界面已是 B、面板还对 A 执行 revert/delete」——直接关闭。
114
+ useEffect(() => {
115
+ const onSession = e => {
116
+ const next = e && e.detail ? e.detail.sessionId : null
117
+ const cur = sessionRef.current
118
+ if (!next || !cur) return
119
+ if (bareSessionId(next) !== bareSessionId(cur)) {
120
+ setOpen(false)
121
+ setTarget(null)
122
+ }
123
+ }
124
+ window.addEventListener(SESSION_EVENT, onSession)
125
+ return () => window.removeEventListener(SESSION_EVENT, onSession)
126
+ }, [])
127
+
128
+ const sid = target && target.sessionId
129
+ // PA-1:409 会把 target.running 锁成 true;面板没有轮询 → 用户停掉会话后按钮仍全灰。
130
+ // overlay 槽不保证有 useSessions,故用有限次重查:1s/3s/8s 各拉一次 /messages,
131
+ // loadMessages 会把 running 同步回权威值(停下来了就自动解锁)。
132
+ const runningRecheckRef = useRef([])
133
+ useEffect(
134
+ () => () => {
135
+ for (const timer of runningRecheckRef.current) clearTimeout(timer)
136
+ },
137
+ [],
138
+ )
139
+
140
+ const loadMessages = useCallback(
141
+ async quiet => {
142
+ if (!sid) return
143
+ const requestId = ++loadSeqRef.current
144
+ const requestSid = sid
145
+ if (!quiet) {
146
+ setState('loading')
147
+ setLoadError(null)
148
+ }
149
+ try {
150
+ const data = await fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(requestSid) + '&view=compact')
151
+ if (requestId !== loadSeqRef.current) return
152
+ setMessages(Array.isArray(data.messages) ? data.messages : [])
153
+ setTarget(prev =>
154
+ prev && prev.sessionId === requestSid
155
+ ? {
156
+ ...prev,
157
+ running: data.running === true,
158
+ title: prev.title || (data.session && data.session.title) || null,
159
+ expectedTitle: (data.session && data.session.confirmTitle) || prev.expectedTitle || prev.title || prev.sessionId,
160
+ }
161
+ : prev,
162
+ )
163
+ setLoadError(null)
164
+ setError(null)
165
+ setState('ready')
166
+ } catch (reason) {
167
+ if (requestId !== loadSeqRef.current) return
168
+ const message = timeoutText(reason, t('panel.loadFail'))
169
+ if (quiet) setError(message)
170
+ else {
171
+ setLoadError(message)
172
+ setState('error')
173
+ }
174
+ }
175
+ },
176
+ [sid, t],
177
+ )
178
+
179
+ useEffect(() => {
180
+ if (!open || !sid) return
181
+ loadMessages(false)
182
+ }, [open, sid, loadMessages])
183
+
184
+ // 409 之后的有限重查(1s/3s/8s):loadMessages 会把 running 同步回权威值
185
+ const scheduleRunningRecheck = useCallback(() => {
186
+ for (const ms of [1000, 3000, 8000]) {
187
+ const timer = setTimeout(() => {
188
+ loadMessages(true).catch(() => {})
189
+ }, ms)
190
+ runningRecheckRef.current.push(timer)
191
+ }
192
+ }, [loadMessages])
193
+
194
+ useEffect(() => {
195
+ if (!open || tab !== 'messages') return
196
+ const q = query.trim()
197
+ if (!q) {
198
+ setHits(null)
199
+ setSearching(false)
200
+ return
201
+ }
202
+ setSearching(true)
203
+ let cancelled = false
204
+ const timer = setTimeout(() => {
205
+ setError(null)
206
+ const url =
207
+ '/api/message-ops/search?sessionId=' +
208
+ encodeURIComponent(sid) +
209
+ '&q=' +
210
+ encodeURIComponent(q) +
211
+ (role !== 'all' ? '&role=' + encodeURIComponent(role) : '') +
212
+ '&limit=' +
213
+ PANEL_SEARCH_LIMIT
214
+ fetchWithTimeout(url, undefined, __readTimeoutMs)
215
+ .then(readOpsJson)
216
+ .then(r => {
217
+ if (cancelled) return
218
+ if (!r.ok) throw opsError(r.status, r.data)
219
+ setHits(Array.isArray(r.data.results) ? r.data.results : [])
220
+ setError(null)
221
+ })
222
+ .catch(reason => {
223
+ if (!cancelled) setError(errText(reason, t('panel.searchFail')))
224
+ })
225
+ .finally(() => {
226
+ if (!cancelled) setSearching(false)
227
+ })
228
+ }, 200)
229
+ return () => {
230
+ cancelled = true
231
+ clearTimeout(timer)
232
+ }
233
+ }, [open, tab, sid, query, role, t])
234
+
235
+ const loadTrash = useCallback(async () => {
236
+ const requestId = ++trashSeqRef.current
237
+ setTrashState('loading')
238
+ setTrashError(null)
239
+ try {
240
+ // 竞态门是组件语义(requestId 是 hook state),保留在调用点;
241
+ // 只把「读响应体 + 校验 + 转文案」换成单点(审计 §2.4)。
242
+ const r = await readOpsJson(await fetchWithTimeout('/api/message-ops/session/trash', undefined, __readTimeoutMs))
243
+ if (requestId !== trashSeqRef.current) return
244
+ if (!r.ok) throw opsError(r.status, r.data)
245
+ setTrash(Array.isArray(r.data.entries) ? r.data.entries : [])
246
+ setTrashError(null)
247
+ setTrashState('ready')
248
+ } catch (reason) {
249
+ if (requestId !== trashSeqRef.current) return
250
+ setTrashError(errText(reason, t('panel.loadFail')))
251
+ setTrashState('error')
252
+ }
253
+ }, [t])
254
+
255
+ useEffect(() => {
256
+ if (open && tab === 'trash') {
257
+ setPurgeId(null) // 重新进入回收站 → 撤防(避免跨操作残留的二次确认态)
258
+ loadTrash()
259
+ }
260
+ }, [open, tab, loadTrash])
261
+
262
+ const close = useCallback(() => {
263
+ if (busy) return
264
+ loadSeqRef.current += 1
265
+ trashSeqRef.current += 1
266
+ detailReq.current += 1
267
+ setOpen(false)
268
+ setTarget(null)
269
+ setPicked(null)
270
+ setConfirmDelete(false)
271
+ setConfirmAction(null)
272
+ setDeleteError(null)
273
+ setLoadError(null)
274
+ setTrashError(null)
275
+ }, [busy])
276
+
277
+ const closeConfirm = useCallback(() => {
278
+ if (busy === 'session-delete') return
279
+ setConfirmDelete(false)
280
+ setConfirmTitle('')
281
+ setDeleteError(null)
282
+ setTimeout(() => {
283
+ const el = deleteBtnRef.current
284
+ if (el && !el.disabled) el.focus()
285
+ else if (panelRef.current) panelRef.current.focus()
286
+ }, 0)
287
+ }, [busy])
288
+
289
+ const cancelAction = useCallback(() => {
290
+ if (busy) return
291
+ const mode = confirmAction
292
+ setConfirmAction(null)
293
+ setTimeout(() => {
294
+ const targetRef = mode === 'revert' ? revertBtnRef.current : deleteOneBtnRef.current
295
+ if (targetRef && !targetRef.disabled) targetRef.focus()
296
+ else if (panelRef.current) panelRef.current.focus()
297
+ }, 0)
298
+ }, [busy, confirmAction])
299
+
300
+ useEffect(() => {
301
+ if (!open) return undefined
302
+ const onKey = e => {
303
+ if (e.key === 'Escape') {
304
+ const action = panelEscapeAction({ busy, confirmDelete, confirmAction, query })
305
+ if (action === 'ignore') return
306
+ if (action === 'closeConfirm') return closeConfirm()
307
+ if (action === 'cancelAction') return cancelAction()
308
+ if (action === 'clearQuery') {
309
+ setQuery('')
310
+ clearPick()
311
+ return
312
+ }
313
+ close()
314
+ } else if (e.key === '/') {
315
+ if (confirmDelete || confirmAction) return
316
+ const el = e.target
317
+ const tag = el && el.tagName
318
+ if (el && (tag === 'INPUT' || tag === 'TEXTAREA' || el.isContentEditable)) return
319
+ e.preventDefault()
320
+ if (searchRef.current) searchRef.current.focus()
321
+ }
322
+ }
323
+ window.addEventListener('keydown', onKey)
324
+ return () => window.removeEventListener('keydown', onKey)
325
+ }, [open, busy, confirmDelete, confirmAction, query, close, closeConfirm, cancelAction])
326
+
327
+ useEffect(() => {
328
+ if (!open) return undefined
329
+ if (!triggerRef.current) triggerRef.current = document.activeElement
330
+ const timer = setTimeout(() => {
331
+ if (searchRef.current) searchRef.current.focus()
332
+ else if (panelRef.current) panelRef.current.focus()
333
+ }, 0)
334
+ const scrim = scrimRef.current
335
+ const hidden = []
336
+ // 0.11.8:槽位会把 scrim 挂进一个**只有 scrim 自己**的独立容器,
337
+ // 于是「遍历 parent.children」永远遍历不到真实背景 —— inert 形同虚设
338
+ // (实测:inert=false,Tab 能跑到背后的会话列表,读屏也读得到)。
339
+ // 正确做法是从宿主挂载点(body 直接子节点)出发,把**包含 scrim 的那条
340
+ // 祖先链之外**的兄弟节点全部隔离;祖先链本身不能 inert(会连面板一起废掉)。
341
+ if (scrim && document.body) {
342
+ const chain = new Set()
343
+ for (let el = scrim; el && el !== document.body; el = el.parentElement) chain.add(el)
344
+ for (const child of Array.from(document.body.children)) {
345
+ if (chain.has(child)) continue
346
+ if (child.tagName === 'SCRIPT' || child.tagName === 'STYLE' || child.tagName === 'LINK') continue
347
+ hidden.push({ child, inert: child.hasAttribute('inert'), aria: child.getAttribute('aria-hidden') })
348
+ child.setAttribute('inert', '')
349
+ child.setAttribute('aria-hidden', 'true')
350
+ }
351
+ // 祖先链上的每一层:把**除当前链节点以外**的兄弟也隔离掉。
352
+ // 典型结构 body > #root > ... > 槽位容器 > scrim,中途每层都可能带界面。
353
+ for (const el of chain) {
354
+ const parent = el.parentElement
355
+ if (!parent || parent === document.body) continue
356
+ for (const sib of Array.from(parent.children)) {
357
+ if (sib === el || chain.has(sib)) continue
358
+ if (sib.tagName === 'SCRIPT' || sib.tagName === 'STYLE' || sib.tagName === 'LINK') continue
359
+ hidden.push({ child: sib, inert: sib.hasAttribute('inert'), aria: sib.getAttribute('aria-hidden') })
360
+ sib.setAttribute('inert', '')
361
+ sib.setAttribute('aria-hidden', 'true')
362
+ }
363
+ }
364
+ }
365
+ // 居中模态必须锁背景滚动:否则滚轮/触屏拖拽会把背后的会话列表滚走,
366
+ // 关闭后视口停在别处。用 overflow:hidden 而非 position:fixed,
367
+ // 后者会丢失滚动位置。保留原有内联值以便精确还原。
368
+ const body = document.body
369
+ const prevOverflow = body && body.style ? body.style.overflow : ''
370
+ const prevPaddingRight = body && body.style ? body.style.paddingRight : ''
371
+ let scrollbarW = 0
372
+ try {
373
+ scrollbarW = window.innerWidth - document.documentElement.clientWidth
374
+ } catch {
375
+ /* non-browser */
376
+ }
377
+ if (body && body.style) {
378
+ body.style.overflow = 'hidden'
379
+ // 为被隐藏的经典滚动条补回等宽内边距,避免整页横向跳动。
380
+ if (scrollbarW > 0) {
381
+ const base = Number.parseFloat(getComputedStyle(body).paddingRight) || 0
382
+ body.style.paddingRight = base + scrollbarW + 'px'
383
+ }
384
+ }
385
+ return () => {
386
+ clearTimeout(timer)
387
+ for (const item of hidden) {
388
+ if (!item.inert) item.child.removeAttribute('inert')
389
+ if (item.aria === null) item.child.removeAttribute('aria-hidden')
390
+ else item.child.setAttribute('aria-hidden', item.aria)
391
+ }
392
+ if (body && body.style) {
393
+ body.style.overflow = prevOverflow
394
+ body.style.paddingRight = prevPaddingRight
395
+ }
396
+ if (openRef.current) return
397
+ const trigger = triggerRef.current
398
+ triggerRef.current = null
399
+ if (trigger && typeof trigger.focus === 'function') {
400
+ setTimeout(() => {
401
+ try {
402
+ trigger.focus()
403
+ } catch {
404
+ /* detached trigger */
405
+ }
406
+ }, 0)
407
+ }
408
+ }
409
+ }, [open, sid])
410
+
411
+ useEffect(() => {
412
+ if (!open) return undefined
413
+ const onKeyDown = e => {
414
+ if (e.key !== 'Tab') return
415
+ const scope = confirmDelete ? confirmRef.current : confirmAction ? actionConfirmRef.current : panelRef.current
416
+ if (!scope) return
417
+ const nodes = focusablesIn(scope)
418
+ if (!nodes.length) {
419
+ e.preventDefault()
420
+ scope.focus()
421
+ return
422
+ }
423
+ const first = nodes[0]
424
+ const last = nodes[nodes.length - 1]
425
+ const active = document.activeElement
426
+ if (active === scope || !scope.contains(active)) {
427
+ e.preventDefault()
428
+ const fallback = e.shiftKey ? last : first
429
+ fallback.focus()
430
+ } else if (e.shiftKey && active === first) {
431
+ e.preventDefault()
432
+ last.focus()
433
+ } else if (!e.shiftKey && active === last) {
434
+ e.preventDefault()
435
+ first.focus()
436
+ }
437
+ }
438
+ document.addEventListener('keydown', onKeyDown, true)
439
+ return () => document.removeEventListener('keydown', onKeyDown, true)
440
+ }, [open, confirmDelete, confirmAction])
441
+
442
+ useEffect(() => {
443
+ if (!open) return
444
+ if (confirmDelete) {
445
+ const input = confirmRef.current && confirmRef.current.querySelector('input')
446
+ if (input) input.focus()
447
+ } else if (confirmAction) {
448
+ const first = actionConfirmRef.current && actionConfirmRef.current.querySelector('button')
449
+ if (first) first.focus()
450
+ }
451
+ }, [open, confirmDelete, confirmAction])
452
+
453
+ const baseRows = query.trim() ? hits || [] : messages
454
+ // 0.33.4(perf-audit #2):派生值进 useMemo。旧实现每次滚动 setScrollTop
455
+ // 都触发一次渲染 → 全量 filter+sort(实测 50k 行 10–19ms/帧,超 16.7ms 预算)。
456
+ const rows = useMemo(
457
+ () =>
458
+ baseRows
459
+ .filter(m => m && m.role !== 'system' && (role === 'all' || m.role === role) && (includeShadowed || !m.shadowed))
460
+ .sort((a, b) => b.seq - a.seq),
461
+ [baseRows, role, includeShadowed],
462
+ )
463
+ const activeIndex = picked ? rows.findIndex(m => m.seq === picked.seq) : -1
464
+
465
+ const clearPick = () => {
466
+ detailReq.current += 1
467
+ setPicked(null)
468
+ setDetail('')
469
+ setDetailState('idle')
470
+ setConfirmAction(null)
471
+ }
472
+
473
+ const scrollRowIntoView = index => {
474
+ const el = listRef.current
475
+ if (!el) return
476
+ const top = index * PANEL_ROW_H
477
+ const view = el.clientHeight || viewport
478
+ let next = el.scrollTop
479
+ if (top < next) next = top
480
+ else if (top + PANEL_ROW_H > next + view) next = top + PANEL_ROW_H - view
481
+ if (next !== el.scrollTop) {
482
+ el.scrollTop = next
483
+ setScrollTop(next)
484
+ }
485
+ }
486
+
487
+ const handleListKeyDown = e => {
488
+ if (!rows.length) return
489
+ const page = Math.max(1, Math.floor(((listRef.current && listRef.current.clientHeight) || viewport) / PANEL_ROW_H) - 1)
490
+ let next = activeIndex
491
+ if (e.key === 'ArrowDown') next = activeIndex < 0 ? 0 : Math.min(rows.length - 1, activeIndex + 1)
492
+ else if (e.key === 'ArrowUp') next = activeIndex < 0 ? rows.length - 1 : Math.max(0, activeIndex - 1)
493
+ else if (e.key === 'Home') next = 0
494
+ else if (e.key === 'End') next = rows.length - 1
495
+ else if (e.key === 'PageDown') next = activeIndex < 0 ? 0 : Math.min(rows.length - 1, activeIndex + page)
496
+ else if (e.key === 'PageUp') next = activeIndex < 0 ? rows.length - 1 : Math.max(0, activeIndex - page)
497
+ else if (e.key === 'Enter' || e.key === ' ') {
498
+ e.preventDefault()
499
+ const row = rows[activeIndex >= 0 ? activeIndex : 0]
500
+ if (row) {
501
+ pick(row)
502
+ if (listRef.current) listRef.current.focus()
503
+ }
504
+ return
505
+ } else {
506
+ return
507
+ }
508
+ e.preventDefault()
509
+ const row = rows[next]
510
+ if (!row) return
511
+ // 0.30.0 P0:键盘与鼠标必须走同一条取全文路径。旧实现只把 detail 塞成
512
+ // 160 字摘要,接着点「从此条分叉」会把截断文本写进新会话输入框。
513
+ pick(row)
514
+ scrollRowIntoView(next)
515
+ }
516
+
517
+ useEffect(() => {
518
+ if (!open || tab !== 'messages') return undefined
519
+ const el = listRef.current
520
+ if (!el) return undefined
521
+ const measure = () => setViewport(el.clientHeight || 480)
522
+ measure()
523
+ if (typeof ResizeObserver === 'undefined') return undefined
524
+ const ro = new ResizeObserver(measure)
525
+ ro.observe(el)
526
+ return () => ro.disconnect()
527
+ }, [open, tab, rows.length])
528
+
529
+ useEffect(() => {
530
+ if (!open || tab !== 'messages') return
531
+ const el = listRef.current
532
+ if (!el) return
533
+ const max = Math.max(0, rows.length * PANEL_ROW_H - (el.clientHeight || viewport))
534
+ if (el.scrollTop > max) {
535
+ el.scrollTop = max
536
+ setScrollTop(max)
537
+ }
538
+ }, [open, tab, rows.length, viewport])
539
+
540
+ const pick = useCallback(
541
+ m => {
542
+ if (!m || busy) return
543
+ setConfirmAction(null)
544
+ setPicked(m)
545
+ // 0.32.2:换选一条消息即作废上一次分叉的「打开新会话」入口,
546
+ // 否则回撤/删除成功的横幅里会挂着上一轮 branch 的 childId。
547
+ setChildId(null)
548
+ setActionError(null)
549
+ setDetail(m.snippet || '')
550
+ setDetailState('loading')
551
+ setDone('')
552
+ const req = ++detailReq.current
553
+ // 0.25.0(手感):全文取数交给 loadPanelText —— 命中缓存零请求、
554
+ // 快速划过列表只发停下来的那一条、同 seq 在途共享。竞态仍由
555
+ // detailReq 把关(过期结果一律丢弃)。
556
+ // 0.46.0(P3-1):结果有四态 —— 全文 / null(真失败)/ 已取消 / 超时。
557
+ // 取消是写操作作废了缓存(不是网络失败):保持「正在读取」并重取一次
558
+ //(缓存已清,重取拿到的就是写后原文);只有真失败才回退 snippet 并注明。
559
+ const showDetail = attempt => {
560
+ loadPanelText(sid, m.seq).then(full => {
561
+ if (req !== detailReq.current) return
562
+ if (full === PANEL_TEXT_CANCELLED) {
563
+ // 再被作废也不报「读取失败」:宁可等下一次选中,也不拿摘要冒充原文。
564
+ setDetailState('loading')
565
+ if (attempt === 0) showDetail(1)
566
+ return
567
+ }
568
+ if (full === PANEL_TEXT_TIMEOUT) {
569
+ setDetail(m.snippet || '')
570
+ setDetailState('timeout')
571
+ return
572
+ }
573
+ // 失败(null)→ 只有截断的 snippet,不许冒充原文(MED-5)。
574
+ // 0.32.2:失败必须显式标注,否则用户以为这 160 字就是全部。
575
+ setDetail(full ?? (m.snippet || ''))
576
+ setDetailState(full == null ? 'snippet' : 'ready')
577
+ })
578
+ }
579
+ showDetail(0)
580
+ },
581
+ [busy, sid],
582
+ )
583
+
584
+ const runAction = useCallback(
585
+ async (mode, confirmed) => {
586
+ if (!target || !picked || busy) return
587
+ if (target.running && mode !== 'branch') return
588
+ if ((mode === 'revert' || mode === 'delete') && confirmed !== true) return
589
+ const actionSid = target.sessionId
590
+ setBusy(mode)
591
+ setError(null)
592
+ setDone('')
593
+ try {
594
+ setActionError(null)
595
+ if (mode === 'branch') {
596
+ // 0.12.0:分叉 = opencode 的 before 语义(新会话不含此条,原文回输入框)。
597
+ // 非破坏操作,故不受 running 限制(官方 fork 会自己拒绝运行中源会话)。
598
+ // 取文本用 `detail`(该条全文,pick 时已按 seq 拉好);非用户消息不带文本。
599
+ const pickedRole = picked && picked.role
600
+ // 0.30.0 P0:分叉写入新会话输入框的必须是**全文**。detail 可能是列表/键盘
601
+ // 路径留下的 snippet(160 字),直接写进去会静默截断用户原文。
602
+ let text = ''
603
+ if (pickedRole === 'user') {
604
+ let full = await loadPanelText(actionSid, picked.seq)
605
+ // 0.46.0(P3-1):取消说明缓存刚被写操作清空,重取一次拿写后原文;
606
+ // 仍取不到就明确失败 —— 宁可取消分叉,也绝不拿摘要当原文。
607
+ if (full === PANEL_TEXT_CANCELLED) full = await loadPanelText(actionSid, picked.seq)
608
+ if (full === PANEL_TEXT_TIMEOUT) throw new Error(t('panel.textFail') + t('panel.timeout'))
609
+ if (full === PANEL_TEXT_CANCELLED || full == null || String(full).trim() === '') throw new Error(t('panel.textFail'))
610
+ text = full
611
+ }
612
+ const created = await forkFromUserMessage(actionSid, picked.seq, text, picked.turnStartSeq)
613
+ if (sessionRef.current !== actionSid) return
614
+ setChildId(created || null)
615
+ setDone(t('panel.branchDone', { id: String(created || '') }))
616
+ notifyDone(t('panel.branchDone', { id: String(created || '') }))
617
+ return
618
+ }
619
+ const res = await fetchWithTimeout('/api/message-ops/' + mode, {
620
+ method: 'POST',
621
+ headers: { 'content-type': 'application/json' },
622
+ body: JSON.stringify({ sessionId: target.sessionId, seq: picked.seq }),
623
+ })
624
+ const r = await readOpsJson(res)
625
+ if (sessionRef.current !== actionSid) return
626
+ // 非 branch 动作不得复用上一轮 branch 留下的「打开新会话」按钮。
627
+ setChildId(null)
628
+ if (!r.ok) {
629
+ // 409 → 面板立刻切「运行中」(组件语义,留在调用点)
630
+ if (r.status === 409) {
631
+ setTarget(prev => (prev ? { ...prev, running: true } : prev))
632
+ scheduleRunningRecheck()
633
+ }
634
+ throw opsError(r.status, r.data)
635
+ }
636
+ if (mode === 'revert') {
637
+ setMessages(prev => prev.map(m => (m.seq >= picked.seq ? { ...m, shadowed: true, visible: false } : m)))
638
+ if (picked.role === 'user') {
639
+ try {
640
+ refillComposer(target.sessionId, picked.seq)
641
+ } catch {
642
+ /* non-blocking */
643
+ }
644
+ }
645
+ } else {
646
+ setMessages(prev => prev.map(m => (m.seq === picked.seq ? { ...m, shadowed: true, visible: false } : m)))
647
+ }
648
+ const msg = t(mode === 'revert' ? 'panel.revertDone' : 'panel.deleteDone')
649
+ setDone(msg)
650
+ setConfirmAction(null)
651
+ setTimeout(() => {
652
+ if (listRef.current) listRef.current.focus()
653
+ }, 0)
654
+ notifyDone(msg)
655
+ emitChanged()
656
+ // 0.26.0:统一走 safeOpenSession(失败 warn,不静默吞 —— 审计 §2.3)
657
+ safeOpenSession(target.sessionId, 'panel-action')
658
+ setTimeout(() => {
659
+ loadMessages(true).catch(() => {})
660
+ }, 650)
661
+ } catch (reason) {
662
+ if (sessionRef.current !== actionSid) return
663
+ // 动作错误独立存放:后台 quiet 重查成功不得把它清掉。
664
+ setActionError(timeoutText(reason, t('errorPrefix')))
665
+ } finally {
666
+ setBusy('')
667
+ }
668
+ },
669
+ [target, picked, busy, t, loadMessages],
670
+ )
671
+
672
+ const deleteSession = useCallback(async () => {
673
+ if (!target || busy || target.running) return
674
+ const expected = target.expectedTitle || ''
675
+ if (!expected || confirmTitle.trim() !== expected) return
676
+ const actionSid = target.sessionId
677
+ setBusy('session-delete')
678
+ setDeleteError(null)
679
+ setDone('')
680
+ try {
681
+ const res = await fetchWithTimeout('/api/message-ops/session/delete', {
682
+ method: 'POST',
683
+ headers: { 'content-type': 'application/json' },
684
+ body: JSON.stringify({ sessionId: target.sessionId, confirmTitle: confirmTitle }),
685
+ })
686
+ const r = await readOpsJson(res)
687
+ if (sessionRef.current !== actionSid) return
688
+ if (!r.ok) {
689
+ if (r.status === 409) {
690
+ setTarget(prev => (prev ? { ...prev, running: true } : prev))
691
+ scheduleRunningRecheck()
692
+ }
693
+ throw opsError(r.status, r.data)
694
+ }
695
+ setConfirmDelete(false)
696
+ setDone(t('panel.deleted'))
697
+ notifyDone(t('panel.deleted'))
698
+ emitChanged()
699
+ // 0.33.13:archive 会经 workspace feed 让侧栏隐藏并关闭当前视图,
700
+ // 不再需要整页 reload(用户会看到「Loading plugins…」且丢掉 SPA 状态)。
701
+ setOpen(false)
702
+ setTarget(null)
703
+ } catch (reason) {
704
+ if (sessionRef.current !== actionSid) return
705
+ setDeleteError(timeoutText(reason, t('errorPrefix')))
706
+ } finally {
707
+ setBusy('')
708
+ }
709
+ }, [target, busy, confirmTitle, t])
710
+
711
+ const restoreEntry = useCallback(
712
+ // 任何一次恢复都先撤防永久删除:否则「删→恢复→再删」会一次点击就真删。
713
+
714
+ async trashId => {
715
+ if (busy) return
716
+ setPurgeId(null) // 撤防永久删除(见上)
717
+ setBusy('restore:' + trashId)
718
+ setError(null)
719
+ setDone('')
720
+ try {
721
+ const res = await fetchWithTimeout('/api/message-ops/session/restore', {
722
+ method: 'POST',
723
+ headers: { 'content-type': 'application/json' },
724
+ body: JSON.stringify({ trashId }),
725
+ })
726
+ const r = await readOpsJson(res)
727
+ if (!r.ok) throw opsError(r.status, r.data)
728
+ setTrash(prev => prev.filter(x => x.trashId !== trashId))
729
+ setDone(t('panel.restored'))
730
+ notifyDone(t('panel.restored'))
731
+ emitChanged()
732
+ // 0.33.13:unarchive 后宿主 feed 会把行放回侧栏,无需整页 reload。
733
+ } catch (reason) {
734
+ setError(timeoutText(reason, t('errorPrefix')))
735
+ } finally {
736
+ setBusy('')
737
+ }
738
+ },
739
+ [busy, t],
740
+ )
741
+
742
+ const purgeEntry = useCallback(
743
+ async trashId => {
744
+ if (busy) return
745
+ if (purgeId !== trashId) {
746
+ setPurgeId(trashId)
747
+ return
748
+ }
749
+ setBusy('purge:' + trashId)
750
+ setError(null)
751
+ setDone('')
752
+ try {
753
+ const res = await fetchWithTimeout('/api/message-ops/session/purge', {
754
+ method: 'POST',
755
+ headers: { 'content-type': 'application/json' },
756
+ body: JSON.stringify({ trashId }),
757
+ })
758
+ const r = await readOpsJson(res)
759
+ if (!r.ok) throw opsError(r.status, r.data)
760
+ setTrash(prev => prev.filter(x => x.trashId !== trashId))
761
+ setPurgeId(null)
762
+ setDone(t('panel.purged'))
763
+ notifyDone(t('panel.purged'))
764
+ } catch (reason) {
765
+ setError(timeoutText(reason, t('errorPrefix')))
766
+ } finally {
767
+ setBusy('')
768
+ }
769
+ },
770
+ [busy, purgeId, t],
771
+ )
772
+
773
+ // 0.33.9(React #310):hook 必须在**任何条件 return 之前**。
774
+ // 单趟计数(原先 3 次 filter + 每帧重算)。
775
+ const [visibleCount, shadowedCount, totalCount] = useMemo(() => {
776
+ let visible = 0
777
+ let shadowed = 0
778
+ let total = 0
779
+ for (const m of messages) {
780
+ if (!m || m.role === 'system') continue
781
+ total += 1
782
+ if (m.shadowed) shadowed += 1
783
+ else if (m.visible) visible += 1
784
+ }
785
+ return [visible, shadowed, total]
786
+ }, [messages])
787
+
788
+ if (!open) return null
789
+
790
+ const pickedLive = picked ? messages.find(m => m.seq === picked.seq) || picked : null
791
+ const canAct = !busy && !target.running && pickedLive && !pickedLive.shadowed
792
+ // 0.20.0(bug-hunt H-1 / M-3):AI 消息回滚已在 0.19.0 从动作区下线
793
+ // (用户明确要求「回撤是用户消息那边的用处」)。面板不能留一个
794
+ // 「能回滚 AI 消息却静默不回填」的旁路,故回滚按钮同样限定为用户消息。
795
+ // 删除按钮仍用 canAct —— 删单条 AI 消息是合理能力,不受此限。
796
+ const canRevert = canAct && pickedLive && pickedLive.role === 'user'
797
+ const revertImpact = pickedLive ? messages.filter(m => m.role !== 'system' && !m.shadowed && m.seq >= pickedLive.seq) : []
798
+ const revertCount = revertImpact.length
799
+ const revertVisibleCount = revertImpact.filter(m => m.visible).length
800
+ const revertEnd = revertImpact.reduce((max, m) => Math.max(max, m.seq), pickedLive ? pickedLive.seq : 0)
801
+ const expectedDeleteTitle = target.expectedTitle || ''
802
+ // 0.12.0:分叉/编辑只对**用户消息**成立(与 opencode 一致:fork 的语义是
803
+ // 「这句话说错了,拿回去重说」,AI 消息没有可回填的原文)。
804
+ const pickedIsUser = !!pickedLive && pickedLive.role === 'user'
805
+ const canFork = !busy && !target.running && pickedIsUser && !pickedLive.shadowed && pickedLive.seq > 0
806
+ // MED-5:只有**真拉到全文**才允许编辑。detail 在 /text 失败时会退化成
807
+ // snippet,而 snippet 被服务端硬截断到 160 字(session-file.js:331)——
808
+ // 拿它冒充原文会让用户改完发出时静默丢掉后半段。
809
+ const deleteBlockedReason = target.running
810
+ ? t('panel.running')
811
+ : state !== 'ready'
812
+ ? state === 'error'
813
+ ? t('panel.loadFail')
814
+ : t('panel.loading')
815
+ : !expectedDeleteTitle
816
+ ? t('panel.deleteUnavailable')
817
+ : ''
818
+ const canConfirmDelete =
819
+ !busy && state === 'ready' && !target.running && !!expectedDeleteTitle && confirmTitle.trim() === expectedDeleteTitle
820
+ const start = Math.min(Math.max(0, rows.length - 1), Math.max(0, Math.floor(scrollTop / PANEL_ROW_H) - 6))
821
+ const end = Math.min(rows.length, start + Math.ceil(viewport / PANEL_ROW_H) + 12)
822
+ const windowRows = rows.slice(start, end)
823
+ const activeRendered = picked && windowRows.some(m => m.seq === picked.seq)
824
+ const showSearchLoading = searching && query.trim().length > 0
825
+
826
+ return React.createElement(
827
+ 'div',
828
+ {
829
+ className: 'mopsPanelScrim',
830
+ role: 'presentation',
831
+ ref: scrimRef,
832
+ onMouseDown: e => {
833
+ // 确认层开着时点遮罩不关整个面板(与 Esc 一致:先退一层)
834
+ if (e.target !== e.currentTarget || confirmDelete || confirmAction) return
835
+ close()
836
+ },
837
+ },
838
+ React.createElement(
839
+ 'section',
840
+ {
841
+ className: 'mopsPanel',
842
+ role: 'dialog',
843
+ 'aria-modal': 'true',
844
+ 'aria-labelledby': 'mops-panel-title',
845
+ 'aria-describedby': 'mops-panel-session',
846
+ 'aria-busy': busy || state === 'loading' ? 'true' : undefined,
847
+ tabIndex: -1,
848
+ ref: panelRef,
849
+ style: { position: 'relative' },
850
+ },
851
+ React.createElement(
852
+ 'header',
853
+ { className: 'mopsPanelHead' },
854
+ React.createElement(
855
+ 'div',
856
+ { style: { minWidth: 0 } },
857
+ React.createElement('div', { className: 'mopsPanelKicker' }, t('dialog.title')),
858
+ React.createElement(
859
+ 'div',
860
+ { className: 'mopsPanelTitle', id: 'mops-panel-title' },
861
+ target.title || target.expectedTitle || target.sessionId,
862
+ ),
863
+ React.createElement('div', { className: 'mopsPanelSub', id: 'mops-panel-session' }, target.sessionId),
864
+ ),
865
+ React.createElement(
866
+ 'button',
867
+ {
868
+ type: 'button',
869
+ className: 'mopsPanelClose',
870
+ title: t('dialog.cancel'),
871
+ 'aria-label': t('dialog.cancel'),
872
+ onClick: close,
873
+ disabled: !!busy,
874
+ },
875
+ '×',
876
+ ),
877
+ ),
878
+ React.createElement(
879
+ 'div',
880
+ { className: 'mopsTabs', role: 'tablist', 'aria-label': t('dialog.title') },
881
+ (() => {
882
+ // 0.33.3(ui-live P2-4):APG tabs 模式 —— id/aria-controls/tabpanel/
883
+ // roving tabindex/方向键。旧实现只有 aria-selected。
884
+ const switchTab = (key, focus) => {
885
+ setTab(key)
886
+ setConfirmDelete(false)
887
+ setConfirmAction(null)
888
+ setDeleteError(null)
889
+ if (focus && typeof document !== 'undefined') {
890
+ const el = document.getElementById('mops-tab-' + key)
891
+ if (el && typeof el.focus === 'function') el.focus()
892
+ }
893
+ }
894
+ const onTabKey = e => {
895
+ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft' || e.key === 'Home' || e.key === 'End') {
896
+ e.preventDefault()
897
+ const next = e.key === 'Home' ? 'messages' : e.key === 'End' ? 'trash' : tab === 'messages' ? 'trash' : 'messages'
898
+ switchTab(next, true)
899
+ }
900
+ }
901
+ return [
902
+ React.createElement(
903
+ 'button',
904
+ {
905
+ key: 'messages',
906
+ type: 'button',
907
+ id: 'mops-tab-messages',
908
+ className: 'mopsTab' + (tab === 'messages' ? ' on' : ''),
909
+ role: 'tab',
910
+ 'aria-selected': tab === 'messages',
911
+ 'aria-controls': 'mops-tabpanel-messages',
912
+ tabIndex: tab === 'messages' ? 0 : -1,
913
+ onKeyDown: onTabKey,
914
+ onClick: () => switchTab('messages', false),
915
+ },
916
+ t('panel.messages') + ' ' + totalCount,
917
+ ),
918
+ React.createElement(
919
+ 'button',
920
+ {
921
+ key: 'trash',
922
+ type: 'button',
923
+ id: 'mops-tab-trash',
924
+ className: 'mopsTab' + (tab === 'trash' ? ' on' : ''),
925
+ role: 'tab',
926
+ 'aria-selected': tab === 'trash',
927
+ 'aria-controls': 'mops-tabpanel-trash',
928
+ tabIndex: tab === 'trash' ? 0 : -1,
929
+ onKeyDown: onTabKey,
930
+ onClick: () => switchTab('trash', false),
931
+ },
932
+ t('panel.trash') + (trash.length ? ' ' + trash.length : ''),
933
+ ),
934
+ ]
935
+ })(),
936
+ ),
937
+ target.running && tab === 'messages' && !confirmAction
938
+ ? React.createElement('div', { className: 'mopsBanner warn' }, t('panel.running'))
939
+ : null,
940
+ (actionError || error) && !confirmAction
941
+ ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, actionError || error)
942
+ : null,
943
+ done
944
+ ? React.createElement(
945
+ 'div',
946
+ { className: 'mopsBanner ok' },
947
+ done,
948
+ childId
949
+ ? React.createElement(
950
+ 'button',
951
+ {
952
+ type: 'button',
953
+ className: 'mopsAction primary',
954
+ style: { marginLeft: 10 },
955
+ onClick: () => {
956
+ safeOpenSession(childId, 'panel-branch')
957
+ },
958
+ },
959
+ t('panel.openNew'),
960
+ )
961
+ : null,
962
+ )
963
+ : null,
964
+ tab === 'messages'
965
+ ? React.createElement(
966
+ 'div',
967
+ {
968
+ className: 'mopsTabPanel',
969
+ role: 'tabpanel',
970
+ id: 'mops-tabpanel-messages',
971
+ 'aria-labelledby': 'mops-tab-messages',
972
+ },
973
+ React.createElement(
974
+ 'div',
975
+ { className: 'mopsSearchRow' },
976
+ React.createElement('input', {
977
+ ref: searchRef,
978
+ className: 'mopsSearch',
979
+ value: query,
980
+ placeholder: t('panel.searchHint'),
981
+ 'aria-label': t('panel.search'),
982
+ // PA-3:Enter/↓ 直接进列表并选中第一条(不必 Tab 过全部 chips)
983
+ onKeyDown: e => {
984
+ if (e.key !== 'Enter' && e.key !== 'ArrowDown') return
985
+ e.preventDefault()
986
+ if (listRef.current) listRef.current.focus()
987
+ const first = rows[0]
988
+ if (first) pick(first)
989
+ },
990
+ onChange: e => {
991
+ setQuery(e.target.value)
992
+ clearPick()
993
+ setScrollTop(0)
994
+ if (listRef.current) listRef.current.scrollTop = 0
995
+ },
996
+ }),
997
+ ),
998
+ React.createElement(
999
+ 'div',
1000
+ { className: 'mopsChips' },
1001
+ ['all', 'user', 'assistant', 'tool'].map(key =>
1002
+ React.createElement(
1003
+ 'button',
1004
+ {
1005
+ key,
1006
+ type: 'button',
1007
+ className: 'mopsChip' + (role === key ? ' on' : ''),
1008
+ onClick: () => {
1009
+ setRole(key)
1010
+ clearPick()
1011
+ setScrollTop(0)
1012
+ if (listRef.current) listRef.current.scrollTop = 0
1013
+ },
1014
+ },
1015
+ t('panel.' + key),
1016
+ ),
1017
+ ),
1018
+ React.createElement(
1019
+ 'label',
1020
+ { className: 'mopsToggle' },
1021
+ React.createElement('input', {
1022
+ type: 'checkbox',
1023
+ checked: includeShadowed,
1024
+ onChange: e => {
1025
+ setIncludeShadowed(e.target.checked)
1026
+ clearPick()
1027
+ setScrollTop(0)
1028
+ if (listRef.current) listRef.current.scrollTop = 0
1029
+ },
1030
+ }),
1031
+ t('panel.includeShadowed'),
1032
+ ),
1033
+ ),
1034
+ React.createElement(
1035
+ 'div',
1036
+ {
1037
+ className: 'mopsList',
1038
+ ref: listRef,
1039
+ role: state === 'ready' && rows.length ? 'listbox' : 'region',
1040
+ tabIndex: state === 'ready' && rows.length ? 0 : -1,
1041
+ 'aria-label': t('panel.messages'),
1042
+ 'aria-busy': state === 'loading' || showSearchLoading ? 'true' : undefined,
1043
+ 'aria-activedescendant': state === 'ready' && activeRendered ? 'mops-opt-' + picked.seq : undefined,
1044
+ onKeyDown: handleListKeyDown,
1045
+ onScroll: e => {
1046
+ // 0.33.4:滚动按帧合批,避免每个 scroll 事件都重渲染。
1047
+ const top = e.currentTarget.scrollTop
1048
+ if (scrollRaf.current != null) return
1049
+ const raf =
1050
+ typeof requestAnimationFrame === 'function' ? requestAnimationFrame : cb => setTimeout(cb, 16)
1051
+ scrollRaf.current = raf(() => {
1052
+ scrollRaf.current = null
1053
+ setScrollTop(top)
1054
+ })
1055
+ },
1056
+ },
1057
+ state === 'loading' || state === 'idle'
1058
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1059
+ : state === 'error'
1060
+ ? React.createElement(
1061
+ 'div',
1062
+ { className: 'mopsEmpty mopsErrorState', role: 'alert' },
1063
+ React.createElement('span', null, loadError || t('panel.loadFail')),
1064
+ React.createElement(
1065
+ 'button',
1066
+ {
1067
+ type: 'button',
1068
+ className: 'mopsAction',
1069
+ onClick: () => {
1070
+ loadMessages(false)
1071
+ setTimeout(() => {
1072
+ if (searchRef.current) searchRef.current.focus()
1073
+ }, 0)
1074
+ },
1075
+ },
1076
+ t('panel.retry'),
1077
+ ),
1078
+ )
1079
+ : rows.length === 0
1080
+ ? React.createElement(
1081
+ 'div',
1082
+ { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' },
1083
+ showSearchLoading ? t('panel.searching') : query.trim() ? t('panel.noMatch') : t('panel.empty'),
1084
+ )
1085
+ : React.createElement(
1086
+ 'div',
1087
+ { style: { height: rows.length * PANEL_ROW_H, position: 'relative' } },
1088
+ windowRows.map((m, i) =>
1089
+ React.createElement(
1090
+ 'div',
1091
+ {
1092
+ key: m.seq,
1093
+ id: 'mops-opt-' + m.seq,
1094
+ role: 'option',
1095
+ 'aria-selected': pickedLive && pickedLive.seq === m.seq,
1096
+ 'aria-setsize': rows.length,
1097
+ 'aria-posinset': start + i + 1,
1098
+ tabIndex: -1,
1099
+ className:
1100
+ 'mopsRow' + (pickedLive && pickedLive.seq === m.seq ? ' on' : '') + (m.shadowed ? ' shadowed' : ''),
1101
+ style: { top: (start + i) * PANEL_ROW_H, height: PANEL_ROW_H },
1102
+ onClick: () => {
1103
+ pick(m)
1104
+ if (listRef.current) listRef.current.focus()
1105
+ },
1106
+ title: '#' + m.seq + ' ' + (m.role || '') + ' · ' + (m.snippet || ''),
1107
+ 'aria-label':
1108
+ '#' +
1109
+ m.seq +
1110
+ ' ' +
1111
+ (m.role || '') +
1112
+ (m.shadowed ? ' ' + t('panel.shadowed') : '') +
1113
+ ' · ' +
1114
+ (m.snippet || '') +
1115
+ (m.time ? ' · ' + fmtClock(m.time) : ''),
1116
+ },
1117
+ React.createElement('span', { className: 'mopsSeq' }, '#' + m.seq),
1118
+ React.createElement('span', { className: 'mopsRole' }, roleCode(m.role)),
1119
+ React.createElement('span', { className: 'mopsSnippet' }, m.snippet || '—'),
1120
+ React.createElement('span', { className: 'mopsClock' }, fmtClock(m.time)),
1121
+ ),
1122
+ ),
1123
+ ),
1124
+ ),
1125
+ React.createElement(
1126
+ 'div',
1127
+ { className: 'mopsDetail' },
1128
+ pickedLive
1129
+ ? React.createElement(
1130
+ React.Fragment,
1131
+ null,
1132
+ React.createElement(
1133
+ 'div',
1134
+ { className: 'mopsDetailMeta' },
1135
+ React.createElement('span', null, '#' + pickedLive.seq),
1136
+ React.createElement('span', null, pickedLive.role || ''),
1137
+ pickedLive.shadowed ? React.createElement('span', null, t('panel.shadowed')) : null,
1138
+ pickedLive.time ? React.createElement('span', null, fmtClock(pickedLive.time)) : null,
1139
+ ),
1140
+ React.createElement(
1141
+ 'pre',
1142
+ { className: 'mopsDetailText' },
1143
+ detailState === 'loading' ? t('panel.detailLoading') : detail || pickedLive.snippet || '—',
1144
+ ),
1145
+ detailState === 'snippet'
1146
+ ? React.createElement('div', { className: 'mopsDetailNote' }, t('panel.snippetOnly'))
1147
+ : detailState === 'timeout'
1148
+ ? React.createElement('div', { className: 'mopsDetailNote' }, t('panel.detailTimeout'))
1149
+ : null,
1150
+ React.createElement(
1151
+ 'div',
1152
+ { className: 'mopsActions' },
1153
+ React.createElement(
1154
+ 'button',
1155
+ {
1156
+ type: 'button',
1157
+ className: 'mopsAction primary',
1158
+ disabled: !canRevert || !!confirmAction,
1159
+ ref: revertBtnRef,
1160
+ onClick: () => setConfirmAction('revert'),
1161
+ title: t('panel.revertHint'),
1162
+ },
1163
+ t('panel.revert') + (revertCount ? ' · ' + revertCount : ''),
1164
+ ),
1165
+ React.createElement(
1166
+ 'button',
1167
+ {
1168
+ type: 'button',
1169
+ className: 'mopsAction danger',
1170
+ disabled: !canAct || !!confirmAction,
1171
+ ref: deleteOneBtnRef,
1172
+ onClick: () => setConfirmAction('delete'),
1173
+ title: t('panel.deleteHint'),
1174
+ },
1175
+ t('panel.delete'),
1176
+ ),
1177
+ // 分叉同样只对用户消息可用(AI 消息没有可回填的原文),
1178
+ // 语义 = opencode 的 before:新会话不含此条,原文进新会话输入框。
1179
+ React.createElement(
1180
+ 'button',
1181
+ {
1182
+ type: 'button',
1183
+ className: 'mopsAction',
1184
+ disabled: !canFork || !!confirmAction,
1185
+ onClick: () => runAction('branch'),
1186
+ title: pickedIsUser ? t('panel.branchHint') : t('panel.branchUserOnly'),
1187
+ },
1188
+ t('panel.branch'),
1189
+ ),
1190
+ ),
1191
+ confirmAction
1192
+ ? React.createElement(
1193
+ 'div',
1194
+ {
1195
+ className: 'mopsActionConfirm',
1196
+ ref: actionConfirmRef,
1197
+ role: 'group',
1198
+ tabIndex: -1,
1199
+ 'aria-labelledby': 'mops-action-confirm-title',
1200
+ },
1201
+ React.createElement(
1202
+ 'div',
1203
+ { className: 'mopsImpactTitle', id: 'mops-action-confirm-title' },
1204
+ t(confirmAction === 'revert' ? 'panel.revertConfirmTitle' : 'panel.deleteConfirmTitle', {
1205
+ seq: String(pickedLive.seq),
1206
+ }),
1207
+ ),
1208
+ (actionError || error)
1209
+ ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, actionError || error)
1210
+ : null,
1211
+ React.createElement(
1212
+ 'div',
1213
+ { className: 'mopsImpact' },
1214
+ confirmAction === 'revert'
1215
+ ? t('panel.revertConfirmBody', {
1216
+ start: String(pickedLive.seq),
1217
+ end: String(revertEnd),
1218
+ n: String(revertCount),
1219
+ v: String(revertVisibleCount),
1220
+ })
1221
+ : t('panel.deleteConfirmBody'),
1222
+ ),
1223
+ React.createElement(
1224
+ 'div',
1225
+ { className: 'mopsConfirmRow' },
1226
+ React.createElement(
1227
+ 'button',
1228
+ {
1229
+ type: 'button',
1230
+ className: 'mopsAction',
1231
+ onClick: cancelAction,
1232
+ disabled: !!busy,
1233
+ },
1234
+ t('panel.cancel'),
1235
+ ),
1236
+ React.createElement(
1237
+ 'button',
1238
+ {
1239
+ type: 'button',
1240
+ className: 'mopsAction danger',
1241
+ onClick: () => runAction(confirmAction, true),
1242
+ disabled: !!busy || !canAct,
1243
+ },
1244
+ busy === confirmAction
1245
+ ? t('panel.busy')
1246
+ : t(confirmAction === 'revert' ? 'panel.confirmRevert' : 'panel.confirmDeleteOne'),
1247
+ ),
1248
+ ),
1249
+ )
1250
+ : null,
1251
+ )
1252
+ : React.createElement('div', { className: 'mopsDetailHint' }, t('panel.selectHint')),
1253
+ ),
1254
+ React.createElement(
1255
+ 'footer',
1256
+ { className: 'mopsPanelFoot' },
1257
+ React.createElement(
1258
+ 'span',
1259
+ { className: 'mopsCount' },
1260
+ t('panel.count', { n: String(totalCount), v: String(visibleCount), s: String(shadowedCount) }),
1261
+ ),
1262
+ React.createElement(
1263
+ 'button',
1264
+ {
1265
+ type: 'button',
1266
+ className: 'mopsDanger',
1267
+ ref: deleteBtnRef,
1268
+ disabled: !!busy || !!deleteBlockedReason,
1269
+ title: deleteBlockedReason || undefined,
1270
+ onClick: () => {
1271
+ setConfirmTitle('')
1272
+ setDeleteError(null)
1273
+ setConfirmAction(null)
1274
+ setConfirmDelete(true)
1275
+ },
1276
+ },
1277
+ t('panel.deleteSession'),
1278
+ ),
1279
+ ),
1280
+ confirmDelete
1281
+ ? React.createElement(
1282
+ 'div',
1283
+ {
1284
+ className: 'mopsConfirm',
1285
+ ref: confirmRef,
1286
+ role: 'alertdialog',
1287
+ 'aria-modal': 'true',
1288
+ 'aria-labelledby': 'mops-delete-title',
1289
+ 'aria-describedby': 'mops-delete-hint mops-delete-impact',
1290
+ tabIndex: -1,
1291
+ },
1292
+ React.createElement('h3', { id: 'mops-delete-title' }, t('panel.deleteSession')),
1293
+ React.createElement('p', { id: 'mops-delete-hint' }, t('panel.deleteSessionHint')),
1294
+ React.createElement(
1295
+ 'p',
1296
+ { className: 'mopsImpact', id: 'mops-delete-impact' },
1297
+ t('panel.deleteSessionImpact', { n: String(totalCount) }),
1298
+ ),
1299
+ deleteBlockedReason
1300
+ ? React.createElement('div', { className: 'mopsBanner warn', role: 'status' }, deleteBlockedReason)
1301
+ : null,
1302
+ target.running
1303
+ ? React.createElement('div', { className: 'mopsBanner warn', role: 'status' }, t('panel.running'))
1304
+ : null,
1305
+ deleteError ? React.createElement('div', { className: 'mopsBanner err', role: 'alert' }, deleteError) : null,
1306
+ React.createElement('input', {
1307
+ id: 'mops-delete-title-input',
1308
+ value: confirmTitle,
1309
+ autoFocus: true,
1310
+ 'aria-label': t('panel.deleteSessionHint'),
1311
+ 'aria-describedby': 'mops-delete-hint',
1312
+ placeholder: expectedDeleteTitle || target.title || target.sessionId,
1313
+ disabled: !!busy || target.running || !expectedDeleteTitle,
1314
+ onChange: e => setConfirmTitle(e.target.value),
1315
+ onKeyDown: e => {
1316
+ if (e.key === 'Enter') {
1317
+ e.preventDefault()
1318
+ if (canConfirmDelete) deleteSession()
1319
+ } else if (e.key === 'Escape') {
1320
+ e.preventDefault()
1321
+ e.stopPropagation()
1322
+ closeConfirm()
1323
+ }
1324
+ },
1325
+ }),
1326
+ React.createElement(
1327
+ 'div',
1328
+ { className: 'mopsConfirmRow' },
1329
+ React.createElement(
1330
+ 'button',
1331
+ {
1332
+ type: 'button',
1333
+ className: 'mopsAction',
1334
+ onClick: closeConfirm,
1335
+ disabled: busy === 'session-delete',
1336
+ },
1337
+ t('panel.cancel'),
1338
+ ),
1339
+ React.createElement(
1340
+ 'button',
1341
+ {
1342
+ type: 'button',
1343
+ className: 'mopsAction danger',
1344
+ disabled: !canConfirmDelete,
1345
+ onClick: deleteSession,
1346
+ },
1347
+ busy === 'session-delete' ? t('panel.deleting') : t('panel.confirmDelete'),
1348
+ ),
1349
+ ),
1350
+ )
1351
+ : null,
1352
+ )
1353
+ : React.createElement(
1354
+ 'div',
1355
+ {
1356
+ className: 'mopsList',
1357
+ style: { borderTop: 0 },
1358
+ role: 'tabpanel',
1359
+ id: 'mops-tabpanel-trash',
1360
+ 'aria-labelledby': 'mops-tab-trash',
1361
+ 'aria-busy': trashState === 'loading' ? 'true' : undefined,
1362
+ },
1363
+ trashState === 'loading' || trashState === 'idle'
1364
+ ? React.createElement('div', { className: 'mopsEmpty', role: 'status', 'aria-live': 'polite' }, t('panel.loading'))
1365
+ : trashState === 'error'
1366
+ ? React.createElement(
1367
+ 'div',
1368
+ { className: 'mopsEmpty mopsErrorState', role: 'alert' },
1369
+ React.createElement('span', null, trashError || t('panel.loadFail')),
1370
+ React.createElement(
1371
+ 'button',
1372
+ {
1373
+ type: 'button',
1374
+ className: 'mopsAction',
1375
+ onClick: () => {
1376
+ loadTrash()
1377
+ setTimeout(() => {
1378
+ if (panelRef.current) panelRef.current.focus()
1379
+ }, 0)
1380
+ },
1381
+ },
1382
+ t('panel.retry'),
1383
+ ),
1384
+ )
1385
+ : trash.length === 0
1386
+ ? React.createElement('div', { className: 'mopsEmpty' }, t('panel.trashEmpty'))
1387
+ : trash.map(item =>
1388
+ React.createElement(
1389
+ 'div',
1390
+ { className: 'mopsTrashItem', key: item.trashId },
1391
+ React.createElement(
1392
+ 'div',
1393
+ { className: 'mopsTrashMain' },
1394
+ React.createElement('div', { className: 'mopsTrashTitle' }, item.title || t('panel.untitled')),
1395
+ React.createElement(
1396
+ 'div',
1397
+ { className: 'mopsTrashMeta' },
1398
+ (item.sessionId || t('panel.trashManual')) +
1399
+ (item.expiresAt ? ' · ' + t('panel.expires') + ' ' + new Date(item.expiresAt).toLocaleDateString() : ''),
1400
+ ),
1401
+ ),
1402
+ // 0.42.0(srv-audit D9/D10):异常态条目不提供 Restore ——
1403
+ // moving(删除中断、仅存副本留作人工恢复)与 corrupt(清单损坏)
1404
+ // 调用恢复只会拿到 409,摆一个必错按钮是坏交互。
1405
+ item.state === 'moving' || item.state === 'corrupt' || item.corrupt === true
1406
+ ? React.createElement(
1407
+ 'span',
1408
+ { className: 'mopsTrashNote' },
1409
+ item.state === 'corrupt' || item.corrupt === true ? t('panel.trashCorrupt') : t('panel.trashMoving'),
1410
+ )
1411
+ : React.createElement(
1412
+ 'button',
1413
+ {
1414
+ type: 'button',
1415
+ className: 'mopsAction',
1416
+ disabled: !!busy,
1417
+ onClick: () => restoreEntry(item.trashId),
1418
+ },
1419
+ busy === 'restore:' + item.trashId ? t('panel.busy') : t('panel.restore'),
1420
+ ),
1421
+ React.createElement(
1422
+ 'button',
1423
+ {
1424
+ type: 'button',
1425
+ className: 'mopsAction danger',
1426
+ disabled: !!busy,
1427
+ onClick: () => purgeEntry(item.trashId),
1428
+ },
1429
+ busy === 'purge:' + item.trashId
1430
+ ? t('panel.busy')
1431
+ : purgeId === item.trashId
1432
+ ? t('panel.purgeConfirm')
1433
+ : t('panel.purge'),
1434
+ ),
1435
+ ),
1436
+ ),
1437
+ ),
1438
+ ),
1439
+ )
1440
+ }
1441
+
1442
+ // --- 0.26.0 / 0.28.0 · 「编辑并回撤重发」的编排层 -----------------------------
1443
+ //
1444
+ // 语义(用户原话:干净的定制编辑框,就在那条消息旁边展开,然后发送):
1445
+ //
1446
+ // 点铅笔 → 纯读:预填 `/messages` 的 row.fullText,在**这条消息自己的行内**
1447
+ // (气泡下、动作行上)展开编辑区。零写操作。
1448
+ // 取消 / Esc → 关闭编辑区并把焦点还给铅笔。零 fetch、零写盘、零 openSession。
1449
+ // (0.28.0 起没有贴边浮层、也没有 click-outside:编辑区是行内元素。)
1450
+ // 点「撤销并发送」这一刻才写,顺序严格如下:
1451
+ // ① POST /api/message-ops/revert { sessionId, seq }
1452
+ // 失败(含 409 运行中)→ 保留浮层与用户已改的文本,报错,**零副作用**
1453
+ // ② markRowsShadowedFrom(seq) —— 与其它回滚入口共用同一个防 409 护栏
1454
+ // ③ emitChanged + openSession —— 视图重建(遮蔽才立即可见)
1455
+ // ④ sessions.using(...).prompt([{ type: 'text', text }], 'queue')
1456
+ // —— 官方发送面。失败按 error.code/message 上抛,**不再**假成功
1457
+ //
1458
+ // 为什么删掉 0.20~0.25 的「写草稿 + 轮询 inputActions.submit」:
1459
+ // 老路径要先写 localStorage 草稿 → 重建视图 → 等宿主重挂编辑器(8×120ms 有界
1460
+ // 轮询)→ 再 setDraft + submit()。它有两个副作用:①改后的文本**留在 composer**
1461
+ // (用户发完还看得见同一段字,正是「UI 上又复现一遍」);②轮询期间宿主任何重渲染
1462
+ // 都可能让 submit 打到已 dispose 的实例。官方 `sessions.using` + `session.prompt`
1463
+ // 是宿主自己的发送面:排队语义由宿主保证,失败有结构化 error code。
1464
+ //
1465
+ // 老宿主降级(sessions 服务 / session.prompt 缺席):**唯一**兜底 = 把文本写进该
1466
+ // 会话草稿并回读校验,再提示按回车(edit.manual)。只有这一条,绝不复制第二套
1467
+ // composer 逻辑。降级路径返回 persisted,组件据此选择文案。
1468
+ //
1469
+ // 为什么不用 fork:「分叉」的语义是源会话一字不动;同一个「编辑」动作若在铅笔里
1470
+ // 改写源会话、在分叉里保留源会话,就是两套相反语义 —— 用户无法预期。
1471
+ /**
1472
+ * 官方 session 引用来源标签。
1473
+ *
1474
+ * `SessionReferenceSource` 是**声明合并可扩展**的开放表(宿主只内置
1475
+ * controllerOperation / gateway 两项),第三方插件自报一个标签是官方允许的用法
1476
+ * (第三方 message-edit 插件同样用 'messageEdit')。它只进 retainedBy 计数,
1477
+ * 运行时**不做白名单校验**(已读 dsh-api-session-controller 的 retainScope 源码)。
1478
+ */