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:
1 parent
31f36302bd
commit
5572ac0d84
15 files changed
+661
-22
No files matched your search
+8
-2
@@ -83,8 +83,10 @@ Flags:
|
|||||||
Flags are applied to the environment before the config is loaded, so
|
Flags are applied to the environment before the config is loaded, so
|
||||||
`--port 8000` is equivalent to `PI2_PORT=8000`.
|
`--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.
|
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
|
## 4. Configuration
|
||||||
|
|
||||||
@@ -287,7 +289,11 @@ For a login-less service to keep running on Linux enable linger
|
|||||||
`Environment=` line) .
|
`Environment=` line) .
|
||||||
- Managed nvim output: `PI2_STATE_DIR/instances/<instanceId>.log`.
|
- Managed nvim output: `PI2_STATE_DIR/instances/<instanceId>.log`.
|
||||||
- `GET /api/v1/health` → `{ok, items:[{name, ok, detail}]}` (`instances`,
|
- `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
|
- `GET /api/v1/diagnostics` → uptime, connection count, event rate, slow
|
||||||
queries, device/workspace/instance counts.
|
queries, device/workspace/instance counts.
|
||||||
- `GET /api/v1/resources` → per-instance RSS, total vs physical memory, soft
|
- `GET /api/v1/resources` → per-instance RSS, total vs physical memory, soft
|
||||||
|
|||||||
+6
-2
@@ -79,7 +79,7 @@ Plugin obligations:
|
|||||||
|
|
||||||
| Endpoint | Notes |
|
| 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/health` | `{ok, items:[{name, ok, detail}]}` |
|
||||||
| `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) |
|
| `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) |
|
||||||
| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` |
|
| `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`,
|
Server → client (same envelope as above): `hello_ack`, `instance_state`, `workspace_update`, `snapshot`,
|
||||||
`event`, `presence`, `resync_required`, `dropped`, `error`.
|
`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.
|
`GET /events` (SSE) emits the same `event` records for degraded transports.
|
||||||
|
|
||||||
## 4. Session state
|
## 4. Session state
|
||||||
@@ -212,7 +216,7 @@ browser cmd(sessionId=s1)
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `E_BAD_REQUEST` | 400 | malformed JSON / missing field |
|
| `E_BAD_REQUEST` | 400 | malformed JSON / missing field |
|
||||||
| `E_UNAUTHORIZED` | 401 | missing/invalid device token |
|
| `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_NOT_FOUND` | 404 | unknown workspace/session/instance |
|
||||||
| `E_PROTOCOL_VERSION` | 426 | `v` unsupported |
|
| `E_PROTOCOL_VERSION` | 426 | `v` unsupported |
|
||||||
| `E_PAYLOAD_TOO_LARGE` | 413 | body/frame > limits |
|
| `E_PAYLOAD_TOO_LARGE` | 413 | body/frame > limits |
|
||||||
|
|||||||
+6
-3
@@ -4,8 +4,9 @@
|
|||||||
*
|
*
|
||||||
* Responsibilities (and nothing else):
|
* Responsibilities (and nothing else):
|
||||||
* 1. parse args / apply `--port|--host|--static-dir` to the config env
|
* 1. parse args / apply `--port|--host|--static-dir` to the config env
|
||||||
* 2. mint `<runtime>/cli.token` (32-byte hex, 0600) for local CLI access
|
* 2. take the singleton lock (`<runtime>/daemon.lock`, stale-aware, `--force`)
|
||||||
* 3. take the singleton lock (`<runtime>/daemon.lock`, stale-aware, `--force`)
|
* 3. only once the lock is ours, mint `<runtime>/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
|
* 4. wire the real dependencies and listen (port 0 allowed, +1..+9 on a busy
|
||||||
* default port), then publish `<runtime>/daemon.json`
|
* default port), then publish `<runtime>/daemon.json`
|
||||||
* 5. print exactly one line: `pi2d listening on http://host:port`
|
* 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 {
|
try {
|
||||||
const runtime = runtimeDir();
|
const runtime = runtimeDir();
|
||||||
ensureDir(runtime, 0o700);
|
ensureDir(runtime, 0o700);
|
||||||
writeCliToken(cliTokenPath(runtime));
|
|
||||||
|
|
||||||
const daemonId = `d-${randomUUID()}`;
|
const daemonId = `d-${randomUUID()}`;
|
||||||
lock = acquireLock({
|
lock = acquireLock({
|
||||||
@@ -189,6 +189,9 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
|||||||
protocolVersion: PROTOCOL_VERSION,
|
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 });
|
wired = await wireDaemon({ config, runtime, logger, daemonId });
|
||||||
server = await wired.start({
|
server = await wired.start({
|
||||||
|
|||||||
@@ -38,6 +38,32 @@ export interface DaemonErrorOptions {
|
|||||||
details?: Record<string, unknown>;
|
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 {
|
export class DaemonError extends Error {
|
||||||
readonly code: string;
|
readonly code: string;
|
||||||
readonly status: number;
|
readonly status: number;
|
||||||
@@ -59,6 +85,16 @@ export class DaemonError extends Error {
|
|||||||
|
|
||||||
static from(error: unknown): DaemonError {
|
static from(error: unknown): DaemonError {
|
||||||
if (error instanceof DaemonError) return error;
|
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);
|
if (error instanceof Error) return new DaemonError(ERROR_CODES.INTERNAL, error.message);
|
||||||
return new DaemonError(ERROR_CODES.INTERNAL, String(error));
|
return new DaemonError(ERROR_CODES.INTERNAL, String(error));
|
||||||
}
|
}
|
||||||
|
|||||||
+52
-4
@@ -1,5 +1,7 @@
|
|||||||
/** Hono application factory for the daemon HTTP surface. */
|
/** 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 { Hono, type Context } from "hono";
|
||||||
import type { HttpBindings } from "@hono/node-server";
|
import type { HttpBindings } from "@hono/node-server";
|
||||||
import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/interfaces.js";
|
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";
|
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 {
|
function json(status: number, body: unknown, headers: Record<string, string> = {}): Response {
|
||||||
return new Response(JSON.stringify(body), {
|
return new Response(JSON.stringify(body), {
|
||||||
status,
|
status,
|
||||||
@@ -155,16 +168,51 @@ export function createApp(deps: AppDeps): Hono<Env> {
|
|||||||
daemonId: deps.daemonId,
|
daemonId: deps.daemonId,
|
||||||
machineId: deps.machineId ?? deps.daemonId,
|
machineId: deps.machineId ?? deps.daemonId,
|
||||||
platform: process.platform,
|
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"],
|
capabilities: ["ws", "sse", "devices", "attention"],
|
||||||
limits: config.limits,
|
limits: config.limits,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const health = (c: Context<Env>) => {
|
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 = [
|
const items = [
|
||||||
{ name: "instances", ok: true, detail: `${instances.list().length} connected` },
|
{
|
||||||
{ name: "workspaces", ok: true, detail: `${workspaces.list().length} registered` },
|
name: "instances",
|
||||||
{ name: "auth", ok: true, detail: `${auth.listDevices().length} devices` },
|
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 },
|
{ name: "static", ok: existsSync(config.staticDir), detail: config.staticDir },
|
||||||
];
|
];
|
||||||
return c.json({ ok: items.every((item) => item.ok), items });
|
return c.json({ ok: items.every((item) => item.ok), items });
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { attachWsServer, type WsServerHandle } from "./ws.js";
|
|||||||
export interface WsServerOverrides {
|
export interface WsServerOverrides {
|
||||||
heartbeatMs?: number;
|
heartbeatMs?: number;
|
||||||
authTimeoutMs?: number;
|
authTimeoutMs?: number;
|
||||||
|
snapshotWaitMs?: number;
|
||||||
maxBufferedBytes?: number;
|
maxBufferedBytes?: number;
|
||||||
closeBufferedBytes?: number;
|
closeBufferedBytes?: number;
|
||||||
maxConnections?: number;
|
maxConnections?: number;
|
||||||
@@ -82,6 +83,7 @@ export async function startServer(config: Config, deps: ServerDeps): Promise<Sta
|
|||||||
now: deps.now,
|
now: deps.now,
|
||||||
heartbeatMs: wsOverrides.heartbeatMs ?? deps.heartbeatMs,
|
heartbeatMs: wsOverrides.heartbeatMs ?? deps.heartbeatMs,
|
||||||
authTimeoutMs: wsOverrides.authTimeoutMs,
|
authTimeoutMs: wsOverrides.authTimeoutMs,
|
||||||
|
snapshotWaitMs: wsOverrides.snapshotWaitMs,
|
||||||
maxBufferedBytes: wsOverrides.maxBufferedBytes,
|
maxBufferedBytes: wsOverrides.maxBufferedBytes,
|
||||||
closeBufferedBytes: wsOverrides.closeBufferedBytes,
|
closeBufferedBytes: wsOverrides.closeBufferedBytes,
|
||||||
maxConnections: wsOverrides.maxConnections,
|
maxConnections: wsOverrides.maxConnections,
|
||||||
|
|||||||
+111
-7
@@ -8,8 +8,8 @@
|
|||||||
import type { Server } from "node:http";
|
import type { Server } from "node:http";
|
||||||
import type { Duplex } from "node:stream";
|
import type { Duplex } from "node:stream";
|
||||||
import { WebSocket, WebSocketServer, type RawData } from "ws";
|
import { WebSocket, WebSocketServer, type RawData } from "ws";
|
||||||
import type { Bus, InstanceManager, Logger } from "../core/interfaces.js";
|
import type { Bus, InstanceManager, Logger, PluginConnection } from "../core/interfaces.js";
|
||||||
import type { InstanceState, SessionState } from "../protocol/types.js";
|
import type { Entry, InstanceState, SessionState } from "../protocol/types.js";
|
||||||
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
|
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
|
||||||
import { isAllowedOrigin, type AuthStore, type DevicePublic } from "./auth.js";
|
import { isAllowedOrigin, type AuthStore, type DevicePublic } from "./auth.js";
|
||||||
import type { Config } from "../config.js";
|
import type { Config } from "../config.js";
|
||||||
@@ -29,6 +29,9 @@ const SERVER_TYPES = new Set([
|
|||||||
const CLOSE_UNAUTHORIZED = 4401;
|
const CLOSE_UNAUTHORIZED = 4401;
|
||||||
const CLOSE_BAD_MESSAGE = 4400;
|
const CLOSE_BAD_MESSAGE = 4400;
|
||||||
const CLOSE_TRY_AGAIN = 1013;
|
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 {
|
export interface WsServerOptions {
|
||||||
server: Server;
|
server: Server;
|
||||||
@@ -41,6 +44,7 @@ export interface WsServerOptions {
|
|||||||
now?: () => number;
|
now?: () => number;
|
||||||
heartbeatMs?: number;
|
heartbeatMs?: number;
|
||||||
authTimeoutMs?: number;
|
authTimeoutMs?: number;
|
||||||
|
snapshotWaitMs?: number;
|
||||||
maxBufferedBytes?: number;
|
maxBufferedBytes?: number;
|
||||||
closeBufferedBytes?: number;
|
closeBufferedBytes?: number;
|
||||||
maxConnections?: number;
|
maxConnections?: number;
|
||||||
@@ -66,11 +70,48 @@ interface ClientState {
|
|||||||
authenticated: boolean;
|
authenticated: boolean;
|
||||||
workspaceIds: Set<string>;
|
workspaceIds: Set<string>;
|
||||||
sessionWorkspaces: Map<string, 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;
|
alive: boolean;
|
||||||
dropped: boolean;
|
dropped: boolean;
|
||||||
authTimer: NodeJS.Timeout | undefined;
|
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 {
|
function writeUpgradeRejection(socket: Duplex, status: number, code: string, message: string): void {
|
||||||
const body = JSON.stringify(errorBody(code, message));
|
const body = JSON.stringify(errorBody(code, message));
|
||||||
const reason = status === 403 ? "Forbidden" : status === 401 ? "Unauthorized" : status === 404 ? "Not Found" : "Service Unavailable";
|
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,
|
now = Date.now,
|
||||||
heartbeatMs = 30_000,
|
heartbeatMs = 30_000,
|
||||||
authTimeoutMs = 10_000,
|
authTimeoutMs = 10_000,
|
||||||
|
snapshotWaitMs = DEFAULT_SNAPSHOT_WAIT_MS,
|
||||||
maxBufferedBytes = 4 * 1024 * 1024,
|
maxBufferedBytes = 4 * 1024 * 1024,
|
||||||
closeBufferedBytes = 8 * 1024 * 1024,
|
closeBufferedBytes = 8 * 1024 * 1024,
|
||||||
maxConnections = config.limits.maxConnections,
|
maxConnections = config.limits.maxConnections,
|
||||||
@@ -185,6 +227,7 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
|
|||||||
const releaseSession = (state: ClientState, sessionId: string): void => {
|
const releaseSession = (state: ClientState, sessionId: string): void => {
|
||||||
const workspaceId = state.sessionWorkspaces.get(sessionId);
|
const workspaceId = state.sessionWorkspaces.get(sessionId);
|
||||||
state.sessionWorkspaces.delete(sessionId);
|
state.sessionWorkspaces.delete(sessionId);
|
||||||
|
state.snapshotsSent.delete(sessionId);
|
||||||
if (!workspaceId) return;
|
if (!workspaceId) return;
|
||||||
const others = [...clients].some(
|
const others = [...clients].some(
|
||||||
(other) => other !== state && other.authenticated && other.sessionWorkspaces.has(sessionId),
|
(other) => other !== state && other.authenticated && other.sessionWorkspaces.has(sessionId),
|
||||||
@@ -205,8 +248,11 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
|
|||||||
sessionId: string,
|
sessionId: string,
|
||||||
epoch: string,
|
epoch: string,
|
||||||
seq: number,
|
seq: number,
|
||||||
snapshot: SessionState,
|
snapshot: CachedSnapshot,
|
||||||
): void => {
|
): 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, {
|
send(state, {
|
||||||
v: 1,
|
v: 1,
|
||||||
type: "snapshot",
|
type: "snapshot",
|
||||||
@@ -214,10 +260,34 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
|
|||||||
epoch,
|
epoch,
|
||||||
seq,
|
seq,
|
||||||
ts: now(),
|
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 (
|
const subscribeSession = async (
|
||||||
state: ClientState,
|
state: ClientState,
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
@@ -258,8 +328,19 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const snapshot = connection.snapshot(sessionId);
|
const cached = readSnapshot(connection, sessionId);
|
||||||
if (snapshot) sendSnapshot(state, sessionId, epoch, lastSeq, snapshot);
|
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> => {
|
const subscribe = async (state: ClientState, payload: Record<string, unknown>): Promise<void> => {
|
||||||
@@ -421,6 +502,7 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
|
|||||||
authenticated: device !== null,
|
authenticated: device !== null,
|
||||||
workspaceIds: new Set(),
|
workspaceIds: new Set(),
|
||||||
sessionWorkspaces: new Map(),
|
sessionWorkspaces: new Map(),
|
||||||
|
snapshotsSent: new Map(),
|
||||||
alive: true,
|
alive: true,
|
||||||
dropped: false,
|
dropped: false,
|
||||||
authTimer: undefined,
|
authTimer: undefined,
|
||||||
@@ -475,7 +557,29 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
|
|||||||
if (!state.authenticated) continue;
|
if (!state.authenticated) continue;
|
||||||
const sessionMatch = sessionId !== undefined && state.sessionWorkspaces.has(sessionId);
|
const sessionMatch = sessionId !== undefined && state.sessionWorkspaces.has(sessionId);
|
||||||
const workspaceMatch = workspaceId !== undefined && state.workspaceIds.has(workspaceId);
|
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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
import type { Socket } from "node:net";
|
import type { Socket } from "node:net";
|
||||||
import type { Bus, Logger, PluginConnection } from "../core/interfaces.js";
|
import type { Bus, Logger, PluginConnection } from "../core/interfaces.js";
|
||||||
import { ERROR_CODES } from "../protocol/errors.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";
|
import { InstanceError, errorMessage } from "./errors.js";
|
||||||
|
|
||||||
export const DEFAULT_COMMAND_TIMEOUT_MS = 25_000;
|
export const DEFAULT_COMMAND_TIMEOUT_MS = 25_000;
|
||||||
@@ -36,6 +36,11 @@ export interface SnapshotCacheEntry {
|
|||||||
epoch: string;
|
epoch: string;
|
||||||
seq: number;
|
seq: number;
|
||||||
state: SessionState;
|
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 {
|
export interface PluginSocketConnectionOptions {
|
||||||
@@ -264,6 +269,7 @@ export class PluginSocketConnection implements PluginConnection {
|
|||||||
return this.sessions.has(sessionId);
|
return this.sessions.has(sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The full cached snapshot: `state` plus the plugin's optional `entries` tail. */
|
||||||
snapshotEntry(sessionId: string): SnapshotCacheEntry | undefined {
|
snapshotEntry(sessionId: string): SnapshotCacheEntry | undefined {
|
||||||
return this.snapshots.get(sessionId);
|
return this.snapshots.get(sessionId);
|
||||||
}
|
}
|
||||||
@@ -392,6 +398,9 @@ export class PluginSocketConnection implements PluginConnection {
|
|||||||
|
|
||||||
const payload = isRecord(record.payload) ? record.payload : {};
|
const payload = isRecord(record.payload) ? record.payload : {};
|
||||||
const state = isRecord(payload.state) ? (payload.state as unknown as SessionState) : undefined;
|
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);
|
const cached = this.snapshots.get(sessionId);
|
||||||
if (cached !== undefined && cached.epoch !== epoch) {
|
if (cached !== undefined && cached.epoch !== epoch) {
|
||||||
@@ -404,6 +413,20 @@ export class PluginSocketConnection implements PluginConnection {
|
|||||||
epoch,
|
epoch,
|
||||||
seq: previous !== undefined && previous.epoch === epoch ? Math.max(previous.seq, seq) : seq,
|
seq: previous !== undefined && previous.epoch === epoch ? Math.max(previous.seq, seq) : seq,
|
||||||
state,
|
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,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+58
-3
@@ -1,10 +1,12 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
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 { join } from "node:path";
|
||||||
import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs } from "../../src/cli/pi2d.js";
|
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 { readCliToken, tokenPerms, writeCliToken } from "../../src/cli/token.js";
|
||||||
import { UsageError } from "../../src/cli/util.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", () => {
|
describe("parseDaemonArgs", () => {
|
||||||
it("defaults to nothing set (foreground daemon, config defaults)", () => {
|
it("defaults to nothing set (foreground daemon, config defaults)", () => {
|
||||||
@@ -77,7 +79,6 @@ describe("local CLI token", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => removeDir(dir));
|
afterEach(() => removeDir(dir));
|
||||||
|
|
||||||
it("is 32 bytes of hex, written atomically with mode 0600", () => {
|
it("is 32 bytes of hex, written atomically with mode 0600", () => {
|
||||||
const path = join(dir, "run", "cli.token");
|
const path = join(dir, "run", "cli.token");
|
||||||
const token = writeCliToken(path);
|
const token = writeCliToken(path);
|
||||||
@@ -110,3 +111,57 @@ describe("local CLI token", () => {
|
|||||||
expect(statSync(path).mode & 0o777).toBe(0o600);
|
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();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { DaemonError, isRetryableCode, statusForCode, toErrorPayload } from "../../src/daemon/errors.js";
|
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 { ERROR_CODES } from "../../src/protocol/errors.js";
|
||||||
|
import { WorkspaceError } from "../../src/workspaces/errors.js";
|
||||||
|
|
||||||
describe("protocol error mapping", () => {
|
describe("protocol error mapping", () => {
|
||||||
const expected: [string, number][] = [
|
const expected: [string, number][] = [
|
||||||
@@ -43,4 +45,27 @@ describe("protocol error mapping", () => {
|
|||||||
const forbidden = new DaemonError(ERROR_CODES.FORBIDDEN, "nope", { details: { origin: "x" } });
|
const forbidden = new DaemonError(ERROR_CODES.FORBIDDEN, "nope", { details: { origin: "x" } });
|
||||||
expect(toErrorPayload(forbidden).body).toMatchObject({ code: ERROR_CODES.FORBIDDEN, 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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -39,6 +39,7 @@ export interface HarnessOptions {
|
|||||||
wsOverrides?: {
|
wsOverrides?: {
|
||||||
maxBufferedBytes?: number;
|
maxBufferedBytes?: number;
|
||||||
closeBufferedBytes?: number;
|
closeBufferedBytes?: number;
|
||||||
|
snapshotWaitMs?: number;
|
||||||
measureBufferedAmount?: (socket: unknown) => number;
|
measureBufferedAmount?: (socket: unknown) => number;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import * as os from "node:os";
|
||||||
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
|
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
|
||||||
import { createHarness, TEST_LIMITS, type Harness } from "./harness.js";
|
import { createHarness, TEST_LIMITS, type Harness } from "./harness.js";
|
||||||
import { DaemonError } from "../../src/daemon/errors.js";
|
import { DaemonError } from "../../src/daemon/errors.js";
|
||||||
import { ERROR_CODES } from "../../src/protocol/errors.js";
|
import { ERROR_CODES } from "../../src/protocol/errors.js";
|
||||||
|
import { WorkspaceError } from "../../src/workspaces/errors.js";
|
||||||
|
|
||||||
describe("HTTP API", () => {
|
describe("HTTP API", () => {
|
||||||
let h: Harness;
|
let h: Harness;
|
||||||
@@ -41,6 +43,13 @@ describe("HTTP API", () => {
|
|||||||
expect(body.daemonId).toBe("d-test");
|
expect(body.daemonId).toBe("d-test");
|
||||||
expect(body.machineId).toBe("m-test");
|
expect(body.machineId).toBe("m-test");
|
||||||
expect(body.limits).toEqual(TEST_LIMITS);
|
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`);
|
const health = await fetch(`${h.url}/api/v1/health`);
|
||||||
expect(health.status).toBe(200);
|
expect(health.status).toBe(200);
|
||||||
@@ -50,6 +59,49 @@ describe("HTTP API", () => {
|
|||||||
expect(healthBody.items.every((item) => item.ok)).toBe(true);
|
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 () => {
|
it("requires a bearer token for all other API reads", async () => {
|
||||||
const anonymous = await fetch(`${h.url}/api/v1/workspaces`);
|
const anonymous = await fetch(`${h.url}/api/v1/workspaces`);
|
||||||
expect(anonymous.status).toBe(401);
|
expect(anonymous.status).toBe(401);
|
||||||
@@ -158,6 +210,24 @@ describe("HTTP API", () => {
|
|||||||
expect(body.retryable).toBe(false);
|
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 () => {
|
it("enforces the body limit", async () => {
|
||||||
const small = await createHarness({ config: { limits: { ...TEST_LIMITS, maxBodyBytes: 16 } } });
|
const small = await createHarness({ config: { limits: { ...TEST_LIMITS, maxBodyBytes: 16 } } });
|
||||||
try {
|
try {
|
||||||
@@ -238,6 +308,7 @@ describe("HTTP API", () => {
|
|||||||
const list = await fetch(`${h.url}/api/v1/devices`, authed());
|
const list = await fetch(`${h.url}/api/v1/devices`, authed());
|
||||||
expect(list.status).toBe(200);
|
expect(list.status).toBe(200);
|
||||||
const devices = (await list.json()) as { id: string; tokenHash?: string }[];
|
const devices = (await list.json()) as { id: string; tokenHash?: string }[];
|
||||||
|
expect(Array.isArray(devices)).toBe(true);
|
||||||
expect(devices).toHaveLength(1);
|
expect(devices).toHaveLength(1);
|
||||||
expect(devices[0]!.tokenHash).toBeUndefined();
|
expect(devices[0]!.tokenHash).toBeUndefined();
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,15 @@ describe("static file surface", () => {
|
|||||||
expect(await res.text()).toContain("<div id=app>");
|
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 () => {
|
it("returns 404 for a missing asset with an extension", async () => {
|
||||||
const res = await fetch(`${h.url}/assets/missing-deadbeef.js`);
|
const res = await fetch(`${h.url}/assets/missing-deadbeef.js`);
|
||||||
expect(res.status).toBe(404);
|
expect(res.status).toBe(404);
|
||||||
|
|||||||
@@ -1,11 +1,37 @@
|
|||||||
import { once } from "node:events";
|
import { once } from "node:events";
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
import WebSocket from "ws";
|
import WebSocket from "ws";
|
||||||
|
import type { Entry, SessionState } from "../../src/protocol/types.js";
|
||||||
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
|
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
|
||||||
|
import type { FakeConnection } from "./fakes.js";
|
||||||
import { createHarness, type Harness } from "./harness.js";
|
import { createHarness, type Harness } from "./harness.js";
|
||||||
|
|
||||||
type Record0 = Record<string, unknown> & { type?: string };
|
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 {
|
class WsClient {
|
||||||
readonly messages: Record0[] = [];
|
readonly messages: Record0[] = [];
|
||||||
private waiters: {
|
private waiters: {
|
||||||
@@ -155,12 +181,158 @@ describe("WebSocket surface", () => {
|
|||||||
expect(snapshot.epoch).toBe("i-ws-1");
|
expect(snapshot.epoch).toBe("i-ws-1");
|
||||||
expect(snapshot.seq).toBe(7);
|
expect(snapshot.seq).toBe(7);
|
||||||
expect((snapshot.payload as { state: { sessionId: string } }).state.sessionId).toBe("s1");
|
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(h.instances.ensureCalls).toContain("ws-1");
|
||||||
expect(conn.subscribed.has("s1")).toBe(true);
|
expect(conn.subscribed.has("s1")).toBe(true);
|
||||||
await client.close();
|
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 () => {
|
it("sends resync_required when epoch or seq do not match", async () => {
|
||||||
await setup();
|
await setup();
|
||||||
const conn = h.instances.get("ws-1")!;
|
const conn = h.instances.get("ws-1")!;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { Socket } from "node:net";
|
import type { Socket } from "node:net";
|
||||||
import { describe, expect, it, afterEach, beforeEach } from "vitest";
|
import { describe, expect, it, afterEach, beforeEach } from "vitest";
|
||||||
import { daemonSocketPath } from "../../src/core/paths.js";
|
import { daemonSocketPath } from "../../src/core/paths.js";
|
||||||
|
import type { Entry } from "../../src/protocol/types.js";
|
||||||
import { PluginSocketConnection } from "../../src/instances/connection.js";
|
import { PluginSocketConnection } from "../../src/instances/connection.js";
|
||||||
import { PluginServer } from "../../src/instances/plugin-server.js";
|
import { PluginServer } from "../../src/instances/plugin-server.js";
|
||||||
import { makeSessionState } from "../daemon/fakes.js";
|
import { makeSessionState } from "../daemon/fakes.js";
|
||||||
@@ -179,6 +180,85 @@ describe("PluginSocketConnection", () => {
|
|||||||
expect(connection.hasSession("s1")).toBe(true);
|
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 () => {
|
it("tracks sessions reported by instance_state", async () => {
|
||||||
client.send({
|
client.send({
|
||||||
v: 1,
|
v: 1,
|
||||||
|
|||||||
Reference in new issue
Block a user