@psyduck25/dsh-session-manager 0.0.0-stage → 0.4.1

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/lib/client.js ADDED
@@ -0,0 +1,1069 @@
1
+ // dsh-session-manager(会话删除管理)的浏览器半侧:设置 → 「会话删除管理」一页。
2
+ //
3
+ // 三件事:
4
+ // 1. 按工作区分组列出所有会话,每行带「锁定」和「删除」;
5
+ // 2. 删除要二次确认,确认后不是立刻销毁,而是进下面的「删除缓冲站」;
6
+ // 3. 缓冲站里的会话可以回档,到期才由宿主彻底删除。
7
+ //
8
+ // 宿主调用走普通 HTTP 路由(lib/index.js 里的 `ctx.webServer.register`)。
9
+ // 样式全部用 `--dsw-alias-*` 主题变量,深浅色自动跟随;不 import 任何 Harness UI 包
10
+ // —— 那些包会随版本变动,自己写控件最稳。
11
+ //
12
+ // ⚠️ 这里的 id 必须逐字等于 package.json 的 name。
13
+ // client-modules 用**包名**当 entry id(dsh-client-modules/lib/index.js 的
14
+ // `graphRow(packageName, ...)`),浏览器端拿这个 id 去核对 bundle 是否注册过;
15
+ // 对不上就整个浏览器半侧作废,设置页里那一项根本不出现 —— 而且不报错、不崩溃,
16
+ // 只是静悄悄地没了。2026-11-18 因为包改名成 @psyduck25/dsh-session-manager
17
+ // 而这里还留着旧名,正是这么丢的。
18
+ window.__ModuleLoader__.load({
19
+ id: '@psyduck25/dsh-session-manager',
20
+ factory(require) {
21
+ const React = require('react')
22
+ const h = React.createElement
23
+
24
+ const SECTION_ID = 'session-manager'
25
+ const ROUTE_PREFIX = '/api/dsh-session-manager'
26
+ const LOCALE_NS = 'session-manager'
27
+ /** 宿主最长要等 3 秒让会话退出内存,留足余量。 */
28
+ const HOST_TIMEOUT_MS = 30_000
29
+
30
+ // ---------------------------------------------------------------- 文案
31
+
32
+ const DICT = {
33
+ en: {
34
+ 'common.retry': 'Retry',
35
+ 'section.label': 'Session manager',
36
+ 'page.title': 'Session manager',
37
+ 'page.desc': 'List every session by workspace, lock the ones you want to keep, and delete the rest through a recycle bin.',
38
+ 'settings.title': 'Recycle bin window',
39
+ 'settings.hint': 'Deleted sessions stay recoverable for this long, then their logs are deleted for real. 0 means deleting for good on confirmation.',
40
+ 'settings.unit': 'hours',
41
+ 'settings.save': 'Save',
42
+ 'settings.reset': 'Restore default',
43
+ 'settings.saved': 'Saved.',
44
+ 'settings.needNumber': 'Enter a whole number of hours first.',
45
+ 'settings.range': 'Allowed range: {min}–{max} hours',
46
+ 'reload.label': 'Reload interface',
47
+ 'reload.hint': 'Reloads this page and re-reads the session list, which clears rows left behind by the browser-side snapshot.',
48
+ 'reload.busy': 'Reloading…',
49
+ 'notice.reloadFailed': 'this page cannot reload itself; press F12 and then Ctrl+R instead',
50
+ 'sessions.title': 'Sessions',
51
+ 'sessions.empty': 'No sessions.',
52
+ 'sessions.refresh': 'Refresh',
53
+ 'sessions.unnamed': 'Untitled',
54
+ 'sessions.orphan': 'No workspace',
55
+ 'sessions.subagent': 'subagent',
56
+ 'sessions.locked': 'Locked',
57
+ 'sessions.live': 'open',
58
+ 'sessions.running': 'running',
59
+ 'sessions.missing': 'log missing',
60
+ 'action.lock': 'Lock',
61
+ 'action.unlock': 'Unlock',
62
+ 'action.delete': 'Delete',
63
+ 'action.adopt': 'File it',
64
+ 'adopt.hint': 'Its folder belongs to {workspace}',
65
+ 'notice.adopted': '“{title}” is filed under {workspace}.',
66
+ 'notice.noWorkspaceForCwd': 'no workspace owns that folder',
67
+ 'notice.noCwd': 'the session records no folder',
68
+ 'notice.noHeader': 'the session log cannot be read',
69
+ 'notice.noRegistry': 'this profile has no workspace registry',
70
+ 'notice.adoptFailed': 'filing it failed',
71
+ 'confirm.delete': 'Delete “{title}”? It moves to the recycle bin and can be recovered for {hours} hours.',
72
+ 'confirm.now': 'Delete “{title}” for good? This cannot be undone.',
73
+ 'confirm.purge': 'Delete “{title}” for good? This cannot be undone.',
74
+ 'confirm.yes': 'Delete',
75
+ 'confirm.no': 'Cancel',
76
+ 'notice.locked': 'This session is locked. Unlock it first.',
77
+ 'notice.alreadyBuffered': 'This session is already in the recycle bin.',
78
+ 'notice.deleted': '“{title}” moved to the recycle bin.',
79
+ 'notice.purged': '“{title}” was deleted for good.',
80
+ 'notice.restored': '“{title}” is back where it was.',
81
+ 'notice.purgeFailed': '“{title}” could not be deleted yet: {reason}',
82
+ 'notice.notBuffered': 'This session is no longer in the recycle bin.',
83
+ 'buffer.title': 'Recycle bin',
84
+ 'buffer.desc': 'These sessions are gone from the workspace list. Restore one to bring it back exactly as it was, or delete it for good now.',
85
+ 'buffer.empty': 'Empty. Deleted sessions wait here.',
86
+ 'buffer.restore': 'Restore',
87
+ 'buffer.purge': 'Delete now',
88
+ 'buffer.remaining': '{time} left',
89
+ 'buffer.pending': 'Expired, waiting: {note}',
90
+ 'buffer.purgeSoon': 'about to be deleted',
91
+ 'reason.running': 'it is in the middle of a turn; stop it and try again',
92
+ 'reason.archiveFailed': 'the workspace could not record the removal',
93
+ 'reason.moveFailed': 'the session log file could not be moved',
94
+ 'reason.noPersistence': 'this profile has no session storage',
95
+ 'reason.noLocation': 'the log file cannot be located',
96
+ 'reason.statFailed': 'could not locate the log file',
97
+ 'reason.readdirFailed': 'could not read the session folder',
98
+ 'reason.unlinkFailed': 'could not remove the log file',
99
+ 'reason.purgeFailed': 'deletion failed',
100
+ 'reason.liveBlocked': 'it is in the middle of a turn; stop it and try again',
101
+ 'reason.noMeta': 'the recycle bin is missing its restore information',
102
+ 'reason.missingLog': 'the session log file could not be found',
103
+ 'reason.deleteFailed': 'deletion failed',
104
+ 'reason.restoreFailed': 'restore failed',
105
+ 'reason.saveFailed': 'saving failed',
106
+ 'reason.readFailed': 'reading sessions failed',
107
+ 'reason.notLoopback': 'this page must be opened on the local address',
108
+ 'reason.badBody': 'the request was rejected',
109
+ 'reason.network': 'the Host could not be reached',
110
+ 'reason.timeout': 'the Host did not answer in time; try again',
111
+ 'reason.detachFailed': 'the workspace still lists it; try again',
112
+ 'time.minutes': '{n}m',
113
+ 'time.hours': '{n}h',
114
+ 'time.days': '{n}d',
115
+ 'time.justNow': 'just now',
116
+ 'time.ago': '{time} ago',
117
+ 'error.prefix': 'Request failed: ',
118
+ 'loading': 'Reading sessions…',
119
+ 'loading.failed': 'Could not read sessions.',
120
+ },
121
+ zh: {
122
+ 'common.retry': '重试',
123
+ 'section.label': '会话删除管理',
124
+ 'page.title': '会话删除管理',
125
+ 'page.desc': '按工作区列出所有会话,锁定的会话不能删除;删除先进缓冲站,到期才真正删掉。',
126
+ 'settings.title': '缓冲时长',
127
+ 'settings.hint': '进入缓冲站的会话在这段时间内都能回档,超时才真正删除日志。填 0 表示二次确认后立即彻底删除。',
128
+ 'settings.unit': '小时',
129
+ 'settings.save': '保存',
130
+ 'settings.reset': '恢复默认',
131
+ 'settings.saved': '已保存。',
132
+ 'settings.needNumber': '先填一个整数的时长。',
133
+ 'settings.range': '可填范围 {min}–{max} 小时',
134
+ 'reload.label': '刷新界面',
135
+ 'reload.hint': '重新加载这个页面并重新读取会话列表;删除后仍然显示的那一行就是靠它清掉的。',
136
+ 'reload.busy': '正在刷新…',
137
+ 'notice.reloadFailed': '这个页面不能自己刷新,请按 F12 打开开发者工具后按 Ctrl+R',
138
+ 'sessions.title': '会话',
139
+ 'sessions.empty': '没有会话。',
140
+ 'sessions.refresh': '刷新',
141
+ 'sessions.unnamed': '未命名',
142
+ 'sessions.orphan': '未归属工作区',
143
+ 'sessions.subagent': '子代理',
144
+ 'sessions.locked': '已锁定',
145
+ 'sessions.live': '打开中',
146
+ 'sessions.running': '运行中',
147
+ 'sessions.missing': '日志缺失',
148
+ 'action.lock': '锁定',
149
+ 'action.unlock': '解锁',
150
+ 'action.delete': '删除',
151
+ 'action.adopt': '归位',
152
+ 'adopt.hint': '它的目录属于 {workspace}',
153
+ 'notice.adopted': '「{title}」已归位到 {workspace}。',
154
+ 'notice.noWorkspaceForCwd': '没有工作区认领它的目录',
155
+ 'notice.noCwd': '这个会话没有记录目录',
156
+ 'notice.noHeader': '读不到这个会话的日志',
157
+ 'notice.noRegistry': '这个配置没有工作区注册表',
158
+ 'notice.adoptFailed': '归位失败',
159
+ 'confirm.delete': '确认删除「{title}」?会先进入删除缓冲站,{hours} 小时内可以回档。',
160
+ 'confirm.now': '确认彻底删除「{title}」?此操作无法撤销。',
161
+ 'confirm.purge': '彻底删除「{title}」?此操作无法撤销。',
162
+ 'confirm.yes': '确认删除',
163
+ 'confirm.no': '取消',
164
+ 'notice.locked': '这个会话已锁定,先解锁再删除。',
165
+ 'notice.alreadyBuffered': '这个会话已经在删除缓冲站里了。',
166
+ 'notice.deleted': '「{title}」已进入删除缓冲站。',
167
+ 'notice.purged': '「{title}」已彻底删除。',
168
+ 'notice.restored': '「{title}」已回档到原来的位置。',
169
+ 'notice.purgeFailed': '「{title}」暂时删不掉:{reason}',
170
+ 'notice.notBuffered': '这个会话已经不在删除缓冲站里了。',
171
+ 'buffer.title': '删除缓冲站',
172
+ 'buffer.desc': '这些会话已经从工作区列表消失。回档会原样恢复;「彻底删除」则立即销毁日志,不再等待到期。',
173
+ 'buffer.empty': '空。删除的会话会先在这里等一会儿。',
174
+ 'buffer.restore': '回档',
175
+ 'buffer.purge': '彻底删除',
176
+ 'buffer.remaining': '还剩 {time}',
177
+ 'buffer.pending': '已到期,等待清理:{note}',
178
+ 'buffer.purgeSoon': '即将删除',
179
+ 'reason.running': '它正在跑一个回合,停下来再删',
180
+ 'reason.archiveFailed': '工作区没能记录这次移除',
181
+ 'reason.moveFailed': '会话日志文件搬不动',
182
+ 'reason.noPersistence': '这个配置没有挂会话存储',
183
+ 'reason.noLocation': '定位不到日志文件',
184
+ 'reason.statFailed': '定位不到日志文件',
185
+ 'reason.readdirFailed': '读不了会话目录',
186
+ 'reason.unlinkFailed': '删不掉日志文件',
187
+ 'reason.purgeFailed': '删除失败',
188
+ 'reason.liveBlocked': '它正在跑一个回合,停下来再删',
189
+ 'reason.noMeta': '回收站里缺少还原信息',
190
+ 'reason.missingLog': '找不到会话日志文件',
191
+ 'reason.deleteFailed': '删除失败',
192
+ 'reason.restoreFailed': '回档失败',
193
+ 'reason.saveFailed': '保存失败',
194
+ 'reason.readFailed': '读取会话列表失败',
195
+ 'reason.notLoopback': '这个页面必须从本机地址打开',
196
+ 'reason.badBody': '请求被拒绝',
197
+ 'reason.network': '连不上宿主',
198
+ 'reason.timeout': '宿主迟迟没有响应,请重试',
199
+ 'reason.detachFailed': '工作区里还挂着它,请重试',
200
+ 'error.prefix': '请求失败:',
201
+ 'time.minutes': '{n}分',
202
+ 'time.hours': '{n}小时',
203
+ 'time.days': '{n}天',
204
+ 'time.justNow': '刚刚',
205
+ 'time.ago': '{time}前',
206
+ 'loading': '正在读取会话…',
207
+ 'loading.failed': '读取会话失败。',
208
+ },
209
+ }
210
+
211
+ function format(dict, key, vars) {
212
+ const template = dict[key] ?? key
213
+ if (vars === undefined) return template
214
+ return template.replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match))
215
+ }
216
+
217
+ /** 语言包优先用 Harness 的 locale 服务,取不到就退回包内字典。 */
218
+ function makeTranslate(locale, active) {
219
+ const fallback = DICT[String(active || 'zh').slice(0, 2)] ?? DICT.zh
220
+ const bound = locale === undefined ? undefined : locale.bind(LOCALE_NS)
221
+ const translator = (key, vars) => {
222
+ let value
223
+ if (bound !== undefined) {
224
+ try {
225
+ value = bound(key, vars)
226
+ } catch {
227
+ value = undefined
228
+ }
229
+ }
230
+ if (typeof value === 'string' && value !== key) return value
231
+ return format(fallback, key, vars)
232
+ }
233
+ translator.dict = fallback
234
+ return translator
235
+ }
236
+
237
+ /**
238
+ * 把宿主返回的错误翻译成当前语言。
239
+ * 宿主只给错误码(code)和原始消息,句子由界面拼,英文界面里不会冒出中文。
240
+ */
241
+ function describeError(t, result) {
242
+ const code = result && typeof result.code === 'string' ? result.code : ''
243
+ if (code !== '') {
244
+ // 归位相关的错误码用 notice.* 文案,其余用 reason.*。
245
+ const asNotice = t(`notice.${code}`)
246
+ if (asNotice !== `notice.${code}`) return asNotice
247
+ const known = t(`reason.${code}`)
248
+ if (known !== `reason.${code}`) return known
249
+ }
250
+ const detail = result && typeof result.error === 'string' ? result.error : ''
251
+ return detail !== '' ? t('error.prefix') + detail : t('error.prefix') + 'HTTP'
252
+ }
253
+
254
+ // ---------------------------------------------------------------- 宿主调用
255
+
256
+ /**
257
+ * 统一成 {ok, ...};页面只处理一种形状。
258
+ *
259
+ * 一定要有超时:宿主那边的删除要等会话退出内存(最长 3 秒,见 DETACH_TIMEOUT_MS),
260
+ * 万一它卡住不回,fetch 会一直挂着,`busy` 就永远不为 null——页面上所有按钮
261
+ * 从此点不动,只能刷新。这里 30 秒兜底,超时按 network 错误报出去。
262
+ */
263
+ async function callHost(action, payload) {
264
+ const controller = new AbortController()
265
+ const timer = setTimeout(() => controller.abort(), HOST_TIMEOUT_MS)
266
+ try {
267
+ const response = await fetch(`${ROUTE_PREFIX}/${action}`, {
268
+ method: 'POST',
269
+ headers: { 'content-type': 'application/json' },
270
+ body: JSON.stringify(payload ?? {}),
271
+ signal: controller.signal,
272
+ })
273
+ let parsed = null
274
+ try {
275
+ parsed = await response.json()
276
+ } catch {
277
+ parsed = null
278
+ }
279
+ if (parsed === null || typeof parsed !== 'object') {
280
+ return { ok: false, status: response.status }
281
+ }
282
+ if (!response.ok && parsed.ok !== false) {
283
+ return { ...parsed, ok: false, status: response.status }
284
+ }
285
+ return parsed
286
+ } catch (error) {
287
+ if (error && error.name === 'AbortError') return { ok: false, code: 'timeout' }
288
+ return { ok: false, code: 'network', error: error && error.message ? error.message : String(error) }
289
+ } finally {
290
+ clearTimeout(timer)
291
+ }
292
+ }
293
+
294
+ // ---------------------------------------------------------------- 小图标
295
+
296
+ function TrashGlyph({ size = 16 }) {
297
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' },
298
+ h('path', { d: 'M4 7h16', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round' }),
299
+ h('path', { d: 'M9.5 7V5.2c0-.66.54-1.2 1.2-1.2h2.6c.66 0 1.2.54 1.2 1.2V7', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round' }),
300
+ h('path', { d: 'M6.6 7l.8 11.2c.05.98.88 1.8 1.86 1.8h5.48c.98 0 1.81-.82 1.86-1.8L17.4 7', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' }),
301
+ h('path', { d: 'M10.4 11.2v5.4M13.6 11.2v5.4', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round' }),
302
+ )
303
+ }
304
+
305
+ function LockGlyph({ locked, size = 14 }) {
306
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' },
307
+ h('rect', {
308
+ x: 5, y: 10.5, width: 14, height: 9.5, rx: 2.2,
309
+ stroke: 'currentColor', strokeWidth: 1.7,
310
+ fill: locked ? 'currentColor' : 'none',
311
+ fillOpacity: locked ? 0.14 : 0,
312
+ }),
313
+ h('path', {
314
+ d: locked ? 'M8.4 10.5V8.2a3.6 3.6 0 0 1 7.2 0v2.3' : 'M8.4 10.5V8.2a3.6 3.6 0 0 1 6.6-2',
315
+ stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round',
316
+ }),
317
+ )
318
+ }
319
+
320
+ function FolderGlyph({ size = 14 }) {
321
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' },
322
+ h('path', {
323
+ d: 'M3.6 7.2c0-1 .8-1.8 1.8-1.8h3.4l1.6 1.9h8.2c1 0 1.8.8 1.8 1.8v7.7c0 1-.8 1.8-1.8 1.8H5.4c-1 0-1.8-.8-1.8-1.8V7.2Z',
324
+ stroke: 'currentColor', strokeWidth: 1.7, strokeLinejoin: 'round',
325
+ }),
326
+ )
327
+ }
328
+
329
+ function RestoreGlyph({ size = 14 }) {
330
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' },
331
+ h('path', { d: 'M4.6 12a7.4 7.4 0 1 0 2.3-5.35', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round' }),
332
+ h('path', { d: 'M4.2 4.6v4.1h4.1', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' }),
333
+ )
334
+ }
335
+
336
+ /** 双向循环箭头:刷新整页。 */
337
+ function ReloadGlyph({ size = 14 }) {
338
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' },
339
+ h('path', {
340
+ d: 'M20 11.2a8 8 0 0 0-13.6-5.1L4 8.5',
341
+ stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round',
342
+ }),
343
+ h('path', { d: 'M4 4.2v4.3h4.3', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' }),
344
+ h('path', {
345
+ d: 'M4 12.8a8 8 0 0 0 13.6 5.1L20 15.5',
346
+ stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round',
347
+ }),
348
+ h('path', { d: 'M20 19.8v-4.3h-4.3', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' }),
349
+ )
350
+ }
351
+
352
+ // ---------------------------------------------------------------- 样式
353
+
354
+ let styleCache = null
355
+ function pageStyles() {
356
+ if (styleCache !== null) return styleCache
357
+ const mono = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace'
358
+ styleCache = {
359
+ page: {
360
+ display: 'flex',
361
+ flexDirection: 'column',
362
+ gap: 14,
363
+ width: '100%',
364
+ maxWidth: 720,
365
+ color: 'var(--dsw-alias-label-primary)',
366
+ font: '13px/1.6 -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif',
367
+ },
368
+ head: { display: 'grid', gridTemplateColumns: 'auto minmax(0, 1fr)', columnGap: 10, rowGap: 2, alignItems: 'center' },
369
+ glyph: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, gridRow: 'span 2', color: 'var(--dsw-alias-label-primary)' },
370
+ title: { margin: 0, fontSize: 15, fontWeight: 600, lineHeight: 1.4 },
371
+ desc: { margin: 0, fontSize: 12, lineHeight: 1.55, color: 'var(--dsw-alias-label-secondary)' },
372
+ card: {
373
+ padding: '14px 16px 16px',
374
+ borderRadius: 'var(--dsw-radius-xl)',
375
+ // 设置页的卡片用 settings-card-* 这一对:浅色主题下 bg-layer-1/2 是同一个
376
+ // 白色,只有它能让卡片和页面分开。
377
+ border: '1px solid var(--dsw-alias-settings-card-stroke)',
378
+ background: 'var(--dsw-alias-settings-card-fill)',
379
+ },
380
+ cardHead: { display: 'flex', alignItems: 'center', gap: 8, margin: '0 0 4px' },
381
+ cardTitle: { margin: 0, fontSize: 12.5, fontWeight: 600 },
382
+ cardHint: { margin: '0 0 10px', fontSize: 11.5, lineHeight: 1.55, color: 'var(--dsw-alias-label-secondary)' },
383
+ row: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginTop: 10 },
384
+ input: {
385
+ width: 88,
386
+ height: 32,
387
+ padding: '0 8px',
388
+ boxSizing: 'border-box',
389
+ textAlign: 'right',
390
+ fontSize: 13,
391
+ fontFamily: mono,
392
+ color: 'var(--dsw-alias-label-primary)',
393
+ background: 'var(--dsw-alias-bg-layer-2)',
394
+ border: '1px solid var(--dsw-alias-border-l2)',
395
+ borderRadius: 'var(--dsw-radius-md)',
396
+ },
397
+ unit: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' },
398
+ buttonPrimary: {
399
+ height: 32,
400
+ padding: '0 16px',
401
+ fontSize: 12.5,
402
+ fontWeight: 600,
403
+ borderRadius: 'var(--dsw-radius-md)',
404
+ cursor: 'pointer',
405
+ color: 'var(--dsw-alias-label-primary-foreground)',
406
+ background: 'var(--dsw-alias-button-primary-fill)',
407
+ border: '1px solid transparent',
408
+ },
409
+ buttonGhost: {
410
+ height: 30,
411
+ padding: '0 12px',
412
+ fontSize: 12.5,
413
+ borderRadius: 'var(--dsw-radius-md)',
414
+ cursor: 'pointer',
415
+ color: 'var(--dsw-alias-label-secondary)',
416
+ background: 'transparent',
417
+ border: '1px solid var(--dsw-alias-border-l2)',
418
+ },
419
+ buttonDanger: {
420
+ height: 30,
421
+ padding: '0 12px',
422
+ fontSize: 12.5,
423
+ borderRadius: 'var(--dsw-radius-md)',
424
+ cursor: 'pointer',
425
+ color: 'var(--dsw-alias-state-error-primary)',
426
+ background: 'transparent',
427
+ border: '1px solid var(--dsw-alias-border-l2)',
428
+ },
429
+ buttonDangerSolid: {
430
+ height: 30,
431
+ padding: '0 12px',
432
+ fontSize: 12.5,
433
+ fontWeight: 600,
434
+ borderRadius: 'var(--dsw-radius-md)',
435
+ cursor: 'pointer',
436
+ color: 'var(--dsw-alias-label-primary-foreground)',
437
+ background: 'var(--dsw-alias-state-error-primary)',
438
+ border: '1px solid transparent',
439
+ },
440
+ buttonIcon: {
441
+ display: 'inline-flex',
442
+ alignItems: 'center',
443
+ gap: 5,
444
+ },
445
+ buttonDisabled: { opacity: 0.45, cursor: 'not-allowed' },
446
+ group: { marginTop: 12 },
447
+ groupHead: {
448
+ display: 'flex',
449
+ alignItems: 'center',
450
+ gap: 7,
451
+ padding: '4px 2px 6px',
452
+ fontSize: 12,
453
+ fontWeight: 600,
454
+ color: 'var(--dsw-alias-label-secondary)',
455
+ },
456
+ groupPath: { fontSize: 11, fontWeight: 400, color: 'var(--dsw-alias-label-secondary)', opacity: 0.75, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
457
+ list: { display: 'flex', flexDirection: 'column', gap: 4 },
458
+ sessionRow: {
459
+ display: 'grid',
460
+ gridTemplateColumns: 'minmax(0, 1fr) auto',
461
+ columnGap: 10,
462
+ alignItems: 'center',
463
+ padding: '7px 10px',
464
+ borderRadius: 'var(--dsw-radius-md)',
465
+ background: 'var(--dsw-alias-bg-layer-2)',
466
+ border: '1px solid var(--dsw-alias-border-l1)',
467
+ },
468
+ sessionRowConfirm: { outline: '1px solid var(--dsw-alias-state-error-primary)' },
469
+ sessionMain: { minWidth: 0, display: 'flex', flexDirection: 'column', gap: 1 },
470
+ sessionTitle: { fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
471
+ sessionMeta: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)', display: 'flex', gap: 8, flexWrap: 'wrap' },
472
+ sessionActions: { display: 'flex', alignItems: 'center', gap: 6 },
473
+ badge: {
474
+ display: 'inline-flex',
475
+ alignItems: 'center',
476
+ gap: 3,
477
+ padding: '0 6px',
478
+ height: 18,
479
+ borderRadius: 'var(--dsw-radius-sm)',
480
+ fontSize: 10.5,
481
+ lineHeight: '18px',
482
+ color: 'var(--dsw-alias-label-secondary)',
483
+ background: 'var(--dsw-alias-bg-layer-1)',
484
+ border: '1px solid var(--dsw-alias-border-l2)',
485
+ },
486
+ badgeLocked: { color: 'var(--dsw-alias-label-primary)' },
487
+ badgeWarn: { color: 'var(--dsw-alias-state-warn-primary)' },
488
+ confirmBar: {
489
+ display: 'flex',
490
+ alignItems: 'center',
491
+ gap: 8,
492
+ flexWrap: 'wrap',
493
+ padding: '8px 10px',
494
+ borderRadius: 'var(--dsw-radius-md)',
495
+ fontSize: 12,
496
+ lineHeight: 1.5,
497
+ color: 'var(--dsw-alias-label-primary)',
498
+ background: 'var(--dsw-alias-bg-layer-1)',
499
+ border: '1px solid var(--dsw-alias-border-l2)',
500
+ },
501
+ confirmText: { flex: '1 1 220px', minWidth: 0 },
502
+ notice: {
503
+ marginTop: 8,
504
+ padding: '7px 9px',
505
+ borderRadius: 'var(--dsw-radius-md)',
506
+ fontSize: 11.5,
507
+ lineHeight: 1.55,
508
+ whiteSpace: 'pre-line',
509
+ border: '1px solid var(--dsw-alias-border-l2)',
510
+ background: 'var(--dsw-alias-bg-layer-2)',
511
+ },
512
+ noticeError: { color: 'var(--dsw-alias-state-error-primary)' },
513
+ noticeOk: { color: 'var(--dsw-alias-label-primary)' },
514
+ empty: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', padding: '6px 2px' },
515
+ }
516
+ return styleCache
517
+ }
518
+
519
+ // ---------------------------------------------------------------- 时间
520
+
521
+ /** 相对时间;单位走语言包,英文界面不会冒出「小时前」。 */
522
+ function relativeTime(timestamp, now, t) {
523
+ if (!Number.isFinite(timestamp) || timestamp <= 0) return ''
524
+ const diff = Math.max(0, now - timestamp)
525
+ const minute = 60_000
526
+ const hour = 60 * minute
527
+ const day = 24 * hour
528
+ if (diff < minute) return t('time.justNow')
529
+ let time
530
+ if (diff < hour) time = t('time.minutes', { n: Math.floor(diff / minute) })
531
+ else if (diff < day) time = t('time.hours', { n: Math.floor(diff / hour) })
532
+ else if (diff < 30 * day) time = t('time.days', { n: Math.floor(diff / day) })
533
+ else return new Date(timestamp).toLocaleDateString()
534
+ return t('time.ago', { time })
535
+ }
536
+
537
+ function remainingTime(expiresAt, now, t) {
538
+ const left = expiresAt - now
539
+ if (left <= 0) return t('buffer.purgeSoon')
540
+ const totalMinutes = Math.ceil(left / 60_000)
541
+ const days = Math.floor(totalMinutes / (60 * 24))
542
+ const hours = Math.floor((totalMinutes - days * 60 * 24) / 60)
543
+ const minutes = totalMinutes % 60
544
+ // 只显示两级:天+小时 / 小时+分 / 分,单位跟语言走。
545
+ // 两级之间用 ' ' 隔开:直接拼会是「1天3小时」「1d3h」,读起来糊成一团。
546
+ if (days > 0) return `${t('time.days', { n: days })} ${t('time.hours', { n: hours })}`
547
+ if (hours > 0) return `${t('time.hours', { n: hours })} ${t('time.minutes', { n: minutes })}`
548
+ return t('time.minutes', { n: minutes })
549
+ }
550
+
551
+ // ---------------------------------------------------------------- 设置页
552
+
553
+ function SessionManagerSection() {
554
+ const { useCallback, useEffect, useMemo, useRef, useState } = React
555
+ const style = useMemo(pageStyles, [])
556
+ const [view, setView] = useState(null)
557
+ const [draft, setDraft] = useState(null)
558
+ const [busy, setBusy] = useState(null)
559
+ const [notice, setNotice] = useState(null)
560
+ const [confirming, setConfirming] = useState(null)
561
+ const [reloading, setReloading] = useState(false)
562
+ const [now, setNow] = useState(() => Date.now())
563
+ const aliveRef = useRef(true)
564
+
565
+ const translate = useTranslate()
566
+ const t = translate
567
+
568
+ const applyView = useCallback((next) => {
569
+ if (!aliveRef.current) return
570
+ if (next && next.ok === true) {
571
+ setView(next)
572
+ setDraft((current) => (current === null ? String(next.settings.bufferHours) : current))
573
+ setNow(Date.now())
574
+ }
575
+ }, [])
576
+
577
+ const refresh = useCallback(async () => {
578
+ const next = await callHost('state', {})
579
+ if (!next.ok) {
580
+ if (aliveRef.current) setNotice({ tone: 'error', text: describeError(t, next) })
581
+ return next
582
+ }
583
+ applyView(next)
584
+ return next
585
+ }, [applyView, t])
586
+
587
+ useEffect(() => {
588
+ aliveRef.current = true
589
+ void refresh()
590
+ return () => {
591
+ aliveRef.current = false
592
+ }
593
+ }, [refresh])
594
+
595
+ // 只负责刷新「还剩多久」的本地时钟,不重复拉数据。
596
+ useEffect(() => {
597
+ const timer = setInterval(() => {
598
+ if (aliveRef.current) setNow(Date.now())
599
+ }, 15_000)
600
+ return () => clearInterval(timer)
601
+ }, [])
602
+
603
+ // 有条目到点时拉一次,让宿主把真正删掉的会话移出缓冲站。
604
+ const dueSignature = view === null
605
+ ? ''
606
+ : view.buffer.filter((entry) => entry.expiresAt <= now).map((entry) => entry.sessionId).join(',')
607
+ useEffect(() => {
608
+ if (dueSignature === '') return
609
+ const timer = setTimeout(() => void refresh(), 3_000)
610
+ return () => clearTimeout(timer)
611
+ }, [dueSignature, refresh])
612
+
613
+ const run = useCallback(
614
+ async (key, action, payload, onDone) => {
615
+ if (busy !== null) return
616
+ setBusy(key)
617
+ setNotice(null)
618
+ const result = await callHost(action, payload)
619
+ if (!aliveRef.current) return
620
+ setBusy(null)
621
+ if (result.ok !== true) {
622
+ setNotice({ tone: 'error', text: describeError(t, result) })
623
+ return
624
+ }
625
+ if (result.view !== undefined) applyView(result.view)
626
+ else applyView(result)
627
+ if (onDone !== undefined) onDone(result)
628
+ },
629
+ [busy, applyView, t],
630
+ )
631
+
632
+ const noticeNode = notice === null
633
+ ? null
634
+ : h('div', {
635
+ role: notice.tone === 'error' ? 'alert' : 'status',
636
+ style: Object.assign(
637
+ {},
638
+ style.notice,
639
+ { marginTop: 0 },
640
+ notice.tone === 'error' ? style.noticeError : style.noticeOk,
641
+ ),
642
+ }, notice.text)
643
+
644
+ if (view === null) {
645
+ // 首次读取失败必须能看见也能重试,否则只会永远停在「正在读取会话…」。
646
+ return h('div', { style: style.page },
647
+ h('div', { style: style.card },
648
+ notice !== null ? t('loading.failed') : t('loading'),
649
+ noticeNode,
650
+ notice === null
651
+ ? null
652
+ : h('div', { style: style.row },
653
+ h('button', {
654
+ type: 'button',
655
+ style: style.buttonPrimary,
656
+ onClick: () => {
657
+ setNotice(null)
658
+ void refresh()
659
+ },
660
+ }, t('common.retry')),
661
+ ),
662
+ ),
663
+ )
664
+ }
665
+
666
+ const settings = view.settings
667
+ const limits = view.limits?.bufferHours ?? { min: 0, max: 720, step: 1 }
668
+ const bufferHours = settings.bufferHours
669
+ const groups = buildGroups(view, t)
670
+ const showSecondConfirm = bufferHours > 0
671
+
672
+ const confirmText = (session) => {
673
+ const title = session.title.trim() === '' ? t('sessions.unnamed') : session.title
674
+ return showSecondConfirm
675
+ ? t('confirm.delete', { title, hours: bufferHours })
676
+ : t('confirm.now', { title })
677
+ }
678
+
679
+ return h('div', { style: style.page },
680
+ h('div', { style: style.head },
681
+ h('span', { style: style.glyph }, h(TrashGlyph, { size: 24 })),
682
+ h('h2', { style: style.title }, t('page.title')),
683
+ h('p', { style: style.desc }, t('page.desc')),
684
+ ),
685
+
686
+ // 刷新整页:DSH 的会话清单在浏览器里是一份内存快照,删掉的会话要等它重新
687
+ // 拉一次才会从左侧消失。DSH 自己在升级提示里就是用 location.reload() 做的,
688
+ // 桌面版正式发行的菜单里没有「刷新页面」,所以这里给一个入口。
689
+ h('div', { style: style.card },
690
+ h('div', { style: style.cardHead }, h('h3', { style: style.cardTitle }, t('reload.label'))),
691
+ h('p', { style: style.cardHint }, t('reload.hint')),
692
+ h('div', { style: style.row },
693
+ h('button', {
694
+ type: 'button',
695
+ style: Object.assign({}, style.buttonGhost, style.buttonIcon, reloading ? style.buttonDisabled : null),
696
+ disabled: reloading,
697
+ onClick: () => {
698
+ if (reloading) return
699
+ setReloading(true)
700
+ const reload = globalThis.location && globalThis.location.reload
701
+ if (typeof reload === 'function') {
702
+ try {
703
+ reload.call(globalThis.location)
704
+ } catch {
705
+ setReloading(false)
706
+ setNotice({ tone: 'error', text: t('notice.reloadFailed') })
707
+ }
708
+ } else {
709
+ setReloading(false)
710
+ setNotice({ tone: 'error', text: t('notice.reloadFailed') })
711
+ }
712
+ },
713
+ }, h(ReloadGlyph, { size: 13 }), reloading ? t('reload.busy') : t('reload.label')),
714
+ ),
715
+ ),
716
+
717
+ // 提示放在页头下面:动作可能来自列表中间,提示得在看得见的地方。
718
+ noticeNode,
719
+
720
+ // 缓冲时长
721
+ h('div', { style: style.card },
722
+ h('div', { style: style.cardHead }, h('h3', { style: style.cardTitle }, t('settings.title'))),
723
+ h('p', { style: style.cardHint }, t('settings.hint')),
724
+ h('div', { style: style.row },
725
+ // 用 text + inputMode 而不是 number:数字框会把滚轮当成改值,
726
+ // 设置页一滚就悄悄改掉缓冲时长。
727
+ h('input', {
728
+ type: 'text',
729
+ inputMode: 'numeric',
730
+ pattern: '[0-9]*',
731
+ style: style.input,
732
+ value: draft ?? String(bufferHours),
733
+ maxLength: String(limits.max).length,
734
+ 'aria-label': t('settings.title'),
735
+ title: t('settings.range', { min: limits.min, max: limits.max }),
736
+ onChange: (event) => {
737
+ const next = event.target.value.replace(/[^\d]/g, '')
738
+ setDraft(next)
739
+ },
740
+ }),
741
+ h('span', { style: style.unit }, t('settings.unit')),
742
+ h('span', { style: { flex: 1 } }),
743
+ h('button', {
744
+ type: 'button',
745
+ style: Object.assign({}, style.buttonPrimary, busy === 'settings' ? style.buttonDisabled : null),
746
+ disabled: busy !== null,
747
+ onClick: () => {
748
+ // 空输入不能当成 0:那等于把每次删除都变成不可撤销。
749
+ const raw = draft ?? String(bufferHours)
750
+ if (raw === '') {
751
+ setNotice({ tone: 'error', text: t('settings.needNumber') })
752
+ return
753
+ }
754
+ void run('settings', 'settings', { bufferHours: Number(raw) }, () => {
755
+ setDraft(null)
756
+ setNotice({ tone: 'ok', text: t('settings.saved') })
757
+ })
758
+ },
759
+ }, t('settings.save')),
760
+ h('button', {
761
+ type: 'button',
762
+ style: Object.assign({}, style.buttonGhost, busy !== null ? style.buttonDisabled : null),
763
+ disabled: busy !== null,
764
+ onClick: () =>
765
+ void run('settings', 'settings', { reset: true }, (result) => {
766
+ setDraft(String(result?.settings?.bufferHours ?? 24))
767
+ setNotice({ tone: 'ok', text: t('settings.saved') })
768
+ }),
769
+ }, t('settings.reset')),
770
+ ),
771
+ ),
772
+
773
+ // 会话列表
774
+ h('div', { style: style.card },
775
+ h('div', { style: style.cardHead },
776
+ h('h3', { style: style.cardTitle }, t('sessions.title')),
777
+ h('span', { style: style.badge }, String(view.sessions.length)),
778
+ h('span', { style: { flex: 1 } }),
779
+ h('button', {
780
+ type: 'button',
781
+ style: Object.assign({}, style.buttonGhost, busy !== null ? style.buttonDisabled : null),
782
+ disabled: busy !== null,
783
+ onClick: () => void run('refresh', 'state', {}, () => setConfirming(null)),
784
+ }, t('sessions.refresh')),
785
+ ),
786
+ groups.length === 0
787
+ ? h('div', { style: style.empty }, t('sessions.empty'))
788
+ : groups.map((group) =>
789
+ h('div', { key: group.key, style: style.group },
790
+ h('div', { style: style.groupHead },
791
+ h(FolderGlyph, { size: 13 }),
792
+ h('span', { style: { whiteSpace: 'nowrap' } }, group.title),
793
+ group.path === '' ? null : h('span', { style: style.groupPath }, group.path),
794
+ h('span', { style: { flex: 1 } }),
795
+ h('span', { style: style.badge }, String(group.sessions.length)),
796
+ ),
797
+ h('div', { style: style.list },
798
+ group.sessions.map((session) => {
799
+ const title = session.title.trim() === '' ? t('sessions.unnamed') : session.title
800
+ const locked = session.locked
801
+ const isConfirming = confirming === session.sessionId
802
+ const rowStyle = isConfirming
803
+ ? Object.assign({}, style.sessionRow, style.sessionRowConfirm)
804
+ : style.sessionRow
805
+ return h('div', { key: session.sessionId, style: rowStyle },
806
+ h('div', { style: style.sessionMain },
807
+ h('span', { style: style.sessionTitle, title }, title),
808
+ h('span', { style: style.sessionMeta },
809
+ session.updatedAt > 0 ? h('span', null, relativeTime(session.updatedAt, now, t)) : null,
810
+ // 两个状态分开显示:「正在运行」是硬拦(这时候动日志会丢对话),
811
+ // 「打开中」只是还挂在内存里,删除会走「先归档、退出内存后补搬」。
812
+ session.running === true
813
+ ? h('span', { style: Object.assign({}, style.badge, style.badgeWarn) }, t('sessions.running'))
814
+ : null,
815
+ session.running !== true && session.live === true
816
+ ? h('span', { style: style.badge }, t('sessions.live'))
817
+ : null,
818
+ locked ? h('span', { style: Object.assign({}, style.badge, style.badgeLocked) }, h(LockGlyph, { locked: true, size: 11 }), t('sessions.locked')) : null,
819
+ session.subagent === true ? h('span', { style: style.badge }, t('sessions.subagent')) : null,
820
+ session.missing === true ? h('span', { style: style.badge }, t('sessions.missing')) : null,
821
+ // 未分组、但目录属于某个工作区:告诉用户它本来该在哪。
822
+ session.adoptIntoTitle ? h('span', { style: style.badge }, t('adopt.hint', { workspace: session.adoptIntoTitle })) : null,
823
+ ),
824
+ ),
825
+ h('div', { style: style.sessionActions },
826
+ session.adoptIntoTitle
827
+ ? h('button', {
828
+ type: 'button',
829
+ style: Object.assign({}, style.buttonGhost, style.buttonIcon, busy !== null ? style.buttonDisabled : null),
830
+ disabled: busy !== null,
831
+ title: t('adopt.hint', { workspace: session.adoptIntoTitle }),
832
+ onClick: () =>
833
+ void run(`adopt:${session.sessionId}`, 'adopt', { sessionId: session.sessionId }, () => {
834
+ setNotice({ tone: 'ok', text: t('notice.adopted', { title, workspace: session.adoptIntoTitle }) })
835
+ }),
836
+ }, h(FolderGlyph, { size: 13 }), t('action.adopt'))
837
+ : null,
838
+ h('button', {
839
+ type: 'button',
840
+ style: Object.assign({}, style.buttonGhost, style.buttonIcon, busy !== null ? style.buttonDisabled : null),
841
+ disabled: busy !== null,
842
+ title: locked ? t('action.unlock') : t('action.lock'),
843
+ onClick: () =>
844
+ void run(`lock:${session.sessionId}`, 'lock', { sessionId: session.sessionId, locked: !locked }, () => setConfirming(null)),
845
+ }, h(LockGlyph, { locked, size: 13 }), locked ? t('action.unlock') : t('action.lock')),
846
+ h('button', {
847
+ type: 'button',
848
+ style: Object.assign(
849
+ {},
850
+ locked ? style.buttonGhost : style.buttonDanger,
851
+ style.buttonIcon,
852
+ locked || busy !== null ? style.buttonDisabled : null,
853
+ ),
854
+ disabled: locked || busy !== null,
855
+ title: locked ? t('sessions.locked') : t('action.delete'),
856
+ onClick: () => setConfirming(isConfirming ? null : session.sessionId),
857
+ }, h(TrashGlyph, { size: 13 }), t('action.delete')),
858
+ ),
859
+ isConfirming
860
+ ? h('div', { style: Object.assign({}, style.confirmBar, { gridColumn: '1 / -1' }) },
861
+ h('span', { style: style.confirmText }, confirmText(session)),
862
+ h('button', {
863
+ type: 'button',
864
+ style: Object.assign({}, style.buttonDangerSolid, busy !== null ? style.buttonDisabled : null),
865
+ disabled: busy !== null,
866
+ onClick: () =>
867
+ void run(`delete:${session.sessionId}`, 'delete', {
868
+ sessionId: session.sessionId,
869
+ title: session.title,
870
+ workspaceId: session.workspaceId ?? '',
871
+ workspaceTitle: group.title,
872
+ }, (result) => {
873
+ setConfirming(null)
874
+ if (result.purged === true) {
875
+ setNotice({ tone: 'ok', text: t('notice.purged', { title }) })
876
+ } else if (typeof result.code === 'string' && result.code !== '') {
877
+ setNotice({
878
+ tone: 'error',
879
+ text: t('notice.purgeFailed', { title, reason: describeError(t, result) }),
880
+ })
881
+ } else {
882
+ setNotice({ tone: 'ok', text: t('notice.deleted', { title }) })
883
+ }
884
+ }),
885
+ }, t('confirm.yes')),
886
+ h('button', {
887
+ type: 'button',
888
+ style: style.buttonGhost,
889
+ disabled: busy !== null,
890
+ onClick: () => setConfirming(null),
891
+ }, t('confirm.no')),
892
+ )
893
+ : null,
894
+ )
895
+ }),
896
+ ),
897
+ ),
898
+ ),
899
+ ),
900
+
901
+ // 删除缓冲站
902
+ h('div', { style: style.card },
903
+ h('div', { style: style.cardHead },
904
+ h('h3', { style: style.cardTitle }, t('buffer.title')),
905
+ h('span', { style: style.badge }, String(view.buffer.length)),
906
+ ),
907
+ h('p', { style: style.cardHint }, t('buffer.desc')),
908
+ view.buffer.length === 0
909
+ ? h('div', { style: style.empty }, t('buffer.empty'))
910
+ : h('div', { style: style.list },
911
+ view.buffer.map((entry) => {
912
+ const title = entry.title.trim() === '' ? t('sessions.unnamed') : entry.title
913
+ return h('div', { key: entry.sessionId, style: style.sessionRow },
914
+ h('div', { style: style.sessionMain },
915
+ h('span', { style: style.sessionTitle, title }, title),
916
+ h('span', { style: style.sessionMeta },
917
+ entry.workspaceTitle === '' ? null : h('span', null, entry.workspaceTitle),
918
+ entry.pending === true
919
+ ? h('span', null, t('buffer.pending', { note: describeError(t, { code: entry.note, error: entry.noteDetail }) }))
920
+ : h('span', null, t('buffer.remaining', { time: remainingTime(entry.expiresAt, now, t) })),
921
+ ),
922
+ ),
923
+ h('div', { style: style.sessionActions },
924
+ h('button', {
925
+ type: 'button',
926
+ style: Object.assign({}, style.buttonGhost, style.buttonIcon, busy !== null ? style.buttonDisabled : null),
927
+ disabled: busy !== null,
928
+ title: t('buffer.restore'),
929
+ onClick: () =>
930
+ void run(`restore:${entry.sessionId}`, 'restore', { sessionId: entry.sessionId }, () => {
931
+ setNotice({ tone: 'ok', text: t('notice.restored', { title }) })
932
+ }),
933
+ }, h(RestoreGlyph, { size: 13 }), t('buffer.restore')),
934
+ // 彻底删除不可撤销,而且紧挨着「回档」,误点代价是日志没了。
935
+ // 所以这里也要一次行内确认:第一次点变成「确认删除?是 / 否」,
936
+ // 和上面列表里的删除按钮同一套交互。
937
+ confirming === `purge:${entry.sessionId}`
938
+ ? h('span', { style: style.confirmBar },
939
+ h('span', { style: style.confirmText }, t('confirm.purge', { title })),
940
+ h('button', {
941
+ type: 'button',
942
+ style: Object.assign({}, style.buttonDanger, style.buttonIcon, busy !== null ? style.buttonDisabled : null),
943
+ disabled: busy !== null,
944
+ onClick: () => {
945
+ setConfirming(null)
946
+ void run(
947
+ `purge:${entry.sessionId}`,
948
+ 'purge',
949
+ { sessionId: entry.sessionId },
950
+ () => setNotice({ tone: 'ok', text: t('notice.purged', { title }) }),
951
+ )
952
+ },
953
+ }, t('confirm.yes')),
954
+ h('button', {
955
+ type: 'button',
956
+ style: style.buttonGhost,
957
+ disabled: busy !== null,
958
+ onClick: () => setConfirming(null),
959
+ }, t('confirm.no')),
960
+ )
961
+ : h('button', {
962
+ type: 'button',
963
+ style: Object.assign({}, style.buttonDanger, style.buttonIcon, busy !== null ? style.buttonDisabled : null),
964
+ disabled: busy !== null,
965
+ title: t('buffer.purge'),
966
+ onClick: () => setConfirming(`purge:${entry.sessionId}`),
967
+ }, h(TrashGlyph, { size: 13 }), t('buffer.purge')),
968
+ ),
969
+ )
970
+ }),
971
+ ),
972
+ ),
973
+ )
974
+ }
975
+
976
+ /** 按工作区分组;不在任何工作区里的会话落到最后一组。 */
977
+ function buildGroups(view, t) {
978
+ const byWorkspace = new Map()
979
+ for (const workspace of view.workspaces) byWorkspace.set(workspace.workspaceId, [])
980
+ const orphans = []
981
+ const order = view.workspaces.map((workspace) => workspace.workspaceId)
982
+ for (const session of view.sessions) {
983
+ const bucket = byWorkspace.get(session.workspaceId)
984
+ if (bucket === undefined) orphans.push(session)
985
+ else bucket.push(session)
986
+ }
987
+ const groups = []
988
+ for (const workspaceId of order) {
989
+ const sessions = byWorkspace.get(workspaceId) ?? []
990
+ if (sessions.length === 0) continue
991
+ const workspace = view.workspaces.find((item) => item.workspaceId === workspaceId)
992
+ groups.push({
993
+ key: workspaceId,
994
+ title: workspace?.title ?? '',
995
+ path: workspace?.path ?? '',
996
+ sessions: [...sessions].sort((left, right) => right.updatedAt - left.updatedAt),
997
+ })
998
+ }
999
+ if (orphans.length > 0) {
1000
+ groups.push({
1001
+ key: '__orphan__',
1002
+ title: t('sessions.orphan'),
1003
+ path: '',
1004
+ sessions: [...orphans].sort((left, right) => right.updatedAt - left.updatedAt),
1005
+ })
1006
+ }
1007
+ return groups
1008
+ }
1009
+
1010
+ /** 当前语言:优先 Harness 的 locale 服务,切换语言时重新渲染。 */
1011
+ const localeState = { service: undefined, active: 'zh' }
1012
+
1013
+ function useTranslate() {
1014
+ const { useEffect, useMemo, useState } = React
1015
+ const [revision, setRevision] = useState(0)
1016
+ useEffect(() => {
1017
+ const service = localeState.service
1018
+ if (service === undefined || typeof service.subscribe !== 'function') return undefined
1019
+ return service.subscribe(() => setRevision((value) => value + 1))
1020
+ }, [])
1021
+ // 必须 memo:translate 的身份变化会让所有 useCallback/useEffect 依赖它,
1022
+ // 每次渲染都重建会退化成不停重拉数据。
1023
+ return useMemo(() => makeTranslate(localeState.service, localeState.active), [revision])
1024
+ }
1025
+
1026
+ // ---------------------------------------------------------------- 注册
1027
+
1028
+ return {
1029
+ inject: ['slots', 'locale'],
1030
+ apply(ctx) {
1031
+ // 语言包:en / zh 各一份,其余语言沿 fallback 链回落到 en。
1032
+ const dicts = DICT
1033
+ for (const [localeId, dict] of Object.entries(dicts)) {
1034
+ ctx.effect(() => ctx.locale.register(LOCALE_NS, localeId, dict), `dsh-session-manager: locale ${localeId}`)
1035
+ }
1036
+ localeState.service = ctx.locale
1037
+ localeState.active = ctx.locale.getLocale?.().active ?? 'zh'
1038
+
1039
+ ctx.effect(() => {
1040
+ const dispose = ctx.locale.subscribe?.(() => {
1041
+ localeState.active = ctx.locale.getLocale?.().active ?? localeState.active
1042
+ })
1043
+ return () => {
1044
+ if (typeof dispose === 'function') dispose()
1045
+ }
1046
+ }, 'dsh-session-manager: locale tracking')
1047
+
1048
+ ctx.slots.inject('settings.section', () =>
1049
+ ctx.slots.register(
1050
+ {
1051
+ name: 'settings.section',
1052
+ id: SECTION_ID,
1053
+ order: 50,
1054
+ label: () => makeTranslate(ctx.locale, ctx.locale.getLocale?.().active ?? 'zh')('section.label'),
1055
+ },
1056
+ SessionManagerSection,
1057
+ ),
1058
+ )
1059
+
1060
+ // 导航图标按 id 派发,两处 id 必须逐字相同
1061
+ ctx.slots.inject('settings.section.icon', () =>
1062
+ ctx.slots.register({ name: 'settings.section.icon', id: SECTION_ID }, (props) =>
1063
+ h(TrashGlyph, { size: props && props.size ? props.size : 16 }),
1064
+ ),
1065
+ )
1066
+ },
1067
+ }
1068
+ },
1069
+ })