dsh-recycle-center 0.4.0

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/index.js ADDED
@@ -0,0 +1,1861 @@
1
+ /**
2
+ * dsh-recyclebin —— 宿主半。
3
+ *
4
+ * 三件事,对应三条规则:
5
+ *
6
+ * 1. 删除:把一个**不在运行中**的会话,连同它的索引文件,一起移进 Windows 回收站。
7
+ * · 会话目录 <DSH_HOME>/sessions/<项目>/<会话 id>/
8
+ * · 索引文件 <DSH_HOME>/storages/session_projcache/sessions/<会话 id>.json
9
+ * 搬之前先从工作区名单里摘掉(走 DSH 自己的 workspaceRegistry),
10
+ * 并把「原来在第几个位置」记下来,恢复时放回原位。
11
+ *
12
+ * 2. 7 天内可恢复:每条删除记录写成一个独立文件
13
+ * <DSH_HOME>/recyclebin/records/<会话 id>.json
14
+ * 恢复 = 把上面两样从回收站取回来 + 挂回原来的工作区原位。
15
+ *
16
+ * 3. 7 天后不可恢复:这条记录文件本身也被移进回收站。
17
+ * 于是它从「可恢复清单」里消失,会话再也没法通过本插件还原。
18
+ *
19
+ * 明确不做的事(写在这里,是为了让读代码的人能核实边界,而不是靠信任):
20
+ * · 不复制、不留档、不压缩备份 —— 数据只有一份,去向只有回收站;
21
+ * · 不读也不写 workspace.json 等 DSH 核心存储文件;
22
+ * · 不解析、不改写对话正文;
23
+ * · 不碰会话上传的附件对象(它们按内容寻址全局共享,属于别的机制的领域);
24
+ * · 绝不清空回收站,也绝不移动回收站里已有的任何条目;
25
+ * · 回收站装不下时一律拒绝,绝不退化成永久删除。
26
+ */
27
+
28
+ import { existsSync, promises as fsp } from 'node:fs'
29
+ import { homedir } from 'node:os'
30
+ import { basename, dirname, join } from 'node:path'
31
+ import { callBin } from './lib/bin.js'
32
+ import { attachmentIdsOfEvents, normalizeAttachmentId, parseLogEvents, readLogFile } from './lib/logtext.js'
33
+ import { isSafeSessionId, isInside } from './lib/safety.js'
34
+
35
+ export const name = 'dsh-recyclebin'
36
+
37
+ /** 只要 Web 服务器;其余服务用 ctx.get 取,取不到就明确拒绝而不是猜。 */
38
+ export const inject = ['webServer']
39
+
40
+ const ROUTE = '/dsh-recyclebin'
41
+ const RETENTION_DAYS = 7
42
+ const RETENTION_MS = RETENTION_DAYS * 24 * 60 * 60 * 1000
43
+ const SWEEP_INTERVAL_MS = 30 * 60 * 1000
44
+ const MAX_BODY_BYTES = 64 * 1024
45
+ const RECORD_VERSION = 1
46
+
47
+ /** 检查附件归属时最多扫多少个会话,超过就判定「算不清」并拒绝删除。 */
48
+ const MAX_SCAN_SESSIONS = 300
49
+
50
+ /** 附件盘点一次最多回给页面多少条(超出只报总数)。 */
51
+ const MAX_REPORTED_ATTACHMENTS = 500
52
+
53
+ /* ── 路径 ─────────────────────────────────────────────────────────────── */
54
+
55
+ /**
56
+ * 解析出来的 DSH 数据目录。启动时由 {@link probeHome} 填一次。
57
+ * 还没解析出来时退回同步的默认值,所以任何时候调用都不会返回空。
58
+ * @type {string | null}
59
+ */
60
+ let resolvedHome = null
61
+
62
+ /**
63
+ * 同步能拿到的显式设置:`$DSH_HOME`。没设就是空串。
64
+ * @returns {string}
65
+ */
66
+ function envHome() {
67
+ return typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : ''
68
+ }
69
+
70
+ /**
71
+ * 从候选里挑一个真的像 DSH 数据目录的:里面有 `sessions/`。
72
+ * 一个都没有就退回第一个,保持和旧行为一致。
73
+ * @param {string[]} list
74
+ * @returns {string}
75
+ */
76
+ function pickHome(list) {
77
+ for (const candidate of list) {
78
+ if (existsSync(join(candidate, 'sessions'))) return candidate
79
+ }
80
+ return list[0]
81
+ }
82
+
83
+ /**
84
+ * 启动时解析一次数据目录。
85
+ *
86
+ * 优先级:
87
+ * 1. `$DSH_HOME` 显式设置 → 直接信,不再检查目录结构
88
+ * (新建的空 home 本来就没有 sessions/,不能因此判它无效)
89
+ * 2. 否则问一下宿主的 `@deepseek-ai/dsh-home-paths`——它支持「显式配置」
90
+ * 这一级优先级,比环境变量更全
91
+ * 3. 再否则退回 `~/.dsh`
92
+ *
93
+ * 第 2、3 步之间用「谁真的有 sessions/」来裁决,避免解析出一个空目录。
94
+ * 整个函数失败不影响运行:`dshHome()` 会继续用同步兜底。
95
+ *
96
+ * @param {any} [logger]
97
+ * @returns {Promise<string>}
98
+ */
99
+ async function probeHome(logger) {
100
+ const explicit = envHome()
101
+ if (explicit !== '') {
102
+ resolvedHome = explicit
103
+ try { logger?.info?.(`dsh-recyclebin: home = ${resolvedHome}(来自 DSH_HOME)`) } catch { /* ignore */ }
104
+ return resolvedHome
105
+ }
106
+
107
+ const candidates = []
108
+ try {
109
+ const library = await import('@deepseek-ai/dsh-home-paths')
110
+ if (library && typeof library.resolveDshHome === 'function') {
111
+ const value = library.resolveDshHome()
112
+ if (typeof value === 'string' && value.trim() !== '') candidates.push(value.trim())
113
+ }
114
+ } catch {
115
+ // 插件通常解析不到宿主包,这里失败是常态,不是错误。
116
+ }
117
+ candidates.push(join(homedir(), '.dsh'))
118
+
119
+ resolvedHome = pickHome([...new Set(candidates)])
120
+ try { logger?.info?.(`dsh-recyclebin: home = ${resolvedHome}`) } catch { /* ignore */ }
121
+ return resolvedHome
122
+ }
123
+
124
+ /**
125
+ * DSH 数据目录。启动解析完成前用同步兜底,任何时刻都不会返回空。
126
+ * @returns {string}
127
+ */
128
+ function dshHome() {
129
+ return resolvedHome ?? (envHome() || join(homedir(), '.dsh'))
130
+ }
131
+
132
+ /** 会话存储根。 */
133
+ function sessionsRoot() {
134
+ return join(dshHome(), 'sessions')
135
+ }
136
+
137
+ /** 会话的索引文件(投影缓存),删除时要一起进回收站。 */
138
+ function projCacheFile(sid) {
139
+ return join(dshHome(), 'storages', 'session_projcache', 'sessions', sid + '.json')
140
+ }
141
+
142
+ /**
143
+ * 本插件自己的记录目录。
144
+ *
145
+ * 0.3.0 之前叫 `session-bin`,改名时会把旧目录**移动**成 `recyclebin`
146
+ * (见 migrateLegacyState)。移动失败时继续用旧目录 —— 宁愿名字不一致,
147
+ * 也不能让已有的删除记录凭空消失、恢复入口失效。
148
+ *
149
+ * @returns {string}
150
+ */
151
+ function stateRoot() {
152
+ const next = join(dshHome(), 'recyclebin')
153
+ if (existsSync(next)) return next
154
+ const prev = join(dshHome(), 'session-bin')
155
+ if (existsSync(prev)) return prev
156
+ return next
157
+ }
158
+
159
+ /** 7 天内的记录,每条一个文件。 */
160
+ function recordsDir() {
161
+ return join(stateRoot(), 'records')
162
+ }
163
+
164
+ /**
165
+ * 把旧名字的数据目录移过来:`<DSH_HOME>/session-bin` → `<DSH_HOME>/recyclebin`。
166
+ *
167
+ * 只做一次目录移动(rename),不复制、不删除任何记录。移动失败时
168
+ * `stateRoot()` 会继续用旧目录,界面照样能看到历史记录 —— 名字不一致
169
+ * 也比「恢复入口凭空消失」好。
170
+ *
171
+ * @param {any} [logger]
172
+ * @returns {Promise<void>}
173
+ */
174
+ async function migrateLegacyState(logger) {
175
+ try {
176
+ const next = join(dshHome(), 'recyclebin')
177
+ const prev = join(dshHome(), 'session-bin')
178
+ if (existsSync(next) || !existsSync(prev)) return
179
+ await fsp.rename(prev, next)
180
+ try {
181
+ logger?.info?.('dsh-recyclebin: 数据目录已从 session-bin 迁移到 recyclebin')
182
+ } catch {
183
+ // 日志失败不影响迁移结果
184
+ }
185
+ } catch (error) {
186
+ try {
187
+ logger?.warn?.('dsh-recyclebin: 数据目录迁移失败,继续使用旧目录:' + String((error && error.message) || error))
188
+ } catch {
189
+ // ignore
190
+ }
191
+ }
192
+ }
193
+
194
+ /** 已经恢复过的记录留在这里(本地归档,不进回收站)。 */
195
+ function restoredDir() {
196
+ return join(stateRoot(), 'restored')
197
+ }
198
+
199
+ /**
200
+ * 某条记录的文件路径。
201
+ * @param {string} sid
202
+ * @returns {string}
203
+ */
204
+ function recordPath(sid) {
205
+ return join(recordsDir(), sid + '.json')
206
+ }
207
+
208
+ /* ── 记录读写 ─────────────────────────────────────────────────────────── */
209
+
210
+ /**
211
+ * @typedef {object} Record
212
+ * @property {string} sid
213
+ * @property {string} title 删除时的显示名,恢复列表里显示它
214
+ * @property {string} dir 会话目录(绝对路径)
215
+ * @property {string[]} movedFiles 实际被移进回收站的全部路径
216
+ * @property {string|null} workspaceId 原来所属的工作区
217
+ * @property {string|null} beforeSid 原来紧跟在它后面的那个会话,null 表示它原本是最后一个
218
+ * @property {number} deletedAt
219
+ * @property {number} expiresAt
220
+ * @property {number} attempts
221
+ */
222
+
223
+ /**
224
+ * 读一条记录;不存在或损坏返回 null。
225
+ * @param {string} sid
226
+ * @returns {Promise<Record | null>}
227
+ */
228
+ async function readRecord(sid) {
229
+ if (!isSafeSessionId(sid)) return null
230
+ try {
231
+ const raw = await fsp.readFile(recordPath(sid), 'utf8')
232
+ const parsed = JSON.parse(raw)
233
+ if (!parsed || parsed.sid !== sid || typeof parsed.dir !== 'string') return null
234
+ return normalizeRecord(parsed)
235
+ } catch {
236
+ return null
237
+ }
238
+ }
239
+
240
+ /**
241
+ * 把外部读到的对象收敛成可信形状。
242
+ * @param {any} raw
243
+ * @returns {Record}
244
+ */
245
+ function normalizeRecord(raw) {
246
+ return {
247
+ version: RECORD_VERSION,
248
+ sid: String(raw.sid),
249
+ title: typeof raw.title === 'string' ? raw.title.slice(0, 200) : String(raw.sid),
250
+ dir: String(raw.dir),
251
+ movedFiles: Array.isArray(raw.movedFiles) ? raw.movedFiles.filter((p) => typeof p === 'string') : [],
252
+ workspaceId: typeof raw.workspaceId === 'string' ? raw.workspaceId : null,
253
+ beforeSid: typeof raw.beforeSid === 'string' ? raw.beforeSid : null,
254
+ deletedAt: Number(raw.deletedAt) || 0,
255
+ expiresAt: Number(raw.expiresAt) || 0,
256
+ attempts: Number(raw.attempts) || 0,
257
+ attachments: normalizeRecordAttachments(raw.attachments),
258
+ }
259
+ }
260
+
261
+ /**
262
+ * 记录里的附件审计块。旧记录没有这一块,返回 null 表示「未记录」。
263
+ * @param {any} raw
264
+ * @returns {{ referenced: number, movedIds: string[], movedArtifacts: number, keptShared: Array<{ id: string, sessions: string[], match: string }> } | null}
265
+ */
266
+ function normalizeRecordAttachments(raw) {
267
+ if (raw === null || typeof raw !== 'object') return null
268
+ const kept = Array.isArray(raw.keptShared) ? raw.keptShared : []
269
+ return {
270
+ referenced: Number(raw.referenced) || 0,
271
+ movedIds: Array.isArray(raw.movedIds) ? raw.movedIds.filter((id) => typeof id === 'string') : [],
272
+ movedArtifacts: Number(raw.movedArtifacts) || 0,
273
+ keptShared: kept
274
+ .filter((row) => row !== null && typeof row === 'object' && typeof row.id === 'string')
275
+ .map((row) => ({
276
+ id: String(row.id),
277
+ sessions: Array.isArray(row.sessions) ? row.sessions.filter((s) => typeof s === 'string') : [],
278
+ match: typeof row.match === 'string' ? row.match : 'unknown',
279
+ })),
280
+ }
281
+ }
282
+
283
+ /**
284
+ * 列出全部记录(目录里有什么就是什么,没有中心索引需要维护)。
285
+ * @returns {Promise<Record[]>}
286
+ */
287
+ async function listRecords() {
288
+ let names
289
+ try {
290
+ names = await fsp.readdir(recordsDir())
291
+ } catch {
292
+ return []
293
+ }
294
+ const rows = []
295
+ for (const name of names) {
296
+ if (!name.endsWith('.json')) continue
297
+ const record = await readRecord(name.slice(0, -5))
298
+ if (record) rows.push(record)
299
+ }
300
+ return rows
301
+ }
302
+
303
+ /**
304
+ * 原子地写一条记录。
305
+ * @param {Record} record
306
+ */
307
+ async function writeRecord(record) {
308
+ await fsp.mkdir(recordsDir(), { recursive: true })
309
+ const target = recordPath(record.sid)
310
+ const tmp = target + '.tmp-' + process.pid
311
+ await fsp.writeFile(tmp, JSON.stringify(record, null, 2) + '\n', 'utf8')
312
+ await fsp.rename(tmp, target)
313
+ }
314
+
315
+ /**
316
+ * 把一条记录从「待恢复」挪到「已恢复」。这是本地移动,不进回收站。
317
+ * @param {Record} record
318
+ */
319
+ async function archiveRecord(record) {
320
+ await fsp.mkdir(restoredDir(), { recursive: true })
321
+ const source = recordPath(record.sid)
322
+ const target = join(restoredDir(), record.sid + '.json')
323
+ try {
324
+ await fsp.rename(source, target)
325
+ } catch {
326
+ // 挪不动就退而求其次:把记录改成已恢复标记,不再出现在列表里
327
+ await fsp.writeFile(target, JSON.stringify({ ...record, restoredAt: Date.now() }, null, 2) + '\n', 'utf8').catch(() => {})
328
+ }
329
+ }
330
+
331
+ /* ── 串行化 ───────────────────────────────────────────────────────────── */
332
+
333
+ /**
334
+ * 会改数据(移动文件、写记录)的操作排成一条队列,同一时刻只跑一个。
335
+ * 防的是连点:两个并发删除会把回收站和记录写成互相矛盾的状态。
336
+ */
337
+ let mutationChain = Promise.resolve()
338
+
339
+ /**
340
+ * @template T
341
+ * @param {() => Promise<T>} task
342
+ * @returns {Promise<T>}
343
+ */
344
+ function withMutationLock(task) {
345
+ const run = mutationChain.then(task, task)
346
+ mutationChain = run.then(() => undefined, () => undefined)
347
+ return run
348
+ }
349
+
350
+ /* ── 会话目录 ─────────────────────────────────────────────────────────── */
351
+
352
+ /**
353
+ * 路径是不是一个「真正的」目录或文件,而不是链接。
354
+ *
355
+ * Windows 的目录联接(Junction)和符号链接在 `lstat` 里表现为
356
+ * `isSymbolicLink() === true`、`isDirectory() === false`。如果用 `stat`
357
+ * (会跟随链接),一个塞进 sessions 目录的 Junction 就会被当成普通会话目录,
358
+ * 删除时顺着链接把别处的文件搬走。所以这里统一用 `lstat`,链接一律拒绝。
359
+ *
360
+ * @param {string} path
361
+ * @param {'dir'|'file'} kind
362
+ * @returns {Promise<boolean>}
363
+ */
364
+ async function isRealEntry(path, kind) {
365
+ try {
366
+ const st = await fsp.lstat(path)
367
+ if (st.isSymbolicLink()) return false
368
+ return kind === 'dir' ? st.isDirectory() : st.isFile()
369
+ } catch {
370
+ return false
371
+ }
372
+ }
373
+
374
+ /**
375
+ * 找出这个会话 id 对应的存储目录。
376
+ * 结构是 <DSH_HOME>/sessions/<一级项目目录>/<会话 id>/,只按目录名精确匹配,
377
+ * 不把任何请求里的字符串拼进路径。
378
+ * 链接(Junction / 符号链接)不算会话目录,直接跳过。
379
+ * @param {string} sid
380
+ * @returns {Promise<string[]>}
381
+ */
382
+ async function findSessionDirs(sid) {
383
+ if (!isSafeSessionId(sid)) return []
384
+ const root = sessionsRoot()
385
+ let projects
386
+ try {
387
+ projects = await fsp.readdir(root, { withFileTypes: true })
388
+ } catch {
389
+ return []
390
+ }
391
+ const hits = []
392
+ for (const project of projects) {
393
+ if (!project.isDirectory()) continue
394
+ const candidate = join(root, project.name, sid)
395
+ if (!isInside(root, candidate)) continue
396
+ if (await isRealEntry(candidate, 'dir')) hits.push(candidate)
397
+ }
398
+ return hits
399
+ }
400
+
401
+ /* ── 附件 ─────────────────────────────────────────────────────────────── */
402
+
403
+ /**
404
+ * 会话目录里的日志文件名。DSH 用 `session.v<N>.jsonl.zstd`。
405
+ *
406
+ * 同一目录里理论上可能出现多代日志(迁移 / 回滚)。`readdir` 的顺序不保证,
407
+ * 所以这里显式挑**版本号最大**的那个,而不是拿第一个。
408
+ * @param {string} dir 会话目录
409
+ * @returns {Promise<string | null>}
410
+ */
411
+ async function logFileIn(dir) {
412
+ try {
413
+ const rows = await fsp.readdir(dir)
414
+ let best = null
415
+ let bestVersion = -1
416
+ for (const row of rows) {
417
+ const match = /^session\.v(\d+)\.jsonl\.zstd$/.exec(row)
418
+ if (match === null) continue
419
+ const version = Number(match[1])
420
+ if (version > bestVersion) {
421
+ bestVersion = version
422
+ best = row
423
+ }
424
+ }
425
+ return best === null ? null : join(dir, best)
426
+ } catch {
427
+ return null
428
+ }
429
+ }
430
+
431
+ /**
432
+ * 一个附件摘要在磁盘上可能对应的全部产物。
433
+ *
434
+ * DSH 的附件是内容寻址的,同一个摘要可能出现在三处:
435
+ * · objects/<前两位>/<摘要> 图片对象
436
+ * · file-objects/<前两位>/<摘要> 通用文件字节
437
+ * · files/<前两位>/<摘要>/ 按文件名建立的只读硬链接目录
438
+ * 只返回实际存在的那些。
439
+ *
440
+ * @param {string} sha 附件摘要(64 位小写十六进制)
441
+ * @returns {Promise<string[]>}
442
+ */
443
+ async function attachmentArtifacts(sha) {
444
+ const digest = normalizeAttachmentId(sha)
445
+ if (digest === null) return []
446
+ const base = join(dshHome(), 'attachments', 'v1')
447
+ const prefix = digest.slice(0, 2)
448
+ const candidates = [
449
+ join(base, 'objects', prefix, digest),
450
+ join(base, 'file-objects', prefix, digest),
451
+ join(base, 'files', prefix, digest),
452
+ ]
453
+ const found = []
454
+ for (const path of candidates) {
455
+ // 同样是 lstat:只认真正的文件/目录,链接一律跳过。
456
+ try {
457
+ const st = await fsp.lstat(path)
458
+ if (!st.isSymbolicLink() && (st.isFile() || st.isDirectory())) found.push(path)
459
+ } catch {
460
+ // 不存在就跳过
461
+ }
462
+ }
463
+ return found
464
+ }
465
+
466
+ /**
467
+ * 会话日志解析结果的缓存。
468
+ *
469
+ * 键是日志绝对路径,值是「上次解析时的 mtime/size + 摘要集合」。
470
+ * 删除流程要扫全部会话,而大多数会话的日志在两次删除之间根本不变,
471
+ * 缓存能把重复解析的代价摊掉。mtime 或 size 一变就重新解析。
472
+ * @type {Map<string, { mtimeMs: number, size: number, ids: string[], ok: boolean, reason?: string }>}
473
+ */
474
+ const attachmentScanCache = new Map()
475
+
476
+ /**
477
+ * 读一个会话的日志,列出它**结构化引用**的附件摘要。
478
+ *
479
+ * 判定只看内容块(`type: 'image' | 'file'` + `attachment.attachmentId`),
480
+ * 不看自由文本 —— 工具输出里打印的 JSON 或路径不会再被当成引用。
481
+ *
482
+ * @param {string} dir 会话目录
483
+ * @returns {Promise<{ ok: boolean, ids: string[], reason?: string }>}
484
+ */
485
+ async function attachmentsOf(dir) {
486
+ const logPath = await logFileIn(dir)
487
+ if (!logPath) return { ok: true, ids: [] }
488
+
489
+ let stat
490
+ try {
491
+ stat = await fsp.stat(logPath)
492
+ } catch {
493
+ return { ok: false, ids: [], reason: '会话日志读不出来(可能过大或无法解析)' }
494
+ }
495
+
496
+ const cached = attachmentScanCache.get(logPath)
497
+ if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
498
+ return cached.ok ? { ok: true, ids: cached.ids } : { ok: false, ids: [], reason: cached.reason }
499
+ }
500
+
501
+ const log = await readLogFile(logPath)
502
+ if (!log) {
503
+ const reason = '会话日志读不出来(可能过大或无法解析)'
504
+ attachmentScanCache.set(logPath, { mtimeMs: stat.mtimeMs, size: stat.size, ids: [], ok: false, reason })
505
+ return { ok: false, ids: [], reason }
506
+ }
507
+ if (!log.complete) {
508
+ const reason = '会话日志有帧解压失败,读不完整'
509
+ attachmentScanCache.set(logPath, { mtimeMs: stat.mtimeMs, size: stat.size, ids: [], ok: false, reason })
510
+ return { ok: false, ids: [], reason }
511
+ }
512
+
513
+ const scanned = attachmentIdsOfEvents(parseLogEvents(log.text))
514
+ if (scanned.truncated) {
515
+ const reason = '会话日志里存在异常巨大的事件,无法完整扫描附件引用'
516
+ attachmentScanCache.set(logPath, { mtimeMs: stat.mtimeMs, size: stat.size, ids: [], ok: false, reason })
517
+ return { ok: false, ids: [], reason }
518
+ }
519
+
520
+ const ids = [...scanned.ids]
521
+ attachmentScanCache.set(logPath, { mtimeMs: stat.mtimeMs, size: stat.size, ids, ok: true })
522
+ return { ok: true, ids }
523
+ }
524
+
525
+ /**
526
+ * 让缓存丢掉某个目录的条目(删除 / 恢复后调用,避免读到旧结论)。
527
+ * @param {string} dir
528
+ */
529
+ function forgetAttachmentScan(dir) {
530
+ for (const key of [...attachmentScanCache.keys()]) {
531
+ if (key.startsWith(dir)) attachmentScanCache.delete(key)
532
+ }
533
+ }
534
+
535
+ /**
536
+ * 判断给定附件摘要里,哪些**还被别的会话引用**。
537
+ *
538
+ * 附件是内容寻址、全局去重的,一个摘要可能同时属于好几段对话。
539
+ * 只有确认没有任何别的会话**结构化引用**它,才敢跟着本次删除一起搬走。
540
+ *
541
+ * 保守原则:只要有一个会话的日志读不完整,就返回 null,
542
+ * 调用方据此拒绝删除 —— 算不清归属就不动手,免得把别人的附件带走。
543
+ *
544
+ * @param {string} sid 正在删除的会话
545
+ * @param {string[]} ids 候选摘要
546
+ * @returns {Promise<Map<string, string[]> | null>} id → 引用它的会话 id;null 表示扫描不可信
547
+ */
548
+ async function sharedAttachmentIds(sid, ids) {
549
+ const shared = new Map()
550
+ if (ids.length === 0) return shared
551
+
552
+ const root = sessionsRoot()
553
+ let projects
554
+ try {
555
+ projects = await fsp.readdir(root, { withFileTypes: true })
556
+ } catch {
557
+ return null
558
+ }
559
+
560
+ const pending = new Set(ids)
561
+ let scanned = 0
562
+
563
+ for (const project of projects) {
564
+ if (!project.isDirectory()) continue
565
+ let sessions
566
+ try {
567
+ sessions = await fsp.readdir(join(root, project.name), { withFileTypes: true })
568
+ } catch {
569
+ continue
570
+ }
571
+ for (const session of sessions) {
572
+ if (!session.isDirectory() || session.name === sid) continue
573
+ scanned += 1
574
+ if (scanned > MAX_SCAN_SESSIONS) return null
575
+
576
+ const dir = join(root, project.name, session.name)
577
+ const scan = await attachmentsOf(dir)
578
+ if (!scan.ok) return null
579
+
580
+ for (const id of [...pending]) {
581
+ if (!scan.ids.includes(id)) continue
582
+ const owners = shared.get(id)
583
+ if (owners === undefined) shared.set(id, [session.name])
584
+ else owners.push(session.name)
585
+ pending.delete(id)
586
+ }
587
+ if (pending.size === 0) return shared
588
+ }
589
+ }
590
+ return shared
591
+ }
592
+
593
+ /* ── 工作区与运行状态 ─────────────────────────────────────────────────── */
594
+
595
+ /**
596
+ * @param {any} ctx
597
+ * @returns {any}
598
+ */
599
+ function registryOf(ctx) {
600
+ try {
601
+ return ctx.get('workspaceRegistry')
602
+ } catch {
603
+ return undefined
604
+ }
605
+ }
606
+
607
+ /**
608
+ * 会话现在挂在哪个工作区。
609
+ * @param {any} ctx
610
+ * @param {string} sid
611
+ * @returns {any} 工作区实体,找不到返回 undefined
612
+ */
613
+ function workspaceOf(ctx, sid) {
614
+ const registry = registryOf(ctx)
615
+ if (!registry || typeof registry.list !== 'function') return undefined
616
+ try {
617
+ return registry.list().find((ws) => Array.isArray(ws.sessionIds) && ws.sessionIds.includes(sid))
618
+ } catch {
619
+ return undefined
620
+ }
621
+ }
622
+
623
+ /**
624
+ * 会话的两个状态,必须分开看:
625
+ *
626
+ * open —— 内存里有没有它的句柄,也就是说它**开着**(标签页/面板里挂着)。
627
+ * 开着不等于在干活:一个闲置的标签页也会让这里为真。
628
+ * active —— 宿主有没有登记进行中的工作(跑回合、工具调用、后台任务)。
629
+ * 这是 DSH 自己归档会话时用的那套判据(`workspace/session-activity`)。
630
+ *
631
+ * 只有 active 才阻止删除。只是开着的话允许删除,但要在界面上说清楚
632
+ * 「那个标签页会失效」,而不是拿「正在运行」糊弄用户。
633
+ *
634
+ * @param {any} ctx
635
+ * @param {string} sid
636
+ * @returns {Promise<{ open: boolean, active: boolean, work: string[] }>}
637
+ */
638
+ async function liveness(ctx, sid) {
639
+ let open = false
640
+ try {
641
+ const sessions = ctx.get('sessions')
642
+ if (sessions && typeof sessions.get === 'function') open = sessions.get(sid) !== undefined
643
+ } catch {
644
+ // 取不到就当没开
645
+ }
646
+
647
+ let active = false
648
+ let work = []
649
+ try {
650
+ if (typeof ctx.waterfall === 'function') {
651
+ const rows = await ctx.waterfall('workspace/session-activity', { sessionId: sid }, () => Promise.resolve([]))
652
+ if (Array.isArray(rows) && rows.length > 0) {
653
+ active = true
654
+ work = rows.map((row) => String((row && (row.kind || row.label || row.name)) || '任务')).slice(0, 5)
655
+ }
656
+ }
657
+ } catch {
658
+ // 事件没有提供方是正常情况
659
+ }
660
+
661
+ return { open, active, work }
662
+ }
663
+
664
+ /**
665
+ * 把一个会话从宿主内存里释放掉。
666
+ *
667
+ * 为什么需要它:删除一个「还开着」的会话时,我们只摘了工作区名单、搬走了文件,
668
+ * 但宿主进程里那个会话实例还在。页面拿到的会话列表仍然包含它,
669
+ * 它又不属于任何工作区,于是被侧栏归到「未分组」里,看起来像是删除失败。
670
+ *
671
+ * DSH 的 `SessionStore` 给每个 `enter()` 进去的会话配了一个 detach 释放器:
672
+ * 调用它会把会话从 store 里删掉,并在 announced 之后广播 `session/disposed`,
673
+ * 上层再据此发出 `api-session/removed` —— 页面那一行就没了。
674
+ *
675
+ * 这是尽力而为:释放器由别的代码持有,调用它属于「替持有者松手」。
676
+ * 会话的文件其实已经删了,这个实例本来也干不了活,所以风险可控;
677
+ * 但任何一步不成立都只是返回「没释放」,绝不抛错影响删除结果。
678
+ *
679
+ * @param {any} ctx
680
+ * @param {string} sid
681
+ * @returns {{ released: boolean, reason: string, error?: string }}
682
+ */
683
+ function releaseLiveSession(ctx, sid) {
684
+ if (!isSafeSessionId(sid)) return { released: false, reason: 'BAD_ID' }
685
+
686
+ let sessions
687
+ try {
688
+ sessions = ctx.get('sessions')
689
+ } catch {
690
+ sessions = undefined
691
+ }
692
+ if (!sessions || typeof sessions.get !== 'function') return { released: false, reason: 'NO_SERVICE' }
693
+
694
+ let session
695
+ try {
696
+ session = sessions.get(sid)
697
+ } catch {
698
+ session = undefined
699
+ }
700
+ if (session === undefined) return { released: false, reason: 'NOT_LIVE' }
701
+
702
+ try {
703
+ const entry = typeof sessions.liveEntryFor === 'function' ? sessions.liveEntryFor(session) : undefined
704
+ if (entry !== undefined && entry !== null && typeof entry.detach === 'function') {
705
+ entry.detach()
706
+ return { released: true, reason: 'DETACHED' }
707
+ }
708
+ return { released: false, reason: 'NO_ENTRY' }
709
+ } catch (error) {
710
+ return { released: false, reason: 'DETACH_FAILED', error: String((error && error.message) || error) }
711
+ }
712
+ }
713
+
714
+ /* ── 删除前分析 ───────────────────────────────────────────────────────── */
715
+
716
+ /**
717
+ * 看一遍这个会话能不能安全地进回收站,并算出要搬哪些路径。
718
+ * @param {any} ctx
719
+ * @param {string} sid
720
+ * @returns {Promise<Record<string, any>>}
721
+ */
722
+ async function analyze(ctx, sid) {
723
+ if (!isSafeSessionId(sid)) return { ok: false, code: 'BAD_ID', error: '会话 id 不合法' }
724
+
725
+ const dirs = await findSessionDirs(sid)
726
+ if (dirs.length === 0) return { ok: false, code: 'NOT_FOUND', error: '找不到这个会话的本地目录(可能已经不在本地了)' }
727
+ if (dirs.length > 1) {
728
+ return { ok: false, code: 'AMBIGUOUS', error: '这个会话 id 对应多个目录,我不替你猜要删哪一个:' + dirs.join(' , ') }
729
+ }
730
+
731
+ const dir = dirs[0]
732
+ const live = await liveness(ctx, sid)
733
+ const probe = await callBin('probe', { path: dir })
734
+ const ws = workspaceOf(ctx, sid)
735
+ const cache = projCacheFile(sid)
736
+ const cacheExists = existsSync(cache)
737
+ const attachments = await attachmentsOf(dir)
738
+
739
+ // 共享判定提前到这里做:确认对话框里就能给出准确数字,而不是「最多 N 个」。
740
+ // 扫描结果有缓存,removeSession 再算一次几乎不花时间。
741
+ let shared = null
742
+ let sharedFailed = null
743
+ if (attachments.ok && attachments.ids.length > 0) {
744
+ shared = await sharedAttachmentIds(sid, attachments.ids)
745
+ if (shared === null) sharedFailed = '无法完成附件归属扫描(有会话日志读不完整)'
746
+ }
747
+
748
+ const sharedCount = shared === null ? 0 : shared.size
749
+ const exclusiveIds = shared === null ? [] : attachments.ids.filter((id) => !shared.has(id))
750
+ const keptDetails = shared === null
751
+ ? []
752
+ : [...shared.entries()].map(([id, sessions]) => ({ id, sessions, match: 'content-block' }))
753
+
754
+ // 要搬走的总量 = 会话目录 + 索引文件(附件在删除那一刻再逐项确认归属后加入)
755
+ const totalBytes = (probe.bytes || 0) + (cacheExists ? (await sizeOf(cache)) : 0)
756
+
757
+ const attachmentText = attachments.ids.length === 0
758
+ ? ''
759
+ : sharedCount === 0
760
+ ? '和它的 ' + attachments.ids.length + ' 个附件'
761
+ : '和它独占的 ' + exclusiveIds.length + ' 个附件(另有 ' + sharedCount + ' 个仍被其他会话引用,会保留)'
762
+
763
+ let verdict = { tone: 'ok', text: '可以删除:会话目录、索引文件' + attachmentText + '会一起移进 Windows 回收站,7 天内能恢复。' }
764
+ if (live.active) verdict = { tone: 'bad', text: '这个会话正在执行任务(' + live.work.join('、') + '),不能删除。等它停下来再试。' }
765
+ else if (!attachments.ok) verdict = { tone: 'bad', text: '读不全会话日志(' + (attachments.reason || '未知原因') + '),无法确认它引用了哪些附件,已拒绝。' }
766
+ else if (sharedFailed !== null) verdict = { tone: 'bad', text: sharedFailed + ',为避免误删别人的附件已拒绝。' }
767
+ else if (!probe.ok) verdict = { tone: 'bad', text: '读不到回收站信息,无法确认能安全放入:' + (probe.error || probe.code || '未知原因') }
768
+ else if (probe.nukeOnDelete === 1) verdict = { tone: 'bad', text: '这台机器上该磁盘的回收站被关闭了(NukeOnDelete=1),删除会直接永久删除,已拒绝。' }
769
+ else if (!probe.quotaKnown || !(probe.capacityMB > 0)) verdict = { tone: 'bad', text: '查不到该磁盘的回收站容量,无法保证放进回收站,已拒绝。' }
770
+ else if (totalBytes > probe.capacityMB * 1024 * 1024) {
771
+ verdict = { tone: 'bad', text: '这个会话连索引共 ' + mb(totalBytes) + ',超过回收站容量 ' + probe.capacityMB + ' MB,放不进去,已拒绝。' }
772
+ }
773
+
774
+ const ids = ws && Array.isArray(ws.sessionIds) ? ws.sessionIds : []
775
+ const at = ids.indexOf(sid)
776
+
777
+ return {
778
+ ok: true,
779
+ sessionId: sid,
780
+ dir,
781
+ cache,
782
+ cacheExists,
783
+ bytes: totalBytes,
784
+ volume: probe.volume || '',
785
+ capacityMB: probe.capacityMB || 0,
786
+ running: live.active,
787
+ open: live.open,
788
+ work: live.work,
789
+ deletable: verdict.tone === 'ok',
790
+ verdict,
791
+ workspaceId: ws ? ws.id : null,
792
+ workspaceTitle: ws ? String(ws.title || '') : '',
793
+ beforeSid: at >= 0 && at + 1 < ids.length ? ids[at + 1] : null,
794
+ attachmentCount: attachments.ids.length,
795
+ attachmentIds: attachments.ids,
796
+ exclusiveIds,
797
+ keptShared: keptDetails,
798
+ }
799
+ }
800
+
801
+ /**
802
+ * 单个路径的体积,取不到算 0。
803
+ * @param {string} path
804
+ * @returns {Promise<number>}
805
+ */
806
+ async function sizeOf(path) {
807
+ try {
808
+ const stat = await fsp.stat(path)
809
+ return stat.isFile() ? stat.size : 0
810
+ } catch {
811
+ return 0
812
+ }
813
+ }
814
+
815
+ /**
816
+ * 字节转成好读的字符串。
817
+ * @param {number} bytes
818
+ * @returns {string}
819
+ */
820
+ function mb(bytes) {
821
+ const value = Number(bytes) || 0
822
+ if (value < 1024 * 1024) return Math.max(1, Math.round(value / 1024)) + ' KB'
823
+ return (Math.round((value / 1048576) * 10) / 10) + ' MB'
824
+ }
825
+
826
+ /* ── 删除 ─────────────────────────────────────────────────────────────── */
827
+
828
+ /**
829
+ * @param {any} ctx
830
+ * @param {string} sid
831
+ * @param {string} title
832
+ * @returns {Promise<Record<string, any>>}
833
+ */
834
+ async function removeSession(ctx, sid, title) {
835
+ const info = await analyze(ctx, sid)
836
+ if (!info.ok) return info
837
+ if (!info.deletable) return { ok: false, code: 'REFUSED', error: info.verdict.text }
838
+
839
+ // 附件归属在删除这一刻再做一次权威判定(analyze 里那次只为展示)。
840
+ // 这一步失败就什么都不动。
841
+ const ids = info.attachmentIds || []
842
+ const shared = await sharedAttachmentIds(sid, ids)
843
+ if (shared === null) {
844
+ return {
845
+ ok: false,
846
+ code: 'ATTACHMENT_SCAN_FAILED',
847
+ error: '这个会话引用了 ' + ids.length + ' 个附件,但没法确认它们是否还被别的会话共用(有会话日志读不完整),为避免误删别人的附件,已取消本次删除。',
848
+ }
849
+ }
850
+ const exclusive = ids.filter((id) => !shared.has(id))
851
+ const keptShared = [...shared.entries()].map(([id, sessions]) => ({ id, sessions, match: 'content-block' }))
852
+ const artifacts = []
853
+ for (const id of exclusive) artifacts.push(...await attachmentArtifacts(id))
854
+
855
+ // 先摘名单,再搬文件。顺序是刻意的:
856
+ // 摘名单失败 → 什么都没动,直接报错;
857
+ // 搬文件失败 → 用 attachSession 挂回去,这一步是 DSH 自己的接口,可靠。
858
+ const ws = workspaceOf(ctx, sid)
859
+ let detached = false
860
+ if (ws) {
861
+ try {
862
+ await ws.detachSession(sid)
863
+ detached = true
864
+ } catch (error) {
865
+ return { ok: false, code: 'DETACH_FAILED', error: '从工作区名单里摘除失败,未做任何移动:' + String((error && error.message) || error) }
866
+ }
867
+ }
868
+
869
+ // 全部要搬走的东西:会话目录 + 索引文件 + 只属于它的附件产物
870
+ const targets = [info.dir]
871
+ if (info.cacheExists) targets.push(info.cache)
872
+ targets.push(...artifacts)
873
+
874
+ // 先释放宿主内存里的会话实例,**再**搬文件。
875
+ //
876
+ // 顺序很关键:释放会触发投影缓存把最终 checkpoint 落盘,而落盘目标正是
877
+ // `storages/session_projcache/sessions/<sid>.json`。如果先搬后释放,
878
+ // 刚搬走的索引会被写回原位,回收站里就会多出一份同名副本。
879
+ //
880
+ // 释放成功时 DSH 自己会广播 session/disposed → api-session/removed,
881
+ // 页面那一行自动消失;释放不掉时补发一条同名广播兜底。
882
+ const release = releaseLiveSession(ctx, sid)
883
+ if (!release.released) {
884
+ try {
885
+ ctx.emit('api-session/removed', sid)
886
+ } catch {
887
+ // 某些组合里这个事件没有订阅方,忽略
888
+ }
889
+ }
890
+
891
+ // 等这次落盘稳定下来再动手,避免搬完之后又被写回。
892
+ const settled = await waitForFileSettle(info.cacheExists ? info.cache : null)
893
+
894
+ const moved = await callBin('recycle', { paths: targets })
895
+ const rows = moved && Array.isArray(moved.results) ? moved.results : []
896
+ const byPath = new Map(rows.map((row) => [row.path, row]))
897
+ const failed = targets.filter((path) => !(byPath.get(path) && byPath.get(path).ok))
898
+
899
+ if (failed.length > 0) {
900
+ // 只把确实还在原位的文件挂回去,避免留下指向空目录的幽灵条目。
901
+ if (detached && ws && existsSync(info.dir)) {
902
+ try { await ws.attachSession(sid) } catch { /* 下面会如实说明 */ }
903
+ }
904
+ const detail = failed
905
+ .map((path) => basename(path) + ':' + String((byPath.get(path) && (byPath.get(path).error || byPath.get(path).code)) || '未知原因'))
906
+ .join(';')
907
+ return { ok: false, code: 'RECYCLE_FAILED', error: '没能全部移进回收站,已尽量保持原样:' + detail }
908
+ }
909
+
910
+ // 兜底:万一落盘比等待更慢,再补搬一次。只统计「意料之外」的复活,
911
+ // 索引文件被重写属于预期内的时序,不再报给用户。
912
+ const extraMoved = await recycleResurrected(targets)
913
+ const unexpected = extraMoved.filter((path) => path !== info.cache)
914
+
915
+ const now = Date.now()
916
+ const record = {
917
+ version: RECORD_VERSION,
918
+ sid,
919
+ title: String(title || sid).slice(0, 200),
920
+ dir: info.dir,
921
+ movedFiles: [...new Set([...targets, ...extraMoved])],
922
+ workspaceId: ws ? String(ws.id) : null,
923
+ beforeSid: info.beforeSid,
924
+ deletedAt: now,
925
+ expiresAt: now + RETENTION_MS,
926
+ attempts: 0,
927
+ // 审计用:谁被搬走、谁被保留、被哪些会话以什么方式引用。
928
+ // 旧记录没有这一块,读取时按空处理。
929
+ attachments: {
930
+ referenced: ids.length,
931
+ movedIds: exclusive.slice(),
932
+ movedArtifacts: artifacts.length,
933
+ keptShared,
934
+ },
935
+ }
936
+
937
+ // 记录写不进去时删除已经发生了,不能谎报失败;如实告诉用户「能删,但列表里看不到」。
938
+ let recorded = true
939
+ try {
940
+ await writeRecord(record)
941
+ } catch {
942
+ recorded = false
943
+ }
944
+
945
+ // 日志已经搬走,缓存里那份结论作废。
946
+ forgetAttachmentScan(info.dir)
947
+
948
+ return {
949
+ ok: true,
950
+ sessionId: sid,
951
+ dir: info.dir,
952
+ bytes: info.bytes,
953
+ workspaceId: record.workspaceId,
954
+ expiresAt: record.expiresAt,
955
+ movedFiles: record.movedFiles.length,
956
+ movedAfterRelease: unexpected.length,
957
+ indexRebuilt: extraMoved.includes(info.cache),
958
+ flushSettled: settled,
959
+ attachments: {
960
+ referencedIds: ids.length,
961
+ movedIds: exclusive.length,
962
+ movedArtifacts: artifacts.length,
963
+ keptShared,
964
+ },
965
+ wasLive: info.open === true,
966
+ released: release.released,
967
+ releaseReason: release.reason,
968
+ recorded,
969
+ warning: recorded ? undefined : '文件已进回收站,但删除记录没写成功,界面上不会出现「恢复」入口;需要时可以去 Windows 回收站手动还原。',
970
+ }
971
+ }
972
+
973
+ /**
974
+ * 等一个文件「不再变化」再动手。
975
+ *
976
+ * 释放会话会让投影缓存把最终 checkpoint 写回 `session_projcache`,
977
+ * 这是节流写回,可能比 release 调用晚一点落地。这里连采样两次相同的
978
+ * mtime+size 才算稳定;文件还不存在时先给它一点出现的时间。
979
+ *
980
+ * @param {string | null} path 要观察的文件;null 表示没有这个文件,直接返回
981
+ * @param {{ timeoutMs?: number, intervalMs?: number }} [options]
982
+ * @returns {Promise<boolean>} 是否在超时前稳定
983
+ */
984
+ async function waitForFileSettle(path, options = {}) {
985
+ if (typeof path !== 'string' || path === '') return true
986
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 1500
987
+ const intervalMs = Number(options.intervalMs) > 0 ? Number(options.intervalMs) : 150
988
+ const started = Date.now()
989
+ let last = null
990
+ for (;;) {
991
+ let stamp
992
+ try {
993
+ const stat = await fsp.stat(path)
994
+ stamp = stat.mtimeMs + ':' + stat.size
995
+ } catch {
996
+ stamp = 'missing'
997
+ }
998
+ if (last !== null && stamp === last && stamp !== 'missing') return true
999
+ last = stamp
1000
+ if (Date.now() - started > timeoutMs) return false
1001
+ await new Promise((resolve) => setTimeout(resolve, intervalMs))
1002
+ }
1003
+ }
1004
+
1005
+ /**
1006
+ * 搬完之后再查一轮:释放会话可能让某些文件被写回原路径。
1007
+ *
1008
+ * 每一轮等一会儿再看,复活了就再搬一次;最多两轮,避免无限循环。
1009
+ * @param {string[]} paths 原本要搬走的路径
1010
+ * @returns {Promise<string[]>} 补搬成功的路径
1011
+ */
1012
+ async function recycleResurrected(paths) {
1013
+ const extra = []
1014
+ for (let round = 0; round < 2; round += 1) {
1015
+ await new Promise((resolve) => setTimeout(resolve, 400))
1016
+ const back = paths.filter((path) => existsSync(path))
1017
+ if (back.length === 0) break
1018
+ const result = await callBin('recycle', { paths: back })
1019
+ const rows = result && Array.isArray(result.results) ? result.results : []
1020
+ for (const row of rows) {
1021
+ if (row && row.ok === true) extra.push(row.path)
1022
+ }
1023
+ }
1024
+ return extra
1025
+ }
1026
+
1027
+ /* ── 恢复 ─────────────────────────────────────────────────────────────── */
1028
+
1029
+ /**
1030
+ * 把一条记录对应的文件从回收站取回来,再挂回原工作区的原位置。
1031
+ * @param {any} ctx
1032
+ * @param {string} sid
1033
+ * @returns {Promise<Record<string, any>>}
1034
+ */
1035
+ async function restoreSession(ctx, sid) {
1036
+ if (!isSafeSessionId(sid)) return { ok: false, code: 'BAD_ID', error: '会话 id 不合法' }
1037
+
1038
+ const record = await readRecord(sid)
1039
+ if (!record) return { ok: false, code: 'NOT_TRACKED', error: '没有这个会话的删除记录(可能已超过 7 天,或不是本插件删的)' }
1040
+ if (Date.now() > record.expiresAt) return { ok: false, code: 'EXPIRED', error: '已超过 7 天保留期,这条记录不再支持恢复' }
1041
+ if (!isInside(sessionsRoot(), record.dir)) {
1042
+ return { ok: false, code: 'BAD_DIR', error: '记录里的原始目录不在会话存储根内,已拒绝恢复' }
1043
+ }
1044
+ if (existsSync(record.dir)) {
1045
+ return { ok: false, code: 'ALREADY_BACK', error: '原位置已经有同名目录了,先处理它再恢复' }
1046
+ }
1047
+
1048
+ // 逐个从回收站取回;已经自己回来的就跳过。
1049
+ // 记录文件是本地的普通文件,理论上可能被改过,所以每个路径都要再过一遍范围检查:
1050
+ // 只允许会话存储根、索引目录、附件仓库这三处。
1051
+ const allowedRoots = [
1052
+ sessionsRoot(),
1053
+ join(dshHome(), 'storages', 'session_projcache'),
1054
+ join(dshHome(), 'attachments', 'v1'),
1055
+ ]
1056
+ const restored = []
1057
+ const failures = []
1058
+ for (const path of record.movedFiles) {
1059
+ if (typeof path !== 'string' || !allowedRoots.some((root) => isInside(root, path))) {
1060
+ failures.push({ path: String(path), code: 'OUT_OF_SCOPE', error: '记录里的路径不在允许范围内,已跳过' })
1061
+ continue
1062
+ }
1063
+ if (existsSync(path)) {
1064
+ restored.push(path)
1065
+ continue
1066
+ }
1067
+ // 回收站里记的是「原位置」的长路径。如果记录里存的是 8.3 短名
1068
+ // (比如 C:\Users\Name~1\…),直接拿 dirname 去比会对不上,
1069
+ // 所以先把父目录解析成长路径再作为匹配依据。
1070
+ const parent = await fsp.realpath(dirname(path)).catch(() => dirname(path))
1071
+ const result = await callBin('restore', { name: basename(path), location: parent })
1072
+ if (result.ok && existsSync(path)) restored.push(path)
1073
+ else failures.push({ path, code: result.code || 'RESTORE_FAILED', error: result.error })
1074
+ }
1075
+
1076
+ if (!existsSync(record.dir)) {
1077
+ const first = failures[0]
1078
+ const reason = first && first.code === 'NOT_IN_BIN'
1079
+ ? '回收站里找不到这个目录了(可能被清空,或已经被手动还原过)'
1080
+ : first && first.code === 'NO_RESTORE_VERB'
1081
+ ? '回收站条目上没有找到「还原」动作,请手动在资源管理器里还原'
1082
+ : '从回收站还原失败:' + String((first && (first.error || first.code)) || '未知原因')
1083
+ return { ok: false, code: (first && first.code) || 'RESTORE_FAILED', error: reason, failures }
1084
+ }
1085
+
1086
+ // 文件回来了,再挂回工作区,并尽量放回原来的位置。
1087
+ let reattached = false
1088
+ let positionRestored = false
1089
+ let attachError = null
1090
+ if (record.workspaceId) {
1091
+ const registry = registryOf(ctx)
1092
+ const ws = registry && typeof registry.get === 'function' ? registry.get(record.workspaceId) : undefined
1093
+ if (ws && typeof ws.attachSession === 'function') {
1094
+ try {
1095
+ await ws.attachSession(sid)
1096
+ reattached = true
1097
+ if (typeof ws.insertSessionBefore === 'function') {
1098
+ try {
1099
+ await ws.insertSessionBefore(sid, record.beforeSid === null ? undefined : record.beforeSid)
1100
+ positionRestored = true
1101
+ } catch {
1102
+ // 原来那个「后面的会话」可能已经被删了;位置放不回去,但会话已经在列表里。
1103
+ }
1104
+ }
1105
+ } catch (error) {
1106
+ attachError = String((error && error.message) || error)
1107
+ }
1108
+ } else {
1109
+ attachError = '原来的工作区已经不在了'
1110
+ }
1111
+ } else {
1112
+ attachError = '删除时它就不在任何工作区里'
1113
+ }
1114
+
1115
+ // 恢复成功后不再往 restored/ 里留一份归档:这条记录也移进回收站,
1116
+ // 插件的状态目录里就什么都不剩。万一移不动(被占用等),退回本地归档,
1117
+ // 至少不会让一条已经恢复的记录重新出现在「可恢复」列表里。
1118
+ const wiped = await callBin('recycle', { paths: [recordPath(sid)] })
1119
+ const wipedRow = wiped && Array.isArray(wiped.results) ? wiped.results[0] : null
1120
+ const recordCleared = Boolean(wipedRow && wipedRow.ok === true)
1121
+ if (!recordCleared) await archiveRecord(record)
1122
+
1123
+ return {
1124
+ ok: true,
1125
+ sessionId: sid,
1126
+ dir: record.dir,
1127
+ restored,
1128
+ failures,
1129
+ reattached,
1130
+ positionRestored,
1131
+ attachError,
1132
+ recordCleared,
1133
+ }
1134
+ }
1135
+
1136
+ /* ── 7 天到期 ─────────────────────────────────────────────────────────── */
1137
+
1138
+ /**
1139
+ * 到期处理:把记录文件本身移进回收站。
1140
+ *
1141
+ * 记录没了,会话就无法再通过本插件恢复 —— 这正是「7 天后不可恢复」的实现方式。
1142
+ * 注意这里搬的是记录,不是用户数据:会话目录早在删除那一刻就已经在回收站里了。
1143
+ *
1144
+ * @returns {Promise<{ settled: number, details: any[] }>}
1145
+ */
1146
+ async function sweepExpired() {
1147
+ const records = await listRecords()
1148
+ const now = Date.now()
1149
+ const due = records.filter((record) => record.expiresAt > 0 && record.expiresAt <= now)
1150
+ if (due.length === 0) return { settled: 0, details: [] }
1151
+
1152
+ const details = []
1153
+ let settled = 0
1154
+
1155
+ for (const record of due) {
1156
+ // 会话目录自己回来了(用户手动还原过),就没必要再保留记录,但也不该
1157
+ // 把记录扔进回收站去占地方 —— 直接归档到本地即可。
1158
+ if (existsSync(record.dir)) {
1159
+ await archiveRecord(record)
1160
+ details.push({ sid: record.sid, action: 'kept', reason: '目录已经回到原位,记录转为本地归档' })
1161
+ settled += 1
1162
+ continue
1163
+ }
1164
+
1165
+ const result = await callBin('recycle', { paths: [recordPath(record.sid)] })
1166
+ const row = result && Array.isArray(result.results) ? result.results[0] : null
1167
+ if (row && row.ok) {
1168
+ settled += 1
1169
+ details.push({ sid: record.sid, action: 'record-moved-to-bin' })
1170
+ } else {
1171
+ // 移不动(比如被占用):累加次数,下次再试;连续三次失败就放弃这条记录。
1172
+ const attempts = record.attempts + 1
1173
+ if (attempts >= 3) {
1174
+ await archiveRecord({ ...record, attempts })
1175
+ details.push({ sid: record.sid, action: 'gave-up', attempts })
1176
+ settled += 1
1177
+ } else {
1178
+ await writeRecord({ ...record, attempts })
1179
+ details.push({ sid: record.sid, action: 'retry-later', attempts })
1180
+ }
1181
+ }
1182
+ }
1183
+
1184
+ return { settled, details }
1185
+ }
1186
+
1187
+ /* ── 立即忘记一条记录 ─────────────────────────────────────────────────── */
1188
+
1189
+ /**
1190
+ * 把某条删除记录**现在就**移进回收站,不用等 7 天。
1191
+ *
1192
+ * 只是提前了到期动作:记录文件进回收站,于是它从页面列表里消失,这个会话
1193
+ * 也就无法再通过本插件恢复。会话本身和它的文件早在删除那一刻就已经在回收站里,
1194
+ * 这里不会再动它们 —— 它们仍然可以自己在资源管理器里还原。
1195
+ *
1196
+ * @param {string} sid
1197
+ * @returns {Promise<Record<string, any>>}
1198
+ */
1199
+ async function forgetRecord(sid) {
1200
+ if (!isSafeSessionId(sid)) return { ok: false, code: 'BAD_ID', error: '会话 id 不合法' }
1201
+
1202
+ const record = await readRecord(sid)
1203
+ if (!record) return { ok: false, code: 'NOT_TRACKED', error: '没有这条删除记录(可能已经恢复或已过期)' }
1204
+
1205
+ const result = await callBin('recycle', { paths: [recordPath(sid)] })
1206
+ const row = result && Array.isArray(result.results) ? result.results[0] : null
1207
+ if (!row || row.ok !== true) {
1208
+ return {
1209
+ ok: false,
1210
+ code: 'RECYCLE_FAILED',
1211
+ error: '没能把删除记录移进回收站:' + String((row && (row.error || row.code)) || (result && result.error) || '未知原因'),
1212
+ }
1213
+ }
1214
+
1215
+ return {
1216
+ ok: true,
1217
+ sessionId: sid,
1218
+ message: '这条删除记录已移进回收站,页面里不再显示它。会话文件本来就在回收站里,需要时仍可在资源管理器中还原。',
1219
+ }
1220
+ }
1221
+
1222
+ /* ── 图片请求缓存 ─────────────────────────────────────────────────────── */
1223
+
1224
+ /**
1225
+ * 发给模型之前生成的「请求版本」图片缓存。
1226
+ *
1227
+ * 和会话删除是两件不同的事:这里存的不是原图,而是按模型要求缩放/重编码后的
1228
+ * 派生副本,纯缓存、可再生。所以它不跟着会话删除走,而是单独给一个入口。
1229
+ * @returns {string}
1230
+ */
1231
+ function cacheRoot() {
1232
+ return join(dshHome(), 'cache', 'attachments', 'request-images')
1233
+ }
1234
+
1235
+ /**
1236
+ * 统计缓存目录的文件数与总字节。
1237
+ * @returns {Promise<{ exists: boolean, files: number, bytes: number }>}
1238
+ */
1239
+ async function cacheStats() {
1240
+ const root = cacheRoot()
1241
+ if (!existsSync(root)) return { exists: false, files: 0, bytes: 0 }
1242
+ let files = 0
1243
+ let bytes = 0
1244
+ const walk = async (dir) => {
1245
+ let entries
1246
+ try {
1247
+ entries = await fsp.readdir(dir, { withFileTypes: true })
1248
+ } catch {
1249
+ return
1250
+ }
1251
+ for (const entry of entries) {
1252
+ const full = join(dir, entry.name)
1253
+ if (entry.isDirectory()) {
1254
+ await walk(full)
1255
+ continue
1256
+ }
1257
+ if (!entry.isFile()) continue
1258
+ try {
1259
+ const stat = await fsp.stat(full)
1260
+ files += 1
1261
+ bytes += stat.size
1262
+ } catch {
1263
+ // 刚好被删掉的文件不算
1264
+ }
1265
+ }
1266
+ }
1267
+ await walk(root)
1268
+ return { exists: true, files, bytes }
1269
+ }
1270
+
1271
+ /**
1272
+ * 把整个图片缓存目录移进回收站。
1273
+ *
1274
+ * 同样的纪律:先确认回收站可用、装得下,再动手;装不下就拒绝,
1275
+ * 绝不用「反正是缓存」当借口退化成永久删除。
1276
+ * @returns {Promise<Record<string, any>>}
1277
+ */
1278
+ async function clearCache() {
1279
+ const root = cacheRoot()
1280
+ if (!existsSync(root)) return { ok: true, moved: 0, bytes: 0, message: '没有缓存需要清理' }
1281
+
1282
+ const stats = await cacheStats()
1283
+ const probe = await callBin('probe', { path: root })
1284
+ if (!probe.ok) {
1285
+ return { ok: false, code: 'PROBE_FAILED', error: '读不到回收站信息,已取消:' + String(probe.error || probe.code || '未知原因') }
1286
+ }
1287
+ if (probe.nukeOnDelete === 1) {
1288
+ return { ok: false, code: 'BIN_DISABLED', error: '这台机器上该磁盘的回收站被关闭了,清理会变成永久删除,已取消。' }
1289
+ }
1290
+ if (!probe.quotaKnown || !(probe.capacityMB > 0)) {
1291
+ return { ok: false, code: 'QUOTA_UNKNOWN', error: '查不到该磁盘的回收站容量,无法保证放进回收站,已取消。' }
1292
+ }
1293
+ if ((probe.bytes || 0) > probe.capacityMB * 1024 * 1024) {
1294
+ return { ok: false, code: 'TOO_BIG', error: '缓存共 ' + mb(probe.bytes) + ',超过回收站容量 ' + probe.capacityMB + ' MB,已取消。' }
1295
+ }
1296
+
1297
+ const result = await callBin('recycle', { paths: [root] })
1298
+ const row = result && Array.isArray(result.results) ? result.results[0] : null
1299
+ if (!row || row.ok !== true) {
1300
+ return {
1301
+ ok: false,
1302
+ code: 'RECYCLE_FAILED',
1303
+ error: '没能把缓存移进回收站:' + String((row && (row.error || row.code)) || (result && result.error) || '未知原因'),
1304
+ }
1305
+ }
1306
+ return { ok: true, moved: stats.files, bytes: stats.bytes, message: '图片缓存已移进回收站,下次发送图片时会自动重新生成。' }
1307
+ }
1308
+
1309
+ /* ── 附件仓库盘点 ─────────────────────────────────────────────────────── */
1310
+
1311
+ /**
1312
+ * 附件仓库根。DSH 的附件是**全局一份**、按内容寻址的,不按会话分目录。
1313
+ * @returns {string}
1314
+ */
1315
+ function attachmentStoreRoot() {
1316
+ return join(dshHome(), 'attachments', 'v1')
1317
+ }
1318
+
1319
+ /**
1320
+ * 会话标题(读投影缓存)。读不到就退回会话 id。
1321
+ * @param {string} sid
1322
+ * @returns {string}
1323
+ */
1324
+ async function sessionTitle(sid) {
1325
+ try {
1326
+ const raw = await fsp.readFile(join(dshHome(), 'storages', 'session_projcache', 'sessions', sid + '.json'), 'utf8')
1327
+ const doc = JSON.parse(raw)
1328
+ const title = doc && doc.record && doc.record.rows && doc.record.rows.title && doc.record.rows.title.val
1329
+ if (typeof title === 'string' && title.trim() !== '') return title.trim().slice(0, 120)
1330
+ } catch {
1331
+ // 没有索引就用 id
1332
+ }
1333
+ return sid
1334
+ }
1335
+
1336
+ /**
1337
+ * 建立「附件摘要 → 引用了它的会话」索引。
1338
+ *
1339
+ * 只统计结构化引用(和删除判定同一套函数)。任何一个会话的日志读不完整就返回
1340
+ * null —— 那样就无法断定谁是孤儿,宁可什么都不清。
1341
+ * @returns {Promise<Map<string, string[]> | null>}
1342
+ */
1343
+ async function referenceIndex() {
1344
+ const root = sessionsRoot()
1345
+ let projects
1346
+ try {
1347
+ projects = await fsp.readdir(root, { withFileTypes: true })
1348
+ } catch {
1349
+ return new Map()
1350
+ }
1351
+
1352
+ const index = new Map()
1353
+ let scanned = 0
1354
+ for (const project of projects) {
1355
+ if (!project.isDirectory()) continue
1356
+ let sessions
1357
+ try {
1358
+ sessions = await fsp.readdir(join(root, project.name), { withFileTypes: true })
1359
+ } catch {
1360
+ continue
1361
+ }
1362
+ for (const session of sessions) {
1363
+ if (!session.isDirectory()) continue
1364
+ scanned += 1
1365
+ if (scanned > MAX_SCAN_SESSIONS) return null
1366
+ const scan = await attachmentsOf(join(root, project.name, session.name))
1367
+ if (!scan.ok) return null
1368
+ for (const id of scan.ids) {
1369
+ const owners = index.get(id)
1370
+ if (owners === undefined) index.set(id, [session.name])
1371
+ else if (!owners.includes(session.name)) owners.push(session.name)
1372
+ }
1373
+ }
1374
+ }
1375
+ return index
1376
+ }
1377
+
1378
+ /**
1379
+ * 递归统计目录字节数。
1380
+ * @param {string} dir
1381
+ * @returns {Promise<number>}
1382
+ */
1383
+ async function directorySize(dir) {
1384
+ let total = 0
1385
+ let entries
1386
+ try {
1387
+ entries = await fsp.readdir(dir, { withFileTypes: true })
1388
+ } catch {
1389
+ return 0
1390
+ }
1391
+ for (const entry of entries) {
1392
+ const full = join(dir, entry.name)
1393
+ if (entry.isDirectory()) {
1394
+ total += await directorySize(full)
1395
+ continue
1396
+ }
1397
+ if (!entry.isFile()) continue
1398
+ try {
1399
+ total += (await fsp.stat(full)).size
1400
+ } catch {
1401
+ // 刚被删掉的文件不算
1402
+ }
1403
+ }
1404
+ return total
1405
+ }
1406
+
1407
+ /**
1408
+ * 盘点附件仓库:每个摘要的产物、大小、被哪些会话引用。
1409
+ *
1410
+ * @returns {Promise<Record<string, any>>}
1411
+ */
1412
+ async function attachmentInventory() {
1413
+ const refs = await referenceIndex()
1414
+ if (refs === null) {
1415
+ return {
1416
+ ok: false,
1417
+ code: 'SCAN_FAILED',
1418
+ error: '有会话日志读不完整,无法判断哪些附件没人引用,已取消盘点(清理也一并取消)。',
1419
+ }
1420
+ }
1421
+
1422
+ const base = attachmentStoreRoot()
1423
+ const rows = new Map()
1424
+ const ensure = (id) => {
1425
+ let row = rows.get(id)
1426
+ if (row === undefined) {
1427
+ row = { id, bytes: 0, artifacts: [], names: [], sessions: [] }
1428
+ rows.set(id, row)
1429
+ }
1430
+ return row
1431
+ }
1432
+
1433
+ for (const kind of ['objects', 'file-objects', 'files']) {
1434
+ const kindRoot = join(base, kind)
1435
+ let buckets
1436
+ try {
1437
+ buckets = await fsp.readdir(kindRoot, { withFileTypes: true })
1438
+ } catch {
1439
+ continue
1440
+ }
1441
+ for (const bucket of buckets) {
1442
+ if (!bucket.isDirectory()) continue
1443
+ const bucketPath = join(kindRoot, bucket.name)
1444
+ if (!isInside(base, bucketPath)) continue
1445
+ let entries
1446
+ try {
1447
+ entries = await fsp.readdir(bucketPath, { withFileTypes: true })
1448
+ } catch {
1449
+ continue
1450
+ }
1451
+ for (const entry of entries) {
1452
+ const id = normalizeAttachmentId(entry.name)
1453
+ if (id === null) continue
1454
+ const full = join(bucketPath, entry.name)
1455
+ let stat
1456
+ try {
1457
+ stat = await fsp.lstat(full)
1458
+ } catch {
1459
+ continue
1460
+ }
1461
+ if (stat.isSymbolicLink()) continue
1462
+ const row = ensure(id)
1463
+ const bytes = stat.isDirectory() ? await directorySize(full) : stat.size
1464
+ row.bytes += bytes
1465
+ row.artifacts.push({ kind, path: full, bytes })
1466
+ if (kind === 'files' && stat.isDirectory()) {
1467
+ try {
1468
+ for (const name of await fsp.readdir(full)) {
1469
+ if (!row.names.includes(name)) row.names.push(name)
1470
+ }
1471
+ } catch {
1472
+ // 读不到名字就算了
1473
+ }
1474
+ }
1475
+ }
1476
+ }
1477
+ }
1478
+
1479
+ const items = []
1480
+ let totalBytes = 0
1481
+ let orphanCount = 0
1482
+ let orphanBytes = 0
1483
+ for (const row of rows.values()) {
1484
+ const owners = refs.get(row.id) || []
1485
+ const orphan = owners.length === 0
1486
+ totalBytes += row.bytes
1487
+ if (orphan) {
1488
+ orphanCount += 1
1489
+ orphanBytes += row.bytes
1490
+ }
1491
+ items.push({
1492
+ id: row.id,
1493
+ bytes: row.bytes,
1494
+ artifacts: row.artifacts.length,
1495
+ names: row.names.slice(0, 3),
1496
+ orphan,
1497
+ sessions: owners.map((sid) => ({ id: sid, title: sid })),
1498
+ })
1499
+ }
1500
+
1501
+ // 孤儿排前面,其余按体积降序
1502
+ items.sort((a, b) => (a.orphan === b.orphan ? b.bytes - a.bytes : a.orphan ? -1 : 1))
1503
+
1504
+ // 会话标题是异步读的,补上(只补有归属的,孤儿没有)
1505
+ const titles = new Map()
1506
+ for (const item of items) {
1507
+ for (const owner of item.sessions) {
1508
+ if (!titles.has(owner.id)) titles.set(owner.id, await sessionTitle(owner.id))
1509
+ owner.title = titles.get(owner.id)
1510
+ }
1511
+ }
1512
+
1513
+ const capped = items.slice(0, MAX_REPORTED_ATTACHMENTS)
1514
+ return {
1515
+ ok: true,
1516
+ store: base,
1517
+ total: items.length,
1518
+ totalBytes,
1519
+ orphanCount,
1520
+ orphanBytes,
1521
+ truncated: items.length > capped.length,
1522
+ items: capped,
1523
+ }
1524
+ }
1525
+
1526
+ /**
1527
+ * 把孤儿附件移进回收站。
1528
+ * @returns {Promise<Record<string, any>>}
1529
+ */
1530
+ async function clearOrphans() {
1531
+ const refs = await referenceIndex()
1532
+ if (refs === null) {
1533
+ return { ok: false, code: 'SCAN_FAILED', error: '有会话日志读不完整,无法判断哪些附件没人引用,已取消清理。' }
1534
+ }
1535
+
1536
+ const base = attachmentStoreRoot()
1537
+ const targets = []
1538
+ let bytes = 0
1539
+ for (const kind of ['objects', 'file-objects', 'files']) {
1540
+ const kindRoot = join(base, kind)
1541
+ let buckets
1542
+ try {
1543
+ buckets = await fsp.readdir(kindRoot, { withFileTypes: true })
1544
+ } catch {
1545
+ continue
1546
+ }
1547
+ for (const bucket of buckets) {
1548
+ if (!bucket.isDirectory()) continue
1549
+ const bucketPath = join(kindRoot, bucket.name)
1550
+ let entries
1551
+ try {
1552
+ entries = await fsp.readdir(bucketPath, { withFileTypes: true })
1553
+ } catch {
1554
+ continue
1555
+ }
1556
+ for (const entry of entries) {
1557
+ const id = normalizeAttachmentId(entry.name)
1558
+ if (id === null) continue
1559
+ if (refs.has(id)) continue
1560
+ const full = join(bucketPath, entry.name)
1561
+ try {
1562
+ const stat = await fsp.lstat(full)
1563
+ if (stat.isSymbolicLink()) continue
1564
+ bytes += stat.isDirectory() ? await directorySize(full) : stat.size
1565
+ } catch {
1566
+ continue
1567
+ }
1568
+ targets.push(full)
1569
+ }
1570
+ }
1571
+ }
1572
+
1573
+ if (targets.length === 0) return { ok: true, moved: 0, bytes: 0, message: '没有需要清理的孤儿附件' }
1574
+
1575
+ const result = await callBin('recycle', { paths: targets })
1576
+ const rows = result && Array.isArray(result.results) ? result.results : []
1577
+ const moved = rows.filter((row) => row && row.ok === true).length
1578
+ const failed = rows.filter((row) => row && row.ok !== true)
1579
+ return {
1580
+ ok: failed.length === 0,
1581
+ moved,
1582
+ bytes,
1583
+ failed: failed.slice(0, 5).map((row) => ({ path: row.path, error: String(row.error || row.code || '未知原因') })),
1584
+ message: '已把 ' + moved + ' 个孤儿附件移进回收站',
1585
+ }
1586
+ }
1587
+
1588
+ /**
1589
+ * 在资源管理器里打开附件仓库。
1590
+ *
1591
+ * 路径是算出来的固定值,不接受任何请求参数 —— 这里没有「打开任意路径」的能力。
1592
+ * 走 PowerShell 的 `Shell.Application.Explore`:直接在宿主进程里 execFile
1593
+ * `explorer.exe` 在 Electron 下经常拉不起窗口(子进程被 job 对象回收太快)。
1594
+ * @returns {Promise<Record<string, any>>}
1595
+ */
1596
+ async function openAttachmentStore() {
1597
+ const dir = attachmentStoreRoot()
1598
+ if (!existsSync(dir)) return { ok: false, code: 'NOT_FOUND', error: '附件仓库目录不存在:' + dir }
1599
+ const result = await callBin('open', { path: dir }, { timeoutMs: 20000 })
1600
+ if (result && result.ok === true) return { ok: true, path: dir }
1601
+ return {
1602
+ ok: false,
1603
+ code: (result && result.code) || 'OPEN_FAILED',
1604
+ error: '打不开资源管理器:' + String((result && (result.error || result.code)) || '未知原因'),
1605
+ }
1606
+ }
1607
+
1608
+ /* ── HTTP ─────────────────────────────────────────────────────────────── */
1609
+
1610
+ /**
1611
+ * 只接受本插件自己页面的请求。
1612
+ *
1613
+ * DSH 的 Web 服务器明确不提供认证和来源策略,这一层必须由路由自己实现,
1614
+ * 否则任何本机程序、以及任何网页发出的「简单请求」都能触发删除。
1615
+ * @param {import('node:http').IncomingMessage} req
1616
+ */
1617
+ function requireOwnPage(req) {
1618
+ if (req.headers['x-dsh-recyclebin'] !== '1') throw new Error('缺少插件请求标记')
1619
+ const origin = req.headers.origin
1620
+ if (typeof origin !== 'string' || origin === '' || origin === 'null') return
1621
+ let host
1622
+ try {
1623
+ host = new URL(origin).host
1624
+ } catch {
1625
+ throw new Error('请求来源不合法')
1626
+ }
1627
+ const self = req.headers.host
1628
+ if (typeof self === 'string' && self !== '' && host !== self) throw new Error('已拒绝跨站请求')
1629
+ }
1630
+
1631
+ /**
1632
+ * @param {import('node:http').IncomingMessage} req
1633
+ * @returns {Promise<Record<string, any>>}
1634
+ */
1635
+ function readJsonBody(req) {
1636
+ return new Promise((resolve) => {
1637
+ let size = 0
1638
+ let done = false
1639
+ const chunks = []
1640
+ const finish = (value) => {
1641
+ if (done) return
1642
+ done = true
1643
+ resolve(value)
1644
+ }
1645
+ req.on('data', (chunk) => {
1646
+ size += chunk.length
1647
+ if (size > MAX_BODY_BYTES) {
1648
+ finish({})
1649
+ req.destroy()
1650
+ return
1651
+ }
1652
+ chunks.push(chunk)
1653
+ })
1654
+ req.on('end', () => {
1655
+ const text = Buffer.concat(chunks).toString('utf8').trim()
1656
+ if (text === '') return finish({})
1657
+ try {
1658
+ const parsed = JSON.parse(text)
1659
+ finish(parsed && typeof parsed === 'object' ? parsed : {})
1660
+ } catch {
1661
+ finish({})
1662
+ }
1663
+ })
1664
+ req.on('error', () => finish({}))
1665
+ })
1666
+ }
1667
+
1668
+ /**
1669
+ * @param {import('node:http').ServerResponse} res
1670
+ * @param {number} status
1671
+ * @param {Record<string, any>} body
1672
+ */
1673
+ function sendJson(res, status, body) {
1674
+ const text = JSON.stringify(body)
1675
+ res.writeHead(status, {
1676
+ 'content-type': 'application/json; charset=utf-8',
1677
+ 'content-length': String(Buffer.byteLength(text, 'utf8')),
1678
+ 'cache-control': 'no-store',
1679
+ })
1680
+ res.end(text)
1681
+ }
1682
+
1683
+ /* ── 挂载 ─────────────────────────────────────────────────────────────── */
1684
+
1685
+ /**
1686
+ * @param {any} ctx 宿主插件上下文
1687
+ */
1688
+ export function apply(ctx) {
1689
+ // 先把数据目录定下来,再创建状态目录——否则可能建到错误的 home 下。
1690
+ const ready = probeHome(ctx?.logger).catch(() => dshHome())
1691
+ void ready
1692
+ .then(() => migrateLegacyState(ctx?.logger))
1693
+ .then(() => fsp.mkdir(recordsDir(), { recursive: true }))
1694
+ .catch(() => {})
1695
+
1696
+ const mount = (path, handler) => ctx.effect(() => ctx.webServer.register({
1697
+ kind: 'exact',
1698
+ path: ROUTE + path,
1699
+ handler: (req, res) => {
1700
+ void (async () => {
1701
+ try {
1702
+ requireOwnPage(req)
1703
+ await handler(req, res)
1704
+ } catch (error) {
1705
+ const message = String((error && error.message) || error)
1706
+ if (!res.headersSent) sendJson(res, 400, { ok: false, error: message })
1707
+ else res.end()
1708
+ }
1709
+ })()
1710
+ },
1711
+ }), 'dsh-recyclebin: ' + path)
1712
+
1713
+ mount('/health', (req, res) => {
1714
+ const home = dshHome()
1715
+ sendJson(res, 200, {
1716
+ ok: true,
1717
+ plugin: name,
1718
+ version: '0.4.0',
1719
+ home,
1720
+ homeResolved: resolvedHome !== null,
1721
+ homeHasSessions: existsSync(join(home, 'sessions')),
1722
+ retentionDays: RETENTION_DAYS,
1723
+ })
1724
+ })
1725
+
1726
+ mount('/list', async (req, res) => {
1727
+ const swept = await withMutationLock(() => sweepExpired()).catch(() => ({ settled: 0, details: [] }))
1728
+ const records = await listRecords()
1729
+ const now = Date.now()
1730
+ const entries = records
1731
+ .slice()
1732
+ .sort((a, b) => b.deletedAt - a.deletedAt)
1733
+ .map((record) => ({
1734
+ sid: record.sid,
1735
+ title: record.title,
1736
+ dir: record.dir,
1737
+ deletedAt: record.deletedAt,
1738
+ expiresAt: record.expiresAt,
1739
+ daysLeft: Math.max(0, Math.ceil((record.expiresAt - now) / 86400000)),
1740
+ inBin: !existsSync(record.dir),
1741
+ files: record.movedFiles.length,
1742
+ }))
1743
+ sendJson(res, 200, { ok: true, entries, retentionDays: RETENTION_DAYS, swept: swept.settled })
1744
+ })
1745
+
1746
+ mount('/analyze', async (req, res) => {
1747
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: '只接受 POST' })
1748
+ const body = await readJsonBody(req)
1749
+ const info = await analyze(ctx, String(body.sessionId || ''))
1750
+ // 摘要列表只在宿主内部用于算归属,不发给页面;
1751
+ // keptShared 保留(只含 id 与会话 id),页面要展示「哪些被保留了」。
1752
+ const { attachmentIds, exclusiveIds, ...visible } = info
1753
+ void attachmentIds
1754
+ void exclusiveIds
1755
+ sendJson(res, 200, visible)
1756
+ })
1757
+
1758
+ mount('/delete', async (req, res) => {
1759
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: '只接受 POST' })
1760
+ const body = await readJsonBody(req)
1761
+ if (body.confirm !== true) return sendJson(res, 400, { ok: false, error: '缺少确认标记' })
1762
+ const result = await withMutationLock(() => removeSession(ctx, String(body.sessionId || ''), String(body.title || '')))
1763
+ sendJson(res, result.ok ? 200 : 400, result)
1764
+ })
1765
+
1766
+ mount('/restore', async (req, res) => {
1767
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: '只接受 POST' })
1768
+ const body = await readJsonBody(req)
1769
+ const result = await withMutationLock(() => restoreSession(ctx, String(body.sessionId || '')))
1770
+ sendJson(res, result.ok ? 200 : 400, result)
1771
+ })
1772
+
1773
+ mount('/forget', async (req, res) => {
1774
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: '只接受 POST' })
1775
+ const body = await readJsonBody(req)
1776
+ if (body.confirm !== true) return sendJson(res, 400, { ok: false, error: '缺少确认标记' })
1777
+ const result = await withMutationLock(() => forgetRecord(String(body.sessionId || '')))
1778
+ sendJson(res, result.ok ? 200 : 400, result)
1779
+ })
1780
+
1781
+ // 手动释放:把某个会话从宿主内存里摘掉。
1782
+ // 正常删除会自动做这件事,这个接口用于清理历史遗留的「幽灵」条目。
1783
+ mount('/release', async (req, res) => {
1784
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: '只接受 POST' })
1785
+ const body = await readJsonBody(req)
1786
+ if (body.confirm !== true) return sendJson(res, 400, { ok: false, error: '缺少确认标记' })
1787
+ const sid = String(body.sessionId || '')
1788
+ const result = await withMutationLock(async () => releaseLiveSession(ctx, sid))
1789
+ sendJson(res, 200, { ok: true, sessionId: sid, ...result })
1790
+ })
1791
+
1792
+ mount('/cache', async (req, res) => {
1793
+ const stats = await cacheStats()
1794
+ sendJson(res, 200, { ok: true, path: cacheRoot(), ...stats })
1795
+ })
1796
+
1797
+ mount('/cache/clear', async (req, res) => {
1798
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: '只接受 POST' })
1799
+ const body = await readJsonBody(req)
1800
+ if (body.confirm !== true) return sendJson(res, 400, { ok: false, error: '缺少确认标记' })
1801
+ const result = await withMutationLock(() => clearCache())
1802
+ sendJson(res, result.ok ? 200 : 400, result)
1803
+ })
1804
+
1805
+ // 附件仓库盘点:列出每个附件、大小、被哪些会话引用,以及谁是孤儿。
1806
+ mount('/attachments', async (req, res) => {
1807
+ const inventory = await attachmentInventory()
1808
+ sendJson(res, inventory.ok ? 200 : 400, inventory)
1809
+ })
1810
+
1811
+ // 把孤儿附件移进回收站。
1812
+ mount('/attachments/clear-orphans', async (req, res) => {
1813
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: '只接受 POST' })
1814
+ const body = await readJsonBody(req)
1815
+ if (body.confirm !== true) return sendJson(res, 400, { ok: false, error: '缺少确认标记' })
1816
+ const result = await withMutationLock(() => clearOrphans())
1817
+ sendJson(res, result.ok ? 200 : 400, result)
1818
+ })
1819
+
1820
+ // 在资源管理器里打开附件仓库(路径固定,不接受参数)。
1821
+ mount('/attachments/open', async (req, res) => {
1822
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: '只接受 POST' })
1823
+ const result = await openAttachmentStore()
1824
+ sendJson(res, result.ok ? 200 : 400, result)
1825
+ })
1826
+
1827
+ // 启动后先跑一次到期清理,之后每 30 分钟一次。
1828
+ const first = setTimeout(() => { withMutationLock(() => sweepExpired()).catch(() => {}) }, 15000)
1829
+ if (first.unref) first.unref()
1830
+ const timer = setInterval(() => { withMutationLock(() => sweepExpired()).catch(() => {}) }, SWEEP_INTERVAL_MS)
1831
+ if (timer.unref) timer.unref()
1832
+ ctx.effect(() => () => {
1833
+ clearTimeout(first)
1834
+ clearInterval(timer)
1835
+ }, 'dsh-recyclebin: sweep timer')
1836
+ }
1837
+
1838
+ // 给离线测试用的出口:这些函数不碰网络,可以直接对临时目录跑。
1839
+ export const internals = {
1840
+ analyze,
1841
+ archiveRecord,
1842
+ attachmentArtifacts,
1843
+ attachmentInventory,
1844
+ attachmentsOf,
1845
+ cacheStats,
1846
+ clearCache,
1847
+ clearOrphans,
1848
+ dshHome,
1849
+ findSessionDirs,
1850
+ forgetRecord,
1851
+ listRecords,
1852
+ openAttachmentStore,
1853
+ probeHome,
1854
+ readRecord,
1855
+ releaseLiveSession,
1856
+ removeSession,
1857
+ restoreSession,
1858
+ sharedAttachmentIds,
1859
+ sweepExpired,
1860
+ writeRecord,
1861
+ }