@todrink/dsh-session-delete 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 todrink
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,121 @@
1
- # Temporary Holding Version
1
+ # Delete session
2
+
3
+ Adds **删除会话 / Delete session** to the Session context menu, directly below
4
+ **归档会话 / Archive session**. Confirming the dialog permanently removes that
5
+ Session's local record instead of hiding it.
6
+
7
+ ## Why
8
+
9
+ DSH archives but never deletes: `归档会话` only records the Session in the
10
+ Workspace's archive set, and `SessionPersistence` exposes `create` / `open` /
11
+ `flush` / `stat` / `list` — no removal. A long-lived profile therefore keeps
12
+ every Session it ever wrote, including the ones nobody will open again, and
13
+ 「已归档」 accumulates entries that can only be hidden.
14
+
15
+ ## Compared with the plugin market
16
+
17
+ Community catalogs list dozens of Session-deletion plugins — the closest in
18
+ shape to this one are `dsh-delete-sessions` (red 「删除会话」 under
19
+ 「归档会话」 with its own confirmation dialog) and `dsh-delete-session-menu`.
20
+ None of them is installed in this profile. This bundle exists as a
21
+ self-contained, dependency-free alternative that was written against this
22
+ exact installation and verified here; installing a market plugin instead is a
23
+ straight swap — remove this bundle first so two menu items never compete.
24
+
25
+ ## Behaviour
26
+
27
+ - Menu: one structured action, `target: 'session'`, `order: 700`,
28
+ `afterContent: true`, `danger: true`. The shipped archive action is
29
+ `order: 600` of the same footer group, so this item renders immediately under
30
+ it.
31
+ - Selecting it opens this plugin's own confirmation dialog in `shell.overlay`
32
+ (title, the Session's title, what is about to be lost, a reminder that
33
+ archiving preserves the record, 取消 / 永久删除).
34
+ - Confirming posts `{ sessionId }` to the Host route
35
+ `POST /session-delete/api/delete`, then re-reads the client's Session list.
36
+ - Failure reasons stay in the dialog: a Session that is open or running is
37
+ refused with an explanation and can be archived instead.
38
+
39
+ ## What is deleted
40
+
41
+ | What | Where | Required? |
42
+ |---|---|---|
43
+ | Stored log (whole per-Session directory) | `<home>/sessions/<project>/<sessionId>/` | yes — the authoritative record |
44
+ | Workspace membership | `storages/workspace.json` → `sessionIds` (`detachSession`) | yes — otherwise the row stays |
45
+ | Archive / pin marks | `storages/workspace.json` → `global.archivedSessionIds` / `pinnedSessionIds` | yes — otherwise the id leaks |
46
+ | Projection checkpoint | `storages/session_projcache/sessions/<sessionId>.json` | best effort (plain-text conversation state) |
47
+
48
+ Left alone on purpose: content-addressed attachments (`attachments/`, shared by
49
+ hash), age-swept spill files in the OS temp directory, `schedule.json` rows, and
50
+ subagent-Session lineage. The SQLite search index needs no call — it reconciles
51
+ against `SessionPersistence.list()` and prunes a Session whose artifact
52
+ disappeared.
53
+
54
+ ## Refusals
55
+
56
+ - The Session is live in this process (`ctx.sessions.get(id)`), or an agent
57
+ still holds it: an open turn appends to the same log, so deleting underneath
58
+ it would corrupt the exchange. Answer `409 session-active`.
59
+ - The id is malformed or the body is not `application/json`: `400` / `415`.
60
+ - The request did not come from this Host's own page: the status
61
+ `ctx.connection.requestRejection` reports, normally `403`.
62
+ - Nothing to remove: `404 not-found`.
63
+
64
+ ## Install
65
+
66
+ ```powershell
67
+ plugin_manager({ action: "install_bundle", target: "<本包目录的绝对路径>" })
68
+ ```
69
+
70
+ The bundle patch inserts the Host row `session-delete`. The client half arrives
71
+ through the normal `/plugins` graph; a linked local package needs a page refresh
72
+ after an edit, and a changed `package.json` needs the row to restart.
73
+
74
+ ## Rollback
75
+
76
+ 1. `plugin_manager` → `remove_bundle` → `@todrink/dsh-session-delete`; the Host row and
77
+ the client contribution go with it. No profile patch of this bundle edits
78
+ another plugin, so nothing else needs restoring.
79
+ 2. Nothing this plugin wrote outside the profile has to be undone: it only
80
+ removes files.
81
+
82
+ ## Verification
83
+
84
+ - `node --check` on `index.js` and `client.js`.
85
+ - Host route harness (35 assertions) against a throwaway `DSH_HOME`: happy path,
86
+ directory and flat artifact layouts, never-materialized directory cleanup,
87
+ projection-cache removal, id validation, method/path/content-type fences,
88
+ foreign-origin rejection, live-session and live-agent refusal, unknown id,
89
+ stale registry row.
90
+ - Client harness (48 assertions) in a VM sandbox with a stub React: module id,
91
+ service injection, both dictionaries, menu contribution shape (target,
92
+ order 700, footer group, danger, icon key, label), the request the slot face
93
+ captures, the rendered dialog tree (title, named session, irreversible
94
+ warning, archive hint, two buttons, `role="dialog"` + `aria-labelledby`),
95
+ route resolution under `http://`, `dsh-app://app/` and a reverse-proxy prefix,
96
+ the POST body, the list refresh, and a Host refusal surfacing its code.
97
+ - Live, in a real browser: installed into the `desktop` profile, then a second
98
+ throwaway `dsh web` host (its own `DSH_HOME` profile, a copied Session) was
99
+ driven with Playwright — the menu item renders directly below 「归档会话」 in
100
+ red, the dialog opens in light and dark themes, 取消 changes nothing, and
101
+ 永久删除 answered `200 {ok:true}` → row gone from the sidebar, Session
102
+ directory gone, notice 「已删除会话「…」」 shown, the other row untouched.
103
+ The real `~/.dsh` data was never the target of a delete.
104
+
105
+ ## Limits
106
+
107
+ - Deletion is not reversible: the JSONL generation files are append-only, and
108
+ nothing in DSH snapshots a Session.
109
+ - A Session open in a *different* peer (another window or a remote client) is
110
+ not visible to this Host's live check; it is refused only once its owner is
111
+ this process. Closing other tabs before deleting is the safe habit.
112
+ - DSH does not offer the Session menu on the **selected** row, so the Session a
113
+ user is looking at cannot reach this action from the sidebar at all; the
114
+ host-side refusal instead covers a Session that is live but not selected.
115
+ - Archived ids already stale in this profile (138 at the time of writing, 3 of
116
+ them without a Session directory) are left untouched; this plugin only cleans
117
+ the id it deletes.
118
+ - A Workspace registry that has already been initialized does not rediscover
119
+ Session directories that reappear on disk, so restoring a deleted Session's
120
+ files by hand will not bring its row back by itself.
2
121
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
package/client.js ADDED
@@ -0,0 +1,400 @@
1
+ /**
2
+ * Browser half of `@todrink/dsh-session-delete`.
3
+ *
4
+ * Contributes one structured action to the Session context menu. It sits in
5
+ * the menu's footer group (the group 「归档会话」 uses) with a higher order, so
6
+ * it renders directly below that item. Selecting it opens a confirmation
7
+ * dialog in `shell.overlay`; confirming posts to the plugin's own Host route,
8
+ * which performs the permanent removal.
9
+ *
10
+ * No Harness Client package is required as a module: React comes from the
11
+ * browser module table, and every control below is this plugin's own, styled
12
+ * with the shared `--dsw-*` theme tokens.
13
+ */
14
+ window.__ModuleLoader__.load({
15
+ id: '@todrink/dsh-session-delete',
16
+ factory(require) {
17
+ const React = require('react')
18
+ const h = React.createElement
19
+ const { useCallback, useEffect, useId, useRef, useState } = React
20
+
21
+ /** Locale namespace owned by this plugin. */
22
+ const NS = 'session-delete'
23
+
24
+ /** Menu icon key contributed into `contextMenu.icon`. */
25
+ const ICON_KEY = 'session-delete.trash'
26
+
27
+ /** Route the Host half registers. */
28
+ const ROUTE = 'session-delete/api'
29
+
30
+ const zh = {
31
+ 'menu.deleteSession': '删除会话',
32
+ 'dialog.title': '删除会话',
33
+ 'dialog.desc': '将永久删除「{name}」的本地记录:对话内容、标题、归档与置顶标记。此操作无法撤销,也无法再从「已归档」里找回。',
34
+ 'dialog.untitled': '(未命名会话)',
35
+ 'dialog.hint': '只是不想让它出现在列表里?用「归档会话」可以保留记录。',
36
+ 'dialog.cancel': '取消',
37
+ 'dialog.confirm': '永久删除',
38
+ 'dialog.pending': '正在删除…',
39
+ 'dialog.running': '这个会话正在使用中(开着对话或者有进行中的回合),暂时不能删除。先关掉它或直接归档,再来删除。',
40
+ 'dialog.gone': '找不到这个会话的本地记录,它可能已经被删除。',
41
+ 'dialog.failed': '删除失败:{message}',
42
+ 'notice.deleted': '已删除会话「{name}」',
43
+ }
44
+
45
+ const en = {
46
+ 'menu.deleteSession': 'Delete session',
47
+ 'dialog.title': 'Delete session',
48
+ 'dialog.desc': 'Deletes the local record of "{name}" for good: its conversation, title, archived and pinned marks. This cannot be undone, and the session cannot be recovered from "Show archived".',
49
+ 'dialog.untitled': '(untitled session)',
50
+ 'dialog.hint': 'Only need it out of the list? "Archive session" keeps the record.',
51
+ 'dialog.cancel': 'Cancel',
52
+ 'dialog.confirm': 'Delete permanently',
53
+ 'dialog.pending': 'Deleting…',
54
+ 'dialog.running': 'This session is in use (open in a conversation, or a turn is running), so it cannot be deleted yet. Close it first, or archive it instead.',
55
+ 'dialog.gone': 'No stored record was found for this session; it may already be deleted.',
56
+ 'dialog.failed': 'Delete failed: {message}',
57
+ 'notice.deleted': 'Deleted session "{name}"',
58
+ }
59
+
60
+ /** Styles for the dialog; rendered with the component so unmounting removes them. */
61
+ const STYLES = `
62
+ .dsh-session-delete__backdrop {
63
+ position: fixed; inset: 0; z-index: 3000;
64
+ display: flex; align-items: center; justify-content: center;
65
+ padding: 24px;
66
+ /* A scrim token, not the "overlay" surface colour (that one is a popover
67
+ background and would paint the whole page opaque). */
68
+ background: var(--dsw-alias-bg-mask-1, rgba(0, 0, 0, 0.24));
69
+ font-family: var(--dsw-font-base-16-font-family, inherit);
70
+ }
71
+ .dsh-session-delete__card {
72
+ width: min(440px, 100%);
73
+ display: flex; flex-direction: column; gap: 12px;
74
+ padding: 20px;
75
+ border: 1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.24));
76
+ border-radius: 12px;
77
+ background: var(--dsw-alias-bg-layer-1, #ffffff);
78
+ box-shadow: var(--dsw-elevation-panel, 0 12px 32px rgba(0, 0, 0, 0.18));
79
+ color: var(--dsw-alias-label-primary, inherit);
80
+ }
81
+ .dsh-session-delete__title {
82
+ margin: 0;
83
+ font-family: var(--dsw-font-m-18-font-family, inherit);
84
+ font-size: var(--dsw-font-m-18-font-size, 16px);
85
+ font-weight: var(--dsw-font-m-18-font-weight, 600);
86
+ line-height: var(--dsw-font-m-18-line-height, 1.4);
87
+ }
88
+ .dsh-session-delete__desc {
89
+ margin: 0;
90
+ font-size: var(--dsw-font-base-16-font-size, 14px);
91
+ line-height: 1.6;
92
+ color: var(--dsw-alias-label-secondary, inherit);
93
+ }
94
+ .dsh-session-delete__hint {
95
+ margin: 0;
96
+ font-size: var(--dsw-font-base-16-font-size, 14px);
97
+ line-height: 1.6;
98
+ color: var(--dsw-alias-label-tertiary, inherit);
99
+ }
100
+ .dsh-session-delete__status {
101
+ font-size: var(--dsw-font-base-16-font-size, 14px);
102
+ color: var(--dsw-alias-label-tertiary, inherit);
103
+ }
104
+ .dsh-session-delete__error {
105
+ font-size: var(--dsw-font-base-16-font-size, 14px);
106
+ line-height: 1.6;
107
+ color: var(--dsw-alias-state-error-primary, #d33);
108
+ }
109
+ .dsh-session-delete__footer {
110
+ display: flex; justify-content: flex-end; gap: 8px;
111
+ margin-top: 4px;
112
+ }
113
+ .dsh-session-delete__button {
114
+ appearance: none;
115
+ min-width: 72px;
116
+ padding: 6px 14px;
117
+ border-radius: 8px;
118
+ border: 1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.32));
119
+ background: transparent;
120
+ color: var(--dsw-alias-label-primary, inherit);
121
+ font: inherit;
122
+ font-size: 14px;
123
+ cursor: pointer;
124
+ }
125
+ .dsh-session-delete__button:hover:not(:disabled) {
126
+ background: var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, 0.12));
127
+ }
128
+ .dsh-session-delete__button:focus-visible {
129
+ outline: var(--dsw-focus-ring-width, 2px) solid var(--dsw-focus-ring-color, #4a7dff);
130
+ outline-offset: 2px;
131
+ }
132
+ .dsh-session-delete__button:disabled { opacity: 0.5; cursor: default; }
133
+ .dsh-session-delete__button--danger {
134
+ border-color: var(--dsw-alias-state-error-primary, #d33);
135
+ color: var(--dsw-alias-state-error-primary, #d33);
136
+ }
137
+ .dsh-session-delete__button--danger:hover:not(:disabled) {
138
+ background: var(--dsw-alias-interactive-bg-hover-danger, rgba(221, 51, 51, 0.1));
139
+ }
140
+ `
141
+
142
+ /**
143
+ * Minimal observable snapshot store: the slot hook the plugin injects reads
144
+ * it through `useSyncExternalStore`.
145
+ * @param initial - starting value.
146
+ */
147
+ function createStore(initial) {
148
+ let value = initial
149
+ const listeners = new Set()
150
+ return {
151
+ getSnapshot: () => value,
152
+ subscribe: (listener) => {
153
+ listeners.add(listener)
154
+ return () => { listeners.delete(listener) }
155
+ },
156
+ set: (next) => {
157
+ if (Object.is(next, value)) return
158
+ value = next
159
+ for (const listener of [...listeners]) listener()
160
+ },
161
+ }
162
+ }
163
+
164
+ /** Directory base for this plugin's Host routes, prefix-safe like the page itself. */
165
+ function routeUrl(method) {
166
+ const raw = typeof document !== 'undefined' && typeof document.baseURI === 'string'
167
+ ? document.baseURI
168
+ : typeof location !== 'undefined' ? location.href : 'http://dsh.internal/'
169
+ const base = new URL(raw, 'http://dsh.internal/')
170
+ base.search = ''
171
+ base.hash = ''
172
+ if (!base.pathname.endsWith('/')) base.pathname += '/'
173
+ return new URL(`${ROUTE}/${method}`, base.href).href
174
+ }
175
+
176
+ /**
177
+ * Ask the Host to remove one Session permanently.
178
+ * @param sessionId - Session to remove.
179
+ * @returns the Host's report.
180
+ * @throws {Error} carrying the Host's reason.
181
+ */
182
+ async function requestDelete(sessionId) {
183
+ const response = await fetch(routeUrl('delete'), {
184
+ method: 'POST',
185
+ headers: { 'content-type': 'application/json' },
186
+ credentials: 'same-origin',
187
+ body: JSON.stringify({ sessionId }),
188
+ })
189
+ let payload
190
+ try {
191
+ payload = await response.json()
192
+ } catch {
193
+ payload = undefined
194
+ }
195
+ if (response.ok && payload?.ok === true) return payload.value
196
+ const error = payload?.error
197
+ const failure = new Error(
198
+ typeof error?.message === 'string' && error.message !== ''
199
+ ? error.message
200
+ : `the Host answered HTTP ${String(response.status)}`,
201
+ )
202
+ failure.code = typeof error?.code === 'string' ? error.code : 'delete-failed'
203
+ throw failure
204
+ }
205
+
206
+ /** Outline trash glyph, drawn for this plugin (14px, currentColor). */
207
+ function TrashIcon() {
208
+ return h('svg', {
209
+ width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none',
210
+ stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round',
211
+ 'aria-hidden': true, focusable: false,
212
+ },
213
+ h('path', { d: 'M2.75 4.25h10.5' }),
214
+ h('path', { d: 'M6.25 4.25V3a.75.75 0 0 1 .75-.75h2a.75.75 0 0 1 .75.75v1.25' }),
215
+ h('path', { d: 'M4 4.25l.6 8.1a1.25 1.25 0 0 0 1.25 1.15h4.3a1.25 1.25 0 0 0 1.25-1.15l.6-8.1' }),
216
+ h('path', { d: 'M6.6 6.75v4.5M9.4 6.75v4.5' }),
217
+ )
218
+ }
219
+
220
+ /**
221
+ * The `shell.overlay` entry: nothing without a pending request, otherwise
222
+ * the confirmation for the Session the menu captured.
223
+ * @param props - the request hook, its settlement, the Host call, and the locale seat.
224
+ * @returns the open dialog, or null.
225
+ */
226
+ function DeleteSessionDialog({ useDeleteRequest, settle, removeSession, t }) {
227
+ const request = useDeleteRequest(value => value)
228
+ if (request === null) return null
229
+ return h(DeleteSessionForm, { key: request.sessionId, request, settle, removeSession, t })
230
+ }
231
+
232
+ /**
233
+ * One request's dialog: busy and error state die with it.
234
+ * @param props - captured request plus the shared callbacks.
235
+ * @returns the dialog.
236
+ */
237
+ function DeleteSessionForm({ request, settle, removeSession, t }) {
238
+ const [busy, setBusy] = useState(false)
239
+ const [error, setError] = useState(null)
240
+ const cancelRef = useRef(null)
241
+ const titleId = useId()
242
+ const descId = useId()
243
+ // An untitled Session carries an empty display title; naming nothing would
244
+ // read as a broken sentence, so the dialog names the placeholder instead.
245
+ const name = typeof request.displayTitle === 'string' && request.displayTitle.trim() !== ''
246
+ ? request.displayTitle
247
+ : t('dialog.untitled')
248
+
249
+ useEffect(() => {
250
+ cancelRef.current?.focus()
251
+ }, [])
252
+
253
+ const close = useCallback(() => {
254
+ if (busy) return
255
+ settle()
256
+ }, [busy, settle])
257
+
258
+ useEffect(() => {
259
+ const onKeyDown = (event) => {
260
+ if (event.key === 'Escape') {
261
+ event.stopPropagation()
262
+ close()
263
+ }
264
+ }
265
+ document.addEventListener('keydown', onKeyDown, true)
266
+ return () => { document.removeEventListener('keydown', onKeyDown, true) }
267
+ }, [close])
268
+
269
+ const confirm = useCallback(() => {
270
+ if (busy) return
271
+ setBusy(true)
272
+ setError(null)
273
+ removeSession(request.sessionId, name).then(() => {
274
+ setBusy(false)
275
+ settle()
276
+ }).catch((reason) => {
277
+ setBusy(false)
278
+ const code = reason && reason.code
279
+ if (code === 'session-active') setError(t('dialog.running'))
280
+ else if (code === 'not-found') setError(t('dialog.gone'))
281
+ else setError(t('dialog.failed', { message: reason instanceof Error ? reason.message : String(reason) }))
282
+ })
283
+ }, [busy, name, removeSession, request.sessionId, settle, t])
284
+
285
+ return h(React.Fragment, null,
286
+ h('style', { key: 'style' }, STYLES),
287
+ h('div', {
288
+ key: 'backdrop',
289
+ className: 'dsh-session-delete__backdrop',
290
+ onMouseDown: (event) => { if (event.target === event.currentTarget) close() },
291
+ },
292
+ h('div', {
293
+ className: 'dsh-session-delete__card',
294
+ role: 'dialog',
295
+ 'aria-modal': 'true',
296
+ 'aria-labelledby': titleId,
297
+ 'aria-describedby': descId,
298
+ },
299
+ h('h2', { className: 'dsh-session-delete__title', id: titleId }, t('dialog.title')),
300
+ h('p', { className: 'dsh-session-delete__desc', id: descId },
301
+ t('dialog.desc', { name })),
302
+ h('p', { className: 'dsh-session-delete__hint' }, t('dialog.hint')),
303
+ busy && h('div', { className: 'dsh-session-delete__status', role: 'status' }, t('dialog.pending')),
304
+ error !== null && h('div', { className: 'dsh-session-delete__error', role: 'alert' }, error),
305
+ h('div', { className: 'dsh-session-delete__footer' },
306
+ h('button', {
307
+ type: 'button',
308
+ ref: cancelRef,
309
+ className: 'dsh-session-delete__button',
310
+ disabled: busy,
311
+ onClick: close,
312
+ }, t('dialog.cancel')),
313
+ h('button', {
314
+ type: 'button',
315
+ className: 'dsh-session-delete__button dsh-session-delete__button--danger',
316
+ disabled: busy,
317
+ onClick: confirm,
318
+ }, t('dialog.confirm')),
319
+ ),
320
+ ),
321
+ ),
322
+ )
323
+ }
324
+
325
+ return {
326
+ name: 'session-delete',
327
+ inject: ['contextMenus', 'slots', 'locale', 'sessions'],
328
+
329
+ /**
330
+ * Register the dictionaries, the Session menu action, its icon, and the dialog.
331
+ * @param ctx - client root context.
332
+ */
333
+ apply(ctx) {
334
+ ctx.effect(() => ctx.locale.register(NS, 'zh', zh), 'session-delete: zh dictionary')
335
+ ctx.effect(() => ctx.locale.register(NS, 'en', en), 'session-delete: en dictionary')
336
+ const t = ctx.locale.bind(NS)
337
+
338
+ const requestStore = createStore(null)
339
+ // The sidebar's session rows are a pulled list: removing a cold Session
340
+ // on disk edits no workspace membership it can push, so the page has to
341
+ // re-read the list for the row to go away.
342
+ const sessionsService = ctx.get('sessions')
343
+ const requestDeleteSession = async (sessionId, displayName) => {
344
+ const value = await requestDelete(sessionId)
345
+ try {
346
+ await sessionsService?.refresh?.()
347
+ } catch (error) {
348
+ console.warn('session-delete: the session list did not refresh', error)
349
+ }
350
+ // Feedback outlives the dialog; a toast failure must not turn a
351
+ // completed delete into a reported failure.
352
+ try {
353
+ ctx.contextMenus.notify(t('notice.deleted', {
354
+ name: typeof displayName === 'string' && displayName !== '' ? displayName : sessionId,
355
+ }), true)
356
+ } catch (error) {
357
+ console.warn('session-delete: the confirmation notice was not shown', error)
358
+ }
359
+ return value
360
+ }
361
+
362
+ ctx.slots.inject('contextMenu.icon', () => ctx.slots.register(
363
+ { name: 'contextMenu.icon', key: ICON_KEY },
364
+ TrashIcon,
365
+ ))
366
+
367
+ ctx.effect(() => ctx.contextMenus.register({
368
+ id: 'session.delete',
369
+ target: 'session',
370
+ // 600 is the shipped archive item; the footer keeps provider order, so
371
+ // this renders directly under 「归档会话」.
372
+ order: 700,
373
+ resolve: (target) => [{
374
+ id: 'delete',
375
+ label: t('menu.deleteSession'),
376
+ icon: { key: ICON_KEY },
377
+ danger: true,
378
+ // Both live in the footer, after the component rows: the group
379
+ // 「归档会话」 already opens.
380
+ afterContent: true,
381
+ run: () => {
382
+ requestStore.set({ sessionId: target.sessionId, displayTitle: target.displayTitle })
383
+ },
384
+ }],
385
+ }), 'session-delete: session menu action')
386
+
387
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
388
+ name: 'shell.overlay',
389
+ id: 'session-delete.delete-dialog',
390
+ locale: NS,
391
+ inject: () => ({
392
+ hooks: { deleteRequest: requestStore },
393
+ settle: () => { requestStore.set(null) },
394
+ removeSession: requestDeleteSession,
395
+ }),
396
+ }, DeleteSessionDialog))
397
+ },
398
+ }
399
+ },
400
+ })
@@ -0,0 +1,6 @@
1
+ # This bundle inserts one Host row. The row serves the plugin's own JSON route
2
+ # and performs the permanent deletion; its client half (client.js) contributes
3
+ # the menu item and the confirmation dialog. No config is read.
4
+ - insert:
5
+ - id: session-delete
6
+ name: '@todrink/dsh-session-delete'
package/icon.svg ADDED
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" role="img" aria-label="Delete session">
2
+ <rect x="2" y="2" width="32" height="32" rx="9" fill="#C8422F"/>
3
+ <g fill="none" stroke="#FFFFFF" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
4
+ <path d="M11.5 13.2h13"/>
5
+ <path d="M15.4 13.2v-1.9c0-.7.6-1.3 1.3-1.3h2.6c.7 0 1.3.6 1.3 1.3v1.9"/>
6
+ <path d="M13 13.2l.8 10.1c.1 1 .9 1.7 1.9 1.7h4.6c1 0 1.8-.7 1.9-1.7l.8-10.1"/>
7
+ <path d="M16 16.9v5.3M20 16.9v5.3"/>
8
+ </g>
9
+ </svg>
package/index.js ADDED
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Host half of `@todrink/dsh-session-delete`.
3
+ *
4
+ * DSH has no delete operation for a stored Session: 「归档会话」 only hides a
5
+ * Session and keeps its log, and `SessionPersistence` exposes create/open/
6
+ * stat/list but no removal. This plugin adds one HTTP route that performs the
7
+ * permanent removal the sidebar menu asks for:
8
+ *
9
+ * 1. refuse a Session that is live in this process (an open turn owns its log);
10
+ * 2. delete the stored per-Session artifact directory the persistence backend
11
+ * reports through `stat().location` (directory named after the Session id —
12
+ * otherwise just the artifact file);
13
+ * 3. detach the id from every Workspace that accounts it, and drop it from the
14
+ * archived/pinned sets, so the sidebar row disappears immediately through
15
+ * the Workspace feed;
16
+ * 4. remove the Session's projection checkpoint (a cache; best effort).
17
+ *
18
+ * The SQLite search index needs no call here: `dsh-session-query-sqlite`
19
+ * reconciles against `SessionPersistence.list()` and prunes a Session whose
20
+ * stored artifact disappeared.
21
+ *
22
+ * @module @todrink/dsh-session-delete
23
+ */
24
+
25
+ import { readdir, rm, stat, unlink } from 'node:fs/promises'
26
+ import { homedir } from 'node:os'
27
+ import { basename, dirname, join } from 'node:path'
28
+
29
+ /** Route prefix owned by this plugin; the client resolves it against its page. */
30
+ const ROUTE_PREFIX = '/session-delete/api'
31
+
32
+ /** Largest accepted request body; the only payload is one Session id. */
33
+ const MAX_BODY_BYTES = 8 * 1024
34
+
35
+ /**
36
+ * Session ids are generated identifiers; refusing anything else keeps the
37
+ * artifact path below derived from a value that cannot traverse directories.
38
+ */
39
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/
40
+
41
+ /** Services this plugin needs; without them it stays inactive instead of throwing. */
42
+ export const inject = ['webServer', 'connection', 'sessionPersistence', 'workspaceRegistry', 'sessions']
43
+
44
+ /** A stable failure the route renders as `{ ok: false, error }`. */
45
+ class SessionDeleteError extends Error {
46
+ /**
47
+ * @param code - stable wire code the client branches on.
48
+ * @param message - user-facing reason.
49
+ * @param status - HTTP status for this failure.
50
+ */
51
+ constructor(code, message, status) {
52
+ super(message)
53
+ this.name = 'SessionDeleteError'
54
+ this.code = code
55
+ this.status = status
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Register the route that deletes one Session permanently.
61
+ * @param ctx - Host context owning the Web server, Session store, persistence, and Workspace registry.
62
+ */
63
+ export function apply(ctx) {
64
+ ctx.effect(() => ctx.webServer.register({
65
+ kind: 'prefix',
66
+ path: ROUTE_PREFIX,
67
+ handler: async (req, res) => {
68
+ // Same-origin fence every shipped plugin route uses: it rejects requests
69
+ // that did not come from this Host's own page or worker. The service
70
+ // answers the HTTP status to use, or undefined to admit the request.
71
+ const rejection = typeof ctx.connection?.requestRejection === 'function'
72
+ ? ctx.connection.requestRejection(req)
73
+ : undefined
74
+ if (rejection !== undefined) {
75
+ writeJson(res, rejection, { ok: false, error: { code: 'forbidden', message: 'forbidden' } })
76
+ return
77
+ }
78
+ const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
79
+ if (pathname !== `${ROUTE_PREFIX}/delete`) {
80
+ writeJson(res, 404, { ok: false, error: { code: 'not-found', message: 'unknown method' } })
81
+ return
82
+ }
83
+ if (req.method !== 'POST') {
84
+ writeJson(res, 405, { ok: false, error: { code: 'method-error', message: 'method not allowed' } })
85
+ return
86
+ }
87
+ const essence = String(req.headers['content-type']).split(';', 1)[0]?.trim().toLowerCase()
88
+ if (essence !== 'application/json') {
89
+ writeJson(res, 415, { ok: false, error: { code: 'unsupported-media-type', message: 'content-type must be application/json' } })
90
+ return
91
+ }
92
+ try {
93
+ const body = await readJsonBody(req)
94
+ const sessionId = body?.sessionId
95
+ if (typeof sessionId !== 'string' || !SESSION_ID_PATTERN.test(sessionId)) {
96
+ throw new SessionDeleteError('bad-request', 'sessionId is missing or malformed', 400)
97
+ }
98
+ const value = await deleteSession(ctx, sessionId)
99
+ ctx.logger?.info?.('session-delete: removed session %s', sessionId)
100
+ writeJson(res, 200, { ok: true, value })
101
+ } catch (error) {
102
+ const code = error instanceof SessionDeleteError ? error.code : 'delete-failed'
103
+ const status = error instanceof SessionDeleteError ? error.status : 500
104
+ const message = error instanceof Error ? error.message : String(error)
105
+ ctx.logger?.warn?.(`session-delete: ${code}: ${message}`)
106
+ writeJson(res, status, { ok: false, error: { code, message } })
107
+ }
108
+ },
109
+ }), 'session-delete: /session-delete/api route')
110
+ }
111
+
112
+ /**
113
+ * Permanently remove one Session: stored artifact, Workspace accounting, and caches.
114
+ * @param ctx - Host context.
115
+ * @param sessionId - Session to remove.
116
+ * @returns what was removed, for the client's notice.
117
+ * @throws {SessionDeleteError} when the Session is live or nothing could be removed.
118
+ */
119
+ async function deleteSession(ctx, sessionId) {
120
+ requireIdle(ctx, sessionId)
121
+ const snapshot = await ctx.sessionPersistence.stat(sessionId, {})
122
+ const location = snapshot?.location
123
+ // Captured before the artifact goes away: `Workspace.sessionIds` filters by
124
+ // the host's candidate check, which a removed artifact can already fail.
125
+ const holders = ctx.workspaceRegistry.list()
126
+ .filter(workspace => workspace.sessionIds.includes(sessionId))
127
+ const removedPaths = await removeArtifact(sessionId, location)
128
+ // A Session that never materialized has no artifact to name, yet the backend
129
+ // may still hold its empty directory. Remove that residue too, so a later
130
+ // `list()` cannot resurrect the identity and the disk stays clean.
131
+ if (removedPaths.length === 0) removedPaths.push(...await removeLeftoverDirectory(ctx, sessionId))
132
+ const detachedWorkspaceIds = []
133
+ for (const workspace of holders) {
134
+ await workspace.detachSession(sessionId)
135
+ detachedWorkspaceIds.push(String(workspace.id))
136
+ }
137
+ // Both are idempotent no-ops for an id that is not in the set; leaving a
138
+ // deleted id in either set would leak into workspace.json forever.
139
+ await ctx.workspaceRegistry.unarchiveSession(sessionId)
140
+ await ctx.workspaceRegistry.unpinSession(sessionId)
141
+ removeProjectionCache(ctx, sessionId)
142
+ if (removedPaths.length === 0 && detachedWorkspaceIds.length === 0) {
143
+ throw new SessionDeleteError('not-found', `no stored session "${sessionId}" to delete`, 404)
144
+ }
145
+ return { sessionId, removedPaths, detachedWorkspaceIds, alreadyGone: location === undefined }
146
+ }
147
+
148
+ /**
149
+ * Refuse a Session that this process still owns: an open turn appends to its
150
+ * log, so removing the log underneath it would corrupt the running exchange.
151
+ * @param ctx - Host context.
152
+ * @param sessionId - Session about to be deleted.
153
+ */
154
+ function requireIdle(ctx, sessionId) {
155
+ if (ctx.sessions.get(sessionId) !== undefined) {
156
+ throw new SessionDeleteError(
157
+ 'session-active',
158
+ 'this session is open or running in this process; archive it first and delete it once it is idle',
159
+ 409,
160
+ )
161
+ }
162
+ const agents = ctx.get('agents')
163
+ if (typeof agents?.get === 'function' && agents.get(sessionId) !== undefined) {
164
+ throw new SessionDeleteError(
165
+ 'session-active',
166
+ 'this session still has an agent in this process; stop it before deleting',
167
+ 409,
168
+ )
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Remove the stored artifact for one Session.
174
+ *
175
+ * The JSONL backend keeps one directory per Session named after its id and one
176
+ * artifact inside it; older formats may leave a sibling generation next to the
177
+ * current one, so the whole dedicated directory goes. Any other layout removes
178
+ * exactly the artifact `stat()` named.
179
+ * @param sessionId - Session to remove.
180
+ * @param location - Backend-resolved artifact path, when the Session materialized.
181
+ * @returns the paths that were removed.
182
+ */
183
+ async function removeArtifact(sessionId, location) {
184
+ if (location === undefined) return []
185
+ const file = location.path
186
+ const directory = dirname(file)
187
+ if (basename(directory) !== sessionId) {
188
+ await unlink(file).catch((error) => {
189
+ if (error?.code !== 'ENOENT') throw error
190
+ })
191
+ return [file]
192
+ }
193
+ // Defence in depth: never recurse into a path that is not the Session's own
194
+ // directory, even though the id pattern already refuses separators.
195
+ if (basename(directory) !== sessionId) return []
196
+ const info = await stat(directory).catch(() => undefined)
197
+ if (info === undefined) return []
198
+ if (!info.isDirectory()) {
199
+ await unlink(directory).catch(() => {})
200
+ return [directory]
201
+ }
202
+ await rm(directory, { recursive: true, force: true })
203
+ return [directory]
204
+ }
205
+
206
+ /**
207
+ * Remove a per-Session directory the persistence backend did not report an
208
+ * artifact for (a Session created but never materialized).
209
+ *
210
+ * Only a directory whose name is exactly the Session id, directly below one
211
+ * project directory of the Sessions root, is touched, so this can never remove
212
+ * another Session's data.
213
+ * @param ctx - Host context, for logging only.
214
+ * @param sessionId - Session whose directory is sought.
215
+ * @returns the removed directory, when one was found.
216
+ */
217
+ async function removeLeftoverDirectory(ctx, sessionId) {
218
+ const root = join(dshHome(), 'sessions')
219
+ const projects = await readdir(root, { withFileTypes: true }).catch(() => [])
220
+ for (const entry of projects) {
221
+ if (!entry.isDirectory()) continue
222
+ const candidate = join(root, entry.name, sessionId)
223
+ if (basename(candidate) !== sessionId) continue
224
+ const info = await stat(candidate).catch(() => undefined)
225
+ if (info?.isDirectory() !== true) continue
226
+ await rm(candidate, { recursive: true, force: true })
227
+ return [candidate]
228
+ }
229
+ return []
230
+ }
231
+
232
+ /**
233
+ * Drop the Session's projection checkpoint. It is a derived cache: a failure
234
+ * here costs one cold replay, never correctness, so it stays silent.
235
+ * @param ctx - Host context.
236
+ * @param sessionId - removed Session.
237
+ */
238
+ function removeProjectionCache(ctx, sessionId) {
239
+ const cache = join(dshHome(), 'storages', 'session_projcache', 'sessions', `${sessionId}.json`)
240
+ void rm(cache, { force: true }).catch((error) => {
241
+ ctx.logger?.warn?.(`session-delete: projection cache not removed (${String(error)})`)
242
+ })
243
+ }
244
+
245
+ /**
246
+ * The DSH home this Host stores sessions and caches under.
247
+ * @returns absolute home directory.
248
+ */
249
+ function dshHome() {
250
+ const configured = process.env.DSH_HOME
251
+ return typeof configured === 'string' && configured !== '' ? configured : join(homedir(), '.dsh')
252
+ }
253
+
254
+ /**
255
+ * Read one bounded JSON object body.
256
+ * @param req - incoming request.
257
+ * @returns parsed object, or undefined for an empty body.
258
+ * @throws {SessionDeleteError} for an oversized or unparsable body.
259
+ */
260
+ async function readJsonBody(req) {
261
+ const chunks = []
262
+ let size = 0
263
+ for await (const chunk of req) {
264
+ size += chunk.length
265
+ if (size > MAX_BODY_BYTES) {
266
+ throw new SessionDeleteError('too-large', 'request body is too large', 413)
267
+ }
268
+ chunks.push(chunk)
269
+ }
270
+ if (size === 0) return undefined
271
+ try {
272
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8'))
273
+ return typeof value === 'object' && value !== null ? value : undefined
274
+ } catch {
275
+ throw new SessionDeleteError('bad-request', 'request body is not valid JSON', 400)
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Answer one JSON response.
281
+ * @param res - response to complete.
282
+ * @param status - HTTP status.
283
+ * @param body - JSON body.
284
+ */
285
+ function writeJson(res, status, body) {
286
+ const text = JSON.stringify(body)
287
+ res.statusCode = status
288
+ res.setHeader('content-type', 'application/json; charset=utf-8')
289
+ res.setHeader('cache-control', 'no-store')
290
+ res.end(text)
291
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Delete session",
4
+ "description": "Adds \"Delete session\" to the session context menu, directly below \"Archive session\": after a confirmation it permanently removes that session's local record — conversation, title, archived and pinned marks — instead of hiding it. A session that is running or open in this process is refused; archive still hides one without deleting it."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "删除会话",
4
+ "description": "在会话右键菜单的「归档会话」下面加一项「删除会话」:确认后永久删除该会话的本地记录(对话内容、标题、归档与置顶标记),而不只是把它归档藏起来。运行中的会话会被拒绝删除;只是想清理列表时仍可用「归档会话」。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@todrink/dsh-session-delete",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "type": "module",
5
+ "description": "Adds Delete session to the session menu, below Archive: permanently removes a stored session and its local history.",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./client": "./client.js",
9
+ "./locale/*.json": "./locale/*.json",
10
+ "./icon": "./icon.svg"
11
+ },
12
+ "files": [
13
+ "index.js",
14
+ "client.js",
15
+ "cordis.patch.yml",
16
+ "locale/*.json",
17
+ "icon.svg",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "engines": {
22
+ "node": ">=18",
23
+ "dsh": ">=0.2.2-rc.5"
24
+ },
25
+ "keywords": [
26
+ "deepseek-harness",
27
+ "dsh",
28
+ "dsh-plugin",
29
+ "dsh-bundle",
30
+ "session",
31
+ "delete",
32
+ "context-menu",
33
+ "cleanup"
34
+ ],
35
+ "license": "MIT",
36
+ "author": {
37
+ "name": "todrink",
38
+ "url": "https://github.com/todrinkcho"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/todrinkcho/dsh-session-delete.git"
43
+ },
44
+ "homepage": "https://github.com/todrinkcho/dsh-session-delete#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/todrinkcho/dsh-session-delete/issues"
47
+ },
48
+ "dsh": {
49
+ "bundle": {
50
+ "patch": "./cordis.patch.yml"
51
+ },
52
+ "client": {
53
+ "platform": "web",
54
+ "immediately": true,
55
+ "inject": [
56
+ "@deepseek-ai/dsh-client-ui-context-menu",
57
+ "@deepseek-ai/dsh-client-locale",
58
+ "@deepseek-ai/dsh-api-session-controller"
59
+ ]
60
+ }
61
+ },
62
+ "publishConfig": {
63
+ "access": "public",
64
+ "registry": "https://registry.npmjs.org"
65
+ }
66
+ }