feat(instances): plugin socket server and one-nvim-per-workspace supervisor

- JSONL plugin server with hello token auth, frame cap, heartbeat and E_LEASE rejection
- PluginConnection with ack correlation, snapshot cache, per-epoch seq
- lazy spawn (headless nvim), degrade-on-crash with process_exit fanout, no auto-restart
- shutdown drain/stop with SIGTERM/SIGKILL escalation, RSS resources view
- 57 tests against a generated fake nvim
This commit is contained in:
yuez committed 2026-10-21 11:50:51 +08:00
1 parent 5b55e622ea
commit a495f2ac71
9 files changed
+3583

No files matched your search

+322
View File
@@ -0,0 +1,322 @@
import type { Socket } from "node:net";
import { describe, expect, it, afterEach, beforeEach } from "vitest";
import { daemonSocketPath } from "../../src/core/paths.js";
import { PluginSocketConnection } from "../../src/instances/connection.js";
import { PluginServer } from "../../src/instances/plugin-server.js";
import { makeSessionState } from "../daemon/fakes.js";
import { FakeBus, PluginClient, delay, makeTempEnv, waitFor, type TempEnv } from "./helpers.js";
function asRecord(value: unknown): Record<string, unknown> {
return value as Record<string, unknown>;
}
describe("PluginSocketConnection", () => {
let env: TempEnv;
let bus: FakeBus;
let server: PluginServer;
let client: PluginClient;
let connection: PluginSocketConnection;
beforeEach(async () => {
env = makeTempEnv();
bus = new FakeBus();
server = new PluginServer({ bus, daemonId: "d-test" });
await server.start();
client = await PluginClient.connect({ socketPath: daemonSocketPath() });
await client.next("hello_ack");
const established = server.connection("ws-test");
if (!established) throw new Error("connection was not established");
connection = established;
});
afterEach(async () => {
client.close();
await server.close();
env.cleanup();
});
it("sends records as JSONL to the plugin", async () => {
connection.send({ type: "instance_state", payload: { status: "ready", sessions: [] } });
const record = await client.next("instance_state");
expect(record.v).toBe(1);
expect(asRecord(record.payload).status).toBe("ready");
expect(client.rawLines).toHaveLength(2); // hello_ack + record
});
it("correlates acks by id even when they arrive out of order", async () => {
client.onRecord((record) => {
if (record.type !== "cmd") return;
const id = String(record.id);
const seq = id === "req-alpha" ? 2 : 1;
setTimeout(
() => client.send({ v: 1, type: "ack", id, seq, payload: { disposition: "started" } }),
id === "req-alpha" ? 80 : 5,
);
});
const alpha = connection.command({ id: "req-alpha", sessionId: "s1", method: "alpha" });
const beta = connection.command({ id: "req-beta", sessionId: "s1", method: "beta" });
expect(await beta).toEqual({ seq: 1, disposition: "started" });
expect(await alpha).toEqual({ seq: 2, disposition: "started" });
const cmd = await client.next("cmd", (record) => String(record.id) === "req-alpha");
expect(asRecord(cmd.payload).method).toBe("alpha");
expect(cmd.sessionId).toBe("s1");
});
it("rejects with the plugin error code and message", async () => {
client.onRecord((record) => {
if (record.type !== "cmd") return;
client.send({
v: 1,
type: "error",
id: record.id,
payload: { code: "E_LEASE", message: "session is owned by instance i-2", retryable: false },
});
});
await expect(connection.command({ id: "req-err", method: "prompt.send" })).rejects.toMatchObject({
code: "E_LEASE",
message: "session is owned by instance i-2",
retryable: false,
});
});
it("times out commands and ignores a late ack", async () => {
const started = Date.now();
await expect(connection.command({ id: "req-slow", method: "slow" }, 60)).rejects.toMatchObject({
code: "E_TIMEOUT",
});
expect(Date.now() - started).toBeGreaterThanOrEqual(50);
expect(connection.pendingCommands).toBe(0);
// A late ack must not resolve anything or throw.
client.send({ v: 1, type: "ack", id: "req-slow", seq: 3, payload: { disposition: "started" } });
await delay(20);
expect(connection.pendingCommands).toBe(0);
});
it("sends subscription records", async () => {
connection.subscribe("s1");
connection.unsubscribe("s1");
const subscribe = await client.next("sub.subscribe");
const unsubscribe = await client.next("sub.unsubscribe");
expect(subscribe.sessionId).toBe("s1");
expect(unsubscribe.sessionId).toBe("s1");
});
it("caches snapshots and invalidates them on epoch change", async () => {
const state = makeSessionState("s1", "ws-test");
client.send({
v: 1,
type: "snapshot",
sessionId: "s1",
epoch: "e1",
seq: 10,
payload: { state },
});
await waitFor(() => connection.snapshot("s1") !== undefined);
expect(connection.snapshot("s1")?.sessionId).toBe("s1");
expect(connection.lastSeq("s1")).toBe(10);
const renamed = { ...state, name: "Renamed" };
client.send({
v: 1,
type: "snapshot",
sessionId: "s1",
epoch: "e1",
seq: 12,
payload: { state: renamed },
});
await waitFor(() => connection.snapshot("s1")?.name === "Renamed");
expect(connection.lastSeq("s1")).toBe(12);
const recreated = { ...state, name: "After restart" };
client.send({
v: 1,
type: "snapshot",
sessionId: "s1",
epoch: "e2",
seq: 1,
payload: { state: recreated },
});
await waitFor(() => connection.snapshot("s1")?.name === "After restart");
expect(connection.snapshotEntry("s1")?.epoch).toBe("e2");
// seq is only valid inside an epoch
expect(connection.lastSeq("s1")).toBe(1);
});
it("does not invent snapshots the plugin never sent", () => {
expect(connection.snapshot("missing")).toBeUndefined();
expect(connection.lastSeq("missing")).toBe(0);
});
it("relays events onto the bus with the plugin envelope", async () => {
client.send({
v: 1,
type: "event",
sessionId: "s1",
epoch: "e1",
seq: 7,
ts: 1733234400123,
mono: 918273,
payload: { event: { type: "agent_start", ts: 1733234400123 } },
});
const published = await waitFor(() => bus.published.find((record) => record.type === "event"));
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(7);
expect(published.ts).toBe(1733234400123);
expect(asRecord(published.payload).event).toMatchObject({ type: "agent_start" });
expect(connection.lastSeq("s1")).toBe(7);
expect(connection.hasSession("s1")).toBe(true);
});
it("tracks sessions reported by instance_state", async () => {
client.send({
v: 1,
type: "instance_state",
payload: {
status: "ready",
sessions: [{ sessionId: "s1", status: "busy" }, { sessionId: "s2" }],
},
});
await waitFor(() => connection.sessionIds().length === 2);
expect(connection.sessionIds().sort()).toEqual(["s1", "s2"]);
client.send({ v: 1, type: "instance_state", payload: { sessions: ["s3"] } });
await waitFor(() => connection.hasSession("s3"));
});
it("fails in-flight commands when the socket closes", async () => {
const pending = connection.command({ id: "req-pending", method: "never" }, 5_000);
connection.close("test shutdown");
await expect(pending).rejects.toMatchObject({ code: "E_INSTANCE_UNAVAILABLE" });
await connection.closedPromise;
expect(connection.isClosed).toBe(true);
expect(connection.closeReason).toBe("test shutdown");
await client.waitForClosed();
await waitFor(() => server.connectionCount === 0);
});
it("treats a plugin bye as a close", async () => {
client.send({ v: 1, type: "bye" });
await connection.closedPromise;
expect(connection.isClosed).toBe(true);
expect(connection.closeReason).toBe("plugin said bye");
});
it("rejects commands once closed", async () => {
connection.close("done");
await connection.closedPromise;
await expect(connection.command({ id: "req-late", method: "x" })).rejects.toMatchObject({
code: "E_INSTANCE_UNAVAILABLE",
});
});
});
describe("PluginSocketConnection write-queue cap", () => {
it("drops events and emits one dropped marker when the queue is full", () => {
const state = { queued: 0, destroyed: false };
const writes: string[] = [];
const socket = {
get writableLength() {
return state.queued;
},
get destroyed() {
return state.destroyed;
},
write(line: string) {
writes.push(line);
state.queued += Buffer.byteLength(line, "utf8");
},
end() {
state.destroyed = true;
},
destroy() {
state.destroyed = true;
},
} as unknown as Socket;
const bus = new FakeBus();
const connection = new PluginSocketConnection({
socket,
hello: {
instanceId: "i-1",
workspaceId: "ws-1",
cwd: "/repo",
pid: 42,
hasUI: false,
listenAddr: null,
pluginVersion: "1.0.0",
},
bus,
maxWriteQueueBytes: 100,
});
connection.send({
type: "event",
sessionId: "s1",
seq: 1,
payload: { event: { type: "text_delta", delta: "x".repeat(200) } },
});
connection.send({
type: "event",
sessionId: "s1",
seq: 2,
payload: { event: { type: "text_delta", delta: "y".repeat(200) } },
});
expect(writes).toHaveLength(0);
expect(connection.droppedCount).toBe(2);
expect(bus.published.filter((record) => record.type === "dropped")).toHaveLength(1);
});
it("closes the connection rather than dropping a control record", () => {
const writes: string[] = [];
const state = { destroyed: false };
const socket = {
writableLength: 1_000,
get destroyed() {
return state.destroyed;
},
write(line: string) {
writes.push(line);
},
end() {
state.destroyed = true;
},
destroy() {
state.destroyed = true;
},
} as unknown as Socket;
const connection = new PluginSocketConnection({
socket,
hello: {
instanceId: "i-1",
workspaceId: "ws-1",
cwd: "/repo",
pid: 42,
hasUI: false,
listenAddr: null,
pluginVersion: "1.0.0",
},
bus: new FakeBus(),
maxWriteQueueBytes: 100,
});
connection.send({ type: "cmd", id: "req-1", payload: { method: "prompt.send" } });
expect(writes).toHaveLength(0);
expect(connection.closeReason).toBe("write queue overflow");
expect(state.destroyed).toBe(true);
});
});
+549
View File
@@ -0,0 +1,549 @@
/**
* Test harness for the instance layer.
*
* Three pieces:
* - `makeTempEnv()` isolates `PI2_RUNTIME_DIR`/`PI2_DATA_DIR`/`PI2_STATE_DIR`
* so the real `core/paths.ts` helpers point into a scratch directory.
* - `PluginClient` speaks the plugin side of the JSONL protocol over a real
* unix socket (tests of `plugin-server` / `connection`).
* - `writeFakeNvim()` generates an executable node script that impersonates
* `nvim` for `PI2_NVIM_BIN`: it dials the daemon, says `hello`, answers
* commands with `ack`/`error`, emits snapshots/instance_state, and can be
* told to crash or ignore shutdown.
*/
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { connect, type Socket } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { daemonTokenPath } from "../../src/core/paths.js";
import { FakeBus } from "../daemon/fakes.js";
export { FakeBus };
export interface TempEnv {
dir: string;
runtime: string;
data: string;
state: string;
/** Restores the env vars captured at creation (call from afterEach/afterAll). */
restore(): void;
cleanup(): void;
}
const ENV_KEYS = ["PI2_RUNTIME_DIR", "PI2_DATA_DIR", "PI2_STATE_DIR", "PI2_NVIM_BIN", "PI2_NVIM_INIT"] as const;
export function makeTempEnv(prefix = "pi2d-instances-"): TempEnv {
const dir = mkdtempSync(join(tmpdir(), prefix));
const runtime = join(dir, "run");
const data = join(dir, "data");
const state = join(dir, "state");
for (const path of [runtime, data, state]) mkdirSync(path, { recursive: true, mode: 0o700 });
const saved = new Map<string, string | undefined>();
for (const key of ENV_KEYS) saved.set(key, process.env[key]);
process.env.PI2_RUNTIME_DIR = runtime;
process.env.PI2_DATA_DIR = data;
process.env.PI2_STATE_DIR = state;
return {
dir,
runtime,
data,
state,
restore() {
for (const [key, value] of saved) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
},
cleanup() {
this.restore();
rmSync(dir, { recursive: true, force: true });
},
};
}
export function readDaemonToken(): string {
return readFileSync(daemonTokenPath(), "utf8").trim();
}
export function makeHello(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
v: 1,
type: "hello",
token: readDaemonToken(),
instanceId: "i-test-1",
workspaceId: "ws-test",
cwd: "/repo/ws-test",
pid: process.pid,
hasUI: false,
listenAddr: "/tmp/i-test.sock",
pluginVersion: "1.8.0",
capabilities: ["snapshot", "attention"],
...overrides,
};
}
export function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export async function waitFor<T>(
predicate: () => T | undefined | false | null,
timeoutMs = 3_000,
intervalMs = 10,
label = "condition",
): Promise<T> {
const deadline = Date.now() + timeoutMs;
let lastError: unknown;
while (Date.now() < deadline) {
try {
const value = predicate();
if (value) return value;
} catch (error) {
lastError = error;
}
await delay(intervalMs);
}
throw new Error(`timed out waiting for ${label} after ${timeoutMs}ms${lastError ? `: ${String(lastError)}` : ""}`);
}
export interface PluginClientOptions {
socketPath: string;
/** Defaults to `makeHello()`; pass `false` to send nothing automatically. */
hello?: Record<string, unknown> | false;
connectTimeoutMs?: number;
}
type RecordHandler = (record: Record<string, unknown>) => void;
interface Waiter {
predicate: (record: Record<string, unknown>) => boolean;
resolve: (record: Record<string, unknown>) => void;
timer: NodeJS.Timeout;
}
/** A plugin-side JSONL client used by plugin-server / connection tests. */
export class PluginClient {
readonly socket: Socket;
readonly records: Record<string, unknown>[] = [];
readonly rawLines: string[] = [];
readonly closePromise: Promise<void>;
private buffer = "";
private waiters: Waiter[] = [];
private handlers: RecordHandler[] = [];
private closed = false;
private closeReason = "";
private constructor(socket: Socket) {
this.socket = socket;
this.closePromise = new Promise<void>((resolve) => {
socket.once("close", () => {
this.closed = true;
resolve();
});
});
socket.setEncoding("utf8");
socket.on("data", (chunk: string) => this.onData(chunk));
socket.on("error", () => {
// close event handles cleanup
});
}
static async connect(options: PluginClientOptions): Promise<PluginClient> {
const socket = connect(options.socketPath);
socket.setEncoding("utf8");
const client = new PluginClient(socket);
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error(`connect to ${options.socketPath} timed out`)),
options.connectTimeoutMs ?? 3_000,
);
timer.unref?.();
socket.once("connect", () => {
clearTimeout(timer);
resolve();
});
socket.once("error", (error) => {
clearTimeout(timer);
reject(error);
});
});
if (options.hello !== false) {
client.send(options.hello ?? makeHello());
}
return client;
}
get isClosed(): boolean {
return this.closed;
}
get reason(): string {
return this.closeReason;
}
send(record: Record<string, unknown>): void {
this.sendRaw(`${JSON.stringify(record)}\n`);
}
sendRaw(text: string): void {
if (this.socket.destroyed) return;
this.socket.write(text);
}
onRecord(handler: RecordHandler): () => void {
this.handlers.push(handler);
return () => {
this.handlers = this.handlers.filter((candidate) => candidate !== handler);
};
}
/** Resolves with the first matching record (already received ones included). */
async next(
type: string,
predicate: (record: Record<string, unknown>) => boolean = () => true,
timeoutMs = 3_000,
): Promise<Record<string, unknown>> {
const matches = (record: Record<string, unknown>): boolean => record.type === type && predicate(record);
const existing = this.records.find(matches);
if (existing) return existing;
return new Promise<Record<string, unknown>>((resolve, reject) => {
const timer = setTimeout(() => {
this.waiters = this.waiters.filter((candidate) => candidate !== waiter);
reject(
new Error(
`timed out waiting for "${type}" after ${timeoutMs}ms; got ${JSON.stringify(this.records.map((r) => r.type))}`,
),
);
}, timeoutMs);
timer.unref?.();
const waiter: Waiter = {
predicate: matches,
resolve: (record) => {
clearTimeout(timer);
resolve(record);
},
timer,
};
this.waiters.push(waiter);
const late = this.records.find(matches);
if (late) {
this.waiters = this.waiters.filter((candidate) => candidate !== waiter);
clearTimeout(timer);
resolve(late);
}
});
}
recordsOfType(type: string): Record<string, unknown>[] {
return this.records.filter((record) => record.type === type);
}
async waitForClosed(timeoutMs = 3_000): Promise<void> {
if (this.closed) return;
await Promise.race([
this.closePromise,
delay(timeoutMs).then(() => {
throw new Error(`socket did not close within ${timeoutMs}ms`);
}),
]);
}
close(): void {
if (!this.socket.destroyed) this.socket.destroy();
}
private onData(chunk: string): void {
this.buffer += chunk;
let newline = this.buffer.indexOf("\n");
while (newline >= 0) {
let line = this.buffer.slice(0, newline);
this.buffer = this.buffer.slice(newline + 1);
if (line.endsWith("\r")) line = line.slice(0, -1);
if (line.trim() !== "") {
this.rawLines.push(line);
try {
const record = JSON.parse(line) as Record<string, unknown>;
this.records.push(record);
for (const handler of [...this.handlers]) {
try {
handler(record);
} catch {
// test handler failures surface through assertions
}
}
for (const waiter of [...this.waiters]) {
if (!waiter.predicate(record)) continue;
this.waiters = this.waiters.filter((candidate) => candidate !== waiter);
clearTimeout(waiter.timer);
waiter.resolve(record);
}
} catch {
// non-JSON from the daemon is a test failure surfaced via rawLines
}
}
newline = this.buffer.indexOf("\n");
}
}
}
export interface FakeNvimOptions {
mode?: "ok" | "no-hello" | "bad-token" | "wrong-version" | "exit-immediately" | "exit-first-run";
instanceId?: string;
workspaceId?: string;
pluginVersion?: string;
hasUI?: boolean;
/** Sessions reported via `instance_state` right after hello. */
sessions?: string[];
/** Snapshot state sent for each subscribed session. */
snapshotState?: Record<string, unknown>;
/** Snapshots emitted right after hello. */
snapshots?: { sessionId: string; epoch?: string; seq?: number; state?: Record<string, unknown> }[];
crashAfterMs?: number;
crashExitCode?: number;
ackDelayMs?: number;
cmdMode?: "ack" | "error" | "silent";
ignoreShutdown?: boolean;
ignoreSigterm?: boolean;
exitCode?: number;
/** For `exit-first-run`: how many initial runs exit instead of connecting. */
failRuns?: number;
runLog?: string;
}
export interface FakeNvim {
bin: string;
runLog: string;
counterFile: string;
}
/** Creates an executable node script that impersonates nvim on the daemon socket. */
export function writeFakeNvim(dir: string, options: FakeNvimOptions = {}): FakeNvim {
const suffix = Math.random().toString(16).slice(2);
const runLog = options.runLog ?? join(dir, `runs-${suffix}.jsonl`);
const counterFile = join(dir, `runs-${suffix}.txt`);
const bin = join(dir, `fake-nvim-${suffix}.mjs`);
const payload = {
...options,
runLog,
counterFile,
};
writeFileSync(bin, fakeNvimScript(payload), { mode: 0o755 });
chmodSync(bin, 0o755);
return { bin, runLog, counterFile };
}
export function readRunLog(path: string): Record<string, unknown>[] {
try {
return readFileSync(path, "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line) as Record<string, unknown>);
} catch {
return [];
}
}
export function startRecords(runLog: string): Record<string, unknown>[] {
return readRunLog(runLog).filter((entry) => entry.kind === "start");
}
function fakeNvimScript(options: FakeNvimOptions & { runLog: string; counterFile: string }): string {
const literal = JSON.stringify(options);
return `#!/usr/bin/env node
// Generated by test/instances/helpers.ts — impersonates nvim for PI2_NVIM_BIN.
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
import { connect } from "node:net";
const opts = ${literal};
const argv = process.argv.slice(2);
const listenIndex = argv.indexOf("--listen");
const listenAddr = listenIndex >= 0 ? argv[listenIndex + 1] : null;
function log(entry) {
if (!opts.runLog) return;
try {
appendFileSync(opts.runLog, JSON.stringify({ pid: process.pid, at: Date.now(), ...entry }) + "\\n");
} catch {
// ignore
}
}
log({
kind: "start",
argv,
cwd: process.cwd(),
listenAddr,
env: {
PI2_RUNTIME_DIR: process.env.PI2_RUNTIME_DIR,
PI2_DAEMON_SOCKET: process.env.PI2_DAEMON_SOCKET,
PI2_DAEMON_TOKEN_PATH: process.env.PI2_DAEMON_TOKEN_PATH,
PI2_WORKSPACE_ID: process.env.PI2_WORKSPACE_ID,
},
});
if (opts.mode === "exit-immediately") process.exit(opts.exitCode ?? 3);
if (opts.mode === "exit-first-run") {
let runs = 0;
try {
runs = Number(readFileSync(opts.counterFile, "utf8")) || 0;
} catch {
runs = 0;
}
runs += 1;
writeFileSync(opts.counterFile, String(runs));
log({ kind: "run", runs });
if (runs <= (opts.failRuns ?? 1)) process.exit(opts.exitCode ?? 3);
}
if (opts.ignoreShutdown || opts.ignoreSigterm) {
// Keep the event loop alive after the daemon drops the socket so the test can
// observe the SIGTERM -> SIGKILL escalation.
setInterval(() => {}, 1_000);
process.on("SIGTERM", () => log({ kind: "sigterm" }));
}
const token =
opts.mode === "bad-token"
? "0".repeat(64)
: readFileSync(process.env.PI2_DAEMON_TOKEN_PATH, "utf8").trim();
const workspaceId = opts.workspaceId ?? process.env.PI2_WORKSPACE_ID;
const instanceId = opts.instanceId ?? ("i-fake-" + process.pid);
const socket = connect(process.env.PI2_DAEMON_SOCKET);
socket.setEncoding("utf8");
let buffer = "";
let seq = 0;
let closed = false;
function rawSend(record) {
if (closed || socket.destroyed) return;
socket.write(JSON.stringify({ v: 1, ...record }) + "\\n");
}
socket.on("connect", () => {
if (opts.mode === "no-hello") {
log({ kind: "silent" });
return;
}
rawSend({
type: "hello",
v: opts.mode === "wrong-version" ? 2 : 1,
token,
instanceId,
workspaceId,
cwd: process.cwd(),
pid: process.pid,
hasUI: opts.hasUI ?? false,
listenAddr,
pluginVersion: opts.pluginVersion ?? "9.9.9-fake",
capabilities: ["snapshot", "attention"],
});
log({ kind: "hello-sent", instanceId });
if (opts.mode === "bad-token" || opts.mode === "wrong-version") return;
setTimeout(() => {
if (opts.sessions) {
rawSend({
type: "instance_state",
payload: {
status: "ready",
sessions: opts.sessions.map((sessionId) => ({ sessionId })),
},
});
}
if (opts.snapshots) {
for (const snapshot of opts.snapshots) {
const state = snapshot.state ?? { ...(opts.snapshotState ?? {}), sessionId: snapshot.sessionId };
rawSend({
type: "snapshot",
sessionId: snapshot.sessionId,
epoch: snapshot.epoch ?? instanceId,
seq: snapshot.seq ?? ++seq,
payload: { state },
});
}
}
}, 0);
if (opts.crashAfterMs !== undefined) {
setTimeout(() => {
log({ kind: "crash" });
process.exit(opts.crashExitCode ?? 0);
}, opts.crashAfterMs);
}
});
function handleCmd(record) {
log({ kind: "cmd", id: record.id, method: record.payload?.method });
if (opts.cmdMode === "silent") return;
const send = () => {
if (opts.cmdMode === "error") {
rawSend({ type: "error", id: record.id, payload: { code: "E_INTERNAL", message: "fake failure", retryable: false } });
} else {
rawSend({ type: "ack", id: record.id, seq: ++seq, payload: { disposition: "started" } });
}
};
if (opts.ackDelayMs) setTimeout(send, opts.ackDelayMs);
else send();
}
socket.on("data", (chunk) => {
buffer += chunk;
let newline = buffer.indexOf("\\n");
while (newline >= 0) {
const line = buffer.slice(0, newline);
buffer = buffer.slice(newline + 1);
newline = buffer.indexOf("\\n");
if (!line.trim()) continue;
let record;
try {
record = JSON.parse(line);
} catch {
continue;
}
log({ kind: "record", record });
if (record.type === "hello_ack") {
log({ kind: "hello-ack", rejected: record.rejected ?? null });
if (record.rejected) {
closed = true;
socket.end();
return;
}
continue;
}
if (record.type === "cmd") handleCmd(record);
if (record.type === "sub.subscribe" && opts.snapshotState) {
rawSend({
type: "snapshot",
sessionId: record.sessionId,
epoch: instanceId,
seq: ++seq,
payload: { state: { ...opts.snapshotState, sessionId: record.sessionId } },
});
}
if (record.type === "instance.shutdown") {
log({ kind: "shutdown", mode: record.payload?.mode });
if (!opts.ignoreShutdown) {
rawSend({ type: "bye" });
setTimeout(() => {
closed = true;
socket.end();
process.exit(0);
}, 10);
}
}
if (record.type === "test.exit") process.exit(record.payload?.code ?? 0);
}
});
socket.on("error", () => {
// the daemon may be gone; tests observe the run log
});
`;
}
+330
View File
@@ -0,0 +1,330 @@
import { readFileSync, statSync } from "node:fs";
import { describe, expect, it, afterEach, beforeEach } from "vitest";
import { daemonSocketPath, daemonTokenPath } from "../../src/core/paths.js";
import { parseHello, PluginServer, type PluginServerOptions } from "../../src/instances/plugin-server.js";
import type { PluginHello } from "../../src/instances/connection.js";
import {
FakeBus,
PluginClient,
delay,
makeHello,
makeTempEnv,
waitFor,
type TempEnv,
} from "./helpers.js";
function asRecord(value: unknown): Record<string, unknown> {
return value as Record<string, unknown>;
}
describe("PluginServer", () => {
let env: TempEnv;
let bus: FakeBus;
let servers: PluginServer[];
beforeEach(() => {
env = makeTempEnv();
bus = new FakeBus();
servers = [];
});
afterEach(async () => {
for (const server of servers.splice(0)) await server.close();
env.cleanup();
});
async function start(options: Partial<PluginServerOptions> = {}): Promise<PluginServer> {
const server = new PluginServer({ bus, daemonId: "d-test", ...options });
await server.start();
servers.push(server);
return server;
}
async function connect(overrides: Record<string, unknown> = {}): Promise<PluginClient> {
return PluginClient.connect({ socketPath: daemonSocketPath(), hello: makeHello(overrides) });
}
it("writes a 32-byte hex token with mode 0600 before accepting connections", async () => {
const server = await start();
const token = readFileSync(daemonTokenPath(), "utf8").trim();
expect(token).toMatch(/^[0-9a-f]{64}$/);
expect(token).toBe(server.token);
expect(statSync(daemonTokenPath()).mode & 0o777).toBe(0o600);
expect(statSync(server.path).mode & 0o777).toBe(0o600);
});
it("accepts a valid hello and replies with hello_ack limits and policy", async () => {
const server = await start({ daemonId: "d-test", policy: { attention: "all" } });
const client = await connect();
const ack = await client.next("hello_ack");
expect(ack.v).toBe(1);
expect(ack.type).toBe("hello_ack");
expect(ack.daemonId).toBe("d-test");
expect(asRecord(ack.limits).maxFrameBytes).toBe(8 * 1024 * 1024);
expect(asRecord(ack.policy).attention).toBe("all");
expect(ack.rejected).toBeUndefined();
expect(server.connectionCount).toBe(1);
expect(server.connection("ws-test")?.instanceId).toBe("i-test-1");
expect(client.isClosed).toBe(false);
await waitFor(() =>
bus.published.find(
(record) =>
record.type === "instance_state" && asRecord(record.payload).status === "ready",
),
);
client.close();
});
it("rejects a bad token with E_UNAUTHORIZED and closes the socket", async () => {
await start();
const client = await connect({ token: "0".repeat(64) });
const error = await client.next("error");
expect(asRecord(error.payload).code).toBe("E_UNAUTHORIZED");
expect(asRecord(error.payload).retryable).toBe(false);
await client.waitForClosed();
});
it("rejects an unsupported protocol version with E_PROTOCOL_VERSION", async () => {
await start();
const client = await connect({ v: 2 });
const error = await client.next("error");
expect(asRecord(error.payload).code).toBe("E_PROTOCOL_VERSION");
await client.waitForClosed();
});
it("rejects a hello with missing fields as E_BAD_REQUEST", async () => {
await start();
const hello = makeHello();
delete hello.cwd;
const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello });
const error = await client.next("error");
expect(asRecord(error.payload).code).toBe("E_BAD_REQUEST");
await client.waitForClosed();
});
it("rejects a first record that is not hello", async () => {
await start();
const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello: false });
client.send({ v: 1, type: "event", sessionId: "s1", seq: 1 });
const error = await client.next("error");
expect(asRecord(error.payload).code).toBe("E_BAD_REQUEST");
await client.waitForClosed();
});
it("rejects malformed JSON", async () => {
await start();
const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello: false });
client.sendRaw("{not json}\n");
const error = await client.next("error");
expect(asRecord(error.payload).code).toBe("E_BAD_REQUEST");
await client.waitForClosed();
});
it("rejects a second instance for an already-managed workspace with E_LEASE", async () => {
const server = await start();
const rejected: { hello: PluginHello; code: string; message: string }[] = [];
server.setHandlers({
onRejected: (hello, rejection) => rejected.push({ hello, code: rejection.code, message: rejection.message }),
});
const first = await connect({ instanceId: "i-first", workspaceId: "ws-1" });
await first.next("hello_ack");
const second = await connect({ instanceId: "i-second", workspaceId: "ws-1" });
const ack = await second.next("hello_ack");
expect(asRecord(ack.rejected).code).toBe("E_LEASE");
expect(asRecord(ack.rejected).message).toBe("workspace already managed by i-first");
await second.waitForClosed();
expect(server.connectionCount).toBe(1);
expect(server.connection("ws-1")?.instanceId).toBe("i-first");
expect(rejected).toHaveLength(1);
expect(rejected[0]?.hello.instanceId).toBe("i-second");
expect(rejected[0]?.code).toBe("E_LEASE");
expect(first.isClosed).toBe(false);
first.close();
});
it("accepts a new instance once the previous one disconnected", async () => {
const server = await start();
const first = await connect({ instanceId: "i-first", workspaceId: "ws-1" });
await first.next("hello_ack");
first.close();
await first.waitForClosed();
await waitFor(() => server.connectionCount === 0);
const second = await connect({ instanceId: "i-second", workspaceId: "ws-1" });
const ack = await second.next("hello_ack");
expect(ack.rejected).toBeUndefined();
expect(server.connection("ws-1")?.instanceId).toBe("i-second");
second.close();
});
it("supports several workspaces at once", async () => {
const server = await start();
const one = await connect({ instanceId: "i-1", workspaceId: "ws-1" });
const two = await connect({ instanceId: "i-2", workspaceId: "ws-2" });
await one.next("hello_ack");
await two.next("hello_ack");
expect(server.connectionCount).toBe(2);
expect(server.connection("ws-1")?.instanceId).toBe("i-1");
expect(server.connection("ws-2")?.instanceId).toBe("i-2");
one.close();
two.close();
});
it("frames on newline only, tolerates CRLF and split writes", async () => {
const server = await start();
const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello: false });
const hello = `${JSON.stringify(makeHello())}\r\n`;
client.sendRaw(hello.slice(0, 12));
await delay(5);
client.sendRaw(hello.slice(12, 40));
await delay(5);
client.sendRaw(hello.slice(40));
await client.next("hello_ack");
const connection = server.connection("ws-test");
expect(connection).toBeDefined();
const event = JSON.stringify({
v: 1,
type: "event",
sessionId: "s1",
epoch: "e1",
seq: 4,
ts: 123,
payload: { event: { type: "agent_start", ts: 123 } },
});
client.sendRaw(event.slice(0, 25));
await delay(5);
client.sendRaw(`${event.slice(25)}\r\n`);
await waitFor(() => bus.published.find((record) => record.type === "event"));
const published = bus.published.find((record) => record.type === "event");
expect(published?.sessionId).toBe("s1");
expect(published?.seq).toBe(4);
client.close();
});
it("rejects a frame larger than maxFrameBytes with E_PAYLOAD_TOO_LARGE", async () => {
await start({ maxFrameBytes: 512 });
const client = await PluginClient.connect({ socketPath: daemonSocketPath(), hello: false });
client.sendRaw("x".repeat(1024));
const error = await client.next("error");
expect(asRecord(error.payload).code).toBe("E_PAYLOAD_TOO_LARGE");
await client.waitForClosed();
});
it("closes sockets that stay quiet past the heartbeat limit", async () => {
const server = await start({ heartbeatMs: 120, heartbeatCheckMs: 10 });
const client = await connect({ instanceId: "i-hb", workspaceId: "ws-hb" });
await client.next("hello_ack");
await client.waitForClosed(3_000);
await waitFor(() => server.connectionCount === 0);
});
it("keeps sockets alive while any record arrives", async () => {
const server = await start({ heartbeatMs: 120, heartbeatCheckMs: 10 });
const client = await connect({ instanceId: "i-hb", workspaceId: "ws-hb" });
await client.next("hello_ack");
const timer = setInterval(() => {
client.send({ v: 1, type: "instance_state", payload: { status: "ready", sessions: [] } });
}, 30);
await delay(400);
expect(client.isClosed).toBe(false);
expect(server.connectionCount).toBe(1);
clearInterval(timer);
await client.waitForClosed(3_000);
});
it("publishes a degraded instance_state when a plugin disconnects", async () => {
await start();
const client = await connect({ instanceId: "i-1", workspaceId: "ws-1" });
await client.next("hello_ack");
client.close();
await waitFor(() =>
bus.published.find(
(record) =>
record.type === "instance_state" &&
record.instanceId === "i-1" &&
asRecord(record.payload).status === "degraded",
),
);
});
it("calls onClose with the disconnect reason", async () => {
const server = await start();
const closes: { instanceId: string; reason: string }[] = [];
server.setHandlers({
onClose: (connection, reason) => closes.push({ instanceId: connection.instanceId, reason }),
});
const client = await connect({ instanceId: "i-1", workspaceId: "ws-1" });
await client.next("hello_ack");
client.close();
await waitFor(() => closes.length === 1);
expect(closes[0]?.instanceId).toBe("i-1");
expect(closes[0]?.reason).toBe("socket closed");
});
it("stops accepting connections after close()", async () => {
const server = await start();
const client = await connect();
await client.next("hello_ack");
await server.close();
await client.waitForClosed();
await expect(
PluginClient.connect({ socketPath: daemonSocketPath(), hello: makeHello() }),
).rejects.toThrow();
});
});
describe("parseHello", () => {
const baseHello: Record<string, unknown> = {
v: 1,
type: "hello",
token: "a".repeat(64),
instanceId: "i-test-1",
workspaceId: "ws-test",
cwd: "/repo/ws-test",
pid: 42,
hasUI: false,
listenAddr: "/tmp/i-test.sock",
pluginVersion: "1.8.0",
};
it("normalizes optional fields", () => {
const hello = parseHello({ ...baseHello, listenAddr: "" });
expect(hello).toMatchObject({
instanceId: "i-test-1",
workspaceId: "ws-test",
hasUI: false,
listenAddr: null,
pluginVersion: "1.8.0",
});
});
it("rejects invalid pids and missing required fields", () => {
expect(parseHello({ ...baseHello, pid: -1 })).toBeUndefined();
expect(parseHello({ ...baseHello, hasUI: "yes" })).toBeUndefined();
expect(parseHello({ ...baseHello, pluginVersion: "" })).toBeUndefined();
expect(parseHello({ ...baseHello, instanceId: "" })).toBeUndefined();
});
});
+518
View File
@@ -0,0 +1,518 @@
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { daemonSocketPath, daemonTokenPath, stateDir } from "../../src/core/paths.js";
import {
createInstanceManager,
parseProcRss,
parsePsRss,
summarizeResources,
type InstanceManagerDeps,
type InstanceManagerHandle,
} from "../../src/instances/supervisor.js";
import type { InstanceState } from "../../src/protocol/types.js";
import { makeSessionState } from "../daemon/fakes.js";
import {
FakeBus,
PluginClient,
delay,
makeHello,
makeTempEnv,
readRunLog,
startRecords,
waitFor,
writeFakeNvim,
type TempEnv,
} from "./helpers.js";
function asRecord(value: unknown): Record<string, unknown> {
return value as Record<string, unknown>;
}
function isRunning(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function processExits(bus: FakeBus): Record<string, unknown>[] {
return bus.published.filter(
(record) =>
record.type === "event" && asRecord(asRecord(record.payload).event).type === "pi2:process_exit",
);
}
describe("InstanceManager", () => {
let env: TempEnv;
let bus: FakeBus;
let manager: InstanceManagerHandle | undefined;
const workspaces = new Map<string, string>();
beforeEach(() => {
env = makeTempEnv();
bus = new FakeBus();
workspaces.clear();
});
afterEach(async () => {
if (manager) await manager.close();
manager = undefined;
env.cleanup();
});
function addWorkspace(id = "ws-1"): string {
const cwd = join(env.dir, "repo", id);
mkdirSync(cwd, { recursive: true });
workspaces.set(id, cwd);
return cwd;
}
async function create(options: {
bin?: string;
deps?: Partial<InstanceManagerDeps>;
} = {}): Promise<InstanceManagerHandle> {
const instance = await createInstanceManager({
bus,
resolveCwd: (workspaceId) => workspaces.get(workspaceId),
ensureTimeoutMs: 4_000,
shutdownGraceMs: 300,
sigtermGraceMs: 200,
minSpawnIntervalMs: 300,
maxSpawnIntervalMs: 1_000,
...(options.bin === undefined ? {} : { nvimBin: options.bin }),
...(options.deps ?? {}),
});
manager = instance;
return instance;
}
it("spawns one nvim with the right argv/env and resolves with a ready state", async () => {
const cwd = addWorkspace();
const fake = writeFakeNvim(env.dir, { sessions: ["s1"] });
const mgr = await create({ bin: fake.bin });
const state = await mgr.ensure("ws-1");
expect(state.status).toBe("ready");
expect(state.instanceId).toMatch(/^i-fake-\d+$/);
expect(state.pluginVersion).toBe("9.9.9-fake");
expect(state.nvimPid).toBeGreaterThan(0);
expect(state.hasUI).toBe(false);
expect(state.attachedClients).toBe(0);
expect(state.startedAt).toBeGreaterThan(0);
expect(state.listenAddr).toMatch(/\/i\/[0-9a-f]{16}\.sock$/);
expect(mgr.get("ws-1")?.instanceId).toBe(state.instanceId);
const starts = startRecords(fake.runLog);
expect(starts).toHaveLength(1);
const start = starts[0]!;
const argv = start.argv as string[];
expect(argv.slice(0, 2)).toEqual(["--headless", "--listen"]);
expect(argv[2]).toBe(state.listenAddr);
expect(argv.slice(3)).toEqual(["-c", 'lua require("pi.host").start()']);
expect(start.cwd).toBe(cwd);
const spawnedEnv = start.env as Record<string, string>;
expect(spawnedEnv.PI2_WORKSPACE_ID).toBe("ws-1");
expect(spawnedEnv.PI2_RUNTIME_DIR).toBe(env.runtime);
expect(spawnedEnv.PI2_DAEMON_SOCKET).toBe(daemonSocketPath());
expect(spawnedEnv.PI2_DAEMON_TOKEN_PATH).toBe(daemonTokenPath());
// Starting -> ready both surfaced on the bus.
const statuses = bus.published
.filter((record) => record.type === "instance_state" && record.workspaceId === "ws-1")
.map((record) => asRecord(record.payload).status);
expect(statuses).toContain("starting");
expect(statuses).toContain("ready");
});
it("passes PI2_NVIM_INIT as -u only when configured", async () => {
addWorkspace();
const init = join(env.dir, "init.lua");
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin, deps: { nvimInit: init } });
await mgr.ensure("ws-1");
const argv = startRecords(fake.runLog)[0]?.argv as string[];
expect(argv.slice(3, 5)).toEqual(["-u", init]);
expect(argv.slice(5)).toEqual(["-c", 'lua require("pi.host").start()']);
});
it("is idempotent and reports state changes to handlers", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin });
const seen: InstanceState[] = [];
mgr.onInstanceChange((state) => seen.push(state));
const first = await mgr.ensure("ws-1");
const second = await mgr.ensure("ws-1");
expect(second.instanceId).toBe(first.instanceId);
expect(startRecords(fake.runLog)).toHaveLength(1);
expect(seen.some((state) => state.status === "ready")).toBe(true);
});
it("lets concurrent ensure() calls share one spawn", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin });
const states = await Promise.all([mgr.ensure("ws-1"), mgr.ensure("ws-1"), mgr.ensure("ws-1")]);
expect(new Set(states.map((state) => state.instanceId)).size).toBe(1);
expect(startRecords(fake.runLog)).toHaveLength(1);
});
it("adopts an already connected plugin instead of spawning", async () => {
const cwd = addWorkspace();
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin });
const plugin = await PluginClient.connect({
socketPath: daemonSocketPath(),
hello: makeHello({ instanceId: "i-adopt", workspaceId: "ws-1", cwd }),
});
await plugin.next("hello_ack");
const state = await mgr.ensure("ws-1");
expect(state.instanceId).toBe("i-adopt");
expect(state.status).toBe("ready");
expect(startRecords(fake.runLog)).toHaveLength(0);
plugin.close();
});
it("times out a silent instance with E_INSTANCE_STARTING and kills it", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir, { mode: "no-hello" });
const mgr = await create({ bin: fake.bin });
await expect(mgr.ensure("ws-1", { timeoutMs: 250 })).rejects.toMatchObject({
code: "E_INSTANCE_STARTING",
retryable: true,
});
const starts = startRecords(fake.runLog);
expect(starts).toHaveLength(1);
const pid = starts[0]?.pid as number;
await waitFor(() => !isRunning(pid), 3_000);
expect(mgr.list().find((state) => state.workspaceId === "ws-1")?.status).toBe("stopped");
// A failed start backs off the next attempt.
await expect(mgr.ensure("ws-1")).rejects.toMatchObject({
code: "E_INSTANCE_UNAVAILABLE",
message: expect.stringContaining("backing off"),
});
});
it("reports E_INSTANCE_UNAVAILABLE when the nvim binary cannot be spawned", async () => {
addWorkspace();
const mgr = await create({ deps: { nvimBin: join(env.dir, "no-such-nvim") } });
await expect(mgr.ensure("ws-1")).rejects.toMatchObject({
code: "E_INSTANCE_UNAVAILABLE",
message: expect.stringContaining("failed to spawn"),
});
const logDir = join(stateDir(), "instances");
await waitFor(() => {
if (!existsSync(logDir)) return false;
const logFile = readdirSync(logDir)[0];
if (logFile === undefined) return false;
return readFileSync(join(logDir, logFile), "utf8").includes("spawn error");
});
});
it("backs off after a failed start, then succeeds on a later ensure", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir, { mode: "exit-first-run", failRuns: 1 });
const mgr = await create({
bin: fake.bin,
deps: { minSpawnIntervalMs: 150, maxSpawnIntervalMs: 500 },
});
await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ code: "E_INSTANCE_UNAVAILABLE" });
expect(startRecords(fake.runLog)).toHaveLength(1);
const started = Date.now();
await expect(mgr.ensure("ws-1")).rejects.toMatchObject({
code: "E_INSTANCE_UNAVAILABLE",
message: expect.stringContaining("backing off"),
});
expect(Date.now() - started).toBeLessThan(150);
expect(startRecords(fake.runLog)).toHaveLength(1);
await delay(220);
const state = await mgr.ensure("ws-1");
expect(state.status).toBe("ready");
expect(startRecords(fake.runLog)).toHaveLength(2);
});
it("rejects a second instance as unmanaged while the managed one keeps serving", async () => {
const cwd = addWorkspace();
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin });
const first = await mgr.ensure("ws-1");
const intruder = await PluginClient.connect({
socketPath: daemonSocketPath(),
hello: makeHello({ instanceId: "i-intruder", workspaceId: "ws-1", cwd }),
});
const ack = await intruder.next("hello_ack");
expect(asRecord(ack.rejected).code).toBe("E_LEASE");
expect(asRecord(ack.rejected).message).toBe(`workspace already managed by ${first.instanceId}`);
await intruder.waitForClosed();
const unmanaged = await waitFor(() =>
mgr.list().find((state) => state.instanceId === "i-intruder"),
);
expect(unmanaged.status).toBe("unmanaged");
expect(unmanaged.workspaceId).toBe("ws-1");
expect(unmanaged.reason).toContain("already managed");
expect(mgr.instanceStates().map((state) => state.instanceId)).toEqual([first.instanceId]);
expect((await mgr.ensure("ws-1")).instanceId).toBe(first.instanceId);
expect(startRecords(fake.runLog)).toHaveLength(1);
});
it("degrades on socket close and fans pi2:process_exit out to known sessions", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir, { sessions: ["s1", "s2"], crashAfterMs: 150 });
const mgr = await create({
bin: fake.bin,
deps: { minSpawnIntervalMs: 800, maxSpawnIntervalMs: 2_000 },
});
const state = await mgr.ensure("ws-1");
await waitFor(() => mgr.get("ws-1")?.hasSession("s2"), 3_000);
const degraded = await waitFor(
() => mgr.list().find((candidate) => candidate.status === "degraded"),
4_000,
);
expect(degraded.instanceId).toBe(state.instanceId);
expect(degraded.nvimPid).toBeNull();
expect(mgr.get("ws-1")).toBeUndefined();
expect(mgr.findWorkspaceBySession("s1")).toBeUndefined();
const exits = processExits(bus);
expect(exits.map((record) => record.sessionId).sort()).toEqual(["s1", "s2"]);
for (const record of exits) {
expect(record.workspaceId).toBe("ws-1");
expect(record.epoch).toBe(state.instanceId);
expect(asRecord(record.payload).event).toMatchObject({
type: "pi2:process_exit",
code: null,
reason: "instance died",
});
}
// Never auto-restarted...
await delay(400);
expect(startRecords(fake.runLog)).toHaveLength(1);
// ...and the next ensure backs off, then spawns a fresh instance.
await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ code: "E_INSTANCE_UNAVAILABLE" });
await delay(500);
const respawned = await mgr.ensure("ws-1");
expect(respawned.instanceId).not.toBe(state.instanceId);
expect(startRecords(fake.runLog)).toHaveLength(2);
});
it("drains an instance on shutdown, reports stopped and does not emit process_exit", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir, { sessions: ["s1"] });
const mgr = await create({ bin: fake.bin });
const state = await mgr.ensure("ws-1");
const pid = state.nvimPid as number;
const exitsBefore = processExits(bus).length;
await mgr.shutdown("ws-1", "drain");
const stopped = mgr.list().find((candidate) => candidate.workspaceId === "ws-1");
expect(stopped?.status).toBe("stopped");
expect(stopped?.nvimPid).toBeNull();
expect(mgr.get("ws-1")).toBeUndefined();
expect(processExits(bus)).toHaveLength(exitsBefore);
expect(
readRunLog(fake.runLog).some(
(entry) => entry.kind === "shutdown" && asRecord(entry).mode === "drain",
),
).toBe(true);
await waitFor(() => !isRunning(pid), 3_000);
const respawned = await mgr.ensure("ws-1");
expect(respawned.instanceId).not.toBe(state.instanceId);
expect(startRecords(fake.runLog)).toHaveLength(2);
});
it("escalates SIGTERM to SIGKILL when the instance ignores shutdown", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir, { ignoreShutdown: true });
const mgr = await create({
bin: fake.bin,
deps: { shutdownGraceMs: 150, sigtermGraceMs: 150 },
});
const state = await mgr.ensure("ws-1");
const pid = state.nvimPid as number;
const started = Date.now();
await mgr.shutdown("ws-1", "stop");
const elapsed = Date.now() - started;
expect(elapsed).toBeGreaterThanOrEqual(250);
expect(mgr.list().find((candidate) => candidate.workspaceId === "ws-1")?.status).toBe("stopped");
expect(readRunLog(fake.runLog).some((entry) => entry.kind === "sigterm")).toBe(true);
await waitFor(() => !isRunning(pid), 3_000);
});
it("treats shutdown of an unknown workspace as a no-op", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin });
await expect(mgr.shutdown("ws-missing", "stop")).resolves.toBeUndefined();
expect(startRecords(fake.runLog)).toHaveLength(0);
});
it("resolves workspace ownership from live sessions and snapshot caches", async () => {
addWorkspace();
const snapshotState = makeSessionState("s9", "ws-1");
const fake = writeFakeNvim(env.dir, {
sessions: ["s1"],
snapshots: [{ sessionId: "s9", state: snapshotState }],
});
const mgr = await create({ bin: fake.bin });
await mgr.ensure("ws-1");
await waitFor(() => mgr.findWorkspaceBySession("s1") === "ws-1");
await waitFor(() => mgr.findWorkspaceBySession("s9") === "ws-1");
expect(mgr.findWorkspaceBySession("unknown")).toBeUndefined();
});
it("unsubscribes the plugin when the last browser subscriber goes away", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin });
await mgr.ensure("ws-1");
mgr.get("ws-1")?.subscribe("s1");
mgr.maybeUnsubscribe("ws-1", "s1");
await waitFor(() =>
readRunLog(fake.runLog).some((entry) => {
if (entry.kind !== "record") return false;
const record = asRecord(asRecord(entry).record);
return record.type === "sub.unsubscribe" && record.sessionId === "s1";
}),
);
const received = readRunLog(fake.runLog)
.filter((entry) => entry.kind === "record")
.map((entry) => asRecord(entry.record).type);
expect(received).toContain("sub.subscribe");
expect(received).toContain("sub.unsubscribe");
});
it("reports E_NOT_FOUND for unknown workspaces without spawning", async () => {
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin });
await expect(mgr.ensure("no-such-workspace")).rejects.toMatchObject({ code: "E_NOT_FOUND" });
expect(startRecords(fake.runLog)).toHaveLength(0);
});
it("reports per-instance RSS and totals for /api/v1/resources", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir, { sessions: ["s1"] });
const mgr = await create({
bin: fake.bin,
deps: {
readRss: async () => 123 * 1024 * 1024,
totalMemory: () => 16 * 1024 ** 3,
},
});
const state = await mgr.ensure("ws-1");
await waitFor(() => mgr.get("ws-1")?.hasSession("s1"));
const snapshot = await mgr.resources();
expect(snapshot.instances).toHaveLength(1);
expect(snapshot.instances[0]).toMatchObject({
workspaceId: "ws-1",
instanceId: state.instanceId,
nvimPid: state.nvimPid,
rssBytes: 123 * 1024 * 1024,
sessions: 1,
hasUI: false,
});
expect(snapshot.totalRssBytes).toBe(123 * 1024 * 1024);
expect(snapshot.physicalMemoryBytes).toBe(16 * 1024 ** 3);
expect(snapshot.warn).toBe(false);
expect(snapshot.reason).toBeUndefined();
});
it("closes the server and kills spawned instances", async () => {
addWorkspace();
const fake = writeFakeNvim(env.dir);
const mgr = await create({ bin: fake.bin });
const state = await mgr.ensure("ws-1");
const pid = state.nvimPid as number;
await mgr.close();
await waitFor(() => !isRunning(pid), 3_000);
await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ code: "E_INSTANCE_UNAVAILABLE" });
expect(existsSync(daemonSocketPath())).toBe(false);
});
});
describe("resources helpers", () => {
it("parses /proc/<pid>/status VmRSS", () => {
expect(parseProcRss("Name:\tnvim\nVmRSS:\t 102400 kB\nVmSize:\t 204800 kB\n")).toBe(102400 * 1024);
expect(parseProcRss("VmRSS: 0 kB")).toBe(0);
expect(parseProcRss("Name: nvim\n")).toBeNull();
expect(parseProcRss("VmRSS: not-a-number kB")).toBeNull();
});
it("parses ps -o rss= output", () => {
expect(parsePsRss(" 204800\n")).toBe(204800 * 1024);
expect(parsePsRss("204800 12\n")).toBe(204800 * 1024);
expect(parsePsRss("")).toBeNull();
expect(parsePsRss("not-a-number")).toBeNull();
});
const instance = (index: number, rssBytes: number | null = 1024) => ({
workspaceId: `ws-${index}`,
instanceId: `i-${index}`,
nvimPid: 1000 + index,
rssBytes,
sessions: 0,
hasUI: false,
});
it("warns above eight instances", () => {
const snapshot = summarizeResources(Array.from({ length: 9 }, (_, index) => instance(index)), 16 * 1024 ** 3);
expect(snapshot.warn).toBe(true);
expect(snapshot.reason).toContain("9 instances");
expect(snapshot.totalRssBytes).toBe(9 * 1024);
});
it("warns when RSS exceeds 60% of physical memory", () => {
const snapshot = summarizeResources([instance(1, 11 * 1024 ** 3)], 16 * 1024 ** 3);
expect(snapshot.warn).toBe(true);
expect(snapshot.reason).toContain("RSS");
});
it("does not warn at exactly eight instances and 60% RSS", () => {
const snapshot = summarizeResources([instance(1, 9.6 * 1024 ** 3)], 16 * 1024 ** 3);
expect(snapshot.warn).toBe(false);
expect(snapshot.reason).toBeUndefined();
});
it("ignores missing RSS in the total", () => {
const snapshot = summarizeResources([instance(1, null), instance(2, 2048)], 16 * 1024 ** 3);
expect(snapshot.totalRssBytes).toBe(2048);
expect(snapshot.warn).toBe(false);
});
});