dsh-delete-session 0.2.6 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js CHANGED
@@ -1,2353 +1,2363 @@
1
- // dsh-delete-session - client half.
2
- //
3
- // Integration is entirely through the host's public slot contract - no menu
4
- // scraping, no React internals:
5
- //
6
- // * `sidebar.workspaces.session.menu.item` - two rows registered beside the
7
- // shipped pin/rename/fork/archive rows: "Select multiple" (order 409) and
8
- // "Delete session" (order 410, in the host's danger colour). Each entry
9
- // renders one `role="menuitem"` button through ui-primitives'
10
- // `MenuItemButton`, so it inherits the host styling and joins the menu's
11
- // own keyboard walk and focus return.
12
- // * `shell.overlay` - the confirmation dialog, rendered with the host's
13
- // `Modal` primitive instead of a hand-built backdrop.
14
- // * `plugins.row.config` - the plugin page card that decides whether a
15
- // delete asks first.
16
- //
17
- // The one surface with no usable slot is the multi-select checkbox on each
18
- // Session row: `sidebar.session.row.leading` is the *else* branch of the host's
19
- // `showStatus ? <SessionStatusDots/> : renderSlot(...)`, so it disappears the
20
- // moment a row is busy - exactly when a batch delete is most likely. Those
21
- // checkboxes therefore stay a DOM decoration over `[role="treeitem"]`, and row
22
- // identity comes from the host's own `data-row-key="session:<id>"` attribute
23
- // rather than from a walk up the React fiber tree.
24
- //
25
- // The module is a classic client bundle (client-modules protocol): it registers
26
- // a factory with `window.__ModuleLoader__` and returns apply().
27
- window.__ModuleLoader__.load({
28
- id: 'dsh-delete-session',
29
- factory: (require) => {
30
- const NS = 'dsh-delete-session'
31
- const react = require('react')
32
- const primitives = require('@deepseek-ai/dsh-client-ui-primitives')
33
-
34
- const { createElement: h, Fragment } = react
35
-
36
- const zh = {
37
- menu: '删除会话',
38
- multiSelect: '多选',
39
- title: '删除会话',
40
- descRecycle: '将把该会话及其全部对话记录(会话日志、工作区记账与统计)从列表中移除,并放进系统回收站。',
41
- descPermanent: '将永久删除该会话及其全部对话记录(会话日志、工作区记账与统计),此操作不可恢复。',
42
- cancel: '取消',
43
- confirm: '删除',
44
- deleting: '删除中…',
45
- done: '已删除会话',
46
- failed: '删除失败:',
47
- busy: '该会话正被 DSH 打开,删除未能完成;请稍后重试(通常几秒后即可),或重启 DSH 后再试。',
48
- notFound: '未找到该会话(可能已被删除)。',
49
- untitled: '未命名会话',
50
- cancelSelect: '取消',
51
- selectedCount: (n) => `已选 ${n} 个`,
52
- batchRunning: (done, total) => `正在删除 ${done}/${total}…`,
53
- moveSelected: '移动',
54
- batchMoving: (done, total) => `正在移动 ${done}/${total}…`,
55
- batchMoved: (ok, fail) => (fail > 0 ? `已移动 ${ok} 个 / ${fail} 个失败` : `已移动 ${ok} 个`),
56
- moveBadResult: (fields) => `移动结果缺少字段:${fields}`,
57
- deleteSelected: '删除',
58
- batchDone: (n) => `已删除 ${n} 个会话`,
59
- batchPartial: (ok, fail) => `已删除 ${ok} 个,${fail} 个失败`,
60
- batchFailed: '批量删除失败:',
61
- pageAsk: '删除时询问',
62
- pageRecycle: '删除至回收站',
63
- pageSyncChildren: '同时删除子会话',
64
- dropHint: '拖到这里删除',
65
- dropRelease: '松手删除「{name}」',
66
- dropFallback: '这个对话',
67
- starAsk: '⭐ 顺手留颗 Star,作者能高兴一整天',
68
- starCta: '行,给你一颗 Star',
69
- pageSyncChildrenOn: '删除对话时,把它派生的子代理会话一起删掉。',
70
- pageSyncChildrenOff: '不勾选时,删除前会列出子会话,由你勾选要删哪些。',
71
- childrenHint: '这个对话有 {n} 个子会话(子代理),勾选的会一起删除。',
72
- pageRecycleOn: '删除后放进系统回收站,可以还原。',
73
- pageRecycleOff: '删除后直接从硬盘移除,不可恢复。',
74
- pageHintAsk: '每次删除会话前都会弹出确认框。',
75
- pageHintAuto: '删除会话会直接执行,不再询问。',
76
- // The produced-file list only exists inside the dialog, so ask mode keeps a
77
- // delete dialog even when the confirmation above is turned off.
78
- pageHintAutoWithArtifacts: '删除会话仍会弹窗——产出文件要先列清单给你勾选。',
79
- pageSummaryAsk: '删除前询问',
80
- pageSummaryAuto: '直接删除',
81
- pageArtifactsOff: '不处理产出文件(保持当前行为)',
82
- pageHintArtifactsOff: '删除会话只清理对话记录,完全不碰工作目录里的文件。',
83
- pageHintArtifactsOn: '删除会话时还会处理这个对话在工作目录里碰过的文件。',
84
- pageArtifactsAuto: '产出文件默认全部进隔离夹',
85
- pageHintArtifactsAuto: '按下面的范围把匹配的文件全部移入隔离夹,不再询问。',
86
- pageHintArtifactsAsk: '删除会话时会列出文件清单,由你勾选。',
87
- pageScopeCreated: '仅新建的文件',
88
- pageScopeAll: '新建的和改过的文件',
89
- pageScopeCreatedHint: '只动这个对话自己创建的文件;它改过的既有文件一律不动。',
90
- pageScopeAllHint: '还会包含这个对话改写过的既有文件 —— 移走它们会改变工作目录里原有的内容。',
91
- pageSkipGit: '跳过 git 仓库内的文件',
92
- pageSkipGitOn: '只处理不在 git 仓库里的文件;仓库里的代码不会被搬走。',
93
- pageSkipGitOff: '仓库里的文件也会被搬进隔离夹 —— 删一个在项目里干过活的对话,可能把项目源码一起搬走。',
94
- pageSummaryArtifactsOff: '不处理产出文件',
95
- pageSummaryArtifactsAuto: '产出文件自动隔离',
96
- pageSummaryArtifactsAsk: '产出文件先询问',
97
- pageRootLabel: '隔离夹保存位置',
98
- pageRootPlaceholder: '留空则使用默认路径',
99
- pageRootBrowse: '选择文件夹…',
100
- pageRootOpen: '打开',
101
- rootOpened: '已在文件管理器中打开',
102
- rootOpenFailed: '打开失败:',
103
- pickerOpening: '已打开系统文件夹对话框,请在弹出的窗口里选择',
104
- pickerFailed: '选择文件夹失败:',
105
- pageRootReset: '用默认',
106
- pageRootDefaultHint: (path) => `当前使用默认路径:${path}`,
107
- pageRootCustomHint: '隔离夹会建在这个目录下,每次删除生成一个带时间戳的子目录',
108
- pickerTitle: '选择隔离夹保存位置',
109
- pickerLoading: '读取中…',
110
- pickerEmpty: '这个目录下没有子目录',
111
- pickerChoose: '选择此目录',
112
- pickerTruncated: '子目录太多,只列出前 500 个',
113
- pickerDefault: (path) => `默认路径:${path}`,
114
- rootSet: '保存位置已更新',
115
- artifactSection: '本对话产出的文件',
116
- artifactOpenFolder: '打开所在文件夹',
117
- artifactDeleteFile: '删除这个文件',
118
- fileDeleted: '文件已删除',
119
- fileRecycled: '文件已移入回收站',
120
- fileDeleteFailed: '删除文件失败:',
121
- revealFailed: '打开文件夹失败:',
122
- artifactLoading: '正在扫描…',
123
- artifactFailed: '扫描失败:',
124
- artifactNone: '没有需要处理的文件。',
125
- artifactCount: (created, modified) => `新建 ${created} 个 · 改过 ${modified} 个`,
126
- artifactAutoNote: (n) => `删除后将把 ${n} 个文件移入隔离夹`,
127
- // Auto mode does not scan, so it can state the outcome but not a count.
128
- artifactAutoOnly: '产出文件会自动全部移入隔离夹,这里不再逐个列出。',
129
- artifactRefused: (n) => `另有 ${n} 项已跳过`,
130
- artifactSelected: (n) => `已选 ${n} 个`,
131
- artifactMore: (n) => `另有 ${n} 个未列出`,
132
- artifactTruncated: '清单过长已截断,未列出的不会处理。',
133
- artifactScopeCreated: '范围:仅新建',
134
- artifactScopeAll: '范围:新建 + 改过',
135
- artifactModifiedWarn: '改过的既有文件(默认不选):',
136
- doneQuarantine: (n) => `已删除会话,${n} 个文件已移入隔离夹`,
137
- doneQuarantineFailed: (ok, fail) => `已删除会话,隔离 ${ok} 个、${fail} 个失败`,
138
- }
139
-
140
- const en = {
141
- menu: 'Delete session',
142
- multiSelect: 'Select multiple',
143
- title: 'Delete session',
144
- descRecycle: 'This removes the session and all of its conversation records (log, workspace accounting and statistics) from the list and puts them in the system trash.',
145
- descPermanent: 'This permanently deletes the session and all of its conversation records (log, workspace accounting and statistics). This cannot be undone.',
146
- cancel: 'Cancel',
147
- confirm: 'Delete',
148
- deleting: 'Deleting...',
149
- done: 'Session deleted',
150
- failed: 'Delete failed: ',
151
- busy: 'This session is currently open in DSH; the delete did not complete. Try again in a moment (usually a few seconds), or restart DSH and retry.',
152
- notFound: 'Session not found (it may already be deleted).',
153
- untitled: 'Untitled session',
154
- cancelSelect: 'Cancel',
155
- selectedCount: (n) => `${n} selected`,
156
- batchRunning: (done, total) => `Deleting ${done}/${total}...`,
157
- moveSelected: 'Move',
158
- batchMoving: (done, total) => `Moving ${done}/${total}...`,
159
- batchMoved: (ok, fail) => (fail > 0 ? `Moved ${ok}, ${fail} failed` : `Moved ${ok}`),
160
- moveBadResult: (fields) => `Move result is missing fields: ${fields}`,
161
- deleteSelected: 'Delete',
162
- batchDone: (n) => `Deleted ${n} session(s)`,
163
- batchPartial: (ok, fail) => `Deleted ${ok}, ${fail} failed`,
164
- batchFailed: 'Batch delete failed: ',
165
- pageAsk: 'Ask before deleting',
166
- pageRecycle: 'Delete to the Recycle Bin',
167
- pageSyncChildren: 'Delete child sessions too',
168
- dropHint: 'Drop here to delete',
169
- dropRelease: 'Release to delete \'{name}\'',
170
- dropFallback: 'this conversation',
171
- starAsk: '⭐ A star would make the author\'s day',
172
- starCta: 'Fine — have one',
173
- pageSyncChildrenOn: 'A delete also removes the subagent sessions it spawned.',
174
- pageSyncChildrenOff: 'When off, the dialog lists the child sessions and you tick the ones to delete.',
175
- childrenHint: 'This conversation has {n} child sessions (subagents). Ticked ones are deleted too.',
176
- pageRecycleOn: 'The session goes to the system trash and can be restored.',
177
- pageRecycleOff: 'The session is removed from the disk right away and cannot be restored.',
178
- pageHintAsk: 'Show a confirmation dialog before every session delete.',
179
- pageHintAuto: 'Delete the session right away without asking.',
180
- pageHintAutoWithArtifacts: 'A delete still opens a dialog, because the produced-file list has to be shown first.',
181
- pageSummaryAsk: 'Ask before deleting',
182
- pageSummaryAuto: 'Delete without asking',
183
- pageArtifactsOff: 'Leave produced files alone (current behaviour)',
184
- pageHintArtifactsOff: 'Deleting a session clears its record only and never touches files in the working directory.',
185
- pageHintArtifactsOn: 'Deleting a session also handles the files this conversation touched in its working directory.',
186
- pageArtifactsAuto: 'Send produced files straight to quarantine',
187
- pageHintArtifactsAuto: 'Every file in the scope below moves to quarantine without asking.',
188
- pageHintArtifactsAsk: 'Deleting a session lists the files and lets you tick what to move.',
189
- pageScopeCreated: 'Only files it created',
190
- pageScopeAll: 'Created and changed files',
191
- pageScopeCreatedHint: 'Touches only files this conversation created; files it merely edited are never moved.',
192
- pageScopeAllHint: 'Also includes pre-existing files this conversation rewrote — moving them changes what was already in the working directory.',
193
- pageSkipGit: 'Skip files inside a git repository',
194
- pageSkipGitOn: 'Only files outside git repositories are handled; code inside a repository is never moved.',
195
- pageSkipGitOff: 'Repository files move into quarantine too — deleting a conversation that worked in a project can carry the project source away.',
196
- pageSummaryArtifactsOff: 'Produced files left alone',
197
- pageSummaryArtifactsAuto: 'Produced files auto-quarantined',
198
- pageSummaryArtifactsAsk: 'Produced files ask first',
199
- pageRootLabel: 'Quarantine folder location',
200
- pageRootPlaceholder: 'Leave empty to use the default path',
201
- pageRootBrowse: 'Choose folder…',
202
- pageRootOpen: 'Open',
203
- rootOpened: 'Opened in the file manager',
204
- rootOpenFailed: 'Could not open: ',
205
- pickerOpening: 'The system folder dialog is open; pick a folder in that window',
206
- pickerFailed: 'Could not open the folder picker: ',
207
- pageRootReset: 'Use default',
208
- pageRootDefaultHint: (path) => `Using the default path: ${path}`,
209
- pageRootCustomHint: 'The quarantine folder is created here, one timestamped subfolder per delete',
210
- pickerTitle: 'Choose where quarantined files go',
211
- pickerLoading: 'Reading…',
212
- pickerEmpty: 'No subfolders here',
213
- pickerChoose: 'Use this folder',
214
- pickerTruncated: 'Too many subfolders: only the first 500 are listed',
215
- pickerDefault: (path) => `Default path: ${path}`,
216
- rootSet: 'Location updated',
217
- artifactSection: 'Files this conversation produced',
218
- artifactOpenFolder: 'Open containing folder',
219
- artifactDeleteFile: 'Delete this file',
220
- fileDeleted: 'File deleted',
221
- fileRecycled: 'File moved to the recycle bin',
222
- fileDeleteFailed: 'Could not delete the file: ',
223
- revealFailed: 'Could not open the folder: ',
224
- artifactLoading: 'Scanning...',
225
- artifactFailed: 'Scan failed: ',
226
- artifactNone: 'Nothing to handle.',
227
- artifactCount: (created, modified) => `${created} created · ${modified} changed`,
228
- artifactAutoNote: (n) => `${n} file(s) will move to quarantine on delete`,
229
- artifactAutoOnly: 'Produced files move to quarantine automatically; they are not listed here.',
230
- artifactRefused: (n) => `${n} more were skipped`,
231
- artifactSelected: (n) => `${n} selected`,
232
- artifactMore: (n) => `${n} more not listed`,
233
- artifactTruncated: 'The list was truncated; anything unlisted is left alone.',
234
- artifactScopeCreated: 'Scope: created only',
235
- artifactScopeAll: 'Scope: created + changed',
236
- artifactModifiedWarn: 'Pre-existing files it changed (unticked by default):',
237
- doneQuarantine: (n) => `Session deleted, ${n} file(s) moved to quarantine`,
238
- doneQuarantineFailed: (ok, fail) => `Session deleted, ${ok} quarantined and ${fail} failed`,
239
- }
240
-
241
- let sessionsSvc = null
242
- let localeSvc = null
243
-
244
- function browserLang() {
245
- if (typeof navigator === 'undefined') return 'zh'
246
- for (const tag of (navigator.languages || []).concat([navigator.language])) {
247
- const primary = String(tag || '').toLowerCase().split('-')[0]
248
- if (primary === 'zh' || primary === 'en') return primary
249
- }
250
- return 'zh'
251
- }
252
-
253
- // The DOM decoration layer (row checkboxes, batch bar, toast) is not a slot
254
- // occupant, so it has no injected `t`; it uses the built-in dictionaries and
255
- // honours the registered `locale` namespace when the host provides one.
256
- // Slot components receive the host-injected `t` and use that instead.
257
- function t(key, a, b) {
258
- if (localeSvc && typeof localeSvc.translate === 'function') {
259
- try {
260
- const text = localeSvc.translate(NS, key)
261
- if (typeof text === 'string' && text !== key) return text
262
- } catch {
263
- // fall back to the built-in dictionaries
264
- }
265
- }
266
- const value = (browserLang() === 'en' ? en : zh)[key]
267
- return typeof value === 'function' ? value(a, b) : value || key
268
- }
269
-
270
- /**
271
- * Wrap a host-injected `t` so function-valued entries render their value.
272
- *
273
- * The locale contract leaves a function entry untouched: `translate(key, a, b)`
274
- * returns the arrow function itself, and the caller is the one that invokes it.
275
- * Using the injected `t` directly therefore printed the function's own source
276
- * in the dialog ("(created, modified) => ...") instead of the numbers.
277
- */
278
- function localizedTranslator(injected) {
279
- const raw = typeof injected === 'function' ? injected : t
280
- if (raw.__dsdelLocalized === true) return raw
281
- const wrapped = (key, a, b) => {
282
- // Our own dictionary answers first, and it is resolved HERE rather than
283
- // through the host. `dsh-client-locale` interpolates whatever it finds as
284
- // soon as params are present - it calls `template.replace(...)` - while
285
- // most of these entries are functions. Handing it params made the host
286
- // throw "template.replace is not a function", and the slot boundary turned
287
- // that into an empty `data-slot-error` anchor: the bar vanished, Cancel
288
- // and all. Calling it without params is no better: the host (and this
289
- // module's own `t`) invoke function entries with no arguments, which
290
- // produces "已选 undefined 个".
291
- const dictionary = browserLang() === 'en' ? en : zh
292
- const local = dictionary[key]
293
- if (local !== undefined) {
294
- if (typeof local === 'function') return local(a, b)
295
- if (typeof local === 'string' && local.includes('{') && a !== undefined) {
296
- const params = a !== null && typeof a === 'object'
297
- ? a
298
- : { n: a, done: a, total: b, ok: a, fail: b, path: a }
299
- return local.replace(/\{(\w+)\}/g, (match, name) => (
300
- params[name] === undefined ? match : String(params[name])
301
- ))
302
- }
303
- return local
304
- }
305
- // A key this plugin does not ship: let the host answer.
306
- const value = raw(key)
307
- return typeof value === 'function' ? value(a, b) : (value === undefined || value === null ? key : value)
308
- }
309
- wrapped.__dsdelLocalized = true
310
- return wrapped
311
- }
312
-
313
- // --- state -----------------------------------------------------------------
314
- // One module-level store shared by the slot components and the DOM layer.
315
- // Components read it through `useSnapshot`, so each stays a plain function of
316
- // the store with no local state - which also keeps it drivable from the
317
- // offline test without a React renderer.
318
-
319
- const state = {
320
- /** { sessionId, title, busy, error, skip } while a confirmation dialog is up. */
321
- dialog: null,
322
- selecting: false,
323
- selected: new Set(),
324
- /** Rows hidden optimistically while their delete request is in flight. */
325
- pending: new Set(),
326
- /** { total, done, failed } while a batch delete runs, else null. */
327
- batch: null,
328
- /** Folder-picker state while it is open, else null. */
329
- picker: null,
330
- /** The host's default quarantine root, fetched once so the card can name it. */
331
- defaultRoot: null,
332
- /**
333
- * The session being dragged over the footer, or null. `over` arms the drop:
334
- * the bar only says "松手删除" once the pointer is actually on it.
335
- */
336
- drag: null,
337
- }
338
-
339
- const listeners = new Set()
340
-
341
- function buildSnapshot() {
342
- return {
343
- dialog: state.dialog,
344
- selecting: state.selecting,
345
- selected: state.selected,
346
- pending: state.pending,
347
- batch: state.batch,
348
- picker: state.picker,
349
- defaultRoot: state.defaultRoot,
350
- drag: state.drag,
351
- selectedCount: state.selected.size,
352
- }
353
- }
354
-
355
- // `useSyncExternalStore` needs a value that is stable between notifications.
356
- let snapshot = buildSnapshot()
357
-
358
- function getSnapshot() {
359
- return snapshot
360
- }
361
-
362
- function subscribe(listener) {
363
- listeners.add(listener)
364
- return () => { listeners.delete(listener) }
365
- }
366
-
367
- function publish() {
368
- snapshot = buildSnapshot()
369
- for (const listener of listeners) {
370
- try { listener() } catch { /* a subscriber must not break the mutation */ }
371
- }
372
- scheduleDecorate()
373
- }
374
-
375
- // `useSyncExternalStore` where the host's React has it (React 18+), otherwise
376
- // a subscribe/effect pair. Chosen once at module scope, so no hook is called
377
- // conditionally during a render.
378
- const useSnapshot = typeof react.useSyncExternalStore === 'function'
379
- ? () => react.useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
380
- : () => {
381
- const [value, setValue] = react.useState(getSnapshot)
382
- react.useEffect(() => subscribe(() => setValue(getSnapshot())), [])
383
- return value
384
- }
385
-
386
- // --- confirmation preference ----------------------------------------------
387
-
388
- // Once the user opts out ("删除时询问" unticked - either in the plugin page or
389
- // via the dialog's "don't ask again") the confirmation dialog is skipped and
390
- // the menu item deletes directly. The plugin page's checkbox and the dialog
391
- // read the same key, and a subscription keeps the card in step when either
392
- // one flips it.
393
- const SKIP_KEY = 'dsh-delete-session:skip-confirm'
394
- const skipListeners = new Set()
395
-
396
- function skipConfirm() {
397
- try { return localStorage.getItem(SKIP_KEY) === '1' } catch { return false }
398
- }
399
-
400
- function setSkipConfirm(value) {
401
- const skip = value === true
402
- try {
403
- if (skip) localStorage.setItem(SKIP_KEY, '1')
404
- else localStorage.removeItem(SKIP_KEY)
405
- } catch { /* private mode: ignore */ }
406
- for (const listener of skipListeners) {
407
- try { listener() } catch { /* a subscriber must not break the toggle */ }
408
- }
409
- }
410
-
411
- function subscribeSkip(listener) {
412
- skipListeners.add(listener)
413
- return () => { skipListeners.delete(listener) }
414
- }
415
-
416
- // --- artifact preferences --------------------------------------------------
417
- // The produced-files feature ships OFF: `OFF_KEY` is ticked unless the user
418
- // explicitly clears it, so an existing install keeps behaving exactly as it
419
- // did before the feature existed. When it is on, `AUTO_KEY` decides whether
420
- // the dialog asks, and `SCOPE_KEY` decides what the candidate set is.
421
-
422
- const OFF_KEY = 'dsh-delete-session:artifacts-off'
423
- const AUTO_KEY = 'dsh-delete-session:artifacts-auto'
424
- const SCOPE_KEY = 'dsh-delete-session:artifact-scope'
425
- /** Where the timestamped quarantine folder is created. Empty means the DSH home. */
426
- const ROOT_KEY = 'dsh-delete-session:quarantine-root'
427
- /** Skip files inside a git working tree when quarantining. */
428
- const SKIP_GIT_KEY = 'dsh-delete-session:skip-git'
429
- /** Whether a delete goes to the system trash instead of vanishing. */
430
- const RECYCLE_KEY = 'dsh-delete-session:recycle'
431
- /** Whether a delete takes the subagent sessions with it, without asking. */
432
- const SYNC_CHILDREN_KEY = 'dsh-delete-session:sync-children'
433
- /** How many artifact rows the dialog lists before collapsing the rest. */
434
- const ARTIFACT_ROWS_SHOWN = 40
435
- const prefListeners = new Set()
436
-
437
- function readPref(key, fallback) {
438
- try {
439
- const value = localStorage.getItem(key)
440
- return value === null ? fallback : value
441
- } catch {
442
- return fallback
443
- }
444
- }
445
-
446
- function writePref(key, value) {
447
- try {
448
- if (value === null) localStorage.removeItem(key)
449
- else localStorage.setItem(key, value)
450
- } catch {
451
- // private mode: the preference simply does not persist
452
- }
453
- for (const listener of prefListeners) {
454
- try { listener() } catch { /* a subscriber must not break the toggle */ }
455
- }
456
- }
457
-
458
- function subscribePrefs(listener) {
459
- prefListeners.add(listener)
460
- return () => { prefListeners.delete(listener) }
461
- }
462
-
463
- /** Whether the produced-files feature is off. Off unless explicitly enabled. */
464
- function artifactsOff() {
465
- return readPref(OFF_KEY, '1') !== '0'
466
- }
467
-
468
- function setArtifactsOff(off) {
469
- writePref(OFF_KEY, off ? null : '0')
470
- }
471
-
472
- /** Whether the whole candidate set moves without asking. */
473
- function artifactsAuto() {
474
- return readPref(AUTO_KEY, '0') === '1'
475
- }
476
-
477
- function setArtifactsAuto(auto) {
478
- writePref(AUTO_KEY, auto ? '1' : null)
479
- }
480
-
481
- /** Candidate scope: files this session created, or those plus the ones it changed. */
482
- function artifactScope() {
483
- return readPref(SCOPE_KEY, 'created') === 'all' ? 'all' : 'created'
484
- }
485
-
486
- function setArtifactScope(scope) {
487
- writePref(SCOPE_KEY, scope === 'all' ? 'all' : 'created')
488
- }
489
-
490
- /**
491
- * Skip files that live inside a git working tree. On by default: a session
492
- * started in a repository produces that repository's source, and moving it
493
- * out from under the project is never what "clean up the files this chat
494
- * created" means.
495
- */
496
- function skipGitRepos() {
497
- return readPref(SKIP_GIT_KEY, '1') === '1'
498
- }
499
-
500
- function setSkipGitRepos(skip) {
501
- writePref(SKIP_GIT_KEY, skip ? null : '0')
502
- }
503
-
504
- /**
505
- * Send the session to the system trash rather than removing it outright.
506
- * On by default: a wrong click should be undoable unless the user said otherwise.
507
- */
508
- function recycleSession() {
509
- return readPref(RECYCLE_KEY, '1') === '1'
510
- }
511
-
512
- function setRecycleSession(on) {
513
- writePref(RECYCLE_KEY, on ? null : '0')
514
- }
515
-
516
- /**
517
- * Take the child sessions along without asking. Off by default: a subagent is
518
- * a conversation of its own, so it is offered rather than swept up.
519
- */
520
- function syncChildren() {
521
- return readPref(SYNC_CHILDREN_KEY, '1') !== '0'
522
- }
523
-
524
- function setSyncChildren(on) {
525
- // "Off" is written as '0' rather than cleared: the default is now on, so a
526
- // removed key would read back as on again.
527
- writePref(SYNC_CHILDREN_KEY, on ? '1' : '0')
528
- }
529
-
530
- /** The chosen quarantine root, or '' for "use the host default". */
531
- function quarantineRoot() {
532
- return readPref(ROOT_KEY, '')
533
- }
534
-
535
- function setQuarantineRoot(value) {
536
- writePref(ROOT_KEY, typeof value === 'string' && value.trim() !== '' ? value.trim() : null)
537
- }
538
-
539
- // --- host calls ------------------------------------------------------------
540
-
541
- /** The read-only artifact scan the dialog renders. */
542
- function postArtifacts(sessionId) {
543
- const root = quarantineRoot()
544
- const payload = root === '' ? { sessionId } : { sessionId, root }
545
- payload.skipGit = skipGitRepos()
546
- return fetch('/dsh-delete-session/artifacts', {
547
- method: 'POST',
548
- headers: { 'content-type': 'application/json' },
549
- body: JSON.stringify(payload),
550
- }).then(async (res) => {
551
- let data = {}
552
- try { data = await res.json() } catch { /* keep {} */ }
553
- if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
554
- return data
555
- })
556
- }
557
-
558
- /** One directory listing for the folder picker. */
559
- function postBrowse(target) {
560
- return fetch('/dsh-delete-session/browse', {
561
- method: 'POST',
562
- headers: { 'content-type': 'application/json' },
563
- body: JSON.stringify(target === undefined || target === '' ? {} : { path: target }),
564
- }).then(async (res) => {
565
- let data = {}
566
- try { data = await res.json() } catch { /* keep {} */ }
567
- if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
568
- return data
569
- })
570
- }
571
-
572
- /**
573
- * Ask the host to raise the real Windows folder dialog. The request stays open
574
- * while the user browses, so `code` is carried on failures: `unsupported`
575
- * means this platform has no native dialog and the in-page picker should run.
576
- */
577
- function postPick() {
578
- return fetch('/dsh-delete-session/pick', {
579
- method: 'POST',
580
- headers: { 'content-type': 'application/json' },
581
- body: JSON.stringify({}),
582
- }).then(async (res) => {
583
- let data = {}
584
- try { data = await res.json() } catch { /* keep {} */ }
585
- if (!res.ok || !data.ok) {
586
- const error = new Error((data && data.error) || `HTTP ${res.status}`)
587
- error.code = data && data.code
588
- throw error
589
- }
590
- return data
591
- })
592
- }
593
-
594
- /** Ask the host to show a directory in the OS file manager. */
595
- function postReveal(target) {
596
- return fetch('/dsh-delete-session/reveal', {
597
- method: 'POST',
598
- headers: { 'content-type': 'application/json' },
599
- body: JSON.stringify({ path: target }),
600
- }).then(async (res) => {
601
- let data = {}
602
- try { data = await res.json() } catch { /* keep {} */ }
603
- if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
604
- return data
605
- })
606
- }
607
-
608
- /** Drop one row from the dialog after its file left the disk. */
609
- function forgetFile(sessionId, target) {
610
- const dialog = state.dialog
611
- if (dialog === null || dialog.sessionId !== sessionId) return
612
- const artifacts = dialog.artifacts
613
- if (artifacts === null || artifacts.plan === null) return
614
- artifacts.selected.delete(target)
615
- const keep = (row) => row.path !== target
616
- artifacts.plan = {
617
- ...artifacts.plan,
618
- created: (artifacts.plan.created || []).filter(keep),
619
- modified: (artifacts.plan.modified || []).filter(keep),
620
- }
621
- publish()
622
- }
623
-
624
- /** Delete one produced file, then drop its row. */
625
- function deleteOneFile(sessionId, target) {
626
- const recycle = recycleSession()
627
- postDeleteFile(sessionId, target, recycle).then((data) => {
628
- forgetFile(sessionId, target)
629
- toast(t(data && data.recycled === true ? 'fileRecycled' : 'fileDeleted'))
630
- }).catch((reason) => {
631
- toast(t('fileDeleteFailed') + String((reason && reason.message) || reason), true)
632
- })
633
- }
634
-
635
- /**
636
- * Delete one produced file. The recycle choice is the same preference that
637
- * governs a conversation delete, so the two never disagree.
638
- */
639
- function postDeleteFile(sessionId, target, recycle) {
640
- return fetch('/dsh-delete-session/delete-file', {
641
- method: 'POST',
642
- headers: { 'content-type': 'application/json' },
643
- body: JSON.stringify({ sessionId, path: target, recycle }),
644
- }).then(async (res) => {
645
- let data = {}
646
- try { data = await res.json() } catch { /* keep {} */ }
647
- if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
648
- return data
649
- })
650
- }
651
-
652
- /**
653
- * Show one produced file's folder. The host validates that the path is a
654
- * directory; the browser has no path module, so the parent is taken with a
655
- * plain last-separator split — Windows separators included.
656
- */
657
- function revealParent(filePath) {
658
- const text = String(filePath === null || filePath === undefined ? '' : filePath).replace(/[\\/]+$/, '')
659
- const cut = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
660
- const parent = cut > 0 ? text.slice(0, cut) : text
661
- if (parent === '') return
662
- postReveal(parent).catch((reason) => {
663
- toast(t('revealFailed') + String((reason && reason.message) || reason), true)
664
- })
665
- }
666
-
667
- /** Show the quarantine folder the current settings would write to. */
668
- function openQuarantineRoot(target) {
669
- if (typeof target !== 'string' || target === '') return
670
- postReveal(target)
671
- .then(() => toast(t('rootOpened')))
672
- .catch((reason) => toast(t('rootOpenFailed') + String((reason && reason.message) || reason), true))
673
- }
674
-
675
- function postDelete(sessionId, quarantine, childSessionIds) {
676
- const root = quarantineRoot()
677
- const payload = quarantine === undefined ? { sessionId } : { sessionId, quarantine }
678
- if (root !== '') payload.root = root
679
- // Subagent sessions are sessions of their own, so they travel as a list the
680
- // host can verify rather than something it has to discover.
681
- if (Array.isArray(childSessionIds) && childSessionIds.length > 0) {
682
- payload.childSessionIds = childSessionIds
683
- }
684
- // Whether the files go to the system trash is a per-delete choice, so it
685
- // travels with the request rather than being read from the host config.
686
- payload.recycle = recycleSession()
687
- return fetch('/dsh-delete-session/delete', {
688
- method: 'POST',
689
- headers: { 'content-type': 'application/json' },
690
- body: JSON.stringify(payload),
691
- }).then(async (res) => {
692
- let data = {}
693
- try { data = await res.json() } catch { /* keep {} */ }
694
- if (!res.ok || !data.ok) {
695
- const code = data && data.code
696
- const message = code === 'busy'
697
- ? t('busy')
698
- : code === 'not-found'
699
- ? t('notFound')
700
- : (data && data.error) || `HTTP ${res.status}`
701
- throw new Error(message)
702
- }
703
- return data
704
- })
705
- }
706
-
707
- function refreshList() {
708
- const svc = sessionsSvc
709
- if (svc) {
710
- try {
711
- if (typeof svc.refresh === 'function') { svc.refresh(); return }
712
- if (typeof svc.refreshList === 'function') { svc.refreshList(); return }
713
- } catch {
714
- // fall through to reload
715
- }
716
- }
717
- try { window.location.reload() } catch { /* ignore */ }
718
- }
719
-
720
- // Deleting the session the main view is showing leaves the app to restore a
721
- // stale neighbour (an unavailable Agent Team row with a disabled composer),
722
- // which reads as "the delete did not work". Open a fresh session instead.
723
- function deletedVariants(id) {
724
- return id.startsWith('session-') ? [id, id.slice('session-'.length)] : [id, `session-${id}`]
725
- }
726
-
727
- function leaveIfCurrent(id) {
728
- let current = null
729
- try {
730
- const raw = localStorage.getItem('dsh.sessions.current')
731
- current = raw ? (JSON.parse(raw) || {}).sessionId || null : null
732
- } catch {
733
- return
734
- }
735
- if (!current || !deletedVariants(id).includes(current)) return
736
- const btn = document.querySelector(
737
- 'button[class*="newSession"], button[aria-label*="New session" i], button[aria-label*="新会话"]',
738
- )
739
- if (btn) {
740
- try {
741
- btn.click()
742
- return
743
- } catch {
744
- // fall through to the state reset
745
- }
746
- }
747
- try {
748
- localStorage.removeItem('dsh.sessions.current')
749
- window.location.reload()
750
- } catch {
751
- // ignore
752
- }
753
- }
754
-
755
- // --- styles ----------------------------------------------------------------
756
- // Only what the DOM decoration layer owns. The confirmation dialog is the
757
- // host's `Modal`, so it brings no backdrop CSS of its own.
758
-
759
- const CSS = [
760
- '.dsdel-toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);z-index:2147483601;background:var(--dsw-alias-bg-overlay,var(--dsw-alias-bg-layer-1,#2b2b2b));color:var(--dsw-alias-label-primary,#fff);border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.3));padding:9px 16px;border-radius:10px;font-size:12.5px;line-height:18px;box-shadow:0 10px 28px rgba(0,0,0,.24);max-width:min(92vw,460px);cursor:pointer;animation:dsdel-toast-in .16s cubic-bezier(.2,.8,.3,1)}',
761
- '@keyframes dsdel-toast-in{from{opacity:0;transform:translate(-50%,6px)}to{opacity:1;transform:translate(-50%,0)}}',
762
- '@media (prefers-reduced-motion:reduce){.dsdel-toast{animation:none}.dsdel-field{transition:none}}',
763
- '.dsdel-check{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;border:1.5px solid var(--dsw-alias-border-l3,rgba(128,128,128,.5));background:transparent;flex:none;margin-right:8px;box-sizing:border-box;cursor:pointer}',
764
- '.dsdel-check-on{background:var(--dsw-alias-state-business-primary,#4c6ef5);border-color:var(--dsw-alias-state-business-primary,#4c6ef5)}',
765
- '.dsdel-check-on::after{content:"";width:9px;height:5px;border-left:2px solid #fff;border-bottom:2px solid #fff;transform:rotate(-45deg) translateY(-1px)}',
766
- // 乐观删除:行先隐藏,失败时随 decorate 恢复
767
- '.dsdel-row-pending{display:none!important}',
768
- '.dsdel-bar{display:flex;align-items:center;gap:8px;width:100%;min-width:0;padding:6px 8px;box-sizing:border-box;font-size:13px}',
769
- // The sidebar foot stacks three things: the footer-action row, the usage
770
- // card and the account row. While a selection runs only the action row
771
- // stays, so the bar sits where the account row used to end the sidebar.
772
- 'body.dsdel-selecting [class*="_footArea"] > *:not([class*="_footerActions"]){display:none}',
773
- // The other footer buttons are named POSITIVELY, by the attributes their
774
- // plugins put on them, and never by "everything except the bar": the bar
775
- // turned out not to be a direct child of the slot container, so an
776
- // exclusion rule silently hid the bar together with its Cancel button.
777
- 'body.dsdel-selecting [data-slot="sidebar.footer.action"] > [data-dsh-plugin]{display:none}',
778
- 'body.dsdel-selecting [data-slot="sidebar.footer.action"] > [class*="_entryRow"]{display:none}',
779
- '.dsdel-drop{border:1px dashed var(--dsw-alias-border-l2,rgba(128,128,128,.4));border-radius:8px;color:var(--dsw-alias-label-secondary,inherit)}',
780
- '.dsdel-drop-over{border-color:var(--dsw-alias-state-error-primary,#e5484d);border-style:solid;background:rgba(229,72,77,.10);color:var(--dsw-alias-state-error-primary,#e5484d)}',
781
- '.dsdel-drop-icon{display:inline-flex;flex:0 0 auto;align-items:center}',
782
- '.dsdel-drop-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
783
- '.dsdel-bar-count{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dsw-alias-label-secondary,inherit)}',
784
- '.dsdel-bar-btn{flex:0 0 auto;white-space:nowrap;appearance:none;min-height:30px;padding:0 12px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.4));background:var(--dsw-alias-fill-elevated,rgba(128,128,128,.08));color:var(--dsw-alias-label-primary,inherit);border-radius:8px;font-size:13px;cursor:pointer}',
785
- '.dsdel-bar-btn:focus-visible{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
786
- '.dsdel-bar-btn:disabled{opacity:.5;cursor:default}',
787
- '.dsdel-bar-danger{border-color:var(--dsw-alias-state-error-primary,#e5484d);background:var(--dsw-alias-state-error-primary,#e5484d);color:#fff}',
788
- // One token layer for every surface this plugin draws. Everything below
789
- // reads these rather than repeating a fallback per rule: the host theme then
790
- // reaches the whole plugin through one block, which is the point of exposing
791
- // tokens at all.
792
- '.dsdel-page,.dsdel-modal,.dsdel-bar{--dsdel-bg:var(--dsw-alias-fill-elevated,rgba(127,127,127,.06));--dsdel-bg-hover:var(--dsw-alias-fill-hover,rgba(127,127,127,.10));--dsdel-border:var(--dsw-alias-border-l2,rgba(127,127,127,.28));--dsdel-label:var(--dsw-alias-label-primary,inherit);--dsdel-label-dim:var(--dsw-alias-label-secondary,#666);--dsdel-label-faint:var(--dsw-alias-label-tertiary,#888);--dsdel-danger:var(--dsw-alias-state-error-primary,#e5484d);--dsdel-radius:10px;--dsdel-radius-sm:8px;--dsdel-ring:color-mix(in srgb,var(--dsw-alias-brand-primary,#4c8dff) 45%,transparent);--dsdel-shadow:0 1px 2px rgba(0,0,0,.04)}',
793
- '.dsdel-page{display:flex;flex-direction:column;gap:8px}',
794
- // Each switch and its explanation read as one block, so a card with eight
795
- // controls stops looking like one long column of tick boxes.
796
- '.dsdel-field{display:flex;flex-direction:column;gap:2px;padding:10px 12px;border:1px solid var(--dsdel-border);border-radius:var(--dsdel-radius);background:var(--dsdel-bg);box-shadow:var(--dsdel-shadow);transition:background .12s ease,border-color .12s ease}',
797
- '.dsdel-field:hover{background:var(--dsdel-bg-hover)}',
798
- '.dsdel-field:focus-within{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
799
- '.dsdel-page-hint{margin:0;color:var(--dsdel-label-faint);font-size:12.5px;line-height:19px;letter-spacing:.01em}',
800
- // One produced file per row: tick on the left, path in the middle, a folder
801
- // button on the right. The button sits outside the label so a click opens
802
- // the folder instead of toggling the tick.
803
- '.dsdel-file-row{display:flex;align-items:center;gap:8px;padding:4px 6px;border-radius:var(--dsdel-radius-sm);transition:background .12s ease}',
804
- '.dsdel-file-row:hover{background:var(--dsdel-bg-hover)}',
805
- '.dsdel-file-label{display:flex;align-items:center;gap:8px;flex:1;min-width:0;cursor:pointer}',
806
- '.dsdel-file-path{flex:1;min-width:0;word-break:break-all;font-size:13px;line-height:20px;color:var(--dsdel-label)}',
807
- '.dsdel-file-open{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:26px;height:26px;padding:0;border:1px solid transparent;border-radius:var(--dsdel-radius-sm);background:transparent;color:var(--dsdel-label-dim);cursor:pointer;transition:background .12s ease,color .12s ease,border-color .12s ease}',
808
- '.dsdel-file-open:hover{background:var(--dsdel-bg);border-color:var(--dsdel-border);color:var(--dsdel-label)}',
809
- '.dsdel-file-open:focus-visible{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
810
- '.dsdel-file-remove:hover{background:color-mix(in srgb,var(--dsdel-danger) 12%,transparent);border-color:color-mix(in srgb,var(--dsdel-danger) 40%,transparent);color:var(--dsdel-danger)}',
811
- '.dsdel-star{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex-wrap:wrap;font-size:12px;color:var(--dsw-alias-label-tertiary,#8b93a1);padding:2px 2px 0;}',
812
- '.dsdel-star-link{color:var(--dsw-alias-brand-primary,#4d76e6);text-decoration:underline;}',
813
- '.dsdel-root-input{flex:1 1 220px;min-width:160px;min-height:30px;padding:0 10px;border:1px solid var(--dsw-alias-border-secondary,#d0d0d0);border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:13px}',
814
- '.dsdel-picker-path{margin:0 0 8px;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,#666);word-break:break-all}',
815
- // A wider confirmation dialog: the class reaches it when `Modal` forwards
816
- // `className`, and the `:has()` rule catches the host-owned container when
817
- // it does not. Both are harmless if the other one is the one that applies.
818
- '.dsdel-dialog-wide{width:min(46vw,860px)!important;max-width:min(46vw,860px)!important;min-height:min(240px,88vh)!important;max-height:88vh!important;display:flex;flex-direction:column;overflow:hidden}',
819
- '.dsdel-dialog-wide > :first-child{flex:1 1 auto;min-height:0;overflow:auto}',
820
- '.dsdel-dialog-wide > :last-child{flex:0 0 auto;margin-top:auto}',
821
- '.dsdel-artifacts{overflow:auto;overscroll-behavior:contain;padding-right:2px}',
822
- '[role="dialog"]:has(.dsdel-file-row),[aria-modal="true"]:has(.dsdel-file-row){width:min(46vw,860px);max-width:min(46vw,860px);min-height:min(240px,88vh);max-height:88vh}',
823
- '.dsdel-picker-list{display:flex;flex-direction:column;gap:2px;max-height:280px;overflow:auto;margin:0 0 8px}',
824
- '.dsdel-picker-row{appearance:none;text-align:left;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:13px;cursor:pointer}',
825
- '.dsdel-picker-row:hover{background:var(--dsw-alias-fill-secondary,rgba(127,127,127,0.12))}',
826
- '.dsdel-modal-text{margin:0;font-size:13px;line-height:1.6;color:var(--dsw-alias-label-secondary,#666);word-break:break-all}',
827
- '.dsdel-modal-meta{margin:0 0 8px;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-tertiary,#888);word-break:break-all}',
828
- '.dsdel-modal-error{margin:8px 0 0;font-size:12px;line-height:16px;color:var(--dsw-alias-state-error-primary,#e5484d)}',
829
- // ui-primitives' `Button` has no danger variant (the host styles its own
830
- // destructive buttons with a package-local CSS-module class), so the
831
- // confirm button carries this class instead.
832
- '.dsdel-danger-btn{border-color:var(--dsw-alias-state-error-primary,#e5484d)!important;background:var(--dsw-alias-state-error-primary,#e5484d)!important;color:#fff!important}',
833
- '.dsdel-danger-btn:disabled{opacity:.5}',
834
- ].join('')
835
-
836
- function ensureStyle() {
837
- if (typeof document === 'undefined') return
838
- const existing = document.querySelector('style[data-dsh-delete-session]')
839
- if (existing !== null) {
840
- // This tag outlives the module instance: when a newer build re-executes in
841
- // the same document, bailing out here would keep the old stylesheet and
842
- // pair it with the new markup. Rewriting it keeps the two in step.
843
- if (existing.textContent !== CSS) existing.textContent = CSS
844
- return
845
- }
846
- const style = document.createElement('style')
847
- style.dataset.dshDeleteSession = '1'
848
- style.textContent = CSS
849
- document.head.appendChild(style)
850
- }
851
-
852
- // --- feedback --------------------------------------------------------------
853
-
854
- function toast(text, isError) {
855
- if (typeof document === 'undefined' || !document.body) return
856
- const el = document.createElement('div')
857
- el.className = 'dsdel-toast'
858
- el.setAttribute('role', 'status')
859
- el.textContent = text
860
- if (isError) {
861
- el.style.background = '#4A1D1D'
862
- el.style.color = '#FFD9D9'
863
- }
864
- document.body.appendChild(el)
865
- const kill = () => el.remove()
866
- el.addEventListener('click', kill)
867
- setTimeout(kill, 3200)
868
- }
869
-
870
- // --- multi-select row decoration -------------------------------------------
871
- // Entered from the session menu ("多选"). While active, every session row gets
872
- // a round checkbox, clicking a row toggles it instead of opening the
873
- // conversation, and a bottom bar runs the batch delete. No select-all and no
874
- // per-row disabling: every row is selectable and the batch deletes
875
- // immediately (the single-session flow keeps its own consent dialog).
876
-
877
- // The bar lives in the sidebar footer slot: the host owns where that row sits,
878
- // so there is no element here to create, dock or hide.
879
- let decorateRaf = null
880
- let rowObserver = null
881
-
882
- // Row identity comes from the host's own drag-and-drop key rather than from
883
- // React internals: every Session row carries `data-row-key="session:<id>"`.
884
- // A row without it is simply not selectable.
885
- const ROW_KEY_PREFIX = 'session:'
886
-
887
- function sessionIdFromRow(row) {
888
- if (!row || typeof row.getAttribute !== 'function') return null
889
- const key = row.getAttribute('data-row-key')
890
- if (typeof key !== 'string' || !key.startsWith(ROW_KEY_PREFIX)) return null
891
- const id = key.slice(ROW_KEY_PREFIX.length)
892
- return id === '' ? null : id
893
- }
894
-
895
- // --- drag a session onto the footer to delete it ---------------------------
896
- //
897
- // The id comes from the host's own `data-row-key`, never from `dataTransfer`:
898
- // the official drag only reorders, and a dragover payload is unreadable anyway.
899
- // The gesture ends in the same place as the menu row - the confirmation dialog
900
- // unless the user turned asking off - so there is exactly one delete policy.
901
-
902
- /** The row under the pointer, with the title the drop target can name. */
903
- function draggedSession(event) {
904
- const target = event === null || event === undefined ? null : event.target
905
- const row = target && typeof target.closest === 'function'
906
- ? target.closest('[role="treeitem"]')
907
- : null
908
- const sessionId = sessionIdFromRow(row)
909
- if (sessionId === null) return null
910
- const text = row !== null && typeof row.textContent === 'string' ? row.textContent.trim() : ''
911
- const title = text === '' ? null : text.slice(0, 40)
912
- return { sessionId, title }
913
- }
914
-
915
- function onDragStartCapture(event) {
916
- // Inside multi-select a drag is the host reordering rows; deleting on drop
917
- // would make the mode quietly destructive.
918
- if (state.selecting) return
919
- const info = draggedSession(event)
920
- if (info === null) return
921
- state.drag = { sessionId: info.sessionId, title: info.title, over: false }
922
- syncFooterMode()
923
- publish()
924
- }
925
-
926
- function onDragEndCapture() {
927
- if (state.drag === null) return
928
- state.drag = null
929
- syncFooterMode()
930
- publish()
931
- }
932
-
933
- /** Drop on the bar: same policy as the menu row. */
934
- function dropToDelete() {
935
- const drag = state.drag
936
- if (drag === null) return
937
- state.drag = null
938
- syncFooterMode()
939
- publish()
940
- const needsDialog = !artifactsOff() && !artifactsAuto()
941
- if (skipConfirm() && !needsDialog) deleteNow({ sessionId: drag.sessionId })
942
- else openDeleteDialog(drag.sessionId, drag.title)
943
- }
944
-
945
- function decorateRows() {
946
- if (typeof document === 'undefined') return
947
- const rows = document.querySelectorAll('[role="treeitem"]')
948
- rows.forEach((row) => {
949
- const id = sessionIdFromRow(row)
950
- if (!id) return
951
- // Checkboxes belong to multi-select only: a single delete (or any other
952
- // decorate pass outside the mode) must not plant them on every row.
953
- // The checkbox is always the row's first element child, so it is read
954
- // through the pointer. `querySelector` here ran twice per row per frame,
955
- // which is the pass's dominant cost once the list is long.
956
- const first = row.firstElementChild
957
- const existing = first !== null && first !== undefined
958
- && first.classList
959
- && first.classList.contains(DEL_CHECK)
960
- ? first
961
- : null
962
- if (!state.selecting) {
963
- if (existing !== null) existing.remove()
964
- } else {
965
- let check = existing
966
- if (!check) {
967
- check = document.createElement('span')
968
- check.className = DEL_CHECK
969
- check.setAttribute('data-dsh-delete-session', 'check')
970
- row.insertBefore(check, row.firstChild)
971
- }
972
- check.classList.toggle('dsdel-check-on', state.selected.has(id))
973
- }
974
- row.classList.toggle('dsdel-row-pending', state.pending.has(id))
975
- })
976
- if (!state.selecting) {
977
- document.querySelectorAll('.dsdel-check').forEach((el) => el.remove())
978
- }
979
- }
980
- /**
981
- * A mutation batch only matters when a node came or went. Text streaming
982
- * inside the transcript produces characterData records forever; scheduling a
983
- * full row scan for those would burn a frame's budget on every token.
984
- */
985
- function onRowMutations(records) {
986
- if (records === undefined || records === null) return scheduleDecorate()
987
- for (const record of records) {
988
- const added = record === null || record === undefined ? null : record.addedNodes
989
- const removed = record === null || record === undefined ? null : record.removedNodes
990
- if ((added !== null && added !== undefined && added.length > 0)
991
- || (removed !== null && removed !== undefined && removed.length > 0)) {
992
- scheduleDecorate()
993
- return
994
- }
995
- }
996
- }
997
-
998
- function scheduleDecorate() {
999
- if (typeof requestAnimationFrame !== 'function') return
1000
- if (decorateRaf !== null) return
1001
- decorateRaf = requestAnimationFrame(() => {
1002
- decorateRaf = null
1003
- try { decorateRows() } catch { /* best-effort DOM shim */ }
1004
- })
1005
- }
1006
-
1007
- /**
1008
- * The bulk-move face `dsh-session-relocate` publishes on `window`. Read when
1009
- * the bar is built rather than cached at module load, so a relocate plugin
1010
- * that registers after this one is still picked up.
1011
- */
1012
- function relocateApi() {
1013
- if (typeof window === 'undefined') return null
1014
- const api = window.__DSH_SESSION_RELOCATE__
1015
- if (!api || api.supportsBulkMove !== true) return null
1016
- if (typeof api.moveSelection !== 'function') return null
1017
- return api
1018
- }
1019
-
1020
- /**
1021
- * The batch bar, rendered into the host's `sidebar.footer.action` seat.
1022
- *
1023
- * The host decides where that row sits, how wide it is and whether the account
1024
- * chip shares it. Occupying the slot means this plugin never measures, docks,
1025
- * hides or restores host DOM: the row gains our controls while a selection is
1026
- * running, and loses them the moment it ends.
1027
- */
1028
- function BulkBar({ t: injected }) {
1029
- const translate = localizedTranslator(injected)
1030
- const view = useSnapshot()
1031
- // A session dragged over the sidebar turns the footer into a drop target.
1032
- if (view.drag !== null && view.drag !== undefined) {
1033
- const armed = view.drag.over === true
1034
- const name = view.drag.title === null || view.drag.title === undefined
1035
- ? translate('dropFallback')
1036
- : view.drag.title
1037
- return h('div', {
1038
- className: armed ? 'dsdel-bar dsdel-drop dsdel-drop-over' : 'dsdel-bar dsdel-drop',
1039
- role: 'toolbar',
1040
- onDragOver: (event) => {
1041
- if (event && typeof event.preventDefault === 'function') event.preventDefault()
1042
- if (event && event.dataTransfer) {
1043
- try { event.dataTransfer.dropEffect = 'move' } catch { /* read-only */ }
1044
- }
1045
- if (state.drag !== null && state.drag.over !== true) {
1046
- state.drag.over = true
1047
- publish()
1048
- }
1049
- },
1050
- onDragLeave: () => {
1051
- if (state.drag !== null && state.drag.over !== false) {
1052
- state.drag.over = false
1053
- publish()
1054
- }
1055
- },
1056
- onDrop: (event) => {
1057
- if (event && typeof event.preventDefault === 'function') event.preventDefault()
1058
- if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1059
- dropToDelete()
1060
- },
1061
- },
1062
- h('span', { key: 'icon', className: 'dsdel-drop-icon' }, glyph(TRASH_PATHS)),
1063
- h('span', { key: 'text', className: 'dsdel-drop-text' },
1064
- armed ? translate('dropRelease', name) : translate('dropHint', name)),
1065
- )
1066
- }
1067
- // Outside selection mode the footer keeps its normal face.
1068
- if (!view.selecting) return null
1069
- const busy = view.batch !== null
1070
- const empty = view.selectedCount === 0
1071
- // A move reports processed-so-far (success + failure + skip) in one number;
1072
- // a delete counts its own two buckets.
1073
- const done = view.batch === null ? 0 : view.batch.kind === 'move' ? view.batch.done : view.batch.done + view.batch.failed
1074
- const label = view.batch === null
1075
- ? translate('selectedCount', view.selectedCount)
1076
- : view.batch.kind === 'move'
1077
- ? translate('batchMoving', done, view.batch.total)
1078
- : translate('batchRunning', done, view.batch.total)
1079
- return h('div', { className: 'dsdel-bar', role: 'toolbar' },
1080
- h('span', { key: 'count', className: 'dsdel-bar-count' }, label),
1081
- h('button', {
1082
- key: 'cancel',
1083
- type: 'button',
1084
- className: 'dsdel-bar-btn dsdel-bar-cancel',
1085
- disabled: busy,
1086
- onClick: (event) => {
1087
- if (event && event.stopPropagation) event.stopPropagation()
1088
- exitSelection()
1089
- },
1090
- }, translate('cancelSelect')),
1091
- // One more button when dsh-session-relocate is installed; otherwise the bar
1092
- // is exactly what it was before.
1093
- relocateApi() === null ? null : h('button', {
1094
- key: 'move',
1095
- type: 'button',
1096
- className: 'dsdel-bar-btn dsdel-bar-move',
1097
- disabled: busy || empty,
1098
- onClick: (event) => {
1099
- if (event && event.stopPropagation) event.stopPropagation()
1100
- runBatchMove()
1101
- },
1102
- }, translate('moveSelected')),
1103
- h('button', {
1104
- key: 'delete',
1105
- type: 'button',
1106
- className: 'dsdel-bar-btn dsdel-bar-danger',
1107
- disabled: busy || empty,
1108
- onClick: (event) => {
1109
- if (event && event.stopPropagation) event.stopPropagation()
1110
- runBatchDelete()
1111
- },
1112
- }, translate('deleteSelected')),
1113
- )
1114
- }
1115
- function toggleSelect(id) {
1116
- if (state.selected.has(id)) state.selected.delete(id)
1117
- else state.selected.add(id)
1118
- publish()
1119
- }
1120
-
1121
- function onSelectClickCapture(e) {
1122
- if (!state.selecting) return
1123
- const row = e.target && e.target.closest ? e.target.closest('[role="treeitem"]') : null
1124
- if (!row) return
1125
- const id = sessionIdFromRow(row)
1126
- if (!id) return
1127
- e.preventDefault()
1128
- e.stopPropagation()
1129
- toggleSelect(id)
1130
- }
1131
-
1132
- function onSelectKeydown(e) {
1133
- if (e.key !== 'Escape') return
1134
- if (state.batch !== null) return
1135
- e.stopPropagation()
1136
- exitSelection()
1137
- }
1138
-
1139
- /**
1140
- * Mark the page while the mode runs. The marker is the only hook the
1141
- * stylesheet needs to let the account row step aside for the bar.
1142
- */
1143
- function markSelecting(on) {
1144
- if (typeof document === 'undefined' || !document.body) return
1145
- const classes = document.body.classList
1146
- if (!classes) return
1147
- if (on) classes.add('dsdel-selecting')
1148
- else classes.remove('dsdel-selecting')
1149
- }
1150
-
1151
- /** The footer is ours while selecting or while a session is dragged over it. */
1152
- function syncFooterMode() {
1153
- markSelecting(state.selecting || state.drag !== null)
1154
- }
1155
-
1156
- function enterSelection() {
1157
- if (state.selecting) return
1158
- state.selecting = true
1159
- state.selected.clear()
1160
- ensureStyle()
1161
- syncFooterMode()
1162
- document.addEventListener('click', onSelectClickCapture, true)
1163
- document.addEventListener('keydown', onSelectKeydown, true)
1164
- if (typeof MutationObserver === 'function') {
1165
- rowObserver = new MutationObserver(onRowMutations)
1166
- // Observation root is the list, not the document: the transcript below
1167
- // streams tokens continuously and would otherwise wake this on every one.
1168
- const list = typeof document.querySelector === 'function'
1169
- ? document.querySelector(LIST_SELECTOR)
1170
- : null
1171
- rowObserver.observe(list !== null && list !== undefined ? list : document.body, {
1172
- childList: true,
1173
- subtree: true,
1174
- })
1175
- }
1176
- publish()
1177
- }
1178
-
1179
- function exitSelection(options) {
1180
- if (!state.selecting) return
1181
- state.selecting = false
1182
- state.selected.clear()
1183
- state.batch = null
1184
- const keepPending = !!(options && options.keepPending)
1185
- if (!keepPending) {
1186
- state.pending.clear()
1187
- document.querySelectorAll('.dsdel-row-pending').forEach((el) => el.classList.remove('dsdel-row-pending'))
1188
- }
1189
- syncFooterMode()
1190
- document.removeEventListener('click', onSelectClickCapture, true)
1191
- document.removeEventListener('keydown', onSelectKeydown, true)
1192
- if (rowObserver) { rowObserver.disconnect(); rowObserver = null }
1193
- document.querySelectorAll('.dsdel-check').forEach((el) => el.remove())
1194
- publish()
1195
- }
1196
-
1197
- // 成功删除后行要保持隐藏直到列表刷新落地,之后再清掉乐观状态(避免行“闪回”)。
1198
- function settlePendingSoon() {
1199
- setTimeout(() => {
1200
- state.pending.clear()
1201
- publish()
1202
- }, 2500)
1203
- }
1204
-
1205
- // 批量删除:客户端并发(小池)+ 乐观隐藏 + 进度显示。
1206
- // 走单会话端点(每个请求各自跑宿主端的完整删除管线),宿主端对同一存储的
1207
- // 记账变更已串行化,因此不同会话并发是安全的;失败的行立即恢复显示并保持选中,
1208
- // 方便直接重试。
1209
- // 6 是实测值:64 个 ~2MB 会话的墙钟时间 4 路 281ms / 6 路 189ms / 8 路 142ms
1210
- // (I/O 并行度约在 8 饱和),6 路比 4 路快约 1/3 且仍在饱和点以下。
1211
- const BATCH_CONCURRENCY = 6
1212
-
1213
- function runBatchDelete() {
1214
- if (state.batch !== null) return
1215
- const ids = [...state.selected]
1216
- if (ids.length === 0) return
1217
- state.batch = { kind: 'delete', total: ids.length, done: 0, failed: 0 }
1218
- state.selected.clear()
1219
- for (const id of ids) state.pending.add(id)
1220
- publish()
1221
-
1222
- const failedIds = []
1223
- let cursor = 0
1224
- const worker = async () => {
1225
- while (true) {
1226
- const index = cursor
1227
- cursor += 1
1228
- if (index >= ids.length) return
1229
- const id = ids[index]
1230
- try {
1231
- await postDelete(id)
1232
- state.batch.done += 1
1233
- } catch {
1234
- state.batch.failed += 1
1235
- failedIds.push(id)
1236
- state.pending.delete(id)
1237
- }
1238
- publish()
1239
- }
1240
- }
1241
- const workers = []
1242
- for (let i = 0; i < Math.min(BATCH_CONCURRENCY, ids.length); i += 1) workers.push(worker())
1243
-
1244
- Promise.all(workers).then(() => {
1245
- const failed = state.batch ? state.batch.failed : 0
1246
- const ok = state.batch ? state.batch.done : 0
1247
- state.batch = null
1248
- if (failed === 0) {
1249
- toast(t('batchDone', ok))
1250
- exitSelection({ keepPending: true })
1251
- settlePendingSoon()
1252
- } else {
1253
- for (const id of failedIds) state.selected.add(id)
1254
- toast(t('batchPartial', ok, failed), true)
1255
- publish()
1256
- }
1257
- refreshList()
1258
- for (const id of ids) {
1259
- if (!failedIds.includes(id)) leaveIfCurrent(id)
1260
- }
1261
- })
1262
- }
1263
-
1264
- /**
1265
- * Hand the selection to dsh-session-relocate. That plugin owns the target
1266
- * picker and the move itself; this side runs the progress readout and the
1267
- * summary. A cancelled picker leaves the selection untouched and says
1268
- * nothing, because nothing happened.
1269
- */
1270
- async function runBatchMove() {
1271
- if (state.batch !== null) return
1272
- const api = relocateApi()
1273
- if (api === null) return
1274
- const ids = [...state.selected]
1275
- if (ids.length === 0) return
1276
-
1277
- state.batch = { kind: 'move', total: ids.length, done: 0, failed: 0 }
1278
- publish()
1279
-
1280
- let result
1281
- try {
1282
- result = await api.moveSelection(ids, {
1283
- onProgress: (done, total) => {
1284
- if (state.batch === null || state.batch.kind !== 'move') return
1285
- if (typeof done === 'number' && Number.isFinite(done)) state.batch.done = Math.max(0, done)
1286
- if (typeof total === 'number' && Number.isFinite(total)) state.batch.total = Math.max(1, total)
1287
- },
1288
- })
1289
- } catch (reason) {
1290
- state.batch = null
1291
- publish()
1292
- toast(t('failed') + String((reason && reason.message) || reason), true)
1293
- return
1294
- }
1295
-
1296
- state.batch = null
1297
- // `canceled` is the contract spelling; `cancelled` is also honoured because
1298
- // the contract's first draft used it. Nothing else about the result is
1299
- // guessed: a missing count is reported, never substituted.
1300
- if (result && (result.canceled === true || result.cancelled === true)) {
1301
- // The user backed out of the target picker; keep the selection for a retry.
1302
- publish()
1303
- return
1304
- }
1305
-
1306
- const missing = ['moved', 'failed', 'total'].filter((key) => !result || typeof result[key] !== 'number')
1307
- if (missing.length > 0) {
1308
- // Falling back here would turn "genuinely zero failures" and "the field
1309
- // was not sent" into the same summary, so the shape is enforced instead.
1310
- toast(t('moveBadResult', missing.join(', ')), true)
1311
- exitSelection()
1312
- refreshList()
1313
- return
1314
- }
1315
-
1316
- toast(t('batchMoved', result.moved, result.failed), result.failed > 0)
1317
- exitSelection()
1318
- refreshList()
1319
- if (result.failed === 0) {
1320
- for (const id of ids) leaveIfCurrent(id)
1321
- }
1322
- }
1323
-
1324
- // --- single delete ---------------------------------------------------------
1325
-
1326
- function deleteNow(info) {
1327
- state.pending.add(info.sessionId)
1328
- publish()
1329
- // The no-dialog path can only honour auto mode: ask mode needs the list,
1330
- // and the menu row forces the dialog in that case. With the feature off no
1331
- // quarantine field is sent at all, keeping the request identical to the
1332
- // version that predates the feature.
1333
- const quarantine = !artifactsOff() && artifactsAuto() ? { scope: artifactScope() } : undefined
1334
- postDelete(info.sessionId, quarantine)
1335
- .then((result) => {
1336
- const outcome = result && result.quarantine ? result.quarantine : null
1337
- if (outcome !== null && outcome.failed.length > 0) {
1338
- toast(t('doneQuarantineFailed', outcome.moved.length, outcome.failed.length), true)
1339
- } else if (outcome !== null && outcome.moved.length > 0) {
1340
- toast(t('doneQuarantine', outcome.moved.length))
1341
- } else {
1342
- toast(t('done'))
1343
- }
1344
- refreshList()
1345
- settlePendingSoon()
1346
- leaveIfCurrent(info.sessionId)
1347
- })
1348
- .catch((reason) => {
1349
- state.pending.delete(info.sessionId)
1350
- publish()
1351
- toast(t('failed') + String((reason && reason.message) || reason), true)
1352
- })
1353
- }
1354
-
1355
- /** The rows a scope selects, in list order. */
1356
- function candidatePaths(plan, scope) {
1357
- if (plan === null || plan === undefined) return []
1358
- const rows = scope === 'all' ? [...plan.created, ...plan.modified] : [...plan.created]
1359
- return rows.map((row) => row.path)
1360
- }
1361
-
1362
- function openDeleteDialog(sessionId, title) {
1363
- // With the feature off the dialog carries no artifact section at all and
1364
- // the delete request stays byte-identical to the previous version.
1365
- //
1366
- // Auto mode sends `{ scope }` and the host derives the whole set itself, so
1367
- // the scan result would never be read: scanning there only burns time before
1368
- // the dialog can appear. Ask mode is the one that needs the listing.
1369
- const artifacts = artifactsOff()
1370
- ? null
1371
- : artifactsAuto()
1372
- ? { auto: true, loading: false, plan: null, error: null, selected: new Set() }
1373
- : { auto: false, loading: true, plan: null, error: null, selected: new Set() }
1374
- state.dialog = {
1375
- sessionId,
1376
- title: title || null,
1377
- busy: false,
1378
- error: null,
1379
- artifacts,
1380
- // The subagent sessions this conversation spawned. Filled in after the
1381
- // dialog opens: the list costs one host call, and on most conversations
1382
- // there is nothing to list.
1383
- children: { loading: true, list: [], selected: new Set() },
1384
- }
1385
- publish()
1386
- if (artifacts !== null && artifacts.auto !== true) loadArtifacts(sessionId)
1387
- loadChildren(sessionId)
1388
- }
1389
-
1390
- /**
1391
- * List the subagent sessions behind this conversation. With the switch on they
1392
- * are all taken with the parent; with it off every one starts ticked and the
1393
- * dialog lets the user narrow the set.
1394
- */
1395
- function loadChildren(sessionId) {
1396
- fetch(`/dsh-delete-session/children`, {
1397
- method: 'POST',
1398
- headers: { 'content-type': 'application/json' },
1399
- body: JSON.stringify({ sessionId }),
1400
- })
1401
- .then(async (res) => {
1402
- let data = {}
1403
- try { data = await res.json() } catch { /* keep {} */ }
1404
- const list = res.ok && Array.isArray(data.children) ? data.children : []
1405
- const dialog = state.dialog
1406
- if (dialog === null || dialog.sessionId !== sessionId) return
1407
- dialog.children = {
1408
- loading: false,
1409
- list,
1410
- selected: new Set(list.map((child) => child.id)),
1411
- }
1412
- publish()
1413
- })
1414
- .catch(() => {
1415
- const dialog = state.dialog
1416
- if (dialog === null || dialog.sessionId !== sessionId) return
1417
- // A host that cannot list children still deletes the parent; reporting
1418
- // an error here would block a delete that is otherwise fine.
1419
- dialog.children = { loading: false, list: [], selected: new Set() }
1420
- publish()
1421
- })
1422
- }
1423
-
1424
- /** The children this delete should take along. */
1425
- function childSessionIdsFor(dialog) {
1426
- if (dialog.children === undefined || dialog.children === null) return []
1427
- if (syncChildren()) return dialog.children.list.map((child) => child.id)
1428
- return dialog.children.list
1429
- .filter((child) => dialog.children.selected.has(child.id))
1430
- .map((child) => child.id)
1431
- }
1432
-
1433
- /** Fetch the read-only scan and preselect the current scope's candidates. */
1434
- function loadArtifacts(sessionId) {
1435
- const settle = (mutate) => {
1436
- const dialog = state.dialog
1437
- if (dialog === null || dialog.artifacts === null || dialog.sessionId !== sessionId) return
1438
- mutate(dialog.artifacts)
1439
- publish()
1440
- }
1441
- postArtifacts(sessionId)
1442
- .then((plan) => settle((artifacts) => {
1443
- artifacts.loading = false
1444
- artifacts.plan = plan
1445
- artifacts.selected = new Set(candidatePaths(plan, artifactScope()))
1446
- }))
1447
- .catch((reason) => settle((artifacts) => {
1448
- artifacts.loading = false
1449
- artifacts.error = String((reason && reason.message) || reason)
1450
- }))
1451
- }
1452
-
1453
- function closeDeleteDialog() {
1454
- if (state.dialog === null || state.dialog.busy) return
1455
- state.dialog = null
1456
- publish()
1457
- }
1458
-
1459
- // --- quarantine folder picker ----------------------------------------------
1460
-
1461
- /**
1462
- * Open the folder picker at the configured root. The browser cannot hand a
1463
- * page a real filesystem path, so the listing comes from the host instead.
1464
- */
1465
- function openPicker() {
1466
- state.picker = {
1467
- loading: true,
1468
- error: null,
1469
- path: '',
1470
- parent: null,
1471
- entries: [],
1472
- roots: [],
1473
- truncated: false,
1474
- defaultRoot: state.defaultRoot,
1475
- }
1476
- publish()
1477
- loadPicker(quarantineRoot())
1478
- }
1479
-
1480
- function closePicker() {
1481
- state.picker = null
1482
- publish()
1483
- }
1484
-
1485
- function loadPicker(target) {
1486
- postBrowse(target)
1487
- .then((listing) => {
1488
- if (state.picker === null) return
1489
- state.picker = {
1490
- loading: false,
1491
- error: null,
1492
- path: listing.path,
1493
- parent: listing.parent,
1494
- entries: listing.entries,
1495
- roots: listing.roots,
1496
- truncated: listing.truncated,
1497
- defaultRoot: listing.defaultRoot,
1498
- }
1499
- state.defaultRoot = listing.defaultRoot
1500
- publish()
1501
- })
1502
- .catch((reason) => {
1503
- if (state.picker === null) return
1504
- state.picker = {
1505
- ...state.picker,
1506
- loading: false,
1507
- error: String((reason && reason.message) || reason),
1508
- }
1509
- publish()
1510
- })
1511
- }
1512
-
1513
- /** Commit the directory the picker is showing. */
1514
- function pickCurrent() {
1515
- const picker = state.picker
1516
- if (picker === null || picker.loading || picker.path === '') return
1517
- setQuarantineRoot(picker.path)
1518
- closePicker()
1519
- toast(t('rootSet'))
1520
- }
1521
-
1522
- /**
1523
- * Prefer the OS folder dialog, which is the one the user actually expects.
1524
- * It only exists on Windows; everywhere else the in-page picker takes over.
1525
- */
1526
- let folderDialogOpen = false
1527
- function chooseFolder() {
1528
- if (folderDialogOpen) return
1529
- folderDialogOpen = true
1530
- // The dialog can open behind the browser window, so say it was raised.
1531
- toast(t('pickerOpening'))
1532
- postPick()
1533
- .then((picked) => {
1534
- if (picked.cancelled === true) return
1535
- setQuarantineRoot(picked.path)
1536
- toast(t('rootSet'))
1537
- })
1538
- .catch((reason) => {
1539
- // Two host answers mean "use the page picker instead": `unsupported`
1540
- // (no directoryPicker service at all) and `browse` (the service exists
1541
- // but serves listings, which is what a remote client gets). Neither is
1542
- // a failure, so neither may surface as a toast.
1543
- if (reason && (reason.code === 'unsupported' || reason.code === 'browse')) {
1544
- openPicker()
1545
- return
1546
- }
1547
- // Nothing was deleted here, so the delete wording would mislead.
1548
- toast(t('pickerFailed') + String((reason && reason.message) || reason), true)
1549
- })
1550
- .finally(() => {
1551
- folderDialogOpen = false
1552
- })
1553
- }
1554
-
1555
- /** Learn the host default once, so the settings card can name it. */
1556
- function loadDefaultRoot() {
1557
- if (state.defaultRoot !== null) return
1558
- postBrowse('')
1559
- .then((listing) => {
1560
- state.defaultRoot = listing.defaultRoot
1561
- publish()
1562
- })
1563
- .catch(() => {
1564
- // the card falls back to a generic label; nothing to report here
1565
- })
1566
- }
1567
-
1568
- /**
1569
- * Build the quarantine request for the open dialog. The host re-derives the
1570
- * candidate set and intersects it with `paths`, so this can only narrow what
1571
- * the user was shown - never widen it.
1572
- */
1573
- function quarantineRequest(dialog) {
1574
- if (dialog.artifacts === null) return undefined
1575
- const scope = artifactScope()
1576
- const skipGit = skipGitRepos()
1577
- // In auto mode no `paths` is sent: the host takes the whole set it derives.
1578
- if (artifactsAuto()) return { scope, skipGit }
1579
- const allowed = new Set(candidatePaths(dialog.artifacts.plan, scope))
1580
- const paths = [...dialog.artifacts.selected].filter((path) => allowed.has(path))
1581
- return { scope, paths, skipGit }
1582
- }
1583
-
1584
- // The "don't ask again" flag is committed only when the user actually
1585
- // confirms, exactly as before - ticking the box and then cancelling must not
1586
- // change the preference.
1587
- function confirmDelete() {
1588
- const dialog = state.dialog
1589
- if (dialog === null || dialog.busy) return
1590
- const quarantine = quarantineRequest(dialog)
1591
- const childSessionIds = childSessionIdsFor(dialog)
1592
- dialog.busy = true
1593
- dialog.error = null
1594
- state.pending.add(dialog.sessionId)
1595
- publish()
1596
- postDelete(dialog.sessionId, quarantine, childSessionIds)
1597
- .then((result) => {
1598
- state.dialog = null
1599
- const outcome = result && result.quarantine ? result.quarantine : null
1600
- if (outcome !== null && outcome.failed.length > 0) {
1601
- toast(t('doneQuarantineFailed', outcome.moved.length, outcome.failed.length), true)
1602
- } else if (outcome !== null && outcome.moved.length > 0) {
1603
- toast(t('doneQuarantine', outcome.moved.length))
1604
- } else {
1605
- toast(t('done'))
1606
- }
1607
- refreshList()
1608
- settlePendingSoon()
1609
- leaveIfCurrent(dialog.sessionId)
1610
- publish()
1611
- })
1612
- .catch((reason) => {
1613
- state.pending.delete(dialog.sessionId)
1614
- dialog.busy = false
1615
- dialog.error = t('failed') + String((reason && reason.message) || reason)
1616
- publish()
1617
- })
1618
- }
1619
-
1620
- // --- menu rows (slot: sidebar.workspaces.session.menu.item) ----------------
1621
-
1622
- /** The sidebar list container; hashed class name, matched by its suffix. */
1623
- const LIST_SELECTOR = '[class*="_regionArea"]'
1624
- /** Marks a row checkbox this plugin planted. */
1625
- const DEL_CHECK = 'dsdel-check'
1626
-
1627
- /** Inline glyphs for the two rows; the host exposes no matching pair. */
1628
- const TRASH_PATHS = ['M4 7h16', 'M10 11v6', 'M14 11v6', 'M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13', 'M9 7V4h6v3']
1629
- /** A folder, for "show this file where it lives". */
1630
- const FOLDER_PATHS = ['M3 6a1 1 0 0 1 1-1h4l2 2h8a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z']
1631
- const SELECT_PATHS = ['M5 7m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0', 'M5 17m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0', 'M11 7h9', 'M11 17h9']
1632
-
1633
- function glyph(paths) {
1634
- return h(
1635
- 'svg',
1636
- {
1637
- width: 16,
1638
- height: 16,
1639
- viewBox: '0 0 24 24',
1640
- fill: 'none',
1641
- stroke: 'currentColor',
1642
- strokeWidth: 1.8,
1643
- strokeLinecap: 'round',
1644
- strokeLinejoin: 'round',
1645
- },
1646
- paths.map((d) => h('path', { key: d, d })),
1647
- )
1648
- }
1649
-
1650
- // ui-primitives' `MenuItemButton` takes a real `danger` parameter (verified
1651
- // against the shipped component), which puts the host's own danger class on
1652
- // the button. Passing it is what keeps the delete row in the host's danger
1653
- // colour - icon included - rather than a plugin guess.
1654
- //
1655
- // No `separatorBefore`: this migration moves the rows onto the host's slot
1656
- // contract and must not change how the menu looks.
1657
-
1658
- /** "Select multiple" row (order 409, directly above the delete row). */
1659
- function SelectMultipleMenuItem({ useMenuOpenState, t: translate }) {
1660
- const [, setMenuOpen] = useMenuOpenState()
1661
- return h(primitives.MenuItemButton, {
1662
- icon: glyph(SELECT_PATHS),
1663
- onSelect: () => {
1664
- setMenuOpen(false)
1665
- enterSelection()
1666
- },
1667
- children: translate('multiSelect'),
1668
- })
1669
- }
1670
-
1671
- /** "Delete session" row (order 410, in the host's danger colour). */
1672
- function DeleteSessionMenuItem({ sessionId, displayTitle, useMenuOpenState, t: translate }) {
1673
- const [, setMenuOpen] = useMenuOpenState()
1674
- return h(primitives.MenuItemButton, {
1675
- danger: true,
1676
- icon: glyph(TRASH_PATHS),
1677
- onSelect: (event) => {
1678
- setMenuOpen(false)
1679
- // Ask mode keeps the dialog even when "don't ask again" is ticked: the
1680
- // file list only exists there, and skipping it would make the feature
1681
- // silently do nothing.
1682
- const needsDialog = !artifactsOff() && !artifactsAuto()
1683
- // Shift-click always asks, even after "don't ask again" was ticked.
1684
- if (skipConfirm() && !needsDialog && !(event && event.shiftKey)) deleteNow({ sessionId })
1685
- else openDeleteDialog(sessionId, displayTitle)
1686
- },
1687
- children: translate('menu'),
1688
- })
1689
- }
1690
-
1691
- // --- confirmation dialog (slot: shell.overlay) -----------------------------
1692
-
1693
- /**
1694
- * The produced-files section: the scan summary, then either the tick list
1695
- * (ask mode) or a single line stating how many files will move (auto mode).
1696
- * A null `artifacts` means the feature is off and the dialog says nothing.
1697
- */
1698
- /**
1699
- * The subagent sessions behind this conversation. Hidden while the switch
1700
- * already answers the question, and while the list is still loading.
1701
- */
1702
- function renderChildren(dialog, translate) {
1703
- const children = dialog.children
1704
- if (children === undefined || children === null) return null
1705
- if (children.loading) return null
1706
- if (children.list.length === 0) return null
1707
- if (syncChildren()) return null
1708
- return h('div', { key: 'children', className: 'dsdel-modal-children' },
1709
- h('p', { key: 'hint', className: 'dsdel-modal-text' },
1710
- translate('childrenHint', children.list.length)),
1711
- ...children.list.map((child) => h(primitives.Checkbox, {
1712
- key: `child:${child.id}`,
1713
- checked: children.selected.has(child.id),
1714
- label: child.cwd ? `${child.id} · ${child.cwd}` : child.id,
1715
- onChange: (checked) => {
1716
- if (checked === true) children.selected.add(child.id)
1717
- else children.selected.delete(child.id)
1718
- publish()
1719
- },
1720
- })),
1721
- )
1722
- }
1723
-
1724
- function renderArtifacts(artifacts, translate) {
1725
- if (artifacts === null) return null
1726
- // Auto mode never scanned, so there is no plan to describe: name the
1727
- // outcome instead of showing a list nobody asked for.
1728
- if (artifacts.auto === true) {
1729
- return h('div', { key: 'artifacts' }, [
1730
- h('p', { key: 'head', className: 'dsdel-modal-text', style: { marginTop: '12px', fontWeight: 600 } },
1731
- translate('artifactSection')),
1732
- h('p', { key: 'auto', className: 'dsdel-modal-text' }, translate('artifactAutoOnly')),
1733
- ])
1734
- }
1735
- if (artifacts.loading) {
1736
- return h('p', { key: 'artifacts', className: 'dsdel-modal-meta', style: { marginTop: '12px' } },
1737
- translate('artifactLoading'))
1738
- }
1739
- if (artifacts.error !== null) {
1740
- return h('p', { key: 'artifacts', className: 'dsdel-modal-error', role: 'alert' },
1741
- translate('artifactFailed') + artifacts.error)
1742
- }
1743
- const plan = artifacts.plan
1744
- if (plan === null) return null
1745
- const scope = artifactScope()
1746
- const auto = artifactsAuto()
1747
- const rows = scope === 'all' ? [...plan.created, ...plan.modified] : [...plan.created]
1748
-
1749
- const elements = [
1750
- h('p', { key: 'head', className: 'dsdel-modal-text', style: { marginTop: '12px', fontWeight: 600 } },
1751
- translate('artifactSection')),
1752
- h('p', { key: 'count', className: 'dsdel-modal-meta' },
1753
- `${translate('artifactCount', plan.created.length, plan.modified.length)} · ${translate(scope === 'all' ? 'artifactScopeAll' : 'artifactScopeCreated')}`),
1754
- ]
1755
-
1756
- if (rows.length === 0) {
1757
- elements.push(h('p', { key: 'none', className: 'dsdel-modal-meta' }, translate('artifactNone')))
1758
- } else if (auto) {
1759
- elements.push(h('p', { key: 'auto', className: 'dsdel-modal-text' }, translate('artifactAutoNote', rows.length)))
1760
- } else {
1761
- elements.push(h('p', { key: 'selected', className: 'dsdel-modal-meta' },
1762
- translate('artifactSelected', artifacts.selected.size)))
1763
- for (const row of rows.slice(0, ARTIFACT_ROWS_SHOWN)) {
1764
- elements.push(h('div', {
1765
- key: `row:${row.path}`,
1766
- 'data-file-row': row.path,
1767
- className: 'dsdel-file-row',
1768
- },
1769
- h('label', {
1770
- key: 'label',
1771
- className: 'dsdel-file-label',
1772
- },
1773
- h('input', {
1774
- type: 'checkbox',
1775
- checked: artifacts.selected.has(row.path),
1776
- onChange: (e) => {
1777
- if (e && e.target && e.target.checked) artifacts.selected.add(row.path)
1778
- else artifacts.selected.delete(row.path)
1779
- publish()
1780
- },
1781
- }),
1782
- h('span', { key: 'path', className: 'dsdel-file-path' }, row.displayPath || row.path),
1783
- ),
1784
- // Delete just this file. Same destination rule as the conversation
1785
- // switch: the system trash when recycling is on, gone when it is not.
1786
- h('button', {
1787
- key: 'remove',
1788
- type: 'button',
1789
- className: 'dsdel-file-open dsdel-file-remove',
1790
- title: translate('artifactDeleteFile'),
1791
- 'aria-label': translate('artifactDeleteFile'),
1792
- onClick: (event) => {
1793
- if (event && typeof event.preventDefault === 'function') event.preventDefault()
1794
- if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1795
- deleteOneFile(state.dialog === null ? '' : state.dialog.sessionId, row.path)
1796
- },
1797
- }, glyph(TRASH_PATHS)),
1798
- // One folder per row. What moves is the file, so the thing worth
1799
- // looking at before deciding is where it lives. The button is a
1800
- // SIBLING of the label: inside it, a click would toggle the tick box.
1801
- h('button', {
1802
- key: 'open',
1803
- type: 'button',
1804
- className: 'dsdel-file-open',
1805
- title: translate('artifactOpenFolder'),
1806
- 'aria-label': translate('artifactOpenFolder'),
1807
- onClick: (event) => {
1808
- if (event && typeof event.preventDefault === 'function') event.preventDefault()
1809
- if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1810
- revealParent(row.path)
1811
- },
1812
- }, glyph(FOLDER_PATHS)),
1813
- ))
1814
- }
1815
- if (rows.length > ARTIFACT_ROWS_SHOWN) {
1816
- elements.push(h('p', { key: 'more', className: 'dsdel-modal-meta' },
1817
- translate('artifactMore', rows.length - ARTIFACT_ROWS_SHOWN)))
1818
- }
1819
- }
1820
-
1821
- if (plan.refused.length > 0) {
1822
- elements.push(h('p', { key: 'refused', className: 'dsdel-modal-meta' },
1823
- translate('artifactRefused', plan.refused.length)))
1824
- }
1825
- if (plan.truncated) {
1826
- elements.push(h('p', { key: 'truncated', className: 'dsdel-modal-meta' }, translate('artifactTruncated')))
1827
- }
1828
- return h('div', { key: 'artifacts', className: 'dsdel-artifacts' }, elements)
1829
- }
1830
-
1831
- /** Folder picker overlay: walk directories, then commit one. */
1832
- function QuarantinePicker({ t: injected }) {
1833
- const translate = localizedTranslator(injected)
1834
- const view = useSnapshot()
1835
- const picker = view.picker
1836
- if (picker === null) return null
1837
-
1838
- const children = []
1839
- if (picker.loading) {
1840
- children.push(h('p', { key: 'loading', className: 'dsdel-modal-meta' }, translate('pickerLoading')))
1841
- } else if (picker.error !== null) {
1842
- children.push(h('p', { key: 'error', className: 'dsdel-modal-error', role: 'alert' }, picker.error))
1843
- } else {
1844
- children.push(h('p', { key: 'path', className: 'dsdel-picker-path' }, picker.path))
1845
-
1846
- const up = []
1847
- if (picker.parent !== null) {
1848
- up.push(h('button', {
1849
- key: 'up',
1850
- type: 'button',
1851
- className: 'dsdel-picker-row',
1852
- onClick: () => loadPicker(picker.parent),
1853
- }, '..'))
1854
- }
1855
- for (const drive of picker.roots) {
1856
- up.push(h('button', {
1857
- key: `drive:${drive.path}`,
1858
- type: 'button',
1859
- className: 'dsdel-picker-row',
1860
- onClick: () => loadPicker(drive.path),
1861
- }, drive.name))
1862
- }
1863
- if (up.length > 0) children.push(h('div', { key: 'up', className: 'dsdel-picker-list' }, up))
1864
-
1865
- if (picker.entries.length === 0) {
1866
- children.push(h('p', { key: 'empty', className: 'dsdel-modal-meta' }, translate('pickerEmpty')))
1867
- } else {
1868
- children.push(h('div', { key: 'list', className: 'dsdel-picker-list' },
1869
- picker.entries.map((entry) => h('button', {
1870
- key: entry.path,
1871
- type: 'button',
1872
- className: 'dsdel-picker-row',
1873
- onClick: () => loadPicker(entry.path),
1874
- }, `${entry.name}/`))))
1875
- }
1876
- if (picker.truncated) {
1877
- children.push(h('p', { key: 'truncated', className: 'dsdel-modal-meta' }, translate('pickerTruncated')))
1878
- }
1879
- children.push(h('p', { key: 'default', className: 'dsdel-modal-meta' },
1880
- translate('pickerDefault', picker.defaultRoot || '-')))
1881
- }
1882
-
1883
- return h(primitives.Modal, {
1884
- open: true,
1885
- onClose: () => closePicker(),
1886
- closeLabel: translate('cancel'),
1887
- title: translate('pickerTitle'),
1888
- footer: [
1889
- h(primitives.Button, {
1890
- key: 'cancel',
1891
- variant: 'outline',
1892
- onClick: () => closePicker(),
1893
- children: translate('cancel'),
1894
- }),
1895
- h(primitives.Button, {
1896
- key: 'choose',
1897
- disabled: picker.loading || picker.path === '',
1898
- onClick: () => pickCurrent(),
1899
- children: translate('pickerChoose'),
1900
- }),
1901
- ],
1902
- children,
1903
- })
1904
- }
1905
-
1906
- function DeleteSessionDialog({ t: injected }) {
1907
- const translate = localizedTranslator(injected)
1908
- const view = useSnapshot()
1909
- const dialog = view.dialog
1910
- if (dialog === null) return null
1911
-
1912
- // The file list sizes its own frame: a short list gets a short dialog, a
1913
- // long one grows until the viewport cap and then scrolls. A forced ratio
1914
- // cannot do that — it pins the height, so the empty band under two lines
1915
- // of text simply moves around.
1916
- const plan = dialog.artifacts !== null && dialog.artifacts !== undefined
1917
- ? dialog.artifacts.plan
1918
- : null
1919
- const listed = plan === null || plan === undefined
1920
- ? 0
1921
- : (plan.created || []).length + (plan.modified || []).length
1922
- const needsFrame = listed > 0 && dialog.artifacts.auto !== true
1923
- const footer = h(
1924
- Fragment,
1925
- null,
1926
- h(primitives.Button, {
1927
- variant: 'outline',
1928
- disabled: dialog.busy,
1929
- onClick: () => closeDeleteDialog(),
1930
- children: translate('cancel'),
1931
- }),
1932
- h(primitives.Button, {
1933
- variant: 'outline',
1934
- className: 'dsdel-danger-btn',
1935
- disabled: dialog.busy,
1936
- onClick: () => confirmDelete(),
1937
- children: dialog.busy ? translate('deleting') : translate('confirm'),
1938
- }),
1939
- )
1940
-
1941
- return h(primitives.Modal, {
1942
- open: true,
1943
- // `Modal` documents no width prop, so the class, the inline style and the
1944
- // `:has()` rule in the stylesheet all try; whichever the host honours wins.
1945
- // 9:16: the file list reads as a column, so the shell is a phone-shaped
1946
- // card. Width is derived from the height budget (94vh tall at most), which
1947
- // keeps the ratio on every window size; the list scrolls inside it.
1948
- ...(needsFrame ? { className: 'dsdel-dialog-wide' } : {}),
1949
- ...(needsFrame ? {
1950
- style: {
1951
- width: 'min(46vw, 860px)',
1952
- maxWidth: 'min(46vw, 860px)',
1953
- minHeight: 'min(240px, 88vh)',
1954
- maxHeight: '88vh',
1955
- },
1956
- } : {}),
1957
- onClose: () => closeDeleteDialog(),
1958
- closeLabel: translate('cancel'),
1959
- title: translate('title'),
1960
- footer,
1961
- children: [
1962
- h('p', { key: 'meta', className: 'dsdel-modal-meta' },
1963
- `${dialog.title || translate('untitled')} · ${dialog.sessionId}`),
1964
- // The sentence has to match the switch: one promises the Recycle Bin,
1965
- // the other promises exactly what an unchecked box means.
1966
- h('p', { key: 'desc', className: 'dsdel-modal-text' },
1967
- translate(recycleSession() ? 'descRecycle' : 'descPermanent')),
1968
- renderArtifacts(dialog.artifacts, translate),
1969
- renderChildren(dialog, translate),
1970
- // Whether a delete asks first is a setting, not a dialog affordance:
1971
- // it lives on the plugin page only, so this dialog never changes it.
1972
- dialog.error !== null
1973
- ? h('p', { key: 'error', className: 'dsdel-modal-error', role: 'alert' }, dialog.error)
1974
- : null,
1975
- ],
1976
- })
1977
- }
1978
-
1979
- // --- plugin page card (slot: plugins.row.config) ---------------------------
1980
-
1981
- // The manager's detail page for this bundle gives the component row a
1982
- // configure arrow once the bundle registers its own row.config entry (key
1983
- // `<bundle package>#<row id>`). The card carries the one setting the dialog
1984
- // also exposes: whether a session delete asks first.
1985
- function AskBeforeDeleteOption({ view, t: injected }) {
1986
- // Unlike the menu rows and the dialog, this entry is registered without a
1987
- // `locale`, so the host injects no `t` here. Falling back to the
1988
- // module-level translator (same dictionaries) keeps the card working
1989
- // instead of throwing on an undefined call.
1990
- const translate = localizedTranslator(injected)
1991
- // `view` is already the prop name (page or summary), so the store snapshot
1992
- // needs its own binding here.
1993
- const pageSnapshot = useSnapshot()
1994
- // The host owns the default path, so it is fetched once per mount.
1995
- const defaultRootValue = () => (pageSnapshot && pageSnapshot.defaultRoot) || ''
1996
- const [ask, setAsk] = react.useState(!skipConfirm())
1997
- const [recycle, setRecycle] = react.useState(recycleSession())
1998
- const [syncChildrenState, setSyncChildrenState] = react.useState(syncChildren())
1999
- const [off, setOff] = react.useState(artifactsOff())
2000
- const [auto, setAuto] = react.useState(artifactsAuto())
2001
- const [scope, setScope] = react.useState(artifactScope())
2002
- const [skipGit, setSkipGit] = react.useState(skipGitRepos())
2003
- const [root, setRoot] = react.useState(quarantineRoot())
2004
- react.useEffect(() => subscribeSkip(() => setAsk(!skipConfirm())), [])
2005
- react.useEffect(() => { loadDefaultRoot() }, [])
2006
- react.useEffect(() => subscribePrefs(() => {
2007
- setOff(artifactsOff())
2008
- setAuto(artifactsAuto())
2009
- setScope(artifactScope())
2010
- setRoot(quarantineRoot())
2011
- }), [])
2012
-
2013
- if (view === 'summary') {
2014
- if (off) return translate('pageSummaryArtifactsOff')
2015
- return translate(auto ? 'pageSummaryArtifactsAuto' : 'pageSummaryArtifactsAsk')
2016
- }
2017
-
2018
- const children = [
2019
- h(primitives.Checkbox, {
2020
- key: 'ask',
2021
- checked: ask,
2022
- label: translate('pageAsk'),
2023
- onChange: (checked) => {
2024
- setAsk(checked === true)
2025
- setSkipConfirm(checked !== true)
2026
- },
2027
- }),
2028
- h('p', { key: 'askHint', className: 'dsdel-page-hint' },
2029
- // Ask mode needs the dialog for its file list, so "delete straight away"
2030
- // would be a promise this combination does not keep.
2031
- translate(ask ? 'pageHintAsk' : (!off && !auto ? 'pageHintAutoWithArtifacts' : 'pageHintAuto'))),
2032
-
2033
- h(primitives.Checkbox, {
2034
- key: 'recycle',
2035
- checked: recycle,
2036
- label: translate('pageRecycle'),
2037
- onChange: (checked) => {
2038
- setRecycle(checked === true)
2039
- setRecycleSession(checked === true)
2040
- },
2041
- }),
2042
- h('p', { key: 'recycleHint', className: 'dsdel-page-hint' },
2043
- translate(recycle ? 'pageRecycleOn' : 'pageRecycleOff')),
2044
-
2045
- h(primitives.Checkbox, {
2046
- key: 'syncChildren',
2047
- checked: syncChildrenState,
2048
- label: translate('pageSyncChildren'),
2049
- onChange: (checked) => {
2050
- setSyncChildrenState(checked === true)
2051
- setSyncChildren(checked === true)
2052
- },
2053
- }),
2054
- h('p', { key: 'syncChildrenHint', className: 'dsdel-page-hint' },
2055
- translate(syncChildrenState ? 'pageSyncChildrenOn' : 'pageSyncChildrenOff')),
2056
-
2057
- h(primitives.Checkbox, {
2058
- key: 'off',
2059
- checked: off,
2060
- label: translate('pageArtifactsOff'),
2061
- onChange: (checked) => {
2062
- setOff(checked === true)
2063
- setArtifactsOff(checked === true)
2064
- },
2065
- }),
2066
- h('p', { key: 'offHint', className: 'dsdel-page-hint' }, translate(off ? 'pageHintArtifactsOff' : 'pageHintArtifactsOn')),
2067
- ]
2068
-
2069
- // Everything below the master switch only matters while the feature is on;
2070
- // leaving it rendered-but-inert would suggest a setting that does nothing.
2071
- // The layout is inline rather than a class: a stylesheet injected into the
2072
- // host page has already proven able to lag behind a rebuilt module, and a
2073
- // group whose indentation depends on it can silently collapse.
2074
- if (!off) {
2075
- children.push(
2076
- h('div', {
2077
- key: 'artifacts-sub',
2078
- style: {
2079
- display: 'flex',
2080
- flexDirection: 'column',
2081
- gap: '8px',
2082
- marginLeft: '10px',
2083
- paddingLeft: '14px',
2084
- borderLeft: '2px solid rgba(127,127,127,0.35)',
2085
- },
2086
- },
2087
- h(primitives.Checkbox, {
2088
- key: 'auto',
2089
- checked: auto,
2090
- label: translate('pageArtifactsAuto'),
2091
- onChange: (checked) => {
2092
- setAuto(checked === true)
2093
- setArtifactsAuto(checked === true)
2094
- },
2095
- }),
2096
- h('p', { key: 'autoHint', className: 'dsdel-page-hint' }, translate(auto ? 'pageHintArtifactsAuto' : 'pageHintArtifactsAsk')),
2097
- h('div', {
2098
- key: 'scope',
2099
- style: {
2100
- display: 'flex',
2101
- flexDirection: 'column',
2102
- gap: '8px',
2103
- marginLeft: '2px',
2104
- paddingLeft: '14px',
2105
- borderLeft: '2px solid rgba(127,127,127,0.2)',
2106
- },
2107
- },
2108
- h(primitives.Checkbox, {
2109
- key: 'scopeCreated',
2110
- checked: scope === 'created',
2111
- label: translate('pageScopeCreated'),
2112
- onChange: (checked) => {
2113
- if (checked !== true) return
2114
- setScope('created')
2115
- setArtifactScope('created')
2116
- },
2117
- }),
2118
- h(primitives.Checkbox, {
2119
- key: 'scopeAll',
2120
- checked: scope === 'all',
2121
- label: translate('pageScopeAll'),
2122
- onChange: (checked) => {
2123
- if (checked !== true) return
2124
- setScope('all')
2125
- setArtifactScope('all')
2126
- },
2127
- }),
2128
- ),
2129
- h('p', { key: 'scopeHint', className: 'dsdel-page-hint' }, translate(scope === 'all' ? 'pageScopeAllHint' : 'pageScopeCreatedHint')),
2130
- h(primitives.Checkbox, {
2131
- key: 'skipGit',
2132
- checked: skipGit,
2133
- label: translate('pageSkipGit'),
2134
- onChange: (checked) => {
2135
- setSkipGit(checked === true)
2136
- setSkipGitRepos(checked === true)
2137
- },
2138
- }),
2139
- h('p', { key: 'skipGitHint', className: 'dsdel-page-hint' },
2140
- translate(skipGit ? 'pageSkipGitOn' : 'pageSkipGitOff')),
2141
- h('div', { key: 'root', style: { display: 'flex', flexDirection: 'column', gap: '6px', marginTop: '2px' } },
2142
- h('p', { key: 'rootLabel', className: 'dsdel-page-hint' }, translate('pageRootLabel')),
2143
- h('div', { key: 'rootRow', style: { display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' } },
2144
- h('input', {
2145
- key: 'rootInput',
2146
- type: 'text',
2147
- className: 'dsdel-root-input',
2148
- value: root,
2149
- placeholder: defaultRootValue() || translate('pageRootPlaceholder'),
2150
- spellCheck: false,
2151
- onChange: (event) => {
2152
- setQuarantineRoot((event && event.target && event.target.value) || '')
2153
- },
2154
- }),
2155
- h(primitives.Button, {
2156
- key: 'browse',
2157
- variant: 'outline',
2158
- onClick: () => chooseFolder(),
2159
- children: translate('pageRootBrowse'),
2160
- }),
2161
- h(primitives.Button, {
2162
- key: 'open',
2163
- variant: 'outline',
2164
- onClick: () => openQuarantineRoot(root === '' ? defaultRootValue() : root),
2165
- children: translate('pageRootOpen'),
2166
- }),
2167
- h(primitives.Button, {
2168
- key: 'reset',
2169
- variant: 'outline',
2170
- disabled: root === '',
2171
- onClick: () => setQuarantineRoot(''),
2172
- children: translate('pageRootReset'),
2173
- }),
2174
- ),
2175
- h('p', { key: 'rootHint', className: 'dsdel-page-hint' },
2176
- root === ''
2177
- ? translate('pageRootDefaultHint', defaultRootValue() || '-')
2178
- : translate('pageRootCustomHint')),
2179
- ),
2180
- ),
2181
- )
2182
- }
2183
-
2184
- // A quiet link to the repository, last in the card. It is a nudge, not a
2185
- // setting, so it never competes with the controls above it — and it is a
2186
- // plain anchor, so clicking it opens the page instead of switching tabs here.
2187
- children.push(h('div', { key: 'star', className: 'dsdel-star' },
2188
- h('span', { key: 'ask' }, translate('starAsk')),
2189
- h('a', {
2190
- key: 'cta',
2191
- className: 'dsdel-star-link',
2192
- href: 'https://github.com/DDDMUC/dsh-delete-session',
2193
- target: '_blank',
2194
- rel: 'noreferrer',
2195
- }, translate('starCta'))))
2196
-
2197
- // Each control owns the nodes that explain it. Grouping them here keeps the
2198
- // markup above flat (a switch and its hint are still two pushes) while the
2199
- // page draws them as one block.
2200
- const FIELD_KEYS = new Set(['ask', 'recycle', 'syncChildren', 'off', 'auto', 'scope', 'skipGit', 'root'])
2201
- function groupFields(nodes) {
2202
- const groups = []
2203
- let current = null
2204
- for (const node of nodes) {
2205
- const key = node !== null && node !== undefined && node.props ? node.props.key : undefined
2206
- if (FIELD_KEYS.has(key)) {
2207
- current = { control: key, nodes: [node] }
2208
- groups.push(current)
2209
- continue
2210
- }
2211
- // The hint of a control is keyed `<control>Hint`; the root row keeps its
2212
- // input, buttons and hint under the same prefix.
2213
- if (current !== null && typeof key === 'string' && key !== 'star' && key !== 'cta'
2214
- && key.startsWith(current.control)) {
2215
- current.nodes.push(node)
2216
- continue
2217
- }
2218
- current = null
2219
- groups.push({ control: null, nodes: [node] })
2220
- }
2221
- return groups.map((group, index) => (group.control === null
2222
- ? group.nodes[0]
2223
- : h('div', { key: `field:${group.control}`, className: 'dsdel-field' }, ...group.nodes)))
2224
- }
2225
-
2226
- return h('div', { className: 'dsdel-page' }, groupFields(children))
2227
- }
2228
-
2229
- // --- plugin ------------------------------------------------------------------
2230
-
2231
- function apply(ctx) {
2232
- ensureStyle()
2233
- // Capability bits other plugins read. Announced before any slot registers,
2234
- // so a relocate plugin that boots after this one finds it in place; the
2235
- // event covers the reverse order.
2236
- if (typeof window !== 'undefined') {
2237
- window.__DSH_DELETE_SESSION__ = { supportsBulkMove: true }
2238
- try {
2239
- if (typeof window.dispatchEvent === 'function' && typeof window.Event === 'function') {
2240
- window.dispatchEvent(new window.Event('dsh-session-delete:ready'))
2241
- }
2242
- } catch {
2243
- // a host without DOM events still reads the global
2244
- }
2245
- }
2246
-
2247
- sessionsSvc = ctx.get('sessions') || null
2248
- if (!sessionsSvc) {
2249
- try { ctx.inject(['sessions'], (sub) => { sessionsSvc = sub.sessions }) } catch { /* optional */ }
2250
- }
2251
- localeSvc = ctx.get('locale') || null
2252
-
2253
- // Slot components are handed a `t` bound to this namespace, so the
2254
- // dictionaries must reach the host - on BOTH arrival paths. If `locale`
2255
- // only turns up through `ctx.inject`, a registration living on the
2256
- // synchronous branch would never run and the menu would fall back to
2257
- // printing raw keys ("multiSelect", "menu"). `ctx.effect` ties the
2258
- // registration's lifetime to the plugin, matching ui-workspace.
2259
- let localeRegistered = false
2260
- const adoptLocale = (svc) => {
2261
- localeSvc = svc || null
2262
- if (localeRegistered || !localeSvc || typeof localeSvc.register !== 'function') return
2263
- localeRegistered = true
2264
- const register = () => localeSvc.register(NS, { zh, en })
2265
- try {
2266
- if (typeof ctx.effect === 'function') ctx.effect(register, `${NS}: dictionaries`)
2267
- else register()
2268
- } catch { /* already registered */ }
2269
- }
2270
- if (localeSvc) adoptLocale(localeSvc)
2271
- else {
2272
- try { ctx.inject(['locale'], (sub) => adoptLocale(sub.locale)) } catch { /* optional */ }
2273
- }
2274
-
2275
- const install = (slots) => {
2276
- // The drag gesture is document-wide (the row is not ours), so these are
2277
- // plain capture listeners rather than slot handlers.
2278
- if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
2279
- document.addEventListener('dragstart', onDragStartCapture, true)
2280
- document.addEventListener('dragend', onDragEndCapture, true)
2281
- }
2282
- // Session menu rows. A package-namespaced id keeps them beside the
2283
- // shipped pin(100)/rename(200)/fork(300)/archive(400)/session-id(450).
2284
- slots.inject('sidebar.workspaces.session.menu.item', () => slots.register(
2285
- { name: 'sidebar.workspaces.session.menu.item', id: `${NS}-multi`, order: 409, locale: NS },
2286
- SelectMultipleMenuItem,
2287
- ))
2288
- slots.inject('sidebar.workspaces.session.menu.item', () => slots.register(
2289
- { name: 'sidebar.workspaces.session.menu.item', id: NS, order: 410, locale: NS },
2290
- DeleteSessionMenuItem,
2291
- ))
2292
- // The confirmation dialog rides the frame-wide overlay seat.
2293
- slots.inject('shell.overlay', () => slots.register(
2294
- { name: 'shell.overlay', id: `${NS}-dialog`, locale: NS },
2295
- DeleteSessionDialog,
2296
- ))
2297
- // The save-path picker is a second overlay: the settings card cannot host
2298
- // a modal of its own.
2299
- slots.inject('shell.overlay', () => slots.register(
2300
- { name: 'shell.overlay', id: `${NS}-picker`, order: 1, locale: NS },
2301
- QuarantinePicker,
2302
- ))
2303
- // The plugin page card, on BOTH seats the manager offers.
2304
- //
2305
- // `plugins.bundle.config` renders on the package page, whose address is
2306
- // `#/panel/plugins/<package>`. `plugins.row.config` renders on the row's
2307
- // own page, `#/panel/plugins/<package>/<rowId>` — and this bundle's row id
2308
- // is the package name, so that address repeated itself. The row seat keeps
2309
- // only its `summary` face, which is the one line the rows list shows.
2310
- slots.inject('plugins.bundle.config', () => slots.register(
2311
- { name: 'plugins.bundle.config', key: NS },
2312
- AskBeforeDeleteOption,
2313
- ))
2314
- slots.inject('plugins.row.config', () => slots.register(
2315
- { name: 'plugins.row.config', key: `${NS}#${NS}` },
2316
- AskBeforeDeleteOption,
2317
- ))
2318
- // The batch bar rides the official footer seat, so the host owns its
2319
- // position and the row it shares with the account chip.
2320
- slots.inject('sidebar.footer.action', () => slots.register(
2321
- { name: 'sidebar.footer.action', id: `${NS}-bulkbar`, order: 30, locale: NS },
2322
- BulkBar,
2323
- ))
2324
-
2325
- // Leaving the mode disconnects the row observer and strips the checkboxes.
2326
- return () => {
2327
- if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
2328
- document.removeEventListener('dragstart', onDragStartCapture, true)
2329
- document.removeEventListener('dragend', onDragEndCapture, true)
2330
- }
2331
- state.drag = null
2332
- syncFooterMode()
2333
- exitSelection()
2334
- }
2335
- }
2336
-
2337
- const slots = ctx.get('slots')
2338
- if (slots) {
2339
- const dispose = install(slots)
2340
- ctx.effect(() => dispose)
2341
- } else {
2342
- try {
2343
- ctx.inject(['slots'], (sub) => {
2344
- const dispose = install(sub.slots)
2345
- ctx.effect(() => dispose)
2346
- })
2347
- } catch { /* no slot surface on this profile */ }
2348
- }
2349
- }
2350
-
2351
- return { apply }
2352
- },
2353
- })
1
+ // dsh-delete-session - client half.
2
+ //
3
+ // Integration is entirely through the host's public slot contract - no menu
4
+ // scraping, no React internals:
5
+ //
6
+ // * `sidebar.workspaces.session.menu.item` - two rows registered beside the
7
+ // shipped pin/rename/fork/archive rows: "Select multiple" (order 409) and
8
+ // "Delete session" (order 410, in the host's danger colour). Each entry
9
+ // renders one `role="menuitem"` button through ui-primitives'
10
+ // `MenuItemButton`, so it inherits the host styling and joins the menu's
11
+ // own keyboard walk and focus return.
12
+ // * `shell.overlay` - the confirmation dialog, rendered with the host's
13
+ // `Modal` primitive instead of a hand-built backdrop.
14
+ // * `plugins.row.config` - the plugin page card that decides whether a
15
+ // delete asks first.
16
+ //
17
+ // The one surface with no usable slot is the multi-select checkbox on each
18
+ // Session row: `sidebar.session.row.leading` is the *else* branch of the host's
19
+ // `showStatus ? <SessionStatusDots/> : renderSlot(...)`, so it disappears the
20
+ // moment a row is busy - exactly when a batch delete is most likely. Those
21
+ // checkboxes therefore stay a DOM decoration over `[role="treeitem"]`, and row
22
+ // identity comes from the host's own `data-row-key="session:<id>"` attribute
23
+ // rather than from a walk up the React fiber tree.
24
+ //
25
+ // The module is a classic client bundle (client-modules protocol): it registers
26
+ // a factory with `window.__ModuleLoader__` and returns apply().
27
+ window.__ModuleLoader__.load({
28
+ id: 'dsh-delete-session',
29
+ factory: (require) => {
30
+ const NS = 'dsh-delete-session'
31
+ const react = require('react')
32
+ const primitives = require('@deepseek-ai/dsh-client-ui-primitives')
33
+
34
+ const { createElement: h, Fragment } = react
35
+
36
+ const zh = {
37
+ menu: '删除会话',
38
+ multiSelect: '多选',
39
+ title: '删除会话',
40
+ descRecycle: '将把该会话及其全部对话记录(会话日志、工作区记账与统计)从列表中移除,并放进系统回收站。',
41
+ descPermanent: '将永久删除该会话及其全部对话记录(会话日志、工作区记账与统计),此操作不可恢复。',
42
+ cancel: '取消',
43
+ confirm: '删除',
44
+ deleting: '删除中…',
45
+ done: '已删除会话',
46
+ failed: '删除失败:',
47
+ busy: '该会话正被 DSH 打开,删除未能完成;请稍后重试(通常几秒后即可),或重启 DSH 后再试。',
48
+ notFound: '未找到该会话(可能已被删除)。',
49
+ untitled: '未命名会话',
50
+ cancelSelect: '取消',
51
+ selectedCount: (n) => `已选 ${n} 个`,
52
+ batchRunning: (done, total) => `正在删除 ${done}/${total}…`,
53
+ moveSelected: '移动',
54
+ batchMoving: (done, total) => `正在移动 ${done}/${total}…`,
55
+ batchMoved: (ok, fail) => (fail > 0 ? `已移动 ${ok} 个 / ${fail} 个失败` : `已移动 ${ok} 个`),
56
+ moveBadResult: (fields) => `移动结果缺少字段:${fields}`,
57
+ deleteSelected: '删除',
58
+ batchDone: (n) => `已删除 ${n} 个会话`,
59
+ batchPartial: (ok, fail) => `已删除 ${ok} 个,${fail} 个失败`,
60
+ batchFailed: '批量删除失败:',
61
+ pageAsk: '删除时询问',
62
+ pageRecycle: '删除至回收站',
63
+ pageSyncChildren: '同时删除子会话',
64
+ dropHint: '拖到这里删除',
65
+ dropRelease: '松手删除「{name}」',
66
+ dropFallback: '这个对话',
67
+ starAsk: '⭐ 顺手留颗 Star,作者能高兴一整天',
68
+ starCta: '行,给你一颗 Star',
69
+ pageSyncChildrenOn: '删除对话时,把它派生的子代理会话一起删掉。',
70
+ pageSyncChildrenOff: '不勾选时,删除前会列出子会话,由你勾选要删哪些。',
71
+ childrenHint: '这个对话有 {n} 个子会话(子代理),勾选的会一起删除。',
72
+ pageRecycleOn: '删除后放进系统回收站,可以还原。',
73
+ pageRecycleOff: '删除后直接从硬盘移除,不可恢复。',
74
+ pageHintAsk: '每次删除会话前都会弹出确认框。',
75
+ pageHintAuto: '删除会话会直接执行,不再询问。',
76
+ // The produced-file list only exists inside the dialog, so ask mode keeps a
77
+ // delete dialog even when the confirmation above is turned off.
78
+ pageHintAutoWithArtifacts: '删除会话仍会弹窗——产出文件要先列清单给你勾选。',
79
+ pageSummaryAsk: '删除前询问',
80
+ pageSummaryAuto: '直接删除',
81
+ pageArtifactsOff: '不处理产出文件(保持当前行为)',
82
+ pageHintArtifactsOff: '删除会话只清理对话记录,完全不碰工作目录里的文件。',
83
+ pageHintArtifactsOn: '删除会话时还会处理这个对话在工作目录里碰过的文件。',
84
+ pageArtifactsAuto: '产出文件默认全部进隔离夹',
85
+ pageHintArtifactsAuto: '按下面的范围把匹配的文件全部移入隔离夹,不再询问。',
86
+ pageHintArtifactsAsk: '删除会话时会列出文件清单,由你勾选。',
87
+ pageScopeCreated: '仅新建的文件',
88
+ pageScopeAll: '新建的和改过的文件',
89
+ pageScopeCreatedHint: '只动这个对话自己创建的文件;它改过的既有文件一律不动。',
90
+ pageScopeAllHint: '还会包含这个对话改写过的既有文件 —— 移走它们会改变工作目录里原有的内容。',
91
+ pageSkipGit: '跳过 git 仓库内的文件',
92
+ pageSkipGitOn: '只处理不在 git 仓库里的文件;仓库里的代码不会被搬走。',
93
+ pageSkipGitOff: '仓库里的文件也会被搬进隔离夹 —— 删一个在项目里干过活的对话,可能把项目源码一起搬走。',
94
+ pageSummaryArtifactsOff: '不处理产出文件',
95
+ pageSummaryArtifactsAuto: '产出文件自动隔离',
96
+ pageSummaryArtifactsAsk: '产出文件先询问',
97
+ pageRootLabel: '隔离夹保存位置',
98
+ pageRootPlaceholder: '留空则使用默认路径',
99
+ pageRootBrowse: '选择文件夹…',
100
+ pageRootOpen: '打开',
101
+ rootOpened: '已在文件管理器中打开',
102
+ rootOpenFailed: '打开失败:',
103
+ pickerOpening: '已打开系统文件夹对话框,请在弹出的窗口里选择',
104
+ pickerFailed: '选择文件夹失败:',
105
+ pageRootReset: '用默认',
106
+ pageRootDefaultHint: (path) => `当前使用默认路径:${path}`,
107
+ pageRootCustomHint: '隔离夹会建在这个目录下,每次删除生成一个带时间戳的子目录',
108
+ pickerTitle: '选择隔离夹保存位置',
109
+ pickerLoading: '读取中…',
110
+ pickerEmpty: '这个目录下没有子目录',
111
+ pickerChoose: '选择此目录',
112
+ pickerTruncated: '子目录太多,只列出前 500 个',
113
+ pickerDefault: (path) => `默认路径:${path}`,
114
+ rootSet: '保存位置已更新',
115
+ artifactSection: '本对话产出的文件',
116
+ artifactOpenFolder: '打开所在文件夹',
117
+ artifactDeleteFile: '删除这个文件',
118
+ fileDeleted: '文件已删除',
119
+ fileRecycled: '文件已移入回收站',
120
+ fileDeleteFailed: '删除文件失败:',
121
+ revealFailed: '打开文件夹失败:',
122
+ artifactLoading: '正在扫描…',
123
+ artifactFailed: '扫描失败:',
124
+ artifactNone: '没有需要处理的文件。',
125
+ artifactCount: (created, modified) => `新建 ${created} 个 · 改过 ${modified} 个`,
126
+ artifactAutoNote: (n) => `删除后将把 ${n} 个文件移入隔离夹`,
127
+ // Auto mode does not scan, so it can state the outcome but not a count.
128
+ artifactAutoOnly: '产出文件会自动全部移入隔离夹,这里不再逐个列出。',
129
+ artifactRefused: (n) => `另有 ${n} 项已跳过`,
130
+ artifactSelected: (n) => `已选 ${n} 个`,
131
+ artifactMore: (n) => `另有 ${n} 个未列出`,
132
+ artifactTruncated: '清单过长已截断,未列出的不会处理。',
133
+ artifactScopeCreated: '范围:仅新建',
134
+ artifactScopeAll: '范围:新建 + 改过',
135
+ artifactModifiedWarn: '改过的既有文件(默认不选):',
136
+ doneQuarantine: (n) => `已删除会话,${n} 个文件已移入隔离夹`,
137
+ doneQuarantineFailed: (ok, fail) => `已删除会话,隔离 ${ok} 个、${fail} 个失败`,
138
+ }
139
+
140
+ const en = {
141
+ menu: 'Delete session',
142
+ multiSelect: 'Select multiple',
143
+ title: 'Delete session',
144
+ descRecycle: 'This removes the session and all of its conversation records (log, workspace accounting and statistics) from the list and puts them in the system trash.',
145
+ descPermanent: 'This permanently deletes the session and all of its conversation records (log, workspace accounting and statistics). This cannot be undone.',
146
+ cancel: 'Cancel',
147
+ confirm: 'Delete',
148
+ deleting: 'Deleting...',
149
+ done: 'Session deleted',
150
+ failed: 'Delete failed: ',
151
+ busy: 'This session is currently open in DSH; the delete did not complete. Try again in a moment (usually a few seconds), or restart DSH and retry.',
152
+ notFound: 'Session not found (it may already be deleted).',
153
+ untitled: 'Untitled session',
154
+ cancelSelect: 'Cancel',
155
+ selectedCount: (n) => `${n} selected`,
156
+ batchRunning: (done, total) => `Deleting ${done}/${total}...`,
157
+ moveSelected: 'Move',
158
+ batchMoving: (done, total) => `Moving ${done}/${total}...`,
159
+ batchMoved: (ok, fail) => (fail > 0 ? `Moved ${ok}, ${fail} failed` : `Moved ${ok}`),
160
+ moveBadResult: (fields) => `Move result is missing fields: ${fields}`,
161
+ deleteSelected: 'Delete',
162
+ batchDone: (n) => `Deleted ${n} session(s)`,
163
+ batchPartial: (ok, fail) => `Deleted ${ok}, ${fail} failed`,
164
+ batchFailed: 'Batch delete failed: ',
165
+ pageAsk: 'Ask before deleting',
166
+ pageRecycle: 'Delete to the Recycle Bin',
167
+ pageSyncChildren: 'Delete child sessions too',
168
+ dropHint: 'Drop here to delete',
169
+ dropRelease: 'Release to delete \'{name}\'',
170
+ dropFallback: 'this conversation',
171
+ starAsk: '⭐ A star would make the author\'s day',
172
+ starCta: 'Fine — have one',
173
+ pageSyncChildrenOn: 'A delete also removes the subagent sessions it spawned.',
174
+ pageSyncChildrenOff: 'When off, the dialog lists the child sessions and you tick the ones to delete.',
175
+ childrenHint: 'This conversation has {n} child sessions (subagents). Ticked ones are deleted too.',
176
+ pageRecycleOn: 'The session goes to the system trash and can be restored.',
177
+ pageRecycleOff: 'The session is removed from the disk right away and cannot be restored.',
178
+ pageHintAsk: 'Show a confirmation dialog before every session delete.',
179
+ pageHintAuto: 'Delete the session right away without asking.',
180
+ pageHintAutoWithArtifacts: 'A delete still opens a dialog, because the produced-file list has to be shown first.',
181
+ pageSummaryAsk: 'Ask before deleting',
182
+ pageSummaryAuto: 'Delete without asking',
183
+ pageArtifactsOff: 'Leave produced files alone (current behaviour)',
184
+ pageHintArtifactsOff: 'Deleting a session clears its record only and never touches files in the working directory.',
185
+ pageHintArtifactsOn: 'Deleting a session also handles the files this conversation touched in its working directory.',
186
+ pageArtifactsAuto: 'Send produced files straight to quarantine',
187
+ pageHintArtifactsAuto: 'Every file in the scope below moves to quarantine without asking.',
188
+ pageHintArtifactsAsk: 'Deleting a session lists the files and lets you tick what to move.',
189
+ pageScopeCreated: 'Only files it created',
190
+ pageScopeAll: 'Created and changed files',
191
+ pageScopeCreatedHint: 'Touches only files this conversation created; files it merely edited are never moved.',
192
+ pageScopeAllHint: 'Also includes pre-existing files this conversation rewrote — moving them changes what was already in the working directory.',
193
+ pageSkipGit: 'Skip files inside a git repository',
194
+ pageSkipGitOn: 'Only files outside git repositories are handled; code inside a repository is never moved.',
195
+ pageSkipGitOff: 'Repository files move into quarantine too — deleting a conversation that worked in a project can carry the project source away.',
196
+ pageSummaryArtifactsOff: 'Produced files left alone',
197
+ pageSummaryArtifactsAuto: 'Produced files auto-quarantined',
198
+ pageSummaryArtifactsAsk: 'Produced files ask first',
199
+ pageRootLabel: 'Quarantine folder location',
200
+ pageRootPlaceholder: 'Leave empty to use the default path',
201
+ pageRootBrowse: 'Choose folder…',
202
+ pageRootOpen: 'Open',
203
+ rootOpened: 'Opened in the file manager',
204
+ rootOpenFailed: 'Could not open: ',
205
+ pickerOpening: 'The system folder dialog is open; pick a folder in that window',
206
+ pickerFailed: 'Could not open the folder picker: ',
207
+ pageRootReset: 'Use default',
208
+ pageRootDefaultHint: (path) => `Using the default path: ${path}`,
209
+ pageRootCustomHint: 'The quarantine folder is created here, one timestamped subfolder per delete',
210
+ pickerTitle: 'Choose where quarantined files go',
211
+ pickerLoading: 'Reading…',
212
+ pickerEmpty: 'No subfolders here',
213
+ pickerChoose: 'Use this folder',
214
+ pickerTruncated: 'Too many subfolders: only the first 500 are listed',
215
+ pickerDefault: (path) => `Default path: ${path}`,
216
+ rootSet: 'Location updated',
217
+ artifactSection: 'Files this conversation produced',
218
+ artifactOpenFolder: 'Open containing folder',
219
+ artifactDeleteFile: 'Delete this file',
220
+ fileDeleted: 'File deleted',
221
+ fileRecycled: 'File moved to the recycle bin',
222
+ fileDeleteFailed: 'Could not delete the file: ',
223
+ revealFailed: 'Could not open the folder: ',
224
+ artifactLoading: 'Scanning...',
225
+ artifactFailed: 'Scan failed: ',
226
+ artifactNone: 'Nothing to handle.',
227
+ artifactCount: (created, modified) => `${created} created · ${modified} changed`,
228
+ artifactAutoNote: (n) => `${n} file(s) will move to quarantine on delete`,
229
+ artifactAutoOnly: 'Produced files move to quarantine automatically; they are not listed here.',
230
+ artifactRefused: (n) => `${n} more were skipped`,
231
+ artifactSelected: (n) => `${n} selected`,
232
+ artifactMore: (n) => `${n} more not listed`,
233
+ artifactTruncated: 'The list was truncated; anything unlisted is left alone.',
234
+ artifactScopeCreated: 'Scope: created only',
235
+ artifactScopeAll: 'Scope: created + changed',
236
+ artifactModifiedWarn: 'Pre-existing files it changed (unticked by default):',
237
+ doneQuarantine: (n) => `Session deleted, ${n} file(s) moved to quarantine`,
238
+ doneQuarantineFailed: (ok, fail) => `Session deleted, ${ok} quarantined and ${fail} failed`,
239
+ }
240
+
241
+ let sessionsSvc = null
242
+ let localeSvc = null
243
+
244
+ function browserLang() {
245
+ if (typeof navigator === 'undefined') return 'zh'
246
+ for (const tag of (navigator.languages || []).concat([navigator.language])) {
247
+ const primary = String(tag || '').toLowerCase().split('-')[0]
248
+ if (primary === 'zh' || primary === 'en') return primary
249
+ }
250
+ return 'zh'
251
+ }
252
+
253
+ // The DOM decoration layer (row checkboxes, batch bar, toast) is not a slot
254
+ // occupant, so it has no injected `t`; it uses the built-in dictionaries and
255
+ // honours the registered `locale` namespace when the host provides one.
256
+ // Slot components receive the host-injected `t` and use that instead.
257
+ function t(key, a, b) {
258
+ if (localeSvc && typeof localeSvc.translate === 'function') {
259
+ try {
260
+ const text = localeSvc.translate(NS, key)
261
+ if (typeof text === 'string' && text !== key) return text
262
+ } catch {
263
+ // fall back to the built-in dictionaries
264
+ }
265
+ }
266
+ const value = (browserLang() === 'en' ? en : zh)[key]
267
+ return typeof value === 'function' ? value(a, b) : value || key
268
+ }
269
+
270
+ /**
271
+ * Wrap a host-injected `t` so function-valued entries render their value.
272
+ *
273
+ * The locale contract leaves a function entry untouched: `translate(key, a, b)`
274
+ * returns the arrow function itself, and the caller is the one that invokes it.
275
+ * Using the injected `t` directly therefore printed the function's own source
276
+ * in the dialog ("(created, modified) => ...") instead of the numbers.
277
+ */
278
+ function localizedTranslator(injected) {
279
+ const raw = typeof injected === 'function' ? injected : t
280
+ if (raw.__dsdelLocalized === true) return raw
281
+ const wrapped = (key, a, b) => {
282
+ // Our own dictionary answers first, and it is resolved HERE rather than
283
+ // through the host. `dsh-client-locale` interpolates whatever it finds as
284
+ // soon as params are present - it calls `template.replace(...)` - while
285
+ // most of these entries are functions. Handing it params made the host
286
+ // throw "template.replace is not a function", and the slot boundary turned
287
+ // that into an empty `data-slot-error` anchor: the bar vanished, Cancel
288
+ // and all. Calling it without params is no better: the host (and this
289
+ // module's own `t`) invoke function entries with no arguments, which
290
+ // produces "已选 undefined 个".
291
+ const dictionary = browserLang() === 'en' ? en : zh
292
+ const local = dictionary[key]
293
+ if (local !== undefined) {
294
+ if (typeof local === 'function') return local(a, b)
295
+ if (typeof local === 'string' && local.includes('{') && a !== undefined) {
296
+ const params = a !== null && typeof a === 'object'
297
+ ? a
298
+ : { n: a, done: a, total: b, ok: a, fail: b, path: a }
299
+ return local.replace(/\{(\w+)\}/g, (match, name) => (
300
+ params[name] === undefined ? match : String(params[name])
301
+ ))
302
+ }
303
+ return local
304
+ }
305
+ // A key this plugin does not ship: let the host answer.
306
+ const value = raw(key)
307
+ return typeof value === 'function' ? value(a, b) : (value === undefined || value === null ? key : value)
308
+ }
309
+ wrapped.__dsdelLocalized = true
310
+ return wrapped
311
+ }
312
+
313
+ // --- state -----------------------------------------------------------------
314
+ // One module-level store shared by the slot components and the DOM layer.
315
+ // Components read it through `useSnapshot`, so each stays a plain function of
316
+ // the store with no local state - which also keeps it drivable from the
317
+ // offline test without a React renderer.
318
+
319
+ const state = {
320
+ /** { sessionId, title, busy, error, skip } while a confirmation dialog is up. */
321
+ dialog: null,
322
+ selecting: false,
323
+ selected: new Set(),
324
+ /** Rows hidden optimistically while their delete request is in flight. */
325
+ pending: new Set(),
326
+ /** { total, done, failed } while a batch delete runs, else null. */
327
+ batch: null,
328
+ /** Folder-picker state while it is open, else null. */
329
+ picker: null,
330
+ /** The host's default quarantine root, fetched once so the card can name it. */
331
+ defaultRoot: null,
332
+ /**
333
+ * The session being dragged over the footer, or null. `over` arms the drop:
334
+ * the bar only says "松手删除" once the pointer is actually on it.
335
+ */
336
+ drag: null,
337
+ }
338
+
339
+ const listeners = new Set()
340
+
341
+ function buildSnapshot() {
342
+ return {
343
+ dialog: state.dialog,
344
+ selecting: state.selecting,
345
+ selected: state.selected,
346
+ pending: state.pending,
347
+ batch: state.batch,
348
+ picker: state.picker,
349
+ defaultRoot: state.defaultRoot,
350
+ drag: state.drag,
351
+ selectedCount: state.selected.size,
352
+ }
353
+ }
354
+
355
+ // `useSyncExternalStore` needs a value that is stable between notifications.
356
+ let snapshot = buildSnapshot()
357
+
358
+ function getSnapshot() {
359
+ return snapshot
360
+ }
361
+
362
+ function subscribe(listener) {
363
+ listeners.add(listener)
364
+ return () => { listeners.delete(listener) }
365
+ }
366
+
367
+ function publish() {
368
+ snapshot = buildSnapshot()
369
+ for (const listener of listeners) {
370
+ try { listener() } catch { /* a subscriber must not break the mutation */ }
371
+ }
372
+ scheduleDecorate()
373
+ }
374
+
375
+ // `useSyncExternalStore` where the host's React has it (React 18+), otherwise
376
+ // a subscribe/effect pair. Chosen once at module scope, so no hook is called
377
+ // conditionally during a render.
378
+ const useSnapshot = typeof react.useSyncExternalStore === 'function'
379
+ ? () => react.useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
380
+ : () => {
381
+ const [value, setValue] = react.useState(getSnapshot)
382
+ react.useEffect(() => subscribe(() => setValue(getSnapshot())), [])
383
+ return value
384
+ }
385
+
386
+ // --- confirmation preference ----------------------------------------------
387
+
388
+ // Once the user opts out ("删除时询问" unticked - either in the plugin page or
389
+ // via the dialog's "don't ask again") the confirmation dialog is skipped and
390
+ // the menu item deletes directly. The plugin page's checkbox and the dialog
391
+ // read the same key, and a subscription keeps the card in step when either
392
+ // one flips it.
393
+ const SKIP_KEY = 'dsh-delete-session:skip-confirm'
394
+ const skipListeners = new Set()
395
+
396
+ function skipConfirm() {
397
+ try { return localStorage.getItem(SKIP_KEY) === '1' } catch { return false }
398
+ }
399
+
400
+ function setSkipConfirm(value) {
401
+ const skip = value === true
402
+ try {
403
+ if (skip) localStorage.setItem(SKIP_KEY, '1')
404
+ else localStorage.removeItem(SKIP_KEY)
405
+ } catch { /* private mode: ignore */ }
406
+ for (const listener of skipListeners) {
407
+ try { listener() } catch { /* a subscriber must not break the toggle */ }
408
+ }
409
+ }
410
+
411
+ function subscribeSkip(listener) {
412
+ skipListeners.add(listener)
413
+ return () => { skipListeners.delete(listener) }
414
+ }
415
+
416
+ // --- artifact preferences --------------------------------------------------
417
+ // The produced-files feature ships OFF: `OFF_KEY` is ticked unless the user
418
+ // explicitly clears it, so an existing install keeps behaving exactly as it
419
+ // did before the feature existed. When it is on, `AUTO_KEY` decides whether
420
+ // the dialog asks, and `SCOPE_KEY` decides what the candidate set is.
421
+
422
+ const OFF_KEY = 'dsh-delete-session:artifacts-off'
423
+ const AUTO_KEY = 'dsh-delete-session:artifacts-auto'
424
+ const SCOPE_KEY = 'dsh-delete-session:artifact-scope'
425
+ /** Where the timestamped quarantine folder is created. Empty means the DSH home. */
426
+ const ROOT_KEY = 'dsh-delete-session:quarantine-root'
427
+ /** Skip files inside a git working tree when quarantining. */
428
+ const SKIP_GIT_KEY = 'dsh-delete-session:skip-git'
429
+ /** Whether a delete goes to the system trash instead of vanishing. */
430
+ const RECYCLE_KEY = 'dsh-delete-session:recycle'
431
+ /** Whether a delete takes the subagent sessions with it, without asking. */
432
+ const SYNC_CHILDREN_KEY = 'dsh-delete-session:sync-children'
433
+ /** How many artifact rows the dialog lists before collapsing the rest. */
434
+ const ARTIFACT_ROWS_SHOWN = 40
435
+ const prefListeners = new Set()
436
+
437
+ function readPref(key, fallback) {
438
+ try {
439
+ const value = localStorage.getItem(key)
440
+ return value === null ? fallback : value
441
+ } catch {
442
+ return fallback
443
+ }
444
+ }
445
+
446
+ function writePref(key, value) {
447
+ try {
448
+ if (value === null) localStorage.removeItem(key)
449
+ else localStorage.setItem(key, value)
450
+ } catch {
451
+ // private mode: the preference simply does not persist
452
+ }
453
+ for (const listener of prefListeners) {
454
+ try { listener() } catch { /* a subscriber must not break the toggle */ }
455
+ }
456
+ }
457
+
458
+ function subscribePrefs(listener) {
459
+ prefListeners.add(listener)
460
+ return () => { prefListeners.delete(listener) }
461
+ }
462
+
463
+ /** Whether the produced-files feature is off. Off unless explicitly enabled. */
464
+ function artifactsOff() {
465
+ return readPref(OFF_KEY, '1') !== '0'
466
+ }
467
+
468
+ function setArtifactsOff(off) {
469
+ writePref(OFF_KEY, off ? null : '0')
470
+ }
471
+
472
+ /** Whether the whole candidate set moves without asking. */
473
+ function artifactsAuto() {
474
+ return readPref(AUTO_KEY, '0') === '1'
475
+ }
476
+
477
+ function setArtifactsAuto(auto) {
478
+ writePref(AUTO_KEY, auto ? '1' : null)
479
+ }
480
+
481
+ /** Candidate scope: files this session created, or those plus the ones it changed. */
482
+ function artifactScope() {
483
+ return readPref(SCOPE_KEY, 'created') === 'all' ? 'all' : 'created'
484
+ }
485
+
486
+ function setArtifactScope(scope) {
487
+ writePref(SCOPE_KEY, scope === 'all' ? 'all' : 'created')
488
+ }
489
+
490
+ /**
491
+ * Skip files that live inside a git working tree. On by default: a session
492
+ * started in a repository produces that repository's source, and moving it
493
+ * out from under the project is never what "clean up the files this chat
494
+ * created" means.
495
+ */
496
+ function skipGitRepos() {
497
+ return readPref(SKIP_GIT_KEY, '1') === '1'
498
+ }
499
+
500
+ function setSkipGitRepos(skip) {
501
+ writePref(SKIP_GIT_KEY, skip ? null : '0')
502
+ }
503
+
504
+ /**
505
+ * Send the session to the system trash rather than removing it outright.
506
+ * On by default: a wrong click should be undoable unless the user said otherwise.
507
+ */
508
+ function recycleSession() {
509
+ return readPref(RECYCLE_KEY, '1') === '1'
510
+ }
511
+
512
+ function setRecycleSession(on) {
513
+ writePref(RECYCLE_KEY, on ? null : '0')
514
+ }
515
+
516
+ /**
517
+ * Take the child sessions along without asking. Off by default: a subagent is
518
+ * a conversation of its own, so it is offered rather than swept up.
519
+ */
520
+ function syncChildren() {
521
+ return readPref(SYNC_CHILDREN_KEY, '1') !== '0'
522
+ }
523
+
524
+ function setSyncChildren(on) {
525
+ // "Off" is written as '0' rather than cleared: the default is now on, so a
526
+ // removed key would read back as on again.
527
+ writePref(SYNC_CHILDREN_KEY, on ? '1' : '0')
528
+ }
529
+
530
+ /** The chosen quarantine root, or '' for "use the host default". */
531
+ function quarantineRoot() {
532
+ return readPref(ROOT_KEY, '')
533
+ }
534
+
535
+ function setQuarantineRoot(value) {
536
+ writePref(ROOT_KEY, typeof value === 'string' && value.trim() !== '' ? value.trim() : null)
537
+ }
538
+
539
+ // --- host calls ------------------------------------------------------------
540
+
541
+ /** The read-only artifact scan the dialog renders. */
542
+ function postArtifacts(sessionId) {
543
+ const root = quarantineRoot()
544
+ const payload = root === '' ? { sessionId } : { sessionId, root }
545
+ payload.skipGit = skipGitRepos()
546
+ return fetch('/dsh-delete-session/artifacts', {
547
+ method: 'POST',
548
+ headers: { 'content-type': 'application/json' },
549
+ body: JSON.stringify(payload),
550
+ }).then(async (res) => {
551
+ let data = {}
552
+ try { data = await res.json() } catch { /* keep {} */ }
553
+ if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
554
+ return data
555
+ })
556
+ }
557
+
558
+ /** One directory listing for the folder picker. */
559
+ function postBrowse(target) {
560
+ return fetch('/dsh-delete-session/browse', {
561
+ method: 'POST',
562
+ headers: { 'content-type': 'application/json' },
563
+ body: JSON.stringify(target === undefined || target === '' ? {} : { path: target }),
564
+ }).then(async (res) => {
565
+ let data = {}
566
+ try { data = await res.json() } catch { /* keep {} */ }
567
+ if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
568
+ return data
569
+ })
570
+ }
571
+
572
+ /**
573
+ * Ask the host to raise the real Windows folder dialog. The request stays open
574
+ * while the user browses, so `code` is carried on failures: `unsupported`
575
+ * means this platform has no native dialog and the in-page picker should run.
576
+ */
577
+ function postPick() {
578
+ return fetch('/dsh-delete-session/pick', {
579
+ method: 'POST',
580
+ headers: { 'content-type': 'application/json' },
581
+ body: JSON.stringify({}),
582
+ }).then(async (res) => {
583
+ let data = {}
584
+ try { data = await res.json() } catch { /* keep {} */ }
585
+ if (!res.ok || !data.ok) {
586
+ const error = new Error((data && data.error) || `HTTP ${res.status}`)
587
+ error.code = data && data.code
588
+ throw error
589
+ }
590
+ return data
591
+ })
592
+ }
593
+
594
+ /** Ask the host to show a directory in the OS file manager. */
595
+ function postReveal(target) {
596
+ return fetch('/dsh-delete-session/reveal', {
597
+ method: 'POST',
598
+ headers: { 'content-type': 'application/json' },
599
+ body: JSON.stringify({ path: target }),
600
+ }).then(async (res) => {
601
+ let data = {}
602
+ try { data = await res.json() } catch { /* keep {} */ }
603
+ if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
604
+ return data
605
+ })
606
+ }
607
+
608
+ /** Drop one row from the dialog after its file left the disk. */
609
+ function forgetFile(sessionId, target) {
610
+ const dialog = state.dialog
611
+ if (dialog === null || dialog.sessionId !== sessionId) return
612
+ const artifacts = dialog.artifacts
613
+ if (artifacts === null || artifacts.plan === null) return
614
+ artifacts.selected.delete(target)
615
+ const keep = (row) => row.path !== target
616
+ artifacts.plan = {
617
+ ...artifacts.plan,
618
+ created: (artifacts.plan.created || []).filter(keep),
619
+ modified: (artifacts.plan.modified || []).filter(keep),
620
+ }
621
+ publish()
622
+ }
623
+
624
+ /** Delete one produced file, then drop its row. */
625
+ function deleteOneFile(sessionId, target) {
626
+ const recycle = recycleSession()
627
+ postDeleteFile(sessionId, target, recycle).then((data) => {
628
+ forgetFile(sessionId, target)
629
+ toast(t(data && data.recycled === true ? 'fileRecycled' : 'fileDeleted'))
630
+ }).catch((reason) => {
631
+ toast(t('fileDeleteFailed') + String((reason && reason.message) || reason), true)
632
+ })
633
+ }
634
+
635
+ /**
636
+ * Delete one produced file. The recycle choice is the same preference that
637
+ * governs a conversation delete, so the two never disagree.
638
+ */
639
+ function postDeleteFile(sessionId, target, recycle) {
640
+ return fetch('/dsh-delete-session/delete-file', {
641
+ method: 'POST',
642
+ headers: { 'content-type': 'application/json' },
643
+ body: JSON.stringify({ sessionId, path: target, recycle }),
644
+ }).then(async (res) => {
645
+ let data = {}
646
+ try { data = await res.json() } catch { /* keep {} */ }
647
+ if (!res.ok || !data.ok) throw new Error((data && data.error) || `HTTP ${res.status}`)
648
+ return data
649
+ })
650
+ }
651
+
652
+ /**
653
+ * Show one produced file's folder. The host validates that the path is a
654
+ * directory; the browser has no path module, so the parent is taken with a
655
+ * plain last-separator split — Windows separators included.
656
+ */
657
+ function revealParent(filePath) {
658
+ const text = String(filePath === null || filePath === undefined ? '' : filePath).replace(/[\\/]+$/, '')
659
+ const cut = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
660
+ const parent = cut > 0 ? text.slice(0, cut) : text
661
+ if (parent === '') return
662
+ postReveal(parent).catch((reason) => {
663
+ toast(t('revealFailed') + String((reason && reason.message) || reason), true)
664
+ })
665
+ }
666
+
667
+ /** Show the quarantine folder the current settings would write to. */
668
+ function openQuarantineRoot(target) {
669
+ if (typeof target !== 'string' || target === '') return
670
+ postReveal(target)
671
+ .then(() => toast(t('rootOpened')))
672
+ .catch((reason) => toast(t('rootOpenFailed') + String((reason && reason.message) || reason), true))
673
+ }
674
+
675
+ function postDelete(sessionId, quarantine, childSessionIds) {
676
+ const root = quarantineRoot()
677
+ const payload = quarantine === undefined ? { sessionId } : { sessionId, quarantine }
678
+ if (root !== '') payload.root = root
679
+ // Subagent sessions are sessions of their own, so they travel as a list the
680
+ // host can verify rather than something it has to discover.
681
+ if (Array.isArray(childSessionIds) && childSessionIds.length > 0) {
682
+ payload.childSessionIds = childSessionIds
683
+ }
684
+ // Whether the files go to the system trash is a per-delete choice, so it
685
+ // travels with the request rather than being read from the host config.
686
+ payload.recycle = recycleSession()
687
+ return fetch('/dsh-delete-session/delete', {
688
+ method: 'POST',
689
+ headers: { 'content-type': 'application/json' },
690
+ body: JSON.stringify(payload),
691
+ }).then(async (res) => {
692
+ let data = {}
693
+ try { data = await res.json() } catch { /* keep {} */ }
694
+ if (!res.ok || !data.ok) {
695
+ const code = data && data.code
696
+ const message = code === 'busy'
697
+ ? t('busy')
698
+ : code === 'not-found'
699
+ ? t('notFound')
700
+ : (data && data.error) || `HTTP ${res.status}`
701
+ throw new Error(message)
702
+ }
703
+ return data
704
+ })
705
+ }
706
+
707
+ function refreshList() {
708
+ const svc = sessionsSvc
709
+ if (svc) {
710
+ try {
711
+ if (typeof svc.refresh === 'function') { svc.refresh(); return }
712
+ if (typeof svc.refreshList === 'function') { svc.refreshList(); return }
713
+ } catch {
714
+ // fall through to reload
715
+ }
716
+ }
717
+ try { window.location.reload() } catch { /* ignore */ }
718
+ }
719
+
720
+ // Deleting the session the main view is showing leaves the app to restore a
721
+ // stale neighbour (an unavailable Agent Team row with a disabled composer),
722
+ // which reads as "the delete did not work". Open a fresh session instead.
723
+ function deletedVariants(id) {
724
+ return id.startsWith('session-') ? [id, id.slice('session-'.length)] : [id, `session-${id}`]
725
+ }
726
+
727
+ function leaveIfCurrent(id) {
728
+ let current = null
729
+ try {
730
+ const raw = localStorage.getItem('dsh.sessions.current')
731
+ current = raw ? (JSON.parse(raw) || {}).sessionId || null : null
732
+ } catch {
733
+ return
734
+ }
735
+ if (!current || !deletedVariants(id).includes(current)) return
736
+ const btn = document.querySelector(
737
+ 'button[class*="newSession"], button[aria-label*="New session" i], button[aria-label*="新会话"]',
738
+ )
739
+ if (btn) {
740
+ try {
741
+ btn.click()
742
+ return
743
+ } catch {
744
+ // fall through to the state reset
745
+ }
746
+ }
747
+ try {
748
+ localStorage.removeItem('dsh.sessions.current')
749
+ window.location.reload()
750
+ } catch {
751
+ // ignore
752
+ }
753
+ }
754
+
755
+ // --- styles ----------------------------------------------------------------
756
+ // Only what the DOM decoration layer owns. The confirmation dialog is the
757
+ // host's `Modal`, so it brings no backdrop CSS of its own.
758
+
759
+ const CSS = [
760
+ '.dsdel-toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);z-index:2147483601;background:var(--dsw-alias-bg-overlay,var(--dsw-alias-bg-layer-1,#2b2b2b));color:var(--dsw-alias-label-primary,#fff);border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.3));padding:9px 16px;border-radius:10px;font-size:12.5px;line-height:18px;box-shadow:0 10px 28px rgba(0,0,0,.24);max-width:min(92vw,460px);cursor:pointer;animation:dsdel-toast-in .16s cubic-bezier(.2,.8,.3,1)}',
761
+ '@keyframes dsdel-toast-in{from{opacity:0;transform:translate(-50%,6px)}to{opacity:1;transform:translate(-50%,0)}}',
762
+ '@media (prefers-reduced-motion:reduce){.dsdel-toast{animation:none}.dsdel-field{transition:none}}',
763
+ '.dsdel-check{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;border:1.5px solid var(--dsw-alias-border-l3,rgba(128,128,128,.5));background:transparent;flex:none;margin-right:8px;box-sizing:border-box;cursor:pointer}',
764
+ '.dsdel-check-on{background:var(--dsw-alias-state-business-primary,#4c6ef5);border-color:var(--dsw-alias-state-business-primary,#4c6ef5)}',
765
+ '.dsdel-check-on::after{content:"";width:9px;height:5px;border-left:2px solid #fff;border-bottom:2px solid #fff;transform:rotate(-45deg) translateY(-1px)}',
766
+ // 乐观删除:行先隐藏,失败时随 decorate 恢复
767
+ '.dsdel-row-pending{display:none!important}',
768
+ '.dsdel-bar{display:flex;align-items:center;gap:8px;width:100%;min-width:0;padding:6px 8px;box-sizing:border-box;font-size:13px}',
769
+ // The sidebar foot stacks three things: the footer-action row, the usage
770
+ // card and the account row. While a selection runs only the action row
771
+ // stays, so the bar sits where the account row used to end the sidebar.
772
+ 'body.dsdel-selecting [class*="_footArea"] > *:not([class*="_footerActions"]){display:none}',
773
+ // The other footer buttons are named POSITIVELY, by the attributes their
774
+ // plugins put on them, and never by "everything except the bar": the bar
775
+ // turned out not to be a direct child of the slot container, so an
776
+ // exclusion rule silently hid the bar together with its Cancel button.
777
+ 'body.dsdel-selecting [data-slot="sidebar.footer.action"] > [data-dsh-plugin]{display:none}',
778
+ 'body.dsdel-selecting [data-slot="sidebar.footer.action"] > [class*="_entryRow"]{display:none}',
779
+ // A third shape: entries with no wrapper at all. The slot outlet is
780
+ // `display:contents` and the component is its direct child, so a bare
781
+ // <button> registration (dsh-sidebar-declutter's 收起面板列表) carries
782
+ // neither `data-dsh-plugin` nor an `_entryRow`, and the two rules above
783
+ // missed it. `> button` reaches exactly that shape.
784
+ //
785
+ // The `:not([role="toolbar"])` guard is not decoration: this plugin's own
786
+ // bar announces itself with role="toolbar", so an unguarded `> button`
787
+ // would hide the bar itself if its root ever became a <button>.
788
+ 'body.dsdel-selecting [data-slot="sidebar.footer.action"] > button:not([role="toolbar"]){display:none}',
789
+ '.dsdel-drop{border:1px dashed var(--dsw-alias-border-l2,rgba(128,128,128,.4));border-radius:8px;color:var(--dsw-alias-label-secondary,inherit)}',
790
+ '.dsdel-drop-over{border-color:var(--dsw-alias-state-error-primary,#e5484d);border-style:solid;background:rgba(229,72,77,.10);color:var(--dsw-alias-state-error-primary,#e5484d)}',
791
+ '.dsdel-drop-icon{display:inline-flex;flex:0 0 auto;align-items:center}',
792
+ '.dsdel-drop-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
793
+ '.dsdel-bar-count{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dsw-alias-label-secondary,inherit)}',
794
+ '.dsdel-bar-btn{flex:0 0 auto;white-space:nowrap;appearance:none;min-height:30px;padding:0 12px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.4));background:var(--dsw-alias-fill-elevated,rgba(128,128,128,.08));color:var(--dsw-alias-label-primary,inherit);border-radius:8px;font-size:13px;cursor:pointer}',
795
+ '.dsdel-bar-btn:focus-visible{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
796
+ '.dsdel-bar-btn:disabled{opacity:.5;cursor:default}',
797
+ '.dsdel-bar-danger{border-color:var(--dsw-alias-state-error-primary,#e5484d);background:var(--dsw-alias-state-error-primary,#e5484d);color:#fff}',
798
+ // One token layer for every surface this plugin draws. Everything below
799
+ // reads these rather than repeating a fallback per rule: the host theme then
800
+ // reaches the whole plugin through one block, which is the point of exposing
801
+ // tokens at all.
802
+ '.dsdel-page,.dsdel-modal,.dsdel-bar{--dsdel-bg:var(--dsw-alias-fill-elevated,rgba(127,127,127,.06));--dsdel-bg-hover:var(--dsw-alias-fill-hover,rgba(127,127,127,.10));--dsdel-border:var(--dsw-alias-border-l2,rgba(127,127,127,.28));--dsdel-label:var(--dsw-alias-label-primary,inherit);--dsdel-label-dim:var(--dsw-alias-label-secondary,#666);--dsdel-label-faint:var(--dsw-alias-label-tertiary,#888);--dsdel-danger:var(--dsw-alias-state-error-primary,#e5484d);--dsdel-radius:10px;--dsdel-radius-sm:8px;--dsdel-ring:color-mix(in srgb,var(--dsw-alias-brand-primary,#4c8dff) 45%,transparent);--dsdel-shadow:0 1px 2px rgba(0,0,0,.04)}',
803
+ '.dsdel-page{display:flex;flex-direction:column;gap:8px}',
804
+ // Each switch and its explanation read as one block, so a card with eight
805
+ // controls stops looking like one long column of tick boxes.
806
+ '.dsdel-field{display:flex;flex-direction:column;gap:2px;padding:10px 12px;border:1px solid var(--dsdel-border);border-radius:var(--dsdel-radius);background:var(--dsdel-bg);box-shadow:var(--dsdel-shadow);transition:background .12s ease,border-color .12s ease}',
807
+ '.dsdel-field:hover{background:var(--dsdel-bg-hover)}',
808
+ '.dsdel-field:focus-within{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
809
+ '.dsdel-page-hint{margin:0;color:var(--dsdel-label-faint);font-size:12.5px;line-height:19px;letter-spacing:.01em}',
810
+ // One produced file per row: tick on the left, path in the middle, a folder
811
+ // button on the right. The button sits outside the label so a click opens
812
+ // the folder instead of toggling the tick.
813
+ '.dsdel-file-row{display:flex;align-items:center;gap:8px;padding:4px 6px;border-radius:var(--dsdel-radius-sm);transition:background .12s ease}',
814
+ '.dsdel-file-row:hover{background:var(--dsdel-bg-hover)}',
815
+ '.dsdel-file-label{display:flex;align-items:center;gap:8px;flex:1;min-width:0;cursor:pointer}',
816
+ '.dsdel-file-path{flex:1;min-width:0;word-break:break-all;font-size:13px;line-height:20px;color:var(--dsdel-label)}',
817
+ '.dsdel-file-open{display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:26px;height:26px;padding:0;border:1px solid transparent;border-radius:var(--dsdel-radius-sm);background:transparent;color:var(--dsdel-label-dim);cursor:pointer;transition:background .12s ease,color .12s ease,border-color .12s ease}',
818
+ '.dsdel-file-open:hover{background:var(--dsdel-bg);border-color:var(--dsdel-border);color:var(--dsdel-label)}',
819
+ '.dsdel-file-open:focus-visible{outline:2px solid var(--dsdel-ring);outline-offset:1px}',
820
+ '.dsdel-file-remove:hover{background:color-mix(in srgb,var(--dsdel-danger) 12%,transparent);border-color:color-mix(in srgb,var(--dsdel-danger) 40%,transparent);color:var(--dsdel-danger)}',
821
+ '.dsdel-star{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex-wrap:wrap;font-size:12px;color:var(--dsw-alias-label-tertiary,#8b93a1);padding:2px 2px 0;}',
822
+ '.dsdel-star-link{color:var(--dsw-alias-brand-primary,#4d76e6);text-decoration:underline;}',
823
+ '.dsdel-root-input{flex:1 1 220px;min-width:160px;min-height:30px;padding:0 10px;border:1px solid var(--dsw-alias-border-secondary,#d0d0d0);border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:13px}',
824
+ '.dsdel-picker-path{margin:0 0 8px;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,#666);word-break:break-all}',
825
+ // A wider confirmation dialog: the class reaches it when `Modal` forwards
826
+ // `className`, and the `:has()` rule catches the host-owned container when
827
+ // it does not. Both are harmless if the other one is the one that applies.
828
+ '.dsdel-dialog-wide{width:min(46vw,860px)!important;max-width:min(46vw,860px)!important;min-height:min(240px,88vh)!important;max-height:88vh!important;display:flex;flex-direction:column;overflow:hidden}',
829
+ '.dsdel-dialog-wide > :first-child{flex:1 1 auto;min-height:0;overflow:auto}',
830
+ '.dsdel-dialog-wide > :last-child{flex:0 0 auto;margin-top:auto}',
831
+ '.dsdel-artifacts{overflow:auto;overscroll-behavior:contain;padding-right:2px}',
832
+ '[role="dialog"]:has(.dsdel-file-row),[aria-modal="true"]:has(.dsdel-file-row){width:min(46vw,860px);max-width:min(46vw,860px);min-height:min(240px,88vh);max-height:88vh}',
833
+ '.dsdel-picker-list{display:flex;flex-direction:column;gap:2px;max-height:280px;overflow:auto;margin:0 0 8px}',
834
+ '.dsdel-picker-row{appearance:none;text-align:left;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:13px;cursor:pointer}',
835
+ '.dsdel-picker-row:hover{background:var(--dsw-alias-fill-secondary,rgba(127,127,127,0.12))}',
836
+ '.dsdel-modal-text{margin:0;font-size:13px;line-height:1.6;color:var(--dsw-alias-label-secondary,#666);word-break:break-all}',
837
+ '.dsdel-modal-meta{margin:0 0 8px;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-tertiary,#888);word-break:break-all}',
838
+ '.dsdel-modal-error{margin:8px 0 0;font-size:12px;line-height:16px;color:var(--dsw-alias-state-error-primary,#e5484d)}',
839
+ // ui-primitives' `Button` has no danger variant (the host styles its own
840
+ // destructive buttons with a package-local CSS-module class), so the
841
+ // confirm button carries this class instead.
842
+ '.dsdel-danger-btn{border-color:var(--dsw-alias-state-error-primary,#e5484d)!important;background:var(--dsw-alias-state-error-primary,#e5484d)!important;color:#fff!important}',
843
+ '.dsdel-danger-btn:disabled{opacity:.5}',
844
+ ].join('')
845
+
846
+ function ensureStyle() {
847
+ if (typeof document === 'undefined') return
848
+ const existing = document.querySelector('style[data-dsh-delete-session]')
849
+ if (existing !== null) {
850
+ // This tag outlives the module instance: when a newer build re-executes in
851
+ // the same document, bailing out here would keep the old stylesheet and
852
+ // pair it with the new markup. Rewriting it keeps the two in step.
853
+ if (existing.textContent !== CSS) existing.textContent = CSS
854
+ return
855
+ }
856
+ const style = document.createElement('style')
857
+ style.dataset.dshDeleteSession = '1'
858
+ style.textContent = CSS
859
+ document.head.appendChild(style)
860
+ }
861
+
862
+ // --- feedback --------------------------------------------------------------
863
+
864
+ function toast(text, isError) {
865
+ if (typeof document === 'undefined' || !document.body) return
866
+ const el = document.createElement('div')
867
+ el.className = 'dsdel-toast'
868
+ el.setAttribute('role', 'status')
869
+ el.textContent = text
870
+ if (isError) {
871
+ el.style.background = '#4A1D1D'
872
+ el.style.color = '#FFD9D9'
873
+ }
874
+ document.body.appendChild(el)
875
+ const kill = () => el.remove()
876
+ el.addEventListener('click', kill)
877
+ setTimeout(kill, 3200)
878
+ }
879
+
880
+ // --- multi-select row decoration -------------------------------------------
881
+ // Entered from the session menu ("多选"). While active, every session row gets
882
+ // a round checkbox, clicking a row toggles it instead of opening the
883
+ // conversation, and a bottom bar runs the batch delete. No select-all and no
884
+ // per-row disabling: every row is selectable and the batch deletes
885
+ // immediately (the single-session flow keeps its own consent dialog).
886
+
887
+ // The bar lives in the sidebar footer slot: the host owns where that row sits,
888
+ // so there is no element here to create, dock or hide.
889
+ let decorateRaf = null
890
+ let rowObserver = null
891
+
892
+ // Row identity comes from the host's own drag-and-drop key rather than from
893
+ // React internals: every Session row carries `data-row-key="session:<id>"`.
894
+ // A row without it is simply not selectable.
895
+ const ROW_KEY_PREFIX = 'session:'
896
+
897
+ function sessionIdFromRow(row) {
898
+ if (!row || typeof row.getAttribute !== 'function') return null
899
+ const key = row.getAttribute('data-row-key')
900
+ if (typeof key !== 'string' || !key.startsWith(ROW_KEY_PREFIX)) return null
901
+ const id = key.slice(ROW_KEY_PREFIX.length)
902
+ return id === '' ? null : id
903
+ }
904
+
905
+ // --- drag a session onto the footer to delete it ---------------------------
906
+ //
907
+ // The id comes from the host's own `data-row-key`, never from `dataTransfer`:
908
+ // the official drag only reorders, and a dragover payload is unreadable anyway.
909
+ // The gesture ends in the same place as the menu row - the confirmation dialog
910
+ // unless the user turned asking off - so there is exactly one delete policy.
911
+
912
+ /** The row under the pointer, with the title the drop target can name. */
913
+ function draggedSession(event) {
914
+ const target = event === null || event === undefined ? null : event.target
915
+ const row = target && typeof target.closest === 'function'
916
+ ? target.closest('[role="treeitem"]')
917
+ : null
918
+ const sessionId = sessionIdFromRow(row)
919
+ if (sessionId === null) return null
920
+ const text = row !== null && typeof row.textContent === 'string' ? row.textContent.trim() : ''
921
+ const title = text === '' ? null : text.slice(0, 40)
922
+ return { sessionId, title }
923
+ }
924
+
925
+ function onDragStartCapture(event) {
926
+ // Inside multi-select a drag is the host reordering rows; deleting on drop
927
+ // would make the mode quietly destructive.
928
+ if (state.selecting) return
929
+ const info = draggedSession(event)
930
+ if (info === null) return
931
+ state.drag = { sessionId: info.sessionId, title: info.title, over: false }
932
+ syncFooterMode()
933
+ publish()
934
+ }
935
+
936
+ function onDragEndCapture() {
937
+ if (state.drag === null) return
938
+ state.drag = null
939
+ syncFooterMode()
940
+ publish()
941
+ }
942
+
943
+ /** Drop on the bar: same policy as the menu row. */
944
+ function dropToDelete() {
945
+ const drag = state.drag
946
+ if (drag === null) return
947
+ state.drag = null
948
+ syncFooterMode()
949
+ publish()
950
+ const needsDialog = !artifactsOff() && !artifactsAuto()
951
+ if (skipConfirm() && !needsDialog) deleteNow({ sessionId: drag.sessionId })
952
+ else openDeleteDialog(drag.sessionId, drag.title)
953
+ }
954
+
955
+ function decorateRows() {
956
+ if (typeof document === 'undefined') return
957
+ const rows = document.querySelectorAll('[role="treeitem"]')
958
+ rows.forEach((row) => {
959
+ const id = sessionIdFromRow(row)
960
+ if (!id) return
961
+ // Checkboxes belong to multi-select only: a single delete (or any other
962
+ // decorate pass outside the mode) must not plant them on every row.
963
+ // The checkbox is always the row's first element child, so it is read
964
+ // through the pointer. `querySelector` here ran twice per row per frame,
965
+ // which is the pass's dominant cost once the list is long.
966
+ const first = row.firstElementChild
967
+ const existing = first !== null && first !== undefined
968
+ && first.classList
969
+ && first.classList.contains(DEL_CHECK)
970
+ ? first
971
+ : null
972
+ if (!state.selecting) {
973
+ if (existing !== null) existing.remove()
974
+ } else {
975
+ let check = existing
976
+ if (!check) {
977
+ check = document.createElement('span')
978
+ check.className = DEL_CHECK
979
+ check.setAttribute('data-dsh-delete-session', 'check')
980
+ row.insertBefore(check, row.firstChild)
981
+ }
982
+ check.classList.toggle('dsdel-check-on', state.selected.has(id))
983
+ }
984
+ row.classList.toggle('dsdel-row-pending', state.pending.has(id))
985
+ })
986
+ if (!state.selecting) {
987
+ document.querySelectorAll('.dsdel-check').forEach((el) => el.remove())
988
+ }
989
+ }
990
+ /**
991
+ * A mutation batch only matters when a node came or went. Text streaming
992
+ * inside the transcript produces characterData records forever; scheduling a
993
+ * full row scan for those would burn a frame's budget on every token.
994
+ */
995
+ function onRowMutations(records) {
996
+ if (records === undefined || records === null) return scheduleDecorate()
997
+ for (const record of records) {
998
+ const added = record === null || record === undefined ? null : record.addedNodes
999
+ const removed = record === null || record === undefined ? null : record.removedNodes
1000
+ if ((added !== null && added !== undefined && added.length > 0)
1001
+ || (removed !== null && removed !== undefined && removed.length > 0)) {
1002
+ scheduleDecorate()
1003
+ return
1004
+ }
1005
+ }
1006
+ }
1007
+
1008
+ function scheduleDecorate() {
1009
+ if (typeof requestAnimationFrame !== 'function') return
1010
+ if (decorateRaf !== null) return
1011
+ decorateRaf = requestAnimationFrame(() => {
1012
+ decorateRaf = null
1013
+ try { decorateRows() } catch { /* best-effort DOM shim */ }
1014
+ })
1015
+ }
1016
+
1017
+ /**
1018
+ * The bulk-move face `dsh-session-relocate` publishes on `window`. Read when
1019
+ * the bar is built rather than cached at module load, so a relocate plugin
1020
+ * that registers after this one is still picked up.
1021
+ */
1022
+ function relocateApi() {
1023
+ if (typeof window === 'undefined') return null
1024
+ const api = window.__DSH_SESSION_RELOCATE__
1025
+ if (!api || api.supportsBulkMove !== true) return null
1026
+ if (typeof api.moveSelection !== 'function') return null
1027
+ return api
1028
+ }
1029
+
1030
+ /**
1031
+ * The batch bar, rendered into the host's `sidebar.footer.action` seat.
1032
+ *
1033
+ * The host decides where that row sits, how wide it is and whether the account
1034
+ * chip shares it. Occupying the slot means this plugin never measures, docks,
1035
+ * hides or restores host DOM: the row gains our controls while a selection is
1036
+ * running, and loses them the moment it ends.
1037
+ */
1038
+ function BulkBar({ t: injected }) {
1039
+ const translate = localizedTranslator(injected)
1040
+ const view = useSnapshot()
1041
+ // A session dragged over the sidebar turns the footer into a drop target.
1042
+ if (view.drag !== null && view.drag !== undefined) {
1043
+ const armed = view.drag.over === true
1044
+ const name = view.drag.title === null || view.drag.title === undefined
1045
+ ? translate('dropFallback')
1046
+ : view.drag.title
1047
+ return h('div', {
1048
+ className: armed ? 'dsdel-bar dsdel-drop dsdel-drop-over' : 'dsdel-bar dsdel-drop',
1049
+ role: 'toolbar',
1050
+ onDragOver: (event) => {
1051
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
1052
+ if (event && event.dataTransfer) {
1053
+ try { event.dataTransfer.dropEffect = 'move' } catch { /* read-only */ }
1054
+ }
1055
+ if (state.drag !== null && state.drag.over !== true) {
1056
+ state.drag.over = true
1057
+ publish()
1058
+ }
1059
+ },
1060
+ onDragLeave: () => {
1061
+ if (state.drag !== null && state.drag.over !== false) {
1062
+ state.drag.over = false
1063
+ publish()
1064
+ }
1065
+ },
1066
+ onDrop: (event) => {
1067
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
1068
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1069
+ dropToDelete()
1070
+ },
1071
+ },
1072
+ h('span', { key: 'icon', className: 'dsdel-drop-icon' }, glyph(TRASH_PATHS)),
1073
+ h('span', { key: 'text', className: 'dsdel-drop-text' },
1074
+ armed ? translate('dropRelease', name) : translate('dropHint', name)),
1075
+ )
1076
+ }
1077
+ // Outside selection mode the footer keeps its normal face.
1078
+ if (!view.selecting) return null
1079
+ const busy = view.batch !== null
1080
+ const empty = view.selectedCount === 0
1081
+ // A move reports processed-so-far (success + failure + skip) in one number;
1082
+ // a delete counts its own two buckets.
1083
+ const done = view.batch === null ? 0 : view.batch.kind === 'move' ? view.batch.done : view.batch.done + view.batch.failed
1084
+ const label = view.batch === null
1085
+ ? translate('selectedCount', view.selectedCount)
1086
+ : view.batch.kind === 'move'
1087
+ ? translate('batchMoving', done, view.batch.total)
1088
+ : translate('batchRunning', done, view.batch.total)
1089
+ return h('div', { className: 'dsdel-bar', role: 'toolbar' },
1090
+ h('span', { key: 'count', className: 'dsdel-bar-count' }, label),
1091
+ h('button', {
1092
+ key: 'cancel',
1093
+ type: 'button',
1094
+ className: 'dsdel-bar-btn dsdel-bar-cancel',
1095
+ disabled: busy,
1096
+ onClick: (event) => {
1097
+ if (event && event.stopPropagation) event.stopPropagation()
1098
+ exitSelection()
1099
+ },
1100
+ }, translate('cancelSelect')),
1101
+ // One more button when dsh-session-relocate is installed; otherwise the bar
1102
+ // is exactly what it was before.
1103
+ relocateApi() === null ? null : h('button', {
1104
+ key: 'move',
1105
+ type: 'button',
1106
+ className: 'dsdel-bar-btn dsdel-bar-move',
1107
+ disabled: busy || empty,
1108
+ onClick: (event) => {
1109
+ if (event && event.stopPropagation) event.stopPropagation()
1110
+ runBatchMove()
1111
+ },
1112
+ }, translate('moveSelected')),
1113
+ h('button', {
1114
+ key: 'delete',
1115
+ type: 'button',
1116
+ className: 'dsdel-bar-btn dsdel-bar-danger',
1117
+ disabled: busy || empty,
1118
+ onClick: (event) => {
1119
+ if (event && event.stopPropagation) event.stopPropagation()
1120
+ runBatchDelete()
1121
+ },
1122
+ }, translate('deleteSelected')),
1123
+ )
1124
+ }
1125
+ function toggleSelect(id) {
1126
+ if (state.selected.has(id)) state.selected.delete(id)
1127
+ else state.selected.add(id)
1128
+ publish()
1129
+ }
1130
+
1131
+ function onSelectClickCapture(e) {
1132
+ if (!state.selecting) return
1133
+ const row = e.target && e.target.closest ? e.target.closest('[role="treeitem"]') : null
1134
+ if (!row) return
1135
+ const id = sessionIdFromRow(row)
1136
+ if (!id) return
1137
+ e.preventDefault()
1138
+ e.stopPropagation()
1139
+ toggleSelect(id)
1140
+ }
1141
+
1142
+ function onSelectKeydown(e) {
1143
+ if (e.key !== 'Escape') return
1144
+ if (state.batch !== null) return
1145
+ e.stopPropagation()
1146
+ exitSelection()
1147
+ }
1148
+
1149
+ /**
1150
+ * Mark the page while the mode runs. The marker is the only hook the
1151
+ * stylesheet needs to let the account row step aside for the bar.
1152
+ */
1153
+ function markSelecting(on) {
1154
+ if (typeof document === 'undefined' || !document.body) return
1155
+ const classes = document.body.classList
1156
+ if (!classes) return
1157
+ if (on) classes.add('dsdel-selecting')
1158
+ else classes.remove('dsdel-selecting')
1159
+ }
1160
+
1161
+ /** The footer is ours while selecting or while a session is dragged over it. */
1162
+ function syncFooterMode() {
1163
+ markSelecting(state.selecting || state.drag !== null)
1164
+ }
1165
+
1166
+ function enterSelection() {
1167
+ if (state.selecting) return
1168
+ state.selecting = true
1169
+ state.selected.clear()
1170
+ ensureStyle()
1171
+ syncFooterMode()
1172
+ document.addEventListener('click', onSelectClickCapture, true)
1173
+ document.addEventListener('keydown', onSelectKeydown, true)
1174
+ if (typeof MutationObserver === 'function') {
1175
+ rowObserver = new MutationObserver(onRowMutations)
1176
+ // Observation root is the list, not the document: the transcript below
1177
+ // streams tokens continuously and would otherwise wake this on every one.
1178
+ const list = typeof document.querySelector === 'function'
1179
+ ? document.querySelector(LIST_SELECTOR)
1180
+ : null
1181
+ rowObserver.observe(list !== null && list !== undefined ? list : document.body, {
1182
+ childList: true,
1183
+ subtree: true,
1184
+ })
1185
+ }
1186
+ publish()
1187
+ }
1188
+
1189
+ function exitSelection(options) {
1190
+ if (!state.selecting) return
1191
+ state.selecting = false
1192
+ state.selected.clear()
1193
+ state.batch = null
1194
+ const keepPending = !!(options && options.keepPending)
1195
+ if (!keepPending) {
1196
+ state.pending.clear()
1197
+ document.querySelectorAll('.dsdel-row-pending').forEach((el) => el.classList.remove('dsdel-row-pending'))
1198
+ }
1199
+ syncFooterMode()
1200
+ document.removeEventListener('click', onSelectClickCapture, true)
1201
+ document.removeEventListener('keydown', onSelectKeydown, true)
1202
+ if (rowObserver) { rowObserver.disconnect(); rowObserver = null }
1203
+ document.querySelectorAll('.dsdel-check').forEach((el) => el.remove())
1204
+ publish()
1205
+ }
1206
+
1207
+ // 成功删除后行要保持隐藏直到列表刷新落地,之后再清掉乐观状态(避免行“闪回”)。
1208
+ function settlePendingSoon() {
1209
+ setTimeout(() => {
1210
+ state.pending.clear()
1211
+ publish()
1212
+ }, 2500)
1213
+ }
1214
+
1215
+ // 批量删除:客户端并发(小池)+ 乐观隐藏 + 进度显示。
1216
+ // 走单会话端点(每个请求各自跑宿主端的完整删除管线),宿主端对同一存储的
1217
+ // 记账变更已串行化,因此不同会话并发是安全的;失败的行立即恢复显示并保持选中,
1218
+ // 方便直接重试。
1219
+ // 6 是实测值:64 个 ~2MB 会话的墙钟时间 4 路 281ms / 6 路 189ms / 8 路 142ms
1220
+ // (I/O 并行度约在 8 饱和),6 路比 4 路快约 1/3 且仍在饱和点以下。
1221
+ const BATCH_CONCURRENCY = 6
1222
+
1223
+ function runBatchDelete() {
1224
+ if (state.batch !== null) return
1225
+ const ids = [...state.selected]
1226
+ if (ids.length === 0) return
1227
+ state.batch = { kind: 'delete', total: ids.length, done: 0, failed: 0 }
1228
+ state.selected.clear()
1229
+ for (const id of ids) state.pending.add(id)
1230
+ publish()
1231
+
1232
+ const failedIds = []
1233
+ let cursor = 0
1234
+ const worker = async () => {
1235
+ while (true) {
1236
+ const index = cursor
1237
+ cursor += 1
1238
+ if (index >= ids.length) return
1239
+ const id = ids[index]
1240
+ try {
1241
+ await postDelete(id)
1242
+ state.batch.done += 1
1243
+ } catch {
1244
+ state.batch.failed += 1
1245
+ failedIds.push(id)
1246
+ state.pending.delete(id)
1247
+ }
1248
+ publish()
1249
+ }
1250
+ }
1251
+ const workers = []
1252
+ for (let i = 0; i < Math.min(BATCH_CONCURRENCY, ids.length); i += 1) workers.push(worker())
1253
+
1254
+ Promise.all(workers).then(() => {
1255
+ const failed = state.batch ? state.batch.failed : 0
1256
+ const ok = state.batch ? state.batch.done : 0
1257
+ state.batch = null
1258
+ if (failed === 0) {
1259
+ toast(t('batchDone', ok))
1260
+ exitSelection({ keepPending: true })
1261
+ settlePendingSoon()
1262
+ } else {
1263
+ for (const id of failedIds) state.selected.add(id)
1264
+ toast(t('batchPartial', ok, failed), true)
1265
+ publish()
1266
+ }
1267
+ refreshList()
1268
+ for (const id of ids) {
1269
+ if (!failedIds.includes(id)) leaveIfCurrent(id)
1270
+ }
1271
+ })
1272
+ }
1273
+
1274
+ /**
1275
+ * Hand the selection to dsh-session-relocate. That plugin owns the target
1276
+ * picker and the move itself; this side runs the progress readout and the
1277
+ * summary. A cancelled picker leaves the selection untouched and says
1278
+ * nothing, because nothing happened.
1279
+ */
1280
+ async function runBatchMove() {
1281
+ if (state.batch !== null) return
1282
+ const api = relocateApi()
1283
+ if (api === null) return
1284
+ const ids = [...state.selected]
1285
+ if (ids.length === 0) return
1286
+
1287
+ state.batch = { kind: 'move', total: ids.length, done: 0, failed: 0 }
1288
+ publish()
1289
+
1290
+ let result
1291
+ try {
1292
+ result = await api.moveSelection(ids, {
1293
+ onProgress: (done, total) => {
1294
+ if (state.batch === null || state.batch.kind !== 'move') return
1295
+ if (typeof done === 'number' && Number.isFinite(done)) state.batch.done = Math.max(0, done)
1296
+ if (typeof total === 'number' && Number.isFinite(total)) state.batch.total = Math.max(1, total)
1297
+ },
1298
+ })
1299
+ } catch (reason) {
1300
+ state.batch = null
1301
+ publish()
1302
+ toast(t('failed') + String((reason && reason.message) || reason), true)
1303
+ return
1304
+ }
1305
+
1306
+ state.batch = null
1307
+ // `canceled` is the contract spelling; `cancelled` is also honoured because
1308
+ // the contract's first draft used it. Nothing else about the result is
1309
+ // guessed: a missing count is reported, never substituted.
1310
+ if (result && (result.canceled === true || result.cancelled === true)) {
1311
+ // The user backed out of the target picker; keep the selection for a retry.
1312
+ publish()
1313
+ return
1314
+ }
1315
+
1316
+ const missing = ['moved', 'failed', 'total'].filter((key) => !result || typeof result[key] !== 'number')
1317
+ if (missing.length > 0) {
1318
+ // Falling back here would turn "genuinely zero failures" and "the field
1319
+ // was not sent" into the same summary, so the shape is enforced instead.
1320
+ toast(t('moveBadResult', missing.join(', ')), true)
1321
+ exitSelection()
1322
+ refreshList()
1323
+ return
1324
+ }
1325
+
1326
+ toast(t('batchMoved', result.moved, result.failed), result.failed > 0)
1327
+ exitSelection()
1328
+ refreshList()
1329
+ if (result.failed === 0) {
1330
+ for (const id of ids) leaveIfCurrent(id)
1331
+ }
1332
+ }
1333
+
1334
+ // --- single delete ---------------------------------------------------------
1335
+
1336
+ function deleteNow(info) {
1337
+ state.pending.add(info.sessionId)
1338
+ publish()
1339
+ // The no-dialog path can only honour auto mode: ask mode needs the list,
1340
+ // and the menu row forces the dialog in that case. With the feature off no
1341
+ // quarantine field is sent at all, keeping the request identical to the
1342
+ // version that predates the feature.
1343
+ const quarantine = !artifactsOff() && artifactsAuto() ? { scope: artifactScope() } : undefined
1344
+ postDelete(info.sessionId, quarantine)
1345
+ .then((result) => {
1346
+ const outcome = result && result.quarantine ? result.quarantine : null
1347
+ if (outcome !== null && outcome.failed.length > 0) {
1348
+ toast(t('doneQuarantineFailed', outcome.moved.length, outcome.failed.length), true)
1349
+ } else if (outcome !== null && outcome.moved.length > 0) {
1350
+ toast(t('doneQuarantine', outcome.moved.length))
1351
+ } else {
1352
+ toast(t('done'))
1353
+ }
1354
+ refreshList()
1355
+ settlePendingSoon()
1356
+ leaveIfCurrent(info.sessionId)
1357
+ })
1358
+ .catch((reason) => {
1359
+ state.pending.delete(info.sessionId)
1360
+ publish()
1361
+ toast(t('failed') + String((reason && reason.message) || reason), true)
1362
+ })
1363
+ }
1364
+
1365
+ /** The rows a scope selects, in list order. */
1366
+ function candidatePaths(plan, scope) {
1367
+ if (plan === null || plan === undefined) return []
1368
+ const rows = scope === 'all' ? [...plan.created, ...plan.modified] : [...plan.created]
1369
+ return rows.map((row) => row.path)
1370
+ }
1371
+
1372
+ function openDeleteDialog(sessionId, title) {
1373
+ // With the feature off the dialog carries no artifact section at all and
1374
+ // the delete request stays byte-identical to the previous version.
1375
+ //
1376
+ // Auto mode sends `{ scope }` and the host derives the whole set itself, so
1377
+ // the scan result would never be read: scanning there only burns time before
1378
+ // the dialog can appear. Ask mode is the one that needs the listing.
1379
+ const artifacts = artifactsOff()
1380
+ ? null
1381
+ : artifactsAuto()
1382
+ ? { auto: true, loading: false, plan: null, error: null, selected: new Set() }
1383
+ : { auto: false, loading: true, plan: null, error: null, selected: new Set() }
1384
+ state.dialog = {
1385
+ sessionId,
1386
+ title: title || null,
1387
+ busy: false,
1388
+ error: null,
1389
+ artifacts,
1390
+ // The subagent sessions this conversation spawned. Filled in after the
1391
+ // dialog opens: the list costs one host call, and on most conversations
1392
+ // there is nothing to list.
1393
+ children: { loading: true, list: [], selected: new Set() },
1394
+ }
1395
+ publish()
1396
+ if (artifacts !== null && artifacts.auto !== true) loadArtifacts(sessionId)
1397
+ loadChildren(sessionId)
1398
+ }
1399
+
1400
+ /**
1401
+ * List the subagent sessions behind this conversation. With the switch on they
1402
+ * are all taken with the parent; with it off every one starts ticked and the
1403
+ * dialog lets the user narrow the set.
1404
+ */
1405
+ function loadChildren(sessionId) {
1406
+ fetch(`/dsh-delete-session/children`, {
1407
+ method: 'POST',
1408
+ headers: { 'content-type': 'application/json' },
1409
+ body: JSON.stringify({ sessionId }),
1410
+ })
1411
+ .then(async (res) => {
1412
+ let data = {}
1413
+ try { data = await res.json() } catch { /* keep {} */ }
1414
+ const list = res.ok && Array.isArray(data.children) ? data.children : []
1415
+ const dialog = state.dialog
1416
+ if (dialog === null || dialog.sessionId !== sessionId) return
1417
+ dialog.children = {
1418
+ loading: false,
1419
+ list,
1420
+ selected: new Set(list.map((child) => child.id)),
1421
+ }
1422
+ publish()
1423
+ })
1424
+ .catch(() => {
1425
+ const dialog = state.dialog
1426
+ if (dialog === null || dialog.sessionId !== sessionId) return
1427
+ // A host that cannot list children still deletes the parent; reporting
1428
+ // an error here would block a delete that is otherwise fine.
1429
+ dialog.children = { loading: false, list: [], selected: new Set() }
1430
+ publish()
1431
+ })
1432
+ }
1433
+
1434
+ /** The children this delete should take along. */
1435
+ function childSessionIdsFor(dialog) {
1436
+ if (dialog.children === undefined || dialog.children === null) return []
1437
+ if (syncChildren()) return dialog.children.list.map((child) => child.id)
1438
+ return dialog.children.list
1439
+ .filter((child) => dialog.children.selected.has(child.id))
1440
+ .map((child) => child.id)
1441
+ }
1442
+
1443
+ /** Fetch the read-only scan and preselect the current scope's candidates. */
1444
+ function loadArtifacts(sessionId) {
1445
+ const settle = (mutate) => {
1446
+ const dialog = state.dialog
1447
+ if (dialog === null || dialog.artifacts === null || dialog.sessionId !== sessionId) return
1448
+ mutate(dialog.artifacts)
1449
+ publish()
1450
+ }
1451
+ postArtifacts(sessionId)
1452
+ .then((plan) => settle((artifacts) => {
1453
+ artifacts.loading = false
1454
+ artifacts.plan = plan
1455
+ artifacts.selected = new Set(candidatePaths(plan, artifactScope()))
1456
+ }))
1457
+ .catch((reason) => settle((artifacts) => {
1458
+ artifacts.loading = false
1459
+ artifacts.error = String((reason && reason.message) || reason)
1460
+ }))
1461
+ }
1462
+
1463
+ function closeDeleteDialog() {
1464
+ if (state.dialog === null || state.dialog.busy) return
1465
+ state.dialog = null
1466
+ publish()
1467
+ }
1468
+
1469
+ // --- quarantine folder picker ----------------------------------------------
1470
+
1471
+ /**
1472
+ * Open the folder picker at the configured root. The browser cannot hand a
1473
+ * page a real filesystem path, so the listing comes from the host instead.
1474
+ */
1475
+ function openPicker() {
1476
+ state.picker = {
1477
+ loading: true,
1478
+ error: null,
1479
+ path: '',
1480
+ parent: null,
1481
+ entries: [],
1482
+ roots: [],
1483
+ truncated: false,
1484
+ defaultRoot: state.defaultRoot,
1485
+ }
1486
+ publish()
1487
+ loadPicker(quarantineRoot())
1488
+ }
1489
+
1490
+ function closePicker() {
1491
+ state.picker = null
1492
+ publish()
1493
+ }
1494
+
1495
+ function loadPicker(target) {
1496
+ postBrowse(target)
1497
+ .then((listing) => {
1498
+ if (state.picker === null) return
1499
+ state.picker = {
1500
+ loading: false,
1501
+ error: null,
1502
+ path: listing.path,
1503
+ parent: listing.parent,
1504
+ entries: listing.entries,
1505
+ roots: listing.roots,
1506
+ truncated: listing.truncated,
1507
+ defaultRoot: listing.defaultRoot,
1508
+ }
1509
+ state.defaultRoot = listing.defaultRoot
1510
+ publish()
1511
+ })
1512
+ .catch((reason) => {
1513
+ if (state.picker === null) return
1514
+ state.picker = {
1515
+ ...state.picker,
1516
+ loading: false,
1517
+ error: String((reason && reason.message) || reason),
1518
+ }
1519
+ publish()
1520
+ })
1521
+ }
1522
+
1523
+ /** Commit the directory the picker is showing. */
1524
+ function pickCurrent() {
1525
+ const picker = state.picker
1526
+ if (picker === null || picker.loading || picker.path === '') return
1527
+ setQuarantineRoot(picker.path)
1528
+ closePicker()
1529
+ toast(t('rootSet'))
1530
+ }
1531
+
1532
+ /**
1533
+ * Prefer the OS folder dialog, which is the one the user actually expects.
1534
+ * It only exists on Windows; everywhere else the in-page picker takes over.
1535
+ */
1536
+ let folderDialogOpen = false
1537
+ function chooseFolder() {
1538
+ if (folderDialogOpen) return
1539
+ folderDialogOpen = true
1540
+ // The dialog can open behind the browser window, so say it was raised.
1541
+ toast(t('pickerOpening'))
1542
+ postPick()
1543
+ .then((picked) => {
1544
+ if (picked.cancelled === true) return
1545
+ setQuarantineRoot(picked.path)
1546
+ toast(t('rootSet'))
1547
+ })
1548
+ .catch((reason) => {
1549
+ // Two host answers mean "use the page picker instead": `unsupported`
1550
+ // (no directoryPicker service at all) and `browse` (the service exists
1551
+ // but serves listings, which is what a remote client gets). Neither is
1552
+ // a failure, so neither may surface as a toast.
1553
+ if (reason && (reason.code === 'unsupported' || reason.code === 'browse')) {
1554
+ openPicker()
1555
+ return
1556
+ }
1557
+ // Nothing was deleted here, so the delete wording would mislead.
1558
+ toast(t('pickerFailed') + String((reason && reason.message) || reason), true)
1559
+ })
1560
+ .finally(() => {
1561
+ folderDialogOpen = false
1562
+ })
1563
+ }
1564
+
1565
+ /** Learn the host default once, so the settings card can name it. */
1566
+ function loadDefaultRoot() {
1567
+ if (state.defaultRoot !== null) return
1568
+ postBrowse('')
1569
+ .then((listing) => {
1570
+ state.defaultRoot = listing.defaultRoot
1571
+ publish()
1572
+ })
1573
+ .catch(() => {
1574
+ // the card falls back to a generic label; nothing to report here
1575
+ })
1576
+ }
1577
+
1578
+ /**
1579
+ * Build the quarantine request for the open dialog. The host re-derives the
1580
+ * candidate set and intersects it with `paths`, so this can only narrow what
1581
+ * the user was shown - never widen it.
1582
+ */
1583
+ function quarantineRequest(dialog) {
1584
+ if (dialog.artifacts === null) return undefined
1585
+ const scope = artifactScope()
1586
+ const skipGit = skipGitRepos()
1587
+ // In auto mode no `paths` is sent: the host takes the whole set it derives.
1588
+ if (artifactsAuto()) return { scope, skipGit }
1589
+ const allowed = new Set(candidatePaths(dialog.artifacts.plan, scope))
1590
+ const paths = [...dialog.artifacts.selected].filter((path) => allowed.has(path))
1591
+ return { scope, paths, skipGit }
1592
+ }
1593
+
1594
+ // The "don't ask again" flag is committed only when the user actually
1595
+ // confirms, exactly as before - ticking the box and then cancelling must not
1596
+ // change the preference.
1597
+ function confirmDelete() {
1598
+ const dialog = state.dialog
1599
+ if (dialog === null || dialog.busy) return
1600
+ const quarantine = quarantineRequest(dialog)
1601
+ const childSessionIds = childSessionIdsFor(dialog)
1602
+ dialog.busy = true
1603
+ dialog.error = null
1604
+ state.pending.add(dialog.sessionId)
1605
+ publish()
1606
+ postDelete(dialog.sessionId, quarantine, childSessionIds)
1607
+ .then((result) => {
1608
+ state.dialog = null
1609
+ const outcome = result && result.quarantine ? result.quarantine : null
1610
+ if (outcome !== null && outcome.failed.length > 0) {
1611
+ toast(t('doneQuarantineFailed', outcome.moved.length, outcome.failed.length), true)
1612
+ } else if (outcome !== null && outcome.moved.length > 0) {
1613
+ toast(t('doneQuarantine', outcome.moved.length))
1614
+ } else {
1615
+ toast(t('done'))
1616
+ }
1617
+ refreshList()
1618
+ settlePendingSoon()
1619
+ leaveIfCurrent(dialog.sessionId)
1620
+ publish()
1621
+ })
1622
+ .catch((reason) => {
1623
+ state.pending.delete(dialog.sessionId)
1624
+ dialog.busy = false
1625
+ dialog.error = t('failed') + String((reason && reason.message) || reason)
1626
+ publish()
1627
+ })
1628
+ }
1629
+
1630
+ // --- menu rows (slot: sidebar.workspaces.session.menu.item) ----------------
1631
+
1632
+ /** The sidebar list container; hashed class name, matched by its suffix. */
1633
+ const LIST_SELECTOR = '[class*="_regionArea"]'
1634
+ /** Marks a row checkbox this plugin planted. */
1635
+ const DEL_CHECK = 'dsdel-check'
1636
+
1637
+ /** Inline glyphs for the two rows; the host exposes no matching pair. */
1638
+ const TRASH_PATHS = ['M4 7h16', 'M10 11v6', 'M14 11v6', 'M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13', 'M9 7V4h6v3']
1639
+ /** A folder, for "show this file where it lives". */
1640
+ const FOLDER_PATHS = ['M3 6a1 1 0 0 1 1-1h4l2 2h8a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z']
1641
+ const SELECT_PATHS = ['M5 7m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0', 'M5 17m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0', 'M11 7h9', 'M11 17h9']
1642
+
1643
+ function glyph(paths) {
1644
+ return h(
1645
+ 'svg',
1646
+ {
1647
+ width: 16,
1648
+ height: 16,
1649
+ viewBox: '0 0 24 24',
1650
+ fill: 'none',
1651
+ stroke: 'currentColor',
1652
+ strokeWidth: 1.8,
1653
+ strokeLinecap: 'round',
1654
+ strokeLinejoin: 'round',
1655
+ },
1656
+ paths.map((d) => h('path', { key: d, d })),
1657
+ )
1658
+ }
1659
+
1660
+ // ui-primitives' `MenuItemButton` takes a real `danger` parameter (verified
1661
+ // against the shipped component), which puts the host's own danger class on
1662
+ // the button. Passing it is what keeps the delete row in the host's danger
1663
+ // colour - icon included - rather than a plugin guess.
1664
+ //
1665
+ // No `separatorBefore`: this migration moves the rows onto the host's slot
1666
+ // contract and must not change how the menu looks.
1667
+
1668
+ /** "Select multiple" row (order 409, directly above the delete row). */
1669
+ function SelectMultipleMenuItem({ useMenuOpenState, t: translate }) {
1670
+ const [, setMenuOpen] = useMenuOpenState()
1671
+ return h(primitives.MenuItemButton, {
1672
+ icon: glyph(SELECT_PATHS),
1673
+ onSelect: () => {
1674
+ setMenuOpen(false)
1675
+ enterSelection()
1676
+ },
1677
+ children: translate('multiSelect'),
1678
+ })
1679
+ }
1680
+
1681
+ /** "Delete session" row (order 410, in the host's danger colour). */
1682
+ function DeleteSessionMenuItem({ sessionId, displayTitle, useMenuOpenState, t: translate }) {
1683
+ const [, setMenuOpen] = useMenuOpenState()
1684
+ return h(primitives.MenuItemButton, {
1685
+ danger: true,
1686
+ icon: glyph(TRASH_PATHS),
1687
+ onSelect: (event) => {
1688
+ setMenuOpen(false)
1689
+ // Ask mode keeps the dialog even when "don't ask again" is ticked: the
1690
+ // file list only exists there, and skipping it would make the feature
1691
+ // silently do nothing.
1692
+ const needsDialog = !artifactsOff() && !artifactsAuto()
1693
+ // Shift-click always asks, even after "don't ask again" was ticked.
1694
+ if (skipConfirm() && !needsDialog && !(event && event.shiftKey)) deleteNow({ sessionId })
1695
+ else openDeleteDialog(sessionId, displayTitle)
1696
+ },
1697
+ children: translate('menu'),
1698
+ })
1699
+ }
1700
+
1701
+ // --- confirmation dialog (slot: shell.overlay) -----------------------------
1702
+
1703
+ /**
1704
+ * The produced-files section: the scan summary, then either the tick list
1705
+ * (ask mode) or a single line stating how many files will move (auto mode).
1706
+ * A null `artifacts` means the feature is off and the dialog says nothing.
1707
+ */
1708
+ /**
1709
+ * The subagent sessions behind this conversation. Hidden while the switch
1710
+ * already answers the question, and while the list is still loading.
1711
+ */
1712
+ function renderChildren(dialog, translate) {
1713
+ const children = dialog.children
1714
+ if (children === undefined || children === null) return null
1715
+ if (children.loading) return null
1716
+ if (children.list.length === 0) return null
1717
+ if (syncChildren()) return null
1718
+ return h('div', { key: 'children', className: 'dsdel-modal-children' },
1719
+ h('p', { key: 'hint', className: 'dsdel-modal-text' },
1720
+ translate('childrenHint', children.list.length)),
1721
+ ...children.list.map((child) => h(primitives.Checkbox, {
1722
+ key: `child:${child.id}`,
1723
+ checked: children.selected.has(child.id),
1724
+ label: child.cwd ? `${child.id} · ${child.cwd}` : child.id,
1725
+ onChange: (checked) => {
1726
+ if (checked === true) children.selected.add(child.id)
1727
+ else children.selected.delete(child.id)
1728
+ publish()
1729
+ },
1730
+ })),
1731
+ )
1732
+ }
1733
+
1734
+ function renderArtifacts(artifacts, translate) {
1735
+ if (artifacts === null) return null
1736
+ // Auto mode never scanned, so there is no plan to describe: name the
1737
+ // outcome instead of showing a list nobody asked for.
1738
+ if (artifacts.auto === true) {
1739
+ return h('div', { key: 'artifacts' }, [
1740
+ h('p', { key: 'head', className: 'dsdel-modal-text', style: { marginTop: '12px', fontWeight: 600 } },
1741
+ translate('artifactSection')),
1742
+ h('p', { key: 'auto', className: 'dsdel-modal-text' }, translate('artifactAutoOnly')),
1743
+ ])
1744
+ }
1745
+ if (artifacts.loading) {
1746
+ return h('p', { key: 'artifacts', className: 'dsdel-modal-meta', style: { marginTop: '12px' } },
1747
+ translate('artifactLoading'))
1748
+ }
1749
+ if (artifacts.error !== null) {
1750
+ return h('p', { key: 'artifacts', className: 'dsdel-modal-error', role: 'alert' },
1751
+ translate('artifactFailed') + artifacts.error)
1752
+ }
1753
+ const plan = artifacts.plan
1754
+ if (plan === null) return null
1755
+ const scope = artifactScope()
1756
+ const auto = artifactsAuto()
1757
+ const rows = scope === 'all' ? [...plan.created, ...plan.modified] : [...plan.created]
1758
+
1759
+ const elements = [
1760
+ h('p', { key: 'head', className: 'dsdel-modal-text', style: { marginTop: '12px', fontWeight: 600 } },
1761
+ translate('artifactSection')),
1762
+ h('p', { key: 'count', className: 'dsdel-modal-meta' },
1763
+ `${translate('artifactCount', plan.created.length, plan.modified.length)} · ${translate(scope === 'all' ? 'artifactScopeAll' : 'artifactScopeCreated')}`),
1764
+ ]
1765
+
1766
+ if (rows.length === 0) {
1767
+ elements.push(h('p', { key: 'none', className: 'dsdel-modal-meta' }, translate('artifactNone')))
1768
+ } else if (auto) {
1769
+ elements.push(h('p', { key: 'auto', className: 'dsdel-modal-text' }, translate('artifactAutoNote', rows.length)))
1770
+ } else {
1771
+ elements.push(h('p', { key: 'selected', className: 'dsdel-modal-meta' },
1772
+ translate('artifactSelected', artifacts.selected.size)))
1773
+ for (const row of rows.slice(0, ARTIFACT_ROWS_SHOWN)) {
1774
+ elements.push(h('div', {
1775
+ key: `row:${row.path}`,
1776
+ 'data-file-row': row.path,
1777
+ className: 'dsdel-file-row',
1778
+ },
1779
+ h('label', {
1780
+ key: 'label',
1781
+ className: 'dsdel-file-label',
1782
+ },
1783
+ h('input', {
1784
+ type: 'checkbox',
1785
+ checked: artifacts.selected.has(row.path),
1786
+ onChange: (e) => {
1787
+ if (e && e.target && e.target.checked) artifacts.selected.add(row.path)
1788
+ else artifacts.selected.delete(row.path)
1789
+ publish()
1790
+ },
1791
+ }),
1792
+ h('span', { key: 'path', className: 'dsdel-file-path' }, row.displayPath || row.path),
1793
+ ),
1794
+ // Delete just this file. Same destination rule as the conversation
1795
+ // switch: the system trash when recycling is on, gone when it is not.
1796
+ h('button', {
1797
+ key: 'remove',
1798
+ type: 'button',
1799
+ className: 'dsdel-file-open dsdel-file-remove',
1800
+ title: translate('artifactDeleteFile'),
1801
+ 'aria-label': translate('artifactDeleteFile'),
1802
+ onClick: (event) => {
1803
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
1804
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1805
+ deleteOneFile(state.dialog === null ? '' : state.dialog.sessionId, row.path)
1806
+ },
1807
+ }, glyph(TRASH_PATHS)),
1808
+ // One folder per row. What moves is the file, so the thing worth
1809
+ // looking at before deciding is where it lives. The button is a
1810
+ // SIBLING of the label: inside it, a click would toggle the tick box.
1811
+ h('button', {
1812
+ key: 'open',
1813
+ type: 'button',
1814
+ className: 'dsdel-file-open',
1815
+ title: translate('artifactOpenFolder'),
1816
+ 'aria-label': translate('artifactOpenFolder'),
1817
+ onClick: (event) => {
1818
+ if (event && typeof event.preventDefault === 'function') event.preventDefault()
1819
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1820
+ revealParent(row.path)
1821
+ },
1822
+ }, glyph(FOLDER_PATHS)),
1823
+ ))
1824
+ }
1825
+ if (rows.length > ARTIFACT_ROWS_SHOWN) {
1826
+ elements.push(h('p', { key: 'more', className: 'dsdel-modal-meta' },
1827
+ translate('artifactMore', rows.length - ARTIFACT_ROWS_SHOWN)))
1828
+ }
1829
+ }
1830
+
1831
+ if (plan.refused.length > 0) {
1832
+ elements.push(h('p', { key: 'refused', className: 'dsdel-modal-meta' },
1833
+ translate('artifactRefused', plan.refused.length)))
1834
+ }
1835
+ if (plan.truncated) {
1836
+ elements.push(h('p', { key: 'truncated', className: 'dsdel-modal-meta' }, translate('artifactTruncated')))
1837
+ }
1838
+ return h('div', { key: 'artifacts', className: 'dsdel-artifacts' }, elements)
1839
+ }
1840
+
1841
+ /** Folder picker overlay: walk directories, then commit one. */
1842
+ function QuarantinePicker({ t: injected }) {
1843
+ const translate = localizedTranslator(injected)
1844
+ const view = useSnapshot()
1845
+ const picker = view.picker
1846
+ if (picker === null) return null
1847
+
1848
+ const children = []
1849
+ if (picker.loading) {
1850
+ children.push(h('p', { key: 'loading', className: 'dsdel-modal-meta' }, translate('pickerLoading')))
1851
+ } else if (picker.error !== null) {
1852
+ children.push(h('p', { key: 'error', className: 'dsdel-modal-error', role: 'alert' }, picker.error))
1853
+ } else {
1854
+ children.push(h('p', { key: 'path', className: 'dsdel-picker-path' }, picker.path))
1855
+
1856
+ const up = []
1857
+ if (picker.parent !== null) {
1858
+ up.push(h('button', {
1859
+ key: 'up',
1860
+ type: 'button',
1861
+ className: 'dsdel-picker-row',
1862
+ onClick: () => loadPicker(picker.parent),
1863
+ }, '..'))
1864
+ }
1865
+ for (const drive of picker.roots) {
1866
+ up.push(h('button', {
1867
+ key: `drive:${drive.path}`,
1868
+ type: 'button',
1869
+ className: 'dsdel-picker-row',
1870
+ onClick: () => loadPicker(drive.path),
1871
+ }, drive.name))
1872
+ }
1873
+ if (up.length > 0) children.push(h('div', { key: 'up', className: 'dsdel-picker-list' }, up))
1874
+
1875
+ if (picker.entries.length === 0) {
1876
+ children.push(h('p', { key: 'empty', className: 'dsdel-modal-meta' }, translate('pickerEmpty')))
1877
+ } else {
1878
+ children.push(h('div', { key: 'list', className: 'dsdel-picker-list' },
1879
+ picker.entries.map((entry) => h('button', {
1880
+ key: entry.path,
1881
+ type: 'button',
1882
+ className: 'dsdel-picker-row',
1883
+ onClick: () => loadPicker(entry.path),
1884
+ }, `${entry.name}/`))))
1885
+ }
1886
+ if (picker.truncated) {
1887
+ children.push(h('p', { key: 'truncated', className: 'dsdel-modal-meta' }, translate('pickerTruncated')))
1888
+ }
1889
+ children.push(h('p', { key: 'default', className: 'dsdel-modal-meta' },
1890
+ translate('pickerDefault', picker.defaultRoot || '-')))
1891
+ }
1892
+
1893
+ return h(primitives.Modal, {
1894
+ open: true,
1895
+ onClose: () => closePicker(),
1896
+ closeLabel: translate('cancel'),
1897
+ title: translate('pickerTitle'),
1898
+ footer: [
1899
+ h(primitives.Button, {
1900
+ key: 'cancel',
1901
+ variant: 'outline',
1902
+ onClick: () => closePicker(),
1903
+ children: translate('cancel'),
1904
+ }),
1905
+ h(primitives.Button, {
1906
+ key: 'choose',
1907
+ disabled: picker.loading || picker.path === '',
1908
+ onClick: () => pickCurrent(),
1909
+ children: translate('pickerChoose'),
1910
+ }),
1911
+ ],
1912
+ children,
1913
+ })
1914
+ }
1915
+
1916
+ function DeleteSessionDialog({ t: injected }) {
1917
+ const translate = localizedTranslator(injected)
1918
+ const view = useSnapshot()
1919
+ const dialog = view.dialog
1920
+ if (dialog === null) return null
1921
+
1922
+ // The file list sizes its own frame: a short list gets a short dialog, a
1923
+ // long one grows until the viewport cap and then scrolls. A forced ratio
1924
+ // cannot do that — it pins the height, so the empty band under two lines
1925
+ // of text simply moves around.
1926
+ const plan = dialog.artifacts !== null && dialog.artifacts !== undefined
1927
+ ? dialog.artifacts.plan
1928
+ : null
1929
+ const listed = plan === null || plan === undefined
1930
+ ? 0
1931
+ : (plan.created || []).length + (plan.modified || []).length
1932
+ const needsFrame = listed > 0 && dialog.artifacts.auto !== true
1933
+ const footer = h(
1934
+ Fragment,
1935
+ null,
1936
+ h(primitives.Button, {
1937
+ variant: 'outline',
1938
+ disabled: dialog.busy,
1939
+ onClick: () => closeDeleteDialog(),
1940
+ children: translate('cancel'),
1941
+ }),
1942
+ h(primitives.Button, {
1943
+ variant: 'outline',
1944
+ className: 'dsdel-danger-btn',
1945
+ disabled: dialog.busy,
1946
+ onClick: () => confirmDelete(),
1947
+ children: dialog.busy ? translate('deleting') : translate('confirm'),
1948
+ }),
1949
+ )
1950
+
1951
+ return h(primitives.Modal, {
1952
+ open: true,
1953
+ // `Modal` documents no width prop, so the class, the inline style and the
1954
+ // `:has()` rule in the stylesheet all try; whichever the host honours wins.
1955
+ // 9:16: the file list reads as a column, so the shell is a phone-shaped
1956
+ // card. Width is derived from the height budget (94vh tall at most), which
1957
+ // keeps the ratio on every window size; the list scrolls inside it.
1958
+ ...(needsFrame ? { className: 'dsdel-dialog-wide' } : {}),
1959
+ ...(needsFrame ? {
1960
+ style: {
1961
+ width: 'min(46vw, 860px)',
1962
+ maxWidth: 'min(46vw, 860px)',
1963
+ minHeight: 'min(240px, 88vh)',
1964
+ maxHeight: '88vh',
1965
+ },
1966
+ } : {}),
1967
+ onClose: () => closeDeleteDialog(),
1968
+ closeLabel: translate('cancel'),
1969
+ title: translate('title'),
1970
+ footer,
1971
+ children: [
1972
+ h('p', { key: 'meta', className: 'dsdel-modal-meta' },
1973
+ `${dialog.title || translate('untitled')} · ${dialog.sessionId}`),
1974
+ // The sentence has to match the switch: one promises the Recycle Bin,
1975
+ // the other promises exactly what an unchecked box means.
1976
+ h('p', { key: 'desc', className: 'dsdel-modal-text' },
1977
+ translate(recycleSession() ? 'descRecycle' : 'descPermanent')),
1978
+ renderArtifacts(dialog.artifacts, translate),
1979
+ renderChildren(dialog, translate),
1980
+ // Whether a delete asks first is a setting, not a dialog affordance:
1981
+ // it lives on the plugin page only, so this dialog never changes it.
1982
+ dialog.error !== null
1983
+ ? h('p', { key: 'error', className: 'dsdel-modal-error', role: 'alert' }, dialog.error)
1984
+ : null,
1985
+ ],
1986
+ })
1987
+ }
1988
+
1989
+ // --- plugin page card (slot: plugins.row.config) ---------------------------
1990
+
1991
+ // The manager's detail page for this bundle gives the component row a
1992
+ // configure arrow once the bundle registers its own row.config entry (key
1993
+ // `<bundle package>#<row id>`). The card carries the one setting the dialog
1994
+ // also exposes: whether a session delete asks first.
1995
+ function AskBeforeDeleteOption({ view, t: injected }) {
1996
+ // Unlike the menu rows and the dialog, this entry is registered without a
1997
+ // `locale`, so the host injects no `t` here. Falling back to the
1998
+ // module-level translator (same dictionaries) keeps the card working
1999
+ // instead of throwing on an undefined call.
2000
+ const translate = localizedTranslator(injected)
2001
+ // `view` is already the prop name (page or summary), so the store snapshot
2002
+ // needs its own binding here.
2003
+ const pageSnapshot = useSnapshot()
2004
+ // The host owns the default path, so it is fetched once per mount.
2005
+ const defaultRootValue = () => (pageSnapshot && pageSnapshot.defaultRoot) || ''
2006
+ const [ask, setAsk] = react.useState(!skipConfirm())
2007
+ const [recycle, setRecycle] = react.useState(recycleSession())
2008
+ const [syncChildrenState, setSyncChildrenState] = react.useState(syncChildren())
2009
+ const [off, setOff] = react.useState(artifactsOff())
2010
+ const [auto, setAuto] = react.useState(artifactsAuto())
2011
+ const [scope, setScope] = react.useState(artifactScope())
2012
+ const [skipGit, setSkipGit] = react.useState(skipGitRepos())
2013
+ const [root, setRoot] = react.useState(quarantineRoot())
2014
+ react.useEffect(() => subscribeSkip(() => setAsk(!skipConfirm())), [])
2015
+ react.useEffect(() => { loadDefaultRoot() }, [])
2016
+ react.useEffect(() => subscribePrefs(() => {
2017
+ setOff(artifactsOff())
2018
+ setAuto(artifactsAuto())
2019
+ setScope(artifactScope())
2020
+ setRoot(quarantineRoot())
2021
+ }), [])
2022
+
2023
+ if (view === 'summary') {
2024
+ if (off) return translate('pageSummaryArtifactsOff')
2025
+ return translate(auto ? 'pageSummaryArtifactsAuto' : 'pageSummaryArtifactsAsk')
2026
+ }
2027
+
2028
+ const children = [
2029
+ h(primitives.Checkbox, {
2030
+ key: 'ask',
2031
+ checked: ask,
2032
+ label: translate('pageAsk'),
2033
+ onChange: (checked) => {
2034
+ setAsk(checked === true)
2035
+ setSkipConfirm(checked !== true)
2036
+ },
2037
+ }),
2038
+ h('p', { key: 'askHint', className: 'dsdel-page-hint' },
2039
+ // Ask mode needs the dialog for its file list, so "delete straight away"
2040
+ // would be a promise this combination does not keep.
2041
+ translate(ask ? 'pageHintAsk' : (!off && !auto ? 'pageHintAutoWithArtifacts' : 'pageHintAuto'))),
2042
+
2043
+ h(primitives.Checkbox, {
2044
+ key: 'recycle',
2045
+ checked: recycle,
2046
+ label: translate('pageRecycle'),
2047
+ onChange: (checked) => {
2048
+ setRecycle(checked === true)
2049
+ setRecycleSession(checked === true)
2050
+ },
2051
+ }),
2052
+ h('p', { key: 'recycleHint', className: 'dsdel-page-hint' },
2053
+ translate(recycle ? 'pageRecycleOn' : 'pageRecycleOff')),
2054
+
2055
+ h(primitives.Checkbox, {
2056
+ key: 'syncChildren',
2057
+ checked: syncChildrenState,
2058
+ label: translate('pageSyncChildren'),
2059
+ onChange: (checked) => {
2060
+ setSyncChildrenState(checked === true)
2061
+ setSyncChildren(checked === true)
2062
+ },
2063
+ }),
2064
+ h('p', { key: 'syncChildrenHint', className: 'dsdel-page-hint' },
2065
+ translate(syncChildrenState ? 'pageSyncChildrenOn' : 'pageSyncChildrenOff')),
2066
+
2067
+ h(primitives.Checkbox, {
2068
+ key: 'off',
2069
+ checked: off,
2070
+ label: translate('pageArtifactsOff'),
2071
+ onChange: (checked) => {
2072
+ setOff(checked === true)
2073
+ setArtifactsOff(checked === true)
2074
+ },
2075
+ }),
2076
+ h('p', { key: 'offHint', className: 'dsdel-page-hint' }, translate(off ? 'pageHintArtifactsOff' : 'pageHintArtifactsOn')),
2077
+ ]
2078
+
2079
+ // Everything below the master switch only matters while the feature is on;
2080
+ // leaving it rendered-but-inert would suggest a setting that does nothing.
2081
+ // The layout is inline rather than a class: a stylesheet injected into the
2082
+ // host page has already proven able to lag behind a rebuilt module, and a
2083
+ // group whose indentation depends on it can silently collapse.
2084
+ if (!off) {
2085
+ children.push(
2086
+ h('div', {
2087
+ key: 'artifacts-sub',
2088
+ style: {
2089
+ display: 'flex',
2090
+ flexDirection: 'column',
2091
+ gap: '8px',
2092
+ marginLeft: '10px',
2093
+ paddingLeft: '14px',
2094
+ borderLeft: '2px solid rgba(127,127,127,0.35)',
2095
+ },
2096
+ },
2097
+ h(primitives.Checkbox, {
2098
+ key: 'auto',
2099
+ checked: auto,
2100
+ label: translate('pageArtifactsAuto'),
2101
+ onChange: (checked) => {
2102
+ setAuto(checked === true)
2103
+ setArtifactsAuto(checked === true)
2104
+ },
2105
+ }),
2106
+ h('p', { key: 'autoHint', className: 'dsdel-page-hint' }, translate(auto ? 'pageHintArtifactsAuto' : 'pageHintArtifactsAsk')),
2107
+ h('div', {
2108
+ key: 'scope',
2109
+ style: {
2110
+ display: 'flex',
2111
+ flexDirection: 'column',
2112
+ gap: '8px',
2113
+ marginLeft: '2px',
2114
+ paddingLeft: '14px',
2115
+ borderLeft: '2px solid rgba(127,127,127,0.2)',
2116
+ },
2117
+ },
2118
+ h(primitives.Checkbox, {
2119
+ key: 'scopeCreated',
2120
+ checked: scope === 'created',
2121
+ label: translate('pageScopeCreated'),
2122
+ onChange: (checked) => {
2123
+ if (checked !== true) return
2124
+ setScope('created')
2125
+ setArtifactScope('created')
2126
+ },
2127
+ }),
2128
+ h(primitives.Checkbox, {
2129
+ key: 'scopeAll',
2130
+ checked: scope === 'all',
2131
+ label: translate('pageScopeAll'),
2132
+ onChange: (checked) => {
2133
+ if (checked !== true) return
2134
+ setScope('all')
2135
+ setArtifactScope('all')
2136
+ },
2137
+ }),
2138
+ ),
2139
+ h('p', { key: 'scopeHint', className: 'dsdel-page-hint' }, translate(scope === 'all' ? 'pageScopeAllHint' : 'pageScopeCreatedHint')),
2140
+ h(primitives.Checkbox, {
2141
+ key: 'skipGit',
2142
+ checked: skipGit,
2143
+ label: translate('pageSkipGit'),
2144
+ onChange: (checked) => {
2145
+ setSkipGit(checked === true)
2146
+ setSkipGitRepos(checked === true)
2147
+ },
2148
+ }),
2149
+ h('p', { key: 'skipGitHint', className: 'dsdel-page-hint' },
2150
+ translate(skipGit ? 'pageSkipGitOn' : 'pageSkipGitOff')),
2151
+ h('div', { key: 'root', style: { display: 'flex', flexDirection: 'column', gap: '6px', marginTop: '2px' } },
2152
+ h('p', { key: 'rootLabel', className: 'dsdel-page-hint' }, translate('pageRootLabel')),
2153
+ h('div', { key: 'rootRow', style: { display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' } },
2154
+ h('input', {
2155
+ key: 'rootInput',
2156
+ type: 'text',
2157
+ className: 'dsdel-root-input',
2158
+ value: root,
2159
+ placeholder: defaultRootValue() || translate('pageRootPlaceholder'),
2160
+ spellCheck: false,
2161
+ onChange: (event) => {
2162
+ setQuarantineRoot((event && event.target && event.target.value) || '')
2163
+ },
2164
+ }),
2165
+ h(primitives.Button, {
2166
+ key: 'browse',
2167
+ variant: 'outline',
2168
+ onClick: () => chooseFolder(),
2169
+ children: translate('pageRootBrowse'),
2170
+ }),
2171
+ h(primitives.Button, {
2172
+ key: 'open',
2173
+ variant: 'outline',
2174
+ onClick: () => openQuarantineRoot(root === '' ? defaultRootValue() : root),
2175
+ children: translate('pageRootOpen'),
2176
+ }),
2177
+ h(primitives.Button, {
2178
+ key: 'reset',
2179
+ variant: 'outline',
2180
+ disabled: root === '',
2181
+ onClick: () => setQuarantineRoot(''),
2182
+ children: translate('pageRootReset'),
2183
+ }),
2184
+ ),
2185
+ h('p', { key: 'rootHint', className: 'dsdel-page-hint' },
2186
+ root === ''
2187
+ ? translate('pageRootDefaultHint', defaultRootValue() || '-')
2188
+ : translate('pageRootCustomHint')),
2189
+ ),
2190
+ ),
2191
+ )
2192
+ }
2193
+
2194
+ // A quiet link to the repository, last in the card. It is a nudge, not a
2195
+ // setting, so it never competes with the controls above it — and it is a
2196
+ // plain anchor, so clicking it opens the page instead of switching tabs here.
2197
+ children.push(h('div', { key: 'star', className: 'dsdel-star' },
2198
+ h('span', { key: 'ask' }, translate('starAsk')),
2199
+ h('a', {
2200
+ key: 'cta',
2201
+ className: 'dsdel-star-link',
2202
+ href: 'https://github.com/DDDMUC/dsh-delete-session',
2203
+ target: '_blank',
2204
+ rel: 'noreferrer',
2205
+ }, translate('starCta'))))
2206
+
2207
+ // Each control owns the nodes that explain it. Grouping them here keeps the
2208
+ // markup above flat (a switch and its hint are still two pushes) while the
2209
+ // page draws them as one block.
2210
+ const FIELD_KEYS = new Set(['ask', 'recycle', 'syncChildren', 'off', 'auto', 'scope', 'skipGit', 'root'])
2211
+ function groupFields(nodes) {
2212
+ const groups = []
2213
+ let current = null
2214
+ for (const node of nodes) {
2215
+ const key = node !== null && node !== undefined && node.props ? node.props.key : undefined
2216
+ if (FIELD_KEYS.has(key)) {
2217
+ current = { control: key, nodes: [node] }
2218
+ groups.push(current)
2219
+ continue
2220
+ }
2221
+ // The hint of a control is keyed `<control>Hint`; the root row keeps its
2222
+ // input, buttons and hint under the same prefix.
2223
+ if (current !== null && typeof key === 'string' && key !== 'star' && key !== 'cta'
2224
+ && key.startsWith(current.control)) {
2225
+ current.nodes.push(node)
2226
+ continue
2227
+ }
2228
+ current = null
2229
+ groups.push({ control: null, nodes: [node] })
2230
+ }
2231
+ return groups.map((group, index) => (group.control === null
2232
+ ? group.nodes[0]
2233
+ : h('div', { key: `field:${group.control}`, className: 'dsdel-field' }, ...group.nodes)))
2234
+ }
2235
+
2236
+ return h('div', { className: 'dsdel-page' }, groupFields(children))
2237
+ }
2238
+
2239
+ // --- plugin ------------------------------------------------------------------
2240
+
2241
+ function apply(ctx) {
2242
+ ensureStyle()
2243
+ // Capability bits other plugins read. Announced before any slot registers,
2244
+ // so a relocate plugin that boots after this one finds it in place; the
2245
+ // event covers the reverse order.
2246
+ if (typeof window !== 'undefined') {
2247
+ window.__DSH_DELETE_SESSION__ = { supportsBulkMove: true }
2248
+ try {
2249
+ if (typeof window.dispatchEvent === 'function' && typeof window.Event === 'function') {
2250
+ window.dispatchEvent(new window.Event('dsh-session-delete:ready'))
2251
+ }
2252
+ } catch {
2253
+ // a host without DOM events still reads the global
2254
+ }
2255
+ }
2256
+
2257
+ sessionsSvc = ctx.get('sessions') || null
2258
+ if (!sessionsSvc) {
2259
+ try { ctx.inject(['sessions'], (sub) => { sessionsSvc = sub.sessions }) } catch { /* optional */ }
2260
+ }
2261
+ localeSvc = ctx.get('locale') || null
2262
+
2263
+ // Slot components are handed a `t` bound to this namespace, so the
2264
+ // dictionaries must reach the host - on BOTH arrival paths. If `locale`
2265
+ // only turns up through `ctx.inject`, a registration living on the
2266
+ // synchronous branch would never run and the menu would fall back to
2267
+ // printing raw keys ("multiSelect", "menu"). `ctx.effect` ties the
2268
+ // registration's lifetime to the plugin, matching ui-workspace.
2269
+ let localeRegistered = false
2270
+ const adoptLocale = (svc) => {
2271
+ localeSvc = svc || null
2272
+ if (localeRegistered || !localeSvc || typeof localeSvc.register !== 'function') return
2273
+ localeRegistered = true
2274
+ const register = () => localeSvc.register(NS, { zh, en })
2275
+ try {
2276
+ if (typeof ctx.effect === 'function') ctx.effect(register, `${NS}: dictionaries`)
2277
+ else register()
2278
+ } catch { /* already registered */ }
2279
+ }
2280
+ if (localeSvc) adoptLocale(localeSvc)
2281
+ else {
2282
+ try { ctx.inject(['locale'], (sub) => adoptLocale(sub.locale)) } catch { /* optional */ }
2283
+ }
2284
+
2285
+ const install = (slots) => {
2286
+ // The drag gesture is document-wide (the row is not ours), so these are
2287
+ // plain capture listeners rather than slot handlers.
2288
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
2289
+ document.addEventListener('dragstart', onDragStartCapture, true)
2290
+ document.addEventListener('dragend', onDragEndCapture, true)
2291
+ }
2292
+ // Session menu rows. A package-namespaced id keeps them beside the
2293
+ // shipped pin(100)/rename(200)/fork(300)/archive(400)/session-id(450).
2294
+ slots.inject('sidebar.workspaces.session.menu.item', () => slots.register(
2295
+ { name: 'sidebar.workspaces.session.menu.item', id: `${NS}-multi`, order: 409, locale: NS },
2296
+ SelectMultipleMenuItem,
2297
+ ))
2298
+ slots.inject('sidebar.workspaces.session.menu.item', () => slots.register(
2299
+ { name: 'sidebar.workspaces.session.menu.item', id: NS, order: 410, locale: NS },
2300
+ DeleteSessionMenuItem,
2301
+ ))
2302
+ // The confirmation dialog rides the frame-wide overlay seat.
2303
+ slots.inject('shell.overlay', () => slots.register(
2304
+ { name: 'shell.overlay', id: `${NS}-dialog`, locale: NS },
2305
+ DeleteSessionDialog,
2306
+ ))
2307
+ // The save-path picker is a second overlay: the settings card cannot host
2308
+ // a modal of its own.
2309
+ slots.inject('shell.overlay', () => slots.register(
2310
+ { name: 'shell.overlay', id: `${NS}-picker`, order: 1, locale: NS },
2311
+ QuarantinePicker,
2312
+ ))
2313
+ // The plugin page card, on BOTH seats the manager offers.
2314
+ //
2315
+ // `plugins.bundle.config` renders on the package page, whose address is
2316
+ // `#/panel/plugins/<package>`. `plugins.row.config` renders on the row's
2317
+ // own page, `#/panel/plugins/<package>/<rowId>` — and this bundle's row id
2318
+ // is the package name, so that address repeated itself. The row seat keeps
2319
+ // only its `summary` face, which is the one line the rows list shows.
2320
+ slots.inject('plugins.bundle.config', () => slots.register(
2321
+ { name: 'plugins.bundle.config', key: NS },
2322
+ AskBeforeDeleteOption,
2323
+ ))
2324
+ slots.inject('plugins.row.config', () => slots.register(
2325
+ { name: 'plugins.row.config', key: `${NS}#${NS}` },
2326
+ AskBeforeDeleteOption,
2327
+ ))
2328
+ // The batch bar rides the official footer seat, so the host owns its
2329
+ // position and the row it shares with the account chip.
2330
+ slots.inject('sidebar.footer.action', () => slots.register(
2331
+ { name: 'sidebar.footer.action', id: `${NS}-bulkbar`, order: 30, locale: NS },
2332
+ BulkBar,
2333
+ ))
2334
+
2335
+ // Leaving the mode disconnects the row observer and strips the checkboxes.
2336
+ return () => {
2337
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
2338
+ document.removeEventListener('dragstart', onDragStartCapture, true)
2339
+ document.removeEventListener('dragend', onDragEndCapture, true)
2340
+ }
2341
+ state.drag = null
2342
+ syncFooterMode()
2343
+ exitSelection()
2344
+ }
2345
+ }
2346
+
2347
+ const slots = ctx.get('slots')
2348
+ if (slots) {
2349
+ const dispose = install(slots)
2350
+ ctx.effect(() => dispose)
2351
+ } else {
2352
+ try {
2353
+ ctx.inject(['slots'], (sub) => {
2354
+ const dispose = install(sub.slots)
2355
+ ctx.effect(() => dispose)
2356
+ })
2357
+ } catch { /* no slot surface on this profile */ }
2358
+ }
2359
+ }
2360
+
2361
+ return { apply }
2362
+ },
2363
+ })