Compare commits
11
Commits
fc51c3be37
...
v0.1.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e775b09037 | ||
|
|
d5d205a7eb | ||
|
|
b95ff6055b | ||
|
|
85faacb0ba | ||
|
|
db387ae248 | ||
|
|
c933eb39ad | ||
|
|
118f24e1ba | ||
|
|
605280d8dc | ||
|
|
cbe73b9aa4 | ||
|
|
a50bb6e8e3 | ||
|
|
d2e20d428a |
No files matched your search
@@ -76,3 +76,41 @@ 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 (Alpine)
|
||||
# Bun's `-musl` artifact needs musl's libstdc++, which the Ubuntu runner
|
||||
# does not ship: running it here fails with unresolved C++ symbols. So the
|
||||
# musl binary is executed where it is actually meant to run.
|
||||
run: |
|
||||
docker run --rm \
|
||||
-v "${{ github.workspace }}/scripts:/s:ro" \
|
||||
-v "${{ github.workspace }}/dist-bin:/b:ro" \
|
||||
alpine:3.20 sh -c 'apk add --no-cache libstdc++ curl >/dev/null 2>&1 && sh /s/boot-check.sh /b/bin/pi2'
|
||||
@@ -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,212 @@ 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 (host-native)
|
||||
if: ${{ !contains(matrix.target, 'musl') }}
|
||||
run: sh scripts/boot-check.sh dist-bin/bin/pi2 "${GITHUB_REF_NAME#v}"
|
||||
|
||||
- name: Boot check (Alpine, musl artifact)
|
||||
# Bun's musl binaries link against musl's libstdc++; the glibc runner
|
||||
# cannot load them ("symbol not found" for std:: symbols), so musl
|
||||
# artifacts are executed on the libc they are built for.
|
||||
if: ${{ contains(matrix.target, 'musl') }}
|
||||
run: |
|
||||
docker run --rm \
|
||||
-v "${{ github.workspace }}/scripts:/s:ro" \
|
||||
-v "${{ github.workspace }}/dist-bin:/b:ro" \
|
||||
alpine:3.20 sh -c 'apk add --no-cache libstdc++ curl >/dev/null 2>&1 && sh /s/boot-check.sh /b/bin/pi2 "${GITHUB_REF_NAME#v}"'
|
||||
|
||||
- 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
|
||||
# The two release credentials live in job-level env because GitHub does not
|
||||
# expose the `secrets` context inside `if:` expressions (a step-level
|
||||
# `if: secrets.X != ''` fails workflow parsing with "Unrecognized
|
||||
# named-value: 'secrets'"). `env` *is* available in a step-level `if`, so
|
||||
# the guards below test the mapped env vars instead.
|
||||
env:
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
AUR_SSH_KEY: ${{ secrets.AUR_SSH_KEY }}
|
||||
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: env.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: env.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 <downloaded-artifact>/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 <downloaded-artifact>/PKGBUILD <downloaded-artifact>/.SRCINFO pi2d-bin/"
|
||||
echo " cd pi2d-bin && git add PKGBUILD .SRCINFO && git commit -m 'pi2d ${version}' && git push origin master"
|
||||
fi
|
||||
@@ -0,0 +1,92 @@
|
||||
name: verify-secrets
|
||||
|
||||
# Manual diagnostic for the two release secrets, so a broken credential is found
|
||||
# here instead of half-way through a release (where the packaging job would push
|
||||
# nothing and the failure would only show up as a missing formula/package).
|
||||
#
|
||||
# gh workflow run verify-secrets.yml
|
||||
# gh run watch
|
||||
#
|
||||
# Each job is a no-op (with a ::warning::) when its secret is unset, and fails
|
||||
# loudly when the secret is set but the credential does not work.
|
||||
#
|
||||
# - HOMEBREW_TAP_TOKEN: a fine-grained PAT with `Contents: Read and write` on
|
||||
# zgs225/homebrew-tap only. Verified with a read (`git ls-remote`) and a write
|
||||
# (a throwaway branch that is deleted again in the same run).
|
||||
# - AUR_SSH_KEY: the private half of the key whose public half is registered at
|
||||
# https://aur.archlinux.org/account. Verified by the ssh welcome banner
|
||||
# (`Welcome to AUR, <user>!`); it does not push anything.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
tap:
|
||||
name: homebrew tap token
|
||||
runs-on: ubuntu-latest
|
||||
# `secrets` is not a valid context inside `if:` (the parser rejects the whole
|
||||
# workflow); map it to env at job level and test the env var instead.
|
||||
env:
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
steps:
|
||||
- name: not configured
|
||||
if: env.HOMEBREW_TAP_TOKEN == ''
|
||||
run: echo "::warning::HOMEBREW_TAP_TOKEN is not set — the packaging job will only print manual instructions"
|
||||
|
||||
- name: read access
|
||||
if: env.HOMEBREW_TAP_TOKEN != ''
|
||||
run: |
|
||||
remote="https://x-access-token:${HOMEBREW_TAP_TOKEN}@github.com/zgs225/homebrew-tap.git"
|
||||
if ! git ls-remote "$remote" HEAD >/dev/null 2>&1; then
|
||||
echo "::error::cannot read zgs225/homebrew-tap with HOMEBREW_TAP_TOKEN (expired, wrong repo scope, or missing Contents: Read)"
|
||||
exit 1
|
||||
fi
|
||||
echo "read ok: token can see zgs225/homebrew-tap"
|
||||
|
||||
- name: write access (throwaway branch)
|
||||
if: env.HOMEBREW_TAP_TOKEN != ''
|
||||
run: |
|
||||
branch="verify-secrets-${GITHUB_RUN_ID}"
|
||||
remote="https://x-access-token:${HOMEBREW_TAP_TOKEN}@github.com/zgs225/homebrew-tap.git"
|
||||
git clone --quiet "$remote" tap
|
||||
cd tap
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git checkout --quiet -b "$branch"
|
||||
date -u +"%Y-%m-%dT%H:%M:%SZ" > .verify-probe
|
||||
git add .verify-probe
|
||||
git commit --quiet -m "chore: verify-secrets probe ${GITHUB_RUN_ID}"
|
||||
if ! git push --quiet origin "HEAD:${branch}"; then
|
||||
echo "::error::HOMEBREW_TAP_TOKEN can read but not write zgs225/homebrew-tap — it needs 'Contents: Read and write'"
|
||||
exit 1
|
||||
fi
|
||||
echo "write ok: pushed ${branch}"
|
||||
git push --quiet origin --delete "$branch"
|
||||
echo "cleanup ok: deleted ${branch} (the tap is back to its previous state)"
|
||||
|
||||
aur:
|
||||
name: aur ssh key
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
AUR_SSH_KEY: ${{ secrets.AUR_SSH_KEY }}
|
||||
steps:
|
||||
- name: not configured
|
||||
if: env.AUR_SSH_KEY == ''
|
||||
run: echo "::warning::AUR_SSH_KEY is not set — the packaging job will only print manual instructions for pi2d-bin"
|
||||
|
||||
- name: key authenticates
|
||||
if: env.AUR_SSH_KEY != ''
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
printf '%s\n' "$AUR_SSH_KEY" > ~/.ssh/aur_ed25519
|
||||
chmod 600 ~/.ssh/aur_ed25519
|
||||
ssh-keyscan -H aur.archlinux.org >> ~/.ssh/known_hosts 2>/dev/null || true
|
||||
banner="$(ssh -i ~/.ssh/aur_ed25519 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -T aur@aur.archlinux.org 2>&1 || true)"
|
||||
echo "$banner"
|
||||
if ! printf '%s' "$banner" | grep -qi "welcome to AUR"; then
|
||||
echo "::error::AUR_SSH_KEY does not authenticate — is the matching public key uploaded at https://aur.archlinux.org/account ?"
|
||||
exit 1
|
||||
fi
|
||||
echo "auth ok: key is registered on AUR"
|
||||
@@ -4,3 +4,4 @@ coverage/
|
||||
*.log
|
||||
.DS_Store
|
||||
tmp/
|
||||
dist-bin/
|
||||
@@ -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 |
|
||||
|
||||
@@ -16,43 +16,125 @@ 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 `pi2d-bin`):**
|
||||
*(AUR account registration is temporarily closed upstream — until it reopens, Arch users install with the [curl installer](#channel-b-standalone-curl-installer-no-node-required) above)*:
|
||||
```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).
|
||||
|
||||
### Open any project from the console
|
||||
|
||||
A project can be opened straight from the web console: type any absolute path, or a `~/…` one, that
|
||||
lies inside the allowed roots (`PI2_WORKSPACE_ROOTS`, default `$HOME`) and the daemon starts a
|
||||
headless pi2.nvim host for it on demand — no `:PiWebStart` first. `:PiWeb` remains the way to hand
|
||||
the browser your *existing* nvim session.
|
||||
|
||||
### Neovim plugin
|
||||
|
||||
@@ -64,19 +146,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 | `<stdpath("data")>/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 | `<stdpath("data")>/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)
|
||||
|
||||
|
||||
@@ -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 `<stdpath("data")>/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
|
||||
`<stdpath("data")>/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. `<stdpath("data")>/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-<version>-<target>.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: `<prefix>/bin` + `<prefix>/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=<token>`), 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-<os>-<arch>`)**:
|
||||
- *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
|
||||
`<stdpath("data")>/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.
|
||||
+129
-22
@@ -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 `<repo>/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-<version>-<os>-<arch>.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 <version>`, 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 <n>`, `-p <n>` | TCP port; `0` = ephemeral (the real port lands in `daemon.json`) |
|
||||
| `--host <addr>` | bind address (default `127.0.0.1`) |
|
||||
| `--host <addr>` | bind address (default `0.0.0.0` (all interfaces)) |
|
||||
| `--static-dir <p>` | 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
|
||||
`<prefix>/bin/pi2` with assets at `<prefix>/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. `<exe>/../share/pi2d/web/dist` — release layout: `<prefix>/bin/pi2` plus
|
||||
`<prefix>/share/pi2d/web/dist` (what the curl installer, Homebrew tap, and AUR `-bin` package install)
|
||||
2. `<exe>/web/dist` — portable unpacked directory (`pi2` next to its UI)
|
||||
3. `<repo>/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` | `<repo>/web/dist` | built web UI |
|
||||
| `PI2_STATIC_DIR` | install layout (`<prefix>/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 |
|
||||
@@ -124,13 +174,40 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
|
||||
| `PI2_WORKSPACE_HIDE_GHOSTS` | `1` | hide workspaces whose `cwd` no longer exists (session files are kept) |
|
||||
| `PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS` | `0` | hide workspaces outside `PI2_WORKSPACE_ROOTS` (opt-in: hides real repos outside `$HOME`) |
|
||||
| `PI2_WORKSPACE_STALE_DAYS` | `0` (= off) | hide workspaces idle for more than `n` days (opt-in: hides real repos) |
|
||||
| `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 <init>` for managed instances |
|
||||
| `PI2_CODING_AGENT_DIR` | `~/.pi/agent` | pi session storage (discovery) |
|
||||
| `PI2_PLUGIN_DIR` | `~/.local/share/nvim/lazy/pi2.nvim` | pi2.nvim checkout: `pi2 doctor` probes it and spawned instances prepend it to `runtimepath`; a leading `~/` is expanded |
|
||||
| `PI2_NVIM_BIN` | `nvim` | nvim binary for managed instances, resolved on the **daemon's** `PATH` (read once, at daemon start) |
|
||||
| `PI2_NVIM_INIT` | – (daemon-generated init) | unset ⇒ a generated minimal init that prepends `PI2_PLUGIN_DIR`/the discovered plugin; `user` ⇒ load the user's own nvim config (no `-u`); any other value ⇒ that file via `-u` |
|
||||
| `PI2_ENSURE_TIMEOUT_MS` | `10000` | how long `instance.ensure` waits for a spawned nvim to say `hello`; expiry answers `E_INSTANCE_STARTING` |
|
||||
| `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.
|
||||
|
||||
A spawned instance inherits the **daemon's** environment, not your shell's, so `PATH` is the
|
||||
service's. Each spawn writes the child's stdout/stderr to
|
||||
`PI2_STATE_DIR/instances/<instanceId>.log` (`0600`, appended per start); the last lines of that
|
||||
file are folded into `instance_state.reason`, which is what the console and `pi2 status` show when
|
||||
a workspace fails to open.
|
||||
|
||||
### 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 +301,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,11 +399,11 @@ object `{daemon, instances, resources, health}`.
|
||||
|
||||
| Check | Fails when | Warns when |
|
||||
|---|---|---|
|
||||
| `node` | < 22 | – |
|
||||
| `node` | < 20 (npm/Node install) | – (compiled binary reports `bundled bun <ver> — 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 <path>` |
|
||||
| `plugin` | `lua/pi/web/bridge.lua` not found | – |
|
||||
| `plugin` | `lua/pi/web/bridge.lua` not found | bridge present but `lua/pi/host.lua` missing — the daemon cannot spawn a workspace from the console |
|
||||
| `runtime-dir` | missing | mode not `0700` |
|
||||
| `cli-token` | mode not `0600` | missing (daemon not started yet) |
|
||||
| `socket` | `d.sock` missing (and no daemon) | missing but daemon answers |
|
||||
@@ -412,7 +490,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 +499,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 +514,26 @@ TimeoutStopSec=15
|
||||
WantedBy=default.target
|
||||
```
|
||||
|
||||
The `ExecStart` line adapts automatically to how `pi2` was invoked:
|
||||
- **Compiled binary install**: `<prefix>/bin/pi2 daemon --foreground` (invokes the compiled executable directly).
|
||||
- **npm / Node install**: `<nodePath> <scriptPath> 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 +594,29 @@ 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 `<exe>/../share/pi2d/web/dist`) or `<repo>/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` |
|
||||
|
||||
### Opening a project fails
|
||||
|
||||
Opening a workspace from the web console spawns a headless nvim on demand, so a broken spawn is
|
||||
what a failed “open” looks like. Work the symptoms in this order:
|
||||
|
||||
1. **`pi2 doctor` → `plugin warn`/`plugin fail`** (or a spawn error naming the plugin): install or
|
||||
update pi2.nvim. The daemon needs `lua/pi/host.lua`; the bridge alone is not enough.
|
||||
2. **`E_INSTANCE_UNAVAILABLE … failed to spawn nvim`**: the binary is not on the daemon's `PATH`
|
||||
(a service PATH is not your shell's). Point `PI2_NVIM_BIN` at an absolute nvim path and
|
||||
restart the daemon.
|
||||
3. **`… did not say hello within 10000ms`** (`E_INSTANCE_STARTING`): nvim started but the plugin
|
||||
never loaded. Read `$PI2_STATE_DIR/instances/<instanceId>.log` — `instance_state.reason`
|
||||
quotes its tail.
|
||||
+408
@@ -0,0 +1,408 @@
|
||||
# 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`<br>*(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`<br>*(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 / Manjaro** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh`<br>*(AUR `pi2d-bin` once AUR registration reopens)* | Standalone binary in `~/.local/lib/pi2d` + `~/.local/bin/pi2`. Package-manager channels are paused: the AUR is not accepting accounts, so the curl installer is the working path today. |
|
||||
| **NixOS** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh`<br>*(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`<br>`systemctl --user enable --now pi2.service`<br>`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:<br>`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`<br>`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 four 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)
|
||||
|
||||
> **AUR registration paused**: New user registration on the AUR is temporarily closed upstream (HTTP 503: "Registration on the AUR is paused while we deal with a wave of automated account creation..."). Until registration reopens and `pi2d-bin` can be submitted, the AUR channel is unavailable. Use **[Channel B: Standalone curl installer](#channel-b-standalone-curl-installer-no-node-required)** instead — it works on Arch today and `pi2 update`s with the same command.
|
||||
|
||||
```bash
|
||||
# (When AUR registration reopens)
|
||||
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 `<node> <scriptPath> 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 — when reopened)**:
|
||||
```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 — when reopened)**:
|
||||
```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 <version>`).
|
||||
- **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.
|
||||
@@ -69,6 +69,10 @@ The plugin dials the daemon (`<runtime>/d.sock`), sends `hello` first.
|
||||
|
||||
Plugin obligations:
|
||||
|
||||
- **`hello` requires `lua/pi/host.lua`.** A daemon-spawned instance is started as
|
||||
`nvim --headless … -u <init> -c 'lua require("pi.host").start()'`, so the host module is what
|
||||
answers on a spawned workspace. Without it the daemon cannot start a workspace from the web
|
||||
console (`pi2 doctor` reports `warn` when `bridgeFound` is true and `hostFound` is false).
|
||||
- **Subscribe before prompt**: the daemon calls `sub.subscribe` before forwarding a command; the plugin
|
||||
answers every new subscription with a `snapshot` (state + a tail of entries).
|
||||
- Throttle deltas: `text_delta`/`thinking_delta` coalesced to ≤30 fps (50 ms), `tool_execution_update` to 100 ms.
|
||||
@@ -85,6 +89,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 +161,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 |
|
||||
@@ -213,6 +235,34 @@ Routing:
|
||||
|
||||
Idempotency: `clientRequestId` is deduplicated for 5 minutes; replays return the original `ack`.
|
||||
|
||||
The daemon-owned write commands have fixed bodies:
|
||||
|
||||
| Command | Params | Response |
|
||||
|---|---|---|
|
||||
| `workspace.add` | `{cwd, alias?, name?, trust?}` | `{accepted, workspaceId, workspace}` |
|
||||
| `instance.ensure` | `{workspaceId}` | `{accepted, instance}` (`InstanceState`) |
|
||||
| `instance.shutdown` | `{workspaceId, mode?}` | `{accepted, workspaceId, mode}` |
|
||||
|
||||
`workspace.add` registers `cwd`, clears `hidden` and answers the same `WorkspaceInfo` row the list
|
||||
serves; `workspaceId` is `sha256(realpath(cwd)).slice(0,16)`. `name` is an alias for `alias` — when
|
||||
both are present `alias` wins, and a whitespace-only value of either is ignored, not stored. `cwd`
|
||||
must be an absolute path or begin with `~`/`~/`: the daemon expands exactly those two forms against
|
||||
its own home and never expands `~user/…`. Validation is ordered and each failure maps to one code:
|
||||
non-empty string, no NUL byte, absolute-or-`~` → `E_BAD_REQUEST`; `realpath` → `E_NOT_FOUND`;
|
||||
inside `PI2_WORKSPACE_ROOTS` → `E_FORBIDDEN`; a directory → `E_BAD_REQUEST`; readable, writable and
|
||||
executable → `E_FORBIDDEN`. The allowlist is applied to the canonical path, so a symlink inside the
|
||||
roots cannot escape them.
|
||||
|
||||
`instance.ensure` is the only way the daemon starts an nvim: it **spawns on demand** and is
|
||||
idempotent per `workspaceId` (concurrent calls coalesce into one spawn). A spawn that cannot happen
|
||||
answers `E_INSTANCE_UNAVAILABLE`; one that stays silent past `PI2_ENSURE_TIMEOUT_MS` (default
|
||||
10000) answers `E_INSTANCE_STARTING`. Both are retryable and repeated failures back off, so a client
|
||||
retries rather than treating them as permanent, and `instance_state.reason` carries the failure text
|
||||
(the summary plus the tail of the instance log) to show the user.
|
||||
|
||||
`instance.shutdown` stops the one managed instance for `workspaceId`; `mode` defaults to `drain`
|
||||
(`stop` is the abrupt form) and no session file is touched.
|
||||
|
||||
### 3.3 WS events
|
||||
|
||||
Client → server: `{"type":"subscribe","payload":{"workspaceId":"ws-1"}}` (workspace scope) or
|
||||
@@ -319,6 +369,11 @@ browser cmd(sessionId=s1)
|
||||
- On disconnect the daemon marks the instance `degraded`; sessions become `interrupted` when the instance
|
||||
reports process exit, or when the instance is restarted (epoch change).
|
||||
|
||||
Every relayed read also ensures: `workspace.query` (`sessions`, `entries`, `attention`, and
|
||||
`models` with a `workspaceId`) routes through the same `instance.ensure`, so a browser read can
|
||||
spawn nvim. `GET /api/v1/workspaces`, `GET /api/v1/sessions/recent` and the daemon-resolved
|
||||
`GET /api/v1/models` (no `workspaceId`) are the reads that never spawn.
|
||||
|
||||
## 6. Attention
|
||||
|
||||
- `pi2:attention_request` is broadcast to **every** client subscribed to that session and to the
|
||||
|
||||
@@ -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 |
|
||||
|
||||
+4
-2
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "@yuez/pi2d",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"type": "module",
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
# 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` (when AUR registration reopens) |
|
||||
|
||||
### Shared Tarball Layout Contract
|
||||
|
||||
All distribution channels consume the release tarballs published on GitHub Releases:
|
||||
```
|
||||
https://github.com/zgs225/pi2d/releases/download/v<VERSION>/pi2d-<VERSION>-<target>.tar.gz
|
||||
```
|
||||
Where `<target>` 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 `<prefix>/bin` and `share/pi2d/web/dist` into
|
||||
`<prefix>/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`)
|
||||
|
||||
> **Note on AUR registration**: Account registration on [aur.archlinux.org](https://aur.archlinux.org) is
|
||||
> temporarily paused upstream (HTTP 503: "Registration on the AUR is paused while we deal with a
|
||||
> wave of automated account creation..."). AUR remains the intended canonical upstream channel for
|
||||
> Arch users once registration reopens. In the interim, Arch users install with the curl
|
||||
> installer (see `docs/install.md`, Channel B) — it is the only package path that works today.
|
||||
|
||||
Once registration reopens:
|
||||
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 <VERSION> --checksums dist-bin/SHA256SUMS --out build/packaging
|
||||
```
|
||||
3. **Homebrew**: the generated `build/packaging/pi2d.rb` is committed and pushed to `Formula/pi2d.rb` in
|
||||
the `zgs225/homebrew-tap` repository.
|
||||
4. **Arch AUR (`pi2d-bin`)**:
|
||||
- Once AUR registration reopens, the generated `build/packaging/PKGBUILD` and
|
||||
`build/packaging/.SRCINFO` will be committed and pushed to the `pi2d-bin` AUR repository.
|
||||
|
||||
## Local Regeneration & Building
|
||||
|
||||
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).
|
||||
@@ -0,0 +1,41 @@
|
||||
# Maintainer: zgs225 <zgs225@gmail.com>
|
||||
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"
|
||||
}
|
||||
@@ -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
|
||||
Executable
+109
@@ -0,0 +1,109 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# Boot check for a built `pi2` artifact.
|
||||
#
|
||||
# sh scripts/boot-check.sh <path-to-pi2> [expected-version]
|
||||
#
|
||||
# Starts the daemon on an ephemeral port with throwaway runtime/data/state
|
||||
# directories, waits for the single stdout line, asserts `/api/v1/info` answers
|
||||
# with protocol v1 (and the expected version), then sends SIGTERM and requires a
|
||||
# clean exit 0.
|
||||
#
|
||||
# POSIX `sh` on purpose: this script also runs inside an Alpine container, where
|
||||
# it validates the `-musl` artifacts (Bun's musl binaries need musl's libstdc++,
|
||||
# which the Ubuntu runners do not have, so they must be executed on Alpine).
|
||||
# Only `curl` and a shell are required; no `jq`, no Node, no Python.
|
||||
set -eu
|
||||
|
||||
BIN="${1:-}"
|
||||
EXPECTED_VERSION="${2:-}"
|
||||
|
||||
if [ -z "$BIN" ] || [ ! -x "$BIN" ]; then
|
||||
echo "usage: boot-check.sh <path-to-pi2> [expected-version]" >&2
|
||||
echo " (missing or not executable: '${BIN}')" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
pass() {
|
||||
printf 'PASS %s\n' "$1"
|
||||
}
|
||||
|
||||
TMP="$(mktemp -d "${TMPDIR:-/tmp}/pi2-boot.XXXXXX")"
|
||||
PID=""
|
||||
cleanup() {
|
||||
if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
|
||||
kill -TERM "$PID" 2>/dev/null || true
|
||||
wait "$PID" 2>/dev/null || true
|
||||
fi
|
||||
rm -rf "$TMP"
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
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
|
||||
mkdir -p "$PI2_RUNTIME_DIR" "$PI2_DATA_DIR" "$PI2_STATE_DIR"
|
||||
|
||||
"$BIN" daemon --port 0 >"$TMP/stdout.log" 2>"$TMP/daemon.log" &
|
||||
PID=$!
|
||||
|
||||
i=0
|
||||
while [ "$i" -lt 200 ]; do
|
||||
if grep -q "listening on http://" "$TMP/stdout.log" 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
kill -0 "$PID" 2>/dev/null || break
|
||||
i=$((i + 1))
|
||||
sleep 0.1
|
||||
done
|
||||
|
||||
if ! grep -q "listening on http://" "$TMP/stdout.log" 2>/dev/null; then
|
||||
echo "FAIL daemon did not reach 'listening on http://'" >&2
|
||||
echo "--- stdout ---" >&2
|
||||
cat "$TMP/stdout.log" >&2 || true
|
||||
echo "--- stderr ---" >&2
|
||||
cat "$TMP/daemon.log" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
pass "daemon started and printed one listening line"
|
||||
|
||||
PORT="$(sed -n 's/.*"port": *\([0-9][0-9]*\).*/\1/p' "$PI2_RUNTIME_DIR/daemon.json" | head -n 1)"
|
||||
if [ -z "${PORT:-}" ]; then
|
||||
echo "FAIL could not read the bound port from daemon.json" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
INFO="$(curl -fsS "http://127.0.0.1:$PORT/api/v1/info")" || {
|
||||
echo "FAIL GET /api/v1/info did not answer" >&2
|
||||
exit 1
|
||||
}
|
||||
case "$INFO" in
|
||||
*'"v":1'*) pass "GET /api/v1/info reports protocol v1" ;;
|
||||
*)
|
||||
echo "FAIL /api/v1/info does not report \"v\":1: $INFO" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -n "$EXPECTED_VERSION" ]; then
|
||||
case "$INFO" in
|
||||
*"\"version\":\"$EXPECTED_VERSION\""*) pass "reported version is $EXPECTED_VERSION" ;;
|
||||
*)
|
||||
echo "FAIL expected version $EXPECTED_VERSION in: $INFO" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
kill -TERM "$PID" 2>/dev/null || true
|
||||
set +e
|
||||
wait "$PID" 2>/dev/null
|
||||
EXIT_CODE=$?
|
||||
set -e
|
||||
PID=""
|
||||
if [ "$EXIT_CODE" -ne 0 ]; then
|
||||
echo "FAIL daemon exited $EXIT_CODE after SIGTERM (expected 0)" >&2
|
||||
exit 1
|
||||
fi
|
||||
pass "SIGTERM -> clean exit 0"
|
||||
Executable
+195
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Build a standalone binary distribution of pi2d.
|
||||
#
|
||||
# Produces:
|
||||
# <output-dir>/bin/pi2
|
||||
# <output-dir>/share/pi2d/web/dist/...
|
||||
# <output-dir>/LICENSE
|
||||
# <output-dir>/pi2d-<version>-<os>-<arch>.tar.gz
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/build-binary.sh [flags]
|
||||
#
|
||||
# Flags:
|
||||
# --target <bun-target> Cross-compile target (e.g. bun-linux-x64, bun-darwin-arm64)
|
||||
# --version <v> Release version (default: version from package.json)
|
||||
# --output-dir <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 <<EOF
|
||||
Usage: $0 [options]
|
||||
|
||||
Options:
|
||||
--target <target> Bun compilation target (default: host target)
|
||||
Supported: linux-x64, linux-arm64, linux-x64-musl,
|
||||
linux-arm64-musl, darwin-x64, darwin-arm64
|
||||
--version <version> Version string (default: package.json version)
|
||||
--output-dir <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
|
||||
Executable
+543
@@ -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=<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=<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
|
||||
Executable
+303
@@ -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 <method> <path> [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 '<title>' "$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"
|
||||
+6
-4
@@ -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")"
|
||||
|
||||
@@ -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]);
|
||||
|
||||
Executable
+302
@@ -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"
|
||||
@@ -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;
|
||||
}
|
||||
+45
-8
@@ -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,14 @@ 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
|
||||
Managed instances:
|
||||
PI2_NVIM_BIN=<path> nvim binary on the daemon's PATH (default nvim)
|
||||
PI2_NVIM_INIT=<file> -u <file>; "user" loads your own config; unset = generated init
|
||||
PI2_PLUGIN_DIR=<dir> pi2.nvim checkout the generated init prepends
|
||||
PI2_ENSURE_TIMEOUT_MS=<n> spawn hello timeout in ms (default 10000)
|
||||
|
||||
Runtime files ($PI2_RUNTIME_DIR):
|
||||
d.sock plugin unix socket (nvim → daemon)
|
||||
@@ -112,10 +117,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 +208,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 +236,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();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+242
-12
@@ -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 { daemonSocketPath, expandTilde, 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,13 +57,21 @@ 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;
|
||||
plugin: { dir: string | undefined; bridgeFound: boolean };
|
||||
plugin: { dir: string | undefined; bridgeFound: boolean; hostFound?: boolean };
|
||||
runtime: { path: string; exists: boolean; mode: number | undefined };
|
||||
cliToken: { path: string; exists: boolean; mode: number | undefined };
|
||||
socket: { path: string; exists: boolean };
|
||||
@@ -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);
|
||||
@@ -159,7 +182,16 @@ export function checkCurl(probe: BinaryProbe): DoctorCheck {
|
||||
|
||||
export function checkPlugin(probe: DoctorContext["plugin"]): DoctorCheck {
|
||||
if (probe.bridgeFound) {
|
||||
return { name: "plugin", status: "ok", detail: `${probe.dir ?? "pi2.nvim"} (lua/pi/web/bridge.lua)` };
|
||||
// The daemon spawns headless hosts with `lua require("pi.host").start()`,
|
||||
// so a plugin without `lua/pi/host.lua` cannot serve the web console.
|
||||
if (probe.hostFound === true) {
|
||||
return { name: "plugin", status: "ok", detail: `${probe.dir ?? "pi2.nvim"} (pi2.nvim host-capable)` };
|
||||
}
|
||||
return {
|
||||
name: "plugin",
|
||||
status: "warn",
|
||||
detail: `pi2.nvim at ${probe.dir ?? "~/.local/share/nvim/lazy/pi2.nvim"} has no lua/pi/host.lua — update the plugin; the daemon cannot start a workspace from the web console`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
name: "plugin",
|
||||
@@ -252,6 +284,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 +473,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 +486,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 +538,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 }> {
|
||||
@@ -393,6 +595,13 @@ async function binaryProbe(command: string, args: readonly string[], options: Do
|
||||
return { found: true, path, version };
|
||||
}
|
||||
|
||||
/** `PI2_PLUGIN_DIR` → plugin root; `~`/`~/…` expand against the resolved home. */
|
||||
function pluginHome(raw: string | undefined, home: string): string {
|
||||
const configured = raw?.trim();
|
||||
if (configured === undefined || configured === "") return join(home, ".local", "share", "nvim", "lazy", "pi2.nvim");
|
||||
return expandTilde(configured, home) ?? configured;
|
||||
}
|
||||
|
||||
export async function collectContext(options: DoctorOptions = {}): Promise<DoctorContext> {
|
||||
const env = options.env ?? process.env;
|
||||
const platform = options.platform ?? osPlatform();
|
||||
@@ -409,8 +618,9 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
|
||||
const pi = await binaryProbe("pi", ["--version"], options, env);
|
||||
const curl = await binaryProbe("curl", ["--version"], options, env);
|
||||
|
||||
const pluginDir = env.PI2_PLUGIN_DIR?.trim() || join(home, ".local", "share", "nvim", "lazy", "pi2.nvim");
|
||||
const pluginDir = pluginHome(env.PI2_PLUGIN_DIR, home);
|
||||
const bridgeFound = existsSync(join(pluginDir, "lua", "pi", "web", "bridge.lua"));
|
||||
const hostFound = existsSync(join(pluginDir, "lua", "pi", "host.lua"));
|
||||
|
||||
const runtimeStat = statOrUndefined(runtime);
|
||||
const cliTokenPath = join(runtime, "cli.token");
|
||||
@@ -456,13 +666,32 @@ 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,
|
||||
plugin: { dir: pluginDir, bridgeFound },
|
||||
plugin: { dir: pluginDir, bridgeFound, hostFound },
|
||||
runtime: { path: runtime, exists: runtimeStat.exists, mode: runtimeStat.mode },
|
||||
cliToken: { path: cliTokenPath, exists: tokenStat.exists, mode: tokenStat.mode },
|
||||
socket: { path: socketPath, exists: existsSync(socketPath) },
|
||||
@@ -471,6 +700,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()) },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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")) {
|
||||
|
||||
+55
-7
@@ -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>",
|
||||
|
||||
+3
-9
@@ -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 {
|
||||
|
||||
+4
-8
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
+32
-5
@@ -28,6 +28,18 @@ export function stateDir(): string {
|
||||
return join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "pi2");
|
||||
}
|
||||
|
||||
/**
|
||||
* `~` → `home`, `~/…` → `home/…`, `~user/…` → `undefined` (never expanded),
|
||||
* anything else unchanged. Shared by the workspace allowlist and the plugin
|
||||
* probe so both accept exactly the same shorthand.
|
||||
*/
|
||||
export function expandTilde(raw: string, home: string = homedir()): string | undefined {
|
||||
if (raw === "~") return home;
|
||||
if (raw.startsWith("~/")) return join(home, raw.slice(2));
|
||||
if (raw.startsWith("~")) return undefined;
|
||||
return raw;
|
||||
}
|
||||
|
||||
export function ensureDir(path: string, mode = 0o700): string {
|
||||
if (!existsSync(path)) mkdirSync(path, { recursive: true, mode });
|
||||
return path;
|
||||
@@ -47,13 +59,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 {
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* Where the pi2.nvim plugin lives on disk.
|
||||
*
|
||||
* The daemon spawns `nvim --headless -u <generated init>` and that init must be
|
||||
* able to `require("pi.host")`. Getting this wrong is invisible from the daemon
|
||||
* side: nvim stays alive, prints into a log nobody reads, and the browser only
|
||||
* sees a 10 s "did not say hello" timeout. So plugin discovery is a first-class
|
||||
* probe with an explicit, ordered candidate list and a human failure line — used
|
||||
* by the supervisor (spawn refusal) and by `pi2 doctor`.
|
||||
*
|
||||
* A directory counts as a plugin only when it is *host-capable*: it must ship
|
||||
* both `lua/pi/host.lua` (the daemon bridge entry point) and
|
||||
* `lua/pi/web/bridge.lua` (the session bridge). Older checkouts that only carry
|
||||
* one of the two are reported, never silently used, because `host.start()`
|
||||
* would fail again on the next `require`.
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, type Dirent } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { expandTilde } from "./paths.js";
|
||||
|
||||
/** Directory name the plugin is installed under (lazy.nvim, pack/*\/start, …). */
|
||||
export const PLUGIN_NAME = "pi2.nvim";
|
||||
|
||||
/** Entry points that every usable plugin checkout must contain. */
|
||||
export const PLUGIN_HOST_FILE = join("lua", "pi", "host.lua");
|
||||
export const PLUGIN_BRIDGE_FILE = join("lua", "pi", "web", "bridge.lua");
|
||||
|
||||
/** One explored location, classified against the host-capability contract. */
|
||||
export interface PluginDirCandidate {
|
||||
dir: string;
|
||||
reason: "ok" | "missing-host" | "missing-bridge" | "absent";
|
||||
}
|
||||
|
||||
/** A confirmed host-capable plugin checkout. */
|
||||
export interface ResolvedPlugin {
|
||||
dir: string;
|
||||
host: string;
|
||||
bridge: string;
|
||||
}
|
||||
|
||||
export type PluginResolution =
|
||||
| { plugin: ResolvedPlugin }
|
||||
| {
|
||||
plugin: undefined;
|
||||
candidates: PluginDirCandidate[];
|
||||
/** The `PI2_PLUGIN_DIR` value that was probed first, if any. */
|
||||
configured: string | undefined;
|
||||
};
|
||||
|
||||
type Readdir = (dir: string, options: { withFileTypes: true }) => Dirent[];
|
||||
|
||||
export interface ResolvePluginDirOptions {
|
||||
/** Defaults to `process.env` (`PI2_PLUGIN_DIR` is read from it). */
|
||||
env?: Record<string, string | undefined>;
|
||||
/** Defaults to `homedir()`; also used to expand a leading `~/`. */
|
||||
home?: string;
|
||||
/** Defaults to `existsSync`; injected in tests to stay hermetic. */
|
||||
exists?: (path: string) => boolean;
|
||||
/** Defaults to `readdirSync`; enumerates `site/pack/*\/{start,opt}`. */
|
||||
readdir?: Readdir;
|
||||
}
|
||||
|
||||
const defaultReaddir: Readdir = (dir, options) => readdirSync(dir, options);
|
||||
|
||||
/**
|
||||
* `site/pack/<name>/{start,opt}/pi2.nvim` for one nvim data directory.
|
||||
*
|
||||
* `readdir` must never throw here: a stock nvim has no `site/pack` at all, and a
|
||||
* missing directory is the normal case, not an error worth surfacing.
|
||||
*/
|
||||
function packCandidates(dataDir: string, readdir: Readdir): string[] {
|
||||
const root = join(dataDir, "site", "pack");
|
||||
let entries: Dirent[];
|
||||
try {
|
||||
entries = readdir(root, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const dirs: string[] = [];
|
||||
for (const kind of ["start", "opt"] as const) {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
dirs.push(join(root, entry.name, kind, PLUGIN_NAME));
|
||||
}
|
||||
}
|
||||
return dirs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordered list of directories that could hold the plugin.
|
||||
*
|
||||
* `PI2_PLUGIN_DIR` first (explicit user intent beats discovery), then the
|
||||
* lazy.nvim default, then `pack/*\/start` before `pack/*\/opt` (start packages
|
||||
* are the ones that are actually loaded at startup), user data dir before the
|
||||
* system-wide ones.
|
||||
*/
|
||||
export function pluginDirCandidates(options: ResolvePluginDirOptions = {}): string[] {
|
||||
const env = options.env ?? process.env;
|
||||
const home = options.home ?? homedir();
|
||||
const readdir = options.readdir ?? defaultReaddir;
|
||||
|
||||
const dirs: string[] = [];
|
||||
const configured = env.PI2_PLUGIN_DIR?.trim();
|
||||
if (configured !== undefined && configured !== "") {
|
||||
dirs.push(resolve(expandTilde(configured, home) ?? configured));
|
||||
}
|
||||
|
||||
const userNvim = join(home, ".local", "share", "nvim");
|
||||
dirs.push(join(userNvim, "lazy", PLUGIN_NAME));
|
||||
for (const dataDir of [userNvim, "/usr/share/nvim", "/usr/local/share/nvim"]) {
|
||||
dirs.push(...packCandidates(dataDir, readdir));
|
||||
}
|
||||
|
||||
// `PI2_PLUGIN_DIR` may name the same directory lazy.nvim would have found;
|
||||
// keep the first occurrence so the reported order matches the probe order.
|
||||
return [...new Set(dirs)];
|
||||
}
|
||||
|
||||
/** Classifies one directory; a match needs BOTH entry points. */
|
||||
export function classifyPluginDir(
|
||||
dir: string,
|
||||
exists: (path: string) => boolean = existsSync,
|
||||
): PluginDirCandidate {
|
||||
if (!exists(dir)) return { dir, reason: "absent" };
|
||||
if (!exists(join(dir, PLUGIN_HOST_FILE))) return { dir, reason: "missing-host" };
|
||||
if (!exists(join(dir, PLUGIN_BRIDGE_FILE))) return { dir, reason: "missing-bridge" };
|
||||
return { dir, reason: "ok" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first host-capable plugin checkout.
|
||||
*
|
||||
* Returns the winning `ResolvedPlugin` or every candidate with its verdict, so
|
||||
* the caller can explain *why* nothing matched instead of shouting "not found"
|
||||
* at a user whose lazy.nvim simply has not installed the plugin yet.
|
||||
*/
|
||||
export function resolvePluginDir(options: ResolvePluginDirOptions = {}): PluginResolution {
|
||||
const home = options.home ?? homedir();
|
||||
const exists = options.exists ?? existsSync;
|
||||
const candidates = pluginDirCandidates({ ...options, home }).map((dir) => classifyPluginDir(dir, exists));
|
||||
const match = candidates.find((candidate) => candidate.reason === "ok");
|
||||
if (match === undefined) {
|
||||
const configured = (options.env ?? process.env).PI2_PLUGIN_DIR?.trim();
|
||||
return {
|
||||
plugin: undefined,
|
||||
candidates: [...candidates],
|
||||
configured: configured === undefined || configured === "" ? undefined : candidates[0]?.dir,
|
||||
};
|
||||
}
|
||||
return {
|
||||
plugin: {
|
||||
dir: match.dir,
|
||||
host: join(match.dir, PLUGIN_HOST_FILE),
|
||||
bridge: join(match.dir, PLUGIN_BRIDGE_FILE),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Collapses the home directory to `~` so messages stay readable. */
|
||||
export function displayPath(path: string, home: string = homedir()): string {
|
||||
if (path === home) return "~";
|
||||
const prefix = `${home}/`;
|
||||
if (path.startsWith(prefix)) return `~/${path.slice(prefix.length)}`;
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* One human line explaining a failed plugin resolution.
|
||||
*
|
||||
* An explicitly configured `PI2_PLUGIN_DIR` is named first: a typo there is the
|
||||
* one failure the user can fix in seconds, and blaming a stale lazy.nvim
|
||||
* checkout instead sends them looking in the wrong place.
|
||||
*
|
||||
* Failing that, a stale checkout (present, but without `host.lua`/`bridge.lua`)
|
||||
* is the case users hit after a plugin update and the one a bare "not found"
|
||||
* hides, so it is reported before the generic message.
|
||||
*/
|
||||
export function describePluginFailure(
|
||||
candidates: readonly PluginDirCandidate[],
|
||||
options: { configured?: string | undefined } = {},
|
||||
): string {
|
||||
const home = homedir();
|
||||
const configured =
|
||||
options.configured === undefined
|
||||
? undefined
|
||||
: candidates.find((candidate) => candidate.dir === options.configured);
|
||||
if (configured !== undefined && configured.reason !== "ok") {
|
||||
const path = displayPath(configured.dir, home);
|
||||
if (configured.reason === "absent") return `PI2_PLUGIN_DIR=${path} does not exist`;
|
||||
const what = configured.reason === "missing-host" ? PLUGIN_HOST_FILE : PLUGIN_BRIDGE_FILE;
|
||||
return `PI2_PLUGIN_DIR=${path} has no ${what} (update the plugin)`;
|
||||
}
|
||||
|
||||
const broken = candidates.find(
|
||||
(candidate) => candidate.reason === "missing-host" || candidate.reason === "missing-bridge",
|
||||
);
|
||||
if (broken !== undefined) {
|
||||
const what = broken.reason === "missing-host" ? PLUGIN_HOST_FILE : PLUGIN_BRIDGE_FILE;
|
||||
return `${PLUGIN_NAME} at ${displayPath(broken.dir, home)} has no ${what} (update the plugin)`;
|
||||
}
|
||||
const first = candidates[0];
|
||||
const seen = candidates.length === 0 ? "no locations" : `${candidates.length} location(s)`;
|
||||
return first === undefined
|
||||
? `no ${PLUGIN_NAME} plugin found (looked in ${seen})`
|
||||
: `no ${PLUGIN_NAME} plugin found (looked in ${seen}, first ${displayPath(first.dir, home)})`;
|
||||
}
|
||||
+19
-9
@@ -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");
|
||||
|
||||
@@ -261,11 +261,15 @@ export class CommandRouter {
|
||||
const input: { cwd: string; alias?: string; trust?: boolean } = {
|
||||
cwd: requireString(params, "cwd"),
|
||||
};
|
||||
const alias = optionalString(params, "alias");
|
||||
// `name` is the web dialog's field; it is an alias when `alias` is absent.
|
||||
// A whitespace-only value is dropped, exactly like an empty `alias`.
|
||||
const alias = optionalString(params, "alias") ?? optionalString(params, "name");
|
||||
if (alias !== undefined) input.alias = alias;
|
||||
if (typeof params.trust === "boolean") input.trust = params.trust;
|
||||
const workspace = await this.workspaces.add(input);
|
||||
return { accepted: true, workspace };
|
||||
// `workspace.workspaceId` is the documented location; the top-level
|
||||
// copy saves the web client a round trip on its fallback path.
|
||||
return { accepted: true, workspaceId: workspace.workspaceId, workspace };
|
||||
}
|
||||
case "workspace.update": {
|
||||
const workspaceId = requireString(params, "workspaceId");
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* The generated nvim init the daemon hands to every headless instance.
|
||||
*
|
||||
* Why this exists: a spawned `nvim --headless -u <user config>` only reaches the
|
||||
* daemon if the user's own config happens to load pi2.nvim and `pi.host`. With
|
||||
* lazy.nvim, a dev worktree behind `PI_DEV_DIR`, or a systemd unit with a frozen
|
||||
* `PATH`, it often does not — and the failure mode is a process that stays alive
|
||||
* and silent. A tiny generated init that (1) prepends the resolved plugin, (2)
|
||||
* keeps nvim from writing swap/shada state into the workspace and (3) `cquit 1`s
|
||||
* when the plugin cannot be loaded, turns that silence into a real exit code and
|
||||
* a log line the supervisor can read back.
|
||||
*
|
||||
* The init deliberately loads nothing else: `pi2 open` must work regardless of
|
||||
* the user's config, and the plugin's own `host.start()` owns the wait loop.
|
||||
*/
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
export const HOST_INIT_FILENAME = "host-init.lua";
|
||||
|
||||
/**
|
||||
* Written once per `(dir, pluginDir)` in the daemon's lifetime.
|
||||
*
|
||||
* Spawns are frequent (one per workspace, plus every crash/retry) while the init
|
||||
* only changes when the plugin directory changes, so a module-level memo keeps
|
||||
* the spawn path free of filesystem writes without needing a cache file.
|
||||
*/
|
||||
const written = new Map<string, string>();
|
||||
|
||||
/** Lua double-quoted string literal: backslash, quote and control chars only. */
|
||||
export function luaString(value: string): string {
|
||||
const escaped = value
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/\n/g, "\\n")
|
||||
.replace(/\r/g, "\\r")
|
||||
.replace(/\t/g, "\\t");
|
||||
return `"${escaped}"`;
|
||||
}
|
||||
|
||||
/** Pure renderer (exported so tests and diagnostics can assert the content). */
|
||||
export function renderHostInit(pluginDir: string): string {
|
||||
return [
|
||||
"-- Generated by pi2d (pi2 daemon). Do not edit: rewritten on spawn.",
|
||||
`-- plugin: ${pluginDir}`,
|
||||
"--",
|
||||
"-- Minimal init for a daemon-managed instance: the user config is NOT",
|
||||
"-- loaded, so a broken/slow/lazy config can never hide the plugin again.",
|
||||
"",
|
||||
`vim.opt.runtimepath:prepend(${luaString(pluginDir)})`,
|
||||
"vim.opt.swapfile = false",
|
||||
'vim.opt.shadafile = "NONE"',
|
||||
'vim.g.mapleader = " "',
|
||||
"",
|
||||
'local ok, host = pcall(require, "pi.host")',
|
||||
"if not ok then",
|
||||
' vim.api.nvim_err_writeln("pi2: " .. tostring(host))',
|
||||
' vim.cmd("cquit 1")',
|
||||
"else",
|
||||
" host.start()",
|
||||
"end",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes `<dir>/host-init.lua` for `pluginDir` and returns its absolute path.
|
||||
*
|
||||
* Atomic rename keeps a half-written init from ever reaching a concurrently
|
||||
* spawning nvim; comparing before writing keeps the file's mtime (and therefore
|
||||
* anything watching it) stable across daemon restarts.
|
||||
*/
|
||||
export async function writeHostInit(options: { dir: string; pluginDir: string }): Promise<string> {
|
||||
const dir = resolve(options.dir);
|
||||
const pluginDir = resolve(options.pluginDir);
|
||||
const key = `${dir}\u0000${pluginDir}`;
|
||||
const cached = written.get(key);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
const content = renderHostInit(pluginDir);
|
||||
const path = join(dir, HOST_INIT_FILENAME);
|
||||
await mkdir(dir, { recursive: true, mode: 0o700 });
|
||||
|
||||
let existing: string | undefined;
|
||||
try {
|
||||
existing = await readFile(path, "utf8");
|
||||
} catch {
|
||||
existing = undefined;
|
||||
}
|
||||
if (existing !== content) {
|
||||
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await writeFile(tmp, content, { mode: 0o600 });
|
||||
await rename(tmp, path);
|
||||
} catch (error) {
|
||||
await unlink(tmp).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
written.set(key, path);
|
||||
return path;
|
||||
}
|
||||
|
||||
/** Test seam: forget every memoized path. */
|
||||
export function resetHostInitCache(): void {
|
||||
written.clear();
|
||||
}
|
||||
@@ -16,10 +16,12 @@ export type { PluginHello, SnapshotCacheEntry, PluginSocketConnectionOptions } f
|
||||
export {
|
||||
createInstanceManager,
|
||||
ManagedInstanceManager,
|
||||
parseEnsureTimeoutMs,
|
||||
parseProcRss,
|
||||
parsePsRss,
|
||||
summarizeResources,
|
||||
DEFAULT_ENSURE_TIMEOUT_MS,
|
||||
DEFAULT_LOG_TAIL_LINES,
|
||||
DEFAULT_MAX_INSTANCES,
|
||||
DEFAULT_RSS_FRACTION,
|
||||
DEFAULT_SHUTDOWN_GRACE_MS,
|
||||
@@ -27,4 +29,5 @@ export {
|
||||
DEFAULT_MIN_SPAWN_INTERVAL_MS,
|
||||
} from "./supervisor.js";
|
||||
export type { InstanceManagerDeps, InstanceManagerHandle, SpawnFunction } from "./supervisor.js";
|
||||
export { HOST_INIT_FILENAME, luaString, renderHostInit, writeHostInit } from "./host-init.js";
|
||||
export { InstanceError, TIMEOUT_CODE, asInstanceError, errorMessage } from "./errors.js";
|
||||
+320
-28
@@ -11,6 +11,7 @@
|
||||
|
||||
import { execFile, spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { closeSync, openSync } from "node:fs";
|
||||
import { appendFile, mkdir, readFile } from "node:fs/promises";
|
||||
import { totalmem } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
@@ -30,15 +31,27 @@ import {
|
||||
runtimeDir,
|
||||
stateDir,
|
||||
} from "../core/paths.js";
|
||||
import { describePluginFailure, resolvePluginDir, type PluginResolution } from "../core/plugin.js";
|
||||
import { ERROR_CODES } from "../protocol/errors.js";
|
||||
import { PROTOCOL_VERSION, type InstanceState } from "../protocol/types.js";
|
||||
import { PluginSocketConnection, type PluginHello } from "./connection.js";
|
||||
import { InstanceError, asInstanceError, errorMessage } from "./errors.js";
|
||||
import { writeHostInit } from "./host-init.js";
|
||||
import { PluginServer, type PluginServerOptions, type PluginServerRejection } from "./plugin-server.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export const DEFAULT_ENSURE_TIMEOUT_MS = 5_000;
|
||||
/**
|
||||
* How long `ensure()` waits for the plugin `hello` by default.
|
||||
*
|
||||
* 10 s, not 5 s: the generated host init starts a *config-less* headless nvim,
|
||||
* but a cold disk cache plus a large plugin directory can still take a few
|
||||
* seconds, and a false timeout looks exactly like a broken plugin from the
|
||||
* browser's point of view. `PI2_ENSURE_TIMEOUT_MS` overrides it.
|
||||
*/
|
||||
export const DEFAULT_ENSURE_TIMEOUT_MS = 10_000;
|
||||
/** Lines of the instance log quoted back on a failed spawn/timeout. */
|
||||
export const DEFAULT_LOG_TAIL_LINES = 40;
|
||||
export const DEFAULT_SHUTDOWN_GRACE_MS = 5_000;
|
||||
export const DEFAULT_SIGTERM_GRACE_MS = 2_000;
|
||||
export const DEFAULT_MIN_SPAWN_INTERVAL_MS = 2_000;
|
||||
@@ -66,6 +79,16 @@ export interface InstanceManagerDeps {
|
||||
logDir?: string;
|
||||
nvimBin?: string;
|
||||
nvimInit?: string;
|
||||
/** Explicit plugin checkout; beats discovery (same effect as `PI2_PLUGIN_DIR`). */
|
||||
pluginDir?: string;
|
||||
/** Where the generated host init lives; defaults to `${stateDir()}/host-init`. */
|
||||
hostInitDir?: string;
|
||||
writeHostInit?: typeof writeHostInit;
|
||||
/** Injectable plugin discovery (defaults to `resolvePluginDir`). */
|
||||
resolvePlugin?: () => PluginResolution;
|
||||
/** Lines of `<instance>.log` quoted on failure; defaults to 40. */
|
||||
logTailLines?: number;
|
||||
readLogTail?: (path: string, lines: number) => Promise<string[]>;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
spawnFn?: SpawnFunction;
|
||||
instanceSocketPath?: (workspaceId: string, instanceId: string) => string;
|
||||
@@ -95,7 +118,7 @@ interface SpawnWaiter {
|
||||
promise: Promise<PluginSocketConnection>;
|
||||
settle(connection: PluginSocketConnection): void;
|
||||
fail(error: InstanceError): void;
|
||||
attach(child: ChildProcess, logPath: string): void;
|
||||
attach(child: ChildProcess, logPath: string, init: SpawnInit | undefined): void;
|
||||
cancel(reason: string): void;
|
||||
}
|
||||
|
||||
@@ -104,6 +127,31 @@ interface SpawnFailure {
|
||||
nextAllowedAt: number;
|
||||
}
|
||||
|
||||
/** Which `-u` this spawn used, recorded so failures can name their inputs. */
|
||||
interface SpawnInit {
|
||||
/** `undefined` means "no `-u`" (the user's own config, or none at all). */
|
||||
path: string | undefined;
|
||||
pluginDir: string | undefined;
|
||||
}
|
||||
|
||||
/** A failed spawn reduced to what a browser can show and a log can keep. */
|
||||
interface SpawnDiagnostics {
|
||||
/** Single line for `InstanceState.reason` (goes out through `instance_state`). */
|
||||
reason: string;
|
||||
/** Multi-line form (summary + log tail) for the thrown `InstanceError`. */
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads `PI2_ENSURE_TIMEOUT_MS`; `undefined` for unset or invalid values so the
|
||||
* caller can warn instead of silently running with a nonsense timeout.
|
||||
*/
|
||||
export function parseEnsureTimeoutMs(raw: string | undefined): number | undefined {
|
||||
if (raw === undefined || raw.trim() === "") return undefined;
|
||||
const value = Number(raw.trim());
|
||||
return Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
/** `VmRSS: 123456 kB` from `/proc/<pid>/status` → bytes. */
|
||||
export function parseProcRss(status: string): number | null {
|
||||
const match = /^\s*VmRSS:\s+(\d+)\s+kB\s*$/m.exec(status);
|
||||
@@ -200,8 +248,16 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
private readonly tokenPath: string;
|
||||
private readonly runtime: string;
|
||||
private readonly logDir: string;
|
||||
private readonly hostInitDir: string;
|
||||
private readonly nvimBin: string;
|
||||
private readonly nvimInit: string | undefined;
|
||||
/** `PI2_NVIM_INIT=user`: spawn with no `-u`, i.e. the user's own config. */
|
||||
private readonly useUserConfig: boolean;
|
||||
private readonly pluginDir: string | undefined;
|
||||
private readonly writeHostInit: (options: { dir: string; pluginDir: string }) => Promise<string>;
|
||||
private readonly resolvePlugin: () => PluginResolution;
|
||||
private readonly logTailLines: number;
|
||||
private readonly readLogTail: (path: string, lines: number) => Promise<string[]>;
|
||||
private readonly spawnFn: SpawnFunction;
|
||||
private readonly instanceSocketPath: (workspaceId: string, instanceId: string) => string;
|
||||
private readonly readRss: (pid: number) => Promise<number | null>;
|
||||
@@ -233,14 +289,40 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
this.tokenPath = deps.tokenPath ?? daemonTokenPath();
|
||||
this.runtime = deps.runtime ?? runtimeDir();
|
||||
this.logDir = deps.logDir ?? join(stateDir(), "instances");
|
||||
this.hostInitDir = deps.hostInitDir ?? join(stateDir(), "host-init");
|
||||
this.nvimBin = deps.nvimBin ?? process.env.PI2_NVIM_BIN ?? "nvim";
|
||||
const init = deps.nvimInit ?? process.env.PI2_NVIM_INIT;
|
||||
this.nvimInit = init !== undefined && init !== "" ? init : undefined;
|
||||
// Three-way init choice (see `resolveNvimInit`): an explicit path wins,
|
||||
// the literal `user` opts back into today's "load my config" behaviour,
|
||||
// and anything else (including unset) uses the generated host init.
|
||||
const init = (deps.nvimInit ?? process.env.PI2_NVIM_INIT ?? "").trim();
|
||||
this.useUserConfig = init === "user";
|
||||
this.nvimInit = init === "" || this.useUserConfig ? undefined : init;
|
||||
this.pluginDir = deps.pluginDir?.trim() || undefined;
|
||||
this.writeHostInit = deps.writeHostInit ?? writeHostInit;
|
||||
this.resolvePlugin =
|
||||
deps.resolvePlugin ??
|
||||
(() => {
|
||||
const env: Record<string, string | undefined> = { ...process.env, ...(deps.env ?? {}) };
|
||||
if (this.pluginDir !== undefined) env.PI2_PLUGIN_DIR = this.pluginDir;
|
||||
return resolvePluginDir({ env });
|
||||
});
|
||||
this.logTailLines = deps.logTailLines ?? DEFAULT_LOG_TAIL_LINES;
|
||||
this.readLogTail = deps.readLogTail ?? defaultReadLogTail;
|
||||
this.spawnFn = deps.spawnFn ?? ((command, args, options) => spawn(command, args, options));
|
||||
this.instanceSocketPath = deps.instanceSocketPath ?? defaultInstanceSocketPath;
|
||||
this.readRss = deps.readRss ?? defaultReadRss;
|
||||
this.totalMemory = deps.totalMemory ?? totalmem;
|
||||
this.ensureTimeoutMs = deps.ensureTimeoutMs ?? DEFAULT_ENSURE_TIMEOUT_MS;
|
||||
const envTimeout = parseEnsureTimeoutMs(process.env.PI2_ENSURE_TIMEOUT_MS);
|
||||
if (
|
||||
deps.ensureTimeoutMs === undefined &&
|
||||
(process.env.PI2_ENSURE_TIMEOUT_MS ?? "").trim() !== "" &&
|
||||
envTimeout === undefined
|
||||
) {
|
||||
this.logger?.warn("ignoring invalid PI2_ENSURE_TIMEOUT_MS", {
|
||||
value: process.env.PI2_ENSURE_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
this.ensureTimeoutMs = deps.ensureTimeoutMs ?? envTimeout ?? DEFAULT_ENSURE_TIMEOUT_MS;
|
||||
this.shutdownGraceMs = deps.shutdownGraceMs ?? DEFAULT_SHUTDOWN_GRACE_MS;
|
||||
this.sigtermGraceMs = deps.sigtermGraceMs ?? DEFAULT_SIGTERM_GRACE_MS;
|
||||
this.minSpawnIntervalMs = deps.minSpawnIntervalMs ?? DEFAULT_MIN_SPAWN_INTERVAL_MS;
|
||||
@@ -463,14 +545,15 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
};
|
||||
this.setState(starting);
|
||||
|
||||
const waiter = this.createWaiter(workspaceId, timeoutMs);
|
||||
const waiter = this.createWaiter(workspaceId, timeoutMs, starting);
|
||||
let child: ChildProcess | undefined;
|
||||
try {
|
||||
const init = await this.resolveNvimInit();
|
||||
const args = [
|
||||
"--headless",
|
||||
"--listen",
|
||||
socketPath,
|
||||
...(this.nvimInit === undefined ? [] : ["-u", this.nvimInit]),
|
||||
...(init.path === undefined ? [] : ["-u", init.path]),
|
||||
"-c",
|
||||
'lua require("pi.host").start()',
|
||||
];
|
||||
@@ -482,17 +565,53 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
PI2_DAEMON_TOKEN_PATH: this.tokenPath,
|
||||
PI2_WORKSPACE_ID: workspaceId,
|
||||
};
|
||||
this.logger?.info("spawning instance", { workspaceId, instanceId, cwd, command: this.nvimBin, logPath });
|
||||
child = this.spawnFn(this.nvimBin, args, {
|
||||
// One line, no secrets: the four knobs that change how this spawn
|
||||
// behaves plus the argv we are about to hand nvim, because "which
|
||||
// -u did it pick" is the first question every report asks.
|
||||
this.logger?.info("spawning instance", {
|
||||
workspaceId,
|
||||
instanceId,
|
||||
cwd,
|
||||
env,
|
||||
stdio: "ignore",
|
||||
detached: true,
|
||||
command: this.nvimBin,
|
||||
args,
|
||||
init: init.path ?? "none",
|
||||
pluginDir: init.pluginDir ?? "none",
|
||||
logPath,
|
||||
env: {
|
||||
PI2_NVIM_BIN: process.env.PI2_NVIM_BIN ?? "",
|
||||
PI2_NVIM_INIT: process.env.PI2_NVIM_INIT ?? "",
|
||||
PI2_PLUGIN_DIR: process.env.PI2_PLUGIN_DIR ?? "",
|
||||
PI2_ENSURE_TIMEOUT_MS: String(this.ensureTimeoutMs),
|
||||
},
|
||||
});
|
||||
this.children.set(workspaceId, child);
|
||||
if (child.pid !== undefined) this.setState({ ...starting, nvimPid: child.pid });
|
||||
child.unref();
|
||||
waiter.attach(child, logPath);
|
||||
let logFd: number | undefined;
|
||||
try {
|
||||
ensureDir(this.logDir);
|
||||
// nvim's stderr is the only place a config/plugin error will ever
|
||||
// appear (`--headless` keeps it off the terminal), so route it into
|
||||
// the per-instance log instead of /dev/null.
|
||||
logFd = openSync(logPath, "a", 0o600);
|
||||
child = this.spawnFn(this.nvimBin, args, {
|
||||
cwd,
|
||||
env,
|
||||
stdio: ["ignore", logFd, logFd],
|
||||
detached: true,
|
||||
});
|
||||
this.children.set(workspaceId, child);
|
||||
if (child.pid !== undefined) this.setState({ ...starting, nvimPid: child.pid });
|
||||
child.unref();
|
||||
} finally {
|
||||
// The child holds its own duplicate; keeping ours open would leak an
|
||||
// fd per spawn. `detached: true` already keeps the child alive.
|
||||
if (logFd !== undefined) {
|
||||
try {
|
||||
closeSync(logFd);
|
||||
} catch {
|
||||
// already closed: the spawn-error path may have closed it
|
||||
}
|
||||
}
|
||||
}
|
||||
waiter.attach(child, logPath, init);
|
||||
|
||||
const connection = await waiter.promise;
|
||||
this.failures.delete(workspaceId);
|
||||
@@ -501,17 +620,24 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
return this.readyState(connection, this.states.get(workspaceId));
|
||||
} catch (error) {
|
||||
const failure = asInstanceError(error);
|
||||
// A refusal before spawn (e.g. no plugin found) leaves a waiter behind
|
||||
// that nobody will ever settle; drop it so `waiters` stays honest.
|
||||
waiter.cancel(failure.message);
|
||||
this.recordFailure(workspaceId);
|
||||
if (child !== undefined) {
|
||||
tryKill(child, "SIGKILL");
|
||||
if (this.children.get(workspaceId) === child) this.children.delete(workspaceId);
|
||||
}
|
||||
// Timeout/early-exit errors carry the single-line log summary in
|
||||
// `details.reason`; every other failure falls back to its message.
|
||||
const reason =
|
||||
typeof failure.details?.reason === "string" ? failure.details.reason : failure.message;
|
||||
this.setState({
|
||||
...(this.states.get(workspaceId) ?? starting),
|
||||
status: "stopped",
|
||||
nvimPid: null,
|
||||
attachedClients: 0,
|
||||
reason: failure.message,
|
||||
reason,
|
||||
});
|
||||
this.logger?.warn("instance failed to start", {
|
||||
workspaceId,
|
||||
@@ -523,9 +649,34 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
}
|
||||
}
|
||||
|
||||
private createWaiter(workspaceId: string, timeoutMs: number): SpawnWaiter {
|
||||
/**
|
||||
* Which `-u` this spawn gets.
|
||||
*
|
||||
* The default is the generated host init: spawning the *user's* config is
|
||||
* what made "open a project from the web console" fail silently, because the
|
||||
* plugin is only reachable if that config happens to load it. `-u` values and
|
||||
* `PI2_NVIM_INIT=user` remain as escape hatches. With no host-capable plugin
|
||||
* at all we refuse up front — a spawn with no plugin can only time out.
|
||||
*/
|
||||
private async resolveNvimInit(): Promise<SpawnInit> {
|
||||
if (this.nvimInit !== undefined) return { path: this.nvimInit, pluginDir: undefined };
|
||||
if (this.useUserConfig) return { path: undefined, pluginDir: undefined };
|
||||
|
||||
const resolution = this.resolvePlugin();
|
||||
if (resolution.plugin === undefined) {
|
||||
throw InstanceError.unavailable(
|
||||
`${describePluginFailure(resolution.candidates, { configured: resolution.configured })}; install/update pi2.nvim, ` +
|
||||
"set PI2_PLUGIN_DIR, or set PI2_NVIM_INIT=user to load your own config",
|
||||
);
|
||||
}
|
||||
const path = await this.writeHostInit({ dir: this.hostInitDir, pluginDir: resolution.plugin.dir });
|
||||
return { path, pluginDir: resolution.plugin.dir };
|
||||
}
|
||||
|
||||
private createWaiter(workspaceId: string, timeoutMs: number, base: InstanceState): SpawnWaiter {
|
||||
const manager = this;
|
||||
let settled = false;
|
||||
let diagnosing = false;
|
||||
let resolvePromise!: (connection: PluginSocketConnection) => void;
|
||||
let rejectPromise!: (error: Error) => void;
|
||||
|
||||
@@ -539,6 +690,10 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
let exited = false;
|
||||
// Set by `attach()`; the timer can fire before any child event, so the
|
||||
// diagnostics path needs to know which init this waiter belongs to.
|
||||
let attachedLogPath: string | undefined;
|
||||
let attachedInit: SpawnInit | undefined;
|
||||
|
||||
const cleanup = (): void => {
|
||||
if (timer !== undefined) {
|
||||
@@ -548,6 +703,44 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
if (this.waiters.get(workspaceId) === waiter) this.waiters.delete(workspaceId);
|
||||
};
|
||||
|
||||
/**
|
||||
* Fails the waiter *after* reading the log tail, so the browser and the
|
||||
* log get the actual nvim output instead of a bare timeout.
|
||||
*/
|
||||
function failWithDiagnostics(options: {
|
||||
marker: string;
|
||||
summary: string;
|
||||
logPath: string | undefined;
|
||||
init: SpawnInit | undefined;
|
||||
makeError: (diagnostics: SpawnDiagnostics) => InstanceError;
|
||||
}): void {
|
||||
if (settled || diagnosing) return;
|
||||
diagnosing = true;
|
||||
void manager
|
||||
.describeSpawnFailure({
|
||||
logPath: options.logPath,
|
||||
marker: options.marker,
|
||||
summary: options.summary,
|
||||
init: options.init,
|
||||
})
|
||||
.then((diagnostics) => {
|
||||
if (settled) return;
|
||||
// `fail()` is not enough on its own: the reason must reach
|
||||
// `InstanceState` so the browser sees it through `instance_state`.
|
||||
manager.setState({
|
||||
...(manager.states.get(workspaceId) ?? base),
|
||||
status: "stopped",
|
||||
nvimPid: null,
|
||||
attachedClients: 0,
|
||||
reason: diagnostics.reason,
|
||||
});
|
||||
waiter.fail(options.makeError(diagnostics));
|
||||
})
|
||||
.finally(() => {
|
||||
diagnosing = false;
|
||||
});
|
||||
}
|
||||
|
||||
const waiter: SpawnWaiter = {
|
||||
promise,
|
||||
settle(connection) {
|
||||
@@ -562,18 +755,39 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
cleanup();
|
||||
rejectPromise(error);
|
||||
},
|
||||
attach(child, logPath) {
|
||||
attach(child, logPath, init) {
|
||||
attachedLogPath = logPath;
|
||||
attachedInit = init;
|
||||
child.once("exit", (code, signal) => {
|
||||
exited = true;
|
||||
if (manager.children.get(workspaceId) === child) manager.children.delete(workspaceId);
|
||||
if (settled) return;
|
||||
const message = `nvim exited before hello (code ${String(code)}, signal ${String(signal)})`;
|
||||
void manager.appendLog(logPath, message);
|
||||
waiter.fail(InstanceError.unavailable(message, { workspaceId }));
|
||||
const summary = `nvim exited before hello (code ${String(code)}, signal ${String(signal)})`;
|
||||
failWithDiagnostics({
|
||||
marker: "exit before hello",
|
||||
summary,
|
||||
logPath,
|
||||
init,
|
||||
makeError: (diagnostics) =>
|
||||
InstanceError.unavailable(diagnostics.message, {
|
||||
workspaceId,
|
||||
reason: diagnostics.reason,
|
||||
}),
|
||||
});
|
||||
});
|
||||
child.once("error", (error) => {
|
||||
void manager.appendLog(logPath, `spawn error: ${error.message}`);
|
||||
waiter.fail(InstanceError.unavailable(`failed to spawn nvim: ${error.message}`, { workspaceId }));
|
||||
if (settled) return;
|
||||
failWithDiagnostics({
|
||||
marker: "spawn error",
|
||||
summary: `failed to spawn nvim: ${error.message}`,
|
||||
logPath,
|
||||
init,
|
||||
makeError: (diagnostics) =>
|
||||
InstanceError.unavailable(diagnostics.message, {
|
||||
workspaceId,
|
||||
reason: diagnostics.reason,
|
||||
}),
|
||||
});
|
||||
});
|
||||
},
|
||||
cancel(reason) {
|
||||
@@ -585,10 +799,26 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
const message = exited
|
||||
? `instance for ${workspaceId} exited before hello`
|
||||
: `instance for ${workspaceId} did not say hello within ${timeoutMs}ms`;
|
||||
waiter.fail(exited ? InstanceError.unavailable(message) : InstanceError.starting(message));
|
||||
if (settled) return;
|
||||
if (exited) {
|
||||
failWithDiagnostics({
|
||||
marker: "exit before hello",
|
||||
summary: `instance for ${workspaceId} exited before hello`,
|
||||
logPath: attachedLogPath,
|
||||
init: attachedInit,
|
||||
makeError: (diagnostics) =>
|
||||
InstanceError.unavailable(diagnostics.message, { reason: diagnostics.reason }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
failWithDiagnostics({
|
||||
marker: "hello timeout",
|
||||
summary: `instance for ${workspaceId} did not say hello within ${timeoutMs}ms`,
|
||||
logPath: attachedLogPath,
|
||||
init: attachedInit,
|
||||
makeError: (diagnostics) =>
|
||||
InstanceError.starting(diagnostics.message, { reason: diagnostics.reason }),
|
||||
});
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
|
||||
@@ -596,6 +826,49 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
return waiter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns "the spawn went quiet" into something a human can act on.
|
||||
*
|
||||
* Writes a marker into the instance log (so the file is self-describing), and
|
||||
* returns both a one-line reason for `instance_state` and a summary + tail for
|
||||
* the thrown error.
|
||||
*/
|
||||
private async describeSpawnFailure(options: {
|
||||
logPath: string | undefined;
|
||||
marker: string;
|
||||
summary: string;
|
||||
init: SpawnInit | undefined;
|
||||
}): Promise<SpawnDiagnostics> {
|
||||
const tail = options.logPath === undefined ? [] : await this.readLogTailLines(options.logPath);
|
||||
if (options.logPath !== undefined) {
|
||||
await this.appendLog(
|
||||
options.logPath,
|
||||
`${options.marker} (-u ${options.init?.path ?? "none"}, plugin ${options.init?.pluginDir ?? "none"})`,
|
||||
);
|
||||
}
|
||||
const nonEmpty = tail.filter((line) => line.trim() !== "");
|
||||
const lastLines = nonEmpty.slice(-3).join(" | ");
|
||||
const reason = truncate(lastLines === "" ? options.summary : `${options.summary}: ${lastLines}`, 500);
|
||||
const detail = tail.slice(-10).join("\n");
|
||||
return {
|
||||
reason,
|
||||
message: detail === "" ? options.summary : `${options.summary}\n${detail}`,
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads the last `logTailLines` lines, capped per line so one long traceback cannot flood the error. */
|
||||
private async readLogTailLines(logPath: string): Promise<string[]> {
|
||||
let lines: string[];
|
||||
try {
|
||||
lines = await this.readLogTail(logPath, this.logTailLines);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return lines
|
||||
.slice(-this.logTailLines)
|
||||
.map((line) => (line.length > 400 ? `${line.slice(0, 400)}…` : line));
|
||||
}
|
||||
|
||||
private handleOpen(connection: PluginSocketConnection): void {
|
||||
if (this.closed) {
|
||||
connection.close("instance manager is closed");
|
||||
@@ -731,6 +1004,25 @@ export class ManagedInstanceManager implements InstanceManagerHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/** Caps a single-line diagnostic so it stays readable in a state payload. */
|
||||
function truncate(value: string, max: number): string {
|
||||
return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Last `lines` lines of a log file.
|
||||
*
|
||||
* Instance logs only hold a spawned nvim's stderr, so they stay small and a full
|
||||
* read is cheaper (and safer) than a seek-from-the-end dance; a missing file is
|
||||
* simply "no output yet".
|
||||
*/
|
||||
async function defaultReadLogTail(path: string, lines: number): Promise<string[]> {
|
||||
const text = await readFile(path, "utf8");
|
||||
const all = text.split("\n");
|
||||
if (all.at(-1) === "") all.pop();
|
||||
return all.slice(-Math.max(1, lines));
|
||||
}
|
||||
|
||||
function sameState(a: InstanceState, b: InstanceState): boolean {
|
||||
return (
|
||||
a.instanceId === b.instanceId &&
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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). */
|
||||
|
||||
+67
-6
@@ -14,10 +14,11 @@ import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import type { InstanceManager, WorkspaceStore as WorkspaceStoreContract } from "../core/interfaces.js";
|
||||
import { dataDir, realpathSafe, workspaceIdForCwd } from "../core/paths.js";
|
||||
import { dataDir, expandTilde, realpathSafe, workspaceIdForCwd } from "../core/paths.js";
|
||||
import { ERROR_CODES } from "../protocol/errors.js";
|
||||
import type {
|
||||
InstanceState,
|
||||
RecentSessionInfo,
|
||||
WorkspaceInfo,
|
||||
WorkspaceVisibility,
|
||||
WorkspaceVisibilityReason,
|
||||
@@ -61,6 +62,11 @@ export interface WorkspaceStoreOptions {
|
||||
env?: WorkspaceEnv;
|
||||
/** Clock for the `PI2_WORKSPACE_STALE_DAYS` comparison; defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
/**
|
||||
* Home for `~`/`~/…` expansion in `add()` and the default allowlist root;
|
||||
* injectable so tests never touch the real home directory.
|
||||
*/
|
||||
home?: string;
|
||||
}
|
||||
|
||||
export interface WorkspaceStoreHandle extends WorkspaceStoreContract {
|
||||
@@ -82,11 +88,13 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
private readonly roots: readonly string[] | undefined;
|
||||
private readonly env: WorkspaceEnv;
|
||||
private readonly now: () => number;
|
||||
private readonly home: string;
|
||||
|
||||
constructor(options: WorkspaceStoreOptions = {}) {
|
||||
this.logger = options.logger;
|
||||
this.env = options.env ?? process.env;
|
||||
this.now = options.now ?? Date.now;
|
||||
this.home = options.home ?? homedir();
|
||||
this.discovery = options.discovery ?? createDiscovery({ ...(options.logger ? { logger: options.logger } : {}) });
|
||||
this.registry =
|
||||
options.registry ??
|
||||
@@ -140,8 +148,18 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
if (raw.includes("\0")) {
|
||||
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "cwd contains a NUL byte");
|
||||
}
|
||||
if (!isAbsolute(raw)) {
|
||||
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, `cwd must be absolute: ${raw}`);
|
||||
// `~` and `~/…` are shell shorthand the web dialog advertises; expand before
|
||||
// the absolute-path check. `~user/…` is deliberately left alone: resolving
|
||||
// another user's home is not something the daemon should guess at.
|
||||
const expanded = expandTilde(raw, this.home);
|
||||
if (expanded === undefined) {
|
||||
throw new WorkspaceError(
|
||||
ERROR_CODES.BAD_REQUEST,
|
||||
`cwd must be an absolute path (or start with ~/): ~user is not expanded: ${raw}`,
|
||||
);
|
||||
}
|
||||
if (!isAbsolute(expanded)) {
|
||||
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, `cwd must be an absolute path (or start with ~/): ${raw}`);
|
||||
}
|
||||
if (input.alias !== undefined && typeof input.alias !== "string") {
|
||||
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "alias must be a string");
|
||||
@@ -153,9 +171,9 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
const roots = this.allowlist();
|
||||
let real: string;
|
||||
try {
|
||||
real = realpathSync(raw);
|
||||
real = realpathSync(expanded);
|
||||
} catch (error) {
|
||||
throw mapFsError(error, raw);
|
||||
throw mapFsError(error, expanded);
|
||||
}
|
||||
// Check the canonical path: symlinks inside the allowlist must not escape it.
|
||||
this.assertAllowed(real, roots);
|
||||
@@ -241,6 +259,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 {
|
||||
@@ -370,7 +425,7 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
if (configured !== undefined) {
|
||||
return configured.map((root) => canonicalRoot(root)).filter((root): root is string => root.length > 0);
|
||||
}
|
||||
return rootsFromEnv(this.env.PI2_WORKSPACE_ROOTS);
|
||||
return rootsFromEnv(this.env.PI2_WORKSPACE_ROOTS, this.home);
|
||||
}
|
||||
|
||||
private assertAllowed(candidate: string, roots: readonly string[]): void {
|
||||
@@ -567,6 +622,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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
+78
-3
@@ -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</title>");
|
||||
});
|
||||
|
||||
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<void> } | 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<void> } | 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
+286
-4
@@ -8,7 +8,9 @@ import {
|
||||
checkLinger,
|
||||
checkNvim,
|
||||
checkNode,
|
||||
checkPlugin,
|
||||
checkProtocol,
|
||||
checkUnit,
|
||||
collectContext,
|
||||
defaultProbes,
|
||||
formatReport,
|
||||
@@ -33,7 +35,7 @@ function context(overrides: Partial<DoctorContext> = {}): DoctorContext {
|
||||
path: "/usr/bin/curl",
|
||||
version: "curl 8.7.1 (x86_64-pc-linux-gnu) libcurl/8.7.1 OpenSSL/3.3.1",
|
||||
},
|
||||
plugin: { dir: "/home/u/.local/share/nvim/lazy/pi2.nvim", bridgeFound: true },
|
||||
plugin: { dir: "/home/u/.local/share/nvim/lazy/pi2.nvim", bridgeFound: true, hostFound: true },
|
||||
runtime: { path: "/run/user/1000/pi2", exists: true, mode: 0o700 },
|
||||
cliToken: { path: "/run/user/1000/pi2/cli.token", exists: true, mode: 0o600 },
|
||||
socket: { path: "/run/user/1000/pi2/d.sock", exists: true },
|
||||
@@ -73,6 +75,7 @@ describe("doctor checks (all passing)", () => {
|
||||
"bind",
|
||||
"service-manager",
|
||||
"linger",
|
||||
"unit",
|
||||
"web-dist",
|
||||
"protocol",
|
||||
]);
|
||||
@@ -89,6 +92,30 @@ 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 plugin check", () => {
|
||||
it("passes only when bridge.lua and lua/pi/host.lua both exist", () => {
|
||||
expect(checkPlugin({ dir: "/p", bridgeFound: true, hostFound: true })).toEqual({
|
||||
name: "plugin",
|
||||
status: "ok",
|
||||
detail: "/p (pi2.nvim host-capable)",
|
||||
});
|
||||
|
||||
const stale = checkPlugin({ dir: "/p", bridgeFound: true, hostFound: false });
|
||||
expect(stale.status).toBe("warn");
|
||||
expect(stale.detail).toContain("/p has no lua/pi/host.lua");
|
||||
expect(checkPlugin({ dir: "/p", bridgeFound: true }).status).toBe("warn");
|
||||
|
||||
expect(checkPlugin({ dir: "/p", bridgeFound: false })).toMatchObject({ status: "fail" });
|
||||
expect(checkPlugin({ dir: undefined, bridgeFound: false }).detail).toContain("set PI2_PLUGIN_DIR or install");
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor bind check", () => {
|
||||
@@ -184,12 +211,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 = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<plist version="1.0">',
|
||||
"<dict>",
|
||||
" <key>ProgramArguments</key>",
|
||||
" <array>",
|
||||
" <string>/missing/node</string>",
|
||||
" <string>daemon</string>",
|
||||
" </array>",
|
||||
"</dict>",
|
||||
"</plist>",
|
||||
].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 = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<plist version="1.0">',
|
||||
"<dict>",
|
||||
" <key>ProgramArguments</key>",
|
||||
" <array>",
|
||||
" <string>/opt/homebrew/bin/node</string>",
|
||||
" <string>/repo/dist/cli/pi2.js</string>",
|
||||
" <string>daemon</string>",
|
||||
" </array>",
|
||||
"</dict>",
|
||||
"</plist>",
|
||||
].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 () => {
|
||||
@@ -210,6 +455,15 @@ describe("doctor failure cases", () => {
|
||||
expect(report.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("warns when the plugin lacks lua/pi/host.lua", async () => {
|
||||
const report = await checks({
|
||||
plugin: { dir: "/home/u/nvim/pi2.nvim", bridgeFound: true, hostFound: false },
|
||||
});
|
||||
expect(statusOf(report, "plugin")).toBe("warn");
|
||||
expect(report.ok).toBe(true);
|
||||
expect(report.checks.find((check) => check.name === "plugin")?.detail).toContain("lua/pi/host.lua");
|
||||
});
|
||||
|
||||
it("fails when the plugin is not installed", async () => {
|
||||
const report = await checks({ plugin: { dir: "/home/u/nvim/pi2.nvim", bridgeFound: false } });
|
||||
expect(statusOf(report, "plugin")).toBe("fail");
|
||||
@@ -312,7 +566,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");
|
||||
});
|
||||
@@ -381,6 +639,30 @@ describe("collectContext", () => {
|
||||
expect(report.checks.find((check) => check.name === "web-dist")?.status).toBe("warn");
|
||||
});
|
||||
|
||||
it("expands a leading ~/ in PI2_PLUGIN_DIR", async () => {
|
||||
const home = join(dir, "home");
|
||||
const pluginDir = join(home, "plugins", "pi2.nvim");
|
||||
mkdirSync(join(pluginDir, "lua", "pi", "web"), { recursive: true });
|
||||
writeFileSync(join(pluginDir, "lua", "pi", "web", "bridge.lua"), "");
|
||||
writeFileSync(join(pluginDir, "lua", "pi", "host.lua"), "");
|
||||
|
||||
const ctx = await collectContext({
|
||||
platform: "linux",
|
||||
home,
|
||||
uid: 1000,
|
||||
env: {
|
||||
PATH: "/usr/bin",
|
||||
PI2_PLUGIN_DIR: "~/plugins/pi2.nvim",
|
||||
PI2_RUNTIME_DIR: join(dir, "run"),
|
||||
PI2_STATIC_DIR: join(dir, "web"),
|
||||
},
|
||||
which: () => undefined,
|
||||
run: async () => ({ ok: false, stdout: "", stderr: "not found" }),
|
||||
});
|
||||
|
||||
expect(ctx.plugin).toEqual({ dir: pluginDir, bridgeFound: true, hostFound: true });
|
||||
});
|
||||
|
||||
it("records a missing daemon as unreachable", async () => {
|
||||
const ctx = await collectContext({
|
||||
platform: "darwin",
|
||||
|
||||
@@ -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 = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
@@ -67,6 +96,35 @@ const MAC_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
</plist>
|
||||
`;
|
||||
|
||||
const BUNDLED_MAC_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>com.pi2.daemon</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/usr/local/bin/pi2</string>
|
||||
<string>daemon</string>
|
||||
<string>--foreground</string>
|
||||
</array>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>PATH</key>
|
||||
<string>/usr/local/bin:/usr/bin:/bin</string>
|
||||
</dict>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>KeepAlive</key>
|
||||
<true/>
|
||||
<key>StandardOutPath</key>
|
||||
<string>/home/u/.local/state/pi2/pi2-daemon.log</string>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>/home/u/.local/state/pi2/pi2-daemon.err.log</string>
|
||||
</dict>
|
||||
</plist>
|
||||
`;
|
||||
|
||||
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("<string>/opt/a&b/node</string>");
|
||||
});
|
||||
|
||||
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 = [
|
||||
" <key>ProgramArguments</key>",
|
||||
" <array>",
|
||||
" <string>/usr/local/bin/pi2</string>",
|
||||
" <string>daemon</string>",
|
||||
" <string>--foreground</string>",
|
||||
" </array>",
|
||||
].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("<string>/opt/a&b/pi2</string>");
|
||||
});
|
||||
|
||||
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[] = [];
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* Plugin discovery (`src/core/plugin.ts`).
|
||||
*
|
||||
* Everything is injected (`env`, `home`, `exists`, `readdir`) so the tests never
|
||||
* look at the machine's real nvim install: a developer with pi2.nvim checked out
|
||||
* would otherwise get different results from CI.
|
||||
*/
|
||||
|
||||
import type { Dirent } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
PLUGIN_NAME,
|
||||
classifyPluginDir,
|
||||
describePluginFailure,
|
||||
displayPath,
|
||||
pluginDirCandidates,
|
||||
resolvePluginDir,
|
||||
} from "../../src/core/plugin.js";
|
||||
|
||||
const HOME = "/home/tester";
|
||||
const HOST = "lua/pi/host.lua";
|
||||
const BRIDGE = "lua/pi/web/bridge.lua";
|
||||
|
||||
/** Fake `exists` over an explicit set of paths. */
|
||||
function fakeExists(paths: readonly string[]): (path: string) => boolean {
|
||||
const set = new Set(paths);
|
||||
return (path) => set.has(path);
|
||||
}
|
||||
|
||||
/** Minimal `Dirent` lookalike; `readdir` is only asked for directory names. */
|
||||
function dir(name: string): Dirent {
|
||||
return { name, isDirectory: () => true } as Dirent;
|
||||
}
|
||||
|
||||
/** A `readdir` that only knows one directory (any other root is "missing"). */
|
||||
function fakeReaddir(entries: Record<string, Dirent[]>): (path: string, o: { withFileTypes: true }) => Dirent[] {
|
||||
return (path) => {
|
||||
const found = entries[path];
|
||||
if (found === undefined) throw new Error(`ENOENT: ${path}`);
|
||||
return found;
|
||||
};
|
||||
}
|
||||
|
||||
const PACK = `${HOME}/.local/share/nvim/site/pack`;
|
||||
|
||||
describe("resolvePluginDir", () => {
|
||||
it("uses PI2_PLUGIN_DIR first and expands a leading ~/", () => {
|
||||
const configured = "/home/tester/work/pi2.nvim";
|
||||
const resolution = resolvePluginDir({
|
||||
env: { PI2_PLUGIN_DIR: " ~/work/pi2.nvim " },
|
||||
home: HOME,
|
||||
exists: fakeExists([configured, `${configured}/${HOST}`, `${configured}/${BRIDGE}`]),
|
||||
readdir: fakeReaddir({}),
|
||||
});
|
||||
|
||||
expect(resolution).toEqual({
|
||||
plugin: {
|
||||
dir: configured,
|
||||
host: `${configured}/${HOST}`,
|
||||
bridge: `${configured}/${BRIDGE}`,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("skips a lazy checkout without lua/pi/host.lua in favour of a pack dir", () => {
|
||||
const lazy = `${HOME}/.local/share/nvim/lazy/${PLUGIN_NAME}`;
|
||||
const packed = `${PACK}/plugins/start/${PLUGIN_NAME}`;
|
||||
const resolution = resolvePluginDir({
|
||||
env: {},
|
||||
home: HOME,
|
||||
exists: fakeExists([
|
||||
lazy,
|
||||
// lazy.nvim installed the plugin but this checkout predates host.lua
|
||||
`${lazy}/${BRIDGE}`,
|
||||
packed,
|
||||
`${packed}/${HOST}`,
|
||||
`${packed}/${BRIDGE}`,
|
||||
]),
|
||||
readdir: fakeReaddir({ [PACK]: [dir("plugins")] }),
|
||||
});
|
||||
|
||||
expect(resolution.plugin?.dir).toBe(packed);
|
||||
});
|
||||
|
||||
it("reports every candidate when nothing is host-capable", () => {
|
||||
const lazy = `${HOME}/.local/share/nvim/lazy/${PLUGIN_NAME}`;
|
||||
const resolution = resolvePluginDir({
|
||||
env: {},
|
||||
home: HOME,
|
||||
exists: fakeExists([lazy, `${lazy}/${HOST}`]),
|
||||
readdir: fakeReaddir({ [PACK]: [dir("a"), dir("b")] }),
|
||||
});
|
||||
|
||||
expect(resolution.plugin).toBeUndefined();
|
||||
expect(resolution.candidates?.map((candidate) => candidate.reason)).toEqual([
|
||||
"missing-bridge",
|
||||
"absent",
|
||||
"absent",
|
||||
"absent",
|
||||
"absent",
|
||||
]);
|
||||
expect(resolution.candidates?.[0]?.dir).toBe(lazy);
|
||||
});
|
||||
|
||||
it("never throws when site/pack is missing and ends in a readable failure", () => {
|
||||
const resolution = resolvePluginDir({
|
||||
env: {},
|
||||
home: HOME,
|
||||
exists: () => false,
|
||||
readdir: () => {
|
||||
throw new Error("ENOENT");
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolution.plugin).toBeUndefined();
|
||||
expect(describePluginFailure(resolution.candidates ?? [])).toContain(`no ${PLUGIN_NAME} plugin found`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pluginDirCandidates", () => {
|
||||
it("orders env dir, lazy.nvim, pack/start, pack/opt, then the system dirs", () => {
|
||||
const dirs = pluginDirCandidates({
|
||||
env: { PI2_PLUGIN_DIR: "/opt/pi2.nvim" },
|
||||
home: HOME,
|
||||
readdir: fakeReaddir({
|
||||
[PACK]: [dir("mine")],
|
||||
"/usr/share/nvim/site/pack": [dir("distro")],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(dirs).toEqual([
|
||||
"/opt/pi2.nvim",
|
||||
`${HOME}/.local/share/nvim/lazy/${PLUGIN_NAME}`,
|
||||
`${PACK}/mine/start/${PLUGIN_NAME}`,
|
||||
`${PACK}/mine/opt/${PLUGIN_NAME}`,
|
||||
`/usr/share/nvim/site/pack/distro/start/${PLUGIN_NAME}`,
|
||||
`/usr/share/nvim/site/pack/distro/opt/${PLUGIN_NAME}`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores a blank PI2_PLUGIN_DIR and dedupes overlapping candidates", () => {
|
||||
const lazy = `${HOME}/.local/share/nvim/lazy/${PLUGIN_NAME}`;
|
||||
const dirs = pluginDirCandidates({
|
||||
env: { PI2_PLUGIN_DIR: " ", HOME },
|
||||
home: HOME,
|
||||
readdir: fakeReaddir({}),
|
||||
});
|
||||
expect(dirs[0]).toBe(lazy);
|
||||
|
||||
const duplicated = pluginDirCandidates({
|
||||
env: { PI2_PLUGIN_DIR: lazy },
|
||||
home: HOME,
|
||||
readdir: fakeReaddir({}),
|
||||
});
|
||||
expect(duplicated.filter((dir) => dir === lazy)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyPluginDir", () => {
|
||||
it("requires both entry points", () => {
|
||||
expect(classifyPluginDir("/p", fakeExists(["/p"]))).toEqual({ dir: "/p", reason: "missing-host" });
|
||||
expect(classifyPluginDir("/p", fakeExists(["/p", `/p/${HOST}`]))).toEqual({
|
||||
dir: "/p",
|
||||
reason: "missing-bridge",
|
||||
});
|
||||
expect(classifyPluginDir("/p", fakeExists(["/p", `/p/${HOST}`, `/p/${BRIDGE}`]))).toEqual({
|
||||
dir: "/p",
|
||||
reason: "ok",
|
||||
});
|
||||
expect(classifyPluginDir("/p", () => false)).toEqual({ dir: "/p", reason: "absent" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("describePluginFailure", () => {
|
||||
it("names the first existing but incomplete checkout (tilde-collapsed)", () => {
|
||||
const lazy = `${homedir()}/.local/share/nvim/lazy/${PLUGIN_NAME}`;
|
||||
const line = describePluginFailure([
|
||||
{ dir: `${homedir()}/.local/share/nvim/site/pack/x/start/${PLUGIN_NAME}`, reason: "absent" },
|
||||
{ dir: lazy, reason: "missing-host" },
|
||||
]);
|
||||
|
||||
expect(line).toBe(`${PLUGIN_NAME} at ~/.local/share/nvim/lazy/${PLUGIN_NAME} has no ${HOST} (update the plugin)`);
|
||||
expect(displayPath(lazy)).toContain("~/");
|
||||
});
|
||||
|
||||
it("reports a missing bridge instead of the host file", () => {
|
||||
const line = describePluginFailure([{ dir: "/tmp/pi2.nvim", reason: "missing-bridge" }]);
|
||||
expect(line).toContain(`has no ${BRIDGE}`);
|
||||
});
|
||||
|
||||
it("falls back to a not-found line naming the first location", () => {
|
||||
const line = describePluginFailure([
|
||||
{ dir: "/tmp/a/pi2.nvim", reason: "absent" },
|
||||
{ dir: "/tmp/b/pi2.nvim", reason: "absent" },
|
||||
]);
|
||||
expect(line).toBe(`no ${PLUGIN_NAME} plugin found (looked in 2 location(s), first /tmp/a/pi2.nvim)`);
|
||||
expect(describePluginFailure([])).toContain("no locations");
|
||||
});
|
||||
|
||||
// A typo in `PI2_PLUGIN_DIR` used to be blamed on a stale lazy.nvim checkout,
|
||||
// which sends the user to the wrong directory (found by the acceptance run).
|
||||
it("names an explicitly configured directory that does not exist", () => {
|
||||
const line = describePluginFailure(
|
||||
[
|
||||
{ dir: "/opt/typo/pi2.nvim", reason: "absent" },
|
||||
{ dir: "/home/x/.local/share/nvim/lazy/pi2.nvim", reason: "missing-host" },
|
||||
],
|
||||
{ configured: "/opt/typo/pi2.nvim" },
|
||||
);
|
||||
|
||||
expect(line).toBe("PI2_PLUGIN_DIR=/opt/typo/pi2.nvim does not exist");
|
||||
});
|
||||
|
||||
it("names a configured directory that is not host-capable", () => {
|
||||
const line = describePluginFailure([{ dir: "/opt/pi2.nvim", reason: "missing-host" }], {
|
||||
configured: "/opt/pi2.nvim",
|
||||
});
|
||||
|
||||
expect(line).toBe(`PI2_PLUGIN_DIR=/opt/pi2.nvim has no ${HOST} (update the plugin)`);
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> }[] = [];
|
||||
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<WorkspaceInfo> {
|
||||
return this.byCwd(cwd) ?? this.add({ cwd });
|
||||
}
|
||||
|
||||
recentSessions(limit = 20): RecentSessionInfo[] {
|
||||
return this.recentSessionRows.slice(0, limit);
|
||||
}
|
||||
}
|
||||
|
||||
export class FakeBus implements Bus {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -102,6 +102,26 @@ describe("CommandRouter", () => {
|
||||
expect(workspaces.refreshCalls).toEqual(["ws-1"]);
|
||||
});
|
||||
|
||||
it("accepts name as the alias when alias is absent", async () => {
|
||||
const added = await router.dispatch({
|
||||
method: "workspace.add",
|
||||
params: { cwd: "/repo/named", name: " Named " },
|
||||
});
|
||||
|
||||
expect(added.status).toBe(202);
|
||||
expect(workspaces.addCalls).toEqual([{ cwd: "/repo/named", alias: " Named " }]);
|
||||
// The response carries the id both where the protocol documents it and at
|
||||
// the top level (the web client's shortcut).
|
||||
expect(added.body).toMatchObject({ accepted: true, workspaceId: "ws-2", workspace: { workspaceId: "ws-2" } });
|
||||
});
|
||||
|
||||
it("prefers alias over name and drops a whitespace-only name", async () => {
|
||||
await router.dispatch({ method: "workspace.add", params: { cwd: "/repo/both", alias: "A", name: "N" } });
|
||||
await router.dispatch({ method: "workspace.add", params: { cwd: "/repo/blank", name: " " } });
|
||||
|
||||
expect(workspaces.addCalls).toEqual([{ cwd: "/repo/both", alias: "A" }, { cwd: "/repo/blank" }]);
|
||||
});
|
||||
|
||||
it("routes instance and system methods to the instance manager", async () => {
|
||||
const ensured = await router.dispatch({ method: "instance.ensure", params: { workspaceId: "ws-1" } });
|
||||
expect(ensured.status).toBe(202);
|
||||
|
||||
@@ -31,7 +31,15 @@ export interface TempEnv {
|
||||
cleanup(): void;
|
||||
}
|
||||
|
||||
const ENV_KEYS = ["PI2_RUNTIME_DIR", "PI2_DATA_DIR", "PI2_STATE_DIR", "PI2_NVIM_BIN", "PI2_NVIM_INIT"] as const;
|
||||
const ENV_KEYS = [
|
||||
"PI2_RUNTIME_DIR",
|
||||
"PI2_DATA_DIR",
|
||||
"PI2_STATE_DIR",
|
||||
"PI2_NVIM_BIN",
|
||||
"PI2_NVIM_INIT",
|
||||
"PI2_PLUGIN_DIR",
|
||||
"PI2_ENSURE_TIMEOUT_MS",
|
||||
] as const;
|
||||
|
||||
export function makeTempEnv(prefix = "pi2-daemon-instances-"): TempEnv {
|
||||
const dir = mkdtempSync(join(tmpdir(), prefix));
|
||||
@@ -42,6 +50,11 @@ export function makeTempEnv(prefix = "pi2-daemon-instances-"): TempEnv {
|
||||
|
||||
const saved = new Map<string, string | undefined>();
|
||||
for (const key of ENV_KEYS) saved.set(key, process.env[key]);
|
||||
// The developer's own spawn knobs must not decide which init a test spawns
|
||||
// with: clear them so the default (generated host init) is what runs.
|
||||
for (const key of ["PI2_NVIM_BIN", "PI2_NVIM_INIT", "PI2_PLUGIN_DIR", "PI2_ENSURE_TIMEOUT_MS"] as const) {
|
||||
delete process.env[key];
|
||||
}
|
||||
process.env.PI2_RUNTIME_DIR = runtime;
|
||||
process.env.PI2_DATA_DIR = data;
|
||||
process.env.PI2_STATE_DIR = state;
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Generated host init (`src/instances/host-init.ts`).
|
||||
*
|
||||
* `node:fs/promises.writeFile` is spied on so "memoized / compared before write"
|
||||
* is asserted by counting real writes instead of racing file mtimes.
|
||||
*/
|
||||
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const writes = vi.hoisted(() => ({ paths: [] as string[] }));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
||||
const writeFile = actual.writeFile as unknown as (...args: unknown[]) => Promise<void>;
|
||||
return {
|
||||
...actual,
|
||||
writeFile: (...args: unknown[]): Promise<void> => {
|
||||
writes.paths.push(String(args[0]));
|
||||
return writeFile(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { HOST_INIT_FILENAME, renderHostInit, resetHostInitCache, writeHostInit } = await import(
|
||||
"../../src/instances/host-init.js"
|
||||
);
|
||||
|
||||
const PLUGIN = "/home/tester/.local/share/nvim/lazy/pi2.nvim";
|
||||
|
||||
describe("renderHostInit", () => {
|
||||
it("prepends the plugin and starts the host without loading the user config", () => {
|
||||
const lua = renderHostInit(PLUGIN);
|
||||
|
||||
expect(lua).toContain(`vim.opt.runtimepath:prepend("${PLUGIN}")`);
|
||||
expect(lua).toContain("vim.opt.swapfile = false");
|
||||
expect(lua).toContain('vim.opt.shadafile = "NONE"');
|
||||
expect(lua).toContain('vim.g.mapleader = " "');
|
||||
expect(lua).toContain('local ok, host = pcall(require, "pi.host")');
|
||||
expect(lua).toContain('vim.api.nvim_err_writeln("pi2: " .. tostring(host))');
|
||||
expect(lua).toContain('vim.cmd("cquit 1")');
|
||||
expect(lua).toContain("host.start()");
|
||||
// Header names the daemon and the plugin it points at, so a stray file in
|
||||
// the state dir explains itself.
|
||||
expect(lua).toContain("pi2d");
|
||||
expect(lua).toContain(`-- plugin: ${PLUGIN}`);
|
||||
// No wait loop of our own: host.start() owns the handshake.
|
||||
expect(lua).not.toContain("vim.wait");
|
||||
// A failing `require` must exit, not fall through to host.start().
|
||||
expect(lua.indexOf("cquit 1")).toBeLessThan(lua.indexOf("host.start()"));
|
||||
});
|
||||
|
||||
it("escapes the plugin dir as a Lua string (no shell quoting)", () => {
|
||||
const lua = renderHostInit('/tmp/we"ird\\dir');
|
||||
expect(lua).toContain('vim.opt.runtimepath:prepend("/tmp/we\\"ird\\\\dir")');
|
||||
expect(lua).not.toContain("'");
|
||||
});
|
||||
});
|
||||
|
||||
describe("writeHostInit", () => {
|
||||
let dir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = resolve(mkdtempSync(join(tmpdir(), "pi2-host-init-")));
|
||||
writes.paths.length = 0;
|
||||
resetHostInitCache();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("writes host-init.lua (mode 0600) and returns the absolute path", async () => {
|
||||
const path = await writeHostInit({ dir, pluginDir: PLUGIN });
|
||||
|
||||
expect(path).toBe(join(dir, HOST_INIT_FILENAME));
|
||||
expect(readFileSync(path, "utf8")).toBe(renderHostInit(PLUGIN));
|
||||
expect(statSync(path).mode & 0o777).toBe(0o600);
|
||||
expect(writes.paths).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not rewrite on the second call for the same (dir, pluginDir)", async () => {
|
||||
const first = await writeHostInit({ dir, pluginDir: PLUGIN });
|
||||
const second = await writeHostInit({ dir, pluginDir: PLUGIN });
|
||||
|
||||
expect(second).toBe(first);
|
||||
expect(writes.paths).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rewrites when the plugin dir changes", async () => {
|
||||
await writeHostInit({ dir, pluginDir: PLUGIN });
|
||||
const other = "/tmp/other/pi2.nvim";
|
||||
const path = await writeHostInit({ dir, pluginDir: other });
|
||||
|
||||
expect(readFileSync(path, "utf8")).toContain(`vim.opt.runtimepath:prepend("${other}")`);
|
||||
expect(writes.paths).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("skips the write when the file already matches", async () => {
|
||||
const path = join(dir, HOST_INIT_FILENAME);
|
||||
writeFileSync(path, renderHostInit(PLUGIN));
|
||||
resetHostInitCache();
|
||||
|
||||
await expect(writeHostInit({ dir, pluginDir: PLUGIN })).resolves.toBe(path);
|
||||
expect(writes.paths).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,10 @@
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { daemonSocketPath, daemonTokenPath, stateDir } from "../../src/core/paths.js";
|
||||
import {
|
||||
createInstanceManager,
|
||||
parseEnsureTimeoutMs,
|
||||
parseProcRss,
|
||||
parsePsRss,
|
||||
summarizeResources,
|
||||
@@ -49,12 +50,18 @@ describe("InstanceManager", () => {
|
||||
let env: TempEnv;
|
||||
let bus: FakeBus;
|
||||
let manager: InstanceManagerHandle | undefined;
|
||||
/** Host-capable fake plugin checkout discovered by every spawn by default. */
|
||||
let pluginRoot: string;
|
||||
const workspaces = new Map<string, string>();
|
||||
|
||||
beforeEach(() => {
|
||||
env = makeTempEnv();
|
||||
bus = new FakeBus();
|
||||
workspaces.clear();
|
||||
pluginRoot = join(env.dir, "pi2.nvim");
|
||||
mkdirSync(join(pluginRoot, "lua", "pi", "web"), { recursive: true });
|
||||
writeFileSync(join(pluginRoot, "lua", "pi", "host.lua"), "-- fake host\n");
|
||||
writeFileSync(join(pluginRoot, "lua", "pi", "web", "bridge.lua"), "-- fake bridge\n");
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -70,18 +77,33 @@ describe("InstanceManager", () => {
|
||||
return cwd;
|
||||
}
|
||||
|
||||
async function create(options: {
|
||||
bin?: string;
|
||||
deps?: Partial<InstanceManagerDeps>;
|
||||
} = {}): Promise<InstanceManagerHandle> {
|
||||
async function create(
|
||||
options: {
|
||||
bin?: string;
|
||||
/** `null` leaves the timeout to `PI2_ENSURE_TIMEOUT_MS`/the default. */
|
||||
ensureTimeoutMs?: number | null;
|
||||
deps?: Partial<InstanceManagerDeps>;
|
||||
} = {},
|
||||
): Promise<InstanceManagerHandle> {
|
||||
const ensureTimeoutMs = options.ensureTimeoutMs === undefined ? 4_000 : options.ensureTimeoutMs;
|
||||
const instance = await createInstanceManager({
|
||||
bus,
|
||||
resolveCwd: (workspaceId) => workspaces.get(workspaceId),
|
||||
ensureTimeoutMs: 4_000,
|
||||
...(ensureTimeoutMs === null ? {} : { ensureTimeoutMs }),
|
||||
shutdownGraceMs: 300,
|
||||
sigtermGraceMs: 200,
|
||||
minSpawnIntervalMs: 300,
|
||||
maxSpawnIntervalMs: 1_000,
|
||||
// Hermetic plugin discovery: the machine's own nvim install must never
|
||||
// decide what these tests spawn with.
|
||||
resolvePlugin: () => ({
|
||||
plugin: {
|
||||
dir: pluginRoot,
|
||||
host: join(pluginRoot, "lua", "pi", "host.lua"),
|
||||
bridge: join(pluginRoot, "lua", "pi", "web", "bridge.lua"),
|
||||
},
|
||||
}),
|
||||
hostInitDir: join(env.dir, "host-init"),
|
||||
...(options.bin === undefined ? {} : { nvimBin: options.bin }),
|
||||
...(options.deps ?? {}),
|
||||
});
|
||||
@@ -112,7 +134,16 @@ describe("InstanceManager", () => {
|
||||
const argv = start.argv as string[];
|
||||
expect(argv.slice(0, 2)).toEqual(["--headless", "--listen"]);
|
||||
expect(argv[2]).toBe(state.listenAddr);
|
||||
expect(argv.slice(3)).toEqual(["-c", 'lua require("pi.host").start()']);
|
||||
// No plugin/config default any more: the daemon hands nvim its generated init.
|
||||
expect(argv.slice(3)).toEqual([
|
||||
"-u",
|
||||
join(env.dir, "host-init", "host-init.lua"),
|
||||
"-c",
|
||||
'lua require("pi.host").start()',
|
||||
]);
|
||||
expect(readFileSync(join(env.dir, "host-init", "host-init.lua"), "utf8")).toContain(
|
||||
`vim.opt.runtimepath:prepend("${pluginRoot}")`,
|
||||
);
|
||||
expect(start.cwd).toBe(cwd);
|
||||
const spawnedEnv = start.env as Record<string, string>;
|
||||
expect(spawnedEnv.PI2_WORKSPACE_ID).toBe("ws-1");
|
||||
@@ -128,19 +159,32 @@ describe("InstanceManager", () => {
|
||||
expect(statuses).toContain("ready");
|
||||
});
|
||||
|
||||
it("passes PI2_NVIM_INIT as -u only when configured", async () => {
|
||||
it("honours an explicit init path from PI2_NVIM_INIT", async () => {
|
||||
addWorkspace();
|
||||
const init = join(env.dir, "init.lua");
|
||||
process.env.PI2_NVIM_INIT = "/x/y.lua";
|
||||
const fake = writeFakeNvim(env.dir);
|
||||
const mgr = await create({ bin: fake.bin, deps: { nvimInit: init } });
|
||||
const mgr = await create({ bin: fake.bin });
|
||||
|
||||
await mgr.ensure("ws-1");
|
||||
|
||||
const argv = startRecords(fake.runLog)[0]?.argv as string[];
|
||||
expect(argv.slice(3, 5)).toEqual(["-u", init]);
|
||||
expect(argv.slice(3, 5)).toEqual(["-u", "/x/y.lua"]);
|
||||
expect(argv.slice(5)).toEqual(["-c", 'lua require("pi.host").start()']);
|
||||
});
|
||||
|
||||
it("spawns the user's own config (no -u) for PI2_NVIM_INIT=user", async () => {
|
||||
addWorkspace();
|
||||
process.env.PI2_NVIM_INIT = "user";
|
||||
const fake = writeFakeNvim(env.dir);
|
||||
const mgr = await create({ bin: fake.bin });
|
||||
|
||||
await mgr.ensure("ws-1");
|
||||
|
||||
const argv = startRecords(fake.runLog)[0]?.argv as string[];
|
||||
expect(argv.slice(3)).toEqual(["-c", 'lua require("pi.host").start()']);
|
||||
expect(argv).not.toContain("-u");
|
||||
});
|
||||
|
||||
it("is idempotent and reports state changes to handlers", async () => {
|
||||
addWorkspace();
|
||||
const fake = writeFakeNvim(env.dir);
|
||||
@@ -207,6 +251,103 @@ describe("InstanceManager", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses to spawn when no host-capable plugin is found", async () => {
|
||||
addWorkspace();
|
||||
const fake = writeFakeNvim(env.dir);
|
||||
const lazy = join(env.dir, "lazy", "pi2.nvim");
|
||||
const mgr = await create({
|
||||
bin: fake.bin,
|
||||
deps: {
|
||||
resolvePlugin: () => ({
|
||||
plugin: undefined,
|
||||
configured: undefined,
|
||||
candidates: [
|
||||
{ dir: lazy, reason: "missing-host" },
|
||||
{ dir: join(env.dir, "pack", "pi2.nvim"), reason: "absent" },
|
||||
],
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const error = await mgr.ensure("ws-1").catch((rejection: unknown) => rejection);
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
const failure = error as Error & { code?: string };
|
||||
expect(failure.code).toBe("E_INSTANCE_UNAVAILABLE");
|
||||
expect(failure.message).toContain("has no lua/pi/host.lua");
|
||||
expect(failure.message).toContain("set PI2_PLUGIN_DIR");
|
||||
expect(failure.message).toContain("PI2_NVIM_INIT=user");
|
||||
// Refusing beats spawning an nvim that can only time out.
|
||||
expect(startRecords(fake.runLog)).toHaveLength(0);
|
||||
|
||||
const stopped = mgr.list().find((state) => state.workspaceId === "ws-1");
|
||||
expect(stopped?.status).toBe("stopped");
|
||||
expect(stopped?.reason).toContain("has no lua/pi/host.lua");
|
||||
expect(stopped?.reason).toContain("PI2_NVIM_INIT=user");
|
||||
|
||||
// The refusal is booked like any other failed start: backoff, no stuck entry.
|
||||
await expect(mgr.ensure("ws-1")).rejects.toMatchObject({
|
||||
code: "E_INSTANCE_UNAVAILABLE",
|
||||
message: expect.stringContaining("backing off"),
|
||||
});
|
||||
expect(startRecords(fake.runLog)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("reports the log tail on hello timeout and puts a one-line reason on the state", async () => {
|
||||
addWorkspace();
|
||||
const fake = writeFakeNvim(env.dir, { mode: "no-hello" });
|
||||
const tail = [
|
||||
"Error detected while processing host-init.lua:",
|
||||
'E5108: Error executing lua: module \'pi.host\' not found',
|
||||
"",
|
||||
"stack traceback:",
|
||||
" [C]: in function 'require'",
|
||||
];
|
||||
const mgr = await create({
|
||||
bin: fake.bin,
|
||||
deps: { readLogTail: async () => [...tail] },
|
||||
});
|
||||
|
||||
const error = await mgr
|
||||
.ensure("ws-1", { timeoutMs: 800 })
|
||||
.catch((rejection: unknown) => rejection);
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
const failure = error as Error & { code?: string };
|
||||
expect(failure.code).toBe("E_INSTANCE_STARTING");
|
||||
expect(failure.message).toContain("did not say hello within 800ms");
|
||||
expect(failure.message).toContain("module 'pi.host' not found");
|
||||
expect(failure.message).toContain("stack traceback:");
|
||||
|
||||
const stopped = mgr.list().find((state) => state.workspaceId === "ws-1");
|
||||
expect(stopped?.status).toBe("stopped");
|
||||
expect(stopped?.reason).toContain("did not say hello within 800ms");
|
||||
expect(stopped?.reason).toContain("stack traceback:");
|
||||
// The reason travels to the browser: it must stay a single line.
|
||||
expect(stopped?.reason).not.toContain("\n");
|
||||
|
||||
const logDir = join(stateDir(), "instances");
|
||||
const logged = readdirSync(logDir)
|
||||
.map((file) => readFileSync(join(logDir, file), "utf8"))
|
||||
.join("\n");
|
||||
expect(logged).toContain("hello timeout (-u ");
|
||||
expect(logged).toContain(pluginRoot);
|
||||
});
|
||||
|
||||
it("honours PI2_ENSURE_TIMEOUT_MS when no timeout is passed", async () => {
|
||||
addWorkspace();
|
||||
process.env.PI2_ENSURE_TIMEOUT_MS = "700";
|
||||
const fake = writeFakeNvim(env.dir, { mode: "no-hello" });
|
||||
const mgr = await create({ bin: fake.bin, ensureTimeoutMs: null });
|
||||
|
||||
const started = Date.now();
|
||||
await expect(mgr.ensure("ws-1")).rejects.toMatchObject({
|
||||
code: "E_INSTANCE_STARTING",
|
||||
message: expect.stringContaining("did not say hello within 700ms"),
|
||||
});
|
||||
const elapsed = Date.now() - started;
|
||||
expect(elapsed).toBeGreaterThanOrEqual(600);
|
||||
expect(elapsed).toBeLessThan(3_000);
|
||||
});
|
||||
|
||||
it("reports E_INSTANCE_UNAVAILABLE when the nvim binary cannot be spawned", async () => {
|
||||
addWorkspace();
|
||||
const mgr = await create({ deps: { nvimBin: join(env.dir, "no-such-nvim") } });
|
||||
@@ -467,6 +608,18 @@ describe("InstanceManager", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ensure timeout override", () => {
|
||||
it("parses PI2_ENSURE_TIMEOUT_MS and ignores junk", () => {
|
||||
expect(parseEnsureTimeoutMs(undefined)).toBeUndefined();
|
||||
expect(parseEnsureTimeoutMs(" ")).toBeUndefined();
|
||||
expect(parseEnsureTimeoutMs("1500")).toBe(1500);
|
||||
expect(parseEnsureTimeoutMs("0")).toBeUndefined();
|
||||
expect(parseEnsureTimeoutMs("-20")).toBeUndefined();
|
||||
expect(parseEnsureTimeoutMs("1.5")).toBeUndefined();
|
||||
expect(parseEnsureTimeoutMs("abc")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resources helpers", () => {
|
||||
it("parses /proc/<pid>/status VmRSS", () => {
|
||||
expect(parseProcRss("Name:\tnvim\nVmRSS:\t 102400 kB\nVmSize:\t 204800 kB\n")).toBe(102400 * 1024);
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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);
|
||||
@@ -234,6 +281,37 @@ describe("workspace store", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("expands ~ and ~/… against the store's home before the allowlist check", async () => {
|
||||
const home = join(allowRoot, "home");
|
||||
const project = join(home, "project");
|
||||
mkdirSync(project, { recursive: true });
|
||||
const { store, registry } = setup({ env: { PI2_WORKSPACE_HIDE_TEMP: "0" }, home });
|
||||
|
||||
const root = await store.add({ cwd: "~" });
|
||||
expect(root.workspaceId).toBe(workspaceIdForCwd(home));
|
||||
expect(root.cwd).toBe(home);
|
||||
expect(root.alias).toBeNull();
|
||||
|
||||
const child = await store.add({ cwd: "~/project", alias: "Project" });
|
||||
expect(child.workspaceId).toBe(workspaceIdForCwd(project));
|
||||
expect(child.cwd).toBe(project);
|
||||
expect(child.alias).toBe("Project");
|
||||
expect(registry.list()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rejects ~user/… and names the accepted forms in the message", async () => {
|
||||
const { store } = setup({ home: allowRoot });
|
||||
|
||||
await expect(store.add({ cwd: "~alice/project" })).rejects.toMatchObject({
|
||||
code: "E_BAD_REQUEST",
|
||||
message: expect.stringContaining("cwd must be an absolute path (or start with ~/)"),
|
||||
});
|
||||
await expect(store.add({ cwd: "relative/project" })).rejects.toMatchObject({
|
||||
code: "E_BAD_REQUEST",
|
||||
message: expect.stringContaining("cwd must be an absolute path (or start with ~/)"),
|
||||
});
|
||||
});
|
||||
|
||||
it("validates relative, missing and non-directory paths", async () => {
|
||||
const file = join(allowRoot, "file.txt");
|
||||
writeFileSync(file, "x");
|
||||
|
||||
+1
-1
@@ -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",
|
||||
|
||||
@@ -17,7 +17,7 @@ import { useConnectionStore } from "@/stores/connection";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
function RouteTitle({ pathname }: { pathname: string }) {
|
||||
const { t } = useTranslation();
|
||||
@@ -105,6 +105,7 @@ export function AppShell() {
|
||||
const wsState = useConnectionStore((state) => state.wsState);
|
||||
const setWsState = useConnectionStore((state) => state.setWsState);
|
||||
const disconnect = useConnectionStore((state) => state.disconnect);
|
||||
const queryClient = useQueryClient();
|
||||
const isConnect = pathname.startsWith("/connect");
|
||||
// The chat page owns its own socket and already publishes wsState.
|
||||
const ownsSocket = !pathname.startsWith("/chat");
|
||||
@@ -173,6 +174,9 @@ export function AppShell() {
|
||||
const client = new PiWsClient({
|
||||
url: defaultWsUrl(),
|
||||
token: getDeviceToken(),
|
||||
// `instance_state` frames otherwise go nowhere on these pages: the card
|
||||
// grid reads the workspace row, so invalidate it (coalesced in ws.ts).
|
||||
queryClient,
|
||||
handlers: {
|
||||
onState: (state: WsConnectionState) => {
|
||||
if (active) setWsState(state);
|
||||
@@ -192,7 +196,7 @@ export function AppShell() {
|
||||
active = false;
|
||||
client.close();
|
||||
};
|
||||
}, [disconnect, href, isConnect, navigate, ownsSocket, paired, setWsState]);
|
||||
}, [disconnect, href, isConnect, navigate, ownsSocket, paired, queryClient, setWsState]);
|
||||
|
||||
/** ⌘K / Ctrl-K opens the palette on every navigation page (never on /connect). */
|
||||
useEffect(() => {
|
||||
|
||||
@@ -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/<id>/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 (
|
||||
<aside className="ws-activity" aria-label={t("workspaces.activity")} data-testid="workspaces-activity">
|
||||
<div className="ws-activity__head">
|
||||
<span className="section-label ws-activity__label">{t("workspaces.activity")}</span>
|
||||
{recent.length > 0 ? <span className="ws-activity__count tabular">{recent.length}</span> : null}
|
||||
{sessions.length > 0 ? <span className="ws-activity__count tabular">{sessions.length}</span> : null}
|
||||
</div>
|
||||
{recent.length > 0 ? (
|
||||
{sessions.length > 0 ? (
|
||||
<div className="ws-activity__list">
|
||||
{recent.map((workspace) => {
|
||||
const state = instanceState(workspace);
|
||||
return (
|
||||
<Link
|
||||
key={workspace.workspaceId}
|
||||
to="/chat"
|
||||
search={{ workspace: workspace.workspaceId }}
|
||||
className="ws-activity__row"
|
||||
data-workspace-id={workspace.workspaceId}
|
||||
data-testid="workspace-activity-row"
|
||||
>
|
||||
<StatusDot status={state.status} title={t(state.labelKey)} />
|
||||
<span className="ws-activity__main">
|
||||
<span className="ws-activity__name">
|
||||
{workspaceName(workspace, t("workspaces.unnamed"))}
|
||||
</span>
|
||||
<span className="ws-activity__ws">
|
||||
{plural("workspaces.sessionCount", workspaceSessionCount(workspace))}
|
||||
</span>
|
||||
</span>
|
||||
<RelativeTime ts={workspace.lastActiveAt} className="ws-activity__rel" />
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
{sessions.map((session) => (
|
||||
<ActivityRow key={session.sessionId} session={session} phrases={phrases} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Empty icon={<Icon name="clock" size={22} />} title={t("workspaces.activityEmpty")} />
|
||||
@@ -74,3 +50,35 @@ export function ActivityColumn({ workspaces }: ActivityColumnProps) {
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<Link
|
||||
to="/chat/$sessionId"
|
||||
params={{ sessionId: session.sessionId }}
|
||||
search={{ workspace: session.workspaceId }}
|
||||
className="ws-activity__row"
|
||||
data-session-id={session.sessionId}
|
||||
data-workspace-id={session.workspaceId}
|
||||
data-testid="workspace-activity-row"
|
||||
>
|
||||
<StatusDot status={dot.status} blink={dot.blink} title={label} />
|
||||
<span className="ws-activity__main">
|
||||
<span className="ws-activity__name">{title.text}</span>
|
||||
<span className="ws-activity__ws">{session.workspaceName}</span>
|
||||
</span>
|
||||
<RelativeTime ts={session.ts || null} className="ws-activity__rel" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -21,22 +21,61 @@ function extractWorkspaceId(result: CommandResult): string | undefined {
|
||||
);
|
||||
}
|
||||
|
||||
/** Trailing slashes are noise; the daemon stores the canonical path either way. */
|
||||
function samePath(a: string, b: string): boolean {
|
||||
const normalize = (value: string) => value.trim().replace(/\/+$/, "");
|
||||
return normalize(a) === normalize(b);
|
||||
}
|
||||
|
||||
function matchesName(workspace: WorkspaceInfo, name: string): boolean {
|
||||
return (workspace.name?.trim() || workspace.alias?.trim()) === name;
|
||||
}
|
||||
|
||||
function findCreated(list: WorkspaceInfo[], cwd: string, name: string): WorkspaceInfo | undefined {
|
||||
const exact = list.find((item) => item.cwd === cwd && (name ? item.name === name : true));
|
||||
if (exact) return exact;
|
||||
return list.find((item) => item.cwd === cwd);
|
||||
// `~` paths never match on cwd (the daemon expands them), so fall back to the
|
||||
// display name the caller just typed.
|
||||
const byPathAndName = list.find((item) => samePath(item.cwd, cwd) && (name ? matchesName(item, name) : true));
|
||||
if (byPathAndName) return byPathAndName;
|
||||
const byPath = list.find((item) => samePath(item.cwd, cwd));
|
||||
if (byPath) return byPath;
|
||||
return name ? list.find((item) => matchesName(item, name)) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `workspace.add` succeeded but its instance did not start. The workspace id is
|
||||
* already known, so the dialog can retry `instance.ensure` without adding twice.
|
||||
*/
|
||||
export class InstanceStartError extends Error {
|
||||
readonly workspaceId: string;
|
||||
/** Whatever `instance.ensure` threw (usually an `ApiError`). */
|
||||
readonly detail: unknown;
|
||||
|
||||
constructor(workspaceId: string, detail: unknown) {
|
||||
super(detail instanceof Error ? detail.message : String(detail));
|
||||
this.name = "InstanceStartError";
|
||||
this.workspaceId = workspaceId;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
/** `instance.ensure` is idempotent (docs/protocol.md §3), so retrying it is safe. */
|
||||
export async function ensureInstance(workspaceId: string): Promise<void> {
|
||||
await api.command({ method: "instance.ensure", params: { workspaceId } });
|
||||
}
|
||||
|
||||
/**
|
||||
* `workspace.add` → resolve the new workspace id (the command response is not
|
||||
* required to carry it, so fall back to a fresh GET) → `instance.ensure`.
|
||||
*
|
||||
* The daemon owns path expansion: `~/…` and `~` are sent verbatim and resolved
|
||||
* there, and the display name travels as `alias` (the field it persists).
|
||||
*/
|
||||
export async function openWorkspace(input: { cwd: string; name?: string }): Promise<string> {
|
||||
const cwd = input.cwd.trim();
|
||||
const name = input.name?.trim() ?? "";
|
||||
const added = (await api.command({
|
||||
method: "workspace.add",
|
||||
params: { cwd, ...(name ? { name } : {}) },
|
||||
params: { cwd, ...(name ? { alias: name } : {}) },
|
||||
})) as unknown as CommandResult;
|
||||
|
||||
let workspaceId = extractWorkspaceId(added);
|
||||
@@ -48,7 +87,11 @@ export async function openWorkspace(input: { cwd: string; name?: string }): Prom
|
||||
throw new Error("workspace.add returned no workspace id");
|
||||
}
|
||||
|
||||
await api.command({ method: "instance.ensure", params: { workspaceId } });
|
||||
try {
|
||||
await ensureInstance(workspaceId);
|
||||
} catch (error) {
|
||||
throw new InstanceStartError(workspaceId, error);
|
||||
}
|
||||
return workspaceId;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -7,6 +8,8 @@ import { Modal } from "@/components/ui/dialog";
|
||||
import { Field, Input } from "@/components/ui/input";
|
||||
import { ApiError, errorI18nKey } from "@/lib/api";
|
||||
|
||||
import { ensureInstance, InstanceStartError } from "./commands";
|
||||
|
||||
export interface NewWorkspaceInput {
|
||||
cwd: string;
|
||||
name?: string;
|
||||
@@ -16,15 +19,95 @@ export interface NewWorkspaceDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCreate: (input: NewWorkspaceInput) => Promise<void>;
|
||||
/** Runs after a successful retry of `instance.ensure`; the page finishes the open. */
|
||||
onRetryOpen?: (workspaceId: string) => void | Promise<void>;
|
||||
}
|
||||
|
||||
/** Path is required, display name optional; validation is inline, not a toast. */
|
||||
export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspaceDialogProps) {
|
||||
/** Longest daemon message echoed back: they are debug strings, not UI copy. */
|
||||
const MAX_DETAIL = 200;
|
||||
|
||||
/**
|
||||
* A path the daemon accepts as typed: absolute, or `~` / `~/…` (it expands the
|
||||
* home directory itself — `~user/…` is deliberately the daemon's call, not ours).
|
||||
*/
|
||||
export function isAbsoluteOrHomePath(value: string): boolean {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.startsWith("/") || trimmed === "~" || trimmed.startsWith("~/");
|
||||
}
|
||||
|
||||
/** Shorten a daemon message; never echo a JSON blob back at the user. */
|
||||
export function humanDetail(message: string | undefined): string | undefined {
|
||||
const text = message?.trim();
|
||||
if (!text) return undefined;
|
||||
if (text.startsWith("{") || text.startsWith("[")) return undefined;
|
||||
return text.length > MAX_DETAIL ? `${text.slice(0, MAX_DETAIL - 1)}…` : text;
|
||||
}
|
||||
|
||||
interface FailureText {
|
||||
message: string;
|
||||
/** Extra daemon text, rendered monospace and wrapped. */
|
||||
detail?: string;
|
||||
/** The message itself embeds a reason, so it needs the monospace/wrap treatment. */
|
||||
reasonStyle?: boolean;
|
||||
}
|
||||
|
||||
function reasonFrom(error: ApiError): string | undefined {
|
||||
const fromDetails = error.details?.["reason"];
|
||||
const raw = typeof fromDetails === "string" ? fromDetails : error.message;
|
||||
return humanDetail(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn an open failure into something specific: code → status → daemon message.
|
||||
* The user must learn *why* nothing happened, not read `E_FORBIDDEN`.
|
||||
*/
|
||||
export function describeOpenFailure(error: unknown, t: TFunction): FailureText {
|
||||
if (!(error instanceof ApiError)) {
|
||||
const detail = humanDetail(error instanceof Error ? error.message : undefined);
|
||||
return { message: t("workspaces.addFailed"), ...(detail ? { detail } : {}) };
|
||||
}
|
||||
|
||||
const message = error.message ?? "";
|
||||
const lower = message.toLowerCase();
|
||||
|
||||
if (error.status === 404 || error.code === "E_NOT_FOUND") {
|
||||
return { message: t("workspaces.errNotFound") };
|
||||
}
|
||||
|
||||
if (error.status === 403 || error.code === "E_FORBIDDEN") {
|
||||
if (lower.includes("root")) return { message: t("workspaces.errOutsideRoots") };
|
||||
if (lower.includes("readable") || lower.includes("writable") || lower.includes("access")) {
|
||||
return { message: t("workspaces.errPermission") };
|
||||
}
|
||||
return { message: t(errorI18nKey(error.code)) };
|
||||
}
|
||||
|
||||
if (error.status === 400 || error.code === "E_BAD_REQUEST") {
|
||||
if (lower.includes("absolute") || lower.includes("~")) return { message: t("workspaces.errNotAbsolute") };
|
||||
return { message: t("workspaces.errBadPath") };
|
||||
}
|
||||
|
||||
if (error.code === "E_INSTANCE_STARTING" || error.code === "E_INSTANCE_UNAVAILABLE") {
|
||||
const reason = reasonFrom(error) ?? t("workspaces.errInstanceUnknown");
|
||||
return { message: t("workspaces.errInstanceFailed", { reason }), reasonStyle: true };
|
||||
}
|
||||
|
||||
const detail = humanDetail(message);
|
||||
return { message: t(errorI18nKey(error.code)), ...(detail ? { detail } : {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Path is required, display name optional; validation is inline, not a toast.
|
||||
* A failed open keeps the dialog open with the concrete reason, and a failure
|
||||
* that happened after `workspace.add` offers a retry of `instance.ensure` only.
|
||||
*/
|
||||
export function NewWorkspaceDialog({ open, onOpenChange, onCreate, onRetryOpen }: NewWorkspaceDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [cwd, setCwd] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [pathError, setPathError] = useState<string | null>(null);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [failure, setFailure] = useState<FailureText | null>(null);
|
||||
const [retryId, setRetryId] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -32,7 +115,8 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
|
||||
setCwd("");
|
||||
setName("");
|
||||
setPathError(null);
|
||||
setFormError(null);
|
||||
setFailure(null);
|
||||
setRetryId(null);
|
||||
setBusy(false);
|
||||
}, [open]);
|
||||
|
||||
@@ -42,18 +126,44 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
|
||||
const trimmed = cwd.trim();
|
||||
if (!trimmed) {
|
||||
setPathError(t("workspaces.pathRequired"));
|
||||
setFormError(null);
|
||||
setFailure(null);
|
||||
return;
|
||||
}
|
||||
if (!isAbsoluteOrHomePath(trimmed)) {
|
||||
setPathError(t("workspaces.errNotAbsolute"));
|
||||
setFailure(null);
|
||||
return;
|
||||
}
|
||||
setPathError(null);
|
||||
setFormError(null);
|
||||
setFailure(null);
|
||||
setRetryId(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await onCreate({ cwd: trimmed, ...(name.trim() ? { name: name.trim() } : {}) });
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
const key = error instanceof ApiError ? errorI18nKey(error.code) : "workspaces.addFailed";
|
||||
setFormError(t(key));
|
||||
if (error instanceof InstanceStartError) {
|
||||
setRetryId(error.workspaceId);
|
||||
setFailure(describeOpenFailure(error.detail, t));
|
||||
} else {
|
||||
setFailure(describeOpenFailure(error, t));
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-run only `instance.ensure` for the workspace that was already created. */
|
||||
async function retry() {
|
||||
if (!retryId || busy) return;
|
||||
setBusy(true);
|
||||
setFailure(null);
|
||||
try {
|
||||
await ensureInstance(retryId);
|
||||
await onRetryOpen?.(retryId);
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
setFailure(describeOpenFailure(error, t));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -69,6 +179,11 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
{retryId ? (
|
||||
<Button variant="ghost" onClick={() => void retry()} disabled={busy} data-testid="workspace-retry-instance">
|
||||
{t("workspaces.retry")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="primary" type="submit" form="new-workspace-form" disabled={busy}>
|
||||
{busy ? t("workspaces.creating") : t("common.open")}
|
||||
</Button>
|
||||
@@ -103,10 +218,19 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
|
||||
<div className="ws-modal-example mono" aria-hidden="true">
|
||||
~/Workspace/Misc/my-project
|
||||
</div>
|
||||
{formError ? (
|
||||
<div className="ws-form__error" role="alert">
|
||||
{failure ? (
|
||||
<div
|
||||
className={failure.reasonStyle ? "ws-form__error ws-form__error--reason" : "ws-form__error"}
|
||||
role="alert"
|
||||
data-testid="workspace-form-error"
|
||||
>
|
||||
<Icon name="alert" />
|
||||
<span>{formError}</span>
|
||||
<span className="ws-form__message">{failure.message}</span>
|
||||
{failure.detail ? (
|
||||
<span className="ws-form__detail mono" title={failure.detail}>
|
||||
{failure.detail}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
|
||||
@@ -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<string, unknown> | undefined {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : 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<string, { disk?: RecentSessionInfo; live?: SessionState }>();
|
||||
|
||||
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<unknown>(`/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],
|
||||
);
|
||||
}
|
||||
@@ -19,7 +19,10 @@ import { isSecondary, reasonLabelKey } from "./visibility";
|
||||
*/
|
||||
export function instanceState(workspace: WorkspaceInfo): { status: DotStatus; labelKey: string } {
|
||||
if (!workspace.exists) return { status: "err", labelKey: "workspaces.instanceMissing" };
|
||||
switch (workspace.instance?.status) {
|
||||
// No instance row at all means "not started yet": this daemon starts one on
|
||||
// demand (opening the workspace), so "stopped" would be a lie.
|
||||
if (!workspace.instance) return { status: "idle", labelKey: "workspaces.instanceNotStarted" };
|
||||
switch (workspace.instance.status) {
|
||||
case "ready":
|
||||
return { status: "ok", labelKey: "workspaces.instanceReady" };
|
||||
case "starting":
|
||||
@@ -36,6 +39,20 @@ export function instanceState(workspace: WorkspaceInfo): { status: DotStatus; la
|
||||
}
|
||||
}
|
||||
|
||||
/** Statuses where the daemon's `instance.reason` explains the label below it. */
|
||||
const REASON_STATUSES: ReadonlySet<string> = new Set(["degraded", "stopped", "unmanaged"]);
|
||||
|
||||
/**
|
||||
* The instance's own explanation, but only for the states where it adds
|
||||
* information (a `ready` instance can still carry a stale reason).
|
||||
*/
|
||||
export function instanceReason(workspace: WorkspaceInfo): string | undefined {
|
||||
const instance = workspace.instance;
|
||||
const reason = instance?.reason?.trim();
|
||||
if (!instance || !reason) return undefined;
|
||||
return REASON_STATUSES.has(instance.status) ? reason : undefined;
|
||||
}
|
||||
|
||||
export interface WorkspaceCardProps {
|
||||
workspace: WorkspaceInfo;
|
||||
}
|
||||
@@ -56,6 +73,7 @@ export function WorkspaceCard({ workspace }: WorkspaceCardProps) {
|
||||
// *whether* they render at all (see features/workspaces/visibility.ts).
|
||||
const secondary = isSecondary(workspace);
|
||||
const reasonKey = secondary ? reasonLabelKey(workspace) : null;
|
||||
const detail = instanceReason(workspace);
|
||||
|
||||
return (
|
||||
<Link
|
||||
@@ -80,6 +98,12 @@ export function WorkspaceCard({ workspace }: WorkspaceCardProps) {
|
||||
</span>
|
||||
</div>
|
||||
<div className="ws-card__cwd mono truncate">{workspace.cwd}</div>
|
||||
{detail ? (
|
||||
// Full text stays in `title`; the line itself is ellipsized by CSS.
|
||||
<div className="ws-card__note truncate" title={detail} data-testid="workspace-instance-reason">
|
||||
{detail}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="ws-card__last">
|
||||
{count > 0 ? (
|
||||
<>
|
||||
|
||||
@@ -10,8 +10,45 @@
|
||||
* The auth frame is the first frame on every socket, before any subscribe.
|
||||
*/
|
||||
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
export type WsConnectionState = "idle" | "connecting" | "authenticating" | "open" | "reconnecting" | "closed";
|
||||
|
||||
/**
|
||||
* Query keys a live `instance_state` makes stale. A workspace card renders
|
||||
* `WorkspaceInfo.instance`, which the frame does not carry, so refetching the row
|
||||
* is the only honest update.
|
||||
*/
|
||||
const INSTANCE_STATE_QUERY_KEYS: readonly (readonly string[])[] = [["workspaces"], ["health"]];
|
||||
|
||||
/** Burst window: `starting → ready` lands inside one startup step. */
|
||||
export const INSTANCE_STATE_COALESCE_MS = 250;
|
||||
|
||||
let invalidationTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let invalidationClient: QueryClient | null = null;
|
||||
|
||||
/**
|
||||
* Coalesce `instance_state` bursts into a single invalidation round. Module-level
|
||||
* on purpose: the console opens more than one socket (shell probe + chat), and a
|
||||
* per-client timer would refetch twice per state change.
|
||||
*/
|
||||
export function scheduleInstanceStateInvalidation(
|
||||
queryClient: QueryClient,
|
||||
delayMs: number = INSTANCE_STATE_COALESCE_MS,
|
||||
): void {
|
||||
invalidationClient = queryClient;
|
||||
if (invalidationTimer !== null) return;
|
||||
invalidationTimer = setTimeout(() => {
|
||||
const client = invalidationClient;
|
||||
invalidationTimer = null;
|
||||
invalidationClient = null;
|
||||
if (!client) return;
|
||||
for (const queryKey of INSTANCE_STATE_QUERY_KEYS) {
|
||||
void client.invalidateQueries({ queryKey: [...queryKey] });
|
||||
}
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
export interface WsFrame {
|
||||
v?: number;
|
||||
type: string;
|
||||
@@ -72,6 +109,13 @@ export interface PiWsOptions {
|
||||
authTimeoutMs?: number;
|
||||
/** 0 disables the keep-alive ping. */
|
||||
heartbeatMs?: number;
|
||||
/**
|
||||
* Optional cache handle: an `instance_state` frame invalidates `['workspaces']`
|
||||
* and `['health']` through it (coalesced) instead of being dropped.
|
||||
*/
|
||||
queryClient?: QueryClient | null;
|
||||
/** Override for the `instance_state` coalescing window (tests). */
|
||||
instanceStateCoalesceMs?: number;
|
||||
handlers?: WsHandlers;
|
||||
}
|
||||
|
||||
@@ -118,6 +162,8 @@ export class PiWsClient {
|
||||
private socket: WebSocketLike | null = null;
|
||||
private state: WsConnectionState = "idle";
|
||||
private token: string | null;
|
||||
private queryClient: QueryClient | null;
|
||||
private readonly instanceStateCoalesceMs: number;
|
||||
private attempt = 0;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private authTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -136,6 +182,8 @@ export class PiWsClient {
|
||||
this.backoffMultiplier = options.backoffMultiplier ?? 2;
|
||||
this.authTimeoutMs = options.authTimeoutMs ?? 8_000;
|
||||
this.heartbeatMs = options.heartbeatMs ?? 25_000;
|
||||
this.queryClient = options.queryClient ?? null;
|
||||
this.instanceStateCoalesceMs = options.instanceStateCoalesceMs ?? INSTANCE_STATE_COALESCE_MS;
|
||||
this.handlers = options.handlers ?? {};
|
||||
}
|
||||
|
||||
@@ -159,6 +207,11 @@ export class PiWsClient {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
/** Late-bound cache handle (the app mounts the provider after the client). */
|
||||
setQueryClient(queryClient: QueryClient | null): void {
|
||||
this.queryClient = queryClient;
|
||||
}
|
||||
|
||||
connect(): void {
|
||||
if (this.state === "connecting" || this.state === "authenticating" || this.state === "open") return;
|
||||
this.manuallyClosed = false;
|
||||
@@ -433,6 +486,15 @@ export class PiWsClient {
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "instance_state": {
|
||||
// The frame carries the instance status (and its sessions), but the
|
||||
// workspace row itself lives in `['workspaces']`; patch-free updates
|
||||
// mean a refetch rather than a guess. Unknown frames stay ignored.
|
||||
if (this.queryClient) {
|
||||
scheduleInstanceStateInvalidation(this.queryClient, this.instanceStateCoalesceMs);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "pong":
|
||||
case "presence":
|
||||
case "dropped":
|
||||
|
||||
@@ -667,11 +667,19 @@
|
||||
"workspaces.emptyText": "Open a working directory (cwd) to get started.",
|
||||
"workspaces.emptyTitle": "No workspaces yet",
|
||||
"workspaces.enter": "Enter →",
|
||||
"workspaces.errPermission": "The daemon cannot read and write that directory",
|
||||
"workspaces.errOutsideRoots": "That path is outside the workspace roots the daemon allows",
|
||||
"workspaces.errNotFound": "No such directory on the server",
|
||||
"workspaces.errNotAbsolute": "Enter an absolute path, or a path that starts with ~/",
|
||||
"workspaces.errInstanceUnknown": "no reason reported by the server",
|
||||
"workspaces.errInstanceFailed": "The workspace was added, but its Neovim instance did not start: {reason}",
|
||||
"workspaces.errBadPath": "The server rejected that path. Check the directory name and try again.",
|
||||
"workspaces.hiddenHint": "These entries stay out of the list by default.",
|
||||
"workspaces.hideHidden": "Hide {n} hidden",
|
||||
"workspaces.idle": "Idle",
|
||||
"workspaces.instanceDegraded": "Instance degraded",
|
||||
"workspaces.instanceMissing": "Working directory is missing",
|
||||
"workspaces.instanceNotStarted": "Not started · opens on demand",
|
||||
"workspaces.instanceReady": "Instance ready",
|
||||
"workspaces.instanceStarting": "Instance starting",
|
||||
"workspaces.instanceStopped": "Instance stopped",
|
||||
@@ -695,6 +703,7 @@
|
||||
"workspaces.reason.outside-roots": "outside roots",
|
||||
"workspaces.reason.stale": "stale",
|
||||
"workspaces.reason.temp": "temp",
|
||||
"workspaces.retry": "Retry starting Neovim",
|
||||
"workspaces.serverSummary": "{sessions} sessions · {running} running",
|
||||
"workspaces.sessionCount": "{n} sessions",
|
||||
"workspaces.sessionCount.one": "{n} session",
|
||||
|
||||
@@ -667,11 +667,19 @@
|
||||
"workspaces.emptyText": "打开一个工作目录(cwd)开始。",
|
||||
"workspaces.emptyTitle": "还没有工作空间",
|
||||
"workspaces.enter": "进入 →",
|
||||
"workspaces.errPermission": "守护进程没有该目录的读写权限",
|
||||
"workspaces.errOutsideRoots": "这个路径不在守护进程允许的工作区根目录内",
|
||||
"workspaces.errNotFound": "服务器上找不到这个目录",
|
||||
"workspaces.errNotAbsolute": "请填入绝对路径,或以 ~/ 开头的路径",
|
||||
"workspaces.errInstanceUnknown": "服务器没有给出原因",
|
||||
"workspaces.errInstanceFailed": "工作区已添加,但 Neovim 实例没能启动:{reason}",
|
||||
"workspaces.errBadPath": "服务器不接受这个路径,请检查目录名后重试",
|
||||
"workspaces.hiddenHint": "这些条目默认不出现在列表中。",
|
||||
"workspaces.hideHidden": "隐藏 {n} 个隐藏项",
|
||||
"workspaces.idle": "空闲",
|
||||
"workspaces.instanceDegraded": "实例降级",
|
||||
"workspaces.instanceMissing": "工作目录不存在",
|
||||
"workspaces.instanceNotStarted": "未启动 · 打开时自动启动",
|
||||
"workspaces.instanceReady": "实例已就绪",
|
||||
"workspaces.instanceStarting": "实例正在启动",
|
||||
"workspaces.instanceStopped": "实例已停止",
|
||||
@@ -695,6 +703,7 @@
|
||||
"workspaces.reason.outside-roots": "根目录外",
|
||||
"workspaces.reason.stale": "长期未动",
|
||||
"workspaces.reason.temp": "临时目录",
|
||||
"workspaces.retry": "重试启动 Neovim",
|
||||
"workspaces.serverSummary": "{sessions} 个会话 · {running} 个运行中",
|
||||
"workspaces.sessionCount": "{n} 个会话",
|
||||
"workspaces.sessionCount.one": "{n} 个会话",
|
||||
|
||||
@@ -96,8 +96,13 @@ export function WorkspacesPage() {
|
||||
|
||||
async function createWorkspace(input: NewWorkspaceInput) {
|
||||
const workspaceId = await openWorkspace(input);
|
||||
await finishOpen(workspaceId, input.name?.trim() || basename(input.cwd));
|
||||
}
|
||||
|
||||
/** Shared tail of a successful open: refresh the grid, toast, enter chat. */
|
||||
async function finishOpen(workspaceId: string, label: string) {
|
||||
await queryClient.invalidateQueries({ queryKey: ["workspaces"] });
|
||||
toast.success(t("workspaces.opened", { name: input.name?.trim() || basename(input.cwd) }));
|
||||
toast.success(t("workspaces.opened", { name: label }));
|
||||
navigate({ href: `/chat?workspace=${encodeURIComponent(workspaceId)}` });
|
||||
}
|
||||
|
||||
@@ -228,7 +233,16 @@ export function WorkspacesPage() {
|
||||
<ActivityColumn workspaces={items} />
|
||||
</div>
|
||||
|
||||
<NewWorkspaceDialog open={dialogOpen} onOpenChange={setDialogOpen} onCreate={createWorkspace} />
|
||||
<NewWorkspaceDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
onCreate={createWorkspace}
|
||||
onRetryOpen={(workspaceId) => {
|
||||
// The workspace already exists; the name is settled server-side.
|
||||
const row = all.find((item) => item.workspaceId === workspaceId);
|
||||
return finishOpen(workspaceId, row?.name?.trim() || (row ? basename(row.cwd) : workspaceId));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
|
||||
|
||||
@@ -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 按钮) ---------- */
|
||||
@@ -118,6 +118,13 @@
|
||||
font-size: var(--fs-xs); line-height: 1.45;
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
/* 实例自己给出的原因(degraded/stopped/unmanaged):单行截断,完整文本在 title 里 */
|
||||
.ws-card__note {
|
||||
min-width: 0;
|
||||
font-size: var(--fs-2xs); line-height: 1.45;
|
||||
color: var(--destructive);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.ws-card__last {
|
||||
display: flex; align-items: baseline; gap: 6px;
|
||||
min-width: 0;
|
||||
@@ -244,12 +251,31 @@
|
||||
.ws-form .field { margin-bottom: 0; }
|
||||
.ws-form__error {
|
||||
display: flex; align-items: flex-start; gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
padding: var(--space-1) 0 var(--space-1) var(--space-3);
|
||||
border-left: 2px solid var(--destructive);
|
||||
color: var(--destructive);
|
||||
font-size: var(--fs-sm);
|
||||
}
|
||||
.ws-form__error svg { flex: none; margin-top: 2px; }
|
||||
.ws-form__error .ws-form__message { min-width: 0; }
|
||||
/* 守护进程的原文:等宽 + 换行,绝不二次截断成一行 */
|
||||
.ws-form__error--reason .ws-form__message {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-word;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-xs);
|
||||
}
|
||||
.ws-form__detail {
|
||||
flex: 1 1 100%;
|
||||
margin-top: 2px;
|
||||
padding-left: calc(var(--space-2) + 12px);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--fs-2xs);
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
.ws-modal-example {
|
||||
margin-top: calc(-1 * var(--space-2));
|
||||
padding: 6px 9px;
|
||||
|
||||
@@ -34,10 +34,32 @@ function routes() {
|
||||
return [
|
||||
{ path: "/workspaces", component: WorkspacesPage },
|
||||
{ path: "/chat", component: () => <div>Chat destination</div> },
|
||||
{ path: "/chat/$sessionId", component: () => <div>Chat session destination</div> },
|
||||
{ path: "/status", component: () => <div>Status destination</div> },
|
||||
];
|
||||
}
|
||||
|
||||
/** 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<string, unknown> & { 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",
|
||||
@@ -291,10 +379,201 @@ describe("WorkspacesPage", () => {
|
||||
|
||||
const commands = commandCalls(fetchMock);
|
||||
expect(commands.map((command) => command.method)).toEqual(["workspace.add", "instance.ensure"]);
|
||||
// The daemon persists the display name as `alias` (`name` is not a param).
|
||||
expect(commands[0]?.params).toEqual({ cwd: "/work/new", alias: "New project" });
|
||||
expect(commands[1]?.params).toEqual({ workspaceId: "ws-new" });
|
||||
expect(await screen.findByText("Chat destination")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("rejects a relative path inline instead of round-tripping to the daemon", async () => {
|
||||
const fetchMock = mockApi([
|
||||
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||
{
|
||||
path: "/api/v1/workspaces",
|
||||
handler: () => ({ body: [workspace({ workspaceId: "ws-old", cwd: "/work/old", name: "Old project" })] }),
|
||||
},
|
||||
recentRoute(),
|
||||
]);
|
||||
|
||||
await renderPage(routes(), "/workspaces", { paired: true });
|
||||
await waitForCards(1);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Open new workspace" }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
fireEvent.change(within(dialog).getByLabelText("Path"), { target: { value: "work/relative" } });
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Open" }));
|
||||
|
||||
expect(
|
||||
await within(dialog).findByText("Enter an absolute path, or a path that starts with ~/"),
|
||||
).toBeInTheDocument();
|
||||
expect(commandCalls(fetchMock)).toHaveLength(0);
|
||||
// Stays open so the path can be corrected in place.
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("sends a ~ path verbatim and lets the daemon expand it", async () => {
|
||||
const fetchMock = mockApi([
|
||||
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||
{
|
||||
path: "/api/v1/workspaces",
|
||||
handler: () => ({ body: [workspace({ workspaceId: "ws-old", cwd: "/work/old", name: "Old project" })] }),
|
||||
},
|
||||
recentRoute(),
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/v1/cmd",
|
||||
handler: ({ body }) => {
|
||||
const command = body as { method?: string };
|
||||
if (command.method === "workspace.add") return { body: { accepted: true, workspaceId: "ws-home" } };
|
||||
return { body: { accepted: true } };
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const { router } = await renderPage(routes(), "/workspaces", { paired: true });
|
||||
await waitForCards(1);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Open new workspace" }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
fireEvent.change(within(dialog).getByLabelText("Path"), { target: { value: "~/Workspace/Misc/my-project" } });
|
||||
fireEvent.change(within(dialog).getByLabelText("Display name"), { target: { value: "My project" } });
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Open" }));
|
||||
|
||||
await waitFor(() => expect(router.state.location.pathname).toBe("/chat"));
|
||||
const commands = commandCalls(fetchMock);
|
||||
expect(commands.map((command) => command.method)).toEqual(["workspace.add", "instance.ensure"]);
|
||||
// Verbatim `~`: the daemon owns home expansion, the browser must not guess.
|
||||
expect(commands[0]?.params).toEqual({ cwd: "~/Workspace/Misc/my-project", alias: "My project" });
|
||||
expect(commands[1]?.params).toEqual({ workspaceId: "ws-home" });
|
||||
});
|
||||
|
||||
it("keeps the dialog open with the daemon reason, then retries only instance.ensure", async () => {
|
||||
let ensures = 0;
|
||||
let items = [workspace({ workspaceId: "ws-old", cwd: "/work/old", name: "Old project" })];
|
||||
const fetchMock = mockApi([
|
||||
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
|
||||
recentRoute(),
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/v1/cmd",
|
||||
handler: ({ body }) => {
|
||||
const command = body as { method?: string };
|
||||
if (command.method === "workspace.add") {
|
||||
items = [...items, workspace({ workspaceId: "ws-new", cwd: "/work/new", name: "New project" })];
|
||||
return { body: { accepted: true, workspaceId: "ws-new" } };
|
||||
}
|
||||
ensures += 1;
|
||||
if (ensures === 1) {
|
||||
return {
|
||||
status: 503,
|
||||
body: {
|
||||
error: {
|
||||
code: "E_INSTANCE_UNAVAILABLE",
|
||||
message: "nvim exited during startup (code 1)",
|
||||
retryable: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
return { body: { accepted: true } };
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const { router } = await renderPage(routes(), "/workspaces", { paired: true });
|
||||
await waitForCards(1);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Open new workspace" }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
fireEvent.change(within(dialog).getByLabelText("Path"), { target: { value: "/work/new" } });
|
||||
fireEvent.change(within(dialog).getByLabelText("Display name"), { target: { value: "New project" } });
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Open" }));
|
||||
|
||||
const alert = await within(dialog).findByTestId("workspace-form-error");
|
||||
// The reason the user can act on, not a code and never a JSON blob.
|
||||
expect(alert).toHaveTextContent("nvim exited during startup (code 1)");
|
||||
expect(alert.textContent ?? "").not.toContain("E_INSTANCE_UNAVAILABLE");
|
||||
expect(alert.textContent ?? "").not.toContain("{");
|
||||
expect(alert.className).toContain("ws-form__error--reason");
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
expect(router.state.location.pathname).toBe("/workspaces");
|
||||
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Retry starting Neovim" }));
|
||||
|
||||
await waitFor(() => expect(router.state.location.pathname).toBe("/chat"));
|
||||
expect(router.state.location.href).toContain("workspace=ws-new");
|
||||
const commands = commandCalls(fetchMock);
|
||||
// One extra instance.ensure only: the workspace was not added a second time.
|
||||
expect(commands.map((command) => command.method)).toEqual(["workspace.add", "instance.ensure", "instance.ensure"]);
|
||||
expect(commands[2]?.params).toEqual({ workspaceId: "ws-new" });
|
||||
});
|
||||
|
||||
it("renders a not-yet-started workspace as idle and explains a degraded instance", async () => {
|
||||
const items = [
|
||||
workspace({ workspaceId: "ws-new", cwd: "/work/new", name: "Not started" }),
|
||||
workspace({
|
||||
workspaceId: "ws-bad",
|
||||
cwd: "/work/bad",
|
||||
name: "Degraded",
|
||||
instance: {
|
||||
workspaceId: "ws-bad",
|
||||
instanceId: "inst-bad",
|
||||
status: "degraded",
|
||||
nvimPid: 42,
|
||||
pluginVersion: null,
|
||||
hasUI: false,
|
||||
attachedClients: 0,
|
||||
listenAddr: null,
|
||||
startedAt: 1_000,
|
||||
reason: "plugin handshake timed out after 1500ms",
|
||||
},
|
||||
}),
|
||||
workspace({
|
||||
workspaceId: "ws-busy",
|
||||
cwd: "/work/busy",
|
||||
name: "Running",
|
||||
instance: {
|
||||
workspaceId: "ws-busy",
|
||||
instanceId: "inst-busy",
|
||||
status: "ready",
|
||||
nvimPid: 43,
|
||||
pluginVersion: "0.1.1",
|
||||
hasUI: true,
|
||||
attachedClients: 1,
|
||||
listenAddr: "127.0.0.1:7779",
|
||||
startedAt: 2_000,
|
||||
reason: "stale startup note",
|
||||
},
|
||||
}),
|
||||
];
|
||||
mockApi([
|
||||
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
|
||||
recentRoute(),
|
||||
]);
|
||||
|
||||
await renderPage(routes(), "/workspaces", { paired: true });
|
||||
await waitForCards(3);
|
||||
|
||||
const rows = screen.getAllByTestId("workspace-row");
|
||||
const [notStarted, degraded, ready] = rows;
|
||||
// No instance row means "opens on demand", not "stopped".
|
||||
expect(notStarted?.querySelector(".ws-card__state .dot")).toHaveClass("dot--idle");
|
||||
expect(notStarted?.querySelector(".ws-card__state")).toHaveTextContent("Not started · opens on demand");
|
||||
expect(notStarted?.querySelector(".ws-card__state")).not.toHaveTextContent("Instance stopped");
|
||||
expect(notStarted?.querySelector('[data-testid="workspace-instance-reason"]')).toBeNull();
|
||||
|
||||
const reason = degraded?.querySelector('[data-testid="workspace-instance-reason"]');
|
||||
expect(reason).toHaveTextContent("plugin handshake timed out after 1500ms");
|
||||
expect(reason).toHaveAttribute("title", "plugin handshake timed out after 1500ms");
|
||||
expect(degraded?.querySelector(".ws-card__state")).toHaveTextContent("Instance degraded");
|
||||
|
||||
// A healthy instance keeps its plain label (a stale reason is not news).
|
||||
expect(ready?.querySelector(".ws-card__state")).toHaveTextContent("Instance ready");
|
||||
expect(ready?.querySelector('[data-testid="workspace-instance-reason"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("redirects /workspace/:workspaceId deep links into chat", async () => {
|
||||
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
|
||||
const { router } = await renderPage(
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { QueryClient, QueryObserver } from "@tanstack/react-query";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
import { PiWsClient, type WebSocketLike, type WsFrame } from "@/lib/ws";
|
||||
|
||||
/** Same fake socket as `ws.test.ts`: no real transport anywhere in unit tests. */
|
||||
class FakeSocket implements WebSocketLike {
|
||||
readyState = 0;
|
||||
sent: WsFrame[] = [];
|
||||
closed = false;
|
||||
onopen: ((event: unknown) => void) | null = null;
|
||||
onmessage: ((event: { data: unknown }) => void) | null = null;
|
||||
onclose: ((event: { code?: number; reason?: string }) => void) | null = null;
|
||||
onerror: ((event: unknown) => void) | null = null;
|
||||
|
||||
send(data: string): void {
|
||||
this.sent.push(JSON.parse(data) as WsFrame);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.readyState = 3;
|
||||
this.onclose?.({ code: 1000, reason: "closed" });
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.readyState = 1;
|
||||
this.onopen?.({});
|
||||
}
|
||||
|
||||
receive(frame: Record<string, unknown>): void {
|
||||
this.onmessage?.({ data: JSON.stringify(frame) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Short window so the coalescing assertions stay fast without fake timers. */
|
||||
const COALESCE_MS = 20;
|
||||
|
||||
function connect(queryClient?: QueryClient) {
|
||||
const sockets: FakeSocket[] = [];
|
||||
const client = new PiWsClient({
|
||||
url: "ws://127.0.0.1:7676/api/v1/ws",
|
||||
token: "pkt_test",
|
||||
heartbeatMs: 0,
|
||||
instanceStateCoalesceMs: COALESCE_MS,
|
||||
...(queryClient ? { queryClient } : {}),
|
||||
socketFactory: () => {
|
||||
const socket = new FakeSocket();
|
||||
sockets.push(socket);
|
||||
return socket;
|
||||
},
|
||||
});
|
||||
client.connect();
|
||||
const socket = sockets[0]!;
|
||||
socket.open();
|
||||
socket.receive({ v: 1, type: "hello_ack", payload: {} });
|
||||
return { client, socket };
|
||||
}
|
||||
|
||||
/** Two queries the workspace page actually runs, observed the way the page does. */
|
||||
function observe(queryClient: QueryClient) {
|
||||
const workspaces = vi.fn(async (): Promise<WorkspaceInfo[]> => []);
|
||||
const health = vi.fn(async () => ({ ok: true, items: [] }));
|
||||
const observers = [
|
||||
new QueryObserver(queryClient, { queryKey: ["workspaces"], queryFn: workspaces }),
|
||||
new QueryObserver(queryClient, { queryKey: ["health"], queryFn: health }),
|
||||
];
|
||||
const unsubscribes = observers.map((observer) => observer.subscribe(() => {}));
|
||||
return {
|
||||
workspaces,
|
||||
health,
|
||||
stop: () => {
|
||||
for (const unsubscribe of unsubscribes) unsubscribe();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function newQueryClient() {
|
||||
return new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } },
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("instance_state frames", () => {
|
||||
it("refetches the workspaces list (and health) instead of being dropped", async () => {
|
||||
const queryClient = newQueryClient();
|
||||
const observed = observe(queryClient);
|
||||
await vi.waitFor(() => expect(observed.workspaces).toHaveBeenCalledTimes(1));
|
||||
expect(observed.health).toHaveBeenCalledTimes(1);
|
||||
|
||||
const { client, socket } = connect(queryClient);
|
||||
socket.receive({
|
||||
v: 1,
|
||||
type: "instance_state",
|
||||
workspaceId: "ws-1",
|
||||
payload: { status: "ready", sessions: [] },
|
||||
});
|
||||
|
||||
// Invalidation, not a local patch: the row (and the health strip) refetch.
|
||||
await vi.waitFor(() => expect(observed.workspaces).toHaveBeenCalledTimes(2));
|
||||
await vi.waitFor(() => expect(observed.health).toHaveBeenCalledTimes(2));
|
||||
|
||||
client.close();
|
||||
observed.stop();
|
||||
});
|
||||
|
||||
it("coalesces a startup burst into a single refetch round", async () => {
|
||||
const queryClient = newQueryClient();
|
||||
const observed = observe(queryClient);
|
||||
await vi.waitFor(() => expect(observed.workspaces).toHaveBeenCalledTimes(1));
|
||||
|
||||
const { client, socket } = connect(queryClient);
|
||||
for (const status of ["starting", "ready", "degraded"]) {
|
||||
socket.receive({ v: 1, type: "instance_state", workspaceId: "ws-1", payload: { status } });
|
||||
}
|
||||
|
||||
await vi.waitFor(() => expect(observed.workspaces).toHaveBeenCalledTimes(2));
|
||||
// A burst must not fan out into one refetch per frame.
|
||||
await new Promise((resolve) => setTimeout(resolve, COALESCE_MS * 3));
|
||||
expect(observed.workspaces).toHaveBeenCalledTimes(2);
|
||||
expect(observed.health).toHaveBeenCalledTimes(2);
|
||||
|
||||
client.close();
|
||||
observed.stop();
|
||||
});
|
||||
|
||||
it("stays tolerant without a query client and keeps ignoring unknown frames", () => {
|
||||
const { client, socket } = connect();
|
||||
expect(client.getState()).toBe("open");
|
||||
|
||||
for (const type of ["instance_state", "mystery_frame", "presence", "pong"]) {
|
||||
expect(() => socket.receive({ v: 1, type, payload: { status: "ready" } })).not.toThrow();
|
||||
}
|
||||
expect(client.getState()).toBe("open");
|
||||
// Still usable afterwards: a second connection state change is still reported.
|
||||
socket.receive({ v: 1, type: "error", payload: { code: "E_INTERNAL", message: "boom" } });
|
||||
expect(client.getState()).toBe("open");
|
||||
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user