dsh-context-manager 0.0.0-stage → 1.6.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.
package/client.js ADDED
@@ -0,0 +1,1150 @@
1
+ /**
2
+ * Client half of the Session Context Manager.
3
+ *
4
+ * The header utility opens a frame-wide dialog listing the messages currently
5
+ * loaded into the view. It folds surface replacements locally so a deleted row
6
+ * disappears immediately, and it performs the deletion through the Host command
7
+ * that owns the authoritative surface rewrite.
8
+ */
9
+ window.__ModuleLoader__.load({
10
+ id: 'dsh-context-manager',
11
+ factory(require) {
12
+ const React = require('react')
13
+ const h = React.createElement
14
+ const { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } = React
15
+
16
+ const NS = 'context-manager'
17
+ const SURFACE_TYPES = new Set([
18
+ 'system/message',
19
+ 'developer/message',
20
+ 'user/message',
21
+ 'assistant/message',
22
+ 'tool/result',
23
+ ])
24
+ const EMPTY_WINDOW = Object.freeze({
25
+ entries: [],
26
+ hasMore: false,
27
+ revision: 0,
28
+ change: Object.freeze({ kind: 'replace', entries: [] }),
29
+ })
30
+
31
+ const zh = {
32
+ open: '上下文管理',
33
+ title: '上下文管理',
34
+ subtitle: '管理当前会话的模型上下文:按条删除、按整轮删除,之后都能恢复。',
35
+ close: '关闭',
36
+ empty: '当前上下文没有可管理的消息。',
37
+ notReady: '会话尚未就绪,请稍后再试。',
38
+ count: '共 {count} 条消息',
39
+ hint: '删除只影响后续模型请求,原始日志和聊天记录会保留。',
40
+ delete: '删除这条消息',
41
+ cancel: '取消',
42
+ confirmDelete: '确认删除',
43
+ confirmQuestion: '从模型上下文中移除?',
44
+ groupHint: '相关的工具结果会一并移除。',
45
+ user: '用户',
46
+ assistant: '助手',
47
+ tool: '工具',
48
+ context: '上下文',
49
+ system: '系统',
50
+ emptyMessage: '(空消息)',
51
+ failed: '操作失败',
52
+ deleted: '已删除 {count} 条消息。',
53
+ restoreQueued: '已加入恢复队列:{count} 条将在下一回合恢复。',
54
+ busy: '正在处理…',
55
+ usage: '删除:/ctxmgr delete <序号,...> · 整轮:/ctxmgr deleteturn <轮号,...>',
56
+ currentSection: '当前消息',
57
+ deletedSection: '已删除',
58
+ selectAll: '全选',
59
+ clearSelection: '清空',
60
+ deleteSelected: '删除选中 ({count})',
61
+ restoreSelected: '恢复选中 ({count})',
62
+ restore: '恢复',
63
+ confirmBatch: '确认删除选中的 {count} 条消息?',
64
+ deletedGroup: '删除组',
65
+ contentNotLoaded: '内容未加载',
66
+ restoreAppended: '恢复到末尾',
67
+ unrestorableTool: '工具结果不可单独恢复',
68
+ unrestorableGroup: '该删除组不可恢复',
69
+ deletedRecord: '删除记录 #{seq}',
70
+ selected: '已选 {count}',
71
+ unavailable: '不可恢复',
72
+ confirmTotal: '共移除 {count} 条消息',
73
+ turnsSection: '对话轮(整轮删除)',
74
+ turnBadge: '轮 {turn}',
75
+ deleteTurn: '删除本轮',
76
+ confirmBatchTurns: '确认删除选中的 {count} 轮对话?',
77
+ turnsDeleted: '已提交删除 {count} 轮对话。',
78
+ inProgressNote: '进行中,下一回合生效',
79
+ noUserMessage: '(无用户提问)',
80
+ turnMeta: '{count} 条',
81
+ expandSection: '展开',
82
+ collapseSection: '折叠',
83
+ }
84
+
85
+ const en = {
86
+ open: 'Context manager',
87
+ title: 'Context manager',
88
+ subtitle: 'Manage the model context of this session: delete messages or whole turns, and restore them later.',
89
+ close: 'Close',
90
+ empty: 'There are no manageable messages in the current context.',
91
+ notReady: 'The session is not ready yet.',
92
+ count: '{count} messages',
93
+ hint: 'Deletion only affects later model requests; the raw log and chat transcript are retained.',
94
+ delete: 'Delete this message',
95
+ cancel: 'Cancel',
96
+ confirmDelete: 'Delete',
97
+ confirmQuestion: 'Remove from the model context?',
98
+ groupHint: 'Related tool results are removed together.',
99
+ user: 'User',
100
+ assistant: 'Assistant',
101
+ tool: 'Tool',
102
+ context: 'Context',
103
+ system: 'System',
104
+ emptyMessage: '(empty)',
105
+ failed: 'Operation failed',
106
+ deleted: 'Deleted {count} messages.',
107
+ restoreQueued: 'Queued {count} message(s) for restore on the next turn.',
108
+ busy: 'Working…',
109
+ usage: 'Delete: /ctxmgr delete <seq,...> · turns: /ctxmgr deleteturn <turn,...>',
110
+ currentSection: 'Current messages',
111
+ deletedSection: 'Deleted',
112
+ selectAll: 'Select all',
113
+ clearSelection: 'Clear',
114
+ deleteSelected: 'Delete selected ({count})',
115
+ restoreSelected: 'Restore selected ({count})',
116
+ restore: 'Restore',
117
+ confirmBatch: 'Delete the {count} selected messages?',
118
+ deletedGroup: 'Deleted group',
119
+ contentNotLoaded: 'content not loaded',
120
+ restoreAppended: 'restored at the tail',
121
+ unrestorableTool: 'A tool result cannot be restored alone',
122
+ unrestorableGroup: 'This deleted group cannot be restored',
123
+ deletedRecord: 'Deleted record #{seq}',
124
+ selected: '{count} selected',
125
+ unavailable: 'Not restorable',
126
+ confirmTotal: '{count} messages will be removed in total',
127
+ turnsSection: 'Turns (delete whole turn)',
128
+ turnBadge: 'Turn {turn}',
129
+ deleteTurn: 'Delete turn',
130
+ confirmBatchTurns: 'Delete the {count} selected turns?',
131
+ turnsDeleted: 'Queued {count} turn(s) for deletion.',
132
+ inProgressNote: 'in progress, applies next turn',
133
+ noUserMessage: '(no user prompt)',
134
+ turnMeta: '{count} messages',
135
+ expandSection: 'Expand',
136
+ collapseSection: 'Collapse',
137
+ }
138
+
139
+ const CSS = `
140
+ .dshmm-btn{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;flex:none}
141
+ .dshmm-btn:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 8%, transparent);color:var(--dsw-alias-label-primary)}
142
+ .dshmm-btn[data-open="true"]{background:color-mix(in srgb, var(--dsw-alias-brand-primary) 14%, transparent);color:var(--dsw-alias-brand-primary)}
143
+ .dshmm-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
144
+ .dshmm-backdrop{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;padding:24px;background:color-mix(in srgb, var(--dsw-alias-bg-base) 58%, transparent);backdrop-filter:blur(2px);pointer-events:auto}
145
+ .dshmm-panel{box-sizing:border-box;width:min(720px,100%);max-height:min(82vh,780px);display:flex;flex-direction:column;overflow:hidden;background:var(--dsw-alias-bg-overlay);color:var(--dsw-alias-label-primary);border:0.5px solid var(--dsw-alias-border-l2);border-radius:16px;box-shadow:var(--dsw-elevation-prominent,0 24px 64px rgba(0,0,0,.28));font-family:inherit;outline:none}
146
+ .dshmm-head{padding:16px 20px 12px;border-bottom:1px solid var(--dsw-alias-border-l1);flex:none}
147
+ .dshmm-titleRow{display:flex;align-items:center;justify-content:space-between;gap:12px}
148
+ .dshmm-title{margin:0;font-size:15px;line-height:22px;font-weight:600;color:var(--dsw-alias-label-primary)}
149
+ .dshmm-subtitle{margin:4px 0 0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
150
+ .dshmm-close{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;flex:none}
151
+ .dshmm-close:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 8%, transparent);color:var(--dsw-alias-label-primary)}
152
+ .dshmm-close:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
153
+ .dshmm-banner{margin:10px 20px 0;padding:8px 10px;border-radius:8px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);background:color-mix(in srgb, var(--dsw-alias-label-primary) 7%, transparent);flex:none;overflow-wrap:anywhere}
154
+ .dshmm-banner[data-kind="success"]{color:var(--dsw-alias-state-success-primary);background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 12%, transparent)}
155
+ .dshmm-banner[data-kind="error"]{color:var(--dsw-alias-state-error-primary);background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent)}
156
+ .dshmm-list{flex:auto;min-height:120px;overflow-y:auto;padding:4px 0;background:var(--dsw-alias-bg-overlay)}
157
+ .dshmm-row{display:flex;align-items:flex-start;gap:12px;padding:10px 20px;border-bottom:1px solid var(--dsw-alias-border-l1);min-width:0}
158
+ .dshmm-row:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent)}
159
+ .dshmm-role{flex:none;min-width:52px;text-align:center;font-size:11px;line-height:18px;padding:1px 8px;margin-top:1px;border-radius:6px;color:var(--dsw-alias-label-secondary);background:color-mix(in srgb, var(--dsw-alias-label-secondary) 10%, transparent);white-space:nowrap}
160
+ .dshmm-row[data-role="user"] .dshmm-role{color:var(--dsw-alias-brand-primary);background:color-mix(in srgb, var(--dsw-alias-brand-primary) 13%, transparent)}
161
+ .dshmm-row[data-role="assistant"] .dshmm-role{color:var(--dsw-alias-state-success-primary);background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 12%, transparent)}
162
+ .dshmm-main{flex:auto;min-width:0}
163
+ .dshmm-preview{font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
164
+ .dshmm-meta{margin-top:2px;font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
165
+ .dshmm-actions{flex:none;display:flex;align-items:center;justify-content:flex-end;min-width:28px}
166
+ .dshmm-iconbtn{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;flex:none}
167
+ .dshmm-iconbtn:hover{background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent);color:var(--dsw-alias-state-error-primary)}
168
+ .dshmm-iconbtn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
169
+ .dshmm-confirm{display:flex;flex-direction:column;align-items:flex-end;gap:6px;max-width:260px}
170
+ .dshmm-confirmText{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);text-align:right}
171
+ .dshmm-confirmActions{display:flex;align-items:center;gap:6px}
172
+ .dshmm-small{appearance:none;border:0;border-radius:6px;padding:4px 9px;font:inherit;font-size:11px;line-height:16px;cursor:pointer;background:color-mix(in srgb, var(--dsw-alias-label-primary) 8%, transparent);color:var(--dsw-alias-label-primary)}
173
+ .dshmm-small:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 13%, transparent)}
174
+ .dshmm-small:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
175
+ .dshmm-small[data-danger="true"]{background:var(--dsw-alias-state-error-primary);color:var(--dsw-alias-bg-base)}
176
+ .dshmm-small[data-danger="true"]:hover{background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 84%, var(--dsw-alias-label-primary))}
177
+ .dshmm-small:disabled{opacity:.55;cursor:default}
178
+ .dshmm-empty{padding:40px 20px;text-align:center;font-size:13px;line-height:20px;color:var(--dsw-alias-label-secondary)}
179
+ .dshmm-foot{padding:10px 20px;border-top:1px solid var(--dsw-alias-border-l1);display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;flex:none}
180
+ .dshmm-footCount{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
181
+ .dshmm-footHint{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);text-align:right;flex:auto;min-width:0}
182
+ .dshmm-code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px}
183
+ .dshmm-section{position:sticky;top:0;z-index:2;display:flex;align-items:center;gap:10px;padding:8px 20px;background:var(--dsw-alias-bg-overlay);border-bottom:1px solid var(--dsw-alias-border-l1);box-shadow:0 1px 0 var(--dsw-alias-border-l1)}
184
+ .dshmm-sectionTitle{font-size:12px;line-height:18px;font-weight:600;color:var(--dsw-alias-label-primary);white-space:nowrap}
185
+ .dshmm-sectionCount{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
186
+ .dshmm-sectionActions{display:flex;align-items:center;gap:6px;margin-left:auto;min-width:0}
187
+ .dshmm-sectionToggle{display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;padding:0;margin:0;font:inherit;color:inherit;cursor:pointer}
188
+ .dshmm-sectionToggle:hover{color:var(--dsw-alias-label-primary)}
189
+ .dshmm-sectionToggle:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
190
+ .dshmm-chevron{font-size:10px;line-height:16px;color:var(--dsw-alias-label-secondary);width:10px;text-align:center}
191
+ .dshmm-sectionToggle:hover .dshmm-chevron{color:var(--dsw-alias-label-primary)}
192
+ .dshmm-selectAll{display:inline-flex;align-items:center;gap:6px;font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);cursor:pointer;white-space:nowrap}
193
+ .dshmm-check{width:14px;height:14px;margin:0;accent-color:var(--dsw-alias-brand-primary);cursor:pointer;flex:none}
194
+ .dshmm-check:disabled{cursor:default;opacity:.45}
195
+ .dshmm-checkWrap{display:flex;align-items:center;padding-top:2px;flex:none}
196
+ .dshmm-deletedRow .dshmm-preview{color:var(--dsw-alias-label-secondary);text-decoration:line-through;text-decoration-color:color-mix(in srgb, var(--dsw-alias-label-secondary) 60%, transparent)}
197
+ .dshmm-deletedChip{flex:none;min-width:52px;text-align:center;font-size:11px;line-height:18px;padding:1px 8px;margin-top:1px;border-radius:6px;color:var(--dsw-alias-state-warn-primary);background:color-mix(in srgb, var(--dsw-alias-state-warn-primary) 12%, transparent);white-space:nowrap}
198
+ .dshmm-reason{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);text-align:right;max-width:160px}
199
+ .dshmm-restore{appearance:none;border:0;border-radius:6px;padding:4px 10px;font:inherit;font-size:11px;line-height:16px;cursor:pointer;background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 14%, transparent);color:var(--dsw-alias-state-success-primary);white-space:nowrap}
200
+ .dshmm-restore:hover{background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 22%, transparent)}
201
+ .dshmm-restore:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
202
+ .dshmm-confirmBar{display:flex;align-items:center;gap:10px;margin:10px 20px 0;padding:8px 10px;border-radius:8px;background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 10%, transparent);color:var(--dsw-alias-label-primary);font-size:12px;line-height:18px;flex:none}
203
+ .dshmm-confirmBar .dshmm-confirmActions{margin-left:auto}
204
+ .dshmm-subtle{font-size:11px;color:var(--dsw-alias-label-secondary)}
205
+ @media (max-width:520px){.dshmm-backdrop{padding:10px}.dshmm-panel{max-height:90vh}.dshmm-footHint{display:none}.dshmm-reason{display:none}}
206
+ `
207
+
208
+ function icon(paths, size) {
209
+ return h(
210
+ 'svg',
211
+ {
212
+ viewBox: '0 0 24 24',
213
+ width: size || 16,
214
+ height: size || 16,
215
+ fill: 'none',
216
+ stroke: 'currentColor',
217
+ strokeWidth: 1.7,
218
+ strokeLinecap: 'round',
219
+ strokeLinejoin: 'round',
220
+ 'aria-hidden': true,
221
+ },
222
+ paths.map((path, index) => h('path', { key: index, d: path })),
223
+ )
224
+ }
225
+
226
+ const IconList = () => icon(['M4 6h11', 'M4 12h9', 'M4 18h7', 'M17 15.5l4 4', 'M21 15.5l-4 4'])
227
+ const IconClose = () => icon(['M6 6l12 12', 'M18 6L6 18'])
228
+ const IconTrash = () => icon(['M4 7h16', 'M9 7V5h6v2', 'M6 7l1 13h10l1-13', 'M10 11v5', 'M14 11v5'])
229
+
230
+ function createManager(sessions, remote) {
231
+ let snapshot = { open: false, sessionId: undefined }
232
+ const listeners = new Set()
233
+ const publish = () => {
234
+ for (const listener of [...listeners]) {
235
+ try {
236
+ listener()
237
+ } catch (_error) {
238
+ /* one failing listener must not block the others */
239
+ }
240
+ }
241
+ }
242
+ return {
243
+ sessions,
244
+ subscribe(listener) {
245
+ listeners.add(listener)
246
+ return () => { listeners.delete(listener) }
247
+ },
248
+ getSnapshot() {
249
+ return snapshot
250
+ },
251
+ open(sessionId) {
252
+ snapshot = { open: true, sessionId }
253
+ publish()
254
+ },
255
+ close() {
256
+ if (!snapshot.open) return
257
+ snapshot = { open: false, sessionId: undefined }
258
+ publish()
259
+ },
260
+ async executeCommand(sessionId, line) {
261
+ const commands = remote?.commands
262
+ if (commands === undefined || typeof commands.execute !== 'function') {
263
+ throw new Error('commands Remote is unavailable.')
264
+ }
265
+ const controller = new AbortController()
266
+ const response = await commands.execute(sessionId, line, [], controller.signal)
267
+ if (response !== null && typeof response === 'object' && response.ok === false) {
268
+ const message = response.error !== null && typeof response.error === 'object' && typeof response.error.message === 'string'
269
+ ? response.error.message
270
+ : 'Remote command failed.'
271
+ throw new Error(message)
272
+ }
273
+ const execution = response !== null && typeof response === 'object' && response.ok === true
274
+ ? response.value
275
+ : response
276
+ if (execution === undefined || execution === null) throw new Error('Command was not recognized.')
277
+ return execution
278
+ },
279
+ }
280
+ }
281
+
282
+ function useManagerState(manager) {
283
+ return useSyncExternalStore(manager.subscribe, manager.getSnapshot, manager.getSnapshot)
284
+ }
285
+
286
+ function useSessionWindow(sessions, sessionId) {
287
+ const subscribe = useCallback((notify) => {
288
+ const binding = sessions.binding(sessionId)
289
+ if (binding === undefined) return () => {}
290
+ return binding.eventSource.subscribe(notify)
291
+ }, [sessions, sessionId])
292
+ const read = useCallback(() => {
293
+ const binding = sessions.binding(sessionId)
294
+ return binding === undefined ? EMPTY_WINDOW : binding.eventSource.getSnapshot()
295
+ }, [sessions, sessionId])
296
+ return useSyncExternalStore(subscribe, read, read)
297
+ }
298
+
299
+ function roleOf(event) {
300
+ if (event.type === 'user/message') return event.data?.source?.kind === 'user' ? 'user' : 'context'
301
+ if (event.type === 'assistant/message') return 'assistant'
302
+ if (event.type === 'tool/result') return 'tool'
303
+ if (event.type === 'developer/message') return 'context'
304
+ return 'system'
305
+ }
306
+
307
+ function previewOf(message, limit) {
308
+ const content = Array.isArray(message?.content) ? message.content : []
309
+ const parts = []
310
+ for (const block of content) {
311
+ if (block === null || typeof block !== 'object') continue
312
+ if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
313
+ else if (block.type === 'tool-call') parts.push(`tool:${typeof block.name === 'string' ? block.name : '?'}`)
314
+ else if (block.type === 'image') parts.push('[image]')
315
+ else if (block.type === 'file') parts.push(`[file${block.attachment?.name ? `: ${block.attachment.name}` : ''}]`)
316
+ else if (block.type === 'tool-addition') parts.push(`+${String(block.toolName)}`)
317
+ else if (block.type === 'tool-removal') parts.push(`-${String(block.toolName)}`)
318
+ }
319
+ const text = parts.join(' ').replace(/\s+/g, ' ').trim()
320
+ if (text.length === 0) return ''
321
+ const max = limit === undefined ? 120 : limit
322
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
323
+ }
324
+
325
+ function toolCallIdsOf(event) {
326
+ if (event === undefined || event.type !== 'assistant/message') return []
327
+ const content = Array.isArray(event.data?.message?.content) ? event.data.message.content : []
328
+ return content
329
+ .filter((block) => block !== null && typeof block === 'object' && block.type === 'tool-call' && typeof block.id === 'string')
330
+ .map((block) => block.id)
331
+ }
332
+
333
+ function hasToolChange(event) {
334
+ const content = event?.data?.message?.content
335
+ return Array.isArray(content)
336
+ && content.some((block) => block?.type === 'tool-addition' || block?.type === 'tool-removal')
337
+ }
338
+
339
+ /** Source kinds this plugin writes for tombstones: current, then older releases. */
340
+ const TOMBSTONE_KINDS = ['context-manager', 'message-manager']
341
+
342
+ function isTombstoneKind(kind) {
343
+ return TOMBSTONE_KINDS.includes(kind)
344
+ }
345
+
346
+ function isTombstoneEvent(event) {
347
+ return event !== undefined
348
+ && event !== null
349
+ && event.type === 'developer/message'
350
+ && Array.isArray(event.data?.message?.content)
351
+ && event.data.message.content.length === 0
352
+ && isTombstoneKind(event.data?.message?.source?.kind)
353
+ && event.surfaceOp !== null
354
+ && typeof event.surfaceOp === 'object'
355
+ && event.surfaceOp.op === 'replace'
356
+ }
357
+
358
+ function parseRestoredTombstoneId(id) {
359
+ if (typeof id !== 'string' || !id.startsWith('restored-assistant-')) return undefined
360
+ const rest = id.slice('restored-assistant-'.length)
361
+ const dash = rest.indexOf('-')
362
+ if (dash <= 0) return undefined
363
+ const seq = Number(rest.slice(0, dash))
364
+ return Number.isSafeInteger(seq) ? seq : undefined
365
+ }
366
+
367
+ function foldEntries(entries) {
368
+ const seqs = []
369
+ const bySeq = new Map()
370
+ const groups = []
371
+ for (const entry of entries) {
372
+ if (entry === null || typeof entry !== 'object' || entry.type === 'transient') continue
373
+ const event = entry.event
374
+ if (event === null || typeof event !== 'object' || typeof event.seq !== 'number') continue
375
+ bySeq.set(event.seq, event)
376
+ if (!SURFACE_TYPES.has(event.type)) continue
377
+ const op = event.surfaceOp
378
+ if (op === undefined) continue
379
+ if (op === 'append') {
380
+ seqs.push(event.seq)
381
+ continue
382
+ }
383
+ if (op !== null && typeof op === 'object' && op.op === 'replace') {
384
+ const start = seqs.indexOf(op.startSeq)
385
+ const end = seqs.indexOf(op.endSeq)
386
+ if (start < 0 || end < start) continue
387
+ const removed = seqs.slice(start, end + 1)
388
+ if (isTombstoneEvent(event)) groups.push({ tombstoneSeq: event.seq, targetSeqs: removed })
389
+ seqs.splice(start, end - start + 1, event.seq)
390
+ }
391
+ }
392
+
393
+ const items = []
394
+ let turn = 0
395
+ let step = 0
396
+ for (let index = 0; index < seqs.length; index += 1) {
397
+ const seq = seqs[index]
398
+ const event = bySeq.get(seq)
399
+ if (event === undefined) continue
400
+ if (Number.isSafeInteger(event.data?.turn)) turn = event.data.turn
401
+ if (Number.isSafeInteger(event.data?.step)) step = event.data.step
402
+ if (event.type === 'system/message') continue
403
+ const message = event.type === 'user/message' ? event.data : event.data?.message
404
+ if (message === null || typeof message !== 'object') continue
405
+ const content = Array.isArray(message.content) ? message.content : []
406
+ if ((event.type === 'developer/message' || event.type === 'assistant/message') && content.length === 0) continue
407
+ let itemTurn = Number.isSafeInteger(event.data?.turn) ? event.data.turn : undefined
408
+ let itemStep = Number.isSafeInteger(event.data?.step) ? event.data.step : undefined
409
+ if (itemTurn === undefined || itemStep === undefined) {
410
+ for (let next = index + 1; next < seqs.length; next += 1) {
411
+ const data = bySeq.get(seqs[next])?.data
412
+ if (Number.isSafeInteger(data?.turn) && Number.isSafeInteger(data?.step)) {
413
+ itemTurn = data.turn
414
+ itemStep = data.step
415
+ break
416
+ }
417
+ }
418
+ }
419
+ items.push({
420
+ seq: event.seq,
421
+ time: event.time,
422
+ type: event.type,
423
+ role: roleOf(event),
424
+ turn: itemTurn ?? turn,
425
+ step: itemStep ?? step,
426
+ messageId: typeof message.id === 'string' ? message.id : undefined,
427
+ preview: previewOf(message),
428
+ blocks: content.length,
429
+ callIds: toolCallIdsOf(event),
430
+ toolCallId: event.type === 'tool/result' && typeof message.toolCallId === 'string' ? message.toolCallId : undefined,
431
+ })
432
+ }
433
+
434
+ const restored = new Set()
435
+ for (const item of items) {
436
+ const tombstoneSeq = parseRestoredTombstoneId(item.messageId)
437
+ if (tombstoneSeq !== undefined) restored.add(tombstoneSeq)
438
+ }
439
+
440
+ const deleted = []
441
+ for (const group of groups) {
442
+ if (restored.has(group.tombstoneSeq)) continue
443
+ const originalEvents = group.targetSeqs.map((seq) => bySeq.get(seq))
444
+ const known = originalEvents.filter((event) => event !== undefined)
445
+ const missing = group.targetSeqs.length - known.length
446
+ const assistant = known.find((event) => event.type === 'assistant/message')
447
+ const calls = assistant === undefined ? [] : toolCallIdsOf(assistant)
448
+ const results = known.filter((event) => event.type === 'tool/result')
449
+ let restorable = false
450
+ let reason = ''
451
+ if (group.targetSeqs.length === 1) {
452
+ const event = known[0]
453
+ if (event === undefined) restorable = true
454
+ else if (event.type === 'user/message') restorable = true
455
+ else if (event.type === 'developer/message' && !hasToolChange(event)) restorable = true
456
+ else if (event.type === 'assistant/message' && calls.length === 0) {
457
+ restorable = true
458
+ reason = 'appended'
459
+ } else if (event.type === 'tool/result') reason = 'tool'
460
+ else reason = 'group'
461
+ } else if (assistant !== undefined && calls.length > 0 && missing === 0 && results.length === group.targetSeqs.length - 1) {
462
+ const ids = new Set(calls.map((block) => block.id))
463
+ const resultIds = new Set(results.map((event) => event.data?.message?.toolCallId))
464
+ restorable = ids.size === resultIds.size && [...ids].every((id) => resultIds.has(id))
465
+ reason = restorable ? 'appended' : 'group'
466
+ } else {
467
+ reason = missing > 0 ? 'missing' : 'group'
468
+ }
469
+ deleted.push({
470
+ tombstoneSeq: group.tombstoneSeq,
471
+ targetSeqs: [...group.targetSeqs],
472
+ count: group.targetSeqs.length,
473
+ items: known.map((event) => {
474
+ const message = event.type === 'user/message' ? event.data : event.data?.message
475
+ return {
476
+ seq: event.seq,
477
+ role: roleOf(event),
478
+ preview: previewOf(message),
479
+ time: event.time,
480
+ }
481
+ }),
482
+ missing,
483
+ restorable,
484
+ reason,
485
+ })
486
+ }
487
+ return { items, deleted }
488
+ }
489
+
490
+ function formatTime(time, locale) {
491
+ if (!Number.isFinite(time)) return ''
492
+ try {
493
+ return new Date(time).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
494
+ } catch (_error) {
495
+ return ''
496
+ }
497
+ }
498
+
499
+ /**
500
+ * Expand one selection the way the Host deletion planner will: deleting an
501
+ * assistant message takes its tool results along, and deleting a tool result
502
+ * takes the owning assistant message and its sibling results along.
503
+ * @returns the full set of seqs the Host would remove.
504
+ */
505
+ function expansionFor(items, selectedSeqs) {
506
+ const bySeq = new Map(items.map((item) => [item.seq, item]))
507
+ const chosen = new Set(selectedSeqs)
508
+ const takeGroup = (assistant) => {
509
+ chosen.add(assistant.seq)
510
+ for (const sibling of items) {
511
+ if (sibling.role === 'tool' && sibling.toolCallId !== undefined
512
+ && assistant.callIds !== undefined && assistant.callIds.includes(sibling.toolCallId)) {
513
+ chosen.add(sibling.seq)
514
+ }
515
+ }
516
+ }
517
+ for (const seq of selectedSeqs) {
518
+ const item = bySeq.get(seq)
519
+ if (item === undefined) continue
520
+ if (item.role === 'tool' && item.toolCallId !== undefined) {
521
+ for (const candidate of items) {
522
+ if (candidate.role === 'assistant' && candidate.callIds !== undefined
523
+ && candidate.callIds.includes(item.toolCallId)) {
524
+ takeGroup(candidate)
525
+ }
526
+ }
527
+ } else if (item.role === 'assistant' && item.callIds !== undefined && item.callIds.length > 0) {
528
+ takeGroup(item)
529
+ }
530
+ }
531
+ return chosen
532
+ }
533
+
534
+ function ContextManagerButton({ sessionId, manager, t }) {
535
+ const state = useManagerState(manager)
536
+ const translate = typeof t === 'function' ? t : manager.translate
537
+ return h(
538
+ React.Fragment,
539
+ null,
540
+ h('style', null, CSS),
541
+ h(
542
+ 'button',
543
+ {
544
+ type: 'button',
545
+ className: 'dshmm-btn',
546
+ title: translate('open'),
547
+ 'aria-label': translate('open'),
548
+ 'data-open': state.open ? 'true' : 'false',
549
+ onClick: () => {
550
+ if (sessionId === undefined) return
551
+ manager.open(sessionId)
552
+ },
553
+ },
554
+ h(IconList),
555
+ ),
556
+ )
557
+ }
558
+
559
+ function ManagerDialog({ manager, sessionId, locale, t, onBackdrop }) {
560
+ const window = useSessionWindow(manager.sessions, sessionId)
561
+ const folded = useMemo(() => foldEntries(window.entries), [window])
562
+ const items = folded.items
563
+ const deleted = folded.deleted
564
+ const [selectedItems, setSelectedItems] = useState(() => new Set())
565
+ const [selectedDeleted, setSelectedDeleted] = useState(() => new Set())
566
+ const [selectedTurnSet, setSelectedTurnSet] = useState(() => new Set())
567
+ const [pending, setPending] = useState(undefined)
568
+ const [status, setStatus] = useState(undefined)
569
+ const [busy, setBusy] = useState(false)
570
+ const listRef = useRef(null)
571
+ const panelRef = useRef(null)
572
+ // The per-message list is secondary to the turns view; start collapsed.
573
+ const [currentCollapsed, setCurrentCollapsed] = useState(true)
574
+
575
+ useEffect(() => {
576
+ const panel = panelRef.current
577
+ if (panel !== null && typeof panel.focus === 'function') panel.focus()
578
+ const list = listRef.current
579
+ if (list !== null) list.scrollTop = list.scrollHeight
580
+ }, [])
581
+
582
+ useEffect(() => {
583
+ const onKeyDown = (event) => {
584
+ if (event.key !== 'Escape') return
585
+ if (busy) return
586
+ event.stopPropagation()
587
+ manager.close()
588
+ }
589
+ document.addEventListener('keydown', onKeyDown, true)
590
+ return () => { document.removeEventListener('keydown', onKeyDown, true) }
591
+ }, [manager, busy])
592
+
593
+ const currentSelectedSeqs = items.filter((item) => selectedItems.has(item.seq)).map((item) => item.seq)
594
+ const restorableDeleted = deleted.filter((group) => group.restorable)
595
+ const deletedSelectedSeqs = restorableDeleted
596
+ .filter((group) => selectedDeleted.has(group.tombstoneSeq))
597
+ .map((group) => group.tombstoneSeq)
598
+ const allCurrentSelected = items.length > 0 && currentSelectedSeqs.length === items.length
599
+ const allDeletedSelected = restorableDeleted.length > 0 && deletedSelectedSeqs.length === restorableDeleted.length
600
+
601
+ // Conversation turns, oldest first; the newest turn with content is the
602
+ // one still in progress, so deleting it is applied on the next turn.
603
+ const turnGroups = useMemo(() => {
604
+ const byTurn = new Map()
605
+ for (const item of items) {
606
+ const group = byTurn.get(item.turn) ?? { turn: item.turn, items: [] }
607
+ group.items.push(item)
608
+ byTurn.set(item.turn, group)
609
+ }
610
+ return [...byTurn.values()].sort((a, b) => a.turn - b.turn)
611
+ }, [items])
612
+ const lastTurn = turnGroups.length > 0 ? turnGroups[turnGroups.length - 1].turn : undefined
613
+ const selectedTurns = turnGroups
614
+ .filter((group) => selectedTurnSet.has(group.turn))
615
+ .map((group) => group.turn)
616
+ const allTurnsSelected = turnGroups.length > 0 && selectedTurns.length === turnGroups.length
617
+
618
+ const toggleCurrent = (seq, checked) => {
619
+ setSelectedItems((current) => {
620
+ const next = new Set(current)
621
+ if (checked) next.add(seq)
622
+ else next.delete(seq)
623
+ return next
624
+ })
625
+ }
626
+ const toggleTurn = (turn, checked) => {
627
+ setSelectedTurnSet((current) => {
628
+ const next = new Set(current)
629
+ if (checked) next.add(turn)
630
+ else next.delete(turn)
631
+ return next
632
+ })
633
+ }
634
+ const toggleAllTurns = () => {
635
+ setSelectedTurnSet(allTurnsSelected ? new Set() : new Set(turnGroups.map((group) => group.turn)))
636
+ }
637
+ const toggleDeleted = (tombstoneSeq, checked) => {
638
+ setSelectedDeleted((current) => {
639
+ const next = new Set(current)
640
+ if (checked) next.add(tombstoneSeq)
641
+ else next.delete(tombstoneSeq)
642
+ return next
643
+ })
644
+ }
645
+ const toggleAllCurrent = () => {
646
+ setSelectedItems(allCurrentSelected ? new Set() : new Set(items.map((item) => item.seq)))
647
+ }
648
+ const toggleAllDeleted = () => {
649
+ setSelectedDeleted(allDeletedSelected ? new Set() : new Set(restorableDeleted.map((group) => group.tombstoneSeq)))
650
+ }
651
+
652
+ const run = async (kind, seqs) => {
653
+ if (busy || seqs.length === 0) return
654
+ setBusy(true)
655
+ setStatus(undefined)
656
+ setPending(undefined)
657
+ try {
658
+ const execution = await manager.executeCommand(sessionId, `/ctxmgr ${kind} ${seqs.join(',')}`)
659
+ const result = execution?.result !== undefined ? execution.result : execution
660
+ if (result !== undefined && result !== null && result.kind === 'error') {
661
+ setStatus({ kind: 'error', text: result.text || t('failed') })
662
+ return
663
+ }
664
+ const fallback = kind === 'restore'
665
+ ? t('restoreQueued', { count: seqs.length })
666
+ : kind === 'deleteturn'
667
+ ? t('turnsDeleted', { count: seqs.length })
668
+ : t('deleted', { count: seqs.length })
669
+ const text = result !== undefined && result !== null && result.kind === 'success' ? result.text : undefined
670
+ setStatus({ kind: 'success', text: text || fallback })
671
+ if (kind === 'delete') setSelectedItems(new Set())
672
+ else if (kind === 'deleteturn') setSelectedTurnSet(new Set())
673
+ else setSelectedDeleted(new Set())
674
+ } catch (error) {
675
+ setStatus({ kind: 'error', text: error instanceof Error ? error.message : String(error) })
676
+ } finally {
677
+ setBusy(false)
678
+ }
679
+ }
680
+
681
+ const confirmPending = () => {
682
+ if (pending === undefined) return
683
+ run(pending.kind === 'turns' ? 'deleteturn' : 'delete', pending.seqs)
684
+ }
685
+
686
+ const renderCurrent = (item) => h(
687
+ 'div',
688
+ { className: 'dshmm-row', key: item.seq, 'data-role': item.role },
689
+ h(
690
+ 'label',
691
+ { className: 'dshmm-checkWrap' },
692
+ h('input', {
693
+ type: 'checkbox',
694
+ className: 'dshmm-check',
695
+ checked: selectedItems.has(item.seq),
696
+ disabled: busy,
697
+ 'aria-label': `Select #${item.seq}`,
698
+ onChange: (event) => toggleCurrent(item.seq, event.target.checked),
699
+ }),
700
+ ),
701
+ h('span', { className: 'dshmm-role' }, t(item.role)),
702
+ h(
703
+ 'div',
704
+ { className: 'dshmm-main' },
705
+ h(
706
+ 'div',
707
+ { className: 'dshmm-preview', title: item.preview || undefined },
708
+ item.preview || t('emptyMessage'),
709
+ ),
710
+ h(
711
+ 'div',
712
+ { className: 'dshmm-meta' },
713
+ `#${item.seq}`,
714
+ ' · ',
715
+ formatTime(item.time, locale),
716
+ item.turn > 0 ? ` · T${item.turn}S${item.step}` : '',
717
+ ),
718
+ ),
719
+ h(
720
+ 'div',
721
+ { className: 'dshmm-actions' },
722
+ h(
723
+ 'button',
724
+ {
725
+ type: 'button',
726
+ className: 'dshmm-iconbtn',
727
+ title: t('delete'),
728
+ 'aria-label': t('delete'),
729
+ disabled: busy,
730
+ onClick: () => {
731
+ setPending({ kind: 'msgs', seqs: [item.seq], total: expansionFor(items, [item.seq]).size })
732
+ setStatus(undefined)
733
+ },
734
+ },
735
+ h(IconTrash),
736
+ ),
737
+ ),
738
+ )
739
+
740
+ const renderTurn = (group) => {
741
+ const own = group.items.find((item) => item.role === 'user')
742
+ const preview = (own ?? group.items[0])?.preview ?? ''
743
+ const inProgress = group.turn === lastTurn
744
+ return h(
745
+ 'div',
746
+ { className: 'dshmm-row', key: `turn-${group.turn}`, 'data-role': 'user' },
747
+ h(
748
+ 'label',
749
+ { className: 'dshmm-checkWrap' },
750
+ h('input', {
751
+ type: 'checkbox',
752
+ className: 'dshmm-check',
753
+ checked: selectedTurnSet.has(group.turn),
754
+ disabled: busy,
755
+ 'aria-label': `Select turn ${group.turn}`,
756
+ onChange: (event) => toggleTurn(group.turn, event.target.checked),
757
+ }),
758
+ ),
759
+ h('span', { className: 'dshmm-role' }, t('turnBadge', { turn: group.turn })),
760
+ h(
761
+ 'div',
762
+ { className: 'dshmm-main' },
763
+ h(
764
+ 'div',
765
+ { className: 'dshmm-preview', title: preview || undefined },
766
+ preview || t('noUserMessage'),
767
+ ),
768
+ h(
769
+ 'div',
770
+ { className: 'dshmm-meta' },
771
+ t('turnMeta', { count: group.items.length }),
772
+ inProgress ? ` · ${t('inProgressNote')}` : '',
773
+ ),
774
+ ),
775
+ h(
776
+ 'div',
777
+ { className: 'dshmm-actions' },
778
+ h(
779
+ 'button',
780
+ {
781
+ type: 'button',
782
+ className: 'dshmm-iconbtn',
783
+ title: t('deleteTurn'),
784
+ 'aria-label': t('deleteTurn'),
785
+ disabled: busy,
786
+ onClick: () => {
787
+ setPending({ kind: 'turns', seqs: [group.turn] })
788
+ setStatus(undefined)
789
+ },
790
+ },
791
+ h(IconTrash),
792
+ ),
793
+ ),
794
+ )
795
+ }
796
+
797
+ const renderDeleted = (group) => {
798
+ const first = group.items[0]
799
+ const summary = group.count === 1
800
+ ? first === undefined
801
+ ? `#${group.targetSeqs[0]} · ${t('contentNotLoaded')}`
802
+ : `${t(first.role)} · ${first.preview || t('emptyMessage')}`
803
+ : `${t('deletedGroup')} · ${group.count}${first !== undefined && first.preview ? ` · ${first.preview}` : ''}`
804
+ const reasonKey = group.reason === 'appended'
805
+ ? 'restoreAppended'
806
+ : group.reason === 'tool'
807
+ ? 'unrestorableTool'
808
+ : group.reason === 'missing'
809
+ ? 'contentNotLoaded'
810
+ : group.reason === 'group'
811
+ ? 'unrestorableGroup'
812
+ : undefined
813
+ return h(
814
+ 'div',
815
+ { className: 'dshmm-row dshmm-deletedRow', key: group.tombstoneSeq, 'data-role': first?.role },
816
+ h(
817
+ 'label',
818
+ { className: 'dshmm-checkWrap' },
819
+ h('input', {
820
+ type: 'checkbox',
821
+ className: 'dshmm-check',
822
+ checked: selectedDeleted.has(group.tombstoneSeq),
823
+ disabled: busy || !group.restorable,
824
+ 'aria-label': `Select deleted #${group.tombstoneSeq}`,
825
+ onChange: (event) => toggleDeleted(group.tombstoneSeq, event.target.checked),
826
+ }),
827
+ ),
828
+ h('span', { className: 'dshmm-role' }, first === undefined ? '—' : t(first.role)),
829
+ h(
830
+ 'div',
831
+ { className: 'dshmm-main' },
832
+ h(
833
+ 'div',
834
+ { className: 'dshmm-preview', title: first?.preview || undefined },
835
+ summary,
836
+ ),
837
+ h(
838
+ 'div',
839
+ { className: 'dshmm-meta' },
840
+ t('deletedRecord', { seq: group.tombstoneSeq }),
841
+ reasonKey === undefined ? '' : ` · ${t(reasonKey)}`,
842
+ ),
843
+ ),
844
+ h(
845
+ 'div',
846
+ { className: 'dshmm-actions' },
847
+ group.restorable
848
+ ? h(
849
+ 'button',
850
+ {
851
+ type: 'button',
852
+ className: 'dshmm-restore',
853
+ disabled: busy,
854
+ onClick: () => run('restore', [group.tombstoneSeq]),
855
+ },
856
+ t('restore'),
857
+ )
858
+ : h('span', { className: 'dshmm-reason' }, t(reasonKey || 'unavailable')),
859
+ ),
860
+ )
861
+ }
862
+
863
+ const sectionHeader = (title, count, allSelected, onToggleAll, actions, selectable, collapse) => h(
864
+ 'div',
865
+ { className: 'dshmm-section' },
866
+ selectable
867
+ ? h(
868
+ 'label',
869
+ { className: 'dshmm-selectAll' },
870
+ h('input', {
871
+ type: 'checkbox',
872
+ className: 'dshmm-check',
873
+ checked: allSelected,
874
+ disabled: busy || count === 0,
875
+ onChange: onToggleAll,
876
+ }),
877
+ allSelected ? t('clearSelection') : t('selectAll'),
878
+ )
879
+ : null,
880
+ collapse === undefined
881
+ ? h('span', { className: 'dshmm-sectionTitle' }, title)
882
+ : h(
883
+ 'button',
884
+ {
885
+ type: 'button',
886
+ className: 'dshmm-sectionToggle',
887
+ title: collapse.collapsed ? t('expandSection') : t('collapseSection'),
888
+ 'aria-label': collapse.collapsed ? t('expandSection') : t('collapseSection'),
889
+ 'aria-expanded': collapse.collapsed ? 'false' : 'true',
890
+ onClick: collapse.onToggle,
891
+ },
892
+ h('span', { className: 'dshmm-chevron' }, collapse.collapsed ? '▸' : '▾'),
893
+ h('span', { className: 'dshmm-sectionTitle' }, title),
894
+ ),
895
+ h('span', { className: 'dshmm-sectionCount' }, String(count)),
896
+ h('div', { className: 'dshmm-sectionActions' }, actions),
897
+ )
898
+
899
+ return h(
900
+ 'div',
901
+ {
902
+ className: 'dshmm-backdrop',
903
+ onMouseDown: (event) => {
904
+ if (event.target === event.currentTarget && !busy) onBackdrop()
905
+ },
906
+ },
907
+ h(
908
+ 'div',
909
+ {
910
+ className: 'dshmm-panel',
911
+ ref: panelRef,
912
+ tabIndex: -1,
913
+ role: 'dialog',
914
+ 'aria-modal': 'true',
915
+ 'aria-label': t('title'),
916
+ },
917
+ h(
918
+ 'div',
919
+ { className: 'dshmm-head' },
920
+ h(
921
+ 'div',
922
+ { className: 'dshmm-titleRow' },
923
+ h('h2', { className: 'dshmm-title' }, t('title')),
924
+ h(
925
+ 'button',
926
+ {
927
+ type: 'button',
928
+ className: 'dshmm-close',
929
+ title: t('close'),
930
+ 'aria-label': t('close'),
931
+ disabled: busy,
932
+ onClick: () => manager.close(),
933
+ },
934
+ h(IconClose),
935
+ ),
936
+ ),
937
+ h('p', { className: 'dshmm-subtitle' }, t('subtitle')),
938
+ ),
939
+ status === undefined
940
+ ? null
941
+ : h(
942
+ 'div',
943
+ { className: 'dshmm-banner', 'data-kind': status.kind, role: 'status' },
944
+ status.text,
945
+ ),
946
+ pending === undefined
947
+ ? null
948
+ : h(
949
+ 'div',
950
+ { className: 'dshmm-confirmBar' },
951
+ h('span', null,
952
+ pending.kind === 'turns'
953
+ ? t('confirmBatchTurns', { count: pending.seqs.length })
954
+ : t('confirmBatch', { count: pending.seqs.length }),
955
+ pending.kind !== 'turns' && pending.total > pending.seqs.length
956
+ ? h('span', { className: 'dshmm-subtle' },
957
+ ` · ${t('confirmTotal', { count: pending.total })} · ${t('groupHint')}`)
958
+ : null,
959
+ ),
960
+ h(
961
+ 'div',
962
+ { className: 'dshmm-confirmActions' },
963
+ h(
964
+ 'button',
965
+ {
966
+ type: 'button',
967
+ className: 'dshmm-small',
968
+ disabled: busy,
969
+ onClick: () => setPending(undefined),
970
+ },
971
+ t('cancel'),
972
+ ),
973
+ h(
974
+ 'button',
975
+ {
976
+ type: 'button',
977
+ className: 'dshmm-small',
978
+ 'data-danger': 'true',
979
+ disabled: busy,
980
+ onClick: confirmPending,
981
+ },
982
+ t('confirmDelete'),
983
+ ),
984
+ ),
985
+ ),
986
+ h(
987
+ 'div',
988
+ { className: 'dshmm-list', ref: listRef },
989
+ window.entries.length === 0
990
+ ? h('div', { className: 'dshmm-empty' }, t('notReady'))
991
+ : items.length === 0 && deleted.length === 0
992
+ ? h('div', { className: 'dshmm-empty' }, t('empty'))
993
+ : h(
994
+ React.Fragment,
995
+ null,
996
+ turnGroups.length === 0
997
+ ? null
998
+ : h(
999
+ React.Fragment,
1000
+ null,
1001
+ sectionHeader(
1002
+ t('turnsSection'),
1003
+ turnGroups.length,
1004
+ allTurnsSelected,
1005
+ toggleAllTurns,
1006
+ h(
1007
+ 'button',
1008
+ {
1009
+ type: 'button',
1010
+ className: 'dshmm-small',
1011
+ 'data-danger': 'true',
1012
+ disabled: busy || selectedTurns.length === 0,
1013
+ onClick: () => setPending({ kind: 'turns', seqs: selectedTurns }),
1014
+ },
1015
+ t('deleteSelected', { count: selectedTurns.length }),
1016
+ ),
1017
+ true,
1018
+ ),
1019
+ turnGroups.map(renderTurn),
1020
+ ),
1021
+ sectionHeader(
1022
+ t('currentSection'),
1023
+ items.length,
1024
+ allCurrentSelected,
1025
+ toggleAllCurrent,
1026
+ h(
1027
+ 'button',
1028
+ {
1029
+ type: 'button',
1030
+ className: 'dshmm-small',
1031
+ 'data-danger': 'true',
1032
+ disabled: busy || currentSelectedSeqs.length === 0,
1033
+ onClick: () => setPending({
1034
+ kind: 'msgs',
1035
+ seqs: currentSelectedSeqs,
1036
+ total: expansionFor(items, currentSelectedSeqs).size,
1037
+ }),
1038
+ },
1039
+ t('deleteSelected', { count: currentSelectedSeqs.length }),
1040
+ ),
1041
+ true,
1042
+ { collapsed: currentCollapsed, onToggle: () => setCurrentCollapsed((value) => !value) },
1043
+ ),
1044
+ items.length === 0
1045
+ ? h('div', { className: 'dshmm-empty' }, t('empty'))
1046
+ : currentCollapsed
1047
+ ? null
1048
+ : items.map(renderCurrent),
1049
+ deleted.length === 0
1050
+ ? null
1051
+ : h(
1052
+ React.Fragment,
1053
+ null,
1054
+ sectionHeader(
1055
+ t('deletedSection'),
1056
+ deleted.length,
1057
+ allDeletedSelected,
1058
+ toggleAllDeleted,
1059
+ h(
1060
+ 'button',
1061
+ {
1062
+ type: 'button',
1063
+ className: 'dshmm-small',
1064
+ disabled: busy || deletedSelectedSeqs.length === 0,
1065
+ onClick: () => run('restore', deletedSelectedSeqs),
1066
+ },
1067
+ t('restoreSelected', { count: deletedSelectedSeqs.length }),
1068
+ ),
1069
+ restorableDeleted.length > 0,
1070
+ ),
1071
+ deleted.map(renderDeleted),
1072
+ ),
1073
+ ),
1074
+ ),
1075
+ h(
1076
+ 'div',
1077
+ { className: 'dshmm-foot' },
1078
+ h(
1079
+ 'span',
1080
+ { className: 'dshmm-footCount' },
1081
+ busy
1082
+ ? t('busy')
1083
+ : `${t('count', { count: items.length })}${deleted.length > 0 ? ` · ${t('deletedSection')} ${deleted.length}` : ''}`,
1084
+ ),
1085
+ h(
1086
+ 'span',
1087
+ { className: 'dshmm-footHint' },
1088
+ t('hint'),
1089
+ ' ',
1090
+ h('span', { className: 'dshmm-code' }, t('usage')),
1091
+ ),
1092
+ ),
1093
+ ),
1094
+ )
1095
+ }
1096
+
1097
+ function ManagerOverlay({ manager, t }) {
1098
+ const state = useManagerState(manager)
1099
+ const translate = typeof t === 'function' ? t : manager.translate
1100
+ const locale = manager.locale
1101
+ if (!state.open || state.sessionId === undefined) return null
1102
+ return h(
1103
+ React.Fragment,
1104
+ null,
1105
+ h('style', null, CSS),
1106
+ h(ManagerDialog, {
1107
+ key: state.sessionId,
1108
+ manager,
1109
+ sessionId: state.sessionId,
1110
+ locale,
1111
+ t: translate,
1112
+ onBackdrop: () => manager.close(),
1113
+ }),
1114
+ )
1115
+ }
1116
+
1117
+ return {
1118
+ inject: ['slots', 'sessions', 'locale', 'remote', 'remote.commands'],
1119
+ apply(ctx) {
1120
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'context-manager: locale dictionaries')
1121
+ const t = ctx.locale.bind(NS)
1122
+ const manager = createManager(ctx.sessions, ctx.remote)
1123
+ manager.translate = t
1124
+ manager.locale = ctx.locale.getLocale()?.active
1125
+
1126
+ ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register(
1127
+ {
1128
+ name: 'conversation.session.header.utilities',
1129
+ id: 'context-manager',
1130
+ order: 20,
1131
+ locale: NS,
1132
+ inject: () => ({ manager }),
1133
+ },
1134
+ ContextManagerButton,
1135
+ ))
1136
+
1137
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register(
1138
+ {
1139
+ name: 'shell.overlay',
1140
+ id: 'context-manager',
1141
+ order: 100,
1142
+ locale: NS,
1143
+ inject: () => ({ manager }),
1144
+ },
1145
+ ManagerOverlay,
1146
+ ))
1147
+ },
1148
+ }
1149
+ },
1150
+ })