diff --git a/docs/deployment.md b/docs/deployment.md index 9a8802e..1f1d7b5 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -83,8 +83,10 @@ Flags: Flags are applied to the environment before the config is loaded, so `--port 8000` is equivalent to `PI2_PORT=8000`. -Daemon startup order: mint `cli.token` → take `daemon.lock` → start the plugin +Daemon startup order: take `daemon.lock` → mint `cli.token` → start the plugin unix socket → listen (with port retry) → write `daemon.json` → print the line. +The token is rotated only by the process that owns the lock, so a rejected +second daemon cannot invalidate the running one. ## 4. Configuration @@ -287,7 +289,11 @@ For a login-less service to keep running on Linux enable linger `Environment=` line) . - Managed nvim output: `PI2_STATE_DIR/instances/.log`. - `GET /api/v1/health` → `{ok, items:[{name, ok, detail}]}` (`instances`, - `workspaces`, `auth`, `static`). + `workspaces`, `auth`, `static`). `instances` fails when a managed instance is + `degraded`; `workspaces` fails when every known workspace path is gone (ghost + discovery entries are normal and only shown in `detail`); `auth` fails when + there is neither an active device nor a local `cli.token`; `static` fails when + `PI2_STATIC_DIR` is missing. - `GET /api/v1/diagnostics` → uptime, connection count, event rate, slow queries, device/workspace/instance counts. - `GET /api/v1/resources` → per-instance RSS, total vs physical memory, soft diff --git a/docs/protocol.md b/docs/protocol.md index df1e653..6e584d9 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -79,7 +79,7 @@ Plugin obligations: | Endpoint | Notes | |---|---| -| `GET /api/v1/info` | `{v, daemonId, machineId, platform, capabilities, limits}` | +| `GET /api/v1/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}` | | `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` | | `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) | | `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` | @@ -111,6 +111,10 @@ Client → server: `{"type":"subscribe","payload":{"workspaceId":"ws-1"}}` (work Server → client (same envelope as above): `hello_ack`, `instance_state`, `workspace_update`, `snapshot`, `event`, `presence`, `resync_required`, `dropped`, `error`. +A session `subscribe` is answered with a `snapshot` as soon as the plugin's reply +arrives (the daemon waits briefly for the plugin's `sub.subscribe` snapshot and also +forwards every later plugin snapshot to current subscribers). + `GET /events` (SSE) emits the same `event` records for degraded transports. ## 4. Session state @@ -212,7 +216,7 @@ browser cmd(sessionId=s1) |---|---|---| | `E_BAD_REQUEST` | 400 | malformed JSON / missing field | | `E_UNAUTHORIZED` | 401 | missing/invalid device token | -| `E_FORBIDDEN` | 403 | bad `Origin`, insufficient scope | +| `E_FORBIDDEN` | 403 | bad `Origin`, insufficient scope, cwd outside `PI2_WORKSPACE_ROOTS` | | `E_NOT_FOUND` | 404 | unknown workspace/session/instance | | `E_PROTOCOL_VERSION` | 426 | `v` unsupported | | `E_PAYLOAD_TOO_LARGE` | 413 | body/frame > limits | diff --git a/src/cli/pi2d.ts b/src/cli/pi2d.ts index c3ce61b..5bd8cf1 100644 --- a/src/cli/pi2d.ts +++ b/src/cli/pi2d.ts @@ -4,8 +4,9 @@ * * Responsibilities (and nothing else): * 1. parse args / apply `--port|--host|--static-dir` to the config env - * 2. mint `/cli.token` (32-byte hex, 0600) for local CLI access - * 3. take the singleton lock (`/daemon.lock`, stale-aware, `--force`) + * 2. take the singleton lock (`/daemon.lock`, stale-aware, `--force`) + * 3. only once the lock is ours, mint `/cli.token` (32-byte hex, 0600) + * for local CLI access — a second daemon must never rotate the live token * 4. wire the real dependencies and listen (port 0 allowed, +1..+9 on a busy * default port), then publish `/daemon.json` * 5. print exactly one line: `pi2d listening on http://host:port` @@ -177,7 +178,6 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions try { const runtime = runtimeDir(); ensureDir(runtime, 0o700); - writeCliToken(cliTokenPath(runtime)); const daemonId = `d-${randomUUID()}`; lock = acquireLock({ @@ -189,6 +189,9 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions protocolVersion: PROTOCOL_VERSION, }, }); + // Rotate the local CLI token only when this process owns the lock: + // otherwise a rejected second daemon would invalidate the live one. + writeCliToken(cliTokenPath(runtime)); wired = await wireDaemon({ config, runtime, logger, daemonId }); server = await wired.start({ diff --git a/src/daemon/errors.ts b/src/daemon/errors.ts index 884536f..3fd641e 100644 --- a/src/daemon/errors.ts +++ b/src/daemon/errors.ts @@ -38,6 +38,32 @@ export interface DaemonErrorOptions { details?: Record; } +/** Shape shared by `WorkspaceError` and `InstanceError` (protocol code, not a Node errno). */ +interface ProtocolErrorLike { + code: string; + message: string; + retryable?: unknown; + details?: unknown; +} + +const PROTOCOL_CODE = /^E_[A-Z][A-Z0-9_]*$/; + +function isProtocolErrorLike(error: unknown): error is ProtocolErrorLike { + if (typeof error !== "object" || error === null) return false; + const candidate = error as { code?: unknown; message?: unknown }; + return ( + typeof candidate.code === "string" && + PROTOCOL_CODE.test(candidate.code) && + typeof candidate.message === "string" + ); +} + +function protocolDetails(error: ProtocolErrorLike): Record | undefined { + return typeof error.details === "object" && error.details !== null && !Array.isArray(error.details) + ? (error.details as Record) + : undefined; +} + export class DaemonError extends Error { readonly code: string; readonly status: number; @@ -59,6 +85,16 @@ export class DaemonError extends Error { static from(error: unknown): DaemonError { if (error instanceof DaemonError) return error; + // The workspace/instance layers raise their own error classes with a + // protocol `code`; preserve it (and therefore its HTTP status) instead + // of collapsing every non-DaemonError into E_INTERNAL/500. + if (isProtocolErrorLike(error)) { + const details = protocolDetails(error); + return new DaemonError(error.code, error.message, { + ...(typeof error.retryable === "boolean" ? { retryable: error.retryable } : {}), + ...(details === undefined ? {} : { details }), + }); + } if (error instanceof Error) return new DaemonError(ERROR_CODES.INTERNAL, error.message); return new DaemonError(ERROR_CODES.INTERNAL, String(error)); } diff --git a/src/daemon/http.ts b/src/daemon/http.ts index ad1aeb8..5e4eee2 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -1,5 +1,7 @@ /** Hono application factory for the daemon HTTP surface. */ -import { existsSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; +import { hostname as osHostname, platform as osPlatform, release as osRelease } from "node:os"; +import { fileURLToPath } from "node:url"; import { Hono, type Context } from "hono"; import type { HttpBindings } from "@hono/node-server"; import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/interfaces.js"; @@ -48,6 +50,17 @@ function isLoopback(c: Context): boolean { return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1"; } +/** Daemon package version; falls back to the v1 baseline when package.json is unavailable. */ +function daemonVersion(): string { + try { + const file = fileURLToPath(new URL("../../package.json", import.meta.url)); + const parsed = JSON.parse(readFileSync(file, "utf8")) as { version?: unknown }; + return typeof parsed.version === "string" && parsed.version.trim() !== "" ? parsed.version : "0.1.0"; + } catch { + return "0.1.0"; + } +} + function json(status: number, body: unknown, headers: Record = {}): Response { return new Response(JSON.stringify(body), { status, @@ -155,16 +168,51 @@ export function createApp(deps: AppDeps): Hono { daemonId: deps.daemonId, machineId: deps.machineId ?? deps.daemonId, platform: process.platform, + hostname: osHostname(), + os: `${osPlatform()} ${osRelease()}`, + version: daemonVersion(), + uptimeMs: Math.max(0, now() - startedAt), + pid: process.pid, + port: config.port, capabilities: ["ws", "sse", "devices", "attention"], limits: config.limits, }), ); const health = (c: Context) => { + const instanceStates = instances.list(); + const degraded = instanceStates.filter((instance) => instance.status === "degraded"); + const workspaceList = workspaces.list(); + const present = workspaceList.filter((workspace) => workspace.exists).length; + const missing = workspaceList.length - present; + const activeDevices = auth.listDevices().filter((device) => device.revokedAt === null).length; + const localToken = + auth.localTokenPath !== undefined && auth.localTokenPath !== "" && existsSync(auth.localTokenPath); const items = [ - { name: "instances", ok: true, detail: `${instances.list().length} connected` }, - { name: "workspaces", ok: true, detail: `${workspaces.list().length} registered` }, - { name: "auth", ok: true, detail: `${auth.listDevices().length} devices` }, + { + name: "instances", + ok: degraded.length === 0, + detail: + degraded.length === 0 + ? `${instanceStates.length} connected` + : `${degraded.length} degraded of ${instanceStates.length}`, + }, + { + name: "workspaces", + // Discovery intentionally keeps ghost entries for old sessions, so a + // few missing cwds are normal. Healthy means at least one known + // workspace is still usable (or none are registered yet). + ok: workspaceList.length === 0 || present > 0, + detail: + missing === 0 + ? `${workspaceList.length} registered` + : `${present} of ${workspaceList.length} present (${missing} missing)`, + }, + { + name: "auth", + ok: activeDevices > 0 || localToken, + detail: `${activeDevices} devices${localToken ? " + local token" : ""}`, + }, { name: "static", ok: existsSync(config.staticDir), detail: config.staticDir }, ]; return c.json({ ok: items.every((item) => item.ok), items }); diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 642117d..6c8c877 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -10,6 +10,7 @@ import { attachWsServer, type WsServerHandle } from "./ws.js"; export interface WsServerOverrides { heartbeatMs?: number; authTimeoutMs?: number; + snapshotWaitMs?: number; maxBufferedBytes?: number; closeBufferedBytes?: number; maxConnections?: number; @@ -82,6 +83,7 @@ export async function startServer(config: Config, deps: ServerDeps): Promise number; heartbeatMs?: number; authTimeoutMs?: number; + snapshotWaitMs?: number; maxBufferedBytes?: number; closeBufferedBytes?: number; maxConnections?: number; @@ -66,11 +70,48 @@ interface ClientState { authenticated: boolean; workspaceIds: Set; sessionWorkspaces: Map; + /** Last snapshot (epoch, seq) sent, so a bus echo is not duplicated. */ + snapshotsSent: Map; alive: boolean; dropped: boolean; authTimer: NodeJS.Timeout | undefined; } +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function delay(ms: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(resolve, ms); + timer.unref?.(); + }); +} + +/** Cached snapshot: `state` plus the plugin's optional `entries` tail (docs/protocol.md §2). */ +interface CachedSnapshot { + state: SessionState; + entries?: Entry[]; +} + +/** + * `PluginSocketConnection` caches the whole plugin snapshot, but the frozen + * `PluginConnection` interface only exposes `state`. Duck-type the richer + * accessor so the documented `entries` tail survives the relay to browsers; + * implementations without it simply relay state. + */ +function readSnapshot(connection: PluginConnection, sessionId: string): CachedSnapshot | undefined { + const richer = connection as PluginConnection & { + snapshotEntry?: (id: string) => { state: SessionState; entries?: Entry[] } | undefined; + }; + const entry = richer.snapshotEntry?.(sessionId); + if (entry !== undefined) { + return { state: entry.state, ...(entry.entries === undefined ? {} : { entries: entry.entries }) }; + } + const state = connection.snapshot(sessionId); + return state === undefined ? undefined : { state }; +} + function writeUpgradeRejection(socket: Duplex, status: number, code: string, message: string): void { const body = JSON.stringify(errorBody(code, message)); const reason = status === 403 ? "Forbidden" : status === 401 ? "Unauthorized" : status === 404 ? "Not Found" : "Service Unavailable"; @@ -102,6 +143,7 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle { now = Date.now, heartbeatMs = 30_000, authTimeoutMs = 10_000, + snapshotWaitMs = DEFAULT_SNAPSHOT_WAIT_MS, maxBufferedBytes = 4 * 1024 * 1024, closeBufferedBytes = 8 * 1024 * 1024, maxConnections = config.limits.maxConnections, @@ -185,6 +227,7 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle { const releaseSession = (state: ClientState, sessionId: string): void => { const workspaceId = state.sessionWorkspaces.get(sessionId); state.sessionWorkspaces.delete(sessionId); + state.snapshotsSent.delete(sessionId); if (!workspaceId) return; const others = [...clients].some( (other) => other !== state && other.authenticated && other.sessionWorkspaces.has(sessionId), @@ -205,8 +248,11 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle { sessionId: string, epoch: string, seq: number, - snapshot: SessionState, + snapshot: CachedSnapshot, ): void => { + const previous = state.snapshotsSent.get(sessionId); + if (previous !== undefined && previous.epoch === epoch && previous.seq === seq) return; + state.snapshotsSent.set(sessionId, { epoch, seq }); send(state, { v: 1, type: "snapshot", @@ -214,10 +260,34 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle { epoch, seq, ts: now(), - payload: { state: snapshot }, + // docs/protocol.md §2: a snapshot payload is `{state, entries[]}`. The + // tail is relayed verbatim and only omitted when the plugin omitted it. + payload: + snapshot.entries === undefined + ? { state: snapshot.state } + : { state: snapshot.state, entries: snapshot.entries }, }); }; + /** + * The plugin answers every `sub.subscribe` with a snapshot, but the reply is + * asynchronous. A fresh browser subscription therefore polls the connection + * cache briefly instead of returning no state at all (the first-subscribe bug). + */ + const waitForSnapshot = async ( + connection: PluginConnection, + sessionId: string, + timeoutMs: number, + ): Promise => { + const attempts = Math.max(1, Math.ceil(timeoutMs / SNAPSHOT_POLL_MS)); + for (let attempt = 0; attempt < attempts; attempt += 1) { + const snapshot = readSnapshot(connection, sessionId); + if (snapshot !== undefined) return snapshot; + if (attempt < attempts - 1) await delay(SNAPSHOT_POLL_MS); + } + return readSnapshot(connection, sessionId); + }; + const subscribeSession = async ( state: ClientState, sessionId: string, @@ -258,8 +328,19 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle { return; } } - const snapshot = connection.snapshot(sessionId); - if (snapshot) sendSnapshot(state, sessionId, epoch, lastSeq, snapshot); + const cached = readSnapshot(connection, sessionId); + if (cached) { + sendSnapshot(state, sessionId, epoch, lastSeq, cached); + return; + } + + const snapshot = await waitForSnapshot(connection, sessionId, snapshotWaitMs); + if (snapshot === undefined) { + logger?.debug("no plugin snapshot after subscribe", { sessionId, workspaceId }); + return; + } + // The cache may have advanced (or the epoch changed) while we waited. + sendSnapshot(state, sessionId, epochFor(workspaceId, instanceState), connection.lastSeq(sessionId), snapshot); }; const subscribe = async (state: ClientState, payload: Record): Promise => { @@ -421,6 +502,7 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle { authenticated: device !== null, workspaceIds: new Set(), sessionWorkspaces: new Map(), + snapshotsSent: new Map(), alive: true, dropped: false, authTimer: undefined, @@ -475,7 +557,29 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle { if (!state.authenticated) continue; const sessionMatch = sessionId !== undefined && state.sessionWorkspaces.has(sessionId); const workspaceMatch = workspaceId !== undefined && state.workspaceIds.has(workspaceId); - if (sessionMatch || workspaceMatch) sendEvent(state, record); + if (!sessionMatch && !workspaceMatch) continue; + + // The plugin's snapshot (published by PluginSocketConnection) is state, + // not an event: deliver it through the snapshot path so the client + // render cache is replaced rather than replayed as a delta. + if (type === "snapshot" && sessionId !== undefined) { + const payload = isRecord(record.payload) ? record.payload : {}; + const snapshot = isRecord(payload.state) ? (payload.state as unknown as SessionState) : undefined; + if (snapshot !== undefined) { + // The plugin's `entries` tail rides along with the state it + // belongs to; dropping it would break the documented payload. + const entries = Array.isArray(payload.entries) ? (payload.entries as Entry[]) : undefined; + const relayed: CachedSnapshot = + entries === undefined ? { state: snapshot } : { state: snapshot, entries }; + const fallbackWorkspace = workspaceId ?? state.sessionWorkspaces.get(sessionId) ?? ""; + const epoch = + typeof record.epoch === "string" ? record.epoch : epochFor(fallbackWorkspace, undefined); + const seq = typeof record.seq === "number" ? record.seq : 0; + sendSnapshot(state, sessionId, epoch, seq, relayed); + continue; + } + } + sendEvent(state, record); } }); diff --git a/src/instances/connection.ts b/src/instances/connection.ts index f86cb17..eacc319 100644 --- a/src/instances/connection.ts +++ b/src/instances/connection.ts @@ -13,7 +13,7 @@ import type { Socket } from "node:net"; import type { Bus, Logger, PluginConnection } from "../core/interfaces.js"; import { ERROR_CODES } from "../protocol/errors.js"; -import { PROTOCOL_VERSION, type SessionState } from "../protocol/types.js"; +import { PROTOCOL_VERSION, type Entry, type SessionState } from "../protocol/types.js"; import { InstanceError, errorMessage } from "./errors.js"; export const DEFAULT_COMMAND_TIMEOUT_MS = 25_000; @@ -36,6 +36,11 @@ export interface SnapshotCacheEntry { epoch: string; seq: number; state: SessionState; + /** + * The plugin's `entries` tail sent next to `state` (docs/protocol.md §2). + * `undefined` when the plugin omitted it (state-only snapshot). + */ + entries?: Entry[]; } export interface PluginSocketConnectionOptions { @@ -264,6 +269,7 @@ export class PluginSocketConnection implements PluginConnection { return this.sessions.has(sessionId); } + /** The full cached snapshot: `state` plus the plugin's optional `entries` tail. */ snapshotEntry(sessionId: string): SnapshotCacheEntry | undefined { return this.snapshots.get(sessionId); } @@ -392,6 +398,9 @@ export class PluginSocketConnection implements PluginConnection { const payload = isRecord(record.payload) ? record.payload : {}; const state = isRecord(payload.state) ? (payload.state as unknown as SessionState) : undefined; + // docs/protocol.md §2: `snapshot` carries `{state, entries[]}` — the tail is + // authoritative plugin data, not something the daemon may drop. + const entries = Array.isArray(payload.entries) ? (payload.entries as Entry[]) : undefined; const cached = this.snapshots.get(sessionId); if (cached !== undefined && cached.epoch !== epoch) { @@ -404,6 +413,20 @@ export class PluginSocketConnection implements PluginConnection { epoch, seq: previous !== undefined && previous.epoch === epoch ? Math.max(previous.seq, seq) : seq, state, + ...(entries === undefined ? {} : { entries }), + }); + + // Forward plugin snapshots so browsers subscribed to the session get the + // authoritative state (the WS server fans bus records out to subscribers). + this.bus.publish({ + v: PROTOCOL_VERSION, + type: "snapshot", + workspaceId: this.workspaceId, + sessionId, + epoch, + seq, + ts: asNumber(record.ts) ?? this.now(), + payload, }); } diff --git a/test/cli/pi2d.test.ts b/test/cli/pi2d.test.ts index c108b5f..75636e1 100644 --- a/test/cli/pi2d.test.ts +++ b/test/cli/pi2d.test.ts @@ -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 { + 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(); + } + }); +}); diff --git a/test/daemon/errors.test.ts b/test/daemon/errors.test.ts index 59b1237..0bb35f6 100644 --- a/test/daemon/errors.test.ts +++ b/test/daemon/errors.test.ts @@ -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); + }); }); diff --git a/test/daemon/harness.ts b/test/daemon/harness.ts index f38cab9..3445fdf 100644 --- a/test/daemon/harness.ts +++ b/test/daemon/harness.ts @@ -39,6 +39,7 @@ export interface HarnessOptions { wsOverrides?: { maxBufferedBytes?: number; closeBufferedBytes?: number; + snapshotWaitMs?: number; measureBufferedAmount?: (socket: unknown) => number; }; } diff --git a/test/daemon/http.test.ts b/test/daemon/http.test.ts index c10ae62..53d49d1 100644 --- a/test/daemon/http.test.ts +++ b/test/daemon/http.test.ts @@ -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(); diff --git a/test/daemon/static.test.ts b/test/daemon/static.test.ts index 00c192c..18f01f4 100644 --- a/test/daemon/static.test.ts +++ b/test/daemon/static.test.ts @@ -39,6 +39,15 @@ describe("static file surface", () => { expect(await res.text()).toContain("
"); }); + 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("
"); + } + }); + 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); diff --git a/test/daemon/ws.test.ts b/test/daemon/ws.test.ts index e40ca45..daeffae 100644 --- a/test/daemon/ws.test.ts +++ b/test/daemon/ws.test.ts @@ -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 & { 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)).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)).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)).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")!; diff --git a/test/instances/connection.test.ts b/test/instances/connection.test.ts index d6d2177..c3a65cb 100644 --- a/test/instances/connection.test.ts +++ b/test/instances/connection.test.ts @@ -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,