diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2b0a080..9c3dd2c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -76,3 +76,76 @@ jobs: } console.log(`tarball ok: ${files.length} files`); ' + + binary: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + with: + version: 10 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + cache-dependency-path: | + pnpm-lock.yaml + web/pnpm-lock.yaml + + - uses: oven-sh/setup-bun@v2 + + - name: Install daemon deps + run: pnpm install --frozen-lockfile + + - name: Install web deps + run: pnpm --dir web install --frozen-lockfile + + - name: Build standalone binary (musl) + run: bash scripts/build-binary.sh --target bun-linux-x64-musl + + - name: Boot check + run: | + sudo apt-get update -y && sudo apt-get install -y musl + if [ ! -f /lib/ld-musl-x86_64.so.1 ]; then + MUSL_LIB="$(find /usr/lib /lib -name 'libc.musl*' -o -name 'ld-musl*' 2>/dev/null | head -n 1)" + if [ -n "$MUSL_LIB" ]; then + sudo ln -s "$MUSL_LIB" /lib/ld-musl-x86_64.so.1 + fi + fi + + TMP="$(mktemp -d)" + export PI2_RUNTIME_DIR="$TMP/run" + export PI2_DATA_DIR="$TMP/data" + export PI2_STATE_DIR="$TMP/state" + mkdir -p "$PI2_RUNTIME_DIR" "$PI2_DATA_DIR" "$PI2_STATE_DIR" + + dist-bin/bin/pi2 daemon --port 0 > "$TMP/daemon.log" 2>&1 & + PID=$! + trap 'kill -TERM "$PID" 2>/dev/null || true; rm -rf "$TMP"' EXIT + + for _ in $(seq 1 50); do + [ -f "$PI2_RUNTIME_DIR/daemon.json" ] && break + kill -0 "$PID" 2>/dev/null || break + sleep 0.1 + done + + if [ ! -f "$PI2_RUNTIME_DIR/daemon.json" ]; then + echo "daemon failed to start; log:" >&2 + cat "$TMP/daemon.log" >&2 + exit 1 + fi + + PORT="$(node -p 'require(process.env.PI2_RUNTIME_DIR + "/daemon.json").port')" + STATUS="$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${PORT}/api/v1/info")" + if [ "$STATUS" != "200" ]; then + echo "expected HTTP 200 from /api/v1/info, got $STATUS" >&2 + exit 1 + fi + + echo "Standalone binary boot check passed (HTTP $STATUS on port $PORT)" + kill -TERM "$PID" 2>/dev/null || true + wait "$PID" 2>/dev/null || true + trap - EXIT + rm -rf "$TMP" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 61c1a89..3283b08 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,11 +9,7 @@ on: # The publish step deliberately gets no NPM_TOKEN / NODE_AUTH_TOKEN env. # See docs/releasing.md. permissions: - # `contents: write` is for the `softprops/action-gh-release` step below, which - # creates the GitHub release; with `contents: read` it fails with 403. Kept at - # workflow level (single job) so the release step does not need a second job - # with its own checkout/install/test cycle. - contents: write + contents: write # create GitHub release and upload binary assets id-token: write # mint the OIDC token npm exchanges for publish rights jobs: @@ -133,3 +129,270 @@ jobs: `npm i -g @yuez/pi2d@${{ github.ref_name }}` Compatible pi2.nvim: protocol v1 (see `docs/protocol.md`). + + binaries: + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + # ubuntu-24.04-arm is GA for public repositories. Running linux-arm64 and + # linux-arm64-musl on native ARM64 runners lets us actually execute and + # boot-check the artifact before publishing it (all six legs are host-native). + include: + - target: linux-x64 + runner: ubuntu-latest + - target: linux-arm64 + runner: ubuntu-24.04-arm + - target: linux-x64-musl + runner: ubuntu-latest + - target: linux-arm64-musl + runner: ubuntu-24.04-arm + - target: darwin-x64 + runner: macos-13 + - target: darwin-arm64 + runner: macos-14 + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + with: + version: 10 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + cache-dependency-path: | + pnpm-lock.yaml + web/pnpm-lock.yaml + + - uses: oven-sh/setup-bun@v2 + + - name: Install deps + run: | + pnpm install --frozen-lockfile + pnpm --dir web install --frozen-lockfile + + - name: Build binary tarball + run: bash scripts/build-binary.sh --target ${{ matrix.target }} + + - name: Boot check + run: | + case "${{ matrix.target }}" in + *musl*) + ARCH="$(uname -m)" + [ "$ARCH" = "arm64" ] && ARCH="aarch64" + LOADER="/lib/ld-musl-${ARCH}.so.1" + if [ ! -f "$LOADER" ]; then + sudo apt-get update -y && sudo apt-get install -y musl + if [ ! -f "$LOADER" ]; then + MUSL_LIB="$(find /usr/lib /lib -name 'libc.musl*' -o -name 'ld-musl*' 2>/dev/null | head -n 1)" + if [ -n "$MUSL_LIB" ]; then + sudo ln -s "$MUSL_LIB" "$LOADER" + fi + fi + fi + ;; + esac + + TMP="$(mktemp -d)" + export PI2_RUNTIME_DIR="$TMP/run" + export PI2_DATA_DIR="$TMP/data" + export PI2_STATE_DIR="$TMP/state" + mkdir -p "$PI2_RUNTIME_DIR" "$PI2_DATA_DIR" "$PI2_STATE_DIR" + + dist-bin/bin/pi2 daemon --port 0 > "$TMP/stdout.log" 2> "$TMP/daemon.log" & + PID=$! + trap 'kill -TERM "$PID" 2>/dev/null || true; rm -rf "$TMP"' EXIT + + for _ in $(seq 1 100); do + if grep -q "listening on http://" "$TMP/stdout.log" 2>/dev/null; then + break + fi + kill -0 "$PID" 2>/dev/null || break + sleep 0.1 + done + + if ! grep -q "listening on http://" "$TMP/stdout.log" 2>/dev/null; then + echo "daemon failed to start or emit listening line; stdout:" >&2 + cat "$TMP/stdout.log" >&2 || true + echo "daemon stderr:" >&2 + cat "$TMP/daemon.log" >&2 || true + exit 1 + fi + + URL="$(grep -o 'http://[^ ]*' "$TMP/stdout.log" | head -n 1)" + INFO="$(curl -fsS "$URL/api/v1/info")" + + tag="${GITHUB_REF_NAME#v}" + node -e ' + const info = JSON.parse(process.argv[1]); + const tag = process.argv[2]; + const ref = process.argv[3]; + if (info.v !== 1) { + console.error(`expected v: 1, got ${info.v}`); + process.exit(1); + } + if (info.version !== tag && info.version !== ref) { + console.error(`expected version ${tag} (or ${ref}), got ${info.version}`); + process.exit(1); + } + console.log(`Boot check ok: v=${info.v}, version=${info.version}`); + ' "$INFO" "$tag" "$GITHUB_REF_NAME" + + kill -TERM "$PID" + set +e + wait "$PID" + EXIT_CODE=$? + set -e + trap - EXIT + rm -rf "$TMP" + + if [ "$EXIT_CODE" -ne 0 ]; then + echo "daemon exited with code $EXIT_CODE on SIGTERM (expected 0)" >&2 + exit 1 + fi + + - name: Upload binary tarball artifact + uses: actions/upload-artifact@v4 + with: + name: pi2d-${{ matrix.target }} + path: dist-bin/pi2d-*.tar.gz + if-no-files-found: error + + checksums: + needs: [publish, binaries] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Download all binary artifacts + uses: actions/download-artifact@v4 + with: + pattern: pi2d-* + path: dist-bin + merge-multiple: true + + - name: Generate SHA256SUMS + run: | + cd dist-bin + sha256sum pi2d-*.tar.gz > SHA256SUMS + echo "Generated SHA256SUMS:" + cat SHA256SUMS + sha256sum -c SHA256SUMS + COUNT="$(wc -l < SHA256SUMS)" + if [ "$COUNT" -ne 6 ]; then + echo "Expected 6 checksums, got $COUNT" >&2 + exit 1 + fi + + - name: Upload SHA256SUMS artifact + uses: actions/upload-artifact@v4 + with: + name: checksums + path: dist-bin/SHA256SUMS + if-no-files-found: error + + - name: Append artifacts to GitHub release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ github.ref_name }} + files: | + dist-bin/*.tar.gz + dist-bin/SHA256SUMS + + packaging: + needs: checksums + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Download checksums artifact + uses: actions/download-artifact@v4 + with: + name: checksums + + - name: Render packaging manifests + run: | + tag="${GITHUB_REF_NAME#v}" + bash scripts/update-packaging.sh \ + --version "$tag" \ + --checksums SHA256SUMS \ + --out build/packaging \ + --no-download + + - name: Upload rendered packaging files + uses: actions/upload-artifact@v4 + with: + name: packaging + path: build/packaging/ + if-no-files-found: error + + - name: Update Homebrew tap formula + if: secrets.HOMEBREW_TAP_TOKEN != '' + env: + HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} + run: | + version="${GITHUB_REF_NAME#v}" + echo "HOMEBREW_TAP_TOKEN is present; pushing formula to zgs225/homebrew-tap..." + git clone "https://x-access-token:${HOMEBREW_TAP_TOKEN}@github.com/zgs225/homebrew-tap.git" tap-repo + mkdir -p tap-repo/Formula + cp build/packaging/pi2d.rb tap-repo/Formula/pi2d.rb + cd tap-repo + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add Formula/pi2d.rb + if git diff --staged --quiet; then + echo "Formula/pi2d.rb is already up to date" + else + git commit -m "pi2d ${version}" + git push origin HEAD + echo "Successfully pushed Formula/pi2d.rb to zgs225/homebrew-tap" + fi + + - name: Update Arch Linux AUR package + if: secrets.AUR_SSH_KEY != '' + env: + AUR_SSH_KEY: ${{ secrets.AUR_SSH_KEY }} + run: | + version="${GITHUB_REF_NAME#v}" + echo "AUR_SSH_KEY is present; pushing to aur@aur.archlinux.org/pi2d-bin.git..." + mkdir -p ~/.ssh + echo "$AUR_SSH_KEY" > ~/.ssh/aur_ed25519 + chmod 600 ~/.ssh/aur_ed25519 + ssh-keyscan -H aur.archlinux.org >> ~/.ssh/known_hosts 2>/dev/null || true + export GIT_SSH_COMMAND="ssh -i ~/.ssh/aur_ed25519 -o StrictHostKeyChecking=accept-new" + git clone ssh://aur@aur.archlinux.org/pi2d-bin.git aur-repo + cp build/packaging/PKGBUILD build/packaging/.SRCINFO aur-repo/ + cd aur-repo + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add PKGBUILD .SRCINFO + if git diff --staged --quiet; then + echo "AUR package is already up to date" + else + git commit -m "pi2d ${version}" + git push origin master + echo "Successfully pushed to AUR pi2d-bin" + fi + + - name: Manual packaging instructions + env: + HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} + AUR_SSH_KEY: ${{ secrets.AUR_SSH_KEY }} + run: | + version="${GITHUB_REF_NAME#v}" + if [ -z "${HOMEBREW_TAP_TOKEN:-}" ]; then + echo "HOMEBREW_TAP_TOKEN not set; skipping automated Homebrew tap update." + echo "To update manually:" + echo " git clone https://github.com/zgs225/homebrew-tap.git" + echo " cp /pi2d.rb homebrew-tap/Formula/pi2d.rb" + echo " cd homebrew-tap && git add Formula/pi2d.rb && git commit -m 'pi2d ${version}' && git push origin main" + fi + if [ -z "${AUR_SSH_KEY:-}" ]; then + echo "AUR_SSH_KEY not set; skipping automated AUR update." + echo "To update manually:" + echo " git clone ssh://aur@aur.archlinux.org/pi2d-bin.git" + echo " cp /PKGBUILD /.SRCINFO pi2d-bin/" + echo " cd pi2d-bin && git add PKGBUILD .SRCINFO && git commit -m 'pi2d ${version}' && git push origin master" + fi diff --git a/.gitignore b/.gitignore index 72d8a00..0e0016d 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ coverage/ *.log .DS_Store tmp/ +dist-bin/ diff --git a/AGENTS.md b/AGENTS.md index 5cb61ec..daa5607 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,8 +15,8 @@ Adding bulk to this file is a mistake, not a contribution. | Install | `pnpm install && pnpm --dir web install` | | Typecheck | `pnpm typecheck && pnpm --dir web typecheck` | | Unit tests | `pnpm test` (daemon) · `pnpm --dir web exec vitest run` (web) | -| Build | `pnpm build` → `dist/` · `pnpm build:web` → `web/dist/` | -| Smoke | `bash scripts/smoke.sh` — isolated tmp dirs, asserts HTTP, static UI, tokens, clean SIGTERM | +| Build | `pnpm build` → `dist/` · `pnpm build:web` → `web/dist/` · `pnpm build:binary` → `dist-bin/` | +| Smoke | `bash scripts/smoke.sh` (Node) · `bash scripts/smoke-binary.sh` (compiled binary) | | E2E | `bash scripts/e2e/run-all.sh` — API suite then Playwright; needs a real `pi`, `nvim`, `curl` | | Dev loop | `pnpm dev` (:7676) · `pnpm --dir web dev` (:5173, proxies `/api` + `/ws`) | | Release | skill `.agents/skills/release/` | @@ -34,9 +34,10 @@ Adding bulk to this file is a mistake, not a contribution. | `src/core/network.ts` | reachable addresses: kind classification, `bases[]` order, CORS origins | | `src/core/qr.ts` | zero-dependency QR encoder (pairing links; rows, no quiet zone) | | `web/` | React console (own lockfile + workspace); built into `web/dist` and served by the daemon | +| `packaging/` | Homebrew formula & Arch AUR PKGBUILD templates, generator script | | `fixtures/` | golden event streams + expected state, shared with pi2.nvim conformance tests | | `test/` | vitest, hermetic, injectable I/O | -| `scripts/` | `smoke.sh`, `e2e/` drivers, `gen-expected.ts` | +| `scripts/` | `install.sh`, `build-binary.sh`, `smoke*.sh`, `e2e/` drivers, `gen-expected.ts` | ## Hard rules @@ -67,6 +68,7 @@ owner/repo/workflow filename, not the npm name). | Doc | Contents | |---|---| | `docs/protocol.md` | the browser ↔ daemon ↔ plugin wire contract | +| `docs/install.md` | canonical CLI-first install guide, channels, run modes, services | | `docs/session-dot.md` | the session-list status dot: the `:PiSessions` matrix, the unread flags, the one blink clock | | `docs/deployment.md` | env vars, runtime files, ports, auth, services, troubleshooting | | `docs/e2e.md` | scenario ids, isolation, skip conditions, report paths | diff --git a/README.md b/README.md index c35cbbe..570fabf 100644 --- a/README.md +++ b/README.md @@ -16,43 +16,117 @@ Hard rules (see `docs/protocol.md`): ## Install -Requirements: **Node >= 22**, **Neovim >= 0.9**, the **`pi` CLI** on `PATH`. +The documented model is **CLI-first** ([ADR 0002](docs/adr/0002-install-and-run.md)): install the `pi2` CLI, optionally run it as a user service, and let the Neovim plugin attach as a client. -You do not normally install this by hand. The pi2.nvim plugin detects a missing daemon, -offers to install it into its own data directory (no sudo, no global `PATH` edits) and -starts it lazily. The result is one command inside Neovim: +Requirements: **Node >= 20** (for the npm channel; the curl installer and system packages ship bundled binaries with no Node dependency), **Neovim >= 0.9**, and the **`pi` CLI** on `PATH`. -``` -:PiWeb -``` +> **Status.** The daemon CLI, the web console and the standalone installer are ready today (`npm i -g @yuez/pi2d` and `install.sh` work today). `:PiWeb` and `:PiWebInstall` land with the next pi2.nvim release, so today the flow is `pi2 daemon` + `pi2 open` (or running the daemon as a user service). -…which opens your browser already signed in, showing the current workspace. +### Channel A: Global package manager (Node >= 20) -> **Status.** The npm package, the packaged web console and the lazy-start contract are -> ready (`npm i -g @yuez/pi2d` works today). `:PiWeb`, `:PiWebInstall` and the access-mode prompt -> land with the next pi2.nvim release; until then use `:PiWebStart` plus a manual install. - -### Package managers (optional, for CLI-first users) +If your machine has Node >= 20: ```bash -npm i -g @yuez/pi2d # installs the `pi2` binary +npm i -g @yuez/pi2d +# or: pnpm add -g @yuez/pi2d bun add -g @yuez/pi2d +mise use -g npm:@yuez/pi2d ``` -Then: +### Channel B: Standalone curl installer (no Node required) + +For machines without Node, with an older distro Node (e.g. Debian 12 ships 18), or where you want a self-contained installation with no global npm or root access: ```bash -pi2 daemon # foreground; the plugin/browser needs this running -pi2 stop # stop a running daemon (or: pi2 daemon stop) -pi2 install-service --write # or run it at login: systemd --user / launchd -pi2 status # daemon + instances + health -pi2 doctor # node/nvim/pi/curl/plugin/runtime/web-dist/protocol checks +curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh ``` -`pi2` is the only executable (`@yuez/pi2d` is the npm package name); `pi2 daemon` is a subcommand -of it, not a separate process. Runtime files, ports, auth, services and troubleshooting: -[docs/deployment.md](docs/deployment.md). +Installs the precompiled binary and web console to `~/.local/lib/pi2d` and symlinks the executable to `~/.local/bin/pi2`. + +To uninstall: + +```bash +curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall +``` + +### Channel C: System packages (Homebrew & AUR) + +*(Available once the release that publishes binaries has shipped)*: + +- **macOS / Linux (Homebrew tap):** + ```bash + brew install zgs225/tap/pi2d + ``` +- **Arch Linux / Manjaro / EndeavourOS (AUR):** + ```bash + paru -S pi2d-bin # or: yay -S pi2d-bin + ``` + +For full installation options and a situation-based guide, see the [Decision table in docs/install.md](docs/install.md#decision-table). + +## Run + +`pi2` is the only executable (`@yuez/pi2d` is the npm package name); `pi2 daemon` is a subcommand of it. Choose one of three run modes: + +### 1. User service (recommended for an always-on console) + +The daemon's value proposition is an always-on URL that stays up across editor restarts and reboots. Generate and write the service unit: + +```bash +pi2 install-service --write +``` + +- **Linux (`systemd --user`)**: writes `~/.config/systemd/user/pi2.service` (loads environment variables from `~/.config/pi2/env` if present). Enable and start it: + ```bash + systemctl --user daemon-reload + systemctl --user enable --now pi2.service + ``` + Logs stream to systemd journal: + ```bash + journalctl --user -u pi2.service -f + ``` + *(To keep the service running across SSH logouts, run `loginctl enable-linger`.)* +- **macOS (`launchd`)**: writes `~/Library/LaunchAgents/com.pi2.daemon.plist`. Load and start it: + ```bash + launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pi2.daemon.plist + launchctl enable gui/$(id -u)/com.pi2.daemon + launchctl kickstart -k gui/$(id -u)/com.pi2.daemon + ``` + Logs go to `~/Library/Logs/pi2/pi2-daemon.log` and `pi2-daemon.err.log`. + +To remove the service: `pi2 uninstall-service --write`. Note that in service mode, stopping the daemon must go through your service manager (e.g. `systemctl --user stop pi2.service`), as process kills will trigger service restarts. + +### 2. Foreground process + +For testing or debugging, run directly in a terminal: + +```bash +pi2 daemon # foreground; logs stream to terminal stdout/stderr +pi2 open # open console signed in (local browser) +pi2 stop # stop the running daemon from another terminal (or: pi2 daemon stop) +``` + +### 3. Neovim plugin autostart (coming with next pi2.nvim release) + +When configured with `web.autostart = "spawn"`, pi2.nvim spawns a detached background `pi2 daemon` when you invoke `:PiWeb`. Logs go to `$PI2_STATE_DIR/daemon.log` (`~/.local/state/pi2/daemon.log` on Linux, `~/Library/Logs/pi2/daemon.log` on macOS). + +See the [Decision table in docs/install.md](docs/install.md#decision-table) for how to pick the right mode for your workflow. + +### Useful CLI commands + +```bash +pi2 daemon # foreground daemon +pi2 stop # stop running daemon (alias: pi2 daemon stop) +pi2 open # open browser console signed in (loopback only) +pi2 install-service --write # render and write user service file +pi2 uninstall-service --write # remove user service file +pi2 status # daemon status, active instances, and health +pi2 doctor # verify node/runtime, nvim, pi, curl, sockets, protocol +pi2 --version # print version +``` + +Runtime files, ports, auth, services and troubleshooting: [docs/deployment.md](docs/deployment.md). ### Neovim plugin @@ -64,19 +138,17 @@ of it, not a separate process. Runtime files, ports, auth, services and troubles } ``` -`:PiWeb` is the whole install path: it resolves the daemon binary, installs it if needed, -spawns it, waits for the socket, and hands the browser a one-time login token. Nothing else -to configure. +The plugin acts as a client: it connects to the running daemon or starts one using `pi2` on `$PATH`. +Once connected, `:PiWeb` opens your browser already signed in to the current workspace. -The plugin looks for the daemon in this order, and `:PiWebStatus` reports which one won: +The plugin resolves the daemon binary in this order (`:PiWebStatus` reports which one won): | # | Source | Where | |---|---|---| -| 1 | `web.daemon` / `$PI2_DAEMON_BIN` | explicit path or command name | -| 2 | `pi2` on `PATH` | a global install | -| 3 | plugin data dir | `/pi2d/node_modules/.bin/pi2` | +| 1 | `web.binary` / `$PI2_DAEMON_BIN` | explicit path or command name | +| 2 | `pi2` on `PATH` | a global CLI install (recommended) | +| 3 | plugin data dir | `/pi2d/node_modules/.bin/pi2` (only if `:PiWebInstall` ran) | | 4 | repo checkout | `node_modules/.bin/pi2` (developing pi2d itself) | -| 5 | `npx -y @yuez/pi2d@latest` | last resort when nothing is writable | ## Remote access (phone, LAN, Tailscale) diff --git a/docs/adr/0002-install-and-run.md b/docs/adr/0002-install-and-run.md new file mode 100644 index 0000000..3af7a5b --- /dev/null +++ b/docs/adr/0002-install-and-run.md @@ -0,0 +1,309 @@ +# ADR 0002 — Installation and run model: CLI first, service-owned daemon, plugin attaches + +- Status: accepted (implementing) +- Date: 2026-10-28 +- Supersedes: the implicit "the plugin installs and spawns the daemon" default in + `README.md` §Install and the resolution table (explicit path → `PATH` → plugin + data dir → repo checkout → `npx @latest`) + +## Context + +`pi2d` is two things at once, and that is why its install story drifted: + +1. a **CLI** (`pi2` + `pi2 daemon`) that serves the web console and supervises one + headless nvim per workspace, and +2. a **dependency of a Neovim plugin** (`:PiWeb` is the only way most users will + ever meet it). + +Today the documented path is the second one: the plugin finds no daemon, `npm +install`s `@yuez/pi2d` into `/pi2d`, spawns it detached, and mints +a loopback token. It works, but it makes the plugin an installer and a supervisor, +which is the exact shape the rest of the ecosystem avoids. Nine reference +implementations were surveyed (see §1). + +## 1. How the reference implementations do it + +| Agent | Install channels | Long-lived process | Self-update | How editors attach | +|---|---|---|---|---| +| **pi** (`@earendil-works/pi-coding-agent`) | `curl -fsSL https://pi.dev/install.sh \| sh` → *managed install*: its own Node under `~/.local/share/pi-node`, launcher in `~/.local/bin`, `managed-install.json` marker; `npm i -g --ignore-scripts` (Node ≥22.19); `nix profile add`; bun-compiled single binary in releases | foreground CLI; `pi --mode rpc` is the long-lived JSONL process a client drives | `pi update [self]` (`pi update` cannot update Nix installs) | the plugin **spawns** `pi --mode rpc` and speaks JSONL; the SDK embeds it in-process | +| **dsh** (DeepSeek Harness) | npm package under a version manager (mise `npm-deepseek-ai-dsh`), `dsh` launcher; profile plugins via `dsh plugin … pnpm` | `dsh web` = foreground HTTP+WS server (3080, `--host/--port/--no-open/--public-url/--tls-*`); also `dsh tui`, `dsh headless` | package manager | `dsh.nvim` spawns a **node bridge** (`bridge/bridge.mjs`) that dials `dsh web`; `auto_start` spawns the *server*, never installs it | +| **Claude Code** | native installer `curl -fsSL https://claude.ai/install.sh \| bash` (auto-updates); brew cask; winget; apt/dnf/apk; npm (legacy) | foreground CLI; IDE extensions spawn it and connect over a WS MCP socket | background auto-update (native); manual for brew/winget | `claudecode.nvim` runs the WS MCP **server inside nvim**; the `claude` binary on `PATH` is a hard requirement | +| **Codex CLI** | `curl -fsSL https://chatgpt.com/codex/install.sh \| sh` → standalone binaries (releases.openai.com, GitHub fallback); `npm i -g @openai/codex`; `brew install --cask codex`; raw tarballs | foreground CLI; `codex app-server` for IDE clients | package manager | IDE extension | +| **opencode** | `curl -fsSL https://opencode.ai/install \| bash`; npm/bun/pnpm/yarn; brew tap; pacman/AUR; choco/scoop; `mise use -g github:…`; Docker; raw releases | **TUI *and* a server**: `opencode serve` (default `127.0.0.1:4096`, OpenAPI 3.1 at `/doc`, `--mdns`, `--cors`, basic auth via `OPENCODE_SERVER_PASSWORD`) | package manager | IDE plugins drive a **running server** (`/tui` endpoint); the TUI itself is just a client | +| **gemini-cli** | `npx @google/gemini-cli`; `npm i -g` (`latest`/`preview`/`nightly`); brew; macports; conda | foreground CLI | npm dist-tag | (retired in favour of Antigravity) | +| **aider** | `curl -LsSf https://aider.chat/install.sh \| sh` (uv-backed, brings Python 3.12); `aider-install`; `uv tool install`; pipx; Docker | foreground CLI | `--upgrade` / package manager | — | +| **crush** | brew tap; `npm i -g @charmland/crush`; pacman; nix/NUR; apt repo; winget/scoop; FreeBSD pkg | foreground TUI (single Go binary) | package manager | — | +| **mason.nvim** (editor-side counter-example) | the *editor* installs into `stdpath("data")`, one `bin/` added to `$PATH`, registry-driven | n/a | `:MasonUpdate` | n/a | + +Common denominators, all nine agreeing: + +1. **The agent is a first-class CLI installed by a package manager or a `curl | sh` + installer — never by the editor plugin.** Plugins that *do* install (`mason.nvim`) + are infrastructure whose entire purpose is installing, with a registry behind them. +2. **Installers that bypass the OS package manager manage their own runtime** (pi + pins Node, aider pins Python via uv, claude/codex ship native binaries). "Your + distro's Node is too old" is never allowed to block the install. +3. **Self-update is an explicit command or an explicit policy** (`pi update`, + `claude`'s background updater, gemini dist-tags, brew upgrades), because agents + move faster than distros. +4. **The long-lived process is an explicit, separately-documented mode** (`pi --mode + rpc`, `dsh web`, `opencode serve`, `codex app-server`) with a stable wire contract, + and **the editor is a client of it**. +5. **Server modes bind loopback by default and take auth seriously** (opencode + password env, dsh accepts only a concrete interface, our loopback CLI token). +6. **Nobody silently auto-updates the server behind the editor's back.** Version skew + is handled by a version field in the handshake or a startup compatibility check. + +`pi2d`'s one genuine asymmetry: the daemon is **not** the agent. It routes to nvim, +which owns sessions. So a daemon alone does nothing (`/workspaces` would be empty of +live instances), and a plugin without a daemon has no browser console. Neither side +can be "the" entry point — but the *install* and the *process* can each have exactly +one owner, and today the plugin wrongly claims both. + +## 2. Decision + +### 2.1 Install: Tier-1 distribution channels and Node floor + +The primary distribution shifts from plugin-orchestrated npm installs to first-class +CLI distribution channels. + +#### Node engine floor: lowered to >= 20 + +The `package.json` `engines` requirement and `pi2 doctor` checks are lowered to +`node >= 20` (from `>= 22`). Nothing in `src/` requires Node 22-only features (no +`node:sqlite`, no `styleText`, no `import.meta.dirname`, no `--experimental-*`). +Lowering to Node 20 broadens compatibility for npm users (including enterprise LTS +and Debian/Ubuntu environments). When running as a compiled binary, no Node runtime +is needed at all. + +#### Tier-1 distribution channels (shipped as compiled binaries) + +Instead of the installer downloading and managing a separate Node runtime, all three +primary channels ship identical precompiled standalone binaries (`bun build --compile`): + +| Channel | Method | Target audience | Runtime dependency | +|---|---|---|---| +| **curl installer** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | Generic Linux & macOS | None (zero external dependencies) | +| **Homebrew tap** | `brew install zgs225/tap/pi2d` | macOS & Linux | None (standalone binary formula) | +| **Arch AUR (`-bin`)** | `paru -S pi2d-bin` / `yay -S pi2d-bin` | Arch Linux, EndeavourOS, Manjaro | None (standalone binary package) | +| **npm global** | `npm i -g @yuez/pi2d` (or `pnpm add -g`, `bun add -g`) | Node developers | Node >= 20 | +| **repo checkout** | `git clone … && pnpm install && pnpm build` | Contributors, offline development | Node >= 20, pnpm | + +The curl installer, Homebrew tap, and Arch AUR package are launched simultaneously (T1). +Because they distribute compiled binaries, the installer no longer needs to pin or install +Node under `~/.local/share/pi2-node`. + +#### Rejection of `npx` as an install or execution path + +Using `npx @yuez/pi2d@latest` or `npx` auto-execution is explicitly rejected: +1. **Network overhead on startup**: `npx` queries npm registries on first use or tag resolution, + introducing multi-second latency to editor startup. +2. **Phantom dependencies**: creates ephemeral cache directories or uncontrolled + `node_modules` under `stdpath("data")`. +3. **Supply chain exposure**: `@latest` resolution opens unpinned supply chain attack vectors. +4. **Version drift**: different editor sessions or background runs can resolve different + daemon versions simultaneously, corrupting singleton socket expectations. + +The plugin's `:PiWebInstall` becomes an explicit convenience command that prompts for +confirmation before installing a pinned version matching the plugin into +`/pi2d`. It never runs `npx`. + +### 2.2 Run: the daemon owns its own lifecycle + +| Mode | Who starts it | When to use | +|---|---|---| +| **user service (default)** | `pi2 install-service --write` → `systemctl --user` / `launchd`; `:PiWeb` only *uses* it | daily use, especially phone/another-browser access — the console has to be up when nvim is not | +| **plugin spawn** | `:PiWeb` spawns a detached `pi2 daemon` if nothing runs (`web.autostart = "spawn"`) | a machine where the user does not want a service; logs to `PI2_STATE_DIR/daemon.log` | +| **foreground** | the user, in a terminal | debugging, `pi2 daemon --foreground` | + +#### `web.autostart = "auto"` semantics + +The plugin setting `web.autostart = "auto"` follows strict three-step semantics: +1. **Attach if running**: Check if a daemon is already active (via `daemon.json` / `d.sock`). + If running, connect immediately — **never** spawn a second daemon. +2. **Start user service**: If an installed user service unit is found (`systemctl --user` or + `launchctl`), trigger unit start (`systemctl --user start pi2.service` or `launchctl kickstart`). +3. **Spawn detached**: If no service is installed, spawn a detached `pi2 daemon` process and + notify the user once in the editor. + +#### `:PiWebStop` behavior in service mode + +When the daemon is managed by a service manager (`systemd` or `launchd`), `:PiWebStop` +**must refuse** to stop the process. If a client terminates a service-managed daemon directly +via SIGTERM, `Restart=on-failure` (systemd) or `KeepAlive` (launchd) will immediately +attempt to restart it or enter an inconsistent state. The plugin must advise the user to +use `systemctl --user stop pi2` or `:PiWebService disable`. + +### 2.3 The plugin is a client + +`pi2.nvim` resolution order becomes, in order, with `:PiWebStatus` reporting the +winner: + +1. `web.binary` / `$PI2_DAEMON_BIN` (explicit path or command name) +2. `pi2` on `$PATH` (the normal case — the CLI install of §2.1) +3. `/pi2d/node_modules/.bin/pi2` (only if `:PiWebInstall` created it) +4. repo checkout `dist/cli/pi2.js` / `node_modules/.bin/pi2` (developing pi2d) +5. **nothing** → one-line error with the install command, no `npx` fallback + +Commands: `:PiWeb` (ensure + open), `:PiWebStatus`, `:PiWebStart`, `:PiWebStop`, +`:PiWebPair`, `:PiWebInstall`, `:PiWebService`, `:PiWebLog`. `:checkhealth pi` grows a +`web` section: binary source, version, daemon reachability, protocol match, service +state, autostart mode. + +### 2.4 Configuration stays environment-only + +The daemon keeps `PI2_*` env as the single config surface (`src/config.ts`, no file +parser, no precedence rules). Two additions: `pi2 config` prints the resolved +configuration plus the paths that produced it, and the systemd unit carries +`EnvironmentFile=-%h/.config/pi2/env` (the leading `-` instructs systemd to ignore missing +files). A `pi2.toml` is rejected: ~20 knobs, all deployment-time, all naturally expressed +as environment variables. + +### 2.5 Packaging: standalone binary contract + +#### Artifact contract + +Stand-alone binary releases are compiled with Bun (`bun build --compile`) and packaged +by `scripts/build-binary.sh` for six cross-compilation targets: +- `linux-x64` +- `linux-arm64` +- `linux-x64-musl` +- `linux-arm64-musl` +- `darwin-x64` +- `darwin-arm64` + +Each release produces a tarball named `pi2d--.tar.gz` and a top-level +`SHA256SUMS` manifest. + +#### Archive layout contract + +Every tarball unpacks with the exact layout: +``` +bin/ + pi2 +share/ + pi2d/ + web/ + dist/ + index.html + ... +LICENSE +``` + +#### Filesystem prefix rule: `/bin` + `/share/pi2d/web/dist` + +This directory structure conforms to standard Unix filesystem hierarchies (FHS). It is +the exact path probed at runtime by `src/core/install.ts`: +```typescript +resolve(dirname(executablePath()), "..", "share", "pi2d", "web", "dist") +``` +Every distribution channel preserves this relationship under its installation prefix: +- **curl installer**: prefix `~/.local/lib/pi2d` (with symlink `~/.local/bin/pi2`) +- **Homebrew**: prefix `#{prefix}` (`/opt/homebrew` or `/usr/local`) +- **Arch AUR**: prefix `/usr` + +#### npm package remains JS-only for Node >= 20 + +The npm package (`@yuez/pi2d`) deliberately remains pure JavaScript/TypeScript output +in `dist/` and `web/dist/`, running under Node >= 20. Packaging native platform binaries +into npm optional dependencies (e.g. `@yuez/pi2d-linux-x64`) is intentionally avoided +for now (Decision 3 '先不修改') to prevent publishing complexity across npm and GitHub +releases before justified by demand. + +### 2.6 Upgrade and restart semantics + +1. **npm upgrade**: running `npm i -g @yuez/pi2d@latest` (or `pnpm`/`bun`) updates the + script in place. The running daemon process continues until restarted via + `systemctl --user restart pi2` or `pi2 stop && pi2 daemon`. +2. **Binary upgrade (installer / brew / AUR)**: package managers or `install.sh` + replace the binary on disk. Under Unix filesystem semantics, an open file descriptor + to the running executable remains valid; existing daemon operations continue uninterrupted + until the service is restarted. +3. **Systemd `Restart=on-failure`**: does not fight intentional shutdowns. A clean `SIGTERM` + (e.g. via `pi2 stop`) causes `pi2 daemon` to exit with code `0`. Systemd considers exit 0 + a clean stop and does not trigger restart. +4. **Node path staleness**: units created for an npm install hardcode the absolute node + path (`process.execPath`). Upgrading Node via a version manager (`mise`, `nvm`, `fnm`) + invalidates that path. `pi2 doctor` detects when node cannot run, and re-running + `pi2 install-service --write` re-renders the unit with the updated path. +5. **Daemon restart & client reconnection**: + - **Managed Neovim instances**: spawned nvim processes do not terminate when the daemon + stops. They dial `d.sock` with exponential backoff (200 ms to 5 s) and reconnect + automatically when the daemon restarts. + - **Web browsers**: WebSocket disconnects trigger client-side reconnection. During the + initial handshake (`hello`), the daemon presents its newly minted `daemonId`. If the + `daemonId` has changed, the browser recognizes a restarted daemon and resynchronizes state. + +### 2.7 Compatibility and protocol handshake + +1. **Protocol v1 handshake**: Every connection over WebSocket or unix socket begins with + a `hello` exchange containing: + - `daemonVersion`: semantic version of the running daemon (e.g. `0.1.5`) + - `protocolVersion`: integer protocol version (currently `1`, defined in `src/protocol/types.ts`) + - `daemonId`: unique UUID minted per daemon process run +2. **Version skew handling**: + - The plugin compares `protocolVersion` against its supported range. + - If the protocol version does not match, the plugin refuses to proceed, prints an + actionable error message, and displays the exact upgrade command for the user's platform. + - `pi2 doctor` probes the live daemon (`/api/v1/info`) and verifies CLI/daemon protocol parity. + +### 2.8 Security hardening + +1. **Service environment file**: `EnvironmentFile=-%h/.config/pi2/env` uses the leading `-` + to ensure systemd boots cleanly even if the file is missing. Recommended permissions are + `0600` (`chmod 0600 ~/.config/pi2/env`) to protect tokens and configuration from other users. +2. **No tokens in logs**: + - Local admin token (`cli.token`) is randomly generated per boot, mode `0600`. + - Device tokens are stored only as SHA-256 hashes in `devices.json`. + - Browser console login (`POST /api/v1/console/session`) passes the session token strictly + within the URL fragment (`#t=`), preventing tokens from leaking into server logs, + HTTP headers, or `Referer` fields. +3. **Pairing rate limits**: + - `POST /api/v1/pair/redeem` enforces strict rate limits: 5 attempts/minute/IP and 50 attempts/hour globally. Exceeding limits returns `429 Too Many Requests`. + - Pairing codes expire in 10 minutes and are single-use. +4. **Service bind warnings**: `pi2 install-service` checks if the daemon is configured to + bind to all interfaces (`0.0.0.0`) without TLS and prints an explicit security warning. +5. **Doctor posture checks**: `pi2 doctor` verifies file permissions (`0700` for runtime dir, + `0600` for `cli.token`), warns when linger is disabled on Linux, and requires explicit + acknowledgement when running non-loopback without an `https:` `PI2_PUBLIC_URL`. + +### 2.9 Deferred features and acceptance criteria + +The following items are deferred to future revisions: + +1. **`pi2 update` in-place self-updater**: + - *Rationale*: Package managers (Homebrew, AUR, npm) already provide robust upgrade mechanisms. + - *Acceptance criteria*: Detects if installed via standalone installer (`~/.local/lib/pi2d`); + queries GitHub Releases API for newer version; verifies release `SHA256SUMS`; performs + atomic replacement of `bin/` and `share/`; signals running systemd/launchd service to + restart; refuses self-update when managed by Homebrew, AUR, or npm with instructions to use + the native package manager. +2. **npm platform-binary packages (`@yuez/pi2d--`)**: + - *Rationale*: The npm package works well as pure JS for Node >= 20. Adding platform-specific + npm packages in `optionalDependencies` complicates CI/CD and release publishing. + - *Acceptance criteria*: CI builds and publishes target-specific packages containing only the + compiled binary; root `@yuez/pi2d` package delegates to platform binary if present, + falling back to Node JS entrypoint. +3. **Upstream distribution repositories (`homebrew-core`, Alpine `aports`, `winget`)**: + - *Rationale*: A custom tap (`zgs225/tap`) and AUR package provide fast release iteration + without third-party review bottlenecks. + - *Acceptance criteria*: Stable v1.0 release, official submission to `homebrew-core` (requires + source-based build), official Alpine community package, and signed Windows MSIX/winget package. + +## Consequences + +- **Documentation order changes**: install the CLI → (optionally) enable the service → + install the plugin → `:PiWeb`. `:PiWeb` stops being the whole install path. +- **Migration for existing users**: users who relied on the legacy auto-install into + `/pi2d` must install the `pi2` CLI via one of the Tier-1 channels + (curl, brew, AUR, or npm). `:PiWeb` stops silently installing or executing via `npx`. +- **Documentation rewrite**: `README.md`, `docs/deployment.md`, and `docs/install.md` are + rewritten to emphasize the CLI-first model and the compiled binary options. +- **Explicit `:PiWebInstall`**: `:PiWebInstall` remains available as an explicit fallback, + installing a pinned version strictly matching the plugin release after user confirmation. +- **Node floor lowered to >= 20**: broader compatibility for npm users without compromising + runtime stability. +- **Standalone binaries eliminate Node dependencies**: users of curl, Homebrew, and AUR + require no Node installation, eliminating "distro Node is too old" issues entirely. +- **Service is optional**: `pi2 daemon` runs standalone in the foreground, and `pi2 doctor` + treats missing service managers or linger as warnings, never fatal errors. diff --git a/docs/deployment.md b/docs/deployment.md index 8894fa4..8ba7485 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -35,15 +35,19 @@ Contents | Component | Requirement | Needed for | |---|---|---| -| Node | **>= 22** (`engines` field) | daemon + CLI | +| Node | **>= 20** (`engines` field for npm install); **none** for compiled binary | daemon + CLI (npm/Node install) | | 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)). +The compiled standalone binary (`bun build --compile`) needs no Node at all and reports +its runtime as `bundled` (e.g. `bundled bun 1.3.14`). `pi2 doctor` checks all of the above +(see [§8.3](#83-pi2-doctor)). ## 2. Build +### Node / npm package build + ```bash pnpm install pnpm build # tsc -> dist/ (dist/cli/pi2.js) @@ -54,8 +58,35 @@ The daemon 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. -There is exactly one built binary, `dist/cli/pi2.js` (client commands **and** the -`daemon` subcommand). It is ESM and starts with a `#!` line. +For an npm install, there is exactly one entrypoint script, `dist/cli/pi2.js` (client +commands **and** the `daemon` subcommand). It is ESM and starts with a `#!` line. + +### Compiled binary build + +```bash +pnpm build:binary # or: bash scripts/build-binary.sh +``` + +Produces the standalone artifact tree under `dist-bin/`: +- `dist-bin/bin/pi2` — compiled executable (`bun build --compile`) with injected `PI2_BUILD_VERSION` +- `dist-bin/share/pi2d/web/dist/` — web console assets +- `dist-bin/LICENSE` — license file +- `dist-bin/pi2d---.tar.gz` — distribution tarball containing `bin`, `share`, and `LICENSE` + +Cross-compilation targets (`bun-linux-x64`, `bun-linux-arm64`, `bun-linux-x64-musl`, +`bun-linux-arm64-musl`, `bun-darwin-x64`, `bun-darwin-arm64`): +```bash +bash scripts/build-binary.sh --target bun-linux-x64 +``` + +To run the whole test gate against the compiled artifact: +```bash +bash scripts/smoke-binary.sh # or: pnpm smoke:binary +``` +It asserts daemon startup on ephemeral port 0, `GET /api/v1/info`, `GET /` (HTML from +`share/pi2d/web/dist`), `GET /api/v1/health` (`static` ok), `pi2 doctor` (bundled runtime +reports ok, no node failure), `pi2 install-service --dry-run` (`ExecStart` contains no +`node` or `pi2.js`), and clean `SIGTERM` cleanup. ## 3. Running the daemon @@ -75,10 +106,10 @@ is no detaching mode; that is what the systemd/launchd units below rely on. `pi2 daemon --version` prints `pi2 `, and an unknown daemon positional exits `2` without starting anything. -Exactly one line goes to **stdout**: +Exactly one line goes to **stdout** (the host in that line is the configured bind, so a wildcard bind prints `0.0.0.0`): ``` -pi2 daemon listening on http://127.0.0.1:7676 +pi2 daemon listening on http://0.0.0.0:7676 ``` Every log record is JSONL on **stderr** (that is what systemd/launchd capture). @@ -89,7 +120,7 @@ Flags (`pi2 daemon [start] …`): | Flag | Meaning | |---|---| | `--port `, `-p ` | TCP port; `0` = ephemeral (the real port lands in `daemon.json`) | -| `--host ` | bind address (default `127.0.0.1`) | +| `--host ` | bind address (default `0.0.0.0` (all interfaces)) | | `--static-dir

` | built web UI directory | | `--force`, `-f` | take the lock even if another `pi2 daemon` holds it | | `--foreground` | stay attached to the terminal (default; used by unit files) | @@ -104,6 +135,25 @@ unix socket → listen (with port retry) → write `daemon.json` → print the l The token is rotated only by the process that owns the lock, so a rejected second daemon cannot invalidate the running one. +### Install shape and asset resolution + +`pi2` runs in two shapes (see [ADR 0002](adr/0002-install-and-run.md)): +1. **npm / Node package**: executed via Node (`node …/dist/cli/pi2.js`), where assets sit + next to the source tree. +2. **Compiled single binary**: compiled via Bun (`bun build --compile`) and installed as + `/bin/pi2` with assets at `/share/pi2d/web/dist`. + +How `pi2` discovers its own version and web UI (`src/core/install.ts`): +- **Version**: build-time define (`PI2_BUILD_VERSION`, injected by `scripts/build-binary.sh`) + → on-disk `package.json` (`../../package.json` next to `dist/cli/` for npm/dev checkout) + → `0.0.0` (`UNKNOWN_VERSION`). +- **Static UI directory** (`defaultStaticDir()`): probed in order, first with `index.html` wins: + 1. `/../share/pi2d/web/dist` — release layout: `/bin/pi2` plus + `/share/pi2d/web/dist` (what the curl installer, Homebrew tap, and AUR `-bin` package install) + 2. `/web/dist` — portable unpacked directory (`pi2` next to its UI) + 3. `/web/dist` — npm install or dev checkout relative to module location +- **Environment override**: `PI2_STATIC_DIR` still wins over all candidate paths when set. + ## 4. Configuration Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`): @@ -114,7 +164,7 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`): | `PI2_HOST` | `0.0.0.0` | bind address (all interfaces); set `127.0.0.1` for a loopback-only daemon | | `PI2_PUBLIC_URL` | – | external base URL, e.g. `https://myhost.tail1234.ts.net` (no trailing slash) | | `PI2_ORIGINS` | – | **extra** CORS/Origin allowlist entries (comma separated), added to the derived origins | -| `PI2_STATIC_DIR` | `/web/dist` | built web UI | +| `PI2_STATIC_DIR` | install layout (`/share/pi2d/web/dist` for a compiled binary, `web/dist` for an npm/dev checkout), resolved by `src/core/install.ts` | built web UI (`PI2_STATIC_DIR` overrides it) | | `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 | @@ -127,10 +177,30 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`): | `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) | +| `PI2_CODING_AGENT_DIR`, falling back to `PI_CODING_AGENT_DIR` | `~/.pi/agent` | pi session storage (discovery) | There is no config file: the environment *is* the configuration. +### Service environment file (`~/.config/pi2/env`) + +For background services, the systemd unit automatically includes: +```ini +EnvironmentFile=-%h/.config/pi2/env +``` +The leading `-` instructs systemd to ignore the file if it does not exist (missing is fine). + +Example `~/.config/pi2/env`: +```sh +PI2_HOST=127.0.0.1 +PI2_PORT=7676 +PI2_PUBLIC_URL=https://myhost.tail1234.ts.net +PI2_WORKSPACE_ROOTS=/home/user/Workspace,/home/user/Projects +``` +Set permissions to `0600` (`chmod 0600 ~/.config/pi2/env`) to protect tokens or sensitive paths. +Note that macOS `launchd` has no direct `EnvironmentFile` equivalent (`ServicePaths.envFile` is +ignored on Darwin); configure environment variables in `launchd` via the plist's +`EnvironmentVariables` dictionary or shell environment. + ### Workspace list (noise policy) `GET /api/v1/workspaces` always returns **every** known workspace, so @@ -224,8 +294,9 @@ overwritten on the next start. 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 +1. **Device tokens** (paired phones/laptops): created by `POST /api/v1/pair/redeem` + (mint is authenticated `POST /api/v1/pair`, redemption is public + `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 `pi2 daemon` on each start. Any request carrying it authenticates as the synthetic device @@ -321,7 +392,7 @@ object `{daemon, instances, resources, health}`. | Check | Fails when | Warns when | |---|---|---| -| `node` | < 22 | – | +| `node` | < 20 (npm/Node install) | – (compiled binary reports `bundled bun — bundled runtime, no separate node needed`) | | `nvim` | missing, or < 0.9 | version unparsable | | `pi` | – | not on `PATH` | | `curl` | – | missing → `not found on PATH (:PiWeb cannot sign the browser in automatically; pair instead)`; present but unparsable → `could not parse version of ` | @@ -412,7 +483,7 @@ systemctl --user daemon-reload systemctl --user enable --now pi2.service ``` -The unit is rendered with absolute paths: +The unit is rendered with absolute paths and supports both install shapes: ```ini [Unit] @@ -421,7 +492,11 @@ After=network.target [Service] Type=simple -ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground +# For a compiled binary install: +ExecStart=/home/user/.local/lib/pi2d/bin/pi2 daemon --foreground +# Or for an npm / Node install: +# ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground +EnvironmentFile=-%h/.config/pi2/env Environment=PATH=/usr/local/bin:/usr/bin:/bin Restart=on-failure RestartSec=2 @@ -432,17 +507,26 @@ TimeoutStopSec=15 WantedBy=default.target ``` +The `ExecStart` line adapts automatically to how `pi2` was invoked: +- **Compiled binary install**: `/bin/pi2 daemon --foreground` (invokes the compiled executable directly). +- **npm / Node install**: ` daemon --foreground` (e.g. `/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground`). + +The unit includes `EnvironmentFile=-%h/.config/pi2/env`, where the leading `-` tells systemd that a missing file is completely fine. + `XDG_CONFIG_HOME` is honoured for the target directory. On macOS the same command writes `~/Library/LaunchAgents/com.pi2.daemon.plist` (`RunAtLoad`, -`KeepAlive`, absolute node + script paths, `ProgramArguments` -`node /repo/dist/cli/pi2.js daemon --foreground`, `StandardOutPath`/ -`StandardErrorPath` under `PI2_STATE_DIR`) and prints: +`KeepAlive`, absolute binary or node + script paths in `ProgramArguments`, +`StandardOutPath`/`StandardErrorPath` under `PI2_STATE_DIR`) and prints: ```bash launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pi2.daemon.plist launchctl enable gui/$(id -u)/com.pi2.daemon ``` +Note: `launchd` on macOS has no direct equivalent for systemd's `EnvironmentFile=`. +Environment variables on macOS must be set in the plist `EnvironmentVariables` dictionary +or via shell environment. + `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). @@ -503,13 +587,15 @@ debugging. | `pi2: another pi2 daemon is running (pid …)` | a live daemon owns this runtime dir. Stop it, or `--force` | | `pi2: no running pi2 daemon (…/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 `pi2 daemon` | +| `pi2 --version prints 0.0.0` | compiled binary built without injected version define; rebuild with `scripts/build-binary.sh` (or `pnpm build:binary`) | | `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) | | `pi2 open` → `403 console login is loopback-only` | the request came from a non-loopback address; pair the device instead | | `pi2 doctor` → `bind warn` | the daemon listens on a non-loopback address without TLS; that is the default posture — pair each device, or set `PI2_HOST=127.0.0.1` / `PI2_PUBLIC_URL=https://…` | -| `health: static=FAIL` | `web/dist` missing — build the web UI or set `PI2_STATIC_DIR` | +| `health: static=FAIL` / UI 404 | web assets not found next to binary (expected at `/../share/pi2d/web/dist`) or `/web/dist` missing — reinstall release tarball, build 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` | +| unit points at a node path that no longer exists | mise/nvm/fnm or system Node upgrade changed the binary path; re-run `pi2 install-service --write && systemctl --user daemon-reload` | | Instances gone after a wifi/laptop sleep | daemon restarted: nvim reconnects automatically; check `pi2 status` | diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 0000000..0647161 --- /dev/null +++ b/docs/install.md @@ -0,0 +1,404 @@ +# Installation & Run Guide + +`pi2d` follows a **CLI-first architecture** ([ADR 0002](adr/0002-install-and-run.md)): install the `pi2` CLI on your machine, optionally run it as a persistent user service, and let editor plugins (like [pi2.nvim](https://github.com/zgs225/pi2.nvim)) connect as clients. + +This document is the canonical reference for installing, running, configuring, upgrading, and troubleshooting `pi2d`. + +--- + +## Decision table + +Find your situation in the table below to choose the right installation command and run model: + +| Situation | Recommended Command | What it gives you | +|---|---|---| +| **I have Node 20+** | `npm i -g @yuez/pi2d`
*(or `pnpm add -g`, `bun add -g`, `mise use -g npm:@yuez/pi2d`)* | The `pi2` CLI running directly on your existing Node.js environment, updated via standard package manager commands. | +| **no Node / old Node** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | Standalone compiled binary in `~/.local/lib/pi2d` symlinked to `~/.local/bin/pi2`. Requires zero Node/npm dependencies and no root access. | +| **macOS** | `brew install zgs225/tap/pi2d`
*(or the curl installer)* | Native Homebrew formula. Places `pi2` in `$(brew --prefix)/bin` and web assets in `$(brew --prefix)/share/pi2d/web/dist`. | +| **Arch / EndeavourOS** | `paru -S pi2d-bin`
*(or `yay -S pi2d-bin`)* | Native Arch package managed by pacman. Binary in `/usr/bin/pi2`, web assets in `/usr/share/pi2d/web/dist`. | +| **NixOS** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh`
*(or dev checkout)* | Standalone binary in user home (`~/.local/bin/pi2`). Bun's `-musl` binaries are dynamically linked against the musl loader, so running a prebuilt binary on NixOS needs `nix-ld` (or an FHS env / `steam-run`-style wrapper). | +| **I want it to survive reboot and logout** | `pi2 install-service --write`
`systemctl --user enable --now pi2.service`
`loginctl enable-linger $USER` | Background systemd user service (or launchd on macOS) that starts at boot and stays alive when SSH sessions disconnect. | +| **I only want to try it** | Install via curl or npm, then run:
`pi2 daemon` | Foreground daemon in your current terminal. Logs stream to stdout/stderr. Stop anytime with `Ctrl-C` or `pi2 stop`. | +| **I develop pi2d itself** | `git clone https://github.com/zgs225/pi2d.git`
`pnpm install && pnpm --dir web install` | Source checkout with hot-reloading backend (`pnpm dev`) and Vite dev server (`pnpm --dir web dev`). | + +--- + +## Install channels + +`pi2d` distributes through three primary channels: + +### Channel A: Global package manager (Node >= 20) + +Best when your workstation or server already has Node.js (version 20 or later) installed. + +```bash +# npm +npm i -g @yuez/pi2d + +# pnpm +pnpm add -g @yuez/pi2d + +# bun +bun add -g @yuez/pi2d + +# mise +mise use -g npm:@yuez/pi2d +``` + +**Where files land**: +- Executable binary: `$(npm config get prefix)/bin/pi2` +- Node package & web assets: `$(npm config get prefix)/lib/node_modules/@yuez/pi2d/` (with web assets in `web/dist/`) + +--- + +### Channel B: Standalone curl installer (no Node required) + +Best for systems with no Node runtime, machines with older distributions (such as Debian 12 shipping Node 18), or environments where you do not want to manage global npm packages. + +```bash +curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh +``` + +The script automatically detects OS (`linux`, `darwin`), architecture (`x64`, `arm64`), and C library (`glibc`, `musl`). It downloads the corresponding precompiled standalone archive from GitHub Releases, verifies its SHA256 checksum, and extracts it with zero root privileges needed. + +**Where files land**: +- Base directory: `~/.local/lib/pi2d/` + - `~/.local/lib/pi2d/bin/pi2` (the compiled binary) + - `~/.local/lib/pi2d/share/pi2d/web/dist/` (the web console UI assets) + - `~/.local/lib/pi2d/LICENSE` +- Symlink: `~/.local/bin/pi2` points to `~/.local/lib/pi2d/bin/pi2` + +Ensure `~/.local/bin` is in your `$PATH` (e.g. in your `~/.bashrc` or `~/.zshrc`): +```bash +export PATH="$HOME/.local/bin:$PATH" +``` + +#### Installer environment knobs + +You can customize the installer behavior using environment variables: + +| Variable | Default | Purpose | +|---|---|---| +| `PI2_VERSION` | latest GitHub release | Release version tag to install (e.g. `0.1.6`) | +| `PI2_INSTALL_DIR` | `$HOME/.local/lib/pi2d` | Directory where the binary and web bundle are extracted | +| `PI2_BIN_DIR` | `$HOME/.local/bin` | Directory where the `pi2` executable symlink is created | +| `PI2_ARCHIVE` | unset | Path to a local `.tar.gz` archive (skips network download) | +| `PI2_SKIP_CHECKSUM` | `0` | Set to `1` to bypass SHA256 checksum verification | +| `PI2_BASE_URL` | GitHub releases URL | Override download mirror or release asset base URL | +| `PI2_CHECKSUM_FILE` | unset | Explicit path to a local `SHA256SUMS` file | + +Example installing a specific version to a custom prefix: +```bash +PI2_VERSION=0.1.6 PI2_BIN_DIR=/usr/local/bin PI2_INSTALL_DIR=/usr/local/lib/pi2d curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh +``` + +--- + +### Channel C: System packages (Homebrew & AUR) + +*(Note: These channels are available once the release publishing compiled binaries has shipped).* + +#### macOS / Linux (Homebrew Tap) +```bash +brew install zgs225/tap/pi2d +``` +- Executable: `$(brew --prefix)/bin/pi2` +- UI Assets: `$(brew --prefix)/share/pi2d/web/dist` + +#### Arch Linux / Manjaro / EndeavourOS (AUR) +```bash +paru -S pi2d-bin +# or: +yay -S pi2d-bin +``` +- Executable: `/usr/bin/pi2` +- UI Assets: `/usr/share/pi2d/web/dist` + +--- + +## Run modes + +`pi2` is the CLI; `pi2 daemon` is the long-lived HTTP/WS gateway. Three run modes are supported: + +### 1. User service (recommended) + +Running `pi2` as a background user service is the recommended default. Because `pi2d` provides a web console with pairing links, QR codes, and remote device tokens, having the URL always reachable across editor sessions and reboots gives the best experience. + +#### Rendering and writing the service + +Run `pi2 install-service` to render the platform-appropriate service file: + +```bash +# Preview what will be installed +pi2 install-service --dry-run + +# Write the service file +pi2 install-service --write +``` + +The CLI inspects how it was installed: +- If running as a standalone compiled binary, `ExecStart` directly executes the binary (e.g. `/home/user/.local/lib/pi2d/bin/pi2 daemon --foreground`). +- If running via Node, `ExecStart` points to ` daemon --foreground`. + +#### Linux (`systemd --user`) + +`pi2 install-service --write` creates `~/.config/systemd/user/pi2.service`. + +1. **Enable and start the service**: + ```bash + systemctl --user daemon-reload + systemctl --user enable --now pi2.service + ``` + +2. **Enable lingering across logout**: + On systemd-based distributions, user managers and their services terminate when the user's last session (desktop login or SSH session) closes. To keep `pi2.service` running 24/7 on servers or remote workstations: + ```bash + loginctl enable-linger $USER + ``` + *(Check linger status anytime with `loginctl show-user $USER --property=Linger` or `pi2 doctor`.)* + +3. **View logs**: + ```bash + journalctl --user -u pi2.service -f + ``` + +4. **Service control**: + ```bash + systemctl --user status pi2.service # check status + systemctl --user restart pi2.service # restart daemon + systemctl --user stop pi2.service # stop daemon + ``` + +> **Important**: When running under systemd with `Restart=on-failure`, do **not** use `:PiWebStop` inside Neovim or process kill signals to shut down the daemon. Always use `systemctl --user stop pi2.service` so systemd does not interpret the shutdown as a failure and immediately restart it. + +#### macOS (`launchd`) + +`pi2 install-service --write` creates `~/Library/LaunchAgents/com.pi2.daemon.plist`. + +1. **Bootstrap and start the agent**: + ```bash + launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pi2.daemon.plist + launchctl enable gui/$(id -u)/com.pi2.daemon + launchctl kickstart -k gui/$(id -u)/com.pi2.daemon + ``` + +2. **View logs**: + Logs are configured directly in the plist: + - Standard output: `~/Library/Logs/pi2/pi2-daemon.log` + - Standard error: `~/Library/Logs/pi2/pi2-daemon.err.log` + ```bash + tail -f ~/Library/Logs/pi2/pi2-daemon.log + ``` + +3. **Stop or unload the agent**: + ```bash + launchctl bootout gui/$(id -u)/com.pi2.daemon + ``` + +#### Removing the service + +To remove the installed service unit from either platform: +```bash +pi2 uninstall-service --write +``` + +--- + +### 2. Foreground process + +For quick evaluation, local experiments, or debugging, run the daemon directly in a terminal: + +```bash +pi2 daemon +``` + +- Output logs stream in real-time to stdout/stderr. +- In another terminal, open the console signed in: + ```bash + pi2 open + ``` +- Stop the foreground daemon with `Ctrl-C` in its terminal, or from any shell via: + ```bash + pi2 stop + ``` + +--- + +### 3. Neovim plugin autostart (lazy spawn) + +If you prefer not to keep a continuous daemon running, the Neovim plugin can start it on demand. + +Configure pi2.nvim: +```lua +require("pi").setup({ + web = { + autostart = "spawn", -- or "auto" (default: checks service first, then spawns) + }, +}) +``` + +When you run `:PiWeb`, the plugin discovers `pi2` on `$PATH`, spawns a detached `pi2 daemon` process, and monitors its health. +- Logs are written to `$PI2_STATE_DIR/daemon.log` (`~/.local/state/pi2/daemon.log` on Linux, `~/Library/Logs/pi2/daemon.log` on macOS). +- Stop the spawned daemon with `:PiWebStop` in Neovim or `pi2 stop` from your terminal. + +--- + +## Configuration + +Daemon configuration is **strictly environment-only** ([ADR 0002](adr/0002-install-and-run.md)). There is no configuration file parser, complex precedence hierarchy, or file drift. + +When running as a systemd user service, the generated unit includes: +```ini +EnvironmentFile=-%h/.config/pi2/env +``` +The leading `-` prefix instructs systemd to ignore the file if it does not exist. Creating this file allows you to configure your daemon persistently without editing the service unit. + +### Example `~/.config/pi2/env` + +Create `~/.config/pi2/env`: + +```bash +# ~/.config/pi2/env — Environment configuration for pi2 daemon + +# Port to bind (default: 7676) +PI2_PORT=7676 + +# Network interface bind address: +# 0.0.0.0 = bind all interfaces (default; allows LAN / phone pairing) +# 127.0.0.1 = loopback only (local machine only) +PI2_HOST=0.0.0.0 + +# Public URL when accessed through a reverse proxy or Tailscale Serve: +# PI2_PUBLIC_URL=https://laptop.tail1234.ts.net + +# Allowed workspace root directories (comma-separated): +# PI2_WORKSPACE_ROOTS=/home/user/workspace,/home/user/projects + +# Logging verbosity: trace | debug | info | warn | error (default: info) +PI2_LOG_LEVEL=info + +# Custom directory overrides (optional, default to standard XDG paths): +# PI2_RUNTIME_DIR=/run/user/1000/pi2 +# PI2_STATE_DIR=/home/user/.local/state/pi2 +# PI2_DATA_DIR=/home/user/.local/share/pi2 +``` + +After editing `~/.config/pi2/env`, restart the systemd service: +```bash +systemctl --user restart pi2.service +``` + +*(On macOS, since launchd lacks an `EnvironmentFile` directive, set system environment variables or pass custom values when rendering via `pi2 install-service`).* + +--- + +## Upgrading and uninstalling + +### Upgrade per channel + +- **Channel A (npm / pnpm / bun / mise)**: + ```bash + npm i -g @yuez/pi2d@latest + # or: + pnpm add -g @yuez/pi2d@latest + bun add -g @yuez/pi2d@latest + mise use -g npm:@yuez/pi2d@latest + ``` + +- **Channel B (Standalone curl installer)**: + Re-run the installer. It replaces the binary and assets cleanly in `~/.local/lib/pi2d`: + ```bash + curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh + ``` + +- **Channel C (Homebrew)**: + ```bash + brew update && brew upgrade pi2d + ``` + +- **Channel C (Arch AUR)**: + ```bash + paru -Syu pi2d-bin + # or: + yay -Syu pi2d-bin + ``` + +### Uninstall per channel + +- **Channel A (npm / pnpm / bun)**: + ```bash + npm rm -g @yuez/pi2d + # or: pnpm rm -g @yuez/pi2d / bun rm -g @yuez/pi2d + ``` + +- **Channel B (curl installer)**: + ```bash + curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall + ``` + *(Or manually delete `rm -rf ~/.local/lib/pi2d ~/.local/bin/pi2`)*. + +- **Channel C (Homebrew)**: + ```bash + brew uninstall pi2d + ``` + +- **Channel C (Arch AUR)**: + ```bash + sudo pacman -R pi2d-bin + ``` + +If you configured a user service, remember to remove it before uninstalling the binary: +```bash +pi2 uninstall-service --write +``` + +--- + +## Verifying your installation + +Use these three CLI commands to verify everything is working properly: + +### 1. Version check +```bash +pi2 --version +``` +Prints the CLI version (e.g. `0.1.5`). + +### 2. Runtime status +```bash +pi2 status +``` +Shows: +- Whether the daemon is currently running and what port/host it is bound to. +- Connected instances (nvim instances supervised per workspace). +- Active resource consumption (RSS, heap memory). +- Health probes. + +### 3. Comprehensive diagnostic (`pi2 doctor`) +```bash +pi2 doctor +``` +Runs an end-to-end check of the environment and outputs a diagnostic table: +- **node/runtime**: checks Node version (>= 20) or confirms bundled runtime (`bundled bun `). +- **nvim**: verifies Neovim >= 0.9 on `$PATH`. +- **pi**: verifies the `pi` coding-agent CLI on `$PATH`. +- **curl**: verifies HTTP client availability. +- **plugin**: checks for `pi2.nvim` bridge installation in Neovim runtime paths. +- **runtime**: checks permissions (`0700`) on `$PI2_RUNTIME_DIR`. +- **cli-token**: checks permissions (`0600`) on admin token. +- **socket / daemon**: checks local daemon connectivity and protocol compatibility. +- **service-manager / linger**: reports systemd/launchd availability and whether user linger is enabled. +- **web-dist**: verifies static web console bundle assets exist and are readable. + +--- + +## Why `npx` is not an install path + +In earlier versions, invoking `npx -y @yuez/pi2d@latest` was considered as an automated fallback. [ADR 0002](adr/0002-install-and-run.md) explicitly rejected this model for several critical reasons: + +1. **Path instability**: `npx` installs packages into temporary, cache-managed paths (`~/.npm/_npx/...`). These directories are routinely evicted by npm cache sweeps or version updates, breaking long-lived processes. +2. **Requires Node anyway**: If a machine has Node installed, `npm i -g @yuez/pi2d` takes seconds, produces a stable binary on `$PATH`, works completely offline, and does not re-query the registry. If a machine does not have Node, `npx` cannot run at all. +3. **Unstable unit `ExecStart`**: Service managers (systemd, launchd) require an immutable, absolute executable path in `ExecStart`. Pointing a background service unit to `npx` causes network lookups at boot time, unpredictable delays, and catastrophic failure in offline environments. +4. **Supply chain and version skew**: Running `@latest` dynamically when opening Neovim introduces network roundtrips, startup lag, and unexpected breaking updates midway through an editing session. + +Instead, installing `pi2` once via your package manager or the standalone curl installer gives you a predictable, deterministic, and offline-capable executable. diff --git a/docs/protocol.md b/docs/protocol.md index 094e1d3..34255fd 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -85,6 +85,7 @@ Plugin obligations: | `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` | | `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) | | `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) | +| `GET /api/v1/sessions/recent?limit=` | disk-projected recent sessions across every workspace (below); never spawns an instance | | `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` | relayed `workspace.query{kind:"entries"}`; plugin paginates | | `GET /api/v1/attention?workspaceId=` | pending attention for one workspace | | `GET /api/v1/devices` | paired devices (daemon-owned; `{id, name, kind, createdAt, lastSeenAt, revokedAt}`) | @@ -156,6 +157,23 @@ A client that lets the user *choose* a workspace should list only `default` rows default; `secondary` rows belong behind a “show hidden” toggle. Lookups by `workspaceId` must ignore `visibility` entirely. +Recent session row (`GET /api/v1/sessions/recent?limit=`): a **disk projection**, not +session state. The daemon scans each known workspace's session directory, reads only +session headers (id, timestamp, cwd), and sorts by file mtime. It never parses +entries, never spawns an instance and never claims ownership of a live session. The +console layers live names/statuses over these rows from +`GET /api/v1/workspaces/:id/sessions` when that workspace has a connected instance. + +| Field | Notes | +|---|---| +| `sessionId`, `sessionFile`, `cwd` | identity + path | +| `workspaceId`, `workspaceName` | owning workspace, resolved from the daemon's registry/discovery | +| `timestamp` | session start from the JSONL header (file-name fallback), epoch ms | +| `modified` | file mtime, epoch ms — the recency sort key | + +The `limit` defaults to 20 and is clamped to 1–200. Rows are deduped by `sessionId` +(two encoded directories can resolve to the same cwd) and returned newest first. + Session row (`GET /api/v1/workspaces/:id/sessions`) — a subset of `SessionState` plus list metadata (`usage`, `flags`, `entries` and `attention` arrive via snapshot/events, not on this row): | Field | Notes | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5c11ebc..c1dad92 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -169,6 +169,7 @@ Everything the console calls is answered from `scripts/ui-fixtures.mjs`: | `POST /api/v1/pair` | `pairCode` | redeem (`{code}` → token+device) and mint (`{accepted,code,url,…}`) | | `GET /api/v1/workspaces` | `workspaces` | 6 rows covering staged/hidden/ghost/tmp/degraded/untrusted | | `GET /api/v1/workspaces/:id/sessions` | `sessions` | `{v,sessions,cursor}`; 6 sessions incl. child, attention, legacy, idle | +| `GET /api/v1/sessions/recent` | `sessions` (disk projection) | `{v,sessions}` newest-first, used by the workspaces activity column | | `GET /api/v1/sessions/:sid/entries` | `entriesBySession` | raw pi entries, `before`/`limit` paging with a cursor | | `GET /api/v1/attention` | `attentionByWorkspace` | flattened per workspace | | `GET /api/v1/models` | `modelProviders` | `{providers:[…]}`, 3 providers | diff --git a/package.json b/package.json index 5467d95..53d0c9d 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "license": "MIT", "description": "pi2 web console daemon (`pi2 daemon`): HTTP/WS gateway, workspace registry and instance supervisor for pi2.nvim", "engines": { - "node": ">=22" + "node": ">=20" }, "bin": { "pi2": "./dist/cli/pi2.js" @@ -39,6 +39,8 @@ "dev": "tsx watch src/cli/pi2.ts daemon", "build": "tsc -p tsconfig.json", "build:web": "pnpm --dir web build", + "build:binary": "bash scripts/build-binary.sh", + "smoke:binary": "bash scripts/smoke-binary.sh", "prepack": "npm run build && npm run build:web", "typecheck": "tsc -p tsconfig.json --noEmit", "test": "vitest run", diff --git a/packaging/README.md b/packaging/README.md new file mode 100644 index 0000000..d6eec00 --- /dev/null +++ b/packaging/README.md @@ -0,0 +1,127 @@ +# System Packaging Channels for pi2d + +This directory contains the packaging templates and documentation for distributing +`pi2d` across system-level package channels. + +## Distribution Channels + +Every channel distributes the prebuilt single-binary artifacts built from Bun, bundling +both the CLI launcher and the React web console. + +| Channel | Target Audience | User Installation Command | +|---|---|---| +| **curl installer** | Generic Linux & macOS | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | +| **Homebrew tap** | macOS & Linux (Homebrew) | `brew install zgs225/tap/pi2d` | +| **Arch AUR (`-bin`)** | Arch Linux / Manjaro / EndeavourOS | `paru -S pi2d-bin` (or `yay -S pi2d-bin`) | + +### Shared Tarball Layout Contract + +All distribution channels consume the release tarballs published on GitHub Releases: +``` +https://github.com/zgs225/pi2d/releases/download/v/pi2d--.tar.gz +``` +Where `` is one of: +- `linux-x64` +- `linux-arm64` +- `linux-x64-musl` +- `linux-arm64-musl` +- `darwin-x64` +- `darwin-arm64` + +Each release tarball unpacks with the following layout at its root: +``` +bin/ + pi2 +share/ + pi2d/ + web/ + dist/ + index.html + ... +LICENSE +``` + +**Crucial layout rule**: `pi2` resolves its web console assets at runtime via: +```typescript +resolve(dirname(executablePath()), "..", "share", "pi2d", "web", "dist") +``` +(defined in `src/core/install.ts`). + +Every channel must install `bin/pi2` into `/bin` and `share/pi2d/web/dist` into +`/share/pi2d/web/dist` under the same prefix (e.g. `/usr/local`, `/opt/homebrew`, +or `/usr`). + +## Files & Templates + +- `packaging/homebrew/pi2d.rb.in`: plain template for Homebrew formula `pi2d.rb`. Contains + platform stanzas (`on_macos`, `on_linux` with `on_arm` and `on_intel`) and `install` / + `test` / `caveats` blocks. Linux stanzas target standard glibc releases. +- `packaging/aur/PKGBUILD.in`: plain template for the Arch Linux AUR package `pi2d-bin`. + Uses `options=('!strip')` because Bun binaries embed bytecode/metadata that strip damages. + Targets x86_64 and aarch64 glibc tarballs (Alpine/musl tarballs are omitted for Arch). +- `scripts/update-packaging.sh`: deterministic generator script substituting placeholders + and validating checksums. + +## One-Time Bootstrap + +### 1. Homebrew Tap (`zgs225/homebrew-tap`) + +1. Create a public repository on GitHub named `zgs225/homebrew-tap`. +2. Create the `Formula/` directory in that repository. +3. Place the initial `Formula/pi2d.rb` generated by `scripts/update-packaging.sh`. +4. Commit and push to `main`. +5. Users can now install with: + ```bash + brew install zgs225/tap/pi2d + ``` + +### 2. Arch Linux AUR (`pi2d-bin`) + +1. Register an account on [aur.archlinux.org](https://aur.archlinux.org) and add your SSH public key. +2. Initialize the AUR package repository locally: + ```bash + git clone ssh://aur@aur.archlinux.org/pi2d-bin.git + ``` +3. Generate the initial `PKGBUILD` and `.SRCINFO` using `scripts/update-packaging.sh`. +4. Copy `PKGBUILD` and `.SRCINFO` into the cloned `pi2d-bin` directory, commit, and push: + ```bash + git add PKGBUILD .SRCINFO + git commit -m "feat: initial release" + git push origin master + ``` +5. Set up an SSH private key as a repository secret (e.g. `AUR_SSH_KEY`) in GitHub repository + `zgs225/pi2d` so the release workflow can push updates to the AUR repository. + +## Release-Time Bump Flow + +During a release (via GitHub Actions workflow when a version tag `vX.Y.Z` is pushed): +1. The release job builds binary tarballs for all 6 targets and generates `SHA256SUMS`. +2. The packaging step executes: + ```bash + bash scripts/update-packaging.sh --version --checksums dist-bin/SHA256SUMS --out build/packaging + ``` +3. The generated `build/packaging/pi2d.rb` is committed and pushed to `Formula/pi2d.rb` in + the `zgs225/homebrew-tap` repository. +4. The generated `build/packaging/PKGBUILD` and `build/packaging/.SRCINFO` are committed + and pushed to the `pi2d-bin` AUR repository. + +## Local Regeneration + +You can regenerate or preview packaging files locally at any time: + +```bash +# Using a local SHA256SUMS file: +bash scripts/update-packaging.sh --version 0.1.6 --checksums dist-bin/SHA256SUMS --out build/packaging + +# Using a directory containing release tarballs: +bash scripts/update-packaging.sh --version 0.1.6 --checksums dist-bin/ --out build/packaging + +# Downloading checksums directly from a published GitHub release: +bash scripts/update-packaging.sh --version 0.1.6 --out build/packaging +``` + +The script performs validation: +- Checks that all 6 target SHA-256 sums are accounted for. +- Fails loudly on unknown targets or malformed checksums. +- Verifies that no unreplaced `@@...@@` placeholders remain. +- Generates a valid `.SRCINFO` (using `makepkg --printsrcinfo` if installed, or an identical fallback). diff --git a/packaging/aur/PKGBUILD.in b/packaging/aur/PKGBUILD.in new file mode 100644 index 0000000..d4ccb5b --- /dev/null +++ b/packaging/aur/PKGBUILD.in @@ -0,0 +1,41 @@ +# Maintainer: zgs225 +pkgname=pi2d-bin +pkgver=@@VERSION@@ +pkgrel=1 +pkgdesc="Web console daemon for pi2.nvim" +arch=('x86_64' 'aarch64') +url="https://github.com/zgs225/pi2d" +license=('MIT') +provides=('pi2d') +conflicts=('pi2d') + +# Prebuilt binary compiled by Bun; stripping the executable can corrupt internal +# bundle offsets, embedded resources, and runtime metadata. +options=('!strip') + +# Note on musl: upstream also publishes linux-x64-musl and linux-arm64-musl targets +# for musl-based distributions such as Alpine Linux. Arch Linux is glibc-based, +# so the standard glibc tarballs (linux-x64 and linux-arm64) are used here. + +source_x86_64=("https://github.com/zgs225/pi2d/releases/download/v${pkgver}/pi2d-${pkgver}-linux-x64.tar.gz") +sha256sums_x86_64=('@@SHA256_LINUX_X64@@') + +source_aarch64=("https://github.com/zgs225/pi2d/releases/download/v${pkgver}/pi2d-${pkgver}-linux-arm64.tar.gz") +sha256sums_aarch64=('@@SHA256_LINUX_ARM64@@') + +# No .install script needed: pi2d runs as an unprivileged user process or user +# service. Systemd user service units can be generated via `pi2 install-service --write`. + +package() { + # Daemon CLI binary (0755) + install -Dm755 "${srcdir}/bin/pi2" "${pkgdir}/usr/bin/pi2" + + # Static web UI assets: /usr/share/pi2d/web/dist (0644 tree) + install -dm755 "${pkgdir}/usr/share/pi2d" + cp -r --no-preserve=ownership "${srcdir}/share/pi2d/web" "${pkgdir}/usr/share/pi2d/" + find "${pkgdir}/usr/share/pi2d/web" -type d -exec chmod 0755 {} + + find "${pkgdir}/usr/share/pi2d/web" -type f -exec chmod 0644 {} + + + # Upstream license + install -Dm644 "${srcdir}/LICENSE" "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE" +} diff --git a/packaging/homebrew/pi2d.rb.in b/packaging/homebrew/pi2d.rb.in new file mode 100644 index 0000000..b846d97 --- /dev/null +++ b/packaging/homebrew/pi2d.rb.in @@ -0,0 +1,44 @@ +class Pi2d < Formula + desc "Web console daemon for pi2.nvim" + homepage "https://github.com/zgs225/pi2d" + version "@@VERSION@@" + license "MIT" + + on_macos do + on_arm do + url "https://github.com/zgs225/pi2d/releases/download/v@@VERSION@@/pi2d-@@VERSION@@-darwin-arm64.tar.gz" + sha256 "@@SHA256_DARWIN_ARM64@@" + end + on_intel do + url "https://github.com/zgs225/pi2d/releases/download/v@@VERSION@@/pi2d-@@VERSION@@-darwin-x64.tar.gz" + sha256 "@@SHA256_DARWIN_X64@@" + end + end + + on_linux do + on_arm do + url "https://github.com/zgs225/pi2d/releases/download/v@@VERSION@@/pi2d-@@VERSION@@-linux-arm64.tar.gz" + sha256 "@@SHA256_LINUX_ARM64@@" + end + on_intel do + url "https://github.com/zgs225/pi2d/releases/download/v@@VERSION@@/pi2d-@@VERSION@@-linux-x64.tar.gz" + sha256 "@@SHA256_LINUX_X64@@" + end + end + + def install + bin.install "bin/pi2" + (share/"pi2d").install "share/pi2d/web" + end + + def caveats + <<~EOS + To run pi2d as a background service: + pi2 install-service --write + EOS + end + + test do + assert_match version.to_s, shell_output("#{bin}/pi2 --version") + end +end diff --git a/scripts/build-binary.sh b/scripts/build-binary.sh new file mode 100755 index 0000000..4c101b1 --- /dev/null +++ b/scripts/build-binary.sh @@ -0,0 +1,195 @@ +#!/usr/bin/env bash +# +# Build a standalone binary distribution of pi2d. +# +# Produces: +# /bin/pi2 +# /share/pi2d/web/dist/... +# /LICENSE +# /pi2d---.tar.gz +# +# Usage: +# bash scripts/build-binary.sh [flags] +# +# Flags: +# --target Cross-compile target (e.g. bun-linux-x64, bun-darwin-arm64) +# --version Release version (default: version from package.json) +# --output-dir

Output directory (default: dist-bin) +# --skip-build Reuse existing dist/ and web/dist/ +# --no-archive Do not produce the .tar.gz archive +set -euo pipefail + +ORIG_CWD="$(pwd)" +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +TARGET="" +VERSION="" +OUTPUT_DIR="" +SKIP_BUILD=0 +NO_ARCHIVE=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --target) + TARGET="$2" + shift 2 + ;; + --target=*) + TARGET="${1#*=}" + shift + ;; + --version) + VERSION="$2" + shift 2 + ;; + --version=*) + VERSION="${1#*=}" + shift + ;; + --output-dir) + OUTPUT_DIR="$2" + shift 2 + ;; + --output-dir=*) + OUTPUT_DIR="${1#*=}" + shift + ;; + --skip-build) + SKIP_BUILD=1 + shift + ;; + --no-archive) + NO_ARCHIVE=1 + shift + ;; + -h|--help) + cat < Bun compilation target (default: host target) + Supported: linux-x64, linux-arm64, linux-x64-musl, + linux-arm64-musl, darwin-x64, darwin-arm64 + --version Version string (default: package.json version) + --output-dir Output directory (default: dist-bin) + --skip-build Skip tsc and web build if dist/ and web/dist/ exist + --no-archive Skip packaging the .tar.gz archive + -h, --help Show this help message +EOF + exit 0 + ;; + *) + printf 'Error: unknown option: %s\n' "$1" >&2 + exit 1 + ;; + esac +done + +cd "$ROOT" + +if [[ -z "$OUTPUT_DIR" ]]; then + OUTPUT_DIR="$ROOT/dist-bin" +elif [[ "$OUTPUT_DIR" != /* ]]; then + OUTPUT_DIR="$ORIG_CWD/$OUTPUT_DIR" +fi + +if [[ -z "$VERSION" ]]; then + VERSION="$(node -e "console.log(JSON.parse(require('fs').readFileSync('package.json', 'utf8')).version)")" +fi + +detect_host_target() { + local os arch + case "$(uname -s)" in + Linux) os="linux" ;; + Darwin) os="darwin" ;; + *) os="$(uname -s | tr '[:upper:]' '[:lower:]')" ;; + esac + + case "$(uname -m)" in + x86_64|amd64) arch="x64" ;; + aarch64|arm64) arch="arm64" ;; + *) arch="$(uname -m)" ;; + esac + + if [[ "$os" == "linux" ]]; then + if ! getconf GNU_LIBC_VERSION >/dev/null 2>&1; then + arch="${arch}-musl" + fi + fi + + printf '%s-%s\n' "$os" "$arch" +} + +if [[ -n "$TARGET" ]]; then + TARGET_NAME="${TARGET#bun-}" + case "$TARGET_NAME" in + linux-x64|linux-arm64|linux-x64-musl|linux-arm64-musl|darwin-x64|darwin-arm64) + OS_ARCH="$TARGET_NAME" + BUN_TARGET="bun-$TARGET_NAME" + ;; + *) + printf 'Error: unsupported target "%s". Supported: linux-x64, linux-arm64, linux-x64-musl, linux-arm64-musl, darwin-x64, darwin-arm64\n' "$TARGET" >&2 + exit 1 + ;; + esac +else + BUN_TARGET="" + OS_ARCH="$(detect_host_target)" +fi + +if [[ "$SKIP_BUILD" -eq 1 && -f "dist/cli/pi2.js" && -d "web/dist" ]]; then + printf '==> reusing existing dist/ and web/dist/\n' +else + printf '==> building TypeScript and web UI\n' + pnpm build + pnpm build:web +fi + +[[ -f "dist/cli/pi2.js" ]] || { printf 'Error: dist/cli/pi2.js not found\n' >&2; exit 1; } +[[ -d "web/dist" ]] || { printf 'Error: web/dist directory not found\n' >&2; exit 1; } +[[ -f "LICENSE" ]] || { printf 'Error: LICENSE file not found\n' >&2; exit 1; } + +ARCHIVE_NAME="pi2d-${VERSION}-${OS_ARCH}.tar.gz" +ARCHIVE_PATH="$OUTPUT_DIR/$ARCHIVE_NAME" + +# Clean stale outputs for idempotency +rm -rf "${OUTPUT_DIR:?}/bin" "${OUTPUT_DIR:?}/share" "${OUTPUT_DIR:?}/LICENSE" +rm -f "$ARCHIVE_PATH" + +mkdir -p "$OUTPUT_DIR/bin" +mkdir -p "$OUTPUT_DIR/share/pi2d/web" + +printf '==> compiling binary with bun\n' +BUN_CMD=( + bun build + dist/cli/pi2.js + --compile + --outfile "$OUTPUT_DIR/bin/pi2" + --define "PI2_BUILD_VERSION=\"$VERSION\"" +) +if [[ -n "$BUN_TARGET" ]]; then + BUN_CMD+=("--target=$BUN_TARGET") +fi + +"${BUN_CMD[@]}" +chmod +x "$OUTPUT_DIR/bin/pi2" + +printf '==> copying assets\n' +cp -R web/dist "$OUTPUT_DIR/share/pi2d/web/dist" +cp LICENSE "$OUTPUT_DIR/LICENSE" + +if [[ "$NO_ARCHIVE" -eq 0 ]]; then + printf '==> packaging tarball\n' + tar -czf "$ARCHIVE_PATH" -C "$OUTPUT_DIR" bin share LICENSE +fi + +BIN_PATH="$OUTPUT_DIR/bin/pi2" +BIN_SIZE="$(du -h "$BIN_PATH" | cut -f1)" + +if [[ "$NO_ARCHIVE" -eq 1 ]]; then + printf 'Artifact: %s (%s)\n' "$BIN_PATH" "$BIN_SIZE" +else + ARCHIVE_SIZE="$(du -h "$ARCHIVE_PATH" | cut -f1)" + printf 'Binary: %s (%s)\n' "$BIN_PATH" "$BIN_SIZE" + printf 'Artifact: %s (%s)\n' "$ARCHIVE_PATH" "$ARCHIVE_SIZE" +fi diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 0000000..c3c12ba --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,543 @@ +#!/bin/sh +# +# pi2 standalone installer +# +# Installs the precompiled pi2 binary and web console assets with no Node, +# no npm, and no root privileges required. +# +# Quick install: +# curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh +# +# Uninstall: +# curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall +# +set -eu + +# ----------------------------------------------------------------------------- +# Configuration & Knobs +# ----------------------------------------------------------------------------- + +PI2_INSTALL_DIR="${PI2_INSTALL_DIR:-$HOME/.local/lib/pi2d}" +PI2_BIN_DIR="${PI2_BIN_DIR:-$HOME/.local/bin}" +PI2_SKIP_CHECKSUM="${PI2_SKIP_CHECKSUM:-0}" + +# Strip trailing slashes for clean path manipulation +PI2_INSTALL_DIR="${PI2_INSTALL_DIR%/}" +PI2_BIN_DIR="${PI2_BIN_DIR%/}" + +staging="" +tmp_dir="" + +cleanup() { + exit_code=$? + trap - EXIT INT TERM + if [ -n "$staging" ] && [ -d "$staging" ]; then + rm -rf "$staging" + fi + if [ -n "$tmp_dir" ] && [ -d "$tmp_dir" ]; then + rm -rf "$tmp_dir" + fi + exit "$exit_code" +} +trap cleanup EXIT INT TERM + +show_help() { + cat << 'EOF' +Usage: install.sh [OPTIONS] + +Installs the compiled pi2 binary and web UI with no Node, no npm, and no root. + +Options: + --uninstall, -u Uninstall pi2 and remove binary symlink + --help, -h Show this help message + +Environment variables: + PI2_VERSION Version to install (default: latest release tag from GitHub) + PI2_INSTALL_DIR Installation directory (default: $HOME/.local/lib/pi2d) + PI2_BIN_DIR Directory for executable symlink (default: $HOME/.local/bin) + PI2_BASE_URL Base URL for release assets (default: GitHub releases URL) + PI2_ARCHIVE Path to a local tarball (skips network download) + PI2_SKIP_CHECKSUM Set to 1 to bypass SHA256 checksum verification + PI2_CHECKSUM_FILE Explicit path to SHA256SUMS file +EOF +} + +print_supported_platforms() { + printf 'Supported platforms:\n' >&2 + printf ' - linux-x64\n' >&2 + printf ' - linux-arm64\n' >&2 + printf ' - linux-x64-musl\n' >&2 + printf ' - linux-arm64-musl\n' >&2 + printf ' - darwin-x64\n' >&2 + printf ' - darwin-arm64\n' >&2 +} + +# ----------------------------------------------------------------------------- +# Platform Detection +# ----------------------------------------------------------------------------- + +detect_platform() { + raw_os="$(uname -s)" + case "$raw_os" in + Linux) os="linux" ;; + Darwin) os="darwin" ;; + *) + printf 'Error: Unsupported operating system: %s\n' "$raw_os" >&2 + print_supported_platforms + exit 1 + ;; + esac + + raw_arch="$(uname -m)" + case "$raw_arch" in + x86_64|amd64) arch="x64" ;; + aarch64|arm64) arch="arm64" ;; + *) + printf 'Error: Unsupported architecture: %s\n' "$raw_arch" >&2 + print_supported_platforms + exit 1 + ;; + esac + + is_musl=0 + if [ "$os" = "linux" ]; then + if [ -f /etc/alpine-release ]; then + is_musl=1 + elif command -v ldd >/dev/null 2>&1 && ldd --version 2>&1 | grep -i musl >/dev/null 2>&1; then + is_musl=1 + elif ls /lib/ld-musl-*.so* >/dev/null 2>&1 || ls /usr/lib/ld-musl-*.so* >/dev/null 2>&1; then + is_musl=1 + fi + fi +} + +# ----------------------------------------------------------------------------- +# HTTP / Download Helpers +# ----------------------------------------------------------------------------- + +fetch_text() { + url="$1" + if command -v curl >/dev/null 2>&1; then + curl -fsSL -H "Accept: application/vnd.github+json" "$url" + elif command -v wget >/dev/null 2>&1; then + wget -qO- --header="Accept: application/vnd.github+json" "$url" + else + printf 'Error: Neither curl nor wget was found. Please install curl or wget.\n' >&2 + exit 1 + fi +} + +download_file() { + url="$1" + dest="$2" + if command -v curl >/dev/null 2>&1; then + curl -fsSL "$url" -o "$dest" + elif command -v wget >/dev/null 2>&1; then + wget -qO "$dest" "$url" + else + printf 'Error: Neither curl nor wget was found. Please install curl or wget.\n' >&2 + exit 1 + fi +} + +# ----------------------------------------------------------------------------- +# Checksum Verification +# ----------------------------------------------------------------------------- + +compute_sha256() { + target_file="$1" + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$target_file" | awk '{print $1}' + elif command -v shasum >/dev/null 2>&1; then + shasum -a 256 "$target_file" | awk '{print $1}' + elif command -v openssl >/dev/null 2>&1; then + openssl dgst -sha256 "$target_file" | awk '{print $NF}' + else + printf 'Error: Neither sha256sum, shasum, nor openssl is available.\n' >&2 + printf 'Install sha256sum/shasum or set PI2_SKIP_CHECKSUM=1 to bypass.\n' >&2 + exit 1 + fi +} + +verify_checksum() { + file_to_check="$1" + checksum_file="$2" + require_entry="${3:-1}" + file_name="$(basename "$file_to_check")" + + expected="$(awk -v fname="$file_name" -v fpath="$file_to_check" '{ + if (NF == 1 && length($1) == 64) { print $1; exit } + name = $2; + sub(/^\*/, "", name); + bname = name; + sub(/.*\//, "", bname); + if (name == fname || name == fpath || bname == fname) { print $1; exit } + }' "$checksum_file")" + + if [ -z "$expected" ]; then + if [ "$require_entry" -eq 1 ]; then + printf 'Error: No SHA256 checksum entry found for %s in %s\n' "$file_name" "$checksum_file" >&2 + exit 1 + else + printf 'info: no checksum entry for %s found in %s; skipping checksum verification\n' "$file_name" "$checksum_file" + return 0 + fi + fi + + actual="$(compute_sha256 "$file_to_check")" + + expected="$(printf '%s' "$expected" | tr '[:upper:]' '[:lower:]')" + actual="$(printf '%s' "$actual" | tr '[:upper:]' '[:lower:]')" + + if [ "$actual" != "$expected" ]; then + printf 'Error: SHA256 checksum verification failed for %s\n' "$file_to_check" >&2 + printf ' Expected: %s\n' "$expected" >&2 + printf ' Actual: %s\n' "$actual" >&2 + exit 1 + fi + + printf 'Checksum verified: %s\n' "$actual" +} + +# ----------------------------------------------------------------------------- +# Parse Arguments +# ----------------------------------------------------------------------------- + +uninstall_mode=0 +for arg in "$@"; do + case "$arg" in + --uninstall|-u|uninstall) + uninstall_mode=1 + ;; + --help|-h|help) + show_help + exit 0 + ;; + *) + printf 'Error: Unknown argument: %s\n\n' "$arg" >&2 + show_help + exit 1 + ;; + esac +done + +detect_platform + +# ----------------------------------------------------------------------------- +# Uninstall Mode +# ----------------------------------------------------------------------------- + +if [ "$uninstall_mode" -eq 1 ]; then + printf 'Uninstalling pi2...\n' + removed_any=0 + + if [ -d "$PI2_INSTALL_DIR" ]; then + rm -rf "$PI2_INSTALL_DIR" + printf ' - Removed install directory: %s\n' "$PI2_INSTALL_DIR" + removed_any=1 + fi + + if [ -e "$PI2_BIN_DIR/pi2" ] || [ -L "$PI2_BIN_DIR/pi2" ]; then + rm -f "$PI2_BIN_DIR/pi2" + printf ' - Removed binary symlink: %s\n' "$PI2_BIN_DIR/pi2" + removed_any=1 + fi + + if [ "$removed_any" -eq 0 ]; then + printf 'No existing installation found at %s or %s/pi2.\n' "$PI2_INSTALL_DIR" "$PI2_BIN_DIR" + else + printf 'pi2 uninstalled successfully.\n' + fi + + # Report untouched directories + if [ -n "${PI2_DATA_DIR:-}" ]; then + disp_data="$PI2_DATA_DIR" + elif [ "$os" = "darwin" ]; then + disp_data="$HOME/Library/Application Support/pi2" + else + disp_data="${XDG_DATA_HOME:-$HOME/.local/share}/pi2" + fi + + if [ -n "${PI2_RUNTIME_DIR:-}" ]; then + disp_runtime="$PI2_RUNTIME_DIR" + elif [ "$os" = "darwin" ]; then + disp_runtime="$HOME/Library/Caches/pi2/run" + else + uid="$(id -u 2>/dev/null || echo 0)" + disp_runtime="${XDG_RUNTIME_DIR:-${TMPDIR:-/tmp}/pi2-${uid}}/pi2" + fi + + if [ -n "${PI2_STATE_DIR:-}" ]; then + disp_state="$PI2_STATE_DIR" + elif [ "$os" = "darwin" ]; then + disp_state="$HOME/Library/Logs/pi2" + else + disp_state="${XDG_STATE_HOME:-$HOME/.local/state}/pi2" + fi + + printf '\nThe following runtime, data, and state directories were left untouched:\n' + printf ' - Runtime: %s\n' "$disp_runtime" + printf ' - Data: %s\n' "$disp_data" + printf ' - State: %s\n' "$disp_state" + exit 0 +fi + +# ----------------------------------------------------------------------------- +# Install Mode: Resolve Artifact +# ----------------------------------------------------------------------------- + +archive_path="" +target="" +version="" + +if [ -n "${PI2_ARCHIVE:-}" ]; then + # Offline install path + if [ ! -f "$PI2_ARCHIVE" ]; then + printf 'Error: Local archive not found: %s\n' "$PI2_ARCHIVE" >&2 + exit 1 + fi + archive_path="$PI2_ARCHIVE" + archive_name="$(basename "$archive_path")" + + if [ -n "${PI2_VERSION:-}" ]; then + version="${PI2_VERSION#v}" + else + case "$archive_name" in + pi2d-*-*) + v="${archive_name#pi2d-}" + version="${v%%-*}" + ;; + *) + version="custom" + ;; + esac + fi + + case "$archive_name" in + pi2d-*-*.tar.gz) + t="${archive_name#pi2d-}" + t="${t#*-}" + target="${t%.tar.gz}" + ;; + *) + target="${os}-${arch}" + ;; + esac + + if [ "$PI2_SKIP_CHECKSUM" = "1" ]; then + printf 'info: skipping checksum verification (PI2_SKIP_CHECKSUM=1)\n' + else + sums_file="" + require_entry=1 + if [ -n "${PI2_CHECKSUM_FILE:-}" ] && [ -f "$PI2_CHECKSUM_FILE" ]; then + sums_file="$PI2_CHECKSUM_FILE" + require_entry=1 + elif [ -f "${archive_path}.sha256" ]; then + sums_file="${archive_path}.sha256" + require_entry=1 + elif [ -f "$(dirname "$archive_path")/SHA256SUMS" ]; then + sums_file="$(dirname "$archive_path")/SHA256SUMS" + require_entry=0 + fi + + if [ -n "$sums_file" ]; then + verify_checksum "$archive_path" "$sums_file" "$require_entry" + else + printf 'info: no SHA256SUMS found next to archive; skipping checksum verification\n' + fi + fi +else + # Online install path + tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/pi2d-install.XXXXXX")" + + if [ -n "${PI2_VERSION:-}" ]; then + version="${PI2_VERSION#v}" + else + printf 'Querying latest release from GitHub...\n' + latest_api_url="https://api.github.com/repos/zgs225/pi2d/releases/latest" + release_json="" + if ! release_json="$(fetch_text "$latest_api_url" 2>/dev/null)"; then + printf 'Error: Failed to fetch latest release from %s\n' "$latest_api_url" >&2 + printf 'The GitHub API may be unreachable or rate-limited.\n' >&2 + printf 'Specify a version explicitly: PI2_VERSION= %s\n' "$0" >&2 + exit 1 + fi + + tag="" + if command -v jq >/dev/null 2>&1; then + tag="$(printf '%s' "$release_json" | jq -r .tag_name 2>/dev/null || true)" + fi + if [ -z "$tag" ] || [ "$tag" = "null" ]; then + tag="$(printf '%s\n' "$release_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)" + fi + + if [ -z "$tag" ] || [ "$tag" = "null" ]; then + printf 'Error: Could not parse release tag from GitHub API response.\n' >&2 + printf 'Specify a version explicitly: PI2_VERSION= %s\n' "$0" >&2 + exit 1 + fi + version="${tag#v}" + fi + + base_url="${PI2_BASE_URL:-https://github.com/zgs225/pi2d/releases/download/v${version}}" + base_url="${base_url%/}" + + # Fetch SHA256SUMS if checksums are enabled + sums_file="" + if [ "$PI2_SKIP_CHECKSUM" != "1" ]; then + sums_url="${base_url}/SHA256SUMS" + sums_file="$tmp_dir/SHA256SUMS" + printf 'Downloading SHA256SUMS from %s...\n' "$sums_url" + if ! download_file "$sums_url" "$sums_file"; then + printf 'Error: Failed to download SHA256SUMS from %s\n' "$sums_url" >&2 + printf 'To bypass checksum verification, set PI2_SKIP_CHECKSUM=1\n' >&2 + exit 1 + fi + fi + + # Determine target architecture/libc + if [ "$os" = "darwin" ]; then + target="darwin-${arch}" + archive_name="pi2d-${version}-${target}.tar.gz" + elif [ "$os" = "linux" ]; then + if [ "$is_musl" -eq 1 ]; then + musl_target="linux-${arch}-musl" + musl_archive="pi2d-${version}-${musl_target}.tar.gz" + glibc_target="linux-${arch}" + glibc_archive="pi2d-${version}-${glibc_target}.tar.gz" + + if [ -n "$sums_file" ] && [ -f "$sums_file" ]; then + if grep -F "$musl_archive" "$sums_file" >/dev/null 2>&1; then + target="$musl_target" + archive_name="$musl_archive" + elif grep -F "$glibc_archive" "$sums_file" >/dev/null 2>&1; then + printf 'info: musl asset not found in SHA256SUMS, falling back to glibc (%s)\n' "$glibc_target" + target="$glibc_target" + archive_name="$glibc_archive" + else + printf 'Error: Neither %s nor %s found in release SHA256SUMS\n' "$musl_archive" "$glibc_archive" >&2 + print_supported_platforms + exit 1 + fi + else + target="$musl_target" + archive_name="$musl_archive" + fi + else + target="linux-${arch}" + archive_name="pi2d-${version}-${target}.tar.gz" + fi + fi + + archive_url="${base_url}/${archive_name}" + archive_path="$tmp_dir/${archive_name}" + printf 'Downloading %s...\n' "$archive_url" + + if ! download_file "$archive_url" "$archive_path"; then + if [ "$os" = "linux" ] && [ "$target" = "linux-${arch}-musl" ]; then + printf 'info: musl archive download failed, falling back to glibc asset\n' + target="linux-${arch}" + archive_name="pi2d-${version}-${target}.tar.gz" + archive_url="${base_url}/${archive_name}" + archive_path="$tmp_dir/${archive_name}" + if ! download_file "$archive_url" "$archive_path"; then + printf 'Error: Failed to download release archive %s from %s\n' "$archive_name" "$base_url" >&2 + print_supported_platforms + exit 1 + fi + else + printf 'Error: Failed to download release archive %s from %s\n' "$archive_name" "$base_url" >&2 + print_supported_platforms + exit 1 + fi + fi + + if [ "$PI2_SKIP_CHECKSUM" = "1" ]; then + printf 'info: skipping checksum verification (PI2_SKIP_CHECKSUM=1)\n' + else + verify_checksum "$archive_path" "$sums_file" 1 + fi +fi + +# ----------------------------------------------------------------------------- +# Unpack & Atomic Install +# ----------------------------------------------------------------------------- + +printf 'Installing pi2 to %s...\n' "$PI2_INSTALL_DIR" +mkdir -p "$PI2_INSTALL_DIR" +staging="$PI2_INSTALL_DIR/.staging.$$" +rm -rf "$staging" +mkdir -p "$staging" + +if ! tar -xzf "$archive_path" -C "$staging"; then + rm -rf "$staging" + staging="" + printf 'Error: Failed to extract archive %s\n' "$archive_path" >&2 + exit 1 +fi + +if [ ! -f "$staging/bin/pi2" ]; then + rm -rf "$staging" + staging="" + printf 'Error: Archive does not contain bin/pi2\n' >&2 + exit 1 +fi + +chmod +x "$staging/bin/pi2" +if [ ! -x "$staging/bin/pi2" ]; then + rm -rf "$staging" + staging="" + printf 'Error: %s/bin/pi2 is not executable\n' "$staging" >&2 + exit 1 +fi + +# Atomic swap: move existing directories aside before moving staged directories +rm -rf "$PI2_INSTALL_DIR/bin.old.$$" "$PI2_INSTALL_DIR/share.old.$$" "$PI2_INSTALL_DIR/LICENSE.old.$$" +[ -d "$PI2_INSTALL_DIR/bin" ] && mv "$PI2_INSTALL_DIR/bin" "$PI2_INSTALL_DIR/bin.old.$$" +[ -d "$PI2_INSTALL_DIR/share" ] && mv "$PI2_INSTALL_DIR/share" "$PI2_INSTALL_DIR/share.old.$$" +[ -f "$PI2_INSTALL_DIR/LICENSE" ] && mv "$PI2_INSTALL_DIR/LICENSE" "$PI2_INSTALL_DIR/LICENSE.old.$$" + +mv "$staging/bin" "$PI2_INSTALL_DIR/bin" +if [ -d "$staging/share" ]; then + mv "$staging/share" "$PI2_INSTALL_DIR/share" +fi +if [ -f "$staging/LICENSE" ]; then + mv "$staging/LICENSE" "$PI2_INSTALL_DIR/LICENSE" +fi + +rm -rf "$PI2_INSTALL_DIR/bin.old.$$" "$PI2_INSTALL_DIR/share.old.$$" "$PI2_INSTALL_DIR/LICENSE.old.$$" "$staging" +staging="" + +# Symlink executable into PI2_BIN_DIR +mkdir -p "$PI2_BIN_DIR" +symlink="$PI2_BIN_DIR/pi2" +binary_target="$PI2_INSTALL_DIR/bin/pi2" + +rm -f "$symlink" +ln -s "$binary_target" "$symlink" + +# ----------------------------------------------------------------------------- +# Final Output & Next Steps +# ----------------------------------------------------------------------------- + +printf '\npi2 %s (%s) installed successfully!\n\n' "$version" "$target" +printf 'Install location:\n' +printf ' - Directory: %s\n' "$PI2_INSTALL_DIR" +printf ' - Executable: %s -> %s\n\n' "$symlink" "$binary_target" + +printf 'Next steps:\n' +printf ' - Run in foreground:\n' +printf ' pi2 daemon\n' +printf ' - Run as background service (systemd user unit or macOS LaunchAgent):\n' +printf ' pi2 install-service --write\n' + +in_path=0 +case ":$PATH:" in + *":$PI2_BIN_DIR:"*) in_path=1 ;; +esac + +if [ "$in_path" -eq 0 ]; then + printf '\nWarning: %s is not in your PATH.\n' "$PI2_BIN_DIR" + printf 'To run pi2 directly, add it to your shell configuration (e.g. ~/.bashrc or ~/.zshrc):\n' + printf " export PATH=\"%s:\$PATH\"\n" "$PI2_BIN_DIR" +fi diff --git a/scripts/smoke-binary.sh b/scripts/smoke-binary.sh new file mode 100755 index 0000000..28302bc --- /dev/null +++ b/scripts/smoke-binary.sh @@ -0,0 +1,303 @@ +#!/usr/bin/env bash +# +# Smoke test for the compiled standalone binary distribution of pi2d. +# +# Asserts the dist-bin/bin/pi2 binary against: +# 1. Daemon startup: writes exactly ONE stdout line matching 'listening on http://' +# 2. GET /api/v1/info: 200, v == 1, version == package.json version +# 3. GET /: 200 and HTML body (served from share/pi2d/web/dist) +# 4. GET /api/v1/health: static item ok +# 5. pi2 doctor: node/runtime check ok, no FAIL for node, exit code 0 or 1 +# 6. pi2 install-service --dry-run: ExecStart first word is binary path, no 'pi2.js' or 'node ' +# 7. SIGTERM: clean exit 0, daemon.json and daemon.lock removed +# +# Usage: +# bash scripts/smoke-binary.sh +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +TMP="$(mktemp -d "${TMPDIR:-/tmp}/pi2-smoke-binary.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 +# Hermetic: bind loopback even though the daemon defaults to 0.0.0.0 (the +# unit/env tests cover the wildcard default); never inherit an ambient PI2_HOST. +export PI2_HOST="${PI2_HOST:-127.0.0.1}" +export PI2_LOG_LEVEL="${PI2_LOG_LEVEL:-warn}" + +LOG="$TMP/pi2-daemon.log" +DAEMON_JSON="$PI2_RUNTIME_DIR/daemon.json" +LOCK="$PI2_RUNTIME_DIR/daemon.lock" +BODY="$TMP/body" +DAEMON_PID="" +FAILED=0 + +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 + FAILED=$((FAILED + 1)) +} + +require() { + command -v "$1" >/dev/null 2>&1 || { + printf 'FAIL missing required command: %s\n' "$1" >&2 + exit 1 + } +} + +require curl +require node + +# request [curl args...] -> writes body to $BODY, echoes 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" 2>/dev/null || echo "000" +} + +expect_status() { + local expected="$1" + local method="$2" + local path="$3" + shift 3 + local actual + actual="$(request "$method" "$path" "$@")" + if [[ "$actual" != "$expected" ]]; then + fail "expected HTTP $expected for $method $path, got $actual ($(head -c 200 "$BODY" 2>/dev/null || true))" + return 1 + fi + return 0 +} + +expect_json() { + local expression="$1" + local what="$2" + local file="${3:-$BODY}" + if ! node --input-type=module -e " + import { readFileSync } from 'node:fs'; + const body = JSON.parse(readFileSync(process.argv[1], 'utf8')); + if (!($expression)) { + process.exit(1); + } + " "$file" 2>/dev/null; then + fail "$what" + return 1 + fi + return 0 +} + +BINARY="$ROOT/dist-bin/bin/pi2" + +if [[ "${PI2_SKIP_BUILD:-0}" == "1" && -x "$BINARY" ]]; then + printf '==> reusing existing binary at %s (PI2_SKIP_BUILD=1)\n' "$BINARY" +else + printf '==> building binary with scripts/build-binary.sh\n' + bash scripts/build-binary.sh --no-archive >"$TMP/build.log" 2>&1 || { + cat "$TMP/build.log" >&2 + printf 'FAIL scripts/build-binary.sh failed\n' >&2 + exit 1 + } +fi + +[[ -x "$BINARY" ]] || { + printf 'FAIL compiled binary missing or not executable at %s\n' "$BINARY" >&2 + exit 1 +} + +PKG_VERSION="$(node -e "console.log(JSON.parse(require('fs').readFileSync('package.json', 'utf8')).version)")" + +# --- Assertion 1: bin/pi2 daemon --port 0 writes exactly ONE stdout line matching 'listening on http://' --- +printf '==> starting pi2 daemon via compiled binary (port 0)\n' +"$BINARY" daemon --port 0 >"$TMP/stdout.log" 2>"$LOG" & +DAEMON_PID=$! + +for _ in $(seq 1 200); do + [[ -f "$DAEMON_JSON" ]] && break + kill -0 "$DAEMON_PID" 2>/dev/null || break + sleep 0.05 +done + +if [[ ! -f "$DAEMON_JSON" ]]; then + fail "daemon.json was not written by compiled binary" + BASE_URL="" +else + 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")" + BASE_URL="http://127.0.0.1:$PORT" + + MATCH_COUNT="$(grep -c 'listening on http://' "$TMP/stdout.log" || true)" + if [[ "$MATCH_COUNT" -eq 1 ]]; then + pass "1. daemon --port 0 wrote exactly ONE line matching 'listening on http://'" + else + fail "1. daemon --port 0 expected exactly ONE matching stdout line, got $MATCH_COUNT ($(cat "$TMP/stdout.log"))" + fi +fi + +# --- Assertion 2: GET /api/v1/info -> 200, v == 1, version == package.json version --- +if [[ -n "$BASE_URL" ]]; then + if expect_status 200 GET /api/v1/info; then + if expect_json "body.v === 1 && body.version === '$PKG_VERSION'" "2. GET /api/v1/info reports v=1 and version=$PKG_VERSION"; then + pass "2. GET /api/v1/info -> 200, v=1, version=$PKG_VERSION" + fi + else + fail "2. GET /api/v1/info did not return 200" + fi +else + fail "2. GET /api/v1/info skipped (daemon not running)" +fi + +# --- Assertion 3: GET / -> 200 and an HTML body (served from share/pi2d/web/dist) --- +if [[ -n "$BASE_URL" ]]; then + if expect_status 200 GET /; then + if ! grep -qi 'text/html' <(curl -sS -D - -o /dev/null --max-time 5 "$BASE_URL/"); then + fail "3. GET / did not return text/html" + elif ! grep -q 'id="root"\|id=app' "$BODY"; then + fail "3. GET / body is not the web UI shell" + elif ! grep -q '' "$BODY"; then + fail "3. GET / body has no <title>" + else + pass "3. GET / -> 200 html from share/pi2d/web/dist" + fi + else + fail "3. GET / returned non-200" + fi +else + fail "3. GET / skipped (daemon not running)" +fi + +# --- Assertion 4: GET /api/v1/health -> static item ok --- +if [[ -n "$BASE_URL" ]]; then + if expect_status 200 GET /api/v1/health; then + if expect_json "Array.isArray(body.items) && body.items.some(item => item.name === 'static' && item.ok === true)" "4. GET /api/v1/health static item ok"; then + pass "4. GET /api/v1/health -> static item ok" + fi + else + fail "4. GET /api/v1/health did not return 200" + fi +else + fail "4. GET /api/v1/health skipped (daemon not running)" +fi + +# --- Assertion 5: bin/pi2 doctor reports node/runtime check as ok and not failure --- +set +e +"$BINARY" doctor >"$TMP/doctor.log" 2>&1 +DOCTOR_EXIT=$? +set -e + +DOCTOR_OK=1 +if [[ "$DOCTOR_EXIT" -ne 0 && "$DOCTOR_EXIT" -ne 1 ]]; then + fail "5. pi2 doctor exited with unexpected code $DOCTOR_EXIT (expected 0 or 1)" + DOCTOR_OK=0 +fi +if grep -E '^[[:space:]]*FAIL[[:space:]]+node\b' "$TMP/doctor.log" >/dev/null 2>&1; then + fail "5. pi2 doctor reported FAIL line for node" + DOCTOR_OK=0 +fi +if ! grep -E '^[[:space:]]*ok[[:space:]]+(node|runtime)\b' "$TMP/doctor.log" >/dev/null 2>&1; then + fail "5. pi2 doctor did not report node/runtime check as ok" + DOCTOR_OK=0 +fi +if [[ "$DOCTOR_OK" -eq 1 ]]; then + pass "5. pi2 doctor reports node/runtime check as ok (exit code $DOCTOR_EXIT)" +fi + +# --- Assertion 6: bin/pi2 install-service --dry-run renders clean ExecStart --- +set +e +"$BINARY" install-service --dry-run >"$TMP/service.log" 2>&1 +SERVICE_EXIT=$? +set -e + +SERVICE_OK=1 +if [[ "$SERVICE_EXIT" -ne 0 ]]; then + fail "6. pi2 install-service --dry-run failed with exit code $SERVICE_EXIT" + SERVICE_OK=0 +fi + +EXEC_START="$(grep '^ExecStart=' "$TMP/service.log" || true)" +if [[ -z "$EXEC_START" ]]; then + fail "6. pi2 install-service --dry-run did not output ExecStart=" + SERVICE_OK=0 +else + FIRST_WORD="$(echo "${EXEC_START#ExecStart=}" | awk '{print $1}' | tr -d '"')" + REAL_BINARY="$(realpath "$BINARY")" + if [[ "$FIRST_WORD" != "$REAL_BINARY" && "$FIRST_WORD" != "$BINARY" ]]; then + fail "6. ExecStart first word is '$FIRST_WORD', expected '$REAL_BINARY'" + SERVICE_OK=0 + fi + if echo "$EXEC_START" | grep -q 'pi2\.js'; then + fail "6. ExecStart contains 'pi2.js': $EXEC_START" + SERVICE_OK=0 + fi + if echo "$EXEC_START" | grep -q 'node '; then + fail "6. ExecStart contains 'node ': $EXEC_START" + SERVICE_OK=0 + fi +fi + +if [[ "$SERVICE_OK" -eq 1 ]]; then + pass "6. pi2 install-service --dry-run renders clean ExecStart without pi2.js or node" +fi + +# --- Assertion 7: SIGTERM -> clean exit 0, daemon.json + daemon.lock removed --- +if [[ -n "$DAEMON_PID" ]] && kill -0 "$DAEMON_PID" 2>/dev/null; then + printf '==> stopping daemon via SIGTERM\n' + kill -TERM "$DAEMON_PID" + set +e + wait "$DAEMON_PID" + DAEMON_EXIT=$? + set -e + DAEMON_PID="" + + SIGTERM_OK=1 + if [[ "$DAEMON_EXIT" -ne 0 ]]; then + fail "7. daemon exited with code $DAEMON_EXIT on SIGTERM (expected 0)" + SIGTERM_OK=0 + fi + if [[ -f "$LOCK" ]]; then + fail "7. daemon.lock was not removed on SIGTERM" + SIGTERM_OK=0 + fi + if [[ -f "$DAEMON_JSON" ]]; then + fail "7. daemon.json was not removed on SIGTERM" + SIGTERM_OK=0 + fi + + if [[ "$SIGTERM_OK" -eq 1 ]]; then + pass "7. SIGTERM -> clean exit 0, daemon.json and daemon.lock removed" + fi +else + fail "7. SIGTERM skipped (daemon was not running)" +fi + +if [[ "$FAILED" -gt 0 ]]; then + printf '\nSMOKE FAILED (%d assertion(s) failed, tmp dir: %s)\n' "$FAILED" "$TMP" >&2 + if [[ -f "$LOG" ]]; then + printf '\n--- pi2 daemon log ---\n' >&2 + tail -n 40 "$LOG" >&2 || true + fi + PI2_SMOKE_KEEP=1 + exit 1 +fi + +printf '\nSMOKE OK (%s)\n' "$TMP" diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 7d15068..23784ee 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -18,6 +18,9 @@ PI2_DATA_DIR="$TMP/data" PI2_STATE_DIR="$TMP/state" export PI2_RUNTIME_DIR PI2_DATA_DIR PI2_STATE_DIR export PI2_PORT=0 +# Hermetic: bind loopback (the daemon defaults to 0.0.0.0, which the unit/env +# tests cover); an ambient PI2_HOST from the developer's shell must not leak in. +export PI2_HOST="${PI2_HOST:-127.0.0.1}" export PI2_LOG_LEVEL="${PI2_LOG_LEVEL:-warn}" LOG="$TMP/pi2-daemon.log" @@ -25,7 +28,6 @@ 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() { @@ -133,9 +135,9 @@ pass "daemon.lock holds pid $DAEMON_PID" expect_json "body.protocolVersion === 1" "daemon.json protocolVersion === 1" "$DAEMON_JSON" -grep -q "^pi2 daemon listening on http://127.0.0.1:$PORT$" "$TMP/stdout.log" || - fail "stdout line missing: expected 'pi2 daemon listening on http://127.0.0.1:$PORT' (got: $(cat "$TMP/stdout.log"))" -pass "stdout announced http://127.0.0.1:$PORT" +grep -q "^pi2 daemon listening on http://$PI2_HOST:$PORT$" "$TMP/stdout.log" || + fail "stdout line missing: expected 'pi2 daemon listening on http://$PI2_HOST:$PORT' (got: $(cat "$TMP/stdout.log"))" +pass "stdout announced http://$PI2_HOST:$PORT" [[ -f "$TOKEN_FILE" ]] || fail "cli.token missing" TOKEN="$(tr -d '\n' <"$TOKEN_FILE")" diff --git a/scripts/ui-mock-server.mjs b/scripts/ui-mock-server.mjs index 1b43e38..7e9da2f 100644 --- a/scripts/ui-mock-server.mjs +++ b/scripts/ui-mock-server.mjs @@ -337,6 +337,27 @@ async function handleApi(req, res, url) { if (pathname === "/api/v1/workspaces" && method === "GET") { return sendJson(res, 200, FIXTURES.workspaces); } + // Disk-projected recent sessions (see docs/protocol.md §3.1). The mock has + // no live/disk split, so it projects the fixture rows and lets the browser + // merge the `/sessions` relay over them, exactly like the real console. + if (pathname === "/api/v1/sessions/recent" && method === "GET") { + const raw = Number(url.searchParams.get("limit")); + const limit = Number.isFinite(raw) && raw > 0 ? Math.min(200, Math.floor(raw)) : 20; + const nameById = new Map(FIXTURES.workspaces.map((workspace) => [workspace.workspaceId, workspace.name])); + const rows = FIXTURES.sessions + .map((session) => ({ + sessionId: session.sessionId, + workspaceId: session.workspaceId, + workspaceName: nameById.get(session.workspaceId) ?? session.workspaceId, + cwd: session.cwd ?? "", + sessionFile: `/sessions/${session.sessionId}.jsonl`, + timestamp: session.createdAt ?? session.lastActiveAt ?? 0, + modified: session.lastActiveAt ?? session.modified ?? 0, + })) + .sort((a, b) => b.modified - a.modified || a.sessionId.localeCompare(b.sessionId)) + .slice(0, limit); + return sendJson(res, 200, { v: 1, sessions: rows }); + } let match = /^\/api\/v1\/workspaces\/([^/]+)\/sessions$/.exec(pathname); if (match && method === "GET") { const workspaceId = decodeURIComponent(match[1]); diff --git a/scripts/update-packaging.sh b/scripts/update-packaging.sh new file mode 100755 index 0000000..b3ba8ca --- /dev/null +++ b/scripts/update-packaging.sh @@ -0,0 +1,302 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" + +VERSION="" +CHECKSUMS_INPUT="" +OUT_DIR="${REPO_ROOT}/build" +NO_DOWNLOAD=0 + +KNOWN_TARGETS=( + "linux-x64" + "linux-arm64" + "linux-x64-musl" + "linux-arm64-musl" + "darwin-x64" + "darwin-arm64" +) + +usage() { + cat <<EOF +Usage: $(basename "$0") [options] + +Generates packaging artifacts (Homebrew formula, Arch PKGBUILD, .SRCINFO) +for system-packaged channels with deterministic checksum substitution. + +Options: + --version <v> Release version (e.g. 0.1.6). Defaults to package.json version. + --checksums <path> Path to SHA256SUMS file or directory containing release assets. + --out <dir> Output directory (default: build/) + --no-download Do not download SHA256SUMS from GitHub; require --checksums. + -h, --help Show this help message. +EOF +} + +# Parse command line flags +while [[ $# -gt 0 ]]; do + case "$1" in + --version) + [[ $# -ge 2 ]] || { echo "Error: --version requires an argument" >&2; exit 1; } + VERSION="$2" + shift 2 + ;; + --checksums) + [[ $# -ge 2 ]] || { echo "Error: --checksums requires an argument" >&2; exit 1; } + CHECKSUMS_INPUT="$2" + shift 2 + ;; + --out) + [[ $# -ge 2 ]] || { echo "Error: --out requires an argument" >&2; exit 1; } + OUT_DIR="$2" + shift 2 + ;; + --no-download) + NO_DOWNLOAD=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + echo "Error: Unknown argument: $1" >&2 + usage >&2 + exit 1 + ;; + esac +done + +# Derive version if not provided +if [[ -z "${VERSION}" ]]; then + if [[ -f "${REPO_ROOT}/package.json" ]]; then + VERSION=$(node -e 'console.log(JSON.parse(require("fs").readFileSync("'"${REPO_ROOT}"'/package.json")).version)' 2>/dev/null || grep -m1 '"version":' "${REPO_ROOT}/package.json" | sed -E 's/.*"version": *"([^"]+)".*/\1/') + fi +fi + +if [[ -z "${VERSION}" ]]; then + echo "Error: Release version not specified and could not be determined from package.json" >&2 + exit 1 +fi + +# Normalize version (Arch PKGBUILD forbids leading 'v') +VERSION="${VERSION#v}" + +is_known_target() { + local t="$1" + for k in "${KNOWN_TARGETS[@]}"; do + if [[ "$k" == "$t" ]]; then + return 0 + fi + done + return 1 +} + +extract_target() { + local fname="$1" + local base + base=$(basename "$fname") + local target="" + + if [[ "$base" == pi2d-"${VERSION}"-*.tar.gz ]]; then + target="${base#pi2d-"${VERSION}"-}" + target="${target%.tar.gz}" + elif [[ "$base" =~ ^pi2d-([0-9][^-]*)-(.*)\.tar\.gz$ ]]; then + local other_ver="${BASH_REMATCH[1]}" + echo "Error: Version mismatch in checksums filename '${base}': expected '${VERSION}', got '${other_ver}'" >&2 + exit 1 + elif [[ "$base" == pi2d-*.tar.gz ]]; then + target="${base#pi2d-}" + target="${target%.tar.gz}" + elif [[ "$base" == *.tar.gz ]]; then + target="${base%.tar.gz}" + else + target="$base" + fi + + if ! is_known_target "$target"; then + echo "Error: Unknown target in checksums: '${target}' (from filename: '${fname}')" >&2 + exit 1 + fi + + echo "$target" +} + +declare -A CHECKSUMS + +process_checksum_line() { + local line="$1" + # Skip empty lines or comments + [[ -z "${line// }" ]] && return 0 + [[ "${line}" =~ ^[[:space:]]*# ]] && return 0 + + local hash="" + local filename="" + read -r hash filename <<< "${line}" + + # Strip any leading * from binary mode sha256sum + filename="${filename#\*}" + # Clean whitespace and carriage returns + hash="${hash//[[:space:]]/}" + filename="${filename//$'\r'/}" + filename="${filename#"${filename%%[![:space:]]*}"}" + filename="${filename%"${filename##*[![:space:]]}"}" + + if ! [[ "${hash}" =~ ^[0-9a-fA-F]{64}$ ]]; then + echo "Error: Invalid sha256 checksum format: '${hash}' for file '${filename}'" >&2 + exit 1 + fi + + local target + target="$(extract_target "${filename}")" + CHECKSUMS["${target}"]="${hash}" +} + +# Collect checksums +if [[ -n "${CHECKSUMS_INPUT}" ]]; then + if [[ -f "${CHECKSUMS_INPUT}" ]]; then + while IFS= read -r line || [[ -n "$line" ]]; do + process_checksum_line "$line" + done < "${CHECKSUMS_INPUT}" + elif [[ -d "${CHECKSUMS_INPUT}" ]]; then + if [[ -f "${CHECKSUMS_INPUT}/SHA256SUMS" ]]; then + while IFS= read -r line || [[ -n "$line" ]]; do + process_checksum_line "$line" + done < "${CHECKSUMS_INPUT}/SHA256SUMS" + else + local_found=0 + for f in "${CHECKSUMS_INPUT}"/*.tar.gz; do + [[ -f "$f" ]] || continue + local_found=1 + hash=$(sha256sum "$f" | awk '{print $1}') + target=$(extract_target "$f") + CHECKSUMS["${target}"]="${hash}" + done + if [[ $local_found -eq 0 ]]; then + echo "Error: Directory '${CHECKSUMS_INPUT}' contains neither SHA256SUMS nor .tar.gz assets" >&2 + exit 1 + fi + fi + else + echo "Error: Checksums path does not exist: ${CHECKSUMS_INPUT}" >&2 + exit 1 + fi +else + if [[ $NO_DOWNLOAD -eq 1 ]]; then + echo "Error: --no-download specified but --checksums was not provided." >&2 + exit 1 + fi + + SUMS_URL="https://github.com/zgs225/pi2d/releases/download/v${VERSION}/SHA256SUMS" + echo "Downloading checksums from ${SUMS_URL}..." + TMP_SUMS=$(mktemp) + trap 'rm -f "${TMP_SUMS}"' EXIT + if ! curl -fsSL "${SUMS_URL}" -o "${TMP_SUMS}"; then + echo "Error: Failed to download SHA256SUMS from ${SUMS_URL}" >&2 + exit 1 + fi + while IFS= read -r line || [[ -n "$line" ]]; do + process_checksum_line "$line" + done < "${TMP_SUMS}" + rm -f "${TMP_SUMS}" + trap - EXIT +fi + +# Ensure all 6 required targets have checksums +for target in "${KNOWN_TARGETS[@]}"; do + if [[ -z "${CHECKSUMS[${target}]:-}" ]]; then + echo "Error: Missing checksum for required target: ${target}" >&2 + exit 1 + fi +done + +SHA256_LINUX_X64="${CHECKSUMS[linux-x64]}" +SHA256_LINUX_ARM64="${CHECKSUMS[linux-arm64]}" +SHA256_LINUX_X64_MUSL="${CHECKSUMS[linux-x64-musl]}" +SHA256_LINUX_ARM64_MUSL="${CHECKSUMS[linux-arm64-musl]}" +SHA256_DARWIN_X64="${CHECKSUMS[darwin-x64]}" +SHA256_DARWIN_ARM64="${CHECKSUMS[darwin-arm64]}" + +BREW_TEMPLATE="${REPO_ROOT}/packaging/homebrew/pi2d.rb.in" +AUR_TEMPLATE="${REPO_ROOT}/packaging/aur/PKGBUILD.in" + +if [[ ! -f "${BREW_TEMPLATE}" ]]; then + echo "Error: Homebrew template not found at ${BREW_TEMPLATE}" >&2 + exit 1 +fi + +if [[ ! -f "${AUR_TEMPLATE}" ]]; then + echo "Error: AUR template not found at ${AUR_TEMPLATE}" >&2 + exit 1 +fi + +mkdir -p "${OUT_DIR}" + +render_template() { + local src="$1" + local dst="$2" + sed \ + -e "s|@@VERSION@@|${VERSION}|g" \ + -e "s|@@SHA256_LINUX_X64@@|${SHA256_LINUX_X64}|g" \ + -e "s|@@SHA256_LINUX_ARM64@@|${SHA256_LINUX_ARM64}|g" \ + -e "s|@@SHA256_LINUX_X64_MUSL@@|${SHA256_LINUX_X64_MUSL}|g" \ + -e "s|@@SHA256_LINUX_ARM64_MUSL@@|${SHA256_LINUX_ARM64_MUSL}|g" \ + -e "s|@@SHA256_DARWIN_X64@@|${SHA256_DARWIN_X64}|g" \ + -e "s|@@SHA256_DARWIN_ARM64@@|${SHA256_DARWIN_ARM64}|g" \ + "${src}" > "${dst}" +} + +render_template "${BREW_TEMPLATE}" "${OUT_DIR}/pi2d.rb" +render_template "${AUR_TEMPLATE}" "${OUT_DIR}/PKGBUILD" + +TAB=$'\t' +if command -v makepkg >/dev/null 2>&1; then + ( cd "${OUT_DIR}" && makepkg --printsrcinfo ) > "${OUT_DIR}/SRCINFO" +else + cat <<EOF > "${OUT_DIR}/SRCINFO" +pkgbase = pi2d-bin +${TAB}pkgdesc = Web console daemon for pi2.nvim +${TAB}pkgver = ${VERSION} +${TAB}pkgrel = 1 +${TAB}url = https://github.com/zgs225/pi2d +${TAB}arch = x86_64 +${TAB}arch = aarch64 +${TAB}license = MIT +${TAB}provides = pi2d +${TAB}conflicts = pi2d +${TAB}options = !strip +${TAB}source_x86_64 = https://github.com/zgs225/pi2d/releases/download/v${VERSION}/pi2d-${VERSION}-linux-x64.tar.gz +${TAB}sha256sums_x86_64 = ${SHA256_LINUX_X64} +${TAB}source_aarch64 = https://github.com/zgs225/pi2d/releases/download/v${VERSION}/pi2d-${VERSION}-linux-arm64.tar.gz +${TAB}sha256sums_aarch64 = ${SHA256_LINUX_ARM64} + +pkgname = pi2d-bin +EOF +fi +cp "${OUT_DIR}/SRCINFO" "${OUT_DIR}/.SRCINFO" + +# Verify no placeholders survived +for file in "${OUT_DIR}/pi2d.rb" "${OUT_DIR}/PKGBUILD" "${OUT_DIR}/SRCINFO" "${OUT_DIR}/.SRCINFO"; do + if grep -q "@@" "${file}"; then + echo "Error: Unsubstituted placeholder found in ${file}:" >&2 + grep -n "@@" "${file}" >&2 + exit 1 + fi +done + +echo "Packaging update completed successfully for pi2d v${VERSION}." +echo "" +echo "Target SHA256 checksums used:" +echo " darwin-arm64: ${SHA256_DARWIN_ARM64}" +echo " darwin-x64: ${SHA256_DARWIN_X64}" +echo " linux-arm64: ${SHA256_LINUX_ARM64}" +echo " linux-arm64-musl: ${SHA256_LINUX_ARM64_MUSL}" +echo " linux-x64: ${SHA256_LINUX_X64}" +echo " linux-x64-musl: ${SHA256_LINUX_X64_MUSL}" +echo "" +echo "Rendered files:" +echo " ${OUT_DIR}/pi2d.rb" +echo " ${OUT_DIR}/PKGBUILD" +echo " ${OUT_DIR}/SRCINFO" +echo " ${OUT_DIR}/.SRCINFO" diff --git a/src/cli/config.ts b/src/cli/config.ts new file mode 100644 index 0000000..b45888f --- /dev/null +++ b/src/cli/config.ts @@ -0,0 +1,255 @@ +/** + * `pi2 config` — print the resolved configuration and the source (environment + * variable or default) that produced each value. + * + * Read-only: no running daemon required, no network, and safe to execute before + * any runtime directories have been created on disk. + */ +import { homedir, platform as osPlatform, tmpdir } from "node:os"; +import { join } from "node:path"; +import { DEFAULT_HOST, DEFAULT_PORT, normalizePublicUrl, parsePort } from "../config.js"; +import { defaultStaticDir, isBundledRuntime, runtimeDescription, version } from "../core/install.js"; +import { rootsFromEnv } from "../workspaces/index.js"; +import { formatTable } from "./util.js"; + +export const CONFIG_USAGE = `pi2 config — print resolved configuration and sources + +Usage: + pi2 config [options] + +Options: + --json emit machine-readable JSON object + -h, --help print this help and exit`; + +export interface ResolvedConfig { + port: number; + host: string; + publicUrl: string | null; + staticDir: string; + runtimeDir: string; + dataDir: string; + stateDir: string; + codingAgentDir: string; + workspaceRoots: string[]; + logLevel: string; + version: string; + platform: string; + runtime: string; + installShape: string; +} + +export type ConfigKey = keyof ResolvedConfig; + +export type ConfigSources = Record<ConfigKey, string>; + +export interface ConfigResolution { + config: ResolvedConfig; + sources: ConfigSources; +} + +export type ConfigJsonOutput = ResolvedConfig & { + sources: ConfigSources; +}; + +export const CONFIG_KEYS: readonly ConfigKey[] = [ + "port", + "host", + "publicUrl", + "staticDir", + "runtimeDir", + "dataDir", + "stateDir", + "codingAgentDir", + "workspaceRoots", + "logLevel", + "version", + "platform", + "runtime", + "installShape", +] as const; + +export interface ResolveConfigOptions { + env?: Record<string, string | undefined>; + platform?: string; + home?: string; + uid?: number; + version?: string; + runtime?: string; + installShape?: string; + staticDir?: string; +} + +function resolveRuntimeDir( + env: Record<string, string | undefined>, + platform: string, + home: string, + uid: number, +): { value: string; source: string } { + if (env.PI2_RUNTIME_DIR !== undefined && env.PI2_RUNTIME_DIR.trim() !== "") { + return { value: env.PI2_RUNTIME_DIR.trim(), source: "PI2_RUNTIME_DIR" }; + } + if (platform === "darwin") { + return { value: join(home, "Library", "Caches", "pi2", "run"), source: "default" }; + } + return { value: join(env.XDG_RUNTIME_DIR ?? join(tmpdir(), `pi2-${uid}`), "pi2"), source: "default" }; +} + +function resolveDataDir( + env: Record<string, string | undefined>, + platform: string, + home: string, +): { value: string; source: string } { + if (env.PI2_DATA_DIR !== undefined && env.PI2_DATA_DIR.trim() !== "") { + return { value: env.PI2_DATA_DIR.trim(), source: "PI2_DATA_DIR" }; + } + if (platform === "darwin") { + return { value: join(home, "Library", "Application Support", "pi2"), source: "default" }; + } + return { value: join(env.XDG_DATA_HOME ?? join(home, ".local", "share"), "pi2"), source: "default" }; +} + +function resolveStateDir( + env: Record<string, string | undefined>, + platform: string, + home: string, +): { value: string; source: string } { + if (env.PI2_STATE_DIR !== undefined && env.PI2_STATE_DIR.trim() !== "") { + return { value: env.PI2_STATE_DIR.trim(), source: "PI2_STATE_DIR" }; + } + if (platform === "darwin") { + return { value: join(home, "Library", "Logs", "pi2"), source: "default" }; + } + return { value: join(env.XDG_STATE_HOME ?? join(home, ".local", "state"), "pi2"), source: "default" }; +} + +export function resolveConfig(options: ResolveConfigOptions = {}): ConfigResolution { + const env = options.env ?? process.env; + const platform = options.platform ?? osPlatform(); + const home = options.home ?? env.HOME ?? homedir(); + const uid = options.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0); + + const port = + env.PI2_PORT !== undefined && env.PI2_PORT.trim() !== "" + ? { value: parsePort(env.PI2_PORT), source: "PI2_PORT" } + : { value: DEFAULT_PORT, source: "default" }; + + const host = + env.PI2_HOST !== undefined && env.PI2_HOST.trim() !== "" + ? { value: env.PI2_HOST.trim(), source: "PI2_HOST" } + : { value: DEFAULT_HOST, source: "default" }; + + const publicUrl = + env.PI2_PUBLIC_URL !== undefined && env.PI2_PUBLIC_URL.trim() !== "" + ? { value: normalizePublicUrl(env.PI2_PUBLIC_URL), source: "PI2_PUBLIC_URL" } + : { value: null, source: "default" }; + + const staticDir = + env.PI2_STATIC_DIR !== undefined && env.PI2_STATIC_DIR.trim() !== "" + ? { value: env.PI2_STATIC_DIR.trim(), source: "PI2_STATIC_DIR" } + : { value: options.staticDir ?? defaultStaticDir(), source: "install layout" }; + + const runtimeDir = resolveRuntimeDir(env, platform, home, uid); + const dataDir = resolveDataDir(env, platform, home); + const stateDir = resolveStateDir(env, platform, home); + + const codingAgentDir = + env.PI2_CODING_AGENT_DIR !== undefined && env.PI2_CODING_AGENT_DIR.trim() !== "" + ? { value: env.PI2_CODING_AGENT_DIR.trim(), source: "PI2_CODING_AGENT_DIR" } + : env.PI_CODING_AGENT_DIR !== undefined && env.PI_CODING_AGENT_DIR.trim() !== "" + ? { value: env.PI_CODING_AGENT_DIR.trim(), source: "PI_CODING_AGENT_DIR" } + : { value: join(home, ".pi", "agent"), source: "default" }; + + const workspaceRoots = + env.PI2_WORKSPACE_ROOTS !== undefined && env.PI2_WORKSPACE_ROOTS.trim() !== "" + ? { value: rootsFromEnv(env.PI2_WORKSPACE_ROOTS, home), source: "PI2_WORKSPACE_ROOTS" } + : { value: rootsFromEnv(undefined, home), source: "default" }; + + const logLevel = + env.PI2_LOG_LEVEL !== undefined && env.PI2_LOG_LEVEL.trim() !== "" + ? { value: env.PI2_LOG_LEVEL.trim().toLowerCase(), source: "PI2_LOG_LEVEL" } + : { value: "info", source: "default" }; + + const versionVal = { value: options.version ?? version(), source: "install layout" }; + const platformVal = { value: platform, source: "system" }; + const runtimeVal = { value: options.runtime ?? runtimeDescription(), source: "runtime" }; + const installShapeVal = { + value: options.installShape ?? (isBundledRuntime() ? "bundled" : "node"), + source: "install layout", + }; + + return { + config: { + port: port.value, + host: host.value, + publicUrl: publicUrl.value, + staticDir: staticDir.value, + runtimeDir: runtimeDir.value, + dataDir: dataDir.value, + stateDir: stateDir.value, + codingAgentDir: codingAgentDir.value, + workspaceRoots: workspaceRoots.value, + logLevel: logLevel.value, + version: versionVal.value, + platform: platformVal.value, + runtime: runtimeVal.value, + installShape: installShapeVal.value, + }, + sources: { + port: port.source, + host: host.source, + publicUrl: publicUrl.source, + staticDir: staticDir.source, + runtimeDir: runtimeDir.source, + dataDir: dataDir.source, + stateDir: stateDir.source, + codingAgentDir: codingAgentDir.source, + workspaceRoots: workspaceRoots.source, + logLevel: logLevel.source, + version: versionVal.source, + platform: platformVal.source, + runtime: runtimeVal.source, + installShape: installShapeVal.source, + }, + }; +} + +export function formatTableValue(key: ConfigKey, value: unknown): string { + if (value === null || value === undefined) return "-"; + if (Array.isArray(value)) { + return value.length === 0 ? "-" : value.join(", "); + } + return String(value); +} + +export function formatConfigTable(resolution: ConfigResolution): string { + const rows = CONFIG_KEYS.map((key) => [ + key, + formatTableValue(key, resolution.config[key]), + resolution.sources[key], + ]); + return formatTable(["key", "value", "source"], rows); +} + +export function configToJson(resolution: ConfigResolution): string { + const jsonOutput: ConfigJsonOutput = { + ...resolution.config, + sources: resolution.sources, + }; + return JSON.stringify(jsonOutput, null, 2); +} + +export interface RunConfigOptions extends ResolveConfigOptions { + json?: boolean; + print?: (line: string) => void; +} + +export function runConfig(options: RunConfigOptions = {}): number { + const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`)); + const resolution = resolveConfig(options); + if (options.json) { + print(configToJson(resolution)); + } else { + print(formatConfigTable(resolution)); + } + return 0; +} diff --git a/src/cli/daemon.ts b/src/cli/daemon.ts index a23208a..e8d944c 100644 --- a/src/cli/daemon.ts +++ b/src/cli/daemon.ts @@ -16,7 +16,7 @@ * (optionally `pi2 daemon start`) to `main()`. */ import { randomUUID } from "node:crypto"; -import { loadConfig, DEFAULT_PORT, type Config } from "../config.js"; +import { loadConfig, DEFAULT_HOST, 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"; @@ -24,7 +24,7 @@ import { createLogger } from "./logger.js"; import { acquireLock, writeDaemonJson, type DaemonLockHandle } from "./lock.js"; import { cliTokenPath, writeCliToken } from "./token.js"; import { boolFlag, errorMessage, packageVersion, parseArgs, stringFlag, UsageError } from "./util.js"; -import { wireDaemon, type WiredDaemon } from "./wiring.js"; +import { wireDaemon, type StartedServer, type WiredDaemon } from "./wiring.js"; /** Extra attempts when the *default* port is taken (7676 → 7677 … 7685). */ export const DEFAULT_PORT_RETRIES = 9; @@ -35,7 +35,7 @@ Usage: pi2 daemon [start] [options] Options: --port <n> TCP port (default ${DEFAULT_PORT}; 0 = ephemeral) - --host <addr> bind address (default 127.0.0.1) + --host <addr> bind address (default ${DEFAULT_HOST} (all interfaces)) --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) @@ -43,9 +43,9 @@ Options: --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, - PI2_PUBLIC_URL + PI2_PORT, PI2_HOST (${DEFAULT_HOST} (all interfaces)), PI2_STATIC_DIR, + PI2_ORIGINS, PI2_RUNTIME_DIR, PI2_DATA_DIR, PI2_STATE_DIR, + PI2_LOG_LEVEL, PI2_WORKSPACE_ROOTS, PI2_PUBLIC_URL Runtime files ($PI2_RUNTIME_DIR): d.sock plugin unix socket (nvim → daemon) @@ -112,10 +112,15 @@ function defaultIo(): CliIo { }; } +export function startupLine(host: string, port: number): string { + return `pi2 daemon listening on http://${host}:${port}`; +} + export interface RunDaemonOptions { out?: (line: string) => void; err?: (line: string) => void; logger?: Logger; + onStarted?: (handle: { server: StartedServer; wired: WiredDaemon; close: () => Promise<void> }) => void | Promise<void>; } /** @@ -198,7 +203,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions lock.update({ port: server.port }); writeDaemonJson(lock.lock); // One machine-readable line; every log record goes to stderr. - io.out(`pi2 daemon listening on ${server.url}`); + io.out(startupLine(config.host, server.port)); } catch (error) { io.err(`pi2: ${errorMessage(error)}`); lock?.release(); @@ -226,12 +231,39 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions process.exit(0); }; + const cleanups: (() => void)[] = []; for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) { - process.once(signal, () => { + const handler = (): void => { void shutdown(signal).catch((error: unknown) => { io.err(`pi2: shutdown failed: ${errorMessage(error)}`); process.exit(1); }); + }; + process.once(signal, handler); + cleanups.push(() => process.off(signal, handler)); + } + + if (options.onStarted !== undefined && server !== undefined && wired !== undefined && lock !== undefined) { + const activeLock = lock; + const activeServer = server; + const activeWired = wired; + await options.onStarted({ + server: activeServer, + wired: activeWired, + close: async () => { + for (const off of cleanups) off(); + try { + await activeServer.close(); + } catch { + // ignore + } + try { + await activeWired.close(); + } catch { + // ignore + } + activeLock.release(); + }, }); } diff --git a/src/cli/doctor.ts b/src/cli/doctor.ts index 08c5810..dee700f 100644 --- a/src/cli/doctor.ts +++ b/src/cli/doctor.ts @@ -6,15 +6,22 @@ * build a context directly instead of poking at the real machine. */ import { execFile } from "node:child_process"; -import { existsSync, statSync } from "node:fs"; +import { existsSync, readFileSync, 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_HOST, DEFAULT_PORT, describeHost, loadConfig } from "../config.js"; +import { defaultStaticDir, executablePath, isBundledRuntime, runtimeDescription } from "../core/install.js"; import { isLoopbackHost } from "../core/network.js"; import { daemonSocketPath, runtimeDir } from "../core/paths.js"; import { PROTOCOL_VERSION } from "../protocol/types.js"; +import { + defaultServicePaths, + launchAgentDir, + LAUNCHD_PLIST_NAME, + systemdUserDir, + SYSTEMD_UNIT_NAME, +} from "./service.js"; import { formatTable } from "./util.js"; const execFileAsync = promisify(execFile); @@ -50,9 +57,17 @@ export interface BindContext { publicUrl: string | null; } +export interface UnitProbe { + path: string; + exists: boolean; + content?: string; + pathExists?: (path: string) => boolean; +} + export interface DoctorContext { platform: NodeJS.Platform; nodeVersion: string; + bundled?: boolean; nvim: BinaryProbe; pi: BinaryProbe; curl: BinaryProbe; @@ -65,6 +80,7 @@ export interface DoctorContext { bind: BindContext; serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string }; linger: { checked: boolean; enabled?: boolean; detail?: string }; + unit?: UnitProbe; webDist: { path: string; exists: boolean }; } @@ -98,15 +114,22 @@ export function parseCurlVersion(output: string | undefined): string | undefined return match?.[1]; } -export const MIN_NODE: readonly [number, number, number] = [22, 0, 0]; +export const MIN_NODE: readonly [number, number, number] = [20, 0, 0]; export const MIN_NVIM: readonly [number, number, number] = [0, 9, 0]; -/** `<repo>/web/dist`, matching `loadConfig()`'s default. */ +/** Built web UI, matching `loadConfig()`'s default. */ export function defaultWebDist(): string { - return fileURLToPath(new URL("../../web/dist", import.meta.url)); + return defaultStaticDir(); } -export function checkNode(version: string): DoctorCheck { +export function checkNode(version: string, bundled = false): DoctorCheck { + if (bundled) { + return { + name: "node", + status: "ok", + detail: `${runtimeDescription()} — bundled runtime, no separate node needed`, + }; + } const parsed = parseVersion(version); if (parsed === undefined) return { name: "node", status: "fail", detail: `unparsable version "${version}"` }; const ok = versionAtLeast(parsed, MIN_NODE); @@ -252,6 +275,174 @@ export function checkLinger(probe: DoctorContext["linger"]): DoctorCheck { return { name: "linger", status: probe.enabled === true ? "ok" : "warn", detail }; } +export function defaultUnitPath(platform: NodeJS.Platform, home: string, configHome?: string): string { + const paths = defaultServicePaths({ homeDir: home, ...(configHome !== undefined ? { configHome } : {}) }); + return platform === "darwin" + ? join(launchAgentDir(paths), LAUNCHD_PLIST_NAME) + : join(systemdUserDir(paths), SYSTEMD_UNIT_NAME); +} + +export function tokenizeCommandLine(cmd: string): string[] { + const tokens: string[] = []; + let current = ""; + let inQuote: '"' | "'" | null = null; + let escape = false; + + for (let index = 0; index < cmd.length; index += 1) { + const char = cmd[index]!; + if (escape) { + current += char; + escape = false; + } else if (char === "\\") { + escape = true; + } else if (inQuote !== null) { + if (char === inQuote) { + inQuote = null; + } else { + current += char; + } + } else if (char === '"' || char === "'") { + inQuote = char; + } else if (/\s/.test(char)) { + if (current.length > 0) { + tokens.push(current); + current = ""; + } + } else { + current += char; + } + } + if (current.length > 0) { + tokens.push(current); + } + return tokens; +} + +export function parsePlistProgramArguments(content: string): string[] { + const arrayMatch = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(content); + if (!arrayMatch) return []; + const strings: string[] = []; + const stringRegex = /<string>([\s\S]*?)<\/string>/g; + let match: RegExpExecArray | null; + while ((match = stringRegex.exec(arrayMatch[1] ?? "")) !== null) { + const val = match[1]; + if (val !== undefined) { + const unescaped = val + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/&/g, "&"); + strings.push(unescaped.trim()); + } + } + return strings; +} + +export function isNodeExecutable(path: string): boolean { + return /(?:^|\/)node(?:\.exe)?$/.test(path); +} + +export function checkUnit( + probe: UnitProbe | undefined, + bundled: boolean = isBundledRuntime(), + platform: NodeJS.Platform = osPlatform(), +): DoctorCheck { + if (probe === undefined || !probe.exists) { + return { + name: "unit", + status: "ok", + detail: "no service unit installed (run `pi2 install-service --write` to keep the daemon running)", + }; + } + + let content = probe.content; + if (content === undefined && probe.path) { + try { + content = readFileSync(probe.path, "utf8"); + } catch { + content = undefined; + } + } + + if (content === undefined) { + return { + name: "unit", + status: "warn", + detail: `could not read unit file ${probe.path}; re-run \`pi2 install-service --write\``, + }; + } + + const isDarwin = platform === "darwin" || probe.path.endsWith(".plist") || content.includes("<plist"); + let executable: string | undefined; + const pathsToCheck: string[] = []; + + if (isDarwin) { + const args = parsePlistProgramArguments(content); + executable = args[0]; + if (executable !== undefined) { + pathsToCheck.push(executable); + } + } else { + const lines = content.split("\n"); + let lastExecStart: string | undefined; + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed.startsWith("ExecStart=")) { + const val = trimmed.slice("ExecStart=".length).trim(); + if (val.length > 0) { + lastExecStart = val; + } + } + } + if (lastExecStart !== undefined) { + const tokens = tokenizeCommandLine(lastExecStart); + const first = tokens[0]?.replace(/^[-+!@]+(?=\/)/, ""); + if (first !== undefined && first.length > 0) { + executable = first; + for (const token of tokens) { + if (token === "daemon" || token.startsWith("-")) break; + pathsToCheck.push(token.replace(/^[-+!@]+(?=\/)/, "")); + } + } + } + } + + if (executable === undefined || pathsToCheck.length === 0) { + return { + name: "unit", + status: "warn", + detail: `could not parse executable from ${probe.path}; re-run \`pi2 install-service --write\``, + }; + } + + const checkExists = probe.pathExists ?? existsSync; + for (const targetPath of pathsToCheck) { + if (!checkExists(targetPath)) { + return { + name: "unit", + status: "warn", + detail: `${targetPath} missing; re-run \`pi2 install-service --write\``, + }; + } + } + + const isNode = isNodeExecutable(executable); + if ((bundled && isNode) || (!bundled && !isNode)) { + return { + name: "unit", + status: "warn", + detail: "unit was rendered for a different install shape; re-run pi2 install-service --write", + }; + } + + return { + name: "unit", + status: "ok", + detail: executable, + }; +} + 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)` }; @@ -273,7 +464,7 @@ export function checkProtocol(probe: DoctorContext["daemon"]): DoctorCheck { export function defaultProbes(ctx: DoctorContext): DoctorProbe[] { const isLinux = ctx.platform === "linux"; return [ - { name: "node", run: () => checkNode(ctx.nodeVersion) }, + { name: "node", run: () => checkNode(ctx.nodeVersion, ctx.bundled ?? isBundledRuntime()) }, { name: "nvim", run: () => checkNvim(ctx.nvim) }, { name: "pi", run: () => checkPi(ctx.pi) }, { name: "curl", run: () => checkCurl(ctx.curl) }, @@ -286,6 +477,7 @@ export function defaultProbes(ctx: DoctorContext): DoctorProbe[] { { name: "bind", run: () => checkBind(ctx.bind) }, { name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) }, ...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []), + { name: "unit", run: () => checkUnit(ctx.unit, ctx.bundled ?? isBundledRuntime(), ctx.platform) }, { name: "web-dist", run: () => checkWebDist(ctx.webDist) }, { name: "protocol", run: () => checkProtocol(ctx.daemon) }, ]; @@ -337,6 +529,7 @@ export interface DoctorOptions { run?: RunLike; which?: (command: string) => string | undefined; now?: () => number; + unit?: Partial<UnitProbe>; } async function defaultRun(command: string, args: readonly string[]): Promise<{ ok: boolean; stdout: string; stderr: string }> { @@ -456,9 +649,28 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto } } + const defaultPath = defaultUnitPath(platform, home, env.XDG_CONFIG_HOME?.trim() || undefined); + const unitPath = options.unit?.path ?? defaultPath; + const unitExists = options.unit?.exists ?? existsSync(unitPath); + let unitContent = options.unit?.content; + if (unitContent === undefined && unitExists) { + try { + unitContent = readFileSync(unitPath, "utf8"); + } catch { + unitContent = undefined; + } + } + const unit: UnitProbe = { + path: unitPath, + exists: unitExists, + ...(unitContent !== undefined ? { content: unitContent } : {}), + ...(options.unit?.pathExists !== undefined ? { pathExists: options.unit.pathExists } : {}), + }; + return { platform, nodeVersion: process.version, + bundled: isBundledRuntime(), nvim, pi, curl, @@ -471,6 +683,7 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto bind: bindContext(env, daemon.port ?? configuredPort), serviceManager, linger, + unit, webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) }, }; } diff --git a/src/cli/pi2.ts b/src/cli/pi2.ts index 312278f..9d09176 100644 --- a/src/cli/pi2.ts +++ b/src/cli/pi2.ts @@ -5,6 +5,7 @@ * pi2 daemon [start] run the web-console daemon (foreground) * pi2 attach [path] attach nvim to the workspace instance (or open nvim) * pi2 status [--json] daemon, instances, resources, health + * pi2 config [--json] resolved configuration and sources * 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 @@ -46,9 +47,11 @@ import { } from "./service.js"; import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js"; import { runStop, STOP_USAGE, type StopOptions } from "./stop.js"; +import { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js"; export { CliError } from "./util.js"; export { runStop, STOP_USAGE, type StopOptions } from "./stop.js"; +export { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js"; export const USAGE = `pi2 — pi2 client @@ -59,6 +62,7 @@ Usage: pi2 attach [path] attach nvim to the workspace instance, else open nvim pi2 status [--json] daemon info, instances, resources, health pi2 open [--print] [--no-browser] open the web console signed in (local only) + pi2 config [--json] resolved configuration and sources pi2 doctor [--json] environment checks pi2 pairing [--base <url>] create a pairing code (URL + code + QR) pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent @@ -688,6 +692,7 @@ export interface Pi2Options { writeFile?: (path: string, content: string) => void; removeFile?: (path: string) => void; runtime?: string; + env?: Record<string, string | undefined>; /** Injected `pi2 daemon` runner (defaults to `src/cli/daemon.ts:main`). */ daemonMain?: (argv: readonly string[], io: { out: (line: string) => void; err: (line: string) => void }) => Promise<number>; stopRunner?: (options: StopOptions) => Promise<number>; @@ -769,6 +774,30 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P noBrowser: boolFlag(parsed.flags, "--no-browser"), }); } + case "config": { + let parsed; + try { + parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } }); + } catch (error) { + if (error instanceof UsageError) { + throw new UsageError(error.message, CONFIG_USAGE); + } + throw error; + } + if (boolFlag(parsed.flags, "--help")) { + out(CONFIG_USAGE); + return 0; + } + if (parsed.positionals.length > 0) { + throw new UsageError(`unexpected argument "${parsed.positionals[0]}"`, CONFIG_USAGE); + } + return runConfig({ + env: options.env ?? process.env, + ...(options.platform === undefined ? {} : { platform: options.platform }), + json: boolFlag(parsed.flags, "--json"), + print: out, + }); + } case "doctor": { const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } }); if (boolFlag(parsed.flags, "--help")) { diff --git a/src/cli/service.ts b/src/cli/service.ts index 9085adf..af35820 100644 --- a/src/cli/service.ts +++ b/src/cli/service.ts @@ -4,19 +4,41 @@ * 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. + * + * Supports two install shapes: + * 1. Bundled binary (`bun build --compile`): invokes the compiled executable directly + * (`ExecStart=<execPath> daemon --foreground` or `ProgramArguments = [execPath, "daemon", "--foreground"]`). + * 2. Node / script: invokes node with the CLI entrypoint script + * (`ExecStart=<nodePath> <scriptPath> daemon --foreground`). + * + * On systemd (Linux), the service unit supports an optional environment file + * (`ServicePaths.envFile`, defaulting to `-%h/.config/pi2/env`, where the leading `-` + * instructs systemd to ignore missing files). Setting `envFile: ""` omits the + * `EnvironmentFile=` directive. launchd (macOS) ignores this setting as macOS + * has no direct launchd equivalent for systemd environment files. */ import { fileURLToPath } from "node:url"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { stateDir } from "../core/paths.js"; +import { executablePath, isBundledRuntime } from "../core/install.js"; export type ServicePlatform = "linux" | "darwin"; export interface ServicePaths { + /** True when running as a compiled binary (`bun build --compile`). */ + bundled?: boolean; + /** Absolute path of the running executable (`process.execPath`). */ + execPath?: string; /** Absolute node binary (`process.execPath`). */ - nodePath: string; + nodePath?: string; /** Absolute path to `dist/cli/pi2.js`. */ - scriptPath: string; + scriptPath?: string; + /** + * Optional systemd environment file (defaults to `-%h/.config/pi2/env`). + * Set to `""` to omit `EnvironmentFile=` entirely. Ignored by launchd. + */ + envFile?: string; /** Where logs go (plist StandardOut/ErrPath). */ stateDir: string; /** Home dir; the unit file lives under it. */ @@ -44,6 +66,7 @@ export interface RenderedService { export const SYSTEMD_UNIT_NAME = "pi2.service"; export const LAUNCHD_LABEL = "com.pi2.daemon"; export const LAUNCHD_PLIST_NAME = `${LAUNCHD_LABEL}.plist`; +export const DEFAULT_SYSTEMD_ENV_FILE = "-%h/.config/pi2/env"; /** `<repo>/dist/cli/pi2.js`, resolved from either `src/cli/` or `dist/cli/`. */ export function defaultScriptPath(): string { @@ -52,8 +75,11 @@ export function defaultScriptPath(): string { export function defaultServicePaths(overrides: Partial<ServicePaths> = {}): ServicePaths { return { + bundled: isBundledRuntime(), + execPath: executablePath(), nodePath: process.execPath, scriptPath: defaultScriptPath(), + envFile: DEFAULT_SYSTEMD_ENV_FILE, stateDir: stateDir(), homeDir: homedir(), ...(process.env.XDG_CONFIG_HOME === undefined ? {} : { configHome: process.env.XDG_CONFIG_HOME }), @@ -93,6 +119,15 @@ function environmentEntries(paths: ServicePaths): [string, string][] { } export function renderSystemdUnit(paths: ServicePaths): string { + const execStart = paths.bundled + ? `ExecStart=${systemdQuote(paths.execPath ?? executablePath())} daemon --foreground` + : `ExecStart=${systemdQuote(paths.nodePath ?? paths.execPath ?? executablePath())} ${systemdQuote(paths.scriptPath ?? defaultScriptPath())} daemon --foreground`; + + const envFileLine = + paths.envFile !== undefined && paths.envFile !== "" + ? [`EnvironmentFile=${paths.envFile}`] + : []; + const env = environmentEntries(paths).map(([key, value]) => `Environment=${key}=${systemdQuote(value)}`); return [ "[Unit]", @@ -101,7 +136,8 @@ export function renderSystemdUnit(paths: ServicePaths): string { "", "[Service]", "Type=simple", - `ExecStart=${systemdQuote(paths.nodePath)} ${systemdQuote(paths.scriptPath)} daemon --foreground`, + execStart, + ...envFileLine, ...env, "Restart=on-failure", "RestartSec=2", @@ -115,6 +151,21 @@ export function renderSystemdUnit(paths: ServicePaths): string { } export function renderLaunchAgent(paths: ServicePaths): string { + const programArgs = paths.bundled + ? [ + ` <string>${xmlEscape(paths.execPath ?? executablePath())}</string>`, + " <string>daemon</string>", + " <string>--foreground</string>", + ] + : [ + ` <string>${xmlEscape(paths.nodePath ?? paths.execPath ?? executablePath())}</string>`, + ` <string>${xmlEscape(paths.scriptPath ?? defaultScriptPath())}</string>`, + " <string>daemon</string>", + " <string>--foreground</string>", + ]; + + // launchd has no direct equivalent for systemd's EnvironmentFile=; + // ServicePaths.envFile is ignored on darwin. const env = environmentEntries(paths); const envBlock = env.length === 0 @@ -137,10 +188,7 @@ export function renderLaunchAgent(paths: ServicePaths): string { ` <string>${LAUNCHD_LABEL}</string>`, " <key>ProgramArguments</key>", " <array>", - ` <string>${xmlEscape(paths.nodePath)}</string>`, - ` <string>${xmlEscape(paths.scriptPath)}</string>`, - " <string>daemon</string>", - " <string>--foreground</string>", + ...programArgs, " </array>", ...envBlock, " <key>RunAtLoad</key>", diff --git a/src/cli/util.ts b/src/cli/util.ts index bd798e6..53bc50b 100644 --- a/src/cli/util.ts +++ b/src/cli/util.ts @@ -1,6 +1,6 @@ /** Small shared helpers for the `pi2` command line front end (and `pi2 daemon`). */ -import { readFileSync, realpathSync } from "node:fs"; -import { fileURLToPath } from "node:url"; +import { realpathSync } from "node:fs"; +import { version } from "../core/install.js"; /** Bad arguments; the CLI prints the usage block and exits 2. */ export class UsageError extends Error { @@ -100,13 +100,7 @@ export function boolFlag(flags: Record<string, FlagValue>, name: string): boolea /** 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"; - } + return version(); } export function realpathOrSelf(path: string): string { diff --git a/src/config.ts b/src/config.ts index dfba42d..1143539 100644 --- a/src/config.ts +++ b/src/config.ts @@ -14,7 +14,7 @@ * is actually reachable on, so it always matches the pairing link. */ import type { NetworkInterfaceInfo } from "node:os"; -import { fileURLToPath } from "node:url"; +import { defaultStaticDir } from "./core/install.js"; import { isLoopbackHost, isWildcardHost, localOrigins } from "./core/network.js"; import { daemonTokenPath, dataDir } from "./core/paths.js"; @@ -36,7 +36,7 @@ export interface Config { host: string; /** TCP port; `0` asks the OS for an ephemeral port (tests). */ port: number; - /** Built web UI (`<repo>/web/dist` by default). */ + /** built web UI — PI2_STATIC_DIR wins, else the install layout (<prefix>/share/pi2d/web/dist for the compiled binary, web/dist for an npm/dev checkout). */ staticDir: string; corsOrigins: string[]; limits: Limits; @@ -53,11 +53,7 @@ export interface ConfigOptions { interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>; } -function defaultStaticDir(): string { - return fileURLToPath(new URL("../web/dist", import.meta.url)); -} - -function parsePort(raw: string | undefined): number { +export function parsePort(raw: string | undefined): number { if (raw === undefined || raw.trim() === "") return DEFAULT_PORT; if (!/^\d+$/.test(raw.trim())) throw new Error(`PI2_PORT must be an integer, got "${raw}"`); const port = Number(raw); @@ -73,7 +69,7 @@ function normalizeOrigin(raw: string): string | null { return value === "" ? null : value; } -function normalizePublicUrl(raw: string | undefined): string | null { +export function normalizePublicUrl(raw: string | undefined): string | null { if (raw === undefined) return null; return normalizeOrigin(raw); } diff --git a/src/core/install.ts b/src/core/install.ts new file mode 100644 index 0000000..9c2a884 --- /dev/null +++ b/src/core/install.ts @@ -0,0 +1,128 @@ +/** + * Where this process runs from, and what it is allowed to assume about that. + * + * `pi2` ships in two shapes (ADR 0002): + * + * 1. an npm package executed by Node (`node …/dist/cli/pi2.js`), where every + * asset sits next to the source tree, and + * 2. a compiled single binary (`bun build --compile`) installed as + * `<prefix>/bin/pi2` with its assets at `<prefix>/share/pi2d/web/dist`. + * + * The compiled shape has no source tree and no `package.json` on disk, so the + * version is injected at build time (`bun build --define`). Everything that + * needs to answer "what am I, where are my files" lives here, so that no other + * module has to guess from `import.meta.url` alone. + */ +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +/** + * Replaced textually by `scripts/build-binary.sh` (`bun build --define`). + * `typeof` on an undeclared identifier is safe, so an unbundled Node run falls + * through to the on-disk `package.json`. + */ +declare const PI2_BUILD_VERSION: string | undefined; + +/** Fallback when neither the build-time define nor `package.json` is readable. */ +export const UNKNOWN_VERSION = "0.0.0"; + +/** Bun's node-compat version string, when running as a compiled binary. */ +function bunVersion(): string | undefined { + const versions = process.versions as { bun?: string } | undefined; + return typeof versions?.bun === "string" ? versions.bun : undefined; +} + +/** + * True when this process is a `bun build --compile` artifact. + * + * The check is deliberately runtime-based rather than build-based: the same + * source runs under both shapes, and only the packaging differs. + */ +export function isBundledRuntime(): boolean { + return bunVersion() !== undefined; +} + +/** `bundled bun 1.3.14` or `node 22.11.0` — for `pi2 doctor` and logs. */ +export function runtimeDescription(): string { + const bun = bunVersion(); + if (bun !== undefined) return `bundled bun ${bun}`; + return `node ${process.version.replace(/^v/, "")}`; +} + +/** Runtime version string only (`22.11.0`, or Bun's compat version). */ +export function runtimeVersion(): string { + return process.version.replace(/^v/, ""); +} + +/** Absolute path of the running executable (`node`, or the compiled `pi2`). */ +export function executablePath(): string { + return process.execPath; +} + +/** `<repo>/package.json` next to `dist/cli/`. Absent inside a compiled binary. */ +function packageJsonVersion(): string | undefined { + 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 !== "" ? parsed.version : undefined; + } catch { + return undefined; + } +} + +/** + * Version of the running `pi2`. + * + * Order: build-time define (compiled binary) → on-disk `package.json` (npm + * install, dev checkout) → `UNKNOWN_VERSION`. Never throws: a version probe + * must not be able to take the daemon down. + */ +export function version(): string { + if (typeof PI2_BUILD_VERSION === "string" && PI2_BUILD_VERSION !== "") return PI2_BUILD_VERSION; + return packageJsonVersion() ?? UNKNOWN_VERSION; +} + +/** + * Static UI locations, most specific first. + * + * 1. `<exe>/../share/pi2d/web/dist` — the release layout: `<prefix>/bin/pi2` + * plus `<prefix>/share/pi2d/web/dist`, which is what the curl installer, + * the Homebrew formula and the AUR `-bin` package all install. + * 2. `<exe>/web/dist` — a portable unpacked directory (`pi2` next to its UI). + * 3. `<repo>/web/dist` — an npm install or a dev checkout, resolved from this + * module's own location. + */ +export function staticDirCandidates(): string[] { + const exeDir = dirname(executablePath()); + return [ + resolve(exeDir, "..", "share", "pi2d", "web", "dist"), + resolve(exeDir, "web", "dist"), + resolve(fileURLToPath(new URL("../../web/dist", import.meta.url))), + ]; +} + +function hasIndex(dir: string): boolean { + return existsSync(join(dir, "index.html")); +} + +/** + * The built web UI for the current install shape, or the dev-checkout path when + * none of the candidates exists (so diagnostics name a path the user can + * create, instead of an arbitrary miss). + */ +export function defaultStaticDir(): string { + for (const candidate of staticDirCandidates()) { + if (hasIndex(candidate)) return candidate; + } + const devPath = staticDirCandidates().at(-1); + return devPath ?? resolve("web", "dist"); +} + +/** + * True when the static dir that `defaultStaticDir()` would pick actually holds + * a built UI. `PI2_STATIC_DIR` overrides this entirely at the config layer. + */ +export function hasBundledStaticDir(dir: string): boolean { + return hasIndex(dir); +} diff --git a/src/core/interfaces.ts b/src/core/interfaces.ts index 31f9e0c..906b5d0 100644 --- a/src/core/interfaces.ts +++ b/src/core/interfaces.ts @@ -11,7 +11,7 @@ * Do not change these shapes without updating `docs/protocol.md`. */ -import type { InstanceState, SessionState, WorkspaceInfo } from "../protocol/types.js"; +import type { InstanceState, RecentSessionInfo, SessionState, WorkspaceInfo } from "../protocol/types.js"; /** One connected plugin (an nvim process running pi2.nvim). */ export interface PluginConnection { @@ -86,6 +86,12 @@ export interface WorkspaceStore { refresh(workspaceId?: string): Promise<void>; /** Ensure a workspace exists for a cwd (used when an instance connects). */ ensureForCwd(cwd: string): Promise<WorkspaceInfo>; + /** + * Newest session files across every known workspace, newest first. Disk + * projection only: ids/timestamps from the JSONL header plus file mtime, no + * entry parsing, no instance spawn (see docs/protocol.md §3.1). + */ + recentSessions(limit?: number): RecentSessionInfo[]; } /** Minimal event bus used by the daemon to fan plugin records out to browsers. */ diff --git a/src/core/paths.ts b/src/core/paths.ts index 5a935ce..cf5d161 100644 --- a/src/core/paths.ts +++ b/src/core/paths.ts @@ -47,13 +47,28 @@ export function instanceSocketPath(workspaceId: string, instanceId: string): str return join(instanceDir(), `${hash}.sock`); } -/** `~/.pi/agent` or `$PI_CODING_AGENT_DIR`; where pi keeps `sessions/--<cwd>--/`. */ -export function piAgentDir(): string { - return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"); +export type PathEnv = NodeJS.ProcessEnv | Record<string, string | undefined>; + +/** + * Pi session storage directory; where pi keeps `sessions/--<cwd>--/`. + * + * Resolution order: + * 1. `PI2_CODING_AGENT_DIR` — pi2's documented override + * 2. `PI_CODING_AGENT_DIR` — pi's own variable (injected by pi when it runs a child) + * 3. `~/.pi/agent` — default location + * + * Empty strings are ignored (fall through to the next candidate). + */ +export function piAgentDir(env: PathEnv = process.env): string { + const pi2 = env.PI2_CODING_AGENT_DIR; + if (pi2 !== undefined && pi2 !== "") return pi2; + const pi = env.PI_CODING_AGENT_DIR; + if (pi !== undefined && pi !== "") return pi; + return join(homedir(), ".pi", "agent"); } -export function sessionsRoot(): string { - return join(piAgentDir(), "sessions"); +export function sessionsRoot(env: PathEnv = process.env): string { + return join(piAgentDir(env), "sessions"); } export function readToken(): string | undefined { diff --git a/src/daemon/http.ts b/src/daemon/http.ts index 0789d7e..5378d7c 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -2,7 +2,6 @@ import { existsSync, readFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; import { hostname as osHostname, platform as osPlatform, release as osRelease } from "node:os"; -import { fileURLToPath } from "node:url"; import { Hono, type Context } from "hono"; import type { HttpBindings } from "@hono/node-server"; import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/interfaces.js"; @@ -11,6 +10,7 @@ import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js"; import type { Config } from "../config.js"; import type { SysinfoSampler } from "../core/sysinfo.js"; import { networkBases } from "../core/network.js"; +import { version } from "../core/install.js"; import { encodeQr, fitsQr } from "../core/qr.js"; import type { AuthStore, DevicePublic } from "./auth.js"; import { isAllowedOrigin, LOCAL_CLI_DEVICE_ID } from "./auth.js"; @@ -69,15 +69,15 @@ function normalizeBase(raw: string): string { return raw.trim().replace(/\/+$/, ""); } -/** Daemon package version; falls back to the v1 baseline when package.json is unavailable. */ +/** + * Daemon version, from the shared install probe. + * + * A compiled binary has no `package.json` on disk, so the version comes from the + * build-time define (`core/install`); reading the file here would silently report + * a stale baseline instead of the version that was built. + */ function daemonVersion(): string { - try { - const file = fileURLToPath(new URL("../../package.json", import.meta.url)); - const parsed = JSON.parse(readFileSync(file, "utf8")) as { version?: unknown }; - return typeof parsed.version === "string" && parsed.version.trim() !== "" ? parsed.version : "0.1.0"; - } catch { - return "0.1.0"; - } + return version(); } function json(status: number, body: unknown, headers: Record<string, string> = {}): Response { @@ -291,6 +291,16 @@ export function createApp(deps: AppDeps): Hono<Env> { return json(200, ack); }); + // Cross-workspace recent-activity feed. Disk projection only: header ids and + // mtimes, no entry parsing and no `instances.ensure()` (that would spawn an + // nvim for every idle workspace). The client layers live names/status over + // these rows through `/workspaces/:id/sessions` when an instance is connected. + app.get("/api/v1/sessions/recent", (c) => { + const raw = Number(c.req.query("limit")); + const limit = Number.isFinite(raw) && raw > 0 ? Math.min(200, Math.floor(raw)) : 20; + return c.json({ sessions: workspaces.recentSessions(limit) }); + }); + app.get("/api/v1/sessions/:sid/entries", async (c) => { const params: Record<string, unknown> = {}; const before = c.req.query("before"); diff --git a/src/protocol/types.ts b/src/protocol/types.ts index 31198e0..d0e0a8a 100644 --- a/src/protocol/types.ts +++ b/src/protocol/types.ts @@ -318,6 +318,26 @@ export type WorkspaceVisibility = "default" | "secondary"; export type WorkspaceVisibilityReason = "hidden" | "ghost" | "temp" | "outside-roots" | "stale"; +/** + * One disk-projected session row for the cross-workspace recent-activity feed. + * + * This is file metadata only (header id/timestamp + mtime); the daemon never + * parses entries or owns session state (docs/protocol.md §3.1). Live names and + * statuses are layered on by the client through `/workspaces/:id/sessions`. + */ +export interface RecentSessionInfo { + sessionId: string; + workspaceId: string; + /** Workspace display name (alias → basename), for the row's meta line. */ + workspaceName: string; + cwd: string; + sessionFile: string; + /** Session start, from the JSONL header (or the file name), epoch ms. */ + timestamp: number; + /** File mtime, epoch ms — the recency sort key. */ + modified: number; +} + export type DaemonCommandMethod = | "instance.ensure" | "instance.shutdown" diff --git a/src/workspaces/discovery.ts b/src/workspaces/discovery.ts index 9a53334..3783130 100644 --- a/src/workspaces/discovery.ts +++ b/src/workspaces/discovery.ts @@ -64,7 +64,7 @@ export interface Discovery { /** Scan every `--*--` directory under the sessions root. */ discover(): DiscoveredWorkspace[]; /** Session files for a cwd, newest first (header-only, cheap). */ - listSessions(cwd: string): SessionFile[]; + listSessions(cwd: string, limit?: number): SessionFile[]; /** Drop one directory's cache entry, or the whole cache when omitted. */ invalidate(dir?: string): void; /** The encoded directory used for a cwd, when it has been discovered. */ @@ -129,7 +129,7 @@ class DiskDiscovery implements Discovery { return out; } - listSessions(cwd: string): SessionFile[] { + listSessions(cwd: string, limit?: number): SessionFile[] { if (typeof cwd !== "string" || cwd.length === 0 || !isAbsolute(cwd)) return []; const workspaceId = workspaceIdForCwd(cwd); const dirs = this.discover() @@ -137,15 +137,21 @@ class DiskDiscovery implements Discovery { .map((entry) => entry.dir); if (dirs.length === 0) return []; - const sessions: SessionFile[] = []; + // Sort the raw file descriptors first so a `limit` reads only the headers + // of the newest files instead of every session in the workspace. + const infos: SessionFileInfo[] = []; const seen = new Set<string>(); for (const dir of dirs) { for (const info of this.sessionFiles(dir)) { if (seen.has(info.file)) continue; seen.add(info.file); - sessions.push(this.describeSession(info)); + infos.push(info); } } + infos.sort((a, b) => b.mtimeMs - a.mtimeMs || b.size - a.size); + const selected = limit !== undefined && limit > 0 ? infos.slice(0, limit) : infos; + + const sessions = selected.map((info) => this.describeSession(info)); sessions.sort((a, b) => b.modified - a.modified || b.timestamp - a.timestamp || a.id.localeCompare(b.id)); return sessions; } @@ -336,8 +342,8 @@ export function discoverWorkspaces(options: DiscoveryOptions = {}): DiscoveredWo return sharedDiscovery(options.root, options.logger).discover(); } -export function listSessions(cwd: string, options: DiscoveryOptions = {}): SessionFile[] { - return sharedDiscovery(options.root, options.logger).listSessions(cwd); +export function listSessions(cwd: string, options: DiscoveryOptions = {}, limit?: number): SessionFile[] { + return sharedDiscovery(options.root, options.logger).listSessions(cwd, limit); } /** Drop cached discovery results for every root (or one directory). */ diff --git a/src/workspaces/index.ts b/src/workspaces/index.ts index 1acb8d7..a70e3f2 100644 --- a/src/workspaces/index.ts +++ b/src/workspaces/index.ts @@ -18,6 +18,7 @@ import { dataDir, realpathSafe, workspaceIdForCwd } from "../core/paths.js"; import { ERROR_CODES } from "../protocol/errors.js"; import type { InstanceState, + RecentSessionInfo, WorkspaceInfo, WorkspaceVisibility, WorkspaceVisibilityReason, @@ -241,6 +242,43 @@ class WorkspaceStore implements WorkspaceStoreHandle { return this.requireInfo(record.workspaceId); } + /** + * Newest session files across every known workspace (registry ∪ discovery). + * + * Each workspace asks discovery for at most `limit` rows, so the header scan + * stays bounded even on a workspace with a long history. Rows are deduped by + * session id (two encoded directories can resolve to the same cwd) and sorted + * by file mtime, then header timestamp, then id for a deterministic order. + */ + recentSessions(limit = 20): RecentSessionInfo[] { + const capped = clampLimit(limit); + const rows: RecentSessionInfo[] = []; + const seen = new Set<string>(); + for (const workspace of this.list()) { + if (!workspace.cwd) continue; + for (const file of this.discovery.listSessions(workspace.cwd, capped)) { + if (file.id === "" || seen.has(file.id)) continue; + seen.add(file.id); + rows.push({ + sessionId: file.id, + workspaceId: workspace.workspaceId, + workspaceName: workspace.name, + cwd: workspace.cwd, + sessionFile: file.file, + timestamp: file.timestamp, + modified: file.modified, + }); + } + } + rows.sort( + (a, b) => + b.modified - a.modified || + b.timestamp - a.timestamp || + a.sessionId.localeCompare(b.sessionId), + ); + return rows.slice(0, capped); + } + // ------------------------------------------------------------------ private requireInfo(workspaceId: string): WorkspaceInfo { @@ -567,6 +605,12 @@ function liveCountOf(state: InstanceState): number { return 0; } +/** Keeps a user-supplied recent-session limit in a cheap, predictable range. */ +function clampLimit(limit: number): number { + if (!Number.isFinite(limit) || limit <= 0) return 20; + return Math.min(200, Math.max(1, Math.floor(limit))); +} + function mapFsError(error: unknown, path: string): WorkspaceError { const code = (error as NodeJS.ErrnoException | undefined)?.code; const detail = error instanceof Error ? error.message : String(error); diff --git a/test/cli/config.test.ts b/test/cli/config.test.ts new file mode 100644 index 0000000..6f6a73e --- /dev/null +++ b/test/cli/config.test.ts @@ -0,0 +1,354 @@ +import { describe, expect, it } from "vitest"; +import { join } from "node:path"; +import { main } from "../../src/cli/pi2.js"; +import { + CONFIG_KEYS, + CONFIG_USAGE, + configToJson, + formatConfigTable, + resolveConfig, + type ConfigJsonOutput, +} from "../../src/cli/config.js"; + +describe("pi2 config", () => { + describe("resolveConfig", () => { + it("returns defaults and layout sources when env is empty", () => { + const resolution = resolveConfig({ + env: {}, + platform: "linux", + home: "/home/user", + uid: 1000, + version: "1.2.3", + runtime: "node 22.0.0", + installShape: "node", + staticDir: "/repo/web/dist", + }); + + expect(resolution.config).toEqual({ + port: 7676, + host: "0.0.0.0", + publicUrl: null, + staticDir: "/repo/web/dist", + runtimeDir: "/tmp/pi2-1000/pi2", + dataDir: "/home/user/.local/share/pi2", + stateDir: "/home/user/.local/state/pi2", + codingAgentDir: "/home/user/.pi/agent", + workspaceRoots: ["/home/user"], + logLevel: "info", + version: "1.2.3", + platform: "linux", + runtime: "node 22.0.0", + installShape: "node", + }); + + expect(resolution.sources).toEqual({ + port: "default", + host: "default", + publicUrl: "default", + staticDir: "install layout", + runtimeDir: "default", + dataDir: "default", + stateDir: "default", + codingAgentDir: "default", + workspaceRoots: "default", + logLevel: "default", + version: "install layout", + platform: "system", + runtime: "runtime", + installShape: "install layout", + }); + }); + + it("resolves darwin paths when platform is darwin", () => { + const resolution = resolveConfig({ + env: {}, + platform: "darwin", + home: "/Users/testuser", + uid: 501, + }); + + expect(resolution.config.platform).toBe("darwin"); + expect(resolution.config.runtimeDir).toBe("/Users/testuser/Library/Caches/pi2/run"); + expect(resolution.config.dataDir).toBe("/Users/testuser/Library/Application Support/pi2"); + expect(resolution.config.stateDir).toBe("/Users/testuser/Library/Logs/pi2"); + expect(resolution.sources.runtimeDir).toBe("default"); + expect(resolution.sources.dataDir).toBe("default"); + expect(resolution.sources.stateDir).toBe("default"); + }); + + it("attributes values to environment variables when set", () => { + const resolution = resolveConfig({ + env: { + PI2_PORT: "0", + PI2_HOST: "127.0.0.1", + PI2_PUBLIC_URL: "https://pi2.local/", + PI2_STATIC_DIR: "/opt/pi2/ui", + PI2_RUNTIME_DIR: "/custom/run", + PI2_DATA_DIR: "/custom/data", + PI2_STATE_DIR: "/custom/state", + PI2_WORKSPACE_ROOTS: "/projects,/extra/work", + PI2_LOG_LEVEL: "DEBUG", + }, + platform: "linux", + home: "/home/user", + uid: 1000, + }); + + expect(resolution.config.port).toBe(0); + expect(resolution.sources.port).toBe("PI2_PORT"); + + expect(resolution.config.host).toBe("127.0.0.1"); + expect(resolution.sources.host).toBe("PI2_HOST"); + + expect(resolution.config.publicUrl).toBe("https://pi2.local"); + expect(resolution.sources.publicUrl).toBe("PI2_PUBLIC_URL"); + + expect(resolution.config.staticDir).toBe("/opt/pi2/ui"); + expect(resolution.sources.staticDir).toBe("PI2_STATIC_DIR"); + + expect(resolution.config.runtimeDir).toBe("/custom/run"); + expect(resolution.sources.runtimeDir).toBe("PI2_RUNTIME_DIR"); + + expect(resolution.config.dataDir).toBe("/custom/data"); + expect(resolution.sources.dataDir).toBe("PI2_DATA_DIR"); + + expect(resolution.config.stateDir).toBe("/custom/state"); + expect(resolution.sources.stateDir).toBe("PI2_STATE_DIR"); + + expect(resolution.config.workspaceRoots).toEqual(["/projects", "/extra/work"]); + expect(resolution.sources.workspaceRoots).toBe("PI2_WORKSPACE_ROOTS"); + + expect(resolution.config.logLevel).toBe("debug"); + expect(resolution.sources.logLevel).toBe("PI2_LOG_LEVEL"); + }); + + it("does not throw when directories do not exist", () => { + expect(() => { + resolveConfig({ + env: { + PI2_RUNTIME_DIR: "/nonexistent/path/for/runtime", + PI2_DATA_DIR: "/nonexistent/path/for/data", + PI2_STATE_DIR: "/nonexistent/path/for/state", + PI2_WORKSPACE_ROOTS: "/nonexistent/workspace/dir", + }, + home: "/nonexistent/home", + }); + }).not.toThrow(); + }); + + it("throws when PI2_PORT is not a valid integer", () => { + expect(() => { + resolveConfig({ env: { PI2_PORT: "not-a-number" } }); + }).toThrow('PI2_PORT must be an integer, got "not-a-number"'); + }); + + it("throws when PI2_PORT is out of range", () => { + expect(() => { + resolveConfig({ env: { PI2_PORT: "70000" } }); + }).toThrow('PI2_PORT must be between 0 and 65535, got "70000"'); + }); + }); + + describe("formatConfigTable", () => { + it("formats a three-column table with key, value, and source", () => { + const resolution = resolveConfig({ + env: { + PI2_PORT: "0", + PI2_HOST: "127.0.0.1", + }, + platform: "linux", + home: "/home/user", + uid: 1000, + version: "1.0.0", + runtime: "node 22.0.0", + installShape: "node", + staticDir: "/repo/web/dist", + }); + + const table = formatConfigTable(resolution); + const lines = table.split("\n"); + + // Header line has key, value, source + expect(lines[0]).toMatch(/^key\s+value\s+source$/); + // Separator line has dashes + expect(lines[1]).toMatch(/^--+\s+--+\s+--+$/); + + // Check that all keys are present in order + for (const key of CONFIG_KEYS) { + expect(table).toContain(key); + } + + // Port 0 and host 127.0.0.1 show up with source PI2_PORT / PI2_HOST + expect(table).toMatch(/port\s+0\s+PI2_PORT/); + expect(table).toMatch(/host\s+127\.0\.0\.1\s+PI2_HOST/); + // Unset publicUrl shows up as - with source default + expect(table).toMatch(/publicUrl\s+-\s+default/); + // staticDir shows source install layout + expect(table).toMatch(/staticDir\s+\/repo\/web\/dist\s+install layout/); + }); + }); + + describe("configToJson", () => { + it("returns a JSON string with resolved keys and sources map", () => { + const resolution = resolveConfig({ + env: { + PI2_PORT: "0", + PI2_HOST: "127.0.0.1", + }, + platform: "linux", + home: "/home/user", + uid: 1000, + version: "1.0.0", + runtime: "node 22.0.0", + installShape: "node", + staticDir: "/repo/web/dist", + }); + + const jsonStr = configToJson(resolution); + const parsed = JSON.parse(jsonStr) as ConfigJsonOutput; + + expect(parsed.port).toBe(0); + expect(parsed.host).toBe("127.0.0.1"); + expect(parsed.publicUrl).toBeNull(); + expect(parsed.staticDir).toBe("/repo/web/dist"); + expect(parsed.logLevel).toBe("info"); + expect(parsed.version).toBe("1.0.0"); + expect(parsed.platform).toBe("linux"); + expect(parsed.runtime).toBe("node 22.0.0"); + expect(parsed.installShape).toBe("node"); + + expect(parsed.sources).toEqual({ + port: "PI2_PORT", + host: "PI2_HOST", + publicUrl: "default", + staticDir: "install layout", + runtimeDir: "default", + dataDir: "default", + stateDir: "default", + codingAgentDir: "default", + workspaceRoots: "default", + logLevel: "default", + version: "install layout", + platform: "system", + runtime: "runtime", + installShape: "install layout", + }); + }); + }); + + describe("CLI integration (main)", () => { + it("prints formatted table with injectable env", async () => { + const out: string[] = []; + const err: string[] = []; + const code = await main(["config"], { + env: { + PI2_PORT: "0", + PI2_HOST: "127.0.0.1", + PI2_RUNTIME_DIR: "/tmp/c1", + PI2_DATA_DIR: "/tmp/c2", + PI2_STATE_DIR: "/tmp/c3", + }, + out: (line) => out.push(line), + err: (line) => err.push(line), + }); + + expect(code).toBe(0); + expect(err).toHaveLength(0); + const text = out.join("\n"); + expect(text).toMatch(/^key\s+value\s+source/); + expect(text).toMatch(/port\s+0\s+PI2_PORT/); + expect(text).toMatch(/host\s+127\.0\.0\.1\s+PI2_HOST/); + expect(text).toMatch(/runtimeDir\s+\/tmp\/c1\s+PI2_RUNTIME_DIR/); + expect(text).toMatch(/dataDir\s+\/tmp\/c2\s+PI2_DATA_DIR/); + expect(text).toMatch(/stateDir\s+\/tmp\/c3\s+PI2_STATE_DIR/); + }); + + it("prints JSON when --json is provided and matches table values", async () => { + const out: string[] = []; + const err: string[] = []; + const code = await main(["config", "--json"], { + env: { + PI2_PORT: "0", + PI2_HOST: "127.0.0.1", + }, + out: (line) => out.push(line), + err: (line) => err.push(line), + }); + + expect(code).toBe(0); + expect(err).toHaveLength(0); + const parsed = JSON.parse(out.join("\n")) as ConfigJsonOutput; + expect(parsed.port).toBe(0); + expect(parsed.host).toBe("127.0.0.1"); + expect(parsed.sources.port).toBe("PI2_PORT"); + expect(parsed.sources.host).toBe("PI2_HOST"); + expect(parsed.sources.runtimeDir).toBe("default"); + }); + + it("prints usage on --help and exits 0", async () => { + const out: string[] = []; + const err: string[] = []; + const code = await main(["config", "--help"], { + out: (line) => out.push(line), + err: (line) => err.push(line), + }); + + expect(code).toBe(0); + expect(err).toHaveLength(0); + expect(out.join("\n")).toBe(CONFIG_USAGE); + }); + + it("prints usage on -h and exits 0", async () => { + const out: string[] = []; + const err: string[] = []; + const code = await main(["config", "-h"], { + out: (line) => out.push(line), + err: (line) => err.push(line), + }); + + expect(code).toBe(0); + expect(err).toHaveLength(0); + expect(out.join("\n")).toBe(CONFIG_USAGE); + }); + + it("exits 2 on unknown flags with usage error", async () => { + const out: string[] = []; + const err: string[] = []; + const code = await main(["config", "--unknown"], { + out: (line) => out.push(line), + err: (line) => err.push(line), + }); + + expect(code).toBe(2); + expect(out).toHaveLength(0); + expect(err.some((line) => line.includes("unknown option --unknown"))).toBe(true); + expect(err.some((line) => line.includes("pi2 config"))).toBe(true); + }); + + it("exits 2 on unexpected positional arguments", async () => { + const out: string[] = []; + const err: string[] = []; + const code = await main(["config", "extra-arg"], { + out: (line) => out.push(line), + err: (line) => err.push(line), + }); + + expect(code).toBe(2); + expect(out).toHaveLength(0); + expect(err.some((line) => line.includes('unexpected argument "extra-arg"'))).toBe(true); + }); + + it("exits 1 on invalid PI2_PORT error", async () => { + const out: string[] = []; + const err: string[] = []; + const code = await main(["config"], { + env: { PI2_PORT: "bad-port" }, + out: (line) => out.push(line), + err: (line) => err.push(line), + }); + + expect(code).toBe(1); + expect(err.some((line) => line.includes("PI2_PORT must be an integer"))).toBe(true); + }); + }); +}); diff --git a/test/cli/daemon.test.ts b/test/cli/daemon.test.ts index b10da8e..45a5c67 100644 --- a/test/cli/daemon.test.ts +++ b/test/cli/daemon.test.ts @@ -1,12 +1,13 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { chmodSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs } from "../../src/cli/daemon.js"; +import { DEFAULT_PORT_RETRIES, main, parseDaemonArgs, startupLine, USAGE } from "../../src/cli/daemon.js"; +import { DEFAULT_HOST } from "../../src/config.js"; import { acquireLock } from "../../src/cli/lock.js"; import { readCliToken, tokenPerms, writeCliToken } from "../../src/cli/token.js"; import { UsageError } from "../../src/cli/util.js"; import { PROTOCOL_VERSION } from "../../src/protocol/types.js"; -import { clearRuntimeEnv, removeDir, setRuntimeEnv, tempDir } from "./helpers.js"; +import { clearRuntimeEnv, removeDir, setRuntimeEnv, silentLogger, tempDir } from "./helpers.js"; describe("parseDaemonArgs", () => { it("defaults to nothing set (foreground daemon, config defaults)", () => { @@ -52,6 +53,10 @@ describe("daemon main (non-listening paths)", () => { expect(out[0]?.split("\n")[0]).toBe("pi2 daemon — pi2 daemon"); expect(out.join("\n")).toContain("Usage: pi2 daemon [start] [options]"); expect(out.join("\n")).toContain("--static-dir"); + expect(out.join("\n")).toContain("0.0.0.0"); + expect(out.join("\n")).toContain("--host <addr> bind address (default 0.0.0.0 (all interfaces))"); + expect(out.join("\n")).toContain("PI2_HOST (0.0.0.0 (all interfaces))"); + expect(USAGE).toContain("0.0.0.0"); }); it("prints the version for --version", async () => { @@ -166,3 +171,73 @@ describe("daemon singleton lock vs cli.token", () => { } }); }); + +describe("daemon startup line", () => { + let dir: string; + + beforeEach(() => { + dir = tempDir("pi2-daemon-startup-"); + setRuntimeEnv(dir); + delete process.env.PI2_HOST; + mkdirSync(join(dir, "web"), { recursive: true }); + writeFileSync(join(dir, "web", "index.html"), "<!doctype html><title>pi2"); + }); + + afterEach(() => { + clearRuntimeEnv(); + delete process.env.PI2_HOST; + removeDir(dir); + }); + + it("formats startup line with verbatim configured host", () => { + const defaultLine = startupLine(DEFAULT_HOST, 7676); + expect(defaultLine).toMatch(/^pi2 daemon listening on http:\/\/\S+:\d+$/); + expect(defaultLine).toBe("pi2 daemon listening on http://0.0.0.0:7676"); + + const explicitLine = startupLine("127.0.0.1", 7676); + expect(explicitLine).toMatch(/^pi2 daemon listening on http:\/\/\S+:\d+$/); + expect(explicitLine).toBe("pi2 daemon listening on http://127.0.0.1:7676"); + }); + + it("announces default wildcard host verbatim on start", async () => { + let handle: { close: () => Promise } | undefined; + const out: string[] = []; + try { + const code = await main(["--port", "0"], { + out: (line) => out.push(line), + err: () => undefined, + logger: silentLogger, + onStarted: (h) => { + handle = h; + }, + }); + expect(code).toBe(0); + expect(out).toHaveLength(1); + expect(out[0]).toMatch(/^pi2 daemon listening on http:\/\/\S+:\d+$/); + expect(out[0]).toMatch(/^pi2 daemon listening on http:\/\/0\.0\.0\.0:\d+$/); + } finally { + if (handle !== undefined) await handle.close(); + } + }); + + it("announces explicit --host 127.0.0.1 verbatim on start", async () => { + let handle: { close: () => Promise } | undefined; + const out: string[] = []; + try { + const code = await main(["--port", "0", "--host", "127.0.0.1"], { + out: (line) => out.push(line), + err: () => undefined, + logger: silentLogger, + onStarted: (h) => { + handle = h; + }, + }); + expect(code).toBe(0); + expect(out).toHaveLength(1); + expect(out[0]).toMatch(/^pi2 daemon listening on http:\/\/\S+:\d+$/); + expect(out[0]).toMatch(/^pi2 daemon listening on http:\/\/127\.0\.0\.1:\d+$/); + } finally { + if (handle !== undefined) await handle.close(); + } + }); +}); diff --git a/test/cli/doctor.test.ts b/test/cli/doctor.test.ts index c0a37c8..c6ebfc3 100644 --- a/test/cli/doctor.test.ts +++ b/test/cli/doctor.test.ts @@ -9,6 +9,7 @@ import { checkNvim, checkNode, checkProtocol, + checkUnit, collectContext, defaultProbes, formatReport, @@ -73,6 +74,7 @@ describe("doctor checks (all passing)", () => { "bind", "service-manager", "linger", + "unit", "web-dist", "protocol", ]); @@ -89,6 +91,12 @@ describe("doctor checks (all passing)", () => { expect(statusOf(report, "linger")).toBeUndefined(); expect(report.ok).toBe(true); }); + + it("accepts bundled node runtime even when node version is low or unparsable", async () => { + const report = await checks({ nodeVersion: "v18.0.0", bundled: true }); + expect(statusOf(report, "node")).toBe("ok"); + expect(report.checks.find((check) => check.name === "node")?.detail).toContain("bundled runtime, no separate node needed"); + }); }); describe("doctor bind check", () => { @@ -184,12 +192,230 @@ describe("doctor curl check", () => { }); }); +describe("doctor unit check", () => { + it("reports ok when no unit file exists", () => { + const check = checkUnit({ path: "/home/u/.config/systemd/user/pi2.service", exists: false }); + expect(check).toEqual({ + name: "unit", + status: "ok", + detail: "no service unit installed (run `pi2 install-service --write` to keep the daemon running)", + }); + expect(checkUnit(undefined).status).toBe("ok"); + }); + + it("warns with the fix hint when unit points at a missing binary path", async () => { + const content = [ + "[Unit]", + "Description=pi2 daemon", + "", + "[Service]", + "ExecStart=/home/u/.local/share/mise/installs/node/22.1.0/bin/node /repo/dist/cli/pi2.js daemon --foreground", + "", + ].join("\n"); + + const check = checkUnit( + { + path: "/home/u/.config/systemd/user/pi2.service", + exists: true, + content, + pathExists: (p) => p !== "/home/u/.local/share/mise/installs/node/22.1.0/bin/node", + }, + false, + "linux", + ); + expect(check.status).toBe("warn"); + expect(check.detail).toContain("/home/u/.local/share/mise/installs/node/22.1.0/bin/node"); + expect(check.detail).toContain("re-run `pi2 install-service --write`"); + + const report = await checks({ + unit: { + path: "/home/u/.config/systemd/user/pi2.service", + exists: true, + content, + pathExists: () => false, + }, + }); + expect(statusOf(report, "unit")).toBe("warn"); + expect(report.ok).toBe(true); + }); + + it("warns with the fix hint when unit points at a missing script path", () => { + const content = "ExecStart=/usr/bin/node /missing/dist/cli/pi2.js daemon --foreground\n"; + const check = checkUnit( + { + path: "/home/u/.config/systemd/user/pi2.service", + exists: true, + content, + pathExists: (p) => p === "/usr/bin/node", + }, + false, + "linux", + ); + expect(check.status).toBe("warn"); + expect(check.detail).toContain("/missing/dist/cli/pi2.js"); + expect(check.detail).toContain("re-run `pi2 install-service --write`"); + }); + + it("warns with the fix hint when plist points at a missing executable", () => { + const content = [ + '', + '', + "", + " ProgramArguments", + " ", + " /missing/node", + " daemon", + " ", + "", + "", + ].join("\n"); + + const check = checkUnit( + { + path: "/Users/u/Library/LaunchAgents/com.pi2.daemon.plist", + exists: true, + content, + pathExists: () => false, + }, + false, + "darwin", + ); + expect(check.status).toBe("warn"); + expect(check.detail).toContain("/missing/node"); + expect(check.detail).toContain("re-run `pi2 install-service --write`"); + }); + + it("reports ok when unit points at an existing path of the current shape (node)", () => { + const content = "ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground\n"; + const check = checkUnit( + { + path: "/home/u/.config/systemd/user/pi2.service", + exists: true, + content, + pathExists: () => true, + }, + false, + "linux", + ); + expect(check).toEqual({ + name: "unit", + status: "ok", + detail: "/usr/bin/node", + }); + }); + + it("reports ok when unit points at an existing path of the current shape (bundled)", () => { + const content = 'ExecStart="/usr/local/bin/pi2" daemon --foreground\n'; + const check = checkUnit( + { + path: "/home/u/.config/systemd/user/pi2.service", + exists: true, + content, + pathExists: () => true, + }, + true, + "linux", + ); + expect(check).toEqual({ + name: "unit", + status: "ok", + detail: "/usr/local/bin/pi2", + }); + }); + + it("reports ok for launchd plist with existing path of current shape", () => { + const content = [ + '', + '', + "", + " ProgramArguments", + " ", + " /opt/homebrew/bin/node", + " /repo/dist/cli/pi2.js", + " daemon", + " ", + "", + "", + ].join("\n"); + + const check = checkUnit( + { + path: "/Users/u/Library/LaunchAgents/com.pi2.daemon.plist", + exists: true, + content, + pathExists: () => true, + }, + false, + "darwin", + ); + expect(check).toEqual({ + name: "unit", + status: "ok", + detail: "/opt/homebrew/bin/node", + }); + }); + + it("warns on shape mismatch when recorded executable is node while running bundled", () => { + const content = "ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground\n"; + const check = checkUnit( + { + path: "/home/u/.config/systemd/user/pi2.service", + exists: true, + content, + pathExists: () => true, + }, + true, // bundled runtime + "linux", + ); + expect(check.status).toBe("warn"); + expect(check.detail).toBe("unit was rendered for a different install shape; re-run pi2 install-service --write"); + }); + + it("warns on shape mismatch when recorded executable is bundled while running under node", () => { + const content = "ExecStart=/usr/local/bin/pi2 daemon --foreground\n"; + const check = checkUnit( + { + path: "/home/u/.config/systemd/user/pi2.service", + exists: true, + content, + pathExists: () => true, + }, + false, // node runtime + "linux", + ); + expect(check.status).toBe("warn"); + expect(check.detail).toBe("unit was rendered for a different install shape; re-run pi2 install-service --write"); + }); + + it("appears in the doctor table output", async () => { + const report = await checks({ + unit: { + path: "/home/u/.config/systemd/user/pi2.service", + exists: true, + content: "ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground\n", + pathExists: () => true, + }, + }); + const text = formatReport(report); + expect(text).toMatch(/ok\s+unit\s+\/usr\/bin\/node/); + + const noUnitReport = await checks({ + unit: { + path: "/home/u/.config/systemd/user/pi2.service", + exists: false, + }, + }); + const noUnitText = formatReport(noUnitReport); + expect(noUnitText).toMatch(/ok\s+unit\s+no service unit installed/); + }); +}); + describe("doctor failure cases", () => { - it("fails on node < 22", async () => { - const report = await checks({ nodeVersion: "v20.11.0" }); + it("fails on node < 20", async () => { + const report = await checks({ nodeVersion: "v18.19.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"); + expect(report.checks.find((check) => check.name === "node")?.detail).toContain("< 20.0.0"); }); it("fails when nvim is missing", async () => { @@ -312,7 +538,11 @@ describe("version helpers", () => { expect(parseNvimVersion("NVIM v0.9.5")).toBe("0.9.5"); expect(parseNvimVersion("garbage")).toBeUndefined(); expect(checkNode("v22.0.0").status).toBe("ok"); + expect(checkNode("v20.0.0").status).toBe("ok"); + expect(checkNode("v18.0.0").status).toBe("fail"); expect(checkNode("garbage").status).toBe("fail"); + expect(checkNode("v18.0.0", true).status).toBe("ok"); + expect(checkNode("v18.0.0", true).detail).toMatch(/bundled runtime, no separate node needed$/); expect(checkNvim({ found: true, path: "/n", version: "v0.10.0" }).status).toBe("ok"); expect(checkLinger({ checked: false }).status).toBe("ok"); }); diff --git a/test/cli/service.test.ts b/test/cli/service.test.ts index 8ab90f8..fd19f8b 100644 --- a/test/cli/service.test.ts +++ b/test/cli/service.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from "vitest"; import { join } from "node:path"; import { + DEFAULT_SYSTEMD_ENV_FILE, defaultScriptPath, + defaultServicePaths, launchAgentDir, renderLaunchAgent, renderService, @@ -20,6 +22,15 @@ const paths: ServicePaths = { pathEnv: "/opt/node/bin:/usr/bin:/bin", }; +const bundledPaths: ServicePaths = { + bundled: true, + execPath: "/usr/local/bin/pi2", + envFile: "-%h/.config/pi2/env", + stateDir: "/home/u/.local/state/pi2", + homeDir: "/home/u", + pathEnv: "/usr/local/bin:/usr/bin:/bin", +}; + const LINUX_UNIT = `[Unit] Description=pi2 daemon After=network.target @@ -37,6 +48,24 @@ TimeoutStopSec=15 WantedBy=default.target `; +const BUNDLED_LINUX_UNIT = `[Unit] +Description=pi2 daemon +After=network.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/pi2 daemon --foreground +EnvironmentFile=-%h/.config/pi2/env +Environment=PATH=/usr/local/bin:/usr/bin:/bin +Restart=on-failure +RestartSec=2 +KillSignal=SIGTERM +TimeoutStopSec=15 + +[Install] +WantedBy=default.target +`; + const MAC_PLIST = ` @@ -67,6 +96,35 @@ const MAC_PLIST = ` `; +const BUNDLED_MAC_PLIST = ` + + + + Label + com.pi2.daemon + ProgramArguments + + /usr/local/bin/pi2 + daemon + --foreground + + EnvironmentVariables + + PATH + /usr/local/bin:/usr/bin:/bin + + RunAtLoad + + KeepAlive + + StandardOutPath + /home/u/.local/state/pi2/pi2-daemon.log + StandardErrorPath + /home/u/.local/state/pi2/pi2-daemon.err.log + + +`; + describe("systemd user unit", () => { it("renders the unit (snapshot)", () => { expect(renderSystemdUnit(paths)).toBe(LINUX_UNIT); @@ -85,6 +143,33 @@ describe("systemd user unit", () => { expect(unit).toContain('ExecStart=/opt/node/bin/node "/repo dir/cli/pi2.js" daemon --foreground'); }); + it("renders the bundled unit (snapshot)", () => { + expect(renderSystemdUnit(bundledPaths)).toBe(BUNDLED_LINUX_UNIT); + }); + + it("renders bundled ExecStart with binary alone, no node or script path, and contains EnvironmentFile", () => { + const unit = renderSystemdUnit(bundledPaths); + expect(unit).toContain("ExecStart=/usr/local/bin/pi2 daemon --foreground"); + expect(unit).not.toContain("/opt/node/bin/node"); + expect(unit).not.toContain("dist/cli/pi2.js"); + expect(unit).toContain("EnvironmentFile=-%h/.config/pi2/env"); + expect(unit.indexOf("EnvironmentFile=")).toBeGreaterThan(unit.indexOf("ExecStart=")); + expect(unit.indexOf("Environment=PATH")).toBeGreaterThan(unit.indexOf("EnvironmentFile=")); + }); + + it("omits EnvironmentFile when envFile is empty string", () => { + const bundledUnit = renderSystemdUnit({ ...bundledPaths, envFile: "" }); + expect(bundledUnit).not.toContain("EnvironmentFile="); + + const nodeUnit = renderSystemdUnit({ ...paths, envFile: "" }); + expect(nodeUnit).not.toContain("EnvironmentFile="); + }); + + it("quotes bundled executable with spaces", () => { + const unit = renderSystemdUnit({ ...bundledPaths, execPath: "/opt/custom bin/pi2" }); + expect(unit).toContain('ExecStart="/opt/custom bin/pi2" daemon --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"); @@ -110,6 +195,31 @@ describe("LaunchAgent plist", () => { expect(plist).toContain("/opt/a&b/node"); }); + it("renders the bundled plist (snapshot)", () => { + expect(renderLaunchAgent(bundledPaths)).toBe(BUNDLED_MAC_PLIST); + }); + + it("renders bundled ProgramArguments with exactly [exe, daemon, --foreground]", () => { + const plist = renderLaunchAgent(bundledPaths); + const argsBlock = [ + " ProgramArguments", + " ", + " /usr/local/bin/pi2", + " daemon", + " --foreground", + " ", + ].join("\n"); + expect(plist).toContain(argsBlock); + expect(plist).not.toContain("/opt/node/bin/node"); + expect(plist).not.toContain("dist/cli/pi2.js"); + expect(plist).not.toContain("EnvironmentFile"); + }); + + it("escapes XML in bundled execPath", () => { + const plist = renderLaunchAgent({ ...bundledPaths, execPath: "/opt/a&b/pi2" }); + expect(plist).toContain("/opt/a&b/pi2"); + }); + it("targets ~/Library/LaunchAgents", () => { expect(launchAgentDir(paths)).toBe("/home/u/Library/LaunchAgents"); const service = renderService("darwin", paths); @@ -122,6 +232,15 @@ describe("LaunchAgent plist", () => { it("resolves dist/cli/pi2.js next to the built CLI", () => { expect(defaultScriptPath()).toMatch(/dist\/cli\/pi2\.js$/); }); + + it("populates bundled, execPath, and default envFile in defaultServicePaths", () => { + const defaults = defaultServicePaths(); + expect(typeof defaults.bundled).toBe("boolean"); + expect(typeof defaults.execPath).toBe("string"); + expect(defaults.envFile).toBe(DEFAULT_SYSTEMD_ENV_FILE); + expect(defaults.nodePath).toBe(process.execPath); + expect(defaults.scriptPath).toMatch(/dist\/cli\/pi2\.js$/); + }); }); describe("install-service / uninstall-service commands", () => { @@ -158,6 +277,23 @@ describe("install-service / uninstall-service commands", () => { expect(lines.join("\n")).toContain("systemctl --user daemon-reload"); }); + it("writes bundled systemd unit on linux with --write", () => { + const lines: string[] = []; + const writes: { path: string; content: string }[] = []; + const code = runInstallService({ + platform: "linux", + paths: bundledPaths, + 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", "pi2.service"), content: BUNDLED_LINUX_UNIT }, + ]); + expect(lines[0]).toBe("wrote /home/u/.config/systemd/user/pi2.service (mode 0644)"); + }); + it("uninstall removes the unit only with --write", () => { const removed: string[] = []; const dry: string[] = []; diff --git a/test/core/install.test.ts b/test/core/install.test.ts new file mode 100644 index 0000000..c3004c7 --- /dev/null +++ b/test/core/install.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { readFileSync } from "node:fs"; +import { dirname, isAbsolute, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { + defaultStaticDir, + executablePath, + isBundledRuntime, + runtimeDescription, + staticDirCandidates, + version, +} from "../../src/core/install.js"; + +describe("install helpers", () => { + it("reports version matching package.json when running from a checkout", () => { + const pkgPath = fileURLToPath(new URL("../../package.json", import.meta.url)); + const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { version: string }; + expect(version()).toBe(pkg.version); + }); + + it("returns three absolute candidates with share/pi2d/web/dist first", () => { + const candidates = staticDirCandidates(); + expect(candidates).toHaveLength(3); + for (const candidate of candidates) { + expect(isAbsolute(candidate)).toBe(true); + } + const exeDir = dirname(executablePath()); + const expectedFirst = resolve(exeDir, "..", "share", "pi2d", "web", "dist"); + expect(candidates[0]).toBe(expectedFirst); + }); + + it("resolves defaultStaticDir without throwing and returns dev checkout web/dist", () => { + expect(() => defaultStaticDir()).not.toThrow(); + const dir = defaultStaticDir(); + expect(isAbsolute(dir)).toBe(true); + const expectedDevPath = resolve(fileURLToPath(new URL("../../web/dist", import.meta.url))); + expect(dir).toBe(expectedDevPath); + }); + + it("reports isBundledRuntime as false under vitest", () => { + expect(isBundledRuntime()).toBe(false); + }); + + it("reports runtimeDescription starting with 'node '", () => { + expect(runtimeDescription().startsWith("node ")).toBe(true); + }); +}); diff --git a/test/core/paths.test.ts b/test/core/paths.test.ts new file mode 100644 index 0000000..15439ad --- /dev/null +++ b/test/core/paths.test.ts @@ -0,0 +1,93 @@ +import { homedir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { piAgentDir, sessionsRoot } from "../../src/core/paths.js"; + +describe("piAgentDir and sessionsRoot", () => { + const originalEnv = { ...process.env }; + + afterEach(() => { + process.env = { ...originalEnv }; + }); + + it("prefers PI2_CODING_AGENT_DIR when both PI2_ and PI_ are set", () => { + const env = { + PI2_CODING_AGENT_DIR: "/custom/pi2/agent", + PI_CODING_AGENT_DIR: "/custom/pi/agent", + }; + expect(piAgentDir(env)).toBe("/custom/pi2/agent"); + expect(sessionsRoot(env)).toBe(join("/custom/pi2/agent", "sessions")); + }); + + it("uses PI_CODING_AGENT_DIR when PI2_CODING_AGENT_DIR is unset", () => { + const env = { + PI_CODING_AGENT_DIR: "/custom/pi/agent", + }; + expect(piAgentDir(env)).toBe("/custom/pi/agent"); + expect(sessionsRoot(env)).toBe(join("/custom/pi/agent", "sessions")); + }); + + it("falls back to ~/.pi/agent when neither variable is set", () => { + const env = {}; + const expected = join(homedir(), ".pi", "agent"); + expect(piAgentDir(env)).toBe(expected); + expect(piAgentDir(env).endsWith(join(".pi", "agent"))).toBe(true); + expect(sessionsRoot(env)).toBe(join(expected, "sessions")); + }); + + it("falls through empty strings to the next candidate", () => { + // PI2 is empty string -> falls through to PI + expect( + piAgentDir({ + PI2_CODING_AGENT_DIR: "", + PI_CODING_AGENT_DIR: "/custom/pi/agent", + }), + ).toBe("/custom/pi/agent"); + + // Both are empty strings -> falls through to ~/.pi/agent + const expected = join(homedir(), ".pi", "agent"); + expect( + piAgentDir({ + PI2_CODING_AGENT_DIR: "", + PI_CODING_AGENT_DIR: "", + }), + ).toBe(expected); + + // PI2 unset, PI is empty string -> falls through to ~/.pi/agent + expect( + piAgentDir({ + PI_CODING_AGENT_DIR: "", + }), + ).toBe(expected); + }); + + it("handles relative paths without crashing", () => { + const relative = "some/relative/agent"; + expect(piAgentDir({ PI2_CODING_AGENT_DIR: relative })).toBe(relative); + expect(sessionsRoot({ PI2_CODING_AGENT_DIR: relative })).toBe(join(relative, "sessions")); + + expect(piAgentDir({ PI_CODING_AGENT_DIR: relative })).toBe(relative); + expect(sessionsRoot({ PI_CODING_AGENT_DIR: relative })).toBe(join(relative, "sessions")); + }); + + it("respects daemon ambient environment injection via process.env", () => { + delete process.env.PI2_CODING_AGENT_DIR; + delete process.env.PI_CODING_AGENT_DIR; + + process.env.PI2_CODING_AGENT_DIR = "/daemon/injected/pi2"; + expect(piAgentDir()).toBe("/daemon/injected/pi2"); + expect(sessionsRoot()).toBe(join("/daemon/injected/pi2", "sessions")); + + process.env.PI_CODING_AGENT_DIR = "/daemon/injected/pi"; + // PI2 still wins + expect(piAgentDir()).toBe("/daemon/injected/pi2"); + + // When PI2 is empty string in process.env, falls through to PI + process.env.PI2_CODING_AGENT_DIR = ""; + expect(piAgentDir()).toBe("/daemon/injected/pi"); + + // When both are empty string in process.env, falls through to default + process.env.PI_CODING_AGENT_DIR = ""; + expect(piAgentDir()).toBe(join(homedir(), ".pi", "agent")); + }); +}); diff --git a/test/daemon/fakes.ts b/test/daemon/fakes.ts index f38ceda..d37767f 100644 --- a/test/daemon/fakes.ts +++ b/test/daemon/fakes.ts @@ -11,7 +11,7 @@ import type { PluginConnection, WorkspaceStore, } from "../../src/core/interfaces.js"; -import type { InstanceState, SessionState, WorkspaceInfo } from "../../src/protocol/types.js"; +import type { InstanceState, RecentSessionInfo, SessionState, WorkspaceInfo } from "../../src/protocol/types.js"; export interface CommandCall { id: string; @@ -211,6 +211,8 @@ export class FakeWorkspaceStore implements WorkspaceStore { updateCalls: { workspaceId: string; patch: Record }[] = []; removeCalls: string[] = []; refreshCalls: (string | undefined)[] = []; + /** Seeded answer for `recentSessions()`; the fake never touches disk. */ + recentSessionRows: RecentSessionInfo[] = []; constructor(seed: WorkspaceInfo[] = []) { for (const workspace of seed) this.workspaces.set(workspace.workspaceId, workspace); @@ -262,6 +264,10 @@ export class FakeWorkspaceStore implements WorkspaceStore { async ensureForCwd(cwd: string): Promise { return this.byCwd(cwd) ?? this.add({ cwd }); } + + recentSessions(limit = 20): RecentSessionInfo[] { + return this.recentSessionRows.slice(0, limit); + } } export class FakeBus implements Bus { diff --git a/test/daemon/http.test.ts b/test/daemon/http.test.ts index 8f3e3fd..b3961c4 100644 --- a/test/daemon/http.test.ts +++ b/test/daemon/http.test.ts @@ -281,6 +281,40 @@ describe("HTTP API", () => { ); }); + it("serves the disk-projected recent-session feed for the activity column", async () => { + h.workspaces.recentSessionRows = [ + { + sessionId: "s-new", + workspaceId: "ws-1", + workspaceName: "alpha", + cwd: "/work/alpha", + sessionFile: "/sessions/a/s-new.jsonl", + timestamp: 1_700_000_000_000, + modified: 1_700_000_100_000, + }, + { + sessionId: "s-old", + workspaceId: "ws-1", + workspaceName: "alpha", + cwd: "/work/alpha", + sessionFile: "/sessions/a/s-old.jsonl", + timestamp: 1_600_000_000_000, + modified: 1_600_000_100_000, + }, + ]; + + // It must not relay to (or spawn) an instance — the fake store answers + // directly and the connection never sees a command. + const res = await fetch(`${h.url}/api/v1/sessions/recent?limit=1`, authed()); + expect(res.status).toBe(200); + const body = (await res.json()) as { sessions: { sessionId: string }[] }; + expect(body.sessions).toEqual([expect.objectContaining({ sessionId: "s-new", workspaceName: "alpha" })]); + expect(conn.commands).toHaveLength(0); + + const fallback = await fetch(`${h.url}/api/v1/sessions/recent`, authed()); + expect(((await fallback.json()) as { sessions: unknown[] }).sessions).toHaveLength(2); + }); + it("routes a disk-only session's entries through workspaceId but keeps the sid", async () => { // A row from disk discovery is not owned by the live instance, so the // workspace hint is what routes it -- and the sid must survive that. diff --git a/test/workspaces/discovery.test.ts b/test/workspaces/discovery.test.ts index 18ad82f..803d1e1 100644 --- a/test/workspaces/discovery.test.ts +++ b/test/workspaces/discovery.test.ts @@ -227,6 +227,36 @@ describe("workspace disk discovery", () => { } }); + it("defaults the root to PI2_CODING_AGENT_DIR/sessions, taking precedence over PI_CODING_AGENT_DIR", () => { + const pi2Agent = join(sandbox, "pi2-agent"); + const pi2Sessions = join(pi2Agent, "sessions"); + mkdirSync(pi2Sessions, { recursive: true }); + writeSessionDir(pi2Sessions, encodedDirName(sandbox), [ + { name: "2026-10-10T06-40-33-032Z_pi2.jsonl", cwd: sandbox, id: "pi2" }, + ]); + const piAgent = join(sandbox, "pi-agent"); + const piSessions = join(piAgent, "sessions"); + mkdirSync(piSessions, { recursive: true }); + writeSessionDir(piSessions, encodedDirName(sandbox), [ + { name: "2026-10-10T06-40-33-032Z_pi.jsonl", cwd: sandbox, id: "pi" }, + ]); + + const prevPi2 = process.env.PI2_CODING_AGENT_DIR; + const prevPi = process.env.PI_CODING_AGENT_DIR; + process.env.PI2_CODING_AGENT_DIR = pi2Agent; + process.env.PI_CODING_AGENT_DIR = piAgent; + try { + const discovered = createDiscovery().discover(); + expect(discovered).toHaveLength(1); + expect(discovered[0]?.dir).toBe(join(pi2Sessions, encodedDirName(sandbox))); + } finally { + if (prevPi2 === undefined) delete process.env.PI2_CODING_AGENT_DIR; + else process.env.PI2_CODING_AGENT_DIR = prevPi2; + if (prevPi === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = prevPi; + } + }); + it("ignores a vanished directory gracefully", () => { const dir = writeSessionDir(root, encodedDirName(sandbox), [ { name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: sandbox, id: "a" }, diff --git a/test/workspaces/store.test.ts b/test/workspaces/store.test.ts index e462cca..8e688c3 100644 --- a/test/workspaces/store.test.ts +++ b/test/workspaces/store.test.ts @@ -53,14 +53,38 @@ describe("workspace store", () => { for (const dir of [sessions, allowRoot, projectA, projectB, projectGhost]) mkdirSync(dir, { recursive: true }); writeSessionDir(sessions, encodedDirName(projectA), [ - { name: "2026-10-10T06-40-33-032Z_a1.jsonl", cwd: projectA, id: "a1" }, - { name: "2026-10-11T06-40-33-032Z_a2.jsonl", cwd: projectA, id: "a2" }, + { + name: "2026-10-10T06-40-33-032Z_a1.jsonl", + cwd: projectA, + id: "a1", + timestamp: "2026-10-10T06:40:33.032Z", + mtime: new Date("2026-10-10T06:40:33.032Z"), + }, + { + name: "2026-10-11T06-40-33-032Z_a2.jsonl", + cwd: projectA, + id: "a2", + timestamp: "2026-10-11T06:40:33.032Z", + mtime: new Date("2026-10-11T06:40:33.032Z"), + }, ]); writeSessionDir(sessions, encodedDirName(projectB), [ - { name: "2026-10-12T06-40-33-032Z_b1.jsonl", cwd: projectB, id: "b1" }, + { + name: "2026-10-12T06-40-33-032Z_b1.jsonl", + cwd: projectB, + id: "b1", + timestamp: "2026-10-12T06:40:33.032Z", + mtime: new Date("2026-10-12T06:40:33.032Z"), + }, ]); writeSessionDir(sessions, encodedDirName(projectGhost), [ - { name: "2026-10-13T06-40-33-032Z_g1.jsonl", cwd: projectGhost, id: "g1" }, + { + name: "2026-10-13T06-40-33-032Z_g1.jsonl", + cwd: projectGhost, + id: "g1", + timestamp: "2026-10-13T06:40:33.032Z", + mtime: new Date("2026-10-13T06:40:33.032Z"), + }, ]); rmSync(projectGhost, { recursive: true, force: true }); }); @@ -116,6 +140,29 @@ describe("workspace store", () => { expect(ghost).toMatchObject({ exists: false, sessionCount: 1, lastActiveAt: expect.any(Number) }); }); + it("lists the newest session files across workspaces for the activity feed", () => { + const { store } = setup(); + + const rows = store.recentSessions(3); + expect(rows.map((row) => row.sessionId)).toEqual(["g1", "b1", "a2"]); + expect(rows.map((row) => row.workspaceId)).toEqual([ + workspaceIdForCwd(projectGhost), + workspaceIdForCwd(projectB), + workspaceIdForCwd(projectA), + ]); + expect(rows[0]).toMatchObject({ + workspaceName: "ghost", + cwd: projectGhost, + timestamp: Date.parse("2026-10-13T06:40:33.032Z"), + modified: Date.parse("2026-10-13T06:40:33.032Z"), + sessionFile: expect.stringContaining("g1"), + }); + // The default (no limit) still returns every discovered session, and an + // out-of-range limit is clamped instead of exploding the header scan. + expect(store.recentSessions()).toHaveLength(4); + expect(store.recentSessions(0)).toHaveLength(4); + }); + it("keeps hidden entries in list(); the UI decides ordering", async () => { const { store } = setup(); const bId = workspaceIdForCwd(projectB); diff --git a/web/package.json b/web/package.json index b047a12..6b10b6d 100644 --- a/web/package.json +++ b/web/package.json @@ -5,7 +5,7 @@ "type": "module", "description": "pi2 web console — React port of the pi2 web UI prototype", "engines": { - "node": ">=22" + "node": ">=20" }, "scripts": { "dev": "vite", diff --git a/web/src/features/workspaces/activity-column.tsx b/web/src/features/workspaces/activity-column.tsx index fcdca54..b1f88a3 100644 --- a/web/src/features/workspaces/activity-column.tsx +++ b/web/src/features/workspaces/activity-column.tsx @@ -5,14 +5,11 @@ import { Icon } from "@/components/icons"; import { RelativeTime } from "@/components/shared/relative-time"; import { Empty } from "@/components/ui/empty"; import { StatusDot } from "@/components/ui/status-dot"; -import { plural } from "@/lib/i18n"; +import { sessionDot, sessionStatusKey } from "@/features/chat/session-state"; +import { sessionTitle } from "@/features/chat/session-title"; import type { WorkspaceInfo } from "@/lib/protocol"; -import { workspaceName, workspaceSessionCount } from "./commands"; -import { instanceState } from "./workspace-card"; - -/** The design lists the newest 5 entries. */ -export const ACTIVITY_LIMIT = 5; +import { useRecentSessions, type RecentSessionRow } from "./recent-sessions"; export interface ActivityColumnProps { workspaces: readonly WorkspaceInfo[]; @@ -20,53 +17,32 @@ export interface ActivityColumnProps { /** * "Recent activity" column (pi2-web-ui-design v0.1.1 §5.1): the newest - * `ACTIVITY_LIMIT` entries by `lastActiveAt`, dot + name + meta + relative - * time, each row linking into the chat UI. + * `RECENT_SESSION_LIMIT` sessions across every visible workspace, dot + title + + * owning-workspace + relative time, each row linking into the chat UI. * - * The prototype derives it from `MOCK.sessions`; the daemon exposes no - * cross-workspace session feed (only `/workspaces//sessions`), so the rows - * are workspace-level and the meta slot carries the session count instead of - * the owning workspace name. + * Two read-only sources feed it (`features/workspaces/recent-sessions.ts`): the + * daemon's disk feed (survives restarts, never spawns an instance) and the + * per-workspace session list for live instances (adds names and live status). */ export function ActivityColumn({ workspaces }: ActivityColumnProps) { const { t } = useTranslation(); - const recent = [...workspaces] - .filter((workspace) => typeof workspace.lastActiveAt === "number" && Number.isFinite(workspace.lastActiveAt)) - .sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0)) - .slice(0, ACTIVITY_LIMIT); + const sessions = useRecentSessions(workspaces, workspaces.length > 0); + const phrases = { + unnamed: t("chat.sessionUnnamed"), + subagentUnnamed: t("chat.subagentUnnamed"), + }; return ( ); } + +type Phrases = { unnamed: string; subagentUnnamed: string }; + +function ActivityRow({ session, phrases }: { session: RecentSessionRow; phrases: Phrases }) { + const { t } = useTranslation(); + // A disk-only row has no live state; the session title contract then falls + // back to `(unnamed)` (never an id), and the dot is the hollow "exited". + const title = session.state + ? sessionTitle(session.state, phrases) + : { text: phrases.unnamed, provisional: true, spinner: false }; + const dot = session.state ? sessionDot(session.state) : { status: "exited" as const }; + const label = session.state ? t(`state.${sessionStatusKey(session.state)}`) : t("state.exited"); + + return ( + + + + {title.text} + {session.workspaceName} + + + + ); +} diff --git a/web/src/features/workspaces/recent-sessions.ts b/web/src/features/workspaces/recent-sessions.ts new file mode 100644 index 0000000..211a507 --- /dev/null +++ b/web/src/features/workspaces/recent-sessions.ts @@ -0,0 +1,160 @@ +import { useQuery } from "@tanstack/react-query"; +import { useMemo } from "react"; + +import { apiRequest } from "@/lib/api"; +import type { RecentSessionInfo, SessionState, WorkspaceInfo } from "@/lib/protocol"; +import { normalizeSessionSummary } from "@/features/chat/session-state"; +import { useWorkspaceSessionsQueries } from "@/features/status/queries"; + +/** The design lists the newest five sessions across every workspace. */ +export const ACTIVITY_LIMIT = 5; + +/** Enough headroom for the client-side merge with live session rows. */ +const FEED_LIMIT = 20; + +export interface RecentSessionRow { + sessionId: string; + workspaceId: string; + workspaceName: string; + /** Recency: live `lastActiveAt`/`createdAt`, else the file's mtime/start. */ + ts: number; + /** Full state when a live instance answered for the workspace; null for disk-only rows. */ + state: SessionState | null; +} + +function rec(value: unknown): Record | undefined { + return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : undefined; +} + +function str(value: unknown): string | undefined { + return typeof value === "string" && value !== "" ? value : undefined; +} + +function num(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +/** + * `GET /api/v1/sessions/recent` → `{sessions: RecentSessionInfo[]}`. + * Tolerates a bare array and drops malformed rows instead of failing the column. + */ +export function normalizeRecentSessions(payload: unknown): RecentSessionInfo[] { + const record = rec(payload); + const list = Array.isArray(payload) ? payload : Array.isArray(record?.sessions) ? record.sessions : []; + const rows: RecentSessionInfo[] = []; + for (const entry of list) { + const row = rec(entry); + const sessionId = str(row?.sessionId); + const workspaceId = str(row?.workspaceId); + if (!row || !sessionId || !workspaceId) continue; + rows.push({ + sessionId, + workspaceId, + workspaceName: str(row.workspaceName) ?? workspaceId, + cwd: str(row.cwd) ?? "", + sessionFile: str(row.sessionFile) ?? "", + timestamp: num(row.timestamp) ?? 0, + modified: num(row.modified) ?? 0, + }); + } + return rows; +} + +/** + * Merge the daemon's disk feed with session states from live instances. + * + * Disk rows are the base (they exist after a daemon restart, before any + * workspace is spawned). A live row with the same id replaces the metadata: + * it carries the authoritative name/first message/status. Sub-sessions are + * dropped — the design's activity column is a list of workspace roots. + */ +export function mergeRecentSessions( + disk: readonly RecentSessionInfo[], + live: readonly SessionState[], + workspaces: readonly WorkspaceInfo[], + limit = ACTIVITY_LIMIT, +): RecentSessionRow[] { + const allowed = new Set(workspaces.map((workspace) => workspace.workspaceId)); + const nameById = new Map(workspaces.map((workspace) => [workspace.workspaceId, workspace.name])); + const byId = new Map(); + + for (const row of disk) { + if (!allowed.has(row.workspaceId)) continue; + byId.set(row.sessionId, { disk: row }); + } + for (const state of live) { + if (!state.sessionId || !allowed.has(state.workspaceId)) continue; + const entry = byId.get(state.sessionId) ?? {}; + entry.live = state; + byId.set(state.sessionId, entry); + } + + const rows: RecentSessionRow[] = []; + for (const [sessionId, entry] of byId) { + if (entry.live?.parentId) continue; + const workspaceId = entry.live?.workspaceId ?? entry.disk?.workspaceId ?? ""; + const ts = Math.max( + entry.live?.lastActiveAt ?? 0, + entry.live?.createdAt ?? 0, + entry.disk?.modified ?? 0, + entry.disk?.timestamp ?? 0, + ); + rows.push({ + sessionId, + workspaceId, + workspaceName: nameById.get(workspaceId) ?? entry.disk?.workspaceName ?? "", + ts, + state: entry.live ?? null, + }); + } + rows.sort((a, b) => b.ts - a.ts || a.sessionId.localeCompare(b.sessionId)); + return rows.slice(0, limit); +} + +/** + * Recent activity for the workspaces page. + * + * Two sources, both read-only: + * - the daemon's disk feed (no instance spawn, survives a restart), and + * - `/workspaces/:id/sessions` for workspaces with a live instance, which adds + * names/first messages/status without spawning anything (the status page + * uses the same query keys). + */ +export function useRecentSessions(workspaces: readonly WorkspaceInfo[], enabled = true): RecentSessionRow[] { + const liveIds = useMemo( + () => workspaces.filter((workspace) => workspace.instance != null).map((workspace) => workspace.workspaceId), + [workspaces], + ); + + const feed = useQuery({ + queryKey: ["recent-sessions"], + queryFn: async ({ signal }) => + normalizeRecentSessions( + await apiRequest(`/api/v1/sessions/recent?limit=${FEED_LIMIT}`, { signal }), + ), + enabled, + staleTime: 10_000, + refetchInterval: 15_000, + retry: false, + }); + + const sessionQueries = useWorkspaceSessionsQueries(liveIds, enabled); + // `useWorkspaceSessionsQueries` returns the daemon's list rows as-is (the + // status page only reads `tasks`); the activity column needs the reducer's + // defaults for flags/attention, so normalize before rendering a dot. + const live = useMemo( + () => + sessionQueries.flatMap((query, index) => { + const workspaceId = liveIds[index] ?? ""; + return (Array.isArray(query.data) ? query.data : []).map((row) => + normalizeSessionSummary(row, workspaceId), + ); + }), + [sessionQueries, liveIds], + ); + + return useMemo( + () => mergeRecentSessions(feed.data ?? [], live, workspaces), + [feed.data, live, workspaces], + ); +} diff --git a/web/src/styles/app.css b/web/src/styles/app.css index abe73f0..a575c03 100644 --- a/web/src/styles/app.css +++ b/web/src/styles/app.css @@ -708,6 +708,9 @@ html[data-pi-blink-slow="dim"] .dot--blink-slow { opacity: .35; } .page-head--lg .page-head__sub { margin-top: 2px; } @media (max-width: 599px) { .page-head { align-items: center; } + /* Column direction turns `flex-basis: 14rem` into a 224px-tall header block, + which reads as a blank band under the title. Fall back to content height. */ + .page-head__text { flex: 0 1 auto; } .page-head__actions { margin-left: 0; } } diff --git a/web/src/styles/pages/workspaces.css b/web/src/styles/pages/workspaces.css index ac0adc2..ddc1e2d 100644 --- a/web/src/styles/pages/workspaces.css +++ b/web/src/styles/pages/workspaces.css @@ -78,10 +78,10 @@ .ws-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .ws-activity { position: sticky; top: calc(var(--topbar-h) + var(--space-4)); } } -/* <1100:单列,活动列排到网格下方 */ +/* <1100:单列,最近活动放在最上面(手机端先看最近会话) */ @media (max-width: 1099px) { - .ws-main { order: 1; } - .ws-activity { order: 2; } + .ws-main { order: 2; } + .ws-activity { order: 1; } } /* ---------- workspace card(整卡 = 一个链接,无行级 primary 按钮) ---------- */ diff --git a/web/tests/workspaces-page.test.tsx b/web/tests/workspaces-page.test.tsx index 2eb6757..12bd14b 100644 --- a/web/tests/workspaces-page.test.tsx +++ b/web/tests/workspaces-page.test.tsx @@ -34,10 +34,32 @@ function routes() { return [ { path: "/workspaces", component: WorkspacesPage }, { path: "/chat", component: () =>
Chat destination
}, + { path: "/chat/$sessionId", component: () =>
Chat session destination
}, { path: "/status", component: () =>
Status destination
}, ]; } +/** The activity column's disk feed; most tests only need it to resolve empty. */ +function recentRoute(rows: unknown[] = []) { + return { path: "/api/v1/sessions/recent", handler: () => ({ body: { sessions: rows } }) }; +} + +/** One workspace's `/sessions` relay (only called for live instances). */ +function sessionsRoute(workspaceId: string, rows: unknown[] = []) { + return { path: `/api/v1/workspaces/${workspaceId}/sessions`, handler: () => ({ body: { sessions: rows } }) }; +} + +function diskSession(overrides: Record & { sessionId: string; workspaceId: string }) { + return { + workspaceName: overrides.workspaceId, + cwd: `/work/${overrides.workspaceId}`, + sessionFile: `/sessions/${overrides.workspaceId}/${overrides.sessionId}.jsonl`, + timestamp: 1_000, + modified: 1_000, + ...overrides, + }; +} + /** Card names are also repeated in the activity column, so wait on the cards. */ async function waitForCards(count: number) { await waitFor(() => expect(screen.getAllByTestId("workspace-row")).toHaveLength(count)); @@ -61,6 +83,7 @@ describe("WorkspacesPage", () => { mockApi([ { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, { path: "/api/v1/workspaces", handler: () => ({ body: items }) }, + recentRoute(), ]); const { container } = await renderPage(routes(), "/workspaces", { paired: true }); @@ -108,6 +131,8 @@ describe("WorkspacesPage", () => { ], }), }, + recentRoute(), + sessionsRoute("ws-a"), ]); const { container } = await renderPage(routes(), "/workspaces", { paired: true }); @@ -145,6 +170,7 @@ describe("WorkspacesPage", () => { ], }), }, + recentRoute(), ]); const { container } = await renderPage(routes(), "/workspaces", { paired: true }); @@ -164,30 +190,91 @@ describe("WorkspacesPage", () => { expect(container.querySelector(".ws-context")).toBeNull(); }); - it("lists the newest workspaces in a recent-activity column", async () => { - const items = [1, 2, 3, 4, 5, 6].map((n) => - workspace({ workspaceId: `ws-${n}`, cwd: `/work/${n}`, name: `Project ${n}`, lastActiveAt: n * 1_000 }), - ); + it("lists the newest sessions across workspaces in a recent-activity column", async () => { + const items = [ + workspace({ workspaceId: "ws-a", cwd: "/work/a", name: "Alpha", lastActiveAt: 1_000 }), + workspace({ workspaceId: "ws-b", cwd: "/work/b", name: "Bravo", lastActiveAt: 2_000 }), + ]; + const rows = [ + diskSession({ sessionId: "s-6", workspaceId: "ws-b", workspaceName: "Bravo", modified: 6_000 }), + diskSession({ sessionId: "s-1", workspaceId: "ws-a", workspaceName: "Alpha", modified: 1_000 }), + diskSession({ sessionId: "s-4", workspaceId: "ws-a", workspaceName: "Alpha", modified: 4_000 }), + diskSession({ sessionId: "s-2", workspaceId: "ws-b", workspaceName: "Bravo", modified: 2_000 }), + diskSession({ sessionId: "s-5", workspaceId: "ws-a", workspaceName: "Alpha", modified: 5_000 }), + diskSession({ sessionId: "s-3", workspaceId: "ws-a", workspaceName: "Alpha", modified: 3_000 }), + ]; mockApi([ { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, { path: "/api/v1/workspaces", handler: () => ({ body: items }) }, + recentRoute(rows), ]); await renderPage(routes(), "/workspaces", { paired: true }); - await waitForCards(6); + await waitForCards(2); const activity = screen.getByTestId("workspaces-activity"); expect(activity.tagName).toBe("ASIDE"); - const rows = within(activity).getAllByTestId("workspace-activity-row"); - // Newest first, capped at 5 (v0.1.1 §5.1). - expect(rows.map((row) => row.getAttribute("data-workspace-id"))).toEqual(["ws-6", "ws-5", "ws-4", "ws-3", "ws-2"]); - expect(rows[0]).toHaveAttribute("href", "/chat?workspace=ws-6"); + const links = await within(activity).findAllByTestId("workspace-activity-row"); + // Newest session first, capped at 5 (v0.1.1 §5.1), regardless of the + // workspace order in the grid. + expect(links.map((row) => row.getAttribute("data-session-id"))).toEqual(["s-6", "s-5", "s-4", "s-3", "s-2"]); + expect(links[0]).toHaveAttribute("href", "/chat/s-6?workspace=ws-b"); + expect(links[0]).toHaveTextContent("Bravo"); // Head carries the section label + the entry count (a11y name is the i18n label). expect(activity).toHaveAttribute("aria-label"); expect(activity.querySelector(".ws-activity__count")).toHaveTextContent("5"); }); + it("enriches a recent-activity row with the live session's title and status", async () => { + const items = [ + workspace({ + workspaceId: "ws-a", + cwd: "/work/a", + name: "Alpha", + sessionCount: 1, + liveCount: 1, + lastActiveAt: 5_000, + instance: { + workspaceId: "ws-a", + instanceId: "inst-a", + status: "ready", + nvimPid: 42, + pluginVersion: "0.1.1", + hasUI: true, + attachedClients: 1, + listenAddr: "127.0.0.1:7777", + startedAt: 1_000, + }, + }), + ]; + const liveRow = { + sessionId: "s-live", + workspaceId: "ws-a", + name: "Refactor the console", + status: "busy", + flags: { attention: false, done: false, error: false }, + lastActiveAt: 9_000, + }; + mockApi([ + { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, + { path: "/api/v1/workspaces", handler: () => ({ body: items }) }, + recentRoute([diskSession({ sessionId: "s-live", workspaceId: "ws-a", modified: 4_000 })]), + sessionsRoute("ws-a", [liveRow]), + ]); + + await renderPage(routes(), "/workspaces", { paired: true }); + await waitForCards(1); + + const activity = screen.getByTestId("workspaces-activity"); + expect(await within(activity).findByText("Refactor the console")).toBeInTheDocument(); + const [row] = within(activity).getAllByTestId("workspace-activity-row"); + expect(row).toHaveAttribute("data-session-id", "s-live"); + expect(row).toHaveAttribute("href", "/chat/s-live?workspace=ws-a"); + expect(row?.querySelector(".ws-activity__ws")).toHaveTextContent("Alpha"); + expect(row?.querySelector(".dot")).toHaveClass("dot--busy"); + }); + it("opens the new-workspace dialog from the empty state", async () => { const fetchMock = mockApi([ { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, @@ -259,6 +346,7 @@ describe("WorkspacesPage", () => { const fetchMock = mockApi([ { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, { path: "/api/v1/workspaces", handler: () => ({ body: items }) }, + recentRoute(), { method: "POST", path: "/api/v1/cmd",