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/<id>.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`.
This commit is contained in:
yuez committed 2026-10-28 17:32:16 +08:00
1 parent c933eb39ad
commit db387ae248
9 files changed
+1162 -40

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
/**
* The generated nvim init the daemon hands to every headless instance.
*
* Why this exists: a spawned `nvim --headless -u <user config>` 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<string, string>();
/** 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 `<dir>/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<string> {
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();
}