@240xu/dsh-message-ops 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,402 +0,0 @@
1
- /**
2
- * Reversible session deletion for dsh-message-ops.
3
- *
4
- * A delete is a move, never an unlink:
5
- * ~/.dsh/sessions/<slug>/<id>/ -> ~/.dsh/trash/session-ops/<trashId>/data/<slug>/<id>/
6
- * The projection-cache row and workspace/archive/pin membership are copied into
7
- * manifest.json, then removed from the live storage domains. Restore puts both
8
- * the directory and the metadata back. Purge is the only destructive operation.
9
- *
10
- * This module deliberately has no dependency on the HTTP layer so the contract
11
- * can be tested with a temporary DSH_HOME and an in-memory storageDomain.
12
- */
13
- import fs from "node:fs";
14
- import os from "node:os";
15
- import path from "node:path";
16
- import { randomUUID } from "node:crypto";
17
- import { OpsError, isSessionId, sessionIdVariants, sessionsRoot, readSessionFile } from "./session-file.js";
18
-
19
- export const TRASH_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
20
- const TRASH_ID_RE = /^\d{10,}-[0-9a-f]{8}$/;
21
-
22
- function dshHome() {
23
- return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
24
- }
25
-
26
- export function trashRoot() {
27
- return path.join(dshHome(), "trash", "session-ops");
28
- }
29
-
30
- function cloneJson(value) {
31
- try { return JSON.parse(JSON.stringify(value)); } catch { return null; }
32
- }
33
-
34
- function findAllSessionDirs(sessionId) {
35
- const root = sessionsRoot();
36
- const variants = sessionIdVariants(sessionId);
37
- let slugs = [];
38
- try { slugs = fs.readdirSync(root, { withFileTypes: true }); } catch { return []; }
39
- const found = [];
40
- for (const slug of slugs) {
41
- if (!slug.isDirectory()) continue;
42
- for (const variant of variants) {
43
- const dir = path.join(root, slug.name, variant);
44
- try {
45
- if (fs.statSync(dir).isDirectory() && !found.some((x) => x.dir === dir)) {
46
- found.push({ dir, slug: slug.name, name: variant });
47
- }
48
- } catch { /* keep scanning */ }
49
- }
50
- }
51
- return found;
52
- }
53
-
54
- function storageDomain(ctx) {
55
- try { return ctx && typeof ctx.get === "function" ? ctx.get("storageDomain") : undefined; } catch { return undefined; }
56
- }
57
-
58
- function projectionTable(ctx) {
59
- const sd = storageDomain(ctx);
60
- const domain = sd && typeof sd.get === "function" ? sd.get("session_projcache") : undefined;
61
- if (!domain || typeof domain.table !== "function") return null;
62
- try { return domain.table("sessions"); } catch { return null; }
63
- }
64
-
65
- function workspaceDomain(ctx) {
66
- const sd = storageDomain(ctx);
67
- const domain = sd && typeof sd.get === "function" ? sd.get("workspace") : undefined;
68
- return domain && typeof domain.table === "function" ? domain : null;
69
- }
70
-
71
- function titleOfRow(row) {
72
- const title = row && row.rows && row.rows.title;
73
- if (title && typeof title.val === "string" && title.val.trim()) return title.val.trim();
74
- return null;
75
- }
76
-
77
- function headerTitle(dir) {
78
- try {
79
- const { header } = readSessionFile(path.join(dir, fs.readdirSync(dir).find((f) => /^session(\.v[34])?\.jsonl\.zstd$/.test(f)) || ""));
80
- for (const key of ["title", "name", "displayTitle"]) {
81
- if (header && typeof header[key] === "string" && header[key].trim()) return header[key].trim();
82
- }
83
- if (header && header.session && typeof header.session.title === "string" && header.session.title.trim()) {
84
- return header.session.title.trim();
85
- }
86
- } catch { /* header unreadable: caller decides */ }
87
- return null;
88
- }
89
-
90
- /** Resolve the confirmation text shown by the delete dialog. Prefers the
91
- * projection-cache title; falls back to the log header; untitled sessions
92
- * confirm by their stable session id. */
93
- export function resolveSessionTitle(ctx, sessionId) {
94
- if (!isSessionId(sessionId)) return null;
95
- const meta = readMetadata(ctx, sessionId);
96
- const title = titleOfRow(meta.projRow);
97
- if (title) return title;
98
- const dirs = findAllSessionDirs(sessionId);
99
- if (dirs.length === 1) {
100
- const fromHeader = headerTitle(dirs[0].dir);
101
- if (fromHeader) return fromHeader;
102
- }
103
- return sessionId;
104
- }
105
-
106
- function readMetadata(ctx, sessionId) {
107
- const variants = sessionIdVariants(sessionId);
108
- const projRows = [];
109
- const table = projectionTable(ctx);
110
- if (table && typeof table.get === "function") {
111
- for (const variant of variants) {
112
- let row;
113
- try { row = table.get(variant); } catch { row = undefined; }
114
- if (row !== undefined) {
115
- const copy = cloneJson(row);
116
- if (copy) projRows.push({ key: variant, row: copy });
117
- }
118
- }
119
- }
120
-
121
- const workspaceIds = [];
122
- const archived = [];
123
- const pinned = [];
124
- const ws = workspaceDomain(ctx);
125
- if (ws) {
126
- if (typeof ws.table === "function") {
127
- try {
128
- for (const [wid, rec] of ws.table("workspaces").entries()) {
129
- if (rec && Array.isArray(rec.sessionIds) && rec.sessionIds.some((x) => variants.includes(x))) {
130
- workspaceIds.push(wid);
131
- }
132
- }
133
- } catch { /* unit absent */ }
134
- }
135
- try {
136
- const state = ws.global && typeof ws.global.get === "function" ? ws.global.get() : null;
137
- if (state && Array.isArray(state.archivedSessionIds) && state.archivedSessionIds.some((x) => variants.includes(x))) archived.push(sessionId);
138
- if (state && Array.isArray(state.pinnedSessionIds) && state.pinnedSessionIds.some((x) => variants.includes(x))) pinned.push(sessionId);
139
- } catch { /* no global slot */ }
140
- }
141
-
142
- return {
143
- projRows,
144
- projRow: projRows.length ? projRows[0].row : null,
145
- workspaceIds,
146
- archived: archived.length > 0,
147
- pinned: pinned.length > 0,
148
- };
149
- }
150
-
151
- async function stripMetadata(ctx, sessionId, meta) {
152
- const variants = sessionIdVariants(sessionId);
153
- const table = projectionTable(ctx);
154
- if (table && typeof table.delete === "function") {
155
- const keys = new Set((meta.projRows || []).map((x) => x.key));
156
- for (const variant of variants) keys.add(variant);
157
- for (const key of keys) {
158
- try {
159
- if (typeof table.get !== "function" || table.get(key) !== undefined) await table.delete(key);
160
- } catch { /* domain closed: the manifest still has the row */ }
161
- }
162
- }
163
-
164
- const ws = workspaceDomain(ctx);
165
- if (ws && typeof ws.table === "function") {
166
- try {
167
- const workspaces = ws.table("workspaces");
168
- for (const [wid, rec] of workspaces.entries()) {
169
- if (!rec || !Array.isArray(rec.sessionIds)) continue;
170
- const next = rec.sessionIds.filter((x) => !variants.includes(x));
171
- if (next.length !== rec.sessionIds.length) await workspaces.put(wid, { ...rec, sessionIds: next });
172
- }
173
- } catch { /* unit absent */ }
174
- }
175
- if (ws && ws.global) {
176
- try {
177
- const state = ws.global.get();
178
- if (state && (Array.isArray(state.archivedSessionIds) || Array.isArray(state.pinnedSessionIds))) {
179
- const next = { ...state };
180
- if (Array.isArray(next.archivedSessionIds)) next.archivedSessionIds = next.archivedSessionIds.filter((x) => !variants.includes(x));
181
- if (Array.isArray(next.pinnedSessionIds)) next.pinnedSessionIds = next.pinnedSessionIds.filter((x) => !variants.includes(x));
182
- await ws.global.set(next);
183
- }
184
- } catch { /* no global slot */ }
185
- }
186
- }
187
-
188
- async function restoreMetadata(ctx, sessionId, meta) {
189
- const table = projectionTable(ctx);
190
- if (table && typeof table.put === "function") {
191
- for (const item of meta.projRows || []) {
192
- try { await table.put(item.key, item.row); } catch { /* domain closed */ }
193
- }
194
- }
195
- const ws = workspaceDomain(ctx);
196
- if (ws && typeof ws.table === "function") {
197
- try {
198
- const workspaces = ws.table("workspaces");
199
- for (const wid of meta.workspaceIds || []) {
200
- let rec = typeof workspaces.get === "function" ? workspaces.get(wid) : undefined;
201
- if (!rec && typeof workspaces.entries === "function") {
202
- for (const [key, value] of workspaces.entries()) {
203
- if (key === wid) { rec = value; break; }
204
- }
205
- }
206
- if (!rec || !Array.isArray(rec.sessionIds)) continue;
207
- if (!rec.sessionIds.includes(sessionId)) {
208
- await workspaces.put(wid, { ...rec, sessionIds: rec.sessionIds.concat([sessionId]) });
209
- }
210
- }
211
- } catch { /* unit absent */ }
212
- }
213
- if (ws && ws.global) {
214
- try {
215
- const state = ws.global.get();
216
- if (state) {
217
- const next = { ...state };
218
- if (meta.archived && Array.isArray(next.archivedSessionIds) && !next.archivedSessionIds.includes(sessionId)) {
219
- next.archivedSessionIds = next.archivedSessionIds.concat([sessionId]);
220
- }
221
- if (meta.pinned && Array.isArray(next.pinnedSessionIds) && !next.pinnedSessionIds.includes(sessionId)) {
222
- next.pinnedSessionIds = next.pinnedSessionIds.concat([sessionId]);
223
- }
224
- await ws.global.set(next);
225
- }
226
- } catch { /* no global slot */ }
227
- }
228
- }
229
-
230
- function moveDir(src, dst) {
231
- fs.mkdirSync(path.dirname(dst), { recursive: true });
232
- try {
233
- fs.renameSync(src, dst);
234
- } catch (err) {
235
- if (!err || err.code !== "EXDEV") throw err;
236
- fs.cpSync(src, dst, { recursive: true, errorOnExist: true });
237
- fs.rmSync(src, { recursive: true, force: true });
238
- }
239
- }
240
-
241
- function writeManifest(dir, manifest) {
242
- fs.mkdirSync(dir, { recursive: true });
243
- const tmp = path.join(dir, "manifest.json.tmp");
244
- fs.writeFileSync(tmp, JSON.stringify(manifest, null, 2));
245
- fs.renameSync(tmp, path.join(dir, "manifest.json"));
246
- }
247
-
248
- function assertTrashId(trashId) {
249
- if (typeof trashId !== "string" || !TRASH_ID_RE.test(trashId)) throw new OpsError("invalid trashId", 400);
250
- }
251
-
252
- function readManifest(trashId) {
253
- assertTrashId(trashId);
254
- const file = path.join(trashRoot(), trashId, "manifest.json");
255
- let raw;
256
- try { raw = fs.readFileSync(file, "utf8"); } catch { throw new OpsError("trash entry not found", 404); }
257
- try { return JSON.parse(raw); } catch { throw new OpsError("corrupt trash manifest", 500); }
258
- }
259
-
260
- function agentRunning(ctx, sessionId) {
261
- let agents;
262
- try { agents = ctx && typeof ctx.get === "function" ? ctx.get("agents") : undefined; } catch { return false; }
263
- if (!agents || typeof agents.get !== "function") return false;
264
- for (const variant of sessionIdVariants(sessionId)) {
265
- const agent = agents.get(variant);
266
- if (agent && agent.status === "running") return true;
267
- }
268
- return false;
269
- }
270
-
271
- /**
272
- * Move one session into the trash. Refuses running sessions and mismatched
273
- * confirmation titles; the caller must pass the title shown in the UI.
274
- */
275
- export async function deleteSessionToTrash(ctx, sessionId, confirmTitle) {
276
- if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
277
- const dirs = findAllSessionDirs(sessionId);
278
- if (dirs.length === 0) throw new OpsError("session not found", 404);
279
- if (dirs.length > 1) throw new OpsError(`ambiguous session id: found ${dirs.length} directories`, 409);
280
- if (agentRunning(ctx, sessionId)) throw new OpsError("session is running; stop it first", 409);
281
-
282
- const meta = readMetadata(ctx, sessionId);
283
- const title = titleOfRow(meta.projRow) || headerTitle(dirs[0].dir);
284
- const expected = title || sessionId;
285
- if (String(confirmTitle == null ? "" : confirmTitle).trim() !== expected) {
286
- throw new OpsError(`title mismatch: type "${expected}" to delete`, 400);
287
- }
288
-
289
- const now = Date.now();
290
- const trashId = `${now}-${randomUUID().slice(0, 8)}`;
291
- const root = path.join(trashRoot(), trashId);
292
- const rel = path.relative(sessionsRoot(), dirs[0].dir);
293
- const dataRel = path.join("data", rel);
294
- const manifest = {
295
- version: 1,
296
- trashId,
297
- sessionId,
298
- title: title || null,
299
- state: "moving",
300
- deletedAt: now,
301
- expiresAt: now + TRASH_RETENTION_MS,
302
- dirs: [{ rel, originalSlug: dirs[0].slug, originalName: dirs[0].name }],
303
- ...meta,
304
- };
305
- writeManifest(root, manifest);
306
-
307
- const source = dirs[0].dir;
308
- const target = path.join(root, dataRel);
309
- let moved = false;
310
- try {
311
- moveDir(source, target);
312
- moved = true;
313
- if (findAllSessionDirs(sessionId).length > 0) throw new OpsError("session directory still present after move", 500);
314
- await stripMetadata(ctx, sessionId, meta);
315
- manifest.state = "trashed";
316
- writeManifest(root, manifest);
317
- } catch (err) {
318
- if (moved) {
319
- try {
320
- moveDir(target, source);
321
- await restoreMetadata(ctx, sessionId, meta);
322
- } catch { /* leave the manifest for manual restore */ }
323
- }
324
- try { fs.rmSync(root, { recursive: true, force: true }); } catch { /* best effort */ }
325
- throw err;
326
- }
327
-
328
- return {
329
- ok: true,
330
- trashId,
331
- sessionId,
332
- title: title || null,
333
- expiresAt: manifest.expiresAt,
334
- workspaceIds: meta.workspaceIds,
335
- archived: meta.archived,
336
- pinned: meta.pinned,
337
- };
338
- }
339
-
340
- export async function listTrash(ctx, { purgeExpired = false, now = Date.now() } = {}) {
341
- let names = [];
342
- try { names = fs.readdirSync(trashRoot(), { withFileTypes: true }); } catch { return []; }
343
- const entries = [];
344
- for (const name of names) {
345
- if (!name.isDirectory() || !TRASH_ID_RE.test(name.name)) continue;
346
- let manifest;
347
- try { manifest = readManifest(name.name); } catch { continue; }
348
- if (purgeExpired && typeof manifest.expiresAt === "number" && manifest.expiresAt <= now) {
349
- try { fs.rmSync(path.join(trashRoot(), name.name), { recursive: true, force: true }); } catch { /* retry next time */ }
350
- continue;
351
- }
352
- entries.push({
353
- trashId: name.name,
354
- sessionId: manifest.sessionId,
355
- title: manifest.title || null,
356
- state: manifest.state || "trashed",
357
- deletedAt: manifest.deletedAt || null,
358
- expiresAt: manifest.expiresAt || null,
359
- workspaceIds: Array.isArray(manifest.workspaceIds) ? manifest.workspaceIds : [],
360
- });
361
- }
362
- entries.sort((a, b) => (b.deletedAt || 0) - (a.deletedAt || 0));
363
- return entries;
364
- }
365
-
366
- export async function restoreTrash(ctx, trashId) {
367
- const manifest = readManifest(trashId);
368
- if (!manifest || !Array.isArray(manifest.dirs) || manifest.dirs.length !== 1) {
369
- throw new OpsError("unsupported trash manifest", 500);
370
- }
371
- const rel = manifest.dirs[0].rel;
372
- const target = path.join(sessionsRoot(), rel);
373
- if (fs.existsSync(target)) throw new OpsError("session directory already exists; refusing to overwrite", 409);
374
-
375
- const root = path.join(trashRoot(), trashId);
376
- const source = path.join(root, "data", rel);
377
- if (!fs.existsSync(source)) throw new OpsError("trash payload missing", 404);
378
-
379
- try {
380
- moveDir(source, target);
381
- if (!fs.existsSync(target)) throw new OpsError("restore move failed", 500);
382
- await restoreMetadata(ctx, manifest.sessionId, manifest);
383
- } catch (err) {
384
- try {
385
- if (fs.existsSync(target) && !fs.existsSync(source)) moveDir(target, source);
386
- } catch { /* leave both for manual recovery */ }
387
- throw err;
388
- }
389
-
390
- try { fs.rmSync(root, { recursive: true, force: true }); } catch { /* manifest cleanup is best effort */ }
391
- return { ok: true, trashId, sessionId: manifest.sessionId, title: manifest.title || null };
392
- }
393
-
394
- export async function purgeTrash(ctx, trashId) {
395
- assertTrashId(trashId);
396
- const root = path.join(trashRoot(), trashId);
397
- if (!fs.existsSync(root)) throw new OpsError("trash entry not found", 404);
398
- fs.rmSync(root, { recursive: true, force: true });
399
- return { ok: true, trashId };
400
- }
401
-
402
- export const _internals = { findAllSessionDirs, readMetadata, stripMetadata, restoreMetadata };
@@ -1,104 +0,0 @@
1
- /**
2
- * Compact payload + per-session search contract (TDD).
3
- *
4
- * The panel must not download fullText for every row (190 KB for 543 rows),
5
- * but search must still match text beyond the 160-char list snippet.
6
- */
7
- import test from 'node:test'
8
- import assert from 'node:assert/strict'
9
- import fs from 'node:fs'
10
- import os from 'node:os'
11
- import path from 'node:path'
12
-
13
- import { _internals } from '../src/index.js'
14
- import { encodeSessionFile } from '../src/session-file.js'
15
-
16
- const SID = 'session-33333333-3333-4333-8333-333333333333'
17
-
18
- function setup(t) {
19
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'mops-search-'))
20
- const prev = process.env.DSH_HOME
21
- process.env.DSH_HOME = home
22
- const dir = path.join(home, 'sessions', '--tmp-project--', SID)
23
- fs.mkdirSync(dir, { recursive: true })
24
- const header = { type: 'session', id: SID, version: 4, createdAt: 1790000000000 }
25
- const events = [
26
- {
27
- type: 'user/message', seq: 1, time: 1,
28
- data: { id: 'u1', source: { kind: 'user' }, message: { role: 'user', content: [{ type: 'text', text: 'hello world' }] } },
29
- },
30
- {
31
- type: 'assistant/message', seq: 2, time: 2,
32
- data: { id: 'a1', message: { role: 'assistant', content: [{ type: 'text', text: 'A'.repeat(300) }, { type: 'text', text: 'needle-inside the long answer' }] } },
33
- },
34
- { type: 'tool/call', seq: 3, time: 3, data: { name: 'web_search', callId: 'c1' } },
35
- {
36
- type: 'system/message', seq: 4, time: 4,
37
- surfaceOp: { op: 'replace', startSeq: 2, endSeq: 3 },
38
- data: { id: 'm1', message: { role: 'system', content: [] } },
39
- },
40
- ]
41
- fs.writeFileSync(path.join(dir, 'session.v4.jsonl.zstd'), encodeSessionFile(header, events))
42
-
43
- t.after(() => {
44
- if (prev === undefined) delete process.env.DSH_HOME
45
- else process.env.DSH_HOME = prev
46
- fs.rmSync(home, { recursive: true, force: true })
47
- })
48
- return { ctx: { get: () => undefined } }
49
- }
50
-
51
- test('compact view drops heavy fields but keeps visibility state and counts', async (t) => {
52
- const { ctx } = setup(t)
53
- const full = await _internals.opsList(ctx, SID)
54
- const compact = await _internals.opsList(ctx, SID, { compact: true })
55
-
56
- assert.equal(full.ok, true)
57
- assert.equal(compact.ok, true)
58
- assert.equal(compact.messages.length, 4)
59
- assert.equal(typeof full.messages[0].fullText, 'string')
60
- assert.equal(compact.messages[0].fullText, undefined, 'compact must not carry fullText')
61
- assert.equal(compact.messages[0].turn, undefined, 'compact must not carry turn')
62
- assert.equal(compact.messages[0].step, undefined, 'compact must not carry step')
63
- assert.equal(compact.messages[0].range, undefined, 'compact must not carry range')
64
- assert.equal(compact.messages[0].sourceKind, undefined, 'compact must not carry sourceKind')
65
- assert.equal(compact.messages[0].id, undefined, 'compact must not carry message ids')
66
- assert.equal(compact.messages[0].type, undefined, 'compact must not carry event type')
67
- assert.equal(compact.messages[0].marker, undefined, 'compact must not carry per-row marker flags')
68
- assert.equal(compact.messages[0].restoresSeq, undefined, 'compact must not carry per-row restore pointers')
69
- assert.equal(compact.messages[1].shadowed, true)
70
- assert.equal(compact.messages[2].shadowed, true)
71
- assert.equal(compact.shadowedCount, 2)
72
- assert.equal(compact.markerCount, 1)
73
- assert.equal(compact.visibleCount, 2)
74
- assert.equal(compact.session.confirmTitle, SID, 'untitled sessions confirm by session id')
75
- })
76
-
77
- test('search matches full text beyond the 160-char snippet', async (t) => {
78
- const { ctx } = setup(t)
79
- const result = await _internals.opsSearch(ctx, SID, 'needle-inside')
80
- assert.equal(result.ok, true)
81
- assert.equal(result.total, 1)
82
- assert.equal(result.results[0].seq, 2)
83
- assert.equal(result.results[0].role, 'assistant')
84
- assert.equal(result.results[0].shadowed, true)
85
- assert.ok(result.results[0].snippet.includes('needle-inside'))
86
- assert.ok(result.results[0].snippet.length <= 160)
87
- })
88
-
89
- test('search supports role filtering and limit metadata', async (t) => {
90
- const { ctx } = setup(t)
91
- const assistant = await _internals.opsSearch(ctx, SID, 'needle', { role: 'assistant' })
92
- const user = await _internals.opsSearch(ctx, SID, 'needle', { role: 'user' })
93
- assert.equal(assistant.total, 1)
94
- assert.equal(user.total, 0)
95
- const limited = await _internals.opsSearch(ctx, SID, 'A', { limit: 1 })
96
- assert.equal(limited.results.length, 1)
97
- assert.equal(limited.truncated, true)
98
- })
99
-
100
- test('search rejects empty and overlong queries', async (t) => {
101
- const { ctx } = setup(t)
102
- await assert.rejects(() => _internals.opsSearch(ctx, SID, ' '), (e) => e.status === 400)
103
- await assert.rejects(() => _internals.opsSearch(ctx, SID, 'x'.repeat(501)), (e) => e.status === 400)
104
- })
@@ -1,179 +0,0 @@
1
- /**
2
- * Session trash contract (TDD).
3
- *
4
- * The trash is a reversible move: the session directory is renamed into
5
- * $DSH_HOME/trash/session-ops/<trashId>/data/... and the projection/workspace
6
- * metadata is captured in a manifest before being removed from the live
7
- * domains. Restore must put all of it back; purge must be explicit.
8
- */
9
- import test from 'node:test'
10
- import assert from 'node:assert/strict'
11
- import fs from 'node:fs'
12
- import os from 'node:os'
13
- import path from 'node:path'
14
-
15
- import {
16
- deleteSessionToTrash,
17
- listTrash,
18
- restoreTrash,
19
- purgeTrash,
20
- trashRoot,
21
- } from '../src/session-trash.js'
22
-
23
- const SID = 'session-11111111-1111-4111-8111-111111111111'
24
- const OTHER = 'session-22222222-2222-4222-8222-222222222222'
25
-
26
- function makeCtx({ running = false } = {}) {
27
- const proj = new Map([[SID, {
28
- identity: { createdAt: 1790000000000 },
29
- rows: { title: { val: '会话标题' } },
30
- }]])
31
- const workspaces = {
32
- w1: { path: '/tmp/project', title: '项目', sessionIds: [SID, OTHER] },
33
- w2: { path: '/tmp/other', title: 'Other', sessionIds: [OTHER] },
34
- }
35
- const global = {
36
- initialized: true,
37
- archivedSessionIds: [SID],
38
- pinnedSessionIds: [SID],
39
- }
40
- const projTable = {
41
- get: (k) => proj.get(k),
42
- delete: async (k) => { proj.delete(k) },
43
- put: async (k, v) => { proj.set(k, v) },
44
- entries: () => proj.entries(),
45
- }
46
- const wsTable = {
47
- entries: () => Object.entries(workspaces),
48
- put: async (k, v) => { workspaces[k] = v },
49
- }
50
- const sd = {
51
- get(name) {
52
- if (name === 'session_projcache') return { table: () => projTable }
53
- if (name === 'workspace') return { table: () => wsTable, global: { get: () => global, set: async (v) => Object.assign(global, v) } }
54
- return undefined
55
- },
56
- }
57
- const ctx = {
58
- get(name) {
59
- if (name === 'storageDomain') return sd
60
- if (name === 'agents') return { get: () => (running ? { status: 'running' } : undefined) }
61
- if (name === 'sessions') return { get: () => undefined, flush: async () => {} }
62
- return undefined
63
- },
64
- }
65
- return { ctx, proj, workspaces, global }
66
- }
67
-
68
- function setup(t) {
69
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'mops-trash-'))
70
- const prev = process.env.DSH_HOME
71
- process.env.DSH_HOME = home
72
- const dir = path.join(home, 'sessions', '--tmp-project--', SID)
73
- fs.mkdirSync(dir, { recursive: true })
74
- fs.writeFileSync(path.join(dir, 'session.v4.jsonl.zstd'), 'fake-frame')
75
- const env = makeCtx()
76
- t.after(() => {
77
- if (prev === undefined) delete process.env.DSH_HOME
78
- else process.env.DSH_HOME = prev
79
- fs.rmSync(home, { recursive: true, force: true })
80
- })
81
- return { home, dir, ...env }
82
- }
83
-
84
- test('delete moves the session directory into trash and strips metadata', async (t) => {
85
- const { ctx, dir, proj, workspaces, global } = setup(t)
86
- const result = await deleteSessionToTrash(ctx, SID, '会话标题')
87
-
88
- assert.equal(result.ok, true)
89
- assert.match(result.trashId, /^\d+-[0-9a-f]{8}$/)
90
- assert.equal(fs.existsSync(dir), false, 'source session dir must be moved away')
91
- assert.equal(proj.has(SID), false, 'projection row must be removed')
92
- assert.deepEqual(workspaces.w1.sessionIds, [OTHER], 'workspace membership must be stripped')
93
- assert.deepEqual(global.archivedSessionIds, [], 'archived marker must be stripped')
94
- assert.deepEqual(global.pinnedSessionIds, [], 'pinned marker must be stripped')
95
-
96
- const manifestPath = path.join(trashRoot(), result.trashId, 'manifest.json')
97
- const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
98
- assert.equal(manifest.state, 'trashed')
99
- assert.equal(manifest.sessionId, SID)
100
- assert.equal(manifest.title, '会话标题')
101
- assert.ok(manifest.projRow, 'projection row must be captured for restore')
102
- assert.deepEqual(manifest.workspaceIds, ['w1'])
103
- assert.equal(manifest.archived, true)
104
- assert.equal(manifest.pinned, true)
105
- assert.ok(fs.existsSync(path.join(trashRoot(), result.trashId, 'data', '--tmp-project--', SID, 'session.v4.jsonl.zstd')))
106
-
107
- const entries = await listTrash(ctx)
108
- assert.equal(entries.length, 1)
109
- assert.equal(entries[0].trashId, result.trashId)
110
- assert.equal(entries[0].title, '会话标题')
111
- })
112
-
113
- test('restore puts the directory and all metadata back', async (t) => {
114
- const { ctx, dir, proj, workspaces, global } = setup(t)
115
- const { trashId } = await deleteSessionToTrash(ctx, SID, '会话标题')
116
-
117
- await restoreTrash(ctx, trashId)
118
-
119
- assert.equal(fs.existsSync(path.join(dir, 'session.v4.jsonl.zstd')), true)
120
- assert.equal(proj.has(SID), true)
121
- assert.equal(proj.get(SID).rows.title.val, '会话标题')
122
- assert.ok(workspaces.w1.sessionIds.includes(SID))
123
- assert.ok(global.archivedSessionIds.includes(SID))
124
- assert.ok(global.pinnedSessionIds.includes(SID))
125
- assert.deepEqual(await listTrash(ctx), [])
126
- })
127
-
128
- test('delete refuses a running session', async (t) => {
129
- const { home } = setup(t)
130
- const { ctx } = makeCtx({ running: true })
131
- await assert.rejects(
132
- () => deleteSessionToTrash(ctx, SID, '会话标题'),
133
- (e) => e.status === 409 && /running/i.test(e.message),
134
- )
135
- assert.equal(fs.existsSync(path.join(home, 'sessions', '--tmp-project--', SID)), true)
136
- })
137
-
138
- test('delete requires the exact title', async (t) => {
139
- const { ctx, dir } = setup(t)
140
- await assert.rejects(
141
- () => deleteSessionToTrash(ctx, SID, 'wrong title'),
142
- (e) => e.status === 400 && /title/i.test(e.message),
143
- )
144
- assert.equal(fs.existsSync(dir), true)
145
- })
146
-
147
- test('purge permanently removes a trash entry', async (t) => {
148
- const { ctx } = setup(t)
149
- const { trashId } = await deleteSessionToTrash(ctx, SID, '会话标题')
150
- await purgeTrash(ctx, trashId)
151
- assert.equal(fs.existsSync(path.join(trashRoot(), trashId)), false)
152
- assert.deepEqual(await listTrash(ctx), [])
153
- })
154
-
155
- test('expired trash entries can be swept without touching fresh ones', async (t) => {
156
- const { ctx } = setup(t)
157
- const old = await deleteSessionToTrash(ctx, SID, '会话标题')
158
- const manifestPath = path.join(trashRoot(), old.trashId, 'manifest.json')
159
- const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
160
- manifest.expiresAt = Date.now() - 1000
161
- fs.writeFileSync(manifestPath, JSON.stringify(manifest))
162
-
163
- const entries = await listTrash(ctx, { purgeExpired: true })
164
- assert.deepEqual(entries, [])
165
- assert.equal(fs.existsSync(path.join(trashRoot(), old.trashId)), false)
166
- })
167
-
168
- test('restore refuses to overwrite an existing session directory', async (t) => {
169
- const { ctx, dir } = setup(t)
170
- const { trashId } = await deleteSessionToTrash(ctx, SID, '会话标题')
171
- fs.mkdirSync(dir, { recursive: true })
172
- fs.writeFileSync(path.join(dir, 'session.v4.jsonl.zstd'), 'new-frame')
173
-
174
- await assert.rejects(
175
- () => restoreTrash(ctx, trashId),
176
- (e) => e.status === 409 && /exists/i.test(e.message),
177
- )
178
- assert.equal(fs.readFileSync(path.join(dir, 'session.v4.jsonl.zstd'), 'utf8'), 'new-frame')
179
- })