dsh-mop 0.2.0 → 0.2.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.
- package/client.js +191 -126
- package/lib/artifacts.mjs +15 -3
- package/lib/clean.mjs +132 -115
- package/lib/errors.mjs +14 -0
- package/lib/guard.mjs +7 -2
- package/lib/routes.mjs +3 -2
- package/lib/session-shell.mjs +9 -11
- package/lib/store.mjs +90 -30
- package/package.json +1 -1
package/lib/store.mjs
CHANGED
|
@@ -10,17 +10,28 @@ import { readdir, readFile, stat, lstat } from 'node:fs/promises';
|
|
|
10
10
|
import { basename as pathBasename, join } from 'node:path';
|
|
11
11
|
import { homedir } from 'node:os';
|
|
12
12
|
import { dshHome } from './home.mjs';
|
|
13
|
-
import {
|
|
13
|
+
import { reject } from './errors.mjs';
|
|
14
|
+
import { isSystemMetadata, SESSION_DIR_RE, SESSION_LOG_RE, EVENT_ONLY_LOG_NAMES, SESSION_LOCK } from './artifacts.mjs';
|
|
14
15
|
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
/** A session still mounted in this instance's memory registry. No public API
|
|
17
|
+
* releases the entry; only a process restart reclaims it. */
|
|
18
|
+
export const isResidentSession = (ctx, id) => !!(ctx.get('sessions')?.get(id) || ctx.get('agents')?.get(id));
|
|
19
|
+
|
|
20
|
+
/** Whether the official registry still tracks the id as archived. */
|
|
21
|
+
export const isArchivedSession = (ctx, id) => (ctx.workspaceRegistry.archivedSessionIds ?? []).includes(id);
|
|
22
|
+
|
|
23
|
+
/** Ids this process purged while their memory entry remained. In-memory only:
|
|
24
|
+
* the plugin keeps no state of its own, and a restart empties both the set
|
|
25
|
+
* and the registry it tracks. */
|
|
26
|
+
const purgedResident = new Set();
|
|
27
|
+
export function markPurgedResident(id) { purgedResident.add(id); }
|
|
17
28
|
|
|
18
29
|
// The official reader distinguishes an event-only v4 log from unsupported
|
|
19
30
|
// formats and other corruption, for both raw and compressed storage.
|
|
20
31
|
export async function isEventOnlyLog(ctx, id, dir) {
|
|
21
32
|
const names = (await readdir(dir)).filter((name) => !isSystemMetadata(name));
|
|
22
|
-
const log = names.find((name) =>
|
|
23
|
-
if (!log || names.some((name) => name !==
|
|
33
|
+
const log = names.find((name) => EVENT_ONLY_LOG_NAMES.includes(name));
|
|
34
|
+
if (!log || names.some((name) => name !== SESSION_LOCK && name !== log)) return false;
|
|
24
35
|
const path = join(dir, log);
|
|
25
36
|
const info = await lstat(path);
|
|
26
37
|
if (!info.isFile() || info.isSymbolicLink()) return false;
|
|
@@ -49,16 +60,40 @@ export function workspaceTable(ctx) {
|
|
|
49
60
|
return table && typeof table.get === 'function' ? table : undefined;
|
|
50
61
|
}
|
|
51
62
|
|
|
63
|
+
/** The official projection-cache table: it owns the in-memory view as well as
|
|
64
|
+
* the file, so deletion must go through it rather than unlink. */
|
|
65
|
+
export function projcacheTable(ctx) {
|
|
66
|
+
const table = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
|
|
67
|
+
return table && typeof table.delete === 'function' ? table : undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Hidden registrations: ids present in the storageDomain record that the
|
|
71
|
+
* official getter (workspace.sessionIds) does not expose. */
|
|
72
|
+
export function hiddenSessionIds(workspace, record) {
|
|
73
|
+
const visible = new Set(workspace.sessionIds ?? []);
|
|
74
|
+
return record.sessionIds.filter((other) => !visible.has(other));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Validated registration record (shape + detachSession callable), or
|
|
78
|
+
* workspace_unavailable. */
|
|
79
|
+
export function registrationRecord(ctx, workspace) {
|
|
80
|
+
const record = workspaceTable(ctx)?.get(workspace.id);
|
|
81
|
+
if (!record || !Array.isArray(record.sessionIds) || typeof workspace.detachSession !== 'function') reject('workspace_unavailable');
|
|
82
|
+
return record;
|
|
83
|
+
}
|
|
84
|
+
|
|
52
85
|
// Size is the sum of regular file contents, never follows symlinks. Unknown
|
|
53
86
|
// entries, access errors or very large trees produce an unknown measurement.
|
|
54
|
-
|
|
87
|
+
// Callers that already readdir'd the directory may pass its Dirent[] to skip
|
|
88
|
+
// the repeated read.
|
|
89
|
+
async function directoryMetrics(path, dirents) {
|
|
55
90
|
let files = 0;
|
|
56
|
-
async function visit(dir) {
|
|
91
|
+
async function visit(dir, entries) {
|
|
57
92
|
const info = await lstat(dir);
|
|
58
93
|
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('not a directory');
|
|
59
94
|
let sizeBytes = 0;
|
|
60
95
|
let mtimeMs = info.mtimeMs;
|
|
61
|
-
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
96
|
+
for (const entry of entries ?? await readdir(dir, { withFileTypes: true })) {
|
|
62
97
|
if (++files > 10000) throw new Error('directory too large to measure');
|
|
63
98
|
const target = join(dir, entry.name);
|
|
64
99
|
if (entry.isDirectory()) {
|
|
@@ -74,7 +109,7 @@ async function directoryMetrics(path) {
|
|
|
74
109
|
}
|
|
75
110
|
return { sizeBytes, mtimeMs };
|
|
76
111
|
}
|
|
77
|
-
try { return await visit(path); } catch { return { sizeBytes: null, mtimeMs: null }; }
|
|
112
|
+
try { return await visit(path, dirents); } catch { return { sizeBytes: null, mtimeMs: null }; }
|
|
78
113
|
}
|
|
79
114
|
|
|
80
115
|
/** 官方 listSessions 条目 → 统一头部(跨形状防御)。 */
|
|
@@ -90,13 +125,15 @@ async function scanDisk() {
|
|
|
90
125
|
const projects = await readdir(root, { withFileTypes: true })
|
|
91
126
|
.then((entries) => entries.filter((e) => e.isDirectory()).map((e) => e.name))
|
|
92
127
|
.catch((error) => { if (error.code === 'ENOENT') return []; throw error; });
|
|
93
|
-
|
|
128
|
+
// Projects (and the session dirs within) are independent; walk them
|
|
129
|
+
// concurrently — results land in shared maps/arrays, order is irrelevant.
|
|
130
|
+
await Promise.all(projects.map(async (project) => {
|
|
94
131
|
const projectDir = join(root, project);
|
|
95
132
|
let entries;
|
|
96
133
|
try {
|
|
97
134
|
entries = await readdir(projectDir, { withFileTypes: true });
|
|
98
135
|
} catch (error) {
|
|
99
|
-
if (error.code === 'ENOENT')
|
|
136
|
+
if (error.code === 'ENOENT') return;
|
|
100
137
|
throw error;
|
|
101
138
|
}
|
|
102
139
|
let sessionCount = 0;
|
|
@@ -104,16 +141,19 @@ async function scanDisk() {
|
|
|
104
141
|
if (!entry.isDirectory() || !SESSION_DIR_RE.test(entry.name)) continue;
|
|
105
142
|
sessionCount += 1;
|
|
106
143
|
const sessionDir = join(projectDir, entry.name);
|
|
107
|
-
|
|
108
|
-
|
|
144
|
+
// 目录在父级 entries 与本次 readdir 之间被删(race):按空残壳记账,
|
|
145
|
+
// 与原串行扫描的语义一致。
|
|
146
|
+
const dirEntries = await readdir(sessionDir, { withFileTypes: true })
|
|
147
|
+
.catch((error) => { if (error.code === 'ENOENT') return []; throw error; });
|
|
148
|
+
const names = dirEntries.map((e) => e.name).filter((name) => !isSystemMetadata(name));
|
|
109
149
|
const logName = names.find((n) => SESSION_LOG_RE.test(n));
|
|
110
150
|
if (!logName) {
|
|
111
151
|
let shellType = names.length === 0 ? 'empty' : 'unknown';
|
|
112
|
-
if (names.length === 1 && names[0] ===
|
|
113
|
-
|
|
114
|
-
if (
|
|
152
|
+
if (names.length === 1 && names[0] === SESSION_LOCK) {
|
|
153
|
+
// Dirent.isFile() is lstat semantics: a symlink is not a file here.
|
|
154
|
+
if (dirEntries.some((e) => e.name === SESSION_LOCK && e.isFile())) shellType = 'lock';
|
|
115
155
|
}
|
|
116
|
-
shellDirs.push({ sessionId: entry.name, sessionDir, shellType, ...await directoryMetrics(sessionDir) });
|
|
156
|
+
shellDirs.push({ sessionId: entry.name, sessionDir, shellType, ...await directoryMetrics(sessionDir, dirEntries) });
|
|
117
157
|
continue;
|
|
118
158
|
}
|
|
119
159
|
const logPath = join(sessionDir, logName);
|
|
@@ -128,11 +168,14 @@ async function scanDisk() {
|
|
|
128
168
|
const info = await stat(projectDir).catch(() => null);
|
|
129
169
|
emptyProjectDirs.push({ path: projectDir, sizeBytes: 0, mtimeMs: info?.mtimeMs ?? null });
|
|
130
170
|
}
|
|
131
|
-
}
|
|
171
|
+
}));
|
|
132
172
|
return { logs, shellDirs, emptyProjectDirs };
|
|
133
173
|
}
|
|
134
174
|
|
|
135
|
-
|
|
175
|
+
/** knownTitles: id → 已从官方 readTitleSnapshots 拿到的标题。文件内容只在
|
|
176
|
+
* 展示需要时读取:orphan 行要 title/cwd,官方标题缺漏时作回退源;其余
|
|
177
|
+
* (绝大多数)只登记路径,避免与官方读侧重复解析同一 JSON。 */
|
|
178
|
+
async function scanProjcache(knownIds, knownTitles) {
|
|
136
179
|
const orphans = [];
|
|
137
180
|
const files = new Map(); // id → 缓存文件路径
|
|
138
181
|
const titles = new Map(); // id → rows.title.val(侧边栏同源标题)
|
|
@@ -142,6 +185,10 @@ async function scanProjcache(knownIds) {
|
|
|
142
185
|
for (const name of names) {
|
|
143
186
|
const id = name.replace(/\.json$/, '');
|
|
144
187
|
const path = join(projcacheDir(), name);
|
|
188
|
+
if (knownIds.has(id) && knownTitles.has(id)) {
|
|
189
|
+
files.set(id, path);
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
145
192
|
let title, cwd;
|
|
146
193
|
try {
|
|
147
194
|
const record = JSON.parse(await readFile(path, 'utf8'))?.record;
|
|
@@ -186,9 +233,8 @@ function filteredWorkspaceRegistrations(ctx, workspaces) {
|
|
|
186
233
|
for (const workspace of workspaces) {
|
|
187
234
|
const record = table.get(workspace.id);
|
|
188
235
|
if (!record || record.path !== workspace.path || !Array.isArray(record.sessionIds)) continue;
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
if (typeof id === 'string' && SESSION_DIR_RE.test(id) && !visible.has(id)) filtered.push({ id, workspace });
|
|
236
|
+
for (const id of hiddenSessionIds(workspace, record)) {
|
|
237
|
+
if (typeof id === 'string' && SESSION_DIR_RE.test(id)) filtered.push({ id, workspace });
|
|
192
238
|
}
|
|
193
239
|
}
|
|
194
240
|
return filtered;
|
|
@@ -277,17 +323,22 @@ export async function buildOverview(ctx, config) {
|
|
|
277
323
|
const diskIds = new Set(disk.logs.keys());
|
|
278
324
|
const sessionIds = new Set([...diskIds, ...listedIds, ...persistedIds].filter(Boolean));
|
|
279
325
|
const knownIds = new Set([...sessionIds, ...disk.shellDirs.map((s) => s.sessionId)]);
|
|
280
|
-
const cache = await scanProjcache(knownIds);
|
|
326
|
+
const cache = await scanProjcache(knownIds, titles);
|
|
281
327
|
|
|
328
|
+
// 官方列表元数据(blank / lastPromptAt)相互独立,并行预取。
|
|
329
|
+
const metadataList = await Promise.all(sessions.map((header) => listMetadataOf(ctx, header)));
|
|
330
|
+
const purgeStateOf = (id) => ({
|
|
331
|
+
purgeBlock: scheduleCheckFailed ? 'reference_check_failed' : scheduleRefs.has(id) ? 'schedule_reference' : null,
|
|
332
|
+
scheduleTasks: scheduleRefs.get(id) ?? [],
|
|
333
|
+
});
|
|
282
334
|
const items = [];
|
|
283
|
-
for (const header of sessions) {
|
|
335
|
+
for (const [index, header] of sessions.entries()) {
|
|
284
336
|
const log = disk.logs.get(header.id);
|
|
285
337
|
const agent = ctx.get('agents')?.get(header.id);
|
|
286
338
|
const live = agent !== undefined && agent.status !== 'idle';
|
|
287
339
|
// 官方查询包含尚未落盘的空白会话;即使无日志也应显示。
|
|
288
340
|
const workspace = registered.get(header.id);
|
|
289
|
-
|
|
290
|
-
const metadata = await listMetadataOf(ctx, header);
|
|
341
|
+
const metadata = metadataList[index];
|
|
291
342
|
items.push({
|
|
292
343
|
id: header.id,
|
|
293
344
|
title: titles.get(header.id) ?? cache.titles.get(header.id) ?? basename(header.cwd) ?? header.id,
|
|
@@ -300,8 +351,7 @@ export async function buildOverview(ctx, config) {
|
|
|
300
351
|
) || null,
|
|
301
352
|
archived: archivedSet.has(header.id),
|
|
302
353
|
protected: protectedWorkspaces.has(workspace?.path ?? header.cwd),
|
|
303
|
-
|
|
304
|
-
scheduleTasks: scheduleRefs.get(header.id) ?? [],
|
|
354
|
+
...purgeStateOf(header.id),
|
|
305
355
|
workspacePath: workspace?.path ?? header.cwd ?? null,
|
|
306
356
|
workspaceTitle: workspace?.title ?? basename(header.cwd) ?? '',
|
|
307
357
|
workspaceCreatedAt: workspace?.createdAt ?? null,
|
|
@@ -311,6 +361,13 @@ export async function buildOverview(ctx, config) {
|
|
|
311
361
|
});
|
|
312
362
|
}
|
|
313
363
|
|
|
364
|
+
// Purged-but-resident entries are deleted, not selectable or restorable:
|
|
365
|
+
// they leave the session lists and reappear below as residue rows.
|
|
366
|
+
const memoryResidentIds = new Set([...purgedResident].filter((id) => isResidentSession(ctx, id)));
|
|
367
|
+
for (let i = items.length - 1; i >= 0; i -= 1) {
|
|
368
|
+
if (memoryResidentIds.has(items[i].id)) items.splice(i, 1);
|
|
369
|
+
}
|
|
370
|
+
|
|
314
371
|
const filteredRegistrations = filteredWorkspaceRegistrations(ctx, workspaces);
|
|
315
372
|
const registrations = new Map();
|
|
316
373
|
for (const workspace of workspaces) {
|
|
@@ -336,8 +393,7 @@ export async function buildOverview(ctx, config) {
|
|
|
336
393
|
items.push({ id, title: cache.titles.get(id) ?? id, cwd: workspace?.path ?? null,
|
|
337
394
|
live: false,
|
|
338
395
|
archived: true, protected: protectedWorkspaces.has(workspace?.path),
|
|
339
|
-
|
|
340
|
-
scheduleTasks: scheduleRefs.get(id) ?? [], workspacePath: workspace?.path ?? null,
|
|
396
|
+
...purgeStateOf(id), workspacePath: workspace?.path ?? null,
|
|
341
397
|
workspaceTitle: workspace?.title ?? '', workspaceCreatedAt: workspace?.createdAt ?? null,
|
|
342
398
|
sizeBytes: null, mtimeMs: null, sessionDir: null });
|
|
343
399
|
}
|
|
@@ -366,6 +422,9 @@ export async function buildOverview(ctx, config) {
|
|
|
366
422
|
const workspace = uniqueRegisteredWorkspace(item.sessionId);
|
|
367
423
|
return { ...item, workspacePath: workspace?.path, workspaceTitle: workspace?.title, workspaceCreatedAt: workspace?.createdAt ?? null };
|
|
368
424
|
});
|
|
425
|
+
const memoryResidents = [...memoryResidentIds].map((id) => ({
|
|
426
|
+
id, title: titles.get(id) ?? cache.titles.get(id) ?? null,
|
|
427
|
+
}));
|
|
369
428
|
return {
|
|
370
429
|
sessions: items,
|
|
371
430
|
residue: {
|
|
@@ -374,6 +433,7 @@ export async function buildOverview(ctx, config) {
|
|
|
374
433
|
ghostRegistrations,
|
|
375
434
|
shellDirs,
|
|
376
435
|
emptyProjectDirs: disk.emptyProjectDirs,
|
|
436
|
+
memoryResidents,
|
|
377
437
|
},
|
|
378
438
|
cacheFiles: cache.files,
|
|
379
439
|
home: homedir(),
|