Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b7e81af0b6 | |||
| c90dd7b147 | |||
| 49a041b1dc | |||
| de8d1079e0 | |||
| 0335e0e6bc | |||
| 18614f378d | |||
| 63ed90ba05 | |||
| 3ed88062d6 | |||
| 27313d4413 | |||
| d4b949a6f4 | |||
| 8930865376 | |||
| 29858ddccb | |||
| 7000a9c5ce | |||
| 99e718ad91 | |||
| 67c948bbe2 | |||
| 8b8582f231 | |||
| b868a2fa85 | |||
| 30bc6debde |
+9
-6
@@ -354,7 +354,7 @@ graph TD
|
||||
| `lib/codex-cli.js` | Shells out to the `codex` CLI (argv array, never a shell string) for the three surfaces with no on-disk reader: MCP servers (`mcp list\|add\|remove`), plugins (`plugin list\|add\|remove`), and marketplaces (`marketplace list\|add\|remove`). `runCodex()` parses stdout as JSON when possible; empty stdout on a zero-exit is a normal empty list, not a parse failure. A non-zero exit is returned as a structured failure (surfaced by the route as 422, never a 500) with `stdout`/`stderr` preserved |
|
||||
| `routes/codex-config.js` | HTTP surface for the Codex Config panel. Read endpoints for every surface (skills, agents, rules, memory, config, mcp, plugins, marketplaces, file, overview) plus mutation endpoints (`PUT /file`, `DELETE /file` delegating to `codex-mutate.js`; `POST /mcp/{add,remove}`, `/plugins/action`, `/marketplaces/{add,action}` delegating to `codex-cli.js`), plus `GET /backups`. Every successful mutation broadcasts `codex_config_changed` over the WebSocket so an open Codex settings tab refetches without polling. All errors return structured `{error: {code, message}}` shapes |
|
||||
| `lib/tmux.js` | Wrapper around tmux CLI for session management. `createSession(sessionName, cwd)` creates a new tmux session in the specified working directory. `sendCommand(sessionName, command)` sends a command into the session. `killSession(sessionName)` terminates the session. `listSessions()` returns all active sessions. Session management is the foundation for the PTY transport layer |
|
||||
| `lib/pty-run.js` | PTY lifecycle for tmux-backed runs. Manages one tmux session per lane, named `agenthub-lane-<lane.id>`. Exports `startRun()` to create/attach a session and return a `runId` opaque handle; internally uses tmux to manage the pseudoterminal. Spawned `claude` processes run inside the session and fire the dashboard's hooks like any other CLI session, so they show up in `/api/sessions`, the analytics, the Kanban board, and the Workflows page automatically. The PTY frames (terminal input/output deltas) are streamed to the client over `/ws-pty/:runId` (see `server/websocket.js`) at binary frame granularity rather than as JSON envelopes; the client's xterm.js terminal widget renders these raw PTY updates live |
|
||||
| `lib/pty-run.js` | PTY lifecycle for tmux-backed runs. Manages one tmux session per lane, named `agenthub-lane-<lane.id>`. Exports `startRun()` to create/attach a session and return a `runId` opaque handle; internally uses tmux to manage the pseudoterminal. Spawned `claude` processes run inside the session and fire the dashboard's hooks like any other CLI session, so they show up in `/api/sessions`, the analytics, the Kanban board, and the Workflows page automatically. The PTY frames (terminal input/output deltas) are streamed to the client over `/ws-pty/:runId` (see `server/websocket.js`) at binary frame granularity rather than as JSON envelopes; the client's xterm.js terminal widget renders these raw PTY updates live. Every spawn also mirrors itself into `dashboard_runs` (cwd, model, prompt preview, `resume_session_id`, lane id, start time) — that row is the ONLY source `publicRun` has for those fields, since the handle itself is recomputed from tmux on every read, so a dropped insert renders as a live run with no cwd, model or start date. `mode` is NOT NULL in that table and `recordRun` swallows insert errors by design, which is why this module passes a literal `"interactive"` rather than null. **Create-or-adopt has one refusal:** a pane already running an agent is adopted silently only when the request asked for nothing but a pane — a `resumeSessionId` or an initial prompt cannot be typed over a live agent, so it throws `ERUNLIVE` (409) rather than reporting a resume that never spawned |
|
||||
| `lib/pty-attach.js` | Client-side PTY attachment via WebSocket. Establishes a `/ws-pty/:runId` connection, receives binary PTY frames, and feeds them to an xterm.js terminal instance. Handles reconnection, resize events (sending `TIOCSWINSZ` ioctl to the tmux pane), and cleanup on disconnect. A single tmux session can have many simultaneous PTY clients (browser Workspace, `agenthub lanes shell` CLI, etc.), all synced live |
|
||||
| `routes/run.js` | HTTP surface for the tmux+PTY Run feature. **Same-origin guard** on every route — browser requests must come from a localhost-ish Origin (`localhost`, `127.0.0.1`, `::1`, `0.0.0.0`); missing-Origin (curl/CLI) requests pass. When `DASHBOARD_TOKEN` is configured it is **also** required on these routes (same as the rest of `/api/*`). `GET /api/run` lists all live runs (computed fresh from tmux state via `tmux list-sessions`). `GET /api/run/tmux` reports whether `tmux` is installed and on PATH (required for the feature to work). `GET /api/run/binary` probes whether `claude` is on `PATH`. `GET /api/run/cwds` suggests cwds (dashboard + home + recent from sessions table). `GET /api/run/history?laneId=...` returns persisted run history, optionally scoped to one lane. `GET /api/run/files?cwd=&q=` powers the Workspace page's `@`-file autocomplete: scoped fuzzy search inside `cwd` skipping `node_modules`, `.git`, `dist`, `build`, `.next`, `.cache`, `coverage`, `vendor`, etc., capped result count, ranked by basename match. `POST /api/run` requires `laneId` in the body and starts/attaches a tmux-backed run. `GET /api/run/:id` returns the run handle. `DELETE /api/run/:id` kills the tmux session (sends SIGTERM to the pane, escalates to SIGKILL after 5 s). The PTY frames are streamed to the client over `/ws-pty/:runId` as binary frames (not JSON), rendering a real interactive terminal in xterm.js on the Workspace page. `tmux` must be installed on the dashboard server's machine (same as better-sqlite3's native-module requirements) |
|
||||
| `routes/lanes.js` | Durable-lane API. `POST /api/lanes/worktree`, `PATCH /api/lanes/:id`, destructive actions, and `DELETE /api/lanes/:id` use the Run route's same-origin guard. Worktree provisioning validates an absolute source git repository, persists a managed lane as `provisioning`, returns `202`, then uses the per-lane lock to resolve the base and add the worktree. Completion broadcasts the existing `lane_update` payload as `idle`; a git failure leaves a row that the non-destructive delete route can forget. `GET /api/lanes/:id/preflight?action=reset\|remove\|purge` produces counted confirmation facts. Confirmed `POST /:id/{reset,remove,purge}` actions require a complete `expect`, run under the same lock, kill a recorded run and wait for the spawner's actual child-exit timestamp (or return `500 ERUNTIMEOUT` before git), clear `run_id`, reject changed facts with `409 ESTALE` including expected/current diagnostics, and require `force` for unpushed managed reset/remove work. Reset and managed removal call the worktree's independent managed-kind, realpath-within-`LANES_ROOT`, and listed-worktree guard; adopted reset is refused, while adopted remove only forgets its row and never modifies its directory, and a managed lane whose directory was deleted by hand takes a prune path that still enforces the managed-kind and inside-`LANES_ROOT` checks. `start` returns `409 ERUNLIVE` rather than overwriting a live `run_id` and orphaning its child. `kind`, `source_repo`, `slug`, `base_branch`, `slot` and `ports` are not patchable — provisioning writes them through `lanesLib.setProvisioningFacts`. Worktree provisioning also runs `lane-runtime.js:provisionLane` (A2) when the repo declares a `.agenthub/profile` — seed `.env`, `bootstrap`, create the database, migrate, seed — before the lane reports `idle`; `reset`/`remove` likewise call `resetLaneData`/`removeLaneData`, with `reset` accepting a body `keepDb: true` to skip the whole drop-recreate-migrate-reseed block. The runtime routes (`GET /:id/runtime`, `POST /:id/up`, `POST /:id/down`, `POST /:id/hook/:name`, `GET /:id/logs/:svc`) are registered **before** the `/:id/:action` catch-all so `up`/`down` are not swallowed as unknown actions, and are deliberately kept out of it: that catch-all drives a lane's Claude run, these drive the application the lane is working on. `GET /api/lanes/pipeline-stats` aggregates per-node pass counts over every lane and every archived feature. |
|
||||
@@ -1965,12 +1965,12 @@ These behaviors are reinforced by explicit `Cache-Control` headers from the prod
|
||||
|
||||
The Update Notifier tells the user when a newer **release** of the dashboard has been published, and — on an ordinary git checkout that can be fast-forwarded — can apply it on one click.
|
||||
|
||||
The version signal is the forge's own release list, read over REST at `/api/v1/repos/<owner>/<repo>/releases/latest` with the owner and repo derived from the `origin` remote URL (no hardcoded host, no credentials for a public repo). The published tag is compared against this install's `package.json` version. When no release can be read — a non-HTTP remote, an offline machine, a repo with no releases — detection falls back to the original commit count against the canonical default branch and puts the reason in `release_check`, so "up to date" never means "we couldn't look".
|
||||
The version signal is the forge's own release list, read over REST at `/api/v1/repos/<owner>/<repo>/releases/latest` (no hardcoded host, no credentials for a public repo). The owner and repo come from one of **two** sources, chosen by install kind: a checkout derives them from its `origin` remote; a plugin-cache install derives them from the marketplace manifest on disk (`pluginMarketplaceUrl`), because it has no remote to read — and often no `.git` at all, since a marketplace entry with `"source": "url"` (this project's own) makes Claude Code unpack an archive rather than clone. The published tag is compared against this install's `package.json` version. When no release can be read — a non-HTTP remote, an offline machine, a repo with no releases — detection falls back to the original commit count against the canonical default branch and puts the reason in `release_check`, so "up to date" never means "we couldn't look".
|
||||
|
||||
Two states the release model makes visible that a commit count cannot:
|
||||
|
||||
- **`dev_build`** — the install is strictly ahead of the newest release and missing nothing from it. It is a build off the branch, not a shipped version, and the Sidebar says so instead of "Up to date".
|
||||
- **`plugin_managed`** — the install runs from `~/.claude/plugins/cache/`. Claude Code owns that directory and replaces it wholesale, so `applyUpdate` will not rewrite it: it refuses with `reason: "plugin_managed"`, decided from the path before any status lookup so the refusal holds offline too. A self-pull would leave a cache directory whose name (a commit sha) no longer matched its contents. **The button still works here**, by a different route: `POST /api/updates/apply` catches that refusal and hands the job to the detached chain in `server/lib/plugin-update.js` — `claude plugin marketplace update <mkt>` → `claude plugin update <plugin>@<mkt> -y` → `plugin-bootstrap.js --force` **from the new cache directory**, which stops this server and starts the new one. It answers `200 {applied:true, mode:"plugin"}`. The one thing no background process can do is `/reload-plugins`: that is a REPL action scoped to the session that runs it, so an already-open Claude Code session still needs it for new skills/commands/hooks. The dashboard does not, because `plugin-bootstrap.js` derives `PLUGIN_ROOT` from its own `__dirname` rather than from `${CLAUDE_PLUGIN_ROOT}`.
|
||||
- **`plugin_managed`** — the install runs from `~/.claude/plugins/cache/`. Claude Code owns that directory and replaces it wholesale, so `applyUpdate` will not rewrite it: it refuses with `reason: "plugin_managed"`, decided from the path before any status lookup so the refusal holds offline too. A self-pull would leave a cache directory whose name (a commit sha) no longer matched its contents. **This branch is evaluated before the `.git` probe, and must stay there.** An archive-sourced cache directory is not a clone, so a `.git` check reached first answers "not a git clone; check manually" and skips the release layer entirely — which is exactly what 1.5.1 shipped: `update_available` pinned false however many releases were published, `plugin_marketplace`/`plugin_name` never set, so `/apply`'s plugin branch could never fire and its 409 claimed nothing newer was published. It reads as "up to date", so it stays invisible while the install happens to be current. **The button still works here**, by a different route: `POST /api/updates/apply` catches that refusal and hands the job to the detached chain in `server/lib/plugin-update.js` — `claude plugin marketplace update <mkt>` → `claude plugin update <plugin>@<mkt> -y` → `plugin-bootstrap.js --force` **from the new cache directory**, which stops this server and starts the new one. It answers `200 {applied:true, mode:"plugin"}`. The one thing no background process can do is `/reload-plugins`: that is a REPL action scoped to the session that runs it, so an already-open Claude Code session still needs it for new skills/commands/hooks. The dashboard does not, because `plugin-bootstrap.js` derives `PLUGIN_ROOT` from its own `__dirname` rather than from `${CLAUDE_PLUGIN_ROOT}`.
|
||||
|
||||
A **shallow clone** (`--depth`) is the third special case, and the plugin cache is one: history is grafted, so every commit-distance number is a graft artefact rather than a distance. All `commits_*_release` fields are `null` there and `dev_build` is never asserted; the version string is the only signal used.
|
||||
### Module Layout
|
||||
@@ -2057,7 +2057,7 @@ sequenceDiagram
|
||||
|
||||
| Component | Responsibility |
|
||||
| --- | --- |
|
||||
| **`server/lib/update-check.js`** | `getUpdatesStatus(root?, { skipFetch?, latestRelease? })` + `applyUpdate(root?)`. Runs every git call via `execFile` (no shell, 10s–120s timeouts) and reads the newest release over `fetch` with an `AbortSignal.timeout` — `fetchLatestRelease` NEVER throws, resolving to `{ok:false, reason}` (`no_remote`, `remote_not_http`, `no_releases`, `unreachable`, `bad_payload`, `http_<status>`) so a status poll degrades instead of erroring. `releaseApiUrl` derives the endpoint from the remote (https, scp-style and `ssh://` forms) and returns null for anything not owner/repo shaped, which is what keeps local-path remotes off the network entirely. `compareVersions` orders numeric triples and strips a leading `v`, since this repo carries both `v1.5.0` and `1.4.6`. `isShallowClone` gates every commit-distance calculation; `detectPluginInstall` reads the marketplace and plugin name out of the cache path. **Branch- and fork-aware** as before: resolves `<remote>/master`/`/main`/`/HEAD`, reads the current branch and its tracked upstream, and shapes `manual_command` per situation — the `claude plugin ...` commands for `plugin_managed`; `git fetch <remote> --tags && git merge --ff-only <tag>` for `release_available`; `git pull --ff-only` when the branch tracks the canonical ref; `git fetch <remote> && git merge --ff-only <ref>` for forks; `git fetch <remote>` only on a feature branch or detached HEAD. Non-git installs, missing remotes, fetch failures, and unresolvable upstream refs are returned as soft payloads — never throws. |
|
||||
| **`server/lib/update-check.js`** | `getUpdatesStatus(root?, { skipFetch?, latestRelease? })` + `applyUpdate(root?)`. Runs every git call via `execFile` (no shell, 10s–120s timeouts) and reads the newest release over `fetch` with an `AbortSignal.timeout` — `fetchLatestRelease` NEVER throws, resolving to `{ok:false, reason}` (`no_remote`, `remote_not_http`, `no_releases`, `unreachable`, `bad_payload`, `http_<status>`) so a status poll degrades instead of erroring. `releaseApiUrl` derives the endpoint from a repository URL (https, scp-style and `ssh://` forms) and returns null for anything not owner/repo shaped, which is what keeps local-path remotes off the network entirely. `fetchLatestRelease` finds that URL via the `origin` remote; `fetchReleaseFromUrl` takes one directly, which is how the **git-free plugin path** works: `pluginMarketplaceUrl(mkt, plugin)` reads `known_marketplaces.json` → the marketplace's `.claude-plugin/marketplace.json` → the entry's `source.url`, returning null (never a guessed host) for a `github` `owner/repo` shorthand and never throwing. **Order matters:** `detectPluginInstall` runs FIRST in `getUpdatesStatus`, ahead of the `.git` probe — a plugin cache unpacked from an archive has no `.git`, and probing first is the 1.5.1 bug that made `update_available` permanently false. `compareVersions` orders numeric triples and strips a leading `v`, since this repo carries both `v1.5.0` and `1.4.6`. `isShallowClone` gates every commit-distance calculation; `detectPluginInstall` reads the marketplace and plugin name out of the cache path. **Branch- and fork-aware** as before: resolves `<remote>/master`/`/main`/`/HEAD`, reads the current branch and its tracked upstream, and shapes `manual_command` per situation — the `claude plugin ...` commands for `plugin_managed`; `git fetch <remote> --tags && git merge --ff-only <tag>` for `release_available`; `git pull --ff-only` when the branch tracks the canonical ref; `git fetch <remote> && git merge --ff-only <ref>` for forks; `git fetch <remote>` only on a feature branch or detached HEAD. Non-git installs, missing remotes, fetch failures, and unresolvable upstream refs are returned as soft payloads — never throws. |
|
||||
| **`server/update-scheduler.js`** | Ticks the lib every `DASHBOARD_UPDATE_CHECK_INTERVAL_MS` (default 300 000, floor 60 000). First tick is scheduled 8s after server start with `.unref()` so it doesn't block shutdown. Broadcasts only when the fingerprint `{update_available, remote_sha, commits_behind, fetch_error, manual_command}` changes — `manual_command` is included so situation transitions (e.g. user switches branches, or adds an `upstream` remote) trigger a re-broadcast even when the SHA and commit count are unchanged. Emits a framed message to stdout on "up-to-date → behind" transitions, and only suggests "restart the dashboard" when the printed command actually rewrites the working tree. `DASHBOARD_UPDATE_CHECK=0\|false\|off` disables the scheduler entirely. |
|
||||
| **`server/routes/updates.js`** | Three endpoints: `GET /status` (read-only check), `POST /check` (check + broadcast), `POST /apply`. `/apply` has **two modes**, chosen by how this copy was installed, never by the request body: **checkout** — fast-forward onto the release tag, `npm run setup`, `npm run build` in production, then `scheduleRestart()`; **plugin** — `applyUpdate`'s `plugin_managed` refusal is caught and `schedulePluginUpdate()` runs instead, answering `200 {applied:true, mode:"plugin"}`. The plugin branch fires only when there is genuinely something to pull (`update_available` plus a marketplace and plugin name parsed from the cache path) — a `plugin_managed` refusal with nothing newer published stays a 409 rather than spawning a chain that would stop the server for nothing. Otherwise 409 `UPDATE_NOT_APPLICABLE` with `reason` `"up_to_date"`, `"not_fast_forwardable"`, or `"plugin_managed"`. Both modes write the response BEFORE anything stops the process. Mounted under `/api/*`, so all three ride the default loopback bind as their trust boundary and are gated by `DASHBOARD_TOKEN` when one is set. |
|
||||
| **`server/lib/plugin-update.js`** + **`scripts/plugin-update-helper.js`** | The plugin-cache update chain. The lib only spawns the helper detached (cwd = the runtime dir, **not** the plugin root, which is about to be superseded) and clears any previous verdict first so a stale success can't be read back as this run's result. All work is in the helper because its last step SIGTERMs the server that asked for the update — the same split as `self-restart.js`, one step further. The helper re-validates the marketplace and plugin names against `/^[A-Za-z0-9][\w.-]*$/` (they reach an argv across a process boundary), resolves `claude` on PATH or at `~/.local/bin/claude` (a hook-spawned server does not inherit the login shell's PATH), picks the newest cache directory that isn't the old root and does contain `scripts/plugin-bootstrap.js`, and records **every** outcome — including an unexpected throw — to `plugin-update.json` under `~/.claude/agenthub/runtime/`, outside the cache so it survives the swap. Steps: `validate`, `resolve_claude`, `marketplace_update`, `plugin_update`, `already_current` (`ok:true`; nothing was pulled and the old server was left running), `bootstrap`, `done`. `readLastPluginUpdate()` surfaces it as `last_plugin_update` on the status payload — without it a failed chain is indistinguishable from a slow one. |
|
||||
@@ -2126,7 +2126,8 @@ The same shape is used by `GET /status`, `POST /check`, and the `update_status`
|
||||
|
||||
| Condition | Returned payload | User-visible effect |
|
||||
| --- | --- | --- |
|
||||
| Not a git clone | `{git_repo:false, update_available:false, message:"Install directory is not a git clone..."}` | Modal suppressed (`update_available` false). Sidebar stays neutral. |
|
||||
| Not a git clone (and not a plugin cache) | `{git_repo:false, update_available:false, message:"Install directory is not a git clone..."}` | Modal suppressed (`update_available` false). Sidebar stays neutral. |
|
||||
| Plugin cache with no `.git` (archive-sourced marketplace entry) | `{git_repo:false, install_kind:"plugin", release_check:"ok", latest_release:"vX.Y.Z", update_available:<version compare>}` | Checked normally: the repo URL comes from the marketplace manifest and `package.json` is the only local signal. The `notGit` note is suppressed and **Update now** is offered. |
|
||||
| No remotes configured | `{git_repo:true, update_available:false, message:"No git remotes configured..."}` | Same as above. |
|
||||
| `git fetch` failed (offline, auth) | `{git_repo:true, update_available:false, canonical_remote, fetch_error:"<stderr>"}` | Sidebar button goes amber; modal stays suppressed until a successful check. |
|
||||
| Canonical default branch unresolvable | `{git_repo:true, update_available:false, canonical_remote, message:"Could not resolve <remote>/master..."}` | Modal suppressed. |
|
||||
@@ -2137,8 +2138,10 @@ The same shape is used by `GET /status`, `POST /check`, and the `update_status`
|
||||
| Newer release, ordinary checkout | `{update_available:true, situation:"release_available", latest_release:"vX.Y.Z", manual_command:"...git fetch origin --tags && git merge --ff-only vX.Y.Z..."}` | Modal opens titled with the release version, links its notes, and shows **Update now**. |
|
||||
| Newer release, plugin-cache install | `{update_available:true, situation:"plugin_managed", install_kind:"plugin", plugin_marketplace:"sg", plugin_name:"agenthub", manual_command:"claude plugin marketplace update sg && ..."}` | Modal opens WITH **Update now**; `POST /apply` answers `200 {applied:true, mode:"plugin"}` and the detached chain pulls the new version and re-bootstraps. The modal notes that an already-open Claude Code session still needs `/reload-plugins` for new skills/commands. |
|
||||
| Plugin chain ran but nothing was published | `{last_plugin_update:{ok:true, step:"already_current"}}` | The old server keeps running, untouched; no restart, no error banner. |
|
||||
| Plugin chain mid-handover | `{last_plugin_update:{ok:true, step:"bootstrap", note:"the new plugin version is installed; the server is being handed over"}}` | Written BEFORE the handover on purpose: that step retires the process tree the helper hangs off, and a helper killed there would otherwise leave `last_plugin_update: null` for an update that succeeded. Overwritten by `done` when the helper survives. |
|
||||
| Plugin chain failed (no `claude` on PATH, `npm ci` broke, bootstrap died) | `{last_plugin_update:{ok:false, step:"resolve_claude"\|"plugin_update"\|"bootstrap", error:"..."}}` | Danger banner in the modal naming the failed step. A `bootstrap` failure means the old server was already stopped, so the verdict says to run `/agenthub-update` to recover — and it is read back by whichever server comes up next, because it lives outside the cache. |
|
||||
| Plugin `/apply` with nothing newer published | 409 `{reason:"plugin_managed"}` | No chain is spawned. Message points at `/agenthub-update` to force a refresh. |
|
||||
| Plugin `/apply` with nothing newer published | 409 `{reason:"plugin_managed", release_check:"ok"}` | No chain is spawned. Message names the newest release and points at `/agenthub-update` to force a refresh. |
|
||||
| Plugin `/apply` after a failed release check | 409 `{reason:"plugin_managed", release_check:"unreachable"\|"no_local_version"\|...}` | No chain is spawned, and the message says the check did not succeed rather than claiming nothing newer exists — an unknown reported as a negative is how a broken check looks identical to an up-to-date install. |
|
||||
| Healthy, behind, on canonical branch | `{update_available:true, situation:"tracking_canonical", manual_command:"...git pull --ff-only..."}` | Modal opens with `git pull` flow + restart hint. |
|
||||
| Healthy, behind, fork (origin = fork, upstream = canonical) | `{update_available:true, situation:"fork_or_diverged_tracking", manual_command:"...git fetch upstream && git merge --ff-only upstream/master..."}` | Modal opens with merge flow + restart hint + `situation_note` explaining the divergence. |
|
||||
| Healthy, behind, on a feature branch | `{update_available:true, situation:"feature_branch", manual_command:"...git fetch <remote>"}` | Modal opens; `situation_note` explains the user is off the canonical branch; restart hint suppressed because the working tree isn't being changed. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Claude Code Working Guide
|
||||
|
||||
_Last synced: eb63569 (2026-09-10) + release-based update detection (`server/lib/update-check.js` reads the forge releases API; a `plugin_managed` install self-updates via the detached `plugin-update` chain) + the install-wide **Update all** batch and session reload (`server/lib/cc-update-all.js`, `server/lib/cc-reload.js`)._ A change that makes any statement in this file, `AGENTS.md`, or a README wrong — a moved path, a new or changed extension point, a retired rule — updates that file in the same change-set and bumps this marker.
|
||||
_Last synced: v1.5.6 (2026-09-11) + the systemd handover rule below (`scripts/systemd-service.js`'s `writeUserService`/`restartUserService` split and `plugin-bootstrap.js`'s deferred `pendingSystemdRestart`) + eb63569 (2026-09-10) + release-based update detection (`server/lib/update-check.js` reads the forge releases API — a checkout via its `origin` remote, a plugin-cache install via the marketplace manifest on disk, since an archive-sourced cache dir has no `.git`; a `plugin_managed` install self-updates via the detached `plugin-update` chain) + the install-wide **Update all** batch and session reload (`server/lib/cc-update-all.js`, `server/lib/cc-reload.js`)._ A change that makes any statement in this file, `AGENTS.md`, or a README wrong — a moved path, a new or changed extension point, a retired rule — updates that file in the same change-set and bumps this marker.
|
||||
|
||||
## Project mission
|
||||
- Maintain a reliable local-first dashboard for Claude Code session monitoring.
|
||||
@@ -43,6 +43,7 @@ A **lane** is a durable unit of parallel agent work — one working directory, m
|
||||
See `docs/LANES.md` for full guide: stage reporting, custom templates, lane actions, and the five node states.
|
||||
|
||||
## Non-negotiable engineering rules
|
||||
- **When a `agenthub.service` unit of ours owns the server, nothing else may stop it.** The bootstrap that performs a self-update is spawned by the running server, so it lives in that server's systemd cgroup: SIGTERM-ing the server from there exits 0 (which `Restart=on-failure` read as "meant to stop") AND trips `KillMode=control-group`, reaping the bootstrap before it can repoint the unit or write `state.json` — a dashboard dead after every update until some later session bootstrapped again. So `scripts/systemd-service.js` splits the API: `writeUserService` repoints the unit and starts NOTHING, `restartUserService` uses `--no-block`, and `plugin-bootstrap.js` defers that restart past `writeState` and `releaseLock` (`pendingSystemdRestart`). The unit is `Restart=always`. Do not add a path that stops the dashboard from inside its own cgroup, and do not move the restart earlier. `agenthub service install` may keep using `installUserService` — it runs from a user's shell, outside the cgroup. `systemdOwned` additionally requires the unit to be ACTIVE (an installed-but-stopped unit owns nothing; treating it as owner skips the stop and then binds an occupied port). A unit naming a RETIRED plugin root is invisible until a reboot, so `fastPathOk` rejects it via `unitIsStale` (pure fs — that path may never spawn a process) and the bootstrap rewrites it; repairing the unit is NOT restarting the server (`pendingSystemdRestart = systemdOwned && needsServer`), and the detached-spawn fallback is guarded by `needsServer` so a stale unit alone never starts a second server onto a bound port.
|
||||
- **A session reload is typed into a live pane, never spawned.** `/reload-plugins` and `/reload-skills` are scoped BY CLAUDE CODE to the session that runs them, so nothing can reload a session from the outside. `server/lib/cc-reload.js` therefore types them into the dashboard's existing tmux lane panes and spawns NO `claude` process — a one-shot `claude -p "/reload-plugins"` reloads only its own short-lived session, exits, and leaves a junk session in the dashboard's own history. Do not add a path that starts a session in order to reload one.
|
||||
- Preserve existing behavior unless explicitly asked to change it.
|
||||
- Prefer minimal, reversible diffs.
|
||||
|
||||
+74
-1
@@ -30,12 +30,64 @@ dashboard, run it from source, or stay on Node 20.
|
||||
| Node.js | 20+ (22+ recommended) | Required for server and client |
|
||||
| npm | 9+ | Comes with Node.js |
|
||||
| Claude Code | 2.x+ | Required for hook integration |
|
||||
| Git | Any | Cloning the repository, and every lane operation (worktrees, branch/status reads) |
|
||||
| **tmux** | 3.x | **Required for the run console** — the browser terminal, `agenthub lanes shell`, typing `/reload-plugins` into a live pane, and the Codex nudge. See [Step 0](#step-0--system-packages) |
|
||||
| Codex CLI | Any | Optional — only for lanes whose tool is `codex` |
|
||||
| GitHub CLI (`gh`) | Any | Optional — only for `agenthub lanes ci status` and the PR stages of `/agenthub:ship-full` |
|
||||
| Python | 3.6+ | Optional — only for `scripts/expand-ts-module-docs.py` (doc generation) |
|
||||
| Git | Any | For cloning the repository |
|
||||
| `superpowers` plugin | Any | Optional — required only by `/agenthub:ship-feature` and `/agenthub:ship-feature-lane`, which drive its skills step by step (and which the built-in pipeline templates name as their per-node commands). Nothing else in AgentHub needs it; `/agenthub-doctor` reports it as `WARN` when absent. **Installed automatically** by the plugin's `SessionStart` bootstrap (opt out with `AGENTHUB_AUTO_INSTALL_PLUGINS=0`); by hand: `claude plugin install superpowers@claude-plugins-official` |
|
||||
|
||||
---
|
||||
|
||||
## Step 0 — System packages
|
||||
|
||||
Node and npm are not enough: `git` backs every lane operation, and **`tmux`
|
||||
backs the run console**. The dashboard shells out to the `tmux` binary and has
|
||||
no bundled fallback, so without it **Start Run** and `agenthub lanes shell`
|
||||
fail while everything else keeps working.
|
||||
|
||||
```bash
|
||||
sudo apt install git tmux # Debian / Ubuntu
|
||||
sudo dnf install git tmux # Fedora / RHEL
|
||||
brew install git tmux # macOS
|
||||
sudo pacman -S git tmux # Arch
|
||||
```
|
||||
|
||||
Windows has no native tmux. Run AgentHub under **WSL2** and install it inside
|
||||
the WSL distro — a tmux from Git Bash or MSYS is not what the server executes.
|
||||
|
||||
Check it:
|
||||
|
||||
```bash
|
||||
tmux -V # e.g. tmux 3.4
|
||||
git --version
|
||||
node -v # v20.x / v22.x / v24.x
|
||||
```
|
||||
|
||||
Once the server is up you can ask it directly — this is the same probe the
|
||||
dashboard uses:
|
||||
|
||||
```bash
|
||||
curl -s localhost:4820/api/run/tmux # {"available":true}
|
||||
```
|
||||
|
||||
**No configuration is needed.** AgentHub creates its own session per lane,
|
||||
named `agenthub-lane-<id>`, and never reads your `~/.tmux.conf` for anything it
|
||||
depends on (mouse mode is set on the session explicitly). You can attach to the
|
||||
exact same pane from a normal terminal:
|
||||
|
||||
```bash
|
||||
agenthub lanes shell # from inside the lane's directory
|
||||
tmux attach -t agenthub-lane-7 # or by name
|
||||
tmux ls # every dashboard session is prefixed agenthub-lane-
|
||||
```
|
||||
|
||||
Detaching is `Ctrl-b d` — it leaves the run alive, which is the whole point:
|
||||
the browser terminal and your local terminal are two clients on one pane, and
|
||||
restarting the dashboard never stops a run.
|
||||
|
||||
---
|
||||
|
||||
## Step 1 — Clone the repository
|
||||
|
||||
```bash
|
||||
@@ -261,6 +313,27 @@ npm run setup
|
||||
|
||||
The Vite dev server and Express server run on different ports. Make sure both are running (`npm run dev` starts both). Open **http://localhost:5173**, not `http://localhost:4820`, during development.
|
||||
|
||||
### "Start Run" fails, or the terminal never attaches
|
||||
|
||||
The run console is tmux-backed. Check, in this order:
|
||||
|
||||
```bash
|
||||
tmux -V # not installed → see Step 0
|
||||
curl -s localhost:4820/api/run/tmux # {"available":false} → the SERVER cannot see tmux
|
||||
curl -s "localhost:4820/api/run/binary?tool=claude" # {"found":true,"path":"…"}
|
||||
```
|
||||
|
||||
`{"available":false}` while your own shell finds tmux means the server runs with
|
||||
a different `PATH` — most often a systemd `--user` service, which does not read
|
||||
your shell profile. Fix it by installing tmux system-wide (`/usr/bin/tmux`)
|
||||
rather than into a shell-managed prefix, then `agenthub service uninstall &&
|
||||
agenthub service install`.
|
||||
|
||||
The same `PATH` rule applies to `claude` and `codex`: a run starts the binary by
|
||||
name, so a `claude` installed only through an interactive shell's profile is
|
||||
invisible to a service-managed server. `{"found":false}` for the lane's tool is
|
||||
that case.
|
||||
|
||||
### No sessions appearing after starting Claude Code
|
||||
|
||||
See [SETUP.md — Troubleshooting](./SETUP.md#troubleshooting) for detailed hook debugging steps.
|
||||
|
||||
@@ -13,10 +13,24 @@ Internal build — all rights reserved.
|
||||
|
||||
*(Tiếng Việt: [README.vi.md](README.vi.md))*
|
||||
|
||||
## What it does
|
||||
## Main features
|
||||
|
||||
**Observe**
|
||||
|
||||
- **Sessions, agents, events.** Everything Claude Code emits, recorded and
|
||||
searchable: tool calls, token usage, cost, subagent trees, transcripts.
|
||||
- **Analytics and cost.** Per-model token totals and estimated cost, with
|
||||
editable pricing rules; top tools, agent types, and workflow patterns.
|
||||
- **Activity feed and alerts.** A live event stream, alert rules, and webhook
|
||||
targets that fire on them.
|
||||
- **History import.** Every session under `~/.claude/projects/` is imported on
|
||||
startup; archives from another machine come in through Settings → Import
|
||||
History (idempotent, never double-counts tokens).
|
||||
- **Remote sources.** Pull session history from other machines over SSH
|
||||
(`agenthub remote-sources`).
|
||||
|
||||
**Drive**
|
||||
|
||||
- **Lanes.** One lane per working directory, surviving session restarts. A lane
|
||||
moves through pipeline stages and the dashboard shows where it is.
|
||||
- **Stage detection.** The stage is inferred from the tool stream, so a session
|
||||
@@ -26,15 +40,72 @@ Internal build — all rights reserved.
|
||||
PTY, rendered with xterm.js) attached to a lane's directory — the exact TUI
|
||||
you'd see locally, fully interactive, resumable, and attachable from a real
|
||||
terminal too via `agenthub lanes shell`. Which CLI it starts is the lane's own
|
||||
setting.
|
||||
- **Analytics (in-dashboard tab), alerts, and a workflow view**, plus a CLI.
|
||||
setting. **This is the part that needs `tmux` installed** — see
|
||||
[Prerequisites](#prerequisites).
|
||||
- **Per-lane app stacks.** A repo that declares `.agenthub/profile/` gets its own
|
||||
slot, ports and services per lane (`agenthub lanes up|down|logs`).
|
||||
- **Ship pipelines.** `/agenthub:ship-full` and `/agenthub:ship-quick` drive a
|
||||
feature from intake to PR, declaring every stage to the dashboard as it goes.
|
||||
|
||||
## Requirements
|
||||
**Configure**
|
||||
|
||||
Node **>= 20** (`engines` in `package.json`). Node **24** is what the test suites
|
||||
are verified on — node 25 currently breaks 6 server tests through a
|
||||
- **Claude Code + Codex configuration explorer.** Settings hosts one panel per
|
||||
tool: every plugin, skill, subagent, slash command, MCP server, hook, settings
|
||||
file, memory file, marketplace, keybinding and statusline Claude Code knows
|
||||
about — read for all of them, edit/create/delete for the text-file surfaces
|
||||
(skills, agents, commands, output styles, `CLAUDE.md`). Plugins, MCP, hooks and
|
||||
`settings.json` stay read-only: they race with the live CLI.
|
||||
- **Updates.** Release-based update detection with an in-UI **Update all**
|
||||
(marketplaces → every plugin → AgentHub last → one session reload).
|
||||
- **A CLI for all of it** (`agenthub`, plus `agenthub repl`), a PWA install, and
|
||||
a UI in English, Vietnamese, Chinese and Korean.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
| Need | Version | Required for |
|
||||
|---|---|---|
|
||||
| **Node.js** | >= 20 (>= 22.5 for a plugin install) | Everything. Both suites are verified green on **24** and **26** |
|
||||
| **npm** | 9+ | Ships with Node |
|
||||
| **git** | any | Cloning, and every lane operation (worktrees, branch/status reads) |
|
||||
| **tmux** | 3.x | The browser run console, `agenthub lanes shell`, typing `/reload-plugins` into a live pane, the Codex nudge |
|
||||
| **Claude Code** | 2.x | Hook ingestion — the whole monitoring side |
|
||||
| **Codex CLI** | any | Optional — only for `codex` lanes |
|
||||
| **GitHub CLI (`gh`)** | any | Optional — only for `agenthub lanes ci status` and the PR stages of the ship pipelines |
|
||||
| **systemd (user)** | — | Optional — only for `agenthub service install` (Linux auto-start on boot) |
|
||||
|
||||
Node **25** is the one version to avoid: it breaks 6 server tests through a
|
||||
better-sqlite3 ABI mismatch and 20 client tests through a global `localStorage`
|
||||
change.
|
||||
change. Both were gone again by 26 (1712 server + 488 client tests green on
|
||||
v26.8.1).
|
||||
|
||||
### Installing tmux
|
||||
|
||||
The dashboard shells out to the `tmux` binary; there is no bundled fallback, so
|
||||
**Start Run** and `agenthub lanes shell` fail without it. Everything else
|
||||
(sessions, analytics, lanes, stage detection, the CLI) works fine.
|
||||
|
||||
```bash
|
||||
sudo apt install tmux # Debian / Ubuntu
|
||||
sudo dnf install tmux # Fedora / RHEL
|
||||
brew install tmux # macOS
|
||||
sudo pacman -S tmux # Arch
|
||||
```
|
||||
|
||||
Windows has no native tmux — run AgentHub under WSL2 and install it there.
|
||||
|
||||
Verify, both from your shell and from the server's point of view:
|
||||
|
||||
```bash
|
||||
tmux -V # e.g. tmux 3.4
|
||||
curl -s localhost:4820/api/run/tmux # {"available":true}
|
||||
```
|
||||
|
||||
A lane's run lives in a tmux session named `agenthub-lane-<id>`, so the browser
|
||||
terminal and a local `tmux attach -t agenthub-lane-<id>` (or `agenthub lanes
|
||||
shell`) are two clients on the same pane — they stay in sync, and killing the
|
||||
dashboard never kills the run.
|
||||
|
||||
### The superpowers plugin
|
||||
|
||||
The **`superpowers` plugin is required by the ship-feature pipelines only**, not
|
||||
by the dashboard. `/agenthub:ship-feature` and `/agenthub:ship-feature-lane` drive
|
||||
|
||||
+93
-7
@@ -13,10 +13,24 @@ Internal build — all rights reserved.
|
||||
|
||||
*(Bản dịch tiếng Việt của [README.md](README.md), tham khảo — README.md gốc là bản chính thức.)*
|
||||
|
||||
## Làm được gì
|
||||
## Chức năng chính
|
||||
|
||||
**Quan sát**
|
||||
|
||||
- **Session, agent, event.** Mọi thứ Claude Code emit ra, ghi lại và tìm kiếm
|
||||
được: tool call, token usage, cost, cây subagent, transcript.
|
||||
- **Analytics và chi phí.** Token và cost ước tính theo từng model, với bảng
|
||||
pricing sửa được; top tool, agent type và workflow pattern.
|
||||
- **Activity feed và alert.** Luồng event trực tiếp, alert rule, và webhook
|
||||
target bắn khi rule khớp.
|
||||
- **Import lịch sử.** Mọi session dưới `~/.claude/projects/` được import lúc
|
||||
khởi động; lịch sử từ máy khác đưa vào qua Settings → Import History
|
||||
(idempotent, không bao giờ đếm trùng token).
|
||||
- **Remote source.** Kéo lịch sử session từ máy khác qua SSH
|
||||
(`agenthub remote-sources`).
|
||||
|
||||
**Điều khiển**
|
||||
|
||||
- **Lane.** Mỗi working directory một lane, sống sót qua session restart. Lane
|
||||
đi qua các pipeline stage và dashboard hiển thị nó đang ở đâu.
|
||||
- **Stage detection.** Stage được suy luận (infer) từ tool stream, nên một
|
||||
@@ -26,14 +40,86 @@ Internal build — all rights reserved.
|
||||
- **Chạy Claude Code hoặc Codex từ trình duyệt.** Một terminal thật (tmux + PTY
|
||||
thật, render bằng xterm.js) gắn vào thư mục của lane — đúng cái TUI bạn thấy ở
|
||||
máy, tương tác đầy đủ, resume được, và attach được từ terminal thật qua
|
||||
`agenthub lanes shell`. Chạy CLI nào là thiết lập riêng của từng lane.
|
||||
- **Analytics (tab trong dashboard), alert và workflow view**, cộng thêm CLI.
|
||||
`agenthub lanes shell`. Chạy CLI nào là thiết lập riêng của từng lane. **Đây
|
||||
chính là phần cần cài `tmux`** — xem [Yêu cầu hệ thống](#yêu-cầu-hệ-thống).
|
||||
- **App stack riêng cho từng lane.** Repo khai báo `.agenthub/profile/` thì mỗi
|
||||
lane được cấp slot, port và service riêng (`agenthub lanes up|down|logs`).
|
||||
- **Ship pipeline.** `/agenthub:ship-full` và `/agenthub:ship-quick` đưa một
|
||||
feature từ intake tới PR, khai báo từng stage về dashboard trên đường đi.
|
||||
|
||||
## Yêu cầu
|
||||
**Cấu hình**
|
||||
|
||||
Node **>= 20** (`engines` trong `package.json`). Node **24** là bản test suite
|
||||
được verify — node 25 hiện đang làm gãy 6 test server do lệch ABI
|
||||
`better-sqlite3` và 20 test client do thay đổi global `localStorage`.
|
||||
- **Trình khám phá cấu hình Claude Code + Codex.** Trang Settings có một panel
|
||||
cho mỗi tool: mọi plugin, skill, subagent, slash command, MCP server, hook,
|
||||
settings file, memory file, marketplace, keybinding và statusline mà Claude
|
||||
Code biết — đọc được tất cả, còn sửa/tạo/xóa thì chỉ cho các bề mặt dạng file
|
||||
text (skill, agent, command, output style, `CLAUDE.md`). Plugin, MCP, hook và
|
||||
`settings.json` để read-only: chúng tranh ghi với CLI đang chạy.
|
||||
- **Cập nhật.** Phát hiện bản mới dựa trên release, kèm nút **Update all** ngay
|
||||
trong UI (marketplace → mọi plugin → AgentHub sau cùng → reload session).
|
||||
- **CLI cho toàn bộ** (`agenthub`, và `agenthub repl`), cài được như PWA, UI có
|
||||
tiếng Anh, Việt, Trung và Hàn.
|
||||
|
||||
## Yêu cầu hệ thống
|
||||
|
||||
| Cần | Phiên bản | Dùng cho |
|
||||
|---|---|---|
|
||||
| **Node.js** | >= 20 (>= 22.5 nếu cài qua plugin) | Tất cả. Cả hai test suite verify xanh trên Node **24** và **26** |
|
||||
| **npm** | 9+ | Đi kèm Node |
|
||||
| **git** | bất kỳ | Clone repo, và mọi thao tác lane (worktree, đọc branch/status) |
|
||||
| **tmux** | 3.x | Run console trên trình duyệt, `agenthub lanes shell`, gõ `/reload-plugins` vào pane đang sống, nhắc nhở Codex |
|
||||
| **Claude Code** | 2.x | Hook ingestion — toàn bộ phần monitoring |
|
||||
| **Codex CLI** | bất kỳ | Tùy chọn — chỉ cho lane dùng `codex` |
|
||||
| **GitHub CLI (`gh`)** | bất kỳ | Tùy chọn — chỉ cho `agenthub lanes ci status` và các stage PR của ship pipeline |
|
||||
| **systemd (user)** | — | Tùy chọn — chỉ cho `agenthub service install` (tự khởi động khi boot, Linux) |
|
||||
|
||||
Node **25** là bản duy nhất nên tránh: nó làm gãy 6 test server do lệch ABI
|
||||
`better-sqlite3` và 20 test client do thay đổi global `localStorage`. Tới 26 thì
|
||||
cả hai đã hết (1712 test server + 488 test client xanh trên v26.8.1).
|
||||
|
||||
### Cài tmux
|
||||
|
||||
Dashboard gọi thẳng binary `tmux`, không có bản dự phòng đi kèm, nên thiếu nó
|
||||
thì **Start Run** và `agenthub lanes shell` sẽ lỗi. Phần còn lại (session,
|
||||
analytics, lane, stage detection, CLI) vẫn chạy bình thường.
|
||||
|
||||
```bash
|
||||
sudo apt install tmux # Debian / Ubuntu
|
||||
sudo dnf install tmux # Fedora / RHEL
|
||||
brew install tmux # macOS
|
||||
sudo pacman -S tmux # Arch
|
||||
```
|
||||
|
||||
Windows không có tmux native — chạy AgentHub trong WSL2 và cài tmux ở trong đó.
|
||||
|
||||
Kiểm tra, cả từ shell của bạn lẫn từ góc nhìn của server:
|
||||
|
||||
```bash
|
||||
tmux -V # ví dụ: tmux 3.4
|
||||
curl -s localhost:4820/api/run/tmux # {"available":true}
|
||||
```
|
||||
|
||||
Mỗi lane chạy trong một tmux session tên `agenthub-lane-<id>`, nên terminal
|
||||
trên trình duyệt và `tmux attach -t agenthub-lane-<id>` (hoặc `agenthub lanes
|
||||
shell`) ở máy là hai client trên cùng một pane — chúng đồng bộ với nhau, và tắt
|
||||
dashboard không bao giờ giết run đang chạy. Detach bằng `Ctrl-b d`.
|
||||
|
||||
### Plugin superpowers
|
||||
|
||||
Plugin **`superpowers` chỉ cần cho ship-feature pipeline**, không cần cho
|
||||
dashboard. `/agenthub:ship-feature` và `/agenthub:ship-feature-lane` lái các skill
|
||||
của nó theo từng phase. Thiếu nó thì dashboard, hook và CLI vẫn chạy bình thường
|
||||
— chỉ hai skill pipeline là dừng giữa chừng; `/agenthub-doctor` báo dòng `WARN`.
|
||||
|
||||
**Bình thường bạn không phải tự cài.** Bootstrap `SessionStart` của plugin cài
|
||||
giúp một lần trong worker chạy nền, và session hiện tại cần `/reload-plugins`
|
||||
thì skill mới resolve được (session sau tự nhận). Cài tay:
|
||||
|
||||
```bash
|
||||
claude plugin install superpowers@claude-plugins-official
|
||||
```
|
||||
|
||||
Đặt `AGENTHUB_AUTO_INSTALL_PLUGINS=0` để tắt cài tự động.
|
||||
|
||||
## Cài như Claude Code plugin
|
||||
|
||||
|
||||
@@ -324,6 +324,26 @@ The SQLite database uses WAL mode with a 5-second busy timeout. If you see lock
|
||||
|
||||
---
|
||||
|
||||
### The run console won't start a run / the terminal never attaches
|
||||
|
||||
Runs are tmux-backed: the server executes the `tmux` binary and has no fallback.
|
||||
|
||||
```bash
|
||||
tmux -V # missing → sudo apt install tmux
|
||||
curl -s http://localhost:4820/api/run/tmux # {"available":true}
|
||||
curl -s "http://localhost:4820/api/run/binary?tool=claude" # {"found":true,"path":"…"}
|
||||
```
|
||||
|
||||
`{"available":false}` while your own shell finds tmux means the **server's**
|
||||
`PATH` differs from yours — typically a systemd `--user` service, which never
|
||||
reads your shell profile. Install tmux system-wide (`/usr/bin/tmux`) and
|
||||
re-run `agenthub service uninstall && agenthub service install`. The same
|
||||
applies to `claude` / `codex`: a run launches them by name.
|
||||
|
||||
Install instructions per OS: [INSTALL.md → Step 0](./INSTALL.md#step-0--system-packages).
|
||||
|
||||
---
|
||||
|
||||
### No sessions appearing after starting Claude Code
|
||||
|
||||
**Check 1 — Is the server running?**
|
||||
|
||||
+22
-2
@@ -1195,7 +1195,10 @@ async function cmdUpdateCheck() {
|
||||
// sees the same fresh result via the update_status websocket broadcast.
|
||||
const s = await post("/api/updates/check");
|
||||
heading("Dashboard updates", s.repo_root || baseUrl());
|
||||
if (!s.git_repo) {
|
||||
// A plugin-cache install legitimately has no clone (an archive-sourced
|
||||
// marketplace entry unpacks one), yet it IS checkable and updatable via the
|
||||
// release API — so only a genuine non-git checkout bails out here.
|
||||
if (!s.git_repo && s.install_kind !== "plugin") {
|
||||
console.log(`${c.yellow("○")} ${s.message}`);
|
||||
return;
|
||||
}
|
||||
@@ -1276,6 +1279,23 @@ async function cmdDoctor() {
|
||||
);
|
||||
console.log(`${c.green("✔")} WS connections ${srv.ws_connections ?? 0}`);
|
||||
|
||||
// Asked of the SERVER, not of this shell: a run is a tmux session the server
|
||||
// spawns, so the only PATH that decides whether Start Run works is its own —
|
||||
// a systemd --user service never reads your shell profile. Missing tmux is a
|
||||
// warning, not a failure: it costs the run console and `lanes shell`, nothing
|
||||
// else.
|
||||
try {
|
||||
const { available } = await get("/api/run/tmux");
|
||||
console.log(
|
||||
available
|
||||
? `${c.green("✔")} tmux available to the server`
|
||||
: `${c.yellow("!")} tmux not on the server's PATH — Start Run and \`agenthub lanes shell\` will fail. ` +
|
||||
`Install it (sudo apt install tmux / brew install tmux), then restart the server`
|
||||
);
|
||||
} catch {
|
||||
console.log(`${c.dim("·")} tmux not reported by this server`);
|
||||
}
|
||||
|
||||
try {
|
||||
const { sources = [] } = await get("/api/remote-sources");
|
||||
if (sources.length === 0) {
|
||||
@@ -2992,7 +3012,7 @@ const COMMAND_GROUPS = [
|
||||
[
|
||||
"Administration",
|
||||
[
|
||||
["doctor", "", "Connectivity, hooks, database, and remote sources diagnosis"],
|
||||
["doctor", "", "Connectivity, hooks, database, tmux, and remote sources diagnosis"],
|
||||
["info", "", "Raw system info JSON"],
|
||||
["export", "[file.json]", "Export all data as JSON"],
|
||||
["cleanup", "--hours N --days M", "Abandon stale / purge old sessions"],
|
||||
|
||||
@@ -372,7 +372,7 @@ export function UpdateNotifier() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!status.git_repo ? (
|
||||
{!status.git_repo && status.install_kind !== "plugin" ? (
|
||||
<div className="text-xs text-fg-secondary bg-surface-2 border border-border rounded-lg px-3 py-2">
|
||||
{t("notGit")}
|
||||
</div>
|
||||
|
||||
@@ -114,6 +114,29 @@ describe("UpdateNotifier — Update now", () => {
|
||||
expect(screen.getByText(i18n.t("updates:pluginAutoNote"))).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("still offers the button when a plugin install has no git clone at all", async () => {
|
||||
// The 1.5.1 bug: an archive-sourced marketplace entry leaves no .git, so
|
||||
// git_repo is legitimately false. Gating the UI on that reported "not a git
|
||||
// clone; check manually" for an install the dashboard can check AND update.
|
||||
statusMock.mockResolvedValue({
|
||||
...BASE_STATUS,
|
||||
git_repo: false,
|
||||
situation: "plugin_managed",
|
||||
install_kind: "plugin",
|
||||
plugin_marketplace: "sg",
|
||||
plugin_name: "agenthub",
|
||||
commits_behind: 0,
|
||||
local_version: "1.5.1",
|
||||
release_check: "ok",
|
||||
latest_release: "v1.6.0",
|
||||
});
|
||||
render(<UpdateNotifier />);
|
||||
|
||||
await screen.findByText(i18n.t("updates:releaseTitle", { version: "v1.6.0" }));
|
||||
expect(screen.getByText(i18n.t("updates:updateNow"))).toBeInTheDocument();
|
||||
expect(screen.queryByText(i18n.t("updates:notGit"))).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("surfaces a previous plugin chain's failure so a dead update isn't silent", async () => {
|
||||
statusMock.mockResolvedValue({
|
||||
...BASE_STATUS,
|
||||
|
||||
@@ -521,14 +521,17 @@ function UnifiedRunRowView({
|
||||
}) {
|
||||
const { t } = useTranslation("run");
|
||||
const startedDate = new Date(row.startedAt);
|
||||
const startedLabel = isNaN(startedDate.getTime())
|
||||
? "-"
|
||||
: startedDate.toLocaleString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
// 0 is "unknown", not the epoch — a run whose persisted row is missing has no
|
||||
// start time, and printing "Jan 1, 08:00 AM" for it reads as real data.
|
||||
const startedLabel =
|
||||
!row.startedAt || isNaN(startedDate.getTime())
|
||||
? "-"
|
||||
: startedDate.toLocaleString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
// Without mode distinction, offer resume for any finished run with a session.
|
||||
// An external session is live but has no attachable tmux session, so Resume
|
||||
// (a new tmux-backed `claude --resume` in its cwd) is what it gets instead.
|
||||
|
||||
@@ -242,6 +242,14 @@ describe("ActiveRunsSwitcher", () => {
|
||||
expect(screen.queryByText(i18n.t("run:runs.externalBadge"))).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a dash, not the epoch, for a row with no start time", () => {
|
||||
// A run whose persisted row is missing arrives with startedAt 0. Rendering
|
||||
// that as "Jan 1, 08:00 AM" presents a gap in the data as real data.
|
||||
renderModal([row("no-start", { startedAt: 0 })]);
|
||||
expect(screen.getByText("-")).toBeTruthy();
|
||||
expect(screen.queryByText(/Jan 1,/)).toBeNull();
|
||||
});
|
||||
|
||||
it("fires attach with the run id of the row that was clicked", () => {
|
||||
const { spies } = renderSwitcher();
|
||||
openModal();
|
||||
|
||||
@@ -9537,7 +9537,7 @@ exports[`screen snapshots > Settings 1`] = `
|
||||
<p
|
||||
class="text-[10px] text-status-warning/90 mt-1"
|
||||
>
|
||||
UI build v1.5.1 (rebuild client to match)
|
||||
UI build v1.5.8 (rebuild client to match)
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
|
||||
+3
-1
@@ -245,7 +245,9 @@ All fields are optional. The tool (CLI invoked) comes from the lane itself, neve
|
||||
- **`approval`** — one of `on-request` or `never`, or omitted/empty for no approval prompt. Passed to `codex -a <value>`.
|
||||
- **`resumeSessionId`** or **`resumeLast: true`** — resume an earlier run instead of starting new. For Codex lanes specifically, `resumeLast: true` uses `codex resume --last`; `resumeSessionId` uses `codex resume <sessionId>`. For Claude lanes, `resumeSessionId` re-attaches a Claude session by id.
|
||||
|
||||
Error `409 ERUNLIVE` is returned if the lane already has a live run; stop it first with the `stop` action.
|
||||
Error `503 ETMUXMISSING` is returned when the host has no `tmux` binary. Every run the dashboard starts is a tmux session, so this is a missing dependency rather than a bad request — the message carries the install command, and the same code comes back from `POST /api/run`. Nothing else in the dashboard is affected.
|
||||
|
||||
Error `409 ERUNLIVE` is returned if the lane already has a live run; stop it first with the `stop` action. The same code and status come back when the lane's tmux pane is already running an agent while a `prompt` or `resumeSessionId` was sent — that argv cannot be typed over a live agent, so the request is refused instead of answered 200 with nothing done. A start that asks for neither still adopts the existing pane silently.
|
||||
|
||||
#### Preflight a destructive lane action
|
||||
|
||||
|
||||
+2
-2
@@ -272,12 +272,12 @@ Because a lane's services are fully detached, restarting the dashboard (or `agen
|
||||
|
||||
| Command | Description |
|
||||
| ------- | ----------- |
|
||||
| `agenthub doctor` | Diagnosis: API reachability, hook installation status + path, database path/size/row counts, server uptime and Node version, WS connections |
|
||||
| `agenthub doctor` | Diagnosis: API reachability, hook installation status + path, database path/size/row counts, server uptime and Node version, WS connections, whether `tmux` is on **the server's** PATH (asked via `GET /api/run/tmux` — a systemd `--user` service does not read your shell profile), remote-source status |
|
||||
| `agenthub info` | The raw `/api/settings/info` JSON (pipe it to `jq`) |
|
||||
| `agenthub export [file.json]` | Full JSON data export (sessions, agents, events, tokens, workflows, dashboard runs, alert rules, pricing) — defaults to a dated filename. Re-importable via `agenthub import-data` |
|
||||
| `agenthub cleanup --hours N --days M` | Abandon active sessions idle for `N` hours and/or purge completed sessions older than `M` days |
|
||||
| `agenthub reinstall-hooks` | Rewrite the Claude Code hook entries in `~/.claude/settings.json` |
|
||||
| `agenthub update-check` | Ask the server whether a newer **release** has been published, read from the forge's own releases API (derived from the `origin` remote); falls back to a commit count against the canonical remote when no release can be read, with the reason in `release_check`. Prints the release tag against the running version, a situation note for fork/feature-branch checkouts, and the **copy-paste update command**. Reports `dev_build` when the install is ahead of the newest release, and `plugin_managed` for an install under `~/.claude/plugins/cache/`. The dashboard UI can self-apply either kind (`POST /api/updates/apply`): a fast-forwardable checkout is fast-forwarded onto the release tag, rebuilt and self-restarted; a plugin install is handed to a detached `claude plugin marketplace update` → `claude plugin update` → `plugin-bootstrap.js --force` chain instead. `/agenthub-update` remains the manual equivalent, and an already-open Claude Code session still needs `/reload-plugins` to pick up new skills and commands. Also refreshes the update banner in any open dashboard tab (same `update_status` broadcast) |
|
||||
| `agenthub update-check` | Ask the server whether a newer **release** has been published, read from the forge's own releases API (a checkout derives the repo from its `origin` remote; a plugin-cache install, which has no clone and often no `.git` at all, derives it from the marketplace manifest on disk); falls back to a commit count against the canonical remote when no release can be read, with the reason in `release_check`. Prints the release tag against the running version, a situation note for fork/feature-branch checkouts, and the **copy-paste update command**. Reports `dev_build` when the install is ahead of the newest release, and `plugin_managed` for an install under `~/.claude/plugins/cache/`. The dashboard UI can self-apply either kind (`POST /api/updates/apply`): a fast-forwardable checkout is fast-forwarded onto the release tag, rebuilt and self-restarted; a plugin install is handed to a detached `claude plugin marketplace update` → `claude plugin update` → `plugin-bootstrap.js --force` chain instead. `/agenthub-update` remains the manual equivalent, and an already-open Claude Code session still needs `/reload-plugins` to pick up new skills and commands. Also refreshes the update banner in any open dashboard tab (same `update_status` broadcast) |
|
||||
| `agenthub clear-data --yes` | Delete **all** data (schema preserved). Refuses to run without `--yes` |
|
||||
| `agenthub open` | Open the dashboard in your default browser (`open` / `xdg-open` / `start`) |
|
||||
| `agenthub version` | Print the agenthub version (also `--version` / `-v`) |
|
||||
|
||||
+9
-1
@@ -139,6 +139,11 @@ graph TB
|
||||
|
||||
- Node.js >= 20.0.0
|
||||
- npm >= 9.0.0
|
||||
- git — every lane operation shells out to it
|
||||
- tmux — only for the browser run console and `agenthub lanes shell`; both
|
||||
execute the binary directly and have no fallback. Per-OS install commands and
|
||||
the two-sided check (your PATH vs the server's) are in
|
||||
[INSTALL.md → Step 0](../INSTALL.md#step-0--system-packages).
|
||||
|
||||
### Setup
|
||||
|
||||
@@ -451,7 +456,10 @@ Environment=NODE_ENV=production
|
||||
Environment=PORT=4820
|
||||
Environment=DASHBOARD_DB_PATH=/var/lib/agenthub/dashboard.db
|
||||
ExecStart=/usr/bin/node server/index.js
|
||||
Restart=on-failure
|
||||
# `always`, not `on-failure`: a graceful SIGTERM exits 0, which `on-failure`
|
||||
# reads as "meant to stop" — one stray kill and the dashboard stays down.
|
||||
# `systemctl stop` still stops it. Same reasoning as the plugin's own unit.
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
+65
-5
@@ -1,6 +1,6 @@
|
||||
# AgentHub — Plugin Marketplace
|
||||
|
||||
Official Claude Code plugins for the Agent Monitor dashboard. The **`agenthub`** plugin _is_ the dashboard — hooks, server, `agenthub` CLI and MCP tools, no checkout required. On top of it, **10 focused plugins** extend Claude Code with skills, agents, slash commands, hooks, and CLI tools for deep analytics, cost guardrails, productivity automation, developer tools, AI-powered insights, session forensics, workflow/fleet intelligence, reliability & SLOs, config & memory governance, and dashboard connectivity.
|
||||
Official Claude Code plugins for the Agent Monitor dashboard. The **`agenthub`** plugin _is_ the dashboard — hooks, server and the `agenthub` CLI, no checkout required. (It shipped an MCP server until `c7dbaf2`, which dropped it; the dashboard reads Claude Code's MCP configuration in the config explorer but no longer serves one.) On top of it, **10 focused plugins** extend Claude Code with skills, agents, slash commands, hooks, and CLI tools for deep analytics, cost guardrails, productivity automation, developer tools, AI-powered insights, session forensics, workflow/fleet intelligence, reliability & SLOs, config & memory governance, and dashboard connectivity.
|
||||
|
||||
Every plugin is powered by the local Agent Monitor REST API at `http://localhost:4820`. They are read-only advisors unless a skill explicitly documents a mutating endpoint (and those preview + confirm before acting).
|
||||
|
||||
@@ -134,7 +134,7 @@ waits on an install:
|
||||
4. **Install** — `npm install --omit=dev --ignore-scripts` into the runtime dir (never into the plugin cache, which is garbage-collected and replaced on every update). `--ignore-scripts` keeps the root `postinstall` from pulling the whole Vite client toolchain.
|
||||
5. **Legacy hook cleanup** — see above.
|
||||
6. **CLI** — write the `~/.local/bin/agenthub` launcher, never clobbering a `agenthub` the bootstrap did not write.
|
||||
7. **UI build** — `client/` is copied into the runtime dir and built there (`npm install && npm run build`), landing in `runtime/client-dist` — the same directory the server serves from. Skipped when a bundle for the current version already exists; a failure here does not fail the bootstrap (API and MCP still work, and `/agenthub-open` can retry) but does mean `/run` 404s until it's fixed.
|
||||
7. **UI build** — `client/` is copied into the runtime dir and built there (`npm ci --include=dev`, falling back to `npm install --include=dev`, then `npm run build`), landing in `runtime/client-dist` — the same directory the server serves from. `--include=dev` is required, not tidy: the entire build toolchain (`vite`, `typescript`, `@vitejs/plugin-react`, `tailwindcss`, `@types/*`) is a devDependency, and npm reads an inherited `NODE_ENV=production` as `--omit=dev`. Every bootstrap descended from the running server carries that env — the self-update chain, and any `SessionStart` fired by a `claude` inside a tmux pane the server started — so without the flag the install drops `vite` and the build dies on missing types. Skipped when a bundle for the current version already exists; a failure here does not fail the bootstrap (the API still works, and `/agenthub-open` can retry) but does mean `/run` 404s until it's fixed — and when a bundle from the PREVIOUS version is still on disk the failure is quieter still: the dashboard keeps serving the old UI against the new API, visible only as the Settings page's `UI build vX (rebuild client to match)` line.
|
||||
8. **Server** — on Linux with `systemd --user` available, install/refresh a
|
||||
`agenthub.service` unit (see [Auto-start on boot](#auto-start-on-boot)) instead
|
||||
of a bare spawn, so the server is supervised and comes back after a reboot
|
||||
@@ -144,6 +144,9 @@ waits on an install:
|
||||
`client-dist` — scoped to this session, same as before this fell back to
|
||||
systemd.
|
||||
9. **Record state** — `runtime/state.json`.
|
||||
10. **Hand over to systemd** — only when a unit of ours already owns the server
|
||||
(see [Who may stop the server](#who-may-stop-the-server)). Deliberately
|
||||
after step 9.
|
||||
|
||||
The first run takes a few minutes — most of it is the UI build, which is what
|
||||
makes client-only routes (`http://localhost:4820/run`, and every other page)
|
||||
@@ -172,11 +175,68 @@ On macOS, Windows, or a Linux box without systemd, nothing changes: the
|
||||
server is a detached spawn started fresh on the next `SessionStart` after a
|
||||
reboot, same as always.
|
||||
|
||||
### Who may stop the server
|
||||
|
||||
**When a `agenthub.service` unit of ours exists, nothing else may stop the
|
||||
dashboard.** The bootstrap that performs a self-update is spawned by the
|
||||
running server, so it lives inside that server's systemd cgroup. SIGTERM-ing
|
||||
the server from there breaks two ways at once:
|
||||
|
||||
- the server exits **0**, and the unit's old `Restart=on-failure` read a clean
|
||||
exit as "meant to stop" — so systemd did not bring it back;
|
||||
- `KillMode=control-group` (systemd's default) reaps **every** process in the
|
||||
cgroup when the main process exits, including the bootstrap itself — mid-run,
|
||||
before it could repoint the unit at the new plugin root or write
|
||||
`runtime/state.json`.
|
||||
|
||||
The result was a dashboard that went down on every self-update and stayed down
|
||||
until some later Claude Code session happened to bootstrap again, leaving a
|
||||
stale `.bootstrap.lock` and a `state.json` still naming the previous version.
|
||||
|
||||
So the order is fixed, and `scripts/systemd-service.js` splits its API to
|
||||
enforce it:
|
||||
|
||||
| Situation | What the bootstrap does |
|
||||
|---|---|
|
||||
| A unit of ours owns the server (`unitIsOurs`) | Never stops it. `writeUserService` repoints the unit at the new plugin root **without starting anything**, the rest of the bootstrap runs, state is written, the lock is released — and only then `restartUserService` asks systemd to restart, with `--no-block` so being killed by its own request costs nothing. |
|
||||
| No unit, or a foreign one | Unchanged: stop the old server, then `installUserService` (or a detached spawn where there is no systemd). Nothing here is inside a unit's cgroup, so the stop is safe. |
|
||||
|
||||
The unit is written with **`Restart=always`**, not `on-failure`: a graceful
|
||||
SIGTERM from anything at all would otherwise leave the dashboard down for good.
|
||||
An explicit `systemctl stop` — which is what `agenthub service uninstall` and
|
||||
the Settings panel do — still stops it.
|
||||
|
||||
`agenthub service install` (the checkout path) keeps using `installUserService`:
|
||||
it runs from your own shell, outside the unit's cgroup, so it may block and
|
||||
start in one step.
|
||||
|
||||
**A unit pointing at a retired plugin root repairs itself on the next session.**
|
||||
This is the residue an interrupted update leaves behind, and it is invisible
|
||||
while the dashboard is up: the server runs fine, every doctor row reads OK, and
|
||||
then a reboot starts a cache directory Claude Code deleted during the update —
|
||||
so the dashboard never comes back, for a reason nothing recorded. The fast path
|
||||
therefore checks it (`unitIsStale`, pure fs — it may not spawn a process on
|
||||
every `SessionStart`) and refuses to short-circuit, and the bootstrap rewrites
|
||||
the unit.
|
||||
|
||||
Repairing the *unit* is not restarting the *server*: when the running server is
|
||||
current and healthy, the corrected unit is simply left to take effect at the
|
||||
next start (`pendingSystemdRestart = systemdOwned && needsServer`). Restarting
|
||||
a working dashboard to fix a file that only matters at boot would be churn the
|
||||
user feels for nothing. For the same reason the detached-spawn fallback is
|
||||
guarded by `needsServer` — entering that branch for a stale unit alone would
|
||||
start a second server onto a port the live one already holds.
|
||||
|
||||
`systemdOwned` requires the unit to be **active**, not merely present: an
|
||||
installed-but-stopped unit owns nothing, and treating it as the owner would
|
||||
skip the stop and then ask systemd to bind an occupied port — a crash loop,
|
||||
courtesy of `Restart=always`.
|
||||
|
||||
### Commands
|
||||
|
||||
| Command | Does |
|
||||
|---|---|
|
||||
| `/agenthub-doctor` | Node version, bootstrap state, runtime deps, server liveness, duplicate hooks, CLI launcher + PATH, **skill plugins** (see below), MCP build freshness, UI bundle |
|
||||
| `/agenthub-doctor` | Node version, bootstrap state, runtime deps, server liveness, duplicate hooks, CLI launcher + PATH, **systemd** (`WARN` when the unit names a retired plugin root — the dashboard will not survive a reboot — or when it is installed but stopped; no unit at all is fine), **tmux** (`WARN` when absent — only the run console, `agenthub lanes shell` and session reloads need it), **skill plugins** (see below), UI bundle |
|
||||
| `/agenthub-update` | Pull the latest `agenthub` release via `claude plugin marketplace update` + `claude plugin update agenthub@<marketplace> -y`, then reinstall dependencies and restart the server (`plugin-bootstrap.js --force`). The plugin pull needs a manual `/reload-plugins` afterward to take effect in the current session — not scriptable from a command. |
|
||||
| `/agenthub-open` | Rebuild the UI bundle and print the dashboard URL. Re-runs the bootstrap first when the server is down or still executing a plugin root that a mid-session `/plugin` update retired, so a fresh bundle never talks to an older server's routes |
|
||||
| `/ship-full <requirement>` | Put the lane on the 16-node `ship-feature` template, then run `/agenthub:ship-feature-lane` **in this session**. The in-session twin of `agenthub ship-full` (which spawns its own `claude` from a terminal) |
|
||||
@@ -268,8 +328,8 @@ not assumed. It does **not**:
|
||||
For a clean machine, do all of this yourself:
|
||||
|
||||
```bash
|
||||
# 1. Stop the server. On Linux, check for the systemd unit first — a bare
|
||||
# `kill` just gets restarted by it (Restart=on-failure).
|
||||
# 1. Stop the server. On Linux, disable the systemd unit FIRST — the unit is
|
||||
# Restart=always, so a bare `kill` is always undone by systemd.
|
||||
systemctl --user disable --now agenthub.service 2>/dev/null
|
||||
rm -f ~/.config/systemd/user/agenthub.service && systemctl --user daemon-reload 2>/dev/null
|
||||
# Fallback for a detached (non-systemd) server, or if the unit above was absent:
|
||||
|
||||
+6
-4
@@ -70,10 +70,12 @@ graph LR
|
||||
|
||||
**Quick Start:**
|
||||
|
||||
1. Read [SETUP.md](../SETUP.md)
|
||||
2. Run `npm run setup`
|
||||
3. Run `npm run dev`
|
||||
4. Open browser to `http://localhost:5173`
|
||||
1. Install the system packages — `node` (20+), `git`, and `tmux` (the run
|
||||
console has no fallback without it): [INSTALL.md → Step 0](../INSTALL.md#step-0--system-packages)
|
||||
2. Read [SETUP.md](../SETUP.md)
|
||||
3. Run `npm run setup`
|
||||
4. Run `npm run dev`
|
||||
5. Open browser to `http://localhost:5173`
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-2
@@ -3,7 +3,7 @@
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: Agent Dashboard for Claude Code API
|
||||
version: 1.5.1
|
||||
version: 1.5.8
|
||||
description: HTTP API for real-time Claude Code session monitoring, agent lifecycle tracking, analytics, pricing, hooks ingestion, and workflow intelligence.
|
||||
contact:
|
||||
name: Nguyễn Ngọc Trí Vĩ
|
||||
@@ -6807,7 +6807,7 @@ paths:
|
||||
schema:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
description: 'applied: false plus reason: "up_to_date" | "not_fast_forwardable" | "plugin_managed". plugin_managed appears here only when a plugin-cache install has nothing newer published; when a newer release exists the plugin chain runs and the answer is 200 instead. Run /agenthub-update to force a refresh.'
|
||||
description: 'applied: false plus reason: "up_to_date" | "not_fast_forwardable" | "plugin_managed". plugin_managed appears here only when a plugin-cache install has nothing to pull: either release_check is "ok" and the published release is already installed, or the release check did not succeed (the message says which — an unknown is never reported as "nothing newer"). When a newer release exists the plugin chain runs and the answer is 200 instead. Run /agenthub-update to force a refresh.'
|
||||
'500':
|
||||
description: Update apply failed
|
||||
content:
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "1.5.1",
|
||||
"version": "1.5.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "agenthub",
|
||||
"version": "1.5.1",
|
||||
"version": "1.5.8",
|
||||
"hasInstallScript": true,
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "1.5.1",
|
||||
"version": "1.5.8",
|
||||
"bin": {
|
||||
"agenthub": "bin/agenthub.js"
|
||||
},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
description: Diagnose a plugin-installed AgentHub — Node, npm, disk, bootstrap, server, hooks, CLI, UI build
|
||||
description: Diagnose a plugin-installed AgentHub — Node, npm, disk, bootstrap, server, hooks, CLI, systemd, tmux, UI build
|
||||
---
|
||||
|
||||
Run the diagnostic and report what it found. Do not fix anything unless the user
|
||||
@@ -31,6 +31,16 @@ Print the output verbatim, then add at most three lines of guidance based on the
|
||||
means that attempt has not run or did not succeed — say `/agenthub-update` retries
|
||||
it, and print the `claude plugin install …` line from the output as the manual
|
||||
route.
|
||||
- `WARN systemd` → when it says the unit names a **previous plugin version**,
|
||||
the dashboard is running now but will NOT come back after a reboot. Starting
|
||||
a new Claude Code session repairs it; print the `--force` command from the
|
||||
output as the immediate fix. "installed but not running" just needs
|
||||
`systemctl --user start agenthub`.
|
||||
- `WARN tmux` → only the run console, `agenthub lanes shell` and the
|
||||
session-reload keystrokes are affected; monitoring, lanes and the CLI are not.
|
||||
Print the install command from the output. If the row says `ok` but Start Run
|
||||
still fails, the server has a different PATH than this check — ask it directly
|
||||
with `curl -s localhost:4820/api/run/tmux`.
|
||||
- `WARN Dashboard UI` → run `/agenthub-open` to build the bundle. When the row
|
||||
quotes a build error, report that error — it is the actual problem.
|
||||
|
||||
|
||||
+86
-25
@@ -107,6 +107,12 @@ function fastPathOk(rt = runtimeDir()) {
|
||||
// pipelines drive. Reading one recorded flag keeps this hot path cheap — the
|
||||
// actual check (manifest + every user SKILL.md) runs once, in the worker.
|
||||
if (!state.skillPluginsSettled) return false;
|
||||
// A live server says nothing about whether it will come back. When our unit
|
||||
// still names a previous plugin cache directory, everything looks healthy
|
||||
// until the next reboot — and then the dashboard is simply gone, from a path
|
||||
// Claude Code deleted long ago. Reading one file is cheap enough for a hot
|
||||
// path; `unitIsStale` deliberately spawns nothing.
|
||||
if (require("./systemd-service").unitIsStale("agenthub", PLUGIN_ROOT)) return false;
|
||||
return serverIsLive();
|
||||
}
|
||||
|
||||
@@ -465,6 +471,11 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
return "locked";
|
||||
}
|
||||
|
||||
// Declared out here because the restart it guards has to happen in the
|
||||
// `finally`, after the lock is released and the state is on disk: it is the
|
||||
// step that may cost this process its own life.
|
||||
let pendingSystemdRestart = false;
|
||||
|
||||
try {
|
||||
const wantDeps = depsHash();
|
||||
const state = readState(rt) || {};
|
||||
@@ -504,44 +515,85 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
log(rt, "built the dashboard UI bundle");
|
||||
}
|
||||
|
||||
const svc = require("./systemd-service");
|
||||
// Who owns the running server decides how it may be retired. A unit of
|
||||
// ours means systemd owns it — and this process is a descendant of that
|
||||
// server, so it sits in the unit's cgroup. SIGTERM-ing the main process
|
||||
// there does two fatal things at once: the clean exit(0) tells systemd
|
||||
// "meant to stop", and `KillMode=control-group` reaps this bootstrap
|
||||
// before it can write state or point the unit at the new cache dir. That
|
||||
// is the bug that left a dashboard dead after every self-update until the
|
||||
// next Claude Code session happened to bootstrap again.
|
||||
// ACTIVE matters, not merely present: a unit of ours that is installed but
|
||||
// stopped owns nothing right now. If a detached server is holding the port
|
||||
// in that state, treating systemd as the owner would skip the stop and then
|
||||
// ask systemd to start a second server onto a bound port — a crash loop,
|
||||
// courtesy of Restart=always.
|
||||
const systemdOwned =
|
||||
svc.systemctlAvailable() && svc.unitIsOurs("agenthub") && svc.unitIsActive("agenthub");
|
||||
|
||||
// After a plugin update the running server executes code from a cache
|
||||
// directory Claude Code has already discarded — retire it first.
|
||||
// directory Claude Code has already discarded — retire it first. Only
|
||||
// when nothing else owns its lifecycle; otherwise systemd retires it, in
|
||||
// one restart job, once everything below is durable.
|
||||
const movedRoot = force || (state.pluginRoot && state.pluginRoot !== PLUGIN_ROOT);
|
||||
if (movedRoot && stopDashboard()) {
|
||||
if (movedRoot && !systemdOwned && stopDashboard()) {
|
||||
log(rt, "stopped the server started from the previous plugin version");
|
||||
waitForPortsFree();
|
||||
}
|
||||
|
||||
if (movedRoot || !serverIsLive()) {
|
||||
const svc = require("./systemd-service");
|
||||
const result = svc.systemctlAvailable()
|
||||
? svc.installUserService({
|
||||
name: "agenthub",
|
||||
description: "AgentHub dashboard server (Claude Code plugin)",
|
||||
workingDir: PLUGIN_ROOT,
|
||||
execStart: `${process.execPath} ${path.join(PLUGIN_ROOT, "server", "index.js")}`,
|
||||
env: {
|
||||
NODE_ENV: "production",
|
||||
NODE_PATH: path.join(rt, "node_modules"),
|
||||
DASHBOARD_CLIENT_DIST: path.join(rt, "client-dist"),
|
||||
// systemd --user units get systemd's own minimal PATH, not the
|
||||
// shell's — forward it so the server can find `claude`/`codex`.
|
||||
PATH: process.env.PATH || "",
|
||||
},
|
||||
})
|
||||
: "unavailable";
|
||||
// Two different needs, deliberately not collapsed. `needsServer` is "the
|
||||
// running process must be replaced"; `unitStale` is "the unit names a cache
|
||||
// directory that is no longer this one", which is invisible until a reboot
|
||||
// and must be repaired even while a perfectly healthy server is up.
|
||||
const needsServer = movedRoot || !serverIsLive();
|
||||
const unitStale = svc.unitIsStale("agenthub", PLUGIN_ROOT);
|
||||
if (needsServer || unitStale) {
|
||||
const unit = {
|
||||
name: "agenthub",
|
||||
description: "AgentHub dashboard server (Claude Code plugin)",
|
||||
workingDir: PLUGIN_ROOT,
|
||||
execStart: `${process.execPath} ${path.join(PLUGIN_ROOT, "server", "index.js")}`,
|
||||
env: {
|
||||
NODE_ENV: "production",
|
||||
NODE_PATH: path.join(rt, "node_modules"),
|
||||
DASHBOARD_CLIENT_DIST: path.join(rt, "client-dist"),
|
||||
// systemd --user units get systemd's own minimal PATH, not the
|
||||
// shell's — forward it so the server can find `claude`/`codex`.
|
||||
PATH: process.env.PATH || "",
|
||||
},
|
||||
};
|
||||
// Two shapes of the same step. When systemd already owns the server the
|
||||
// unit is only REWRITTEN here — pointing at the new plugin root — and
|
||||
// the restart is deferred to `pendingSystemdRestart` below, because
|
||||
// starting it now would kill this process mid-bootstrap. Otherwise
|
||||
// there is no cgroup to be reaped by, and install-and-start is fine.
|
||||
const result = systemdOwned
|
||||
? svc.writeUserService(unit)
|
||||
: svc.systemctlAvailable()
|
||||
? svc.installUserService(unit)
|
||||
: "unavailable";
|
||||
if (result === "written" || result === "unchanged") {
|
||||
if (result === "written") svc.enableLinger();
|
||||
// Only when the RUNNING process has to change. A stale unit beside a
|
||||
// healthy server is now corrected on disk and left to take effect at
|
||||
// the next start — restarting a working dashboard to fix a file that
|
||||
// only matters at boot would be churn the user feels for no reason.
|
||||
pendingSystemdRestart = systemdOwned && needsServer;
|
||||
log(
|
||||
rt,
|
||||
result === "written"
|
||||
? "installed a systemd --user service — the dashboard now survives reboots without Claude Code"
|
||||
: "systemd --user service already up to date"
|
||||
result === "unchanged"
|
||||
? "systemd --user service already up to date"
|
||||
: unitStale && !needsServer
|
||||
? "repointed the systemd --user service at the current plugin version (it named a retired one)"
|
||||
: "installed a systemd --user service — the dashboard now survives reboots without Claude Code"
|
||||
);
|
||||
} else {
|
||||
} else if (needsServer) {
|
||||
// No systemd (macOS/Windows/WSL without it), or the unit exists but
|
||||
// wasn't ours to touch — same detached-spawn fallback as before,
|
||||
// scoped to this session only.
|
||||
// scoped to this session only. Guarded by `needsServer`: entering this
|
||||
// block for a stale unit alone must never spawn a second server onto
|
||||
// the port the live one already holds.
|
||||
const pid = startDashboard(rt);
|
||||
log(
|
||||
rt,
|
||||
@@ -572,6 +624,15 @@ function bootstrap(rt = runtimeDir(), { force = false } = {}) {
|
||||
return "ok";
|
||||
} finally {
|
||||
releaseLock(rt);
|
||||
// LAST, and after the lock: systemd stops the old main process to start
|
||||
// the new one, and this process shares its cgroup, so it may not outlive
|
||||
// this call. Everything that had to be durable already is — the state
|
||||
// file is written and the lock is gone, so even being killed here leaves
|
||||
// no debris and no half-recorded bootstrap.
|
||||
if (pendingSystemdRestart) {
|
||||
log(rt, "handing the server over to systemd (restarting the unit)");
|
||||
require("./systemd-service").restartUserService("agenthub");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
* npm, free disk on the data dir, bootstrap state, runtime dependencies (every
|
||||
* declared package, not just that node_modules exists), server liveness,
|
||||
* duplicate hook entries (the one failure that silently doubles every token and
|
||||
* cost figure), the `agenthub` CLI launcher and its PATH, whether the slash
|
||||
* cost figure), the `agenthub` CLI launcher and its PATH, the `tmux` binary
|
||||
* every browser-started run depends on, whether the slash
|
||||
* commands the pipeline templates name as node drivers are actually resolvable
|
||||
* (the `superpowers` plugin, today), and the dashboard bundle — quoting the last
|
||||
* build error when it is missing.
|
||||
@@ -82,6 +83,8 @@ function diagnose() {
|
||||
);
|
||||
|
||||
add(...cliStatus());
|
||||
add(...systemdStatus());
|
||||
add(...tmuxStatus());
|
||||
add(...skillPluginStatus());
|
||||
|
||||
add(...dashboardUiStatus(rt));
|
||||
@@ -218,6 +221,76 @@ function skillPluginStatus() {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The failure this row exists for is silent by construction: a unit still
|
||||
* naming a retired plugin cache directory keeps a running dashboard looking
|
||||
* perfectly healthy, and only bites at the next reboot — when the server does
|
||||
* not come back, from a path Claude Code deleted weeks earlier. Nothing else
|
||||
* in this report would show it.
|
||||
*
|
||||
* WARN, never FAIL: the dashboard in front of you is working, and on macOS,
|
||||
* Windows or a Linux box without systemd there is no unit to have an opinion
|
||||
* about.
|
||||
*/
|
||||
function systemdStatus() {
|
||||
const svc = require("./systemd-service");
|
||||
const unit = svc.unitPath("agenthub");
|
||||
|
||||
if (!svc.unitIsOurs("agenthub")) {
|
||||
if (fs.existsSync(unit)) {
|
||||
return ["warn", "systemd", `${unit} exists but was not written by AgentHub — left untouched`];
|
||||
}
|
||||
return [
|
||||
"ok",
|
||||
"systemd",
|
||||
svc.systemctlAvailable()
|
||||
? "no unit — the server is started per session (install one with `agenthub service install`)"
|
||||
: "not available on this platform — the server is started per session",
|
||||
];
|
||||
}
|
||||
|
||||
if (svc.unitIsStale("agenthub", PLUGIN_ROOT)) {
|
||||
return [
|
||||
"warn",
|
||||
"systemd",
|
||||
`${unit} still points at a previous plugin version — the dashboard will NOT come back after a reboot. ` +
|
||||
`Starting a new Claude Code session repairs it; or run: node ${path.join(PLUGIN_ROOT, "scripts", "plugin-bootstrap.js")} --force`,
|
||||
];
|
||||
}
|
||||
|
||||
if (!svc.unitIsActive("agenthub")) {
|
||||
return [
|
||||
"warn",
|
||||
"systemd",
|
||||
"unit is installed and current but not running — start it with `systemctl --user start agenthub`",
|
||||
];
|
||||
}
|
||||
return ["ok", "systemd", "unit is current and running — the dashboard survives reboots"];
|
||||
}
|
||||
|
||||
/**
|
||||
* WARN (never FAIL) when `tmux` is absent: every run the dashboard starts is a
|
||||
* tmux session (`server/lib/tmux.js`), so without the binary the run console,
|
||||
* `agenthub lanes shell` and the session-reload keystrokes all fail — while
|
||||
* sessions, analytics, lanes and the CLI keep working. Same reasoning as the
|
||||
* skill-plugins row: a partial feature loss must not fail a doctor run.
|
||||
*
|
||||
* This checks the doctor's own PATH. A server started as a systemd `--user`
|
||||
* service can still see a different one — `GET /api/run/tmux` is the server's
|
||||
* own answer, and `agenthub doctor` reports that.
|
||||
*/
|
||||
function tmuxStatus() {
|
||||
if (require("../server/lib/tmux").isTmuxAvailable()) {
|
||||
return ["ok", "tmux", "on PATH — the run console can start sessions"];
|
||||
}
|
||||
return [
|
||||
"warn",
|
||||
"tmux",
|
||||
"not found — Start Run and `agenthub lanes shell` will fail (everything else is unaffected). " +
|
||||
"Install it: sudo apt install tmux / brew install tmux (Windows: run AgentHub under WSL2)",
|
||||
];
|
||||
}
|
||||
|
||||
function countLegacyHookEntries() {
|
||||
try {
|
||||
const settings = JSON.parse(fs.readFileSync(getSettingsPath(), "utf8"));
|
||||
|
||||
+11
-1
@@ -73,7 +73,17 @@ function buildClient({
|
||||
// tarball against the lockfile's integrity hash, so a bad cache entry is
|
||||
// refetched instead of silently reused. It needs a lockfile that matches
|
||||
// package.json — fall back to `install` when the copy has none or has drifted.
|
||||
const npmFlags = ["--no-audit", "--no-fund"];
|
||||
//
|
||||
// `--include=dev` is not optional here: the whole build toolchain (vite,
|
||||
// typescript, @vitejs/plugin-react, tailwindcss, @types/*) lives in the
|
||||
// client's devDependencies, and npm reads `NODE_ENV=production` as
|
||||
// `--omit=dev`. Every bootstrap descended from the running server inherits
|
||||
// that NODE_ENV — the self-update chain and any SessionStart fired from a
|
||||
// tmux pane the server started — so the install silently dropped `vite`,
|
||||
// `npm run build` failed, and the PREVIOUS bundle stayed in place: the
|
||||
// dashboard kept serving the old version's UI while the API was already the
|
||||
// new one. An explicit CLI flag outranks the env, which is the point.
|
||||
const npmFlags = ["--no-audit", "--no-fund", "--include=dev"];
|
||||
if (
|
||||
!exec(NPM, ["ci", ...npmFlags], src, stdio) &&
|
||||
!exec(NPM, ["install", ...npmFlags], src, stdio)
|
||||
|
||||
@@ -157,6 +157,18 @@ function main() {
|
||||
}
|
||||
|
||||
log(`new plugin root: ${newRoot}`);
|
||||
// Write the verdict BEFORE the handover, not only after it. The step below
|
||||
// retires the process tree this helper hangs off, and an observed run reached
|
||||
// the new server with no verdict file at all — so the dashboard reported
|
||||
// `last_plugin_update: null` for an update that had in fact succeeded. A
|
||||
// pre-written record is overwritten by the real outcome when this survives,
|
||||
// and is the outcome when it does not.
|
||||
record({
|
||||
ok: true,
|
||||
step: "bootstrap",
|
||||
plugin_root: newRoot,
|
||||
note: "the new plugin version is installed; the server is being handed over",
|
||||
});
|
||||
try {
|
||||
// Foreground and blocking: this stops the old server (us), waits for the
|
||||
// ports, then starts the new one. It must finish before we record success.
|
||||
|
||||
+117
-13
@@ -26,9 +26,71 @@ function unitPath(name) {
|
||||
return path.join(unitDir(), `${name}.service`);
|
||||
}
|
||||
|
||||
// Test seam: swap the systemctl implementation so unit tests never talk to a
|
||||
// real service manager. Mirrors tmux.js's __setExecImpl/__reset style.
|
||||
let execImpl = (args, opts) => spawnSync("systemctl", ["--user", ...args], opts);
|
||||
|
||||
function __setExecImpl(fn) {
|
||||
execImpl = fn;
|
||||
}
|
||||
function __reset() {
|
||||
execImpl = (args, opts) => spawnSync("systemctl", ["--user", ...args], opts);
|
||||
}
|
||||
|
||||
function systemctlAvailable() {
|
||||
if (process.platform !== "linux") return false;
|
||||
return spawnSync("systemctl", ["--user", "--version"], { stdio: "ignore" }).status === 0;
|
||||
return execImpl(["--version"], { stdio: "ignore" }).status === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is there a unit by this name, and did WE write it? The distinction decides
|
||||
* whether the dashboard may be stopped by hand: a unit of ours means systemd
|
||||
* owns the process, and SIGTERM-ing it out of band is the one thing that must
|
||||
* never happen (see `restartUserService`).
|
||||
*/
|
||||
function unitIsOurs(name) {
|
||||
try {
|
||||
return fs.readFileSync(unitPath(name), "utf8").includes(MARKER);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `Restart=always`, not `on-failure`: a graceful SIGTERM exits 0, which
|
||||
* `on-failure` reads as "meant to stop". One stray kill — or an out-of-band
|
||||
* stop during a plugin self-update — then left the dashboard down until some
|
||||
* later Claude Code session happened to run the bootstrap. An explicit
|
||||
* `systemctl stop` (what uninstall does) still stops it for good.
|
||||
*/
|
||||
/**
|
||||
* Does our unit still point at `root`? A plugin update moves the install to a
|
||||
* new cache directory, and a unit left naming the old one is a failure that
|
||||
* shows NOTHING until the next reboot — the dashboard simply does not come
|
||||
* back, from a path Claude Code garbage-collected weeks earlier.
|
||||
*
|
||||
* Pure fs, no `systemctl`: this is called from the bootstrap's fast path, which
|
||||
* runs on every single SessionStart and may not spawn a process.
|
||||
*
|
||||
* A foreign unit is never "stale" — it is not ours to judge or rewrite.
|
||||
*/
|
||||
function unitIsStale(name, root) {
|
||||
let body;
|
||||
try {
|
||||
body = fs.readFileSync(unitPath(name), "utf8");
|
||||
} catch {
|
||||
return false; // no unit at all: nothing to be stale
|
||||
}
|
||||
if (!body.includes(MARKER)) return false;
|
||||
return !body.includes(`\nWorkingDirectory=${root}\n`);
|
||||
}
|
||||
|
||||
/** Is the unit currently running? Costs a `systemctl` call — never call it
|
||||
* from the fast path. */
|
||||
function unitIsActive(name) {
|
||||
if (!systemctlAvailable()) return false;
|
||||
const res = execImpl(["is-active", `${name}.service`], { encoding: "utf8", stdio: "pipe" });
|
||||
return String(res.stdout || "").trim() === "active";
|
||||
}
|
||||
|
||||
function unitContent({ description, workingDir, execStart, env }) {
|
||||
@@ -44,7 +106,7 @@ After=network.target
|
||||
Type=simple
|
||||
WorkingDirectory=${workingDir}
|
||||
ExecStart=${execStart}
|
||||
Restart=on-failure
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
${envLines}
|
||||
|
||||
@@ -54,17 +116,18 @@ WantedBy=default.target
|
||||
}
|
||||
|
||||
function systemctl(args) {
|
||||
return spawnSync("systemctl", ["--user", ...args], { stdio: "inherit" });
|
||||
return execImpl(args, { stdio: "inherit" });
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes (or refreshes) the unit file and enables + starts it. Idempotent:
|
||||
* an unchanged unit is left running as-is; a changed one (e.g. a plugin
|
||||
* cache path after an update) is reloaded and restarted.
|
||||
* Writes (or refreshes) the unit file and enables it for boot — but starts
|
||||
* nothing. Split out of `installUserService` for the plugin self-update, which
|
||||
* must be able to point the unit at the new cache directory *before* anything
|
||||
* stops the running server, and defer the restart to its very last act.
|
||||
*
|
||||
* @returns {"written"|"unchanged"|"foreign"|"unavailable"|"failed"}
|
||||
*/
|
||||
function installUserService({ name, description, workingDir, execStart, env = {} }) {
|
||||
function writeUserService({ name, description, workingDir, execStart, env = {} }) {
|
||||
if (!systemctlAvailable()) return "unavailable";
|
||||
const body = unitContent({ description, workingDir, execStart, env });
|
||||
const target = unitPath(name);
|
||||
@@ -72,22 +135,56 @@ function installUserService({ name, description, workingDir, execStart, env = {}
|
||||
if (fs.existsSync(target)) {
|
||||
const current = fs.readFileSync(target, "utf8");
|
||||
if (!current.includes(MARKER)) return "foreign";
|
||||
if (current === body) {
|
||||
systemctl(["enable", "--now", `${name}.service`]);
|
||||
return "unchanged";
|
||||
}
|
||||
if (current === body) return "unchanged";
|
||||
}
|
||||
fs.mkdirSync(unitDir(), { recursive: true });
|
||||
fs.writeFileSync(target, body, "utf8");
|
||||
systemctl(["daemon-reload"]);
|
||||
systemctl(["enable", "--now", `${name}.service`]);
|
||||
systemctl(["restart", `${name}.service`]);
|
||||
systemctl(["enable", `${name}.service`]);
|
||||
return "written";
|
||||
} catch {
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask systemd to restart the unit and do NOT wait for it.
|
||||
*
|
||||
* `--no-block` is the whole point, not a nicety. The caller is the bootstrap
|
||||
* spawned by the running server, so it lives in that server's cgroup; the
|
||||
* moment systemd stops the old main process, `KillMode=control-group` reaps
|
||||
* the caller too. Blocking here means being killed mid-call, which is why the
|
||||
* restart must be the last thing the bootstrap does — by then there is nothing
|
||||
* left to lose.
|
||||
*/
|
||||
function restartUserService(name) {
|
||||
if (!systemctlAvailable()) return "unavailable";
|
||||
const res = systemctl(["restart", "--no-block", `${name}.service`]);
|
||||
return res.status === 0 ? "restarted" : "failed";
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes (or refreshes) the unit file and enables + starts it. Idempotent:
|
||||
* an unchanged unit is left running as-is; a changed one (e.g. a plugin
|
||||
* cache path after an update) is reloaded and restarted.
|
||||
*
|
||||
* Safe for `agenthub service install`, which is invoked from a user's own
|
||||
* shell and is therefore not inside the unit's cgroup. The plugin bootstrap
|
||||
* is, and uses `writeUserService` + `restartUserService` instead.
|
||||
*
|
||||
* @returns {"written"|"unchanged"|"foreign"|"unavailable"|"failed"}
|
||||
*/
|
||||
function installUserService(opts) {
|
||||
const result = writeUserService(opts);
|
||||
if (result === "unchanged") {
|
||||
systemctl(["enable", "--now", `${opts.name}.service`]);
|
||||
} else if (result === "written") {
|
||||
systemctl(["enable", "--now", `${opts.name}.service`]);
|
||||
systemctl(["restart", `${opts.name}.service`]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** @returns {"removed"|"absent"|"foreign"|"unavailable"} */
|
||||
function uninstallUserService(name) {
|
||||
if (!systemctlAvailable()) return "unavailable";
|
||||
@@ -110,8 +207,15 @@ function enableLinger() {
|
||||
|
||||
module.exports = {
|
||||
systemctlAvailable,
|
||||
unitIsOurs,
|
||||
unitIsStale,
|
||||
unitIsActive,
|
||||
writeUserService,
|
||||
restartUserService,
|
||||
installUserService,
|
||||
uninstallUserService,
|
||||
enableLinger,
|
||||
unitPath,
|
||||
__setExecImpl,
|
||||
__reset,
|
||||
};
|
||||
|
||||
+6
-1
@@ -555,7 +555,12 @@ failures return `500` with `error.stderr`.
|
||||
|
||||
`start` returns `409 ERUNLIVE` when the lane's recorded run is still `spawning`
|
||||
or `running`: overwriting `run_id` would orphan that child, and a later `reset`
|
||||
would then `git clean -fd` a directory the orphan is still writing into.
|
||||
would then `git clean -fd` a directory the orphan is still writing into. It
|
||||
returns the same code when the lane's tmux pane is running an agent and the
|
||||
request carried a `prompt` or `resumeSessionId` — `pty-run.js` will not type
|
||||
over a live agent, and adopting the pane silently would answer 200 for a resume
|
||||
that never spawned. `POST /api/run` maps that code to `409` too; a start with
|
||||
neither field still adopts the pane.
|
||||
|
||||
Besides the stage a skill declares explicitly, every lane also carries a
|
||||
server-inferred `detected_stage`: `server/lib/stage-detect.js` matches each
|
||||
|
||||
@@ -369,7 +369,7 @@ describe("agenthub CLI — import & administration", () => {
|
||||
assert.match(err, /Usage: agenthub import/);
|
||||
});
|
||||
|
||||
it("doctor reports API, hooks, database, remotes, and uptime lines", async () => {
|
||||
it("doctor reports API, hooks, database, tmux, remotes, and uptime lines", async () => {
|
||||
const { code, out } = await agenthub("doctor");
|
||||
// Exit 1 when hooks are missing (common in the test harness) — still prints a full report.
|
||||
assert.ok(code === 0 || code === 1, `unexpected exit ${code}`);
|
||||
@@ -377,6 +377,10 @@ describe("agenthub CLI — import & administration", () => {
|
||||
assert.match(out, /Claude Code hooks/);
|
||||
assert.match(out, /Database/);
|
||||
assert.match(out, /Server uptime/);
|
||||
// Asked of the server (GET /api/run/tmux), not of this shell: a missing
|
||||
// tmux is why Start Run fails, and the server's PATH is the one that
|
||||
// decides. Reported either way, and never fatal.
|
||||
assert.match(out, /tmux/);
|
||||
assert.match(out, /Remote sources/);
|
||||
});
|
||||
|
||||
|
||||
@@ -129,6 +129,71 @@ describe("fast path", () => {
|
||||
);
|
||||
assert.equal(boot.fastPathOk(RT), false);
|
||||
});
|
||||
|
||||
it("is false when the systemd unit still names a retired plugin root", () => {
|
||||
// The one failure a live server hides completely: everything is healthy
|
||||
// until the next reboot, and then the dashboard never comes back because
|
||||
// its unit points into a cache directory Claude Code has deleted. The fast
|
||||
// path has to reject it, or no SessionStart ever repairs it.
|
||||
//
|
||||
// Everything else here is deliberately HEALTHY — including a live server,
|
||||
// without which `fastPathOk` is false anyway and this test would pass
|
||||
// against the unfixed code.
|
||||
const ROOT = path.resolve(__dirname, "..", "..");
|
||||
const pkg = require("../../package.json");
|
||||
const infoPath = path.join(TMP_HOME, ".agenthub.json");
|
||||
const prevHome = process.env.HOME;
|
||||
// HOME first: `unitPath()` resolves against it, and computing the path
|
||||
// before this line points every write in this test at the REAL
|
||||
// ~/.config/systemd/user/agenthub.service — which the cleanup below then
|
||||
// deletes. (Asked how I know.)
|
||||
process.env.HOME = TMP_HOME;
|
||||
const unit = require("../../scripts/systemd-service").unitPath("agenthub");
|
||||
assert.ok(
|
||||
unit.startsWith(TMP_HOME + path.sep),
|
||||
`refusing to touch a unit outside the temp home: ${unit}`
|
||||
);
|
||||
|
||||
const writeUnit = (workingDir) => {
|
||||
fs.mkdirSync(path.dirname(unit), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
unit,
|
||||
"[Unit]\n# agenthub-managed-unit — regenerated on install, do not edit by hand\n" +
|
||||
`[Service]\nWorkingDirectory=${workingDir}\n`,
|
||||
"utf8"
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
fs.mkdirSync(path.join(RT, "node_modules"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
infoPath,
|
||||
JSON.stringify({ servers: [{ port: 4820, pid: process.pid, startedAt: "x" }] })
|
||||
);
|
||||
boot.writeState(
|
||||
{
|
||||
pluginVersion: pkg.version,
|
||||
depsHash: boot.depsHash(),
|
||||
pluginRoot: ROOT,
|
||||
skillPluginsSettled: "nothing-missing",
|
||||
},
|
||||
RT
|
||||
);
|
||||
|
||||
// Control: a unit naming THIS root is the steady state — fast path taken.
|
||||
writeUnit(ROOT);
|
||||
assert.equal(boot.fastPathOk(RT), true, "a current unit must not block the fast path");
|
||||
|
||||
// The regression: same healthy install, unit left on a retired root.
|
||||
writeUnit("/plugins/cache/agenthub/deadbeef");
|
||||
assert.equal(boot.fastPathOk(RT), false);
|
||||
} finally {
|
||||
fs.rmSync(infoPath, { force: true });
|
||||
fs.rmSync(unit, { force: true });
|
||||
if (prevHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = prevHome;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("skill-plugin auto-install gate", () => {
|
||||
@@ -391,6 +456,21 @@ describe("buildClient dependency install", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("installs devDependencies explicitly, because NODE_ENV=production omits them", () => {
|
||||
// The whole client build toolchain (vite, typescript, @types/*) is a
|
||||
// devDependency, and npm turns NODE_ENV=production into --omit=dev. Every
|
||||
// bootstrap descended from the running server inherits that env, so the
|
||||
// install dropped vite, `npm run build` failed, and the dashboard kept
|
||||
// serving the PREVIOUS version's bundle after a self-update.
|
||||
resetRuntime();
|
||||
const calls = [];
|
||||
buildClient({ rt: RT, root: fakeRoot(), exec: fakeExec(calls) });
|
||||
|
||||
for (const call of calls.filter((c) => c.startsWith("ci") || c.startsWith("install"))) {
|
||||
assert.match(call, /--include=dev/, `dependency install must include dev deps: ${call}`);
|
||||
}
|
||||
});
|
||||
|
||||
it("fails without building when neither install path works", () => {
|
||||
resetRuntime();
|
||||
const calls = [];
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* @file Tests the `systemd` row of scripts/plugin-doctor.js.
|
||||
*
|
||||
* The row exists for a failure nothing else in the report can see: a unit still
|
||||
* naming a retired plugin cache directory leaves a running, healthy-looking
|
||||
* dashboard that simply does not come back after the next reboot — it starts a
|
||||
* path Claude Code deleted during the update. Every other row would read OK.
|
||||
*
|
||||
* WARN and never FAIL: the dashboard in front of the user works, and plenty of
|
||||
* machines legitimately have no unit at all.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, beforeEach, after } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
|
||||
const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-doctor-systemd-"));
|
||||
const prevHome = process.env.HOME;
|
||||
// Before anything resolves a unit path: `unitPath()` reads HOME, and a path
|
||||
// computed against the real one makes these tests rewrite the developer's own
|
||||
// ~/.config/systemd/user/agenthub.service.
|
||||
process.env.HOME = TMP_HOME;
|
||||
process.env.CLAUDE_HOME = path.join(TMP_HOME, ".claude");
|
||||
|
||||
const svc = require("../../scripts/systemd-service");
|
||||
const { diagnose } = require("../../scripts/plugin-doctor");
|
||||
|
||||
const UNIT = svc.unitPath("agenthub");
|
||||
const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");
|
||||
|
||||
assert.ok(UNIT.startsWith(TMP_HOME + path.sep), `refusing to touch ${UNIT}`);
|
||||
|
||||
beforeEach(() => {
|
||||
fs.rmSync(UNIT, { force: true });
|
||||
// Claim systemd exists and the unit is running, so each test varies exactly
|
||||
// one thing: the unit file on disk.
|
||||
svc.__setExecImpl((args) => ({
|
||||
status: 0,
|
||||
stdout: args[0] === "is-active" ? "active\n" : "",
|
||||
}));
|
||||
});
|
||||
|
||||
after(() => {
|
||||
svc.__reset();
|
||||
if (prevHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = prevHome;
|
||||
delete process.env.CLAUDE_HOME;
|
||||
fs.rmSync(TMP_HOME, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function row() {
|
||||
const found = diagnose().find((r) => r.label === "systemd");
|
||||
assert.ok(found, "the doctor must always emit a systemd row");
|
||||
return found;
|
||||
}
|
||||
|
||||
function writeUnit(workingDir) {
|
||||
fs.mkdirSync(path.dirname(UNIT), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
UNIT,
|
||||
"[Unit]\n# agenthub-managed-unit — regenerated on install, do not edit by hand\n" +
|
||||
`[Service]\nWorkingDirectory=${workingDir}\n`,
|
||||
"utf8"
|
||||
);
|
||||
}
|
||||
|
||||
const linuxOnly = { skip: process.platform !== "linux" ? "systemd is Linux-only" : false };
|
||||
|
||||
describe("plugin-doctor: systemd row", linuxOnly, () => {
|
||||
it("warns, never fails, when the unit names a retired plugin root", () => {
|
||||
writeUnit("/plugins/cache/sg/agenthub/deadbeef");
|
||||
const r = row();
|
||||
|
||||
assert.equal(r.level, "warn", "a working dashboard must not fail the doctor run");
|
||||
assert.match(r.detail, /previous plugin version/i);
|
||||
// The consequence is the whole point — a reader who does not know it will
|
||||
// ignore the row.
|
||||
assert.match(r.detail, /reboot/i);
|
||||
assert.match(r.detail, /plugin-bootstrap\.js --force|new Claude Code session/);
|
||||
});
|
||||
|
||||
it("passes when the unit is current and running", () => {
|
||||
writeUnit(PLUGIN_ROOT);
|
||||
const r = row();
|
||||
|
||||
assert.equal(r.level, "ok", r.detail);
|
||||
assert.match(r.detail, /current and running/i);
|
||||
});
|
||||
|
||||
it("warns when the unit is current but stopped", () => {
|
||||
writeUnit(PLUGIN_ROOT);
|
||||
svc.__setExecImpl((args) => ({
|
||||
status: 3,
|
||||
stdout: args[0] === "is-active" ? "inactive\n" : "",
|
||||
}));
|
||||
|
||||
const r = row();
|
||||
assert.equal(r.level, "warn");
|
||||
assert.match(r.detail, /not running/i);
|
||||
});
|
||||
|
||||
it("reports no unit as fine, not as a problem", () => {
|
||||
// A plugin install without `agenthub service install` is a normal setup:
|
||||
// the server is started per session.
|
||||
const r = row();
|
||||
assert.equal(r.level, "ok", r.detail);
|
||||
assert.match(r.detail, /no unit/i);
|
||||
});
|
||||
|
||||
it("warns about a unit it did not write, and never claims it is stale", () => {
|
||||
fs.mkdirSync(path.dirname(UNIT), { recursive: true });
|
||||
fs.writeFileSync(UNIT, "[Service]\nExecStart=/opt/someone-elses-agenthub\n", "utf8");
|
||||
|
||||
const r = row();
|
||||
assert.equal(r.level, "warn");
|
||||
assert.match(r.detail, /not written by AgentHub|left untouched/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @file Tests the `tmux` row of scripts/plugin-doctor.js — the check that tells
|
||||
* an install its browser run console cannot work, because every run the
|
||||
* dashboard starts is a tmux session (server/lib/tmux.js). The row must WARN
|
||||
* and never FAIL: sessions, analytics, lanes and the CLI all work without the
|
||||
* binary, so failing a doctor run over it would cry wolf. tmux is faked through
|
||||
* the module's own exec seam, so the test never depends on the host having it.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, after } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
|
||||
const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-doctor-tmux-"));
|
||||
process.env.CLAUDE_HOME = TMP_HOME;
|
||||
|
||||
const tmux = require("../lib/tmux");
|
||||
const { diagnose } = require("../../scripts/plugin-doctor");
|
||||
|
||||
after(() => {
|
||||
tmux.__reset();
|
||||
fs.rmSync(TMP_HOME, { recursive: true, force: true });
|
||||
delete process.env.CLAUDE_HOME;
|
||||
});
|
||||
|
||||
/** Fake the tmux binary as present or absent, then read back the row. */
|
||||
function rowWithTmux(present) {
|
||||
tmux.__setExecImpl(() => {
|
||||
if (!present) throw new Error("spawnSync tmux ENOENT");
|
||||
return "tmux 3.4\n";
|
||||
});
|
||||
const row = diagnose().find((r) => r.label === "tmux");
|
||||
assert.ok(row, "the doctor must always emit a tmux row");
|
||||
return row;
|
||||
}
|
||||
|
||||
describe("plugin-doctor: tmux row", () => {
|
||||
it("warns, never fails, when tmux is not on PATH", () => {
|
||||
const row = rowWithTmux(false);
|
||||
|
||||
assert.equal(row.level, "warn", "a missing tmux must not fail the doctor run");
|
||||
assert.match(row.detail, /lanes shell/, "the reader needs to know WHAT breaks");
|
||||
assert.match(row.detail, /install/i, "and how to fix it");
|
||||
});
|
||||
|
||||
it("passes when tmux is available", () => {
|
||||
const row = rowWithTmux(true);
|
||||
|
||||
assert.equal(row.level, "ok", row.detail);
|
||||
});
|
||||
});
|
||||
@@ -58,6 +58,29 @@ describe("pty-run", () => {
|
||||
assert.ok(newSessionCall.includes("opus"));
|
||||
});
|
||||
|
||||
it("spawnRun refuses with ETMUXMISSING, naming the fix, when tmux is not installed", () => {
|
||||
// Before this guard the ENOENT escaped from three calls down as
|
||||
// `spawnSync tmux ENOENT` and the route answered 400 — blaming the request
|
||||
// for a missing host package, with no hint of what to install.
|
||||
const calls = [];
|
||||
tmux.__setExecImpl((args) => {
|
||||
calls.push(args);
|
||||
const e = new Error("spawnSync tmux ENOENT");
|
||||
e.code = "ENOENT";
|
||||
throw e;
|
||||
});
|
||||
|
||||
assert.throws(
|
||||
() => pty.spawnRun({ laneId: 42, cwd: "/tmp/repo" }),
|
||||
(err) => err.code === "ETMUXMISSING" && /install/i.test(err.message),
|
||||
"a missing tmux must be reported as such, with the install command"
|
||||
);
|
||||
assert.ok(
|
||||
!calls.some((c) => c[0] === "new-session"),
|
||||
"must not attempt a session it already knows cannot be created"
|
||||
);
|
||||
});
|
||||
|
||||
it("spawnRun is a no-op (adopts) when the existing session's pane runs claude", () => {
|
||||
const calls = [];
|
||||
tmux.__setExecImpl((args) => {
|
||||
@@ -335,4 +358,91 @@ describe("pty-run", () => {
|
||||
);
|
||||
assert.ok(!call.some((a) => String(a).startsWith("--dangerously-bypass")));
|
||||
});
|
||||
|
||||
// `dashboard_runs.mode` is NOT NULL and recordRun swallows insert errors, so a
|
||||
// null there persisted nothing at all while every call still looked fine: the
|
||||
// runs modal rendered a row with no cwd, model, prompt or start time, and a
|
||||
// resumed session kept its separate `external` row because no run row ever
|
||||
// carried its session id. These assert the row actually lands.
|
||||
it("refuses to swallow a resume or a prompt when the pane already runs an agent", () => {
|
||||
// Adopting silently here answered 200 while spawning no `--resume` at all:
|
||||
// the dashboard reported a resumed session that never happened.
|
||||
tmux.__setExecImpl((args) => {
|
||||
if (args[0] === "display-message") return "claude\n";
|
||||
return ""; // has-session succeeds → pane is busy with a live agent
|
||||
});
|
||||
assert.throws(
|
||||
() => pty.spawnRun({ laneId: 51, cwd: "/tmp/repo", resumeSessionId: "abc12345" }),
|
||||
(err) => err.code === "ERUNLIVE"
|
||||
);
|
||||
assert.throws(
|
||||
() => pty.spawnRun({ laneId: 51, cwd: "/tmp/repo", initialPrompt: "do the thing" }),
|
||||
(err) => err.code === "ERUNLIVE"
|
||||
);
|
||||
});
|
||||
|
||||
it("still adopts a busy pane when the request asked for nothing but a pane", () => {
|
||||
const calls = [];
|
||||
tmux.__setExecImpl((args) => {
|
||||
calls.push(args);
|
||||
if (args[0] === "display-message") return "claude\n";
|
||||
return "";
|
||||
});
|
||||
const handle = pty.spawnRun({ laneId: 52, cwd: "/tmp/repo" });
|
||||
assert.equal(handle.id, "agenthub-lane-52");
|
||||
assert.ok(!calls.some((c) => c[0] === "new-session"));
|
||||
assert.ok(!calls.some((c) => c[0] === "send-keys"));
|
||||
});
|
||||
|
||||
describe("run persistence", () => {
|
||||
const dashboardRuns = require("../lib/dashboard-runs");
|
||||
|
||||
it("spawnRun persists the run so the runs list has cwd, model and prompt", () => {
|
||||
tmux.__setExecImpl((args) => {
|
||||
if (args[0] === "has-session") {
|
||||
const e = new Error("gone");
|
||||
e.status = 1;
|
||||
throw e;
|
||||
}
|
||||
return "";
|
||||
});
|
||||
pty.spawnRun({
|
||||
laneId: 71,
|
||||
cwd: "/tmp/persisted",
|
||||
model: "claude-opus-5",
|
||||
initialPrompt: "ship it",
|
||||
});
|
||||
|
||||
const row = dashboardRuns.getRun("agenthub-lane-71");
|
||||
assert.ok(row, "expected a dashboard_runs row for the spawned run");
|
||||
assert.equal(row.cwd, "/tmp/persisted");
|
||||
assert.equal(row.model, "claude-opus-5");
|
||||
assert.equal(row.prompt_preview, "ship it");
|
||||
assert.equal(row.lane_id, 71);
|
||||
assert.ok(row.started_at, "started_at must be set, or the UI dates the row to the epoch");
|
||||
assert.ok(row.mode, "mode is NOT NULL — a null here silently drops the whole insert");
|
||||
});
|
||||
|
||||
it("a resumed run carries the session id, which is what dedupes the external row", () => {
|
||||
tmux.__setExecImpl((args) => {
|
||||
if (args[0] === "has-session") {
|
||||
const e = new Error("gone");
|
||||
e.status = 1;
|
||||
throw e;
|
||||
}
|
||||
return "";
|
||||
});
|
||||
const sessionId = "c2055094-09cf-4735-9712-09e5cdf7023f";
|
||||
const handle = pty.spawnRun({
|
||||
laneId: 72,
|
||||
cwd: "/tmp/resumed",
|
||||
resumeSessionId: sessionId,
|
||||
});
|
||||
|
||||
// The UI reads sessionId off the run list; an external session whose id is
|
||||
// already on a run row is not repeated as its own `external` row.
|
||||
assert.equal(handle.sessionId, sessionId);
|
||||
assert.equal(dashboardRuns.getRun("agenthub-lane-72").resume_session_id, sessionId);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -118,6 +118,23 @@ describe("/api/run", () => {
|
||||
assert.equal(body.error.code, "EBADCWD");
|
||||
});
|
||||
|
||||
it("POST / answers 503, not 400, when the host has no tmux", async () => {
|
||||
// The request is fine; the dependency is absent. 400 would tell the user to
|
||||
// fix their input, and the body must carry the install line the UI shows.
|
||||
tmux.__setExecImpl(() => {
|
||||
const e = new Error("spawnSync tmux ENOENT");
|
||||
e.code = "ENOENT";
|
||||
throw e;
|
||||
});
|
||||
const { status, body } = await fetchJson("/api/run", {
|
||||
method: "POST",
|
||||
body: { laneId: 9, cwd: TMP },
|
||||
});
|
||||
assert.equal(status, 503);
|
||||
assert.equal(body.error.code, "ETMUXMISSING");
|
||||
assert.match(body.error.message, /install/i);
|
||||
});
|
||||
|
||||
it("POST / spawns a tmux session and GET /:id finds it", async () => {
|
||||
let hasSessionCalls = 0;
|
||||
tmux.__setExecImpl((args) => {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* @file Tests scripts/systemd-service.js, and specifically the split that
|
||||
* exists because of one incident: the plugin self-update killed the dashboard
|
||||
* and left it dead.
|
||||
*
|
||||
* The bootstrap that performs an update is spawned by the running server, so
|
||||
* it lives in that server's systemd cgroup. The old code SIGTERM-ed the server
|
||||
* from inside that cgroup, which (a) exits 0, and `Restart=on-failure` reads a
|
||||
* clean exit as "meant to stop", and (b) trips `KillMode=control-group`, so
|
||||
* systemd reaped the bootstrap before it could write state or repoint the unit
|
||||
* at the new plugin root. The dashboard then stayed down until some later
|
||||
* Claude Code session happened to bootstrap again.
|
||||
*
|
||||
* Hence: writing the unit must not start anything, restarting must not block,
|
||||
* and a clean exit must no longer be read as "leave it stopped".
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, beforeEach, after } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
|
||||
const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-systemd-"));
|
||||
const prevHome = process.env.HOME;
|
||||
process.env.HOME = TMP_HOME;
|
||||
|
||||
const svc = require("../../scripts/systemd-service");
|
||||
|
||||
/** Every systemctl invocation this test saw, as flat argv strings. */
|
||||
let calls = [];
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
// Each test starts from "no unit on disk" — otherwise a previous test's
|
||||
// write turns the next one's `written` into `unchanged`.
|
||||
fs.rmSync(svc.unitPath("agenthub"), { force: true });
|
||||
svc.__setExecImpl((args) => {
|
||||
// `--version` is the availability probe every entry point runs first, not
|
||||
// an action — recording it would bury the calls these tests are about.
|
||||
if (args[0] !== "--version") calls.push(args.join(" "));
|
||||
return { status: 0 };
|
||||
});
|
||||
});
|
||||
|
||||
after(() => {
|
||||
svc.__reset();
|
||||
if (prevHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = prevHome;
|
||||
fs.rmSync(TMP_HOME, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const UNIT = {
|
||||
name: "agenthub",
|
||||
description: "AgentHub dashboard server (Claude Code plugin)",
|
||||
workingDir: "/plugin/root/new",
|
||||
execStart: "/usr/bin/node /plugin/root/new/server/index.js",
|
||||
env: { NODE_ENV: "production" },
|
||||
};
|
||||
|
||||
function unitFile() {
|
||||
return fs.readFileSync(svc.unitPath("agenthub"), "utf8");
|
||||
}
|
||||
|
||||
const linuxOnly = { skip: process.platform !== "linux" ? "systemd is Linux-only" : false };
|
||||
|
||||
describe("systemd-service — unit content", linuxOnly, () => {
|
||||
it("restarts always, because a graceful SIGTERM exits 0", () => {
|
||||
svc.writeUserService(UNIT);
|
||||
const body = unitFile();
|
||||
|
||||
// `on-failure` is what let one stray kill (or an out-of-band stop during
|
||||
// an update) leave the dashboard down indefinitely.
|
||||
assert.match(body, /^Restart=always$/m);
|
||||
assert.doesNotMatch(body, /^Restart=on-failure$/m);
|
||||
});
|
||||
|
||||
it("carries the ownership marker, so a hand-written unit is never clobbered", () => {
|
||||
svc.writeUserService(UNIT);
|
||||
assert.match(unitFile(), /agenthub-managed-unit/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("systemd-service — writeUserService", linuxOnly, () => {
|
||||
it("writes and enables the unit but starts NOTHING", () => {
|
||||
// The point of the split: the update must be able to repoint the unit at
|
||||
// the new plugin root while the old server is still serving requests.
|
||||
const result = svc.writeUserService(UNIT);
|
||||
|
||||
assert.equal(result, "written");
|
||||
assert.ok(
|
||||
calls.some((c) => c.startsWith("daemon-reload")),
|
||||
"a rewritten unit must be reloaded"
|
||||
);
|
||||
assert.ok(
|
||||
calls.some((c) => c === "enable agenthub.service"),
|
||||
"it must still be enabled for boot"
|
||||
);
|
||||
assert.ok(
|
||||
!calls.some((c) => c.includes("--now") || c.startsWith("restart") || c.startsWith("start")),
|
||||
`nothing may be started here, got: ${JSON.stringify(calls)}`
|
||||
);
|
||||
});
|
||||
|
||||
it("reports an identical unit as unchanged and touches systemd not at all", () => {
|
||||
svc.writeUserService(UNIT);
|
||||
calls = [];
|
||||
|
||||
assert.equal(svc.writeUserService(UNIT), "unchanged");
|
||||
assert.deepEqual(calls, [], "an unchanged unit needs no systemctl call");
|
||||
});
|
||||
|
||||
it("refuses a unit it did not write", () => {
|
||||
fs.mkdirSync(path.dirname(svc.unitPath("agenthub")), { recursive: true });
|
||||
fs.writeFileSync(svc.unitPath("agenthub"), "[Service]\nExecStart=/opt/mine\n", "utf8");
|
||||
|
||||
assert.equal(svc.writeUserService(UNIT), "foreign");
|
||||
assert.equal(svc.unitIsOurs("agenthub"), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("systemd-service — restartUserService", linuxOnly, () => {
|
||||
it("never blocks, because the caller is inside the cgroup being restarted", () => {
|
||||
assert.equal(svc.restartUserService("agenthub"), "restarted");
|
||||
assert.deepEqual(calls, ["restart --no-block agenthub.service"]);
|
||||
});
|
||||
|
||||
it("reports failure rather than throwing when systemctl refuses", () => {
|
||||
// Available, but the restart itself is rejected — distinct from "no
|
||||
// systemd here", which must not be reported as a failure.
|
||||
svc.__setExecImpl((args) => ({ status: args[0] === "--version" ? 0 : 1 }));
|
||||
assert.equal(svc.restartUserService("agenthub"), "failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("systemd-service — unitIsStale", linuxOnly, () => {
|
||||
it("is true when the unit names a plugin root that is no longer the current one", () => {
|
||||
// Invisible while the server runs, fatal at the next reboot: the unit
|
||||
// starts a path Claude Code garbage-collected after the update.
|
||||
svc.writeUserService({ ...UNIT, workingDir: "/plugin/root/old" });
|
||||
assert.equal(svc.unitIsStale("agenthub", "/plugin/root/new"), true);
|
||||
});
|
||||
|
||||
it("is false for a unit already naming the current root", () => {
|
||||
svc.writeUserService(UNIT);
|
||||
assert.equal(svc.unitIsStale("agenthub", "/plugin/root/new"), false);
|
||||
});
|
||||
|
||||
it("is false when there is no unit, and for one we do not own", () => {
|
||||
assert.equal(svc.unitIsStale("agenthub", "/plugin/root/new"), false);
|
||||
|
||||
fs.mkdirSync(path.dirname(svc.unitPath("agenthub")), { recursive: true });
|
||||
fs.writeFileSync(svc.unitPath("agenthub"), "[Service]\nWorkingDirectory=/opt/mine\n", "utf8");
|
||||
assert.equal(
|
||||
svc.unitIsStale("agenthub", "/plugin/root/new"),
|
||||
false,
|
||||
"a foreign unit is not ours to call stale, or to rewrite"
|
||||
);
|
||||
});
|
||||
|
||||
it("spawns nothing — the bootstrap fast path runs it on every SessionStart", () => {
|
||||
svc.writeUserService(UNIT);
|
||||
calls = [];
|
||||
|
||||
svc.unitIsStale("agenthub", "/plugin/root/new");
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
});
|
||||
|
||||
describe("systemd-service — unitIsActive", linuxOnly, () => {
|
||||
it("is true only for `active`", () => {
|
||||
svc.__setExecImpl((args) => ({ status: 0, stdout: args[0] === "is-active" ? "active\n" : "" }));
|
||||
assert.equal(svc.unitIsActive("agenthub"), true);
|
||||
|
||||
svc.__setExecImpl((args) => ({
|
||||
status: 3,
|
||||
stdout: args[0] === "is-active" ? "inactive\n" : "",
|
||||
}));
|
||||
assert.equal(svc.unitIsActive("agenthub"), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("systemd-service — unitIsOurs", linuxOnly, () => {
|
||||
it("is false when no unit exists at all", () => {
|
||||
fs.rmSync(svc.unitPath("agenthub"), { force: true });
|
||||
assert.equal(svc.unitIsOurs("agenthub"), false);
|
||||
});
|
||||
|
||||
it("is true for a unit this code wrote", () => {
|
||||
svc.writeUserService(UNIT);
|
||||
assert.equal(svc.unitIsOurs("agenthub"), true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
/**
|
||||
* @file Regression tests for update detection on a plugin-cache install that is
|
||||
* NOT a git clone.
|
||||
*
|
||||
* This is the case 1.5.1 shipped broken. When a marketplace entry declares
|
||||
* `"source": "url"` — this project's own does — Claude Code unpacks an archive,
|
||||
* so the cache directory has no `.git`. `getUpdatesStatus` probed for `.git`
|
||||
* first and returned "Install directory is not a git clone; check for updates
|
||||
* manually", skipping the entire release layer: `update_available` was
|
||||
* permanently false however many releases were published, `plugin_marketplace`
|
||||
* and `plugin_name` were never set, so `POST /api/updates/apply`'s plugin branch
|
||||
* could never fire either. The bug read as "up to date" and was therefore
|
||||
* invisible for as long as the install happened to be current.
|
||||
*
|
||||
* These tests pin the git-free path: the repository URL comes from the
|
||||
* marketplace manifest on disk, version comparison is the only signal, and a
|
||||
* newer release must flip `update_available` to true.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const { describe, it, before, after, beforeEach } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
|
||||
const {
|
||||
getUpdatesStatus,
|
||||
pluginMarketplaceUrl,
|
||||
fetchReleaseFromUrl,
|
||||
detectPluginInstall,
|
||||
} = require("../lib/update-check");
|
||||
|
||||
let tmpDir;
|
||||
let prevHome;
|
||||
|
||||
before(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "upd-nogit-"));
|
||||
prevHome = process.env.CLAUDE_HOME;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
if (prevHome === undefined) delete process.env.CLAUDE_HOME;
|
||||
else process.env.CLAUDE_HOME = prevHome;
|
||||
try {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
/* best effort */
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Build a fake Claude home containing a marketplace manifest and an
|
||||
* archive-style plugin cache directory — no `.git` anywhere.
|
||||
*
|
||||
* @param {object} opts
|
||||
* @param {any} [opts.source] the marketplace entry's `source` value
|
||||
* @param {string|null} [opts.version] package.json version, or null to omit the file
|
||||
* @param {boolean} [opts.knownMarketplaces] write known_marketplaces.json
|
||||
* @returns {{root: string, home: string}} the plugin cache root
|
||||
*/
|
||||
function makePluginInstall(name, opts = {}) {
|
||||
const {
|
||||
source = { source: "url", url: "https://forge.example.com/Owner/Repo.git", ref: "main" },
|
||||
version = "1.5.1",
|
||||
knownMarketplaces = true,
|
||||
} = opts;
|
||||
|
||||
const home = path.join(tmpDir, name, ".claude");
|
||||
const mktDir = path.join(home, "plugins", "marketplaces", "sg");
|
||||
const root = path.join(home, "plugins", "cache", "sg", "agenthub", "d4052ed23506");
|
||||
fs.mkdirSync(path.join(mktDir, ".claude-plugin"), { recursive: true });
|
||||
fs.mkdirSync(root, { recursive: true });
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(mktDir, ".claude-plugin", "marketplace.json"),
|
||||
JSON.stringify({ name: "sg", plugins: [{ name: "agenthub", source }] })
|
||||
);
|
||||
if (knownMarketplaces) {
|
||||
fs.writeFileSync(
|
||||
path.join(home, "plugins", "known_marketplaces.json"),
|
||||
JSON.stringify({ sg: { installLocation: mktDir } })
|
||||
);
|
||||
}
|
||||
if (version !== null) {
|
||||
fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ version }));
|
||||
}
|
||||
|
||||
process.env.CLAUDE_HOME = home;
|
||||
return { root, home };
|
||||
}
|
||||
|
||||
/** A resolved release, as fetchReleaseFromUrl would return it. */
|
||||
function release(tag) {
|
||||
return {
|
||||
ok: true,
|
||||
tag,
|
||||
name: tag.replace(/^v/, ""),
|
||||
url: `https://forge.example.com/Owner/Repo/releases/tag/${tag}`,
|
||||
published_at: "2026-09-10T09:18:48Z",
|
||||
notes: "notes",
|
||||
};
|
||||
}
|
||||
|
||||
describe("pluginMarketplaceUrl", () => {
|
||||
it("reads the plugin's repository URL out of the marketplace manifest", () => {
|
||||
makePluginInstall("ok");
|
||||
assert.equal(
|
||||
pluginMarketplaceUrl("sg", "agenthub"),
|
||||
"https://forge.example.com/Owner/Repo.git"
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the conventional marketplace location when the index is missing", () => {
|
||||
// known_marketplaces.json is an index, not the authority — the manifest is.
|
||||
makePluginInstall("noindex", { knownMarketplaces: false });
|
||||
assert.equal(
|
||||
pluginMarketplaceUrl("sg", "agenthub"),
|
||||
"https://forge.example.com/Owner/Repo.git"
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts a bare URL string as the source", () => {
|
||||
makePluginInstall("strsrc", { source: "https://forge.example.com/Owner/Repo.git" });
|
||||
assert.equal(
|
||||
pluginMarketplaceUrl("sg", "agenthub"),
|
||||
"https://forge.example.com/Owner/Repo.git"
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null for a github owner/repo shorthand rather than guessing a host", () => {
|
||||
// Inventing github.com here would produce an API URL that 404s and a
|
||||
// confidently wrong "up to date".
|
||||
makePluginInstall("ghshort", { source: { source: "github", repo: "Owner/Repo" } });
|
||||
assert.equal(pluginMarketplaceUrl("sg", "agenthub"), null);
|
||||
});
|
||||
|
||||
it("returns null when the manifest has no entry for that plugin", () => {
|
||||
const { home } = makePluginInstall("nomatch");
|
||||
const manifest = path.join(
|
||||
home,
|
||||
"plugins",
|
||||
"marketplaces",
|
||||
"sg",
|
||||
".claude-plugin",
|
||||
"marketplace.json"
|
||||
);
|
||||
fs.writeFileSync(manifest, JSON.stringify({ name: "sg", plugins: [{ name: "other" }] }));
|
||||
assert.equal(pluginMarketplaceUrl("sg", "agenthub"), null);
|
||||
});
|
||||
|
||||
it("returns null instead of throwing on a malformed manifest", () => {
|
||||
const { home } = makePluginInstall("badjson");
|
||||
const manifest = path.join(
|
||||
home,
|
||||
"plugins",
|
||||
"marketplaces",
|
||||
"sg",
|
||||
".claude-plugin",
|
||||
"marketplace.json"
|
||||
);
|
||||
fs.writeFileSync(manifest, "{not json");
|
||||
assert.equal(pluginMarketplaceUrl("sg", "agenthub"), null);
|
||||
});
|
||||
|
||||
it("returns null when nothing is on disk at all", () => {
|
||||
process.env.CLAUDE_HOME = path.join(tmpDir, "empty-home");
|
||||
assert.equal(pluginMarketplaceUrl("sg", "agenthub"), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUpdatesStatus — plugin cache with no .git", () => {
|
||||
it("checks the release API instead of reporting 'not a git clone'", async () => {
|
||||
const { root } = makePluginInstall("regression");
|
||||
assert.equal(fs.existsSync(path.join(root, ".git")), false, "fixture must have no .git");
|
||||
|
||||
const s = await getUpdatesStatus(root, { latestRelease: release("v1.5.1") });
|
||||
|
||||
// The old behaviour: the not-a-git-clone message, everything else absent.
|
||||
// Asserted on the message's CONTENT, not on it being null — a plugin
|
||||
// install now carries its own sentence, and null was only ever a proxy for
|
||||
// "did not fall through here".
|
||||
assert.doesNotMatch(
|
||||
s.message,
|
||||
/not a git clone/i,
|
||||
"must not fall through to the not-a-git-clone payload"
|
||||
);
|
||||
assert.equal(s.release_check, "ok", "the release layer must actually run");
|
||||
assert.equal(s.install_kind, "plugin");
|
||||
assert.equal(s.plugin_marketplace, "sg");
|
||||
assert.equal(s.plugin_name, "agenthub");
|
||||
assert.equal(s.local_version, "1.5.1");
|
||||
assert.equal(s.latest_release, "v1.5.1");
|
||||
assert.equal(s.situation, "plugin_managed");
|
||||
});
|
||||
|
||||
it("reports up-to-date for the RIGHT reason when versions match", async () => {
|
||||
const { root } = makePluginInstall("current");
|
||||
const s = await getUpdatesStatus(root, { latestRelease: release("v1.5.1") });
|
||||
assert.equal(s.update_available, false);
|
||||
// The distinction that matters: false because it looked and found nothing,
|
||||
// not false because it never looked.
|
||||
assert.equal(s.release_check, "ok");
|
||||
assert.equal(s.latest_release, "v1.5.1");
|
||||
});
|
||||
|
||||
it("flips update_available to true when a newer release is published", async () => {
|
||||
// The whole point: before the fix this stayed false forever.
|
||||
const { root } = makePluginInstall("newer");
|
||||
const s = await getUpdatesStatus(root, { latestRelease: release("v1.6.0") });
|
||||
assert.equal(s.update_available, true);
|
||||
assert.equal(s.latest_release, "v1.6.0");
|
||||
// The fields POST /apply's plugin branch requires must all be present, or
|
||||
// the batch can never be spawned.
|
||||
assert.ok(s.plugin_marketplace && s.plugin_name && s.repo_root);
|
||||
});
|
||||
|
||||
it("carries a human-readable message in every outcome, never a null", async () => {
|
||||
// `agenthub update-check` prints `message` as its headline. Null here made
|
||||
// it print the literal "null" on every plugin-cache install — the one kind
|
||||
// that has no commit count to fall back on.
|
||||
const cases = [
|
||||
[makePluginInstall("msg-newer").root, { latestRelease: release("v1.6.0") }, /v1\.6\.0/],
|
||||
[makePluginInstall("msg-current").root, { latestRelease: release("v1.5.0") }, /newest/i],
|
||||
[
|
||||
makePluginInstall("msg-failed").root,
|
||||
{ latestRelease: { ok: false, reason: "unreachable" } },
|
||||
/unreachable/,
|
||||
],
|
||||
[
|
||||
makePluginInstall("msg-noversion", { version: null }).root,
|
||||
{ latestRelease: release("v1.6.0") },
|
||||
/no version|cannot be compared/i,
|
||||
],
|
||||
];
|
||||
for (const [root, opts, expected] of cases) {
|
||||
const s = await getUpdatesStatus(root, opts);
|
||||
assert.equal(typeof s.message, "string", `message must be a string, got ${s.message}`);
|
||||
assert.match(s.message, expected);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not treat an older published release as an update", async () => {
|
||||
const { root } = makePluginInstall("older");
|
||||
const s = await getUpdatesStatus(root, { latestRelease: release("v1.4.0") });
|
||||
assert.equal(s.update_available, false);
|
||||
// Not a dev_build either: a plugin install is whatever shipped, it cannot
|
||||
// be "ahead" in the way a checkout can.
|
||||
assert.equal(s.dev_build, false);
|
||||
});
|
||||
|
||||
it("never claims to have checked when the release lookup failed", async () => {
|
||||
const { root } = makePluginInstall("unreachable");
|
||||
const s = await getUpdatesStatus(root, {
|
||||
latestRelease: { ok: false, reason: "unreachable" },
|
||||
});
|
||||
assert.equal(s.release_check, "unreachable");
|
||||
assert.equal(s.update_available, false);
|
||||
assert.equal(s.latest_release, null);
|
||||
});
|
||||
|
||||
it("reports no_local_version when package.json cannot be read", async () => {
|
||||
// With nothing to compare against, "up to date" would be a guess.
|
||||
const { root } = makePluginInstall("noversion", { version: null });
|
||||
const s = await getUpdatesStatus(root, { latestRelease: release("v1.6.0") });
|
||||
assert.equal(s.release_check, "no_local_version");
|
||||
assert.equal(s.update_available, false);
|
||||
});
|
||||
|
||||
it("reports no git-derived numbers rather than fabricating them", async () => {
|
||||
const { root } = makePluginInstall("nonumbers");
|
||||
const s = await getUpdatesStatus(root, { latestRelease: release("v1.6.0") });
|
||||
assert.equal(s.git_repo, false, "honest: there is no clone here");
|
||||
assert.equal(s.shallow_clone, false);
|
||||
assert.equal(s.commits_behind_release, null);
|
||||
assert.equal(s.commits_ahead_of_release, null);
|
||||
assert.equal(s.release_sha, null);
|
||||
});
|
||||
|
||||
it("prints the claude plugin commands as the manual fallback", async () => {
|
||||
const { root } = makePluginInstall("manual");
|
||||
const s = await getUpdatesStatus(root, { latestRelease: release("v1.6.0") });
|
||||
assert.match(s.manual_command, /claude plugin marketplace update sg/);
|
||||
assert.match(s.manual_command, /claude plugin update agenthub@sg -y/);
|
||||
// No git command may be suggested for a directory that is not a clone.
|
||||
assert.doesNotMatch(s.manual_command, /git /);
|
||||
});
|
||||
|
||||
it("takes the marketplace and plugin from the path, not from a caller", async () => {
|
||||
const { root } = makePluginInstall("frompath");
|
||||
assert.deepEqual(detectPluginInstall(root), { marketplace: "sg", plugin: "agenthub" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchReleaseFromUrl", () => {
|
||||
let realFetch;
|
||||
beforeEach(() => {
|
||||
realFetch = global.fetch;
|
||||
});
|
||||
|
||||
it("never touches the network for a URL that isn't owner/repo shaped", async () => {
|
||||
global.fetch = () => {
|
||||
throw new Error("must not fetch for an unusable URL");
|
||||
};
|
||||
try {
|
||||
const res = await fetchReleaseFromUrl("/some/local/path");
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.reason, "remote_not_http");
|
||||
} finally {
|
||||
global.fetch = realFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("reports no_remote for a missing URL instead of throwing", async () => {
|
||||
global.fetch = () => {
|
||||
throw new Error("must not fetch without a URL");
|
||||
};
|
||||
try {
|
||||
const res = await fetchReleaseFromUrl(null);
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.reason, "no_remote");
|
||||
} finally {
|
||||
global.fetch = realFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves the tag from a Gitea-shaped releases payload", async () => {
|
||||
global.fetch = async () => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ tag_name: "v9.9.9", name: "9.9.9", html_url: "u", body: "b" }),
|
||||
});
|
||||
try {
|
||||
const res = await fetchReleaseFromUrl("https://forge.example.com/Owner/Repo.git");
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.tag, "v9.9.9");
|
||||
} finally {
|
||||
global.fetch = realFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("treats 404 as 'no releases yet', not a fault", async () => {
|
||||
global.fetch = async () => ({ ok: false, status: 404, json: async () => ({}) });
|
||||
try {
|
||||
const res = await fetchReleaseFromUrl("https://forge.example.com/Owner/Repo.git");
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.reason, "no_releases");
|
||||
} finally {
|
||||
global.fetch = realFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -91,8 +91,12 @@ function recordRun(handle) {
|
||||
lane_id: typeof handle.laneId === "number" ? handle.laneId : null,
|
||||
tool: handle.tool === "codex" ? "codex" : "claude",
|
||||
});
|
||||
} catch {
|
||||
/* persistence is best-effort */
|
||||
} catch (err) {
|
||||
// Best-effort by design (a live run must never fail because sqlite did),
|
||||
// but not silent: a swallowed insert leaves the runs modal showing rows with
|
||||
// no cwd, model, prompt or start time, which reads as a UI bug rather than a
|
||||
// persistence one. Say it once, here, where the cause is known.
|
||||
console.warn(`[dashboard-runs] failed to record run ${handle?.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-1
@@ -181,6 +181,21 @@ function spawnRun(args) {
|
||||
throw makeErr("EBADSESSION", "resumeSessionId is not a valid session id");
|
||||
}
|
||||
|
||||
// A run IS a tmux session, so an absent binary is a precondition failure, not
|
||||
// a spawn failure. Without this the caller gets `spawnSync tmux ENOENT` from
|
||||
// three directories down — a message that names no fix — and the route maps
|
||||
// it to 400, blaming the request for the host's missing package. Checked here
|
||||
// rather than in each route because both spawn paths (POST /api/run and
|
||||
// POST /api/lanes/:id/start) come through this function.
|
||||
if (!tmux.isTmuxAvailable()) {
|
||||
throw makeErr(
|
||||
"ETMUXMISSING",
|
||||
"tmux is not installed, and every run the dashboard starts is a tmux session. " +
|
||||
"Install it (sudo apt install tmux / brew install tmux; on Windows run AgentHub under WSL2), " +
|
||||
"then restart the dashboard. Everything else keeps working without it."
|
||||
);
|
||||
}
|
||||
|
||||
const id = runIdForLane(laneId);
|
||||
const startedAt = Date.now();
|
||||
const argv = buildArgv({
|
||||
@@ -200,7 +215,13 @@ function spawnRun(args) {
|
||||
dashboardRuns.recordRun({
|
||||
id,
|
||||
sessionId: resumeSessionId || null,
|
||||
mode: null,
|
||||
// `dashboard_runs.mode` is NOT NULL. Passing null made every insert throw
|
||||
// inside recordRun's best-effort catch, so no tmux-backed run was ever
|
||||
// persisted: publicRun then read its cwd/model/prompt/startedAt off a row
|
||||
// that did not exist (a blank row dated Jan 1 1970 in the runs modal), and
|
||||
// session_id never landed either, so a resumed session stayed listed as a
|
||||
// separate `external` row. Every run here is one interactive pane.
|
||||
mode: "interactive",
|
||||
cwd,
|
||||
tool: tool === "codex" ? "codex" : "claude",
|
||||
model: model || null,
|
||||
@@ -238,6 +259,18 @@ function spawnRun(args) {
|
||||
// Pane is running something (a live `claude`, an editor, a build): adopt
|
||||
// silently, same convention as this repo's server port-adoption logic — no
|
||||
// error, no duplicate session. Attaching shows the user what is running.
|
||||
//
|
||||
// Adopting is only honest when the request asked for nothing more than a
|
||||
// pane. A Resume or an initial prompt cannot be delivered into a pane that is
|
||||
// already running an agent (typing over it is what the shell-pane branch
|
||||
// above exists to avoid), so answering 200 there reports work that never
|
||||
// happened: the user sees "resumed" while no `--resume` was ever spawned.
|
||||
else if (resumeSessionId || initialPrompt) {
|
||||
throw makeErr(
|
||||
"ERUNLIVE",
|
||||
`lane ${laneId}'s pane is already running \`${tmux.paneCommand(id) || "a process"}\` — stop it before resuming a session or sending a prompt`
|
||||
);
|
||||
}
|
||||
|
||||
return getRun(id);
|
||||
}
|
||||
|
||||
+186
-12
@@ -2,21 +2,33 @@
|
||||
* @file Detects whether this install is behind the newest published RELEASE of
|
||||
* its own repository, and can fast-forward onto that release tag on request.
|
||||
*
|
||||
* The release is read straight from the forge's REST API, derived from the
|
||||
* `origin` remote URL (`/api/v1/repos/<owner>/<repo>/releases/latest` — the
|
||||
* Gitea/Forgejo shape this project is hosted on), so the check needs no
|
||||
* hardcoded host and no credentials for a public repo. When no release can be
|
||||
* read — a non-HTTP remote, an offline machine, a repo with no releases yet —
|
||||
* detection degrades to the original commit-count comparison against the
|
||||
* canonical default branch rather than reporting a false "up to date".
|
||||
* The release is read straight from the forge's REST API
|
||||
* (`/api/v1/repos/<owner>/<repo>/releases/latest` — the Gitea/Forgejo shape
|
||||
* this project is hosted on), so the check needs no hardcoded host and no
|
||||
* credentials for a public repo. When no release can be read — a non-HTTP
|
||||
* remote, an offline machine, a repo with no releases yet — detection degrades
|
||||
* to the original commit-count comparison against the canonical default branch
|
||||
* rather than reporting a false "up to date".
|
||||
*
|
||||
* **Two independent paths, chosen by install kind.** A checkout derives the API
|
||||
* URL from its `origin` remote. A plugin-cache install does NOT: when a
|
||||
* marketplace entry declares `"source": "url"` (this project's own does) Claude
|
||||
* Code unpacks an archive, so the cache directory has no `.git` and there is no
|
||||
* remote to read. That path is answered entirely without git — the repository
|
||||
* URL comes from the marketplace manifest on disk (`pluginMarketplaceUrl`) and
|
||||
* the package.json version is the only comparison signal. Getting this wrong is
|
||||
* what shipped in 1.5.1: the `.git` probe ran first, returned "not a git clone",
|
||||
* and skipped the release layer, so `update_available` stayed false however many
|
||||
* releases were published — a bug that reads as "up to date" and is therefore
|
||||
* invisible while the install happens to be current. Keep the plugin branch
|
||||
* ahead of the `.git` probe.
|
||||
*
|
||||
* Two states the release model makes visible that a commit count cannot:
|
||||
* a checkout sitting AHEAD of the newest release tag is a `dev_build`, not an
|
||||
* up-to-date install; and an install living under `~/.claude/plugins/cache/`
|
||||
* is `plugin_managed`, where this process must NOT self-update — Claude Code
|
||||
* only re-resolves `${CLAUDE_PLUGIN_ROOT}` on `/reload-plugins`, a REPL-only
|
||||
* action no server can trigger, so a self-pull would leave a cache directory
|
||||
* whose name (a commit sha) no longer matches its contents.
|
||||
* is `plugin_managed`, which this process does not rewrite itself — Claude Code
|
||||
* owns that directory, so `applyUpdate` refuses and `routes/updates.js` hands
|
||||
* the job to the detached `claude plugin update` chain instead.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -24,6 +36,7 @@ const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { execFile } = require("child_process");
|
||||
const { readLastPluginUpdate } = require("./plugin-update");
|
||||
const { getClaudeHome } = require("./claude-home");
|
||||
|
||||
const DEFAULT_ROOT = path.join(__dirname, "..", "..");
|
||||
|
||||
@@ -239,8 +252,21 @@ async function fetchLatestRelease(root, timeoutMs = 10_000) {
|
||||
} catch {
|
||||
return { ok: false, reason: "no_remote" };
|
||||
}
|
||||
return fetchReleaseFromUrl(remoteUrl, timeoutMs);
|
||||
}
|
||||
|
||||
const api = releaseApiUrl(remoteUrl);
|
||||
/**
|
||||
* The HTTP half of the release lookup, split out because a **plugin-cache
|
||||
* install has no git remote to derive the URL from** — it is unpacked from an
|
||||
* archive, so `pluginMarketplaceUrl()` supplies the repository URL instead and
|
||||
* calls straight in here. Same contract as `fetchLatestRelease`: never throws.
|
||||
*
|
||||
* @param {string} repoUrl a repository URL (https, scp-style, or ssh://)
|
||||
* @param {number} [timeoutMs]
|
||||
*/
|
||||
async function fetchReleaseFromUrl(repoUrl, timeoutMs = 10_000) {
|
||||
if (!repoUrl) return { ok: false, reason: "no_remote" };
|
||||
const api = releaseApiUrl(repoUrl);
|
||||
if (!api) return { ok: false, reason: "remote_not_http" };
|
||||
|
||||
try {
|
||||
@@ -279,6 +305,141 @@ async function fetchLatestRelease(root, timeoutMs = 10_000) {
|
||||
* a tag that is actually a plain ancestor. Callers must fall back to comparing
|
||||
* version strings, the one signal a shallow clone still answers correctly.
|
||||
*/
|
||||
/**
|
||||
* Repository URL a marketplace declares for one of its plugins, read off disk.
|
||||
*
|
||||
* This exists because a plugin-cache install is NOT necessarily a git clone.
|
||||
* When a marketplace entry uses `"source": "url"` (this project's own does),
|
||||
* Claude Code unpacks an archive and the cache directory has no `.git` at all —
|
||||
* so there is no remote to derive the releases API from, and every git-based
|
||||
* signal is unavailable. The marketplace manifest is the authority on where the
|
||||
* plugin came from, and it is already on disk next to the cache.
|
||||
*
|
||||
* Path: `<claude home>/plugins/known_marketplaces.json` gives the marketplace's
|
||||
* `installLocation`; that directory's `.claude-plugin/marketplace.json` lists
|
||||
* the plugins, each with its own `source`.
|
||||
*
|
||||
* @param {string} marketplace marketplace name (from the cache path)
|
||||
* @param {string} plugin plugin name (from the cache path)
|
||||
* @returns {string|null} the URL, or null when it cannot be determined. Never throws.
|
||||
*/
|
||||
function pluginMarketplaceUrl(marketplace, plugin) {
|
||||
try {
|
||||
const pluginsDir = path.join(getClaudeHome(), "plugins");
|
||||
let installLocation = path.join(pluginsDir, "marketplaces", marketplace);
|
||||
try {
|
||||
const known = JSON.parse(
|
||||
fs.readFileSync(path.join(pluginsDir, "known_marketplaces.json"), "utf8")
|
||||
);
|
||||
const entry = known && known[marketplace];
|
||||
if (entry && typeof entry.installLocation === "string" && entry.installLocation) {
|
||||
installLocation = entry.installLocation;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to the conventional location — the manifest below is what
|
||||
// actually matters, and it may well be readable without this index.
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(path.join(installLocation, ".claude-plugin", "marketplace.json"), "utf8")
|
||||
);
|
||||
const entry = (manifest?.plugins || []).find((p) => p && p.name === plugin);
|
||||
if (!entry) return null;
|
||||
|
||||
// `source` is either a string (a bare URL or owner/repo) or an object with
|
||||
// its own `source` discriminator plus `url`/`repo`.
|
||||
const src = entry.source;
|
||||
if (typeof src === "string") return src.includes("://") ? src : null;
|
||||
if (src && typeof src.url === "string" && src.url) return src.url;
|
||||
// A `github`-style `repo: "owner/repo"` shorthand carries no host; this
|
||||
// build is distributed from its own forge, so rather than guessing
|
||||
// github.com the caller reports "remote_not_http" and prints the manual
|
||||
// command instead of inventing an API URL that would 404.
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Full update status for an install running out of the plugin cache, computed
|
||||
* WITHOUT git. Version comparison is the only signal available and the only one
|
||||
* that means anything here: the cache directory name is a content hash, and
|
||||
* even when a `.git` happens to exist it is a depth-1 clone whose commit
|
||||
* distances are graft artefacts.
|
||||
*
|
||||
* Returns the same payload shape as the git path, with every git-derived field
|
||||
* null, so one client renders both.
|
||||
*/
|
||||
async function pluginStatus(root, pluginInstall, options = {}) {
|
||||
const localVersion = readLocalVersion(root);
|
||||
const repoUrl = pluginMarketplaceUrl(pluginInstall.marketplace, pluginInstall.plugin);
|
||||
const release =
|
||||
options.latestRelease ??
|
||||
(options.skipFetch ? { ok: false, reason: "skipped" } : await fetchReleaseFromUrl(repoUrl));
|
||||
|
||||
// No local version means nothing to compare against — report "could not
|
||||
// look" rather than a false "up to date".
|
||||
const comparable = release.ok && Boolean(localVersion);
|
||||
const releaseIsNewer = comparable && compareVersions(release.tag, localVersion) > 0;
|
||||
|
||||
const manualParts = [
|
||||
`claude plugin marketplace update ${pluginInstall.marketplace}`,
|
||||
`claude plugin update ${pluginInstall.plugin}@${pluginInstall.marketplace} -y`,
|
||||
];
|
||||
|
||||
return {
|
||||
// Truthfully false: there is no clone here. Consumers must branch on
|
||||
// `install_kind`, not on this, or they will report "check manually" for an
|
||||
// install the dashboard can in fact check AND update.
|
||||
git_repo: false,
|
||||
update_available: releaseIsNewer,
|
||||
repo_root: root,
|
||||
situation: "plugin_managed",
|
||||
situation_note:
|
||||
`This dashboard runs from the Claude Code plugin cache (marketplace ` +
|
||||
`'${pluginInstall.marketplace}'). Updating is handled by Claude Code's own plugin ` +
|
||||
`commands — "Update now" runs them for you and restarts the dashboard. An already-open ` +
|
||||
`Claude Code session still needs '/reload-plugins' to pick up new skills and commands.`,
|
||||
manual_command: manualParts.join(" && "),
|
||||
// A plugin install compares versions exactly like a checkout does, so it
|
||||
// gets the same sentence. Left null, `agenthub update-check` printed the
|
||||
// literal "null" as its headline on every plugin-cache install — the one
|
||||
// install kind that cannot fall back to a commit count.
|
||||
message: releaseIsNewer
|
||||
? `Release ${release.tag} is available (this install reports ${localVersion || "no version"}).`
|
||||
: comparable
|
||||
? `Running the newest release (${release.tag}).`
|
||||
: release.ok
|
||||
? `This install reports no version, so it cannot be compared with release ${release.tag}.`
|
||||
: `Could not read the latest release (${release.reason}); version comparison unavailable.`,
|
||||
|
||||
install_kind: "plugin",
|
||||
plugin_marketplace: pluginInstall.marketplace,
|
||||
plugin_name: pluginInstall.plugin,
|
||||
last_plugin_update: readLastPluginUpdate(),
|
||||
|
||||
local_version: localVersion,
|
||||
// Not a clone, so there is nothing to be shallow about and no distances to
|
||||
// report. Kept present-and-null so the payload shape never varies.
|
||||
shallow_clone: false,
|
||||
local_sha: null,
|
||||
remote_sha: null,
|
||||
commits_behind: 0,
|
||||
release_check: release.ok ? (localVersion ? "ok" : "no_local_version") : release.reason,
|
||||
latest_release: release.ok ? release.tag : null,
|
||||
latest_release_name: release.ok ? release.name : null,
|
||||
latest_release_url: release.ok ? release.url : null,
|
||||
latest_release_published_at: release.ok ? release.published_at : null,
|
||||
latest_release_notes: release.ok ? release.notes : null,
|
||||
release_sha: null,
|
||||
commits_behind_release: null,
|
||||
commits_ahead_of_release: null,
|
||||
// A plugin install is whatever the marketplace shipped; it cannot be ahead.
|
||||
dev_build: false,
|
||||
};
|
||||
}
|
||||
|
||||
async function isShallowClone(root) {
|
||||
try {
|
||||
const out = await execGit(root, ["rev-parse", "--is-shallow-repository"], { timeout: 10_000 });
|
||||
@@ -306,6 +467,17 @@ async function countCommits(root, range) {
|
||||
*/
|
||||
async function getUpdatesStatus(gitRoot = DEFAULT_ROOT, options = {}) {
|
||||
const root = path.resolve(gitRoot);
|
||||
|
||||
// A plugin-cache install is answered WITHOUT git, and this must come before
|
||||
// the `.git` probe below. When a marketplace entry uses `"source": "url"`,
|
||||
// Claude Code unpacks an archive and there is no `.git` at all — so the probe
|
||||
// would return "not a git clone; check for updates manually" and skip the
|
||||
// entire release layer, leaving update_available permanently false however
|
||||
// many releases get published. Version compare needs no clone; the repository
|
||||
// URL comes from the marketplace manifest.
|
||||
const earlyPluginInstall = detectPluginInstall(root);
|
||||
if (earlyPluginInstall) return pluginStatus(root, earlyPluginInstall, options);
|
||||
|
||||
const gitDir = path.join(root, ".git");
|
||||
if (!fs.existsSync(gitDir)) {
|
||||
return {
|
||||
@@ -632,6 +804,8 @@ module.exports = {
|
||||
compareVersions,
|
||||
releaseApiUrl,
|
||||
detectPluginInstall,
|
||||
pluginMarketplaceUrl,
|
||||
fetchReleaseFromUrl,
|
||||
fetchLatestRelease,
|
||||
isShallowClone,
|
||||
};
|
||||
|
||||
+1
-1
@@ -2471,7 +2471,7 @@ function createOpenApiSpec() {
|
||||
type: "object",
|
||||
additionalProperties: true,
|
||||
description:
|
||||
'applied: false plus reason: "up_to_date" | "not_fast_forwardable" | "plugin_managed". plugin_managed appears here only when a plugin-cache install has nothing newer published; when a newer release exists the plugin chain runs and the answer is 200 instead. Run /agenthub-update to force a refresh.',
|
||||
'applied: false plus reason: "up_to_date" | "not_fast_forwardable" | "plugin_managed". plugin_managed appears here only when a plugin-cache install has nothing to pull: either release_check is "ok" and the published release is already installed, or the release check did not succeed (the message says which — an unknown is never reported as "nothing newer"). When a newer release exists the plugin chain runs and the answer is 200 instead. Run /agenthub-update to force a refresh.',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -898,7 +898,9 @@ function sendLifecycleError(res, err) {
|
||||
if (["ENOTMANAGED", "EOUTSIDEROOT", "ENOTWORKTREE", "EEXPECT"].includes(err.code)) {
|
||||
return res.status(400).json({ error: { code: err.code, message: err.message } });
|
||||
}
|
||||
if (["ESTALE", "EUNPUSHED"].includes(err.code)) {
|
||||
// ERUNLIVE: the lane's pane is busy with a live agent, so a resume/prompt
|
||||
// could not be delivered — a conflict, not a bad request or a server fault.
|
||||
if (["ESTALE", "EUNPUSHED", "ERUNLIVE"].includes(err.code)) {
|
||||
return res.status(409).json({
|
||||
error: {
|
||||
code: err.code,
|
||||
@@ -1358,6 +1360,12 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
// A host with no tmux cannot start a run, but nothing is broken on this
|
||||
// side — 503 plus the install line, not a 500 the reader can only read as a
|
||||
// dashboard bug.
|
||||
if (err.code === "ETMUXMISSING") {
|
||||
return res.status(503).json({ error: { code: err.code, message: err.message } });
|
||||
}
|
||||
return res.status(500).json({ error: { code: err.code, message: err.message } });
|
||||
}
|
||||
|
||||
|
||||
@@ -256,6 +256,15 @@ router.post("/", (req, res) => {
|
||||
});
|
||||
return res.status(201).json(handle);
|
||||
} catch (err) {
|
||||
// A busy pane is a conflict with live state, not a malformed request.
|
||||
if (err.code === "ERUNLIVE") {
|
||||
return res.status(409).json({ error: { code: err.code, message: err.message } });
|
||||
}
|
||||
// Nor is a host missing tmux: the request was fine, the dependency is not
|
||||
// installed. 400 would tell the user to fix their input.
|
||||
if (err.code === "ETMUXMISSING") {
|
||||
return res.status(503).json({ error: { code: err.code, message: err.message } });
|
||||
}
|
||||
if (err.code && err.code.startsWith("E")) {
|
||||
return res.status(400).json({ error: { code: err.code, message: err.message } });
|
||||
}
|
||||
|
||||
@@ -91,7 +91,13 @@ router.post("/apply", async (_req, res) => {
|
||||
result.reason === "up_to_date"
|
||||
? "Already up to date."
|
||||
: result.reason === "plugin_managed"
|
||||
? "This install runs from the Claude Code plugin cache and nothing newer is published; run /agenthub-update to force a refresh."
|
||||
? // Do not claim "nothing newer is published" unless the release
|
||||
// lookup actually succeeded — saying so after a failed check
|
||||
// reports an unknown as a negative, which is how a broken
|
||||
// check looks identical to an up-to-date install.
|
||||
result.release_check === "ok"
|
||||
? `This install runs from the Claude Code plugin cache and ${result.latest_release || "the published release"} is already the newest; run /agenthub-update to force a refresh.`
|
||||
: `This install runs from the Claude Code plugin cache and the release check did not succeed (${result.release_check || "unknown"}), so there is nothing to apply; run /agenthub-update to update it by hand.`
|
||||
: "Current branch can't be fast-forwarded automatically.",
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user