dsh-message-actions 0.2.4 → 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 +104 -244
- package/lib/client.js +7307 -4483
- package/lib/http.cjs +37 -1
- package/lib/index.js +625 -83
- package/lib/session-manager.mjs +1164 -0
- package/lib/sessions.cjs +210 -0
- package/lib/shared.cjs +2873 -2357
- package/lib/store.cjs +288 -265
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +5 -2
- package/README.cn.md +0 -289
|
@@ -0,0 +1,1164 @@
|
|
|
1
|
+
// dsh-message-actions — 会话管理(删除到回收站 / 恢复 / 彻底清理 / 归档)。
|
|
2
|
+
//
|
|
3
|
+
// 数据源与写入都走宿主官方服务:
|
|
4
|
+
// - sessionQuery.listSessions / readSession / readTitleSnapshots:枚举与正文;
|
|
5
|
+
// - sessionPersistence.open / create / append / stat:删除与恢复日志;
|
|
6
|
+
// - workspaceRegistry:工作区分组、归档集与成员关系。
|
|
7
|
+
//
|
|
8
|
+
// 删除采用「整目录移入回收站」而不是删文件:恢复时原样移回,宿主无需迁移格式。
|
|
9
|
+
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import fsp from "node:fs/promises";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import zlib from "node:zlib";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import { promisify } from "node:util";
|
|
16
|
+
import pure from "./sessions.cjs";
|
|
17
|
+
|
|
18
|
+
const {
|
|
19
|
+
isSessionId,
|
|
20
|
+
isTrashId,
|
|
21
|
+
isContainedPath,
|
|
22
|
+
sessionDirOf,
|
|
23
|
+
titleTextOf,
|
|
24
|
+
normalizeTrashMeta,
|
|
25
|
+
sortSessionsNewestFirst,
|
|
26
|
+
sortTrashNewestFirst,
|
|
27
|
+
TRASH_META_VERSION,
|
|
28
|
+
MAX_TITLE_LENGTH
|
|
29
|
+
} = pure;
|
|
30
|
+
|
|
31
|
+
const TRASH_DIR_NAME = "dsh-message-actions-trash";
|
|
32
|
+
const TRASH_META_FILE = "meta.json";
|
|
33
|
+
const TRASH_SESSION_DIR = "session";
|
|
34
|
+
const TOMBSTONE_FILE = "purged.json";
|
|
35
|
+
const STAGING_PREFIX = "_staging-";
|
|
36
|
+
const MAX_TOMBSTONES = 500;
|
|
37
|
+
const MAX_BATCH = 50;
|
|
38
|
+
const MAX_TRASH_ENTRIES = 500;
|
|
39
|
+
const TITLE_CACHE_MS = 20000;
|
|
40
|
+
const TITLE_CACHE_MAX = 600;
|
|
41
|
+
const META_CONCURRENCY = 6;
|
|
42
|
+
|
|
43
|
+
/** 结果里区分「已完成」与「需要重启宿主才能看到分组」。 */
|
|
44
|
+
function resultOf(id, patch) {
|
|
45
|
+
return Object.assign({ id, ok: true }, patch || {});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function failureOf(id, code, message) {
|
|
49
|
+
return { id, ok: false, error: code, message: message || code };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function normalizePathKey(value) {
|
|
53
|
+
if (typeof value !== "string" || value === "") return "";
|
|
54
|
+
let key = path.resolve(value);
|
|
55
|
+
if (process.platform === "win32") key = key.toLowerCase();
|
|
56
|
+
return key.replace(/[\\/]+$/, "");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function isDirectory(value) {
|
|
60
|
+
try {
|
|
61
|
+
return fs.statSync(value).isDirectory();
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
// 会话日志读取(回收站校验 / 归档 / 恢复时确认归属)
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
const LOG_NAME_RE = /^session\.v\d+\.jsonl(?:\.zstd)?$/;
|
|
72
|
+
const ZSTD_MAGIC = 0x28b52ffd;
|
|
73
|
+
const zstdDecompressSync = typeof zlib.zstdDecompressSync === "function" ? zlib.zstdDecompressSync : null;
|
|
74
|
+
const zstdDecompress = typeof zlib.zstdDecompress === "function" ? promisify(zlib.zstdDecompress) : null;
|
|
75
|
+
|
|
76
|
+
function isZstdBuffer(buf) {
|
|
77
|
+
return buf.length >= 4 && buf.readUInt32BE(0) === ZSTD_MAGIC;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 扫描 zstd 压缩流里的每个独立帧,返回各自的字节区间。
|
|
82
|
+
*
|
|
83
|
+
* 宿主的会话日志是「多帧拼接」:首帧只压缩一行 header,之后每次追加写入
|
|
84
|
+
* 的新事件各自成帧。Node 的 `zstdDecompress(Sync)` 只解首帧,所以移动日志
|
|
85
|
+
* 时绝不能整段解压再压缩(那样会丢掉首帧之后的所有事件);正确做法是
|
|
86
|
+
* 只重写首帧、原样保留其余字节。
|
|
87
|
+
*
|
|
88
|
+
* 遇到被截断的帧时返回 `tornStart`,由调用方决定按损坏处理。
|
|
89
|
+
*/
|
|
90
|
+
function scanZstdFrames(buf) {
|
|
91
|
+
const frames = [];
|
|
92
|
+
let pos = 0;
|
|
93
|
+
while (pos < buf.length) {
|
|
94
|
+
if (pos + 4 > buf.length || buf.readUInt32BE(pos) !== ZSTD_MAGIC) {
|
|
95
|
+
return { frames, tornStart: pos };
|
|
96
|
+
}
|
|
97
|
+
const start = pos;
|
|
98
|
+
pos += 4;
|
|
99
|
+
if (pos >= buf.length) return { frames, tornStart: start };
|
|
100
|
+
const descriptor = buf[pos];
|
|
101
|
+
pos += 1;
|
|
102
|
+
if ((descriptor & 0x08) !== 0) return { frames, tornStart: start };
|
|
103
|
+
const fcsFlag = descriptor >> 6;
|
|
104
|
+
const singleSegment = (descriptor >> 5) & 1;
|
|
105
|
+
const checksumFlag = (descriptor >> 2) & 1;
|
|
106
|
+
const dictFlag = descriptor & 0x03;
|
|
107
|
+
let cursor = pos;
|
|
108
|
+
if (!singleSegment) {
|
|
109
|
+
if (cursor + 1 > buf.length) return { frames, tornStart: start };
|
|
110
|
+
cursor += 1;
|
|
111
|
+
}
|
|
112
|
+
const dictSize = dictFlag === 0 ? 0 : dictFlag === 1 ? 1 : dictFlag === 2 ? 2 : 4;
|
|
113
|
+
if (cursor + dictSize > buf.length) return { frames, tornStart: start };
|
|
114
|
+
cursor += dictSize;
|
|
115
|
+
const fcsSize = singleSegment ? [1, 2, 4, 8][fcsFlag] : [0, 2, 4, 8][fcsFlag];
|
|
116
|
+
if (cursor + fcsSize > buf.length) return { frames, tornStart: start };
|
|
117
|
+
cursor += fcsSize;
|
|
118
|
+
while (true) {
|
|
119
|
+
if (cursor + 3 > buf.length) return { frames, tornStart: start };
|
|
120
|
+
const blockHeader = buf[cursor] | (buf[cursor + 1] << 8) | (buf[cursor + 2] << 16);
|
|
121
|
+
cursor += 3;
|
|
122
|
+
const lastBlock = blockHeader & 1;
|
|
123
|
+
const blockType = (blockHeader >> 1) & 3;
|
|
124
|
+
const blockSize = blockHeader >> 3;
|
|
125
|
+
if (blockType === 3) return { frames, tornStart: start };
|
|
126
|
+
if (blockType === 1) {
|
|
127
|
+
if (cursor + 1 > buf.length) return { frames, tornStart: start };
|
|
128
|
+
cursor += 1;
|
|
129
|
+
} else {
|
|
130
|
+
if (cursor + blockSize > buf.length) return { frames, tornStart: start };
|
|
131
|
+
cursor += blockSize;
|
|
132
|
+
}
|
|
133
|
+
if (lastBlock) break;
|
|
134
|
+
}
|
|
135
|
+
if (checksumFlag) {
|
|
136
|
+
if (cursor + 4 > buf.length) return { frames, tornStart: start };
|
|
137
|
+
cursor += 4;
|
|
138
|
+
}
|
|
139
|
+
pos = cursor;
|
|
140
|
+
frames.push({ start, end: pos });
|
|
141
|
+
}
|
|
142
|
+
return { frames, tornStart: undefined };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function decompressZstdBuffer(buf) {
|
|
146
|
+
try {
|
|
147
|
+
if (zstdDecompressSync) return zstdDecompressSync(buf);
|
|
148
|
+
if (zstdDecompress) return Buffer.from(await zstdDecompress(buf));
|
|
149
|
+
} catch (err) {
|
|
150
|
+
throw Object.assign(new Error(`could not decode session log: ${err instanceof Error ? err.message : String(err)}`), { code: "LOG_DECODE_FAILED" });
|
|
151
|
+
}
|
|
152
|
+
throw Object.assign(new Error("zstd logs are not supported by this runtime"), { code: "ZSTD_UNAVAILABLE" });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 在会话目录里找日志文件(`session.v4.jsonl.zstd` / 明文测试桩同名文件)。 */
|
|
156
|
+
function findLogFile(dir) {
|
|
157
|
+
let names;
|
|
158
|
+
try {
|
|
159
|
+
names = fs.readdirSync(dir);
|
|
160
|
+
} catch {
|
|
161
|
+
return "";
|
|
162
|
+
}
|
|
163
|
+
const hit = names.find((name) => LOG_NAME_RE.test(name));
|
|
164
|
+
return hit ? path.join(dir, hit) : "";
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function splitLogText(text) {
|
|
168
|
+
const index = text.indexOf("\n");
|
|
169
|
+
if (index === -1) return { firstLine: text, rest: "" };
|
|
170
|
+
return { firstLine: text.slice(0, index), rest: text.slice(index + 1) };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 读取会话日志的「首帧 / 首行」。zstd 日志的首帧只含 header,
|
|
175
|
+
* 这里只解首帧,避免把整个多帧日志读进内存。
|
|
176
|
+
*/
|
|
177
|
+
async function readLogText(dir) {
|
|
178
|
+
const file = findLogFile(dir);
|
|
179
|
+
if (file === "") {
|
|
180
|
+
throw Object.assign(new Error(`session log not found in ${dir}`), { code: "LOG_NOT_FOUND" });
|
|
181
|
+
}
|
|
182
|
+
const buf = await fsp.readFile(file);
|
|
183
|
+
if (!isZstdBuffer(buf)) return { file, compressed: false, text: buf.toString("utf8") };
|
|
184
|
+
const scan = scanZstdFrames(buf);
|
|
185
|
+
if (scan.frames.length === 0) {
|
|
186
|
+
throw Object.assign(new Error(`session log is not a valid Zstandard stream: ${file}`), { code: "LOG_DECODE_FAILED" });
|
|
187
|
+
}
|
|
188
|
+
const first = scan.frames[0];
|
|
189
|
+
const text = (await decompressZstdBuffer(buf.subarray(first.start, first.end))).toString("utf8");
|
|
190
|
+
return { file, compressed: true, text, scan, buf };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 校验目录里的日志首行 header.id 是否就是目标会话(防止误删/误恢复同目录的其他日志)。 */
|
|
194
|
+
async function logBelongsTo(dir, sessionId) {
|
|
195
|
+
try {
|
|
196
|
+
const log = await readLogText(dir);
|
|
197
|
+
const header = JSON.parse(splitLogText(log.text).firstLine);
|
|
198
|
+
return !!header && header.id === sessionId;
|
|
199
|
+
} catch {
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function createSessionManager(ctx, options) {
|
|
205
|
+
const opts = options && typeof options === "object" ? options : {};
|
|
206
|
+
const warn = (message) => {
|
|
207
|
+
if (typeof ctx.logger?.warn === "function") ctx.logger.warn(`[dsh-message-actions] ${message}`);
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
function service(name) {
|
|
211
|
+
try {
|
|
212
|
+
return ctx.get(name);
|
|
213
|
+
} catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const persistence = () => service("sessionPersistence");
|
|
219
|
+
const query = () => {
|
|
220
|
+
const value = service("sessionQuery");
|
|
221
|
+
return value && typeof value.listSessions === "function" ? value : null;
|
|
222
|
+
};
|
|
223
|
+
const registry = () => {
|
|
224
|
+
const value = service("workspaceRegistry");
|
|
225
|
+
return value && typeof value.list === "function" ? value : null;
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
function sessionRoot() {
|
|
229
|
+
const sp = persistence();
|
|
230
|
+
const root = sp && typeof sp.root === "string" ? sp.root : "";
|
|
231
|
+
if (root === "" || !path.isAbsolute(root)) return "";
|
|
232
|
+
return path.resolve(root);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function trashRoot() {
|
|
236
|
+
const root = sessionRoot();
|
|
237
|
+
if (root === "") return "";
|
|
238
|
+
return path.join(path.dirname(root), TRASH_DIR_NAME);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function ensureTrashRoot() {
|
|
242
|
+
const root = trashRoot();
|
|
243
|
+
if (root === "") throw Object.assign(new Error("session persistence is unavailable"), { code: "TRASH_UNAVAILABLE" });
|
|
244
|
+
await fsp.mkdir(root, { recursive: true, mode: 0o700 });
|
|
245
|
+
return root;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// -------------------------------------------------------------------------
|
|
249
|
+
// 已彻底清理的墓碑
|
|
250
|
+
//
|
|
251
|
+
// 物理删除日志后,宿主内存里可能仍持有 live 会话,listSessions 会把它以
|
|
252
|
+
// 「未分组」返回。墓碑记录这些 id:只有磁盘日志确实不存在时才隐藏,
|
|
253
|
+
// 同名会话被重新创建后会自然失效。
|
|
254
|
+
// -------------------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
function tombstonePath() {
|
|
257
|
+
const root = trashRoot();
|
|
258
|
+
return root === "" ? "" : path.join(root, TOMBSTONE_FILE);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function normalizeTombstone(raw) {
|
|
262
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
263
|
+
if (!isSessionId(raw.id)) return null;
|
|
264
|
+
const header = raw.header;
|
|
265
|
+
if (!header || typeof header !== "object" || Array.isArray(header)) return null;
|
|
266
|
+
if (header.id !== raw.id) return null;
|
|
267
|
+
if (typeof header.cwd !== "string" || header.cwd.length > 4096) return null;
|
|
268
|
+
if (!Number.isFinite(raw.purgedAt) || raw.purgedAt <= 0) return null;
|
|
269
|
+
return { id: raw.id, header, purgedAt: Math.trunc(raw.purgedAt) };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async function readTombstones() {
|
|
273
|
+
const file = tombstonePath();
|
|
274
|
+
if (file === "") return [];
|
|
275
|
+
try {
|
|
276
|
+
const raw = JSON.parse(await fsp.readFile(file, "utf8"));
|
|
277
|
+
if (!Array.isArray(raw)) return [];
|
|
278
|
+
const out = [];
|
|
279
|
+
for (const item of raw) {
|
|
280
|
+
const value = normalizeTombstone(item);
|
|
281
|
+
if (value) out.push(value);
|
|
282
|
+
if (out.length >= MAX_TOMBSTONES) break;
|
|
283
|
+
}
|
|
284
|
+
return out;
|
|
285
|
+
} catch {
|
|
286
|
+
return [];
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function writeTombstones(list) {
|
|
291
|
+
const file = tombstonePath();
|
|
292
|
+
if (file === "") return false;
|
|
293
|
+
try {
|
|
294
|
+
await fsp.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
295
|
+
const temp = file + ".tmp";
|
|
296
|
+
await fsp.writeFile(temp, JSON.stringify(list.slice(0, MAX_TOMBSTONES)), { mode: 0o600 });
|
|
297
|
+
await fsp.rename(temp, file);
|
|
298
|
+
return true;
|
|
299
|
+
} catch (err) {
|
|
300
|
+
warn(`could not write purge tombstones: ${err instanceof Error ? err.message : String(err)}`);
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async function addTombstone(header) {
|
|
306
|
+
if (!header || !isSessionId(header.id)) return false;
|
|
307
|
+
const list = (await readTombstones()).filter((item) => item.id !== header.id);
|
|
308
|
+
list.unshift({ id: header.id, header, purgedAt: Date.now() });
|
|
309
|
+
return writeTombstones(list);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function removeTombstone(sessionId) {
|
|
313
|
+
const list = await readTombstones();
|
|
314
|
+
const next = list.filter((item) => item.id !== sessionId);
|
|
315
|
+
if (next.length === list.length) return true;
|
|
316
|
+
return writeTombstones(next);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** 只返回「日志确实不在磁盘上」的墓碑 id,避免误隐藏重建后的同名会话。 */
|
|
320
|
+
async function activePurgedIds(sp, root) {
|
|
321
|
+
const list = await readTombstones();
|
|
322
|
+
const out = [];
|
|
323
|
+
for (const item of list) {
|
|
324
|
+
const dir = locatedDir(sp, item.header, root);
|
|
325
|
+
if (insideRoot(root, dir) && findLogFile(dir) !== "") continue;
|
|
326
|
+
out.push(item.id);
|
|
327
|
+
}
|
|
328
|
+
return out;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// -------------------------------------------------------------------------
|
|
332
|
+
// 工作区
|
|
333
|
+
// -------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
function workspaces() {
|
|
336
|
+
const serviceValue = registry();
|
|
337
|
+
if (!serviceValue) return [];
|
|
338
|
+
let list = [];
|
|
339
|
+
try {
|
|
340
|
+
list = serviceValue.list();
|
|
341
|
+
} catch (err) {
|
|
342
|
+
warn(`workspace list failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
343
|
+
return [];
|
|
344
|
+
}
|
|
345
|
+
const out = [];
|
|
346
|
+
for (const entity of Array.isArray(list) ? list : []) {
|
|
347
|
+
if (!entity || typeof entity.id !== "string" || typeof entity.path !== "string") continue;
|
|
348
|
+
out.push({
|
|
349
|
+
id: entity.id,
|
|
350
|
+
title: typeof entity.title === "string" ? entity.title : entity.path,
|
|
351
|
+
path: entity.path
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
return out;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function workspaceOf(cwd, sessionId, list) {
|
|
358
|
+
const key = normalizePathKey(cwd);
|
|
359
|
+
for (const item of list) {
|
|
360
|
+
if (key !== "" && normalizePathKey(item.path) === key) return item;
|
|
361
|
+
}
|
|
362
|
+
// cwd 被重命名 / 软链接时,按 registry 已记录的成员关系兜底。
|
|
363
|
+
const serviceValue = registry();
|
|
364
|
+
if (serviceValue) {
|
|
365
|
+
for (const item of list) {
|
|
366
|
+
try {
|
|
367
|
+
const entity = serviceValue.get(item.id);
|
|
368
|
+
if (entity && Array.isArray(entity.sessionIds) && entity.sessionIds.includes(sessionId)) return item;
|
|
369
|
+
} catch {
|
|
370
|
+
/* ignore */
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function archivedSet() {
|
|
378
|
+
const serviceValue = registry();
|
|
379
|
+
if (!serviceValue) return new Set();
|
|
380
|
+
try {
|
|
381
|
+
return new Set(Array.isArray(serviceValue.archivedSessionIds) ? serviceValue.archivedSessionIds : []);
|
|
382
|
+
} catch {
|
|
383
|
+
return new Set();
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function runningSet() {
|
|
388
|
+
const running = new Set();
|
|
389
|
+
try {
|
|
390
|
+
const agents = service("agents");
|
|
391
|
+
if (agents && typeof agents.list === "function") {
|
|
392
|
+
for (const agent of agents.list()) {
|
|
393
|
+
if (!agent || agent.status !== "running") continue;
|
|
394
|
+
const id = agent.session && typeof agent.session.id === "string" ? agent.session.id : agent.id;
|
|
395
|
+
if (typeof id === "string") running.add(id);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
} catch {
|
|
399
|
+
/* 运行状态只是装饰 */
|
|
400
|
+
}
|
|
401
|
+
return running;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// -------------------------------------------------------------------------
|
|
405
|
+
// 标题
|
|
406
|
+
// -------------------------------------------------------------------------
|
|
407
|
+
|
|
408
|
+
const titleCache = new Map();
|
|
409
|
+
|
|
410
|
+
function cacheTitle(id, title) {
|
|
411
|
+
if (titleCache.size >= TITLE_CACHE_MAX && !titleCache.has(id)) {
|
|
412
|
+
const oldest = titleCache.keys().next();
|
|
413
|
+
if (!oldest.done) titleCache.delete(oldest.value);
|
|
414
|
+
}
|
|
415
|
+
titleCache.set(id, { at: Date.now(), title });
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function forgetTitle(id) {
|
|
419
|
+
titleCache.delete(id);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async function titlesFor(ids) {
|
|
423
|
+
const out = new Map();
|
|
424
|
+
const missing = [];
|
|
425
|
+
const now = Date.now();
|
|
426
|
+
for (const id of ids) {
|
|
427
|
+
const cached = titleCache.get(id);
|
|
428
|
+
if (cached && now - cached.at < TITLE_CACHE_MS) out.set(id, cached.title);
|
|
429
|
+
else missing.push(id);
|
|
430
|
+
}
|
|
431
|
+
if (missing.length === 0) return out;
|
|
432
|
+
const serviceValue = query();
|
|
433
|
+
if (!serviceValue || typeof serviceValue.readTitleSnapshots !== "function") {
|
|
434
|
+
for (const id of missing) out.set(id, "");
|
|
435
|
+
return out;
|
|
436
|
+
}
|
|
437
|
+
let results;
|
|
438
|
+
try {
|
|
439
|
+
results = await serviceValue.readTitleSnapshots(missing);
|
|
440
|
+
} catch (err) {
|
|
441
|
+
warn(`title lookup failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
442
|
+
for (const id of missing) out.set(id, "");
|
|
443
|
+
return out;
|
|
444
|
+
}
|
|
445
|
+
for (let index = 0; index < missing.length; index += 1) {
|
|
446
|
+
const id = missing[index];
|
|
447
|
+
const outcome = Array.isArray(results) ? results[index] : null;
|
|
448
|
+
const title = outcome && outcome.status === "fulfilled"
|
|
449
|
+
? titleTextOf(outcome.value && outcome.value.title).slice(0, MAX_TITLE_LENGTH)
|
|
450
|
+
: "";
|
|
451
|
+
cacheTitle(id, title);
|
|
452
|
+
out.set(id, title);
|
|
453
|
+
}
|
|
454
|
+
return out;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// -------------------------------------------------------------------------
|
|
458
|
+
// 回收站读取
|
|
459
|
+
// -------------------------------------------------------------------------
|
|
460
|
+
|
|
461
|
+
async function readTrashEntries() {
|
|
462
|
+
const root = trashRoot();
|
|
463
|
+
if (root === "") return [];
|
|
464
|
+
let dirents;
|
|
465
|
+
try {
|
|
466
|
+
dirents = await fsp.readdir(root, { withFileTypes: true });
|
|
467
|
+
} catch (err) {
|
|
468
|
+
if (err && err.code === "ENOENT") return [];
|
|
469
|
+
throw err;
|
|
470
|
+
}
|
|
471
|
+
const entries = [];
|
|
472
|
+
for (const dirent of dirents) {
|
|
473
|
+
if (!dirent.isDirectory() || !isTrashId(dirent.name) || dirent.name.startsWith(STAGING_PREFIX)) continue;
|
|
474
|
+
if (entries.length >= MAX_TRASH_ENTRIES) break;
|
|
475
|
+
const dir = path.join(root, dirent.name);
|
|
476
|
+
if (!isContainedPath(root, dir)) continue;
|
|
477
|
+
try {
|
|
478
|
+
const raw = JSON.parse(await fsp.readFile(path.join(dir, TRASH_META_FILE), "utf8"));
|
|
479
|
+
const meta = normalizeTrashMeta(raw);
|
|
480
|
+
if (!meta || meta.trashId !== dirent.name) {
|
|
481
|
+
warn(`skipping malformed trash entry "${dirent.name}"`);
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
// 新格式是「软回收站」:日志留在原工作区,回收站条目只有 meta.json。
|
|
485
|
+
// 旧格式(物理移入 session/ 子目录)继续兼容。
|
|
486
|
+
const sessionDir = path.join(dir, TRASH_SESSION_DIR);
|
|
487
|
+
const soft = !isDirectory(sessionDir);
|
|
488
|
+
let missing = false;
|
|
489
|
+
if (soft) {
|
|
490
|
+
const sp = persistence();
|
|
491
|
+
const rootPath = sessionRoot();
|
|
492
|
+
const currentDir = sp && rootPath ? locatedDir(sp, meta.header, rootPath) : "";
|
|
493
|
+
missing = !(currentDir !== ""
|
|
494
|
+
&& insideRoot(rootPath, currentDir)
|
|
495
|
+
&& isDirectory(currentDir)
|
|
496
|
+
&& findLogFile(currentDir) !== "");
|
|
497
|
+
}
|
|
498
|
+
entries.push(Object.assign({}, meta, { soft, missing }));
|
|
499
|
+
} catch (err) {
|
|
500
|
+
if (!err || err.code !== "ENOENT") {
|
|
501
|
+
warn(`could not read trash entry "${dirent.name}": ${err instanceof Error ? err.message : String(err)}`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
return sortTrashNewestFirst(entries);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
async function entryFor(trashId) {
|
|
509
|
+
if (!isTrashId(trashId)) return null;
|
|
510
|
+
const root = trashRoot();
|
|
511
|
+
if (root === "") return null;
|
|
512
|
+
const dir = path.join(root, trashId);
|
|
513
|
+
if (!isContainedPath(root, dir)) return null;
|
|
514
|
+
try {
|
|
515
|
+
const raw = JSON.parse(await fsp.readFile(path.join(dir, TRASH_META_FILE), "utf8"));
|
|
516
|
+
const meta = normalizeTrashMeta(raw);
|
|
517
|
+
if (!meta || meta.trashId !== trashId) return null;
|
|
518
|
+
const sessionDir = path.join(dir, TRASH_SESSION_DIR);
|
|
519
|
+
if (!isContainedPath(dir, sessionDir)) return null;
|
|
520
|
+
const soft = !isDirectory(sessionDir);
|
|
521
|
+
return { meta, dir, sessionDir: soft ? "" : sessionDir, soft };
|
|
522
|
+
} catch {
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// -------------------------------------------------------------------------
|
|
528
|
+
// 列表
|
|
529
|
+
// -------------------------------------------------------------------------
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* 补充模型 / 消息数等展示字段。
|
|
533
|
+
* 数据来自宿主的统计服务(内部带 revision 缓存),这里只做并发节流;
|
|
534
|
+
* 任何一条失败都留空,绝不影响列表本身。
|
|
535
|
+
*/
|
|
536
|
+
async function enrichRows(paired) {
|
|
537
|
+
const metaFn = typeof opts.sessionMeta === "function" ? opts.sessionMeta : null;
|
|
538
|
+
if (!metaFn || paired.length === 0) return;
|
|
539
|
+
let cursor = 0;
|
|
540
|
+
const worker = async () => {
|
|
541
|
+
while (cursor < paired.length) {
|
|
542
|
+
const index = cursor;
|
|
543
|
+
cursor += 1;
|
|
544
|
+
const { row, record } = paired[index];
|
|
545
|
+
let meta = null;
|
|
546
|
+
try {
|
|
547
|
+
meta = await metaFn(record);
|
|
548
|
+
} catch {
|
|
549
|
+
meta = null;
|
|
550
|
+
}
|
|
551
|
+
if (!meta) continue;
|
|
552
|
+
if (typeof meta.model === "string" && meta.model !== "") row.model = meta.model;
|
|
553
|
+
if (typeof meta.provider === "string" && meta.provider !== "") row.provider = meta.provider;
|
|
554
|
+
if (Number.isFinite(meta.messages) && meta.messages > 0) row.messages = meta.messages;
|
|
555
|
+
if (Number.isFinite(meta.turns) && meta.turns > 0) row.turns = meta.turns;
|
|
556
|
+
if (Number.isFinite(meta.tokens) && meta.tokens > 0) row.tokens = meta.tokens;
|
|
557
|
+
if (row.title === "" && typeof meta.title === "string" && meta.title !== "") row.title = meta.title;
|
|
558
|
+
if (Number.isFinite(meta.lastActiveAt) && meta.lastActiveAt > row.updatedAt) {
|
|
559
|
+
row.updatedAt = meta.lastActiveAt;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
const size = Math.min(META_CONCURRENCY, paired.length);
|
|
564
|
+
await Promise.all(Array.from({ length: size }, worker));
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* 会话管理快照。
|
|
569
|
+
* `lean` 用于跳过逐条正文统计(只返回工作区与会话基础字段)。
|
|
570
|
+
* 跳过模型、消息数等需要折叠日志的补充字段,避免菜单打开时等待。
|
|
571
|
+
*/
|
|
572
|
+
async function payload(options) {
|
|
573
|
+
const lean = !!(options && options.lean);
|
|
574
|
+
const hiddenOnly = !!(options && options.hiddenOnly);
|
|
575
|
+
const serviceValue = query();
|
|
576
|
+
const sp = persistence();
|
|
577
|
+
const root = sessionRoot();
|
|
578
|
+
const available = serviceValue !== null && sp !== null && root !== "";
|
|
579
|
+
const wsList = workspaces();
|
|
580
|
+
if (!available) {
|
|
581
|
+
return {
|
|
582
|
+
available: false,
|
|
583
|
+
sessions: [],
|
|
584
|
+
workspaces: wsList,
|
|
585
|
+
trash: { count: 0, bytes: 0, entries: [] },
|
|
586
|
+
trashedIds: [],
|
|
587
|
+
purgedIds: [],
|
|
588
|
+
canReset: false
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
// 侧边栏隐藏行只需要两个 id 列表:不枚举会话、不折叠日志。
|
|
592
|
+
if (hiddenOnly) {
|
|
593
|
+
let trashEntries = [];
|
|
594
|
+
let purgedIds = [];
|
|
595
|
+
try {
|
|
596
|
+
trashEntries = await readTrashEntries();
|
|
597
|
+
} catch {
|
|
598
|
+
trashEntries = [];
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
purgedIds = await activePurgedIds(sp, root);
|
|
602
|
+
} catch {
|
|
603
|
+
purgedIds = [];
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
available: true,
|
|
607
|
+
trashedIds: trashEntries.map((entry) => entry.id),
|
|
608
|
+
purgedIds,
|
|
609
|
+
trashCount: trashEntries.length
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
let records = [];
|
|
613
|
+
try {
|
|
614
|
+
records = await serviceValue.listSessions();
|
|
615
|
+
} catch (err) {
|
|
616
|
+
warn(`session list failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
617
|
+
return {
|
|
618
|
+
available: false,
|
|
619
|
+
sessions: [],
|
|
620
|
+
workspaces: wsList,
|
|
621
|
+
trash: { count: 0, bytes: 0, entries: await readTrashEntries().catch(() => []) },
|
|
622
|
+
canReset: false
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
const list = Array.isArray(records) ? records : [];
|
|
626
|
+
// 先读回收站再组装列表:删除后宿主可能仍把 live 会话留在内存里返回,
|
|
627
|
+
// 这些 id 必须从列表里剔掉,否则会以「未分组」形态残留在界面上。
|
|
628
|
+
let trashEntries = [];
|
|
629
|
+
try {
|
|
630
|
+
trashEntries = await readTrashEntries();
|
|
631
|
+
} catch (err) {
|
|
632
|
+
warn(`trash list failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
633
|
+
}
|
|
634
|
+
const trashedIds = new Set(trashEntries.map((entry) => entry.id));
|
|
635
|
+
let purgedIds = [];
|
|
636
|
+
try {
|
|
637
|
+
purgedIds = await activePurgedIds(sp, root);
|
|
638
|
+
} catch {
|
|
639
|
+
purgedIds = [];
|
|
640
|
+
}
|
|
641
|
+
const purgedSet = new Set(purgedIds);
|
|
642
|
+
const ids = [];
|
|
643
|
+
for (const record of list) {
|
|
644
|
+
const id = record && record.header && record.header.id;
|
|
645
|
+
if (typeof id === "string" && isSessionId(id) && !trashedIds.has(id) && !purgedSet.has(id)) ids.push(id);
|
|
646
|
+
}
|
|
647
|
+
const titles = await titlesFor(ids);
|
|
648
|
+
const running = runningSet();
|
|
649
|
+
const archived = archivedSet();
|
|
650
|
+
const rows = [];
|
|
651
|
+
const paired = [];
|
|
652
|
+
for (const record of list) {
|
|
653
|
+
const header = record && record.header;
|
|
654
|
+
if (!header || typeof header.id !== "string") continue;
|
|
655
|
+
const id = header.id;
|
|
656
|
+
if (trashedIds.has(id) || purgedSet.has(id)) continue;
|
|
657
|
+
// 兜底:live 会话目录已被移走(旧版物理回收站)时,宿主内存仍会返回该行。
|
|
658
|
+
// 直接看物理日志是否存在,避免回收站元数据暂时不可读时又落回「未分组」。
|
|
659
|
+
if (record.live === true && findLogFile(locatedDir(sp, header, root)) === "") continue;
|
|
660
|
+
const ws = workspaceOf(header.cwd, id, wsList);
|
|
661
|
+
const createdAt = header.createdAt !== undefined ? header.createdAt : 0;
|
|
662
|
+
const row = {
|
|
663
|
+
id,
|
|
664
|
+
title: titles.get(id) || "",
|
|
665
|
+
cwd: typeof header.cwd === "string" ? header.cwd : "",
|
|
666
|
+
workspaceId: ws ? ws.id : "",
|
|
667
|
+
workspaceTitle: ws ? ws.title : "",
|
|
668
|
+
createdAt,
|
|
669
|
+
updatedAt: createdAt,
|
|
670
|
+
model: "",
|
|
671
|
+
provider: "",
|
|
672
|
+
messages: 0,
|
|
673
|
+
turns: 0,
|
|
674
|
+
tokens: 0,
|
|
675
|
+
live: record.live === true,
|
|
676
|
+
running: running.has(id),
|
|
677
|
+
archived: archived.has(id),
|
|
678
|
+
child: typeof header.parentSession === "string" && header.parentSession !== ""
|
|
679
|
+
};
|
|
680
|
+
rows.push(row);
|
|
681
|
+
paired.push({ row, record });
|
|
682
|
+
}
|
|
683
|
+
if (!lean) await enrichRows(paired);
|
|
684
|
+
const sorted = sortSessionsNewestFirst(rows);
|
|
685
|
+
const trashBytes = trashEntries.reduce((sum, entry) => sum + (Number.isFinite(entry.sizeBytes) ? entry.sizeBytes : 0), 0);
|
|
686
|
+
return {
|
|
687
|
+
available: true,
|
|
688
|
+
sessions: sorted,
|
|
689
|
+
workspaces: wsList,
|
|
690
|
+
trash: {
|
|
691
|
+
count: trashEntries.length,
|
|
692
|
+
bytes: trashBytes,
|
|
693
|
+
entries: trashEntries
|
|
694
|
+
},
|
|
695
|
+
trashedIds: trashEntries.map((entry) => entry.id),
|
|
696
|
+
purgedIds,
|
|
697
|
+
canReset: true
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// -------------------------------------------------------------------------
|
|
702
|
+
// 目录搬移
|
|
703
|
+
// -------------------------------------------------------------------------
|
|
704
|
+
|
|
705
|
+
async function moveDirectory(source, target) {
|
|
706
|
+
try {
|
|
707
|
+
await fsp.rename(source, target);
|
|
708
|
+
return;
|
|
709
|
+
} catch (err) {
|
|
710
|
+
if (!err || err.code !== "EXDEV") throw err;
|
|
711
|
+
}
|
|
712
|
+
await fsp.cp(source, target, { recursive: true, errorOnExist: true, force: false });
|
|
713
|
+
await fsp.rm(source, { recursive: true, force: true });
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* 宿主自己的路径编码入口。移动时必须用它同时算出源 / 目标路径,
|
|
718
|
+
* 否则插件自研的 projectKey 一旦与宿主不同,日志就会写到宿主扫不到的目录。
|
|
719
|
+
*/
|
|
720
|
+
function locateLogPath(sp, header) {
|
|
721
|
+
try {
|
|
722
|
+
if (sp && typeof sp.locate === "function") {
|
|
723
|
+
const located = sp.locate(header);
|
|
724
|
+
if (located && typeof located.path === "string" && located.path !== "") return located.path;
|
|
725
|
+
}
|
|
726
|
+
} catch {
|
|
727
|
+
/* 旧宿主没有 locate:回退到公开的命名约定 */
|
|
728
|
+
}
|
|
729
|
+
return "";
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
function locatedDir(sp, header, fallbackRoot) {
|
|
733
|
+
const logPath = locateLogPath(sp, header);
|
|
734
|
+
if (logPath !== "") return path.dirname(logPath);
|
|
735
|
+
return sessionDirOf(fallbackRoot, header.cwd, header.id);
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
function insideRoot(root, dir) {
|
|
739
|
+
return isContainedPath(root, dir) && normalizePathKey(root) !== normalizePathKey(dir);
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// -------------------------------------------------------------------------
|
|
743
|
+
// 工作区成员同步
|
|
744
|
+
// -------------------------------------------------------------------------
|
|
745
|
+
|
|
746
|
+
async function detachFromWorkspaces(sessionId) {
|
|
747
|
+
const serviceValue = registry();
|
|
748
|
+
if (!serviceValue) return false;
|
|
749
|
+
let touched = false;
|
|
750
|
+
try {
|
|
751
|
+
for (const entity of serviceValue.list()) {
|
|
752
|
+
if (!entity || !Array.isArray(entity.sessionIds) || !entity.sessionIds.includes(sessionId)) continue;
|
|
753
|
+
if (typeof entity.detachSession !== "function") continue;
|
|
754
|
+
try {
|
|
755
|
+
await entity.detachSession(sessionId);
|
|
756
|
+
touched = true;
|
|
757
|
+
} catch {
|
|
758
|
+
/* ignore */
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
} catch {
|
|
762
|
+
/* ignore */
|
|
763
|
+
}
|
|
764
|
+
// 清理宿主内存索引,避免「文件已不在原处、侧边栏仍命中」。
|
|
765
|
+
for (const key of ["sessionPaths", "missingSessionPaths", "headers"]) {
|
|
766
|
+
const map = serviceValue[key];
|
|
767
|
+
if (map && typeof map.delete === "function") {
|
|
768
|
+
try {
|
|
769
|
+
map.delete(sessionId);
|
|
770
|
+
} catch {
|
|
771
|
+
/* ignore */
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return touched;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* 把会话挂到目标工作区。
|
|
780
|
+
*
|
|
781
|
+
* `sessionPaths` 的语义是「会话所属工作区的规范路径」,不是会话日志目录;
|
|
782
|
+
* 宿主的 `entity.sessionIds` 会用 `sessionPaths.get(id) === entity.path`
|
|
783
|
+
* 过滤成员,写错就会让会话从分组里消失、掉进「未分组」。
|
|
784
|
+
*/
|
|
785
|
+
async function attachToWorkspace(sessionId, header, workspacePath) {
|
|
786
|
+
const serviceValue = registry();
|
|
787
|
+
if (!serviceValue) return false;
|
|
788
|
+
const canonical = typeof workspacePath === "string" && workspacePath !== ""
|
|
789
|
+
? workspacePath
|
|
790
|
+
: (header && typeof header.cwd === "string" ? header.cwd : "");
|
|
791
|
+
try {
|
|
792
|
+
if (serviceValue.headers && typeof serviceValue.headers.set === "function") {
|
|
793
|
+
serviceValue.headers.set(sessionId, header);
|
|
794
|
+
}
|
|
795
|
+
if (serviceValue.sessionPaths && typeof serviceValue.sessionPaths.set === "function") {
|
|
796
|
+
serviceValue.sessionPaths.set(sessionId, canonical);
|
|
797
|
+
}
|
|
798
|
+
if (serviceValue.missingSessionPaths && typeof serviceValue.missingSessionPaths.delete === "function") {
|
|
799
|
+
serviceValue.missingSessionPaths.delete(sessionId);
|
|
800
|
+
}
|
|
801
|
+
} catch {
|
|
802
|
+
/* 旧宿主没有这些内部索引:交给重启后的启动索引 */
|
|
803
|
+
}
|
|
804
|
+
const key = normalizePathKey(canonical);
|
|
805
|
+
for (const entity of serviceValue.list()) {
|
|
806
|
+
if (!entity || normalizePathKey(entity.path) !== key) continue;
|
|
807
|
+
if (typeof entity.attachSession !== "function") return false;
|
|
808
|
+
try {
|
|
809
|
+
await entity.attachSession(sessionId);
|
|
810
|
+
} catch (err) {
|
|
811
|
+
warn(`could not attach session "${sessionId}" to workspace: ${err instanceof Error ? err.message : String(err)}`);
|
|
812
|
+
return false;
|
|
813
|
+
}
|
|
814
|
+
// attachSession 在「记录里已存在该 id」时会跳过写入;再用 sessionIds 确认一次。
|
|
815
|
+
const ids = Array.isArray(entity.sessionIds) ? entity.sessionIds : [];
|
|
816
|
+
if (!ids.includes(sessionId)) {
|
|
817
|
+
warn(`workspace "${key}" did not accept session "${sessionId}" after attach`);
|
|
818
|
+
return false;
|
|
819
|
+
}
|
|
820
|
+
return true;
|
|
821
|
+
}
|
|
822
|
+
return false;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* 宿主的工作区索引是启动时扫描建立的。恢复后主动触发它的重建入口,
|
|
827
|
+
* 把 headers / sessionPaths / missingSessionPaths 全部按磁盘现状重算。
|
|
828
|
+
*/
|
|
829
|
+
async function refreshRegistryIndex() {
|
|
830
|
+
const serviceValue = registry();
|
|
831
|
+
if (!serviceValue) return false;
|
|
832
|
+
try {
|
|
833
|
+
if (typeof serviceValue.listStoredHeaders === "function"
|
|
834
|
+
&& typeof serviceValue.replaceHeaderIndex === "function") {
|
|
835
|
+
const headers = await serviceValue.listStoredHeaders();
|
|
836
|
+
await serviceValue.replaceHeaderIndex(headers);
|
|
837
|
+
if (typeof serviceValue.indexLiveSessions === "function") await serviceValue.indexLiveSessions();
|
|
838
|
+
return true;
|
|
839
|
+
}
|
|
840
|
+
} catch (err) {
|
|
841
|
+
warn(`registry index refresh failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
842
|
+
}
|
|
843
|
+
return false;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
async function unarchive(sessionId) {
|
|
847
|
+
const serviceValue = registry();
|
|
848
|
+
if (!serviceValue || typeof serviceValue.unarchiveSession !== "function") return;
|
|
849
|
+
try {
|
|
850
|
+
await serviceValue.unarchiveSession(sessionId);
|
|
851
|
+
} catch {
|
|
852
|
+
/* ignore */
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
function recordOf(records, id) {
|
|
857
|
+
for (const record of Array.isArray(records) ? records : []) {
|
|
858
|
+
if (record && record.header && record.header.id === id) return record;
|
|
859
|
+
}
|
|
860
|
+
return null;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
// -------------------------------------------------------------------------
|
|
864
|
+
// 删除到回收站
|
|
865
|
+
// -------------------------------------------------------------------------
|
|
866
|
+
|
|
867
|
+
async function removeToTrash(ids) {
|
|
868
|
+
const sp = persistence();
|
|
869
|
+
const queryService = query();
|
|
870
|
+
const root = sessionRoot();
|
|
871
|
+
if (!sp || !queryService || root === "") {
|
|
872
|
+
return ids.map((id) => failureOf(id, "TRASH_UNAVAILABLE"));
|
|
873
|
+
}
|
|
874
|
+
const records = await queryService.listSessions().catch((err) => {
|
|
875
|
+
warn(`session list failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
876
|
+
return null;
|
|
877
|
+
});
|
|
878
|
+
if (!records) return ids.map((id) => failureOf(id, "TRASH_UNAVAILABLE"));
|
|
879
|
+
const wsList = workspaces();
|
|
880
|
+
const titles = await titlesFor(ids).catch(() => new Map());
|
|
881
|
+
let trash = "";
|
|
882
|
+
try {
|
|
883
|
+
trash = await ensureTrashRoot();
|
|
884
|
+
} catch (err) {
|
|
885
|
+
warn(`trash root is unavailable: ${err instanceof Error ? err.message : String(err)}`);
|
|
886
|
+
return ids.map((id) => failureOf(id, "TRASH_UNAVAILABLE"));
|
|
887
|
+
}
|
|
888
|
+
const results = [];
|
|
889
|
+
for (const id of ids) {
|
|
890
|
+
if (!isSessionId(id)) {
|
|
891
|
+
results.push(failureOf(id, "INVALID_REQUEST"));
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
const record = recordOf(records, id);
|
|
895
|
+
if (!record) {
|
|
896
|
+
results.push(failureOf(id, "TARGET_NOT_FOUND"));
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
// 只拒绝「正在生成」的会话。仅被宿主打开(live)的会话可以删除:
|
|
900
|
+
// 软回收站只写索引,不碰日志,因此对写句柄完全无影响。
|
|
901
|
+
if (record.running === true || runningSet().has(id)) {
|
|
902
|
+
results.push(failureOf(id, "SESSION_RUNNING"));
|
|
903
|
+
continue;
|
|
904
|
+
}
|
|
905
|
+
let staging = "";
|
|
906
|
+
try {
|
|
907
|
+
const snapshot = await sp.stat(id);
|
|
908
|
+
if (!snapshot || !snapshot.header) {
|
|
909
|
+
results.push(failureOf(id, "TARGET_NOT_FOUND"));
|
|
910
|
+
continue;
|
|
911
|
+
}
|
|
912
|
+
const header = snapshot.header;
|
|
913
|
+
const sourceDir = locatedDir(sp, header, root);
|
|
914
|
+
if (!insideRoot(root, sourceDir) || !isDirectory(sourceDir) || findLogFile(sourceDir) === "") {
|
|
915
|
+
results.push(failureOf(id, "TARGET_NOT_FOUND"));
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
const workspace = workspaceOf(header.cwd, id, wsList) || workspaceOf(record.header.cwd, id, wsList);
|
|
919
|
+
const trashId = "trash-" + Date.now().toString(36) + "-" + randomUUID();
|
|
920
|
+
staging = path.join(trash, trashId);
|
|
921
|
+
if (!isContainedPath(trash, staging)) {
|
|
922
|
+
results.push(failureOf(id, "INTERNAL"));
|
|
923
|
+
continue;
|
|
924
|
+
}
|
|
925
|
+
await fsp.mkdir(staging, { recursive: true, mode: 0o700 });
|
|
926
|
+
const meta = {
|
|
927
|
+
version: TRASH_META_VERSION,
|
|
928
|
+
trashId,
|
|
929
|
+
id,
|
|
930
|
+
deletedAt: Date.now(),
|
|
931
|
+
title: (titles.get(id) || "").slice(0, MAX_TITLE_LENGTH),
|
|
932
|
+
header,
|
|
933
|
+
originalDir: sourceDir,
|
|
934
|
+
sizeBytes: Number.isFinite(snapshot.sizeBytes) ? snapshot.sizeBytes : 0,
|
|
935
|
+
workspaceId: workspace ? workspace.id : "",
|
|
936
|
+
workspaceTitle: workspace ? workspace.title : ""
|
|
937
|
+
};
|
|
938
|
+
const metaPath = path.join(staging, TRASH_META_FILE);
|
|
939
|
+
const tempPath = metaPath + ".tmp";
|
|
940
|
+
await fsp.writeFile(tempPath, JSON.stringify(meta, null, 2), { mode: 0o600 });
|
|
941
|
+
await fsp.rename(tempPath, metaPath);
|
|
942
|
+
// 软回收站:日志留在原工作区目录,不动文件、不解除工作区成员关系。
|
|
943
|
+
// 这样恢复只需删索引,宿主侧栏无需重新挂载即可立刻显示;
|
|
944
|
+
// 也不会因为把文件移出工作区而落入 DSH 的「未分组」。
|
|
945
|
+
await removeTombstone(id);
|
|
946
|
+
forgetTitle(id);
|
|
947
|
+
results.push(resultOf(id, { trashId, soft: true, restartRequired: false }));
|
|
948
|
+
} catch (err) {
|
|
949
|
+
if (staging !== "") await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
|
|
950
|
+
results.push(failureOf(id, "WRITE_FAILED", err instanceof Error ? err.message : String(err)));
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
return results;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// -------------------------------------------------------------------------
|
|
957
|
+
// 恢复
|
|
958
|
+
// -------------------------------------------------------------------------
|
|
959
|
+
|
|
960
|
+
async function restore(trashIds) {
|
|
961
|
+
const sp = persistence();
|
|
962
|
+
const root = sessionRoot();
|
|
963
|
+
if (!sp || root === "") return trashIds.map((id) => failureOf(id, "TRASH_UNAVAILABLE"));
|
|
964
|
+
const results = [];
|
|
965
|
+
for (const trashId of trashIds) {
|
|
966
|
+
const entry = await entryFor(trashId);
|
|
967
|
+
if (!entry) {
|
|
968
|
+
results.push(failureOf(trashId, "TRASH_NOT_FOUND"));
|
|
969
|
+
continue;
|
|
970
|
+
}
|
|
971
|
+
const { meta, dir, sessionDir, soft } = entry;
|
|
972
|
+
const targetDir = locatedDir(sp, meta.header, root);
|
|
973
|
+
if (!insideRoot(root, targetDir)) {
|
|
974
|
+
results.push(failureOf(trashId, "INTERNAL"));
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
// 软回收站:日志从未离开原工作区,恢复 = 删除索引。
|
|
978
|
+
// 不移动文件、不重新挂载工作区,宿主侧栏行当场恢复,无需重启。
|
|
979
|
+
if (soft) {
|
|
980
|
+
if (!isDirectory(targetDir) || findLogFile(targetDir) === "" || !(await logBelongsTo(targetDir, meta.id))) {
|
|
981
|
+
results.push(failureOf(trashId, "TRASH_LOG_MISSING"));
|
|
982
|
+
continue;
|
|
983
|
+
}
|
|
984
|
+
try {
|
|
985
|
+
await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
986
|
+
await removeTombstone(meta.id);
|
|
987
|
+
forgetTitle(meta.id);
|
|
988
|
+
results.push(resultOf(trashId, {
|
|
989
|
+
sessionId: meta.id,
|
|
990
|
+
title: meta.title,
|
|
991
|
+
soft: true,
|
|
992
|
+
restartRequired: false
|
|
993
|
+
}));
|
|
994
|
+
} catch (err) {
|
|
995
|
+
results.push(failureOf(trashId, "WRITE_FAILED", err instanceof Error ? err.message : String(err)));
|
|
996
|
+
}
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
// 旧版物理回收站:日志曾被移到 session/ 子目录,需要移回原工作区并重新挂载。
|
|
1000
|
+
if (fs.existsSync(targetDir)) {
|
|
1001
|
+
results.push(failureOf(trashId, "TRASH_CONFLICT"));
|
|
1002
|
+
continue;
|
|
1003
|
+
}
|
|
1004
|
+
try {
|
|
1005
|
+
await fsp.mkdir(path.dirname(targetDir), { recursive: true, mode: 0o700 });
|
|
1006
|
+
await moveDirectory(sessionDir, targetDir);
|
|
1007
|
+
await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
1008
|
+
await removeTombstone(meta.id);
|
|
1009
|
+
await unarchive(meta.id);
|
|
1010
|
+
const attached = await attachToWorkspace(meta.id, meta.header, meta.header.cwd);
|
|
1011
|
+
if (attached) await refreshRegistryIndex();
|
|
1012
|
+
forgetTitle(meta.id);
|
|
1013
|
+
results.push(resultOf(trashId, {
|
|
1014
|
+
sessionId: meta.id,
|
|
1015
|
+
title: meta.title,
|
|
1016
|
+
soft: false,
|
|
1017
|
+
restartRequired: !attached
|
|
1018
|
+
}));
|
|
1019
|
+
} catch (err) {
|
|
1020
|
+
results.push(failureOf(trashId, "WRITE_FAILED", err instanceof Error ? err.message : String(err)));
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
return results;
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
// -------------------------------------------------------------------------
|
|
1027
|
+
// 彻底清理
|
|
1028
|
+
// -------------------------------------------------------------------------
|
|
1029
|
+
|
|
1030
|
+
async function purge(trashIds, all) {
|
|
1031
|
+
const sp = persistence();
|
|
1032
|
+
const root = trashRoot();
|
|
1033
|
+
const sessionRootPath = sessionRoot();
|
|
1034
|
+
if (root === "") return { results: trashIds.map((id) => failureOf(id, "TRASH_UNAVAILABLE")) };
|
|
1035
|
+
let targets = trashIds;
|
|
1036
|
+
if (all) {
|
|
1037
|
+
try {
|
|
1038
|
+
targets = (await readTrashEntries()).map((entry) => entry.trashId);
|
|
1039
|
+
} catch {
|
|
1040
|
+
targets = [];
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
const running = runningSet();
|
|
1044
|
+
const results = [];
|
|
1045
|
+
for (const trashId of targets) {
|
|
1046
|
+
const entry = await entryFor(trashId);
|
|
1047
|
+
if (!entry) {
|
|
1048
|
+
results.push(failureOf(trashId, "TRASH_NOT_FOUND"));
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
if (!isContainedPath(root, entry.dir)) {
|
|
1052
|
+
results.push(failureOf(trashId, "INTERNAL"));
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
const sessionId = entry.meta.id;
|
|
1056
|
+
if (running.has(sessionId)) {
|
|
1057
|
+
results.push(failureOf(trashId, "SESSION_RUNNING"));
|
|
1058
|
+
continue;
|
|
1059
|
+
}
|
|
1060
|
+
try {
|
|
1061
|
+
if (entry.soft) {
|
|
1062
|
+
const targetDir = sessionRootPath === "" ? "" : locatedDir(sp, entry.meta.header, sessionRootPath);
|
|
1063
|
+
// 只删除能确认属于该会话的目录,绝不动来源不明的路径。
|
|
1064
|
+
if (!insideRoot(sessionRootPath, targetDir) || !(await logBelongsTo(targetDir, sessionId))) {
|
|
1065
|
+
results.push(failureOf(trashId, "TRASH_LOG_MISSING"));
|
|
1066
|
+
continue;
|
|
1067
|
+
}
|
|
1068
|
+
await fsp.rm(targetDir, { recursive: true, force: true });
|
|
1069
|
+
await detachFromWorkspaces(sessionId);
|
|
1070
|
+
await unarchive(sessionId);
|
|
1071
|
+
forgetTitle(sessionId);
|
|
1072
|
+
await addTombstone(entry.meta.header);
|
|
1073
|
+
await fsp.rm(entry.dir, { recursive: true, force: true });
|
|
1074
|
+
} else {
|
|
1075
|
+
await fsp.rm(entry.dir, { recursive: true, force: true });
|
|
1076
|
+
await detachFromWorkspaces(sessionId);
|
|
1077
|
+
await unarchive(sessionId);
|
|
1078
|
+
forgetTitle(sessionId);
|
|
1079
|
+
await addTombstone(entry.meta.header);
|
|
1080
|
+
}
|
|
1081
|
+
results.push(resultOf(trashId, { sessionId, soft: entry.soft }));
|
|
1082
|
+
} catch (err) {
|
|
1083
|
+
results.push(failureOf(trashId, "WRITE_FAILED", err instanceof Error ? err.message : String(err)));
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
return { results };
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
/**
|
|
1090
|
+
* 批量归档:逐条独立执行;已归档的会话视为成功(宿主归档是幂等的)。
|
|
1091
|
+
* 正在生成回复的会话按 SESSION_RUNNING 单独失败,其余继续。
|
|
1092
|
+
*/
|
|
1093
|
+
async function archive(ids) {
|
|
1094
|
+
const serviceValue = registry();
|
|
1095
|
+
if (!serviceValue || typeof serviceValue.archiveSession !== "function") {
|
|
1096
|
+
return { results: ids.map((id) => failureOf(id, "ARCHIVE_UNAVAILABLE")) };
|
|
1097
|
+
}
|
|
1098
|
+
const queryService = query();
|
|
1099
|
+
const records = queryService
|
|
1100
|
+
? await queryService.listSessions().catch((err) => {
|
|
1101
|
+
warn(`session list failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1102
|
+
return null;
|
|
1103
|
+
})
|
|
1104
|
+
: null;
|
|
1105
|
+
const running = runningSet();
|
|
1106
|
+
const results = [];
|
|
1107
|
+
for (const id of ids) {
|
|
1108
|
+
if (!isSessionId(id)) {
|
|
1109
|
+
results.push(failureOf(id, "INVALID_REQUEST"));
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
if (running.has(id)) {
|
|
1113
|
+
results.push(failureOf(id, "SESSION_RUNNING"));
|
|
1114
|
+
continue;
|
|
1115
|
+
}
|
|
1116
|
+
if (!records || !recordOf(records, id)) {
|
|
1117
|
+
results.push(failureOf(id, "TARGET_NOT_FOUND"));
|
|
1118
|
+
continue;
|
|
1119
|
+
}
|
|
1120
|
+
try {
|
|
1121
|
+
await serviceValue.archiveSession(id);
|
|
1122
|
+
forgetTitle(id);
|
|
1123
|
+
results.push(resultOf(id, { sessionId: id }));
|
|
1124
|
+
} catch (err) {
|
|
1125
|
+
const code = err && err.name === "WorkspaceUnknownSessionError"
|
|
1126
|
+
? "TARGET_NOT_FOUND"
|
|
1127
|
+
: err && err.name === "WorkspaceActiveSessionError"
|
|
1128
|
+
? "SESSION_RUNNING"
|
|
1129
|
+
: "WRITE_FAILED";
|
|
1130
|
+
results.push(failureOf(id, code, err instanceof Error ? err.message : String(err)));
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
return { results };
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
// -------------------------------------------------------------------------
|
|
1137
|
+
// 审计清理:移除上次崩溃残留的 _staging-* 目录
|
|
1138
|
+
// -------------------------------------------------------------------------
|
|
1139
|
+
|
|
1140
|
+
async function sweepStaging() {
|
|
1141
|
+
const root = trashRoot();
|
|
1142
|
+
if (root === "") return;
|
|
1143
|
+
try {
|
|
1144
|
+
const dirents = await fsp.readdir(root, { withFileTypes: true });
|
|
1145
|
+
for (const dirent of dirents) {
|
|
1146
|
+
if (!dirent.isDirectory() || !dirent.name.startsWith(STAGING_PREFIX)) continue;
|
|
1147
|
+
const dir = path.join(root, dirent.name);
|
|
1148
|
+
if (!isContainedPath(root, dir)) continue;
|
|
1149
|
+
// 只清理超过一小时的残留,避免多开宿主时删掉另一个实例正在用的暂存目录。
|
|
1150
|
+
try {
|
|
1151
|
+
const info = await fsp.stat(dir);
|
|
1152
|
+
if (Date.now() - info.mtimeMs < 3600000) continue;
|
|
1153
|
+
} catch {
|
|
1154
|
+
continue;
|
|
1155
|
+
}
|
|
1156
|
+
await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
1157
|
+
}
|
|
1158
|
+
} catch {
|
|
1159
|
+
/* 回收站尚未创建 */
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
return { payload, removeToTrash, restore, purge, archive, unarchive, sweepStaging };
|
|
1164
|
+
}
|