From db387ae248da98ebde51bdedf85c459a5114b167 Mon Sep 17 00:00:00 2001 From: yuez Date: Wed, 28 Oct 2026 17:32:16 +0800 Subject: [PATCH] feat(instances): spawn a host-capable nvim without the user's config Opening a project from the console needed `:PiWebStart` first because the managed spawn loaded the *user's* nvim config and ran with `stdio:"ignore"`. When that config did not resolve pi2.nvim (lazy.nvim, a dev worktree behind `PI_DEV_DIR`, a service with a frozen PATH) or the checkout lacked `lua/pi/host.lua`, nvim stayed alive and silent and `instance.ensure` could only report a bare 5 s timeout: nothing to read, nothing to fix. - `core/plugin`: discover the plugin (`PI2_PLUGIN_DIR`, lazy.nvim, `site/pack/*/{start,opt}`, system dirs) and require both `lua/pi/host.lua` and `lua/pi/web/bridge.lua`; name a misconfigured `PI2_PLUGIN_DIR` first. - `instances/host-init`: generate a minimal init (prepend the plugin, prepend nothing else, `cquit 1` when `pi.host` is missing) so a spawn fails with a real exit code instead of silence. `PI2_NVIM_INIT` keeps `user` (the old behaviour) and any explicit path. - supervisor: refuse to spawn when no host-capable plugin exists, route the child's stdout/stderr into `instances/.log`, and fold the log tail into `instance_state.reason` and the thrown error. `PI2_ENSURE_TIMEOUT_MS` (default 10000) replaces the fixed 5 s. - `core/paths`: one shared `expandTilde` for the plugin probe, the workspace allowlist and `pi2 doctor`. --- src/core/paths.ts | 12 ++ src/core/plugin.ts | 208 ++++++++++++++++++ src/instances/host-init.ts | 110 ++++++++++ src/instances/index.ts | 3 + src/instances/supervisor.ts | 348 +++++++++++++++++++++++++++--- test/core/plugin.test.ts | 222 +++++++++++++++++++ test/instances/helpers.ts | 15 +- test/instances/host-init.test.ts | 109 ++++++++++ test/instances/supervisor.test.ts | 175 ++++++++++++++- 9 files changed, 1162 insertions(+), 40 deletions(-) create mode 100644 src/core/plugin.ts create mode 100644 src/instances/host-init.ts create mode 100644 test/core/plugin.test.ts create mode 100644 test/instances/host-init.test.ts diff --git a/src/core/paths.ts b/src/core/paths.ts index cf5d161..99ea178 100644 --- a/src/core/paths.ts +++ b/src/core/paths.ts @@ -28,6 +28,18 @@ export function stateDir(): string { return join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "pi2"); } +/** + * `~` → `home`, `~/…` → `home/…`, `~user/…` → `undefined` (never expanded), + * anything else unchanged. Shared by the workspace allowlist and the plugin + * probe so both accept exactly the same shorthand. + */ +export function expandTilde(raw: string, home: string = homedir()): string | undefined { + if (raw === "~") return home; + if (raw.startsWith("~/")) return join(home, raw.slice(2)); + if (raw.startsWith("~")) return undefined; + return raw; +} + export function ensureDir(path: string, mode = 0o700): string { if (!existsSync(path)) mkdirSync(path, { recursive: true, mode }); return path; diff --git a/src/core/plugin.ts b/src/core/plugin.ts new file mode 100644 index 0000000..46be3de --- /dev/null +++ b/src/core/plugin.ts @@ -0,0 +1,208 @@ +/** + * Where the pi2.nvim plugin lives on disk. + * + * The daemon spawns `nvim --headless -u ` and that init must be + * able to `require("pi.host")`. Getting this wrong is invisible from the daemon + * side: nvim stays alive, prints into a log nobody reads, and the browser only + * sees a 10 s "did not say hello" timeout. So plugin discovery is a first-class + * probe with an explicit, ordered candidate list and a human failure line — used + * by the supervisor (spawn refusal) and by `pi2 doctor`. + * + * A directory counts as a plugin only when it is *host-capable*: it must ship + * both `lua/pi/host.lua` (the daemon bridge entry point) and + * `lua/pi/web/bridge.lua` (the session bridge). Older checkouts that only carry + * one of the two are reported, never silently used, because `host.start()` + * would fail again on the next `require`. + */ + +import { existsSync, readdirSync, type Dirent } from "node:fs"; +import { homedir } from "node:os"; +import { join, resolve } from "node:path"; +import { expandTilde } from "./paths.js"; + +/** Directory name the plugin is installed under (lazy.nvim, pack/*\/start, …). */ +export const PLUGIN_NAME = "pi2.nvim"; + +/** Entry points that every usable plugin checkout must contain. */ +export const PLUGIN_HOST_FILE = join("lua", "pi", "host.lua"); +export const PLUGIN_BRIDGE_FILE = join("lua", "pi", "web", "bridge.lua"); + +/** One explored location, classified against the host-capability contract. */ +export interface PluginDirCandidate { + dir: string; + reason: "ok" | "missing-host" | "missing-bridge" | "absent"; +} + +/** A confirmed host-capable plugin checkout. */ +export interface ResolvedPlugin { + dir: string; + host: string; + bridge: string; +} + +export type PluginResolution = + | { plugin: ResolvedPlugin } + | { + plugin: undefined; + candidates: PluginDirCandidate[]; + /** The `PI2_PLUGIN_DIR` value that was probed first, if any. */ + configured: string | undefined; + }; + +type Readdir = (dir: string, options: { withFileTypes: true }) => Dirent[]; + +export interface ResolvePluginDirOptions { + /** Defaults to `process.env` (`PI2_PLUGIN_DIR` is read from it). */ + env?: Record; + /** Defaults to `homedir()`; also used to expand a leading `~/`. */ + home?: string; + /** Defaults to `existsSync`; injected in tests to stay hermetic. */ + exists?: (path: string) => boolean; + /** Defaults to `readdirSync`; enumerates `site/pack/*\/{start,opt}`. */ + readdir?: Readdir; +} + +const defaultReaddir: Readdir = (dir, options) => readdirSync(dir, options); + +/** + * `site/pack//{start,opt}/pi2.nvim` for one nvim data directory. + * + * `readdir` must never throw here: a stock nvim has no `site/pack` at all, and a + * missing directory is the normal case, not an error worth surfacing. + */ +function packCandidates(dataDir: string, readdir: Readdir): string[] { + const root = join(dataDir, "site", "pack"); + let entries: Dirent[]; + try { + entries = readdir(root, { withFileTypes: true }); + } catch { + return []; + } + const dirs: string[] = []; + for (const kind of ["start", "opt"] as const) { + for (const entry of entries) { + if (!entry.isDirectory()) continue; + dirs.push(join(root, entry.name, kind, PLUGIN_NAME)); + } + } + return dirs; +} + +/** + * Ordered list of directories that could hold the plugin. + * + * `PI2_PLUGIN_DIR` first (explicit user intent beats discovery), then the + * lazy.nvim default, then `pack/*\/start` before `pack/*\/opt` (start packages + * are the ones that are actually loaded at startup), user data dir before the + * system-wide ones. + */ +export function pluginDirCandidates(options: ResolvePluginDirOptions = {}): string[] { + const env = options.env ?? process.env; + const home = options.home ?? homedir(); + const readdir = options.readdir ?? defaultReaddir; + + const dirs: string[] = []; + const configured = env.PI2_PLUGIN_DIR?.trim(); + if (configured !== undefined && configured !== "") { + dirs.push(resolve(expandTilde(configured, home) ?? configured)); + } + + const userNvim = join(home, ".local", "share", "nvim"); + dirs.push(join(userNvim, "lazy", PLUGIN_NAME)); + for (const dataDir of [userNvim, "/usr/share/nvim", "/usr/local/share/nvim"]) { + dirs.push(...packCandidates(dataDir, readdir)); + } + + // `PI2_PLUGIN_DIR` may name the same directory lazy.nvim would have found; + // keep the first occurrence so the reported order matches the probe order. + return [...new Set(dirs)]; +} + +/** Classifies one directory; a match needs BOTH entry points. */ +export function classifyPluginDir( + dir: string, + exists: (path: string) => boolean = existsSync, +): PluginDirCandidate { + if (!exists(dir)) return { dir, reason: "absent" }; + if (!exists(join(dir, PLUGIN_HOST_FILE))) return { dir, reason: "missing-host" }; + if (!exists(join(dir, PLUGIN_BRIDGE_FILE))) return { dir, reason: "missing-bridge" }; + return { dir, reason: "ok" }; +} + +/** + * Finds the first host-capable plugin checkout. + * + * Returns the winning `ResolvedPlugin` or every candidate with its verdict, so + * the caller can explain *why* nothing matched instead of shouting "not found" + * at a user whose lazy.nvim simply has not installed the plugin yet. + */ +export function resolvePluginDir(options: ResolvePluginDirOptions = {}): PluginResolution { + const home = options.home ?? homedir(); + const exists = options.exists ?? existsSync; + const candidates = pluginDirCandidates({ ...options, home }).map((dir) => classifyPluginDir(dir, exists)); + const match = candidates.find((candidate) => candidate.reason === "ok"); + if (match === undefined) { + const configured = (options.env ?? process.env).PI2_PLUGIN_DIR?.trim(); + return { + plugin: undefined, + candidates: [...candidates], + configured: configured === undefined || configured === "" ? undefined : candidates[0]?.dir, + }; + } + return { + plugin: { + dir: match.dir, + host: join(match.dir, PLUGIN_HOST_FILE), + bridge: join(match.dir, PLUGIN_BRIDGE_FILE), + }, + }; +} + +/** Collapses the home directory to `~` so messages stay readable. */ +export function displayPath(path: string, home: string = homedir()): string { + if (path === home) return "~"; + const prefix = `${home}/`; + if (path.startsWith(prefix)) return `~/${path.slice(prefix.length)}`; + return path; +} + +/** + * One human line explaining a failed plugin resolution. + * + * An explicitly configured `PI2_PLUGIN_DIR` is named first: a typo there is the + * one failure the user can fix in seconds, and blaming a stale lazy.nvim + * checkout instead sends them looking in the wrong place. + * + * Failing that, a stale checkout (present, but without `host.lua`/`bridge.lua`) + * is the case users hit after a plugin update and the one a bare "not found" + * hides, so it is reported before the generic message. + */ +export function describePluginFailure( + candidates: readonly PluginDirCandidate[], + options: { configured?: string | undefined } = {}, +): string { + const home = homedir(); + const configured = + options.configured === undefined + ? undefined + : candidates.find((candidate) => candidate.dir === options.configured); + if (configured !== undefined && configured.reason !== "ok") { + const path = displayPath(configured.dir, home); + if (configured.reason === "absent") return `PI2_PLUGIN_DIR=${path} does not exist`; + const what = configured.reason === "missing-host" ? PLUGIN_HOST_FILE : PLUGIN_BRIDGE_FILE; + return `PI2_PLUGIN_DIR=${path} has no ${what} (update the plugin)`; + } + + const broken = candidates.find( + (candidate) => candidate.reason === "missing-host" || candidate.reason === "missing-bridge", + ); + if (broken !== undefined) { + const what = broken.reason === "missing-host" ? PLUGIN_HOST_FILE : PLUGIN_BRIDGE_FILE; + return `${PLUGIN_NAME} at ${displayPath(broken.dir, home)} has no ${what} (update the plugin)`; + } + const first = candidates[0]; + const seen = candidates.length === 0 ? "no locations" : `${candidates.length} location(s)`; + return first === undefined + ? `no ${PLUGIN_NAME} plugin found (looked in ${seen})` + : `no ${PLUGIN_NAME} plugin found (looked in ${seen}, first ${displayPath(first.dir, home)})`; +} diff --git a/src/instances/host-init.ts b/src/instances/host-init.ts new file mode 100644 index 0000000..f9ee526 --- /dev/null +++ b/src/instances/host-init.ts @@ -0,0 +1,110 @@ +/** + * The generated nvim init the daemon hands to every headless instance. + * + * Why this exists: a spawned `nvim --headless -u ` only reaches the + * daemon if the user's own config happens to load pi2.nvim and `pi.host`. With + * lazy.nvim, a dev worktree behind `PI_DEV_DIR`, or a systemd unit with a frozen + * `PATH`, it often does not — and the failure mode is a process that stays alive + * and silent. A tiny generated init that (1) prepends the resolved plugin, (2) + * keeps nvim from writing swap/shada state into the workspace and (3) `cquit 1`s + * when the plugin cannot be loaded, turns that silence into a real exit code and + * a log line the supervisor can read back. + * + * The init deliberately loads nothing else: `pi2 open` must work regardless of + * the user's config, and the plugin's own `host.start()` owns the wait loop. + */ + +import { randomUUID } from "node:crypto"; +import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; + +export const HOST_INIT_FILENAME = "host-init.lua"; + +/** + * Written once per `(dir, pluginDir)` in the daemon's lifetime. + * + * Spawns are frequent (one per workspace, plus every crash/retry) while the init + * only changes when the plugin directory changes, so a module-level memo keeps + * the spawn path free of filesystem writes without needing a cache file. + */ +const written = new Map(); + +/** Lua double-quoted string literal: backslash, quote and control chars only. */ +export function luaString(value: string): string { + const escaped = value + .replace(/\\/g, "\\\\") + .replace(/"/g, '\\"') + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/\t/g, "\\t"); + return `"${escaped}"`; +} + +/** Pure renderer (exported so tests and diagnostics can assert the content). */ +export function renderHostInit(pluginDir: string): string { + return [ + "-- Generated by pi2d (pi2 daemon). Do not edit: rewritten on spawn.", + `-- plugin: ${pluginDir}`, + "--", + "-- Minimal init for a daemon-managed instance: the user config is NOT", + "-- loaded, so a broken/slow/lazy config can never hide the plugin again.", + "", + `vim.opt.runtimepath:prepend(${luaString(pluginDir)})`, + "vim.opt.swapfile = false", + 'vim.opt.shadafile = "NONE"', + 'vim.g.mapleader = " "', + "", + 'local ok, host = pcall(require, "pi.host")', + "if not ok then", + ' vim.api.nvim_err_writeln("pi2: " .. tostring(host))', + ' vim.cmd("cquit 1")', + "else", + " host.start()", + "end", + "", + ].join("\n"); +} + +/** + * Writes `/host-init.lua` for `pluginDir` and returns its absolute path. + * + * Atomic rename keeps a half-written init from ever reaching a concurrently + * spawning nvim; comparing before writing keeps the file's mtime (and therefore + * anything watching it) stable across daemon restarts. + */ +export async function writeHostInit(options: { dir: string; pluginDir: string }): Promise { + const dir = resolve(options.dir); + const pluginDir = resolve(options.pluginDir); + const key = `${dir}\u0000${pluginDir}`; + const cached = written.get(key); + if (cached !== undefined) return cached; + + const content = renderHostInit(pluginDir); + const path = join(dir, HOST_INIT_FILENAME); + await mkdir(dir, { recursive: true, mode: 0o700 }); + + let existing: string | undefined; + try { + existing = await readFile(path, "utf8"); + } catch { + existing = undefined; + } + if (existing !== content) { + const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`; + try { + await writeFile(tmp, content, { mode: 0o600 }); + await rename(tmp, path); + } catch (error) { + await unlink(tmp).catch(() => undefined); + throw error; + } + } + + written.set(key, path); + return path; +} + +/** Test seam: forget every memoized path. */ +export function resetHostInitCache(): void { + written.clear(); +} diff --git a/src/instances/index.ts b/src/instances/index.ts index ebc5a1a..093eef4 100644 --- a/src/instances/index.ts +++ b/src/instances/index.ts @@ -16,10 +16,12 @@ export type { PluginHello, SnapshotCacheEntry, PluginSocketConnectionOptions } f export { createInstanceManager, ManagedInstanceManager, + parseEnsureTimeoutMs, parseProcRss, parsePsRss, summarizeResources, DEFAULT_ENSURE_TIMEOUT_MS, + DEFAULT_LOG_TAIL_LINES, DEFAULT_MAX_INSTANCES, DEFAULT_RSS_FRACTION, DEFAULT_SHUTDOWN_GRACE_MS, @@ -27,4 +29,5 @@ export { DEFAULT_MIN_SPAWN_INTERVAL_MS, } from "./supervisor.js"; export type { InstanceManagerDeps, InstanceManagerHandle, SpawnFunction } from "./supervisor.js"; +export { HOST_INIT_FILENAME, luaString, renderHostInit, writeHostInit } from "./host-init.js"; export { InstanceError, TIMEOUT_CODE, asInstanceError, errorMessage } from "./errors.js"; diff --git a/src/instances/supervisor.ts b/src/instances/supervisor.ts index a4415a4..d1e7c5c 100644 --- a/src/instances/supervisor.ts +++ b/src/instances/supervisor.ts @@ -11,6 +11,7 @@ import { execFile, spawn, type ChildProcess, type SpawnOptions } from "node:child_process"; import { randomUUID } from "node:crypto"; +import { closeSync, openSync } from "node:fs"; import { appendFile, mkdir, readFile } from "node:fs/promises"; import { totalmem } from "node:os"; import { dirname, join } from "node:path"; @@ -30,15 +31,27 @@ import { runtimeDir, stateDir, } from "../core/paths.js"; +import { describePluginFailure, resolvePluginDir, type PluginResolution } from "../core/plugin.js"; import { ERROR_CODES } from "../protocol/errors.js"; import { PROTOCOL_VERSION, type InstanceState } from "../protocol/types.js"; import { PluginSocketConnection, type PluginHello } from "./connection.js"; import { InstanceError, asInstanceError, errorMessage } from "./errors.js"; +import { writeHostInit } from "./host-init.js"; import { PluginServer, type PluginServerOptions, type PluginServerRejection } from "./plugin-server.js"; const execFileAsync = promisify(execFile); -export const DEFAULT_ENSURE_TIMEOUT_MS = 5_000; +/** + * How long `ensure()` waits for the plugin `hello` by default. + * + * 10 s, not 5 s: the generated host init starts a *config-less* headless nvim, + * but a cold disk cache plus a large plugin directory can still take a few + * seconds, and a false timeout looks exactly like a broken plugin from the + * browser's point of view. `PI2_ENSURE_TIMEOUT_MS` overrides it. + */ +export const DEFAULT_ENSURE_TIMEOUT_MS = 10_000; +/** Lines of the instance log quoted back on a failed spawn/timeout. */ +export const DEFAULT_LOG_TAIL_LINES = 40; export const DEFAULT_SHUTDOWN_GRACE_MS = 5_000; export const DEFAULT_SIGTERM_GRACE_MS = 2_000; export const DEFAULT_MIN_SPAWN_INTERVAL_MS = 2_000; @@ -66,6 +79,16 @@ export interface InstanceManagerDeps { logDir?: string; nvimBin?: string; nvimInit?: string; + /** Explicit plugin checkout; beats discovery (same effect as `PI2_PLUGIN_DIR`). */ + pluginDir?: string; + /** Where the generated host init lives; defaults to `${stateDir()}/host-init`. */ + hostInitDir?: string; + writeHostInit?: typeof writeHostInit; + /** Injectable plugin discovery (defaults to `resolvePluginDir`). */ + resolvePlugin?: () => PluginResolution; + /** Lines of `.log` quoted on failure; defaults to 40. */ + logTailLines?: number; + readLogTail?: (path: string, lines: number) => Promise; env?: NodeJS.ProcessEnv; spawnFn?: SpawnFunction; instanceSocketPath?: (workspaceId: string, instanceId: string) => string; @@ -95,7 +118,7 @@ interface SpawnWaiter { promise: Promise; settle(connection: PluginSocketConnection): void; fail(error: InstanceError): void; - attach(child: ChildProcess, logPath: string): void; + attach(child: ChildProcess, logPath: string, init: SpawnInit | undefined): void; cancel(reason: string): void; } @@ -104,6 +127,31 @@ interface SpawnFailure { nextAllowedAt: number; } +/** Which `-u` this spawn used, recorded so failures can name their inputs. */ +interface SpawnInit { + /** `undefined` means "no `-u`" (the user's own config, or none at all). */ + path: string | undefined; + pluginDir: string | undefined; +} + +/** A failed spawn reduced to what a browser can show and a log can keep. */ +interface SpawnDiagnostics { + /** Single line for `InstanceState.reason` (goes out through `instance_state`). */ + reason: string; + /** Multi-line form (summary + log tail) for the thrown `InstanceError`. */ + message: string; +} + +/** + * Reads `PI2_ENSURE_TIMEOUT_MS`; `undefined` for unset or invalid values so the + * caller can warn instead of silently running with a nonsense timeout. + */ +export function parseEnsureTimeoutMs(raw: string | undefined): number | undefined { + if (raw === undefined || raw.trim() === "") return undefined; + const value = Number(raw.trim()); + return Number.isSafeInteger(value) && value > 0 ? value : undefined; +} + /** `VmRSS: 123456 kB` from `/proc//status` → bytes. */ export function parseProcRss(status: string): number | null { const match = /^\s*VmRSS:\s+(\d+)\s+kB\s*$/m.exec(status); @@ -200,8 +248,16 @@ export class ManagedInstanceManager implements InstanceManagerHandle { private readonly tokenPath: string; private readonly runtime: string; private readonly logDir: string; + private readonly hostInitDir: string; private readonly nvimBin: string; private readonly nvimInit: string | undefined; + /** `PI2_NVIM_INIT=user`: spawn with no `-u`, i.e. the user's own config. */ + private readonly useUserConfig: boolean; + private readonly pluginDir: string | undefined; + private readonly writeHostInit: (options: { dir: string; pluginDir: string }) => Promise; + private readonly resolvePlugin: () => PluginResolution; + private readonly logTailLines: number; + private readonly readLogTail: (path: string, lines: number) => Promise; private readonly spawnFn: SpawnFunction; private readonly instanceSocketPath: (workspaceId: string, instanceId: string) => string; private readonly readRss: (pid: number) => Promise; @@ -233,14 +289,40 @@ export class ManagedInstanceManager implements InstanceManagerHandle { this.tokenPath = deps.tokenPath ?? daemonTokenPath(); this.runtime = deps.runtime ?? runtimeDir(); this.logDir = deps.logDir ?? join(stateDir(), "instances"); + this.hostInitDir = deps.hostInitDir ?? join(stateDir(), "host-init"); this.nvimBin = deps.nvimBin ?? process.env.PI2_NVIM_BIN ?? "nvim"; - const init = deps.nvimInit ?? process.env.PI2_NVIM_INIT; - this.nvimInit = init !== undefined && init !== "" ? init : undefined; + // Three-way init choice (see `resolveNvimInit`): an explicit path wins, + // the literal `user` opts back into today's "load my config" behaviour, + // and anything else (including unset) uses the generated host init. + const init = (deps.nvimInit ?? process.env.PI2_NVIM_INIT ?? "").trim(); + this.useUserConfig = init === "user"; + this.nvimInit = init === "" || this.useUserConfig ? undefined : init; + this.pluginDir = deps.pluginDir?.trim() || undefined; + this.writeHostInit = deps.writeHostInit ?? writeHostInit; + this.resolvePlugin = + deps.resolvePlugin ?? + (() => { + const env: Record = { ...process.env, ...(deps.env ?? {}) }; + if (this.pluginDir !== undefined) env.PI2_PLUGIN_DIR = this.pluginDir; + return resolvePluginDir({ env }); + }); + this.logTailLines = deps.logTailLines ?? DEFAULT_LOG_TAIL_LINES; + this.readLogTail = deps.readLogTail ?? defaultReadLogTail; this.spawnFn = deps.spawnFn ?? ((command, args, options) => spawn(command, args, options)); this.instanceSocketPath = deps.instanceSocketPath ?? defaultInstanceSocketPath; this.readRss = deps.readRss ?? defaultReadRss; this.totalMemory = deps.totalMemory ?? totalmem; - this.ensureTimeoutMs = deps.ensureTimeoutMs ?? DEFAULT_ENSURE_TIMEOUT_MS; + const envTimeout = parseEnsureTimeoutMs(process.env.PI2_ENSURE_TIMEOUT_MS); + if ( + deps.ensureTimeoutMs === undefined && + (process.env.PI2_ENSURE_TIMEOUT_MS ?? "").trim() !== "" && + envTimeout === undefined + ) { + this.logger?.warn("ignoring invalid PI2_ENSURE_TIMEOUT_MS", { + value: process.env.PI2_ENSURE_TIMEOUT_MS, + }); + } + this.ensureTimeoutMs = deps.ensureTimeoutMs ?? envTimeout ?? DEFAULT_ENSURE_TIMEOUT_MS; this.shutdownGraceMs = deps.shutdownGraceMs ?? DEFAULT_SHUTDOWN_GRACE_MS; this.sigtermGraceMs = deps.sigtermGraceMs ?? DEFAULT_SIGTERM_GRACE_MS; this.minSpawnIntervalMs = deps.minSpawnIntervalMs ?? DEFAULT_MIN_SPAWN_INTERVAL_MS; @@ -463,14 +545,15 @@ export class ManagedInstanceManager implements InstanceManagerHandle { }; this.setState(starting); - const waiter = this.createWaiter(workspaceId, timeoutMs); + const waiter = this.createWaiter(workspaceId, timeoutMs, starting); let child: ChildProcess | undefined; try { + const init = await this.resolveNvimInit(); const args = [ "--headless", "--listen", socketPath, - ...(this.nvimInit === undefined ? [] : ["-u", this.nvimInit]), + ...(init.path === undefined ? [] : ["-u", init.path]), "-c", 'lua require("pi.host").start()', ]; @@ -482,17 +565,53 @@ export class ManagedInstanceManager implements InstanceManagerHandle { PI2_DAEMON_TOKEN_PATH: this.tokenPath, PI2_WORKSPACE_ID: workspaceId, }; - this.logger?.info("spawning instance", { workspaceId, instanceId, cwd, command: this.nvimBin, logPath }); - child = this.spawnFn(this.nvimBin, args, { + // One line, no secrets: the four knobs that change how this spawn + // behaves plus the argv we are about to hand nvim, because "which + // -u did it pick" is the first question every report asks. + this.logger?.info("spawning instance", { + workspaceId, + instanceId, cwd, - env, - stdio: "ignore", - detached: true, + command: this.nvimBin, + args, + init: init.path ?? "none", + pluginDir: init.pluginDir ?? "none", + logPath, + env: { + PI2_NVIM_BIN: process.env.PI2_NVIM_BIN ?? "", + PI2_NVIM_INIT: process.env.PI2_NVIM_INIT ?? "", + PI2_PLUGIN_DIR: process.env.PI2_PLUGIN_DIR ?? "", + PI2_ENSURE_TIMEOUT_MS: String(this.ensureTimeoutMs), + }, }); - this.children.set(workspaceId, child); - if (child.pid !== undefined) this.setState({ ...starting, nvimPid: child.pid }); - child.unref(); - waiter.attach(child, logPath); + let logFd: number | undefined; + try { + ensureDir(this.logDir); + // nvim's stderr is the only place a config/plugin error will ever + // appear (`--headless` keeps it off the terminal), so route it into + // the per-instance log instead of /dev/null. + logFd = openSync(logPath, "a", 0o600); + child = this.spawnFn(this.nvimBin, args, { + cwd, + env, + stdio: ["ignore", logFd, logFd], + detached: true, + }); + this.children.set(workspaceId, child); + if (child.pid !== undefined) this.setState({ ...starting, nvimPid: child.pid }); + child.unref(); + } finally { + // The child holds its own duplicate; keeping ours open would leak an + // fd per spawn. `detached: true` already keeps the child alive. + if (logFd !== undefined) { + try { + closeSync(logFd); + } catch { + // already closed: the spawn-error path may have closed it + } + } + } + waiter.attach(child, logPath, init); const connection = await waiter.promise; this.failures.delete(workspaceId); @@ -501,17 +620,24 @@ export class ManagedInstanceManager implements InstanceManagerHandle { return this.readyState(connection, this.states.get(workspaceId)); } catch (error) { const failure = asInstanceError(error); + // A refusal before spawn (e.g. no plugin found) leaves a waiter behind + // that nobody will ever settle; drop it so `waiters` stays honest. + waiter.cancel(failure.message); this.recordFailure(workspaceId); if (child !== undefined) { tryKill(child, "SIGKILL"); if (this.children.get(workspaceId) === child) this.children.delete(workspaceId); } + // Timeout/early-exit errors carry the single-line log summary in + // `details.reason`; every other failure falls back to its message. + const reason = + typeof failure.details?.reason === "string" ? failure.details.reason : failure.message; this.setState({ ...(this.states.get(workspaceId) ?? starting), status: "stopped", nvimPid: null, attachedClients: 0, - reason: failure.message, + reason, }); this.logger?.warn("instance failed to start", { workspaceId, @@ -523,9 +649,34 @@ export class ManagedInstanceManager implements InstanceManagerHandle { } } - private createWaiter(workspaceId: string, timeoutMs: number): SpawnWaiter { + /** + * Which `-u` this spawn gets. + * + * The default is the generated host init: spawning the *user's* config is + * what made "open a project from the web console" fail silently, because the + * plugin is only reachable if that config happens to load it. `-u` values and + * `PI2_NVIM_INIT=user` remain as escape hatches. With no host-capable plugin + * at all we refuse up front — a spawn with no plugin can only time out. + */ + private async resolveNvimInit(): Promise { + if (this.nvimInit !== undefined) return { path: this.nvimInit, pluginDir: undefined }; + if (this.useUserConfig) return { path: undefined, pluginDir: undefined }; + + const resolution = this.resolvePlugin(); + if (resolution.plugin === undefined) { + throw InstanceError.unavailable( + `${describePluginFailure(resolution.candidates, { configured: resolution.configured })}; install/update pi2.nvim, ` + + "set PI2_PLUGIN_DIR, or set PI2_NVIM_INIT=user to load your own config", + ); + } + const path = await this.writeHostInit({ dir: this.hostInitDir, pluginDir: resolution.plugin.dir }); + return { path, pluginDir: resolution.plugin.dir }; + } + + private createWaiter(workspaceId: string, timeoutMs: number, base: InstanceState): SpawnWaiter { const manager = this; let settled = false; + let diagnosing = false; let resolvePromise!: (connection: PluginSocketConnection) => void; let rejectPromise!: (error: Error) => void; @@ -539,6 +690,10 @@ export class ManagedInstanceManager implements InstanceManagerHandle { let timer: NodeJS.Timeout | undefined; let exited = false; + // Set by `attach()`; the timer can fire before any child event, so the + // diagnostics path needs to know which init this waiter belongs to. + let attachedLogPath: string | undefined; + let attachedInit: SpawnInit | undefined; const cleanup = (): void => { if (timer !== undefined) { @@ -548,6 +703,44 @@ export class ManagedInstanceManager implements InstanceManagerHandle { if (this.waiters.get(workspaceId) === waiter) this.waiters.delete(workspaceId); }; + /** + * Fails the waiter *after* reading the log tail, so the browser and the + * log get the actual nvim output instead of a bare timeout. + */ + function failWithDiagnostics(options: { + marker: string; + summary: string; + logPath: string | undefined; + init: SpawnInit | undefined; + makeError: (diagnostics: SpawnDiagnostics) => InstanceError; + }): void { + if (settled || diagnosing) return; + diagnosing = true; + void manager + .describeSpawnFailure({ + logPath: options.logPath, + marker: options.marker, + summary: options.summary, + init: options.init, + }) + .then((diagnostics) => { + if (settled) return; + // `fail()` is not enough on its own: the reason must reach + // `InstanceState` so the browser sees it through `instance_state`. + manager.setState({ + ...(manager.states.get(workspaceId) ?? base), + status: "stopped", + nvimPid: null, + attachedClients: 0, + reason: diagnostics.reason, + }); + waiter.fail(options.makeError(diagnostics)); + }) + .finally(() => { + diagnosing = false; + }); + } + const waiter: SpawnWaiter = { promise, settle(connection) { @@ -562,18 +755,39 @@ export class ManagedInstanceManager implements InstanceManagerHandle { cleanup(); rejectPromise(error); }, - attach(child, logPath) { + attach(child, logPath, init) { + attachedLogPath = logPath; + attachedInit = init; child.once("exit", (code, signal) => { exited = true; if (manager.children.get(workspaceId) === child) manager.children.delete(workspaceId); if (settled) return; - const message = `nvim exited before hello (code ${String(code)}, signal ${String(signal)})`; - void manager.appendLog(logPath, message); - waiter.fail(InstanceError.unavailable(message, { workspaceId })); + const summary = `nvim exited before hello (code ${String(code)}, signal ${String(signal)})`; + failWithDiagnostics({ + marker: "exit before hello", + summary, + logPath, + init, + makeError: (diagnostics) => + InstanceError.unavailable(diagnostics.message, { + workspaceId, + reason: diagnostics.reason, + }), + }); }); child.once("error", (error) => { - void manager.appendLog(logPath, `spawn error: ${error.message}`); - waiter.fail(InstanceError.unavailable(`failed to spawn nvim: ${error.message}`, { workspaceId })); + if (settled) return; + failWithDiagnostics({ + marker: "spawn error", + summary: `failed to spawn nvim: ${error.message}`, + logPath, + init, + makeError: (diagnostics) => + InstanceError.unavailable(diagnostics.message, { + workspaceId, + reason: diagnostics.reason, + }), + }); }); }, cancel(reason) { @@ -585,10 +799,26 @@ export class ManagedInstanceManager implements InstanceManagerHandle { }; timer = setTimeout(() => { - const message = exited - ? `instance for ${workspaceId} exited before hello` - : `instance for ${workspaceId} did not say hello within ${timeoutMs}ms`; - waiter.fail(exited ? InstanceError.unavailable(message) : InstanceError.starting(message)); + if (settled) return; + if (exited) { + failWithDiagnostics({ + marker: "exit before hello", + summary: `instance for ${workspaceId} exited before hello`, + logPath: attachedLogPath, + init: attachedInit, + makeError: (diagnostics) => + InstanceError.unavailable(diagnostics.message, { reason: diagnostics.reason }), + }); + return; + } + failWithDiagnostics({ + marker: "hello timeout", + summary: `instance for ${workspaceId} did not say hello within ${timeoutMs}ms`, + logPath: attachedLogPath, + init: attachedInit, + makeError: (diagnostics) => + InstanceError.starting(diagnostics.message, { reason: diagnostics.reason }), + }); }, timeoutMs); timer.unref?.(); @@ -596,6 +826,49 @@ export class ManagedInstanceManager implements InstanceManagerHandle { return waiter; } + /** + * Turns "the spawn went quiet" into something a human can act on. + * + * Writes a marker into the instance log (so the file is self-describing), and + * returns both a one-line reason for `instance_state` and a summary + tail for + * the thrown error. + */ + private async describeSpawnFailure(options: { + logPath: string | undefined; + marker: string; + summary: string; + init: SpawnInit | undefined; + }): Promise { + const tail = options.logPath === undefined ? [] : await this.readLogTailLines(options.logPath); + if (options.logPath !== undefined) { + await this.appendLog( + options.logPath, + `${options.marker} (-u ${options.init?.path ?? "none"}, plugin ${options.init?.pluginDir ?? "none"})`, + ); + } + const nonEmpty = tail.filter((line) => line.trim() !== ""); + const lastLines = nonEmpty.slice(-3).join(" | "); + const reason = truncate(lastLines === "" ? options.summary : `${options.summary}: ${lastLines}`, 500); + const detail = tail.slice(-10).join("\n"); + return { + reason, + message: detail === "" ? options.summary : `${options.summary}\n${detail}`, + }; + } + + /** Reads the last `logTailLines` lines, capped per line so one long traceback cannot flood the error. */ + private async readLogTailLines(logPath: string): Promise { + let lines: string[]; + try { + lines = await this.readLogTail(logPath, this.logTailLines); + } catch { + return []; + } + return lines + .slice(-this.logTailLines) + .map((line) => (line.length > 400 ? `${line.slice(0, 400)}…` : line)); + } + private handleOpen(connection: PluginSocketConnection): void { if (this.closed) { connection.close("instance manager is closed"); @@ -731,6 +1004,25 @@ export class ManagedInstanceManager implements InstanceManagerHandle { } } +/** Caps a single-line diagnostic so it stays readable in a state payload. */ +function truncate(value: string, max: number): string { + return value.length <= max ? value : `${value.slice(0, max - 1)}…`; +} + +/** + * Last `lines` lines of a log file. + * + * Instance logs only hold a spawned nvim's stderr, so they stay small and a full + * read is cheaper (and safer) than a seek-from-the-end dance; a missing file is + * simply "no output yet". + */ +async function defaultReadLogTail(path: string, lines: number): Promise { + const text = await readFile(path, "utf8"); + const all = text.split("\n"); + if (all.at(-1) === "") all.pop(); + return all.slice(-Math.max(1, lines)); +} + function sameState(a: InstanceState, b: InstanceState): boolean { return ( a.instanceId === b.instanceId && diff --git a/test/core/plugin.test.ts b/test/core/plugin.test.ts new file mode 100644 index 0000000..0a662e5 --- /dev/null +++ b/test/core/plugin.test.ts @@ -0,0 +1,222 @@ +/** + * Plugin discovery (`src/core/plugin.ts`). + * + * Everything is injected (`env`, `home`, `exists`, `readdir`) so the tests never + * look at the machine's real nvim install: a developer with pi2.nvim checked out + * would otherwise get different results from CI. + */ + +import type { Dirent } from "node:fs"; +import { homedir } from "node:os"; +import { describe, expect, it } from "vitest"; +import { + PLUGIN_NAME, + classifyPluginDir, + describePluginFailure, + displayPath, + pluginDirCandidates, + resolvePluginDir, +} from "../../src/core/plugin.js"; + +const HOME = "/home/tester"; +const HOST = "lua/pi/host.lua"; +const BRIDGE = "lua/pi/web/bridge.lua"; + +/** Fake `exists` over an explicit set of paths. */ +function fakeExists(paths: readonly string[]): (path: string) => boolean { + const set = new Set(paths); + return (path) => set.has(path); +} + +/** Minimal `Dirent` lookalike; `readdir` is only asked for directory names. */ +function dir(name: string): Dirent { + return { name, isDirectory: () => true } as Dirent; +} + +/** A `readdir` that only knows one directory (any other root is "missing"). */ +function fakeReaddir(entries: Record): (path: string, o: { withFileTypes: true }) => Dirent[] { + return (path) => { + const found = entries[path]; + if (found === undefined) throw new Error(`ENOENT: ${path}`); + return found; + }; +} + +const PACK = `${HOME}/.local/share/nvim/site/pack`; + +describe("resolvePluginDir", () => { + it("uses PI2_PLUGIN_DIR first and expands a leading ~/", () => { + const configured = "/home/tester/work/pi2.nvim"; + const resolution = resolvePluginDir({ + env: { PI2_PLUGIN_DIR: " ~/work/pi2.nvim " }, + home: HOME, + exists: fakeExists([configured, `${configured}/${HOST}`, `${configured}/${BRIDGE}`]), + readdir: fakeReaddir({}), + }); + + expect(resolution).toEqual({ + plugin: { + dir: configured, + host: `${configured}/${HOST}`, + bridge: `${configured}/${BRIDGE}`, + }, + }); + }); + + it("skips a lazy checkout without lua/pi/host.lua in favour of a pack dir", () => { + const lazy = `${HOME}/.local/share/nvim/lazy/${PLUGIN_NAME}`; + const packed = `${PACK}/plugins/start/${PLUGIN_NAME}`; + const resolution = resolvePluginDir({ + env: {}, + home: HOME, + exists: fakeExists([ + lazy, + // lazy.nvim installed the plugin but this checkout predates host.lua + `${lazy}/${BRIDGE}`, + packed, + `${packed}/${HOST}`, + `${packed}/${BRIDGE}`, + ]), + readdir: fakeReaddir({ [PACK]: [dir("plugins")] }), + }); + + expect(resolution.plugin?.dir).toBe(packed); + }); + + it("reports every candidate when nothing is host-capable", () => { + const lazy = `${HOME}/.local/share/nvim/lazy/${PLUGIN_NAME}`; + const resolution = resolvePluginDir({ + env: {}, + home: HOME, + exists: fakeExists([lazy, `${lazy}/${HOST}`]), + readdir: fakeReaddir({ [PACK]: [dir("a"), dir("b")] }), + }); + + expect(resolution.plugin).toBeUndefined(); + expect(resolution.candidates?.map((candidate) => candidate.reason)).toEqual([ + "missing-bridge", + "absent", + "absent", + "absent", + "absent", + ]); + expect(resolution.candidates?.[0]?.dir).toBe(lazy); + }); + + it("never throws when site/pack is missing and ends in a readable failure", () => { + const resolution = resolvePluginDir({ + env: {}, + home: HOME, + exists: () => false, + readdir: () => { + throw new Error("ENOENT"); + }, + }); + + expect(resolution.plugin).toBeUndefined(); + expect(describePluginFailure(resolution.candidates ?? [])).toContain(`no ${PLUGIN_NAME} plugin found`); + }); +}); + +describe("pluginDirCandidates", () => { + it("orders env dir, lazy.nvim, pack/start, pack/opt, then the system dirs", () => { + const dirs = pluginDirCandidates({ + env: { PI2_PLUGIN_DIR: "/opt/pi2.nvim" }, + home: HOME, + readdir: fakeReaddir({ + [PACK]: [dir("mine")], + "/usr/share/nvim/site/pack": [dir("distro")], + }), + }); + + expect(dirs).toEqual([ + "/opt/pi2.nvim", + `${HOME}/.local/share/nvim/lazy/${PLUGIN_NAME}`, + `${PACK}/mine/start/${PLUGIN_NAME}`, + `${PACK}/mine/opt/${PLUGIN_NAME}`, + `/usr/share/nvim/site/pack/distro/start/${PLUGIN_NAME}`, + `/usr/share/nvim/site/pack/distro/opt/${PLUGIN_NAME}`, + ]); + }); + + it("ignores a blank PI2_PLUGIN_DIR and dedupes overlapping candidates", () => { + const lazy = `${HOME}/.local/share/nvim/lazy/${PLUGIN_NAME}`; + const dirs = pluginDirCandidates({ + env: { PI2_PLUGIN_DIR: " ", HOME }, + home: HOME, + readdir: fakeReaddir({}), + }); + expect(dirs[0]).toBe(lazy); + + const duplicated = pluginDirCandidates({ + env: { PI2_PLUGIN_DIR: lazy }, + home: HOME, + readdir: fakeReaddir({}), + }); + expect(duplicated.filter((dir) => dir === lazy)).toHaveLength(1); + }); +}); + +describe("classifyPluginDir", () => { + it("requires both entry points", () => { + expect(classifyPluginDir("/p", fakeExists(["/p"]))).toEqual({ dir: "/p", reason: "missing-host" }); + expect(classifyPluginDir("/p", fakeExists(["/p", `/p/${HOST}`]))).toEqual({ + dir: "/p", + reason: "missing-bridge", + }); + expect(classifyPluginDir("/p", fakeExists(["/p", `/p/${HOST}`, `/p/${BRIDGE}`]))).toEqual({ + dir: "/p", + reason: "ok", + }); + expect(classifyPluginDir("/p", () => false)).toEqual({ dir: "/p", reason: "absent" }); + }); +}); + +describe("describePluginFailure", () => { + it("names the first existing but incomplete checkout (tilde-collapsed)", () => { + const lazy = `${homedir()}/.local/share/nvim/lazy/${PLUGIN_NAME}`; + const line = describePluginFailure([ + { dir: `${homedir()}/.local/share/nvim/site/pack/x/start/${PLUGIN_NAME}`, reason: "absent" }, + { dir: lazy, reason: "missing-host" }, + ]); + + expect(line).toBe(`${PLUGIN_NAME} at ~/.local/share/nvim/lazy/${PLUGIN_NAME} has no ${HOST} (update the plugin)`); + expect(displayPath(lazy)).toContain("~/"); + }); + + it("reports a missing bridge instead of the host file", () => { + const line = describePluginFailure([{ dir: "/tmp/pi2.nvim", reason: "missing-bridge" }]); + expect(line).toContain(`has no ${BRIDGE}`); + }); + + it("falls back to a not-found line naming the first location", () => { + const line = describePluginFailure([ + { dir: "/tmp/a/pi2.nvim", reason: "absent" }, + { dir: "/tmp/b/pi2.nvim", reason: "absent" }, + ]); + expect(line).toBe(`no ${PLUGIN_NAME} plugin found (looked in 2 location(s), first /tmp/a/pi2.nvim)`); + expect(describePluginFailure([])).toContain("no locations"); + }); + + // A typo in `PI2_PLUGIN_DIR` used to be blamed on a stale lazy.nvim checkout, + // which sends the user to the wrong directory (found by the acceptance run). + it("names an explicitly configured directory that does not exist", () => { + const line = describePluginFailure( + [ + { dir: "/opt/typo/pi2.nvim", reason: "absent" }, + { dir: "/home/x/.local/share/nvim/lazy/pi2.nvim", reason: "missing-host" }, + ], + { configured: "/opt/typo/pi2.nvim" }, + ); + + expect(line).toBe("PI2_PLUGIN_DIR=/opt/typo/pi2.nvim does not exist"); + }); + + it("names a configured directory that is not host-capable", () => { + const line = describePluginFailure([{ dir: "/opt/pi2.nvim", reason: "missing-host" }], { + configured: "/opt/pi2.nvim", + }); + + expect(line).toBe(`PI2_PLUGIN_DIR=/opt/pi2.nvim has no ${HOST} (update the plugin)`); + }); +}); diff --git a/test/instances/helpers.ts b/test/instances/helpers.ts index 6e57343..13bfbba 100644 --- a/test/instances/helpers.ts +++ b/test/instances/helpers.ts @@ -31,7 +31,15 @@ export interface TempEnv { cleanup(): void; } -const ENV_KEYS = ["PI2_RUNTIME_DIR", "PI2_DATA_DIR", "PI2_STATE_DIR", "PI2_NVIM_BIN", "PI2_NVIM_INIT"] as const; +const ENV_KEYS = [ + "PI2_RUNTIME_DIR", + "PI2_DATA_DIR", + "PI2_STATE_DIR", + "PI2_NVIM_BIN", + "PI2_NVIM_INIT", + "PI2_PLUGIN_DIR", + "PI2_ENSURE_TIMEOUT_MS", +] as const; export function makeTempEnv(prefix = "pi2-daemon-instances-"): TempEnv { const dir = mkdtempSync(join(tmpdir(), prefix)); @@ -42,6 +50,11 @@ export function makeTempEnv(prefix = "pi2-daemon-instances-"): TempEnv { const saved = new Map(); for (const key of ENV_KEYS) saved.set(key, process.env[key]); + // The developer's own spawn knobs must not decide which init a test spawns + // with: clear them so the default (generated host init) is what runs. + for (const key of ["PI2_NVIM_BIN", "PI2_NVIM_INIT", "PI2_PLUGIN_DIR", "PI2_ENSURE_TIMEOUT_MS"] as const) { + delete process.env[key]; + } process.env.PI2_RUNTIME_DIR = runtime; process.env.PI2_DATA_DIR = data; process.env.PI2_STATE_DIR = state; diff --git a/test/instances/host-init.test.ts b/test/instances/host-init.test.ts new file mode 100644 index 0000000..4603124 --- /dev/null +++ b/test/instances/host-init.test.ts @@ -0,0 +1,109 @@ +/** + * Generated host init (`src/instances/host-init.ts`). + * + * `node:fs/promises.writeFile` is spied on so "memoized / compared before write" + * is asserted by counting real writes instead of racing file mtimes. + */ + +import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const writes = vi.hoisted(() => ({ paths: [] as string[] })); + +vi.mock("node:fs/promises", async (importOriginal) => { + const actual = await importOriginal(); + const writeFile = actual.writeFile as unknown as (...args: unknown[]) => Promise; + return { + ...actual, + writeFile: (...args: unknown[]): Promise => { + writes.paths.push(String(args[0])); + return writeFile(...args); + }, + }; +}); + +const { HOST_INIT_FILENAME, renderHostInit, resetHostInitCache, writeHostInit } = await import( + "../../src/instances/host-init.js" +); + +const PLUGIN = "/home/tester/.local/share/nvim/lazy/pi2.nvim"; + +describe("renderHostInit", () => { + it("prepends the plugin and starts the host without loading the user config", () => { + const lua = renderHostInit(PLUGIN); + + expect(lua).toContain(`vim.opt.runtimepath:prepend("${PLUGIN}")`); + expect(lua).toContain("vim.opt.swapfile = false"); + expect(lua).toContain('vim.opt.shadafile = "NONE"'); + expect(lua).toContain('vim.g.mapleader = " "'); + expect(lua).toContain('local ok, host = pcall(require, "pi.host")'); + expect(lua).toContain('vim.api.nvim_err_writeln("pi2: " .. tostring(host))'); + expect(lua).toContain('vim.cmd("cquit 1")'); + expect(lua).toContain("host.start()"); + // Header names the daemon and the plugin it points at, so a stray file in + // the state dir explains itself. + expect(lua).toContain("pi2d"); + expect(lua).toContain(`-- plugin: ${PLUGIN}`); + // No wait loop of our own: host.start() owns the handshake. + expect(lua).not.toContain("vim.wait"); + // A failing `require` must exit, not fall through to host.start(). + expect(lua.indexOf("cquit 1")).toBeLessThan(lua.indexOf("host.start()")); + }); + + it("escapes the plugin dir as a Lua string (no shell quoting)", () => { + const lua = renderHostInit('/tmp/we"ird\\dir'); + expect(lua).toContain('vim.opt.runtimepath:prepend("/tmp/we\\"ird\\\\dir")'); + expect(lua).not.toContain("'"); + }); +}); + +describe("writeHostInit", () => { + let dir: string; + + beforeEach(() => { + dir = resolve(mkdtempSync(join(tmpdir(), "pi2-host-init-"))); + writes.paths.length = 0; + resetHostInitCache(); + }); + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + it("writes host-init.lua (mode 0600) and returns the absolute path", async () => { + const path = await writeHostInit({ dir, pluginDir: PLUGIN }); + + expect(path).toBe(join(dir, HOST_INIT_FILENAME)); + expect(readFileSync(path, "utf8")).toBe(renderHostInit(PLUGIN)); + expect(statSync(path).mode & 0o777).toBe(0o600); + expect(writes.paths).toHaveLength(1); + }); + + it("does not rewrite on the second call for the same (dir, pluginDir)", async () => { + const first = await writeHostInit({ dir, pluginDir: PLUGIN }); + const second = await writeHostInit({ dir, pluginDir: PLUGIN }); + + expect(second).toBe(first); + expect(writes.paths).toHaveLength(1); + }); + + it("rewrites when the plugin dir changes", async () => { + await writeHostInit({ dir, pluginDir: PLUGIN }); + const other = "/tmp/other/pi2.nvim"; + const path = await writeHostInit({ dir, pluginDir: other }); + + expect(readFileSync(path, "utf8")).toContain(`vim.opt.runtimepath:prepend("${other}")`); + expect(writes.paths).toHaveLength(2); + }); + + it("skips the write when the file already matches", async () => { + const path = join(dir, HOST_INIT_FILENAME); + writeFileSync(path, renderHostInit(PLUGIN)); + resetHostInitCache(); + + await expect(writeHostInit({ dir, pluginDir: PLUGIN })).resolves.toBe(path); + expect(writes.paths).toHaveLength(0); + }); +}); diff --git a/test/instances/supervisor.test.ts b/test/instances/supervisor.test.ts index 93e9e97..b7b37f7 100644 --- a/test/instances/supervisor.test.ts +++ b/test/instances/supervisor.test.ts @@ -1,9 +1,10 @@ -import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } 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, + parseEnsureTimeoutMs, parseProcRss, parsePsRss, summarizeResources, @@ -49,12 +50,18 @@ describe("InstanceManager", () => { let env: TempEnv; let bus: FakeBus; let manager: InstanceManagerHandle | undefined; + /** Host-capable fake plugin checkout discovered by every spawn by default. */ + let pluginRoot: string; const workspaces = new Map(); beforeEach(() => { env = makeTempEnv(); bus = new FakeBus(); workspaces.clear(); + pluginRoot = join(env.dir, "pi2.nvim"); + mkdirSync(join(pluginRoot, "lua", "pi", "web"), { recursive: true }); + writeFileSync(join(pluginRoot, "lua", "pi", "host.lua"), "-- fake host\n"); + writeFileSync(join(pluginRoot, "lua", "pi", "web", "bridge.lua"), "-- fake bridge\n"); }); afterEach(async () => { @@ -70,18 +77,33 @@ describe("InstanceManager", () => { return cwd; } - async function create(options: { - bin?: string; - deps?: Partial; - } = {}): Promise { + async function create( + options: { + bin?: string; + /** `null` leaves the timeout to `PI2_ENSURE_TIMEOUT_MS`/the default. */ + ensureTimeoutMs?: number | null; + deps?: Partial; + } = {}, + ): Promise { + const ensureTimeoutMs = options.ensureTimeoutMs === undefined ? 4_000 : options.ensureTimeoutMs; const instance = await createInstanceManager({ bus, resolveCwd: (workspaceId) => workspaces.get(workspaceId), - ensureTimeoutMs: 4_000, + ...(ensureTimeoutMs === null ? {} : { ensureTimeoutMs }), shutdownGraceMs: 300, sigtermGraceMs: 200, minSpawnIntervalMs: 300, maxSpawnIntervalMs: 1_000, + // Hermetic plugin discovery: the machine's own nvim install must never + // decide what these tests spawn with. + resolvePlugin: () => ({ + plugin: { + dir: pluginRoot, + host: join(pluginRoot, "lua", "pi", "host.lua"), + bridge: join(pluginRoot, "lua", "pi", "web", "bridge.lua"), + }, + }), + hostInitDir: join(env.dir, "host-init"), ...(options.bin === undefined ? {} : { nvimBin: options.bin }), ...(options.deps ?? {}), }); @@ -112,7 +134,16 @@ describe("InstanceManager", () => { 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()']); + // No plugin/config default any more: the daemon hands nvim its generated init. + expect(argv.slice(3)).toEqual([ + "-u", + join(env.dir, "host-init", "host-init.lua"), + "-c", + 'lua require("pi.host").start()', + ]); + expect(readFileSync(join(env.dir, "host-init", "host-init.lua"), "utf8")).toContain( + `vim.opt.runtimepath:prepend("${pluginRoot}")`, + ); expect(start.cwd).toBe(cwd); const spawnedEnv = start.env as Record; expect(spawnedEnv.PI2_WORKSPACE_ID).toBe("ws-1"); @@ -128,19 +159,32 @@ describe("InstanceManager", () => { expect(statuses).toContain("ready"); }); - it("passes PI2_NVIM_INIT as -u only when configured", async () => { + it("honours an explicit init path from PI2_NVIM_INIT", async () => { addWorkspace(); - const init = join(env.dir, "init.lua"); + process.env.PI2_NVIM_INIT = "/x/y.lua"; const fake = writeFakeNvim(env.dir); - const mgr = await create({ bin: fake.bin, deps: { nvimInit: init } }); + const mgr = await create({ bin: fake.bin }); 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(3, 5)).toEqual(["-u", "/x/y.lua"]); expect(argv.slice(5)).toEqual(["-c", 'lua require("pi.host").start()']); }); + it("spawns the user's own config (no -u) for PI2_NVIM_INIT=user", async () => { + addWorkspace(); + process.env.PI2_NVIM_INIT = "user"; + const fake = writeFakeNvim(env.dir); + const mgr = await create({ bin: fake.bin }); + + await mgr.ensure("ws-1"); + + const argv = startRecords(fake.runLog)[0]?.argv as string[]; + expect(argv.slice(3)).toEqual(["-c", 'lua require("pi.host").start()']); + expect(argv).not.toContain("-u"); + }); + it("is idempotent and reports state changes to handlers", async () => { addWorkspace(); const fake = writeFakeNvim(env.dir); @@ -207,6 +251,103 @@ describe("InstanceManager", () => { }); }); + it("refuses to spawn when no host-capable plugin is found", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir); + const lazy = join(env.dir, "lazy", "pi2.nvim"); + const mgr = await create({ + bin: fake.bin, + deps: { + resolvePlugin: () => ({ + plugin: undefined, + configured: undefined, + candidates: [ + { dir: lazy, reason: "missing-host" }, + { dir: join(env.dir, "pack", "pi2.nvim"), reason: "absent" }, + ], + }), + }, + }); + + const error = await mgr.ensure("ws-1").catch((rejection: unknown) => rejection); + expect(error).toBeInstanceOf(Error); + const failure = error as Error & { code?: string }; + expect(failure.code).toBe("E_INSTANCE_UNAVAILABLE"); + expect(failure.message).toContain("has no lua/pi/host.lua"); + expect(failure.message).toContain("set PI2_PLUGIN_DIR"); + expect(failure.message).toContain("PI2_NVIM_INIT=user"); + // Refusing beats spawning an nvim that can only time out. + expect(startRecords(fake.runLog)).toHaveLength(0); + + const stopped = mgr.list().find((state) => state.workspaceId === "ws-1"); + expect(stopped?.status).toBe("stopped"); + expect(stopped?.reason).toContain("has no lua/pi/host.lua"); + expect(stopped?.reason).toContain("PI2_NVIM_INIT=user"); + + // The refusal is booked like any other failed start: backoff, no stuck entry. + await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ + code: "E_INSTANCE_UNAVAILABLE", + message: expect.stringContaining("backing off"), + }); + expect(startRecords(fake.runLog)).toHaveLength(0); + }); + + it("reports the log tail on hello timeout and puts a one-line reason on the state", async () => { + addWorkspace(); + const fake = writeFakeNvim(env.dir, { mode: "no-hello" }); + const tail = [ + "Error detected while processing host-init.lua:", + 'E5108: Error executing lua: module \'pi.host\' not found', + "", + "stack traceback:", + " [C]: in function 'require'", + ]; + const mgr = await create({ + bin: fake.bin, + deps: { readLogTail: async () => [...tail] }, + }); + + const error = await mgr + .ensure("ws-1", { timeoutMs: 800 }) + .catch((rejection: unknown) => rejection); + expect(error).toBeInstanceOf(Error); + const failure = error as Error & { code?: string }; + expect(failure.code).toBe("E_INSTANCE_STARTING"); + expect(failure.message).toContain("did not say hello within 800ms"); + expect(failure.message).toContain("module 'pi.host' not found"); + expect(failure.message).toContain("stack traceback:"); + + const stopped = mgr.list().find((state) => state.workspaceId === "ws-1"); + expect(stopped?.status).toBe("stopped"); + expect(stopped?.reason).toContain("did not say hello within 800ms"); + expect(stopped?.reason).toContain("stack traceback:"); + // The reason travels to the browser: it must stay a single line. + expect(stopped?.reason).not.toContain("\n"); + + const logDir = join(stateDir(), "instances"); + const logged = readdirSync(logDir) + .map((file) => readFileSync(join(logDir, file), "utf8")) + .join("\n"); + expect(logged).toContain("hello timeout (-u "); + expect(logged).toContain(pluginRoot); + }); + + it("honours PI2_ENSURE_TIMEOUT_MS when no timeout is passed", async () => { + addWorkspace(); + process.env.PI2_ENSURE_TIMEOUT_MS = "700"; + const fake = writeFakeNvim(env.dir, { mode: "no-hello" }); + const mgr = await create({ bin: fake.bin, ensureTimeoutMs: null }); + + const started = Date.now(); + await expect(mgr.ensure("ws-1")).rejects.toMatchObject({ + code: "E_INSTANCE_STARTING", + message: expect.stringContaining("did not say hello within 700ms"), + }); + const elapsed = Date.now() - started; + expect(elapsed).toBeGreaterThanOrEqual(600); + expect(elapsed).toBeLessThan(3_000); + }); + 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") } }); @@ -467,6 +608,18 @@ describe("InstanceManager", () => { }); }); +describe("ensure timeout override", () => { + it("parses PI2_ENSURE_TIMEOUT_MS and ignores junk", () => { + expect(parseEnsureTimeoutMs(undefined)).toBeUndefined(); + expect(parseEnsureTimeoutMs(" ")).toBeUndefined(); + expect(parseEnsureTimeoutMs("1500")).toBe(1500); + expect(parseEnsureTimeoutMs("0")).toBeUndefined(); + expect(parseEnsureTimeoutMs("-20")).toBeUndefined(); + expect(parseEnsureTimeoutMs("1.5")).toBeUndefined(); + expect(parseEnsureTimeoutMs("abc")).toBeUndefined(); + }); +}); + describe("resources helpers", () => { it("parses /proc//status VmRSS", () => { expect(parseProcRss("Name:\tnvim\nVmRSS:\t 102400 kB\nVmSize:\t 204800 kB\n")).toBe(102400 * 1024);