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

+36
View File
@@ -38,6 +38,32 @@ export interface DaemonErrorOptions {
details?: Record<string, unknown>;
}
/** 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<string, unknown> | undefined {
return typeof error.details === "object" && error.details !== null && !Array.isArray(error.details)
? (error.details as Record<string, unknown>)
: 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));
}
+52 -4
View File
@@ -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<Env>): 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<string, string> = {}): Response {
return new Response(JSON.stringify(body), {
status,
@@ -155,16 +168,51 @@ export function createApp(deps: AppDeps): Hono<Env> {
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<Env>) => {
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 });
+2
View File
@@ -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<Sta
now: deps.now,
heartbeatMs: wsOverrides.heartbeatMs ?? deps.heartbeatMs,
authTimeoutMs: wsOverrides.authTimeoutMs,
snapshotWaitMs: wsOverrides.snapshotWaitMs,
maxBufferedBytes: wsOverrides.maxBufferedBytes,
closeBufferedBytes: wsOverrides.closeBufferedBytes,
maxConnections: wsOverrides.maxConnections,
+111 -7
View File
@@ -8,8 +8,8 @@
import type { Server } from "node:http";
import type { Duplex } from "node:stream";
import { WebSocket, WebSocketServer, type RawData } from "ws";
import type { Bus, InstanceManager, Logger } from "../core/interfaces.js";
import type { InstanceState, SessionState } from "../protocol/types.js";
import type { Bus, InstanceManager, Logger, PluginConnection } from "../core/interfaces.js";
import type { Entry, InstanceState, SessionState } from "../protocol/types.js";
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { isAllowedOrigin, type AuthStore, type DevicePublic } from "./auth.js";
import type { Config } from "../config.js";
@@ -29,6 +29,9 @@ const SERVER_TYPES = new Set([
const CLOSE_UNAUTHORIZED = 4401;
const CLOSE_BAD_MESSAGE = 4400;
const CLOSE_TRY_AGAIN = 1013;
/** How long a fresh subscription waits for the plugin's `snapshot`. */
export const DEFAULT_SNAPSHOT_WAIT_MS = 1_500;
const SNAPSHOT_POLL_MS = 20;
export interface WsServerOptions {
server: Server;
@@ -41,6 +44,7 @@ export interface WsServerOptions {
now?: () => number;
heartbeatMs?: number;
authTimeoutMs?: number;
snapshotWaitMs?: number;
maxBufferedBytes?: number;
closeBufferedBytes?: number;
maxConnections?: number;
@@ -66,11 +70,48 @@ interface ClientState {
authenticated: boolean;
workspaceIds: Set<string>;
sessionWorkspaces: Map<string, string>;
/** Last snapshot (epoch, seq) sent, so a bus echo is not duplicated. */
snapshotsSent: Map<string, { epoch: string; seq: number }>;
alive: boolean;
dropped: boolean;
authTimer: NodeJS.Timeout | undefined;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function delay(ms: number): Promise<void> {
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<CachedSnapshot | undefined> => {
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<string, unknown>): Promise<void> => {
@@ -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);
}
});