feat(workspaces): registry and header-only disk discovery
- atomic 0600 workspaces.json with corrupt-file recovery - discovery reads only the first JSONL line for the authoritative cwd - cache by dir mtime+count: cold 27-37ms / warm 9.6ms on 1313 files - 38 tests, real-machine benchmark documented in the report
This commit is contained in:
1 parent
ba3719fad9
commit
4e98ef8658
8 files changed
+1875
No files matched your search
@@ -0,0 +1,240 @@
|
||||
import { mkdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { workspaceIdForCwd } from "../../src/core/paths.js";
|
||||
import { createDiscovery } from "../../src/workspaces/discovery.js";
|
||||
import { cleanup, encodedDirName, makeSandbox, sessionHeader, writeSessionDir } from "./helpers.js";
|
||||
|
||||
describe("workspace disk discovery", () => {
|
||||
let sandbox: string;
|
||||
let root: string;
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = makeSandbox("pi2d-discovery-");
|
||||
root = join(sandbox, "agent", "sessions");
|
||||
mkdirSync(root, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => cleanup(sandbox));
|
||||
|
||||
it("returns nothing when the sessions root is missing", () => {
|
||||
const discovery = createDiscovery({ root: join(sandbox, "nope") });
|
||||
expect(discovery.discover()).toEqual([]);
|
||||
expect(discovery.listSessions("/tmp")).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the header cwd as authoritative for dashed and unicode paths", () => {
|
||||
// A path where '-' is both a literal path character and the encoded separator.
|
||||
const project = join(sandbox, "weird-dir", "日本語", "sub-dir");
|
||||
mkdirSync(project, { recursive: true });
|
||||
// Deliberately misleading directory name: it cannot be reversed.
|
||||
writeSessionDir(root, "--definitely-not-weird-dir--", [
|
||||
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: project, id: "session-a" },
|
||||
]);
|
||||
|
||||
const [entry] = createDiscovery({ root }).discover();
|
||||
expect(entry).toMatchObject({
|
||||
cwd: project,
|
||||
workspaceId: workspaceIdForCwd(project),
|
||||
sessionCount: 1,
|
||||
exists: true,
|
||||
dir: join(root, "--definitely-not-weird-dir--"),
|
||||
});
|
||||
expect(entry?.lastActiveAt).toBeTypeOf("number");
|
||||
});
|
||||
|
||||
it("selects the newest file by mtime, not by file name", () => {
|
||||
const oldProject = join(sandbox, "old-project");
|
||||
const newProject = join(sandbox, "new-project");
|
||||
mkdirSync(oldProject);
|
||||
mkdirSync(newProject);
|
||||
writeSessionDir(root, encodedDirName(newProject), [
|
||||
{
|
||||
name: "2026-12-31T23-59-59-999Z_lexicographically-newest.jsonl",
|
||||
cwd: oldProject,
|
||||
id: "old",
|
||||
mtime: new Date("2026-01-01T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
name: "2000-01-01T00-00-00-000Z_actually-newest.jsonl",
|
||||
cwd: newProject,
|
||||
id: "new",
|
||||
mtime: new Date("2026-06-01T00:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
const [entry] = createDiscovery({ root }).discover();
|
||||
expect(entry?.cwd).toBe(newProject);
|
||||
expect(entry?.sessionCount).toBe(2);
|
||||
expect(entry?.lastActiveAt).toBe(Date.parse("2026-06-01T00:00:00.000Z"));
|
||||
});
|
||||
|
||||
it("keeps ghost workspaces flagged instead of dropping them", () => {
|
||||
const gone = join(sandbox, "deleted-project");
|
||||
writeSessionDir(root, encodedDirName(gone), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_ghost.jsonl", cwd: gone, id: "ghost" },
|
||||
]);
|
||||
|
||||
const [entry] = createDiscovery({ root }).discover();
|
||||
expect(entry).toMatchObject({ cwd: gone, exists: false, sessionCount: 1 });
|
||||
});
|
||||
|
||||
it("skips directories with no session files and ignores non-jsonl files", () => {
|
||||
mkdirSync(join(root, "--empty--"));
|
||||
writeSessionDir(root, "--only-noise--", []);
|
||||
writeFileSync(join(root, "--only-noise--", "notes.txt"), "not a session");
|
||||
writeSessionDir(root, "--real--", [
|
||||
{ name: "2026-10-10T06-40-33-032Z_real.jsonl", cwd: sandbox, id: "real" },
|
||||
]);
|
||||
|
||||
expect(createDiscovery({ root }).discover()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("never parses past the first line", () => {
|
||||
const dir = writeSessionDir(root, encodedDirName(sandbox), [
|
||||
{
|
||||
name: "2026-10-10T06-40-33-032Z_header.jsonl",
|
||||
cwd: sandbox,
|
||||
id: "header",
|
||||
body: "this is not json at all\n{}]\n",
|
||||
},
|
||||
]);
|
||||
|
||||
const discovery = createDiscovery({ root });
|
||||
expect(discovery.discover()[0]?.cwd).toBe(sandbox);
|
||||
expect(discovery.listSessions(sandbox)[0]?.id).toBe("header");
|
||||
expect(statSync(join(dir, "2026-10-10T06-40-33-032Z_header.jsonl")).isFile()).toBe(true);
|
||||
});
|
||||
|
||||
it("serves a cache hit without re-reading the header", () => {
|
||||
const dir = writeSessionDir(root, encodedDirName(sandbox), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_cached.jsonl", cwd: sandbox, id: "cached" },
|
||||
]);
|
||||
const file = join(dir, "2026-10-10T06-40-33-032Z_cached.jsonl");
|
||||
const discovery = createDiscovery({ root });
|
||||
expect(discovery.discover()[0]?.cwd).toBe(sandbox);
|
||||
|
||||
// Corrupt the header in place (directory mtime and file count unchanged).
|
||||
writeFileSync(file, `${JSON.stringify({ type: "not-a-session", cwd: "/definitely/wrong" })}\n`);
|
||||
|
||||
// Still served from cache: the header was not read again.
|
||||
expect(discovery.discover()[0]?.cwd).toBe(sandbox);
|
||||
|
||||
// Explicit invalidation forces a re-read and the header is now unusable.
|
||||
discovery.invalidate();
|
||||
expect(discovery.discover()).toEqual([]);
|
||||
});
|
||||
|
||||
it("detects newly created session files via the directory signature", () => {
|
||||
const dir = writeSessionDir(root, encodedDirName(sandbox), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_one.jsonl", cwd: sandbox, id: "one" },
|
||||
]);
|
||||
const discovery = createDiscovery({ root });
|
||||
expect(discovery.discover()[0]?.sessionCount).toBe(1);
|
||||
|
||||
writeFileSync(
|
||||
join(dir, "2026-10-11T06-40-33-032Z_two.jsonl"),
|
||||
`${sessionHeader(sandbox, "two")}\n`,
|
||||
);
|
||||
expect(discovery.discover()[0]?.sessionCount).toBe(2);
|
||||
expect(discovery.listSessions(sandbox)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("invalidates a single directory when asked", () => {
|
||||
const other = join(sandbox, "other");
|
||||
mkdirSync(other);
|
||||
const dirA = writeSessionDir(root, encodedDirName(sandbox), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: sandbox, id: "a" },
|
||||
]);
|
||||
writeSessionDir(root, encodedDirName(other), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_b.jsonl", cwd: other, id: "b" },
|
||||
]);
|
||||
const discovery = createDiscovery({ root });
|
||||
expect(discovery.discover()).toHaveLength(2);
|
||||
|
||||
discovery.invalidate(dirA);
|
||||
// Both still discoverable; the cache entry for A was dropped and rebuilt.
|
||||
expect(discovery.discover()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("lists sessions from the header only, newest first", () => {
|
||||
const dir = writeSessionDir(root, encodedDirName(sandbox), [
|
||||
{
|
||||
name: "2026-01-01T00-00-00-000Z_old.jsonl",
|
||||
cwd: sandbox,
|
||||
id: "header-old",
|
||||
timestamp: "2026-01-01T00:00:00.000Z",
|
||||
mtime: new Date("2026-01-02T00:00:00.000Z"),
|
||||
body: "garbage that must never be parsed\n",
|
||||
},
|
||||
{
|
||||
name: "2026-02-02T00-00-00-000Z_new.jsonl",
|
||||
cwd: sandbox,
|
||||
id: "header-new",
|
||||
timestamp: "2026-02-02T00:00:00.000Z",
|
||||
mtime: new Date("2026-02-03T00:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
const sessions = createDiscovery({ root }).listSessions(sandbox);
|
||||
expect(sessions.map((s) => s.id)).toEqual(["header-new", "header-old"]);
|
||||
expect(sessions[0]).toMatchObject({
|
||||
file: join(dir, "2026-02-02T00-00-00-000Z_new.jsonl"),
|
||||
timestamp: Date.parse("2026-02-02T00:00:00.000Z"),
|
||||
modified: Date.parse("2026-02-03T00:00:00.000Z"),
|
||||
});
|
||||
expect(sessions.every((s) => s.firstMessage === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("falls back to the file name when a header is unreadable", () => {
|
||||
const dir = writeSessionDir(root, encodedDirName(sandbox), [
|
||||
{ name: "2026-03-01T00-00-00-000Z_good.jsonl", cwd: sandbox, id: "good" },
|
||||
]);
|
||||
const broken = join(dir, "2026-03-04T05-06-07-008Z_fallback-id.jsonl");
|
||||
writeFileSync(broken, "not a session header\n");
|
||||
// Newer mtime so the fallback entry is first.
|
||||
utimesSync(broken, new Date("2026-03-05T00:00:00.000Z"), new Date("2026-03-05T00:00:00.000Z"));
|
||||
|
||||
const sessions = createDiscovery({ root }).listSessions(sandbox);
|
||||
expect(sessions).toHaveLength(2);
|
||||
expect(sessions.find((s) => s.id === "fallback-id")).toMatchObject({
|
||||
id: "fallback-id",
|
||||
timestamp: Date.parse("2026-03-04T05:06:07.008Z"),
|
||||
});
|
||||
});
|
||||
|
||||
it("returns no sessions for unknown cwds", () => {
|
||||
writeSessionDir(root, encodedDirName(sandbox), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: sandbox, id: "a" },
|
||||
]);
|
||||
expect(createDiscovery({ root }).listSessions(join(sandbox, "unknown"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("defaults the root to PI_CODING_AGENT_DIR/sessions", () => {
|
||||
const agent = join(sandbox, "custom-agent");
|
||||
const sessions = join(agent, "sessions");
|
||||
mkdirSync(sessions, { recursive: true });
|
||||
writeSessionDir(sessions, encodedDirName(sandbox), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_env.jsonl", cwd: sandbox, id: "env" },
|
||||
]);
|
||||
const previous = process.env.PI_CODING_AGENT_DIR;
|
||||
process.env.PI_CODING_AGENT_DIR = agent;
|
||||
try {
|
||||
expect(createDiscovery().discover()).toHaveLength(1);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
||||
else process.env.PI_CODING_AGENT_DIR = previous;
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores a vanished directory gracefully", () => {
|
||||
const dir = writeSessionDir(root, encodedDirName(sandbox), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: sandbox, id: "a" },
|
||||
]);
|
||||
const discovery = createDiscovery({ root });
|
||||
expect(discovery.discover()).toHaveLength(1);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
discovery.invalidate();
|
||||
expect(discovery.discover()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
export interface SessionSpec {
|
||||
/** File name inside the encoded session directory. */
|
||||
name: string;
|
||||
/** cwd written into the session header (authoritative). */
|
||||
cwd: string;
|
||||
id?: string;
|
||||
timestamp?: string;
|
||||
/** Extra JSONL lines appended after the header (never parsed by discovery). */
|
||||
body?: string;
|
||||
/** File mtime, used to test newest-file selection. */
|
||||
mtime?: Date | number;
|
||||
}
|
||||
|
||||
export function makeSandbox(prefix = "pi2d-ws-"): string {
|
||||
return mkdtempSync(join(tmpdir(), prefix));
|
||||
}
|
||||
|
||||
export function cleanup(dir: string | undefined): void {
|
||||
if (dir) rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
/** Mimics pi's `--<cwd with slashes replaced by dashes>--` directory naming. */
|
||||
export function encodedDirName(cwd: string): string {
|
||||
return `--${cwd.replace(/^\/+/, "").replace(/\//g, "-")}--`;
|
||||
}
|
||||
|
||||
export function sessionHeader(cwd: string, id: string, timestamp = "2026-10-10T06:40:33.032Z"): string {
|
||||
return JSON.stringify({ type: "session", version: 3, id, timestamp, cwd });
|
||||
}
|
||||
|
||||
/** Creates an encoded sessions directory with real-looking JSONL files. */
|
||||
export function writeSessionDir(root: string, dirName: string, files: SessionSpec[]): string {
|
||||
const dir = join(root, dirName);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const file of files) {
|
||||
const id = file.id ?? "01a00000-0000-7000-8000-000000000000";
|
||||
const timestamp = file.timestamp ?? "2026-10-10T06:40:33.032Z";
|
||||
const body = file.body ?? '{"type":"message","id":"m1","message":{"role":"user","content":"hi"}}\n';
|
||||
const path = join(dir, file.name);
|
||||
writeFileSync(path, `${sessionHeader(file.cwd, id, timestamp)}\n${body}`);
|
||||
if (file.mtime !== undefined) utimesSync(path, file.mtime, file.mtime);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { workspaceIdForCwd } from "../../src/core/paths.js";
|
||||
import { WorkspaceError, WorkspaceRegistry } from "../../src/workspaces/registry.js";
|
||||
import { cleanup, makeSandbox } from "./helpers.js";
|
||||
|
||||
describe("workspace registry", () => {
|
||||
let sandbox: string;
|
||||
let file: string;
|
||||
let project: string;
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = makeSandbox("pi2d-registry-");
|
||||
file = join(sandbox, "data", "workspaces.json");
|
||||
project = join(sandbox, "project");
|
||||
mkdirSync(project, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => cleanup(sandbox));
|
||||
|
||||
it("defaults to dataDir()/workspaces.json", async () => {
|
||||
const previous = process.env.PI2_DATA_DIR;
|
||||
process.env.PI2_DATA_DIR = join(sandbox, "xdg-data");
|
||||
try {
|
||||
const registry = new WorkspaceRegistry();
|
||||
await registry.ensureForCwd(project);
|
||||
expect(registry.filePath).toBe(join(sandbox, "xdg-data", "workspaces.json"));
|
||||
expect(existsSync(registry.filePath)).toBe(true);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.PI2_DATA_DIR;
|
||||
else process.env.PI2_DATA_DIR = previous;
|
||||
}
|
||||
});
|
||||
|
||||
it("serialises concurrent writes without losing entries", async () => {
|
||||
const other = join(sandbox, "other");
|
||||
mkdirSync(other);
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
|
||||
await Promise.all([registry.ensureForCwd(project), registry.ensureForCwd(other)]);
|
||||
expect(registry.list()).toHaveLength(2);
|
||||
expect(new WorkspaceRegistry({ filePath: file }).list()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("starts empty when the file does not exist", () => {
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
expect(registry.list()).toEqual([]);
|
||||
expect(registry.get("nope")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("writes atomically with mode 0600 and leaves no temp files behind", async () => {
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
const record = await registry.ensureForCwd(project);
|
||||
|
||||
expect(existsSync(file)).toBe(true);
|
||||
expect(statSync(file).mode & 0o777).toBe(0o600);
|
||||
expect(readdirSync(join(sandbox, "data")).filter((n) => n.includes(".tmp"))).toEqual([]);
|
||||
|
||||
const parsed = JSON.parse(readFileSync(file, "utf8")) as {
|
||||
version: number;
|
||||
workspaces: Record<string, { cwd: string; trusted: boolean }>;
|
||||
};
|
||||
expect(parsed.version).toBe(1);
|
||||
expect(parsed.workspaces[record.workspaceId]?.cwd).toBe(record.entry.cwd);
|
||||
expect(parsed.workspaces[record.workspaceId]?.trusted).toBe(false);
|
||||
});
|
||||
|
||||
it("forces 0600 even when a pre-existing file was world readable", async () => {
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
await registry.ensureForCwd(project);
|
||||
chmodSync(file, 0o644);
|
||||
expect(statSync(file).mode & 0o777).toBe(0o644);
|
||||
|
||||
await registry.update(workspaceIdForCwd(project), { pinned: true });
|
||||
expect(statSync(file).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it("backs up a corrupt registry and starts empty", () => {
|
||||
mkdirSync(join(sandbox, "data"), { recursive: true });
|
||||
const corrupt = '{"version":1,"workspaces":{"broken":';
|
||||
writeFileSync(file, corrupt);
|
||||
const warnings: string[] = [];
|
||||
|
||||
const registry = new WorkspaceRegistry({
|
||||
filePath: file,
|
||||
logger: { warn: (msg) => warnings.push(msg) },
|
||||
});
|
||||
|
||||
expect(registry.list()).toEqual([]);
|
||||
expect(readFileSync(`${file}.bak`, "utf8")).toBe(corrupt);
|
||||
expect(warnings.some((w) => w.includes("corrupt"))).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects malformed-but-valid JSON as corrupt", () => {
|
||||
mkdirSync(join(sandbox, "data"), { recursive: true });
|
||||
writeFileSync(file, JSON.stringify({ version: 2, workspaces: {} }));
|
||||
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
expect(registry.list()).toEqual([]);
|
||||
expect(existsSync(`${file}.bak`)).toBe(true);
|
||||
});
|
||||
|
||||
it("supports CRUD and persists across instances", async () => {
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
const real = await registry.ensureForCwd(project);
|
||||
expect(real.workspaceId).toBe(workspaceIdForCwd(project));
|
||||
expect(real.entry.createdAt).toBeGreaterThan(0);
|
||||
|
||||
const byCwd = registry.byCwd(project);
|
||||
expect(byCwd?.workspaceId).toBe(real.workspaceId);
|
||||
|
||||
const updated = await registry.update(real.workspaceId, {
|
||||
alias: " My Project ",
|
||||
pinned: true,
|
||||
hidden: true,
|
||||
trusted: true,
|
||||
});
|
||||
expect(updated.entry).toMatchObject({
|
||||
alias: "My Project",
|
||||
pinned: true,
|
||||
hidden: true,
|
||||
trusted: true,
|
||||
});
|
||||
|
||||
const reloaded = new WorkspaceRegistry({ filePath: file });
|
||||
expect(reloaded.get(real.workspaceId)?.entry).toMatchObject({
|
||||
cwd: real.entry.cwd,
|
||||
alias: "My Project",
|
||||
pinned: true,
|
||||
hidden: true,
|
||||
trusted: true,
|
||||
});
|
||||
|
||||
const cleared = await reloaded.update(real.workspaceId, { alias: null });
|
||||
expect(cleared.entry.alias).toBeUndefined();
|
||||
|
||||
await reloaded.remove(real.workspaceId);
|
||||
expect(reloaded.get(real.workspaceId)).toBeUndefined();
|
||||
expect(new WorkspaceRegistry({ filePath: file }).list()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not change createdAt or duplicate entries on repeated ensureForCwd", async () => {
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
const first = await registry.ensureForCwd(project);
|
||||
const second = await registry.ensureForCwd(project);
|
||||
|
||||
expect(second.workspaceId).toBe(first.workspaceId);
|
||||
expect(second.entry.createdAt).toBe(first.entry.createdAt);
|
||||
expect(registry.list()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects relative and missing cwds", async () => {
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
|
||||
await expect(registry.ensureForCwd("relative/path")).rejects.toBeInstanceOf(WorkspaceError);
|
||||
await expect(registry.ensureForCwd("relative/path")).rejects.toMatchObject({ code: "E_BAD_REQUEST" });
|
||||
await expect(registry.ensureForCwd(join(sandbox, "missing"))).rejects.toMatchObject({
|
||||
code: "E_NOT_FOUND",
|
||||
});
|
||||
expect(registry.list()).toEqual([]);
|
||||
});
|
||||
|
||||
it("canonicalises symlinks to one workspace", async () => {
|
||||
const { symlinkSync, realpathSync } = await import("node:fs");
|
||||
const link = join(sandbox, "link");
|
||||
symlinkSync(project, link);
|
||||
|
||||
const registry = new WorkspaceRegistry({ filePath: file });
|
||||
const a = await registry.ensureForCwd(project);
|
||||
const b = await registry.ensureForCwd(link);
|
||||
|
||||
expect(b.workspaceId).toBe(a.workspaceId);
|
||||
expect(b.entry.cwd).toBe(realpathSync(project));
|
||||
expect(registry.list()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import { existsSync, mkdirSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { workspaceIdForCwd } from "../../src/core/paths.js";
|
||||
import type { InstanceManager } from "../../src/core/interfaces.js";
|
||||
import type { InstanceState } from "../../src/protocol/types.js";
|
||||
import { createDiscovery } from "../../src/workspaces/discovery.js";
|
||||
import { createWorkspaceStore } from "../../src/workspaces/index.js";
|
||||
import { WorkspaceRegistry } from "../../src/workspaces/registry.js";
|
||||
import { cleanup, encodedDirName, makeSandbox, sessionHeader, writeSessionDir } from "./helpers.js";
|
||||
|
||||
type FakeInstanceState = InstanceState & { sessions?: unknown[]; sessionCount?: number };
|
||||
|
||||
function fakeInstances(listed: FakeInstanceState[], connected = listed): InstanceManager {
|
||||
return {
|
||||
list: () => listed,
|
||||
instanceStates: () => connected,
|
||||
} as unknown as InstanceManager;
|
||||
}
|
||||
|
||||
function instance(workspaceId: string, overrides: Partial<FakeInstanceState> = {}): FakeInstanceState {
|
||||
return {
|
||||
workspaceId,
|
||||
instanceId: `i-${workspaceId.slice(0, 4)}`,
|
||||
status: "ready",
|
||||
nvimPid: 4242,
|
||||
pluginVersion: "1.8.0",
|
||||
hasUI: true,
|
||||
attachedClients: 1,
|
||||
listenAddr: null,
|
||||
startedAt: Date.now(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("workspace store", () => {
|
||||
let sandbox: string;
|
||||
let sessions: string;
|
||||
let dataFile: string;
|
||||
let allowRoot: string;
|
||||
let projectA: string;
|
||||
let projectB: string;
|
||||
let projectGhost: string;
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = makeSandbox("pi2d-store-");
|
||||
sessions = join(sandbox, "agent", "sessions");
|
||||
dataFile = join(sandbox, "data", "workspaces.json");
|
||||
allowRoot = join(sandbox, "code");
|
||||
projectA = join(allowRoot, "alpha");
|
||||
projectB = join(allowRoot, "beta");
|
||||
projectGhost = join(allowRoot, "ghost");
|
||||
for (const dir of [sessions, allowRoot, projectA, projectB, projectGhost]) mkdirSync(dir, { recursive: true });
|
||||
|
||||
writeSessionDir(sessions, encodedDirName(projectA), [
|
||||
{ name: "2026-10-10T06-40-33-032Z_a1.jsonl", cwd: projectA, id: "a1" },
|
||||
{ name: "2026-10-11T06-40-33-032Z_a2.jsonl", cwd: projectA, id: "a2" },
|
||||
]);
|
||||
writeSessionDir(sessions, encodedDirName(projectB), [
|
||||
{ name: "2026-10-12T06-40-33-032Z_b1.jsonl", cwd: projectB, id: "b1" },
|
||||
]);
|
||||
writeSessionDir(sessions, encodedDirName(projectGhost), [
|
||||
{ name: "2026-10-13T06-40-33-032Z_g1.jsonl", cwd: projectGhost, id: "g1" },
|
||||
]);
|
||||
rmSync(projectGhost, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
afterEach(() => cleanup(sandbox));
|
||||
|
||||
function setup(opts: Parameters<typeof createWorkspaceStore>[0] = {}) {
|
||||
const discovery = createDiscovery({ root: sessions });
|
||||
const registry = new WorkspaceRegistry({ filePath: dataFile });
|
||||
const store = createWorkspaceStore({ discovery, registry, roots: [allowRoot], ...opts });
|
||||
return { store, discovery, registry };
|
||||
}
|
||||
|
||||
it("merges registry entries with disk discovery and instance state", async () => {
|
||||
const aId = workspaceIdForCwd(projectA);
|
||||
const { store, registry } = setup({
|
||||
instances: fakeInstances([instance(aId, { sessions: [{}, {}, {}] })]),
|
||||
});
|
||||
await registry.ensureForCwd(projectA);
|
||||
await store.update(aId, { alias: "Alpha", pinned: true, trusted: true });
|
||||
|
||||
const all = store.list();
|
||||
expect(all).toHaveLength(3);
|
||||
|
||||
const a = store.get(aId);
|
||||
expect(a).toMatchObject({
|
||||
workspaceId: aId,
|
||||
cwd: projectA,
|
||||
name: "Alpha",
|
||||
alias: "Alpha",
|
||||
pinned: true,
|
||||
hidden: false,
|
||||
trusted: true,
|
||||
exists: true,
|
||||
sessionCount: 2,
|
||||
liveCount: 3,
|
||||
});
|
||||
expect(a?.instance).toMatchObject({ workspaceId: aId, instanceId: `i-${aId.slice(0, 4)}` });
|
||||
|
||||
const b = store.byCwd(projectB);
|
||||
expect(b).toMatchObject({
|
||||
workspaceId: workspaceIdForCwd(projectB),
|
||||
name: "beta",
|
||||
alias: null,
|
||||
trusted: false,
|
||||
exists: true,
|
||||
sessionCount: 1,
|
||||
liveCount: 0,
|
||||
instance: null,
|
||||
});
|
||||
|
||||
const ghost = store.get(workspaceIdForCwd(projectGhost));
|
||||
expect(ghost).toMatchObject({ exists: false, sessionCount: 1, lastActiveAt: expect.any(Number) });
|
||||
});
|
||||
|
||||
it("keeps hidden entries in list(); the UI decides ordering", async () => {
|
||||
const { store } = setup();
|
||||
const bId = workspaceIdForCwd(projectB);
|
||||
await store.update(bId, { hidden: true, pinned: true, alias: "Bee" });
|
||||
expect(store.list().find((w) => w.workspaceId === bId)).toMatchObject({
|
||||
hidden: true,
|
||||
pinned: true,
|
||||
alias: "Bee",
|
||||
});
|
||||
expect(store.get(bId)?.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it("adds existing, readable, writable directories inside the allowlist", async () => {
|
||||
const { store, registry } = setup();
|
||||
const info = await store.add({ cwd: projectA, alias: " Alpha ", trust: true });
|
||||
|
||||
expect(info).toMatchObject({
|
||||
workspaceId: workspaceIdForCwd(projectA),
|
||||
alias: "Alpha",
|
||||
trusted: true,
|
||||
pinned: false,
|
||||
hidden: false,
|
||||
});
|
||||
expect(registry.list()).toHaveLength(1);
|
||||
|
||||
const again = await store.add({ cwd: projectA, alias: "Renamed" });
|
||||
expect(again.workspaceId).toBe(info.workspaceId);
|
||||
expect(again.alias).toBe("Renamed");
|
||||
expect(again.trusted).toBe(true);
|
||||
expect(registry.list()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects paths outside the allowlist with E_FORBIDDEN", async () => {
|
||||
const outside = join(sandbox, "outside");
|
||||
mkdirSync(outside);
|
||||
const { store } = setup();
|
||||
|
||||
await expect(store.add({ cwd: outside })).rejects.toMatchObject({
|
||||
code: "E_FORBIDDEN",
|
||||
name: "WorkspaceError",
|
||||
});
|
||||
await expect(store.add({ cwd: sandbox })).rejects.toMatchObject({ code: "E_FORBIDDEN" });
|
||||
});
|
||||
|
||||
it("rejects symlinks that escape the allowlist", async () => {
|
||||
const outside = join(sandbox, "outside");
|
||||
mkdirSync(outside);
|
||||
const link = join(allowRoot, "escape");
|
||||
symlinkSync(outside, link);
|
||||
const { store } = setup();
|
||||
|
||||
await expect(store.add({ cwd: link })).rejects.toMatchObject({ code: "E_FORBIDDEN" });
|
||||
});
|
||||
|
||||
it("honours PI2_WORKSPACE_ROOTS (comma separated) when no explicit roots are given", async () => {
|
||||
const outside = join(sandbox, "outside");
|
||||
mkdirSync(outside);
|
||||
const previous = process.env.PI2_WORKSPACE_ROOTS;
|
||||
process.env.PI2_WORKSPACE_ROOTS = `${join(sandbox, "nope")}, ${allowRoot}`;
|
||||
try {
|
||||
const { store } = setup({ roots: undefined });
|
||||
await expect(store.add({ cwd: projectB })).resolves.toMatchObject({ cwd: projectB });
|
||||
await expect(store.add({ cwd: outside })).rejects.toMatchObject({ code: "E_FORBIDDEN" });
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.PI2_WORKSPACE_ROOTS;
|
||||
else process.env.PI2_WORKSPACE_ROOTS = previous;
|
||||
}
|
||||
});
|
||||
|
||||
it("validates relative, missing and non-directory paths", async () => {
|
||||
const file = join(allowRoot, "file.txt");
|
||||
writeFileSync(file, "x");
|
||||
const { store } = setup();
|
||||
|
||||
await expect(store.add({ cwd: "relative/project" })).rejects.toMatchObject({ code: "E_BAD_REQUEST" });
|
||||
await expect(store.add({ cwd: join(allowRoot, "missing") })).rejects.toMatchObject({
|
||||
code: "E_NOT_FOUND",
|
||||
});
|
||||
await expect(store.add({ cwd: file })).rejects.toMatchObject({ code: "E_BAD_REQUEST" });
|
||||
});
|
||||
|
||||
it("makes ensureForCwd idempotent without applying the allowlist (instance connects)", async () => {
|
||||
const outside = join(sandbox, "outside");
|
||||
mkdirSync(outside);
|
||||
const { store, registry } = setup();
|
||||
|
||||
const first = await store.ensureForCwd(projectA);
|
||||
const second = await store.ensureForCwd(projectA);
|
||||
expect(second.workspaceId).toBe(first.workspaceId);
|
||||
expect(registry.list()).toHaveLength(1);
|
||||
|
||||
const external = await store.ensureForCwd(outside);
|
||||
expect(external.cwd).toBe(outside);
|
||||
expect(external.trusted).toBe(false);
|
||||
|
||||
await expect(store.ensureForCwd("relative")).rejects.toMatchObject({ code: "E_BAD_REQUEST" });
|
||||
});
|
||||
|
||||
it("updates discovered-only workspaces by registering them first", async () => {
|
||||
const { store, registry } = setup();
|
||||
const bId = workspaceIdForCwd(projectB);
|
||||
expect(registry.get(bId)).toBeUndefined();
|
||||
|
||||
const updated = await store.update(bId, { pinned: true, trusted: true });
|
||||
expect(updated).toMatchObject({ workspaceId: bId, pinned: true, trusted: true });
|
||||
expect(registry.get(bId)?.entry.cwd).toBe(projectB);
|
||||
|
||||
await expect(store.update("0000000000000000", { pinned: true })).rejects.toMatchObject({
|
||||
code: "E_NOT_FOUND",
|
||||
});
|
||||
});
|
||||
|
||||
it("removes only the registry entry and leaves session files on disk", async () => {
|
||||
const { store, registry } = setup();
|
||||
const info = await store.add({ cwd: projectA, alias: "Alpha", trust: true });
|
||||
const sessionDir = join(sessions, encodedDirName(projectA));
|
||||
expect(readdirSync(sessionDir)).toHaveLength(2);
|
||||
|
||||
await store.remove(info.workspaceId);
|
||||
expect(registry.get(info.workspaceId)).toBeUndefined();
|
||||
expect(existsSync(sessionDir)).toBe(true);
|
||||
expect(readdirSync(sessionDir)).toHaveLength(2);
|
||||
|
||||
// The workspace reappears from disk discovery, but without registry metadata.
|
||||
const after = store.get(info.workspaceId);
|
||||
expect(after).toMatchObject({ exists: true, sessionCount: 2, trusted: false });
|
||||
expect(after?.alias).toBeNull();
|
||||
|
||||
await expect(store.remove("0000000000000000")).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("refresh() picks up new session files", async () => {
|
||||
const { store } = setup();
|
||||
const aId = workspaceIdForCwd(projectA);
|
||||
expect(store.get(aId)?.sessionCount).toBe(2);
|
||||
|
||||
writeFileSync(
|
||||
join(sessions, encodedDirName(projectA), "2026-10-14T06-40-33-032Z_a3.jsonl"),
|
||||
`${sessionHeader(projectA, "a3")}\n`,
|
||||
);
|
||||
await store.refresh(aId);
|
||||
expect(store.get(aId)?.sessionCount).toBe(3);
|
||||
|
||||
await store.refresh();
|
||||
expect(store.list()).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("tolerates a missing instance manager", () => {
|
||||
const { store } = setup({ instances: undefined });
|
||||
expect(store.list().every((w) => w.liveCount === 0 && w.instance === null)).toBe(true);
|
||||
});
|
||||
|
||||
it("counts live sessions from instanceStates() even when list() has a stopped instance", async () => {
|
||||
const aId = workspaceIdForCwd(projectA);
|
||||
const listed = [instance(aId, { status: "stopped" })];
|
||||
const connected = [instance(aId, { sessionCount: 2 })];
|
||||
const { store } = setup({ instances: fakeInstances(listed, connected) });
|
||||
|
||||
const info = store.get(aId);
|
||||
expect(info?.instance).toMatchObject({ status: "stopped" });
|
||||
expect(info?.liveCount).toBe(2);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user