feat(cli): runnable daemon, local CLI, doctor, service files and smoke test

- composition root wiring config/auth/workspaces/instances/http
- singleton lock + daemon.json + port retry + local cli.token (admin scope)
- pi2 attach/status/doctor/pairing/install-service
- systemd user unit + launchd plist rendering (never auto-enabled)
- smoke.sh boots the real daemon on an ephemeral port and asserts auth/static/lifecycle
- 93 new tests (263 total), tsc + build + smoke green
This commit is contained in:
yuez committed 2026-10-21 12:45:11 +08:00
1 parent a495f2ac71
commit 18e3e0ab4e
23 files changed
+4494 -1

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { AuthStore, LOCAL_CLI_DEVICE_ID, SCOPES } from "../../src/daemon/auth.js";
import { writeCliToken } from "../../src/cli/token.js";
import { removeDir, tempDir } from "./helpers.js";
describe("AuthStore local CLI token", () => {
let dir: string;
let tokenPath: string;
let storePath: string;
beforeEach(() => {
dir = tempDir("pi2-local-token-");
tokenPath = join(dir, "cli.token");
storePath = join(dir, "devices.json");
});
afterEach(() => removeDir(dir));
it("accepts the token file contents as the synthetic admin device", () => {
const token = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
const device = auth.verifyToken(token);
expect(device).not.toBeNull();
expect(device!.id).toBe(LOCAL_CLI_DEVICE_ID);
expect(device!.id).toBe("local-cli");
expect(device!.name).toBe("local CLI");
expect(device!.scopes).toEqual([...SCOPES]);
expect(device!.scopes).toEqual(["read", "steer", "control", "admin"]);
expect(device!.revokedAt).toBeNull();
expect((device as unknown as Record<string, unknown>).tokenHash).toBeUndefined();
});
it("tolerates a trailing newline in the token file", () => {
const token = writeCliToken(tokenPath);
writeFileSync(tokenPath, `${token}\n\n`, { mode: 0o600 });
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
expect(auth.verifyToken(token)?.id).toBe(LOCAL_CLI_DEVICE_ID);
});
it("rejects wrong, truncated, empty and missing tokens", () => {
const token = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
expect(auth.verifyToken("")).toBeNull();
expect(auth.verifyToken("not-a-token")).toBeNull();
expect(auth.verifyToken(token.slice(0, -1))).toBeNull();
expect(auth.verifyToken(token.slice(0, -1) + (token.endsWith("a") ? "b" : "a"))).toBeNull();
writeFileSync(tokenPath, "\n", { mode: 0o600 });
expect(auth.verifyToken("")).toBeNull();
expect(auth.verifyToken(token)).toBeNull();
rmSync(tokenPath, { force: true });
expect(auth.verifyToken(token)).toBeNull();
});
it("rotates: a rewritten token file invalidates the previous one", () => {
const first = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
expect(auth.verifyToken(first)?.id).toBe(LOCAL_CLI_DEVICE_ID);
const second = writeCliToken(tokenPath);
expect(second).not.toBe(first);
expect(auth.verifyToken(first)).toBeNull();
expect(auth.verifyToken(second)?.id).toBe(LOCAL_CLI_DEVICE_ID);
});
it("keeps paired devices working and never lists the synthetic one", () => {
writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
const { token } = auth.createDevice({ name: "Pixel", kind: "phone", scopes: ["read"] });
expect(auth.verifyToken(token)?.name).toBe("Pixel");
expect(auth.listDevices().map((device) => device.id)).not.toContain(LOCAL_CLI_DEVICE_ID);
expect(auth.listDevices()).toHaveLength(1);
// The synthetic device is not revocable; a paired device is.
expect(auth.revokeDevice(LOCAL_CLI_DEVICE_ID)).toBe(false);
expect(auth.revokeDevice(auth.listDevices()[0]!.id)).toBe(true);
expect(auth.verifyToken(token)).toBeNull();
});
it("is inert without localTokenPath (existing API unchanged)", () => {
const token = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath });
expect(auth.localTokenPath).toBeUndefined();
expect(auth.verifyToken(token)).toBeNull();
});
it("does not persist anything to the device store", () => {
const token = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
auth.verifyToken(token);
const reloaded = new AuthStore({ path: storePath, localTokenPath: tokenPath });
expect(reloaded.listDevices()).toHaveLength(0);
expect(reloaded.verifyToken(token)?.id).toBe(LOCAL_CLI_DEVICE_ID);
});
});
+291
View File
@@ -0,0 +1,291 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
checkCliToken,
checkLinger,
checkNvim,
checkNode,
checkProtocol,
collectContext,
defaultProbes,
formatReport,
parseNvimVersion,
parseVersion,
reportToJson,
runDoctor,
versionAtLeast,
type DoctorContext,
} from "../../src/cli/doctor.js";
import { clearRuntimeEnv, removeDir, tempDir } from "./helpers.js";
function context(overrides: Partial<DoctorContext> = {}): DoctorContext {
const base: DoctorContext = {
platform: "linux",
nodeVersion: "v22.11.0",
nvim: { found: true, path: "/usr/bin/nvim", version: "v0.10.2" },
pi: { found: true, path: "/usr/local/bin/pi", version: "1.8.0" },
plugin: { dir: "/home/u/.local/share/nvim/lazy/pi2.nvim", bridgeFound: true },
runtime: { path: "/run/user/1000/pi2", exists: true, mode: 0o700 },
cliToken: { path: "/run/user/1000/pi2/cli.token", exists: true, mode: 0o600 },
socket: { path: "/run/user/1000/pi2/d.sock", exists: true },
daemon: { reachable: true, port: 7676, protocolVersion: 1 },
port: { configured: 7676, bound: true },
serviceManager: { name: "systemd", available: true },
linger: { checked: true, enabled: true },
webDist: { path: "/repo/web/dist", exists: true },
};
return { ...base, ...overrides };
}
async function checks(overrides: Partial<DoctorContext> = {}) {
return runDoctor(defaultProbes(context(overrides)));
}
function statusOf(report: Awaited<ReturnType<typeof checks>>, name: string): string | undefined {
return report.checks.find((check) => check.name === name)?.status;
}
describe("doctor checks (all passing)", () => {
it("reports ok and every check", async () => {
const report = await checks();
expect(report.ok).toBe(true);
expect(report.checks.map((check) => check.name)).toEqual([
"node",
"nvim",
"pi",
"plugin",
"runtime-dir",
"cli-token",
"socket",
"daemon",
"port",
"service-manager",
"linger",
"web-dist",
"protocol",
]);
expect(report.checks.every((check) => check.status === "ok")).toBe(true);
expect(report.checks.find((check) => check.name === "node")?.detail).toContain("v22.11.0");
});
it("omits the linger check on macOS", async () => {
const report = await checks({
platform: "darwin",
serviceManager: { name: "launchd", available: true },
linger: { checked: false },
});
expect(statusOf(report, "linger")).toBeUndefined();
expect(report.ok).toBe(true);
});
});
describe("doctor failure cases", () => {
it("fails on node < 22", async () => {
const report = await checks({ nodeVersion: "v20.11.0" });
expect(report.ok).toBe(false);
expect(statusOf(report, "node")).toBe("fail");
expect(report.checks.find((check) => check.name === "node")?.detail).toContain("< 22.0.0");
});
it("fails when nvim is missing", async () => {
const report = await checks({ nvim: { found: false, error: "nvim not found on PATH" } });
expect(statusOf(report, "nvim")).toBe("fail");
expect(report.ok).toBe(false);
});
it("fails on nvim < 0.9 (no --remote-ui)", async () => {
const report = await checks({ nvim: { found: true, path: "/usr/bin/nvim", version: "v0.8.3" } });
expect(statusOf(report, "nvim")).toBe("fail");
expect(report.checks.find((check) => check.name === "nvim")?.detail).toContain("--remote-ui");
});
it("warns (does not fail) when pi is missing", async () => {
const report = await checks({ pi: { found: false } });
expect(statusOf(report, "pi")).toBe("warn");
expect(report.ok).toBe(true);
});
it("fails when the plugin is not installed", async () => {
const report = await checks({ plugin: { dir: "/home/u/nvim/pi2.nvim", bridgeFound: false } });
expect(statusOf(report, "plugin")).toBe("fail");
expect(report.ok).toBe(false);
});
it("fails when the runtime dir is missing and warns on loose modes", async () => {
expect(statusOf(await checks({ runtime: { path: "/run/pi2", exists: false, mode: undefined } }), "runtime-dir")).toBe(
"fail",
);
const loose = await checks({ runtime: { path: "/run/pi2", exists: true, mode: 0o755 } });
expect(statusOf(loose, "runtime-dir")).toBe("warn");
expect(loose.ok).toBe(true);
});
it("fails when the CLI token is readable by others", async () => {
const report = await checks({ cliToken: { path: "/run/pi2/cli.token", exists: true, mode: 0o644 } });
expect(statusOf(report, "cli-token")).toBe("fail");
expect(report.ok).toBe(false);
expect(checkCliToken({ path: "/run/pi2/cli.token", exists: false, mode: undefined }).status).toBe("warn");
expect(checkCliToken({ path: "/run/pi2/cli.token", exists: true, mode: 0o600 }).status).toBe("ok");
});
it("fails when the socket is missing and no daemon answers", async () => {
const report = await checks({
socket: { path: "/run/pi2/d.sock", exists: false },
daemon: { reachable: false, error: "connection refused" },
port: { configured: 7676, bound: false },
});
expect(statusOf(report, "socket")).toBe("fail");
expect(statusOf(report, "daemon")).toBe("fail");
expect(statusOf(report, "protocol")).toBe("fail");
expect(report.ok).toBe(false);
// A free port is fine on its own.
expect(statusOf(report, "port")).toBe("ok");
});
it("fails on a protocol version mismatch", async () => {
const report = await checks({ daemon: { reachable: true, port: 7676, protocolVersion: 2 } });
expect(statusOf(report, "protocol")).toBe("fail");
expect(checkProtocol({ reachable: true, port: 1, protocolVersion: 1 }).status).toBe("ok");
});
it("warns when web/dist, the service manager or linger are unavailable", async () => {
const report = await checks({
webDist: { path: "/repo/web/dist", exists: false },
serviceManager: { name: "systemd", available: false },
linger: { checked: true, enabled: false },
});
expect(statusOf(report, "web-dist")).toBe("warn");
expect(statusOf(report, "service-manager")).toBe("warn");
expect(statusOf(report, "linger")).toBe("warn");
expect(report.ok).toBe(true);
});
it("turns a throwing probe into a failing check", async () => {
const report = await runDoctor([
{ name: "boom", run: () => Promise.reject(new Error("kaboom")) },
{ name: "fine", run: () => ({ name: "fine", status: "ok", detail: "ok" }) },
]);
expect(report.ok).toBe(false);
expect(report.checks[0]).toEqual({ name: "boom", status: "fail", detail: "kaboom" });
});
});
describe("doctor output", () => {
it("renders a table with an overall line", async () => {
const text = formatReport(await checks());
expect(text).toContain("check");
expect(text).toContain("detail");
expect(text).toContain("runtime-dir");
expect(text.trimEnd().endsWith("overall: ok")).toBe(true);
const failed = formatReport(await checks({ nodeVersion: "v18.0.0" }));
expect(failed).toContain("FAIL");
expect(failed.trimEnd().endsWith("overall: FAILED")).toBe(true);
});
it("emits a stable JSON shape", async () => {
const parsed = JSON.parse(reportToJson(await checks())) as {
ok: boolean;
checks: { name: string; status: string; detail: string }[];
};
expect(parsed.ok).toBe(true);
expect(Array.isArray(parsed.checks)).toBe(true);
expect(Object.keys(parsed.checks[0]!)).toEqual(["name", "status", "detail"]);
expect(parsed.checks.find((check) => check.name === "daemon")?.detail).toContain("http://127.0.0.1:7676");
});
});
describe("version helpers", () => {
it("parses and compares versions", () => {
expect(parseVersion("v22.1.0")).toEqual([22, 1, 0]);
expect(parseVersion("22.10.3")).toEqual([22, 10, 3]);
expect(parseVersion("nope")).toBeUndefined();
expect(versionAtLeast([22, 0, 0], [22, 0, 0])).toBe(true);
expect(versionAtLeast([22, 0, 0], [22, 1, 0])).toBe(false);
expect(versionAtLeast([23, 0, 0], [22, 9, 9])).toBe(true);
expect(parseNvimVersion("NVIM v0.10.2\nBuild type: Release")).toBe("0.10.2");
expect(parseNvimVersion("NVIM v0.9.5")).toBe("0.9.5");
expect(parseNvimVersion("garbage")).toBeUndefined();
expect(checkNode("v22.0.0").status).toBe("ok");
expect(checkNode("garbage").status).toBe("fail");
expect(checkNvim({ found: true, path: "/n", version: "v0.10.0" }).status).toBe("ok");
expect(checkLinger({ checked: false }).status).toBe("ok");
});
});
describe("collectContext", () => {
let dir: string;
beforeEach(() => {
dir = tempDir("pi2-doctor-");
process.env.PI2_RUNTIME_DIR = join(dir, "run");
process.env.PI2_DATA_DIR = join(dir, "data");
mkdirSync(join(dir, "run"), { recursive: true, mode: 0o700 });
writeFileSync(join(dir, "run", "cli.token"), "t".repeat(64), { mode: 0o600 });
writeFileSync(join(dir, "run", "d.sock"), "");
process.env.PI2_STATIC_DIR = join(dir, "web");
});
afterEach(() => {
clearRuntimeEnv();
removeDir(dir);
});
it("gathers real state through injectable probes", async () => {
const home = join(dir, "home");
mkdirSync(join(home, ".local", "share", "nvim", "lazy", "pi2.nvim", "lua", "pi", "web"), {
recursive: true,
});
writeFileSync(join(home, ".local", "share", "nvim", "lazy", "pi2.nvim", "lua", "pi", "web", "bridge.lua"), "");
const ctx = await collectContext({
platform: "linux",
home,
uid: 1000,
env: { PATH: "/usr/bin", PI2_RUNTIME_DIR: join(dir, "run"), PI2_STATIC_DIR: join(dir, "web") },
which: (command) => `/usr/bin/${command}`,
run: async (command, args) => {
if (command === "nvim") return { ok: true, stdout: "NVIM v0.10.2\nBuild type: Release\n", stderr: "" };
if (command === "pi") return { ok: true, stdout: "1.8.0\n", stderr: "" };
if (command === "loginctl" && args[1] === "1000") return { ok: true, stdout: "Linger=yes\n", stderr: "" };
return { ok: false, stdout: "", stderr: "unexpected" };
},
daemonInfo: async () => ({ port: 7712, protocolVersion: 1 }),
});
expect(ctx.nvim).toEqual({ found: true, path: "/usr/bin/nvim", version: "v0.10.2" });
expect(ctx.pi.version).toBe("1.8.0");
expect(ctx.plugin.bridgeFound).toBe(true);
expect(ctx.runtime.exists).toBe(true);
expect(ctx.cliToken.mode).toBe(0o600);
expect(ctx.socket.exists).toBe(true);
expect(ctx.daemon).toEqual({ reachable: true, port: 7712, protocolVersion: 1 });
expect(ctx.port).toEqual({ configured: 7712, bound: true });
expect(ctx.serviceManager).toEqual({ name: "systemd", available: true });
expect(ctx.linger).toMatchObject({ checked: true, enabled: true });
expect(ctx.webDist.path).toBe(join(dir, "web"));
const report = await runDoctor(defaultProbes(ctx));
// web/dist does not exist here, everything else passes.
expect(report.ok).toBe(true);
expect(report.checks.find((check) => check.name === "web-dist")?.status).toBe("warn");
});
it("records a missing daemon as unreachable", async () => {
const ctx = await collectContext({
platform: "darwin",
home: join(dir, "home"),
env: { PATH: "/usr/bin", PI2_RUNTIME_DIR: join(dir, "run") },
which: (command) => (command === "launchctl" ? "/bin/launchctl" : `/usr/bin/${command}`),
run: async () => ({ ok: false, stdout: "", stderr: "not found" }),
daemonInfo: async () => ({ error: "connection refused" }),
});
expect(ctx.daemon.reachable).toBe(false);
expect(ctx.linger.checked).toBe(false);
expect(ctx.serviceManager.name).toBe("launchd");
const report = await runDoctor(defaultProbes(ctx));
expect(report.ok).toBe(false);
expect(report.checks.some((check) => check.name === "linger")).toBe(false);
});
});
+55
View File
@@ -0,0 +1,55 @@
/** Shared helpers for the CLI specs (temp dirs, silent logger, bare config). */
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Config, Limits } from "../../src/config.js";
import type { Logger } from "../../src/core/interfaces.js";
export const TEST_LIMITS: Limits = {
maxBodyBytes: 8 * 1024 * 1024,
maxFrameBytes: 8 * 1024 * 1024,
maxConnections: 64,
};
export function tempDir(prefix = "pi2d-cli-"): string {
return mkdtempSync(join(tmpdir(), prefix));
}
export function removeDir(dir: string): void {
rmSync(dir, { recursive: true, force: true });
}
export function testConfig(overrides: Partial<Config> = {}): Config {
const base: Config = {
host: "127.0.0.1",
port: 0,
staticDir: "/nonexistent-web-dist",
corsOrigins: [],
limits: TEST_LIMITS,
tokenPath: "/tmp/pi2d-cli-test.sock.token",
deviceStorePath: "/tmp/pi2d-cli-test-devices.json",
};
return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } };
}
export const silentLogger: Logger = {
debug: () => undefined,
info: () => undefined,
warn: () => undefined,
error: () => undefined,
child: () => silentLogger,
};
export function setRuntimeEnv(dir: string): void {
process.env.PI2_RUNTIME_DIR = join(dir, "run");
process.env.PI2_DATA_DIR = join(dir, "data");
process.env.PI2_STATE_DIR = join(dir, "state");
process.env.PI2_PORT = "0";
process.env.PI2_STATIC_DIR = join(dir, "web");
}
export function clearRuntimeEnv(): void {
for (const key of ["PI2_RUNTIME_DIR", "PI2_DATA_DIR", "PI2_STATE_DIR", "PI2_PORT", "PI2_STATIC_DIR"]) {
delete process.env[key];
}
}
+128
View File
@@ -0,0 +1,128 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createServer, type AddressInfo, type Server as NetServer } from "node:net";
import { AuthStore } from "../../src/daemon/auth.js";
import type { ServerDeps } from "../../src/daemon/server.js";
import { isAddressInUse, listenWithRetry, withPort } from "../../src/cli/listen.js";
import { FakeBus, FakeInstanceManager, FakeWorkspaceStore } from "../daemon/fakes.js";
import { removeDir, silentLogger, tempDir, testConfig } from "./helpers.js";
async function occupyPort(): Promise<{ port: number; close(): Promise<void> }> {
const server: NetServer = createServer();
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => resolve());
});
const address = server.address() as AddressInfo;
return {
port: address.port,
close: (): Promise<void> => new Promise((resolve) => server.close(() => resolve())),
};
}
describe("listenWithRetry", () => {
let dir: string;
let deps: ServerDeps;
const cleanups: (() => Promise<void>)[] = [];
beforeEach(() => {
dir = tempDir("pi2-listen-");
deps = {
auth: new AuthStore({ path: `${dir}/devices.json` }),
instances: new FakeInstanceManager(),
workspaces: new FakeWorkspaceStore([]),
bus: new FakeBus(),
logger: silentLogger,
daemonId: "d-listen",
};
});
afterEach(async () => {
for (const cleanup of cleanups.splice(0)) await cleanup();
removeDir(dir);
});
it("binds port 0 without retrying", async () => {
const config = testConfig({ port: 0 });
const server = await listenWithRetry(config, deps, { retries: 9 });
cleanups.push(() => server.close());
expect(server.port).toBeGreaterThan(0);
expect(server.url).toContain(`:${server.port}`);
});
it("walks to the next port when the default is taken", async () => {
const busy = await occupyPort();
cleanups.push(() => busy.close());
const config = testConfig({
port: busy.port,
corsOrigins: [`http://127.0.0.1:${busy.port}`, `http://localhost:${busy.port}`],
});
const retries: { from: number; to: number }[] = [];
const server = await listenWithRetry(config, deps, {
retries: 9,
onRetry: (info) => retries.push({ from: info.from, to: info.to }),
});
cleanups.push(() => server.close());
expect(server.port).toBeGreaterThan(busy.port);
expect(retries[0]).toEqual({ from: busy.port, to: busy.port + 1 });
// The derived CORS origins follow the effective port.
expect(server.config.corsOrigins).toEqual([
`http://127.0.0.1:${server.port}`,
`http://localhost:${server.port}`,
]);
});
it("fails fast on an explicit port", async () => {
const busy = await occupyPort();
cleanups.push(() => busy.close());
const config = testConfig({ port: busy.port });
await expect(listenWithRetry(config, deps, { retries: 0 })).rejects.toSatisfy(isAddressInUse);
});
it("stops retrying when the budget is exhausted", async () => {
const busy = await occupyPort();
cleanups.push(() => busy.close());
const busyNext = createServer();
await new Promise<void>((resolve, reject) => {
busyNext.once("error", reject);
busyNext.listen(busy.port + 1, "127.0.0.1", () => resolve());
});
cleanups.push(() => new Promise<void>((resolve) => busyNext.close(() => resolve())));
const config = testConfig({ port: busy.port });
let attempts = 0;
await expect(
listenWithRetry(config, deps, {
retries: 1,
onRetry: () => {
attempts += 1;
},
}),
).rejects.toSatisfy(isAddressInUse);
expect(attempts).toBe(1);
});
});
describe("withPort", () => {
it("rewrites derived origins and keeps custom ones", () => {
const config = testConfig({
port: 7676,
corsOrigins: ["http://127.0.0.1:7676", "http://localhost:7676", "https://pi2.example"],
});
expect(withPort(config, 7676)).toBe(config);
expect(withPort(config, 7678).corsOrigins).toEqual([
"http://127.0.0.1:7678",
"http://localhost:7678",
"https://pi2.example",
]);
expect(withPort(config, 7678).port).toBe(7678);
});
});
describe("isAddressInUse", () => {
it("recognises EADDRINUSE only", () => {
expect(isAddressInUse(Object.assign(new Error("busy"), { code: "EADDRINUSE" }))).toBe(true);
expect(isAddressInUse(Object.assign(new Error("denied"), { code: "EACCES" }))).toBe(false);
expect(isAddressInUse(new Error("plain"))).toBe(false);
});
});
+201
View File
@@ -0,0 +1,201 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
acquireLock,
assessLock,
LockError,
readDaemonJson,
readLockFile,
writeDaemonJson,
type DaemonLock,
} from "../../src/cli/lock.js";
import { PROTOCOL_VERSION } from "../../src/protocol/types.js";
import { removeDir, tempDir } from "./helpers.js";
const BOOT = "boot-abc";
function payload(overrides: Partial<DaemonLock> = {}): Omit<DaemonLock, "pid" | "bootId"> & { pid?: number; bootId?: string } {
return {
port: 7676,
daemonId: "d-test",
startedAt: 1_700_000_000_000,
protocolVersion: PROTOCOL_VERSION,
...overrides,
};
}
describe("daemon lock", () => {
let dir: string;
let lockPath: string;
beforeEach(() => {
dir = tempDir("pi2-lock-");
mkdirSync(dir, { recursive: true });
lockPath = join(dir, "daemon.lock");
});
afterEach(() => removeDir(dir));
it("creates the lock with the payload and mode 0600", () => {
const handle = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT });
expect(handle.lock).toEqual({
pid: process.pid,
bootId: BOOT,
port: 7676,
daemonId: "d-test",
startedAt: 1_700_000_000_000,
protocolVersion: PROTOCOL_VERSION,
});
expect(readLockFile(lockPath)).toEqual(handle.lock);
expect(statSync(lockPath).mode & 0o777).toBe(0o600);
expect(readFileSync(lockPath, "utf8").endsWith("\n")).toBe(true);
handle.release();
expect(existsSync(lockPath)).toBe(false);
});
it("refuses a second daemon while the holder is alive", () => {
const first = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT });
expect(() => acquireLock({ lockPath, payload: payload({ daemonId: "d-two" }), bootId: () => BOOT })).toThrow(
LockError,
);
try {
acquireLock({ lockPath, payload: payload({ daemonId: "d-two" }), bootId: () => BOOT });
} catch (error) {
const lockError = error as LockError;
expect(lockError.code).toBe("E_LOCKED");
expect(lockError.holder?.daemonId).toBe("d-test");
expect(lockError.holder?.pid).toBe(process.pid);
expect(lockError.message).toContain("--force");
}
// The original lock survived the failed attempt.
expect(readLockFile(lockPath)?.daemonId).toBe("d-test");
first.release();
});
it("overrides a live lock with --force", () => {
const first = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT });
const forced = acquireLock({ lockPath, payload: payload({ daemonId: "d-forced" }), bootId: () => BOOT, force: true });
expect(forced.lock.daemonId).toBe("d-forced");
expect(readLockFile(lockPath)?.daemonId).toBe("d-forced");
// The displaced daemon must not delete the new lock on shutdown.
first.release();
expect(readLockFile(lockPath)?.daemonId).toBe("d-forced");
forced.release();
expect(existsSync(lockPath)).toBe(false);
});
it("treats a dead pid as stale", () => {
acquireLock({ lockPath, payload: payload({ daemonId: "d-dead" }), bootId: () => BOOT });
const handle = acquireLock({
lockPath,
payload: payload({ daemonId: "d-new" }),
bootId: () => BOOT,
isPidAlive: () => false,
});
expect(handle.lock.daemonId).toBe("d-new");
handle.release();
});
it("treats a pid from a previous boot as stale (pid reuse)", () => {
acquireLock({ lockPath, payload: payload({ daemonId: "d-old" }), bootId: () => "boot-old" });
const handle = acquireLock({
lockPath,
payload: payload({ daemonId: "d-new" }),
bootId: () => BOOT,
isPidAlive: () => true,
});
expect(handle.lock.daemonId).toBe("d-new");
expect(handle.lock.bootId).toBe(BOOT);
handle.release();
});
it("ignores a malformed lock file (crash during write)", () => {
writeFileSync(lockPath, "{not json");
const handle = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT });
expect(readLockFile(lockPath)?.daemonId).toBe("d-test");
handle.release();
});
it("update() rewrites the payload in place", () => {
const handle = acquireLock({ lockPath, payload: payload({ port: 0 }), bootId: () => BOOT });
handle.update({ port: 7712 });
expect(handle.lock.port).toBe(7712);
expect(readLockFile(lockPath)?.port).toBe(7712);
expect(readLockFile(lockPath)?.daemonId).toBe("d-test");
handle.release();
});
it("assessLock explains why a lock is stale", () => {
const lock: DaemonLock = {
pid: 42,
bootId: BOOT,
port: 7676,
daemonId: "d-1",
startedAt: 1,
protocolVersion: PROTOCOL_VERSION,
};
expect(assessLock(lock, { isPidAlive: () => true, bootId: () => BOOT })).toEqual({ live: true, reason: "alive" });
expect(assessLock(lock, { isPidAlive: () => false, bootId: () => BOOT })).toEqual({
live: false,
reason: "no-pid",
});
expect(assessLock(lock, { isPidAlive: () => true, bootId: () => "other" })).toEqual({
live: false,
reason: "boot-changed",
});
});
});
describe("daemon.json", () => {
let dir: string;
let lockPath: string;
let daemonJsonPath: string;
beforeEach(() => {
dir = tempDir("pi2-daemonjson-");
lockPath = join(dir, "daemon.lock");
daemonJsonPath = join(dir, "daemon.json");
});
afterEach(() => removeDir(dir));
it("publishes the same payload as the lock, mode 0600", () => {
const handle = acquireLock({
lockPath,
payload: { port: 7713, daemonId: "d-json", startedAt: 5, protocolVersion: PROTOCOL_VERSION },
bootId: () => BOOT,
});
writeDaemonJson(handle.lock, daemonJsonPath);
const discovered = readDaemonJson(daemonJsonPath);
expect(discovered).toEqual({
pid: process.pid,
bootId: BOOT,
port: 7713,
daemonId: "d-json",
startedAt: 5,
protocolVersion: PROTOCOL_VERSION,
});
expect(statSync(daemonJsonPath).mode & 0o777).toBe(0o600);
handle.release();
});
it("is removed by release() and missing files read as undefined", () => {
const handle = acquireLock({
lockPath,
payload: { port: 7676, daemonId: "d-json", startedAt: 5, protocolVersion: PROTOCOL_VERSION },
bootId: () => BOOT,
});
writeDaemonJson(handle.lock, daemonJsonPath);
handle.release();
expect(existsSync(daemonJsonPath)).toBe(false);
expect(readDaemonJson(daemonJsonPath)).toBeUndefined();
// A discovery file owned by another daemon is left alone.
writeDaemonJson({ ...handle.lock, daemonId: "d-other" }, daemonJsonPath);
expect(readDaemonJson(daemonJsonPath)?.daemonId).toBe("d-other");
});
});
+484
View File
@@ -0,0 +1,484 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdirSync, realpathSync, writeFileSync } from "node:fs";
import { basename, join } from "node:path";
import type { DaemonClient } from "../../src/cli/pi2.js";
import { CliError, createClient, main, resolveEndpoint, runAttach, runDoctorCommand, runPairing, runStatus } from "../../src/cli/pi2.js";
import { writeDaemonJson, type DaemonLock } from "../../src/cli/lock.js";
import { writeCliToken } from "../../src/cli/token.js";
import type { WorkspaceInfo } from "../../src/protocol/types.js";
import { PROTOCOL_VERSION } from "../../src/protocol/types.js";
import { removeDir, tempDir } from "./helpers.js";
const DAEMON: DaemonLock = {
pid: 1234,
bootId: "boot-1",
port: 7712,
daemonId: "d-test",
startedAt: 1,
protocolVersion: PROTOCOL_VERSION,
};
function workspace(cwd: string, overrides: Partial<WorkspaceInfo> = {}): WorkspaceInfo {
return {
workspaceId: "ws-1",
cwd,
name: basename(cwd),
trusted: true,
exists: true,
sessionCount: 0,
liveCount: 0,
lastActiveAt: null,
instance: null,
...overrides,
};
}
function instance(overrides: Partial<NonNullable<WorkspaceInfo["instance"]>> = {}): NonNullable<WorkspaceInfo["instance"]> {
return {
workspaceId: "ws-1",
instanceId: "i-1",
status: "ready",
nvimPid: 4321,
pluginVersion: "1.8.0",
hasUI: true,
attachedClients: 0,
listenAddr: "/run/user/1000/pi2/i/ab12.sock",
startedAt: 1,
...overrides,
};
}
interface FakeData {
workspaces?: WorkspaceInfo[];
info?: Record<string, unknown>;
resources?: Record<string, unknown>;
health?: Record<string, unknown>;
pair?: Record<string, unknown>;
postError?: Error;
}
function fakeClient(data: FakeData = {}): DaemonClient & { calls: string[] } {
const calls: string[] = [];
return {
calls,
baseUrl: `http://127.0.0.1:${DAEMON.port}`,
token: "cli-token",
daemon: DAEMON,
async get<T>(path: string): Promise<T> {
calls.push(path);
if (path === "/api/v1/workspaces") return (data.workspaces ?? []) as unknown as T;
if (path === "/api/v1/info") {
return (data.info ?? {
v: PROTOCOL_VERSION,
daemonId: "d-test",
machineId: "m-test",
platform: "linux",
capabilities: ["ws", "sse"],
limits: { maxBodyBytes: 1, maxFrameBytes: 1, maxConnections: 1 },
}) as unknown as T;
}
if (path === "/api/v1/resources") {
return (data.resources ?? {
instances: [],
totalRssBytes: 0,
physicalMemoryBytes: 16 * 1024 * 1024 * 1024,
warn: false,
}) as unknown as T;
}
if (path === "/api/v1/health") {
return (data.health ?? { ok: true, items: [{ name: "instances", ok: true, detail: "0 connected" }] }) as unknown as T;
}
throw new CliError(`unexpected GET ${path}`);
},
async post(path: string, body: unknown): Promise<{ status: number; body: Record<string, unknown> }> {
calls.push(`${path} ${JSON.stringify(body)}`);
if (data.postError !== undefined) throw data.postError;
if (path === "/api/v1/pair") {
return { status: 202, body: data.pair ?? { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } };
}
throw new CliError(`unexpected POST ${path}`);
},
};
}
interface ExecCall {
command: string;
args: string[];
cwd: string;
}
function recorder(): { calls: ExecCall[]; exec: (command: string, args: string[], options: { cwd: string }) => void } {
const calls: ExecCall[] = [];
return {
calls,
exec: (command, args, options) => {
calls.push({ command, args, cwd: options.cwd });
},
};
}
describe("resolveEndpoint / createClient", () => {
let dir: string;
beforeEach(() => {
dir = tempDir("pi2-cli-ep-");
});
afterEach(() => removeDir(dir));
it("reads daemon.json and cli.token from the runtime dir", () => {
writeDaemonJson(DAEMON, join(dir, "daemon.json"));
const token = writeCliToken(join(dir, "cli.token"));
const endpoint = resolveEndpoint(dir);
expect(endpoint.baseUrl).toBe("http://127.0.0.1:7712");
expect(endpoint.token).toBe(token);
expect(endpoint.daemon.daemonId).toBe("d-test");
const client = createClient({ endpoint });
expect(client.baseUrl).toBe(endpoint.baseUrl);
});
it("explains a missing daemon or token", () => {
expect(() => resolveEndpoint(dir)).toThrowError(/no running pi2d/);
writeDaemonJson(DAEMON, join(dir, "daemon.json"));
expect(() => resolveEndpoint(dir)).toThrowError(/missing CLI token/);
});
it("turns a connection failure into a CliError", async () => {
writeDaemonJson({ ...DAEMON, port: 1 }, join(dir, "daemon.json"));
writeCliToken(join(dir, "cli.token"));
const client = createClient({ endpoint: resolveEndpoint(dir), timeoutMs: 500 });
await expect(client.get("/api/v1/info")).rejects.toThrowError(/cannot reach pi2d/);
});
});
describe("pi2 attach", () => {
let dir: string;
let cwd: string;
beforeEach(() => {
dir = tempDir("pi2-cli-attach-");
cwd = realpathSync(dir);
});
afterEach(() => removeDir(dir));
it("attaches to a ready instance with --remote-ui when a TTY is present", async () => {
const listenAddr = "/run/user/1000/pi2/i/ab12.sock";
const recorded = recorder();
const code = await runAttach({
cwd,
isTTY: true,
exec: recorded.exec,
client: () => fakeClient({ workspaces: [workspace(cwd, { instance: instance({ listenAddr }) })] }),
});
expect(code).toBe(0);
expect(recorded.calls).toEqual([
{ command: "nvim", args: ["--server", listenAddr, "--remote-ui"], cwd },
]);
});
it("prints the command instead of exec when stdout is not a TTY", async () => {
const listenAddr = "/run/user/1000/pi2/i/ab12.sock";
const recorded = recorder();
const lines: string[] = [];
const code = await runAttach({
cwd,
isTTY: false,
exec: recorded.exec,
print: (line) => lines.push(line),
client: () => fakeClient({ workspaces: [workspace(cwd, { instance: instance({ listenAddr }) })] }),
});
expect(code).toBe(0);
expect(recorded.calls).toEqual([]);
expect(lines).toEqual([`nvim --server ${listenAddr} --remote-ui`]);
});
it("starts a plain nvim when the workspace has no instance", async () => {
const recorded = recorder();
await runAttach({
cwd,
isTTY: true,
exec: recorded.exec,
client: () => fakeClient({ workspaces: [workspace(cwd)] }),
});
expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]);
});
it("does not attach to a headless instance without a listen address", async () => {
const recorded = recorder();
await runAttach({
cwd,
isTTY: true,
exec: recorded.exec,
client: () =>
fakeClient({
workspaces: [workspace(cwd, { instance: instance({ listenAddr: null, hasUI: false }) })],
}),
});
expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]);
});
it("does not attach to a stopping instance", async () => {
const recorded = recorder();
await runAttach({
cwd,
isTTY: true,
exec: recorded.exec,
client: () => fakeClient({ workspaces: [workspace(cwd, { instance: instance({ status: "stopping" }) })] }),
});
expect(recorded.calls[0]?.args).toEqual([]);
});
it("resolves the path argument against cwd (realpath comparison)", async () => {
const sub = join(cwd, "packages", "app");
mkdirSync(sub, { recursive: true });
const recorded = recorder();
const client = fakeClient({
workspaces: [workspace(realpathSync(sub), { instance: instance({ listenAddr: "/tmp/nvim.sock" }) })],
});
await runAttach({ cwd, path: "packages/app", isTTY: true, exec: recorded.exec, client: () => client });
expect(recorded.calls[0]).toEqual({
command: "nvim",
args: ["--server", "/tmp/nvim.sock", "--remote-ui"],
cwd: realpathSync(sub),
});
});
it("falls back to plain nvim when the daemon is not running", async () => {
const recorded = recorder();
const warnings: string[] = [];
const code = await runAttach({
cwd,
isTTY: true,
exec: recorded.exec,
warn: (line) => warnings.push(line),
client: () => {
throw new CliError("no running pi2d (daemon.json missing)");
},
});
expect(code).toBe(0);
expect(warnings[0]).toContain("no running pi2d");
expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]);
});
it("falls back to plain nvim when the HTTP call fails", async () => {
const recorded = recorder();
const warnings: string[] = [];
await runAttach({
cwd,
isTTY: true,
exec: recorded.exec,
warn: (line) => warnings.push(line),
client: () => {
const client = fakeClient();
client.get = async () => {
throw new CliError("cannot reach pi2d");
};
return client;
},
});
expect(warnings[0]).toContain("cannot reach pi2d");
expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]);
});
});
describe("pi2 status", () => {
it("renders a table with daemon, instances, resources and health", async () => {
const lines: string[] = [];
const client = fakeClient({
workspaces: [
workspace("/repo/pi2", {
name: "pi2",
liveCount: 2,
instance: instance({ status: "ready", hasUI: true }),
}),
],
resources: {
instances: [{ workspaceId: "ws-1", instanceId: "i-1", nvimPid: 4321, rssBytes: 1024 * 1024, sessions: 2, hasUI: true }],
totalRssBytes: 1024 * 1024,
physicalMemoryBytes: 16 * 1024 * 1024 * 1024,
warn: false,
},
});
const code = await runStatus({ client, print: (line) => lines.push(line) });
expect(code).toBe(0);
const text = lines.join("\n");
expect(text).toContain("daemon http://127.0.0.1:7712");
expect(text).toContain("pi2");
expect(text).toContain("/repo/pi2");
expect(text).toContain("ready");
expect(text).toContain("resources 1 instance(s)");
expect(text).toContain("health ok");
});
it("emits JSON and exits 1 when health is not ok", async () => {
const lines: string[] = [];
const code = await runStatus({
json: true,
print: (line) => lines.push(line),
client: fakeClient({ health: { ok: false, items: [{ name: "static", ok: false, detail: "missing" }] } }),
});
expect(code).toBe(1);
const parsed = JSON.parse(lines.join("\n")) as {
daemon: { url: string; v: number };
instances: unknown[];
resources: { totalRssBytes: number };
health: { ok: boolean };
};
expect(parsed.daemon.url).toBe("http://127.0.0.1:7712");
expect(parsed.daemon.v).toBe(PROTOCOL_VERSION);
expect(parsed.instances).toEqual([]);
expect(parsed.health.ok).toBe(false);
});
});
describe("pi2 pairing", () => {
it("posts with the local token and prints url, code and qr payload", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } });
const code = await runPairing({ client, print: (line) => lines.push(line) });
expect(code).toBe(0);
const text = lines.join("\n");
expect(text).toContain("url http://127.0.0.1:7712/pair/ABCD2345");
expect(text).toContain("code ABCD2345");
expect(text).toContain('"code":"ABCD2345"');
expect(text).toContain('"v":1');
expect(client.calls[0]).toBe("/api/v1/pair {}");
});
it("exits non-zero when the daemon rejects the request", async () => {
await expect(
runPairing({ client: fakeClient({ postError: new CliError("pair failed: E_UNAUTHORIZED") }) }),
).rejects.toThrowError(/E_UNAUTHORIZED/);
});
});
describe("pi2 doctor (daemon probe wiring)", () => {
it("reports the live daemon port and protocol version", async () => {
const report = await runDoctorCommand({ client: () => fakeClient() });
const daemon = report.checks.find((check) => check.name === "daemon");
expect(daemon?.status).toBe("ok");
expect(daemon?.detail).toContain("http://127.0.0.1:7712");
expect(report.checks.find((check) => check.name === "protocol")?.status).toBe("ok");
expect(report.checks.find((check) => check.name === "port")?.detail).toBe("7712 bound by pi2d");
});
it("reports an unreachable daemon without throwing", async () => {
const report = await runDoctorCommand({
client: () => {
throw new CliError("no running pi2d (daemon.json missing)");
},
});
const daemon = report.checks.find((check) => check.name === "daemon");
expect(daemon?.status).toBe("fail");
expect(daemon?.detail).toContain("no running pi2d");
expect(report.ok).toBe(false);
});
});
describe("pi2 main", () => {
it("prints usage and version", async () => {
const out: string[] = [];
expect(await main([], { out: (line) => out.push(line) })).toBe(0);
expect(out.join("\n")).toContain("pi2 attach [path]");
out.length = 0;
expect(await main(["--version"], { out: (line) => out.push(line) })).toBe(0);
expect(out[0]).toMatch(/^pi2 \d+\.\d+\.\d+/);
});
it("rejects unknown commands and options with exit 2", async () => {
const err: string[] = [];
expect(await main(["nope"], { err: (line) => err.push(line) })).toBe(2);
expect(err[0]).toBe('pi2: unknown command "nope"');
err.length = 0;
expect(await main(["attach", "--bogus"], { err: (line) => err.push(line) })).toBe(2);
expect(err[0]).toContain("unknown option --bogus");
});
it("routes status --json through the injected client", async () => {
const out: string[] = [];
const client = fakeClient();
expect(await main(["status", "--json"], { out: (line) => out.push(line), client: () => client })).toBe(0);
expect(JSON.parse(out.join("\n"))).toMatchObject({ daemon: { url: "http://127.0.0.1:7712" } });
});
it("reports a missing daemon for status with exit 1", async () => {
const err: string[] = [];
const code = await main(["status"], {
err: (line) => err.push(line),
client: () => {
throw new CliError("no running pi2d");
},
});
expect(code).toBe(1);
expect(err[0]).toBe("pi2: no running pi2d");
});
it("routes attach through runAttach with an injected exec", async () => {
const recorded = recorder();
const code = await main(["attach"], {
cwd: process.cwd(),
isTTY: true,
exec: recorded.exec,
client: () => fakeClient({ workspaces: [] }),
});
expect(code).toBe(0);
expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd: process.cwd() }]);
});
it("installs a service with --write through the injected writer", async () => {
const out: string[] = [];
const writes: { path: string; content: string }[] = [];
const code = await main(["install-service", "--write"], {
out: (line) => out.push(line),
platform: "linux",
servicePaths: {
nodePath: "/usr/bin/node",
scriptPath: "/repo/dist/cli/pi2d.js",
stateDir: "/state",
homeDir: "/home/u",
pathEnv: "/usr/bin",
},
writeFile: (path, content) => writes.push({ path, content }),
});
expect(code).toBe(0);
expect(writes[0]?.path).toBe(join("/home/u/.config/systemd/user", "pi2d.service"));
expect(writes[0]?.content).toContain("ExecStart=/usr/bin/node /repo/dist/cli/pi2d.js --foreground");
expect(out.join("\n")).toContain("systemctl --user enable --now pi2d.service");
});
it("prints the service on the default dry-run", async () => {
const out: string[] = [];
const code = await main(["install-service"], {
out: (line) => out.push(line),
platform: "darwin",
servicePaths: {
nodePath: "/usr/bin/node",
scriptPath: "/repo/dist/cli/pi2d.js",
stateDir: "/state",
homeDir: "/home/u",
pathEnv: "/usr/bin",
},
});
expect(code).toBe(0);
expect(out.join("\n")).toContain("<key>KeepAlive</key>");
expect(out.join("\n")).toContain("would write /home/u/Library/LaunchAgents/com.pi2.pi2d.plist");
});
it("renders doctor output and exits 1 when a check fails", async () => {
const out: string[] = [];
const code = await main(["doctor", "--json"], {
out: (line) => out.push(line),
doctor: async () => ({ ok: false, checks: [{ name: "node", status: "fail", detail: "v18.0.0" }] }),
});
expect(code).toBe(1);
expect(JSON.parse(out.join("\n"))).toEqual({
ok: false,
checks: [{ name: "node", status: "fail", detail: "v18.0.0" }],
});
});
});
+112
View File
@@ -0,0 +1,112 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { chmodSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs } from "../../src/cli/pi2d.js";
import { readCliToken, tokenPerms, writeCliToken } from "../../src/cli/token.js";
import { UsageError } from "../../src/cli/util.js";
import { removeDir, tempDir } from "./helpers.js";
describe("parseDaemonArgs", () => {
it("defaults to nothing set (foreground daemon, config defaults)", () => {
expect(parseDaemonArgs([])).toEqual({ force: false, foreground: false, help: false, version: false });
});
it("parses every flag, in both value syntaxes", () => {
expect(parseDaemonArgs(["--port", "7676", "--host", "0.0.0.0", "--static-dir=/srv/ui", "--force", "--foreground"])).toEqual({
port: 7676,
host: "0.0.0.0",
staticDir: "/srv/ui",
force: true,
foreground: true,
help: false,
version: false,
});
expect(parseDaemonArgs(["-p", "0"]).port).toBe(0);
expect(parseDaemonArgs(["-f"]).force).toBe(true);
expect(parseDaemonArgs(["--help"]).help).toBe(true);
expect(parseDaemonArgs(["-h"]).help).toBe(true);
expect(parseDaemonArgs(["-V"]).version).toBe(true);
});
it("rejects bad ports and stray positionals", () => {
for (const port of ["abc", "-1", "70000", "1.5"]) {
expect(() => parseDaemonArgs(["--port", port])).toThrow(UsageError);
}
expect(() => parseDaemonArgs(["extra"])).toThrow(/unexpected argument extra/);
expect(() => parseDaemonArgs(["--nope"])).toThrow(/unknown option --nope/);
expect(() => parseDaemonArgs(["--port"])).toThrow(/requires a value/);
});
it("retries the default port at most +9", () => {
expect(DEFAULT_PORT_RETRIES).toBe(9);
});
});
describe("pi2d main (non-listening paths)", () => {
it("prints usage for --help", async () => {
const out: string[] = [];
const code = await main(["--help"], { out: (line) => out.push(line), err: () => undefined });
expect(code).toBe(0);
expect(out.join("\n")).toContain("Usage: pi2d [options]");
expect(out.join("\n")).toContain("--static-dir");
});
it("prints the version for --version", async () => {
const out: string[] = [];
const code = await main(["--version"], { out: (line) => out.push(line), err: () => undefined });
expect(code).toBe(0);
expect(out[0]).toMatch(/^pi2d \d+\.\d+\.\d+/);
});
it("exits 2 on bad arguments", async () => {
const err: string[] = [];
const code = await main(["--port", "nope"], {
out: () => undefined,
err: (line) => err.push(line),
});
expect(code).toBe(2);
expect(err[0]).toContain("--port must be an integer");
});
});
describe("local CLI token", () => {
let dir: string;
beforeEach(() => {
dir = tempDir("pi2-token-");
});
afterEach(() => removeDir(dir));
it("is 32 bytes of hex, written atomically with mode 0600", () => {
const path = join(dir, "run", "cli.token");
const token = writeCliToken(path);
expect(token).toMatch(/^[0-9a-f]{64}$/);
expect(statSync(path).mode & 0o777).toBe(0o600);
expect(readFileSync(path, "utf8").trim()).toBe(token);
expect(readCliToken(path)).toBe(token);
expect(tokenPerms(path)).toEqual({ exists: true, mode: 0o600 });
});
it("rotates on every start", () => {
const path = join(dir, "cli.token");
const first = writeCliToken(path);
const second = writeCliToken(path);
expect(second).not.toBe(first);
expect(readCliToken(path)).toBe(second);
});
it("reads as undefined when missing", () => {
const path = join(dir, "missing.token");
expect(readCliToken(path)).toBeUndefined();
expect(tokenPerms(path)).toEqual({ exists: false, mode: undefined });
});
it("tightens the mode of a pre-existing world-readable token", () => {
const path = join(dir, "cli.token");
writeCliToken(path);
chmodSync(path, 0o644);
writeCliToken(path);
expect(statSync(path).mode & 0o777).toBe(0o600);
});
});
+188
View File
@@ -0,0 +1,188 @@
import { describe, expect, it } from "vitest";
import { join } from "node:path";
import {
defaultScriptPath,
launchAgentDir,
renderLaunchAgent,
renderService,
renderSystemdUnit,
serviceDir,
systemdUserDir,
type ServicePaths,
} from "../../src/cli/service.js";
import { runInstallService, runUninstallService } from "../../src/cli/pi2.js";
const paths: ServicePaths = {
nodePath: "/opt/node/bin/node",
scriptPath: "/repo/dist/cli/pi2d.js",
stateDir: "/home/u/.local/state/pi2",
homeDir: "/home/u",
pathEnv: "/opt/node/bin:/usr/bin:/bin",
};
const LINUX_UNIT = `[Unit]
Description=pi2 daemon (pi2d)
After=network.target
[Service]
Type=simple
ExecStart=/opt/node/bin/node /repo/dist/cli/pi2d.js --foreground
Environment=PATH=/opt/node/bin:/usr/bin:/bin
Restart=on-failure
RestartSec=2
KillSignal=SIGTERM
TimeoutStopSec=15
[Install]
WantedBy=default.target
`;
const MAC_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.pi2.pi2d</string>
<key>ProgramArguments</key>
<array>
<string>/opt/node/bin/node</string>
<string>/repo/dist/cli/pi2d.js</string>
<string>--foreground</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/node/bin:/usr/bin:/bin</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/home/u/.local/state/pi2/pi2d.log</string>
<key>StandardErrorPath</key>
<string>/home/u/.local/state/pi2/pi2d.err.log</string>
</dict>
</plist>
`;
describe("systemd user unit", () => {
it("renders the unit (snapshot)", () => {
expect(renderSystemdUnit(paths)).toBe(LINUX_UNIT);
});
it("adds extra Environment= entries", () => {
const unit = renderSystemdUnit({ ...paths, env: { PI2_PORT: "7676", PI2_LOG_LEVEL: "debug" } });
expect(unit).toContain("Environment=PATH=/opt/node/bin:/usr/bin:/bin");
expect(unit).toContain("Environment=PI2_PORT=7676");
expect(unit).toContain("Environment=PI2_LOG_LEVEL=debug");
expect(unit.indexOf("Environment=PI2_PORT")).toBeGreaterThan(unit.indexOf("ExecStart="));
});
it("quotes values with spaces", () => {
const unit = renderSystemdUnit({ ...paths, scriptPath: "/repo dir/cli/pi2d.js" });
expect(unit).toContain('ExecStart=/opt/node/bin/node "/repo dir/cli/pi2d.js" --foreground');
});
it("targets ~/.config/systemd/user and honours XDG_CONFIG_HOME", () => {
expect(systemdUserDir(paths)).toBe("/home/u/.config/systemd/user");
expect(systemdUserDir({ ...paths, configHome: "/xdg" })).toBe("/xdg/systemd/user");
const service = renderService("linux", paths);
expect(service.path).toBe("/home/u/.config/systemd/user/pi2d.service");
expect(service.name).toBe("pi2d.service");
expect(serviceDir(service)).toBe("/home/u/.config/systemd/user");
expect(service.commands).toEqual([
"systemctl --user daemon-reload",
"systemctl --user enable --now pi2d.service",
]);
expect(service.removeCommands).toContain("systemctl --user disable --now pi2d.service");
});
});
describe("LaunchAgent plist", () => {
it("renders the plist (snapshot)", () => {
expect(renderLaunchAgent(paths)).toBe(MAC_PLIST);
});
it("escapes XML in paths", () => {
const plist = renderLaunchAgent({ ...paths, nodePath: "/opt/a&b/node" });
expect(plist).toContain("<string>/opt/a&amp;b/node</string>");
});
it("targets ~/Library/LaunchAgents", () => {
expect(launchAgentDir(paths)).toBe("/home/u/Library/LaunchAgents");
const service = renderService("darwin", paths);
expect(service.path).toBe("/home/u/Library/LaunchAgents/com.pi2.pi2d.plist");
expect(service.name).toBe("com.pi2.pi2d.plist");
expect(service.commands[0]).toContain("launchctl bootstrap gui/$(id -u)");
expect(service.removeCommands[0]).toContain("launchctl bootout");
});
it("resolves dist/cli/pi2d.js next to the built CLI", () => {
expect(defaultScriptPath()).toMatch(/dist\/cli\/pi2d\.js$/);
});
});
describe("install-service / uninstall-service commands", () => {
it("prints the unit on --dry-run and writes nothing", () => {
const lines: string[] = [];
const writes: string[] = [];
const code = runInstallService({
platform: "linux",
paths,
write: false,
print: (line) => lines.push(line),
writeFile: (path) => writes.push(path),
});
expect(code).toBe(0);
expect(writes).toEqual([]);
expect(lines.join("\n")).toContain("[Service]");
expect(lines.join("\n")).toContain("would write /home/u/.config/systemd/user/pi2d.service");
expect(lines.join("\n")).toContain("systemctl --user enable --now pi2d.service");
});
it("writes the unit on --write and prints the enable commands", () => {
const lines: string[] = [];
const writes: { path: string; content: string }[] = [];
const code = runInstallService({
platform: "linux",
paths,
write: true,
print: (line) => lines.push(line),
writeFile: (path, content) => writes.push({ path, content }),
});
expect(code).toBe(0);
expect(writes).toEqual([{ path: join("/home/u/.config/systemd/user", "pi2d.service"), content: LINUX_UNIT }]);
expect(lines[0]).toBe("wrote /home/u/.config/systemd/user/pi2d.service (mode 0644)");
expect(lines.join("\n")).toContain("systemctl --user daemon-reload");
});
it("uninstall removes the unit only with --write", () => {
const removed: string[] = [];
const dry: string[] = [];
expect(
runUninstallService({
platform: "darwin",
paths,
write: false,
print: (line) => dry.push(line),
removeFile: (path) => removed.push(path),
}),
).toBe(0);
expect(removed).toEqual([]);
expect(dry.join("\n")).toContain("would remove /home/u/Library/LaunchAgents/com.pi2.pi2d.plist");
const lines: string[] = [];
expect(
runUninstallService({
platform: "darwin",
paths,
write: true,
print: (line) => lines.push(line),
removeFile: (path) => removed.push(path),
}),
).toBe(0);
expect(removed).toEqual(["/home/u/Library/LaunchAgents/com.pi2.pi2d.plist"]);
expect(lines.join("\n")).toContain("launchctl bootout");
});
});
+102
View File
@@ -0,0 +1,102 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { PROTOCOL_VERSION } from "../../src/protocol/types.js";
import { writeCliToken } from "../../src/cli/token.js";
import { wireDaemon, type WiredDaemon } from "../../src/cli/wiring.js";
import { clearRuntimeEnv, removeDir, setRuntimeEnv, silentLogger, tempDir } from "./helpers.js";
describe("wireDaemon", () => {
let dir: string;
let wired: WiredDaemon | undefined;
beforeEach(() => {
dir = tempDir();
setRuntimeEnv(dir);
mkdirSync(join(dir, "web"), { recursive: true });
writeFileSync(join(dir, "web", "index.html"), "<!doctype html><title>pi2</title><div id=app></div>");
mkdirSync(join(dir, "sessions"), { recursive: true });
});
afterEach(async () => {
if (wired !== undefined) await wired.close();
wired = undefined;
clearRuntimeEnv();
removeDir(dir);
});
it("boots on port 0 with temp dirs and serves info, health and the static UI", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
const token = writeCliToken(wired.cliTokenPath);
const server = await wired.start();
expect(server.port).toBeGreaterThan(0);
expect(wired.config.port).toBe(server.port);
expect(wired.config.host).toBe("127.0.0.1");
expect(wired.deps.daemonId).toMatch(/^d-/);
expect(wired.deps.instances).toBe(wired.instanceManager);
expect(wired.deps.workspaces).toBe(wired.workspaceStore);
expect(wired.deps.auth).toBe(wired.auth);
const info = await fetch(`${server.url}/api/v1/info`);
expect(info.status).toBe(200);
const infoBody = (await info.json()) as { v: number; daemonId: string; capabilities: string[] };
expect(infoBody.v).toBe(PROTOCOL_VERSION);
expect(infoBody.daemonId).toBe(wired.deps.daemonId);
expect(infoBody.capabilities).toContain("ws");
const health = await fetch(`${server.url}/api/v1/health`);
expect(health.status).toBe(200);
const healthBody = (await health.json()) as { ok: boolean; items: { name: string; ok: boolean }[] };
expect(healthBody.ok).toBe(true);
expect(healthBody.items.find((item) => item.name === "static")?.ok).toBe(true);
const page = await fetch(`${server.url}/`);
expect(page.status).toBe(200);
expect(page.headers.get("content-type")).toContain("text/html");
expect(await page.text()).toContain("<div id=app>");
// The minted CLI token authenticates as the local admin device.
const authorized = await fetch(`${server.url}/api/v1/workspaces`, {
headers: { authorization: `Bearer ${token}` },
});
expect(authorized.status).toBe(200);
expect(Array.isArray(await authorized.json())).toBe(true);
const anonymous = await fetch(`${server.url}/api/v1/workspaces`);
expect(anonymous.status).toBe(401);
});
it("starts the plugin unix socket in the configured runtime dir", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
const { existsSync } = await import("node:fs");
expect(existsSync(join(dir, "run", "d.sock"))).toBe(true);
expect(existsSync(join(dir, "run", "d.sock.token"))).toBe(true);
await wired.close();
wired = undefined;
expect(existsSync(join(dir, "run", "d.sock"))).toBe(false);
});
it("resolves workspace cwd through the store and rejects unknown workspaces", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
await expect(wired.instanceManager.ensure("ws-missing", { timeoutMs: 100 })).rejects.toMatchObject({
code: "E_NOT_FOUND",
});
});
it("is idempotent on start()", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
const first = await wired.start();
const second = await wired.start();
expect(second).toBe(first);
});
it("close() is idempotent", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
await wired.start();
await wired.close();
await wired.close();
wired = undefined;
});
});