dsh-context-manager 0.0.0-stage → 1.7.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,1371 @@
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
+ cleanSelected: '按 token 优化 ({count})',
84
+ tokens: 'tokens(估算)',
85
+ estimated: '估算值:4 字符 ≈ 1 token,中文与 JSON 会明显低估',
86
+ totalTokens: '当前总占用 ≈{tokens} tokens(估算)',
87
+ cleanHint: '清理仅选取大体积工具/助手消息,按估算 token 降序,用户消息与最近 3 条受保护',
88
+ protectedUser: '用户消息受保护',
89
+ filterLabel: '过滤',
90
+ filterAll: '全部',
91
+ filterRole: '只看 {role}',
92
+ filterEmpty: '没有符合过滤条件的消息。',
93
+ filterCount: '显示 {shown}/{total}',
94
+ protectedChip: '受保护',
95
+ recallChip: '可召回 #{seq}',
96
+ userTokens: '用户 tokens(保护):{tokens}',
97
+ tokenSuffix: '≈{tokens} tok',
98
+ cleanNote: '清理使用启发式估算,实际释放可能略有偏差',
99
+ cleaned: '已按预算清理,目标释放 {tokens} tokens(估算)',
100
+ undoLast: '撤销上次操作',
101
+ undoDone: '已提交撤销,下一回合恢复。',
102
+ batchLabel: '批次 {id}',
103
+ cleanBudget: '预算',
104
+ cleanInvalid: '请输入正整数 token 预算。',
105
+ }
106
+
107
+ const en = {
108
+ open: 'Context manager',
109
+ title: 'Context manager',
110
+ subtitle: 'Manage the model context of this session: delete messages or whole turns, and restore them later.',
111
+ close: 'Close',
112
+ empty: 'There are no manageable messages in the current context.',
113
+ notReady: 'The session is not ready yet.',
114
+ count: '{count} messages',
115
+ hint: 'Deletion only affects later model requests; the raw log and chat transcript are retained.',
116
+ delete: 'Delete this message',
117
+ cancel: 'Cancel',
118
+ confirmDelete: 'Delete',
119
+ confirmQuestion: 'Remove from the model context?',
120
+ groupHint: 'Related tool results are removed together.',
121
+ user: 'User',
122
+ assistant: 'Assistant',
123
+ tool: 'Tool',
124
+ context: 'Context',
125
+ system: 'System',
126
+ emptyMessage: '(empty)',
127
+ failed: 'Operation failed',
128
+ deleted: 'Deleted {count} messages.',
129
+ restoreQueued: 'Queued {count} message(s) for restore on the next turn.',
130
+ busy: 'Working…',
131
+ usage: 'Delete: /ctxmgr delete <seq,...> · turns: /ctxmgr deleteturn <turn,...>',
132
+ currentSection: 'Current messages',
133
+ deletedSection: 'Deleted',
134
+ selectAll: 'Select all',
135
+ clearSelection: 'Clear',
136
+ deleteSelected: 'Delete selected ({count})',
137
+ restoreSelected: 'Restore selected ({count})',
138
+ restore: 'Restore',
139
+ confirmBatch: 'Delete the {count} selected messages?',
140
+ deletedGroup: 'Deleted group',
141
+ contentNotLoaded: 'content not loaded',
142
+ restoreAppended: 'restored at the tail',
143
+ unrestorableTool: 'A tool result cannot be restored alone',
144
+ unrestorableGroup: 'This deleted group cannot be restored',
145
+ deletedRecord: 'Deleted record #{seq}',
146
+ selected: '{count} selected',
147
+ unavailable: 'Not restorable',
148
+ confirmTotal: '{count} messages will be removed in total',
149
+ turnsSection: 'Turns (delete whole turn)',
150
+ turnBadge: 'Turn {turn}',
151
+ deleteTurn: 'Delete turn',
152
+ confirmBatchTurns: 'Delete the {count} selected turns?',
153
+ turnsDeleted: 'Queued {count} turn(s) for deletion.',
154
+ inProgressNote: 'in progress, applies next turn',
155
+ noUserMessage: '(no user prompt)',
156
+ turnMeta: '{count} messages',
157
+ expandSection: 'Expand',
158
+ collapseSection: 'Collapse',
159
+ cleanSelected: 'Optimize by tokens ({count})',
160
+ tokens: 'tokens (estimated)',
161
+ estimated: 'Estimate: 4 characters ≈ 1 token; CJK text and JSON are notably underpriced',
162
+ totalTokens: 'Current usage ≈{tokens} tokens (estimated)',
163
+ cleanHint: 'Cleaning picks only large tool/assistant messages ranked by estimated tokens; user messages and the most recent 3 messages are protected',
164
+ protectedUser: 'User messages protected',
165
+ filterLabel: 'Filter',
166
+ filterAll: 'All',
167
+ filterRole: '{role} only',
168
+ filterEmpty: 'No messages match the filter.',
169
+ filterCount: 'showing {shown}/{total}',
170
+ protectedChip: 'protected',
171
+ recallChip: 'recall #{seq}',
172
+ userTokens: 'User tokens (protected): {tokens}',
173
+ tokenSuffix: '≈{tokens} tok',
174
+ cleanNote: 'Cleaning uses heuristic estimates; actual relief may differ',
175
+ cleaned: 'Cleaned toward {tokens} tokens (estimated)',
176
+ undoLast: 'Undo last batch',
177
+ undoDone: 'Undo queued; restores on the next turn.',
178
+ batchLabel: 'batch {id}',
179
+ cleanBudget: 'Budget',
180
+ cleanInvalid: 'Enter a positive integer token budget.',
181
+ }
182
+
183
+ const CSS = `
184
+ .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}
185
+ .dshmm-btn:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 8%, transparent);color:var(--dsw-alias-label-primary)}
186
+ .dshmm-btn[data-open="true"]{background:color-mix(in srgb, var(--dsw-alias-brand-primary) 14%, transparent);color:var(--dsw-alias-brand-primary)}
187
+ .dshmm-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
188
+ .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}
189
+ .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}
190
+ .dshmm-head{padding:16px 20px 12px;border-bottom:1px solid var(--dsw-alias-border-l1);flex:none}
191
+ .dshmm-titleRow{display:flex;align-items:center;justify-content:space-between;gap:12px}
192
+ .dshmm-title{margin:0;font-size:15px;line-height:22px;font-weight:600;color:var(--dsw-alias-label-primary)}
193
+ .dshmm-subtitle{margin:4px 0 0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
194
+ .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}
195
+ .dshmm-close:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 8%, transparent);color:var(--dsw-alias-label-primary)}
196
+ .dshmm-close:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
197
+ .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}
198
+ .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)}
199
+ .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)}
200
+ .dshmm-list{flex:auto;min-height:120px;overflow-y:auto;padding:4px 0;background:var(--dsw-alias-bg-overlay)}
201
+ .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}
202
+ .dshmm-row:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent)}
203
+ .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}
204
+ .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)}
205
+ .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)}
206
+ .dshmm-main{flex:auto;min-width:0}
207
+ .dshmm-preview{font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
208
+ .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}
209
+ .dshmm-actions{flex:none;display:flex;align-items:center;justify-content:flex-end;min-width:28px}
210
+ .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}
211
+ .dshmm-iconbtn:hover{background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent);color:var(--dsw-alias-state-error-primary)}
212
+ .dshmm-iconbtn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
213
+ .dshmm-confirm{display:flex;flex-direction:column;align-items:flex-end;gap:6px;max-width:260px}
214
+ .dshmm-confirmText{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);text-align:right}
215
+ .dshmm-confirmActions{display:flex;align-items:center;gap:6px}
216
+ .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)}
217
+ .dshmm-small:hover{background:color-mix(in srgb, var(--dsw-alias-label-primary) 13%, transparent)}
218
+ .dshmm-small:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
219
+ .dshmm-small[data-danger="true"]{background:var(--dsw-alias-state-error-primary);color:var(--dsw-alias-bg-base)}
220
+ .dshmm-small[data-danger="true"]:hover{background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 84%, var(--dsw-alias-label-primary))}
221
+ .dshmm-small:disabled{opacity:.55;cursor:default}
222
+ .dshmm-empty{padding:40px 20px;text-align:center;font-size:13px;line-height:20px;color:var(--dsw-alias-label-secondary)}
223
+ .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}
224
+ .dshmm-footCount{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
225
+ .dshmm-footHint{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);text-align:right;flex:auto;min-width:0}
226
+ .dshmm-code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px}
227
+ .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)}
228
+ .dshmm-sectionTitle{font-size:12px;line-height:18px;font-weight:600;color:var(--dsw-alias-label-primary);white-space:nowrap}
229
+ .dshmm-sectionCount{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
230
+ .dshmm-sectionActions{display:flex;align-items:center;gap:6px;margin-left:auto;min-width:0}
231
+ .dshmm-sectionToggle{display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;padding:0;margin:0;font:inherit;color:inherit;cursor:pointer}
232
+ .dshmm-sectionToggle:hover{color:var(--dsw-alias-label-primary)}
233
+ .dshmm-sectionToggle:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
234
+ .dshmm-chevron{font-size:10px;line-height:16px;color:var(--dsw-alias-label-secondary);width:10px;text-align:center}
235
+ .dshmm-sectionToggle:hover .dshmm-chevron{color:var(--dsw-alias-label-primary)}
236
+ .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}
237
+ .dshmm-check{width:14px;height:14px;margin:0;accent-color:var(--dsw-alias-brand-primary);cursor:pointer;flex:none}
238
+ .dshmm-check:disabled{cursor:default;opacity:.45}
239
+ .dshmm-checkWrap{display:flex;align-items:center;padding-top:2px;flex:none}
240
+ .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)}
241
+ .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}
242
+ .dshmm-reason{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);text-align:right;max-width:160px}
243
+ .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}
244
+ .dshmm-restore:hover{background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 22%, transparent)}
245
+ .dshmm-restore:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
246
+ .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}
247
+ .dshmm-confirmBar .dshmm-confirmActions{margin-left:auto}
248
+ .dshmm-subtle{font-size:11px;color:var(--dsw-alias-label-secondary)}
249
+ .dshmm-cleanbar{display:flex;align-items:center;gap:8px;margin:8px 20px 0;padding:8px 10px;border-radius:8px;background:color-mix(in srgb, var(--dsw-alias-label-primary) 6%, transparent);flex:none;flex-wrap:wrap}
250
+ .dshmm-cleanlabel{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);flex:auto;min-width:0}
251
+ .dshmm-cleaninput{appearance:none;border:0.5px solid var(--dsw-alias-border-l2);border-radius:6px;padding:4px 8px;font:inherit;font-size:11px;line-height:16px;width:96px;background:var(--dsw-alias-bg-overlay);color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}
252
+ .dshmm-cleaninput:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
253
+ .dshmm-chip{flex:none;font-size:10px;line-height:15px;padding:0 6px;margin-top:2px;border-radius:5px;white-space:nowrap}
254
+ .dshmm-chipProtect{color:var(--dsw-alias-brand-primary);background:color-mix(in srgb, var(--dsw-alias-brand-primary) 12%, transparent)}
255
+ .dshmm-filterbar{display:flex;align-items:center;gap:8px;margin:8px 20px 0;flex:none;flex-wrap:wrap}
256
+ .dshmm-filterLabel{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary)}
257
+ .dshmm-select{appearance:none;border:0.5px solid var(--dsw-alias-border-l2);border-radius:6px;padding:4px 8px;font:inherit;font-size:11px;line-height:16px;background:var(--dsw-alias-bg-overlay);color:var(--dsw-alias-label-primary);cursor:pointer}
258
+ .dshmm-select:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
259
+ .dshmm-filterCount{font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
260
+ @media (max-width:520px){.dshmm-backdrop{padding:10px}.dshmm-panel{max-height:90vh}.dshmm-footHint{display:none}.dshmm-reason{display:none}}
261
+ `
262
+
263
+ function icon(paths, size) {
264
+ return h(
265
+ 'svg',
266
+ {
267
+ viewBox: '0 0 24 24',
268
+ width: size || 16,
269
+ height: size || 16,
270
+ fill: 'none',
271
+ stroke: 'currentColor',
272
+ strokeWidth: 1.7,
273
+ strokeLinecap: 'round',
274
+ strokeLinejoin: 'round',
275
+ 'aria-hidden': true,
276
+ },
277
+ paths.map((path, index) => h('path', { key: index, d: path })),
278
+ )
279
+ }
280
+
281
+ const IconList = () => icon(['M4 6h11', 'M4 12h9', 'M4 18h7', 'M17 15.5l4 4', 'M21 15.5l-4 4'])
282
+ const IconClose = () => icon(['M6 6l12 12', 'M18 6L6 18'])
283
+ const IconTrash = () => icon(['M4 7h16', 'M9 7V5h6v2', 'M6 7l1 13h10l1-13', 'M10 11v5', 'M14 11v5'])
284
+
285
+ function createManager(sessions, remote) {
286
+ let snapshot = { open: false, sessionId: undefined }
287
+ const listeners = new Set()
288
+ const publish = () => {
289
+ for (const listener of [...listeners]) {
290
+ try {
291
+ listener()
292
+ } catch (_error) {
293
+ /* one failing listener must not block the others */
294
+ }
295
+ }
296
+ }
297
+ return {
298
+ sessions,
299
+ subscribe(listener) {
300
+ listeners.add(listener)
301
+ return () => { listeners.delete(listener) }
302
+ },
303
+ getSnapshot() {
304
+ return snapshot
305
+ },
306
+ open(sessionId) {
307
+ snapshot = { open: true, sessionId }
308
+ publish()
309
+ },
310
+ close() {
311
+ if (!snapshot.open) return
312
+ snapshot = { open: false, sessionId: undefined }
313
+ publish()
314
+ },
315
+ async executeCommand(sessionId, line) {
316
+ const commands = remote?.commands
317
+ if (commands === undefined || typeof commands.execute !== 'function') {
318
+ throw new Error('commands Remote is unavailable.')
319
+ }
320
+ const controller = new AbortController()
321
+ const response = await commands.execute(sessionId, line, [], controller.signal)
322
+ if (response !== null && typeof response === 'object' && response.ok === false) {
323
+ const message = response.error !== null && typeof response.error === 'object' && typeof response.error.message === 'string'
324
+ ? response.error.message
325
+ : 'Remote command failed.'
326
+ throw new Error(message)
327
+ }
328
+ const execution = response !== null && typeof response === 'object' && response.ok === true
329
+ ? response.value
330
+ : response
331
+ if (execution === undefined || execution === null) throw new Error('Command was not recognized.')
332
+ return execution
333
+ },
334
+ }
335
+ }
336
+
337
+ function useManagerState(manager) {
338
+ return useSyncExternalStore(manager.subscribe, manager.getSnapshot, manager.getSnapshot)
339
+ }
340
+
341
+ function useSessionWindow(sessions, sessionId) {
342
+ const subscribe = useCallback((notify) => {
343
+ const binding = sessions.binding(sessionId)
344
+ if (binding === undefined) return () => {}
345
+ return binding.eventSource.subscribe(notify)
346
+ }, [sessions, sessionId])
347
+ const read = useCallback(() => {
348
+ const binding = sessions.binding(sessionId)
349
+ return binding === undefined ? EMPTY_WINDOW : binding.eventSource.getSnapshot()
350
+ }, [sessions, sessionId])
351
+ return useSyncExternalStore(subscribe, read, read)
352
+ }
353
+
354
+ function roleOf(event) {
355
+ if (event.type === 'user/message') return event.data?.source?.kind === 'user' ? 'user' : 'context'
356
+ if (event.type === 'assistant/message') return 'assistant'
357
+ if (event.type === 'tool/result') return 'tool'
358
+ if (event.type === 'developer/message') return 'context'
359
+ return 'system'
360
+ }
361
+
362
+ function previewOf(message, limit) {
363
+ const content = Array.isArray(message?.content) ? message.content : []
364
+ const parts = []
365
+ for (const block of content) {
366
+ if (block === null || typeof block !== 'object') continue
367
+ if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
368
+ else if (block.type === 'tool-call') parts.push(`tool:${typeof block.name === 'string' ? block.name : '?'}`)
369
+ else if (block.type === 'image') parts.push('[image]')
370
+ else if (block.type === 'file') parts.push(`[file${block.attachment?.name ? `: ${block.attachment.name}` : ''}]`)
371
+ else if (block.type === 'tool-addition') parts.push(`+${String(block.toolName)}`)
372
+ else if (block.type === 'tool-removal') parts.push(`-${String(block.toolName)}`)
373
+ }
374
+ const text = parts.join(' ').replace(/\s+/g, ' ').trim()
375
+ if (text.length === 0) return ''
376
+ const max = limit === undefined ? 120 : limit
377
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
378
+ }
379
+
380
+ function toolCallIdsOf(event) {
381
+ if (event === undefined || event.type !== 'assistant/message') return []
382
+ const content = Array.isArray(event.data?.message?.content) ? event.data.message.content : []
383
+ return content
384
+ .filter((block) => block !== null && typeof block === 'object' && block.type === 'tool-call' && typeof block.id === 'string')
385
+ .map((block) => block.id)
386
+ }
387
+
388
+ function hasToolChange(event) {
389
+ const content = event?.data?.message?.content
390
+ return Array.isArray(content)
391
+ && content.some((block) => block?.type === 'tool-addition' || block?.type === 'tool-removal')
392
+ }
393
+
394
+ /** Heuristic token estimate (4 chars ≈ 1 token), mirrors the Host estimate; CJK/JSON underpriced. */
395
+ function estimateTokens(message, isSystem) {
396
+ if (message === undefined || message === null) return 0
397
+ const content = Array.isArray(message.content) ? message.content : []
398
+ if (content.length === 0) return 0
399
+ if (isSystem) {
400
+ let chars = 0
401
+ for (const block of content) chars += block?.type === 'text' ? (block.text?.length ?? 0) : JSON.stringify(block).length
402
+ return Math.ceil(chars / 4) + 4
403
+ }
404
+ let tokens = 0
405
+ for (const block of content) {
406
+ if (block === null || typeof block !== 'object') continue
407
+ if (block.type === 'text' || block.type === 'reasoning') tokens += Math.ceil((block.text?.length ?? 0) / 4) + 4
408
+ else if (block.type === 'tool-call') tokens += Math.ceil((block.name?.length ?? 0) / 4) + Math.ceil((block.arguments?.length ?? 0) / 4) + 4
409
+ else tokens += 4 + Math.ceil(JSON.stringify(block).length / 4)
410
+ }
411
+ return tokens + 4
412
+ }
413
+
414
+ /** Source kinds this plugin writes for tombstones: current, then older releases. */
415
+ const TOMBSTONE_KINDS = ['context-manager', 'message-manager']
416
+
417
+ function isTombstoneKind(kind) {
418
+ return TOMBSTONE_KINDS.includes(kind)
419
+ }
420
+
421
+ function isTombstoneEvent(event) {
422
+ return event !== undefined
423
+ && event !== null
424
+ && event.type === 'developer/message'
425
+ && Array.isArray(event.data?.message?.content)
426
+ && event.data.message.content.length === 0
427
+ && isTombstoneKind(event.data?.message?.source?.kind)
428
+ && event.surfaceOp !== null
429
+ && typeof event.surfaceOp === 'object'
430
+ && event.surfaceOp.op === 'replace'
431
+ }
432
+
433
+ function parseRestoredTombstoneId(id) {
434
+ if (typeof id !== 'string' || !id.startsWith('restored-assistant-')) return undefined
435
+ const rest = id.slice('restored-assistant-'.length)
436
+ const dash = rest.indexOf('-')
437
+ if (dash <= 0) return undefined
438
+ const seq = Number(rest.slice(0, dash))
439
+ return Number.isSafeInteger(seq) ? seq : undefined
440
+ }
441
+
442
+ function foldEntries(entries) {
443
+ const seqs = []
444
+ const bySeq = new Map()
445
+ const groups = []
446
+ for (const entry of entries) {
447
+ if (entry === null || typeof entry !== 'object' || entry.type === 'transient') continue
448
+ const event = entry.event
449
+ if (event === null || typeof event !== 'object' || typeof event.seq !== 'number') continue
450
+ bySeq.set(event.seq, event)
451
+ if (!SURFACE_TYPES.has(event.type)) continue
452
+ const op = event.surfaceOp
453
+ if (op === undefined) continue
454
+ if (op === 'append') {
455
+ seqs.push(event.seq)
456
+ continue
457
+ }
458
+ if (op !== null && typeof op === 'object' && op.op === 'replace') {
459
+ const start = seqs.indexOf(op.startSeq)
460
+ const end = seqs.indexOf(op.endSeq)
461
+ if (start < 0 || end < start) continue
462
+ const removed = seqs.slice(start, end + 1)
463
+ if (isTombstoneEvent(event)) {
464
+ groups.push({
465
+ tombstoneSeq: event.seq,
466
+ targetSeqs: removed,
467
+ batchId: typeof event.data?.message?.source?.batchId === 'string'
468
+ ? event.data.message.source.batchId
469
+ : undefined,
470
+ recall: Array.isArray(event.data?.message?.source?.recall)
471
+ ? event.data.message.source.recall
472
+ : [],
473
+ })
474
+ }
475
+ seqs.splice(start, end - start + 1, event.seq)
476
+ }
477
+ }
478
+
479
+ const items = []
480
+ let turn = 0
481
+ let step = 0
482
+ for (let index = 0; index < seqs.length; index += 1) {
483
+ const seq = seqs[index]
484
+ const event = bySeq.get(seq)
485
+ if (event === undefined) continue
486
+ if (Number.isSafeInteger(event.data?.turn)) turn = event.data.turn
487
+ if (Number.isSafeInteger(event.data?.step)) step = event.data.step
488
+ if (event.type === 'system/message') continue
489
+ const message = event.type === 'user/message' ? event.data : event.data?.message
490
+ if (message === null || typeof message !== 'object') continue
491
+ const content = Array.isArray(message.content) ? message.content : []
492
+ if ((event.type === 'developer/message' || event.type === 'assistant/message') && content.length === 0) continue
493
+ let itemTurn = Number.isSafeInteger(event.data?.turn) ? event.data.turn : undefined
494
+ let itemStep = Number.isSafeInteger(event.data?.step) ? event.data.step : undefined
495
+ if (itemTurn === undefined || itemStep === undefined) {
496
+ for (let next = index + 1; next < seqs.length; next += 1) {
497
+ const data = bySeq.get(seqs[next])?.data
498
+ if (Number.isSafeInteger(data?.turn) && Number.isSafeInteger(data?.step)) {
499
+ itemTurn = data.turn
500
+ itemStep = data.step
501
+ break
502
+ }
503
+ }
504
+ }
505
+ items.push({
506
+ seq: event.seq,
507
+ time: event.time,
508
+ type: event.type,
509
+ role: roleOf(event),
510
+ turn: itemTurn ?? turn,
511
+ step: itemStep ?? step,
512
+ messageId: typeof message.id === 'string' ? message.id : undefined,
513
+ preview: previewOf(message),
514
+ blocks: content.length,
515
+ callIds: toolCallIdsOf(event),
516
+ toolCallId: event.type === 'tool/result' && typeof message.toolCallId === 'string' ? message.toolCallId : undefined,
517
+ tokens: content.length === 0 ? 0 : estimateTokens(message, event.type === 'system/message'),
518
+ })
519
+ }
520
+
521
+ const restored = new Set()
522
+ for (const item of items) {
523
+ const tombstoneSeq = parseRestoredTombstoneId(item.messageId)
524
+ if (tombstoneSeq !== undefined) restored.add(tombstoneSeq)
525
+ }
526
+
527
+ const deleted = []
528
+ for (const group of groups) {
529
+ if (restored.has(group.tombstoneSeq)) continue
530
+ const originalEvents = group.targetSeqs.map((seq) => bySeq.get(seq))
531
+ const known = originalEvents.filter((event) => event !== undefined)
532
+ const missing = group.targetSeqs.length - known.length
533
+ const assistant = known.find((event) => event.type === 'assistant/message')
534
+ const calls = assistant === undefined ? [] : toolCallIdsOf(assistant)
535
+ const results = known.filter((event) => event.type === 'tool/result')
536
+ let restorable = false
537
+ let reason = ''
538
+ if (group.targetSeqs.length === 1) {
539
+ const event = known[0]
540
+ if (event === undefined) restorable = true
541
+ else if (event.type === 'user/message') restorable = true
542
+ else if (event.type === 'developer/message' && !hasToolChange(event)) restorable = true
543
+ else if (event.type === 'assistant/message' && calls.length === 0) {
544
+ restorable = true
545
+ reason = 'appended'
546
+ } else if (event.type === 'tool/result') reason = 'tool'
547
+ else reason = 'group'
548
+ } else if (assistant !== undefined && calls.length > 0 && missing === 0 && results.length === group.targetSeqs.length - 1) {
549
+ const ids = new Set(calls.map((block) => block.id))
550
+ const resultIds = new Set(results.map((event) => event.data?.message?.toolCallId))
551
+ restorable = ids.size === resultIds.size && [...ids].every((id) => resultIds.has(id))
552
+ reason = restorable ? 'appended' : 'group'
553
+ } else {
554
+ reason = missing > 0 ? 'missing' : 'group'
555
+ }
556
+ deleted.push({
557
+ tombstoneSeq: group.tombstoneSeq,
558
+ targetSeqs: [...group.targetSeqs],
559
+ count: group.targetSeqs.length,
560
+ items: known.map((event) => {
561
+ const message = event.type === 'user/message' ? event.data : event.data?.message
562
+ return {
563
+ seq: event.seq,
564
+ role: roleOf(event),
565
+ preview: previewOf(message),
566
+ time: event.time,
567
+ }
568
+ }),
569
+ missing,
570
+ restorable,
571
+ reason,
572
+ })
573
+ }
574
+ return { items, deleted }
575
+ }
576
+
577
+ function formatTime(time, locale) {
578
+ if (!Number.isFinite(time)) return ''
579
+ try {
580
+ return new Date(time).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
581
+ } catch (_error) {
582
+ return ''
583
+ }
584
+ }
585
+
586
+ /**
587
+ * Expand one selection the way the Host deletion planner will: deleting an
588
+ * assistant message takes its tool results along, and deleting a tool result
589
+ * takes the owning assistant message and its sibling results along.
590
+ * @returns the full set of seqs the Host would remove.
591
+ */
592
+ function expansionFor(items, selectedSeqs) {
593
+ const bySeq = new Map(items.map((item) => [item.seq, item]))
594
+ const chosen = new Set(selectedSeqs)
595
+ const takeGroup = (assistant) => {
596
+ chosen.add(assistant.seq)
597
+ for (const sibling of items) {
598
+ if (sibling.role === 'tool' && sibling.toolCallId !== undefined
599
+ && assistant.callIds !== undefined && assistant.callIds.includes(sibling.toolCallId)) {
600
+ chosen.add(sibling.seq)
601
+ }
602
+ }
603
+ }
604
+ for (const seq of selectedSeqs) {
605
+ const item = bySeq.get(seq)
606
+ if (item === undefined) continue
607
+ if (item.role === 'tool' && item.toolCallId !== undefined) {
608
+ for (const candidate of items) {
609
+ if (candidate.role === 'assistant' && candidate.callIds !== undefined
610
+ && candidate.callIds.includes(item.toolCallId)) {
611
+ takeGroup(candidate)
612
+ }
613
+ }
614
+ } else if (item.role === 'assistant' && item.callIds !== undefined && item.callIds.length > 0) {
615
+ takeGroup(item)
616
+ }
617
+ }
618
+ return chosen
619
+ }
620
+
621
+ function ContextManagerButton({ sessionId, manager, t }) {
622
+ const state = useManagerState(manager)
623
+ const translate = typeof t === 'function' ? t : manager.translate
624
+ return h(
625
+ React.Fragment,
626
+ null,
627
+ h('style', null, CSS),
628
+ h(
629
+ 'button',
630
+ {
631
+ type: 'button',
632
+ className: 'dshmm-btn',
633
+ title: translate('open'),
634
+ 'aria-label': translate('open'),
635
+ 'data-open': state.open ? 'true' : 'false',
636
+ onClick: () => {
637
+ if (sessionId === undefined) return
638
+ manager.open(sessionId)
639
+ },
640
+ },
641
+ h(IconList),
642
+ ),
643
+ )
644
+ }
645
+
646
+ function ManagerDialog({ manager, sessionId, locale, t, onBackdrop }) {
647
+ const window = useSessionWindow(manager.sessions, sessionId)
648
+ const folded = useMemo(() => foldEntries(window.entries), [window])
649
+ const items = folded.items
650
+ const deleted = folded.deleted
651
+ const [selectedItems, setSelectedItems] = useState(() => new Set())
652
+ const [selectedDeleted, setSelectedDeleted] = useState(() => new Set())
653
+ const [selectedTurnSet, setSelectedTurnSet] = useState(() => new Set())
654
+ const [pending, setPending] = useState(undefined)
655
+ const [status, setStatus] = useState(undefined)
656
+ const [busy, setBusy] = useState(false)
657
+ const listRef = useRef(null)
658
+ const panelRef = useRef(null)
659
+ // The per-message list is secondary to the turns view; start collapsed.
660
+ const [currentCollapsed, setCurrentCollapsed] = useState(true)
661
+ const [cleanBudget, setCleanBudget] = useState('20000')
662
+ const [roleFilter, setRoleFilter] = useState('all')
663
+
664
+ useEffect(() => {
665
+ const panel = panelRef.current
666
+ if (panel !== null && typeof panel.focus === 'function') panel.focus()
667
+ const list = listRef.current
668
+ if (list !== null) list.scrollTop = list.scrollHeight
669
+ }, [])
670
+
671
+ useEffect(() => {
672
+ const onKeyDown = (event) => {
673
+ if (event.key !== 'Escape') return
674
+ if (busy) return
675
+ event.stopPropagation()
676
+ manager.close()
677
+ }
678
+ document.addEventListener('keydown', onKeyDown, true)
679
+ return () => { document.removeEventListener('keydown', onKeyDown, true) }
680
+ }, [manager, busy])
681
+
682
+ const totalTokens = items.reduce((sum, item) => sum + (item.tokens ?? 0), 0)
683
+ // Filtering is a view concern only: selection, token totals and the Host
684
+ // planner still see the complete list.
685
+ const visibleItems = roleFilter === 'all' ? items : items.filter((item) => item.role === roleFilter)
686
+ const currentSelectedSeqs = items.filter((item) => selectedItems.has(item.seq)).map((item) => item.seq)
687
+ const restorableDeleted = deleted.filter((group) => group.restorable)
688
+ const deletedSelectedSeqs = restorableDeleted
689
+ .filter((group) => selectedDeleted.has(group.tombstoneSeq))
690
+ .map((group) => group.tombstoneSeq)
691
+ const allCurrentSelected = items.length > 0 && currentSelectedSeqs.length === items.length
692
+ const allDeletedSelected = restorableDeleted.length > 0 && deletedSelectedSeqs.length === restorableDeleted.length
693
+
694
+ // Conversation turns, oldest first; the newest turn with content is the
695
+ // one still in progress, so deleting it is applied on the next turn.
696
+ const turnGroups = useMemo(() => {
697
+ const byTurn = new Map()
698
+ for (const item of items) {
699
+ const group = byTurn.get(item.turn) ?? { turn: item.turn, items: [], tokens: 0 }
700
+ group.items.push(item)
701
+ group.tokens = (group.tokens ?? 0) + (item.tokens ?? 0)
702
+ byTurn.set(item.turn, group)
703
+ }
704
+ return [...byTurn.values()].sort((a, b) => a.turn - b.turn)
705
+ }, [items])
706
+ const lastTurn = turnGroups.length > 0 ? turnGroups[turnGroups.length - 1].turn : undefined
707
+ const selectedTurns = turnGroups
708
+ .filter((group) => selectedTurnSet.has(group.turn))
709
+ .map((group) => group.turn)
710
+ const allTurnsSelected = turnGroups.length > 0 && selectedTurns.length === turnGroups.length
711
+
712
+ const toggleCurrent = (seq, checked) => {
713
+ setSelectedItems((current) => {
714
+ const next = new Set(current)
715
+ if (checked) next.add(seq)
716
+ else next.delete(seq)
717
+ return next
718
+ })
719
+ }
720
+ const toggleTurn = (turn, checked) => {
721
+ setSelectedTurnSet((current) => {
722
+ const next = new Set(current)
723
+ if (checked) next.add(turn)
724
+ else next.delete(turn)
725
+ return next
726
+ })
727
+ }
728
+ const toggleAllTurns = () => {
729
+ setSelectedTurnSet(allTurnsSelected ? new Set() : new Set(turnGroups.map((group) => group.turn)))
730
+ }
731
+ const toggleDeleted = (tombstoneSeq, checked) => {
732
+ setSelectedDeleted((current) => {
733
+ const next = new Set(current)
734
+ if (checked) next.add(tombstoneSeq)
735
+ else next.delete(tombstoneSeq)
736
+ return next
737
+ })
738
+ }
739
+ const toggleAllCurrent = () => {
740
+ setSelectedItems(allCurrentSelected ? new Set() : new Set(items.map((item) => item.seq)))
741
+ }
742
+ const toggleAllDeleted = () => {
743
+ setSelectedDeleted(allDeletedSelected ? new Set() : new Set(restorableDeleted.map((group) => group.tombstoneSeq)))
744
+ }
745
+
746
+ const run = async (kind, seqs) => {
747
+ if (busy || seqs.length === 0) return
748
+ setBusy(true)
749
+ setStatus(undefined)
750
+ setPending(undefined)
751
+ try {
752
+ const execution = await manager.executeCommand(sessionId, `/ctxmgr ${kind} ${seqs.join(',')}`)
753
+ const result = execution?.result !== undefined ? execution.result : execution
754
+ if (result !== undefined && result !== null && result.kind === 'error') {
755
+ setStatus({ kind: 'error', text: result.text || t('failed') })
756
+ return
757
+ }
758
+ const fallback = kind === 'restore'
759
+ ? t('restoreQueued', { count: seqs.length })
760
+ : kind === 'deleteturn'
761
+ ? t('turnsDeleted', { count: seqs.length })
762
+ : t('deleted', { count: seqs.length })
763
+ const text = result !== undefined && result !== null && result.kind === 'success' ? result.text : undefined
764
+ setStatus({ kind: 'success', text: text || fallback })
765
+ if (kind === 'delete') setSelectedItems(new Set())
766
+ else if (kind === 'deleteturn') setSelectedTurnSet(new Set())
767
+ else setSelectedDeleted(new Set())
768
+ } catch (error) {
769
+ setStatus({ kind: 'error', text: error instanceof Error ? error.message : String(error) })
770
+ } finally {
771
+ setBusy(false)
772
+ }
773
+ }
774
+
775
+ const runClean = async (targetTokens) => {
776
+ if (busy || !Number.isSafeInteger(targetTokens) || targetTokens <= 0) return
777
+ setBusy(true)
778
+ setStatus(undefined)
779
+ setPending(undefined)
780
+ try {
781
+ const execution = await manager.executeCommand(sessionId, `/ctxmgr clean ${targetTokens}`)
782
+ const result = execution?.result !== undefined ? execution.result : execution
783
+ if (result !== undefined && result !== null && result.kind === 'error') {
784
+ setStatus({ kind: 'error', text: result.text || t('failed') })
785
+ return
786
+ }
787
+ const text = result !== undefined && result !== null && result.kind === 'success' ? result.text : undefined
788
+ setStatus({ kind: 'success', text: text || t('cleaned', { tokens: targetTokens.toLocaleString('en-US') }) })
789
+ setSelectedItems(new Set())
790
+ } catch (error) {
791
+ setStatus({ kind: 'error', text: error instanceof Error ? error.message : String(error) })
792
+ } finally {
793
+ setBusy(false)
794
+ }
795
+ }
796
+
797
+ const runUndo = async () => {
798
+ if (busy) return
799
+ setBusy(true)
800
+ setStatus(undefined)
801
+ setPending(undefined)
802
+ try {
803
+ const execution = await manager.executeCommand(sessionId, '/ctxmgr undo-batch')
804
+ const result = execution?.result !== undefined ? execution.result : execution
805
+ if (result !== undefined && result !== null && result.kind === 'error') {
806
+ setStatus({ kind: 'error', text: result.text || t('failed') })
807
+ return
808
+ }
809
+ const text = result !== undefined && result !== null && result.kind === 'success' ? result.text : undefined
810
+ setStatus({ kind: 'success', text: text || t('undoDone') })
811
+ setSelectedDeleted(new Set())
812
+ } catch (error) {
813
+ setStatus({ kind: 'error', text: error instanceof Error ? error.message : String(error) })
814
+ } finally {
815
+ setBusy(false)
816
+ }
817
+ }
818
+
819
+ const confirmPending = () => {
820
+ if (pending === undefined) return
821
+ run(pending.kind === 'turns' ? 'deleteturn' : 'delete', pending.seqs)
822
+ }
823
+
824
+ const renderCurrent = (item) => h(
825
+ 'div',
826
+ { className: 'dshmm-row', key: item.seq, 'data-role': item.role },
827
+ h(
828
+ 'label',
829
+ { className: 'dshmm-checkWrap' },
830
+ h('input', {
831
+ type: 'checkbox',
832
+ className: 'dshmm-check',
833
+ checked: selectedItems.has(item.seq),
834
+ disabled: busy,
835
+ 'aria-label': `Select #${item.seq}`,
836
+ onChange: (event) => toggleCurrent(item.seq, event.target.checked),
837
+ }),
838
+ ),
839
+ h('span', { className: 'dshmm-role' }, t(item.role)),
840
+ item.role === 'user'
841
+ ? h('span', { className: 'dshmm-chip dshmm-chipProtect', title: t('protectedUser') }, t('protectedChip'))
842
+ : null,
843
+ h(
844
+ 'div',
845
+ { className: 'dshmm-main' },
846
+ h(
847
+ 'div',
848
+ { className: 'dshmm-preview', title: item.preview || undefined },
849
+ item.preview || t('emptyMessage'),
850
+ ),
851
+ h(
852
+ 'div',
853
+ { className: 'dshmm-meta' },
854
+ `#${item.seq}`,
855
+ ' · ',
856
+ formatTime(item.time, locale),
857
+ item.turn > 0 ? ` · T${item.turn}S${item.step}` : '',
858
+ item.tokens !== undefined && Number.isFinite(item.tokens)
859
+ ? ` · ${t('tokenSuffix', { tokens: Math.round(item.tokens).toLocaleString('en-US') })}`
860
+ : '',
861
+ ),
862
+ ),
863
+ h(
864
+ 'div',
865
+ { className: 'dshmm-actions' },
866
+ h(
867
+ 'button',
868
+ {
869
+ type: 'button',
870
+ className: 'dshmm-iconbtn',
871
+ title: t('delete'),
872
+ 'aria-label': t('delete'),
873
+ disabled: busy,
874
+ onClick: () => {
875
+ setPending({ kind: 'msgs', seqs: [item.seq], total: expansionFor(items, [item.seq]).size })
876
+ setStatus(undefined)
877
+ },
878
+ },
879
+ h(IconTrash),
880
+ ),
881
+ ),
882
+ )
883
+
884
+ const renderTurn = (group) => {
885
+ const own = group.items.find((item) => item.role === 'user')
886
+ const preview = (own ?? group.items[0])?.preview ?? ''
887
+ const inProgress = group.turn === lastTurn
888
+ return h(
889
+ 'div',
890
+ { className: 'dshmm-row', key: `turn-${group.turn}`, 'data-role': 'user' },
891
+ h(
892
+ 'label',
893
+ { className: 'dshmm-checkWrap' },
894
+ h('input', {
895
+ type: 'checkbox',
896
+ className: 'dshmm-check',
897
+ checked: selectedTurnSet.has(group.turn),
898
+ disabled: busy,
899
+ 'aria-label': `Select turn ${group.turn}`,
900
+ onChange: (event) => toggleTurn(group.turn, event.target.checked),
901
+ }),
902
+ ),
903
+ h('span', { className: 'dshmm-role' }, t('turnBadge', { turn: group.turn })),
904
+ h(
905
+ 'div',
906
+ { className: 'dshmm-main' },
907
+ h(
908
+ 'div',
909
+ { className: 'dshmm-preview', title: preview || undefined },
910
+ preview || t('noUserMessage'),
911
+ ),
912
+ h(
913
+ 'div',
914
+ { className: 'dshmm-meta' },
915
+ t('turnMeta', { count: group.items.length }),
916
+ ` · ${t('tokenSuffix', { tokens: group.tokens.toLocaleString('en-US') })}`,
917
+ inProgress ? ` · ${t('inProgressNote')}` : '',
918
+ ),
919
+ ),
920
+ h(
921
+ 'div',
922
+ { className: 'dshmm-actions' },
923
+ h(
924
+ 'button',
925
+ {
926
+ type: 'button',
927
+ className: 'dshmm-iconbtn',
928
+ title: t('deleteTurn'),
929
+ 'aria-label': t('deleteTurn'),
930
+ disabled: busy,
931
+ onClick: () => {
932
+ setPending({ kind: 'turns', seqs: [group.turn] })
933
+ setStatus(undefined)
934
+ },
935
+ },
936
+ h(IconTrash),
937
+ ),
938
+ ),
939
+ )
940
+ }
941
+
942
+ const renderDeleted = (group) => {
943
+ const first = group.items[0]
944
+ const recalled = Array.isArray(group.recall) ? group.recall : []
945
+ const summary = first === undefined && recalled.length > 0
946
+ ? `${t('recallChip', { seq: recalled[0].seq })} · ${recalled[0].preview || t('emptyMessage')}`
947
+ : group.count === 1
948
+ ? first === undefined
949
+ ? `#${group.targetSeqs[0]} · ${t('contentNotLoaded')}`
950
+ : `${t(first.role)} · ${first.preview || t('emptyMessage')}`
951
+ : `${t('deletedGroup')} · ${group.count}${first !== undefined && first.preview ? ` · ${first.preview}` : ''}`
952
+ const reasonKey = group.reason === 'appended'
953
+ ? 'restoreAppended'
954
+ : group.reason === 'tool'
955
+ ? 'unrestorableTool'
956
+ : group.reason === 'missing'
957
+ ? 'contentNotLoaded'
958
+ : group.reason === 'group'
959
+ ? 'unrestorableGroup'
960
+ : undefined
961
+ return h(
962
+ 'div',
963
+ { className: 'dshmm-row dshmm-deletedRow', key: group.tombstoneSeq, 'data-role': first?.role },
964
+ h(
965
+ 'label',
966
+ { className: 'dshmm-checkWrap' },
967
+ h('input', {
968
+ type: 'checkbox',
969
+ className: 'dshmm-check',
970
+ checked: selectedDeleted.has(group.tombstoneSeq),
971
+ disabled: busy || !group.restorable,
972
+ 'aria-label': `Select deleted #${group.tombstoneSeq}`,
973
+ onChange: (event) => toggleDeleted(group.tombstoneSeq, event.target.checked),
974
+ }),
975
+ ),
976
+ h('span', { className: 'dshmm-role' }, first === undefined ? '—' : t(first.role)),
977
+ h(
978
+ 'div',
979
+ { className: 'dshmm-main' },
980
+ h(
981
+ 'div',
982
+ { className: 'dshmm-preview', title: first?.preview || undefined },
983
+ summary,
984
+ ),
985
+ h(
986
+ 'div',
987
+ { className: 'dshmm-meta' },
988
+ t('deletedRecord', { seq: group.tombstoneSeq }),
989
+ typeof group.batchId === 'string' ? ` · ${t('batchLabel', { id: group.batchId.slice(0, 8) })}` : '',
990
+ reasonKey === undefined ? '' : ` · ${t(reasonKey)}`,
991
+ ),
992
+ ),
993
+ h(
994
+ 'div',
995
+ { className: 'dshmm-actions' },
996
+ group.restorable
997
+ ? h(
998
+ 'button',
999
+ {
1000
+ type: 'button',
1001
+ className: 'dshmm-restore',
1002
+ disabled: busy,
1003
+ onClick: () => run('restore', [group.tombstoneSeq]),
1004
+ },
1005
+ t('restore'),
1006
+ )
1007
+ : h('span', { className: 'dshmm-reason' }, t(reasonKey || 'unavailable')),
1008
+ ),
1009
+ )
1010
+ }
1011
+
1012
+ const sectionHeader = (title, count, allSelected, onToggleAll, actions, selectable, collapse) => h(
1013
+ 'div',
1014
+ { className: 'dshmm-section' },
1015
+ selectable
1016
+ ? h(
1017
+ 'label',
1018
+ { className: 'dshmm-selectAll' },
1019
+ h('input', {
1020
+ type: 'checkbox',
1021
+ className: 'dshmm-check',
1022
+ checked: allSelected,
1023
+ disabled: busy || count === 0,
1024
+ onChange: onToggleAll,
1025
+ }),
1026
+ allSelected ? t('clearSelection') : t('selectAll'),
1027
+ )
1028
+ : null,
1029
+ collapse === undefined
1030
+ ? h('span', { className: 'dshmm-sectionTitle' }, title)
1031
+ : h(
1032
+ 'button',
1033
+ {
1034
+ type: 'button',
1035
+ className: 'dshmm-sectionToggle',
1036
+ title: collapse.collapsed ? t('expandSection') : t('collapseSection'),
1037
+ 'aria-label': collapse.collapsed ? t('expandSection') : t('collapseSection'),
1038
+ 'aria-expanded': collapse.collapsed ? 'false' : 'true',
1039
+ onClick: collapse.onToggle,
1040
+ },
1041
+ h('span', { className: 'dshmm-chevron' }, collapse.collapsed ? '▸' : '▾'),
1042
+ h('span', { className: 'dshmm-sectionTitle' }, title),
1043
+ ),
1044
+ h('span', { className: 'dshmm-sectionCount' }, String(count)),
1045
+ h('div', { className: 'dshmm-sectionActions' }, actions),
1046
+ )
1047
+
1048
+ return h(
1049
+ 'div',
1050
+ {
1051
+ className: 'dshmm-backdrop',
1052
+ onMouseDown: (event) => {
1053
+ if (event.target === event.currentTarget && !busy) onBackdrop()
1054
+ },
1055
+ },
1056
+ h(
1057
+ 'div',
1058
+ {
1059
+ className: 'dshmm-panel',
1060
+ ref: panelRef,
1061
+ tabIndex: -1,
1062
+ role: 'dialog',
1063
+ 'aria-modal': 'true',
1064
+ 'aria-label': t('title'),
1065
+ },
1066
+ h(
1067
+ 'div',
1068
+ { className: 'dshmm-head' },
1069
+ h(
1070
+ 'div',
1071
+ { className: 'dshmm-titleRow' },
1072
+ h('h2', { className: 'dshmm-title' }, t('title')),
1073
+ h(
1074
+ 'button',
1075
+ {
1076
+ type: 'button',
1077
+ className: 'dshmm-close',
1078
+ title: t('close'),
1079
+ 'aria-label': t('close'),
1080
+ disabled: busy,
1081
+ onClick: () => manager.close(),
1082
+ },
1083
+ h(IconClose),
1084
+ ),
1085
+ ),
1086
+ h('p', { className: 'dshmm-subtitle' }, t('subtitle')),
1087
+ h(
1088
+ 'div',
1089
+ { className: 'dshmm-filterbar' },
1090
+ h('span', { className: 'dshmm-filterLabel' }, t('filterLabel')),
1091
+ h(
1092
+ 'select',
1093
+ {
1094
+ className: 'dshmm-select',
1095
+ value: roleFilter,
1096
+ disabled: busy,
1097
+ 'aria-label': t('filterLabel'),
1098
+ onChange: (event) => setRoleFilter(event.target.value),
1099
+ },
1100
+ h('option', { value: 'all' }, t('filterAll')),
1101
+ ['user', 'assistant', 'tool', 'context'].map((role) => h(
1102
+ 'option',
1103
+ { key: role, value: role },
1104
+ t('filterRole', { role: t(role) }),
1105
+ )),
1106
+ ),
1107
+ roleFilter === 'all'
1108
+ ? null
1109
+ : h('span', { className: 'dshmm-filterCount' }, t('filterCount', { shown: visibleItems.length, total: items.length })),
1110
+ ),
1111
+ h(
1112
+ 'div',
1113
+ { className: 'dshmm-cleanbar' },
1114
+ h('span', { className: 'dshmm-cleanlabel' }, t('cleanHint')),
1115
+ h('input', {
1116
+ type: 'number',
1117
+ min: 1,
1118
+ step: 1000,
1119
+ className: 'dshmm-cleaninput',
1120
+ value: cleanBudget,
1121
+ disabled: busy,
1122
+ 'aria-label': t('cleanBudget'),
1123
+ placeholder: t('cleanBudget'),
1124
+ onChange: (event) => setCleanBudget(event.target.value),
1125
+ }),
1126
+ h(
1127
+ 'button',
1128
+ {
1129
+ type: 'button',
1130
+ className: 'dshmm-small',
1131
+ disabled: busy,
1132
+ onClick: () => {
1133
+ const budget = Number.parseInt(cleanBudget, 10)
1134
+ if (!Number.isSafeInteger(budget) || budget <= 0) {
1135
+ setStatus({ kind: 'error', text: t('cleanInvalid') })
1136
+ return
1137
+ }
1138
+ runClean(budget)
1139
+ },
1140
+ },
1141
+ t('cleanSelected', { count: cleanBudget }),
1142
+ ),
1143
+ ),
1144
+ ),
1145
+ status === undefined
1146
+ ? null
1147
+ : h(
1148
+ 'div',
1149
+ { className: 'dshmm-banner', 'data-kind': status.kind, role: 'status' },
1150
+ status.text,
1151
+ ),
1152
+ pending === undefined
1153
+ ? null
1154
+ : h(
1155
+ 'div',
1156
+ { className: 'dshmm-confirmBar' },
1157
+ h('span', null,
1158
+ pending.kind === 'turns'
1159
+ ? t('confirmBatchTurns', { count: pending.seqs.length })
1160
+ : t('confirmBatch', { count: pending.seqs.length }),
1161
+ pending.kind !== 'turns' && pending.total > pending.seqs.length
1162
+ ? h('span', { className: 'dshmm-subtle' },
1163
+ ` · ${t('confirmTotal', { count: pending.total })} · ${t('groupHint')}`)
1164
+ : null,
1165
+ ),
1166
+ h(
1167
+ 'div',
1168
+ { className: 'dshmm-confirmActions' },
1169
+ h(
1170
+ 'button',
1171
+ {
1172
+ type: 'button',
1173
+ className: 'dshmm-small',
1174
+ disabled: busy,
1175
+ onClick: () => setPending(undefined),
1176
+ },
1177
+ t('cancel'),
1178
+ ),
1179
+ h(
1180
+ 'button',
1181
+ {
1182
+ type: 'button',
1183
+ className: 'dshmm-small',
1184
+ 'data-danger': 'true',
1185
+ disabled: busy,
1186
+ onClick: confirmPending,
1187
+ },
1188
+ t('confirmDelete'),
1189
+ ),
1190
+ ),
1191
+ ),
1192
+ h(
1193
+ 'div',
1194
+ { className: 'dshmm-list', ref: listRef },
1195
+ window.entries.length === 0
1196
+ ? h('div', { className: 'dshmm-empty' }, t('notReady'))
1197
+ : items.length === 0 && deleted.length === 0
1198
+ ? h('div', { className: 'dshmm-empty' }, t('empty'))
1199
+ : h(
1200
+ React.Fragment,
1201
+ null,
1202
+ turnGroups.length === 0
1203
+ ? null
1204
+ : h(
1205
+ React.Fragment,
1206
+ null,
1207
+ sectionHeader(
1208
+ t('turnsSection'),
1209
+ turnGroups.length,
1210
+ allTurnsSelected,
1211
+ toggleAllTurns,
1212
+ h(
1213
+ 'button',
1214
+ {
1215
+ type: 'button',
1216
+ className: 'dshmm-small',
1217
+ 'data-danger': 'true',
1218
+ disabled: busy || selectedTurns.length === 0,
1219
+ onClick: () => setPending({ kind: 'turns', seqs: selectedTurns }),
1220
+ },
1221
+ t('deleteSelected', { count: selectedTurns.length }),
1222
+ ),
1223
+ true,
1224
+ ),
1225
+ turnGroups.map(renderTurn),
1226
+ ),
1227
+ sectionHeader(
1228
+ t('currentSection'),
1229
+ items.length,
1230
+ allCurrentSelected,
1231
+ toggleAllCurrent,
1232
+ h(
1233
+ 'button',
1234
+ {
1235
+ type: 'button',
1236
+ className: 'dshmm-small',
1237
+ 'data-danger': 'true',
1238
+ disabled: busy || currentSelectedSeqs.length === 0,
1239
+ onClick: () => setPending({
1240
+ kind: 'msgs',
1241
+ seqs: currentSelectedSeqs,
1242
+ total: expansionFor(items, currentSelectedSeqs).size,
1243
+ }),
1244
+ },
1245
+ t('deleteSelected', { count: currentSelectedSeqs.length }),
1246
+ ),
1247
+ true,
1248
+ { collapsed: currentCollapsed, onToggle: () => setCurrentCollapsed((value) => !value) },
1249
+ ),
1250
+ items.length === 0
1251
+ ? h('div', { className: 'dshmm-empty' }, t('empty'))
1252
+ : currentCollapsed
1253
+ ? null
1254
+ : visibleItems.length === 0
1255
+ ? h('div', { className: 'dshmm-empty' }, t('filterEmpty'))
1256
+ : visibleItems.map(renderCurrent),
1257
+
1258
+ deleted.length === 0
1259
+ ? null
1260
+ : h(
1261
+ React.Fragment,
1262
+ null,
1263
+ sectionHeader(
1264
+ t('deletedSection'),
1265
+ deleted.length,
1266
+ allDeletedSelected,
1267
+ toggleAllDeleted,
1268
+ h(
1269
+ 'button',
1270
+ {
1271
+ type: 'button',
1272
+ className: 'dshmm-small',
1273
+ disabled: busy || deletedSelectedSeqs.length === 0,
1274
+ onClick: () => run('restore', deletedSelectedSeqs),
1275
+ },
1276
+ t('restoreSelected', { count: deletedSelectedSeqs.length }),
1277
+ ),
1278
+ restorableDeleted.length > 0,
1279
+ ),
1280
+ deleted.map(renderDeleted),
1281
+ ),
1282
+ ),
1283
+ ),
1284
+ h(
1285
+ 'div',
1286
+ { className: 'dshmm-foot' },
1287
+ h(
1288
+ 'span',
1289
+ { className: 'dshmm-footCount' },
1290
+ busy
1291
+ ? t('busy')
1292
+ : `${t('count', { count: items.length })} · ${t('totalTokens', { tokens: totalTokens.toLocaleString('en-US') })}${deleted.length > 0 ? ` · ${t('deletedSection')} ${deleted.length}` : ''}`,
1293
+ ),
1294
+ deleted.length === 0
1295
+ ? null
1296
+ : h(
1297
+ 'button',
1298
+ {
1299
+ type: 'button',
1300
+ className: 'dshmm-small',
1301
+ disabled: busy,
1302
+ onClick: runUndo,
1303
+ },
1304
+ t('undoLast'),
1305
+ ),
1306
+ h(
1307
+ 'span',
1308
+ { className: 'dshmm-footHint' },
1309
+ t('hint'),
1310
+ ' ',
1311
+ h('span', { className: 'dshmm-code' }, t('usage')),
1312
+ ),
1313
+ ),
1314
+ ),
1315
+ )
1316
+ }
1317
+
1318
+ function ManagerOverlay({ manager, t }) {
1319
+ const state = useManagerState(manager)
1320
+ const translate = typeof t === 'function' ? t : manager.translate
1321
+ const locale = manager.locale
1322
+ if (!state.open || state.sessionId === undefined) return null
1323
+ return h(
1324
+ React.Fragment,
1325
+ null,
1326
+ h('style', null, CSS),
1327
+ h(ManagerDialog, {
1328
+ key: state.sessionId,
1329
+ manager,
1330
+ sessionId: state.sessionId,
1331
+ locale,
1332
+ t: translate,
1333
+ onBackdrop: () => manager.close(),
1334
+ }),
1335
+ )
1336
+ }
1337
+
1338
+ return {
1339
+ inject: ['slots', 'sessions', 'locale', 'remote', 'remote.commands'],
1340
+ apply(ctx) {
1341
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'context-manager: locale dictionaries')
1342
+ const t = ctx.locale.bind(NS)
1343
+ const manager = createManager(ctx.sessions, ctx.remote)
1344
+ manager.translate = t
1345
+ manager.locale = ctx.locale.getLocale()?.active
1346
+
1347
+ ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register(
1348
+ {
1349
+ name: 'conversation.session.header.utilities',
1350
+ id: 'context-manager',
1351
+ order: 20,
1352
+ locale: NS,
1353
+ inject: () => ({ manager }),
1354
+ },
1355
+ ContextManagerButton,
1356
+ ))
1357
+
1358
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register(
1359
+ {
1360
+ name: 'shell.overlay',
1361
+ id: 'context-manager',
1362
+ order: 100,
1363
+ locale: NS,
1364
+ inject: () => ({ manager }),
1365
+ },
1366
+ ManagerOverlay,
1367
+ ))
1368
+ },
1369
+ }
1370
+ },
1371
+ })