dsh-session-ops 0.2.7 → 0.2.9

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/README.md CHANGED
@@ -33,8 +33,15 @@ The plugin row is declared in the bundled `cordis.patch.yml`; its entry id is `s
33
33
  - `<DSH_HOME>/rewind-snapshots/<session-id>/` (rewind snapshots, if present)
34
34
 
35
35
  All three are removed from disk, and project directories left empty are cleaned up. **There is no
36
- trash and no undo.** Back up `$DSH_HOME` yourself; the panel provides a dry run and two
37
- confirmations, but the operator owns the outcome.
36
+ trash and no undo.** Back up `$DSH_HOME` yourself; the panel provides a dry run and a one-click confirmation card, but the operator owns the outcome.
37
+
38
+ The context-menu row resolves through a **single-session probe** (`/session-admin/api/probe`): a
39
+ menu `resolve` gets a 1 s budget (`resolutionTimeoutMs`, and a timed-out provider is dropped), while
40
+ a table-wide dry run measures every session directory (≈3.6 s for 391 sessions here) — so the row
41
+ used to appear only sometimes. The probe skips byte measurement and shares the exact guard chain
42
+ with `delete`; it only decides whether the row is enabled, and `delete` re-checks every guard. The
43
+ confirmation card is drawn in the page (never `window.confirm` / `window.prompt`: Electron throws
44
+ `prompt() is not supported.`) and deliberately asks for a single click — no typed confirmation word.
38
45
 
39
46
  Safe defaults (configurable): `allowWorkspaceSessions=false`, `allowLiveSessions=false`,
40
47
  `refuseRunning=true` — workspace sessions, live sessions and mid-turn moves are refused by default.
package/README.zh.md CHANGED
@@ -28,7 +28,9 @@ dsh plugin --profile <profile> add dsh-session-ops
28
28
  - `<DSH_HOME>/storages/session_projcache/sessions/<session-id>.json`:投影缓存
29
29
  - `<DSH_HOME>/rewind-snapshots/<session-id>/`:回退快照(若有)
30
30
 
31
- 删除后顺手清理因此变空的项目目录。没有回收站,删了无法恢复;删除前请自行备份 `$DSH_HOME`。面板提供预演与确认卡片(输入「删除」才能继续),但最终责任在操作者。
31
+ 删除后顺手清理因此变空的项目目录。没有回收站,删了无法恢复;删除前请自行备份 `$DSH_HOME`。面板提供预演与确认卡片(弹出来点一次「删除」即可),但最终责任在操作者。
32
+
33
+ 右键菜单的「删除会话…」用**单条预演**(`/session-admin/api/probe`)决定能不能点:菜单的 `resolve` 只有 1 s 预算(`resolutionTimeoutMs`,超时整项被丢弃),而整表 dryRun 要把每个会话目录的体积都走一遍(本机 391 条约 3.6 s),结果就是这一项在菜单里时有时无。`probe` 只做无体积统计的扫描 + 与 `delete` **同一份**守卫判定,毫秒级返回 `{removable, reason}`;它只管菜单显示,真删时 `delete` 会重新过一遍守卫。确认卡片是页面里自己画的(不用 `window.confirm` / `window.prompt`——Electron 里 `window.prompt` 直接抛 `prompt() is not supported.`):卡片刻意只用一次点击,不要求输入确认词。
32
34
 
33
35
  默认安全边界(可在配置里改):`allowWorkspaceSessions=false`、`allowLiveSessions=false`、`refuseRunning=true`。工作区会话、正在跑的会话、运行中的搬迁默认都被拒绝。
34
36
 
@@ -56,7 +58,7 @@ DSH 0.2.2-rc.3 起,会话标题栏的「会话面板」里会出现本插件
56
58
  | `root` | `''` | 会话根目录;空则取 `sessionPersistence.root`(jsonl 后端为 `$DSH_HOME/sessions`) |
57
59
  | `adminAllowHosts` | `[]` | 删除半边的 LAN 信任列表(按 `Host` 头解析 `host` 或 `host:port`) |
58
60
  | `moveAllowHosts` | `[]` | 搬迁半边的 LAN 信任列表(按 `Host` 头完整值精确匹配) |
59
- | `headerDeleteButton` | `true` | 会话标题栏垃圾桶图标(图标 + 输入确认词的确认卡片) |
61
+ | `headerDeleteButton` | `true` | 会话标题栏垃圾桶图标(图标 + 一次点击的确认卡片) |
60
62
  | `allowWorkspaceSessions` | `false` | 允许删除已归属工作区的会话 |
61
63
  | `allowLiveSessions` | `false` | 允许删除宿主里驻留的会话 |
62
64
  | `maxBatch` | `200` | 单次批量删除上限 |
package/lib/admin.js CHANGED
@@ -286,6 +286,70 @@ export function createSessionAdmin(options = {}) {
286
286
  return true;
287
287
  });
288
288
  }
289
+ /**
290
+ * 一条会话现在不能删的理由;能删返回 `undefined`。
291
+ *
292
+ * `remove()`(真删)与 `probe()`(菜单预演)共用这一处判定,顺序也一致:
293
+ * 两处若各写一遍,「菜单里显示可删、点下去却被拒」就会成为常态。
294
+ *
295
+ * `live` 是「**正在跑**」的集合,不是「Host 仍挂着」的集合。这个区分是必需的:
296
+ *
297
+ * 会话在创建 agent 时被 enter(dsh-agent-loop/index.js:1714),而 agent 只在被
298
+ * dispose 时才 detach —— 长期运行的 `dsh web` 里,只要碰过就基本一直挂着。若把
299
+ * 「挂着」当作不可删,删除功能(以及待删除队列)在真实使用中会永久失效。
300
+ *
301
+ * 那为什么删「挂着但空闲」的是安全的?因为删除会移除**整个会话目录**,而持久化
302
+ * 的追加写是 `open(path, "a")`(dsh-session-persistence-jsonl/index.js:3049):
303
+ * 它只在文件不存在时创建文件,**不会创建父目录**。目录已经没了,于是后续写入直接
304
+ * 拿到 ENOENT 并失败——一个响亮、局部的错误,而不是生成一个「无头日志」把整个
305
+ * profile 的启动搞崩(那才是真正要避免的结局)。已实测该 open 语义。
306
+ *
307
+ * @param record - 目标会话的扫描记录。
308
+ * @param id - 目标会话 id。
309
+ * @param live - 正在跑一轮的会话集合。
310
+ * @param options2 - 同一份 `RemoveOptions`(放行开关与 `callerSessionId`)。
311
+ * @param removed - 本批已经删掉多少条(只为 `batch-limit`)。
312
+ * @returns 拒绝理由,或 `undefined` 表示可删。
313
+ */
314
+ function refusalOf(record, id, live, options2, removed) {
315
+ if (options2.callerSessionId !== undefined && id === options2.callerSessionId)
316
+ return 'caller-session';
317
+ if (live.has(id) && options2.includeLive !== true)
318
+ return 'running-session';
319
+ if (record.workspaceId !== null && options2.includeWorkspace !== true)
320
+ return 'workspace-session';
321
+ if (record.archived && options2.includeArchived !== true)
322
+ return 'archived-session';
323
+ if (record.subagent && options2.includeSubagent !== true)
324
+ return 'subagent-session';
325
+ if (removed >= (options2.maxBatch ?? 200))
326
+ return 'batch-limit';
327
+ // 目录穿越防线:会话目录必须真的在 sessions/ 里。
328
+ if (!isInside(sessionsRoot, record.dir))
329
+ return 'outside-sessions-root';
330
+ return undefined;
331
+ }
332
+ /**
333
+ * 单条会话的删除预演:只读、毫秒级。
334
+ *
335
+ * 为什么要有它:菜单的 `resolve` 有 1 s 预算(`resolutionTimeoutMs`,超时整项被丢弃)。
336
+ * 用整表 `delete` dryRun 做预演,要把每个会话目录的体积都走一遍(本机 391 条 ≈ 3.6 s),
337
+ * 于是「删除会话…」在菜单里时有时无。这里只做 `scan({ measure: false })`(readdir +
338
+ * 已缓存的会话头),毫秒级完成,判定与 `remove()` 逐条一致。
339
+ *
340
+ * 真正的删除仍然在 `remove()` 里重新过一遍守卫:预演不是执行许可。
341
+ *
342
+ * @param id - 目标会话 id。
343
+ * @param options2 - 放行开关、正在跑的集合与 `callerSessionId`(与 `remove` 同形)。
344
+ * @returns 可删与否,以及不能删的理由。
345
+ */
346
+ function probe(id, options2 = {}) {
347
+ const record = scan({ measure: false }).find((entry) => entry.id === id);
348
+ if (record === undefined)
349
+ return { sessionId: id, removable: false, reason: 'not-found' };
350
+ const reason = refusalOf(record, id, options2.live ?? new Set(), options2, 0);
351
+ return reason === undefined ? { sessionId: id, removable: true } : { sessionId: id, removable: false, reason };
352
+ }
289
353
  /**
290
354
  * 删除若干会话的持久化数据。
291
355
  *
@@ -316,46 +380,9 @@ export function createSessionAdmin(options = {}) {
316
380
  results.push({ id, status: 'skipped', reason: 'not-found' });
317
381
  continue;
318
382
  }
319
- if (options2.callerSessionId !== undefined && id === options2.callerSessionId) {
320
- results.push({ id, status: 'skipped', reason: 'caller-session' });
321
- continue;
322
- }
323
- /*
324
- * `live` 是「**正在跑**」的集合,不是「Host 仍挂着」的集合。这个区分是必需的:
325
- *
326
- * 会话在创建 agent 时被 enter(dsh-agent-loop/index.js:1714),而 agent 只在被
327
- * dispose 时才 detach —— 长期运行的 `dsh web` 里,只要碰过就基本一直挂着。若把
328
- * 「挂着」当作不可删,删除功能(以及待删除队列)在真实使用中会永久失效。
329
- *
330
- * 那为什么删「挂着但空闲」的是安全的?因为删除会移除**整个会话目录**,而持久化
331
- * 的追加写是 `open(path, "a")`(dsh-session-persistence-jsonl/index.js:3049):
332
- * 它只在文件不存在时创建文件,**不会创建父目录**。目录已经没了,于是后续写入直接
333
- * 拿到 ENOENT 并失败——一个响亮、局部的错误,而不是生成一个「无头日志」把整个
334
- * profile 的启动搞崩(那才是真正要避免的结局)。已实测该 open 语义。
335
- */
336
- if (live.has(id) && options2.includeLive !== true) {
337
- results.push({ id, status: 'skipped', reason: 'running-session' });
338
- continue;
339
- }
340
- if (record.workspaceId !== null && options2.includeWorkspace !== true) {
341
- results.push({ id, status: 'skipped', reason: 'workspace-session' });
342
- continue;
343
- }
344
- if (record.archived && options2.includeArchived !== true) {
345
- results.push({ id, status: 'skipped', reason: 'archived-session' });
346
- continue;
347
- }
348
- if (record.subagent && options2.includeSubagent !== true) {
349
- results.push({ id, status: 'skipped', reason: 'subagent-session' });
350
- continue;
351
- }
352
- if (removed >= maxBatch) {
353
- results.push({ id, status: 'skipped', reason: 'batch-limit' });
354
- continue;
355
- }
356
- // 目录穿越防线:会话目录必须真的在 sessions/ 里。
357
- if (!isInside(sessionsRoot, record.dir)) {
358
- results.push({ id, status: 'skipped', reason: 'outside-sessions-root' });
383
+ const refused = refusalOf(record, id, live, { ...options2, maxBatch }, removed);
384
+ if (refused !== undefined) {
385
+ results.push({ id, status: 'skipped', reason: refused });
359
386
  continue;
360
387
  }
361
388
  if (dryRun) {
@@ -444,7 +471,7 @@ export function createSessionAdmin(options = {}) {
444
471
  }
445
472
  return pruned;
446
473
  }
447
- return { home, sessionsRoot, projcacheRoot, rewindRoot, scan, select, remove };
474
+ return { home, sessionsRoot, projcacheRoot, rewindRoot, scan, select, remove, probe };
448
475
  }
449
476
  /** 拆 `host[:port]`(支持 `[::1]:3080` 形态)。 */
450
477
  function parseAuthority(value) {
@@ -745,6 +772,29 @@ function buildApi(admin, config, log, holds, health) {
745
772
  scope: payload?.scope ?? 'all',
746
773
  };
747
774
  },
775
+ /**
776
+ * 单条会话的删除预演(右键菜单用)。
777
+ *
778
+ * 菜单的 `resolve` 有 1 s 预算(`resolutionTimeoutMs`,超时整项被丢弃)。整表
779
+ * `delete` dryRun 要把每个会话目录的体积都走一遍(本机 391 条 ≈ 3.6 s),于是
780
+ * 「删除会话…」在菜单里时有时无。这个方法只做无体积统计的扫描 + 同一份守卫判定,
781
+ * 毫秒级返回 `{removable, reason}`,判定与 `delete` 逐条一致。
782
+ *
783
+ * 它**不是执行许可**:`delete` 会重新过一遍守卫。
784
+ */
785
+ async probe(payload) {
786
+ const sessionId = payload?.sessionId;
787
+ if (typeof sessionId !== 'string' || sessionId === '')
788
+ throw new Error('sessionId is required');
789
+ return admin.probe(sessionId, {
790
+ includeWorkspace: payload?.includeWorkspace === true || config.allowWorkspaceSessions,
791
+ includeArchived: payload?.includeArchived === true,
792
+ includeSubagent: payload?.includeSubagent === true,
793
+ includeLive: payload?.includeLive === true || config.allowLiveSessions,
794
+ live: holds.running(),
795
+ callerSessionId: typeof payload?.callerSessionId === 'string' ? payload.callerSessionId : undefined,
796
+ });
797
+ },
748
798
  /** 扫描会话并按范围返回。 */
749
799
  async list(payload) {
750
800
  const records = admin.scan();
package/lib/client.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * 与 `dsh-session-move:panel`(+`…:panel-via-better-sidebar`),标题分别是
23
23
  * 「会话管理」「会话归位」,角标语义不变(删除半边:未分组条数;搬迁半边:无);
24
24
  * - 会话标题栏垃圾桶的 id `dsh-session-admin:delete-current`(仍然是**图标**,
25
- * 开关由 Host 的 `headerDeleteButton` 决定,默认开启,删除要在卡片里输入确认词);
25
+ * 开关由 Host 的 `headerDeleteButton` 决定,默认开启,删除要过一次确认卡片);
26
26
  * - 数据面仍然只打各自的前缀:`/session-admin/api` 与 `/session-move/api`。
27
27
  *
28
28
  * ## 统一右键菜单(DSH 0.2.2-rc.1 起)
@@ -33,7 +33,7 @@
33
33
  * - 「移动会话到工作区…」(搬迁半边,order 500):菜单里只判断能不能搬并写出理由,
34
34
  * 点下去时重新读一次 Host 状态,然后打开既有右栏「会话归位」面板并选中这条会话;
35
35
  * - 「删除会话…」(删除半边,order 620,`afterContent` 与原生「归档」同区):与标题栏
36
- * 垃圾桶**共用** `deleteSessionFlow`(预演 → 输入确认词 → 删除),`run` 里会再预演
36
+ * 垃圾桶**共用** `deleteSessionFlow`(预演 → 确认卡片 → 删除),`run` 里会再预演
37
37
  * 一次,所以菜单打开到点下去之间状态变了也不会绕过守卫。
38
38
  *
39
39
  * 两项的图标注册在 `contextMenu.icon` 的 keyed slot 上;没有 `contextMenus` 服务
@@ -155,8 +155,9 @@
155
155
  * `删除失败:prompt() is not supported.`——功能看起来像坏了,其实一次都没删过。
156
156
  * 卡片挂在 `document.body` 上,不依赖宿主对话框,桌面端与浏览器行为一致。
157
157
  *
158
- * 防误删的口径没降:确认按钮在输入框里打出「删除」之前一直禁用——要求一次有意的
159
- * 动作,回车或连点顺手确认不掉。
158
+ * 一步:说明删什么,点「删除」即可。「删除」是危险色按钮且排在最后,误点仍要
159
+ * 多走一步;Esc、取消、点遮罩都按取消处理。
160
+ *
160
161
  * @param summary - 这次删除的对象描述(条数、体积或会话 id)。
161
162
  * @returns 用户是否确认删除。
162
163
  */
@@ -178,7 +179,7 @@
178
179
  card.setAttribute('role', 'alertdialog');
179
180
  card.setAttribute('aria-modal', 'true');
180
181
  card.style.width = '100%';
181
- card.style.maxWidth = '420px';
182
+ card.style.maxWidth = '400px';
182
183
  card.style.boxSizing = 'border-box';
183
184
  card.style.display = 'flex';
184
185
  card.style.flexDirection = 'column';
@@ -198,16 +199,6 @@
198
199
  note.style.lineHeight = '1.5';
199
200
  note.style.color = 'var(--dsw-alias-label-secondary, rgba(128, 128, 128, 0.95))';
200
201
  note.textContent = '会话日志、投影缓存与回退快照一并移除,无法撤销。';
201
- const input = document.createElement('input');
202
- input.type = 'text';
203
- input.autocomplete = 'off';
204
- input.placeholder = '输入「删除」以确认';
205
- input.style.padding = '6px 9px';
206
- input.style.fontSize = '12.5px';
207
- input.style.borderRadius = '8px';
208
- input.style.border = '1px solid var(--dsw-alias-border-l2, var(--dsh-border, #d0d5dd))';
209
- input.style.background = 'transparent';
210
- input.style.color = 'inherit';
211
202
  const bar = document.createElement('div');
212
203
  bar.style.display = 'flex';
213
204
  bar.style.gap = '8px';
@@ -221,25 +212,17 @@
221
212
  accept.type = 'button';
222
213
  accept.textContent = '删除';
223
214
  accept.style.cssText =
224
- 'padding:5px 12px;font-size:12.5px;border-radius:8px;border:1px solid transparent;background:var(--dsw-alias-state-error-primary, #d92d20);color:#fff';
225
- /** 输入框内容 → 确认按钮可用性(唯一判据:整串等于「删除」)。 */
226
- function syncAccept() {
227
- const ready = input.value.trim() === '删除';
228
- accept.disabled = !ready;
229
- accept.style.opacity = ready ? '1' : '0.45';
230
- accept.style.cursor = ready ? 'pointer' : 'default';
231
- }
215
+ 'padding:5px 12px;font-size:12.5px;border-radius:8px;border:1px solid transparent;background:var(--dsw-alias-state-error-primary, #d92d20);color:#fff;cursor:pointer';
232
216
  let settled = false;
233
217
  function finish(confirmed) {
234
218
  if (settled)
235
219
  return;
236
220
  settled = true;
237
221
  confirmDeletionOpen = false;
238
- input.removeEventListener('input', syncAccept);
239
- input.removeEventListener('keydown', onKey);
240
222
  dismiss.removeEventListener('click', onDismiss);
241
223
  accept.removeEventListener('click', onAccept);
242
224
  overlay.removeEventListener('mousedown', onBackdrop);
225
+ document.removeEventListener('keydown', onKey, true);
243
226
  if (overlay.parentNode !== null)
244
227
  overlay.parentNode.removeChild(overlay);
245
228
  resolve(confirmed);
@@ -248,42 +231,33 @@
248
231
  finish(false);
249
232
  }
250
233
  function onAccept() {
251
- if (accept.disabled !== true)
252
- finish(true);
234
+ finish(true);
253
235
  }
254
236
  function onBackdrop(event) {
255
237
  if (event.target === overlay)
256
238
  finish(false);
257
239
  }
258
240
  function onKey(event) {
259
- if (event.key === 'Escape') {
260
- if (typeof event.preventDefault === 'function')
261
- event.preventDefault();
262
- finish(false);
241
+ if (event.key !== 'Escape')
263
242
  return;
264
- }
265
- if (event.key === 'Enter' && input.value.trim() === '删除') {
266
- if (typeof event.preventDefault === 'function')
267
- event.preventDefault();
268
- finish(true);
269
- }
243
+ if (typeof event.preventDefault === 'function')
244
+ event.preventDefault();
245
+ finish(false);
270
246
  }
271
- input.addEventListener('input', syncAccept);
272
- input.addEventListener('keydown', onKey);
273
247
  dismiss.addEventListener('click', onDismiss);
274
248
  accept.addEventListener('click', onAccept);
275
249
  overlay.addEventListener('mousedown', onBackdrop);
250
+ // Esc 兜底:捕获阶段监听,输入框有焦点时也收得到。
251
+ document.addEventListener('keydown', onKey, true);
276
252
  card.appendChild(what);
277
253
  card.appendChild(note);
278
- card.appendChild(input);
279
254
  bar.appendChild(dismiss);
280
255
  bar.appendChild(accept);
281
256
  card.appendChild(bar);
282
257
  overlay.appendChild(card);
283
- syncAccept();
284
258
  document.body.appendChild(overlay);
285
- if (typeof input.focus === 'function')
286
- input.focus();
259
+ if (typeof accept.focus === 'function')
260
+ accept.focus();
287
261
  });
288
262
  }
289
263
  /** 时间戳 → `MM-DD HH:mm`。 */
@@ -816,7 +790,7 @@
816
790
  ? h('div', { style: { marginTop: 6 } }, h('div', { style: S.muted }, `未处理 ${refusalRows.length} 条:`), refusalRows.slice(0, 12).map((row) => h('div', { key: row.id, style: S.muted }, `${row.id} — ${REASONS[row.reason] ?? row.reason}`)), refusalRows.length > 12 ? h('div', { style: S.muted }, `…以及另外 ${refusalRows.length - 12} 条`) : null)
817
791
  : null);
818
792
  // 待删除队列:条目、状态、撤销、立即重试。
819
- return h('div', { style: fill ? { ...S.root, ...S_FILL.root } : S.root }, h('div', { style: S.muted }, 'DSH 只能「归档」(隐藏)会话;这里做的是把会话的持久化数据真正从磁盘移除。删除要在确认卡片里输入「删除」,不可恢复。'), head, pathBar, toolbar, failure !== undefined ? h('div', { style: S.error }, `失败:${failure}`) : null, list, resultBox);
793
+ return h('div', { style: fill ? { ...S.root, ...S_FILL.root } : S.root }, h('div', { style: S.muted }, 'DSH 只能「归档」(隐藏)会话;这里做的是把会话的持久化数据真正从磁盘移除。删除会弹一张确认卡片,确认后不可恢复。'), head, pathBar, toolbar, failure !== undefined ? h('div', { style: S.error }, `失败:${failure}`) : null, list, resultBox);
820
794
  };
821
795
  }
822
796
  /** 右侧页签的标题条。 */
@@ -869,6 +843,21 @@
869
843
  }
870
844
  /** 当前选中的会话 id;拿不到(没有会话服务 / 老外壳)时为 undefined。 */
871
845
  function currentSessionId(ctx) {
846
+ /*
847
+ * 0.2.3 起 `ctx.sessions.list.getSnapshot().current` 没了:`SessionListState` 只剩
848
+ * `ids` / `byId` / `phase` / `projectionsBySession`,当前选中会话搬到
849
+ * `ctx.uiSession.adapter.current`(`StandardSourceBinding`,值里带 sessionId)。
850
+ * 之前只读旧字段,于是标题栏垃圾桶永远报「没有选中会话」。
851
+ */
852
+ try {
853
+ const binding = ctx?.uiSession?.adapter?.current?.getSnapshot?.();
854
+ const id = binding?.sessionId ?? binding?.owner?.sessionId;
855
+ if (typeof id === 'string' && id !== '')
856
+ return id;
857
+ }
858
+ catch {
859
+ /* 换下一个来源 */
860
+ }
872
861
  try {
873
862
  return ctx.sessions.list.getSnapshot().current;
874
863
  }
@@ -883,6 +872,19 @@
883
872
  * 目录重新写日志——那正是「无头日志」的由来,而删除守卫正是为了避免它。
884
873
  */
885
874
  function leaveDeletedSession(ctx) {
875
+ /*
876
+ * 0.2.3 的 `ctx.sessions` 没有 `create()`:新会话入口在 `ctx.uiWorkspace`
877
+ * (`startSession` / `connectWorkspace`)。先试新入口,旧宿主退回 `sessions.create`。
878
+ */
879
+ try {
880
+ if (typeof ctx?.uiWorkspace?.startSession === 'function') {
881
+ ctx.uiWorkspace.startSession();
882
+ return;
883
+ }
884
+ }
885
+ catch {
886
+ /* 退到旧入口 */
887
+ }
886
888
  try {
887
889
  ctx.sessions.create();
888
890
  return;
@@ -898,7 +900,39 @@
898
900
  }
899
901
  }
900
902
  /**
901
- * 删除一个会话的整条流程:预演 → 输入确认词 → 删除。
903
+ * 单条删除预演:优先 Host 的 `probe`,老宿主退回整表 dryRun。
904
+ *
905
+ * 为什么不是直接 dryRun:`delete` 的 dryRun 要把每个会话目录的体积都走一遍
906
+ * (本机 391 条约 3.6 s),而菜单的 `resolve` 只有 1 s 预算,超时整项被丢弃,
907
+ * 表现就是「删除会话…」在右键菜单里时有时无;确认卡片也要等这 3.6 s 才出现。
908
+ * `probe`(0.2.8 起)只做无体积统计的扫描 + 同一份守卫判定,毫秒级。
909
+ *
910
+ * 老宿主没有这个方法(404 / bad-request),退回 dryRun —— 慢,但判定同样权威,
911
+ * 且这条路径上的失败会照旧抛给调用方。
912
+ *
913
+ * @param api - Host API 客户端。
914
+ * @param sessionId - 目标会话 id。
915
+ * @param signal - 菜单关闭时作废在途请求。
916
+ * @returns `{ removable, reason? }`,与 `delete` 的逐条结果同义。
917
+ */
918
+ async function probeDeletion(api, sessionId, signal = undefined) {
919
+ const scope = { includeWorkspace: true, includeArchived: true, includeSubagent: true };
920
+ try {
921
+ const verdict = await api.call('probe', { sessionId, ...scope }, signal);
922
+ if (typeof verdict?.removable === 'boolean')
923
+ return verdict;
924
+ }
925
+ catch (error) {
926
+ // 被取消(菜单关了)就不再发第二个请求。
927
+ if (signal?.aborted === true)
928
+ throw error;
929
+ }
930
+ const report = await api.call('delete', { sessionIds: [sessionId], dryRun: true, ...scope }, signal);
931
+ const row = report?.results?.[0];
932
+ return { sessionId, removable: report?.removed > 0, reason: row?.reason };
933
+ }
934
+ /**
935
+ * 删除一个会话的整条流程:预演 → 确认卡片 → 删除。
902
936
  *
903
937
  * 标题栏垃圾桶与右键菜单共用这一段:两处删的是同一个东西,只是入口不同,守卫与
904
938
  * 确认必须逐字一致,否则「从菜单删」就等于绕开「从图标删」的那些检查。
@@ -920,10 +954,10 @@
920
954
  includeArchived: true,
921
955
  includeSubagent: true,
922
956
  };
923
- const probe = await api.call('delete', { ...target, dryRun: true });
924
- const entry = probe.results[0];
925
- if (probe.removed === 0) {
926
- return { ok: false, note: REASONS[entry?.reason] ?? entry?.reason ?? '无法删除' };
957
+ // 预演只判「现在能不能删」;预演不是执行许可,下面那次 delete 会重新过守卫。
958
+ const verdict = await probeDeletion(api, sessionId);
959
+ if (verdict?.removable !== true) {
960
+ return { ok: false, note: REASONS[verdict?.reason] ?? verdict?.reason ?? '无法删除' };
927
961
  }
928
962
  if (!(await confirmDeletion(`永久删除会话 ${sessionId}?`)))
929
963
  return { ok: false };
@@ -943,11 +977,13 @@
943
977
  function createHeaderButton(React, ctx, api) {
944
978
  const h = React.createElement;
945
979
  const TrashIcon = createTrashIcon(React);
946
- return function SessionAdminHeaderButton() {
980
+ return function SessionAdminHeaderButton(props) {
947
981
  const [busy, setBusy] = React.useState(false);
948
982
  const [note, setNote] = React.useState(undefined);
949
983
  async function onClick() {
950
- const id = currentSessionId(ctx);
984
+ // 标题栏这一格由外壳按会话挂载,`sessionId` 是外壳给的标准 props(最权威);
985
+ // 老外壳没有这个 prop 时才回落到「当前选中会话」的查询。
986
+ const id = props?.sessionId ?? currentSessionId(ctx);
951
987
  if (id === undefined) {
952
988
  setNote('没有选中会话');
953
989
  return;
@@ -1028,13 +1064,7 @@
1028
1064
  };
1029
1065
  let probe;
1030
1066
  try {
1031
- probe = await api.call('delete', {
1032
- sessionIds: [sessionId],
1033
- dryRun: true,
1034
- includeWorkspace: true,
1035
- includeArchived: true,
1036
- includeSubagent: true,
1037
- }, signal);
1067
+ probe = await probeDeletion(api, sessionId, signal);
1038
1068
  }
1039
1069
  catch (error) {
1040
1070
  // 菜单在请求途中被关掉了:静默作废(registry 会丢弃这份结果)。
@@ -1048,9 +1078,8 @@
1048
1078
  },
1049
1079
  ];
1050
1080
  }
1051
- const entry = probe?.results?.[0];
1052
- if (!(probe?.removed > 0)) {
1053
- const why = REASONS_SHORT[entry?.reason] ?? entry?.reason ?? '现在不能删';
1081
+ if (probe?.removable !== true) {
1082
+ const why = REASONS_SHORT[probe?.reason] ?? probe?.reason ?? '现在不能删';
1054
1083
  return [{ ...base, label: `删除会话…(${why})`, disabled: true }];
1055
1084
  }
1056
1085
  return [{ ...base, label: '删除会话…', run }];
@@ -1090,7 +1119,7 @@
1090
1119
  key: 'headerDeleteButton',
1091
1120
  kind: 'boolean',
1092
1121
  label: '标题栏删除图标',
1093
- hint: '在会话标题栏显示垃圾桶图标(默认开启)。它是图标而不是按钮,且删除要在卡片里输入确认词。改完刷新页面生效。',
1122
+ hint: '在会话标题栏显示垃圾桶图标(默认开启)。它是图标而不是按钮,且删除要过一次确认卡片。改完刷新页面生效。',
1094
1123
  },
1095
1124
  {
1096
1125
  key: 'allowLiveSessions',
@@ -117,6 +117,16 @@ export interface RemoveReport {
117
117
  pruned: string[];
118
118
  results: RemoveResult[];
119
119
  }
120
+ /**
121
+ * {@link SessionAdmin.probe} 的结论:一条会话现在能不能删、不能删的理由。
122
+ *
123
+ * `reason` 与 {@link RemoveResult.reason} 同一套取值,客户端直接用同一张文案表。
124
+ */
125
+ export interface ProbeVerdict {
126
+ sessionId: string;
127
+ removable: boolean;
128
+ reason?: string;
129
+ }
120
130
  /** {@link createSessionAdmin} 的选项。 */
121
131
  export interface CreateSessionAdminOptions {
122
132
  /** DSH 主目录(默认 `dshHome()`)。 */
@@ -135,6 +145,7 @@ export interface SessionAdmin {
135
145
  scan(options?: ScanOptions): SessionRecord[];
136
146
  select(records: SessionRecord[], query?: SelectQuery): SessionRecord[];
137
147
  remove(ids: string[], options?: RemoveOptions): Promise<RemoveReport>;
148
+ probe(id: string, options?: RemoveOptions): ProbeVerdict;
138
149
  }
139
150
  /**
140
151
  * 构造一个会话管理员。所有根目录都可注入,便于在测试里指向沙箱。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-session-ops",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"