dsh-session-ops 0.2.7 → 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/README.md CHANGED
@@ -33,8 +33,16 @@ 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 an in-page
37
+ confirmation card, but the operator owns the outcome.
38
+
39
+ The context-menu row resolves through a **single-session probe** (`/session-admin/api/probe`): a
40
+ menu `resolve` gets a 1 s budget (`resolutionTimeoutMs`, and a timed-out provider is dropped), while
41
+ a table-wide dry run measures every session directory (≈3.6 s for 391 sessions here) — so the row
42
+ used to appear only sometimes. The probe skips byte measurement and shares the exact guard chain
43
+ with `delete`; it only decides whether the row is enabled, and `delete` re-checks every guard. The
44
+ confirmation card is drawn in the page (never `window.confirm` / `window.prompt`: Electron throws
45
+ `prompt() is not supported.`), and its delete button stays disabled until 删除 is typed.
38
46
 
39
47
  Safe defaults (configurable): `allowWorkspaceSessions=false`, `allowLiveSessions=false`,
40
48
  `refuseRunning=true` — workspace sessions, live sessions and mid-turn moves are refused by default.
package/README.zh.md CHANGED
@@ -30,6 +30,8 @@ dsh plugin --profile <profile> add dsh-session-ops
30
30
 
31
31
  删除后顺手清理因此变空的项目目录。没有回收站,删了无法恢复;删除前请自行备份 `$DSH_HOME`。面板提供预演与确认卡片(输入「删除」才能继续),但最终责任在操作者。
32
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.`),输入「删除」之前删除按钮一直禁用。
34
+
33
35
  默认安全边界(可在配置里改):`allowWorkspaceSessions=false`、`allowLiveSessions=false`、`refuseRunning=true`。工作区会话、正在跑的会话、运行中的搬迁默认都被拒绝。
34
36
 
35
37
  搬迁不是删除:日志目录从旧 project 目录整体移到新目录,`header.cwd` 改写,工作区成员表跟着变。内核 0.2.2+ 的会话目录里有 `session.lock`,搬迁时会一起搬走(inode 不变);目标目录已有租约时直接拒绝,不会留下「锁在旧目录、日志在新目录」的半套状态。
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
@@ -869,6 +869,21 @@
869
869
  }
870
870
  /** 当前选中的会话 id;拿不到(没有会话服务 / 老外壳)时为 undefined。 */
871
871
  function currentSessionId(ctx) {
872
+ /*
873
+ * 0.2.3 起 `ctx.sessions.list.getSnapshot().current` 没了:`SessionListState` 只剩
874
+ * `ids` / `byId` / `phase` / `projectionsBySession`,当前选中会话搬到
875
+ * `ctx.uiSession.adapter.current`(`StandardSourceBinding`,值里带 sessionId)。
876
+ * 之前只读旧字段,于是标题栏垃圾桶永远报「没有选中会话」。
877
+ */
878
+ try {
879
+ const binding = ctx?.uiSession?.adapter?.current?.getSnapshot?.();
880
+ const id = binding?.sessionId ?? binding?.owner?.sessionId;
881
+ if (typeof id === 'string' && id !== '')
882
+ return id;
883
+ }
884
+ catch {
885
+ /* 换下一个来源 */
886
+ }
872
887
  try {
873
888
  return ctx.sessions.list.getSnapshot().current;
874
889
  }
@@ -883,6 +898,19 @@
883
898
  * 目录重新写日志——那正是「无头日志」的由来,而删除守卫正是为了避免它。
884
899
  */
885
900
  function leaveDeletedSession(ctx) {
901
+ /*
902
+ * 0.2.3 的 `ctx.sessions` 没有 `create()`:新会话入口在 `ctx.uiWorkspace`
903
+ * (`startSession` / `connectWorkspace`)。先试新入口,旧宿主退回 `sessions.create`。
904
+ */
905
+ try {
906
+ if (typeof ctx?.uiWorkspace?.startSession === 'function') {
907
+ ctx.uiWorkspace.startSession();
908
+ return;
909
+ }
910
+ }
911
+ catch {
912
+ /* 退到旧入口 */
913
+ }
886
914
  try {
887
915
  ctx.sessions.create();
888
916
  return;
@@ -897,6 +925,38 @@
897
925
  /* 已经无可挽回,界面刷新失败也不影响数据层 */
898
926
  }
899
927
  }
928
+ /**
929
+ * 单条删除预演:优先 Host 的 `probe`,老宿主退回整表 dryRun。
930
+ *
931
+ * 为什么不是直接 dryRun:`delete` 的 dryRun 要把每个会话目录的体积都走一遍
932
+ * (本机 391 条约 3.6 s),而菜单的 `resolve` 只有 1 s 预算,超时整项被丢弃,
933
+ * 表现就是「删除会话…」在右键菜单里时有时无;确认卡片也要等这 3.6 s 才出现。
934
+ * `probe`(0.2.8 起)只做无体积统计的扫描 + 同一份守卫判定,毫秒级。
935
+ *
936
+ * 老宿主没有这个方法(404 / bad-request),退回 dryRun —— 慢,但判定同样权威,
937
+ * 且这条路径上的失败会照旧抛给调用方。
938
+ *
939
+ * @param api - Host API 客户端。
940
+ * @param sessionId - 目标会话 id。
941
+ * @param signal - 菜单关闭时作废在途请求。
942
+ * @returns `{ removable, reason? }`,与 `delete` 的逐条结果同义。
943
+ */
944
+ async function probeDeletion(api, sessionId, signal = undefined) {
945
+ const scope = { includeWorkspace: true, includeArchived: true, includeSubagent: true };
946
+ try {
947
+ const verdict = await api.call('probe', { sessionId, ...scope }, signal);
948
+ if (typeof verdict?.removable === 'boolean')
949
+ return verdict;
950
+ }
951
+ catch (error) {
952
+ // 被取消(菜单关了)就不再发第二个请求。
953
+ if (signal?.aborted === true)
954
+ throw error;
955
+ }
956
+ const report = await api.call('delete', { sessionIds: [sessionId], dryRun: true, ...scope }, signal);
957
+ const row = report?.results?.[0];
958
+ return { sessionId, removable: report?.removed > 0, reason: row?.reason };
959
+ }
900
960
  /**
901
961
  * 删除一个会话的整条流程:预演 → 输入确认词 → 删除。
902
962
  *
@@ -920,10 +980,10 @@
920
980
  includeArchived: true,
921
981
  includeSubagent: true,
922
982
  };
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 ?? '无法删除' };
983
+ // 预演只判「现在能不能删」;预演不是执行许可,下面那次 delete 会重新过守卫。
984
+ const verdict = await probeDeletion(api, sessionId);
985
+ if (verdict?.removable !== true) {
986
+ return { ok: false, note: REASONS[verdict?.reason] ?? verdict?.reason ?? '无法删除' };
927
987
  }
928
988
  if (!(await confirmDeletion(`永久删除会话 ${sessionId}?`)))
929
989
  return { ok: false };
@@ -943,11 +1003,13 @@
943
1003
  function createHeaderButton(React, ctx, api) {
944
1004
  const h = React.createElement;
945
1005
  const TrashIcon = createTrashIcon(React);
946
- return function SessionAdminHeaderButton() {
1006
+ return function SessionAdminHeaderButton(props) {
947
1007
  const [busy, setBusy] = React.useState(false);
948
1008
  const [note, setNote] = React.useState(undefined);
949
1009
  async function onClick() {
950
- const id = currentSessionId(ctx);
1010
+ // 标题栏这一格由外壳按会话挂载,`sessionId` 是外壳给的标准 props(最权威);
1011
+ // 老外壳没有这个 prop 时才回落到「当前选中会话」的查询。
1012
+ const id = props?.sessionId ?? currentSessionId(ctx);
951
1013
  if (id === undefined) {
952
1014
  setNote('没有选中会话');
953
1015
  return;
@@ -1028,13 +1090,7 @@
1028
1090
  };
1029
1091
  let probe;
1030
1092
  try {
1031
- probe = await api.call('delete', {
1032
- sessionIds: [sessionId],
1033
- dryRun: true,
1034
- includeWorkspace: true,
1035
- includeArchived: true,
1036
- includeSubagent: true,
1037
- }, signal);
1093
+ probe = await probeDeletion(api, sessionId, signal);
1038
1094
  }
1039
1095
  catch (error) {
1040
1096
  // 菜单在请求途中被关掉了:静默作废(registry 会丢弃这份结果)。
@@ -1048,9 +1104,8 @@
1048
1104
  },
1049
1105
  ];
1050
1106
  }
1051
- const entry = probe?.results?.[0];
1052
- if (!(probe?.removed > 0)) {
1053
- const why = REASONS_SHORT[entry?.reason] ?? entry?.reason ?? '现在不能删';
1107
+ if (probe?.removable !== true) {
1108
+ const why = REASONS_SHORT[probe?.reason] ?? probe?.reason ?? '现在不能删';
1054
1109
  return [{ ...base, label: `删除会话…(${why})`, disabled: true }];
1055
1110
  }
1056
1111
  return [{ ...base, label: '删除会话…', run }];
@@ -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.8",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"