@240xu/dsh-message-ops 0.10.9 → 0.11.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/README.md +17 -1
- package/package.json +1 -1
- package/src/client.js +646 -1
- package/src/index.js +182 -6
- package/src/session-trash.js +402 -0
- package/test/composer-refill.test.js +2 -2
- package/test/ops-core.test.js +6 -1
- package/test/ops-search.test.js +104 -0
- package/test/session-trash.test.js +179 -0
package/src/index.js
CHANGED
|
@@ -14,6 +14,7 @@ import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqF
|
|
|
14
14
|
restoreProgress, pendingRestoreTurns,
|
|
15
15
|
isTrustedApiRequest, isJsonContentType, webAuthGate,
|
|
16
16
|
} from "./ops-core.js";
|
|
17
|
+
import { deleteSessionToTrash, listTrash, restoreTrash, purgeTrash, resolveSessionTitle } from "./session-trash.js";
|
|
17
18
|
|
|
18
19
|
export const name = "dsh-message-ops";
|
|
19
20
|
// 保持 inject 为空:tools 是可选增强而非硬依赖(cordis 的 inject 是
|
|
@@ -455,8 +456,9 @@ async function loadDerived(logPath) {
|
|
|
455
456
|
return entry.promise;
|
|
456
457
|
}
|
|
457
458
|
|
|
458
|
-
async function opsList(targetCtx, sessionId) {
|
|
459
|
+
async function opsList(targetCtx, sessionId, opts = {}) {
|
|
459
460
|
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
461
|
+
const compact = opts && opts.compact === true;
|
|
460
462
|
const { logPath } = pickSessionDir(sessionId);
|
|
461
463
|
// 文件派生段(读日志 → 消息 → 遮蔽集 → marker 进度 → turn 边界)走缓存:
|
|
462
464
|
// key = logPath、失效看读前 stat 的 mtimeMs+size,见 loadDerived 注释。
|
|
@@ -470,6 +472,8 @@ async function opsList(targetCtx, sessionId) {
|
|
|
470
472
|
applyLiveCommitted(messages, live);
|
|
471
473
|
const visibleNodes = live && live.surface && Array.isArray(live.surface.nodes) ? new Set(live.surface.nodes) : null;
|
|
472
474
|
let visibleCount = 0;
|
|
475
|
+
let shadowedCount = 0;
|
|
476
|
+
let markerCount = 0;
|
|
473
477
|
for (const m of messages) {
|
|
474
478
|
m.visible = visibleNodes ? visibleNodes.has(m.seq) : !shadowed.has(m.seq);
|
|
475
479
|
// 0.9.6:**shadowed 与 visible 是两套语义,不能混用。**
|
|
@@ -484,22 +488,128 @@ async function opsList(targetCtx, sessionId) {
|
|
|
484
488
|
// transcript 藏行必须用它;visible 只留给「可回滚目标」(lastRevertable)。
|
|
485
489
|
m.shadowed = shadowed.has(m.seq);
|
|
486
490
|
if (m.visible) visibleCount++;
|
|
491
|
+
if (m.shadowed) shadowedCount++;
|
|
492
|
+
if (m.marker === true) markerCount++;
|
|
487
493
|
}
|
|
488
494
|
|
|
495
|
+
const visibleMessages = compact
|
|
496
|
+
? messages.map((m) => ({
|
|
497
|
+
seq: m.seq,
|
|
498
|
+
role: m.role,
|
|
499
|
+
snippet: m.snippet,
|
|
500
|
+
time: m.time,
|
|
501
|
+
visible: m.visible,
|
|
502
|
+
shadowed: m.shadowed,
|
|
503
|
+
}))
|
|
504
|
+
: messages;
|
|
505
|
+
|
|
489
506
|
return {
|
|
490
507
|
ok: true,
|
|
491
|
-
session: {
|
|
508
|
+
session: {
|
|
509
|
+
id: header.id,
|
|
510
|
+
createdAt: header.createdAt,
|
|
511
|
+
parentSession: header.parentSession ?? null,
|
|
512
|
+
confirmTitle: resolveSessionTitle(targetCtx, sessionId) || header.id,
|
|
513
|
+
},
|
|
492
514
|
running: isRunning(targetCtx, sessionId),
|
|
493
515
|
runningSource: __runningSource,
|
|
494
516
|
total: messages.length,
|
|
495
517
|
visibleCount,
|
|
518
|
+
shadowedCount,
|
|
519
|
+
markerCount,
|
|
496
520
|
turnEndSeq,
|
|
497
|
-
messages,
|
|
521
|
+
messages: visibleMessages,
|
|
498
522
|
};
|
|
499
523
|
}
|
|
500
524
|
|
|
501
|
-
|
|
502
|
-
|
|
525
|
+
// ---------------------------------------------------------------------------
|
|
526
|
+
// Per-session search (full text, beyond the 160-char snippet)
|
|
527
|
+
// ---------------------------------------------------------------------------
|
|
528
|
+
const SEARCH_CACHE_MAX = 8;
|
|
529
|
+
const searchCache = new Map(); // logPath -> { mtimeMs, size, promise }
|
|
530
|
+
|
|
531
|
+
/** Build the searchable corpus once per log revision (full text, lowercased lazily). */
|
|
532
|
+
async function buildSearchCorpus(logPath) {
|
|
533
|
+
const { events } = await readSessionFileAsync(logPath);
|
|
534
|
+
const messages = listMessages(events);
|
|
535
|
+
const shadowed = computeShadowed(events);
|
|
536
|
+
const bySeq = new Map();
|
|
537
|
+
for (const e of events) if (e && typeof e.seq === "number") bySeq.set(e.seq, e);
|
|
538
|
+
const corpus = [];
|
|
539
|
+
for (const m of messages) {
|
|
540
|
+
const ev = bySeq.get(m.seq);
|
|
541
|
+
const text = ev ? messageTextFull(ev) : "";
|
|
542
|
+
corpus.push({
|
|
543
|
+
seq: m.seq,
|
|
544
|
+
type: m.type,
|
|
545
|
+
role: m.role,
|
|
546
|
+
marker: m.marker === true,
|
|
547
|
+
shadowed: shadowed.has(m.seq),
|
|
548
|
+
text: text || m.snippet || "",
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
return corpus;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
async function loadSearchCorpus(logPath) {
|
|
555
|
+
const st = await statFile(logPath);
|
|
556
|
+
const hit = searchCache.get(logPath);
|
|
557
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
|
|
558
|
+
searchCache.delete(logPath);
|
|
559
|
+
searchCache.set(logPath, hit);
|
|
560
|
+
return hit.promise;
|
|
561
|
+
}
|
|
562
|
+
const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: buildSearchCorpus(logPath) };
|
|
563
|
+
searchCache.delete(logPath);
|
|
564
|
+
searchCache.set(logPath, entry);
|
|
565
|
+
while (searchCache.size > SEARCH_CACHE_MAX) searchCache.delete(searchCache.keys().next().value);
|
|
566
|
+
entry.promise.catch(() => { if (searchCache.get(logPath) === entry) searchCache.delete(logPath); });
|
|
567
|
+
return entry.promise;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function searchSnippet(text, query, radius = 45) {
|
|
571
|
+
const lower = text.toLowerCase();
|
|
572
|
+
const at = lower.indexOf(query);
|
|
573
|
+
const start = at < 0 ? 0 : Math.max(0, at - radius);
|
|
574
|
+
const end = at < 0 ? Math.min(text.length, 160) : Math.min(text.length, at + query.length + radius);
|
|
575
|
+
const raw = text.slice(start, end).replace(/\s+/g, " ").trim();
|
|
576
|
+
return (start > 0 ? "…" : "") + raw.slice(0, 158) + (end < text.length ? "…" : "");
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
async function opsSearch(targetCtx, sessionId, query, opts = {}) {
|
|
580
|
+
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
581
|
+
const q = typeof query === "string" ? query.trim() : "";
|
|
582
|
+
if (q.length === 0) throw new OpsError("query is required", 400);
|
|
583
|
+
if (q.length > 500) throw new OpsError("query too long (max 500)", 400);
|
|
584
|
+
const role = opts && typeof opts.role === "string" && opts.role ? opts.role : null;
|
|
585
|
+
if (role && !["user", "assistant", "system", "tool"].includes(role)) {
|
|
586
|
+
throw new OpsError("invalid role", 400);
|
|
587
|
+
}
|
|
588
|
+
const limit = Number.isSafeInteger(opts && opts.limit) ? Math.max(1, Math.min(100, opts.limit)) : 50;
|
|
589
|
+
const { logPath } = pickSessionDir(sessionId);
|
|
590
|
+
const corpus = await loadSearchCorpus(logPath);
|
|
591
|
+
const needle = q.toLowerCase();
|
|
592
|
+
const results = [];
|
|
593
|
+
let total = 0;
|
|
594
|
+
for (const row of corpus) {
|
|
595
|
+
if (role && row.role !== role) continue;
|
|
596
|
+
if (!row.text.toLowerCase().includes(needle)) continue;
|
|
597
|
+
total++;
|
|
598
|
+
if (results.length >= limit) continue;
|
|
599
|
+
results.push({
|
|
600
|
+
seq: row.seq,
|
|
601
|
+
type: row.type,
|
|
602
|
+
role: row.role,
|
|
603
|
+
marker: row.marker,
|
|
604
|
+
shadowed: row.shadowed,
|
|
605
|
+
snippet: searchSnippet(row.text, needle),
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
return { ok: true, query: q, role, limit, total, truncated: total > results.length, results };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** 测试钩子(非公开 API):直接驱动 list / search 与文件派生缓存。 */
|
|
612
|
+
export const _internals = { opsList, opsSearch, loadDerived, loadSearchCorpus, derivedCache, searchCache };
|
|
503
613
|
|
|
504
614
|
async function opsCommit(targetCtx, mode, sessionId, seq) {
|
|
505
615
|
if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
|
|
@@ -797,13 +907,40 @@ export function apply(ctx) {
|
|
|
797
907
|
if (!(await fence(targetCtx, req, res))) return;
|
|
798
908
|
try {
|
|
799
909
|
const url = new URL(req.url, "http://localhost");
|
|
800
|
-
return sendJson(res, 200, await opsList(targetCtx, url.searchParams.get("sessionId") || ""
|
|
910
|
+
return sendJson(res, 200, await opsList(targetCtx, url.searchParams.get("sessionId") || "", {
|
|
911
|
+
compact: url.searchParams.get("view") === "compact",
|
|
912
|
+
}));
|
|
801
913
|
} catch (err) {
|
|
802
914
|
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
803
915
|
}
|
|
804
916
|
},
|
|
805
917
|
}), "dsh-message-ops: messages route");
|
|
806
918
|
|
|
919
|
+
// --- GET /api/message-ops/search:会话内全文搜索(服务端,匹配 snippet 之外) --
|
|
920
|
+
targetCtx.effect(() => host.register({
|
|
921
|
+
kind: "exact",
|
|
922
|
+
path: "/api/message-ops/search",
|
|
923
|
+
handler: async (req, res) => {
|
|
924
|
+
if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
925
|
+
if (!(await fence(targetCtx, req, res))) return;
|
|
926
|
+
try {
|
|
927
|
+
const url = new URL(req.url, "http://localhost");
|
|
928
|
+
const limitRaw = Number.parseInt(url.searchParams.get("limit") || "", 10);
|
|
929
|
+
return sendJson(res, 200, await opsSearch(
|
|
930
|
+
targetCtx,
|
|
931
|
+
url.searchParams.get("sessionId") || "",
|
|
932
|
+
url.searchParams.get("q") || "",
|
|
933
|
+
{
|
|
934
|
+
role: url.searchParams.get("role") || null,
|
|
935
|
+
limit: Number.isSafeInteger(limitRaw) ? limitRaw : undefined,
|
|
936
|
+
},
|
|
937
|
+
));
|
|
938
|
+
} catch (err) {
|
|
939
|
+
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
940
|
+
}
|
|
941
|
+
},
|
|
942
|
+
}), "dsh-message-ops: search route");
|
|
943
|
+
|
|
807
944
|
// --- GET /api/message-ops/text:单条消息全文(0.5.2 引用按钮按需取) ----------
|
|
808
945
|
// assistant 消息的 fullText 不在 messages 列表里(载荷控制),quote 点击时单取。
|
|
809
946
|
targetCtx.effect(() => host.register({
|
|
@@ -877,6 +1014,45 @@ export function apply(ctx) {
|
|
|
877
1014
|
},
|
|
878
1015
|
}), "dsh-message-ops: restore route");
|
|
879
1016
|
|
|
1017
|
+
// --- Session trash:删除整条会话(可逆),列表 / 恢复 / 永久清理 ----------
|
|
1018
|
+
targetCtx.effect(() => host.register({
|
|
1019
|
+
kind: "exact",
|
|
1020
|
+
path: "/api/message-ops/session/trash",
|
|
1021
|
+
handler: async (req, res) => {
|
|
1022
|
+
if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
1023
|
+
if (!(await fence(targetCtx, req, res))) return;
|
|
1024
|
+
try {
|
|
1025
|
+
return sendJson(res, 200, { ok: true, entries: await listTrash(targetCtx, { purgeExpired: true }) });
|
|
1026
|
+
} catch (err) {
|
|
1027
|
+
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
1028
|
+
}
|
|
1029
|
+
},
|
|
1030
|
+
}), "dsh-message-ops: session trash route");
|
|
1031
|
+
|
|
1032
|
+
const sessionAction = (path, action) => targetCtx.effect(() => host.register({
|
|
1033
|
+
kind: "exact",
|
|
1034
|
+
path,
|
|
1035
|
+
handler: async (req, res) => {
|
|
1036
|
+
if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
1037
|
+
if (!(await writeFence(targetCtx, req, res))) return;
|
|
1038
|
+
const body = await readFencedBody(req, res);
|
|
1039
|
+
if (body === undefined) return;
|
|
1040
|
+
if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
|
|
1041
|
+
try {
|
|
1042
|
+
return sendJson(res, 200, await action(targetCtx, body));
|
|
1043
|
+
} catch (err) {
|
|
1044
|
+
return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
|
|
1045
|
+
}
|
|
1046
|
+
},
|
|
1047
|
+
}), "dsh-message-ops: " + path);
|
|
1048
|
+
|
|
1049
|
+
sessionAction("/api/message-ops/session/delete", (c, b) =>
|
|
1050
|
+
deleteSessionToTrash(c, b.sessionId, b.confirmTitle));
|
|
1051
|
+
sessionAction("/api/message-ops/session/restore", (c, b) =>
|
|
1052
|
+
restoreTrash(c, b.trashId));
|
|
1053
|
+
sessionAction("/api/message-ops/session/purge", (c, b) =>
|
|
1054
|
+
purgeTrash(c, b.trashId));
|
|
1055
|
+
|
|
880
1056
|
}
|
|
881
1057
|
|
|
882
1058
|
const ws = ctx.get("webServer");
|
|
@@ -0,0 +1,402 @@
|
|
|
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 };
|
|
@@ -65,9 +65,9 @@ test('R4:afterWrite 必须传带 session- 前缀的 id 给 openSession', () =>
|
|
|
65
65
|
|
|
66
66
|
test('R2:所有 revert 入口都接了 refillComposer', () => {
|
|
67
67
|
const calls = (src.match(/\brefillComposer\(/g) || []).length
|
|
68
|
-
//
|
|
68
|
+
// 四个回滚入口:runUndo(/undo) + runRevert(AI 时钟) + runUserRevert(悬停) + OpsPanel(A 抽屉)
|
|
69
69
|
// 注意:定义写法是 `refillComposer = (`,不匹配 `refillComposer(`
|
|
70
|
-
assert.equal(calls,
|
|
70
|
+
assert.equal(calls, 4, `refillComposer 调用 ${calls} 处,应为 4 个回滚入口`)
|
|
71
71
|
assert.ok(/var refillComposer = \(/.test(src), '缺 refillComposer 定义')
|
|
72
72
|
// 反例:restore / redo 不该回填(它们是加回内容,不是删)
|
|
73
73
|
const redo = src.match(/var runRedo = \(\) => \{[\s\S]*?\n \}/)
|
package/test/ops-core.test.js
CHANGED
|
@@ -174,7 +174,7 @@ test('apply:无 webServer、无 tools 时走 inject 等待,不抛错', () =>
|
|
|
174
174
|
assert.equal(ctx.registrations.length, 0)
|
|
175
175
|
})
|
|
176
176
|
|
|
177
|
-
test('apply:webServer 存在时注册全部
|
|
177
|
+
test('apply:webServer 存在时注册全部 10 条路由;tools 缺失走 inject 等待', () => {
|
|
178
178
|
const ctx = mockCtx({ webServer: { register: (route) => ctx.registrations.push(route) } })
|
|
179
179
|
assert.doesNotThrow(() => apply(ctx))
|
|
180
180
|
const paths = ctx.registrations.map((r) => r.path).sort()
|
|
@@ -183,6 +183,11 @@ test('apply:webServer 存在时注册全部 5 条路由;tools 缺失走 inje
|
|
|
183
183
|
'/api/message-ops/messages',
|
|
184
184
|
'/api/message-ops/restore',
|
|
185
185
|
'/api/message-ops/revert',
|
|
186
|
+
'/api/message-ops/search',
|
|
187
|
+
'/api/message-ops/session/delete',
|
|
188
|
+
'/api/message-ops/session/purge',
|
|
189
|
+
'/api/message-ops/session/restore',
|
|
190
|
+
'/api/message-ops/session/trash',
|
|
186
191
|
'/api/message-ops/text',
|
|
187
192
|
], '0.9.0:branch/export 路由已移除(改用官方 session/fork 与 /api/session.export)')
|
|
188
193
|
// tools 缺失 → 容错等待而非 fatal
|