fix(daemon): forward snapshot entries and map workspace errors

- Preserve the snapshot entries tail in the cache and WS frames (cold,
  cached and bus paths), so the browser receives {state, entries}.
- Await a plugin snapshot on the first subscribe of a fresh session.
- Return E_FORBIDDEN (403) for workspace paths outside PI2_WORKSPACE_ROOTS.
- Mint cli.token only after the singleton lock is held, so a second daemon
  cannot invalidate the running one.
- Add hostname/os/version/uptimeMs/pid/port to /api/v1/info and make
  /health reflect instance, workspace and auth state.
This commit is contained in:
yuez committed 2026-10-21 20:42:02 +08:00
1 parent 31f36302bd
commit 5572ac0d84
15 files changed
+661 -22

No files matched your search

+58 -3
View File
@@ -1,10 +1,12 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { chmodSync, readFileSync, statSync } from "node:fs";
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs } from "../../src/cli/pi2d.js";
import { acquireLock } from "../../src/cli/lock.js";
import { readCliToken, tokenPerms, writeCliToken } from "../../src/cli/token.js";
import { UsageError } from "../../src/cli/util.js";
import { removeDir, tempDir } from "./helpers.js";
import { PROTOCOL_VERSION } from "../../src/protocol/types.js";
import { clearRuntimeEnv, removeDir, setRuntimeEnv, tempDir } from "./helpers.js";
describe("parseDaemonArgs", () => {
it("defaults to nothing set (foreground daemon, config defaults)", () => {
@@ -77,7 +79,6 @@ describe("local CLI 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);
@@ -110,3 +111,57 @@ describe("local CLI token", () => {
expect(statSync(path).mode & 0o777).toBe(0o600);
});
});
describe("pi2d singleton lock vs cli.token", () => {
let dir: string;
let tokenPath: string;
beforeEach(() => {
dir = tempDir("pi2d-main-lock-");
setRuntimeEnv(dir);
mkdirSync(join(dir, "web"), { recursive: true });
tokenPath = join(dir, "run", "cli.token");
});
afterEach(() => {
clearRuntimeEnv();
removeDir(dir);
});
function holdLock(): ReturnType<typeof acquireLock> {
return acquireLock({
payload: {
port: 0,
daemonId: "d-holder",
startedAt: Date.now(),
protocolVersion: PROTOCOL_VERSION,
},
});
}
it("does not rotate cli.token when another daemon holds the lock", async () => {
mkdirSync(join(dir, "run"), { recursive: true });
const original = writeCliToken(tokenPath);
const holder = holdLock();
try {
const err: string[] = [];
const code = await main([], { out: () => undefined, err: (line) => err.push(line) });
expect(code).toBe(1);
expect(err.join("\n")).toContain("another pi2d is running");
expect(readCliToken(tokenPath)).toBe(original);
} finally {
holder.release();
}
});
it("does not create cli.token before the lock is acquired", async () => {
const holder = holdLock();
try {
const code = await main([], { out: () => undefined, err: () => undefined });
expect(code).toBe(1);
expect(existsSync(tokenPath)).toBe(false);
} finally {
holder.release();
}
});
});
+25
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import { DaemonError, isRetryableCode, statusForCode, toErrorPayload } from "../../src/daemon/errors.js";
import { InstanceError } from "../../src/instances/errors.js";
import { ERROR_CODES } from "../../src/protocol/errors.js";
import { WorkspaceError } from "../../src/workspaces/errors.js";
describe("protocol error mapping", () => {
const expected: [string, number][] = [
@@ -43,4 +45,27 @@ describe("protocol error mapping", () => {
const forbidden = new DaemonError(ERROR_CODES.FORBIDDEN, "nope", { details: { origin: "x" } });
expect(toErrorPayload(forbidden).body).toMatchObject({ code: ERROR_CODES.FORBIDDEN, details: { origin: "x" } });
});
it("preserves protocol codes raised by the workspace and instance layers", () => {
const outside = new WorkspaceError(ERROR_CODES.FORBIDDEN, "workspace path is outside the allowed roots: /etc");
expect(toErrorPayload(outside)).toMatchObject({
status: 403,
body: { code: ERROR_CODES.FORBIDDEN, retryable: false },
});
const missing = new WorkspaceError(ERROR_CODES.NOT_FOUND, "cwd does not exist: /nope");
expect(toErrorPayload(missing).status).toBe(404);
const unavailable = new InstanceError(ERROR_CODES.INSTANCE_UNAVAILABLE, "no instance", true, {
workspaceId: "ws-1",
});
expect(toErrorPayload(unavailable)).toMatchObject({
status: 503,
body: { code: ERROR_CODES.INSTANCE_UNAVAILABLE, retryable: true, details: { workspaceId: "ws-1" } },
});
// Node errno codes must not be mistaken for protocol codes.
const errno = Object.assign(new Error("no such file"), { code: "ENOENT" });
expect(toErrorPayload(errno).body.code).toBe(ERROR_CODES.INTERNAL);
});
});
+1
View File
@@ -39,6 +39,7 @@ export interface HarnessOptions {
wsOverrides?: {
maxBufferedBytes?: number;
closeBufferedBytes?: number;
snapshotWaitMs?: number;
measureBufferedAmount?: (socket: unknown) => number;
};
}
+71
View File
@@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import * as os from "node:os";
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
import { createHarness, TEST_LIMITS, type Harness } from "./harness.js";
import { DaemonError } from "../../src/daemon/errors.js";
import { ERROR_CODES } from "../../src/protocol/errors.js";
import { WorkspaceError } from "../../src/workspaces/errors.js";
describe("HTTP API", () => {
let h: Harness;
@@ -41,6 +43,13 @@ describe("HTTP API", () => {
expect(body.daemonId).toBe("d-test");
expect(body.machineId).toBe("m-test");
expect(body.limits).toEqual(TEST_LIMITS);
expect(body.hostname).toBe(os.hostname());
expect(body.os).toBe(`${os.platform()} ${os.release()}`);
expect(body.version).toMatch(/^\d+\.\d+\.\d+/);
expect(body.uptimeMs).toBeTypeOf("number");
expect(body.uptimeMs as number).toBeGreaterThanOrEqual(0);
expect(body.pid).toBe(process.pid);
expect(body.port).toBe(h.server.port);
const health = await fetch(`${h.url}/api/v1/health`);
expect(health.status).toBe(200);
@@ -50,6 +59,49 @@ describe("HTTP API", () => {
expect(healthBody.items.every((item) => item.ok)).toBe(true);
});
it("reflects degraded instances and missing workspaces in health items", async () => {
h.instances.states.get("ws-1")!.status = "degraded";
h.workspaces.workspaces.get("ws-1")!.exists = false;
const res = await fetch(`${h.url}/api/v1/health`);
expect(res.status).toBe(200);
const body = (await res.json()) as {
ok: boolean;
items: { name: string; ok: boolean; detail: string }[];
};
expect(body.ok).toBe(false);
expect(body.items.find((item) => item.name === "instances")).toMatchObject({ ok: false });
expect(body.items.find((item) => item.name === "instances")?.detail).toContain("degraded");
expect(body.items.find((item) => item.name === "workspaces")).toMatchObject({ ok: false });
expect(body.items.find((item) => item.name === "workspaces")?.detail).toContain("missing");
expect(body.items.find((item) => item.name === "auth")?.ok).toBe(true);
});
it("stays healthy when some discovered workspaces are ghosts", async () => {
h.workspaces.workspaces.set("ws-2", makeWorkspaceInfo("ws-2", { exists: false }));
const res = await fetch(`${h.url}/api/v1/health`);
expect(res.status).toBe(200);
const body = (await res.json()) as { items: { name: string; ok: boolean; detail: string }[] };
const workspaces = body.items.find((item) => item.name === "workspaces");
expect(workspaces?.ok).toBe(true);
expect(workspaces?.detail).toContain("1 missing");
});
it("marks auth unhealthy without a device token or local CLI token", async () => {
const bare = await createHarness();
try {
const res = await fetch(`${bare.url}/api/v1/health`);
expect(res.status).toBe(200);
const body = (await res.json()) as { ok: boolean; items: { name: string; ok: boolean; detail: string }[] };
const authItem = body.items.find((item) => item.name === "auth");
expect(authItem?.ok).toBe(false);
expect(authItem?.detail).toContain("0 devices");
} finally {
await bare.cleanup();
}
});
it("requires a bearer token for all other API reads", async () => {
const anonymous = await fetch(`${h.url}/api/v1/workspaces`);
expect(anonymous.status).toBe(401);
@@ -158,6 +210,24 @@ describe("HTTP API", () => {
expect(body.retryable).toBe(false);
});
it("returns 403 E_FORBIDDEN when workspace.add is outside the allowed roots", async () => {
h.workspaces.add = async () => {
throw new WorkspaceError(
ERROR_CODES.FORBIDDEN,
"workspace path is outside the allowed roots: /etc",
);
};
const res = await fetch(
`${h.url}/api/v1/cmd`,
authed({ method: "POST", body: JSON.stringify({ method: "workspace.add", params: { cwd: "/etc" } }) }),
);
expect(res.status).toBe(403);
const body = (await res.json()) as { code: string; retryable: boolean; message: string };
expect(body.code).toBe(ERROR_CODES.FORBIDDEN);
expect(body.retryable).toBe(false);
expect(body.message).toContain("outside the allowed roots");
});
it("enforces the body limit", async () => {
const small = await createHarness({ config: { limits: { ...TEST_LIMITS, maxBodyBytes: 16 } } });
try {
@@ -238,6 +308,7 @@ describe("HTTP API", () => {
const list = await fetch(`${h.url}/api/v1/devices`, authed());
expect(list.status).toBe(200);
const devices = (await list.json()) as { id: string; tokenHash?: string }[];
expect(Array.isArray(devices)).toBe(true);
expect(devices).toHaveLength(1);
expect(devices[0]!.tokenHash).toBeUndefined();
+9
View File
@@ -39,6 +39,15 @@ describe("static file surface", () => {
expect(await res.text()).toContain("<div id=app>");
});
it("serves the SPA shell for pairing deep links", async () => {
for (const path of ["/pair/ABCD1234", "/pair"]) {
const res = await fetch(`${h.url}${path}`);
expect(res.status).toBe(200);
expect(res.headers.get("cache-control")).toBe("no-store");
expect(await res.text()).toContain("<div id=app>");
}
});
it("returns 404 for a missing asset with an extension", async () => {
const res = await fetch(`${h.url}/assets/missing-deadbeef.js`);
expect(res.status).toBe(404);
+172
View File
@@ -1,11 +1,37 @@
import { once } from "node:events";
import { afterEach, describe, expect, it } from "vitest";
import WebSocket from "ws";
import type { Entry, SessionState } from "../../src/protocol/types.js";
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
import type { FakeConnection } from "./fakes.js";
import { createHarness, type Harness } from "./harness.js";
type Record0 = Record<string, unknown> & { type?: string };
/** A plugin snapshot payload (docs/protocol.md §2: `{state, entries[]}`). */
type SnapshotPayload = { state: SessionState; entries?: Entry[] };
/**
* `PluginSocketConnection` exposes the cached snapshot through `snapshotEntry`;
* the test fake only implements the frozen `snapshot` accessor, so the entries
* relay is exercised by attaching the richer accessor locally.
*/
function withSnapshotEntry(
conn: FakeConnection,
read: (sessionId: string) => SnapshotPayload | undefined,
): void {
(conn as unknown as { snapshotEntry: (sessionId: string) => SnapshotPayload | undefined }).snapshotEntry =
read;
}
/** A short entries tail, the way the plugin sends one after `state`. */
function makeEntryTail(): Entry[] {
return [
{ id: "m1", role: "user", ts: 1, blocks: [{ type: "text", text: "hi" }], done: true },
{ id: "m2", role: "assistant", ts: 2, blocks: [{ type: "text", text: "hello" }], done: true },
];
}
class WsClient {
readonly messages: Record0[] = [];
private waiters: {
@@ -155,12 +181,158 @@ describe("WebSocket surface", () => {
expect(snapshot.epoch).toBe("i-ws-1");
expect(snapshot.seq).toBe(7);
expect((snapshot.payload as { state: { sessionId: string } }).state.sessionId).toBe("s1");
// State-only plugin snapshots stay state-only: no invented `entries` tail.
expect(Object.keys(snapshot.payload as Record<string, unknown>)).toEqual(["state"]);
expect(h.instances.ensureCalls).toContain("ws-1");
expect(conn.subscribed.has("s1")).toBe(true);
await client.close();
});
it("relays the cached snapshot `entries` tail on subscribe", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
const state = makeSessionState("s1", "ws-1");
const entries = makeEntryTail();
conn.snapshots.set("s1", state);
conn.seqs.set("s1", 7);
withSnapshotEntry(conn, (sessionId) => (sessionId === "s1" ? { state, entries } : undefined));
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
const snapshot = await client.next((message) => message.type === "snapshot");
const payload = snapshot.payload as SnapshotPayload;
expect(snapshot.epoch).toBe("i-ws-1");
expect(snapshot.seq).toBe(7);
expect(payload.state.sessionId).toBe("s1");
expect(payload.entries).toEqual(entries);
await client.close();
});
it("waits for the plugin snapshot when the cache is cold", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
conn.seqs.set("s1", 4);
// The plugin replies to sub.subscribe asynchronously, after the client
// has already subscribed. The daemon must not return an empty subscribe.
conn.subscribe = (sessionId) => {
conn.subscribed.add(sessionId);
setTimeout(() => conn.snapshots.set(sessionId, makeSessionState(sessionId, "ws-1")), 40);
};
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
const snapshot = await client.next((message) => message.type === "snapshot", 3000);
expect(snapshot.sessionId).toBe("s1");
expect(snapshot.epoch).toBe("i-ws-1");
expect(snapshot.seq).toBe(4);
expect((snapshot.payload as { state: { sessionId: string } }).state.sessionId).toBe("s1");
expect(Object.keys(snapshot.payload as Record<string, unknown>)).toEqual(["state"]);
await client.close();
});
it("relays the `entries` tail for a cold subscribe", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
const state = makeSessionState("s1", "ws-1");
const entries = makeEntryTail();
conn.seqs.set("s1", 4);
let reply: SnapshotPayload | undefined;
withSnapshotEntry(conn, (sessionId) => (sessionId === "s1" ? reply : undefined));
// The plugin answers `sub.subscribe` asynchronously with {state, entries}.
conn.subscribe = (sessionId) => {
conn.subscribed.add(sessionId);
setTimeout(() => {
conn.snapshots.set(sessionId, state);
reply = { state, entries };
}, 40);
};
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
const snapshot = await client.next((message) => message.type === "snapshot", 3000);
const payload = snapshot.payload as SnapshotPayload;
expect(snapshot.epoch).toBe("i-ws-1");
expect(snapshot.seq).toBe(4);
expect(payload.state.sessionId).toBe("s1");
expect(payload.entries).toEqual(entries);
await client.close();
});
it("forwards plugin snapshots published on the bus and dedupes the echo", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
const initial = makeSessionState("s1", "ws-1");
conn.snapshots.set("s1", initial);
conn.seqs.set("s1", 3);
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
await client.next((message) => message.type === "snapshot");
const updated = { ...initial, name: "Renamed by plugin" };
const record = {
v: 1,
type: "snapshot",
workspaceId: "ws-1",
sessionId: "s1",
epoch: "i-ws-1",
seq: 5,
ts: 1,
payload: { state: updated },
};
h.bus.publish(record);
const snapshot = await client.next((message) => message.type === "snapshot" && message.seq === 5);
expect((snapshot.payload as { state: { name: string } }).state.name).toBe("Renamed by plugin");
expect(Object.keys(snapshot.payload as Record<string, unknown>)).toEqual(["state"]);
// The plugin also caches that snapshot, so a subsequent subscribe relay
// must not send the same (epoch, seq) twice.
conn.snapshots.set("s1", updated);
conn.seqs.set("s1", 5);
h.bus.publish(record);
await client.expectSilence();
await client.close();
});
it("forwards the `entries` tail of a snapshot published on the bus", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
const initial = makeSessionState("s1", "ws-1");
conn.snapshots.set("s1", initial);
conn.seqs.set("s1", 3);
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
await client.next((message) => message.type === "snapshot");
const updated = { ...initial, name: "Renamed by plugin" };
const entries = makeEntryTail();
const record = {
v: 1,
type: "snapshot",
workspaceId: "ws-1",
sessionId: "s1",
epoch: "i-ws-1",
seq: 5,
ts: 1,
payload: { state: updated, entries },
};
h.bus.publish(record);
const snapshot = await client.next((message) => message.type === "snapshot" && message.seq === 5);
const payload = snapshot.payload as SnapshotPayload;
expect(payload.state.name).toBe("Renamed by plugin");
expect(payload.entries).toEqual(entries);
// Dedupe is still by (epoch, seq): the identical record is not re-sent.
h.bus.publish(record);
await client.expectSilence();
await client.close();
});
it("sends resync_required when epoch or seq do not match", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
+80
View File
@@ -1,6 +1,7 @@
import type { Socket } from "node:net";
import { describe, expect, it, afterEach, beforeEach } from "vitest";
import { daemonSocketPath } from "../../src/core/paths.js";
import type { Entry } from "../../src/protocol/types.js";
import { PluginSocketConnection } from "../../src/instances/connection.js";
import { PluginServer } from "../../src/instances/plugin-server.js";
import { makeSessionState } from "../daemon/fakes.js";
@@ -179,6 +180,85 @@ describe("PluginSocketConnection", () => {
expect(connection.hasSession("s1")).toBe(true);
});
it("publishes snapshots onto the bus for browser fan-out", async () => {
const state = makeSessionState("s1", "ws-test");
client.send({
v: 1,
type: "snapshot",
sessionId: "s1",
epoch: "e1",
seq: 3,
ts: 1733234400999,
payload: { state },
});
const published = await waitFor(() => bus.published.find((record) => record.type === "snapshot"));
expect(published.v).toBe(1);
expect(published.workspaceId).toBe("ws-test");
expect(published.sessionId).toBe("s1");
expect(published.epoch).toBe("e1");
expect(published.seq).toBe(3);
expect(published.ts).toBe(1733234400999);
expect(asRecord(asRecord(published.payload).state).sessionId).toBe("s1");
});
it("keeps the plugin's `entries` tail next to the state it belongs to", async () => {
const state = makeSessionState("s1", "ws-test");
const entries: Entry[] = [
{ id: "m1", role: "user", ts: 1, blocks: [{ type: "text", text: "hi" }], done: true },
{ id: "m2", role: "assistant", ts: 2, blocks: [{ type: "text", text: "hello" }], done: true },
];
client.send({
v: 1,
type: "snapshot",
sessionId: "s1",
epoch: "e1",
seq: 4,
payload: { state, entries },
});
const cached = await waitFor(() => connection.snapshotEntry("s1"));
expect(cached.entries).toEqual(entries);
expect(cached.state.sessionId).toBe("s1");
expect(connection.snapshot("s1")?.sessionId).toBe("s1");
const published = await waitFor(() => bus.published.find((record) => record.type === "snapshot"));
expect(asRecord(published.payload).entries).toEqual(entries);
expect(asRecord(asRecord(published.payload).state).sessionId).toBe("s1");
});
it("does not invent an `entries` tail for state-only snapshots", async () => {
const state = makeSessionState("s1", "ws-test");
client.send({
v: 1,
type: "snapshot",
sessionId: "s1",
epoch: "e1",
seq: 5,
payload: { state },
});
const cached = await waitFor(() => connection.snapshotEntry("s1"));
expect(cached.entries).toBeUndefined();
expect("entries" in cached).toBe(false);
const published = await waitFor(() => bus.published.find((record) => record.type === "snapshot"));
expect("entries" in asRecord(published.payload)).toBe(false);
});
it("drops the cached `entries` tail when the epoch changes", async () => {
const state = makeSessionState("s1", "ws-test");
const entries: Entry[] = [
{ id: "m1", role: "user", ts: 1, blocks: [{ type: "text", text: "hi" }], done: true },
];
client.send({ v: 1, type: "snapshot", sessionId: "s1", epoch: "e1", seq: 6, payload: { state, entries } });
await waitFor(() => connection.snapshotEntry("s1")?.entries !== undefined);
client.send({ v: 1, type: "snapshot", sessionId: "s1", epoch: "e2", seq: 1, payload: { state } });
await waitFor(() => connection.snapshotEntry("s1")?.epoch === "e2");
expect(connection.snapshotEntry("s1")?.entries).toBeUndefined();
});
it("tracks sessions reported by instance_state", async () => {
client.send({
v: 1,