dsh-mop 0.0.0-stage → 0.1.4
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/LICENSE +21 -0
- package/README.md +43 -2
- package/client.de.js +39 -0
- package/client.en.js +39 -0
- package/client.es.js +39 -0
- package/client.fr.js +39 -0
- package/client.ja.js +39 -0
- package/client.js +997 -0
- package/client.pt.js +39 -0
- package/client.ru.js +39 -0
- package/client.zh.js +39 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +5 -0
- package/index.js +25 -0
- package/lib/artifacts.mjs +47 -0
- package/lib/clean.mjs +313 -0
- package/lib/errors.mjs +6 -0
- package/lib/guard.mjs +20 -0
- package/lib/home.mjs +12 -0
- package/lib/release-session.mjs +30 -0
- package/lib/routes.mjs +139 -0
- package/lib/session-shell.mjs +45 -0
- package/lib/store.mjs +358 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +37 -4
package/lib/routes.mjs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-mop · connection.fetch 路由
|
|
3
|
+
*
|
|
4
|
+
* 认证与 peer 准入由载体层负责(仅 owner peer 可达精确路由)。
|
|
5
|
+
* overview / archive / purge / unarchive / residue 路由。
|
|
6
|
+
*/
|
|
7
|
+
import { buildOverview } from './store.mjs';
|
|
8
|
+
import { purgeSessions, cleanResidue, listResidue } from './clean.mjs';
|
|
9
|
+
|
|
10
|
+
const PREFIX = '/api/dsh-mop';
|
|
11
|
+
|
|
12
|
+
function json(data, status = 200) {
|
|
13
|
+
return new Response(JSON.stringify(data), {
|
|
14
|
+
status,
|
|
15
|
+
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function readJsonBody(request) {
|
|
20
|
+
const text = await request.text();
|
|
21
|
+
if (!text.trim()) return {};
|
|
22
|
+
const data = JSON.parse(text);
|
|
23
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
24
|
+
throw new Error('request body must be a JSON object');
|
|
25
|
+
}
|
|
26
|
+
return data;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sessionIdsOf(body) {
|
|
30
|
+
return Array.isArray(body.sessionIds)
|
|
31
|
+
? body.sessionIds.filter((id) => typeof id === 'string' && id)
|
|
32
|
+
: [];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 注册全部路由(每条路由的注销由 ctx.effect 承载)。 */
|
|
36
|
+
export function registerRoutes(ctx, config) {
|
|
37
|
+
const get = (path, handler) => ctx.effect(() => ctx.connection.fetch.register({
|
|
38
|
+
path: `${PREFIX}.${path}`, methods: ['GET', 'HEAD'], requestBody: 'buffered',
|
|
39
|
+
fetch: async (request) => (request.method === 'HEAD' ? new Response(null, { status: 200 }) : handler(request)),
|
|
40
|
+
}), `dsh-mop: ${PREFIX}.${path}`);
|
|
41
|
+
const post = (path, handler) => ctx.effect(() => ctx.connection.fetch.register({
|
|
42
|
+
path: `${PREFIX}.${path}`, methods: ['POST'], requestBody: 'buffered',
|
|
43
|
+
fetch: async (request) => {
|
|
44
|
+
try { return await handler(await readJsonBody(request)); }
|
|
45
|
+
catch (error) { return json({ error: String(error?.message ?? error) }, 500); }
|
|
46
|
+
},
|
|
47
|
+
}), `dsh-mop: ${PREFIX}.${path}`);
|
|
48
|
+
|
|
49
|
+
get('overview', async () => {
|
|
50
|
+
const overview = await buildOverview(ctx, config);
|
|
51
|
+
const pick = (s) => ({
|
|
52
|
+
id: s.id, title: s.title,
|
|
53
|
+
live: s.live,
|
|
54
|
+
archived: s.archived, protected: s.protected, purgeBlock: s.purgeBlock, scheduleTasks: s.scheduleTasks,
|
|
55
|
+
cwd: s.cwd, workspacePath: s.workspacePath, workspaceTitle: s.workspaceTitle, workspaceCreatedAt: s.workspaceCreatedAt,
|
|
56
|
+
sizeBytes: s.sizeBytes, mtimeMs: s.mtimeMs,
|
|
57
|
+
});
|
|
58
|
+
return json({
|
|
59
|
+
apiVersion: 3,
|
|
60
|
+
sessions: overview.sessions.filter((s) => !s.archived).map(pick),
|
|
61
|
+
recycled: overview.sessions.filter((s) => s.archived).map(pick),
|
|
62
|
+
home: overview.home,
|
|
63
|
+
residue: { items: listResidue(overview) },
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
post('archive', async (body) => {
|
|
68
|
+
const ids = sessionIdsOf(body);
|
|
69
|
+
const stopActivity = body.stopActivity === true;
|
|
70
|
+
if (ids.length === 0) return json({ error: 'sessionIds[] is required' }, 400);
|
|
71
|
+
const overview = await buildOverview(ctx, config);
|
|
72
|
+
const byId = new Map(overview.sessions.map((session) => [session.id, session]));
|
|
73
|
+
const done = [];
|
|
74
|
+
const failed = [];
|
|
75
|
+
for (const id of new Set(ids)) {
|
|
76
|
+
const session = byId.get(id);
|
|
77
|
+
if (!session || session.archived || session.protected) {
|
|
78
|
+
failed.push({ id, code: !session ? 'session_not_found' : session.protected ? 'protected_workspace' : 'already_archived' });
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
await ctx.workspaceRegistry.archiveSession(id, stopActivity ? { stopActivity: true } : {});
|
|
83
|
+
done.push(id);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (error?.name === 'WorkspaceActiveSessionError' && Array.isArray(error.activity)) {
|
|
86
|
+
failed.push({ id, title: session.title, code: 'session_active', activity: error.activity });
|
|
87
|
+
} else {
|
|
88
|
+
failed.push({ id, ...(error?.cleanCode ? { code: error.cleanCode } : { message: String(error?.message ?? error) }) });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return json({ done, failed });
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
post('purge', async (body) => {
|
|
96
|
+
const ids = sessionIdsOf(body);
|
|
97
|
+
if (ids.length === 0) return json({ error: 'sessionIds[] is required' }, 400);
|
|
98
|
+
const overview = await buildOverview(ctx, config);
|
|
99
|
+
return json(await purgeSessions(ctx, overview, ids));
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
post('unarchive', async (body) => {
|
|
103
|
+
const ids = sessionIdsOf(body);
|
|
104
|
+
if (ids.length === 0) return json({ error: 'sessionIds[] is required' }, 400);
|
|
105
|
+
const done = [];
|
|
106
|
+
const failed = [];
|
|
107
|
+
for (const id of ids) {
|
|
108
|
+
try {
|
|
109
|
+
await ctx.workspaceRegistry.unarchiveSession(id);
|
|
110
|
+
done.push(id);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
failed.push({ id, ...(error?.cleanCode ? { code: error.cleanCode } : { message: String(error?.message ?? error) }) });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return json({ done, failed });
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
post('task', async ({ sessionId, id }) => {
|
|
119
|
+
if (typeof sessionId !== 'string' || typeof id !== 'string' || !id) return json({ error: 'sessionId and id are required' }, 400);
|
|
120
|
+
const overview = await buildOverview(ctx, config);
|
|
121
|
+
const session = overview.sessions.find((item) => item.id === sessionId);
|
|
122
|
+
const orphan = (overview.residue.orphanTasks ?? []).some((task) => task.id === id && task.targetSessionId === sessionId);
|
|
123
|
+
if (!session?.scheduleTasks.some((task) => task.id === id) && !orphan) return json({ error: 'dsh-mop:task_not_found' }, 404);
|
|
124
|
+
const schedule = ctx.get('schedule');
|
|
125
|
+
if (!schedule || typeof schedule.view !== 'function') return json({ error: 'dsh-mop:task_unavailable' }, 503);
|
|
126
|
+
const task = await schedule.view({ id });
|
|
127
|
+
if (!task || task.code === 'schedule_not_found') return json({ error: 'dsh-mop:task_not_found' }, 404);
|
|
128
|
+
return json({ task });
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
post('residue', async (body) => {
|
|
132
|
+
const keys = Array.isArray(body.keys) ? body.keys.filter((key) => typeof key === 'string' && key) : [];
|
|
133
|
+
if (keys.length === 0) return json({ error: 'keys[] is required' }, 400);
|
|
134
|
+
const overview = await buildOverview(ctx, config);
|
|
135
|
+
const confirmedTasks = body.confirmedTasks && typeof body.confirmedTasks === 'object' && !Array.isArray(body.confirmedTasks)
|
|
136
|
+
? body.confirmedTasks : {};
|
|
137
|
+
return json(await cleanResidue(ctx, overview, keys, confirmedTasks));
|
|
138
|
+
});
|
|
139
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { lstat, readdir, rmdir, unlink } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { dshHome } from './home.mjs';
|
|
4
|
+
import { assertSessionDirSafe } from './guard.mjs';
|
|
5
|
+
import { assertCanonicalSessionPath, isSystemMetadata, removeEmptyProject } from './artifacts.mjs';
|
|
6
|
+
import { reject } from './errors.mjs';
|
|
7
|
+
|
|
8
|
+
/** Validate and remove a session directory and its recognized files. */
|
|
9
|
+
export async function removeSessionShell(sessionDir, id, { recheck, mode = 'metadata', cleanup = async () => {} }) {
|
|
10
|
+
const target = resolve(sessionDir);
|
|
11
|
+
assertSessionDirSafe(target, id);
|
|
12
|
+
await assertCanonicalSessionPath(dshHome('sessions'), target);
|
|
13
|
+
const names = await readdir(target);
|
|
14
|
+
const allowed = (name) => name === 'session.lock' || isSystemMetadata(name)
|
|
15
|
+
|| (mode === 'event-only' && ['session.v4.jsonl', 'session.v4.jsonl.zstd'].includes(name))
|
|
16
|
+
|| (mode === 'unknown' && !/^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(name));
|
|
17
|
+
if (names.some((name) => !allowed(name))) reject('unknown_artifact');
|
|
18
|
+
const files = [...names.filter((name) => name !== 'session.lock'), ...names.filter((name) => name === 'session.lock')];
|
|
19
|
+
const identities = new Map();
|
|
20
|
+
for (const name of files) {
|
|
21
|
+
const file = await lstat(join(target, name), { bigint: true });
|
|
22
|
+
if (!file.isFile() || file.isSymbolicLink()) reject('unsafe_path');
|
|
23
|
+
identities.set(name, file);
|
|
24
|
+
}
|
|
25
|
+
await recheck();
|
|
26
|
+
const expected = new Set(names);
|
|
27
|
+
const verify = async () => {
|
|
28
|
+
await assertCanonicalSessionPath(dshHome('sessions'), target);
|
|
29
|
+
const entries = await readdir(target);
|
|
30
|
+
if (entries.length !== expected.size || entries.some((name) => !expected.has(name))) reject('session_changed');
|
|
31
|
+
for (const [name, previous] of identities) {
|
|
32
|
+
const file = await lstat(join(target, name), { bigint: true });
|
|
33
|
+
if (!file.isFile() || file.isSymbolicLink() || file.dev !== previous.dev || file.ino !== previous.ino
|
|
34
|
+
|| file.size !== previous.size || file.mtimeNs !== previous.mtimeNs) reject('session_changed');
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
await verify();
|
|
38
|
+
await cleanup();
|
|
39
|
+
await verify();
|
|
40
|
+
for (const name of files) await unlink(join(target, name));
|
|
41
|
+
await rmdir(target);
|
|
42
|
+
try { await removeEmptyProject(dirname(target), dshHome('sessions')); } catch (error) {
|
|
43
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code) && error?.cleanCode !== 'session_changed') throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
package/lib/store.mjs
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-mop · 会话存储索引
|
|
3
|
+
*
|
|
4
|
+
* 会话清单、标题、工作区分组、活跃状态一律走官方服务
|
|
5
|
+
* (sessionQuery / workspaceRegistry / agents);磁盘只补服务不提供的
|
|
6
|
+
* 事实:日志路径与体积、投影缓存孤儿、残壳目录、空项目目录。
|
|
7
|
+
*/
|
|
8
|
+
import { readdir, readFile, stat, lstat } from 'node:fs/promises';
|
|
9
|
+
import { basename as pathBasename, join } from 'node:path';
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
import { dshHome } from './home.mjs';
|
|
12
|
+
import { isSystemMetadata } from './artifacts.mjs';
|
|
13
|
+
|
|
14
|
+
const SESSION_DIR_RE = /^session-[0-9a-zA-Z-]+$/;
|
|
15
|
+
const SESSION_LOG_RE = /^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/;
|
|
16
|
+
|
|
17
|
+
// The official reader distinguishes an event-only v4 log from unsupported
|
|
18
|
+
// formats and other corruption, for both raw and compressed storage.
|
|
19
|
+
export async function isEventOnlyLog(ctx, id, dir) {
|
|
20
|
+
const names = (await readdir(dir)).filter((name) => !isSystemMetadata(name));
|
|
21
|
+
const log = names.find((name) => name === 'session.v4.jsonl' || name === 'session.v4.jsonl.zstd');
|
|
22
|
+
if (!log || names.some((name) => name !== 'session.lock' && name !== log)) return false;
|
|
23
|
+
const path = join(dir, log);
|
|
24
|
+
const info = await lstat(path);
|
|
25
|
+
if (!info.isFile() || info.isSymbolicLink()) return false;
|
|
26
|
+
try {
|
|
27
|
+
const handle = await ctx.sessionPersistence.open(id, 'read');
|
|
28
|
+
await handle.close();
|
|
29
|
+
return false;
|
|
30
|
+
} catch (error) {
|
|
31
|
+
return error?.name === 'SessionPersistenceCorruptionError'
|
|
32
|
+
&& String(error.message).includes('first line is not a session header')
|
|
33
|
+
&& String(error.message).includes(`(raw log: ${path})`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function sessionsRoot() {
|
|
38
|
+
return dshHome('sessions');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function projcacheDir() {
|
|
42
|
+
return dshHome('storages', 'session_projcache', 'sessions');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Size is the sum of regular file contents, never follows symlinks. Unknown
|
|
46
|
+
// entries, access errors or very large trees produce an unknown measurement.
|
|
47
|
+
async function directoryMetrics(path) {
|
|
48
|
+
let files = 0;
|
|
49
|
+
async function visit(dir) {
|
|
50
|
+
const info = await lstat(dir);
|
|
51
|
+
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('not a directory');
|
|
52
|
+
let sizeBytes = 0;
|
|
53
|
+
let mtimeMs = info.mtimeMs;
|
|
54
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
55
|
+
if (++files > 10000) throw new Error('directory too large to measure');
|
|
56
|
+
const target = join(dir, entry.name);
|
|
57
|
+
if (entry.isDirectory()) {
|
|
58
|
+
const child = await visit(target);
|
|
59
|
+
sizeBytes += child.sizeBytes;
|
|
60
|
+
mtimeMs = Math.max(mtimeMs, child.mtimeMs);
|
|
61
|
+
} else if (entry.isFile()) {
|
|
62
|
+
const child = await lstat(target);
|
|
63
|
+
if (!child.isFile()) throw new Error('file changed while measuring');
|
|
64
|
+
sizeBytes += child.size;
|
|
65
|
+
mtimeMs = Math.max(mtimeMs, child.mtimeMs);
|
|
66
|
+
} else throw new Error('unsupported entry');
|
|
67
|
+
}
|
|
68
|
+
return { sizeBytes, mtimeMs };
|
|
69
|
+
}
|
|
70
|
+
try { return await visit(path); } catch { return { sizeBytes: null, mtimeMs: null }; }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 官方 listSessions 条目 → 统一头部(跨形状防御)。 */
|
|
74
|
+
function headerOf(item) {
|
|
75
|
+
return item?.header && typeof item.header.id === 'string' ? item.header : item;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function scanDisk() {
|
|
79
|
+
const root = sessionsRoot();
|
|
80
|
+
const logs = new Map(); // id → {sessionDir, sizeBytes, mtimeMs}
|
|
81
|
+
const shellDirs = [];
|
|
82
|
+
const emptyProjectDirs = [];
|
|
83
|
+
const projects = await readdir(root, { withFileTypes: true })
|
|
84
|
+
.then((entries) => entries.filter((e) => e.isDirectory()).map((e) => e.name))
|
|
85
|
+
.catch((error) => { if (error.code === 'ENOENT') return []; throw error; });
|
|
86
|
+
for (const project of projects) {
|
|
87
|
+
const projectDir = join(root, project);
|
|
88
|
+
let entries;
|
|
89
|
+
try {
|
|
90
|
+
entries = await readdir(projectDir, { withFileTypes: true });
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error.code === 'ENOENT') continue;
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
let sessionCount = 0;
|
|
96
|
+
for (const entry of entries) {
|
|
97
|
+
if (!entry.isDirectory() || !SESSION_DIR_RE.test(entry.name)) continue;
|
|
98
|
+
sessionCount += 1;
|
|
99
|
+
const sessionDir = join(projectDir, entry.name);
|
|
100
|
+
const names = (await readdir(sessionDir).catch((error) => { if (error.code === 'ENOENT') return []; throw error; }))
|
|
101
|
+
.filter((name) => !isSystemMetadata(name));
|
|
102
|
+
const logName = names.find((n) => SESSION_LOG_RE.test(n));
|
|
103
|
+
if (!logName) {
|
|
104
|
+
let shellType = names.length === 0 ? 'empty' : 'unknown';
|
|
105
|
+
if (names.length === 1 && names[0] === 'session.lock') {
|
|
106
|
+
const lock = await lstat(join(sessionDir, 'session.lock')).catch(() => null);
|
|
107
|
+
if (lock?.isFile() && !lock.isSymbolicLink()) shellType = 'lock';
|
|
108
|
+
}
|
|
109
|
+
shellDirs.push({ sessionId: entry.name, sessionDir, shellType, ...await directoryMetrics(sessionDir) });
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const logPath = join(sessionDir, logName);
|
|
113
|
+
const info = await stat(logPath).catch(() => undefined);
|
|
114
|
+
logs.set(entry.name, {
|
|
115
|
+
sessionDir,
|
|
116
|
+
sizeBytes: info?.size ?? null,
|
|
117
|
+
mtimeMs: info?.mtimeMs ?? null,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
if (sessionCount === 0 && entries.every((entry) => entry.isFile() && isSystemMetadata(entry.name))) {
|
|
121
|
+
const info = await stat(projectDir).catch(() => null);
|
|
122
|
+
emptyProjectDirs.push({ path: projectDir, sizeBytes: 0, mtimeMs: info?.mtimeMs ?? null });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return { logs, shellDirs, emptyProjectDirs };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function scanProjcache(knownIds) {
|
|
129
|
+
const orphans = [];
|
|
130
|
+
const files = new Map(); // id → 缓存文件路径
|
|
131
|
+
const titles = new Map(); // id → rows.title.val(侧边栏同源标题)
|
|
132
|
+
const names = await readdir(projcacheDir(), { withFileTypes: true })
|
|
133
|
+
.then((entries) => entries.filter((e) => e.isFile() && e.name.endsWith('.json')).map((e) => e.name))
|
|
134
|
+
.catch(() => []);
|
|
135
|
+
for (const name of names) {
|
|
136
|
+
const id = name.replace(/\.json$/, '');
|
|
137
|
+
const path = join(projcacheDir(), name);
|
|
138
|
+
let title, cwd;
|
|
139
|
+
try {
|
|
140
|
+
const record = JSON.parse(await readFile(path, 'utf8'))?.record;
|
|
141
|
+
title = record?.rows?.title?.val;
|
|
142
|
+
cwd = record?.identity?.cwd;
|
|
143
|
+
} catch { /* 无标题也可清理 */ }
|
|
144
|
+
if (typeof title === 'string' && title) titles.set(id, title);
|
|
145
|
+
files.set(id, path);
|
|
146
|
+
if (!knownIds.has(id)) {
|
|
147
|
+
const info = await stat(path).catch(() => null);
|
|
148
|
+
orphans.push({ id, title: typeof title === 'string' ? title : undefined, cwd: typeof cwd === 'string' && cwd ? cwd : undefined,
|
|
149
|
+
sizeBytes: info?.size ?? null, mtimeMs: info?.mtimeMs ?? null });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { orphans, files, titles };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** DSH rc.5's workspace getter hides filtered candidates. Read its JSON
|
|
156
|
+
* snapshot only to display those registrations; never mutate this file. */
|
|
157
|
+
async function filteredWorkspaceRegistrations(workspaces) {
|
|
158
|
+
let snapshot;
|
|
159
|
+
try { snapshot = JSON.parse(await readFile(dshHome('storages', 'workspace.json'), 'utf8')); }
|
|
160
|
+
catch { return []; }
|
|
161
|
+
if (snapshot?.unit?.name !== 'workspace' || snapshot.unit.version !== 2) return [];
|
|
162
|
+
const records = snapshot?.tables?.workspaces;
|
|
163
|
+
if (!records || typeof records !== 'object' || Array.isArray(records)) return [];
|
|
164
|
+
const filtered = [];
|
|
165
|
+
for (const workspace of workspaces) {
|
|
166
|
+
const stored = records[workspace.id];
|
|
167
|
+
if (!stored || stored.path !== workspace.path || !Array.isArray(stored.sessionIds)) continue;
|
|
168
|
+
const visible = new Set(workspace.sessionIds ?? []);
|
|
169
|
+
for (const id of stored.sessionIds) {
|
|
170
|
+
if (typeof id === 'string' && SESSION_DIR_RE.test(id) && !visible.has(id)) filtered.push({ id, workspace });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return filtered;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 建全量索引。
|
|
178
|
+
*/
|
|
179
|
+
export async function buildOverview(ctx, config) {
|
|
180
|
+
const [listed, workspaces, archivedIds, disk, persistence] = await Promise.all([
|
|
181
|
+
ctx.sessionQuery.listSessions(),
|
|
182
|
+
ctx.workspaceRegistry.list(),
|
|
183
|
+
Promise.resolve(ctx.workspaceRegistry.archivedSessionIds ?? []),
|
|
184
|
+
scanDisk(),
|
|
185
|
+
ctx.sessionPersistence.list(),
|
|
186
|
+
]);
|
|
187
|
+
|
|
188
|
+
const sessions = (Array.isArray(listed) ? listed : []).map(headerOf).filter(Boolean);
|
|
189
|
+
const listedIds = new Set(sessions.map((header) => header.id));
|
|
190
|
+
const sizeById = new Map();
|
|
191
|
+
for (const snapshot of persistence) {
|
|
192
|
+
const header = headerOf(snapshot);
|
|
193
|
+
if (header && typeof header.id === 'string' && typeof snapshot.sizeBytes === 'number') {
|
|
194
|
+
sizeById.set(header.id, snapshot.sizeBytes);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const titles = new Map();
|
|
199
|
+
try {
|
|
200
|
+
// 官方返回 result 包装数组:{status:'fulfilled', value:{session, title?}}
|
|
201
|
+
const snapshots = await ctx.sessionQuery.readTitleSnapshots(sessions.map((h) => h.id));
|
|
202
|
+
for (const result of Array.isArray(snapshots) ? snapshots : []) {
|
|
203
|
+
if (result?.status !== 'fulfilled') continue;
|
|
204
|
+
const value = result.value;
|
|
205
|
+
if (value?.session?.id && typeof value.title === 'string' && value.title) {
|
|
206
|
+
titles.set(value.session.id, value.title);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
} catch { /* 标题缺失时退化 */ }
|
|
210
|
+
|
|
211
|
+
// 工作区分组与注册事实
|
|
212
|
+
const registered = new Map(); // sessionId → workspace entity
|
|
213
|
+
for (const workspace of workspaces) {
|
|
214
|
+
for (const sid of workspace.sessionIds ?? []) registered.set(sid, workspace);
|
|
215
|
+
}
|
|
216
|
+
const archivedSet = new Set(archivedIds);
|
|
217
|
+
const protectedWorkspaces = new Set(config.protectWorkspaces ?? []);
|
|
218
|
+
// Schedule catalog entries are durable references, including paused tasks.
|
|
219
|
+
// A completed session reference/fork is a copied snapshot, not such a link.
|
|
220
|
+
const scheduleRefs = new Map();
|
|
221
|
+
let scheduleCheckFailed = false;
|
|
222
|
+
let scheduleCatalog = [];
|
|
223
|
+
const schedule = ctx.get('schedule');
|
|
224
|
+
if (schedule) {
|
|
225
|
+
try {
|
|
226
|
+
const catalog = await schedule.catalog();
|
|
227
|
+
if (!Array.isArray(catalog)) throw new Error('invalid schedule catalog');
|
|
228
|
+
scheduleCatalog = catalog;
|
|
229
|
+
for (const task of catalog) {
|
|
230
|
+
const ids = new Set(task.involvedSessionIds ?? []);
|
|
231
|
+
if (task.target?.kind !== 'new' && typeof task.target?.sessionId === 'string') ids.add(task.target.sessionId);
|
|
232
|
+
if (typeof task.lastDelivery?.targetSessionId === 'string') ids.add(task.lastDelivery.targetSessionId);
|
|
233
|
+
for (const id of ids) {
|
|
234
|
+
if (typeof id !== 'string') continue;
|
|
235
|
+
if (!scheduleRefs.has(id)) scheduleRefs.set(id, []);
|
|
236
|
+
scheduleRefs.get(id).push({ id: task.id, title: task.title || task.id, status: task.status });
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
} catch { scheduleCheckFailed = true; scheduleCatalog = []; }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 投影缓存扫描(标题回退源 + 残留判定基线)
|
|
243
|
+
const persistedIds = new Set(persistence.map((s) => headerOf(s)?.id).filter(Boolean));
|
|
244
|
+
for (const [id, log] of disk.logs) {
|
|
245
|
+
if (persistedIds.has(id)) continue;
|
|
246
|
+
if (await isEventOnlyLog(ctx, id, log.sessionDir).catch(() => false)) {
|
|
247
|
+
disk.logs.delete(id);
|
|
248
|
+
disk.shellDirs.push({ sessionId: id, sessionDir: log.sessionDir, shellType: 'log', ...await directoryMetrics(log.sessionDir) });
|
|
249
|
+
} else if (!listedIds.has(id)) {
|
|
250
|
+
// Keep unrecognized and future formats visible without making them
|
|
251
|
+
// eligible for deletion.
|
|
252
|
+
disk.logs.delete(id);
|
|
253
|
+
disk.shellDirs.push({ sessionId: id, sessionDir: log.sessionDir, shellType: 'unknown', ...await directoryMetrics(log.sessionDir) });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const diskIds = new Set(disk.logs.keys());
|
|
257
|
+
const sessionIds = new Set([...diskIds, ...listedIds, ...persistedIds].filter(Boolean));
|
|
258
|
+
const knownIds = new Set([...sessionIds, ...disk.shellDirs.map((s) => s.sessionId)]);
|
|
259
|
+
const cache = await scanProjcache(knownIds);
|
|
260
|
+
|
|
261
|
+
const items = [];
|
|
262
|
+
for (const header of sessions) {
|
|
263
|
+
const log = disk.logs.get(header.id);
|
|
264
|
+
const agent = ctx.get('agents')?.get(header.id);
|
|
265
|
+
const live = agent !== undefined && agent.status !== 'idle';
|
|
266
|
+
// 官方查询包含尚未落盘的空白会话;即使无日志也应显示。
|
|
267
|
+
const workspace = registered.get(header.id);
|
|
268
|
+
items.push({
|
|
269
|
+
id: header.id,
|
|
270
|
+
title: titles.get(header.id) ?? cache.titles.get(header.id) ?? basename(header.cwd) ?? header.id,
|
|
271
|
+
cwd: header.cwd ?? null,
|
|
272
|
+
live,
|
|
273
|
+
archived: archivedSet.has(header.id),
|
|
274
|
+
protected: protectedWorkspaces.has(workspace?.path ?? header.cwd),
|
|
275
|
+
purgeBlock: scheduleCheckFailed ? 'reference_check_failed' : scheduleRefs.has(header.id) ? 'schedule_reference' : null,
|
|
276
|
+
scheduleTasks: scheduleRefs.get(header.id) ?? [],
|
|
277
|
+
workspacePath: workspace?.path ?? header.cwd ?? null,
|
|
278
|
+
workspaceTitle: workspace?.title ?? basename(header.cwd) ?? '',
|
|
279
|
+
workspaceCreatedAt: workspace?.createdAt ?? null,
|
|
280
|
+
sizeBytes: sizeById.get(header.id) ?? log?.sizeBytes ?? null,
|
|
281
|
+
mtimeMs: log?.mtimeMs ?? null,
|
|
282
|
+
sessionDir: log?.sessionDir ?? null,
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const filteredRegistrations = await filteredWorkspaceRegistrations(workspaces);
|
|
287
|
+
const registrations = new Map();
|
|
288
|
+
for (const workspace of workspaces) {
|
|
289
|
+
for (const id of workspace.sessionIds ?? []) registrations.set(`${workspace.id}:${id}`, { id, workspace });
|
|
290
|
+
}
|
|
291
|
+
for (const entry of filteredRegistrations) registrations.set(`${entry.workspace.id}:${entry.id}`, entry);
|
|
292
|
+
const registrationsBySession = new Map();
|
|
293
|
+
for (const { id, workspace } of registrations.values()) {
|
|
294
|
+
if (!registrationsBySession.has(id)) registrationsBySession.set(id, new Map());
|
|
295
|
+
registrationsBySession.get(id).set(workspace.id, workspace);
|
|
296
|
+
}
|
|
297
|
+
const uniqueRegisteredWorkspace = (id) => {
|
|
298
|
+
const matches = registrationsBySession.get(id);
|
|
299
|
+
return matches?.size === 1 ? matches.values().next().value : undefined;
|
|
300
|
+
};
|
|
301
|
+
// Preserve archived IDs after an interrupted purge, even when the log has
|
|
302
|
+
// already gone. This also exposes pre-existing stale archive entries.
|
|
303
|
+
const itemIds = new Set(items.map((item) => item.id));
|
|
304
|
+
const recoverableShellIds = new Set(disk.shellDirs.filter((item) => ['empty', 'lock', 'log'].includes(item.shellType)).map((item) => item.sessionId));
|
|
305
|
+
for (const id of archivedSet) {
|
|
306
|
+
if (itemIds.has(id) || recoverableShellIds.has(id) || !SESSION_DIR_RE.test(id)) continue;
|
|
307
|
+
const workspace = uniqueRegisteredWorkspace(id);
|
|
308
|
+
items.push({ id, title: cache.titles.get(id) ?? id, cwd: workspace?.path ?? null,
|
|
309
|
+
live: false,
|
|
310
|
+
archived: true, protected: protectedWorkspaces.has(workspace?.path),
|
|
311
|
+
purgeBlock: scheduleCheckFailed ? 'reference_check_failed' : scheduleRefs.has(id) ? 'schedule_reference' : null,
|
|
312
|
+
scheduleTasks: scheduleRefs.get(id) ?? [], workspacePath: workspace?.path ?? null,
|
|
313
|
+
workspaceTitle: workspace?.title ?? '', workspaceCreatedAt: workspace?.createdAt ?? null,
|
|
314
|
+
sizeBytes: null, mtimeMs: null, sessionDir: null });
|
|
315
|
+
}
|
|
316
|
+
const ghostRegistrations = [...registrations.values()].filter(({ id }) => !knownIds.has(id)).map(({ id, workspace }) => ({
|
|
317
|
+
id, workspaceId: workspace.id, workspacePath: workspace.path, workspaceTitle: workspace.title, workspaceCreatedAt: workspace.createdAt ?? null,
|
|
318
|
+
}));
|
|
319
|
+
const workspacesByPath = new Map(workspaces.map((w) => [w.path, w]));
|
|
320
|
+
// `new_once` reserves an ID before its first delivery; it is not a missing
|
|
321
|
+
// session. After delivery DSH changes its target kind to `session`.
|
|
322
|
+
const orphanTasks = scheduleCatalog.filter((task) => task.target?.kind === 'session'
|
|
323
|
+
&& typeof task.target.sessionId === 'string' && !knownIds.has(task.target.sessionId)
|
|
324
|
+
&& !archivedSet.has(task.target.sessionId)).map((task) => {
|
|
325
|
+
const workspace = uniqueRegisteredWorkspace(task.target.sessionId);
|
|
326
|
+
const time = Date.parse(task.updatedAt ?? task.createdAt ?? '');
|
|
327
|
+
return { id: task.id, title: task.title || task.id, status: task.status,
|
|
328
|
+
targetSessionId: task.target.sessionId, updatedAt: task.updatedAt ?? null,
|
|
329
|
+
mtimeMs: Number.isFinite(time) ? time : null, workspacePath: workspace?.path,
|
|
330
|
+
workspaceTitle: workspace?.title, workspaceCreatedAt: workspace?.createdAt ?? null };
|
|
331
|
+
});
|
|
332
|
+
const orphanCaches = cache.orphans.map((item) => {
|
|
333
|
+
const workspace = item.cwd ? workspacesByPath.get(item.cwd) : uniqueRegisteredWorkspace(item.id);
|
|
334
|
+
const workspacePath = item.cwd ?? workspace?.path;
|
|
335
|
+
return { ...item, workspacePath, workspaceTitle: workspace?.title ?? basename(workspacePath), workspaceCreatedAt: workspace?.createdAt ?? null };
|
|
336
|
+
});
|
|
337
|
+
const shellDirs = disk.shellDirs.filter((s) => !sessionIds.has(s.sessionId)).map((item) => {
|
|
338
|
+
const workspace = uniqueRegisteredWorkspace(item.sessionId);
|
|
339
|
+
return { ...item, workspacePath: workspace?.path, workspaceTitle: workspace?.title, workspaceCreatedAt: workspace?.createdAt ?? null };
|
|
340
|
+
});
|
|
341
|
+
return {
|
|
342
|
+
sessions: items,
|
|
343
|
+
residue: {
|
|
344
|
+
orphanCaches,
|
|
345
|
+
orphanTasks,
|
|
346
|
+
ghostRegistrations,
|
|
347
|
+
shellDirs,
|
|
348
|
+
emptyProjectDirs: disk.emptyProjectDirs,
|
|
349
|
+
},
|
|
350
|
+
cacheFiles: cache.files,
|
|
351
|
+
home: homedir(),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function basename(path) {
|
|
356
|
+
if (typeof path !== 'string' || !path) return undefined;
|
|
357
|
+
return pathBasename(path) || undefined;
|
|
358
|
+
}
|
package/locale/de.json
ADDED
package/locale/en.json
ADDED
package/locale/es.json
ADDED
package/locale/fr.json
ADDED
package/locale/ja.json
ADDED
package/locale/pt.json
ADDED
package/locale/ru.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-mop",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.4",
|
|
4
|
+
"author": "tryhub",
|
|
5
|
+
"homepage": "https://gitee.com/tryhub/dsh-mop",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://gitee.com/tryhub/dsh-mop.git"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./index.js",
|
|
13
|
+
"./client": "./client.js",
|
|
14
|
+
"./locale/*.json": "./locale/*.json",
|
|
15
|
+
"./icon": "./icon.svg"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"index.js",
|
|
19
|
+
"client.js",
|
|
20
|
+
"client.*.js",
|
|
21
|
+
"cordis.patch.yml",
|
|
22
|
+
"lib",
|
|
23
|
+
"locale/*.json",
|
|
24
|
+
"icon.svg"
|
|
25
|
+
],
|
|
26
|
+
"dsh": {
|
|
27
|
+
"displayName": "dsh-mop",
|
|
28
|
+
"bundle": {
|
|
29
|
+
"patch": "./cordis.patch.yml"
|
|
30
|
+
},
|
|
31
|
+
"client": {
|
|
32
|
+
"platform": "web",
|
|
33
|
+
"inject": [
|
|
34
|
+
"@deepseek-ai/dsh-client-locale",
|
|
35
|
+
"@deepseek-ai/dsh-client-ui-settings"
|
|
36
|
+
]
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|