Compare commits
17
Commits
66682725d4
...
a8425a51b6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8425a51b6 | ||
|
|
181b22ad00 | ||
|
|
b3183fd4d0 | ||
|
|
2589e6df72 | ||
|
|
9eb7075d70 | ||
|
|
ef0d9b9125 | ||
|
|
0193230cd3 | ||
|
|
64a1a98c1f | ||
|
|
58e247644d | ||
|
|
62d1d9cd38 | ||
|
|
84869f3dc6 | ||
|
|
51ef1c250b | ||
|
|
9ab0830223 | ||
|
|
01db49fb38 | ||
|
|
9eb857465c | ||
|
|
e32e86a377 | ||
|
|
7c98510fea |
No files matched your search
@@ -0,0 +1,90 @@
|
||||
---
|
||||
name: release
|
||||
description: Cut and verify a pi2d release — pick the version, tag it, let GitHub Actions publish to npm through Trusted Publishing (OIDC), then verify the registry artifact, provenance, a clean install and a booting daemon. Use when asked to "release", "publish", "cut a version", "bump the version", or to diagnose a failed release run.
|
||||
---
|
||||
|
||||
# Release pi2d
|
||||
|
||||
Runbook. Architecture and house rules live in `AGENTS.md`; the npmjs.com checklist, provenance
|
||||
rationale and the long troubleshooting table live in `../../../docs/releasing.md`. This file is the
|
||||
procedure to execute.
|
||||
|
||||
## Non-negotiables
|
||||
|
||||
- **Publish only from CI.** Tag → `.github/workflows/release.yml` → OIDC. A local `npm publish`
|
||||
is the one-time bootstrap only (see below), never the steady state.
|
||||
- **No tokens.** The publish step holds no credentials; the workflow's first guard step fails the
|
||||
job when `NPM_TOKEN` / `NODE_AUTH_TOKEN` is still present in the repo.
|
||||
- **Tag == `package.json` version.** The workflow verifies the pair and refuses to publish a
|
||||
mismatch.
|
||||
- **Push the tag explicitly.** `git push --follow-tags` only pushes *annotated* tags; a
|
||||
lightweight tag is skipped silently and `release.yml` never runs.
|
||||
|
||||
## Steady-state release
|
||||
|
||||
1. **Preconditions** — clean tree on `main`, in sync with `origin/main`, and CI green on the commit
|
||||
you are about to tag: `gh run list --repo zgs225/pi2d --workflow ci.yml --limit 3`.
|
||||
2. **Pick the version with the user** (do not assume). Semver: breaking → major, feature → minor,
|
||||
fix → patch. There is no `CHANGELOG.md`; build the notes from
|
||||
`git log --oneline "$(git describe --tags --abbrev=0)"..HEAD`, grouped by conventional type.
|
||||
3. **Bump and commit:**
|
||||
```bash
|
||||
npm version <x.y.z> --no-git-tag-version
|
||||
git commit -am "chore: release <x.y.z>"
|
||||
```
|
||||
4. **Tag and push** (annotated tag, pushed explicitly):
|
||||
```bash
|
||||
git tag -a "v<x.y.z>" -m "v<x.y.z>"
|
||||
git push origin main
|
||||
git push origin "v<x.y.z>"
|
||||
```
|
||||
5. **Watch the publish:**
|
||||
```bash
|
||||
gh run watch "$(gh run list --repo zgs225/pi2d --workflow release.yml --limit 1 \
|
||||
--json databaseId --jq '.[0].databaseId')" --repo zgs225/pi2d --exit-status
|
||||
```
|
||||
The interesting steps are `Upgrade npm`, `Preflight — npm/node support trusted publishing`,
|
||||
`Publish to npm (trusted publishing, no token)` and `Create GitHub release`.
|
||||
6. **Verify the artifact** — do not trust a green job, check the registry:
|
||||
```bash
|
||||
bash .agents/skills/release/scripts/verify-release.sh <x.y.z>
|
||||
```
|
||||
It asserts the exact version is on the registry, the SLSA provenance attestation exists, a clean
|
||||
install from the public registry reports `pi2 <x.y.z>`, the tarball ships `web/dist`,
|
||||
`dist/cli/pi2.js` and `LICENSE`, the daemon boots and serves `/` + a healthy
|
||||
`/api/v1/health`, and the GitHub release exists. Every line is `PASS`/`FAIL`; exit non-zero on
|
||||
any failure.
|
||||
7. **Report** the version, the run URL, the verification output and the release URL. Mention whether
|
||||
the new version is `latest` (a backport is not).
|
||||
|
||||
## Bootstrap (once per package name, already done for `@yuez/pi2d`)
|
||||
|
||||
Only relevant if the package has left the registry. npmjs.com offers the Trusted Publisher page
|
||||
only for a package that already exists, so the first publish is manual:
|
||||
|
||||
1. From the repo root: `npm login` (account `yuez`, 2FA) → `npm whoami` → `npm publish --access public`.
|
||||
That artifact has no provenance; every later release does.
|
||||
2. Then add the trusted publisher on npmjs.com: owner `zgs225` (GitHub), repo `pi2d`, workflow
|
||||
filename `release.yml`, environment empty, **and tick `npm publish`** (post-2026-09-03 configs
|
||||
allow only `npm stage publish` by default). The first CI publish must happen within 2 days or the
|
||||
configuration expires.
|
||||
3. Bump to a **higher** version for the first CI release — npm rejects republishing a version.
|
||||
|
||||
## Failure playbook
|
||||
|
||||
| Symptom | Cause / action |
|
||||
|---|---|
|
||||
| No `release.yml` run after pushing | The tag never reached the remote. Check `gh api repos/zgs225/pi2d/tags --jq '.[].name'`; a lightweight tag plus `--follow-tags` is silent. Push the tag explicitly. |
|
||||
| `ENEEDAUTH` / "Unable to authenticate" | OIDC or policy mismatch: workflow filename must be exactly `release.yml`, `npm publish` must be ticked under allowed actions, `id-token: write` must be present, and the trusted publisher must be attached to *this* package. |
|
||||
| `Preflight` fails on npm version | setup-node's node 22 ships npm 10; the `Upgrade npm` step must run before the preflight. |
|
||||
| `Refuse token-based publishing` fails | A `NPM_TOKEN`/`NODE_AUTH_TOKEN` repo secret still exists. Delete it — OIDC is the intended path. |
|
||||
| `E403 Package name too similar` | Unscoped names hit the registry's similarity filter; this package is scoped as `@yuez/pi2d` and must stay scoped. |
|
||||
| `E403 You cannot publish over the previously published versions` | The version was already published (often the bootstrap). Bump and re-tag. |
|
||||
| `Create GitHub release` 403 | Workflow `permissions` lost `contents: write`. |
|
||||
| `EOTP` on a local publish | Only the bootstrap needs 2FA; pass `--otp=<code>`. Steady state never publishes locally. |
|
||||
|
||||
## Definition of done
|
||||
|
||||
Registry shows the version with a `slsa.dev/provenance` attestation, `verify-release.sh` prints
|
||||
`OK`, the GitHub release exists, the working tree is clean, and the report tells the user what to
|
||||
install (`npm i -g @yuez/pi2d@<x.y.z>`).
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#!/usr/bin/env bash
|
||||
# Verify a published `@yuez/pi2d` release end to end.
|
||||
#
|
||||
# bash .agents/skills/release/scripts/verify-release.sh <x.y.z>
|
||||
#
|
||||
# Checks, in order: the registry carries that exact version, the provenance
|
||||
# attestation is present, a clean install from the public registry reports the
|
||||
# same version, the packaged daemon boots and serves the console + health, and
|
||||
# the GitHub release exists. Every line is PASS/FAIL/INFO; the script exits
|
||||
# non-zero when any check fails.
|
||||
set -uo pipefail
|
||||
|
||||
PKG="@yuez/pi2d"
|
||||
REPO="zgs225/pi2d"
|
||||
VERSION="${1:-}"
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "usage: verify-release.sh <x.y.z>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
WORK=$(mktemp -d "${TMPDIR:-/tmp}/pi2d-verify-release.XXXXXX")
|
||||
DPID=""
|
||||
cleanup() {
|
||||
[ -n "$DPID" ] && kill "$DPID" 2>/dev/null
|
||||
[ -n "$DPID" ] && wait "$DPID" 2>/dev/null
|
||||
rm -rf "$WORK"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
FAILED=0
|
||||
pass() { printf 'PASS %-42s %s\n' "$1" "${2:-}"; }
|
||||
fail() { printf 'FAIL %-42s %s\n' "$1" "${2:-}"; FAILED=1; }
|
||||
info() { printf 'INFO %-42s %s\n' "$1" "${2:-}"; }
|
||||
|
||||
# 1 — the registry has this version -----------------------------------------
|
||||
PUBLISHED=$(npm view "$PKG@$VERSION" version 2>/dev/null)
|
||||
if [ "$PUBLISHED" = "$VERSION" ]; then
|
||||
pass "registry version" "$PKG@$PUBLISHED"
|
||||
else
|
||||
fail "registry version" "expected $VERSION, got '${PUBLISHED:-<missing>}'"
|
||||
fi
|
||||
|
||||
LATEST=$(npm view "$PKG" dist-tags.latest 2>/dev/null)
|
||||
if [ "$LATEST" = "$VERSION" ]; then
|
||||
pass "dist-tag latest" "$LATEST"
|
||||
else
|
||||
info "dist-tag latest" "$LATEST (this release is not the latest tag)"
|
||||
fi
|
||||
|
||||
# 2 — provenance -------------------------------------------------------------
|
||||
PREDICATE=$(npm view "$PKG@$VERSION" dist.attestations.provenance.predicateType 2>/dev/null)
|
||||
case "$PREDICATE" in
|
||||
*slsa.dev/provenance*) pass "provenance attestation" "$PREDICATE" ;;
|
||||
"") fail "provenance attestation" "none (bootstrap version? published outside CI?)" ;;
|
||||
*) fail "provenance attestation" "unexpected predicate $PREDICATE" ;;
|
||||
esac
|
||||
|
||||
# 3 — a clean install from the public registry -------------------------------
|
||||
if npm i -g --prefix "$WORK/prefix" --no-audit --no-fund "$PKG@$VERSION" >"$WORK/install.log" 2>&1; then
|
||||
pass "clean global install" "$(tail -1 "$WORK/install.log")"
|
||||
else
|
||||
fail "clean global install" "see $WORK/install.log"
|
||||
fi
|
||||
PI2="$WORK/prefix/bin/pi2"
|
||||
if [ -x "$PI2" ]; then
|
||||
INSTALLED=$("$PI2" --version 2>&1 | head -1)
|
||||
if [ "$INSTALLED" = "pi2 $VERSION" ]; then
|
||||
pass "installed binary version" "$INSTALLED"
|
||||
else
|
||||
fail "installed binary version" "expected 'pi2 $VERSION', got '$INSTALLED'"
|
||||
fi
|
||||
PKG_DIR="$WORK/prefix/lib/node_modules/$PKG"
|
||||
for f in "web/dist/index.html" "dist/cli/pi2.js" "LICENSE"; do
|
||||
if [ -e "$PKG_DIR/$f" ]; then
|
||||
pass "tarball ships" "$f"
|
||||
else
|
||||
fail "tarball ships" "$f missing"
|
||||
fi
|
||||
done
|
||||
else
|
||||
fail "installed binary version" "no $PI2"
|
||||
fi
|
||||
|
||||
# 4 — the daemon boots and serves --------------------------------------------
|
||||
export PI2_RUNTIME_DIR="$WORK/rt" PI2_DATA_DIR="$WORK/data" PI2_STATE_DIR="$WORK/state"
|
||||
if [ -x "$PI2" ]; then
|
||||
"$PI2" daemon -p 0 >"$WORK/daemon.out" 2>"$WORK/daemon.err" &
|
||||
DPID=$!
|
||||
for _ in $(seq 1 150); do [ -f "$WORK/rt/daemon.json" ] && break; sleep 0.1; done
|
||||
if [ -f "$WORK/rt/daemon.json" ]; then
|
||||
PORT=$(node -pe "JSON.parse(require('fs').readFileSync('$WORK/rt/daemon.json','utf8')).port" 2>/dev/null)
|
||||
pass "daemon start" "$(head -1 "$WORK/daemon.out")"
|
||||
CODE=$(curl -s -o "$WORK/index.html" -w '%{http_code}' --max-time 10 "http://127.0.0.1:$PORT/")
|
||||
[ "$CODE" = "200" ] && pass "GET / serves the console" "200, $(wc -c <"$WORK/index.html" | tr -d ' ') bytes" \
|
||||
|| fail "GET / serves the console" "HTTP $CODE"
|
||||
HEALTH=$(curl -s --max-time 10 "http://127.0.0.1:$PORT/api/v1/health")
|
||||
if printf '%s' "$HEALTH" | grep -q '"ok":true'; then
|
||||
pass "health ok" "$(printf '%s' "$HEALTH" | node -pe 'JSON.parse(require("fs").readFileSync(0,"utf8")).items.map(i=>i.name+"="+(i.ok?"ok":"FAIL")).join(" ")' 2>/dev/null)"
|
||||
else
|
||||
fail "health ok" "${HEALTH:-<no response>}"
|
||||
fi
|
||||
kill "$DPID" 2>/dev/null; wait "$DPID" 2>/dev/null; DPID=""
|
||||
[ -f "$WORK/rt/daemon.lock" ] && fail "clean shutdown" "daemon.lock left behind" \
|
||||
|| pass "clean shutdown" "lock + daemon.json removed"
|
||||
else
|
||||
fail "daemon start" "$(tail -2 "$WORK/daemon.err" | tr '\n' ' ')"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 5 — the GitHub release -----------------------------------------------------
|
||||
if command -v gh >/dev/null 2>&1; then
|
||||
if gh release view "v$VERSION" --repo "$REPO" --json url --jq .url >"$WORK/release.url" 2>/dev/null; then
|
||||
pass "GitHub release" "$(cat "$WORK/release.url")"
|
||||
else
|
||||
info "GitHub release" "no release for v$VERSION (informational)"
|
||||
fi
|
||||
else
|
||||
info "GitHub release" "gh not installed, skipped"
|
||||
fi
|
||||
|
||||
echo
|
||||
if [ "$FAILED" -eq 0 ]; then
|
||||
echo "OK — $PKG@$VERSION is published and usable."
|
||||
else
|
||||
echo "FAILED — see the FAIL lines above." >&2
|
||||
fi
|
||||
exit "$FAILED"
|
||||
@@ -0,0 +1,78 @@
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
check:
|
||||
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
|
||||
|
||||
- name: Install daemon deps
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Install web deps
|
||||
run: pnpm --dir web install --frozen-lockfile
|
||||
|
||||
- name: Typecheck daemon
|
||||
run: pnpm typecheck
|
||||
|
||||
- name: Typecheck web
|
||||
run: pnpm --dir web typecheck
|
||||
|
||||
- name: Unit tests (daemon)
|
||||
run: pnpm test
|
||||
|
||||
- name: Unit tests (web)
|
||||
run: pnpm --dir web exec vitest run
|
||||
|
||||
- name: Build daemon
|
||||
run: pnpm build
|
||||
|
||||
- name: Build web
|
||||
run: pnpm build:web
|
||||
|
||||
- name: Smoke (daemon + static UI round trip)
|
||||
run: bash scripts/smoke.sh
|
||||
|
||||
# --ignore-scripts: everything is already built above, and prepack's build
|
||||
# output would corrupt the JSON on stdout.
|
||||
- name: Check the publishable tarball embeds dist + web/dist
|
||||
run: |
|
||||
node -e 'if (!require("./package.json").scripts.prepack) { console.error("prepack missing"); process.exit(1) }'
|
||||
npm pack --dry-run --json --ignore-scripts > pack.json
|
||||
node -e '
|
||||
const [t] = require("./pack.json");
|
||||
const files = t.files.map((f) => f.path);
|
||||
for (const need of ["dist/cli/pi2.js", "web/dist/index.html", "docs/protocol.md"]) {
|
||||
if (!files.includes(need)) {
|
||||
console.error(`missing from tarball: ${need}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
if (files.some((f) => f.startsWith("src/") || f.startsWith("test/"))) {
|
||||
console.error("tarball leaks source or tests");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`tarball ok: ${files.length} files`);
|
||||
'
|
||||
@@ -0,0 +1,135 @@
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
|
||||
# Authentication is npm Trusted Publishing (OIDC): the npm CLI picks up the
|
||||
# GitHub Actions OIDC token and exchanges it for a short-lived publish token.
|
||||
# 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
|
||||
id-token: write # mint the OIDC token npm exchanges for publish rights
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
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
|
||||
registry-url: https://registry.npmjs.org
|
||||
cache: pnpm
|
||||
cache-dependency-path: |
|
||||
pnpm-lock.yaml
|
||||
web/pnpm-lock.yaml
|
||||
|
||||
- name: Tag must match package.json version
|
||||
run: |
|
||||
tag="${GITHUB_REF_NAME#v}"
|
||||
pkg="$(node -p 'require("./package.json").version')"
|
||||
if [ "$tag" != "$pkg" ]; then
|
||||
echo "tag $GITHUB_REF_NAME does not match package.json $pkg" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Install deps
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm --dir web install --frozen-lockfile
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
pnpm typecheck
|
||||
pnpm test
|
||||
pnpm --dir web exec vitest run
|
||||
|
||||
# A leftover automation token would silently win over OIDC and hide a
|
||||
# broken trusted-publisher configuration, so fail loudly instead.
|
||||
# Repository secrets are NOT exported as environment variables on their
|
||||
# own, so they are mapped into THIS step's env explicitly: otherwise the
|
||||
# guard would see nothing and pass while the publish step (which gets no
|
||||
# env at all) would be the first place a stale token could leak in.
|
||||
- name: Refuse token-based publishing
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
|
||||
run: |
|
||||
for var in NODE_AUTH_TOKEN NPM_TOKEN; do
|
||||
if [ -n "${!var:-}" ]; then
|
||||
echo "::error::env var $var is set. This workflow publishes with npm Trusted Publishing (OIDC) and must run without a token. Delete the repository secret and re-run."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo "no publish token present — OIDC trusted publishing only"
|
||||
|
||||
# actions/setup-node's node 22 ships npm 10.x, which cannot do trusted
|
||||
# publishing (needs >= 11.5.1).
|
||||
- name: Upgrade npm
|
||||
run: npm install -g npm@11
|
||||
|
||||
- name: Preflight — npm/node support trusted publishing
|
||||
run: |
|
||||
node <<'EOF'
|
||||
const { execSync } = require("node:child_process");
|
||||
|
||||
const atLeast = (have, want) => {
|
||||
const a = have.split(".").map(Number);
|
||||
const b = want.split(".").map(Number);
|
||||
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
||||
const x = a[i] || 0;
|
||||
const y = b[i] || 0;
|
||||
if (x !== y) return x > y;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const fail = [];
|
||||
const npm = execSync("npm --version").toString().trim();
|
||||
const node = process.version.replace(/^v/, "");
|
||||
console.log(`npm ${npm} / node ${node}`);
|
||||
|
||||
if (!atLeast(npm, "11.5.1")) {
|
||||
fail.push(`npm ${npm} is too old for trusted publishing (need >= 11.5.1); did 'npm install -g npm@11' run?`);
|
||||
}
|
||||
if (!atLeast(node, "22.14.0")) {
|
||||
fail.push(`node ${node} is too old for trusted publishing (need >= 22.14.0)`);
|
||||
}
|
||||
if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL) {
|
||||
fail.push("no OIDC token endpoint in the environment; 'permissions: id-token: write' is missing or the job is not running on GitHub Actions");
|
||||
}
|
||||
|
||||
if (fail.length) {
|
||||
for (const f of fail) console.error(`::error::${f}`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("trusted publishing preflight ok (OIDC endpoint present)");
|
||||
EOF
|
||||
|
||||
# `prepack` builds dist/ and web/dist/ as part of pack+publish, so the
|
||||
# published tarball is always built from the tagged source; no separate
|
||||
# build step is needed here. No --provenance: provenance is automatic for
|
||||
# a public package published from a public repo via OIDC.
|
||||
# Deliberately no `env:` on this step — OIDC only.
|
||||
- name: Publish to npm (trusted publishing, no token)
|
||||
run: npm publish --access public
|
||||
|
||||
- name: Create GitHub release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
generate_release_notes: true
|
||||
body: |
|
||||
`npm i -g @yuez/pi2d@${{ github.ref_name }}`
|
||||
|
||||
Compatible pi2.nvim: protocol v1 (see `docs/protocol.md`).
|
||||
@@ -0,0 +1,77 @@
|
||||
# AGENTS.md — pi2d
|
||||
|
||||
`pi2 daemon`: the web-console daemon for [pi2.nvim](https://github.com/zgs225/pi2.nvim).
|
||||
A browser talks HTTP/WS to it; it relays JSONL to one nvim per workspace. It is a router and
|
||||
supervisor — it never runs `pi` and never owns session state.
|
||||
|
||||
**This file is an index and must stay under 100 lines.** When something needs more than a line
|
||||
or two, put the depth in `docs/` or a skill under `.agents/skills/` and leave a pointer here.
|
||||
Adding bulk to this file is a mistake, not a contribution.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Task | Command |
|
||||
|---|---|
|
||||
| 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 |
|
||||
| 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/` |
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `src/protocol/` | wire types, command/event vocabulary, error codes, canonical reducer |
|
||||
| `src/daemon/` | HTTP/WS/SSE, auth, static assets, routing, event relay |
|
||||
| `src/instances/` | discovery, lazy spawn, one-instance-per-workspace, crash handling |
|
||||
| `src/workspaces/` | registry, disk discovery, aliases/trust, visibility policy |
|
||||
| `src/cli/` | `pi2` — `daemon`, `open`, `attach`, `status`, `doctor`, `pairing`, `install-service` |
|
||||
| `src/config.ts` | env-only configuration (`PI2_*`, `PI2_ACCESS_MODE`, `PI2_WORKSPACE_*`) |
|
||||
| `web/` | React console (own lockfile + workspace); built into `web/dist` and served by the daemon |
|
||||
| `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` |
|
||||
|
||||
## Hard rules
|
||||
|
||||
1. **`docs/protocol.md` is the contract.** Any wire change lands with the daemon, the web client
|
||||
and the pi2.nvim bridge in view; `fixtures/` are regenerated via `scripts/gen-expected.ts`.
|
||||
2. **The daemon is not an agent runtime.** No `pi` spawning, no JSONL session parsing, no session
|
||||
state. Snapshots and mutations are relayed to the plugin, which stays the single authority.
|
||||
3. **`dist/` and `web/dist/` are build output** — gitignored, never committed. They ship inside
|
||||
the npm tarball through `prepack` + the `files` allowlist.
|
||||
4. **Two lockfiles.** Root `pnpm-lock.yaml` and `web/pnpm-lock.yaml` are independent: use
|
||||
`pnpm --dir web …` for anything web-side, never a root install.
|
||||
5. **Tests are hermetic.** No real sockets, spawns or networks outside `scripts/e2e/`; inject
|
||||
probes (`DoctorContext`, `WorkspaceStoreOptions.env`, fake instance managers) and keep
|
||||
`fixtures/` byte-identical.
|
||||
6. **Local sign-in is loopback-only.** `POST /api/v1/console/session` requires the CLI token from
|
||||
the runtime dir, the browser token travels in the URL fragment only, device tokens are stored
|
||||
hashed, and `lan`/`tailscale` modes never auto-sign-in.
|
||||
7. **Conventional commits** (`feat(daemon):`, `fix(web):`, `docs:`, `ci:`), scoped to the area.
|
||||
|
||||
## Naming, so you do not get lost
|
||||
|
||||
npm package `@yuez/pi2d` (scoped — the unscoped `pi2d` is rejected by the registry's similarity
|
||||
filter), executable `pi2`, GitHub repo `zgs225/pi2d` (the trusted publisher matches on
|
||||
owner/repo/workflow filename, not the npm name).
|
||||
|
||||
## Where to read deeper
|
||||
|
||||
| Doc | Contents |
|
||||
|---|---|
|
||||
| `docs/protocol.md` | the browser ↔ daemon ↔ plugin wire contract |
|
||||
| `docs/deployment.md` | env vars, runtime files, ports, auth, services, troubleshooting |
|
||||
| `docs/e2e.md` | scenario ids, isolation, skip conditions, report paths |
|
||||
| `docs/releasing.md` | npm Trusted Publishing, the bootstrap phases, verification |
|
||||
| `README.md` | install paths, `:PiWeb`, access modes |
|
||||
| `.agents/skills/release/` | how to cut and verify a release |
|
||||
|
||||
## Before you say "done"
|
||||
|
||||
`pnpm typecheck && pnpm test && pnpm --dir web typecheck && pnpm --dir web exec vitest run &&
|
||||
bash scripts/smoke.sh` green; docs updated where behaviour changed; no build output staged.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 yuez
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,4 +1,4 @@
|
||||
# pi2 daemon — pi2 web console daemon
|
||||
# pi2d — pi2 web console daemon
|
||||
|
||||
The always-on web side of [pi2.nvim](https://github.com/zgs225/pi2.nvim). It is a **router + supervisor**, not an agent runtime:
|
||||
|
||||
@@ -14,17 +14,111 @@ Hard rules (see `docs/protocol.md`):
|
||||
3. All mutations are commands relayed to the plugin; the plugin (inside nvim) is the single source of truth.
|
||||
4. The web client keeps a render cache only; a `snapshot` from the plugin replaces it wholesale.
|
||||
|
||||
## Quick start
|
||||
## Install
|
||||
|
||||
Requirements: **Node >= 22**, **Neovim >= 0.9**, the **`pi` CLI** on `PATH`.
|
||||
|
||||
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:
|
||||
|
||||
```
|
||||
:PiWeb
|
||||
```
|
||||
|
||||
…which opens your browser already signed in, showing the current workspace.
|
||||
|
||||
> **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)
|
||||
|
||||
```bash
|
||||
npm i -g @yuez/pi2d # installs the `pi2` binary
|
||||
pnpm add -g @yuez/pi2d
|
||||
bun add -g @yuez/pi2d
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
```bash
|
||||
pi2 daemon # foreground; the plugin/browser needs this running
|
||||
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
|
||||
```
|
||||
|
||||
`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).
|
||||
|
||||
### Neovim plugin
|
||||
|
||||
```lua
|
||||
{
|
||||
"zgs225/pi2.nvim",
|
||||
opts = {}, -- add `web = { enabled = true }` to start the bridge at setup
|
||||
cmd = { "PiWeb", "PiWebStart", "PiWebStatus" },
|
||||
}
|
||||
```
|
||||
|
||||
`: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 looks for the daemon in this order, and `: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` |
|
||||
| 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)
|
||||
|
||||
The daemon binds `127.0.0.1` by default and never exposes itself to the network on its own.
|
||||
`:PiWeb` asks once which access mode you want and remembers the answer; `web.access = "lan"`
|
||||
(or `"tailscale"`, or `"local"`) skips the prompt.
|
||||
|
||||
| Mode | Bind | Browser access | Login |
|
||||
|---|---|---|---|
|
||||
| `local` | `127.0.0.1` | same machine | automatic (one-time token handed to the browser) |
|
||||
| `lan` | `0.0.0.0` | `http://<lan-ip>:7676` | pairing code / QR, **never** automatic |
|
||||
| `tailscale` | `127.0.0.1` + `tailscale serve` | `https://<host>.<tailnet>.ts.net` | pairing code / QR, **never** automatic |
|
||||
|
||||
Pair a device from the CLI:
|
||||
|
||||
```bash
|
||||
pi2 pairing # loopback URL + code + QR payload
|
||||
pi2 pairing --public-url https://myhost.tail1234.ts.net
|
||||
```
|
||||
|
||||
Or from the web console's device page. Tokens are per-device, revocable, and stored
|
||||
hashed; `pi2 doctor` reports the active mode and warns when a non-loopback bind has no TLS.
|
||||
|
||||
## Developing pi2d
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm test
|
||||
pnpm dev # starts on 127.0.0.1:7676
|
||||
pnpm --dir web install
|
||||
pnpm dev # daemon on 127.0.0.1:7676 (tsx watch)
|
||||
pnpm --dir web dev # vite dev server on :5173, proxying /api and /ws to the daemon
|
||||
```
|
||||
|
||||
The daemon is the `pi2 daemon` subcommand of the single shipped `pi2` binary — there is no
|
||||
separate executable. The plugin starts it lazily when it is not running; you normally do not
|
||||
start it by hand.
|
||||
`pnpm build` → `dist/`, `pnpm build:web` → `web/dist/`. The published tarball ships both, so
|
||||
`pi2 daemon` serves the web console from its own package with no extra step.
|
||||
|
||||
Releasing: bump `version` in `package.json`, tag `v<version>`, push the tag. That is the whole
|
||||
flow — `.github/workflows/release.yml` verifies the tag matches `package.json`, runs the
|
||||
checks, and publishes to npm. Authentication is **OIDC trusted publishing**: the publish step
|
||||
holds no npm token, and `id-token: write` lets the npm CLI exchange a short-lived GitHub OIDC
|
||||
token for publish rights (provenance is attached automatically). There is no `NPM_TOKEN` secret
|
||||
to configure or rotate, and a guard step fails the run if one ever exists. The one-time bootstrap
|
||||
(first publish by hand, then the npmjs.com trusted-publisher setup), the local dry run and
|
||||
troubleshooting: [docs/releasing.md](docs/releasing.md).
|
||||
|
||||
## Layout
|
||||
|
||||
@@ -35,6 +129,7 @@ start it by hand.
|
||||
| `src/instances/` | discovery, lazy spawn, single-instance enforcement, crash handling |
|
||||
| `src/workspaces/` | workspace registry, disk discovery, aliases/trust |
|
||||
| `src/cli/` | `pi2` — the `daemon` subcommand plus `attach`/`status`/`doctor` |
|
||||
| `web/` | the React web console (built into `web/dist`, served by the daemon) |
|
||||
| `fixtures/` | golden event streams + expected session state (shared with pi2.nvim tests) |
|
||||
| `docs/protocol.md` | the wire contract (browser ↔ daemon ↔ plugin) |
|
||||
|
||||
|
||||
+90
-7
@@ -111,14 +111,20 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
|
||||
| Variable | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `PI2_PORT` | `7676` | HTTP/WS port, `0` = ephemeral |
|
||||
| `PI2_HOST` | `127.0.0.1` | bind address |
|
||||
| `PI2_HOST` | `127.0.0.1` (`0.0.0.0` in `lan` mode) | bind address; wins over the mode default |
|
||||
| `PI2_ACCESS_MODE` | `local` | `local` / `lan` / `tailscale` (see below) |
|
||||
| `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_ORIGINS` | `http://127.0.0.1:<port>,http://localhost:<port>` | CORS/Origin allowlist (comma separated) |
|
||||
| `PI2_RUNTIME_DIR` | Linux `$XDG_RUNTIME_DIR/pi2`, macOS `~/Library/Caches/pi2/run` | sockets, lock, tokens |
|
||||
| `PI2_DATA_DIR` | Linux `$XDG_DATA_HOME/pi2`, macOS `~/Library/Application Support/pi2` | `devices.json`, `workspaces.json` |
|
||||
| `PI2_STATE_DIR` | Linux `$XDG_STATE_HOME/pi2`, macOS `~/Library/Logs/pi2` | instance logs |
|
||||
| `PI2_LOG_LEVEL` | `info` | `debug`/`info`/`warn`/`error`/`silent` |
|
||||
| `PI2_WORKSPACE_ROOTS` | `$HOME` | allowlist for `workspace.add` |
|
||||
| `PI2_WORKSPACE_ROOTS` | `$HOME` | allowlist for `workspace.add`, and the root set for `PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS` (comma separated, `~` expanded) |
|
||||
| `PI2_WORKSPACE_HIDE_TEMP` | `1` | hide workspaces under the absolute `$TMPDIR` (ignored when relative), `/tmp`, `/var/tmp`, `/var/folders`, `/private/var/folders` |
|
||||
| `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 |
|
||||
@@ -126,6 +132,48 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
|
||||
|
||||
There is no config file: the environment *is* the configuration.
|
||||
|
||||
### Workspace list (noise policy)
|
||||
|
||||
`GET /api/v1/workspaces` always returns **every** known workspace, so
|
||||
`/workspace/<workspaceId>` deep links keep resolving. The noise policy is a
|
||||
derived, non-persisted `visibility` (`default` | `secondary`) plus
|
||||
`visibilityReason` (`hidden` | `ghost` | `temp` | `outside-roots` | `stale`),
|
||||
with this precedence (first match wins):
|
||||
|
||||
1. `hidden: true` → secondary (explicit intent, never rescued).
|
||||
2. A live instance (`instance != null` or `liveCount > 0`), `pinned` or
|
||||
`trusted` → default (rescue: a workspace you are using is never hidden).
|
||||
3. `PI2_WORKSPACE_HIDE_TEMP` → secondary/`temp`.
|
||||
4. `PI2_WORKSPACE_HIDE_GHOSTS` → secondary/`ghost`.
|
||||
5. `PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS` → secondary/`outside-roots`.
|
||||
6. `PI2_WORKSPACE_STALE_DAYS` → secondary/`stale` (`lastActiveAt: null` never
|
||||
counts as stale).
|
||||
7. Otherwise default.
|
||||
|
||||
Boolean switches accept `1/true/yes/on` and `0/false/no/off`; anything else
|
||||
falls back to the default. `workspace.add` always clears `hidden`, so opening a
|
||||
previously hidden path brings it back. In the browser console the workspaces
|
||||
page lists `default` rows only behind a persisted “Show N hidden” toggle
|
||||
(`localStorage` key `pi2-workspaces-show-all`, default off) that reveals the
|
||||
secondary rows dimmed with a reason badge; any workspace picker offers
|
||||
`default` rows only, while lookups by id ignore `visibility` entirely.
|
||||
|
||||
### Access modes
|
||||
|
||||
| `PI2_ACCESS_MODE` | bind (unless `PI2_HOST`) | derived `corsOrigins` |
|
||||
|---|---|---|
|
||||
| `local` (default) | `127.0.0.1` | `http://127.0.0.1:<port>`, `http://localhost:<port>`, `http://[::1]:<port>` |
|
||||
| `lan` | `0.0.0.0` | loopback three **plus** `http://<detected-lan-ip>:<port>` |
|
||||
| `tailscale` | `127.0.0.1` | loopback three **plus** the origin of `PI2_PUBLIC_URL` |
|
||||
|
||||
Origins are normalized (trailing `/` stripped, empties dropped) and
|
||||
`PI2_ORIGINS` is appended — never a replacement. LAN detection is best effort:
|
||||
when the address is unknown that extra origin is simply skipped. `tailscale`
|
||||
assumes `tailscale serve` terminates TLS in front of the loopback daemon; the
|
||||
daemon never does TLS itself. An unknown mode fails startup with one line:
|
||||
`pi2: PI2_ACCESS_MODE must be local, lan or tailscale`. Changing the mode
|
||||
requires restarting `pi2 daemon`.
|
||||
|
||||
## 5. Runtime files
|
||||
|
||||
All of these live in `PI2_RUNTIME_DIR` (created `0700`):
|
||||
@@ -134,7 +182,7 @@ All of these live in `PI2_RUNTIME_DIR` (created `0700`):
|
||||
|---|---|---|
|
||||
| `d.sock` | `0600` | plugin ↔ daemon JSONL socket (nvim dials it) |
|
||||
| `d.sock.token` | `0600` | handshake token for `hello`; rotated per daemon start |
|
||||
| `daemon.lock` | `0600` | singleton lock: `{pid, bootId, port, daemonId, startedAt, protocolVersion}` |
|
||||
| `daemon.lock` | `0600` | singleton lock: `{pid, bootId, port, daemonId, startedAt, protocolVersion, access?, publicUrl?}` |
|
||||
| `daemon.json` | `0600` | same payload, written **after** `listen()` so tools learn the real port |
|
||||
| `cli.token` | `0600` | 32-byte hex local admin token, rotated per daemon start |
|
||||
|
||||
@@ -178,6 +226,20 @@ a token; everything else under `/api/*` needs `Authorization: Bearer …`.
|
||||
Unknown `/api/*` paths answer `401` when unauthenticated and `404` when
|
||||
authenticated (auth runs before routing).
|
||||
|
||||
### Local-browser login (`POST /api/v1/console/session`)
|
||||
|
||||
`pi2 open` calls this endpoint (loopback **and** local CLI token required) to
|
||||
sign the browser in without a pairing code: it rotates the single
|
||||
`local browser` device (`kind:"laptop"`, all four scopes) and answers
|
||||
`{token, device, url}` with
|
||||
`url = http://127.0.0.1:<actual bound port>/#t=<token>`. The token lives in the
|
||||
fragment, so it never reaches a request line, a `Referer` header or a proxy
|
||||
access log, and the daemon never logs it. Every call rotates the token (same
|
||||
device `id`) and invalidates the previous URL.
|
||||
|
||||
Non-loopback callers get `403 E_FORBIDDEN` (`console login is loopback-only`);
|
||||
remote browsers pair instead (see §8.5).
|
||||
|
||||
## 8. The `pi2` CLI
|
||||
|
||||
`pi2` discovers the daemon from `daemon.json` (port) and `cli.token` (auth) in
|
||||
@@ -234,12 +296,14 @@ object `{daemon, instances, resources, health}`.
|
||||
| `node` | < 22 | – |
|
||||
| `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 | – |
|
||||
| `runtime-dir` | missing | mode not `0700` |
|
||||
| `cli-token` | mode not `0600` | missing (daemon not started yet) |
|
||||
| `socket` | `d.sock` missing (and no daemon) | missing but daemon answers |
|
||||
| `daemon` | `/api/v1/info` unreachable | – |
|
||||
| `port` | – (reports bound/free) | – |
|
||||
| `access` | `lan`/`tailscale` with a non-loopback bind and no `PI2_PUBLIC_URL` | `lan`/`tailscale` (adds `— no TLS, prefer \`tailscale serve\`` without an `https:` public URL) |
|
||||
| `service-manager` | – | systemd/launchd not found |
|
||||
| `linger` (Linux) | – | `Linger=no` |
|
||||
| `web-dist` | – | missing |
|
||||
@@ -249,7 +313,21 @@ object `{daemon, instances, resources, health}`.
|
||||
only `fail` makes `ok:false`/exit `1`. All probes are injectable, so the checks
|
||||
are unit tested without touching the host.
|
||||
|
||||
### 8.4 `pi2 pairing`
|
||||
### 8.4 `pi2 open [--print] [--no-browser]`
|
||||
|
||||
```bash
|
||||
pi2 open # mint a loopback session and open the browser, signed in
|
||||
pi2 open --print # print the signed-in URL only (implies --no-browser)
|
||||
pi2 open --no-browser # print the URL instead of launching a browser
|
||||
```
|
||||
|
||||
Resolves `daemon.json` + `cli.token`, `POST`s `/api/v1/console/session`, then
|
||||
launches `xdg-open` (Linux) / `open` (macOS) detached. The opener never blocks
|
||||
the command: if it is missing or fails, `pi2 open` prints the URL and still
|
||||
exits `0`. This is a local-only shortcut; use `pi2 pairing` for LAN/Tailscale
|
||||
browsers.
|
||||
|
||||
### 8.5 `pi2 pairing [--public-url <url>]`
|
||||
|
||||
`POST /api/v1/pair` with the local token and prints:
|
||||
|
||||
@@ -262,9 +340,12 @@ qr {"v":1,"code":"ABCD2345","url":"…","expiresAt":…,"nonce":"…"}
|
||||
|
||||
The URL is rebuilt from the *actual* daemon base URL because the daemon's own
|
||||
`url` field is derived from the configured port (stale after a retry or
|
||||
`--port 0`).
|
||||
`--port 0`). `--public-url <url>` rebuilds both the printed `url` and the QR
|
||||
payload's `url` on that base (e.g. `https://host.ts.net/pair/ABCD2345`); it
|
||||
defaults to `daemon.json`'s `publicUrl`, then `PI2_PUBLIC_URL`. The code, expiry
|
||||
and nonce are unchanged.
|
||||
|
||||
### 8.5 `pi2 install-service` / `pi2 uninstall-service`
|
||||
### 8.6 `pi2 install-service` / `pi2 uninstall-service`
|
||||
|
||||
See [§9](#9-services-systemd--launchd). `--dry-run` (default) prints the file
|
||||
and the follow-up commands; `--write` writes the file (`0644`) and prints the
|
||||
@@ -373,6 +454,8 @@ debugging.
|
||||
| `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` → `access FAIL` | `PI2_ACCESS_MODE=lan/tailscale` binds a non-loopback address without `PI2_PUBLIC_URL`; set it or use `tailscale serve` |
|
||||
| `health: static=FAIL` | `web/dist` missing — build the web UI or set `PI2_STATIC_DIR` |
|
||||
| Browser console loads but no workspaces | no nvim with the plugin has connected yet; run `pi2 attach` in a project |
|
||||
| `pi2 doctor` → `plugin FAIL` | install pi2.nvim, or point `PI2_PLUGIN_DIR` at the checkout |
|
||||
|
||||
+12
-3
@@ -28,7 +28,7 @@ the real daemon/plugin/browser, never `MOCK.*` data.
|
||||
|
||||
The v1 gate is green when:
|
||||
|
||||
- **A0–A12** (API/WS against a real headless nvim + real pi) pass.
|
||||
- **A0–A13** (API/WS against a real headless nvim + real pi) pass.
|
||||
- **B1–B14** (Playwright against the daemon-served production bundle) pass.
|
||||
- **C1–C4** (responsive, theme, language, no console errors) pass.
|
||||
- `tsc --noEmit`, `vitest run` (daemon), `vitest run` (web) stay green.
|
||||
@@ -110,7 +110,7 @@ then the browser suite, each in its own temp root. Both drivers are standalone w
|
||||
|
||||
## 4. Scenarios
|
||||
|
||||
All scenario ids below are implemented in the two drivers: `scenario("A0", …)` … `scenario("A12", …)`
|
||||
All scenario ids below are implemented in the two drivers: `scenario("A0", …)` … `scenario("A13", …)`
|
||||
in `api-e2e.mjs`, `scenario("B1", …)` … `scenario("B14", …)` and `scenario("C1", …)` …
|
||||
`scenario("C4", …)` in `ui-e2e.mjs`. A driver exits non-zero only on **FAIL**; SKIP is
|
||||
tolerant, and every skip is printed with its reason and written into the report.
|
||||
@@ -220,6 +220,15 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
|
||||
- reject case: another file is requested; respond `{cancelled:true}` (or Rejected);
|
||||
the file does not exist and the turn continues/settles without error state.
|
||||
|
||||
**A13 Console login handoff**
|
||||
- `POST /api/v1/console/session` with the CLI token → 200, one `local browser`/`laptop`
|
||||
device with every scope, and a `http://127.0.0.1:<port>/#t=<token>` URL (fragment only,
|
||||
never `?t=`).
|
||||
- the handed-off token authenticates; a second login returns the **same** token so a second
|
||||
`:PiWeb` does not log the open tab out.
|
||||
- no CLI token → 401, a device token → 401 (loopback-only, local-CLI-only).
|
||||
- revoking the device → 204, the old token → 401, and the next login mints a new token.
|
||||
|
||||
**A12 Errors**
|
||||
- unknown session id → `E_SESSION_NOT_FOUND`; malformed `cmd` → `E_BAD_REQUEST`;
|
||||
unknown method → `E_METHOD_NOT_ALLOWED`; oversized/malformed JSON does not kill the
|
||||
@@ -365,7 +374,7 @@ which were skipped and why (non-blocking only), and the command that reproduces
|
||||
```bash
|
||||
cd <repo> # the pi2 CLI/daemon checkout (this repository)
|
||||
|
||||
# backend only (A0–A12): tsc, then `pi2 daemon` + headless nvim + real pi
|
||||
# backend only (A0–A13): tsc, then `pi2 daemon` + headless nvim + real pi
|
||||
bash scripts/e2e/run-api.sh
|
||||
|
||||
# browser (B1–B14, C1–C4): also builds web/dist (pnpm), then Playwright
|
||||
|
||||
@@ -90,6 +90,33 @@ Plugin obligations:
|
||||
| `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice |
|
||||
| `GET /api/v1/diagnostics` | connections, event rates, slow queries, instance table |
|
||||
|
||||
Workspace row (`GET /api/v1/workspaces`) — registry entry ∪ disk discovery ∪ live instance state. Every known workspace is returned; rows are never filtered, so `/workspace/<workspaceId>` deep links always resolve:
|
||||
|
||||
| Field | Notes |
|
||||
|---|---|
|
||||
| `workspaceId` | `sha256(realpath(cwd)).slice(0,16)` |
|
||||
| `cwd`, `name`, `alias` | `name` falls back to `alias`, then `basename(cwd)` |
|
||||
| `pinned`, `hidden`, `trusted` | persisted user intent from `workspaces.json` |
|
||||
| `exists` | `false` = ghost (the cwd is gone; the session files are not) |
|
||||
| `sessionCount`, `liveCount`, `lastActiveAt` | disk projection (`lastActiveAt` may be `null`) |
|
||||
| `instance` | live `InstanceState` or `null` |
|
||||
| `visibility?: "default" \| "secondary"` | derived, never persisted: the workspace-noise policy. Missing ⇒ `default` |
|
||||
| `visibilityReason?` | `hidden` \| `ghost` \| `temp` \| `outside-roots` \| `stale`; absent for `default` rows |
|
||||
|
||||
The classification is advisory and client-side only (precedence, first match wins):
|
||||
|
||||
1. `hidden: true` → `secondary`/`hidden` — explicit user intent always wins, no rescue.
|
||||
2. A live instance (`instance != null` or `liveCount > 0`), `pinned` or `trusted` → `default` (rescue).
|
||||
3. `PI2_WORKSPACE_HIDE_TEMP=1` (default `1`) and `cwd` is under `$TMPDIR`, `/tmp`, `/var/tmp`, `/var/folders` or `/private/var/folders` → `secondary`/`temp`.
|
||||
4. `PI2_WORKSPACE_HIDE_GHOSTS=1` (default `1`) and `exists === false` → `secondary`/`ghost`.
|
||||
5. `PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS=1` (default `0`) and `cwd` is outside `PI2_WORKSPACE_ROOTS` → `secondary`/`outside-roots`.
|
||||
6. `PI2_WORKSPACE_STALE_DAYS=<n>` (default `0` = off) and `lastActiveAt` older than `n` days → `secondary`/`stale` (`lastActiveAt: null` never counts).
|
||||
7. Otherwise `default`.
|
||||
|
||||
A client that lets the user *choose* a workspace should list only `default` rows by
|
||||
default; `secondary` rows belong behind a “show hidden” toggle. Lookups by
|
||||
`workspaceId` must ignore `visibility` entirely.
|
||||
|
||||
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 |
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
# Releasing pi2d
|
||||
|
||||
Steady-state publishing is fully automated by
|
||||
[`.github/workflows/release.yml`](../.github/workflows/release.yml) and authenticates with
|
||||
**npm Trusted Publishing (OIDC)**. The publish step gets no token: the workflow asks GitHub for a
|
||||
short-lived OIDC token and the npm CLI trades it for publish rights.
|
||||
|
||||
```
|
||||
bump version → git tag v<version> → push tag → release.yml → npm publish (OIDC) → GitHub release
|
||||
```
|
||||
|
||||
That pipeline applies to **every release after the first one**. The very first version has to be
|
||||
published by hand — see [Bootstrap](#bootstrap-the-first-publish-three-phases) — because npmjs.com
|
||||
only offers the Trusted Publisher settings page for a package that already exists on the registry,
|
||||
and `@yuez/pi2d` does not exist yet (`npm view @yuez/pi2d` → 404).
|
||||
|
||||
## Bootstrap: the first publish (three phases)
|
||||
|
||||
### Phase 0 — publish the first version from your machine (once, no provenance)
|
||||
|
||||
npmjs.com has no `@yuez/pi2d` package page yet, so there is nowhere to configure a trusted publisher and
|
||||
CI cannot authenticate. The first version is therefore published manually from the repo root:
|
||||
|
||||
```bash
|
||||
npm login # npm account yuez; 2FA prompt
|
||||
npm whoami # must print: yuez
|
||||
npm publish --access public # from the repo root; runs `prepack` (builds dist/ and web/dist/)
|
||||
```
|
||||
|
||||
This bootstrap tarball is **built and published from your machine, so it has no provenance
|
||||
attestation** — that is expected and unavoidable. Every release after it is built and published by
|
||||
`release.yml` via OIDC and does carry automatic provenance.
|
||||
|
||||
The version you publish here is burned: `npm` rejects a second publish of the same version, so the
|
||||
first CI release must use a **higher** `package.json` version (bump it in Phase 2, before tagging).
|
||||
|
||||
### Phase 1 — register the trusted publisher (possible only now)
|
||||
|
||||
The package page exists after Phase 0. Configure the publisher on
|
||||
<https://www.npmjs.com/package/@yuez/pi2d> — no CI secrets are involved.
|
||||
|
||||
1. **Log in** to npmjs.com as the owner of `@yuez/pi2d` (npm account `yuez`) and make sure 2FA is enabled on
|
||||
that account.
|
||||
2. Package page → **Settings** → **Trusted publishing** → **Add a trusted publisher** →
|
||||
**GitHub Actions**.
|
||||
3. Fill in exactly these fields (they are matched literally):
|
||||
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Organization or user | `zgs225` |
|
||||
| Repository | `pi2d` |
|
||||
| Workflow filename | `release.yml` |
|
||||
| Environment name | *leave empty* (the workflow declares no `environment:`) |
|
||||
| Allowed actions | tick **`npm publish`** (see next point) |
|
||||
|
||||
* The workflow filename is **just the filename** — `release.yml`, not
|
||||
`.github/workflows/release.yml`.
|
||||
* Filenames are **case-sensitive**: `Release.yml` or `release.yaml` will not match.
|
||||
|
||||
4. **⚠️ Tick `npm publish` under "Allowed actions".** Trusted publishers created after
|
||||
**2026-09-03** default to allowing **`npm stage publish` only**, and this workflow runs a plain
|
||||
`npm publish`. `npm stage publish` itself is *always* allowed (it is not a switch you can turn
|
||||
off), but a plain `npm publish` is **not** covered by it — if you leave the box unticked the CI
|
||||
publish is rejected. (No need to "add" `npm stage publish`; it is on regardless.)
|
||||
5. **⚠️ Publish within 2 days.** A newly created trusted publisher must complete its first
|
||||
successful publish within **2 days**, otherwise it expires and can no longer be edited — you have
|
||||
to delete it and create a new one. Create it when you are ready to tag, then go straight to
|
||||
Phase 2.
|
||||
6. **No token secret.** Delete any `NPM_TOKEN` / `NODE_AUTH_TOKEN` repository secret (GitHub →
|
||||
Settings → Secrets and variables → Actions). The workflow fails when one is present.
|
||||
|
||||
Provenance needs no configuration: it is generated automatically for a public package published
|
||||
from a public repo via OIDC. `--provenance` is not passed (and must not be re-added).
|
||||
|
||||
### Phase 2 — first CI release, then lock it down
|
||||
|
||||
```bash
|
||||
# 1. bump to a version HIGHER than the Phase 0 bootstrap version
|
||||
# (edit package.json "version", then commit and push)
|
||||
# 2. tag and push — this triggers the workflow
|
||||
git tag v0.1.1
|
||||
git push origin v0.1.1
|
||||
```
|
||||
|
||||
Wait for the run to succeed (it must finish within the 2-day window from Phase 1). Then retire the
|
||||
bootstrap credential:
|
||||
|
||||
1. <https://www.npmjs.com/settings/zgs225/tokens> → delete the *Automation* (or granular) token
|
||||
used in Phase 0.
|
||||
2. GitHub → Settings → Secrets and variables → Actions → delete the `NPM_TOKEN` secret, if any.
|
||||
3. Package settings → **Require 2FA and disallow tokens**, so no token can publish at all and OIDC
|
||||
is the only path.
|
||||
|
||||
From here on, only the [release checklist](#release-checklist-every-release) is needed.
|
||||
|
||||
## Requirements (must hold)
|
||||
|
||||
| Thing | Required | Where it is enforced |
|
||||
|---|---|---|
|
||||
| npm CLI | **>= 11.5.1** | `Upgrade npm` step (`npm install -g npm@11`) + `Preflight` step |
|
||||
| Node | **>= 22.14.0** | `Preflight` step (`node 22` from `actions/setup-node` is 22.x, fine) |
|
||||
| Workflow permissions | `id-token: write` + `contents: write` | top-level `permissions:` in `release.yml` |
|
||||
| Registry | `https://registry.npmjs.org` | `actions/setup-node` `registry-url` |
|
||||
| Auth token in the **publish** step | **none** | no `env:` on the publish step; `Refuse token-based publishing` step |
|
||||
| `package.json` `repository.url` | `git+https://github.com/zgs225/pi2d.git` | nothing in CI — informational only (see below) |
|
||||
|
||||
Why the two permissions:
|
||||
|
||||
* `id-token: write` lets the job mint the OIDC token npm exchanges for publish rights.
|
||||
* `contents: write` is required by the `softprops/action-gh-release` step that creates the GitHub
|
||||
release; with `contents: read` that step fails with 403. It is granted at workflow level because
|
||||
the release step lives in the single `publish` job — a separate job would mean a second
|
||||
checkout + install + test cycle for no benefit. The npm publish step still receives no token.
|
||||
|
||||
`repository.url` is **not validated by CI**. Nothing fails if it drifts; it only feeds npm's
|
||||
"Repository" link and the provenance metadata, so keep it pointing at the GitHub repo manually.
|
||||
|
||||
`actions/setup-node@v4` with `node-version: 22` installs npm **10.x**, which cannot do trusted
|
||||
publishing — hence the explicit `npm install -g npm@11` followed by the preflight assertion that
|
||||
fails the job when `npm --version` < 11.5.1. Do not drop either step.
|
||||
|
||||
## Release checklist (every release)
|
||||
|
||||
```bash
|
||||
# 1. bump version in package.json and commit/push
|
||||
node -p 'require("./package.json").version' # e.g. 0.1.1
|
||||
|
||||
# 2. optional but recommended: prove the tarball still builds and packs
|
||||
npm publish --dry-run --access public 2>&1 | tail -5
|
||||
|
||||
# 3. tag and push — this is what triggers the workflow
|
||||
git tag v0.1.1
|
||||
git push origin v0.1.1
|
||||
```
|
||||
|
||||
The tag must equal `package.json.version` (without the `v`); `release.yml` checks this first and
|
||||
fails fast on a mismatch. The publish step runs `npm publish --access public` with no token, and
|
||||
`prepack` builds `dist/` and `web/dist/` so the tarball always comes from the tagged source.
|
||||
After a successful publish the workflow opens a GitHub release with generated notes.
|
||||
|
||||
The dry run above warns about missing auth — expected locally, it never contacts the registry for
|
||||
a real publish. It still validates `prepack`, the `files` list and the tarball contents.
|
||||
|
||||
## Verifying a publish
|
||||
|
||||
```bash
|
||||
npm view @yuez/pi2d version dist.integrity dist.attestations
|
||||
npm view @yuez/pi2d dist.tarball
|
||||
npm audit signatures # in a scratch dir, after `npm i @yuez/pi2d`
|
||||
```
|
||||
|
||||
* npmjs.com shows a green **provenance badge** on the package page and on the version's
|
||||
"Provenance" section; it links to the exact commit and workflow run that built the tarball.
|
||||
(The Phase 0 bootstrap version has no badge — that is expected.)
|
||||
* `npm view @yuez/pi2d dist.integrity` must match the tarball you expected; the release page should list
|
||||
the attestation (`dist.attestations.provenance`).
|
||||
* In the workflow log, the publish step should report authenticated publishing via OIDC — never a
|
||||
token.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Cause / fix |
|
||||
|---|---|
|
||||
| `ENEEDAUTH` / "Unable to authenticate" / "not authenticated" on publish | May — not certainly — be a trusted-publisher/OIDC mismatch; if OIDC itself worked the error is a policy denial. Check, in order: (1) workflow filename is exactly `release.yml` (case-sensitive, filename only); (2) "Allowed actions" has **`npm publish`** ticked (post-2026-09-03 configs allow only `npm stage publish` by default, and stage publishing is *always* allowed, so it will not cover a plain `npm publish`); (3) `permissions: id-token: write` is present; (4) the package exists on the registry and the trusted publisher is attached to *that* package; (5) owner/repo are `zgs225`/`pi2d`. The account that pushed the tag does not matter — matching uses owner, repo and workflow filename only (a fork or a renamed repo will not match). |
|
||||
| Preflight fails: `npm 10.x is too old for trusted publishing` | `npm install -g npm@11` step was removed, or the preflight ran before it. Order matters: upgrade, then assert. |
|
||||
| Preflight fails: `no OIDC token endpoint` | `permissions: id-token: write` missing/overridden at job level, or the workflow is not running on GitHub Actions. |
|
||||
| `Refuse token-based publishing` fails | A repository secret named `NODE_AUTH_TOKEN` or `NPM_TOKEN` exists (the guard step maps both into its own env precisely to detect this). Delete the secret — OIDC is the intended path. |
|
||||
| `Create GitHub release` fails with 403 | Workflow `permissions:` lost `contents: write`. |
|
||||
| Publish rejected: version already exists | The tag was reused, or you tagged the Phase 0 bootstrap version. Bump `package.json`, delete the tag locally and remotely, re-tag. |
|
||||
| Trusted publisher "expired"/not editable | The 2-day first-publish window lapsed. Delete it, create it again, and publish promptly. |
|
||||
| No "Trusted publishing" section on npmjs.com | The package does not exist on the registry yet → do Phase 0 first. |
|
||||
| `repository.url` looks wrong on npm | Nothing in CI validates or fails on it; fix `git+https://github.com/zgs225/pi2d.git` in `package.json` and publish again. |
|
||||
|
||||
### Fallback: publishing with a token (not the default path)
|
||||
|
||||
If trusted publishing is temporarily unusable (e.g. the 2-day window expired mid-release), a
|
||||
manual publish from a workstation is an acceptable emergency fallback — **a documented exception,
|
||||
not the norm**:
|
||||
|
||||
```bash
|
||||
npm login # account zgs225, 2FA
|
||||
npm whoami # confirm identity
|
||||
npm publish --access public # runs prepack locally, publishes from this machine
|
||||
```
|
||||
|
||||
Set the token on that single command only if an interactive login is impossible, e.g.
|
||||
`npm publish --access public --//registry.npmjs.org/:_authToken="$TOKEN"` (it is not read from a
|
||||
bare `NODE_AUTH_TOKEN` env var unless an `.npmrc` expands it). Never add the token back to GitHub:
|
||||
the release workflow deliberately rejects it.
|
||||
+30
-3
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "pi2-web-daemon",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"name": "@yuez/pi2d",
|
||||
"version": "0.1.2",
|
||||
"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"
|
||||
@@ -10,9 +10,36 @@
|
||||
"bin": {
|
||||
"pi2": "./dist/cli/pi2.js"
|
||||
},
|
||||
"files": [
|
||||
"dist/",
|
||||
"web/dist/",
|
||||
"docs/protocol.md",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/zgs225/pi2d.git"
|
||||
},
|
||||
"homepage": "https://github.com/zgs225/pi2d#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/zgs225/pi2d/issues"
|
||||
},
|
||||
"keywords": [
|
||||
"pi",
|
||||
"neovim",
|
||||
"coding-agent",
|
||||
"web-console",
|
||||
"daemon"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/cli/pi2.ts daemon",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"build:web": "pnpm --dir web build",
|
||||
"prepack": "npm run build && npm run build:web",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
allowBuilds:
|
||||
esbuild: set this to true or false
|
||||
esbuild: true
|
||||
+69
-1
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* A0–A12 — API/WS end-to-end driver (docs/e2e.md §4.1).
|
||||
* A0–A13 — API/WS end-to-end driver (docs/e2e.md §4.1).
|
||||
*
|
||||
* Runs against a live daemon + one managed headless nvim per workspace + a real
|
||||
* `pi --mode rpc` child. The lifecycle (temp dirs, ephemeral port, pairing,
|
||||
@@ -2870,6 +2870,74 @@ scenario("A12", "Errors", async (ctx) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// A13 — console login (local browser handoff)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
scenario("A13", "Console login handoff", async (ctx) => {
|
||||
const session = () => http("POST", "/api/v1/console/session", { token: CLI_TOKEN });
|
||||
|
||||
const first = await session();
|
||||
ctx.eq("POST /api/v1/console/session → 200", first.status, 200);
|
||||
const token = first.json?.token;
|
||||
const url = typeof first.json?.url === "string" ? first.json.url : "";
|
||||
const deviceId = first.json?.device?.id;
|
||||
|
||||
ctx.eq("the session names the local-browser device", first.json?.device?.name, "local browser");
|
||||
ctx.eq("the local-browser device is a laptop", first.json?.device?.kind, "laptop");
|
||||
ctx.eq("the local-browser device holds every scope", first.json?.device?.scopes, [
|
||||
"read",
|
||||
"steer",
|
||||
"control",
|
||||
"admin",
|
||||
]);
|
||||
ctx.check("the handoff url puts the token in the fragment", /\/#t=[A-Za-z0-9_-]{20,}$/.test(url), {
|
||||
expected: "http://127.0.0.1:<port>/#t=<token>",
|
||||
observed: url.replace(/#t=.{6}.*/, "#t=<redacted>"),
|
||||
});
|
||||
ctx.check("the handoff url never carries the token in the query string", !url.includes("?t="), {
|
||||
expected: "no ?t=",
|
||||
observed: url.replace(/#t=.{6}.*/, "#t=<redacted>"),
|
||||
});
|
||||
ctx.check("the handoff url targets loopback", url.startsWith("http://127.0.0.1:"), {
|
||||
expected: "http://127.0.0.1:<port>/#t=…",
|
||||
observed: url.replace(/#t=.{6}.*/, "#t=<redacted>"),
|
||||
});
|
||||
|
||||
const used = await http("GET", "/api/v1/workspaces", { token });
|
||||
ctx.eq("the handed-off token authenticates → 200", used.status, 200);
|
||||
|
||||
// `:PiWeb` twice must not log the tab that is already open out.
|
||||
const second = await session();
|
||||
ctx.eq("a second login reuses the same token", second.json?.token, token);
|
||||
const stillUsed = await http("GET", "/api/v1/workspaces", { token });
|
||||
ctx.eq("the first tab keeps working after a second :PiWeb", stillUsed.status, 200);
|
||||
|
||||
const anonymous = await http("POST", "/api/v1/console/session");
|
||||
ctx.eq("no cli token → 401", anonymous.status, 401);
|
||||
const asDevice = await http("POST", "/api/v1/console/session", { token });
|
||||
ctx.eq("a device token cannot mint another console session", asDevice.status, 401);
|
||||
|
||||
const devices = await http("GET", "/api/v1/devices", { token: CLI_TOKEN });
|
||||
const browsers = (Array.isArray(devices.json) ? devices.json : []).filter(
|
||||
(device) => device?.name === "local browser",
|
||||
);
|
||||
ctx.eq("exactly one local-browser device exists", browsers.length, 1);
|
||||
|
||||
// Revocation drops the stored plaintext, so the next login mints a new token.
|
||||
const revoked = await http("DELETE", `/api/v1/devices/${encodeURIComponent(deviceId)}`, { token: CLI_TOKEN });
|
||||
ctx.eq("revoking the local browser → 204", revoked.status, 204);
|
||||
const afterRevoke = await session();
|
||||
ctx.check("the next login mints a new token", afterRevoke.status === 200 && afterRevoke.json?.token !== token, {
|
||||
expected: "200 with a different token",
|
||||
observed: { status: afterRevoke.status, sameToken: afterRevoke.json?.token === token },
|
||||
});
|
||||
const deadToken = await http("GET", "/api/v1/workspaces", { token });
|
||||
ctx.eq("the revoked token is rejected → 401", deadToken.status, 401);
|
||||
const freshToken = await http("GET", "/api/v1/workspaces", { token: afterRevoke.json?.token });
|
||||
ctx.eq("the new token works → 200", freshToken.status, 200);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// reporting
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+4
-1
@@ -44,7 +44,8 @@ Options:
|
||||
|
||||
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_DATA_DIR, PI2_STATE_DIR, PI2_LOG_LEVEL, PI2_WORKSPACE_ROOTS,
|
||||
PI2_ACCESS_MODE (local|lan|tailscale), PI2_PUBLIC_URL
|
||||
|
||||
Runtime files ($PI2_RUNTIME_DIR):
|
||||
d.sock plugin unix socket (nvim → daemon)
|
||||
@@ -180,6 +181,8 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
|
||||
daemonId,
|
||||
startedAt: Date.now(),
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
access: config.access,
|
||||
publicUrl: config.publicUrl,
|
||||
},
|
||||
});
|
||||
// Rotate the local CLI token only when this process owns the lock:
|
||||
|
||||
+80
-1
@@ -11,7 +11,7 @@ import { homedir, platform as osPlatform } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { DEFAULT_PORT } from "../config.js";
|
||||
import { DEFAULT_PORT, loadConfig, type AccessMode } from "../config.js";
|
||||
import { daemonSocketPath, runtimeDir } from "../core/paths.js";
|
||||
import { PROTOCOL_VERSION } from "../protocol/types.js";
|
||||
import { formatTable } from "./util.js";
|
||||
@@ -43,17 +43,26 @@ export interface BinaryProbe {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface AccessModeContext {
|
||||
mode: AccessMode;
|
||||
host: string;
|
||||
port: number;
|
||||
publicUrl: string | null;
|
||||
}
|
||||
|
||||
export interface DoctorContext {
|
||||
platform: NodeJS.Platform;
|
||||
nodeVersion: string;
|
||||
nvim: BinaryProbe;
|
||||
pi: BinaryProbe;
|
||||
curl: BinaryProbe;
|
||||
plugin: { dir: string | undefined; bridgeFound: boolean };
|
||||
runtime: { path: string; exists: boolean; mode: number | undefined };
|
||||
cliToken: { path: string; exists: boolean; mode: number | undefined };
|
||||
socket: { path: string; exists: boolean };
|
||||
daemon: { reachable: boolean; port?: number; protocolVersion?: number; error?: string };
|
||||
port: { configured: number; bound: boolean };
|
||||
access: AccessModeContext;
|
||||
serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string };
|
||||
linger: { checked: boolean; enabled?: boolean; detail?: string };
|
||||
webDist: { path: string; exists: boolean };
|
||||
@@ -82,6 +91,13 @@ export function parseNvimVersion(output: string): string | undefined {
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
/** `curl 8.7.1 (x86_64-pc-linux-gnu) …` (first line of `curl --version`) → `8.7.1`. */
|
||||
export function parseCurlVersion(output: string | undefined): string | undefined {
|
||||
if (output === undefined) return undefined;
|
||||
const match = /^curl\s+v?(\d+\.\d+\.\d+)/.exec(output.trim());
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
export const MIN_NODE: readonly [number, number, number] = [22, 0, 0];
|
||||
export const MIN_NVIM: readonly [number, number, number] = [0, 9, 0];
|
||||
|
||||
@@ -122,6 +138,25 @@ export function checkPi(probe: BinaryProbe): DoctorCheck {
|
||||
return { name: "pi", status: "ok", detail: `${probe.version?.trim() ?? "unknown version"} (${probe.path ?? "pi"})` };
|
||||
}
|
||||
|
||||
/**
|
||||
* `curl`: `:PiWeb`'s login handshake shells out to curl (Neovim has no HTTP
|
||||
* client), so a missing binary only breaks local sign-in — warn, never fail.
|
||||
*/
|
||||
export function checkCurl(probe: BinaryProbe): DoctorCheck {
|
||||
if (!probe.found) {
|
||||
return {
|
||||
name: "curl",
|
||||
status: "warn",
|
||||
detail: "not found on PATH (:PiWeb cannot sign the browser in automatically; pair instead)",
|
||||
};
|
||||
}
|
||||
const version = parseCurlVersion(probe.version);
|
||||
if (version === undefined) {
|
||||
return { name: "curl", status: "warn", detail: `could not parse version of ${probe.path ?? "curl"}` };
|
||||
}
|
||||
return { name: "curl", status: "ok", detail: `${version} (${probe.path ?? "curl"})` };
|
||||
}
|
||||
|
||||
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)` };
|
||||
@@ -182,6 +217,30 @@ export function checkPort(probe: DoctorContext["port"]): DoctorCheck {
|
||||
return { name: "port", status: "ok", detail: `${probe.configured} free` };
|
||||
}
|
||||
|
||||
function isLoopbackHost(host: string): boolean {
|
||||
return host === "127.0.0.1" || host === "::1" || host === "localhost";
|
||||
}
|
||||
|
||||
/**
|
||||
* `access`: local is fine; lan/tailscale warn because the daemon has no TLS of
|
||||
* its own, and fail when a non-loopback bind is exposed without a public URL.
|
||||
*/
|
||||
export function checkAccess(probe: AccessModeContext): DoctorCheck {
|
||||
if (probe.mode === "local") return { name: "access", status: "ok", detail: "local (loopback only)" };
|
||||
|
||||
const publicSuffix = probe.publicUrl === null ? "" : `, public ${probe.publicUrl}`;
|
||||
const detail = `${probe.mode} (bind ${probe.host}/${probe.port}${publicSuffix})`;
|
||||
if (probe.publicUrl === null && !isLoopbackHost(probe.host)) {
|
||||
return { name: "access", status: "fail", detail };
|
||||
}
|
||||
const tls = probe.publicUrl !== null && probe.publicUrl.startsWith("https:");
|
||||
return {
|
||||
name: "access",
|
||||
status: "warn",
|
||||
detail: tls ? detail : `${detail} — no TLS, prefer \`tailscale serve\``,
|
||||
};
|
||||
}
|
||||
|
||||
export function checkServiceManager(probe: DoctorContext["serviceManager"]): DoctorCheck {
|
||||
return {
|
||||
name: "service-manager",
|
||||
@@ -220,12 +279,14 @@ export function defaultProbes(ctx: DoctorContext): DoctorProbe[] {
|
||||
{ name: "node", run: () => checkNode(ctx.nodeVersion) },
|
||||
{ name: "nvim", run: () => checkNvim(ctx.nvim) },
|
||||
{ name: "pi", run: () => checkPi(ctx.pi) },
|
||||
{ name: "curl", run: () => checkCurl(ctx.curl) },
|
||||
{ name: "plugin", run: () => checkPlugin(ctx.plugin) },
|
||||
{ name: "runtime-dir", run: () => checkRuntimeDir(ctx.runtime) },
|
||||
{ name: "cli-token", run: () => checkCliToken(ctx.cliToken) },
|
||||
{ name: "socket", run: () => checkSocket(ctx.socket, ctx.daemon.reachable) },
|
||||
{ name: "daemon", run: () => checkDaemon(ctx.daemon) },
|
||||
{ name: "port", run: () => checkPort(ctx.port) },
|
||||
{ name: "access", run: () => checkAccess(ctx.access) },
|
||||
{ name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) },
|
||||
...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []),
|
||||
{ name: "web-dist", run: () => checkWebDist(ctx.webDist) },
|
||||
@@ -309,6 +370,21 @@ function statOrUndefined(path: string): { exists: boolean; mode: number | undefi
|
||||
}
|
||||
}
|
||||
|
||||
/** Best-effort access context; an unparsable environment reports `local`. */
|
||||
function accessContext(env: NodeJS.ProcessEnv, port: number): AccessModeContext {
|
||||
try {
|
||||
const config = loadConfig(env);
|
||||
return { mode: config.access, host: config.host, port, publicUrl: config.publicUrl };
|
||||
} catch {
|
||||
return {
|
||||
mode: "local",
|
||||
host: env.PI2_HOST?.trim() || "127.0.0.1",
|
||||
port,
|
||||
publicUrl: env.PI2_PUBLIC_URL?.trim().replace(/\/+$/, "") || null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function binaryProbe(command: string, args: readonly string[], options: DoctorOptions, env: NodeJS.ProcessEnv): Promise<BinaryProbe> {
|
||||
const path = (options.which ?? ((name: string) => whichSync(name, env)))(command);
|
||||
if (path === undefined) return { found: false, error: `${command} not found on PATH` };
|
||||
@@ -335,6 +411,7 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
|
||||
if (parsed !== undefined) nvim.version = `v${parsed}`;
|
||||
}
|
||||
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 bridgeFound = existsSync(join(pluginDir, "lua", "pi", "web", "bridge.lua"));
|
||||
@@ -388,12 +465,14 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
|
||||
nodeVersion: process.version,
|
||||
nvim,
|
||||
pi,
|
||||
curl,
|
||||
plugin: { dir: pluginDir, bridgeFound },
|
||||
runtime: { path: runtime, exists: runtimeStat.exists, mode: runtimeStat.mode },
|
||||
cliToken: { path: cliTokenPath, exists: tokenStat.exists, mode: tokenStat.mode },
|
||||
socket: { path: socketPath, exists: existsSync(socketPath) },
|
||||
daemon,
|
||||
port: { configured: daemon.port ?? configuredPort, bound: daemon.reachable },
|
||||
access: accessContext(env, daemon.port ?? configuredPort),
|
||||
serviceManager,
|
||||
linger,
|
||||
webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) },
|
||||
|
||||
+17
-2
@@ -5,9 +5,13 @@
|
||||
* Both files carry the same payload:
|
||||
*
|
||||
* ```jsonc
|
||||
* {"pid":1234,"bootId":"…","port":7676,"daemonId":"d-…","startedAt":1733,"protocolVersion":1}
|
||||
* {"pid":1234,"bootId":"…","port":7676,"daemonId":"d-…","startedAt":1733,"protocolVersion":1,
|
||||
* "access":"local","publicUrl":null}
|
||||
* ```
|
||||
*
|
||||
* `access`/`publicUrl` are optional so readers built before the access modes
|
||||
* keep working.
|
||||
*
|
||||
* The lock is created with `wx` (atomic: only one daemon wins) and is
|
||||
* considered **stale** when the pid is gone or the recorded boot id differs
|
||||
* from the current one (pid reuse after a reboot). `--force` ignores a live
|
||||
@@ -19,6 +23,7 @@ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { dirname, join } from "node:path";
|
||||
import { daemonLockPath, ensureDir, runtimeDir } from "../core/paths.js";
|
||||
import { ACCESS_MODES, type AccessMode } from "../config.js";
|
||||
|
||||
export const LOCK_FILE = "daemon.lock";
|
||||
export const DAEMON_JSON_FILE = "daemon.json";
|
||||
@@ -30,6 +35,10 @@ export interface DaemonLock {
|
||||
daemonId: string;
|
||||
startedAt: number;
|
||||
protocolVersion: number;
|
||||
/** Optional: written by daemons that know about access modes. */
|
||||
access?: AccessMode;
|
||||
/** Optional: external base URL (or explicit `null` when unset). */
|
||||
publicUrl?: string | null;
|
||||
}
|
||||
|
||||
export type LockErrorCode = "E_LOCKED";
|
||||
@@ -79,6 +88,10 @@ export function isPidAlive(pid: number): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function isAccessMode(value: unknown): value is AccessMode {
|
||||
return typeof value === "string" && (ACCESS_MODES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function isLock(value: unknown): value is DaemonLock {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const candidate = value as Partial<DaemonLock>;
|
||||
@@ -91,7 +104,9 @@ function isLock(value: unknown): value is DaemonLock {
|
||||
typeof candidate.daemonId === "string" &&
|
||||
candidate.daemonId !== "" &&
|
||||
typeof candidate.startedAt === "number" &&
|
||||
typeof candidate.protocolVersion === "number"
|
||||
typeof candidate.protocolVersion === "number" &&
|
||||
(candidate.access === undefined || isAccessMode(candidate.access)) &&
|
||||
(candidate.publicUrl === undefined || candidate.publicUrl === null || typeof candidate.publicUrl === "string")
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+118
-8
@@ -14,7 +14,7 @@
|
||||
* bound port, `cli.token` the local admin token (see docs/deployment.md).
|
||||
*/
|
||||
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { platform as osPlatform } from "node:os";
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
packageVersion,
|
||||
parseArgs,
|
||||
realpathOrSelf,
|
||||
stringFlag,
|
||||
UsageError,
|
||||
} from "./util.js";
|
||||
import {
|
||||
@@ -51,12 +52,18 @@ Usage:
|
||||
pi2 daemon [start] [options] run the web-console daemon (foreground)
|
||||
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 doctor [--json] environment checks
|
||||
pi2 pairing create a pairing code (URL + code + QR payload)
|
||||
pi2 pairing [--public-url <url>] create a pairing code (URL + code + QR payload)
|
||||
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
|
||||
pi2 uninstall-service [--dry-run|--write] remove the unit
|
||||
pi2 --version | --help
|
||||
|
||||
\`pi2 open\` flags: --print prints the URL only; --no-browser prints it instead
|
||||
of launching a browser (--print implies --no-browser).
|
||||
\`pi2 pairing\` flags: --public-url <url> rebuilds the URL on that public base
|
||||
(defaults to daemon.json's publicUrl, then PI2_PUBLIC_URL).
|
||||
|
||||
The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and
|
||||
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`.
|
||||
See docs/deployment.md.`;
|
||||
@@ -258,6 +265,8 @@ interface InfoBody {
|
||||
platform: string;
|
||||
capabilities: string[];
|
||||
limits: { maxBodyBytes: number; maxFrameBytes: number; maxConnections: number };
|
||||
access?: string;
|
||||
publicUrl?: string | null;
|
||||
}
|
||||
|
||||
interface HealthBody {
|
||||
@@ -298,7 +307,13 @@ export async function runStatus(options: StatusOptions): Promise<number> {
|
||||
print(
|
||||
JSON.stringify(
|
||||
{
|
||||
daemon: { url: client.baseUrl, ...info },
|
||||
daemon: {
|
||||
url: client.baseUrl,
|
||||
...info,
|
||||
// Older daemons may not report them; daemon.json does.
|
||||
access: info.access ?? client.daemon.access,
|
||||
publicUrl: info.publicUrl ?? client.daemon.publicUrl ?? null,
|
||||
},
|
||||
instances,
|
||||
resources,
|
||||
health,
|
||||
@@ -350,6 +365,21 @@ export async function runStatus(options: StatusOptions): Promise<number> {
|
||||
export interface PairingOptions {
|
||||
client: DaemonClient;
|
||||
print?: (line: string) => void;
|
||||
/** Rebuild the printed/QR url on this public base (e.g. `https://host.ts.net`). */
|
||||
publicUrl?: string | null;
|
||||
}
|
||||
|
||||
function withoutTrailingSlash(value: string): string {
|
||||
return value.trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/** `--public-url` → `daemon.json.publicUrl` → `PI2_PUBLIC_URL`, first non-empty wins. */
|
||||
export function resolvePublicUrl(client: DaemonClient, flag: string | undefined): string | null {
|
||||
for (const candidate of [flag, client.daemon.publicUrl, process.env.PI2_PUBLIC_URL]) {
|
||||
const value = candidate === undefined || candidate === null ? "" : withoutTrailingSlash(candidate);
|
||||
if (value !== "") return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function runPairing(options: PairingOptions): Promise<number> {
|
||||
@@ -359,9 +389,13 @@ export async function runPairing(options: PairingOptions): Promise<number> {
|
||||
if (code === undefined) throw new CliError("pairing failed: daemon returned no code");
|
||||
const expiresAt = typeof result.body.expiresAt === "number" ? result.body.expiresAt : undefined;
|
||||
const nonce = typeof result.body.nonce === "string" ? result.body.nonce : undefined;
|
||||
// Rebuild the URL from the *actual* base URL: the daemon's own `url` field is
|
||||
// derived from the configured port, which is stale after a retry or `--port 0`.
|
||||
const url = `${options.client.baseUrl}/pair/${code}`;
|
||||
// Rebuild the URL from the *actual* base URL (or the public base when one is
|
||||
// known): the daemon's own `url` field is derived from the configured port,
|
||||
// which is stale after a retry or `--port 0`.
|
||||
const base = options.publicUrl === undefined || options.publicUrl === null || options.publicUrl.trim() === ""
|
||||
? options.client.baseUrl
|
||||
: withoutTrailingSlash(options.publicUrl);
|
||||
const url = `${base}/pair/${code}`;
|
||||
const payload = JSON.stringify({ v: PROTOCOL_VERSION, code, url, ...(expiresAt === undefined ? {} : { expiresAt }), ...(nonce === undefined ? {} : { nonce }) });
|
||||
|
||||
print(`url ${url}`);
|
||||
@@ -373,6 +407,52 @@ export async function runPairing(options: PairingOptions): Promise<number> {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// open
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface OpenOptions {
|
||||
client: DaemonClient;
|
||||
print?: (line: string) => void;
|
||||
/** `--print`: print the URL only and exit. */
|
||||
printOnly?: boolean;
|
||||
/** `--no-browser`: print the URL instead of launching one. */
|
||||
noBrowser?: boolean;
|
||||
/** Opener override; call `onError` when the launch fails. */
|
||||
openUrl?: (url: string, onError: () => void) => void;
|
||||
}
|
||||
|
||||
/** Detached platform opener: `pi2 open` never waits for the browser. */
|
||||
export function openInBrowser(url: string, onError: () => void): void {
|
||||
const command = osPlatform() === "darwin" ? "open" : "xdg-open";
|
||||
try {
|
||||
const child = spawn(command, [url], { detached: true, stdio: "ignore" });
|
||||
child.once("error", onError);
|
||||
child.unref();
|
||||
} catch {
|
||||
onError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `pi2 open`: mint a loopback browser session and put the browser on it. The
|
||||
* token stays inside the returned URL (fragment), and only the URL is printed.
|
||||
*/
|
||||
export async function runOpen(options: OpenOptions): Promise<number> {
|
||||
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
|
||||
const result = await options.client.post("/api/v1/console/session", {});
|
||||
const url = typeof result.body.url === "string" ? result.body.url : undefined;
|
||||
if (url === undefined) throw new CliError("console session failed: daemon returned no url");
|
||||
|
||||
if (options.printOnly === true || options.noBrowser === true) {
|
||||
print(url);
|
||||
return 0;
|
||||
}
|
||||
// A missing xdg-open only costs the auto-launch; the URL is still useful.
|
||||
(options.openUrl ?? openInBrowser)(url, () => print(url));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// doctor
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -522,6 +602,24 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
|
||||
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
|
||||
return await runStatus({ client, json: boolFlag(parsed.flags, "--json"), print: out });
|
||||
}
|
||||
case "open": {
|
||||
const parsed = parseArgs(rest, {
|
||||
booleans: ["--print", "--no-browser", "--help"],
|
||||
aliases: { "-h": "--help" },
|
||||
});
|
||||
if (boolFlag(parsed.flags, "--help")) {
|
||||
out(USAGE);
|
||||
return 0;
|
||||
}
|
||||
if (parsed.positionals.length > 0) throw new UsageError("open takes no arguments");
|
||||
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
|
||||
return await runOpen({
|
||||
client,
|
||||
print: out,
|
||||
printOnly: boolFlag(parsed.flags, "--print"),
|
||||
noBrowser: boolFlag(parsed.flags, "--no-browser"),
|
||||
});
|
||||
}
|
||||
case "doctor": {
|
||||
const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } });
|
||||
if (boolFlag(parsed.flags, "--help")) {
|
||||
@@ -534,9 +632,21 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
|
||||
}
|
||||
case "pairing":
|
||||
case "pair": {
|
||||
parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } });
|
||||
const parsed = parseArgs(rest, {
|
||||
values: ["--public-url"],
|
||||
booleans: ["--help"],
|
||||
aliases: { "-h": "--help" },
|
||||
});
|
||||
if (boolFlag(parsed.flags, "--help")) {
|
||||
out(USAGE);
|
||||
return 0;
|
||||
}
|
||||
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
|
||||
return await runPairing({ client, print: out });
|
||||
return await runPairing({
|
||||
client,
|
||||
print: out,
|
||||
publicUrl: resolvePublicUrl(client, stringFlag(parsed.flags, "--public-url")),
|
||||
});
|
||||
}
|
||||
case "install-service":
|
||||
case "uninstall-service": {
|
||||
|
||||
+113
-11
@@ -3,7 +3,13 @@
|
||||
*
|
||||
* Defaults follow `docs/protocol.md`; deployment-specific values come from the
|
||||
* environment so `pi2 daemon` can be started without a config file.
|
||||
*
|
||||
* `PI2_ACCESS_MODE` picks the bind address and the derived CORS origins:
|
||||
* `local` is loopback-only, `lan` adds the detected LAN address and
|
||||
* `tailscale` adds the origin of `PI2_PUBLIC_URL`. `PI2_ORIGINS` is *additive*
|
||||
* to the derived list; it never replaces it.
|
||||
*/
|
||||
import { networkInterfaces } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { daemonTokenPath, dataDir } from "./core/paths.js";
|
||||
|
||||
@@ -12,6 +18,9 @@ export const DEFAULT_MAX_BODY_BYTES = 8 * 1024 * 1024;
|
||||
export const DEFAULT_MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
||||
export const DEFAULT_MAX_CONNECTIONS = 64;
|
||||
|
||||
export type AccessMode = "local" | "lan" | "tailscale";
|
||||
export const ACCESS_MODES: readonly AccessMode[] = ["local", "lan", "tailscale"];
|
||||
|
||||
export interface Limits {
|
||||
maxBodyBytes: number;
|
||||
maxFrameBytes: number;
|
||||
@@ -28,10 +37,18 @@ export interface Config {
|
||||
limits: Limits;
|
||||
tokenPath: string;
|
||||
deviceStorePath: string;
|
||||
access: AccessMode;
|
||||
/** External base URL (no trailing slash), e.g. `https://host.tail1234.ts.net`. */
|
||||
publicUrl: string | null;
|
||||
}
|
||||
|
||||
export type ConfigEnv = Record<string, string | undefined>;
|
||||
|
||||
export interface ConfigOptions {
|
||||
/** LAN address probe for `PI2_ACCESS_MODE=lan`; overridable in tests. */
|
||||
detectLanIp?: () => string | null;
|
||||
}
|
||||
|
||||
function defaultStaticDir(): string {
|
||||
return fileURLToPath(new URL("../web/dist", import.meta.url));
|
||||
}
|
||||
@@ -46,24 +63,107 @@ function parsePort(raw: string | undefined): number {
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseOrigins(raw: string | undefined, port: number): string[] {
|
||||
if (raw !== undefined) {
|
||||
return raw
|
||||
.split(",")
|
||||
.map((origin) => origin.trim())
|
||||
.filter((origin) => origin.length > 0);
|
||||
}
|
||||
return [`http://127.0.0.1:${port}`, `http://localhost:${port}`];
|
||||
/** Unknown modes fail fast; the daemon prints the message as a one-line `pi2: ` error. */
|
||||
export function parseAccessMode(raw: string | undefined): AccessMode {
|
||||
const value = raw?.trim() ?? "";
|
||||
if (value === "") return "local";
|
||||
if ((ACCESS_MODES as readonly string[]).includes(value)) return value as AccessMode;
|
||||
throw new Error("PI2_ACCESS_MODE must be local, lan or tailscale");
|
||||
}
|
||||
|
||||
export function loadConfig(env: ConfigEnv = process.env): Config {
|
||||
/** Trailing slashes and empty strings are not meaningful origins. */
|
||||
function normalizeOrigin(raw: string): string | null {
|
||||
const value = raw.trim().replace(/\/+$/, "");
|
||||
return value === "" ? null : value;
|
||||
}
|
||||
|
||||
function normalizePublicUrl(raw: string | undefined): string | null {
|
||||
if (raw === undefined) return null;
|
||||
return normalizeOrigin(raw);
|
||||
}
|
||||
|
||||
/** `https://host/path?q=1` → `https://host`; unparsable values fall back verbatim. */
|
||||
function originOf(url: string): string | null {
|
||||
try {
|
||||
return new URL(url).origin;
|
||||
} catch {
|
||||
return normalizeOrigin(url);
|
||||
}
|
||||
}
|
||||
|
||||
function parseOrigins(raw: string | undefined): string[] {
|
||||
if (raw === undefined) return [];
|
||||
return raw
|
||||
.split(",")
|
||||
.map((origin) => normalizeOrigin(origin))
|
||||
.filter((origin): origin is string => origin !== null);
|
||||
}
|
||||
|
||||
function dedupe(origins: readonly string[]): string[] {
|
||||
return [...new Set(origins)];
|
||||
}
|
||||
|
||||
function defaultHostFor(access: AccessMode): string {
|
||||
return access === "lan" ? "0.0.0.0" : "127.0.0.1";
|
||||
}
|
||||
|
||||
function loopbackOrigins(port: number): string[] {
|
||||
return [`http://127.0.0.1:${port}`, `http://localhost:${port}`, `http://[::1]:${port}`];
|
||||
}
|
||||
|
||||
/**
|
||||
* First non-internal IPv4 address, best effort: `lan` mode only *adds* an
|
||||
* origin, and an unknown address just leaves the loopback list in place.
|
||||
*/
|
||||
export function detectLanIp(): string | null {
|
||||
try {
|
||||
for (const addresses of Object.values(networkInterfaces())) {
|
||||
for (const address of addresses ?? []) {
|
||||
if (address.family !== "IPv4" || address.internal) continue;
|
||||
if (address.address.startsWith("169.254.")) continue;
|
||||
return address.address;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// best effort only
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function derivedOrigins(
|
||||
access: AccessMode,
|
||||
port: number,
|
||||
publicUrl: string | null,
|
||||
detect: () => string | null,
|
||||
): string[] {
|
||||
const origins = loopbackOrigins(port);
|
||||
if (access === "lan") {
|
||||
let lanIp: string | null = null;
|
||||
try {
|
||||
lanIp = detect();
|
||||
} catch {
|
||||
lanIp = null;
|
||||
}
|
||||
if (lanIp !== null && lanIp.trim() !== "") origins.push(`http://${lanIp.trim()}:${port}`);
|
||||
} else if (access === "tailscale" && publicUrl !== null) {
|
||||
const origin = originOf(publicUrl);
|
||||
if (origin !== null) origins.push(origin);
|
||||
}
|
||||
return origins;
|
||||
}
|
||||
|
||||
export function loadConfig(env: ConfigEnv = process.env, options: ConfigOptions = {}): Config {
|
||||
const port = parsePort(env.PI2_PORT);
|
||||
const host = env.PI2_HOST?.trim() || "127.0.0.1";
|
||||
const access = parseAccessMode(env.PI2_ACCESS_MODE);
|
||||
const publicUrl = normalizePublicUrl(env.PI2_PUBLIC_URL);
|
||||
const host = env.PI2_HOST?.trim() || defaultHostFor(access);
|
||||
const derived = derivedOrigins(access, port, publicUrl, options.detectLanIp ?? detectLanIp);
|
||||
|
||||
return {
|
||||
host,
|
||||
port,
|
||||
staticDir: env.PI2_STATIC_DIR?.trim() || defaultStaticDir(),
|
||||
corsOrigins: parseOrigins(env.PI2_ORIGINS, port),
|
||||
corsOrigins: dedupe([...derived, ...parseOrigins(env.PI2_ORIGINS)]),
|
||||
limits: {
|
||||
maxBodyBytes: DEFAULT_MAX_BODY_BYTES,
|
||||
maxFrameBytes: DEFAULT_MAX_FRAME_BYTES,
|
||||
@@ -71,5 +171,7 @@ export function loadConfig(env: ConfigEnv = process.env): Config {
|
||||
},
|
||||
tokenPath: daemonTokenPath(),
|
||||
deviceStorePath: `${dataDir()}/devices.json`,
|
||||
access,
|
||||
publicUrl,
|
||||
};
|
||||
}
|
||||
+104
-1
@@ -9,7 +9,7 @@
|
||||
* `local-cli` device with every scope; see `docs/deployment.md` §7.
|
||||
*/
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { dataDir } from "../core/paths.js";
|
||||
import { ERROR_CODES } from "../protocol/errors.js";
|
||||
@@ -72,11 +72,25 @@ export interface AuthStoreOptions {
|
||||
* `local-cli` device with every scope. Checked after the persisted devices.
|
||||
*/
|
||||
localTokenPath?: string;
|
||||
/**
|
||||
* Where the plaintext local-browser token lives. Defaults to
|
||||
* `<dataDir>/local-browser.token` (mode 0600), next to `devices.json`.
|
||||
*/
|
||||
localBrowserTokenPath?: string;
|
||||
}
|
||||
|
||||
/** Synthetic device id used for the local CLI token (never persisted). */
|
||||
export const LOCAL_CLI_DEVICE_ID = "local-cli";
|
||||
|
||||
/** The single device that represents the browser opened by `pi2 open`. */
|
||||
export const LOCAL_BROWSER_NAME = "local browser";
|
||||
export const LOCAL_BROWSER_KIND: DeviceKind = "laptop";
|
||||
|
||||
export interface LocalBrowserSession {
|
||||
token: string;
|
||||
device: DevicePublic;
|
||||
}
|
||||
|
||||
/** Constant-time string compare; the token length itself is not a secret. */
|
||||
function tokensEqual(expected: string, candidate: string): boolean {
|
||||
const left = Buffer.from(expected, "utf8");
|
||||
@@ -142,6 +156,7 @@ function pairCode(): string {
|
||||
export class AuthStore {
|
||||
readonly path: string;
|
||||
readonly localTokenPath: string | undefined;
|
||||
readonly localBrowserTokenPath: string;
|
||||
private readonly now: () => number;
|
||||
private readonly baseUrl: string;
|
||||
private readonly touchIntervalMs: number;
|
||||
@@ -155,6 +170,7 @@ export class AuthStore {
|
||||
this.touchIntervalMs = options.touchIntervalMs ?? 60_000;
|
||||
this.localTokenPath =
|
||||
options.localTokenPath === undefined || options.localTokenPath === "" ? undefined : options.localTokenPath;
|
||||
this.localBrowserTokenPath = options.localBrowserTokenPath ?? `${dirname(this.path)}/local-browser.token`;
|
||||
this.load();
|
||||
}
|
||||
|
||||
@@ -206,6 +222,9 @@ export class AuthStore {
|
||||
if (!record || record.revokedAt !== null) return false;
|
||||
record.revokedAt = this.now();
|
||||
this.persist();
|
||||
// Revoking the local browser also drops the plaintext token, so the next
|
||||
// `:PiWeb` / `pi2 open` mints a fresh one instead of handing out a dead URL.
|
||||
if (record.name === LOCAL_BROWSER_NAME && record.kind === LOCAL_BROWSER_KIND) this.clearLocalBrowserToken();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -261,6 +280,90 @@ export class AuthStore {
|
||||
return this.pairs.has(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* The local-browser login handshake (`POST /api/v1/console/session`).
|
||||
*
|
||||
* There is exactly one "local browser" device and, until it is revoked, one
|
||||
* stable token: `pi2 open` and `:PiWeb` hand the same credentials to the
|
||||
* browser on every call, so opening the console twice never invalidates the
|
||||
* tab that is already open. The plaintext lives in
|
||||
* `<dataDir>/local-browser.token` (0600, like `cli.token`); `devices.json`
|
||||
* keeps only the hash.
|
||||
*
|
||||
* Revoking the device (or deleting the file) forces a new token on the next
|
||||
* login; that path also covers a `devices.json` whose hash no longer matches
|
||||
* the stored plaintext.
|
||||
*/
|
||||
localBrowserSession(): LocalBrowserSession {
|
||||
const existing = this.devices.find(
|
||||
(device) => device.name === LOCAL_BROWSER_NAME && device.kind === LOCAL_BROWSER_KIND,
|
||||
);
|
||||
const stored = this.readLocalBrowserToken();
|
||||
if (
|
||||
existing !== undefined &&
|
||||
existing.revokedAt === null &&
|
||||
stored !== null &&
|
||||
timingSafeEqualHex(existing.tokenHash, hashToken(stored))
|
||||
) {
|
||||
return { token: stored, device: publicDevice(existing) };
|
||||
}
|
||||
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const hash = hashToken(token);
|
||||
if (existing === undefined) {
|
||||
// `createDevice` mints its own token; overwrite it so the created and
|
||||
// rotated paths end in the same state (one record, this token).
|
||||
const created = this.createDevice({
|
||||
name: LOCAL_BROWSER_NAME,
|
||||
kind: LOCAL_BROWSER_KIND,
|
||||
scopes: [...SCOPES],
|
||||
});
|
||||
const record = this.devices.find((device) => device.id === created.device.id);
|
||||
if (record === undefined) return created;
|
||||
record.tokenHash = hash;
|
||||
record.scopes = [...SCOPES];
|
||||
this.persist();
|
||||
this.writeLocalBrowserToken(token);
|
||||
return { token, device: publicDevice(record) };
|
||||
}
|
||||
|
||||
existing.tokenHash = hash;
|
||||
existing.scopes = [...SCOPES];
|
||||
existing.revokedAt = null;
|
||||
this.persist();
|
||||
this.writeLocalBrowserToken(token);
|
||||
return { token, device: publicDevice(existing) };
|
||||
}
|
||||
|
||||
/** Stored plaintext for the local browser; `null` when absent or unreadable. */
|
||||
private readLocalBrowserToken(): string | null {
|
||||
if (!existsSync(this.localBrowserTokenPath)) return null;
|
||||
try {
|
||||
const contents = readFileSync(this.localBrowserTokenPath, "utf8").trim();
|
||||
return contents === "" ? null : contents;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomic 0600 write, same pattern as `persist()`. */
|
||||
private writeLocalBrowserToken(token: string): void {
|
||||
const directory = dirname(this.localBrowserTokenPath);
|
||||
if (!existsSync(directory)) mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||||
const temporary = `${this.localBrowserTokenPath}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
||||
writeFileSync(temporary, `${token}\n`, { mode: 0o600 });
|
||||
renameSync(temporary, this.localBrowserTokenPath);
|
||||
}
|
||||
|
||||
/** Drop the stored token; the next login mints a new one. */
|
||||
private clearLocalBrowserToken(): void {
|
||||
try {
|
||||
if (existsSync(this.localBrowserTokenPath)) unlinkSync(this.localBrowserTokenPath);
|
||||
} catch {
|
||||
/* best effort: a missing file is the desired state */
|
||||
}
|
||||
}
|
||||
|
||||
/** The local CLI token grants every scope; it is not persisted or revocable. */
|
||||
private localCliDevice(): DevicePublic {
|
||||
const timestamp = this.now();
|
||||
|
||||
+38
-3
@@ -9,7 +9,7 @@ import { ERROR_CODES, errorBody } from "../protocol/errors.js";
|
||||
import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
|
||||
import type { Config } from "../config.js";
|
||||
import type { AuthStore, DevicePublic } from "./auth.js";
|
||||
import { isAllowedOrigin } from "./auth.js";
|
||||
import { isAllowedOrigin, LOCAL_CLI_DEVICE_ID } from "./auth.js";
|
||||
import { DaemonError, toErrorPayload } from "./errors.js";
|
||||
import { CommandRouter } from "./router.js";
|
||||
import { createSseHandler } from "./sse.js";
|
||||
@@ -68,7 +68,16 @@ function json(status: number, body: unknown, headers: Record<string, string> = {
|
||||
});
|
||||
}
|
||||
|
||||
async function readJsonBody(c: Context<Env>, maxBytes: number): Promise<Record<string, unknown>> {
|
||||
interface ReadJsonOptions {
|
||||
/** An absent body is `{}` (used by `console/session`, whose body is optional). */
|
||||
optional?: boolean;
|
||||
}
|
||||
|
||||
async function readJsonBody(
|
||||
c: Context<Env>,
|
||||
maxBytes: number,
|
||||
options: ReadJsonOptions = {},
|
||||
): Promise<Record<string, unknown>> {
|
||||
const declared = c.req.header("content-length");
|
||||
if (declared !== undefined) {
|
||||
const length = Number(declared);
|
||||
@@ -80,7 +89,10 @@ async function readJsonBody(c: Context<Env>, maxBytes: number): Promise<Record<s
|
||||
if (Buffer.byteLength(text, "utf8") > maxBytes) {
|
||||
throw DaemonError.payloadTooLarge(`body exceeds ${maxBytes} bytes`);
|
||||
}
|
||||
if (text.trim() === "") throw DaemonError.badRequest("request body is required");
|
||||
if (text.trim() === "") {
|
||||
if (options.optional === true) return {};
|
||||
throw DaemonError.badRequest("request body is required");
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
@@ -176,9 +188,32 @@ export function createApp(deps: AppDeps): Hono<Env> {
|
||||
port: config.port,
|
||||
capabilities: ["ws", "sse", "devices", "attention"],
|
||||
limits: config.limits,
|
||||
access: config.access,
|
||||
publicUrl: config.publicUrl,
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* Local-browser login handshake: loopback + the local CLI token only.
|
||||
* The token in the returned URL lives in the fragment (`#t=`), so it never
|
||||
* reaches an HTTP request line, a `Referer` header or a proxy access log.
|
||||
*/
|
||||
app.post("/api/v1/console/session", async (c) => {
|
||||
// Remote clients pair instead; refuse before touching the device store.
|
||||
if (!isLoopback(c)) return json(403, errorBody(ERROR_CODES.FORBIDDEN, "console login is loopback-only"));
|
||||
const callerToken = bearer(c);
|
||||
const caller = callerToken === undefined ? null : auth.verifyToken(callerToken);
|
||||
if (caller === null || caller.id !== LOCAL_CLI_DEVICE_ID) {
|
||||
return json(401, errorBody(ERROR_CODES.UNAUTHORIZED, "console login requires the local CLI token"));
|
||||
}
|
||||
await readJsonBody(c, config.limits.maxBodyBytes, { optional: true });
|
||||
const session = auth.localBrowserSession();
|
||||
// Always loopback and the *actual* bound port (`config.port` already
|
||||
// reflects retries/ephemeral ports), even when the daemon binds 0.0.0.0.
|
||||
const url = `http://127.0.0.1:${config.port}/#t=${encodeURIComponent(session.token)}`;
|
||||
return c.json({ token: session.token, device: session.device, url });
|
||||
});
|
||||
|
||||
const health = (c: Context<Env>) => {
|
||||
const instanceStates = instances.list();
|
||||
const degraded = instanceStates.filter((instance) => instance.status === "degraded");
|
||||
|
||||
@@ -278,8 +278,21 @@ export interface WorkspaceInfo {
|
||||
liveCount: number;
|
||||
lastActiveAt: number | null;
|
||||
instance: InstanceState | null;
|
||||
/**
|
||||
* Derived, non-persisted noise classification (see docs/protocol.md).
|
||||
* `secondary` rows are still served and addressable — a client decides
|
||||
* whether to list them behind a "show hidden" toggle. Older daemons omit
|
||||
* the field; treat a missing value as `default`.
|
||||
*/
|
||||
visibility?: WorkspaceVisibility;
|
||||
/** Why a row is `secondary`; absent for `default` rows. */
|
||||
visibilityReason?: WorkspaceVisibilityReason;
|
||||
}
|
||||
|
||||
export type WorkspaceVisibility = "default" | "secondary";
|
||||
|
||||
export type WorkspaceVisibilityReason = "hidden" | "ghost" | "temp" | "outside-roots" | "stale";
|
||||
|
||||
export type DaemonCommandMethod =
|
||||
| "instance.ensure"
|
||||
| "instance.shutdown"
|
||||
|
||||
+183
-14
@@ -2,8 +2,12 @@
|
||||
* WorkspaceStore: merges the durable registry, disk discovery and live
|
||||
* instance state into the `WorkspaceInfo` shape served by the daemon.
|
||||
*
|
||||
* Ordering and hiding are intentionally left to the UI; `list()` returns every
|
||||
* known workspace (including `hidden` ones) with stable registry-first order.
|
||||
* `list()` returns every known workspace (including `hidden` ones) with stable
|
||||
* registry-first order: rows are never filtered, so `/workspace/<id>` deep
|
||||
* links keep resolving. Instead every row carries a derived, non-persisted
|
||||
* `visibility` (`default` | `secondary`) + `visibilityReason` that the UI uses
|
||||
* to collapse workspace noise (ghosts, temp dirs, …) into a "show hidden"
|
||||
* section. Ordering and presentation stay with the UI.
|
||||
*/
|
||||
|
||||
import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
||||
@@ -12,7 +16,12 @@ 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 { ERROR_CODES } from "../protocol/errors.js";
|
||||
import type { InstanceState, WorkspaceInfo } from "../protocol/types.js";
|
||||
import type {
|
||||
InstanceState,
|
||||
WorkspaceInfo,
|
||||
WorkspaceVisibility,
|
||||
WorkspaceVisibilityReason,
|
||||
} from "../protocol/types.js";
|
||||
import {
|
||||
createDiscovery,
|
||||
type DiscoveredWorkspace,
|
||||
@@ -28,6 +37,8 @@ import {
|
||||
type WorkspacePatch,
|
||||
} from "./registry.js";
|
||||
|
||||
export type WorkspaceEnv = Record<string, string | undefined>;
|
||||
|
||||
export interface WorkspaceStoreOptions {
|
||||
/** Defaults to a discovery over `sessionsRoot()`. */
|
||||
discovery?: Discovery;
|
||||
@@ -43,6 +54,13 @@ export interface WorkspaceStoreOptions {
|
||||
* anywhere the user already opened nvim.
|
||||
*/
|
||||
roots?: readonly string[];
|
||||
/**
|
||||
* Environment used for `PI2_WORKSPACE_*` (roots + visibility policy);
|
||||
* injectable so tests stay hermetic. Defaults to `process.env`.
|
||||
*/
|
||||
env?: WorkspaceEnv;
|
||||
/** Clock for the `PI2_WORKSPACE_STALE_DAYS` comparison; defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export interface WorkspaceStoreHandle extends WorkspaceStoreContract {
|
||||
@@ -62,9 +80,13 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
private readonly instances: Pick<InstanceManager, "list" | "instanceStates"> | undefined;
|
||||
private readonly logger: WorkspaceStoreOptions["logger"] | undefined;
|
||||
private readonly roots: readonly string[] | undefined;
|
||||
private readonly env: WorkspaceEnv;
|
||||
private readonly now: () => number;
|
||||
|
||||
constructor(options: WorkspaceStoreOptions = {}) {
|
||||
this.logger = options.logger;
|
||||
this.env = options.env ?? process.env;
|
||||
this.now = options.now ?? Date.now;
|
||||
this.discovery = options.discovery ?? createDiscovery({ ...(options.logger ? { logger: options.logger } : {}) });
|
||||
this.registry =
|
||||
options.registry ??
|
||||
@@ -157,15 +179,16 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
}
|
||||
|
||||
await this.registry.ensureForCwd(real);
|
||||
const patch: WorkspacePatch = {};
|
||||
// Explicitly reopen: `registry.update()` only touches the keys it is
|
||||
// given, so a previously hidden workspace would otherwise stay hidden
|
||||
// and vanish from the list after the user just asked to open it.
|
||||
const patch: WorkspacePatch = { hidden: false };
|
||||
if (input.alias !== undefined) {
|
||||
const alias = input.alias.trim();
|
||||
patch.alias = alias.length > 0 ? alias : null;
|
||||
}
|
||||
if (input.trust !== undefined) patch.trusted = input.trust;
|
||||
if (Object.keys(patch).length > 0) {
|
||||
await this.registry.update(workspaceIdForCwd(real), patch);
|
||||
}
|
||||
|
||||
return this.requireInfo(workspaceIdForCwd(real));
|
||||
}
|
||||
@@ -274,19 +297,40 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
): WorkspaceInfo {
|
||||
const cwd = entry?.cwd ?? discovered?.cwd ?? "";
|
||||
const alias = entry?.alias ?? null;
|
||||
const pinned = entry?.pinned ?? false;
|
||||
const hidden = entry?.hidden ?? false;
|
||||
const trusted = entry?.trusted ?? false;
|
||||
const exists = discovered?.exists ?? isDirectory(cwd);
|
||||
const lastActiveAt = discovered?.lastActiveAt ?? null;
|
||||
const liveCount = views.live.get(workspaceId) ?? 0;
|
||||
const instance = views.instances.get(workspaceId) ?? null;
|
||||
const classification = classifyWorkspace({
|
||||
cwd,
|
||||
hidden,
|
||||
pinned,
|
||||
trusted,
|
||||
exists,
|
||||
lastActiveAt,
|
||||
liveCount,
|
||||
instance,
|
||||
roots: this.allowlist(),
|
||||
env: this.env,
|
||||
now: this.now(),
|
||||
});
|
||||
return {
|
||||
workspaceId,
|
||||
cwd,
|
||||
name: alias ?? (basename(cwd) || cwd),
|
||||
alias,
|
||||
pinned: entry?.pinned ?? false,
|
||||
hidden: entry?.hidden ?? false,
|
||||
trusted: entry?.trusted ?? false,
|
||||
exists: discovered?.exists ?? isDirectory(cwd),
|
||||
pinned,
|
||||
hidden,
|
||||
trusted,
|
||||
exists,
|
||||
sessionCount: discovered?.sessionCount ?? 0,
|
||||
liveCount: views.live.get(workspaceId) ?? 0,
|
||||
lastActiveAt: discovered?.lastActiveAt ?? null,
|
||||
instance: views.instances.get(workspaceId) ?? null,
|
||||
liveCount,
|
||||
lastActiveAt,
|
||||
instance,
|
||||
...classification,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -326,7 +370,7 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
if (configured !== undefined) {
|
||||
return configured.map((root) => canonicalRoot(root)).filter((root): root is string => root.length > 0);
|
||||
}
|
||||
return rootsFromEnv(process.env.PI2_WORKSPACE_ROOTS);
|
||||
return rootsFromEnv(this.env.PI2_WORKSPACE_ROOTS);
|
||||
}
|
||||
|
||||
private assertAllowed(candidate: string, roots: readonly string[]): void {
|
||||
@@ -342,6 +386,131 @@ export function createWorkspaceStore(options: WorkspaceStoreOptions = {}): Works
|
||||
return new WorkspaceStore(options);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Workspace visibility policy (derived, never persisted) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
|
||||
const FALSE_VALUES = new Set(["0", "false", "no", "off"]);
|
||||
|
||||
/** Built-in temp roots, in addition to `$TMPDIR` when it is set and absolute. */
|
||||
const DEFAULT_TEMP_ROOTS: readonly string[] = ["/tmp", "/var/tmp", "/var/folders", "/private/var/folders"];
|
||||
|
||||
export interface ClassifyWorkspaceInput {
|
||||
cwd: string;
|
||||
hidden?: boolean | undefined;
|
||||
pinned?: boolean | undefined;
|
||||
trusted?: boolean | undefined;
|
||||
exists: boolean;
|
||||
lastActiveAt: number | null;
|
||||
/** Live instance for this workspace (`WorkspaceInfo.instance`). */
|
||||
instance?: InstanceState | null | undefined;
|
||||
/** Live sessions reported by the instance (`WorkspaceInfo.liveCount`). */
|
||||
liveCount?: number | undefined;
|
||||
/** Roots for the `outside-roots` rule; defaults to `PI2_WORKSPACE_ROOTS` / `$HOME`. */
|
||||
roots?: readonly string[] | undefined;
|
||||
/** Policy switches; defaults to `process.env`. */
|
||||
env?: WorkspaceEnv | undefined;
|
||||
/** Clock for `PI2_WORKSPACE_STALE_DAYS`; defaults to `Date.now()`. */
|
||||
now?: number | undefined;
|
||||
}
|
||||
|
||||
export interface WorkspaceClassification {
|
||||
visibility: WorkspaceVisibility;
|
||||
visibilityReason?: WorkspaceVisibilityReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the workspace-noise policy for one row. Pure and non-persisted so the
|
||||
* same inputs always produce the same classification. Precedence (first match
|
||||
* wins):
|
||||
*
|
||||
* 1. `hidden` → secondary/hidden (explicit intent)
|
||||
* 2. live instance, pinned or trusted → default (rescue)
|
||||
* 3. `PI2_WORKSPACE_HIDE_TEMP` (1) → secondary/temp
|
||||
* 4. `PI2_WORKSPACE_HIDE_GHOSTS` (1) → secondary/ghost
|
||||
* 5. `PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS` (0) → secondary/outside-roots
|
||||
* 6. `PI2_WORKSPACE_STALE_DAYS` (0=off) → secondary/stale
|
||||
* 7. otherwise → default
|
||||
*/
|
||||
export function classifyWorkspace(input: ClassifyWorkspaceInput): WorkspaceClassification {
|
||||
const env = input.env ?? process.env;
|
||||
const cwd = typeof input.cwd === "string" ? input.cwd : "";
|
||||
const real = cwd.length > 0 ? realpathSafe(cwd) : "";
|
||||
|
||||
if (input.hidden === true) return secondary("hidden");
|
||||
|
||||
const liveCount = typeof input.liveCount === "number" && Number.isFinite(input.liveCount) ? input.liveCount : 0;
|
||||
if (input.instance != null || liveCount > 0 || input.pinned === true || input.trusted === true) {
|
||||
return { visibility: "default" };
|
||||
}
|
||||
|
||||
if (parseBooleanEnv(env.PI2_WORKSPACE_HIDE_TEMP, true) && real !== "" && isTempPath(real, env)) {
|
||||
return secondary("temp");
|
||||
}
|
||||
|
||||
if (parseBooleanEnv(env.PI2_WORKSPACE_HIDE_GHOSTS, true) && input.exists === false) {
|
||||
return secondary("ghost");
|
||||
}
|
||||
|
||||
if (parseBooleanEnv(env.PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS, false)) {
|
||||
// Both sides canonicalised, mirroring the `add()` allowlist.
|
||||
const roots = (input.roots ?? rootsFromEnv(env.PI2_WORKSPACE_ROOTS)).map((root) => realpathSafe(root));
|
||||
if (real !== "" && !roots.some((root) => isWithin(root, real))) return secondary("outside-roots");
|
||||
}
|
||||
|
||||
const staleDays = parseNonNegativeInt(env.PI2_WORKSPACE_STALE_DAYS);
|
||||
if (staleDays > 0 && typeof input.lastActiveAt === "number" && Number.isFinite(input.lastActiveAt)) {
|
||||
const now = typeof input.now === "number" && Number.isFinite(input.now) ? input.now : Date.now();
|
||||
if (now - input.lastActiveAt > staleDays * DAY_MS) return secondary("stale");
|
||||
}
|
||||
|
||||
return { visibility: "default" };
|
||||
}
|
||||
|
||||
/** `1/true/yes/on` enable, `0/false/no/off` disable, anything else → `fallback`. Never throws. */
|
||||
export function parseBooleanEnv(raw: string | undefined, fallback: boolean): boolean {
|
||||
if (typeof raw !== "string") return fallback;
|
||||
const value = raw.trim().toLowerCase();
|
||||
if (TRUE_VALUES.has(value)) return true;
|
||||
if (FALSE_VALUES.has(value)) return false;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Non-negative integer days, or `0` (policy disabled) for garbage. Never throws. */
|
||||
export function parseNonNegativeInt(raw: string | undefined): number {
|
||||
if (typeof raw !== "string") return 0;
|
||||
const value = raw.trim();
|
||||
if (!/^\d+$/.test(value)) return 0;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : 0;
|
||||
}
|
||||
|
||||
/** `$TMPDIR` (when set) plus the platform defaults, realpath'd and deduped. */
|
||||
export function tempRoots(env: WorkspaceEnv = process.env): string[] {
|
||||
const candidates = [env.TMPDIR, ...DEFAULT_TEMP_ROOTS];
|
||||
const roots: string[] = [];
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate !== "string") continue;
|
||||
const value = candidate.trim();
|
||||
if (value.length === 0 || !isAbsolute(value)) continue;
|
||||
roots.push(realpathSafe(value));
|
||||
}
|
||||
return [...new Set(roots)];
|
||||
}
|
||||
|
||||
/** True for a temp root itself or any path below one (both sides realpath'd). */
|
||||
export function isTempPath(cwd: string, env: WorkspaceEnv = process.env): boolean {
|
||||
if (typeof cwd !== "string" || cwd.length === 0) return false;
|
||||
const real = realpathSafe(cwd);
|
||||
return tempRoots(env).some((root) => isWithin(root, real));
|
||||
}
|
||||
|
||||
function secondary(reason: WorkspaceVisibilityReason): WorkspaceClassification {
|
||||
return { visibility: "secondary", visibilityReason: reason };
|
||||
}
|
||||
|
||||
export function rootsFromEnv(raw: string | undefined, fallback: string = homedir()): string[] {
|
||||
const parts = (raw ?? "")
|
||||
.split(",")
|
||||
|
||||
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
checkAccess,
|
||||
checkCliToken,
|
||||
checkCurl,
|
||||
checkLinger,
|
||||
checkNvim,
|
||||
checkNode,
|
||||
@@ -10,6 +12,7 @@ import {
|
||||
collectContext,
|
||||
defaultProbes,
|
||||
formatReport,
|
||||
parseCurlVersion,
|
||||
parseNvimVersion,
|
||||
parseVersion,
|
||||
reportToJson,
|
||||
@@ -25,12 +28,18 @@ function context(overrides: Partial<DoctorContext> = {}): DoctorContext {
|
||||
nodeVersion: "v22.11.0",
|
||||
nvim: { found: true, path: "/usr/bin/nvim", version: "v0.10.2" },
|
||||
pi: { found: true, path: "/usr/local/bin/pi", version: "1.8.0" },
|
||||
curl: {
|
||||
found: true,
|
||||
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 },
|
||||
runtime: { path: "/run/user/1000/pi2", exists: true, mode: 0o700 },
|
||||
cliToken: { path: "/run/user/1000/pi2/cli.token", exists: true, mode: 0o600 },
|
||||
socket: { path: "/run/user/1000/pi2/d.sock", exists: true },
|
||||
daemon: { reachable: true, port: 7676, protocolVersion: 1 },
|
||||
port: { configured: 7676, bound: true },
|
||||
access: { mode: "local", host: "127.0.0.1", port: 7676, publicUrl: null },
|
||||
serviceManager: { name: "systemd", available: true },
|
||||
linger: { checked: true, enabled: true },
|
||||
webDist: { path: "/repo/web/dist", exists: true },
|
||||
@@ -54,12 +63,14 @@ describe("doctor checks (all passing)", () => {
|
||||
"node",
|
||||
"nvim",
|
||||
"pi",
|
||||
"curl",
|
||||
"plugin",
|
||||
"runtime-dir",
|
||||
"cli-token",
|
||||
"socket",
|
||||
"daemon",
|
||||
"port",
|
||||
"access",
|
||||
"service-manager",
|
||||
"linger",
|
||||
"web-dist",
|
||||
@@ -80,6 +91,108 @@ describe("doctor checks (all passing)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor access check", () => {
|
||||
it("is ok for local mode", () => {
|
||||
const check = checkAccess({ mode: "local", host: "127.0.0.1", port: 7676, publicUrl: null });
|
||||
expect(check).toEqual({ name: "access", status: "ok", detail: "local (loopback only)" });
|
||||
});
|
||||
|
||||
it("warns for lan/tailscale with a TLS-terminated public URL", () => {
|
||||
const lan = checkAccess({ mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: "https://host.ts.net" });
|
||||
expect(lan.status).toBe("warn");
|
||||
expect(lan.detail).toBe("lan (bind 0.0.0.0/7676, public https://host.ts.net)");
|
||||
expect(lan.detail).not.toContain("no TLS");
|
||||
|
||||
const tailscale = checkAccess({ mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: "https://host.ts.net" });
|
||||
expect(tailscale.status).toBe("warn");
|
||||
expect(tailscale.detail).toBe("tailscale (bind 127.0.0.1/7676, public https://host.ts.net)");
|
||||
});
|
||||
|
||||
it("adds the no-TLS hint when the public URL is missing or plain http", () => {
|
||||
const loopback = checkAccess({ mode: "lan", host: "127.0.0.1", port: 7676, publicUrl: null });
|
||||
expect(loopback.status).toBe("warn");
|
||||
expect(loopback.detail).toContain("lan (bind 127.0.0.1/7676)");
|
||||
expect(loopback.detail).toContain("no TLS, prefer `tailscale serve`");
|
||||
|
||||
const plain = checkAccess({ mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: "http://host.ts.net" });
|
||||
expect(plain.status).toBe("warn");
|
||||
expect(plain.detail).toContain("no TLS, prefer `tailscale serve`");
|
||||
});
|
||||
|
||||
it("fails when a non-loopback bind has no public URL", () => {
|
||||
const check = checkAccess({ mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: null });
|
||||
expect(check).toEqual({ name: "access", status: "fail", detail: "lan (bind 0.0.0.0/7676)" });
|
||||
|
||||
const tailscale = checkAccess({ mode: "tailscale", host: "100.64.0.1", port: 7676, publicUrl: null });
|
||||
expect(tailscale.status).toBe("fail");
|
||||
});
|
||||
|
||||
it("is wired into the default probe list after port", async () => {
|
||||
const report = await checks({ access: { mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: null } });
|
||||
const names = report.checks.map((check) => check.name);
|
||||
expect(names.indexOf("access")).toBe(names.indexOf("port") + 1);
|
||||
expect(statusOf(report, "access")).toBe("warn");
|
||||
// A warn keeps the overall report ok.
|
||||
expect(report.ok).toBe(true);
|
||||
|
||||
const failed = await checks({ access: { mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: null } });
|
||||
expect(statusOf(failed, "access")).toBe("fail");
|
||||
expect(failed.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor curl check", () => {
|
||||
it("is ok and reports the parsed version with its path", () => {
|
||||
const check = checkCurl({ found: true, path: "/usr/bin/curl", version: "curl 8.7.1 (x86_64-pc-linux-gnu) libcurl/8.7.1" });
|
||||
expect(check).toEqual({ name: "curl", status: "ok", detail: "8.7.1 (/usr/bin/curl)" });
|
||||
});
|
||||
|
||||
it("warns with an actionable hint when curl is missing", async () => {
|
||||
const check = checkCurl({ found: false, error: "curl not found on PATH" });
|
||||
expect(check).toEqual({
|
||||
name: "curl",
|
||||
status: "warn",
|
||||
detail: "not found on PATH (:PiWeb cannot sign the browser in automatically; pair instead)",
|
||||
});
|
||||
expect(check.detail).toContain("pair instead");
|
||||
|
||||
const report = await checks({ curl: { found: false } });
|
||||
expect(statusOf(report, "curl")).toBe("warn");
|
||||
// A warn keeps the overall report ok.
|
||||
expect(report.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("warns when the version cannot be parsed", () => {
|
||||
expect(checkCurl({ found: true, path: "/usr/bin/curl", version: "garbage" })).toEqual({
|
||||
name: "curl",
|
||||
status: "warn",
|
||||
detail: "could not parse version of /usr/bin/curl",
|
||||
});
|
||||
expect(checkCurl({ found: true, path: "/usr/bin/curl" }).status).toBe("warn");
|
||||
expect(parseCurlVersion("curl 8.7.1 (x86_64-pc-linux-gnu) libcurl/8.7.1")).toBe("8.7.1");
|
||||
expect(parseCurlVersion("garbage")).toBeUndefined();
|
||||
expect(parseCurlVersion(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("is wired into the report right after pi, in the table and in --json", async () => {
|
||||
const report = await checks();
|
||||
const names = report.checks.map((check) => check.name);
|
||||
expect(names.indexOf("curl")).toBe(names.indexOf("pi") + 1);
|
||||
expect(names.indexOf("plugin")).toBe(names.indexOf("curl") + 1);
|
||||
expect(report.checks.find((check) => check.name === "curl")).toEqual({
|
||||
name: "curl",
|
||||
status: "ok",
|
||||
detail: "8.7.1 (/usr/bin/curl)",
|
||||
});
|
||||
expect(formatReport(report)).toMatch(/ok\s+curl\s+8\.7\.1 \(\/usr\/bin\/curl\)/);
|
||||
|
||||
const parsed = JSON.parse(reportToJson(report)) as { ok: boolean; checks: { name: string; status: string; detail: string }[] };
|
||||
expect(parsed.ok).toBe(true);
|
||||
expect(parsed.checks.map((check) => check.name).indexOf("curl")).toBe(names.indexOf("pi") + 1);
|
||||
expect(parsed.checks.find((check) => check.name === "curl")?.detail).toBe("8.7.1 (/usr/bin/curl)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor failure cases", () => {
|
||||
it("fails on node < 22", async () => {
|
||||
const report = await checks({ nodeVersion: "v20.11.0" });
|
||||
@@ -248,6 +361,9 @@ describe("collectContext", () => {
|
||||
run: async (command, args) => {
|
||||
if (command === "nvim") return { ok: true, stdout: "NVIM v0.10.2\nBuild type: Release\n", stderr: "" };
|
||||
if (command === "pi") return { ok: true, stdout: "1.8.0\n", stderr: "" };
|
||||
if (command === "curl") {
|
||||
return { ok: true, stdout: "curl 8.7.1 (x86_64-pc-linux-gnu) libcurl/8.7.1\nRelease-Date: 2024-03-27\n", stderr: "" };
|
||||
}
|
||||
if (command === "loginctl" && args[1] === "1000") return { ok: true, stdout: "Linger=yes\n", stderr: "" };
|
||||
return { ok: false, stdout: "", stderr: "unexpected" };
|
||||
},
|
||||
@@ -256,12 +372,14 @@ describe("collectContext", () => {
|
||||
|
||||
expect(ctx.nvim).toEqual({ found: true, path: "/usr/bin/nvim", version: "v0.10.2" });
|
||||
expect(ctx.pi.version).toBe("1.8.0");
|
||||
expect(ctx.curl).toEqual({ found: true, path: "/usr/bin/curl", version: "curl 8.7.1 (x86_64-pc-linux-gnu) libcurl/8.7.1" });
|
||||
expect(ctx.plugin.bridgeFound).toBe(true);
|
||||
expect(ctx.runtime.exists).toBe(true);
|
||||
expect(ctx.cliToken.mode).toBe(0o600);
|
||||
expect(ctx.socket.exists).toBe(true);
|
||||
expect(ctx.daemon).toEqual({ reachable: true, port: 7712, protocolVersion: 1 });
|
||||
expect(ctx.port).toEqual({ configured: 7712, bound: true });
|
||||
expect(ctx.access).toEqual({ mode: "local", host: "127.0.0.1", port: 7712, publicUrl: null });
|
||||
expect(ctx.serviceManager).toEqual({ name: "systemd", available: true });
|
||||
expect(ctx.linger).toMatchObject({ checked: true, enabled: true });
|
||||
expect(ctx.webDist.path).toBe(join(dir, "web"));
|
||||
|
||||
@@ -28,6 +28,8 @@ export function testConfig(overrides: Partial<Config> = {}): Config {
|
||||
limits: TEST_LIMITS,
|
||||
tokenPath: "/tmp/pi2-daemon-cli-test.sock.token",
|
||||
deviceStorePath: "/tmp/pi2-daemon-cli-test-devices.json",
|
||||
access: "local",
|
||||
publicUrl: null,
|
||||
};
|
||||
return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } };
|
||||
}
|
||||
|
||||
@@ -183,6 +183,36 @@ describe("daemon.json", () => {
|
||||
handle.release();
|
||||
});
|
||||
|
||||
it("carries the optional access/publicUrl fields and stays readable without them", () => {
|
||||
const handle = acquireLock({
|
||||
lockPath,
|
||||
payload: {
|
||||
port: 7676,
|
||||
daemonId: "d-access",
|
||||
startedAt: 5,
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
access: "tailscale",
|
||||
publicUrl: "https://host.ts.net",
|
||||
},
|
||||
bootId: () => BOOT,
|
||||
});
|
||||
expect(readLockFile(lockPath)?.access).toBe("tailscale");
|
||||
expect(readLockFile(lockPath)?.publicUrl).toBe("https://host.ts.net");
|
||||
handle.release();
|
||||
|
||||
// A legacy payload (no new fields) still parses.
|
||||
const legacy = { ...payload(), pid: process.pid, bootId: BOOT };
|
||||
writeFileSync(lockPath, `${JSON.stringify(legacy)}\n`);
|
||||
expect(readLockFile(lockPath)?.access).toBeUndefined();
|
||||
expect(readLockFile(lockPath)?.publicUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
it("refuses a malformed access field", () => {
|
||||
const legacy = { ...payload(), pid: process.pid, bootId: BOOT, access: "public" };
|
||||
writeFileSync(lockPath, `${JSON.stringify(legacy)}\n`);
|
||||
expect(readLockFile(lockPath)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("is removed by release() and missing files read as undefined", () => {
|
||||
const handle = acquireLock({
|
||||
lockPath,
|
||||
|
||||
+105
-1
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { mkdirSync, realpathSync, writeFileSync } from "node:fs";
|
||||
import { basename, join } from "node:path";
|
||||
import type { DaemonClient } from "../../src/cli/pi2.js";
|
||||
import { CliError, createClient, main, resolveEndpoint, runAttach, runDoctorCommand, runPairing, runStatus } from "../../src/cli/pi2.js";
|
||||
import { CliError, createClient, main, resolveEndpoint, runAttach, runDoctorCommand, runOpen, runPairing, runStatus } from "../../src/cli/pi2.js";
|
||||
import { writeDaemonJson, type DaemonLock } from "../../src/cli/lock.js";
|
||||
import { writeCliToken } from "../../src/cli/token.js";
|
||||
import type { WorkspaceInfo } from "../../src/protocol/types.js";
|
||||
@@ -54,6 +54,7 @@ interface FakeData {
|
||||
resources?: Record<string, unknown>;
|
||||
health?: Record<string, unknown>;
|
||||
pair?: Record<string, unknown>;
|
||||
session?: Record<string, unknown>;
|
||||
postError?: Error;
|
||||
}
|
||||
|
||||
@@ -96,6 +97,9 @@ function fakeClient(data: FakeData = {}): DaemonClient & { calls: string[] } {
|
||||
if (path === "/api/v1/pair") {
|
||||
return { status: 202, body: data.pair ?? { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } };
|
||||
}
|
||||
if (path === "/api/v1/console/session") {
|
||||
return { status: 200, body: data.session ?? { token: "browser-token", url: "http://127.0.0.1:7712/#t=browser-token" } };
|
||||
}
|
||||
throw new CliError(`unexpected POST ${path}`);
|
||||
},
|
||||
};
|
||||
@@ -353,6 +357,106 @@ describe("pi2 pairing", () => {
|
||||
runPairing({ client: fakeClient({ postError: new CliError("pair failed: E_UNAUTHORIZED") }) }),
|
||||
).rejects.toThrowError(/E_UNAUTHORIZED/);
|
||||
});
|
||||
|
||||
it("rebuilds the URL on --public-url when given", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
|
||||
await runPairing({ client, print: (line) => lines.push(line), publicUrl: "https://myhost.tail1234.ts.net/" });
|
||||
const text = lines.join("\n");
|
||||
expect(text).toContain("url https://myhost.tail1234.ts.net/pair/ABCD2345");
|
||||
expect(text).toContain('"url":"https://myhost.tail1234.ts.net/pair/ABCD2345"');
|
||||
expect(text).toContain("code ABCD2345");
|
||||
});
|
||||
|
||||
it("defaults --public-url to daemon.json's publicUrl", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
|
||||
await main(["pairing"], {
|
||||
out: (line) => lines.push(line),
|
||||
client: () => ({ ...client, daemon: { ...DAEMON, publicUrl: "https://from-daemon.ts.net" } }),
|
||||
});
|
||||
expect(lines.join("\n")).toContain("url https://from-daemon.ts.net/pair/ABCD2345");
|
||||
});
|
||||
|
||||
it("keeps the loopback URL without flags", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
|
||||
await main(["pairing"], { out: (line) => lines.push(line), client: () => client });
|
||||
expect(lines.join("\n")).toContain("url http://127.0.0.1:7712/pair/ABCD2345");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pi2 open", () => {
|
||||
it("--print posts the console session and prints only the URL", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({
|
||||
session: { token: "tok", url: "http://127.0.0.1:7712/#t=tok" },
|
||||
});
|
||||
const code = await runOpen({ client, print: (line) => lines.push(line), printOnly: true });
|
||||
expect(code).toBe(0);
|
||||
expect(lines).toEqual(["http://127.0.0.1:7712/#t=tok"]);
|
||||
expect(client.calls).toEqual(["/api/v1/console/session {}"]);
|
||||
});
|
||||
|
||||
it("--print implies --no-browser (never launches an opener)", async () => {
|
||||
const lines: string[] = [];
|
||||
const opens: string[] = [];
|
||||
const code = await runOpen({
|
||||
client: fakeClient({ session: { url: "http://127.0.0.1:7712/#t=tok" } }),
|
||||
print: (line) => lines.push(line),
|
||||
printOnly: true,
|
||||
openUrl: (url) => opens.push(url),
|
||||
});
|
||||
expect(code).toBe(0);
|
||||
expect(opens).toEqual([]);
|
||||
expect(lines).toEqual(["http://127.0.0.1:7712/#t=tok"]);
|
||||
});
|
||||
|
||||
it("launches the opener with the URL", async () => {
|
||||
const opens: string[] = [];
|
||||
const lines: string[] = [];
|
||||
const code = await runOpen({
|
||||
client: fakeClient({ session: { url: "http://127.0.0.1:7712/#t=tok" } }),
|
||||
print: (line) => lines.push(line),
|
||||
openUrl: (url) => opens.push(url),
|
||||
});
|
||||
expect(code).toBe(0);
|
||||
expect(opens).toEqual(["http://127.0.0.1:7712/#t=tok"]);
|
||||
expect(lines).toEqual([]);
|
||||
});
|
||||
|
||||
it("prints the URL and still exits 0 when the opener fails", async () => {
|
||||
const lines: string[] = [];
|
||||
const code = await runOpen({
|
||||
client: fakeClient({ session: { url: "http://127.0.0.1:7712/#t=tok" } }),
|
||||
print: (line) => lines.push(line),
|
||||
openUrl: (_url, onError) => onError(),
|
||||
});
|
||||
expect(code).toBe(0);
|
||||
expect(lines).toEqual(["http://127.0.0.1:7712/#t=tok"]);
|
||||
});
|
||||
|
||||
it("routes `pi2 open --print` through main", async () => {
|
||||
const out: string[] = [];
|
||||
const code = await main(["open", "--print"], {
|
||||
out: (line) => out.push(line),
|
||||
client: () => fakeClient({ session: { url: "http://127.0.0.1:7712/#t=tok" } }),
|
||||
});
|
||||
expect(code).toBe(0);
|
||||
expect(out).toEqual(["http://127.0.0.1:7712/#t=tok"]);
|
||||
});
|
||||
|
||||
it("exits 1 with the daemon-resolution message when no daemon runs", async () => {
|
||||
const err: string[] = [];
|
||||
const code = await main(["open", "--print"], {
|
||||
err: (line) => err.push(line),
|
||||
client: () => {
|
||||
throw new CliError("no running pi2 daemon (…/daemon.json missing). Start it with `pi2 daemon`.");
|
||||
},
|
||||
});
|
||||
expect(code).toBe(1);
|
||||
expect(err[0]).toContain("no running pi2 daemon");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pi2 doctor (daemon probe wiring)", () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync, unlinkSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AuthStore, hashToken, isAllowedOrigin, timingSafeEqualHex } from "../../src/daemon/auth.js";
|
||||
@@ -127,6 +127,89 @@ describe("auth device store", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("local browser session", () => {
|
||||
let dir: string;
|
||||
let path: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "pi2-auth-browser-"));
|
||||
path = join(dir, "devices.json");
|
||||
});
|
||||
|
||||
afterEach(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
it("creates exactly one local-browser device with every scope", () => {
|
||||
const auth = new AuthStore({ path, now: () => 1_000 });
|
||||
const session = auth.localBrowserSession();
|
||||
|
||||
expect(session.device.name).toBe("local browser");
|
||||
expect(session.device.kind).toBe("laptop");
|
||||
expect(session.device.scopes).toEqual(["read", "steer", "control", "admin"]);
|
||||
expect(session.device.createdAt).toBe(1_000);
|
||||
expect(session.device.lastSeenAt).toBe(1_000);
|
||||
expect(session.device.revokedAt).toBeNull();
|
||||
expect(auth.listDevices()).toHaveLength(1);
|
||||
expect(auth.verifyToken(session.token)?.id).toBe(session.device.id);
|
||||
});
|
||||
|
||||
it("reuses the same token across logins, so a second :PiWeb keeps the open tab alive", () => {
|
||||
const auth = new AuthStore({ path, now: () => 2_000 });
|
||||
const first = auth.localBrowserSession();
|
||||
const second = auth.localBrowserSession();
|
||||
|
||||
expect(second.token).toBe(first.token);
|
||||
expect(second.device.id).toBe(first.device.id);
|
||||
expect(auth.verifyToken(first.token)?.id).toBe(first.device.id);
|
||||
expect(auth.listDevices()).toHaveLength(1);
|
||||
|
||||
const persisted = JSON.parse(readFileSync(path, "utf8")) as {
|
||||
devices: { tokenHash: string; name: string }[];
|
||||
};
|
||||
expect(persisted.devices).toHaveLength(1);
|
||||
expect(persisted.devices[0]!.tokenHash).toBe(hashToken(first.token));
|
||||
|
||||
const tokenPath = join(dir, "local-browser.token");
|
||||
expect(readFileSync(tokenPath, "utf8").trim()).toBe(first.token);
|
||||
expect(statSync(tokenPath).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it("mints a new token once the device is revoked", () => {
|
||||
const auth = new AuthStore({ path, now: () => 3_000 });
|
||||
const first = auth.localBrowserSession();
|
||||
expect(auth.revokeDevice(first.device.id)).toBe(true);
|
||||
expect(auth.verifyToken(first.token)).toBeNull();
|
||||
|
||||
const second = auth.localBrowserSession();
|
||||
expect(second.device.id).toBe(first.device.id);
|
||||
expect(second.device.revokedAt).toBeNull();
|
||||
expect(second.token).not.toBe(first.token);
|
||||
expect(auth.verifyToken(first.token)).toBeNull();
|
||||
expect(auth.verifyToken(second.token)?.revokedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("mints a new token when the stored plaintext is missing or stale", () => {
|
||||
const auth = new AuthStore({ path, now: () => 4_000 });
|
||||
const first = auth.localBrowserSession();
|
||||
|
||||
unlinkSync(join(dir, "local-browser.token"));
|
||||
const second = auth.localBrowserSession();
|
||||
expect(second.token).not.toBe(first.token);
|
||||
expect(auth.verifyToken(second.token)?.id).toBe(first.device.id);
|
||||
expect(auth.listDevices()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("survives a store reload with the same token", () => {
|
||||
const first = new AuthStore({ path });
|
||||
const session = first.localBrowserSession();
|
||||
const reloaded = new AuthStore({ path });
|
||||
expect(reloaded.verifyToken(session.token)?.name).toBe("local browser");
|
||||
const again = reloaded.localBrowserSession();
|
||||
expect(again.token).toBe(session.token);
|
||||
expect(again.device.id).toBe(session.device.id);
|
||||
expect(reloaded.listDevices()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isAllowedOrigin", () => {
|
||||
const allow = ["http://127.0.0.1:7676", "http://localhost:7676"];
|
||||
|
||||
|
||||
@@ -5,13 +5,21 @@ import { loadConfig } from "../../src/config.js";
|
||||
|
||||
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
||||
|
||||
const LOOPBACK = (port: number): string[] => [
|
||||
`http://127.0.0.1:${port}`,
|
||||
`http://localhost:${port}`,
|
||||
`http://[::1]:${port}`,
|
||||
];
|
||||
|
||||
describe("loadConfig", () => {
|
||||
it("uses protocol defaults", () => {
|
||||
it("uses protocol defaults (access mode local)", () => {
|
||||
const config = loadConfig({});
|
||||
expect(config.host).toBe("127.0.0.1");
|
||||
expect(config.port).toBe(7676);
|
||||
expect(config.access).toBe("local");
|
||||
expect(config.publicUrl).toBeNull();
|
||||
expect(config.staticDir).toBe(join(repoRoot, "web", "dist"));
|
||||
expect(config.corsOrigins).toEqual(["http://127.0.0.1:7676", "http://localhost:7676"]);
|
||||
expect(config.corsOrigins).toEqual(LOOPBACK(7676));
|
||||
expect(config.limits.maxBodyBytes).toBe(8 * 1024 * 1024);
|
||||
expect(config.limits.maxFrameBytes).toBe(8 * 1024 * 1024);
|
||||
expect(config.limits.maxConnections).toBe(64);
|
||||
@@ -19,7 +27,7 @@ describe("loadConfig", () => {
|
||||
expect(config.deviceStorePath).toMatch(/devices\.json$/);
|
||||
});
|
||||
|
||||
it("honours environment overrides", () => {
|
||||
it("honours environment overrides; PI2_ORIGINS is additive", () => {
|
||||
const config = loadConfig({
|
||||
PI2_PORT: "0",
|
||||
PI2_HOST: "0.0.0.0",
|
||||
@@ -29,7 +37,9 @@ describe("loadConfig", () => {
|
||||
expect(config.port).toBe(0);
|
||||
expect(config.host).toBe("0.0.0.0");
|
||||
expect(config.staticDir).toBe("/srv/pi2/web");
|
||||
expect(config.corsOrigins).toEqual(["http://a.test", "http://b.test"]);
|
||||
// Loopback origins stay in place; the extras are appended, normalized,
|
||||
// and empty entries dropped.
|
||||
expect(config.corsOrigins).toEqual([...LOOPBACK(0), "http://a.test", "http://b.test"]);
|
||||
});
|
||||
|
||||
it("rejects invalid ports", () => {
|
||||
@@ -38,8 +48,80 @@ describe("loadConfig", () => {
|
||||
expect(() => loadConfig({ PI2_PORT: "70000" })).toThrow(/PI2_PORT/);
|
||||
});
|
||||
|
||||
it("derives default origins from the port", () => {
|
||||
it("derives loopback origins from the port", () => {
|
||||
const config = loadConfig({ PI2_PORT: "8080" });
|
||||
expect(config.corsOrigins).toEqual(["http://127.0.0.1:8080", "http://localhost:8080"]);
|
||||
expect(config.corsOrigins).toEqual(LOOPBACK(8080));
|
||||
});
|
||||
|
||||
it("derives local mode origins without a LAN address", () => {
|
||||
const config = loadConfig(
|
||||
{ PI2_ACCESS_MODE: "local" },
|
||||
{ detectLanIp: () => "192.168.2.10" },
|
||||
);
|
||||
expect(config.access).toBe("local");
|
||||
expect(config.host).toBe("127.0.0.1");
|
||||
expect(config.corsOrigins).toEqual(LOOPBACK(7676));
|
||||
});
|
||||
|
||||
it("lan mode binds 0.0.0.0 and adds the detected LAN origin", () => {
|
||||
const config = loadConfig(
|
||||
{ PI2_ACCESS_MODE: "lan" },
|
||||
{ detectLanIp: () => "192.168.2.10" },
|
||||
);
|
||||
expect(config.access).toBe("lan");
|
||||
expect(config.host).toBe("0.0.0.0");
|
||||
expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "http://192.168.2.10:7676"]);
|
||||
});
|
||||
|
||||
it("lan mode skips the extra origin when detection fails or throws", () => {
|
||||
expect(
|
||||
loadConfig({ PI2_ACCESS_MODE: "lan" }, { detectLanIp: () => null }).corsOrigins,
|
||||
).toEqual(LOOPBACK(7676));
|
||||
expect(
|
||||
loadConfig(
|
||||
{ PI2_ACCESS_MODE: "lan" },
|
||||
{
|
||||
detectLanIp: () => {
|
||||
throw new Error("no interfaces");
|
||||
},
|
||||
},
|
||||
).corsOrigins,
|
||||
).toEqual(LOOPBACK(7676));
|
||||
});
|
||||
|
||||
it("tailscale mode stays on loopback and adds the public URL origin", () => {
|
||||
const config = loadConfig({
|
||||
PI2_ACCESS_MODE: "tailscale",
|
||||
PI2_PUBLIC_URL: "https://myhost.tail1234.ts.net/",
|
||||
});
|
||||
expect(config.access).toBe("tailscale");
|
||||
expect(config.host).toBe("127.0.0.1");
|
||||
expect(config.publicUrl).toBe("https://myhost.tail1234.ts.net");
|
||||
expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "https://myhost.tail1234.ts.net"]);
|
||||
});
|
||||
|
||||
it("tailscale without PI2_PUBLIC_URL keeps only loopback origins", () => {
|
||||
const config = loadConfig({ PI2_ACCESS_MODE: "tailscale" });
|
||||
expect(config.publicUrl).toBeNull();
|
||||
expect(config.corsOrigins).toEqual(LOOPBACK(7676));
|
||||
});
|
||||
|
||||
it("lets PI2_HOST win over the mode default", () => {
|
||||
expect(loadConfig({ PI2_ACCESS_MODE: "lan", PI2_HOST: "127.0.0.1" }).host).toBe("127.0.0.1");
|
||||
expect(loadConfig({ PI2_ACCESS_MODE: "tailscale", PI2_HOST: "0.0.0.0" }).host).toBe("0.0.0.0");
|
||||
expect(loadConfig({ PI2_ACCESS_MODE: "local", PI2_HOST: "192.168.2.5" }).host).toBe("192.168.2.5");
|
||||
});
|
||||
|
||||
it("normalizes and de-duplicates explicit origins", () => {
|
||||
const config = loadConfig({
|
||||
PI2_ORIGINS: "https://a.test/, http://127.0.0.1:7676, ,http://a.test",
|
||||
});
|
||||
expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "https://a.test", "http://a.test"]);
|
||||
});
|
||||
|
||||
it("fails fast on an unknown access mode", () => {
|
||||
expect(() => loadConfig({ PI2_ACCESS_MODE: "public" })).toThrow(
|
||||
"PI2_ACCESS_MODE must be local, lan or tailscale",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AuthStore } from "../../src/daemon/auth.js";
|
||||
import { createApp } from "../../src/daemon/http.js";
|
||||
import type { Config } from "../../src/config.js";
|
||||
import { FakeBus, FakeInstanceManager, FakeWorkspaceStore } from "./fakes.js";
|
||||
import { createHarness, TEST_LIMITS, type Harness } from "./harness.js";
|
||||
|
||||
const CLI_TOKEN = "c".repeat(64);
|
||||
|
||||
interface SessionBody {
|
||||
token: string;
|
||||
device: {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
scopes: string[];
|
||||
createdAt: number;
|
||||
lastSeenAt: number;
|
||||
revokedAt: number | null;
|
||||
};
|
||||
url: string;
|
||||
}
|
||||
|
||||
/** Non-loopback requests only exist behind the socket; drive Hono directly. */
|
||||
async function appWithRemoteAddress(config: Config, auth: AuthStore, remoteAddress: string): Promise<Response> {
|
||||
const app = createApp({
|
||||
config,
|
||||
auth,
|
||||
instances: new FakeInstanceManager(),
|
||||
workspaces: new FakeWorkspaceStore(),
|
||||
bus: new FakeBus(),
|
||||
daemonId: "d-test",
|
||||
});
|
||||
return app.request(
|
||||
"/api/v1/console/session",
|
||||
{ method: "POST", headers: { authorization: `Bearer ${CLI_TOKEN}` } },
|
||||
{ incoming: { socket: { remoteAddress } } } as never,
|
||||
);
|
||||
}
|
||||
|
||||
describe("POST /api/v1/console/session", () => {
|
||||
let h: Harness;
|
||||
|
||||
afterEach(async () => {
|
||||
await h.cleanup();
|
||||
});
|
||||
|
||||
it("mints a loopback browser session for the local CLI token", async () => {
|
||||
h = await createHarness({ cliToken: CLI_TOKEN });
|
||||
|
||||
const res = await fetch(`${h.url}/api/v1/console/session`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${CLI_TOKEN}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as SessionBody;
|
||||
|
||||
expect(body.device.name).toBe("local browser");
|
||||
expect(body.device.kind).toBe("laptop");
|
||||
expect(body.device.scopes).toEqual(["read", "steer", "control", "admin"]);
|
||||
expect(body.token.length).toBeGreaterThanOrEqual(40);
|
||||
expect(body.url).toBe(`http://127.0.0.1:${h.server.port}/#t=${encodeURIComponent(body.token)}`);
|
||||
expect(body.url).not.toContain("?t=");
|
||||
expect(h.auth.verifyToken(body.token)?.id).toBe(body.device.id);
|
||||
// Exactly one device record, and no local-CLI record leaks into it.
|
||||
expect(h.auth.listDevices().map((device) => device.name)).toEqual(["local browser"]);
|
||||
});
|
||||
|
||||
it("accepts an absent body ({} is optional)", async () => {
|
||||
h = await createHarness({ cliToken: CLI_TOKEN });
|
||||
const res = await fetch(`${h.url}/api/v1/console/session`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${CLI_TOKEN}` },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("reuses one device and one token across calls, so reopening keeps the tab alive", async () => {
|
||||
h = await createHarness({ cliToken: CLI_TOKEN });
|
||||
const call = async (): Promise<SessionBody> => {
|
||||
const res = await fetch(`${h.url}/api/v1/console/session`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${CLI_TOKEN}` },
|
||||
});
|
||||
return (await res.json()) as SessionBody;
|
||||
};
|
||||
|
||||
const first = await call();
|
||||
const second = await call();
|
||||
expect(second.device.id).toBe(first.device.id);
|
||||
expect(second.token).toBe(first.token);
|
||||
expect(second.url).toBe(first.url);
|
||||
expect(h.auth.verifyToken(second.token)?.id).toBe(first.device.id);
|
||||
expect(h.auth.listDevices()).toHaveLength(1);
|
||||
expect(second.url).toContain(`#t=${encodeURIComponent(second.token)}`);
|
||||
});
|
||||
|
||||
it("mints a new token after the local browser is revoked", async () => {
|
||||
h = await createHarness({ cliToken: CLI_TOKEN });
|
||||
const call = async (): Promise<SessionBody> => {
|
||||
const res = await fetch(`${h.url}/api/v1/console/session`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${CLI_TOKEN}` },
|
||||
});
|
||||
return (await res.json()) as SessionBody;
|
||||
};
|
||||
|
||||
const first = await call();
|
||||
expect(h.auth.revokeDevice(first.device.id)).toBe(true);
|
||||
|
||||
const second = await call();
|
||||
expect(second.device.id).toBe(first.device.id);
|
||||
expect(second.token).not.toBe(first.token);
|
||||
expect(h.auth.verifyToken(first.token)).toBeNull();
|
||||
expect(h.auth.verifyToken(second.token)?.id).toBe(first.device.id);
|
||||
});
|
||||
|
||||
it("answers 401 without a token", async () => {
|
||||
h = await createHarness({ cliToken: CLI_TOKEN });
|
||||
const res = await fetch(`${h.url}/api/v1/console/session`, { method: "POST" });
|
||||
expect(res.status).toBe(401);
|
||||
expect(((await res.json()) as { code: string }).code).toBe("E_UNAUTHORIZED");
|
||||
});
|
||||
|
||||
it("answers 401 for a paired device token (the CLI token is required)", async () => {
|
||||
h = await createHarness({ cliToken: CLI_TOKEN });
|
||||
const deviceToken = h.createToken("paired phone");
|
||||
const res = await fetch(`${h.url}/api/v1/console/session`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${deviceToken}` },
|
||||
});
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("answers 403 from a non-loopback client", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "pi2-console-"));
|
||||
try {
|
||||
writeFileSync(join(dir, "cli.token"), `${CLI_TOKEN}\n`, { mode: 0o600 });
|
||||
const auth = new AuthStore({ path: join(dir, "devices.json"), localTokenPath: join(dir, "cli.token") });
|
||||
const config: Config = {
|
||||
host: "0.0.0.0",
|
||||
port: 7676,
|
||||
staticDir: join(dir, "web"),
|
||||
corsOrigins: [],
|
||||
limits: TEST_LIMITS,
|
||||
tokenPath: join(dir, "d.sock.token"),
|
||||
deviceStorePath: join(dir, "devices.json"),
|
||||
access: "lan",
|
||||
publicUrl: null,
|
||||
};
|
||||
|
||||
for (const remoteAddress of ["192.168.2.50", "100.101.102.103"]) {
|
||||
const res = await appWithRemoteAddress(config, auth, remoteAddress);
|
||||
expect(res.status).toBe(403);
|
||||
const body = (await res.json()) as { code: string; message: string };
|
||||
expect(body.code).toBe("E_FORBIDDEN");
|
||||
expect(body.message).toBe("console login is loopback-only");
|
||||
}
|
||||
// No device was created by the rejected calls.
|
||||
expect(auth.listDevices()).toEqual([]);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/v1/info access fields", () => {
|
||||
it("reports access always and publicUrl as string|null", async () => {
|
||||
const h = await createHarness({ config: { access: "tailscale", publicUrl: "https://host.ts.net" } });
|
||||
try {
|
||||
const body = (await (await fetch(`${h.url}/api/v1/info`)).json()) as Record<string, unknown>;
|
||||
expect(body.access).toBe("tailscale");
|
||||
expect(body.publicUrl).toBe("https://host.ts.net");
|
||||
// Existing keys survive.
|
||||
expect(body.v).toBe(1);
|
||||
expect(body.port).toBe(h.server.port);
|
||||
} finally {
|
||||
await h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the local default", async () => {
|
||||
const h = await createHarness();
|
||||
try {
|
||||
const body = (await (await fetch(`${h.url}/api/v1/info`)).json()) as Record<string, unknown>;
|
||||
expect(body.access).toBe("local");
|
||||
expect(body.publicUrl).toBeNull();
|
||||
} finally {
|
||||
await h.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
+14
-1
@@ -26,6 +26,8 @@ export function testConfig(overrides: Partial<Config> = {}): Config {
|
||||
limits: TEST_LIMITS,
|
||||
tokenPath: "/tmp/pi2-daemon-test.sock.token",
|
||||
deviceStorePath: "/tmp/pi2-daemon-test-devices.json",
|
||||
access: "local",
|
||||
publicUrl: null,
|
||||
};
|
||||
return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } };
|
||||
}
|
||||
@@ -35,6 +37,8 @@ export interface HarnessOptions {
|
||||
seedInstances?: string[];
|
||||
config?: Partial<Config>;
|
||||
staticFiles?: Record<string, string>;
|
||||
/** Written to `<dir>/cli.token` and accepted by the daemon's AuthStore. */
|
||||
cliToken?: string;
|
||||
heartbeatMs?: number;
|
||||
wsOverrides?: {
|
||||
maxBufferedBytes?: number;
|
||||
@@ -74,7 +78,16 @@ export async function createHarness(options: HarnessOptions = {}): Promise<Harne
|
||||
writeFileSync(target, content);
|
||||
}
|
||||
|
||||
const auth = new AuthStore({ path: join(dir, "devices.json"), baseUrl: "http://127.0.0.1:0" });
|
||||
const auth = new AuthStore({
|
||||
path: join(dir, "devices.json"),
|
||||
baseUrl: "http://127.0.0.1:0",
|
||||
...(options.cliToken === undefined
|
||||
? {}
|
||||
: { localTokenPath: join(dir, "cli.token") }),
|
||||
});
|
||||
if (options.cliToken !== undefined) {
|
||||
writeFileSync(join(dir, "cli.token"), `${options.cliToken}\n`, { mode: 0o600 });
|
||||
}
|
||||
const instances = new FakeInstanceManager();
|
||||
for (const workspaceId of options.seedInstances ?? []) instances.addWorkspace(workspaceId);
|
||||
const workspaces = new FakeWorkspaceStore(options.workspaces ?? []);
|
||||
|
||||
@@ -128,6 +128,55 @@ describe("workspace store", () => {
|
||||
expect(store.get(bId)?.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps secondary rows in list() and get() so deep links still resolve", async () => {
|
||||
// The sandbox lives under $TMPDIR, so temp-hiding is switched off here to
|
||||
// isolate the hidden/ghost rules (and to exercise the env injection).
|
||||
const { store } = setup({ env: { PI2_WORKSPACE_HIDE_TEMP: "0" } });
|
||||
const bId = workspaceIdForCwd(projectB);
|
||||
await store.update(bId, { hidden: true });
|
||||
const ghostId = workspaceIdForCwd(projectGhost);
|
||||
|
||||
const all = store.list();
|
||||
expect(all).toHaveLength(3);
|
||||
expect(all.map((workspace) => workspace.workspaceId).sort()).toEqual(
|
||||
[workspaceIdForCwd(projectA), bId, ghostId].sort(),
|
||||
);
|
||||
|
||||
expect(store.get(bId)).toMatchObject({ hidden: true, visibility: "secondary", visibilityReason: "hidden" });
|
||||
expect(store.get(ghostId)).toMatchObject({
|
||||
exists: false,
|
||||
visibility: "secondary",
|
||||
visibilityReason: "ghost",
|
||||
});
|
||||
expect(store.get(workspaceIdForCwd(projectA))).toMatchObject({ visibility: "default" });
|
||||
expect(store.get(workspaceIdForCwd(projectA))).not.toHaveProperty("visibilityReason");
|
||||
});
|
||||
|
||||
it("classifies sandbox paths under $TMPDIR as temp when the policy is on", () => {
|
||||
const { store } = setup({ env: {} });
|
||||
expect(store.get(workspaceIdForCwd(projectA))).toMatchObject({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
});
|
||||
|
||||
it("add() clears hidden on a previously hidden workspace", async () => {
|
||||
const { store, registry } = setup({ env: { PI2_WORKSPACE_HIDE_TEMP: "0" } });
|
||||
const info = await store.add({ cwd: projectA });
|
||||
await store.update(info.workspaceId, { hidden: true });
|
||||
expect(store.get(info.workspaceId)).toMatchObject({
|
||||
hidden: true,
|
||||
visibility: "secondary",
|
||||
visibilityReason: "hidden",
|
||||
});
|
||||
|
||||
const reopened = await store.add({ cwd: projectA });
|
||||
expect(reopened).toMatchObject({ hidden: false, visibility: "default" });
|
||||
expect(reopened).not.toHaveProperty("visibilityReason");
|
||||
expect(registry.get(info.workspaceId)?.entry.hidden).toBe(false);
|
||||
expect(registry.list()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("adds existing, readable, writable directories inside the allowlist", async () => {
|
||||
const { store, registry } = setup();
|
||||
const info = await store.add({ cwd: projectA, alias: " Alpha ", trust: true });
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { InstanceState } from "../../src/protocol/types.js";
|
||||
import {
|
||||
classifyWorkspace,
|
||||
isTempPath,
|
||||
parseBooleanEnv,
|
||||
parseNonNegativeInt,
|
||||
tempRoots,
|
||||
type ClassifyWorkspaceInput,
|
||||
} from "../../src/workspaces/index.js";
|
||||
import { cleanup, makeSandbox } from "./helpers.js";
|
||||
|
||||
const DAY = 86_400_000;
|
||||
const NOW = Date.UTC(2026, 9, 15, 12, 0, 0);
|
||||
|
||||
function instanceState(workspaceId: string): InstanceState {
|
||||
return {
|
||||
workspaceId,
|
||||
instanceId: "i-1",
|
||||
status: "ready",
|
||||
nvimPid: 4242,
|
||||
pluginVersion: "1.8.0",
|
||||
hasUI: true,
|
||||
attachedClients: 1,
|
||||
listenAddr: null,
|
||||
startedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
describe("classifyWorkspace", () => {
|
||||
// Synthetic, non-existent roots: the test must not depend on the host's
|
||||
// $HOME or on the mkdtemp sandbox (which itself lives under /tmp).
|
||||
const home = "/pi2-test-home";
|
||||
const other = "/pi2-test-other";
|
||||
const third = "/pi2-test-third";
|
||||
let sandbox: string;
|
||||
let temp: string;
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = makeSandbox("pi2-daemon-visibility-");
|
||||
temp = join(sandbox, "temp");
|
||||
mkdirSync(temp, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => cleanup(sandbox));
|
||||
|
||||
/** Hermetic base row: no env leakage from the host, roots pinned to `home`. */
|
||||
function row(overrides: Partial<ClassifyWorkspaceInput> = {}): ClassifyWorkspaceInput {
|
||||
return {
|
||||
cwd: join(home, "code", "alpha"),
|
||||
exists: true,
|
||||
lastActiveAt: NOW - DAY,
|
||||
roots: [home],
|
||||
env: { TMPDIR: temp },
|
||||
now: NOW,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
it("defaults to a visible row with no reason", () => {
|
||||
expect(classifyWorkspace(row())).toEqual({ visibility: "default" });
|
||||
});
|
||||
|
||||
it("precedence 1: hidden wins over every rescue", () => {
|
||||
const classified = classifyWorkspace(
|
||||
row({
|
||||
hidden: true,
|
||||
pinned: true,
|
||||
trusted: true,
|
||||
liveCount: 2,
|
||||
instance: instanceState("ws-1"),
|
||||
exists: false,
|
||||
cwd: join(temp, "scratch"),
|
||||
}),
|
||||
);
|
||||
expect(classified).toEqual({ visibility: "secondary", visibilityReason: "hidden" });
|
||||
});
|
||||
|
||||
it("precedence 2: a live instance, pin or trust rescues temp/ghost/stale rows", () => {
|
||||
const tempGhostStale = {
|
||||
cwd: join(temp, "scratch", "deep"),
|
||||
exists: false,
|
||||
lastActiveAt: NOW - 365 * DAY,
|
||||
env: { TMPDIR: temp, PI2_WORKSPACE_STALE_DAYS: "7" },
|
||||
};
|
||||
expect(classifyWorkspace(row(tempGhostStale))).toMatchObject({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
for (const rescue of [
|
||||
{ instance: instanceState("ws-1") },
|
||||
{ liveCount: 1 },
|
||||
{ pinned: true },
|
||||
{ trusted: true },
|
||||
]) {
|
||||
expect(classifyWorkspace(row({ ...tempGhostStale, ...rescue })), JSON.stringify(rescue)).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("precedence 3: temp paths hide by default, including trailing subpaths", () => {
|
||||
expect(classifyWorkspace(row({ cwd: temp }))).toEqual({ visibility: "secondary", visibilityReason: "temp" });
|
||||
expect(classifyWorkspace(row({ cwd: join(temp, "a", "b", "c") }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
// Built-in roots work without TMPDIR.
|
||||
expect(classifyWorkspace(row({ cwd: "/tmp/pi2-not-created", env: {} }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
expect(classifyWorkspace(row({ env: { TMPDIR: temp, PI2_WORKSPACE_HIDE_TEMP: "0" } }))).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
});
|
||||
|
||||
it("precedence 4: ghosts hide by default and beat outside-roots/stale", () => {
|
||||
const elsewhere = join(other, "gone");
|
||||
expect(classifyWorkspace(row({ cwd: elsewhere, exists: false }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "ghost",
|
||||
});
|
||||
expect(
|
||||
classifyWorkspace(
|
||||
row({
|
||||
cwd: elsewhere,
|
||||
exists: false,
|
||||
lastActiveAt: NOW - 400 * DAY,
|
||||
env: { TMPDIR: temp, PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "1", PI2_WORKSPACE_STALE_DAYS: "30" },
|
||||
}),
|
||||
),
|
||||
).toEqual({ visibility: "secondary", visibilityReason: "ghost" });
|
||||
expect(
|
||||
classifyWorkspace(row({ exists: false, env: { TMPDIR: temp, PI2_WORKSPACE_HIDE_GHOSTS: "0" } })),
|
||||
).toEqual({ visibility: "default" });
|
||||
});
|
||||
|
||||
it("precedence 5: outside-roots is opt-in and parses PI2_WORKSPACE_ROOTS as a list", () => {
|
||||
const outside = row({ cwd: join(other, "project"), roots: [home], env: { TMPDIR: temp } });
|
||||
// Default is 0 → still visible.
|
||||
expect(classifyWorkspace(outside)).toEqual({ visibility: "default" });
|
||||
expect(classifyWorkspace({ ...outside, env: { TMPDIR: temp, PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "1" } })).toEqual(
|
||||
{ visibility: "secondary", visibilityReason: "outside-roots" },
|
||||
);
|
||||
|
||||
// Both roots from the env list are honoured; the third path is outside.
|
||||
const roots = `${home}, ${other}`;
|
||||
const env = { TMPDIR: temp, PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "1", PI2_WORKSPACE_ROOTS: roots };
|
||||
expect(classifyWorkspace(row({ cwd: join(home, "a"), roots: undefined, env }))).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
expect(classifyWorkspace(row({ cwd: join(other, "b"), roots: undefined, env }))).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
expect(classifyWorkspace(row({ cwd: join(third, "c"), roots: undefined, env }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "outside-roots",
|
||||
});
|
||||
});
|
||||
|
||||
it("precedence 6: stale is opt-in and never applies to lastActiveAt === null", () => {
|
||||
const old = row({ lastActiveAt: NOW - 31 * DAY, env: { TMPDIR: temp } });
|
||||
// Default 0 = disabled.
|
||||
expect(classifyWorkspace(old)).toEqual({ visibility: "default" });
|
||||
expect(classifyWorkspace({ ...old, env: { TMPDIR: temp, PI2_WORKSPACE_STALE_DAYS: "30" } })).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "stale",
|
||||
});
|
||||
const fresh = row({ lastActiveAt: NOW - 29 * DAY, env: { TMPDIR: temp, PI2_WORKSPACE_STALE_DAYS: "30" } });
|
||||
expect(classifyWorkspace(fresh)).toEqual({ visibility: "default" });
|
||||
expect(
|
||||
classifyWorkspace(
|
||||
row({ lastActiveAt: null, env: { TMPDIR: temp, PI2_WORKSPACE_STALE_DAYS: "1" } }),
|
||||
),
|
||||
).toEqual({ visibility: "default" });
|
||||
});
|
||||
|
||||
it("never throws on garbage env values", () => {
|
||||
const garbage = {
|
||||
PI2_WORKSPACE_HIDE_TEMP: "maybe",
|
||||
PI2_WORKSPACE_HIDE_GHOSTS: " ",
|
||||
PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "2",
|
||||
PI2_WORKSPACE_STALE_DAYS: "-3",
|
||||
};
|
||||
// Garbage booleans fall back to the defaults (temp+ghost on, roots off);
|
||||
// garbage stale-days falls back to 0 (off).
|
||||
expect(classifyWorkspace(row({ cwd: join(temp, "x"), env: garbage }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
expect(classifyWorkspace(row({ exists: false, env: garbage }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "ghost",
|
||||
});
|
||||
expect(classifyWorkspace(row({ cwd: join(other, "x"), lastActiveAt: null, env: garbage }))).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
// Unknown cwd / missing roots must not throw.
|
||||
expect(classifyWorkspace({ cwd: "", exists: true, lastActiveAt: null, env: garbage })).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
});
|
||||
|
||||
it("parseBooleanEnv accepts 1/true/yes/on and 0/false/no/off, else the fallback", () => {
|
||||
for (const raw of ["1", "true", "TRUE", "yes", "on", " on "]) {
|
||||
expect(parseBooleanEnv(raw, false), raw).toBe(true);
|
||||
}
|
||||
for (const raw of ["0", "false", "False", "no", "off", " off "]) {
|
||||
expect(parseBooleanEnv(raw, true), raw).toBe(false);
|
||||
}
|
||||
for (const raw of [undefined, "", "maybe", "2", "enabled"]) {
|
||||
expect(parseBooleanEnv(raw, true), String(raw)).toBe(true);
|
||||
expect(parseBooleanEnv(raw, false), String(raw)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("parseNonNegativeInt keeps positive integers and falls back to 0", () => {
|
||||
expect(parseNonNegativeInt("30")).toBe(30);
|
||||
expect(parseNonNegativeInt(" 7 ")).toBe(7);
|
||||
expect(parseNonNegativeInt("0")).toBe(0);
|
||||
for (const raw of [undefined, "", "-1", "1.5", "abc", "1e3", "999999999999999999999"]) {
|
||||
expect(parseNonNegativeInt(raw), String(raw)).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("tempRoots includes $TMPDIR plus the platform defaults and isTempPath matches subpaths", () => {
|
||||
const roots = tempRoots({ TMPDIR: temp });
|
||||
expect(roots).toContain(temp);
|
||||
expect(roots).toContain("/tmp");
|
||||
expect(new Set(roots).size).toBe(roots.length);
|
||||
expect(isTempPath(join(temp, "x", "y"), { TMPDIR: temp })).toBe(true);
|
||||
expect(isTempPath(temp, { TMPDIR: temp })).toBe(true);
|
||||
expect(isTempPath(join(home, "code"), { TMPDIR: temp })).toBe(false);
|
||||
expect(isTempPath("", { TMPDIR: temp })).toBe(false);
|
||||
});
|
||||
|
||||
it("hides a temp ghost as temp (temp precedes ghost)", () => {
|
||||
expect(classifyWorkspace(row({ cwd: join(temp, "gone"), exists: false }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies rows with an unknown workspaceId-shaped input safely", () => {
|
||||
// Registry-only rows can carry an empty cwd; no path rule may fire.
|
||||
expect(classifyWorkspace(row({ cwd: "", exists: false, env: { PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "1" } }))).toEqual(
|
||||
{ visibility: "secondary", visibilityReason: "ghost" },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Workspace-noise policy, browser side.
|
||||
*
|
||||
* The daemon classifies every row (`visibility: "default" | "secondary"` +
|
||||
* `visibilityReason`) but never filters the list, so `/workspace/<id>` deep
|
||||
* links keep resolving. This module only partitions the served rows for
|
||||
* list/picker surfaces: `primary` is what the user normally wants, `secondary`
|
||||
* is noise (explicitly hidden, ghosts, temp dirs, …) behind a toggle.
|
||||
*/
|
||||
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
|
||||
/** Persisted toggle: "show N hidden" on the workspaces page. */
|
||||
export const SHOW_ALL_STORAGE_KEY = "pi2-workspaces-show-all";
|
||||
|
||||
export interface WorkspacePartition {
|
||||
primary: WorkspaceInfo[];
|
||||
secondary: WorkspaceInfo[];
|
||||
}
|
||||
|
||||
/** Legacy daemons omit `visibility`; `hidden` alone still means secondary. */
|
||||
export function isSecondary(workspace: WorkspaceInfo): boolean {
|
||||
if (workspace.visibility === "secondary") return true;
|
||||
return workspace.hidden === true;
|
||||
}
|
||||
|
||||
/** Reason for the badge; `hidden` is inferred for pre-classification daemons. */
|
||||
export function visibilityReason(workspace: WorkspaceInfo): string | null {
|
||||
if (typeof workspace.visibilityReason === "string" && workspace.visibilityReason.length > 0) {
|
||||
return workspace.visibilityReason;
|
||||
}
|
||||
return workspace.hidden === true ? "hidden" : null;
|
||||
}
|
||||
|
||||
/** i18n key for the reason badge (or `null` for a default row). */
|
||||
export function reasonLabelKey(workspace: WorkspaceInfo): string | null {
|
||||
const reason = visibilityReason(workspace);
|
||||
return reason === null ? null : `workspaces.reason.${reason}`;
|
||||
}
|
||||
|
||||
/** Split served rows into the normal list and the collapsed noise. */
|
||||
export function partitionWorkspaces(list: readonly WorkspaceInfo[], _showAll = false): WorkspacePartition {
|
||||
const primary: WorkspaceInfo[] = [];
|
||||
const secondary: WorkspaceInfo[] = [];
|
||||
for (const workspace of list) {
|
||||
if (isSecondary(workspace)) secondary.push(workspace);
|
||||
else primary.push(workspace);
|
||||
}
|
||||
return { primary, secondary };
|
||||
}
|
||||
|
||||
/** How many rows the "show N hidden" toggle would reveal (0 hides the toggle). */
|
||||
export function countSecondary(list: readonly WorkspaceInfo[]): number {
|
||||
return partitionWorkspaces(list).secondary.length;
|
||||
}
|
||||
|
||||
/** `localStorage` read; default off and any failure means off. */
|
||||
export function readShowAll(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(SHOW_ALL_STORAGE_KEY) === "1";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** `localStorage` write; storage failures must never break the page. */
|
||||
export function writeShowAll(showAll: boolean): void {
|
||||
try {
|
||||
localStorage.setItem(SHOW_ALL_STORAGE_KEY, showAll ? "1" : "0");
|
||||
} catch {
|
||||
// private mode / quota: the in-memory toggle still works
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { plural } from "@/lib/i18n";
|
||||
import type { WorkspaceInfo } from "@/lib/protocol";
|
||||
|
||||
import { workspaceName } from "./commands";
|
||||
import { isSecondary, reasonLabelKey } from "./visibility";
|
||||
|
||||
function serverDot(status: ServerIdentity["status"]): DotStatus {
|
||||
if (status === "online") return "ok";
|
||||
@@ -78,9 +79,20 @@ export function WorkspaceRow({ workspace }: WorkspaceRowProps) {
|
||||
const { t } = useTranslation();
|
||||
const dot = instanceDot(workspace);
|
||||
const count = Math.max(workspace.liveCount || 0, workspace.sessionCount || 0);
|
||||
// Secondary rows are dimmed and carry the policy reason; the page decides
|
||||
// *whether* they render (see features/workspaces/visibility.ts).
|
||||
const secondary = isSecondary(workspace);
|
||||
const reasonKey = secondary ? reasonLabelKey(workspace) : null;
|
||||
|
||||
return (
|
||||
<div className="list-row" data-workspace-id={workspace.workspaceId} data-testid="workspace-row">
|
||||
<div
|
||||
className={secondary ? "list-row list-row--secondary" : "list-row"}
|
||||
style={secondary ? { opacity: 0.55 } : undefined}
|
||||
data-workspace-id={workspace.workspaceId}
|
||||
data-testid="workspace-row"
|
||||
data-visibility={secondary ? "secondary" : "default"}
|
||||
data-visibility-reason={reasonKey ? workspace.visibilityReason ?? "hidden" : undefined}
|
||||
>
|
||||
<span className="ico list-row__icon">
|
||||
<Icon name="folder" />
|
||||
</span>
|
||||
@@ -88,6 +100,11 @@ export function WorkspaceRow({ workspace }: WorkspaceRowProps) {
|
||||
<div className="list-row__name">{workspaceName(workspace, t("workspaces.unnamed"))}</div>
|
||||
<div className="list-row__cwd mono muted truncate">{workspace.cwd}</div>
|
||||
</div>
|
||||
{reasonKey ? (
|
||||
<Badge className="list-row__count" data-testid="workspace-reason">
|
||||
{t(reasonKey)}
|
||||
</Badge>
|
||||
) : null}
|
||||
<Badge tone="info" className="list-row__count">
|
||||
{plural("workspaces.sessionCount", count)}
|
||||
</Badge>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* One-time login handoff for `:PiWeb`.
|
||||
*
|
||||
* The daemon opens `http://<host>:<port>/#t=<token>` (or `#token=<token>`).
|
||||
* The token is read once, stored through the existing device-token helper and
|
||||
* removed from the address bar/history before the router resolves its first
|
||||
* route. Anything that is not a valid handoff is left untouched, so a bad
|
||||
* link stays visibly broken instead of silently landing on `/connect`.
|
||||
*/
|
||||
|
||||
/** Fragment forms the daemon may hand off: `#t=<token>` and `#token=<token>`. */
|
||||
export const HANDOFF_HASH_PATTERN = /^(?:t|token)=(.+)$/;
|
||||
|
||||
/** Device tokens are base64url-ish and at least 20 characters long. */
|
||||
export const HANDOFF_TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,}$/;
|
||||
|
||||
export interface HandoffLocation {
|
||||
readonly hash: string;
|
||||
readonly pathname: string;
|
||||
readonly search: string;
|
||||
}
|
||||
|
||||
export interface HandoffHistory {
|
||||
replaceState(data: unknown, unused: string, url?: string | URL | null): void;
|
||||
}
|
||||
|
||||
export type HandoffTokenSink = (token: string | null) => void;
|
||||
|
||||
/**
|
||||
* Extract a valid handoff token from a location hash. Returns `null` for any
|
||||
* other fragment, including malformed percent-encoding.
|
||||
*/
|
||||
export function readHandoff(hash: string): string | null {
|
||||
if (!hash) return null;
|
||||
const fragment = hash.startsWith("#") ? hash.slice(1) : hash;
|
||||
const match = HANDOFF_HASH_PATTERN.exec(fragment);
|
||||
const encoded = match?.[1];
|
||||
if (!encoded) return null;
|
||||
|
||||
let token: string;
|
||||
try {
|
||||
token = decodeURIComponent(encoded);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return HANDOFF_TOKEN_PATTERN.test(token) ? token : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a handoff token and strip the fragment while keeping the path and
|
||||
* query string. No-ops (and never writes history) when the hash is not a
|
||||
* valid handoff.
|
||||
*/
|
||||
export function consumeHandoff(
|
||||
location: HandoffLocation,
|
||||
history: HandoffHistory,
|
||||
setToken: HandoffTokenSink,
|
||||
): string | null {
|
||||
const token = readHandoff(location.hash);
|
||||
if (!token) return null;
|
||||
|
||||
setToken(token);
|
||||
history.replaceState(null, "", location.pathname + location.search);
|
||||
return token;
|
||||
}
|
||||
+11
-1
@@ -385,6 +385,11 @@
|
||||
"time.minutesAgo": "{n}m ago",
|
||||
"workspaces.activeRecently": "Active in the last hour",
|
||||
"workspaces.addFailed": "Could not open the workspace. Check that the path is accessible.",
|
||||
"workspaces.allHidden": "All workspaces are hidden",
|
||||
"workspaces.allHiddenText": "Turn on “Show {n} hidden” to list them.",
|
||||
"workspaces.hideHidden": "Hide {n} hidden",
|
||||
"workspaces.showHidden": "Show {n} hidden",
|
||||
"workspaces.showHiddenAria": "Show hidden workspaces",
|
||||
"workspaces.contextAria": "Current server",
|
||||
"workspaces.count": "{n} workspaces",
|
||||
"workspaces.count.one": "{n} workspace",
|
||||
@@ -420,5 +425,10 @@
|
||||
"workspaces.sessionCount.other": "{n} sessions",
|
||||
"workspaces.subtitle": "A workspace is a Neovim working directory (cwd); sessions are isolated per cwd.",
|
||||
"workspaces.title": "Workspaces",
|
||||
"workspaces.unnamed": "Untitled"
|
||||
"workspaces.unnamed": "Untitled",
|
||||
"workspaces.reason.ghost": "missing",
|
||||
"workspaces.reason.hidden": "hidden",
|
||||
"workspaces.reason.outside-roots": "outside roots",
|
||||
"workspaces.reason.stale": "stale",
|
||||
"workspaces.reason.temp": "temp"
|
||||
}
|
||||
+11
-1
@@ -385,6 +385,11 @@
|
||||
"time.minutesAgo": "{n} 分钟前",
|
||||
"workspaces.activeRecently": "最近 1 小时有活动",
|
||||
"workspaces.addFailed": "打开工作空间失败,请检查路径是否可访问",
|
||||
"workspaces.allHidden": "所有工作空间都被隐藏了",
|
||||
"workspaces.allHiddenText": "打开“显示 {n} 个隐藏项”以查看。",
|
||||
"workspaces.hideHidden": "隐藏 {n} 个隐藏项",
|
||||
"workspaces.showHidden": "显示 {n} 个隐藏项",
|
||||
"workspaces.showHiddenAria": "显示隐藏的工作空间",
|
||||
"workspaces.contextAria": "当前服务器",
|
||||
"workspaces.count": "{n} 个工作空间",
|
||||
"workspaces.count.one": "{n} 个工作空间",
|
||||
@@ -420,5 +425,10 @@
|
||||
"workspaces.sessionCount.other": "{n} 个会话",
|
||||
"workspaces.subtitle": "工作空间 = Neovim 工作目录(cwd),会话严格按 cwd 隔离。",
|
||||
"workspaces.title": "工作空间",
|
||||
"workspaces.unnamed": "未命名"
|
||||
"workspaces.unnamed": "未命名",
|
||||
"workspaces.reason.ghost": "目录不存在",
|
||||
"workspaces.reason.hidden": "已隐藏",
|
||||
"workspaces.reason.outside-roots": "根目录外",
|
||||
"workspaces.reason.stale": "长期未动",
|
||||
"workspaces.reason.temp": "临时目录"
|
||||
}
|
||||
@@ -8,7 +8,9 @@ import "@/styles/app.css";
|
||||
import "@/lib/i18n";
|
||||
|
||||
import { Toaster } from "@/components/ui/toast";
|
||||
import { consumeHandoff } from "@/lib/handoff";
|
||||
import { router } from "@/router";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -39,6 +41,14 @@ function App() {
|
||||
);
|
||||
}
|
||||
|
||||
// `:PiWeb` hands the device token over in the fragment. Consume it before the
|
||||
// router resolves its first route, and go through the connection store (not
|
||||
// `setDeviceToken`) so the `pi2-connection` marker the guards read is set too:
|
||||
// otherwise a fresh browser would still bounce to `/connect` on its first load.
|
||||
consumeHandoff(window.location, window.history, (token) => {
|
||||
useConnectionStore.getState().connect({ token, endpoint: window.location.origin });
|
||||
});
|
||||
|
||||
const container = document.getElementById("root");
|
||||
if (!container) throw new Error("Missing #root element");
|
||||
createRoot(container).render(<App />);
|
||||
@@ -15,8 +15,7 @@ import { ConnectionCard } from "@/features/status/connection-card";
|
||||
import { deviceKey, DevicesCard } from "@/features/status/devices-card";
|
||||
import { HealthCard } from "@/features/status/health-card";
|
||||
import { ModelsCard } from "@/features/status/models-card";
|
||||
import {
|
||||
mergeTasks,
|
||||
import { mergeTasks,
|
||||
sessionTasks,
|
||||
useDevicesQuery,
|
||||
useHealthQuery,
|
||||
@@ -34,6 +33,7 @@ import { ResourcesCard } from "@/features/status/resources-card";
|
||||
import { deriveServerIdentity, type InfoExtras } from "@/features/status/server";
|
||||
import { ServerInfoCard } from "@/features/status/server-info-card";
|
||||
import { TasksCard } from "@/features/status/tasks-card";
|
||||
import { partitionWorkspaces } from "@/features/workspaces/visibility";
|
||||
import { ApiError, api, errorI18nKey } from "@/lib/api";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
@@ -72,7 +72,10 @@ export function StatusPage() {
|
||||
const pairCode = usePairCodeQuery(paired);
|
||||
|
||||
const workspaces = workspacesQuery.data ?? [];
|
||||
const visibleWorkspaces = workspaces.filter((workspace) => !workspace.hidden);
|
||||
// Counters, the models probe and the task list only consider the rows the
|
||||
// workspace-noise policy keeps in the default view: a ghost or a /tmp
|
||||
// scratch dir must not become the "first workspace" used for `/models`.
|
||||
const { primary: visibleWorkspaces } = partitionWorkspaces(workspaces);
|
||||
const workspaceCount = visibleWorkspaces.length;
|
||||
const sessionCount = visibleWorkspaces.reduce((total, workspace) => total + (workspace.sessionCount || 0), 0);
|
||||
const modelsWorkspaceId = visibleWorkspaces[0]?.workspaceId ?? null;
|
||||
|
||||
@@ -13,6 +13,12 @@ import { deriveServerIdentity, type InfoExtras } from "@/features/status/server"
|
||||
import { useInfoQuery, useWorkspacesQuery } from "@/features/status/queries";
|
||||
import { openWorkspace } from "@/features/workspaces/commands";
|
||||
import { NewWorkspaceDialog, type NewWorkspaceInput } from "@/features/workspaces/new-workspace-dialog";
|
||||
import {
|
||||
countSecondary,
|
||||
partitionWorkspaces,
|
||||
readShowAll,
|
||||
writeShowAll,
|
||||
} from "@/features/workspaces/visibility";
|
||||
import {
|
||||
ServerContextBar,
|
||||
WorkspaceRow,
|
||||
@@ -48,13 +54,25 @@ export function WorkspacesPage() {
|
||||
const workspaces = useWorkspacesQuery();
|
||||
const info = useInfoQuery();
|
||||
|
||||
const items = useMemo(
|
||||
() => (workspaces.data ?? []).filter((workspace) => !workspace.hidden).slice().sort(compareWorkspaces),
|
||||
[workspaces.data],
|
||||
);
|
||||
// Persisted "show N hidden" toggle (localStorage, default off): secondary
|
||||
// rows (hidden/ghost/temp/…) stay out of the list until asked for.
|
||||
const [showAll, setShowAll] = useState<boolean>(() => readShowAll());
|
||||
|
||||
function toggleShowAll() {
|
||||
setShowAll((previous) => {
|
||||
const next = !previous;
|
||||
writeShowAll(next);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
const all = useMemo(() => (workspaces.data ?? []).slice().sort(compareWorkspaces), [workspaces.data]);
|
||||
const secondaryCount = useMemo(() => countSecondary(all), [all]);
|
||||
const { primary, secondary } = useMemo(() => partitionWorkspaces(all, showAll), [all, showAll]);
|
||||
const items = showAll ? [...primary, ...secondary].sort(compareWorkspaces) : primary;
|
||||
const sessionCount = useMemo(
|
||||
() => items.reduce((total, workspace) => total + Math.max(workspace.liveCount || 0, workspace.sessionCount || 0), 0),
|
||||
[items],
|
||||
() => primary.reduce((total, workspace) => total + Math.max(workspace.liveCount || 0, workspace.sessionCount || 0), 0),
|
||||
[primary],
|
||||
);
|
||||
|
||||
const server = deriveServerIdentity({
|
||||
@@ -85,10 +103,24 @@ export function WorkspacesPage() {
|
||||
subtitle={t("workspaces.subtitle")}
|
||||
docTitle={t("nav.workspaces")}
|
||||
actions={
|
||||
<>
|
||||
{secondaryCount > 0 ? (
|
||||
<Button
|
||||
variant={showAll ? "default" : "ghost"}
|
||||
aria-pressed={showAll}
|
||||
aria-label={t("workspaces.showHiddenAria")}
|
||||
data-testid="workspaces-show-all"
|
||||
onClick={toggleShowAll}
|
||||
>
|
||||
<Icon name="eye" />
|
||||
{t(showAll ? "workspaces.hideHidden" : "workspaces.showHidden", { n: secondaryCount })}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="primary" onClick={() => setDialogOpen(true)}>
|
||||
<Icon name="plus" />
|
||||
{t("workspaces.new")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -116,17 +148,24 @@ export function WorkspacesPage() {
|
||||
}
|
||||
/>
|
||||
</Panel>
|
||||
) : items.length === 0 ? (
|
||||
) : all.length === 0 || (primary.length === 0 && !showAll) ? (
|
||||
<Panel>
|
||||
<Empty
|
||||
icon={<Icon name="folder" size={28} />}
|
||||
title={t("workspaces.emptyTitle")}
|
||||
description={t("workspaces.emptyText")}
|
||||
title={all.length === 0 ? t("workspaces.emptyTitle") : t("workspaces.allHidden")}
|
||||
description={all.length === 0 ? t("workspaces.emptyText") : t("workspaces.allHiddenText", { n: secondaryCount })}
|
||||
action={
|
||||
all.length === 0 ? (
|
||||
<Button variant="primary" onClick={() => setDialogOpen(true)}>
|
||||
<Icon name="plus" />
|
||||
{t("workspaces.new")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="ghost" onClick={toggleShowAll}>
|
||||
<Icon name="eye" />
|
||||
{t("workspaces.showHidden", { n: secondaryCount })}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Panel>
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { setDeviceToken, TOKEN_STORAGE_KEY } from "@/lib/api";
|
||||
import { consumeHandoff, readHandoff } from "@/lib/handoff";
|
||||
|
||||
/** 23 characters, valid base64url alphabet. */
|
||||
const TOKEN = "AbC-dEf_GhI-jKl_MnO-123";
|
||||
const ENCODED_TOKEN = "AbC%2DdEf_GhI%2DjKl_MnO%2D123";
|
||||
|
||||
function locationWith(hash: string, pathname = "/workspaces", search = "") {
|
||||
return { hash, pathname, search };
|
||||
}
|
||||
|
||||
function historySpy() {
|
||||
return { replaceState: vi.fn() };
|
||||
}
|
||||
|
||||
describe("readHandoff", () => {
|
||||
it("accepts the short `#t=` form", () => {
|
||||
expect(readHandoff(`#t=${TOKEN}`)).toBe(TOKEN);
|
||||
});
|
||||
|
||||
it("accepts the long `#token=` form", () => {
|
||||
expect(readHandoff(`#token=${TOKEN}`)).toBe(TOKEN);
|
||||
});
|
||||
|
||||
it("decodes URL-encoded token characters", () => {
|
||||
expect(readHandoff(`#t=${ENCODED_TOKEN}`)).toBe(TOKEN);
|
||||
expect(readHandoff(`#token=${encodeURIComponent("a".repeat(20))}`)).toBe("a".repeat(20));
|
||||
});
|
||||
|
||||
it("rejects anything that is not a valid handoff", () => {
|
||||
for (const hash of [
|
||||
"",
|
||||
"#",
|
||||
"#t=",
|
||||
"#t=tooshort",
|
||||
`#t=${"a".repeat(19)}`,
|
||||
"#token=tooshort",
|
||||
`#x=${TOKEN}`,
|
||||
`#t=${TOKEN}!`,
|
||||
`#t=${TOKEN}&next=/workspaces`,
|
||||
`#token=${encodeURIComponent(`Bearer ${TOKEN}`)}`,
|
||||
"#t=%E0%A4%A",
|
||||
"#pair/ABCD1234",
|
||||
]) {
|
||||
expect(readHandoff(hash), hash).toBeNull();
|
||||
}
|
||||
expect(readHandoff(`#t=${"a".repeat(20)}`)).toBe("a".repeat(20));
|
||||
});
|
||||
});
|
||||
|
||||
describe("consumeHandoff", () => {
|
||||
it("stores the token and strips the hash exactly once", () => {
|
||||
const history = historySpy();
|
||||
const setToken = vi.fn();
|
||||
|
||||
expect(consumeHandoff(locationWith(`#t=${TOKEN}`), history, setToken)).toBe(TOKEN);
|
||||
expect(setToken).toHaveBeenCalledExactlyOnceWith(TOKEN);
|
||||
expect(history.replaceState).toHaveBeenCalledTimes(1);
|
||||
expect(history.replaceState).toHaveBeenCalledWith(null, "", "/workspaces");
|
||||
});
|
||||
|
||||
it("keeps the query string when stripping the hash", () => {
|
||||
const history = historySpy();
|
||||
|
||||
consumeHandoff(
|
||||
locationWith(`#token=${TOKEN}`, "/workspace/ws-1", "?next=%2Fchat%2F01a1&tab=todo"),
|
||||
history,
|
||||
vi.fn(),
|
||||
);
|
||||
expect(history.replaceState).toHaveBeenCalledWith(
|
||||
null,
|
||||
"",
|
||||
"/workspace/ws-1?next=%2Fchat%2F01a1&tab=todo",
|
||||
);
|
||||
});
|
||||
|
||||
it("no-ops without a handoff hash (no history write, no token write)", () => {
|
||||
for (const hash of ["", "#", "#t=tooshort", "#/pair/ABCD1234"]) {
|
||||
const history = historySpy();
|
||||
const setToken = vi.fn();
|
||||
expect(consumeHandoff(locationWith(hash, "/workspaces", "?tab=devices"), history, setToken)).toBeNull();
|
||||
expect(history.replaceState, hash).not.toHaveBeenCalled();
|
||||
expect(setToken, hash).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it("works against the real location/history and the shared token storage", () => {
|
||||
window.history.replaceState(null, "", `/workspaces?tab=devices#t=${TOKEN}`);
|
||||
const replaceState = vi.spyOn(window.history, "replaceState");
|
||||
|
||||
expect(consumeHandoff(window.location, window.history, setDeviceToken)).toBe(TOKEN);
|
||||
|
||||
expect(localStorage.getItem(TOKEN_STORAGE_KEY)).toBe(`Bearer ${TOKEN}`);
|
||||
expect(window.location.hash).toBe("");
|
||||
expect(`${window.location.pathname}${window.location.search}`).toBe("/workspaces?tab=devices");
|
||||
expect(replaceState).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("leaves a broken link visibly broken", () => {
|
||||
window.history.replaceState(null, "", "/workspaces#t=tooshort");
|
||||
const setToken = vi.fn();
|
||||
|
||||
expect(consumeHandoff(window.location, window.history, setToken)).toBeNull();
|
||||
expect(setToken).not.toHaveBeenCalled();
|
||||
expect(window.location.hash).toBe("#t=tooshort");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import { fireEvent, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { mockApi } from "./helpers/api-mock";
|
||||
import { renderPage } from "./helpers/render-page";
|
||||
|
||||
import {
|
||||
countSecondary,
|
||||
partitionWorkspaces,
|
||||
readShowAll,
|
||||
reasonLabelKey,
|
||||
SHOW_ALL_STORAGE_KEY,
|
||||
writeShowAll,
|
||||
} from "@/features/workspaces/visibility";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import type { WorkspaceInfo, WorkspaceVisibilityReason } from "@/lib/protocol";
|
||||
import { WorkspacesPage } from "@/pages/workspaces";
|
||||
|
||||
const infoBody = {
|
||||
v: 1,
|
||||
daemonId: "daemon-1",
|
||||
machineId: "machine-1",
|
||||
platform: "linux",
|
||||
capabilities: ["read", "steer"],
|
||||
limits: { maxInstances: 5 },
|
||||
};
|
||||
|
||||
function workspace(
|
||||
overrides: Partial<WorkspaceInfo> & Pick<WorkspaceInfo, "workspaceId" | "cwd" | "name">,
|
||||
): WorkspaceInfo {
|
||||
return {
|
||||
trusted: true,
|
||||
exists: true,
|
||||
sessionCount: 0,
|
||||
liveCount: 0,
|
||||
lastActiveAt: 0,
|
||||
instance: null,
|
||||
visibility: "default",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function secondary(
|
||||
workspaceId: string,
|
||||
name: string,
|
||||
reason: WorkspaceVisibilityReason,
|
||||
overrides: Partial<WorkspaceInfo> = {},
|
||||
): WorkspaceInfo {
|
||||
return workspace({
|
||||
workspaceId,
|
||||
cwd: `/work/${name.toLowerCase()}`,
|
||||
name,
|
||||
visibility: "secondary",
|
||||
visibilityReason: reason,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
const primary = workspace({ workspaceId: "ws-a", cwd: "/work/alpha", name: "Alpha", lastActiveAt: 3_000 });
|
||||
const ghost = secondary("ws-g", "Ghost", "ghost", { exists: false, lastActiveAt: 2_000 });
|
||||
const hidden = secondary("ws-h", "Hidden", "hidden", { hidden: true, lastActiveAt: 1_000 });
|
||||
|
||||
function routes() {
|
||||
return [{ path: "/workspaces", component: WorkspacesPage }];
|
||||
}
|
||||
|
||||
function serve(items: WorkspaceInfo[]) {
|
||||
return mockApi([
|
||||
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
|
||||
]);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await setLanguage("en");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("partitionWorkspaces", () => {
|
||||
it("splits default rows from secondary rows without dropping any", () => {
|
||||
const legacyHidden = workspace({ workspaceId: "ws-l", cwd: "/work/legacy", name: "Legacy", hidden: true });
|
||||
delete legacyHidden.visibility;
|
||||
const list = [primary, ghost, hidden, legacyHidden];
|
||||
|
||||
const { primary: shown, secondary: collapsed } = partitionWorkspaces(list);
|
||||
expect(shown.map((item) => item.workspaceId)).toEqual(["ws-a"]);
|
||||
// Legacy daemons omit `visibility`; `hidden: true` still means secondary.
|
||||
expect(collapsed.map((item) => item.workspaceId)).toEqual(["ws-g", "ws-h", "ws-l"]);
|
||||
expect(partitionWorkspaces(list, true)).toEqual({ primary: shown, secondary: collapsed });
|
||||
expect(countSecondary(list)).toBe(3);
|
||||
expect(countSecondary([primary])).toBe(0);
|
||||
});
|
||||
|
||||
it("maps every reason to a badge i18n key", () => {
|
||||
expect(reasonLabelKey(primary)).toBeNull();
|
||||
expect(reasonLabelKey(ghost)).toBe("workspaces.reason.ghost");
|
||||
expect(reasonLabelKey(hidden)).toBe("workspaces.reason.hidden");
|
||||
expect(reasonLabelKey(secondary("ws-t", "Tmp", "temp"))).toBe("workspaces.reason.temp");
|
||||
expect(reasonLabelKey(secondary("ws-o", "Out", "outside-roots"))).toBe("workspaces.reason.outside-roots");
|
||||
expect(reasonLabelKey(secondary("ws-s", "Stale", "stale"))).toBe("workspaces.reason.stale");
|
||||
// Pre-classification daemon: hidden infers the reason.
|
||||
const legacy = workspace({ workspaceId: "ws-x", cwd: "/work/x", name: "X", hidden: true });
|
||||
expect(reasonLabelKey(legacy)).toBe("workspaces.reason.hidden");
|
||||
});
|
||||
});
|
||||
|
||||
describe("show-all persistence", () => {
|
||||
it("defaults to off and round-trips through localStorage", () => {
|
||||
expect(readShowAll()).toBe(false);
|
||||
writeShowAll(true);
|
||||
expect(localStorage.getItem(SHOW_ALL_STORAGE_KEY)).toBe("1");
|
||||
expect(readShowAll()).toBe(true);
|
||||
writeShowAll(false);
|
||||
expect(readShowAll()).toBe(false);
|
||||
});
|
||||
|
||||
it("treats an unexpected stored value as off", () => {
|
||||
localStorage.setItem(SHOW_ALL_STORAGE_KEY, "yes");
|
||||
expect(readShowAll()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkspacesPage secondary rows", () => {
|
||||
it("lists only primary rows by default and counts the hidden ones", async () => {
|
||||
serve([primary, ghost, hidden]);
|
||||
const { container } = await renderPage(routes(), "/workspaces");
|
||||
|
||||
await screen.findByText("Alpha");
|
||||
expect(screen.queryByText("Ghost")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Hidden")).not.toBeInTheDocument();
|
||||
|
||||
const toggle = await screen.findByTestId("workspaces-show-all");
|
||||
expect(toggle).toHaveTextContent("Show 2 hidden");
|
||||
expect(toggle).toHaveAttribute("aria-pressed", "false");
|
||||
expect(container.querySelectorAll('[data-testid="workspace-row"]')).toHaveLength(1);
|
||||
expect(readShowAll()).toBe(false);
|
||||
});
|
||||
|
||||
it("reveals dimmed secondary rows with a reason badge on toggle", async () => {
|
||||
serve([primary, ghost, hidden]);
|
||||
await renderPage(routes(), "/workspaces");
|
||||
await screen.findByText("Alpha");
|
||||
|
||||
fireEvent.click(screen.getByTestId("workspaces-show-all"));
|
||||
|
||||
expect(await screen.findByText("Ghost")).toBeInTheDocument();
|
||||
expect(screen.getByText("Hidden")).toBeInTheDocument();
|
||||
|
||||
const rows = screen.getAllByTestId("workspace-row");
|
||||
expect(rows.map((row) => row.getAttribute("data-visibility"))).toEqual(["default", "secondary", "secondary"]);
|
||||
const ghostRow = rows.find((row) => row.getAttribute("data-workspace-id") === "ws-g");
|
||||
expect(ghostRow).toHaveAttribute("data-visibility-reason", "ghost");
|
||||
expect(ghostRow).toHaveStyle({ opacity: "0.55" });
|
||||
expect(ghostRow?.querySelector('[data-testid="workspace-reason"]')).toHaveTextContent("missing");
|
||||
|
||||
const toggle = screen.getByTestId("workspaces-show-all");
|
||||
expect(toggle).toHaveTextContent("Hide 2 hidden");
|
||||
expect(toggle).toHaveAttribute("aria-pressed", "true");
|
||||
await waitFor(() => expect(localStorage.getItem(SHOW_ALL_STORAGE_KEY)).toBe("1"));
|
||||
|
||||
fireEvent.click(toggle);
|
||||
await waitFor(() => expect(screen.queryByText("Ghost")).not.toBeInTheDocument());
|
||||
expect(localStorage.getItem(SHOW_ALL_STORAGE_KEY)).toBe("0");
|
||||
});
|
||||
|
||||
it("honours a persisted toggle on mount", async () => {
|
||||
serve([primary, ghost, hidden]);
|
||||
await renderPage(routes(), "/workspaces", { storage: { [SHOW_ALL_STORAGE_KEY]: "1" } });
|
||||
|
||||
expect(await screen.findByText("Alpha")).toBeInTheDocument();
|
||||
expect(await screen.findByText("Ghost")).toBeInTheDocument();
|
||||
expect(screen.getByText("Hidden")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offers the toggle from the empty state when every row is secondary", async () => {
|
||||
serve([ghost, hidden]);
|
||||
await renderPage(routes(), "/workspaces");
|
||||
|
||||
expect(await screen.findByText("All workspaces are hidden")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByTestId("workspaces-show-all"));
|
||||
expect(await screen.findByText("Ghost")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user