diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..9a8802e --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,339 @@ +# Deployment and operations + +`pi2d` is the pi2 web-console daemon. It owns the HTTP/WS surface, the +workspace registry, the instance supervisor (one managed nvim per workspace) +and the device/CLI auth. This document covers running it, its runtime files, +the `pi2` CLI and the day-to-day ops commands. + +``` +browser ──HTTP + WS/SSE──▶ pi2d ──JSONL over unix socket──▶ plugin (nvim) + ▲ + pi2 CLI │ (HTTP, local admin token) +``` + +Contents + +1. [Requirements](#1-requirements) +2. [Build](#2-build) +3. [Running the daemon](#3-running-the-daemon) +4. [Configuration](#4-configuration) +5. [Runtime files](#5-runtime-files) +6. [Ports and the singleton lock](#6-ports-and-the-singleton-lock) +7. [Authentication](#7-authentication) +8. [The `pi2` CLI](#8-the-pi2-cli) +9. [Services (systemd / launchd)](#9-services-systemd--launchd) +10. [Logs and health](#10-logs-and-health) +11. [Restart and shutdown semantics](#11-restart-and-shutdown-semantics) +12. [Smoke test](#12-smoke-test) +13. [Troubleshooting](#13-troubleshooting) + +--- + +## 1. Requirements + +| Component | Requirement | Needed for | +|---|---|---| +| Node | **>= 22** (`engines` field) | daemon + CLI | +| Neovim | **>= 0.9** | managed instances; `nvim --remote-ui` for `pi2 attach` | +| pi CLI | any recent version | agent sessions inside nvim | +| pi2.nvim | `lua/pi/web/bridge.lua` present | the plugin that dials the daemon | + +`pi2 doctor` checks all of the above (see [§8.3](#83-pi2-doctor)). + +## 2. Build + +```bash +pnpm install +pnpm build # tsc -> dist/ (dist/cli/pi2d.js, dist/cli/pi2.js) +pnpm --dir web build # optional: web/dist for the browser console +``` + +`pi2d` serves the browser console from `/web/dist` (or `PI2_STATIC_DIR`). +Without it `/` returns 404/SPA fallback behaviour and `/api/v1/health` reports +`static=FAIL`; the API and `pi2` keep working. + +Binaries: `dist/cli/pi2d.js` (daemon, `pi2d`) and `dist/cli/pi2.js` (client, +`pi2`). Both are ESM and start with a `#!` line. + +## 3. Running the daemon + +```bash +node dist/cli/pi2d.js --foreground # or: pnpm dev (tsx watch) +``` + +Exactly one line goes to **stdout**: + +``` +pi2d listening on http://127.0.0.1:7676 +``` + +Every log record is JSONL on **stderr** (that is what systemd/launchd capture). + +Flags: + +| Flag | Meaning | +|---|---| +| `--port ` | TCP port; `0` = ephemeral (the real port lands in `daemon.json`) | +| `--host ` | bind address (default `127.0.0.1`) | +| `--static-dir

` | built web UI directory | +| `--force` | take the lock even if another `pi2d` holds it | +| `--foreground` | stay attached to the terminal (default; used by unit files) | +| `--version`, `--help` | print and exit | + +Flags are applied to the environment before the config is loaded, so +`--port 8000` is equivalent to `PI2_PORT=8000`. + +Daemon startup order: mint `cli.token` → take `daemon.lock` → start the plugin +unix socket → listen (with port retry) → write `daemon.json` → print the line. + +## 4. Configuration + +Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`): + +| Variable | Default | Meaning | +|---|---|---| +| `PI2_PORT` | `7676` | HTTP/WS port, `0` = ephemeral | +| `PI2_HOST` | `127.0.0.1` | bind address | +| `PI2_STATIC_DIR` | `/web/dist` | built web UI | +| `PI2_ORIGINS` | `http://127.0.0.1:,http://localhost:` | CORS/Origin allowlist (comma separated) | +| `PI2_RUNTIME_DIR` | Linux `$XDG_RUNTIME_DIR/pi2`, macOS `~/Library/Caches/pi2/run` | sockets, lock, tokens | +| `PI2_DATA_DIR` | Linux `$XDG_DATA_HOME/pi2`, macOS `~/Library/Application Support/pi2` | `devices.json`, `workspaces.json` | +| `PI2_STATE_DIR` | Linux `$XDG_STATE_HOME/pi2`, macOS `~/Library/Logs/pi2` | instance logs | +| `PI2_LOG_LEVEL` | `info` | `debug`/`info`/`warn`/`error`/`silent` | +| `PI2_WORKSPACE_ROOTS` | `$HOME` | allowlist for `workspace.add` | +| `PI2_PLUGIN_DIR` | `~/.local/share/nvim/lazy/pi2.nvim` | plugin location for `pi2 doctor` | +| `PI2_NVIM_BIN` | `nvim` | binary used for managed instances | +| `PI2_NVIM_INIT` | – | extra `-u ` for managed instances | +| `PI2_CODING_AGENT_DIR` | `~/.pi/agent` | pi session storage (discovery) | + +There is no config file: the environment *is* the configuration. + +## 5. Runtime files + +All of these live in `PI2_RUNTIME_DIR` (created `0700`): + +| File | Mode | Purpose | +|---|---|---| +| `d.sock` | `0600` | plugin ↔ daemon JSONL socket (nvim dials it) | +| `d.sock.token` | `0600` | handshake token for `hello`; rotated per daemon start | +| `daemon.lock` | `0600` | singleton lock: `{pid, bootId, port, daemonId, startedAt, protocolVersion}` | +| `daemon.json` | `0600` | same payload, written **after** `listen()` so tools learn the real port | +| `cli.token` | `0600` | 32-byte hex local admin token, rotated per daemon start | + +Plus `i/` (per-instance nvim `--listen` sockets) and, under `PI2_STATE_DIR`, +`instances/.log` for spawned nvim output. + +`daemon.lock` and `daemon.json` are removed on a clean shutdown; a stale pair +from a crash is detected as stale (dead pid **or** different boot id) and +overwritten on the next start. + +## 6. Ports and the singleton lock + +- One daemon per runtime dir. A second `pi2d` exits `1` with + `pi2d: another pi2d is running (pid …, port …); use --force to override`. +- `--force` takes over the lock; the displaced daemon keeps serving until it + exits, and it will *not* delete the new lock on shutdown (ownership is + checked by pid + `daemonId`). +- **Default-port retry:** when the port comes from the default (`7676`, no + `--port`, no `PI2_PORT`), `EADDRINUSE` walks `+1 … +9` (`7677`–`7685`) and + logs a warning per attempt. An explicitly configured port never moves — + a conflict there is an error. +- Derived CORS origins follow the effective port, so a bumped port still works + from the browser. + +## 7. Authentication + +Two token kinds: + +1. **Device tokens** (paired phones/laptops): created by `POST /api/v1/pair` + (redeem) or `pair.create`; only SHA-256 hashes are stored in + `PI2_DATA_DIR/devices.json`. +2. **Local CLI token**: `PI2_RUNTIME_DIR/cli.token`, minted by `pi2d` on each + start. Any request carrying it authenticates as the synthetic device + `{id:"local-cli", name:"local CLI", scopes:["read","steer","control","admin"]}` + (constant-time compare, never persisted, not revocable, not listed by + `GET /api/v1/devices`). Rotating the file invalidates the old value + immediately. + +`GET /api/v1/info` and `GET /api/v1/health` are readable from loopback without +a token; everything else under `/api/*` needs `Authorization: Bearer …`. +Unknown `/api/*` paths answer `401` when unauthenticated and `404` when +authenticated (auth runs before routing). + +## 8. The `pi2` CLI + +`pi2` discovers the daemon from `daemon.json` (port) and `cli.token` (auth) in +`PI2_RUNTIME_DIR`, so it needs no flags. Every command exits non-zero with a +one-line `pi2: …` message on failure. + +### 8.1 `pi2 attach [path]` + +```bash +pi2 attach # current directory +pi2 attach ../other +``` + +Resolves the path (`realpath`), lists workspaces, and looks for the one whose +`cwd` matches: + +- **instance with a listen address** (`ready`/`degraded`): with a TTY, + `exec nvim --server --remote-ui`; without a TTY it prints the + command and exits `0`. +- **no instance** (or no daemon at all): `exec nvim` in that directory — the + plugin registers itself, the daemon does not spawn a headless nvim. + +`attach` never spawns a managed (headless) instance; that only happens through +`instance.ensure` (browser/API). + +### 8.2 `pi2 status [--json]` + +Shows daemon identity (URL, `daemonId`, protocol `v`, platform), a table of +instances (`workspace`, `cwd`, `status`, `ui`, `sessions`, `pid`), the resource +summary (RSS total vs physical memory and the soft-limit warning) and the +health items. Exits `1` when `/api/v1/health` is not ok. `--json` prints one +object `{daemon, instances, resources, health}`. + +### 8.3 `pi2 doctor [--json]` + +| Check | Fails when | Warns when | +|---|---|---| +| `node` | < 22 | – | +| `nvim` | missing, or < 0.9 | version unparsable | +| `pi` | – | not on `PATH` | +| `plugin` | `lua/pi/web/bridge.lua` not found | – | +| `runtime-dir` | missing | mode not `0700` | +| `cli-token` | mode not `0600` | missing (daemon not started yet) | +| `socket` | `d.sock` missing (and no daemon) | missing but daemon answers | +| `daemon` | `/api/v1/info` unreachable | – | +| `port` | – (reports bound/free) | – | +| `service-manager` | – | systemd/launchd not found | +| `linger` (Linux) | – | `Linger=no` | +| `web-dist` | – | missing | +| `protocol` | daemon `v` ≠ CLI `v` | – | + +`--json` emits `{ok, checks:[{name,status,detail}]}` (`status` ∈ `ok|warn|fail`); +only `fail` makes `ok:false`/exit `1`. All probes are injectable, so the checks +are unit tested without touching the host. + +### 8.4 `pi2 pairing` + +`POST /api/v1/pair` with the local token and prints: + +``` +url http://127.0.0.1:7676/pair/ABCD2345 +code ABCD2345 +expires 2026-10-21T04:30:15.085Z (600s) +qr {"v":1,"code":"ABCD2345","url":"…","expiresAt":…,"nonce":"…"} +``` + +The URL is rebuilt from the *actual* daemon base URL because the daemon's own +`url` field is derived from the configured port (stale after a retry or +`--port 0`). + +### 8.5 `pi2 install-service` / `pi2 uninstall-service` + +See [§9](#9-services-systemd--launchd). `--dry-run` (default) prints the file +and the follow-up commands; `--write` writes the file (`0644`) and prints the +commands. The CLI never executes `systemctl`/`launchctl`. + +## 9. Services (systemd / launchd) + +```bash +pi2 install-service --dry-run # inspect, nothing written +pi2 install-service --write # ~/.config/systemd/user/pi2d.service +systemctl --user daemon-reload +systemctl --user enable --now pi2d.service +``` + +The unit is rendered with absolute paths: + +```ini +[Unit] +Description=pi2 daemon (pi2d) +After=network.target + +[Service] +Type=simple +ExecStart=/usr/bin/node /repo/dist/cli/pi2d.js --foreground +Environment=PATH=/usr/local/bin:/usr/bin:/bin +Restart=on-failure +RestartSec=2 +KillSignal=SIGTERM +TimeoutStopSec=15 + +[Install] +WantedBy=default.target +``` + +`XDG_CONFIG_HOME` is honoured for the target directory. On macOS the same +command writes `~/Library/LaunchAgents/com.pi2.pi2d.plist` (`RunAtLoad`, +`KeepAlive`, absolute node + script paths, `StandardOutPath`/`StandardErrorPath` +under `PI2_STATE_DIR`) and prints: + +```bash +launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pi2.pi2d.plist +launchctl enable gui/$(id -u)/com.pi2.pi2d +``` + +`uninstall-service --write` removes the file and prints the disable commands. +For a login-less service to keep running on Linux enable linger +(`loginctl enable-linger $USER`, `pi2 doctor` warns when it is off). + +## 10. Logs and health + +- `pi2d` logs JSONL to stderr: `systemctl --user status pi2d` / + `journalctl --user -u pi2d -f` on Linux, `~/Library/Logs/pi2/pi2d.log` on + macOS. Raise verbosity with `PI2_LOG_LEVEL=debug` (in the unit's + `Environment=` line) . +- Managed nvim output: `PI2_STATE_DIR/instances/.log`. +- `GET /api/v1/health` → `{ok, items:[{name, ok, detail}]}` (`instances`, + `workspaces`, `auth`, `static`). +- `GET /api/v1/diagnostics` → uptime, connection count, event rate, slow + queries, device/workspace/instance counts. +- `GET /api/v1/resources` → per-instance RSS, total vs physical memory, soft + warning (`instances > 8` or RSS > 60 %). + +## 11. Restart and shutdown semantics + +- **SIGINT/SIGTERM/SIGHUP** (`pi2d`): close HTTP + WS, close the plugin socket, + release `daemon.lock`/`daemon.json`, exit `0`. **Managed nvim processes are + not stopped** — they keep running and reconnect (exponential backoff, + 200 ms → 5 s) the next time the daemon starts. +- `instance.shutdown {mode:"drain"|"stop"}` stops one instance (drain first, + SIGTERM, then SIGKILL). +- `system.shutdown` (daemon-owned command) stops every managed instance before + the daemon is expected to exit. Note: the current router ignores the `drain` + parameter and stops instances with `mode:"stop"`. +- A crashed daemon leaves `d.sock`/`daemon.lock` behind; both are handled on + the next start (socket unlinked, lock detected as stale). + +## 12. Smoke test + +```bash +bash scripts/smoke.sh +``` + +Builds, starts `pi2d` on an ephemeral port with throwaway +`PI2_RUNTIME_DIR`/`PI2_DATA_DIR`/`PI2_STATE_DIR`, waits for `daemon.json`, then +asserts: `/api/v1/info` (200, `v=1`), `/api/v1/health` (200 ok), `/` (200 html +from `web/dist`), `/api/v1/nope` (404 with token, 401 without), +`/api/v1/workspaces` (200 array with the CLI token, 401 without/with a bogus +token), the `cli.token` format/mode, the lock payload, and a clean `SIGTERM` +exit with lock + `daemon.json` removed. Prints one `PASS` line per assertion. +`PI2_SMOKE_KEEP=1` keeps the temp dir (and `pi2d` log) for debugging. + +## 13. Troubleshooting + +| Symptom | Cause / fix | +|---|---| +| `pi2d: another pi2d is running (pid …)` | a live daemon owns this runtime dir. Stop it, or `--force` | +| `pi2: no running pi2d (…/daemon.json missing)` | daemon not started, or started with a different `PI2_RUNTIME_DIR` | +| `pi2: missing CLI token (…/cli.token)` | token deleted or daemon restarted; restart `pi2d` | +| `401 E_UNAUTHORIZED` from `curl` | send `Authorization: Bearer $(cat $PI2_RUNTIME_DIR/cli.token)` | +| `EADDRINUSE` on an explicit port | pick another `--port` (only the default port retries) | +| `403` with the browser console | origin not in `PI2_ORIGINS` (derived from the port) | +| `health: static=FAIL` | `web/dist` missing — build the web UI or set `PI2_STATIC_DIR` | +| Browser console loads but no workspaces | no nvim with the plugin has connected yet; run `pi2 attach` in a project | +| `pi2 doctor` → `plugin FAIL` | install pi2.nvim, or point `PI2_PLUGIN_DIR` at the checkout | +| `pi2 doctor` → `linger warn` | services stop at logout; `loginctl enable-linger $USER` | +| Instances gone after a wifi/laptop sleep | daemon restarted: nvim reconnects automatically; check `pi2 status` | diff --git a/package.json b/package.json index 880f9e9..3338ae2 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,9 @@ "typecheck": "tsc -p tsconfig.json --noEmit", "test": "vitest run", "test:watch": "vitest", - "lint": "tsc -p tsconfig.json --noEmit" + "lint": "tsc -p tsconfig.json --noEmit", + "start": "node dist/cli/pi2d.js --foreground", + "smoke": "bash scripts/smoke.sh" }, "dependencies": { "@hono/node-server": "^1.13.7", diff --git a/scripts/smoke.sh b/scripts/smoke.sh new file mode 100755 index 0000000..5987a24 --- /dev/null +++ b/scripts/smoke.sh @@ -0,0 +1,203 @@ +#!/usr/bin/env bash +# +# End-to-end smoke test for the pi2 daemon. +# +# Builds the project, starts `pi2d` on an ephemeral port with throwaway runtime +# dirs, then asserts the HTTP surface (info/health/static/404/auth), the +# discovery file and a clean SIGTERM shutdown. +# +# Usage: bash scripts/smoke.sh +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +TMP="$(mktemp -d "${TMPDIR:-/tmp}/pi2-smoke.XXXXXX")" +PI2_RUNTIME_DIR="$TMP/run" +PI2_DATA_DIR="$TMP/data" +PI2_STATE_DIR="$TMP/state" +export PI2_RUNTIME_DIR PI2_DATA_DIR PI2_STATE_DIR +export PI2_PORT=0 +export PI2_LOG_LEVEL="${PI2_LOG_LEVEL:-warn}" + +LOG="$TMP/pi2d.log" +DAEMON_JSON="$PI2_RUNTIME_DIR/daemon.json" +LOCK="$PI2_RUNTIME_DIR/daemon.lock" +TOKEN_FILE="$PI2_RUNTIME_DIR/cli.token" +BODY="$TMP/body" +STARTED=0 +DAEMON_PID="" + +cleanup() { + if [[ -n "$DAEMON_PID" ]] && kill -0 "$DAEMON_PID" 2>/dev/null; then + kill -TERM "$DAEMON_PID" 2>/dev/null || true + for _ in $(seq 1 50); do + kill -0 "$DAEMON_PID" 2>/dev/null || break + sleep 0.1 + done + kill -KILL "$DAEMON_PID" 2>/dev/null || true + fi + [[ "${PI2_SMOKE_KEEP:-0}" == "1" ]] || rm -rf "$TMP" +} +trap cleanup EXIT + +pass() { printf 'PASS %s\n' "$*"; } +fail() { + printf 'FAIL %s\n' "$*" >&2 + if [[ -f "$LOG" ]]; then + printf '\n--- pi2d log ---\n' >&2 + tail -n 40 "$LOG" >&2 || true + fi + printf '\n--- tmp dir: %s ---\n' "$TMP" >&2 + PI2_SMOKE_KEEP=1 + exit 1 +} + +require() { + command -v "$1" >/dev/null 2>&1 || fail "missing required command: $1" +} + +# request [curl args...] -> writes the body to $BODY, echoes the status +request() { + local method="$1" + local path="$2" + shift 2 + curl -sS --max-time 5 -o "$BODY" -w '%{http_code}' -X "$method" "$@" "$BASE_URL$path" || fail "curl failed: $method $path" +} + +expect_status() { + local expected="$1" + local method="$2" + local path="$3" + shift 3 + local actual + actual="$(request "$method" "$path" "$@")" + [[ "$actual" == "$expected" ]] || fail "expected HTTP $expected for $method $path, got $actual ($(head -c 200 "$BODY"))" +} + +# expect_json [file] — `body` is the parsed JSON +expect_json() { + local expression="$1" + local what="$2" + local file="${3:-$BODY}" + node --input-type=module -e " + import { readFileSync } from 'node:fs'; + const body = JSON.parse(readFileSync(process.argv[1], 'utf8')); + if (!($expression)) { + console.error('assertion failed: $what'); + process.exit(1); + } + " "$file" || fail "$what" +} + +require curl +require node + +[[ -f web/dist/index.html ]] || fail "web/dist/index.html missing — build the web UI first" + +printf '==> building\n' +# `npm run build` is exactly this tsc invocation; calling tsc directly keeps the +# smoke test independent of the package manager's dependency-check policy. +if ! npx tsc -p tsconfig.json >"$TMP/build.log" 2>&1; then + cat "$TMP/build.log" >&2 + fail "build failed" +fi +[[ -f dist/cli/pi2d.js ]] || fail "dist/cli/pi2d.js missing after build" +[[ -f dist/cli/pi2.js ]] || fail "dist/cli/pi2.js missing after build" +pass "build produced dist/cli/pi2d.js and dist/cli/pi2.js" + +printf '==> starting pi2d (port 0)\n' +node dist/cli/pi2d.js --foreground >"$TMP/stdout.log" 2>"$LOG" & +DAEMON_PID=$! + +for _ in $(seq 1 200); do + [[ -f "$DAEMON_JSON" ]] && break + kill -0 "$DAEMON_PID" 2>/dev/null || fail "pi2d exited before writing daemon.json" + sleep 0.05 +done +[[ -f "$DAEMON_JSON" ]] || fail "daemon.json was not written" +pass "daemon.json written" + +PORT="$(node --input-type=module -e " + import { readFileSync } from 'node:fs'; + const info = JSON.parse(readFileSync(process.argv[1], 'utf8')); + process.stdout.write(String(info.port)); +" "$DAEMON_JSON")" +[[ "$PORT" =~ ^[0-9]+$ ]] || fail "daemon.json has no usable port: $PORT" +[[ "$PORT" -gt 0 ]] || fail "daemon.json port must be explicit, got $PORT" +BASE_URL="http://127.0.0.1:$PORT" +pass "bound port $PORT" + +[[ -f "$LOCK" ]] || fail "daemon.lock missing while running" +grep -q "\"pid\": $DAEMON_PID" "$LOCK" || fail "daemon.lock does not carry pid $DAEMON_PID" +pass "daemon.lock holds pid $DAEMON_PID" + +expect_json "body.protocolVersion === 1" "daemon.json protocolVersion === 1" "$DAEMON_JSON" + +grep -q "^pi2d listening on http://127.0.0.1:$PORT$" "$TMP/stdout.log" || + fail "stdout line missing: expected 'pi2d listening on http://127.0.0.1:$PORT' (got: $(cat "$TMP/stdout.log"))" +pass "stdout announced http://127.0.0.1:$PORT" + +[[ -f "$TOKEN_FILE" ]] || fail "cli.token missing" +TOKEN="$(tr -d '\n' <"$TOKEN_FILE")" +[[ ${#TOKEN} -eq 64 ]] || fail "cli.token must be 64 hex chars, got ${#TOKEN}" +MODE="$(stat -c '%a' "$TOKEN_FILE" 2>/dev/null || stat -f '%Lp' "$TOKEN_FILE")" +[[ "$MODE" == "600" ]] || fail "cli.token mode must be 600, got $MODE" +pass "cli.token is 64 hex chars, mode 0600" + +expect_status 200 GET /api/v1/info +expect_json "body.v === 1 && typeof body.daemonId === 'string'" "/api/v1/info reports v=1" +pass "GET /api/v1/info -> 200 v=1" + +expect_status 200 GET /api/v1/health +expect_json "body.ok === true" "/api/v1/health ok" +pass "GET /api/v1/health -> 200 ok" + +expect_status 200 GET / +grep -qi 'text/html' <(curl -sS -D - -o /dev/null --max-time 5 "$BASE_URL/") || fail "GET / did not return text/html" +grep -q 'id="root"\|id=app' "$BODY" || fail "GET / body is not the web UI shell" +grep -q '' "$BODY" || fail "GET / body has no <title>" +pass "GET / -> 200 html from web/dist" + +expect_status 404 GET /api/v1/nope -H "authorization: Bearer $TOKEN" +pass "GET /api/v1/nope (authenticated) -> 404" +expect_status 401 GET /api/v1/nope +pass "GET /api/v1/nope (unauthenticated) -> 401" + +expect_status 200 GET /api/v1/workspaces -H "authorization: Bearer $TOKEN" +expect_json "Array.isArray(body)" "/api/v1/workspaces is an array" +pass "GET /api/v1/workspaces with the CLI token -> 200 array" + +expect_status 401 GET /api/v1/workspaces +expect_json "body.code === 'E_UNAUTHORIZED'" "401 body carries E_UNAUTHORIZED" +pass "GET /api/v1/workspaces without a token -> 401" + +expect_status 401 GET /api/v1/workspaces -H "authorization: Bearer deadbeef" +pass "GET /api/v1/workspaces with a bogus token -> 401" + +printf '==> stopping pi2d (SIGTERM)\n' +kill -TERM "$DAEMON_PID" +for _ in $(seq 1 100); do + kill -0 "$DAEMON_PID" 2>/dev/null || break + sleep 0.05 +done +kill -0 "$DAEMON_PID" 2>/dev/null && fail "pi2d did not exit within 5s of SIGTERM" + +set +e +wait "$DAEMON_PID" +EXIT_CODE=$? +set -e +[[ "$EXIT_CODE" -eq 0 ]] || fail "pi2d exited with code $EXIT_CODE" +pass "SIGTERM -> clean exit (code 0)" + +[[ ! -f "$LOCK" ]] || fail "daemon.lock was not removed on shutdown" +pass "daemon.lock removed" +[[ ! -f "$DAEMON_JSON" ]] || fail "daemon.json was not removed on shutdown" +pass "daemon.json removed" + +set +e +curl -sS --max-time 1 -o /dev/null "$BASE_URL/api/v1/health" 2>/dev/null +set -e +pass "port $PORT is no longer serving" + +printf '\nSMOKE OK (%s)\n' "$TMP" diff --git a/src/cli/doctor.ts b/src/cli/doctor.ts new file mode 100644 index 0000000..fca047e --- /dev/null +++ b/src/cli/doctor.ts @@ -0,0 +1,407 @@ +/** + * `pi2 doctor` — environment checks with injectable probes. + * + * Every input the checks need lives in a `DoctorContext`; `defaultProbes(ctx)` + * turns that context into the check list and `runDoctor()` executes it. Tests + * build a context directly instead of poking at the real machine. + */ +import { execFile } from "node:child_process"; +import { existsSync, statSync } from "node:fs"; +import { homedir, platform as osPlatform } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { fileURLToPath } from "node:url"; +import { DEFAULT_PORT } from "../config.js"; +import { daemonSocketPath, runtimeDir } from "../core/paths.js"; +import { PROTOCOL_VERSION } from "../protocol/types.js"; +import { formatTable } from "./util.js"; + +const execFileAsync = promisify(execFile); + +export type CheckStatus = "ok" | "warn" | "fail"; + +export interface DoctorCheck { + name: string; + status: CheckStatus; + detail: string; +} + +export interface DoctorProbe { + name: string; + run(): DoctorCheck | Promise<DoctorCheck>; +} + +export interface DoctorReport { + ok: boolean; + checks: DoctorCheck[]; +} + +export interface BinaryProbe { + found: boolean; + path?: string; + version?: string; + error?: string; +} + +export interface DoctorContext { + platform: NodeJS.Platform; + nodeVersion: string; + nvim: BinaryProbe; + pi: BinaryProbe; + plugin: { dir: string | undefined; bridgeFound: boolean }; + runtime: { path: string; exists: boolean; mode: number | undefined }; + cliToken: { path: string; exists: boolean; mode: number | undefined }; + socket: { path: string; exists: boolean }; + daemon: { reachable: boolean; port?: number; protocolVersion?: number; error?: string }; + port: { configured: number; bound: boolean }; + serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string }; + linger: { checked: boolean; enabled?: boolean; detail?: string }; + webDist: { path: string; exists: boolean }; +} + +/** `v22.1.0` / `22.1.0` → `[22,1,0]`. */ +export function parseVersion(raw: string | undefined): [number, number, number] | undefined { + if (raw === undefined) return undefined; + const match = /(\d+)\.(\d+)\.(\d+)/.exec(raw); + if (!match) return undefined; + return [Number(match[1]), Number(match[2]), Number(match[3])]; +} + +export function versionAtLeast(version: readonly [number, number, number], minimum: readonly [number, number, number]): boolean { + for (let index = 0; index < 3; index += 1) { + const left = version[index] ?? 0; + const right = minimum[index] ?? 0; + if (left !== right) return left > right; + } + return true; +} + +/** `NVIM v0.10.2` (first line of `nvim --version`) → `0.10.2`. */ +export function parseNvimVersion(output: string): string | undefined { + const match = /NVIM v(\d+\.\d+\.\d+)/.exec(output); + return match?.[1]; +} + +export const MIN_NODE: readonly [number, number, number] = [22, 0, 0]; +export const MIN_NVIM: readonly [number, number, number] = [0, 9, 0]; + +/** `<repo>/web/dist`, matching `loadConfig()`'s default. */ +export function defaultWebDist(): string { + return fileURLToPath(new URL("../../web/dist", import.meta.url)); +} + +export function checkNode(version: string): DoctorCheck { + const parsed = parseVersion(version); + if (parsed === undefined) return { name: "node", status: "fail", detail: `unparsable version "${version}"` }; + const ok = versionAtLeast(parsed, MIN_NODE); + return { + name: "node", + status: ok ? "ok" : "fail", + detail: `${version}${ok ? "" : ` (< ${MIN_NODE.join(".")})`}`, + }; +} + +export function checkNvim(probe: BinaryProbe): DoctorCheck { + if (!probe.found) { + return { name: "nvim", status: "fail", detail: probe.error ?? "nvim not found on PATH" }; + } + const version = parseVersion(probe.version); + if (version === undefined) { + return { name: "nvim", status: "warn", detail: `could not parse version of ${probe.path ?? "nvim"}` }; + } + const ok = versionAtLeast(version, MIN_NVIM); + return { + name: "nvim", + status: ok ? "ok" : "fail", + detail: `${probe.version?.trim() ?? version.join(".")} (${probe.path ?? "nvim"})${ok ? "" : ` < ${MIN_NVIM.join(".")} for --remote-ui`}`, + }; +} + +export function checkPi(probe: BinaryProbe): DoctorCheck { + if (!probe.found) return { name: "pi", status: "warn", detail: probe.error ?? "pi not found on PATH (plugin-only sessions still work)" }; + return { name: "pi", status: "ok", detail: `${probe.version?.trim() ?? "unknown version"} (${probe.path ?? "pi"})` }; +} + +export function checkPlugin(probe: DoctorContext["plugin"]): DoctorCheck { + if (probe.bridgeFound) { + return { name: "plugin", status: "ok", detail: `${probe.dir ?? "pi2.nvim"} (lua/pi/web/bridge.lua)` }; + } + return { + name: "plugin", + status: "fail", + detail: `pi2.nvim not found (set PI2_PLUGIN_DIR or install it); looked in ${probe.dir ?? "~/.local/share/nvim/lazy/pi2.nvim"}`, + }; +} + +function permsDetail(mode: number | undefined): string { + return mode === undefined ? "mode unknown" : `mode ${mode.toString(8).padStart(4, "0")}`; +} + +export function checkRuntimeDir(probe: DoctorContext["runtime"]): DoctorCheck { + if (!probe.exists) return { name: "runtime-dir", status: "fail", detail: `${probe.path} missing` }; + const ok = probe.mode !== undefined && (probe.mode & 0o077) === 0; + return { + name: "runtime-dir", + status: ok ? "ok" : "warn", + detail: `${probe.path} (${permsDetail(probe.mode)}${ok ? "" : ", expected 0700"})`, + }; +} + +export function checkCliToken(probe: DoctorContext["cliToken"]): DoctorCheck { + if (!probe.exists) { + return { name: "cli-token", status: "warn", detail: `${probe.path} missing (start pi2d to mint it)` }; + } + const ok = probe.mode !== undefined && (probe.mode & 0o077) === 0; + return { + name: "cli-token", + status: ok ? "ok" : "fail", + detail: `${probe.path} (${permsDetail(probe.mode)}${ok ? "" : ", expected 0600"})`, + }; +} + +export function checkSocket(probe: DoctorContext["socket"], daemonReachable: boolean): DoctorCheck { + if (!probe.exists) { + return { + name: "socket", + status: daemonReachable ? "warn" : "fail", + detail: `${probe.path} missing`, + }; + } + return { name: "socket", status: "ok", detail: `${probe.path} present` }; +} + +export function checkDaemon(probe: DoctorContext["daemon"]): DoctorCheck { + if (!probe.reachable) { + return { name: "daemon", status: "fail", detail: probe.error ?? "not reachable (is pi2d running?)" }; + } + return { name: "daemon", status: "ok", detail: `http://127.0.0.1:${probe.port ?? "?"} reachable` }; +} + +export function checkPort(probe: DoctorContext["port"]): DoctorCheck { + if (probe.bound) return { name: "port", status: "ok", detail: `${probe.configured} bound by pi2d` }; + return { name: "port", status: "ok", detail: `${probe.configured} free` }; +} + +export function checkServiceManager(probe: DoctorContext["serviceManager"]): DoctorCheck { + return { + name: "service-manager", + status: probe.available ? "ok" : "warn", + detail: probe.detail ?? (probe.available ? `${probe.name} available` : `${probe.name} not reachable`), + }; +} + +export function checkLinger(probe: DoctorContext["linger"]): DoctorCheck { + if (!probe.checked) return { name: "linger", status: "ok", detail: "not applicable" }; + const detail = probe.detail ?? (probe.enabled === true ? "Linger=yes" : "Linger=no (enable with loginctl enable-linger)"); + return { name: "linger", status: probe.enabled === true ? "ok" : "warn", detail }; +} + +export function checkWebDist(probe: DoctorContext["webDist"]): DoctorCheck { + if (probe.exists) return { name: "web-dist", status: "ok", detail: probe.path }; + return { name: "web-dist", status: "warn", detail: `${probe.path} missing (build the web UI for the browser console)` }; +} + +export function checkProtocol(probe: DoctorContext["daemon"]): DoctorCheck { + if (!probe.reachable) return { name: "protocol", status: "fail", detail: "no daemon to compare against" }; + if (probe.protocolVersion === PROTOCOL_VERSION) { + return { name: "protocol", status: "ok", detail: `v${PROTOCOL_VERSION}` }; + } + return { + name: "protocol", + status: "fail", + detail: `daemon speaks v${String(probe.protocolVersion)}, CLI expects v${PROTOCOL_VERSION}`, + }; +} + +/** The canonical check list, in display order. */ +export function defaultProbes(ctx: DoctorContext): DoctorProbe[] { + const isLinux = ctx.platform === "linux"; + return [ + { name: "node", run: () => checkNode(ctx.nodeVersion) }, + { name: "nvim", run: () => checkNvim(ctx.nvim) }, + { name: "pi", run: () => checkPi(ctx.pi) }, + { name: "plugin", run: () => checkPlugin(ctx.plugin) }, + { name: "runtime-dir", run: () => checkRuntimeDir(ctx.runtime) }, + { name: "cli-token", run: () => checkCliToken(ctx.cliToken) }, + { name: "socket", run: () => checkSocket(ctx.socket, ctx.daemon.reachable) }, + { name: "daemon", run: () => checkDaemon(ctx.daemon) }, + { name: "port", run: () => checkPort(ctx.port) }, + { name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) }, + ...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []), + { name: "web-dist", run: () => checkWebDist(ctx.webDist) }, + { name: "protocol", run: () => checkProtocol(ctx.daemon) }, + ]; +} + +export async function runDoctor(probes: readonly DoctorProbe[]): Promise<DoctorReport> { + const checks: DoctorCheck[] = []; + for (const probe of probes) { + try { + checks.push(await probe.run()); + } catch (error) { + checks.push({ + name: probe.name, + status: "fail", + detail: error instanceof Error ? error.message : String(error), + }); + } + } + return { ok: checks.every((check) => check.status !== "fail"), checks }; +} + +const MARKS: Record<CheckStatus, string> = { ok: "ok ", warn: "warn", fail: "FAIL" }; + +export function formatReport(report: DoctorReport): string { + const rows = report.checks.map((check) => [MARKS[check.status], check.name, check.detail]); + return [formatTable(["", "check", "detail"], rows), "", `overall: ${report.ok ? "ok" : "FAILED"}`].join("\n"); +} + +export function reportToJson(report: DoctorReport): string { + return `${JSON.stringify({ ok: report.ok, checks: report.checks }, null, 2)}`; +} + +// --------------------------------------------------------------------------- +// Real-environment context +// --------------------------------------------------------------------------- + +export interface RunLike { + (command: string, args: readonly string[]): Promise<{ ok: boolean; stdout: string; stderr: string }>; +} + +export interface DoctorOptions { + platform?: NodeJS.Platform; + env?: NodeJS.ProcessEnv; + runtime?: string; + home?: string; + uid?: number; + /** Reachable daemon info (`/api/v1/info`), or the reason it is not reachable. */ + daemonInfo?: () => Promise<{ port: number; protocolVersion: number } | { error: string }>; + run?: RunLike; + which?: (command: string) => string | undefined; + now?: () => number; +} + +async function defaultRun(command: string, args: readonly string[]): Promise<{ ok: boolean; stdout: string; stderr: string }> { + try { + const { stdout, stderr } = await execFileAsync(command, [...args], { timeout: 5_000, encoding: "utf8" }); + return { ok: true, stdout, stderr }; + } catch (error) { + const failure = error as NodeJS.ErrnoException & { stdout?: string; stderr?: string }; + return { ok: false, stdout: failure.stdout ?? "", stderr: failure.stderr ?? failure.message ?? "" }; + } +} + +function whichSync(command: string, env: NodeJS.ProcessEnv): string | undefined { + const path = env.PATH ?? ""; + for (const dir of path.split(":")) { + if (dir === "") continue; + const candidate = join(dir, command); + if (existsSync(candidate)) return candidate; + } + return undefined; +} + +function statOrUndefined(path: string): { exists: boolean; mode: number | undefined } { + try { + return { exists: true, mode: statSync(path).mode & 0o777 }; + } catch { + return { exists: false, mode: undefined }; + } +} + +async function binaryProbe(command: string, args: readonly string[], options: DoctorOptions, env: NodeJS.ProcessEnv): Promise<BinaryProbe> { + const path = (options.which ?? ((name: string) => whichSync(name, env)))(command); + if (path === undefined) return { found: false, error: `${command} not found on PATH` }; + const run = options.run ?? defaultRun; + const result = await run(command, args); + if (!result.ok) { + return { found: true, path, ...(result.stderr.trim() === "" ? {} : { error: result.stderr.trim() }) }; + } + const version = result.stdout.trim().split("\n")[0] ?? ""; + return { found: true, path, version }; +} + +export async function collectContext(options: DoctorOptions = {}): Promise<DoctorContext> { + const env = options.env ?? process.env; + const platform = options.platform ?? osPlatform(); + const runtime = options.runtime ?? runtimeDir(); + const home = options.home ?? homedir(); + const run = options.run ?? defaultRun; + const uid = options.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0); + + const nvim = await binaryProbe("nvim", ["--version"], options, env); + if (nvim.found && nvim.version !== undefined) { + const parsed = parseNvimVersion(nvim.version); + if (parsed !== undefined) nvim.version = `v${parsed}`; + } + const pi = await binaryProbe("pi", ["--version"], options, env); + + const pluginDir = env.PI2_PLUGIN_DIR?.trim() || join(home, ".local", "share", "nvim", "lazy", "pi2.nvim"); + const bridgeFound = existsSync(join(pluginDir, "lua", "pi", "web", "bridge.lua")); + + const runtimeStat = statOrUndefined(runtime); + const cliTokenPath = join(runtime, "cli.token"); + const tokenStat = statOrUndefined(cliTokenPath); + const socketPath = daemonSocketPath(); + const configuredPort = Number(env.PI2_PORT ?? DEFAULT_PORT) || DEFAULT_PORT; + + let daemon: DoctorContext["daemon"]; + if (options.daemonInfo !== undefined) { + try { + const info = await options.daemonInfo(); + daemon = + "error" in info + ? { reachable: false, error: info.error } + : { reachable: true, port: info.port, protocolVersion: info.protocolVersion }; + } catch (error) { + daemon = { reachable: false, error: error instanceof Error ? error.message : String(error) }; + } + } else { + daemon = { reachable: false, error: "no daemon reachable (is pi2d running?)" }; + } + + const serviceManager: DoctorContext["serviceManager"] = + platform === "darwin" + ? { + name: "launchd", + available: (options.which ?? ((name: string) => whichSync(name, env)))("launchctl") !== undefined, + } + : { name: "systemd", available: (options.which ?? ((name: string) => whichSync(name, env)))("systemctl") !== undefined }; + + let linger: DoctorContext["linger"] = { checked: false }; + if (platform === "linux") { + const result = await run("loginctl", ["show-user", String(uid), "-p", "Linger"]); + if (result.ok) { + const value = /Linger=(\w+)/.exec(result.stdout)?.[1]; + linger = { + checked: true, + enabled: value === "yes", + detail: `Linger=${value ?? "unknown"}`, + }; + } else { + linger = { checked: true, enabled: undefined, detail: "loginctl unavailable" }; + } + } + + return { + platform, + nodeVersion: process.version, + nvim, + pi, + plugin: { dir: pluginDir, bridgeFound }, + runtime: { path: runtime, exists: runtimeStat.exists, mode: runtimeStat.mode }, + cliToken: { path: cliTokenPath, exists: tokenStat.exists, mode: tokenStat.mode }, + socket: { path: socketPath, exists: existsSync(socketPath) }, + daemon, + port: { configured: daemon.port ?? configuredPort, bound: daemon.reachable }, + serviceManager, + linger, + webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) }, + }; +} + +/** Full run against the real machine (with optional injectable overrides). */ +export async function diagnose(options: DoctorOptions = {}): Promise<DoctorReport> { + const ctx = await collectContext(options); + return runDoctor(defaultProbes(ctx)); +} diff --git a/src/cli/listen.ts b/src/cli/listen.ts new file mode 100644 index 0000000..98976c9 --- /dev/null +++ b/src/cli/listen.ts @@ -0,0 +1,63 @@ +/** + * Listening with a bounded port retry. + * + * `pi2d` uses the default port 7676; when another process already owns it the + * daemon walks `+1 … +9` instead of failing to start (the browser UI and the + * `pi2` CLI both read the actual port from `runtime/daemon.json`, so a bump is + * invisible to users). An explicitly configured port is never re-mapped: a + * conflict there is a real error. + */ +import type { Config } from "../config.js"; +import { startServer, type ServerDeps, type StartedServer } from "../daemon/server.js"; + +export interface ListenOptions { + /** Extra port attempts after the first failure (0 = no retry). */ + retries?: number; + onRetry?: (info: { from: number; to: number; error: Error }) => void; +} + +function errorCode(error: unknown): string | undefined { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return typeof code === "string" ? code : undefined; +} + +/** `EADDRINUSE` on either the HTTP server or an earlier await. */ +export function isAddressInUse(error: unknown): boolean { + return errorCode(error) === "EADDRINUSE"; +} + +/** + * Rewrite the derived CORS origins when the effective port changes, mirroring + * what `startServer` does for an ephemeral (`:0`) bind. + */ +export function withPort(config: Config, port: number): Config { + if (port === config.port) return config; + return { + ...config, + port, + corsOrigins: config.corsOrigins.map((origin) => + origin.endsWith(`:${config.port}`) ? `${origin.slice(0, -String(config.port).length)}${port}` : origin, + ), + }; +} + +export async function listenWithRetry( + config: Config, + deps: ServerDeps, + options: ListenOptions = {}, +): Promise<StartedServer> { + const retries = config.port === 0 ? 0 : Math.max(0, options.retries ?? 0); + let port = config.port; + + for (let attempt = 0; ; attempt += 1) { + try { + return await startServer(withPort(config, port), deps); + } catch (error) { + if (!isAddressInUse(error) || attempt >= retries) throw error; + if (port >= 65535) throw error; + const next = port + 1; + options.onRetry?.({ from: port, to: next, error: error instanceof Error ? error : new Error(String(error)) }); + port = next; + } + } +} diff --git a/src/cli/lock.ts b/src/cli/lock.ts new file mode 100644 index 0000000..5a415a8 --- /dev/null +++ b/src/cli/lock.ts @@ -0,0 +1,249 @@ +/** + * Daemon singleton lock (`<runtime>/daemon.lock`) and discovery file + * (`<runtime>/daemon.json`). + * + * Both files carry the same payload: + * + * ```jsonc + * {"pid":1234,"bootId":"…","port":7676,"daemonId":"d-…","startedAt":1733,"protocolVersion":1} + * ``` + * + * The lock is created with `wx` (atomic: only one daemon wins) and is + * considered **stale** when the pid is gone or the recorded boot id differs + * from the current one (pid reuse after a reboot). `--force` ignores a live + * lock. `daemon.json` is written after `listen()` so other tools can find the + * actual port without parsing arguments. + */ +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { randomBytes } from "node:crypto"; +import { dirname, join } from "node:path"; +import { daemonLockPath, ensureDir, runtimeDir } from "../core/paths.js"; + +export const LOCK_FILE = "daemon.lock"; +export const DAEMON_JSON_FILE = "daemon.json"; + +export interface DaemonLock { + pid: number; + bootId: string; + port: number; + daemonId: string; + startedAt: number; + protocolVersion: number; +} + +export type LockErrorCode = "E_LOCKED"; + +export class LockError extends Error { + readonly code: LockErrorCode; + readonly holder: DaemonLock | undefined; + + constructor(code: LockErrorCode, message: string, holder?: DaemonLock) { + super(message); + this.name = "LockError"; + this.code = code; + this.holder = holder; + } +} + +export const defaultLockPath = (): string => join(runtimeDir(), LOCK_FILE); +export const defaultDaemonJsonPath = (): string => join(runtimeDir(), DAEMON_JSON_FILE); + +/** Linux boot id; on macOS the boottime; otherwise a stable placeholder. */ +export function readBootId(): string { + try { + const value = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(); + if (value !== "") return value; + } catch { + // not Linux + } + if (process.platform === "darwin") { + try { + const value = execFileSync("sysctl", ["-n", "kern.boottime"], { encoding: "utf8" }).trim(); + if (value !== "") return value; + } catch { + // sysctl missing + } + } + return "unknown"; +} + +export function isPidAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + // EPERM means the process exists but belongs to someone else. + return (error as NodeJS.ErrnoException).code === "EPERM"; + } +} + +function isLock(value: unknown): value is DaemonLock { + if (typeof value !== "object" || value === null) return false; + const candidate = value as Partial<DaemonLock>; + return ( + typeof candidate.pid === "number" && + Number.isInteger(candidate.pid) && + candidate.pid > 0 && + typeof candidate.bootId === "string" && + typeof candidate.port === "number" && + typeof candidate.daemonId === "string" && + candidate.daemonId !== "" && + typeof candidate.startedAt === "number" && + typeof candidate.protocolVersion === "number" + ); +} + +/** Parse a lock/daemon.json file; `undefined` when absent or malformed. */ +export function parseDaemonFile(raw: string): DaemonLock | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return undefined; + } + return isLock(parsed) ? parsed : undefined; +} + +export function readLockFile(path: string = defaultLockPath()): DaemonLock | undefined { + if (!existsSync(path)) return undefined; + try { + return parseDaemonFile(readFileSync(path, "utf8")); + } catch { + return undefined; + } +} + +export function readDaemonJson(path: string = defaultDaemonJsonPath()): DaemonLock | undefined { + return readLockFile(path); +} + +export interface StalenessOptions { + isPidAlive?: (pid: number) => boolean; + bootId?: () => string; +} + +export interface Staleness { + live: boolean; + reason: "alive" | "no-pid" | "boot-changed"; +} + +/** A lock is live only when the pid still exists *and* we are on the same boot. */ +export function assessLock(lock: DaemonLock, options: StalenessOptions = {}): Staleness { + const alive = (options.isPidAlive ?? isPidAlive)(lock.pid); + if (!alive) return { live: false, reason: "no-pid" }; + const bootId = (options.bootId ?? readBootId)(); + if (bootId !== "unknown" && lock.bootId !== "unknown" && bootId !== lock.bootId) { + return { live: false, reason: "boot-changed" }; + } + return { live: true, reason: "alive" }; +} + +function writeAtomic(path: string, payload: DaemonLock, mode = 0o600): void { + ensureDir(dirname(path)); + const temporary = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + writeFileSync(temporary, `${JSON.stringify(payload, null, 2)}\n`, { mode }); + renameSync(temporary, path); +} + +export interface AcquireLockOptions { + lockPath?: string; + force?: boolean; + /** `pid` defaults to the current process. */ + payload: Omit<DaemonLock, "pid" | "bootId"> & { pid?: number; bootId?: string }; + isPidAlive?: (pid: number) => boolean; + bootId?: () => string; +} + +export interface DaemonLockHandle { + readonly path: string; + readonly lock: DaemonLock; + /** Rewrite the lock in place (e.g. once the real port is known). */ + update(patch: Partial<DaemonLock>): DaemonLock; + /** Remove the lock (and `daemon.json`) when we still own them. */ + release(): void; +} + +export function acquireLock(options: AcquireLockOptions): DaemonLockHandle { + const path = options.lockPath ?? daemonLockPath(); + ensureDir(dirname(path)); + const bootId = options.payload.bootId ?? (options.bootId ?? readBootId)(); + const candidate: DaemonLock = { + ...options.payload, + pid: options.payload.pid ?? process.pid, + bootId, + }; + + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + writeFileSync(path, `${JSON.stringify(candidate, null, 2)}\n`, { flag: "wx", mode: 0o600 }); + return makeHandle(path, candidate); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + + const holder = readLockFile(path); + if (holder !== undefined) { + const staleness = assessLock(holder, { + ...(options.isPidAlive === undefined ? {} : { isPidAlive: options.isPidAlive }), + bootId: () => bootId, + }); + if (staleness.live && options.force !== true) { + throw new LockError( + "E_LOCKED", + `another pi2d is running (pid ${holder.pid}, port ${holder.port}); use --force to override`, + holder, + ); + } + } + // Stale, forced, or unreadable (a half-written lock from a crash). + try { + unlinkSync(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + } + + throw new LockError("E_LOCKED", `could not acquire ${path}: another pi2d keeps re-creating it`); +} + +function makeHandle(path: string, initial: DaemonLock): DaemonLockHandle { + let current = initial; + return { + path, + get lock(): DaemonLock { + return current; + }, + update(patch: Partial<DaemonLock>): DaemonLock { + current = { ...current, ...patch }; + writeAtomic(path, current); + return current; + }, + release(): void { + const onDisk = readLockFile(path); + if (onDisk === undefined || (onDisk.pid === current.pid && onDisk.daemonId === current.daemonId)) { + try { + unlinkSync(path); + } catch { + // already gone + } + } + // A stale daemon.json would point tools at a dead port. + const daemonJsonPath = join(dirname(path), DAEMON_JSON_FILE); + const discovery = readLockFile(daemonJsonPath); + if (discovery !== undefined && discovery.daemonId === current.daemonId) { + try { + unlinkSync(daemonJsonPath); + } catch { + // already gone + } + } + }, + }; +} + +export function writeDaemonJson(payload: DaemonLock, path: string = defaultDaemonJsonPath()): string { + writeAtomic(path, payload); + return path; +} diff --git a/src/cli/logger.ts b/src/cli/logger.ts new file mode 100644 index 0000000..f2cbd70 --- /dev/null +++ b/src/cli/logger.ts @@ -0,0 +1,82 @@ +/** + * Console logger for the CLI entry points. + * + * `pi2d` prints exactly one machine-readable line on stdout (`pi2d listening + * on …`); every log record therefore goes to stderr in JSONL so it can be + * piped into a log file or a systemd journal without corrupting stdout. + */ +import type { Logger, LogLevel } from "../core/interfaces.js"; + +const LEVELS: Record<LogLevel, number> = { debug: 10, info: 20, warn: 30, error: 40 }; + +export interface ConsoleLoggerOptions { + level?: LogLevel | "silent"; + /** Defaults to `process.stderr`. */ + write?: (line: string) => void; + now?: () => number; +} + +export class ConsoleLogger implements Logger { + private readonly threshold: number; + private readonly write: (line: string) => void; + private readonly now: () => number; + private readonly fields: Record<string, unknown>; + + constructor(options: ConsoleLoggerOptions = {}, fields: Record<string, unknown> = {}) { + const level = options.level ?? "info"; + this.threshold = level === "silent" ? Number.POSITIVE_INFINITY : LEVELS[level]; + this.write = options.write ?? ((line) => process.stderr.write(`${line}\n`)); + this.now = options.now ?? Date.now; + this.fields = fields; + } + + debug(msg: string, fields?: Record<string, unknown>): void { + this.log("debug", msg, fields); + } + + info(msg: string, fields?: Record<string, unknown>): void { + this.log("info", msg, fields); + } + + warn(msg: string, fields?: Record<string, unknown>): void { + this.log("warn", msg, fields); + } + + error(msg: string, fields?: Record<string, unknown>): void { + this.log("error", msg, fields); + } + + child(fields: Record<string, unknown>): Logger { + return new ConsoleLogger( + { level: this.threshold === Number.POSITIVE_INFINITY ? "silent" : levelFor(this.threshold), now: this.now }, + { ...this.fields, ...fields }, + ); + } + + private log(level: LogLevel, msg: string, fields?: Record<string, unknown>): void { + if (LEVELS[level] < this.threshold) return; + try { + this.write(JSON.stringify({ ts: this.now(), level, msg, ...this.fields, ...(fields ?? {}) })); + } catch { + // A non-serialisable field must never take the daemon down. + this.write(JSON.stringify({ ts: this.now(), level, msg })); + } + } +} + +function levelFor(threshold: number): LogLevel { + if (threshold <= LEVELS.debug) return "debug"; + if (threshold <= LEVELS.info) return "info"; + if (threshold <= LEVELS.warn) return "warn"; + return "error"; +} + +export function createLogger(level?: LogLevel | "silent"): ConsoleLogger { + const envLevel = process.env.PI2_LOG_LEVEL?.trim().toLowerCase(); + const resolved = level ?? (isLogLevel(envLevel) ? envLevel : "info"); + return new ConsoleLogger({ level: resolved }); +} + +function isLogLevel(value: string | undefined): value is LogLevel | "silent" { + return value === "debug" || value === "info" || value === "warn" || value === "error" || value === "silent"; +} diff --git a/src/cli/pi2.ts b/src/cli/pi2.ts new file mode 100644 index 0000000..ef31b1d --- /dev/null +++ b/src/cli/pi2.ts @@ -0,0 +1,591 @@ +#!/usr/bin/env node +/** + * `pi2` — the user-facing CLI. + * + * pi2 attach [path] attach nvim to the workspace instance (or open nvim) + * pi2 status [--json] daemon, instances, resources, health + * pi2 doctor [--json] environment checks + * pi2 pairing create a pairing code for another device + * pi2 install-service render/install a systemd user unit or LaunchAgent + * pi2 uninstall-service remove it again + * + * Everything is discovered from the runtime dir: `daemon.json` carries the + * bound port, `cli.token` the local admin token (see docs/deployment.md). + */ +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { platform as osPlatform } from "node:os"; +import { runtimeDir } from "../core/paths.js"; +import type { InstanceResourcesSnapshot } from "../core/interfaces.js"; +import type { WorkspaceInfo } from "../protocol/types.js"; +import { PROTOCOL_VERSION } from "../protocol/types.js"; +import { readDaemonJson, type DaemonLock } from "./lock.js"; +import { cliTokenPath, readCliToken } from "./token.js"; +import { + boolFlag, + errorMessage, + formatBytes, + formatTable, + packageVersion, + parseArgs, + realpathOrSelf, + UsageError, +} from "./util.js"; +import { + defaultServicePaths, + renderService, + serviceDir, + type RenderedService, + type ServicePaths, + type ServicePlatform, +} from "./service.js"; +import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js"; + +export const USAGE = `pi2 — pi2 client + +Usage: + pi2 attach [path] attach nvim to the workspace instance, else open nvim + pi2 status [--json] daemon info, instances, resources, health + pi2 doctor [--json] environment checks + pi2 pairing create a pairing code (URL + code + QR payload) + pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent + pi2 uninstall-service [--dry-run|--write] remove the unit + pi2 --version | --help + +The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and +$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2d\`. +See docs/deployment.md.`; + +/** A user-facing failure: printed as-is, exits with `code`. */ +export class CliError extends Error { + readonly code: number; + + constructor(message: string, code = 1) { + super(message); + this.name = "CliError"; + this.code = code; + } +} + +export interface Endpoint { + baseUrl: string; + token: string; + daemon: DaemonLock; +} + +export interface DaemonClient { + readonly baseUrl: string; + readonly token: string; + readonly daemon: DaemonLock; + get<T>(path: string): Promise<T>; + post(path: string, body: unknown): Promise<{ status: number; body: Record<string, unknown> }>; +} + +/** Read `daemon.json` + `cli.token`; throws a helpful `CliError` when absent. */ +export function resolveEndpoint(runtime: string = runtimeDir()): Endpoint { + const daemon = readDaemonJson(resolve(runtime, "daemon.json")); + if (daemon === undefined) { + throw new CliError( + `no running pi2d (${resolve(runtime, "daemon.json")} missing). Start it with \`pi2d --foreground\`.`, + ); + } + const token = readCliToken(cliTokenPath(runtime)); + if (token === undefined) { + throw new CliError(`missing CLI token (${cliTokenPath(runtime)}). Restart \`pi2d\`.`); + } + return { baseUrl: `http://127.0.0.1:${daemon.port}`, token, daemon }; +} + +export interface ClientOptions { + endpoint?: Endpoint; + runtime?: string; + timeoutMs?: number; + fetchImpl?: typeof fetch; +} + +export function createClient(options: ClientOptions = {}): DaemonClient { + const endpoint = options.endpoint ?? resolveEndpoint(options.runtime); + const fetchImpl = options.fetchImpl ?? fetch; + const timeoutMs = options.timeoutMs ?? 5_000; + + async function request(path: string, init: RequestInit): Promise<Response> { + const url = `${endpoint.baseUrl}${path}`; + try { + return await fetchImpl(url, { + ...init, + headers: { + authorization: `Bearer ${endpoint.token}`, + "content-type": "application/json", + ...(init.headers ?? {}), + }, + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (error) { + throw new CliError(`cannot reach pi2d at ${endpoint.baseUrl}: ${errorMessage(error)}`); + } + } + + return { + baseUrl: endpoint.baseUrl, + token: endpoint.token, + daemon: endpoint.daemon, + async get<T>(path: string): Promise<T> { + const response = await request(path, { method: "GET" }); + if (!response.ok) throw new CliError(`${path} failed: HTTP ${response.status} ${await safeText(response)}`); + return (await response.json()) as T; + }, + async post(path: string, body: unknown): Promise<{ status: number; body: Record<string, unknown> }> { + const response = await request(path, { method: "POST", body: JSON.stringify(body) }); + const text = await safeText(response); + let parsed: Record<string, unknown> = {}; + if (text.trim() !== "") { + try { + parsed = JSON.parse(text) as Record<string, unknown>; + } catch { + parsed = { raw: text }; + } + } + if (!response.ok) { + const code = typeof parsed.code === "string" ? parsed.code : `HTTP ${response.status}`; + const message = typeof parsed.message === "string" ? parsed.message : text; + throw new CliError(`${path} failed: ${code} ${message}`.trim()); + } + return { status: response.status, body: parsed }; + }, + }; +} + +async function safeText(response: Response): Promise<string> { + try { + return (await response.text()).trim(); + } catch { + return ""; + } +} + +// --------------------------------------------------------------------------- +// attach +// --------------------------------------------------------------------------- + +export interface ExecOptions { + cwd: string; +} + +export interface AttachOptions { + /** Directory to attach (defaults to `cwd`). */ + path?: string; + cwd?: string; + isTTY?: boolean; + exec?: (command: string, args: string[], options: ExecOptions) => void; + print?: (line: string) => void; + warn?: (line: string) => void; + client?: () => DaemonClient; +} + +/** Replace this process with nvim (stdio inherited). */ +export function execNvim(command: string, args: string[], options: ExecOptions): void { + const result = spawnSync(command, args, { stdio: "inherit", cwd: options.cwd }); + if (result.error !== undefined && result.error !== null) { + throw new CliError(`could not exec ${command}: ${result.error.message}`); + } + process.exit(result.status ?? 0); +} + +/** + * `pi2 attach`: if the workspace already has a managed instance with a UI + * socket, attach to it with `--remote-ui`; otherwise start a plain `nvim`. + * Never spawns a headless instance — the plugin registers itself. + */ +export async function runAttach(options: AttachOptions = {}): Promise<number> { + const cwd = options.cwd ?? process.cwd(); + const target = realpathOrSelf(options.path === undefined ? cwd : resolve(cwd, options.path)); + const exec = options.exec ?? execNvim; + const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`)); + const warn = options.warn ?? ((line: string) => process.stderr.write(`${line}\n`)); + const isTTY = options.isTTY ?? process.stdout.isTTY === true; + + const openPlainNvim = (): number => { + exec("nvim", [], { cwd: target }); + return 0; + }; + + const factory = options.client ?? (() => createClient()); + let client: DaemonClient; + try { + client = factory(); + } catch (error) { + // No daemon: nvim still works, the plugin just has nothing to dial. + warn(`pi2: ${errorMessage(error)}`); + return openPlainNvim(); + } + + let workspaces: WorkspaceInfo[]; + try { + workspaces = await client.get<WorkspaceInfo[]>("/api/v1/workspaces"); + } catch (error) { + warn(`pi2: ${errorMessage(error)}`); + return openPlainNvim(); + } + + const workspace = workspaces.find((candidate) => realpathOrSelf(candidate.cwd) === target); + const instance = workspace?.instance ?? null; + if (instance != null && instance.listenAddr !== null && instance.status !== "stopped" && instance.status !== "stopping") { + const args = ["--server", instance.listenAddr, "--remote-ui"]; + if (isTTY) { + exec("nvim", args, { cwd: target }); + } else { + print(`nvim ${args.join(" ")}`); + } + return 0; + } + + return openPlainNvim(); +} + +// --------------------------------------------------------------------------- +// status +// --------------------------------------------------------------------------- + +interface InfoBody { + v: number; + daemonId: string; + machineId: string; + platform: string; + capabilities: string[]; + limits: { maxBodyBytes: number; maxFrameBytes: number; maxConnections: number }; +} + +interface HealthBody { + ok: boolean; + items: { name: string; ok: boolean; detail: string }[]; +} + +export interface StatusOptions { + json?: boolean; + client: DaemonClient; + print?: (line: string) => void; +} + +export async function runStatus(options: StatusOptions): Promise<number> { + const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`)); + const client = options.client; + const [info, workspaces, resources, health] = await Promise.all([ + client.get<InfoBody>("/api/v1/info"), + client.get<WorkspaceInfo[]>("/api/v1/workspaces"), + client.get<InstanceResourcesSnapshot>("/api/v1/resources"), + client.get<HealthBody>("/api/v1/health"), + ]); + + const instances = workspaces + .filter((workspace) => workspace.instance != null) + .map((workspace) => ({ + workspaceId: workspace.workspaceId, + name: workspace.alias ?? workspace.name, + cwd: workspace.cwd, + status: workspace.instance?.status ?? "unknown", + hasUI: workspace.instance?.hasUI ?? false, + listenAddr: workspace.instance?.listenAddr ?? null, + nvimPid: workspace.instance?.nvimPid ?? null, + sessions: workspace.liveCount, + })); + + if (options.json === true) { + print( + JSON.stringify( + { + daemon: { url: client.baseUrl, ...info }, + instances, + resources, + health, + }, + null, + 2, + ), + ); + return health.ok ? 0 : 1; + } + + print(`daemon ${client.baseUrl} id ${info.daemonId} v${info.v} ${info.platform}`); + print(`machine ${info.machineId} capabilities ${info.capabilities.join(",")}`); + print(""); + + if (instances.length === 0) { + print("instances (none — open nvim in a workspace to register one)"); + } else { + print( + formatTable( + ["workspace", "cwd", "status", "ui", "sessions", "pid"], + instances.map((instance) => [ + instance.name, + instance.cwd, + instance.status, + instance.hasUI ? "yes" : "no", + String(instance.sessions), + instance.nvimPid === null ? "-" : String(instance.nvimPid), + ]), + ), + ); + } + print(""); + + const rss = `${formatBytes(resources.totalRssBytes)} of ${formatBytes(resources.physicalMemoryBytes)}`; + print(`resources ${resources.instances.length} instance(s), rss ${rss}${resources.warn ? ` WARN: ${resources.reason ?? ""}` : ""}`); + print( + `health ${health.ok ? "ok" : "degraded"} ${health.items + .map((item) => `${item.name}=${item.ok ? "ok" : "FAIL"}`) + .join(" ")}`, + ); + return health.ok ? 0 : 1; +} + +// --------------------------------------------------------------------------- +// pairing +// --------------------------------------------------------------------------- + +export interface PairingOptions { + client: DaemonClient; + print?: (line: string) => void; +} + +export async function runPairing(options: PairingOptions): Promise<number> { + const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`)); + const result = await options.client.post("/api/v1/pair", {}); + const code = typeof result.body.code === "string" ? result.body.code : undefined; + if (code === undefined) throw new CliError("pairing failed: daemon returned no code"); + const expiresAt = typeof result.body.expiresAt === "number" ? result.body.expiresAt : undefined; + const nonce = typeof result.body.nonce === "string" ? result.body.nonce : undefined; + // Rebuild the URL from the *actual* base URL: the daemon's own `url` field is + // derived from the configured port, which is stale after a retry or `--port 0`. + const url = `${options.client.baseUrl}/pair/${code}`; + const payload = JSON.stringify({ v: PROTOCOL_VERSION, code, url, ...(expiresAt === undefined ? {} : { expiresAt }), ...(nonce === undefined ? {} : { nonce }) }); + + print(`url ${url}`); + print(`code ${code}`); + if (expiresAt !== undefined) { + print(`expires ${new Date(expiresAt).toISOString()} (${Math.max(0, Math.round((expiresAt - Date.now()) / 1000))}s)`); + } + print(`qr ${payload}`); + return 0; +} + +// --------------------------------------------------------------------------- +// doctor +// --------------------------------------------------------------------------- + +/** `pi2 doctor`: real probes, plus the live daemon when one is running. */ +export async function runDoctorCommand( + options: { runtime?: string; client?: () => DaemonClient } = {}, +): Promise<DoctorReport> { + const runtime = options.runtime; + return diagnose({ + ...(runtime === undefined ? {} : { runtime }), + daemonInfo: async () => { + try { + const client = options.client?.() ?? createClient({ ...(runtime === undefined ? {} : { runtime }) }); + const info = await client.get<{ v: number }>("/api/v1/info"); + return { port: client.daemon.port, protocolVersion: info.v }; + } catch (error) { + return { error: error instanceof CliError ? error.message : errorMessage(error) }; + } + }, + }); +} + +// --------------------------------------------------------------------------- +// install-service / uninstall-service +// --------------------------------------------------------------------------- +export interface ServiceCommandOptions { + platform: ServicePlatform; + paths: ServicePaths; + write: boolean; + print?: (line: string) => void; + writeFile?: (path: string, content: string) => void; + removeFile?: (path: string) => void; +} + +function defaultWriteFile(path: string, content: string): void { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content, { mode: 0o644 }); +} + +function defaultRemoveFile(path: string): void { + rmSync(path, { force: true }); +} + +export function runInstallService(options: ServiceCommandOptions): number { + const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`)); + const service = renderService(options.platform, options.paths); + + if (!options.write) { + print(service.content); + print(`# dry-run: would write ${service.path} (mode 0644)`); + print(`# then run:\n${service.commands.map((command) => `# ${command}`).join("\n")}`); + return 0; + } + + (options.writeFile ?? defaultWriteFile)(service.path, service.content); + print(`wrote ${service.path} (mode 0644)`); + print("enable it with:"); + for (const command of service.commands) print(` ${command}`); + return 0; +} + +export function runUninstallService(options: ServiceCommandOptions): number { + const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`)); + const service: RenderedService = renderService(options.platform, options.paths); + + if (!options.write) { + print(`# dry-run: would remove ${service.path}`); + print(`# then run:\n${service.removeCommands.map((command) => `# ${command}`).join("\n")}`); + return 0; + } + + (options.removeFile ?? defaultRemoveFile)(service.path); + print(`removed ${service.path}`); + print("finish with:"); + for (const command of service.removeCommands) print(` ${command}`); + return 0; +} + +// --------------------------------------------------------------------------- +// main +// --------------------------------------------------------------------------- + +export interface Pi2Options { + out?: (line: string) => void; + err?: (line: string) => void; + client?: () => DaemonClient; + exec?: (command: string, args: string[], options: ExecOptions) => void; + cwd?: string; + isTTY?: boolean; + doctor?: () => Promise<DoctorReport>; + servicePaths?: ServicePaths; + platform?: ServicePlatform; + writeFile?: (path: string, content: string) => void; + removeFile?: (path: string) => void; + runtime?: string; +} + +export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> { + const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`)); + const err = options.err ?? ((line: string) => process.stderr.write(`${line}\n`)); + const [command, ...rest] = argv; + + if (command === undefined || command === "help" || command === "--help" || command === "-h") { + out(USAGE); + return 0; + } + if (command === "--version" || command === "-V" || command === "version") { + out(`pi2 ${packageVersion()}`); + return 0; + } + + try { + switch (command) { + case "attach": { + const parsed = parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } }); + if (boolFlag(parsed.flags, "--help")) { + out(USAGE); + return 0; + } + if (parsed.positionals.length > 1) throw new UsageError("attach takes at most one path"); + return await runAttach({ + ...(parsed.positionals[0] === undefined ? {} : { path: parsed.positionals[0] }), + ...(options.cwd === undefined ? {} : { cwd: options.cwd }), + ...(options.isTTY === undefined ? {} : { isTTY: options.isTTY }), + ...(options.exec === undefined ? {} : { exec: options.exec }), + ...(options.client === undefined ? {} : { client: options.client }), + print: out, + warn: err, + }); + } + case "status": { + const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } }); + if (boolFlag(parsed.flags, "--help")) { + out(USAGE); + return 0; + } + const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))(); + return await runStatus({ client, json: boolFlag(parsed.flags, "--json"), print: out }); + } + case "doctor": { + const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } }); + if (boolFlag(parsed.flags, "--help")) { + out(USAGE); + return 0; + } + const report = await (options.doctor ?? (() => runDoctorCommand(options)))(); + out(boolFlag(parsed.flags, "--json") ? reportToJson(report) : formatReport(report)); + return report.ok ? 0 : 1; + } + case "pairing": + case "pair": { + parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } }); + const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))(); + return await runPairing({ client, print: out }); + } + case "install-service": + case "uninstall-service": { + const parsed = parseArgs(rest, { booleans: ["--dry-run", "--write", "--help"], aliases: { "-h": "--help" } }); + if (boolFlag(parsed.flags, "--help")) { + out(USAGE); + return 0; + } + const platform = options.platform ?? (osPlatform() === "darwin" ? "darwin" : "linux"); + const paths = options.servicePaths ?? defaultServicePaths(); + const serviceOptions: ServiceCommandOptions = { + platform, + paths, + write: boolFlag(parsed.flags, "--write"), + print: out, + ...(options.writeFile === undefined ? {} : { writeFile: options.writeFile }), + ...(options.removeFile === undefined ? {} : { removeFile: options.removeFile }), + }; + return command === "install-service" ? runInstallService(serviceOptions) : runUninstallService(serviceOptions); + } + default: + err(`pi2: unknown command "${command}"`); + err(USAGE); + return 2; + } + } catch (error) { + if (error instanceof UsageError) { + err(`pi2: ${error.message}`); + err(error.usage ?? USAGE); + return 2; + } + if (error instanceof CliError) { + err(`pi2: ${error.message}`); + return error.code; + } + err(`pi2: ${errorMessage(error)}`); + return 1; + } +} + +function isDirectRun(): boolean { + const entry = process.argv[1]; + if (entry === undefined) return false; + try { + return realpathOrSelf(entry) === realpathOrSelf(fileURLToPath(import.meta.url)); + } catch { + return false; + } +} + +if (isDirectRun()) { + void main(process.argv.slice(2)).then( + (code) => { + if (code !== 0) process.exitCode = code; + }, + (error: unknown) => { + process.stderr.write(`pi2: ${errorMessage(error)}\n`); + process.exitCode = 1; + }, + ); +} + +/** Exposed so `service.test.ts` can check the same rendering the command uses. */ +export { renderService, serviceDir }; diff --git a/src/cli/pi2d.ts b/src/cli/pi2d.ts new file mode 100644 index 0000000..c3ce61b --- /dev/null +++ b/src/cli/pi2d.ts @@ -0,0 +1,262 @@ +#!/usr/bin/env node +/** + * `pi2d` — the pi2 daemon entry point. + * + * Responsibilities (and nothing else): + * 1. parse args / apply `--port|--host|--static-dir` to the config env + * 2. mint `<runtime>/cli.token` (32-byte hex, 0600) for local CLI access + * 3. take the singleton lock (`<runtime>/daemon.lock`, stale-aware, `--force`) + * 4. wire the real dependencies and listen (port 0 allowed, +1..+9 on a busy + * default port), then publish `<runtime>/daemon.json` + * 5. print exactly one line: `pi2d listening on http://host:port` + * 6. on SIGINT/SIGTERM close http + the plugin socket and release the lock — + * **without** stopping nvim instances (they reconnect on the next start) + */ +import { randomUUID } from "node:crypto"; +import { fileURLToPath } from "node:url"; +import { loadConfig, DEFAULT_PORT, type Config } from "../config.js"; +import { ensureDir, runtimeDir } from "../core/paths.js"; +import type { Logger } from "../core/interfaces.js"; +import { PROTOCOL_VERSION } from "../protocol/types.js"; +import { createLogger } from "./logger.js"; +import { acquireLock, writeDaemonJson, type DaemonLockHandle } from "./lock.js"; +import { cliTokenPath, writeCliToken } from "./token.js"; +import { + boolFlag, + errorMessage, + packageVersion, + parseArgs, + realpathOrSelf, + stringFlag, + UsageError, +} from "./util.js"; +import { wireDaemon, type WiredDaemon } from "./wiring.js"; + +/** Extra attempts when the *default* port is taken (7676 → 7677 … 7685). */ +export const DEFAULT_PORT_RETRIES = 9; + +export const USAGE = `pi2d — pi2 daemon + +Usage: pi2d [options] + +Options: + --port <n> TCP port (default ${DEFAULT_PORT}; 0 = ephemeral) + --host <addr> bind address (default 127.0.0.1) + --static-dir <p> built web UI (default <repo>/web/dist) + --force override a live daemon.lock + --foreground stay in the foreground (default; kept for unit files) + --version print the version and exit + --help print this help and exit + +Environment: + PI2_PORT, PI2_HOST, PI2_STATIC_DIR, PI2_ORIGINS, PI2_RUNTIME_DIR, + PI2_DATA_DIR, PI2_STATE_DIR, PI2_LOG_LEVEL, PI2_WORKSPACE_ROOTS + +Runtime files ($PI2_RUNTIME_DIR): + d.sock plugin unix socket (nvim → daemon) + d.sock.token plugin handshake token + daemon.lock singleton lock (pid + bootId) + daemon.json discovery file for the pi2 CLI / tools + cli.token local admin token for the pi2 CLI + +See docs/deployment.md.`; + +export interface DaemonArgs { + port?: number; + host?: string; + staticDir?: string; + force: boolean; + foreground: boolean; + help: boolean; + version: boolean; +} + +export function parseDaemonArgs(argv: readonly string[]): DaemonArgs { + const { flags, positionals } = parseArgs(argv, { + values: ["--port", "--host", "--static-dir"], + booleans: ["--force", "--foreground", "--help", "--version"], + aliases: { "-h": "--help", "-V": "--version", "-p": "--port", "-f": "--force" }, + }); + if (positionals.length > 0) { + throw new UsageError(`unexpected argument ${positionals[0]}`, USAGE); + } + + const args: DaemonArgs = { + force: boolFlag(flags, "--force"), + foreground: boolFlag(flags, "--foreground"), + help: boolFlag(flags, "--help"), + version: boolFlag(flags, "--version"), + }; + + const port = stringFlag(flags, "--port"); + if (port !== undefined) { + if (!/^\d+$/.test(port.trim())) throw new UsageError(`--port must be an integer, got "${port}"`, USAGE); + const value = Number(port); + if (!Number.isSafeInteger(value) || value < 0 || value > 65535) { + throw new UsageError(`--port must be between 0 and 65535, got "${port}"`, USAGE); + } + args.port = value; + } + const host = stringFlag(flags, "--host"); + if (host !== undefined) args.host = host; + const staticDir = stringFlag(flags, "--static-dir"); + if (staticDir !== undefined) args.staticDir = staticDir; + + return args; +} + +export interface CliIo { + out(line: string): void; + err(line: string): void; +} + +function defaultIo(): CliIo { + return { + out: (line) => process.stdout.write(`${line}\n`), + err: (line) => process.stderr.write(`${line}\n`), + }; +} + +export interface RunDaemonOptions { + out?: (line: string) => void; + err?: (line: string) => void; + logger?: Logger; +} + +/** + * Start the daemon. Resolves `0` once the server is listening (the process then + * stays alive) and `1`/`2` on failure — the caller decides whether to exit. + */ +export async function main(argv: readonly string[], ioOptions: RunDaemonOptions = {}): Promise<number> { + const defaults = defaultIo(); + const io: CliIo = { out: ioOptions.out ?? defaults.out, err: ioOptions.err ?? defaults.err }; + const options = ioOptions; + let args: DaemonArgs; + try { + args = parseDaemonArgs(argv); + } catch (error) { + if (error instanceof UsageError) { + io.err(`pi2d: ${error.message}`); + io.err(error.usage ?? USAGE); + return 2; + } + throw error; + } + + if (args.help) { + io.out(USAGE); + return 0; + } + if (args.version) { + io.out(`pi2d ${packageVersion()}`); + return 0; + } + + // The daemon process is the single consumer of these values; child nvim + // instances then inherit a consistent environment. + if (args.port !== undefined) process.env.PI2_PORT = String(args.port); + if (args.host !== undefined) process.env.PI2_HOST = args.host; + if (args.staticDir !== undefined) process.env.PI2_STATIC_DIR = args.staticDir; + + const portIsDefault = args.port === undefined && (process.env.PI2_PORT ?? "").trim() === ""; + const logger = options.logger ?? createLogger(); + + let config: Config; + try { + config = loadConfig(); + } catch (error) { + io.err(`pi2d: ${errorMessage(error)}`); + return 1; + } + + let lock: DaemonLockHandle | undefined; + let wired: WiredDaemon | undefined; + let server: Awaited<ReturnType<WiredDaemon["start"]>> | undefined; + let stopping = false; + + try { + const runtime = runtimeDir(); + ensureDir(runtime, 0o700); + writeCliToken(cliTokenPath(runtime)); + + const daemonId = `d-${randomUUID()}`; + lock = acquireLock({ + force: args.force, + payload: { + port: config.port, + daemonId, + startedAt: Date.now(), + protocolVersion: PROTOCOL_VERSION, + }, + }); + + wired = await wireDaemon({ config, runtime, logger, daemonId }); + server = await wired.start({ + retries: portIsDefault ? DEFAULT_PORT_RETRIES : 0, + onRetry: (info) => logger.warn("port busy, trying next", { from: info.from, to: info.to }), + }); + + lock.update({ port: server.port }); + writeDaemonJson(lock.lock); + // One machine-readable line; every log record goes to stderr. + io.out(`pi2d listening on ${server.url}`); + } catch (error) { + io.err(`pi2d: ${errorMessage(error)}`); + lock?.release(); + if (wired !== undefined) await wired.close().catch(() => undefined); + return 1; + } + + const shutdown = async (signal: string): Promise<void> => { + if (stopping) return; + stopping = true; + logger.info("shutting down", { signal }); + try { + if (server !== undefined) await server.close(); + } catch (error) { + logger.warn("http close failed", { error: errorMessage(error) }); + } + try { + // Only the plugin socket: managed nvim instances must survive a + // daemon restart and reconnect on the next start (protocol §5). + await wired?.instanceManager.pluginServer.close(); + } catch (error) { + logger.warn("plugin socket close failed", { error: errorMessage(error) }); + } + lock?.release(); + process.exit(0); + }; + + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) { + process.once(signal, () => { + void shutdown(signal).catch((error: unknown) => { + io.err(`pi2d: shutdown failed: ${errorMessage(error)}`); + process.exit(1); + }); + }); + } + + return 0; +} + +function isDirectRun(): boolean { + const entry = process.argv[1]; + if (entry === undefined) return false; + try { + return realpathOrSelf(entry) === realpathOrSelf(fileURLToPath(import.meta.url)); + } catch { + return false; + } +} + +if (isDirectRun()) { + void main(process.argv.slice(2)).then( + (code) => { + if (code !== 0) process.exitCode = code; + }, + (error: unknown) => { + process.stderr.write(`pi2d: ${errorMessage(error)}\n`); + process.exitCode = 1; + }, + ); +} diff --git a/src/cli/service.ts b/src/cli/service.ts new file mode 100644 index 0000000..6b28460 --- /dev/null +++ b/src/cli/service.ts @@ -0,0 +1,187 @@ +/** + * Service file rendering for `pi2 install-service` / `uninstall-service`. + * + * Pure string generation: nothing here executes a command. `--dry-run` prints + * the rendered file, `--write` writes it (0644) and prints the enable/load + * commands for the user to run — the CLI never talks to systemd or launchd. + */ +import { fileURLToPath } from "node:url"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { stateDir } from "../core/paths.js"; + +export type ServicePlatform = "linux" | "darwin"; + +export interface ServicePaths { + /** Absolute node binary (`process.execPath`). */ + nodePath: string; + /** Absolute path to `dist/cli/pi2d.js`. */ + scriptPath: string; + /** Where logs go (plist StandardOut/ErrPath). */ + stateDir: string; + /** Home dir; the unit file lives under it. */ + homeDir: string; + /** `XDG_CONFIG_HOME` override for the systemd user dir. */ + configHome?: string; + /** PATH the service should see (defaults to `process.env.PATH`). */ + pathEnv?: string; + /** Extra `Environment=` entries (e.g. `{PI2_PORT: "7676"}`). */ + env?: Record<string, string>; +} + +export interface RenderedService { + /** `pi2d.service` on Linux, `com.pi2.pi2d.plist` on macOS. */ + name: string; + /** Absolute install path. */ + path: string; + content: string; + /** Commands the user must run (printed, never executed). */ + commands: string[]; + /** Commands that undo the install (printed on uninstall). */ + removeCommands: string[]; +} + +export const SYSTEMD_UNIT_NAME = "pi2d.service"; +export const LAUNCHD_LABEL = "com.pi2.pi2d"; +export const LAUNCHD_PLIST_NAME = `${LAUNCHD_LABEL}.plist`; + +/** `<repo>/dist/cli/pi2d.js`, resolved from either `src/cli/` or `dist/cli/`. */ +export function defaultScriptPath(): string { + return fileURLToPath(new URL("../../dist/cli/pi2d.js", import.meta.url)); +} + +export function defaultServicePaths(overrides: Partial<ServicePaths> = {}): ServicePaths { + return { + nodePath: process.execPath, + scriptPath: defaultScriptPath(), + stateDir: stateDir(), + homeDir: homedir(), + ...(process.env.XDG_CONFIG_HOME === undefined ? {} : { configHome: process.env.XDG_CONFIG_HOME }), + pathEnv: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", + ...overrides, + }; +} + +export function systemdUserDir(paths: ServicePaths): string { + const configHome = paths.configHome ?? join(paths.homeDir, ".config"); + return join(configHome, "systemd", "user"); +} + +export function launchAgentDir(paths: ServicePaths): string { + return join(paths.homeDir, "Library", "LaunchAgents"); +} + +function systemdQuote(value: string): string { + if (/[\s"'\\]/.test(value)) return `"${value.replace(/(["\\])/g, "\\$1")}"`; + return value; +} + +function xmlEscape(value: string): string { + return value + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function environmentEntries(paths: ServicePaths): [string, string][] { + const entries: [string, string][] = []; + if (paths.pathEnv !== undefined && paths.pathEnv !== "") entries.push(["PATH", paths.pathEnv]); + for (const [key, value] of Object.entries(paths.env ?? {})) entries.push([key, value]); + return entries; +} + +export function renderSystemdUnit(paths: ServicePaths): string { + const env = environmentEntries(paths).map(([key, value]) => `Environment=${key}=${systemdQuote(value)}`); + return [ + "[Unit]", + "Description=pi2 daemon (pi2d)", + "After=network.target", + "", + "[Service]", + "Type=simple", + `ExecStart=${systemdQuote(paths.nodePath)} ${systemdQuote(paths.scriptPath)} --foreground`, + ...env, + "Restart=on-failure", + "RestartSec=2", + "KillSignal=SIGTERM", + "TimeoutStopSec=15", + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"); +} + +export function renderLaunchAgent(paths: ServicePaths): string { + const env = environmentEntries(paths); + const envBlock = + env.length === 0 + ? [] + : [ + " <key>EnvironmentVariables</key>", + " <dict>", + ...env.flatMap(([key, value]) => [ + ` <key>${xmlEscape(key)}</key>`, + ` <string>${xmlEscape(value)}</string>`, + ]), + " </dict>", + ]; + return [ + '<?xml version="1.0" encoding="UTF-8"?>', + '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">', + '<plist version="1.0">', + "<dict>", + ` <key>Label</key>`, + ` <string>${LAUNCHD_LABEL}</string>`, + " <key>ProgramArguments</key>", + " <array>", + ` <string>${xmlEscape(paths.nodePath)}</string>`, + ` <string>${xmlEscape(paths.scriptPath)}</string>`, + " <string>--foreground</string>", + " </array>", + ...envBlock, + " <key>RunAtLoad</key>", + " <true/>", + " <key>KeepAlive</key>", + " <true/>", + " <key>StandardOutPath</key>", + ` <string>${xmlEscape(join(paths.stateDir, "pi2d.log"))}</string>`, + " <key>StandardErrorPath</key>", + ` <string>${xmlEscape(join(paths.stateDir, "pi2d.err.log"))}</string>`, + "</dict>", + "</plist>", + "", + ].join("\n"); +} + +export function renderService(platform: ServicePlatform, paths: ServicePaths): RenderedService { + if (platform === "darwin") { + const target = join(launchAgentDir(paths), LAUNCHD_PLIST_NAME); + return { + name: LAUNCHD_PLIST_NAME, + path: target, + content: renderLaunchAgent(paths), + commands: [ + `launchctl bootstrap gui/$(id -u) ${target}`, + `launchctl enable gui/$(id -u)/${LAUNCHD_LABEL}`, + `launchctl kickstart -k gui/$(id -u)/${LAUNCHD_LABEL}`, + ], + removeCommands: [`launchctl bootout gui/$(id -u)/${LAUNCHD_LABEL}`, `rm -f ${target}`], + }; + } + const target = join(systemdUserDir(paths), SYSTEMD_UNIT_NAME); + return { + name: SYSTEMD_UNIT_NAME, + path: target, + content: renderSystemdUnit(paths), + commands: ["systemctl --user daemon-reload", `systemctl --user enable --now ${SYSTEMD_UNIT_NAME}`], + removeCommands: [`systemctl --user disable --now ${SYSTEMD_UNIT_NAME}`, `rm -f ${target}`], + }; +} + +/** Directory that must exist before writing the file. */ +export function serviceDir(service: RenderedService): string { + return dirname(service.path); +} diff --git a/src/cli/token.ts b/src/cli/token.ts new file mode 100644 index 0000000..7c96f25 --- /dev/null +++ b/src/cli/token.ts @@ -0,0 +1,54 @@ +/** + * The local CLI token (`<runtime>/cli.token`). + * + * `pi2d` mints a fresh 32-byte hex token on every start and writes it 0600. + * `AuthStore` accepts it as the synthetic `local-cli` admin device, so every + * local `pi2*` command can talk to the daemon without pairing. The token is + * per-daemon-lifetime: restarting `pi2d` rotates it. + */ +import { randomBytes } from "node:crypto"; +import { chmodSync, existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { ensureDir, runtimeDir } from "../core/paths.js"; +import { CLI_TOKEN_FILE } from "./wiring.js"; + +export const CLI_TOKEN_BYTES = 32; + +export function cliTokenPath(runtime: string = runtimeDir()): string { + return join(runtime, CLI_TOKEN_FILE); +} + +/** Mint a fresh token and write it atomically (mode 0600). */ +export function writeCliToken(path: string = cliTokenPath()): string { + const token = randomBytes(CLI_TOKEN_BYTES).toString("hex"); + ensureDir(dirname(path), 0o700); + const temporary = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + writeFileSync(temporary, `${token}\n`, { mode: 0o600 }); + chmodSync(temporary, 0o600); + renameSync(temporary, path); + chmodSync(path, 0o600); + return token; +} + +export function readCliToken(path: string = cliTokenPath()): string | undefined { + try { + const value = readFileSync(path, "utf8").trim(); + return value === "" ? undefined : value; + } catch { + return undefined; + } +} + +export interface TokenPerms { + exists: boolean; + mode: number | undefined; +} + +export function tokenPerms(path: string = cliTokenPath()): TokenPerms { + if (!existsSync(path)) return { exists: false, mode: undefined }; + try { + return { exists: true, mode: statSync(path).mode & 0o777 }; + } catch { + return { exists: false, mode: undefined }; + } +} diff --git a/src/cli/util.ts b/src/cli/util.ts new file mode 100644 index 0000000..e4b47b3 --- /dev/null +++ b/src/cli/util.ts @@ -0,0 +1,151 @@ +/** Small shared helpers for the `pi2` / `pi2d` command line front ends. */ +import { readFileSync, realpathSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +/** Bad arguments; the CLI prints the usage block and exits 2. */ +export class UsageError extends Error { + readonly usage: string | undefined; + + constructor(message: string, usage?: string) { + super(message); + this.name = "UsageError"; + this.usage = usage; + } +} + +export type FlagValue = string | boolean; + +export interface FlagSpec { + /** Flags that take a value (`--port 7676` or `--port=7676`). */ + values?: readonly string[]; + /** Flags that do not (`--force`). */ + booleans?: readonly string[]; + /** Short aliases: `{ "-h": "--help" }`. */ + aliases?: Readonly<Record<string, string>>; +} + +export interface ParsedArgs { + positionals: string[]; + flags: Record<string, FlagValue>; +} + +export function parseArgs(argv: readonly string[], spec: FlagSpec = {}): ParsedArgs { + const values = new Set(spec.values ?? []); + const booleans = new Set(spec.booleans ?? []); + const aliases = spec.aliases ?? {}; + const flags: Record<string, FlagValue> = {}; + const positionals: string[] = []; + + for (let index = 0; index < argv.length; index += 1) { + const raw = argv[index]!; + if (raw === "--") { + positionals.push(...argv.slice(index + 1)); + break; + } + if (!raw.startsWith("-") || raw === "-") { + positionals.push(raw); + continue; + } + const [head, inline] = splitFlag(raw); + const name = aliases[head] ?? head; + if (booleans.has(name)) { + if (inline !== undefined) throw new UsageError(`${name} does not take a value`); + flags[name] = true; + continue; + } + if (values.has(name)) { + if (inline !== undefined) { + flags[name] = inline; + continue; + } + const next = argv[index + 1]; + if (next === undefined || (next.startsWith("-") && next !== "-")) { + throw new UsageError(`${name} requires a value`); + } + flags[name] = next; + index += 1; + continue; + } + throw new UsageError(`unknown option ${head}`); + } + + return { positionals, flags }; +} + +function splitFlag(raw: string): [string, string | undefined] { + const equals = raw.indexOf("="); + if (equals === -1) return [raw, undefined]; + return [raw.slice(0, equals), raw.slice(equals + 1)]; +} + +export function stringFlag(flags: Record<string, FlagValue>, name: string): string | undefined { + const value = flags[name]; + return typeof value === "string" ? value : undefined; +} + +export function boolFlag(flags: Record<string, FlagValue>, name: string): boolean { + return flags[name] === true; +} + +/** Version of the installed package (`dist/cli/*` sits two levels below it). */ +export function packageVersion(): string { + try { + const file = fileURLToPath(new URL("../../package.json", import.meta.url)); + const parsed = JSON.parse(readFileSync(file, "utf8")) as { version?: unknown }; + return typeof parsed.version === "string" ? parsed.version : "0.0.0"; + } catch { + return "0.0.0"; + } +} + +export function realpathOrSelf(path: string): string { + try { + return realpathSync(path); + } catch { + return path; + } +} + +/** Fixed-width text table; the last column is never padded. */ +export function formatTable(header: readonly string[], rows: readonly (readonly string[])[]): string { + const widths = header.map((cell, column) => + Math.max(cell.length, ...rows.map((row) => (row[column] ?? "").length)), + ); + const line = (cells: readonly string[]): string => + cells + .map((cell, column) => (column === cells.length - 1 ? cell : cell.padEnd(widths[column] ?? 0))) + .join(" ") + .trimEnd(); + return [line(header), line(header.map((_, column) => "-".repeat(widths[column] ?? 0))), ...rows.map(line)].join( + "\n", + ); +} + +/** `1234567` → `1.2 MiB`. */ +export function formatBytes(bytes: number | null | undefined): string { + if (bytes === null || bytes === undefined || !Number.isFinite(bytes)) return "-"; + const units = ["B", "KiB", "MiB", "GiB", "TiB"]; + let value = bytes; + let unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit += 1; + } + return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`; +} + +export function formatDuration(ms: number | null | undefined): string { + if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return "-"; + const seconds = Math.floor(ms / 1000); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}m${seconds % 60}s`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}h${minutes % 60}m`; + return `${Math.floor(hours / 24)}d${hours % 24}h`; +} + +export function errorMessage(error: unknown): string { + if (error instanceof Error) return error.message; + return String(error); +} diff --git a/src/cli/wiring.ts b/src/cli/wiring.ts new file mode 100644 index 0000000..88c245c --- /dev/null +++ b/src/cli/wiring.ts @@ -0,0 +1,189 @@ +/** + * Composition root: the real dependency graph behind `pi2d`. + * + * Everything the daemon serves is assembled here so that the CLI entry point + * only has to deal with process concerns (args, lock, signals, daemon.json): + * + * config -> `loadConfig()` (env driven, see docs/deployment.md) + * bus -> `InMemoryBus` (WS/SSE fan-out) + * auth -> `AuthStore` over `<dataDir>/devices.json` + `<runtime>/cli.token` + * workspaces -> `createWorkspaceStore({ discovery, registry, instances })` + * instances -> `createInstanceManager()` (starts the plugin unix socket itself) + * http/ws -> `startServer(config, deps)` + */ +import { randomUUID } from "node:crypto"; +import { join } from "node:path"; +import { loadConfig, type Config, type ConfigEnv } from "../config.js"; +import { dataDir, daemonSocketPath, daemonTokenPath, runtimeDir, stateDir } from "../core/paths.js"; +import type { Logger } from "../core/interfaces.js"; +import { AuthStore } from "../daemon/auth.js"; +import { InMemoryBus } from "../daemon/hub.js"; +import { startServer, type ServerDeps, type StartedServer } from "../daemon/server.js"; +import { createInstanceManager, type InstanceManagerHandle } from "../instances/index.js"; +import { createDiscovery, createWorkspaceStore, WorkspaceRegistry, type WorkspaceStoreHandle } from "../workspaces/index.js"; +import { listenWithRetry, type ListenOptions } from "./listen.js"; + +/** File name of the local CLI token inside the runtime dir. */ +export const CLI_TOKEN_FILE = "cli.token"; + +export interface WireOptions { + /** Environment used for `loadConfig`; defaults to `process.env`. */ + env?: ConfigEnv; + /** Direct config overrides, applied after the environment. */ + config?: Partial<Config>; + logger?: Logger; + daemonId?: string; + machineId?: string; + /** Runtime dir for the plugin socket + CLI token; defaults to `runtimeDir()`. */ + runtime?: string; + /** Instance log dir; defaults to `<stateDir>/instances`. */ + logDir?: string; + /** Workspace registry file; defaults to `<dataDir>/workspaces.json`. */ + registryPath?: string; + /** Discovery override (`sessionsRoot()` by default). */ + discoveryRoot?: string; + nvimBin?: string; + nvimInit?: string; + now?: () => number; + /** Extra `ServerDeps` (heartbeat/ws overrides) for tests. */ + server?: Pick<ServerDeps, "heartbeatMs" | "ws">; +} + +export interface WiredDaemon { + /** Effective config; `config.port` is updated by `start()` to the bound port. */ + config: Config; + deps: ServerDeps; + instanceManager: InstanceManagerHandle; + workspaceStore: WorkspaceStoreHandle; + auth: AuthStore; + bus: InMemoryBus; + /** The http+ws server, once `start()` succeeded. */ + server: StartedServer | undefined; + /** `<runtime>/cli.token` — the local admin token for this daemon. */ + cliTokenPath: string; + runtime: string; + /** Start http+ws (idempotent). `options` is passed to `listenWithRetry`. */ + start(options?: ListenOptions): Promise<StartedServer>; + /** Close the http server (if started) and the instance layer. */ + close(): Promise<void>; +} + +function machineIdFor(host: string): string { + // Stable per host so browsers grouped by machine survive daemon restarts. + let hash = 0; + for (let i = 0; i < host.length; i += 1) hash = (hash * 31 + host.charCodeAt(i)) >>> 0; + return `m-${hash.toString(16).padStart(8, "0")}`; +} + +export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon> { + const env = options.env ?? process.env; + const now = options.now ?? Date.now; + const runtime = options.runtime ?? runtimeDir(); + const daemonId = options.daemonId ?? `d-${randomUUID()}`; + + const base = loadConfig(env); + const config: Config = { + ...base, + ...options.config, + limits: { ...base.limits, ...(options.config?.limits ?? {}) }, + corsOrigins: options.config?.corsOrigins ?? base.corsOrigins, + }; + + const bus = new InMemoryBus(options.logger === undefined ? {} : { logger: options.logger }); + const cliTokenPath = join(runtime, CLI_TOKEN_FILE); + const auth = new AuthStore({ + path: config.deviceStorePath, + baseUrl: `http://${config.host}:${config.port}`, + localTokenPath: cliTokenPath, + ...(options.now === undefined ? {} : { now: options.now }), + }); + + // `resolveCwd` needs the store, and the store needs the manager: keep one + // late-bound reference instead of duplicating the registry lookup. + let workspaceStore: WorkspaceStoreHandle | undefined; + const instanceManager = await createInstanceManager({ + bus, + ...(options.logger === undefined ? {} : { logger: options.logger }), + daemonId, + now, + socketPath: daemonSocketPath(), + tokenPath: daemonTokenPath(), + runtime, + logDir: options.logDir ?? join(stateDir(), "instances"), + ...(options.nvimBin === undefined ? {} : { nvimBin: options.nvimBin }), + ...(options.nvimInit === undefined ? {} : { nvimInit: options.nvimInit }), + resolveCwd: (workspaceId: string): string | undefined => { + const workspace = workspaceStore?.get(workspaceId); + if (workspace === undefined) return undefined; + return workspace.cwd; + }, + }); + + const discovery = createDiscovery({ + ...(options.discoveryRoot === undefined ? {} : { root: options.discoveryRoot }), + ...(options.logger === undefined ? {} : { logger: options.logger }), + }); + const registry = new WorkspaceRegistry({ + filePath: options.registryPath ?? join(dataDir(), "workspaces.json"), + ...(options.logger === undefined ? {} : { logger: options.logger }), + }); + workspaceStore = createWorkspaceStore({ + discovery, + registry, + instances: instanceManager, + ...(options.logger === undefined ? {} : { logger: options.logger }), + }); + + const startedAt = now(); + const deps: ServerDeps = { + auth, + instances: instanceManager, + workspaces: workspaceStore, + bus, + ...(options.logger === undefined ? {} : { logger: options.logger }), + daemonId, + machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"), + startedAt, + now, + ...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }), + ...(options.server?.ws === undefined ? {} : { ws: options.server.ws }), + }; + + let server: StartedServer | undefined; + let closing: Promise<void> | undefined; + + const wired: WiredDaemon = { + config, + deps, + instanceManager, + workspaceStore, + auth, + bus, + server, + cliTokenPath, + runtime, + async start(listenOptions: ListenOptions = {}): Promise<StartedServer> { + if (server !== undefined) return server; + server = await listenWithRetry(wired.config, deps, listenOptions); + wired.server = server; + wired.config = server.config; + return server; + }, + async close(): Promise<void> { + if (closing !== undefined) return closing; + closing = (async () => { + const current = wired.server; + if (current !== undefined) await current.close(); + // `instanceManager.close()` also stops the plugin socket server; + // the CLI's SIGTERM path closes the socket without killing nvim. + await instanceManager.close(); + })(); + return closing; + }, + }; + + return wired; +} + +export { startServer }; +export type { StartedServer }; diff --git a/src/daemon/auth.ts b/src/daemon/auth.ts index a03e163..645fe97 100644 --- a/src/daemon/auth.ts +++ b/src/daemon/auth.ts @@ -3,6 +3,10 @@ * * Tokens are bearer credentials for the HTTP/WS surfaces. Only a SHA-256 hash * is persisted, in `$PI2_DATA_DIR/devices.json` (mode 0600, atomic replace). + * + * A second, non-persisted credential exists for local tooling: the CLI token in + * `<runtime>/cli.token` (written by `pi2d`). It authenticates as the synthetic + * `local-cli` device with every scope; see `docs/deployment.md` §7. */ import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; @@ -62,6 +66,23 @@ export interface AuthStoreOptions { baseUrl?: string; /** `touchDevice` write throttle. */ touchIntervalMs?: number; + /** + * File holding the local CLI token (`<runtime>/cli.token`, written by `pi2d`). + * A bearer token equal to its trimmed contents authenticates as the synthetic + * `local-cli` device with every scope. Checked after the persisted devices. + */ + localTokenPath?: string; +} + +/** Synthetic device id used for the local CLI token (never persisted). */ +export const LOCAL_CLI_DEVICE_ID = "local-cli"; + +/** Constant-time string compare; the token length itself is not a secret. */ +function tokensEqual(expected: string, candidate: string): boolean { + const left = Buffer.from(expected, "utf8"); + const right = Buffer.from(candidate, "utf8"); + if (left.length !== right.length) return false; + return timingSafeEqual(left, right); } interface PairEntry { @@ -120,6 +141,7 @@ function pairCode(): string { export class AuthStore { readonly path: string; + readonly localTokenPath: string | undefined; private readonly now: () => number; private readonly baseUrl: string; private readonly touchIntervalMs: number; @@ -131,6 +153,8 @@ export class AuthStore { this.now = options.now ?? Date.now; this.baseUrl = (options.baseUrl ?? "http://127.0.0.1:7676").replace(/\/+$/, ""); this.touchIntervalMs = options.touchIntervalMs ?? 60_000; + this.localTokenPath = + options.localTokenPath === undefined || options.localTokenPath === "" ? undefined : options.localTokenPath; this.load(); } @@ -162,6 +186,7 @@ export class AuthStore { verifyToken(rawToken: string): DevicePublic | null { if (typeof rawToken !== "string" || rawToken.length === 0) return null; + if (this.matchesLocalToken(rawToken)) return this.localCliDevice(); const digest = hashToken(rawToken); let matched: DeviceRecord | undefined; // Compare against every record so the timing does not reveal the position. @@ -236,6 +261,33 @@ export class AuthStore { return this.pairs.has(code); } + /** The local CLI token grants every scope; it is not persisted or revocable. */ + private localCliDevice(): DevicePublic { + const timestamp = this.now(); + return { + id: LOCAL_CLI_DEVICE_ID, + name: "local CLI", + kind: "laptop", + scopes: [...SCOPES], + createdAt: 0, + lastSeenAt: timestamp, + revokedAt: null, + }; + } + + private matchesLocalToken(candidate: string): boolean { + const path = this.localTokenPath; + if (path === undefined) return false; + let contents: string; + try { + contents = readFileSync(path, "utf8").trim(); + } catch { + return false; + } + if (contents === "") return false; + return tokensEqual(contents, candidate); + } + private prunePairs(timestamp: number): void { for (const [code, entry] of this.pairs) { if (entry.used || timestamp > entry.expiresAt) this.pairs.delete(code); diff --git a/test/cli/auth-local-token.test.ts b/test/cli/auth-local-token.test.ts new file mode 100644 index 0000000..81234cc --- /dev/null +++ b/test/cli/auth-local-token.test.ts @@ -0,0 +1,101 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { AuthStore, LOCAL_CLI_DEVICE_ID, SCOPES } from "../../src/daemon/auth.js"; +import { writeCliToken } from "../../src/cli/token.js"; +import { removeDir, tempDir } from "./helpers.js"; + +describe("AuthStore local CLI token", () => { + let dir: string; + let tokenPath: string; + let storePath: string; + + beforeEach(() => { + dir = tempDir("pi2-local-token-"); + tokenPath = join(dir, "cli.token"); + storePath = join(dir, "devices.json"); + }); + + afterEach(() => removeDir(dir)); + + it("accepts the token file contents as the synthetic admin device", () => { + const token = writeCliToken(tokenPath); + const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath }); + + const device = auth.verifyToken(token); + expect(device).not.toBeNull(); + expect(device!.id).toBe(LOCAL_CLI_DEVICE_ID); + expect(device!.id).toBe("local-cli"); + expect(device!.name).toBe("local CLI"); + expect(device!.scopes).toEqual([...SCOPES]); + expect(device!.scopes).toEqual(["read", "steer", "control", "admin"]); + expect(device!.revokedAt).toBeNull(); + expect((device as unknown as Record<string, unknown>).tokenHash).toBeUndefined(); + }); + + it("tolerates a trailing newline in the token file", () => { + const token = writeCliToken(tokenPath); + writeFileSync(tokenPath, `${token}\n\n`, { mode: 0o600 }); + const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath }); + expect(auth.verifyToken(token)?.id).toBe(LOCAL_CLI_DEVICE_ID); + }); + + it("rejects wrong, truncated, empty and missing tokens", () => { + const token = writeCliToken(tokenPath); + const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath }); + + expect(auth.verifyToken("")).toBeNull(); + expect(auth.verifyToken("not-a-token")).toBeNull(); + expect(auth.verifyToken(token.slice(0, -1))).toBeNull(); + expect(auth.verifyToken(token.slice(0, -1) + (token.endsWith("a") ? "b" : "a"))).toBeNull(); + + writeFileSync(tokenPath, "\n", { mode: 0o600 }); + expect(auth.verifyToken("")).toBeNull(); + expect(auth.verifyToken(token)).toBeNull(); + + rmSync(tokenPath, { force: true }); + expect(auth.verifyToken(token)).toBeNull(); + }); + + it("rotates: a rewritten token file invalidates the previous one", () => { + const first = writeCliToken(tokenPath); + const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath }); + expect(auth.verifyToken(first)?.id).toBe(LOCAL_CLI_DEVICE_ID); + + const second = writeCliToken(tokenPath); + expect(second).not.toBe(first); + expect(auth.verifyToken(first)).toBeNull(); + expect(auth.verifyToken(second)?.id).toBe(LOCAL_CLI_DEVICE_ID); + }); + + it("keeps paired devices working and never lists the synthetic one", () => { + writeCliToken(tokenPath); + const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath }); + const { token } = auth.createDevice({ name: "Pixel", kind: "phone", scopes: ["read"] }); + + expect(auth.verifyToken(token)?.name).toBe("Pixel"); + expect(auth.listDevices().map((device) => device.id)).not.toContain(LOCAL_CLI_DEVICE_ID); + expect(auth.listDevices()).toHaveLength(1); + + // The synthetic device is not revocable; a paired device is. + expect(auth.revokeDevice(LOCAL_CLI_DEVICE_ID)).toBe(false); + expect(auth.revokeDevice(auth.listDevices()[0]!.id)).toBe(true); + expect(auth.verifyToken(token)).toBeNull(); + }); + + it("is inert without localTokenPath (existing API unchanged)", () => { + const token = writeCliToken(tokenPath); + const auth = new AuthStore({ path: storePath }); + expect(auth.localTokenPath).toBeUndefined(); + expect(auth.verifyToken(token)).toBeNull(); + }); + + it("does not persist anything to the device store", () => { + const token = writeCliToken(tokenPath); + const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath }); + auth.verifyToken(token); + const reloaded = new AuthStore({ path: storePath, localTokenPath: tokenPath }); + expect(reloaded.listDevices()).toHaveLength(0); + expect(reloaded.verifyToken(token)?.id).toBe(LOCAL_CLI_DEVICE_ID); + }); +}); diff --git a/test/cli/doctor.test.ts b/test/cli/doctor.test.ts new file mode 100644 index 0000000..182ad55 --- /dev/null +++ b/test/cli/doctor.test.ts @@ -0,0 +1,291 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + checkCliToken, + checkLinger, + checkNvim, + checkNode, + checkProtocol, + collectContext, + defaultProbes, + formatReport, + parseNvimVersion, + parseVersion, + reportToJson, + runDoctor, + versionAtLeast, + type DoctorContext, +} from "../../src/cli/doctor.js"; +import { clearRuntimeEnv, removeDir, tempDir } from "./helpers.js"; + +function context(overrides: Partial<DoctorContext> = {}): DoctorContext { + const base: DoctorContext = { + platform: "linux", + nodeVersion: "v22.11.0", + nvim: { found: true, path: "/usr/bin/nvim", version: "v0.10.2" }, + pi: { found: true, path: "/usr/local/bin/pi", version: "1.8.0" }, + plugin: { dir: "/home/u/.local/share/nvim/lazy/pi2.nvim", bridgeFound: true }, + runtime: { path: "/run/user/1000/pi2", exists: true, mode: 0o700 }, + cliToken: { path: "/run/user/1000/pi2/cli.token", exists: true, mode: 0o600 }, + socket: { path: "/run/user/1000/pi2/d.sock", exists: true }, + daemon: { reachable: true, port: 7676, protocolVersion: 1 }, + port: { configured: 7676, bound: true }, + serviceManager: { name: "systemd", available: true }, + linger: { checked: true, enabled: true }, + webDist: { path: "/repo/web/dist", exists: true }, + }; + return { ...base, ...overrides }; +} + +async function checks(overrides: Partial<DoctorContext> = {}) { + return runDoctor(defaultProbes(context(overrides))); +} + +function statusOf(report: Awaited<ReturnType<typeof checks>>, name: string): string | undefined { + return report.checks.find((check) => check.name === name)?.status; +} + +describe("doctor checks (all passing)", () => { + it("reports ok and every check", async () => { + const report = await checks(); + expect(report.ok).toBe(true); + expect(report.checks.map((check) => check.name)).toEqual([ + "node", + "nvim", + "pi", + "plugin", + "runtime-dir", + "cli-token", + "socket", + "daemon", + "port", + "service-manager", + "linger", + "web-dist", + "protocol", + ]); + expect(report.checks.every((check) => check.status === "ok")).toBe(true); + expect(report.checks.find((check) => check.name === "node")?.detail).toContain("v22.11.0"); + }); + + it("omits the linger check on macOS", async () => { + const report = await checks({ + platform: "darwin", + serviceManager: { name: "launchd", available: true }, + linger: { checked: false }, + }); + expect(statusOf(report, "linger")).toBeUndefined(); + expect(report.ok).toBe(true); + }); +}); + +describe("doctor failure cases", () => { + it("fails on node < 22", async () => { + const report = await checks({ nodeVersion: "v20.11.0" }); + expect(report.ok).toBe(false); + expect(statusOf(report, "node")).toBe("fail"); + expect(report.checks.find((check) => check.name === "node")?.detail).toContain("< 22.0.0"); + }); + + it("fails when nvim is missing", async () => { + const report = await checks({ nvim: { found: false, error: "nvim not found on PATH" } }); + expect(statusOf(report, "nvim")).toBe("fail"); + expect(report.ok).toBe(false); + }); + + it("fails on nvim < 0.9 (no --remote-ui)", async () => { + const report = await checks({ nvim: { found: true, path: "/usr/bin/nvim", version: "v0.8.3" } }); + expect(statusOf(report, "nvim")).toBe("fail"); + expect(report.checks.find((check) => check.name === "nvim")?.detail).toContain("--remote-ui"); + }); + + it("warns (does not fail) when pi is missing", async () => { + const report = await checks({ pi: { found: false } }); + expect(statusOf(report, "pi")).toBe("warn"); + expect(report.ok).toBe(true); + }); + + it("fails when the plugin is not installed", async () => { + const report = await checks({ plugin: { dir: "/home/u/nvim/pi2.nvim", bridgeFound: false } }); + expect(statusOf(report, "plugin")).toBe("fail"); + expect(report.ok).toBe(false); + }); + + it("fails when the runtime dir is missing and warns on loose modes", async () => { + expect(statusOf(await checks({ runtime: { path: "/run/pi2", exists: false, mode: undefined } }), "runtime-dir")).toBe( + "fail", + ); + const loose = await checks({ runtime: { path: "/run/pi2", exists: true, mode: 0o755 } }); + expect(statusOf(loose, "runtime-dir")).toBe("warn"); + expect(loose.ok).toBe(true); + }); + + it("fails when the CLI token is readable by others", async () => { + const report = await checks({ cliToken: { path: "/run/pi2/cli.token", exists: true, mode: 0o644 } }); + expect(statusOf(report, "cli-token")).toBe("fail"); + expect(report.ok).toBe(false); + expect(checkCliToken({ path: "/run/pi2/cli.token", exists: false, mode: undefined }).status).toBe("warn"); + expect(checkCliToken({ path: "/run/pi2/cli.token", exists: true, mode: 0o600 }).status).toBe("ok"); + }); + + it("fails when the socket is missing and no daemon answers", async () => { + const report = await checks({ + socket: { path: "/run/pi2/d.sock", exists: false }, + daemon: { reachable: false, error: "connection refused" }, + port: { configured: 7676, bound: false }, + }); + expect(statusOf(report, "socket")).toBe("fail"); + expect(statusOf(report, "daemon")).toBe("fail"); + expect(statusOf(report, "protocol")).toBe("fail"); + expect(report.ok).toBe(false); + // A free port is fine on its own. + expect(statusOf(report, "port")).toBe("ok"); + }); + + it("fails on a protocol version mismatch", async () => { + const report = await checks({ daemon: { reachable: true, port: 7676, protocolVersion: 2 } }); + expect(statusOf(report, "protocol")).toBe("fail"); + expect(checkProtocol({ reachable: true, port: 1, protocolVersion: 1 }).status).toBe("ok"); + }); + + it("warns when web/dist, the service manager or linger are unavailable", async () => { + const report = await checks({ + webDist: { path: "/repo/web/dist", exists: false }, + serviceManager: { name: "systemd", available: false }, + linger: { checked: true, enabled: false }, + }); + expect(statusOf(report, "web-dist")).toBe("warn"); + expect(statusOf(report, "service-manager")).toBe("warn"); + expect(statusOf(report, "linger")).toBe("warn"); + expect(report.ok).toBe(true); + }); + + it("turns a throwing probe into a failing check", async () => { + const report = await runDoctor([ + { name: "boom", run: () => Promise.reject(new Error("kaboom")) }, + { name: "fine", run: () => ({ name: "fine", status: "ok", detail: "ok" }) }, + ]); + expect(report.ok).toBe(false); + expect(report.checks[0]).toEqual({ name: "boom", status: "fail", detail: "kaboom" }); + }); +}); + +describe("doctor output", () => { + it("renders a table with an overall line", async () => { + const text = formatReport(await checks()); + expect(text).toContain("check"); + expect(text).toContain("detail"); + expect(text).toContain("runtime-dir"); + expect(text.trimEnd().endsWith("overall: ok")).toBe(true); + + const failed = formatReport(await checks({ nodeVersion: "v18.0.0" })); + expect(failed).toContain("FAIL"); + expect(failed.trimEnd().endsWith("overall: FAILED")).toBe(true); + }); + + it("emits a stable JSON shape", async () => { + const parsed = JSON.parse(reportToJson(await checks())) as { + ok: boolean; + checks: { name: string; status: string; detail: string }[]; + }; + expect(parsed.ok).toBe(true); + expect(Array.isArray(parsed.checks)).toBe(true); + expect(Object.keys(parsed.checks[0]!)).toEqual(["name", "status", "detail"]); + expect(parsed.checks.find((check) => check.name === "daemon")?.detail).toContain("http://127.0.0.1:7676"); + }); +}); + +describe("version helpers", () => { + it("parses and compares versions", () => { + expect(parseVersion("v22.1.0")).toEqual([22, 1, 0]); + expect(parseVersion("22.10.3")).toEqual([22, 10, 3]); + expect(parseVersion("nope")).toBeUndefined(); + expect(versionAtLeast([22, 0, 0], [22, 0, 0])).toBe(true); + expect(versionAtLeast([22, 0, 0], [22, 1, 0])).toBe(false); + expect(versionAtLeast([23, 0, 0], [22, 9, 9])).toBe(true); + expect(parseNvimVersion("NVIM v0.10.2\nBuild type: Release")).toBe("0.10.2"); + expect(parseNvimVersion("NVIM v0.9.5")).toBe("0.9.5"); + expect(parseNvimVersion("garbage")).toBeUndefined(); + expect(checkNode("v22.0.0").status).toBe("ok"); + expect(checkNode("garbage").status).toBe("fail"); + expect(checkNvim({ found: true, path: "/n", version: "v0.10.0" }).status).toBe("ok"); + expect(checkLinger({ checked: false }).status).toBe("ok"); + }); +}); + +describe("collectContext", () => { + let dir: string; + + beforeEach(() => { + dir = tempDir("pi2-doctor-"); + process.env.PI2_RUNTIME_DIR = join(dir, "run"); + process.env.PI2_DATA_DIR = join(dir, "data"); + mkdirSync(join(dir, "run"), { recursive: true, mode: 0o700 }); + writeFileSync(join(dir, "run", "cli.token"), "t".repeat(64), { mode: 0o600 }); + writeFileSync(join(dir, "run", "d.sock"), ""); + process.env.PI2_STATIC_DIR = join(dir, "web"); + }); + + afterEach(() => { + clearRuntimeEnv(); + removeDir(dir); + }); + + it("gathers real state through injectable probes", async () => { + const home = join(dir, "home"); + mkdirSync(join(home, ".local", "share", "nvim", "lazy", "pi2.nvim", "lua", "pi", "web"), { + recursive: true, + }); + writeFileSync(join(home, ".local", "share", "nvim", "lazy", "pi2.nvim", "lua", "pi", "web", "bridge.lua"), ""); + + const ctx = await collectContext({ + platform: "linux", + home, + uid: 1000, + env: { PATH: "/usr/bin", PI2_RUNTIME_DIR: join(dir, "run"), PI2_STATIC_DIR: join(dir, "web") }, + which: (command) => `/usr/bin/${command}`, + run: async (command, args) => { + if (command === "nvim") return { ok: true, stdout: "NVIM v0.10.2\nBuild type: Release\n", stderr: "" }; + if (command === "pi") return { ok: true, stdout: "1.8.0\n", stderr: "" }; + if (command === "loginctl" && args[1] === "1000") return { ok: true, stdout: "Linger=yes\n", stderr: "" }; + return { ok: false, stdout: "", stderr: "unexpected" }; + }, + daemonInfo: async () => ({ port: 7712, protocolVersion: 1 }), + }); + + expect(ctx.nvim).toEqual({ found: true, path: "/usr/bin/nvim", version: "v0.10.2" }); + expect(ctx.pi.version).toBe("1.8.0"); + expect(ctx.plugin.bridgeFound).toBe(true); + expect(ctx.runtime.exists).toBe(true); + expect(ctx.cliToken.mode).toBe(0o600); + expect(ctx.socket.exists).toBe(true); + expect(ctx.daemon).toEqual({ reachable: true, port: 7712, protocolVersion: 1 }); + expect(ctx.port).toEqual({ configured: 7712, bound: true }); + expect(ctx.serviceManager).toEqual({ name: "systemd", available: true }); + expect(ctx.linger).toMatchObject({ checked: true, enabled: true }); + expect(ctx.webDist.path).toBe(join(dir, "web")); + + const report = await runDoctor(defaultProbes(ctx)); + // web/dist does not exist here, everything else passes. + expect(report.ok).toBe(true); + expect(report.checks.find((check) => check.name === "web-dist")?.status).toBe("warn"); + }); + + it("records a missing daemon as unreachable", async () => { + const ctx = await collectContext({ + platform: "darwin", + home: join(dir, "home"), + env: { PATH: "/usr/bin", PI2_RUNTIME_DIR: join(dir, "run") }, + which: (command) => (command === "launchctl" ? "/bin/launchctl" : `/usr/bin/${command}`), + run: async () => ({ ok: false, stdout: "", stderr: "not found" }), + daemonInfo: async () => ({ error: "connection refused" }), + }); + expect(ctx.daemon.reachable).toBe(false); + expect(ctx.linger.checked).toBe(false); + expect(ctx.serviceManager.name).toBe("launchd"); + const report = await runDoctor(defaultProbes(ctx)); + expect(report.ok).toBe(false); + expect(report.checks.some((check) => check.name === "linger")).toBe(false); + }); +}); diff --git a/test/cli/helpers.ts b/test/cli/helpers.ts new file mode 100644 index 0000000..974ed98 --- /dev/null +++ b/test/cli/helpers.ts @@ -0,0 +1,55 @@ +/** Shared helpers for the CLI specs (temp dirs, silent logger, bare config). */ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Config, Limits } from "../../src/config.js"; +import type { Logger } from "../../src/core/interfaces.js"; + +export const TEST_LIMITS: Limits = { + maxBodyBytes: 8 * 1024 * 1024, + maxFrameBytes: 8 * 1024 * 1024, + maxConnections: 64, +}; + +export function tempDir(prefix = "pi2d-cli-"): string { + return mkdtempSync(join(tmpdir(), prefix)); +} + +export function removeDir(dir: string): void { + rmSync(dir, { recursive: true, force: true }); +} + +export function testConfig(overrides: Partial<Config> = {}): Config { + const base: Config = { + host: "127.0.0.1", + port: 0, + staticDir: "/nonexistent-web-dist", + corsOrigins: [], + limits: TEST_LIMITS, + tokenPath: "/tmp/pi2d-cli-test.sock.token", + deviceStorePath: "/tmp/pi2d-cli-test-devices.json", + }; + return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } }; +} + +export const silentLogger: Logger = { + debug: () => undefined, + info: () => undefined, + warn: () => undefined, + error: () => undefined, + child: () => silentLogger, +}; + +export function setRuntimeEnv(dir: string): void { + process.env.PI2_RUNTIME_DIR = join(dir, "run"); + process.env.PI2_DATA_DIR = join(dir, "data"); + process.env.PI2_STATE_DIR = join(dir, "state"); + process.env.PI2_PORT = "0"; + process.env.PI2_STATIC_DIR = join(dir, "web"); +} + +export function clearRuntimeEnv(): void { + for (const key of ["PI2_RUNTIME_DIR", "PI2_DATA_DIR", "PI2_STATE_DIR", "PI2_PORT", "PI2_STATIC_DIR"]) { + delete process.env[key]; + } +} diff --git a/test/cli/listen.test.ts b/test/cli/listen.test.ts new file mode 100644 index 0000000..7680efc --- /dev/null +++ b/test/cli/listen.test.ts @@ -0,0 +1,128 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { createServer, type AddressInfo, type Server as NetServer } from "node:net"; +import { AuthStore } from "../../src/daemon/auth.js"; +import type { ServerDeps } from "../../src/daemon/server.js"; +import { isAddressInUse, listenWithRetry, withPort } from "../../src/cli/listen.js"; +import { FakeBus, FakeInstanceManager, FakeWorkspaceStore } from "../daemon/fakes.js"; +import { removeDir, silentLogger, tempDir, testConfig } from "./helpers.js"; + +async function occupyPort(): Promise<{ port: number; close(): Promise<void> }> { + const server: NetServer = createServer(); + await new Promise<void>((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => resolve()); + }); + const address = server.address() as AddressInfo; + return { + port: address.port, + close: (): Promise<void> => new Promise((resolve) => server.close(() => resolve())), + }; +} + +describe("listenWithRetry", () => { + let dir: string; + let deps: ServerDeps; + const cleanups: (() => Promise<void>)[] = []; + + beforeEach(() => { + dir = tempDir("pi2-listen-"); + deps = { + auth: new AuthStore({ path: `${dir}/devices.json` }), + instances: new FakeInstanceManager(), + workspaces: new FakeWorkspaceStore([]), + bus: new FakeBus(), + logger: silentLogger, + daemonId: "d-listen", + }; + }); + + afterEach(async () => { + for (const cleanup of cleanups.splice(0)) await cleanup(); + removeDir(dir); + }); + + it("binds port 0 without retrying", async () => { + const config = testConfig({ port: 0 }); + const server = await listenWithRetry(config, deps, { retries: 9 }); + cleanups.push(() => server.close()); + expect(server.port).toBeGreaterThan(0); + expect(server.url).toContain(`:${server.port}`); + }); + + it("walks to the next port when the default is taken", async () => { + const busy = await occupyPort(); + cleanups.push(() => busy.close()); + const config = testConfig({ + port: busy.port, + corsOrigins: [`http://127.0.0.1:${busy.port}`, `http://localhost:${busy.port}`], + }); + const retries: { from: number; to: number }[] = []; + const server = await listenWithRetry(config, deps, { + retries: 9, + onRetry: (info) => retries.push({ from: info.from, to: info.to }), + }); + cleanups.push(() => server.close()); + + expect(server.port).toBeGreaterThan(busy.port); + expect(retries[0]).toEqual({ from: busy.port, to: busy.port + 1 }); + // The derived CORS origins follow the effective port. + expect(server.config.corsOrigins).toEqual([ + `http://127.0.0.1:${server.port}`, + `http://localhost:${server.port}`, + ]); + }); + + it("fails fast on an explicit port", async () => { + const busy = await occupyPort(); + cleanups.push(() => busy.close()); + const config = testConfig({ port: busy.port }); + await expect(listenWithRetry(config, deps, { retries: 0 })).rejects.toSatisfy(isAddressInUse); + }); + + it("stops retrying when the budget is exhausted", async () => { + const busy = await occupyPort(); + cleanups.push(() => busy.close()); + const busyNext = createServer(); + await new Promise<void>((resolve, reject) => { + busyNext.once("error", reject); + busyNext.listen(busy.port + 1, "127.0.0.1", () => resolve()); + }); + cleanups.push(() => new Promise<void>((resolve) => busyNext.close(() => resolve()))); + + const config = testConfig({ port: busy.port }); + let attempts = 0; + await expect( + listenWithRetry(config, deps, { + retries: 1, + onRetry: () => { + attempts += 1; + }, + }), + ).rejects.toSatisfy(isAddressInUse); + expect(attempts).toBe(1); + }); +}); + +describe("withPort", () => { + it("rewrites derived origins and keeps custom ones", () => { + const config = testConfig({ + port: 7676, + corsOrigins: ["http://127.0.0.1:7676", "http://localhost:7676", "https://pi2.example"], + }); + expect(withPort(config, 7676)).toBe(config); + expect(withPort(config, 7678).corsOrigins).toEqual([ + "http://127.0.0.1:7678", + "http://localhost:7678", + "https://pi2.example", + ]); + expect(withPort(config, 7678).port).toBe(7678); + }); +}); + +describe("isAddressInUse", () => { + it("recognises EADDRINUSE only", () => { + expect(isAddressInUse(Object.assign(new Error("busy"), { code: "EADDRINUSE" }))).toBe(true); + expect(isAddressInUse(Object.assign(new Error("denied"), { code: "EACCES" }))).toBe(false); + expect(isAddressInUse(new Error("plain"))).toBe(false); + }); +}); diff --git a/test/cli/lock.test.ts b/test/cli/lock.test.ts new file mode 100644 index 0000000..e50bfda --- /dev/null +++ b/test/cli/lock.test.ts @@ -0,0 +1,201 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + acquireLock, + assessLock, + LockError, + readDaemonJson, + readLockFile, + writeDaemonJson, + type DaemonLock, +} from "../../src/cli/lock.js"; +import { PROTOCOL_VERSION } from "../../src/protocol/types.js"; +import { removeDir, tempDir } from "./helpers.js"; + +const BOOT = "boot-abc"; + +function payload(overrides: Partial<DaemonLock> = {}): Omit<DaemonLock, "pid" | "bootId"> & { pid?: number; bootId?: string } { + return { + port: 7676, + daemonId: "d-test", + startedAt: 1_700_000_000_000, + protocolVersion: PROTOCOL_VERSION, + ...overrides, + }; +} + +describe("daemon lock", () => { + let dir: string; + let lockPath: string; + + beforeEach(() => { + dir = tempDir("pi2-lock-"); + mkdirSync(dir, { recursive: true }); + lockPath = join(dir, "daemon.lock"); + }); + + afterEach(() => removeDir(dir)); + + it("creates the lock with the payload and mode 0600", () => { + const handle = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT }); + expect(handle.lock).toEqual({ + pid: process.pid, + bootId: BOOT, + port: 7676, + daemonId: "d-test", + startedAt: 1_700_000_000_000, + protocolVersion: PROTOCOL_VERSION, + }); + expect(readLockFile(lockPath)).toEqual(handle.lock); + expect(statSync(lockPath).mode & 0o777).toBe(0o600); + expect(readFileSync(lockPath, "utf8").endsWith("\n")).toBe(true); + + handle.release(); + expect(existsSync(lockPath)).toBe(false); + }); + + it("refuses a second daemon while the holder is alive", () => { + const first = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT }); + expect(() => acquireLock({ lockPath, payload: payload({ daemonId: "d-two" }), bootId: () => BOOT })).toThrow( + LockError, + ); + try { + acquireLock({ lockPath, payload: payload({ daemonId: "d-two" }), bootId: () => BOOT }); + } catch (error) { + const lockError = error as LockError; + expect(lockError.code).toBe("E_LOCKED"); + expect(lockError.holder?.daemonId).toBe("d-test"); + expect(lockError.holder?.pid).toBe(process.pid); + expect(lockError.message).toContain("--force"); + } + // The original lock survived the failed attempt. + expect(readLockFile(lockPath)?.daemonId).toBe("d-test"); + first.release(); + }); + + it("overrides a live lock with --force", () => { + const first = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT }); + const forced = acquireLock({ lockPath, payload: payload({ daemonId: "d-forced" }), bootId: () => BOOT, force: true }); + expect(forced.lock.daemonId).toBe("d-forced"); + expect(readLockFile(lockPath)?.daemonId).toBe("d-forced"); + + // The displaced daemon must not delete the new lock on shutdown. + first.release(); + expect(readLockFile(lockPath)?.daemonId).toBe("d-forced"); + forced.release(); + expect(existsSync(lockPath)).toBe(false); + }); + + it("treats a dead pid as stale", () => { + acquireLock({ lockPath, payload: payload({ daemonId: "d-dead" }), bootId: () => BOOT }); + const handle = acquireLock({ + lockPath, + payload: payload({ daemonId: "d-new" }), + bootId: () => BOOT, + isPidAlive: () => false, + }); + expect(handle.lock.daemonId).toBe("d-new"); + handle.release(); + }); + + it("treats a pid from a previous boot as stale (pid reuse)", () => { + acquireLock({ lockPath, payload: payload({ daemonId: "d-old" }), bootId: () => "boot-old" }); + const handle = acquireLock({ + lockPath, + payload: payload({ daemonId: "d-new" }), + bootId: () => BOOT, + isPidAlive: () => true, + }); + expect(handle.lock.daemonId).toBe("d-new"); + expect(handle.lock.bootId).toBe(BOOT); + handle.release(); + }); + + it("ignores a malformed lock file (crash during write)", () => { + writeFileSync(lockPath, "{not json"); + const handle = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT }); + expect(readLockFile(lockPath)?.daemonId).toBe("d-test"); + handle.release(); + }); + + it("update() rewrites the payload in place", () => { + const handle = acquireLock({ lockPath, payload: payload({ port: 0 }), bootId: () => BOOT }); + handle.update({ port: 7712 }); + expect(handle.lock.port).toBe(7712); + expect(readLockFile(lockPath)?.port).toBe(7712); + expect(readLockFile(lockPath)?.daemonId).toBe("d-test"); + handle.release(); + }); + + it("assessLock explains why a lock is stale", () => { + const lock: DaemonLock = { + pid: 42, + bootId: BOOT, + port: 7676, + daemonId: "d-1", + startedAt: 1, + protocolVersion: PROTOCOL_VERSION, + }; + expect(assessLock(lock, { isPidAlive: () => true, bootId: () => BOOT })).toEqual({ live: true, reason: "alive" }); + expect(assessLock(lock, { isPidAlive: () => false, bootId: () => BOOT })).toEqual({ + live: false, + reason: "no-pid", + }); + expect(assessLock(lock, { isPidAlive: () => true, bootId: () => "other" })).toEqual({ + live: false, + reason: "boot-changed", + }); + }); +}); + +describe("daemon.json", () => { + let dir: string; + let lockPath: string; + let daemonJsonPath: string; + + beforeEach(() => { + dir = tempDir("pi2-daemonjson-"); + lockPath = join(dir, "daemon.lock"); + daemonJsonPath = join(dir, "daemon.json"); + }); + + afterEach(() => removeDir(dir)); + + it("publishes the same payload as the lock, mode 0600", () => { + const handle = acquireLock({ + lockPath, + payload: { port: 7713, daemonId: "d-json", startedAt: 5, protocolVersion: PROTOCOL_VERSION }, + bootId: () => BOOT, + }); + writeDaemonJson(handle.lock, daemonJsonPath); + + const discovered = readDaemonJson(daemonJsonPath); + expect(discovered).toEqual({ + pid: process.pid, + bootId: BOOT, + port: 7713, + daemonId: "d-json", + startedAt: 5, + protocolVersion: PROTOCOL_VERSION, + }); + expect(statSync(daemonJsonPath).mode & 0o777).toBe(0o600); + handle.release(); + }); + + it("is removed by release() and missing files read as undefined", () => { + const handle = acquireLock({ + lockPath, + payload: { port: 7676, daemonId: "d-json", startedAt: 5, protocolVersion: PROTOCOL_VERSION }, + bootId: () => BOOT, + }); + writeDaemonJson(handle.lock, daemonJsonPath); + handle.release(); + expect(existsSync(daemonJsonPath)).toBe(false); + expect(readDaemonJson(daemonJsonPath)).toBeUndefined(); + + // A discovery file owned by another daemon is left alone. + writeDaemonJson({ ...handle.lock, daemonId: "d-other" }, daemonJsonPath); + expect(readDaemonJson(daemonJsonPath)?.daemonId).toBe("d-other"); + }); +}); diff --git a/test/cli/pi2.test.ts b/test/cli/pi2.test.ts new file mode 100644 index 0000000..125de39 --- /dev/null +++ b/test/cli/pi2.test.ts @@ -0,0 +1,484 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { mkdirSync, realpathSync, writeFileSync } from "node:fs"; +import { basename, join } from "node:path"; +import type { DaemonClient } from "../../src/cli/pi2.js"; +import { CliError, createClient, main, resolveEndpoint, runAttach, runDoctorCommand, runPairing, runStatus } from "../../src/cli/pi2.js"; +import { writeDaemonJson, type DaemonLock } from "../../src/cli/lock.js"; +import { writeCliToken } from "../../src/cli/token.js"; +import type { WorkspaceInfo } from "../../src/protocol/types.js"; +import { PROTOCOL_VERSION } from "../../src/protocol/types.js"; +import { removeDir, tempDir } from "./helpers.js"; + +const DAEMON: DaemonLock = { + pid: 1234, + bootId: "boot-1", + port: 7712, + daemonId: "d-test", + startedAt: 1, + protocolVersion: PROTOCOL_VERSION, +}; + +function workspace(cwd: string, overrides: Partial<WorkspaceInfo> = {}): WorkspaceInfo { + return { + workspaceId: "ws-1", + cwd, + name: basename(cwd), + trusted: true, + exists: true, + sessionCount: 0, + liveCount: 0, + lastActiveAt: null, + instance: null, + ...overrides, + }; +} + +function instance(overrides: Partial<NonNullable<WorkspaceInfo["instance"]>> = {}): NonNullable<WorkspaceInfo["instance"]> { + return { + workspaceId: "ws-1", + instanceId: "i-1", + status: "ready", + nvimPid: 4321, + pluginVersion: "1.8.0", + hasUI: true, + attachedClients: 0, + listenAddr: "/run/user/1000/pi2/i/ab12.sock", + startedAt: 1, + ...overrides, + }; +} + +interface FakeData { + workspaces?: WorkspaceInfo[]; + info?: Record<string, unknown>; + resources?: Record<string, unknown>; + health?: Record<string, unknown>; + pair?: Record<string, unknown>; + postError?: Error; +} + +function fakeClient(data: FakeData = {}): DaemonClient & { calls: string[] } { + const calls: string[] = []; + return { + calls, + baseUrl: `http://127.0.0.1:${DAEMON.port}`, + token: "cli-token", + daemon: DAEMON, + async get<T>(path: string): Promise<T> { + calls.push(path); + if (path === "/api/v1/workspaces") return (data.workspaces ?? []) as unknown as T; + if (path === "/api/v1/info") { + return (data.info ?? { + v: PROTOCOL_VERSION, + daemonId: "d-test", + machineId: "m-test", + platform: "linux", + capabilities: ["ws", "sse"], + limits: { maxBodyBytes: 1, maxFrameBytes: 1, maxConnections: 1 }, + }) as unknown as T; + } + if (path === "/api/v1/resources") { + return (data.resources ?? { + instances: [], + totalRssBytes: 0, + physicalMemoryBytes: 16 * 1024 * 1024 * 1024, + warn: false, + }) as unknown as T; + } + if (path === "/api/v1/health") { + return (data.health ?? { ok: true, items: [{ name: "instances", ok: true, detail: "0 connected" }] }) as unknown as T; + } + throw new CliError(`unexpected GET ${path}`); + }, + async post(path: string, body: unknown): Promise<{ status: number; body: Record<string, unknown> }> { + calls.push(`${path} ${JSON.stringify(body)}`); + if (data.postError !== undefined) throw data.postError; + if (path === "/api/v1/pair") { + return { status: 202, body: data.pair ?? { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } }; + } + throw new CliError(`unexpected POST ${path}`); + }, + }; +} + +interface ExecCall { + command: string; + args: string[]; + cwd: string; +} + +function recorder(): { calls: ExecCall[]; exec: (command: string, args: string[], options: { cwd: string }) => void } { + const calls: ExecCall[] = []; + return { + calls, + exec: (command, args, options) => { + calls.push({ command, args, cwd: options.cwd }); + }, + }; +} + +describe("resolveEndpoint / createClient", () => { + let dir: string; + + beforeEach(() => { + dir = tempDir("pi2-cli-ep-"); + }); + + afterEach(() => removeDir(dir)); + + it("reads daemon.json and cli.token from the runtime dir", () => { + writeDaemonJson(DAEMON, join(dir, "daemon.json")); + const token = writeCliToken(join(dir, "cli.token")); + + const endpoint = resolveEndpoint(dir); + expect(endpoint.baseUrl).toBe("http://127.0.0.1:7712"); + expect(endpoint.token).toBe(token); + expect(endpoint.daemon.daemonId).toBe("d-test"); + + const client = createClient({ endpoint }); + expect(client.baseUrl).toBe(endpoint.baseUrl); + }); + + it("explains a missing daemon or token", () => { + expect(() => resolveEndpoint(dir)).toThrowError(/no running pi2d/); + writeDaemonJson(DAEMON, join(dir, "daemon.json")); + expect(() => resolveEndpoint(dir)).toThrowError(/missing CLI token/); + }); + + it("turns a connection failure into a CliError", async () => { + writeDaemonJson({ ...DAEMON, port: 1 }, join(dir, "daemon.json")); + writeCliToken(join(dir, "cli.token")); + const client = createClient({ endpoint: resolveEndpoint(dir), timeoutMs: 500 }); + await expect(client.get("/api/v1/info")).rejects.toThrowError(/cannot reach pi2d/); + }); +}); + +describe("pi2 attach", () => { + let dir: string; + let cwd: string; + + beforeEach(() => { + dir = tempDir("pi2-cli-attach-"); + cwd = realpathSync(dir); + }); + + afterEach(() => removeDir(dir)); + + it("attaches to a ready instance with --remote-ui when a TTY is present", async () => { + const listenAddr = "/run/user/1000/pi2/i/ab12.sock"; + const recorded = recorder(); + const code = await runAttach({ + cwd, + isTTY: true, + exec: recorded.exec, + client: () => fakeClient({ workspaces: [workspace(cwd, { instance: instance({ listenAddr }) })] }), + }); + expect(code).toBe(0); + expect(recorded.calls).toEqual([ + { command: "nvim", args: ["--server", listenAddr, "--remote-ui"], cwd }, + ]); + }); + + it("prints the command instead of exec when stdout is not a TTY", async () => { + const listenAddr = "/run/user/1000/pi2/i/ab12.sock"; + const recorded = recorder(); + const lines: string[] = []; + const code = await runAttach({ + cwd, + isTTY: false, + exec: recorded.exec, + print: (line) => lines.push(line), + client: () => fakeClient({ workspaces: [workspace(cwd, { instance: instance({ listenAddr }) })] }), + }); + expect(code).toBe(0); + expect(recorded.calls).toEqual([]); + expect(lines).toEqual([`nvim --server ${listenAddr} --remote-ui`]); + }); + + it("starts a plain nvim when the workspace has no instance", async () => { + const recorded = recorder(); + await runAttach({ + cwd, + isTTY: true, + exec: recorded.exec, + client: () => fakeClient({ workspaces: [workspace(cwd)] }), + }); + expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]); + }); + + it("does not attach to a headless instance without a listen address", async () => { + const recorded = recorder(); + await runAttach({ + cwd, + isTTY: true, + exec: recorded.exec, + client: () => + fakeClient({ + workspaces: [workspace(cwd, { instance: instance({ listenAddr: null, hasUI: false }) })], + }), + }); + expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]); + }); + + it("does not attach to a stopping instance", async () => { + const recorded = recorder(); + await runAttach({ + cwd, + isTTY: true, + exec: recorded.exec, + client: () => fakeClient({ workspaces: [workspace(cwd, { instance: instance({ status: "stopping" }) })] }), + }); + expect(recorded.calls[0]?.args).toEqual([]); + }); + + it("resolves the path argument against cwd (realpath comparison)", async () => { + const sub = join(cwd, "packages", "app"); + mkdirSync(sub, { recursive: true }); + const recorded = recorder(); + const client = fakeClient({ + workspaces: [workspace(realpathSync(sub), { instance: instance({ listenAddr: "/tmp/nvim.sock" }) })], + }); + await runAttach({ cwd, path: "packages/app", isTTY: true, exec: recorded.exec, client: () => client }); + expect(recorded.calls[0]).toEqual({ + command: "nvim", + args: ["--server", "/tmp/nvim.sock", "--remote-ui"], + cwd: realpathSync(sub), + }); + }); + + it("falls back to plain nvim when the daemon is not running", async () => { + const recorded = recorder(); + const warnings: string[] = []; + const code = await runAttach({ + cwd, + isTTY: true, + exec: recorded.exec, + warn: (line) => warnings.push(line), + client: () => { + throw new CliError("no running pi2d (daemon.json missing)"); + }, + }); + expect(code).toBe(0); + expect(warnings[0]).toContain("no running pi2d"); + expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]); + }); + + it("falls back to plain nvim when the HTTP call fails", async () => { + const recorded = recorder(); + const warnings: string[] = []; + await runAttach({ + cwd, + isTTY: true, + exec: recorded.exec, + warn: (line) => warnings.push(line), + client: () => { + const client = fakeClient(); + client.get = async () => { + throw new CliError("cannot reach pi2d"); + }; + return client; + }, + }); + expect(warnings[0]).toContain("cannot reach pi2d"); + expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd }]); + }); +}); + +describe("pi2 status", () => { + it("renders a table with daemon, instances, resources and health", async () => { + const lines: string[] = []; + const client = fakeClient({ + workspaces: [ + workspace("/repo/pi2", { + name: "pi2", + liveCount: 2, + instance: instance({ status: "ready", hasUI: true }), + }), + ], + resources: { + instances: [{ workspaceId: "ws-1", instanceId: "i-1", nvimPid: 4321, rssBytes: 1024 * 1024, sessions: 2, hasUI: true }], + totalRssBytes: 1024 * 1024, + physicalMemoryBytes: 16 * 1024 * 1024 * 1024, + warn: false, + }, + }); + const code = await runStatus({ client, print: (line) => lines.push(line) }); + expect(code).toBe(0); + const text = lines.join("\n"); + expect(text).toContain("daemon http://127.0.0.1:7712"); + expect(text).toContain("pi2"); + expect(text).toContain("/repo/pi2"); + expect(text).toContain("ready"); + expect(text).toContain("resources 1 instance(s)"); + expect(text).toContain("health ok"); + }); + + it("emits JSON and exits 1 when health is not ok", async () => { + const lines: string[] = []; + const code = await runStatus({ + json: true, + print: (line) => lines.push(line), + client: fakeClient({ health: { ok: false, items: [{ name: "static", ok: false, detail: "missing" }] } }), + }); + expect(code).toBe(1); + const parsed = JSON.parse(lines.join("\n")) as { + daemon: { url: string; v: number }; + instances: unknown[]; + resources: { totalRssBytes: number }; + health: { ok: boolean }; + }; + expect(parsed.daemon.url).toBe("http://127.0.0.1:7712"); + expect(parsed.daemon.v).toBe(PROTOCOL_VERSION); + expect(parsed.instances).toEqual([]); + expect(parsed.health.ok).toBe(false); + }); +}); + +describe("pi2 pairing", () => { + it("posts with the local token and prints url, code and qr payload", async () => { + const lines: string[] = []; + const client = fakeClient({ pair: { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } }); + const code = await runPairing({ client, print: (line) => lines.push(line) }); + expect(code).toBe(0); + const text = lines.join("\n"); + expect(text).toContain("url http://127.0.0.1:7712/pair/ABCD2345"); + expect(text).toContain("code ABCD2345"); + expect(text).toContain('"code":"ABCD2345"'); + expect(text).toContain('"v":1'); + expect(client.calls[0]).toBe("/api/v1/pair {}"); + }); + + it("exits non-zero when the daemon rejects the request", async () => { + await expect( + runPairing({ client: fakeClient({ postError: new CliError("pair failed: E_UNAUTHORIZED") }) }), + ).rejects.toThrowError(/E_UNAUTHORIZED/); + }); +}); + +describe("pi2 doctor (daemon probe wiring)", () => { + it("reports the live daemon port and protocol version", async () => { + const report = await runDoctorCommand({ client: () => fakeClient() }); + const daemon = report.checks.find((check) => check.name === "daemon"); + expect(daemon?.status).toBe("ok"); + expect(daemon?.detail).toContain("http://127.0.0.1:7712"); + expect(report.checks.find((check) => check.name === "protocol")?.status).toBe("ok"); + expect(report.checks.find((check) => check.name === "port")?.detail).toBe("7712 bound by pi2d"); + }); + + it("reports an unreachable daemon without throwing", async () => { + const report = await runDoctorCommand({ + client: () => { + throw new CliError("no running pi2d (daemon.json missing)"); + }, + }); + const daemon = report.checks.find((check) => check.name === "daemon"); + expect(daemon?.status).toBe("fail"); + expect(daemon?.detail).toContain("no running pi2d"); + expect(report.ok).toBe(false); + }); +}); + +describe("pi2 main", () => { + it("prints usage and version", async () => { + const out: string[] = []; + expect(await main([], { out: (line) => out.push(line) })).toBe(0); + expect(out.join("\n")).toContain("pi2 attach [path]"); + + out.length = 0; + expect(await main(["--version"], { out: (line) => out.push(line) })).toBe(0); + expect(out[0]).toMatch(/^pi2 \d+\.\d+\.\d+/); + }); + + it("rejects unknown commands and options with exit 2", async () => { + const err: string[] = []; + expect(await main(["nope"], { err: (line) => err.push(line) })).toBe(2); + expect(err[0]).toBe('pi2: unknown command "nope"'); + + err.length = 0; + expect(await main(["attach", "--bogus"], { err: (line) => err.push(line) })).toBe(2); + expect(err[0]).toContain("unknown option --bogus"); + }); + + it("routes status --json through the injected client", async () => { + const out: string[] = []; + const client = fakeClient(); + expect(await main(["status", "--json"], { out: (line) => out.push(line), client: () => client })).toBe(0); + expect(JSON.parse(out.join("\n"))).toMatchObject({ daemon: { url: "http://127.0.0.1:7712" } }); + }); + + it("reports a missing daemon for status with exit 1", async () => { + const err: string[] = []; + const code = await main(["status"], { + err: (line) => err.push(line), + client: () => { + throw new CliError("no running pi2d"); + }, + }); + expect(code).toBe(1); + expect(err[0]).toBe("pi2: no running pi2d"); + }); + + it("routes attach through runAttach with an injected exec", async () => { + const recorded = recorder(); + const code = await main(["attach"], { + cwd: process.cwd(), + isTTY: true, + exec: recorded.exec, + client: () => fakeClient({ workspaces: [] }), + }); + expect(code).toBe(0); + expect(recorded.calls).toEqual([{ command: "nvim", args: [], cwd: process.cwd() }]); + }); + + it("installs a service with --write through the injected writer", async () => { + const out: string[] = []; + const writes: { path: string; content: string }[] = []; + const code = await main(["install-service", "--write"], { + out: (line) => out.push(line), + platform: "linux", + servicePaths: { + nodePath: "/usr/bin/node", + scriptPath: "/repo/dist/cli/pi2d.js", + stateDir: "/state", + homeDir: "/home/u", + pathEnv: "/usr/bin", + }, + writeFile: (path, content) => writes.push({ path, content }), + }); + expect(code).toBe(0); + expect(writes[0]?.path).toBe(join("/home/u/.config/systemd/user", "pi2d.service")); + expect(writes[0]?.content).toContain("ExecStart=/usr/bin/node /repo/dist/cli/pi2d.js --foreground"); + expect(out.join("\n")).toContain("systemctl --user enable --now pi2d.service"); + }); + + it("prints the service on the default dry-run", async () => { + const out: string[] = []; + const code = await main(["install-service"], { + out: (line) => out.push(line), + platform: "darwin", + servicePaths: { + nodePath: "/usr/bin/node", + scriptPath: "/repo/dist/cli/pi2d.js", + stateDir: "/state", + homeDir: "/home/u", + pathEnv: "/usr/bin", + }, + }); + expect(code).toBe(0); + expect(out.join("\n")).toContain("<key>KeepAlive</key>"); + expect(out.join("\n")).toContain("would write /home/u/Library/LaunchAgents/com.pi2.pi2d.plist"); + }); + + it("renders doctor output and exits 1 when a check fails", async () => { + const out: string[] = []; + const code = await main(["doctor", "--json"], { + out: (line) => out.push(line), + doctor: async () => ({ ok: false, checks: [{ name: "node", status: "fail", detail: "v18.0.0" }] }), + }); + expect(code).toBe(1); + expect(JSON.parse(out.join("\n"))).toEqual({ + ok: false, + checks: [{ name: "node", status: "fail", detail: "v18.0.0" }], + }); + }); +}); diff --git a/test/cli/pi2d.test.ts b/test/cli/pi2d.test.ts new file mode 100644 index 0000000..c108b5f --- /dev/null +++ b/test/cli/pi2d.test.ts @@ -0,0 +1,112 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { chmodSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs } from "../../src/cli/pi2d.js"; +import { readCliToken, tokenPerms, writeCliToken } from "../../src/cli/token.js"; +import { UsageError } from "../../src/cli/util.js"; +import { removeDir, tempDir } from "./helpers.js"; + +describe("parseDaemonArgs", () => { + it("defaults to nothing set (foreground daemon, config defaults)", () => { + expect(parseDaemonArgs([])).toEqual({ force: false, foreground: false, help: false, version: false }); + }); + + it("parses every flag, in both value syntaxes", () => { + expect(parseDaemonArgs(["--port", "7676", "--host", "0.0.0.0", "--static-dir=/srv/ui", "--force", "--foreground"])).toEqual({ + port: 7676, + host: "0.0.0.0", + staticDir: "/srv/ui", + force: true, + foreground: true, + help: false, + version: false, + }); + expect(parseDaemonArgs(["-p", "0"]).port).toBe(0); + expect(parseDaemonArgs(["-f"]).force).toBe(true); + expect(parseDaemonArgs(["--help"]).help).toBe(true); + expect(parseDaemonArgs(["-h"]).help).toBe(true); + expect(parseDaemonArgs(["-V"]).version).toBe(true); + }); + + it("rejects bad ports and stray positionals", () => { + for (const port of ["abc", "-1", "70000", "1.5"]) { + expect(() => parseDaemonArgs(["--port", port])).toThrow(UsageError); + } + expect(() => parseDaemonArgs(["extra"])).toThrow(/unexpected argument extra/); + expect(() => parseDaemonArgs(["--nope"])).toThrow(/unknown option --nope/); + expect(() => parseDaemonArgs(["--port"])).toThrow(/requires a value/); + }); + + it("retries the default port at most +9", () => { + expect(DEFAULT_PORT_RETRIES).toBe(9); + }); +}); + +describe("pi2d main (non-listening paths)", () => { + it("prints usage for --help", async () => { + const out: string[] = []; + const code = await main(["--help"], { out: (line) => out.push(line), err: () => undefined }); + expect(code).toBe(0); + expect(out.join("\n")).toContain("Usage: pi2d [options]"); + expect(out.join("\n")).toContain("--static-dir"); + }); + + it("prints the version for --version", async () => { + const out: string[] = []; + const code = await main(["--version"], { out: (line) => out.push(line), err: () => undefined }); + expect(code).toBe(0); + expect(out[0]).toMatch(/^pi2d \d+\.\d+\.\d+/); + }); + + it("exits 2 on bad arguments", async () => { + const err: string[] = []; + const code = await main(["--port", "nope"], { + out: () => undefined, + err: (line) => err.push(line), + }); + expect(code).toBe(2); + expect(err[0]).toContain("--port must be an integer"); + }); +}); + +describe("local CLI token", () => { + let dir: string; + + beforeEach(() => { + dir = tempDir("pi2-token-"); + }); + + afterEach(() => removeDir(dir)); + + it("is 32 bytes of hex, written atomically with mode 0600", () => { + const path = join(dir, "run", "cli.token"); + const token = writeCliToken(path); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(statSync(path).mode & 0o777).toBe(0o600); + expect(readFileSync(path, "utf8").trim()).toBe(token); + expect(readCliToken(path)).toBe(token); + expect(tokenPerms(path)).toEqual({ exists: true, mode: 0o600 }); + }); + + it("rotates on every start", () => { + const path = join(dir, "cli.token"); + const first = writeCliToken(path); + const second = writeCliToken(path); + expect(second).not.toBe(first); + expect(readCliToken(path)).toBe(second); + }); + + it("reads as undefined when missing", () => { + const path = join(dir, "missing.token"); + expect(readCliToken(path)).toBeUndefined(); + expect(tokenPerms(path)).toEqual({ exists: false, mode: undefined }); + }); + + it("tightens the mode of a pre-existing world-readable token", () => { + const path = join(dir, "cli.token"); + writeCliToken(path); + chmodSync(path, 0o644); + writeCliToken(path); + expect(statSync(path).mode & 0o777).toBe(0o600); + }); +}); diff --git a/test/cli/service.test.ts b/test/cli/service.test.ts new file mode 100644 index 0000000..4876ae4 --- /dev/null +++ b/test/cli/service.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it } from "vitest"; +import { join } from "node:path"; +import { + defaultScriptPath, + launchAgentDir, + renderLaunchAgent, + renderService, + renderSystemdUnit, + serviceDir, + systemdUserDir, + type ServicePaths, +} from "../../src/cli/service.js"; +import { runInstallService, runUninstallService } from "../../src/cli/pi2.js"; + +const paths: ServicePaths = { + nodePath: "/opt/node/bin/node", + scriptPath: "/repo/dist/cli/pi2d.js", + stateDir: "/home/u/.local/state/pi2", + homeDir: "/home/u", + pathEnv: "/opt/node/bin:/usr/bin:/bin", +}; + +const LINUX_UNIT = `[Unit] +Description=pi2 daemon (pi2d) +After=network.target + +[Service] +Type=simple +ExecStart=/opt/node/bin/node /repo/dist/cli/pi2d.js --foreground +Environment=PATH=/opt/node/bin:/usr/bin:/bin +Restart=on-failure +RestartSec=2 +KillSignal=SIGTERM +TimeoutStopSec=15 + +[Install] +WantedBy=default.target +`; + +const MAC_PLIST = `<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>Label</key> + <string>com.pi2.pi2d</string> + <key>ProgramArguments</key> + <array> + <string>/opt/node/bin/node</string> + <string>/repo/dist/cli/pi2d.js</string> + <string>--foreground</string> + </array> + <key>EnvironmentVariables</key> + <dict> + <key>PATH</key> + <string>/opt/node/bin:/usr/bin:/bin</string> + </dict> + <key>RunAtLoad</key> + <true/> + <key>KeepAlive</key> + <true/> + <key>StandardOutPath</key> + <string>/home/u/.local/state/pi2/pi2d.log</string> + <key>StandardErrorPath</key> + <string>/home/u/.local/state/pi2/pi2d.err.log</string> +</dict> +</plist> +`; + +describe("systemd user unit", () => { + it("renders the unit (snapshot)", () => { + expect(renderSystemdUnit(paths)).toBe(LINUX_UNIT); + }); + + it("adds extra Environment= entries", () => { + const unit = renderSystemdUnit({ ...paths, env: { PI2_PORT: "7676", PI2_LOG_LEVEL: "debug" } }); + expect(unit).toContain("Environment=PATH=/opt/node/bin:/usr/bin:/bin"); + expect(unit).toContain("Environment=PI2_PORT=7676"); + expect(unit).toContain("Environment=PI2_LOG_LEVEL=debug"); + expect(unit.indexOf("Environment=PI2_PORT")).toBeGreaterThan(unit.indexOf("ExecStart=")); + }); + + it("quotes values with spaces", () => { + const unit = renderSystemdUnit({ ...paths, scriptPath: "/repo dir/cli/pi2d.js" }); + expect(unit).toContain('ExecStart=/opt/node/bin/node "/repo dir/cli/pi2d.js" --foreground'); + }); + + it("targets ~/.config/systemd/user and honours XDG_CONFIG_HOME", () => { + expect(systemdUserDir(paths)).toBe("/home/u/.config/systemd/user"); + expect(systemdUserDir({ ...paths, configHome: "/xdg" })).toBe("/xdg/systemd/user"); + const service = renderService("linux", paths); + expect(service.path).toBe("/home/u/.config/systemd/user/pi2d.service"); + expect(service.name).toBe("pi2d.service"); + expect(serviceDir(service)).toBe("/home/u/.config/systemd/user"); + expect(service.commands).toEqual([ + "systemctl --user daemon-reload", + "systemctl --user enable --now pi2d.service", + ]); + expect(service.removeCommands).toContain("systemctl --user disable --now pi2d.service"); + }); +}); + +describe("LaunchAgent plist", () => { + it("renders the plist (snapshot)", () => { + expect(renderLaunchAgent(paths)).toBe(MAC_PLIST); + }); + + it("escapes XML in paths", () => { + const plist = renderLaunchAgent({ ...paths, nodePath: "/opt/a&b/node" }); + expect(plist).toContain("<string>/opt/a&b/node</string>"); + }); + + it("targets ~/Library/LaunchAgents", () => { + expect(launchAgentDir(paths)).toBe("/home/u/Library/LaunchAgents"); + const service = renderService("darwin", paths); + expect(service.path).toBe("/home/u/Library/LaunchAgents/com.pi2.pi2d.plist"); + expect(service.name).toBe("com.pi2.pi2d.plist"); + expect(service.commands[0]).toContain("launchctl bootstrap gui/$(id -u)"); + expect(service.removeCommands[0]).toContain("launchctl bootout"); + }); + + it("resolves dist/cli/pi2d.js next to the built CLI", () => { + expect(defaultScriptPath()).toMatch(/dist\/cli\/pi2d\.js$/); + }); +}); + +describe("install-service / uninstall-service commands", () => { + it("prints the unit on --dry-run and writes nothing", () => { + const lines: string[] = []; + const writes: string[] = []; + const code = runInstallService({ + platform: "linux", + paths, + write: false, + print: (line) => lines.push(line), + writeFile: (path) => writes.push(path), + }); + expect(code).toBe(0); + expect(writes).toEqual([]); + expect(lines.join("\n")).toContain("[Service]"); + expect(lines.join("\n")).toContain("would write /home/u/.config/systemd/user/pi2d.service"); + expect(lines.join("\n")).toContain("systemctl --user enable --now pi2d.service"); + }); + + it("writes the unit on --write and prints the enable commands", () => { + const lines: string[] = []; + const writes: { path: string; content: string }[] = []; + const code = runInstallService({ + platform: "linux", + paths, + write: true, + print: (line) => lines.push(line), + writeFile: (path, content) => writes.push({ path, content }), + }); + expect(code).toBe(0); + expect(writes).toEqual([{ path: join("/home/u/.config/systemd/user", "pi2d.service"), content: LINUX_UNIT }]); + expect(lines[0]).toBe("wrote /home/u/.config/systemd/user/pi2d.service (mode 0644)"); + expect(lines.join("\n")).toContain("systemctl --user daemon-reload"); + }); + + it("uninstall removes the unit only with --write", () => { + const removed: string[] = []; + const dry: string[] = []; + expect( + runUninstallService({ + platform: "darwin", + paths, + write: false, + print: (line) => dry.push(line), + removeFile: (path) => removed.push(path), + }), + ).toBe(0); + expect(removed).toEqual([]); + expect(dry.join("\n")).toContain("would remove /home/u/Library/LaunchAgents/com.pi2.pi2d.plist"); + + const lines: string[] = []; + expect( + runUninstallService({ + platform: "darwin", + paths, + write: true, + print: (line) => lines.push(line), + removeFile: (path) => removed.push(path), + }), + ).toBe(0); + expect(removed).toEqual(["/home/u/Library/LaunchAgents/com.pi2.pi2d.plist"]); + expect(lines.join("\n")).toContain("launchctl bootout"); + }); +}); diff --git a/test/cli/wiring.test.ts b/test/cli/wiring.test.ts new file mode 100644 index 0000000..7a31400 --- /dev/null +++ b/test/cli/wiring.test.ts @@ -0,0 +1,102 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { PROTOCOL_VERSION } from "../../src/protocol/types.js"; +import { writeCliToken } from "../../src/cli/token.js"; +import { wireDaemon, type WiredDaemon } from "../../src/cli/wiring.js"; +import { clearRuntimeEnv, removeDir, setRuntimeEnv, silentLogger, tempDir } from "./helpers.js"; + +describe("wireDaemon", () => { + let dir: string; + let wired: WiredDaemon | undefined; + + beforeEach(() => { + dir = tempDir(); + setRuntimeEnv(dir); + mkdirSync(join(dir, "web"), { recursive: true }); + writeFileSync(join(dir, "web", "index.html"), "<!doctype html><title>pi2

"); + mkdirSync(join(dir, "sessions"), { recursive: true }); + }); + + afterEach(async () => { + if (wired !== undefined) await wired.close(); + wired = undefined; + clearRuntimeEnv(); + removeDir(dir); + }); + + it("boots on port 0 with temp dirs and serves info, health and the static UI", async () => { + wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") }); + const token = writeCliToken(wired.cliTokenPath); + const server = await wired.start(); + + expect(server.port).toBeGreaterThan(0); + expect(wired.config.port).toBe(server.port); + expect(wired.config.host).toBe("127.0.0.1"); + expect(wired.deps.daemonId).toMatch(/^d-/); + expect(wired.deps.instances).toBe(wired.instanceManager); + expect(wired.deps.workspaces).toBe(wired.workspaceStore); + expect(wired.deps.auth).toBe(wired.auth); + + const info = await fetch(`${server.url}/api/v1/info`); + expect(info.status).toBe(200); + const infoBody = (await info.json()) as { v: number; daemonId: string; capabilities: string[] }; + expect(infoBody.v).toBe(PROTOCOL_VERSION); + expect(infoBody.daemonId).toBe(wired.deps.daemonId); + expect(infoBody.capabilities).toContain("ws"); + + const health = await fetch(`${server.url}/api/v1/health`); + expect(health.status).toBe(200); + const healthBody = (await health.json()) as { ok: boolean; items: { name: string; ok: boolean }[] }; + expect(healthBody.ok).toBe(true); + expect(healthBody.items.find((item) => item.name === "static")?.ok).toBe(true); + + const page = await fetch(`${server.url}/`); + expect(page.status).toBe(200); + expect(page.headers.get("content-type")).toContain("text/html"); + expect(await page.text()).toContain("
"); + + // The minted CLI token authenticates as the local admin device. + const authorized = await fetch(`${server.url}/api/v1/workspaces`, { + headers: { authorization: `Bearer ${token}` }, + }); + expect(authorized.status).toBe(200); + expect(Array.isArray(await authorized.json())).toBe(true); + + const anonymous = await fetch(`${server.url}/api/v1/workspaces`); + expect(anonymous.status).toBe(401); + }); + + it("starts the plugin unix socket in the configured runtime dir", async () => { + wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") }); + const { existsSync } = await import("node:fs"); + expect(existsSync(join(dir, "run", "d.sock"))).toBe(true); + expect(existsSync(join(dir, "run", "d.sock.token"))).toBe(true); + + await wired.close(); + wired = undefined; + expect(existsSync(join(dir, "run", "d.sock"))).toBe(false); + }); + + it("resolves workspace cwd through the store and rejects unknown workspaces", async () => { + wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") }); + await expect(wired.instanceManager.ensure("ws-missing", { timeoutMs: 100 })).rejects.toMatchObject({ + code: "E_NOT_FOUND", + }); + }); + + it("is idempotent on start()", async () => { + wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") }); + const first = await wired.start(); + const second = await wired.start(); + expect(second).toBe(first); + }); + + it("close() is idempotent", async () => { + wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") }); + await wired.start(); + await wired.close(); + await wired.close(); + wired = undefined; + }); +});